Compare commits

..
Author SHA1 Message Date
Cursor Agent 31735f3ec7 Extract duplicated VCS path utilities into shared VcsPathUtils module
Move splitNullSeparatedPaths and chunkPathsForCheckIgnore from both
GitVcsDriver.ts and JjVcsDriver.ts into a shared VcsPathUtils.ts module
to eliminate code duplication and prevent future drift.
2026-05-02 09:06:51 +00:00
Julius Marminge e07cc3e3ae Use effect file system and node services in VCS tests
- Replace ad hoc temp-dir handling with scoped FileSystem APIs
- Provide NodeServices in VCS driver and status broadcaster tests
- Normalize CWDs through FileSystem realpath
2026-05-02 01:57:03 -07:00
Julius Marminge c3c4aca232 Add JJ VCS driver support
- Detect and route jj repositories alongside git
- Thread VCS kind through status and UI labels
- Add jj driver contract coverage and shared freshness helper
2026-05-02 01:38:13 -07:00
Julius Marminge a73408c324 Handle empty GitHub PR listings and fallback branch lookup
- Treat empty `gh pr list` output as no results
- Fall back to `main` when provider default-branch detection fails
- Add coverage for PR creation fallback behavior
2026-05-02 00:03:12 -07:00
Cursor Agent 1e0a7598c7 fix: rename local sourceControlProvider to hostingProvider to avoid shadowing outer function
Applied via @cursor push command
2026-05-02 00:03:12 -07:00
Julius Marminge 8a5b784eae Scope VCS process lifetimes with a helper
- Replace raw spawn access with `withProcess` for scoped use
- Ensure child processes are finalized even on early exits
- Keep `run` built on the scoped helper for safer cleanup
2026-05-02 00:03:12 -07:00
Julius Marminge 7788858149 Expose spawned VCS process handles
- Add a reusable `spawn` API for VCS processes
- Factor stream collection into `collectText`
- Preserve existing `run` behavior on top of the new handle
2026-05-02 00:03:12 -07:00
Julius Marminge b743d0b66e Use typed exit codes in VCS process results
- Switch VCS process and git driver results to `ChildProcessSpawner.ExitCode`
- Update status checks and fallback results to use the new typed exit code
- Refresh tests to match the new result shape
2026-05-02 00:03:12 -07:00
Julius Marminge ccb97da75c Update git ref mock data for primary remote
- Rename branch fixtures to refs and primary remote flags
- Align Git actions and keybinding tests with new ref labels
2026-05-02 00:03:12 -07:00
Julius Marminge 3a254bad33 Normalize VCS CWDs and forward git env
- Resolve symlinked working directories before caching and workflow calls
- Pass execute env through the Git VCS driver
2026-05-02 00:03:12 -07:00
Julius Marminge a889dc68ca Refactor git services into source control layers
- Move GitManager and GitHubCli contracts/layers to their new modules
- Update server wiring and tests for the relocated pluggable git setup
2026-05-02 00:03:12 -07:00
Julius Marminge dcbb182f82 Extract text generation into dedicated server module
- Move git text-generation layers and tests under `src/textGeneration`
- Route server and provider drivers to the new module
- Replace the old git-scoped `TextGenerationLive` registry layer
2026-05-02 00:03:12 -07:00
Julius Marminge e21b1514a5 Rename git hosting provider fields to source control provider
- Rename shared/server status fields and detectors from hostingProvider to sourceControlProvider
- Move provider schema into contracts/sourceControl and update status/event tests
- Refresh branch toolbar labels from switchRef to checkout
2026-05-02 00:03:12 -07:00
Julius Marminge e795698818 Rename git APIs around refs
- Replace branch-centric git/VCS types and methods with ref-based names
- Update server, web, and tests to use the new pluggable integration shape
2026-05-02 00:03:12 -07:00
Julius Marminge 506e0fc049 Add pluggable source control provider detection
- Detect GitHub, GitLab, and Azure DevOps remotes in the shared parser
- Cache provider resolution and return unsupported stubs for unregistered kinds
- Remove deprecated git RPCs from the web IPC surface
2026-05-02 00:02:06 -07:00
Julius Marminge e8d67ffb91 Rename Array import alias in GitManager
- Use `Arr` alias for Effect Array in `GitManager`
- Keep pull request sorting logic unchanged
2026-05-02 00:02:06 -07:00
Julius Marminge c0e867b4d9 Sort pull requests by updated time and fix git mock shape
- Use Effect ordering for PR recency sorting in the server git manager
- Update web git status test mocks to match the split `vcs` and `git` APIs
2026-05-02 00:02:06 -07:00
Julius Marminge 6d7de0b314 Normalize timestamps across VCS and source control contracts
- Switch freshness and PR update times to typed `DateTime`/`Option` values
- Update GitHub and VCS adapters, tests, and sorting to use the new shapes
2026-05-02 00:02:06 -07:00
Julius Marminge 38185dc696 Add pluggable source control routing
- Route git workflows through source control providers
- Replace git status broadcaster with VCS status service
- Update orchestration, server, and web contracts for provider-aware git
2026-05-02 00:02:06 -07:00
Julius Marminge 87c2e3e1ef Use mock layers for Git VCS driver tests
- Replace ad hoc `succeed` casts with `Layer.mock` in integration and reactor tests
- Keep Git VCS driver fixtures type-safe while preserving existing test behavior
2026-05-02 00:02:06 -07:00
Julius Marminge 5c227dcaa7 Tighten VCS driver test assertions
- Switch integration and contract tests to Effect/Vitest assertions
- Avoid platform-specific realpath assumptions in repository identity checks
- Use Path service for portable test file and worktree path handling
2026-05-02 00:02:06 -07:00
Julius Marminge ccbad67c43 Refactor VCS driver tests into shared contract harness
- Add a reusable VCS driver contract suite
- Rework Git driver tests to use real repo fixtures
2026-05-02 00:02:06 -07:00
Julius Marminge 127e91bc86 Refactor GitVcsDriverCore test setup
- Simplify shared test helpers and temp repo setup
- Switch the test layer wiring to merge Node services
- Remove unused shell/process scaffolding from the spec
2026-05-02 00:02:06 -07:00
Julius Marminge e01c92ff0a Add VCS driver registry for pluggable git integration
- Route checkpointing and workspace services through a VCS driver registry
- Split git driver construction from the driver service wrapper
- Update tests and harnesses to mock the registry instead of the raw driver
2026-05-02 00:02:06 -07:00
Julius Marminge a11d6b92ea Refactor git core into pluggable VCS driver
- Move low-level git service into `GitVcsDriverCore`
- Update server wiring and tests to use the new driver
2026-05-02 00:02:06 -07:00
Julius Marminge 82a8394cd8 Split git VCS driver from core service
- Introduce a dedicated `GitVcsDriver` service and `vcsLayer`
- Update server, orchestration, and workspace wiring to use the new layer
- Adjust tests and mocks for the new git-specific dependency
2026-05-02 00:02:06 -07:00
Julius Marminge 0ce293b37e Use Effect time APIs for VCS and workspace scans
- Switch freshness and scan timestamps to `DateTime.now` from Effect
- Keep timestamps consistent within each async operation
2026-05-02 00:02:06 -07:00
Julius Marminge 0b0d98c1fd Fix GitVcsDriver test dependency import
- Import `VcsProcess` as a namespace in the test
- Update layer injection to target `VcsProcess.VcsProcess`
2026-05-02 00:02:06 -07:00
Julius Marminge ecac3ac795 Use VcsProcess module directly in tests
- Remove the aliased service import
- Reference `VcsProcess.VcsProcess` explicitly in checkpoint and workspace tests
2026-05-02 00:02:06 -07:00
Julius Marminge 5e0327dee6 Standardize VCS layer imports across server tests
- Switch GitVcsDriver and VcsProcess usages to namespace imports
- Update server and integration wiring to use `.layer` consistently
- Keep test type annotations aligned with the exported service types
2026-05-02 00:02:06 -07:00
Julius Marminge 8f09b8d0ab Refactor VCS layers into top-level modules
- Move VcsDriver and VcsProcess out of nested service/layer paths
- Update server, workspace, orchestration, and tests to use new exports
- Rename layer exports to `layer` for consistency
2026-05-02 00:02:06 -07:00
Julius Marminge 972a6876b8 Introduce pluggable VCS driver for git operations
- Replace direct GitCore dependencies with VcsDriver and VcsProcess
- Move checkpointing, workspace, and orchestration flows onto the new VCS abstraction
- Drop workspace-specific git helpers from GitCore
2026-05-02 00:02:06 -07:00
Julius Marminge 0cd920f32e Add version control foundation plans
- Add phase 1 VCS driver plan
- Add phase 2 source control provider plan
- Index both plans in `.plans/README.md`
2026-05-02 00:02:06 -07:00
Julius MarmingeandJulius Marminge 4ceabac764 Fix dialog footer button clipping in Git actions dialog (#2458)
Co-authored-by: Julius Marminge <[email protected]>
2026-05-01 23:57:44 -07:00
Julius MarmingeandJulius Marminge 7a3f21e7ca [codex] fix Discord release version flag (#2449)
Co-authored-by: Julius Marminge <[email protected]>
2026-05-01 18:39:41 +00:00
Julius MarmingeandJulius Marminge 17b43960e8 Add structured Discord webhook logging for release notifications (#2431)
Co-authored-by: Julius Marminge <[email protected]>
2026-05-01 03:53:47 +00:00
Julius MarmingeandJulius Marminge e5c7ac5a8c Optimize release workflow job execution (#2430)
Co-authored-by: Julius Marminge <[email protected]>
2026-04-30 20:08:11 -07:00
a480f07241 Add Discord release announcements (#2429)
Co-authored-by: Cursor Agent <[email protected]>
Co-authored-by: Julius Marminge <[email protected]>
2026-04-30 19:13:05 -07:00
Adam Mansfield 1eb6fcea84 fix: opencode is not on PATH on Windows (#2183) 2026-04-30 18:15:45 -07:00
4ef361da73 fix(mobile): enable touch scrolling in file picker modal (#2420)
Co-authored-by: Claude Haiku 4.5 <[email protected]>
Co-authored-by: Julius Marminge <[email protected]>
2026-04-30 18:12:48 -07:00
Noah Gregory c07ac592d8 fix: bump electron version to v40.9.3 and add it to our trusted dependencies (#2427) 2026-04-30 17:34:21 -07:00
d649ccf715 fix(web): respect iOS safe areas across mobile chrome & other mobile layout fixes (#2392)
Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
Co-authored-by: Julius Marminge <[email protected]>
2026-04-30 16:26:36 -07:00
shivam f54f4385e5 Narrow the right sidebar and update task panel and diff panel (#2409) 2026-04-30 15:33:06 -07:00
Julius Marminge e25ce07cc2 Add new GitHub users to VOUCHED.td (#2425) 2026-04-30 18:58:31 +00:00
532a1d891d fix(web): make thread archive button always visible on mobile (#2423)
Co-authored-by: Claude Sonnet 4.7 <[email protected]>
Co-authored-by: Julius Marminge <[email protected]>
2026-04-30 18:46:05 +00:00
9e2f7129e3 fix(web): make new thread button always visible on mobile (#2419)
Co-authored-by: Claude Haiku 4.5 <[email protected]>
Co-authored-by: Julius Marminge <[email protected]>
2026-04-30 18:18:12 +00:00
a4298f1ceb fix(web): hide mobile sidebar after thread selection or creation (#1293)
Co-authored-by: Murat Aslan <[email protected]>
Co-authored-by: Julius Marminge <[email protected]>
2026-04-30 11:10:37 -07:00
kp 86c94b4852 fix(web): allow closing diff panel in non-git projects (#2413) 2026-04-30 04:36:05 +00:00
Guilherme Vieira 69d9a659a3 fix(git): hide stale merged/closed PRs on the default branch (#1966) 2026-04-29 21:29:48 -07:00
9acf46a76d fix(web): prevent iOS Safari auto-zoom on input focus (#1652)
Co-authored-by: Claude Opus 4.6 <[email protected]>
Co-authored-by: codex <[email protected]>
Co-authored-by: Julius Marminge <[email protected]>
2026-04-29 18:03:40 -07:00
Bas Milius 44b39fe2ec fix(server): key AskUserQuestion answers by question text (#2404) 2026-04-29 17:44:44 -07:00
Julius Marmingeandcodex 02903f2db8 [codex] fix terminal dimension validation (#2411)
Co-authored-by: codex <[email protected]>
2026-04-30 00:09:00 +00:00
Julius Marmingeandcodex 22b7d8c524 [codex] Fix visited timestamp under clock skew (#2408)
Co-authored-by: codex <[email protected]>
2026-04-29 17:07:21 -07:00
pomp fe2fde5172 Add OpenCode to README (#2154) 2026-04-29 23:49:49 +00:00
zurielbm 7da6522fb8 fix: updated UI "add project" icon to match the command pallete icon (#2176) 2026-04-29 23:48:08 +00:00
08e6d4cfbf feat: Multi-Provider support (#2277)
Co-authored-by: Claude Opus 4.7 <[email protected]>
Co-authored-by: codex <[email protected]>
2026-04-29 16:13:55 -07:00
Josh Meads 35822884d1 Stop OpenCode refresh from leaking serve processes
OpenCode can leave the long-lived serve child in the spawned process group after the wrapper exits. Provider refresh owns only a scoped inventory probe, so cleanup targets that local process group when the refresh scope closes.

Constraint: Keep active OpenCode thread sessions scoped to their own session lifecycle.
Rejected: Disable provider refresh | would hide model and auth state changes.
Confidence: high
Scope-risk: narrow
Tested: bun run test src/provider/Layers/OpenCodeProvider.test.ts src/provider/Layers/OpenCodeAdapter.test.ts
Tested: bun fmt
Tested: bun lint
Tested: bun typecheck
Tested: bun run build:desktop
2026-04-29 11:02:16 -07:00
Julius Marminge dbebc387dd Ignore stale WebSocket lifecycle events after reconnect (#2372) 2026-04-27 09:50:19 -07:00
Julius Marmingeandcodex 5cf83ffe8f fix(release): use configured node for smoke manifest merge (#2364)
Co-authored-by: codex <[email protected]>
2026-04-27 02:30:18 +00:00
t3-code[bot] ada410bccf chore(release): prepare v0.0.21 2026-04-23 18:05:15 +00:00
legs 00b5c3e1b3 Add task sidebar auto-open setting (#2314) 2026-04-23 13:59:08 -04:00
188df6da07 Fix Claude session cwd resume drift (#2292)
Co-authored-by: Cursor Agent <[email protected]>
Co-authored-by: Julius Marminge <[email protected]>
Co-authored-by: codex <[email protected]>
2026-04-23 13:29:54 -04:00
Pedro Silva 0d55a42840 fix(web): ignore stale runtime projection snapshots (#2301) 2026-04-23 15:52:02 +00:00
Thimo Sietsma 0ee302e24d fix(request-permission): add dynamic_tool_call to command request (#2311) 2026-04-23 15:42:35 +00:00
Julius Marminge d5b7690f95 Exclude subscribe RPCs from latency tracking (#2313) 2026-04-23 15:24:06 +00:00
327 changed files with 26431 additions and 12545 deletions

No files matched your search

+3
View File
@@ -30,3 +30,6 @@ github:Yash-Singh1
github:eggfriedrice24
github:Ymit24
github:shivamhwp
github:jappyjan
github:justsomelegs
github:UtkarshUsername
+67 -7
View File
@@ -30,7 +30,7 @@ jobs:
check_changes:
name: Check for changes since last nightly
if: github.event_name == 'schedule'
runs-on: ubuntu-24.04
runs-on: blacksmith-8vcpu-ubuntu-2404
outputs:
has_changes: ${{ steps.check.outputs.has_changes }}
steps:
@@ -376,13 +376,16 @@ jobs:
registry-url: https://registry.npmjs.org
- name: Install dependencies
run: bun install --frozen-lockfile
run: bun install --frozen-lockfile --filter=t3 --filter=@t3tools/web --filter=@t3tools/scripts
- name: Align package versions to release version
run: node scripts/update-release-package-versions.ts "${{ needs.preflight.outputs.version }}"
- name: Build web package
run: bun --filter=@t3tools/web run build
- name: Build CLI package
run: bun run build --filter=@t3tools/web --filter=t3
run: bun --filter=t3 run build
- name: Publish CLI package
run: node apps/server/scripts/cli.ts publish --tag "${{ needs.preflight.outputs.cli_dist_tag }}" --app-version "${{ needs.preflight.outputs.version }}" --verbose
@@ -391,7 +394,7 @@ jobs:
name: Publish GitHub Release
needs: [preflight, build, publish_cli]
if: ${{ !failure() && !cancelled() && needs.preflight.result == 'success' && needs.build.result == 'success' && needs.publish_cli.result == 'success' }}
runs-on: ubuntu-24.04 # blacksmith-8vcpu-ubuntu-2404
runs-on: blacksmith-8vcpu-ubuntu-2404
timeout-minutes: 10
steps:
- id: app_token
@@ -418,7 +421,7 @@ jobs:
node-version-file: package.json
- name: Install dependencies
run: bun install --frozen-lockfile
run: bun install --frozen-lockfile --filter=@t3tools/scripts
- name: Download all desktop artifacts
uses: actions/download-artifact@v8
@@ -552,7 +555,7 @@ jobs:
node-version-file: package.json
- name: Install dependencies
run: bun install --frozen-lockfile
run: bun install --frozen-lockfile --filter=@t3tools/scripts
- id: update_versions
name: Update version strings
@@ -562,7 +565,7 @@ jobs:
- name: Format package.json files
if: steps.update_versions.outputs.changed == 'true'
run: bunx oxfmt apps/server/package.json apps/desktop/package.json apps/web/package.json packages/contracts/package.json
run: bunx oxfmt@0.40.0 apps/server/package.json apps/desktop/package.json apps/web/package.json packages/contracts/package.json
- name: Refresh lockfile
if: steps.update_versions.outputs.changed == 'true'
@@ -585,3 +588,60 @@ jobs:
git add apps/server/package.json apps/desktop/package.json apps/web/package.json packages/contracts/package.json bun.lock
git commit -m "chore(release): prepare $RELEASE_TAG"
git push origin HEAD:main
announce_discord:
name: Announce release on Discord
if: |
always() && !cancelled() &&
needs.preflight.result == 'success' &&
needs.release.result == 'success' &&
(needs.finalize.result == 'success' || needs.finalize.result == 'skipped')
needs: [preflight, release, finalize]
runs-on: blacksmith-8vcpu-ubuntu-2404
timeout-minutes: 10
steps:
- name: Checkout
uses: actions/checkout@v6
with:
ref: ${{ needs.preflight.outputs.ref }}
- name: Setup Bun
uses: oven-sh/setup-bun@v2
with:
bun-version-file: package.json
- name: Setup Node
uses: actions/setup-node@v6
with:
node-version-file: package.json
- name: Install dependencies
run: bun install --frozen-lockfile --filter=@t3tools/scripts
- name: Announce prerelease on Discord
if: needs.preflight.outputs.is_prerelease == 'true'
continue-on-error: true
env:
DISCORD_MENTION_ROLE_ID: ${{ secrets.DISCORD_RELEASE_NIGHTLY_ROLE_ID }}
DISCORD_WEBHOOK_URL: ${{ secrets.DISCORD_RELEASE_WEBHOOK_URL }}
run: |
node scripts/notify-discord-release.ts prerelease \
--role-id "$DISCORD_MENTION_ROLE_ID" \
--release-name "${{ needs.preflight.outputs.release_name }}" \
--release-version "${{ needs.preflight.outputs.version }}" \
--tag "${{ needs.preflight.outputs.tag }}" \
--release-url "https://github.com/${{ github.repository }}/releases/tag/${{ needs.preflight.outputs.tag }}"
- name: Announce latest release on Discord
if: needs.preflight.outputs.make_latest == 'true'
continue-on-error: true
env:
DISCORD_MENTION_ROLE_ID: ${{ secrets.DISCORD_RELEASE_LATEST_ROLE_ID }}
DISCORD_WEBHOOK_URL: ${{ secrets.DISCORD_RELEASE_WEBHOOK_URL }}
run: |
node scripts/notify-discord-release.ts latest \
--role-id "$DISCORD_MENTION_ROLE_ID" \
--release-name "${{ needs.preflight.outputs.release_name }}" \
--release-version "${{ needs.preflight.outputs.version }}" \
--tag "${{ needs.preflight.outputs.tag }}" \
--release-url "https://github.com/${{ github.repository }}/releases/tag/${{ needs.preflight.outputs.tag }}"
@@ -0,0 +1,216 @@
# Version Control Phase 1: VCS Driver Foundation
## Goal
Introduce a provider-neutral VCS layer and rewrite the local Git implementation as an Effect-native driver. This phase should preserve user-visible behavior while replacing the Git-first service boundary with an abstraction that can support Git, Jujutsu, and later Sapling or another viable VCS.
The existing `GitCore` implementation is a behavior reference and source of regression tests, not the target architecture. New code should follow the newer package style used by `effect-acp` and `effect-codex-app-server`: typed service tags, schema-backed tagged errors, scoped process usage, explicit decode boundaries, and no Promise-based process helper as the core execution primitive.
## Scope
- Add VCS-domain contracts in `packages/contracts/src/vcs.ts`.
- Add shared runtime parsing helpers in `packages/shared/src/vcs/*` only when they are useful to both server and web.
- Add server services under `apps/server/src/vcs`:
- `Services/VcsDriver.ts`
- `Services/VcsRepositoryResolver.ts`
- `Services/VcsProcess.ts`
- `Layers/GitVcsDriver.ts`
- `errors.ts`
- Migrate server callers from Git-specific terms where the operation is actually VCS-generic.
- Update active consumers to the new VCS APIs in the same phase; do not add backwards-compatible export shims.
- Leave source-control hosting providers out of this phase except for remote metadata needed to describe repository status.
## Non-Goals
- No GitLab, Azure DevOps, or GitHub provider rewrite yet.
- No Jujutsu driver yet, but every interface must be designed so a Jujutsu driver does not have to pretend to be Git.
- No T3 Review implementation yet.
- No broad UI redesign.
## Driver Model
Use provider-neutral nouns in new APIs:
- `VcsDriver`: local repository mechanics.
- `RepositoryIdentity`: detected VCS kind, root path, common metadata path when available, remotes.
- `WorkingCopyStatus`: dirty state, changed files, aggregate insertions/deletions, current branch/bookmark/change name.
- `ChangeSet`: a committed or pending unit of change, not necessarily a Git commit.
- `RefName`: branch, bookmark, tag, or provider-specific ref.
The initial driver capabilities should be explicit:
```ts
export interface VcsDriverCapabilities {
readonly kind: "git" | "jj" | "sapling" | "unknown";
readonly supportsWorktrees: boolean;
readonly supportsBookmarks: boolean;
readonly supportsAtomicSnapshot: boolean;
readonly supportsPushDefaultRemote: boolean;
}
```
Do not model Jujutsu as `GitCoreShape extends ...`. The Git driver can expose Git-specific implementation details internally, but the public VCS layer should describe operations by intent:
- `detectRepository(cwd)`
- `status(cwd, options)`
- `listRefs(cwd, query/pagination)`
- `checkoutRef(cwd, ref)`
- `createRef(cwd, ref, from?)`
- `createWorkspace(cwd, ref, path?)`
- `removeWorkspace(path)`
- `prepareChangeContext(cwd, filePaths?)`
- `createChange(cwd, message, options)`
- `push(cwd, target?)`
- `rangeContext(cwd, base, head)`
- `listWorkspaceFiles(cwd, options)`
## Effect Process Layer
Create a small reusable `VcsProcess` service instead of using `runProcess`.
Requirements:
- Implement with `ChildProcess` and `ChildProcessSpawner` from `effect/unstable/process`.
- Support scoped acquisition/release for long-running commands and interruption.
- Support bounded stdout/stderr collection with truncation markers.
- DO not eagerly consume full stdout/stderr, return stream apis and expose helpers for consumers so we don't consume streams to memory unnecessarily...
- Support stdin.
- Support timeout through Effect scheduling/interruption, not ad-hoc timers.
- Stream output lines to progress callbacks as Effects.
- Return a typed `ProcessOutput` value for successful execution.
- Fail with typed errors, not generic thrown exceptions.
Errors should be schema-backed tagged classes, for example:
- `VcsProcessSpawnError`
- `VcsProcessExitError`
- `VcsProcessTimeoutError`
- `VcsOutputDecodeError`
- `VcsRepositoryDetectionError`
- `VcsUnsupportedOperationError`
Every error should carry operation name, command display string, cwd when applicable, exit code when applicable, stderr/stdout tails when useful, and original cause where available. Override `message` for user readable messages that provides meaning and hints where appropriate. Errors are schema backed so the full error details will be persisted and serialized properly when stored to DB/Logfiles.
## Git Driver Rewrite
Rewrite Git support against `VcsProcess`.
Carry forward current behavior from:
- `apps/server/src/git/Layers/GitCore.ts`
- `apps/server/src/git/Layers/GitCore.test.ts`
- current Git status/branch/worktree contracts
But split the implementation into smaller modules:
- command execution and hardening config
- repository detection
- status parsing
- branch/ref parsing
- worktree operations
- commit/range context generation
- push/pull operations
Keep parsing deterministic. Prefer Git porcelain formats, null-separated output, and schema decoding for JSON-like command output. Avoid regex parsing where Git gives a structured format.
## Freshness and Local Caching
Define freshness rules in the VCS layer before adding more providers. Local VCS status is cheap enough to refresh often; network-backed status is not.
Treat these as live/local:
- repository detection for the active cwd
- working copy dirty state
- staged/unstaged/untracked file summaries
- current branch/bookmark/change name
- local branch/bookmark lists
- local worktree/workspace lists
These may run on user-visible polling, but should still be debounced and coalesced per repository root. Prefer filesystem-triggered invalidation where available, with a short fallback poll interval. Concurrent requests for the same repository/status shape should share one in-flight Effect.
Treat these as cached or explicit-refresh only:
- remote tracking branch refreshes
- ahead/behind counts that require network fetches
- default branch discovery from a remote provider
- remote branch lists beyond locally known refs
The VCS driver should expose freshness metadata with status results:
```ts
export interface VcsFreshness {
readonly source: "live-local" | "cached-local" | "cached-remote" | "explicit-remote";
readonly observedAt: string;
readonly expiresAt?: string;
}
```
Remote refreshes should be opt-in per operation, for example `refresh: "local-only" | "allow-cached-remote" | "force-remote"`. The default for background status should be `local-only`.
Use Effect `Cache` for repository identity and expensive local metadata:
- key by resolved repository root plus VCS kind
- invalidate on cwd/root changes and workspace mutation operations
- use short TTLs for local status caches when filesystem events are unavailable
- never hide command failures behind stale values unless the caller explicitly accepts stale data
## Cutover Policy
Prefer direct migration and deletion over compatibility wrappers.
Rules:
- Update consumers to call `VcsDriver`/`VcsRepositoryResolver` directly as soon as the new API exists.
- Delete migrated `GitCore` service methods and tests in the same PR that moves their consumers.
- Do not keep backwards-compatible export shims, barrel aliases, or old service names for convenience.
- Transitional modules are allowed only when a caller group is too complex or risky to migrate in the same PR.
- Every transitional module must have a narrow owner, a removal checklist, and a test proving it delegates to the new implementation.
- No new feature work may depend on transitional modules.
Expected transitional candidates:
- The highest-level `GitManager` orchestration can be migrated in slices if doing the full Commit + PR flow in one PR is too risky.
- WebSocket payload compatibility can remain only where changing it would require a coordinated UI/server protocol migration. Internal server code should still use the new VCS contracts.
## Tests
Add integration-style tests with real temporary Git repositories for the new Git driver:
- non-repository detection
- status for clean/dirty/untracked/staged states
- branch/ref list with pagination
- checkout/create branch
- worktree create/remove
- commit context generation with file filters
- commit creation with hook progress events
- push behavior against a local bare remote
- status polling does not perform remote network refresh by default
- concurrent duplicate status requests are coalesced
- bounded output/truncation
- timeout/interruption
- typed error shape for command failure and missing executable
Move or duplicate only the tests needed to prove behavior, then delete the old service tests in the same migration slice.
## Migration Steps
1. Add `vcs` contracts and tagged errors.
2. Add `VcsProcess` and unit tests around process execution semantics.
3. Add `VcsDriver` and `VcsRepositoryResolver` service contracts.
4. Implement `GitVcsDriver` with real Git command integration tests.
5. Move `GitStatusBroadcaster` and branch/worktree flows to the VCS service directly.
6. Move commit/range/push callers to the VCS service directly.
7. Delete migrated `GitCore` internals and tests as each caller group moves.
8. Add a transitional adapter only for any remaining `GitManager` path that is explicitly too complex to cut over safely in one PR.
9. Remove every transitional adapter before starting Phase 2 unless the adapter is documented as blocking on the provider cutover.
## Acceptance Criteria
- Current Git branch/status/worktree/commit behavior remains intact.
- New Git implementation does not depend on `processRunner.ts`.
- New errors are typed and inspectable by tests.
- VCS interfaces contain no GitHub/GitLab/Azure concepts.
- Active consumers use the new VCS APIs directly; any remaining transitional module has a written removal checklist and no compatibility export shim.
- Background status refresh is local-only by default and cannot hit provider rate limits.
- Jujutsu can be added by implementing a real driver instead of conforming to Git command semantics.
- `bun fmt`, `bun lint`, and `bun typecheck` pass.
@@ -0,0 +1,268 @@
# Version Control Phase 2: Source Control Provider Foundation
## Goal
Introduce a pluggable source-control provider layer and rewrite GitHub support as an Effect-native provider. This phase should preserve the existing GitHub Commit + PR flow while making GitLab and Azure DevOps additive drivers rather than branches inside GitHub-oriented code.
The existing `GitHubCli` service and GitHub-specific `GitManager` paths are behavior references. The new provider layer should use detailed tagged errors, schema decode boundaries, `effect/unstable/process`, capability flags, and provider-neutral change-request types.
## Scope
- Add provider-domain contracts in `packages/contracts/src/sourceControl.ts`.
- Add provider URL/reference parsing helpers in `packages/shared/src/sourceControl/*`.
- Add server services under `apps/server/src/sourceControl`:
- `Services/SourceControlProvider.ts`
- `Services/SourceControlProviderRegistry.ts`
- `Services/SourceControlProcess.ts`
- `Layers/GitHubSourceControlProvider.ts`
- `errors.ts`
- Migrate PR creation, PR lookup, default-branch lookup, clone URL lookup, and PR checkout through the provider layer.
- Update active consumers to the provider APIs directly; do not add backwards-compatible `GitHubCli` export shims.
- Keep GitHub as the only production provider at the end of this phase, but make GitLab and Azure implementation paths obvious and bounded.
## Non-Goals
- No GitLab implementation in this phase, except fixtures/contracts that prove the abstraction can represent merge requests.
- No Azure DevOps implementation in this phase, except URL/reference parser test cases if cheap.
- No in-app review UI yet.
- No hard dependency on one CLI forever. The first GitHub driver may use `gh`, but the interface should support REST/GraphQL implementations later.
## Provider Model
Use provider-neutral names:
- `SourceControlProvider`: hosted repository and change-request mechanics.
- `ChangeRequest`: GitHub pull request, GitLab merge request, Azure pull request.
- `ChangeRequestThread`: review or discussion thread.
- `ChangeRequestComment`: top-level or inline comment.
- `ProviderRepository`: owner/project/repo identity plus clone URLs.
Core provider operations:
- `detectRemote(remoteUrl)`
- `checkAuth(cwd)`
- `getRepository(cwd | remoteUrl)`
- `getDefaultTargetRef(repository)`
- `listChangeRequests(repository, filters)`
- `getChangeRequest(repository, reference)`
- `createChangeRequest(repository, input)`
- `checkoutChangeRequest(cwd, changeRequest, options)`
- `getCloneUrls(repository)`
Review-facing operations should be designed now, even if unimplemented:
- `listReviewThreads(changeRequest)`
- `createReviewComment(changeRequest, input)`
- `replyToReviewThread(thread, input)`
- `resolveReviewThread(thread)`
- `submitReview(changeRequest, input)`
Each operation should be guarded by capabilities:
```ts
export interface SourceControlProviderCapabilities {
readonly kind: "github" | "gitlab" | "azure-devops" | "unknown";
readonly supportsCreateChangeRequest: boolean;
readonly supportsCheckoutChangeRequest: boolean;
readonly supportsReviewThreads: boolean;
readonly supportsInlineComments: boolean;
readonly supportsDraftChangeRequests: boolean;
}
```
## Provider Registry
Add a registry that resolves a provider from repository remotes and explicit user input.
Rules:
- Detection should be pure where possible and testable without spawning CLIs.
- Remote URL parsing belongs in `packages/shared`, not server-only provider layers.
- Unknown providers should return explicit unsupported-operation errors, not silently fall back to GitHub.
- Provider selection should be stable per operation and logged with enough context to debug bad remote detection.
The registry should support multiple provider implementations at runtime, not a single dispatcher file with inline provider branches.
## Rate Limits and Provider Caching
Design the provider layer around a strict freshness budget. Provider API and CLI calls must not be part of frequent background polling unless the operation is explicitly marked safe and cached.
Default behavior:
- Pure URL/remote parsing is always live because it is local.
- Provider detection from local remotes is live-local.
- Authentication checks are cached.
- Repository metadata is cached.
- Default branch metadata is cached.
- Change-request lists are cached and refreshed on explicit user actions or coarse intervals.
- Full review threads, comments, file diffs, and timeline data are fetched only when the user opens the relevant review surface or explicitly refreshes it.
- Create/update operations invalidate affected cache keys immediately after success.
The provider API should make freshness explicit:
```ts
export interface SourceControlFreshness {
readonly source: "live-local" | "cached-provider" | "live-provider";
readonly observedAt: string;
readonly expiresAt?: string;
readonly stale?: boolean;
}
export type ProviderRefreshPolicy =
| "cache-first"
| "stale-while-revalidate"
| "force-refresh"
| "local-only";
```
Every read operation that can touch a provider should accept a refresh policy. Background UI reads should default to `cache-first` or `stale-while-revalidate`; direct user actions like pressing refresh can use `force-refresh`.
Use Effect `Cache` for provider data:
- auth status: key by provider kind, hostname, workspace identity, and account if known; TTL around minutes, not seconds
- repository metadata/default branch: key by provider repository stable ID or normalized remote URL; TTL around tens of minutes
- change-request summary lists: key by provider repository, state/filter, source ref, target ref; short TTL with stale-while-revalidate
- individual change-request summaries: key by provider repository and provider CR ID; short TTL, invalidated after create/update/comment operations
- review threads/comments/diffs: key by provider CR ID and head SHA/version when available; fetch on demand for T3 Review
Provider drivers should surface rate-limit signals when available:
- remaining quota
- reset time
- retry-after duration
- whether the limit is primary, secondary/abuse, or unknown
Rate-limit errors should be typed, retryable when the provider gives a reset/retry time, and visible enough for the UI to avoid repeatedly retrying a blocked operation.
Avoid rate-limit footguns:
- no provider calls from render loops or fast status polling
- no listing all PRs/MRs across all repos to infer one branch state
- no silent GitHub fallback for unknown providers
- no unbounded cache cardinality for branch names or free-form search queries
- no per-thread duplicate provider refresh when multiple views observe the same repository
## GitHub Provider Rewrite
Rewrite GitHub support as `GitHubSourceControlProvider`.
Carry forward behavior from:
- `apps/server/src/git/Layers/GitHubCli.ts`
- `apps/server/src/git/Layers/GitHubCli.test.ts`
- `apps/server/src/git/githubPullRequests.ts`
- GitHub-specific `GitManager` PR paths
Implementation requirements:
- Use `SourceControlProcess` built on `effect/unstable/process`, not `runProcess`.
- Decode `gh api` and `gh pr --json` responses with Effect Schema.
- Use typed errors for auth failure, missing CLI, command failure, output decode failure, unsupported reference, and provider mismatch.
- Keep stdout/stderr bounded.
- Avoid global mutable auth caches unless they are Effect `Cache` values with explicit keys, TTLs, and invalidation behavior.
- Parse provider rate-limit headers or CLI/API error payloads when available and map them to typed rate-limit errors.
- Keep GitHub nouns inside the GitHub driver; convert to `ChangeRequest` at the provider boundary.
## GitManager Cutover
Refactor `GitManager` so it coordinates three independent services:
- `VcsDriver` for local repository mechanics.
- `SourceControlProviderRegistry` for hosted provider selection.
- `TextGeneration` for message/body generation.
`GitManager` should stop depending directly on GitHub services. User-visible step labels should be provider-neutral unless the selected provider is known and the label is intentionally provider-specific.
The Commit + PR flow should become:
1. Resolve VCS repository and local status.
2. Resolve source-control provider from remotes.
3. Generate commit content through the existing text generation service.
4. Create local change through `VcsDriver`.
5. Push through `VcsDriver` or a narrow provider push helper only if the VCS requires provider-specific target syntax.
6. Generate change-request title/body.
7. Create the change request through `SourceControlProvider`.
## Cutover Policy
This phase should aggressively remove old GitHub-specific internals.
Rules:
- Move each active consumer directly to `SourceControlProviderRegistry` or a concrete provider test layer.
- Delete migrated `GitHubCli` methods, tests, and GitHub-specific helper exports in the same PR that moves their final consumer.
- Do not add compatibility export shims from `apps/server/src/git` to `apps/server/src/sourceControl`.
- Transitional modules are allowed only for a bounded `GitManager` slice that cannot move safely with the rest of the provider cutover.
- Every transitional module must have an owner comment, a removal checklist, and no public exports consumed by new code.
- Provider-neutral web parsing should replace GitHub-only parsing directly; do not keep parallel parser stacks unless a route still requires both during a single PR.
## GitLab and Azure Readiness
Use the triaged references as implementation inputs, not merge targets:
- GitLab PR #592 is useful for `glab mr` command mapping and JSON normalization.
- Azure issue #1138 defines a good first Azure slice: remote/URL detection and change-request thread setup for same-repo URLs.
The abstraction should let Phase 3 add:
- `GitLabSourceControlProvider` using `glab`.
- `AzureDevOpsSourceControlProvider` using `az repos pr` or REST APIs.
No provider should need to edit GitHub code to join the registry.
## T3 Review Design Constraint
Do not optimize only for creation/checkout. The provider layer must be able to support a future in-app review surface.
That means contracts should include stable IDs and enough metadata for:
- file-level diffs
- inline review threads
- resolved/unresolved state
- top-level discussion comments
- pending review submission
- provider URL back-links
Provider-specific fields can live in a metadata bag, but core review behavior should not require the UI to know whether the backing service is GitHub, GitLab, or Azure DevOps.
## Tests
Add tests at three levels:
- Pure parser tests for GitHub, GitLab, and Azure remote URLs and change-request references.
- Provider unit tests with fake `SourceControlProcess` output and schema decode failures.
- Integration-style GitHub CLI tests only where they can run hermetically or be skipped without hiding unit coverage.
Required cases:
- GitHub PR URL, number, and branch-ish references.
- GitLab MR URL/reference parsing.
- Azure DevOps PR URL parsing for same-repo URLs.
- unknown provider returns unsupported-operation errors.
- missing CLI and auth failures produce distinct typed errors.
- invalid CLI JSON fails at decode boundary with useful context.
## Migration Steps
1. Add `sourceControl` contracts and provider-neutral schemas.
2. Add shared remote/reference parser helpers and tests.
3. Add `SourceControlProcess` and provider errors.
4. Add provider registry with GitHub-only registration.
5. Implement `GitHubSourceControlProvider` from scratch against the new process layer.
6. Cut GitHub PR operations in `GitManager` over to the provider registry.
7. Replace web PR-reference parsing with provider-neutral parser output while keeping current GitHub UX.
8. Add provider cache metrics and tests for cache hit, stale refresh, invalidation, and rate-limit error mapping.
9. Delete the migrated `GitHubCli` implementation, tests, and GitHub-specific helper exports unless an explicit transitional checklist remains.
## Acceptance Criteria
- Existing GitHub Commit + PR and PR checkout flows still work.
- `GitManager` no longer imports or depends on `GitHubCli`.
- Active consumers use source-control provider APIs directly; any remaining transitional module has a written removal checklist and no compatibility export shim.
- Source-control contracts can represent GitHub PRs, GitLab MRs, and Azure DevOps PRs.
- Unknown/unsupported providers fail explicitly and visibly.
- GitHub command execution does not depend on `processRunner.ts`.
- Background provider reads are cached/coalesced and do not consume provider API quota on every status refresh.
- Rate-limit responses become typed errors with retry/reset metadata where available.
- The provider API includes the review operations needed by future T3 Review work, even if they are capability-gated.
- `bun fmt`, `bun lint`, and `bun typecheck` pass.
+2
View File
@@ -10,3 +10,5 @@
8. `08-precommit-format-and-lint.md`
9. `09-event-state-test-expansion.md`
10. `10-unify-process-session-abstraction.md`
19. `19-version-control-phase-1-vcs-driver-foundation.md`
20. `20-version-control-phase-2-source-control-provider-foundation.md`
+4 -3
View File
@@ -5,11 +5,12 @@ T3 Code is a minimal web GUI for coding agents (currently Codex and Claude, more
## Installation
> [!WARNING]
> T3 Code currently supports Codex and Claude.
> T3 Code currently supports Codex, Claude, and OpenCode.
> Install and authenticate at least one provider before use:
>
> - Codex: install [Codex CLI](https://github.com/openai/codex) and run `codex login`
> - Claude: install Claude Code and run `claude auth login`
> - Codex: install [Codex CLI](https://developers.openai.com/codex/cli) and run `codex login`
> - Claude: install [Claude Code](https://claude.com/product/claude-code) and run `claude auth login`
> - OpenCode: install [OpenCode](https://opencode.ai) and run `opencode auth login`
### Run without installing
+2 -2
View File
@@ -1,6 +1,6 @@
{
"name": "@t3tools/desktop",
"version": "0.0.20",
"version": "0.0.21",
"private": true,
"type": "module",
"main": "dist-electron/main.cjs",
@@ -16,7 +16,7 @@
},
"dependencies": {
"effect": "catalog:",
"electron": "40.6.0",
"electron": "40.9.3",
"electron-updater": "^6.6.2"
},
"devDependencies": {
@@ -49,10 +49,12 @@ function makeSecretStorage(available: boolean): DesktopSecretStorage {
}
const clientSettings: ClientSettings = {
autoOpenPlanSidebar: false,
confirmThreadArchive: true,
confirmThreadDelete: false,
diffWordWrap: true,
favorites: [],
providerModelPreferences: {},
sidebarProjectGroupingMode: "repository_path",
sidebarProjectGroupingOverrides: {
"environment-1:/tmp/project-a": "separate",
@@ -3,7 +3,8 @@ import { execFileSync } from "node:child_process";
import * as NodeServices from "@effect/platform-node/NodeServices";
import {
ApprovalRequestId,
ProviderKind,
CodexSettings,
ProviderDriverKind,
type OrchestrationEvent,
type OrchestrationThread,
} from "@t3tools/contracts";
@@ -24,10 +25,7 @@ import {
import { CheckpointStoreLive } from "../src/checkpointing/Layers/CheckpointStore.ts";
import { CheckpointStore } from "../src/checkpointing/Services/CheckpointStore.ts";
import { GitCoreLive } from "../src/git/Layers/GitCore.ts";
import { GitCore, type GitCoreShape } from "../src/git/Services/GitCore.ts";
import { GitStatusBroadcaster } from "../src/git/Services/GitStatusBroadcaster.ts";
import { TextGeneration, type TextGenerationShape } from "../src/git/Services/TextGeneration.ts";
import { TextGeneration, type TextGenerationShape } from "../src/textGeneration/TextGeneration.ts";
import { OrchestrationCommandReceiptRepositoryLive } from "../src/persistence/Layers/OrchestrationCommandReceipts.ts";
import { OrchestrationEventStoreLive } from "../src/persistence/Layers/OrchestrationEventStore.ts";
import { ProjectionCheckpointRepositoryLive } from "../src/persistence/Layers/ProjectionCheckpoints.ts";
@@ -36,13 +34,16 @@ import { ProviderSessionRuntimeRepositoryLive } from "../src/persistence/Layers/
import { makeSqlitePersistenceLive } from "../src/persistence/Layers/Sqlite.ts";
import { ProjectionCheckpointRepository } from "../src/persistence/Services/ProjectionCheckpoints.ts";
import { ProjectionPendingApprovalRepository } from "../src/persistence/Services/ProjectionPendingApprovals.ts";
import { ProviderUnsupportedError } from "../src/provider/Errors.ts";
import { makeAdapterRegistryMock } from "../src/provider/testUtils/providerAdapterRegistryMock.ts";
import { ProviderAdapterRegistry } from "../src/provider/Services/ProviderAdapterRegistry.ts";
import { ProviderSessionDirectoryLive } from "../src/provider/Layers/ProviderSessionDirectory.ts";
import { ServerSettingsService } from "../src/serverSettings.ts";
import { makeProviderServiceLive } from "../src/provider/Layers/ProviderService.ts";
import { makeCodexAdapterLive } from "../src/provider/Layers/CodexAdapter.ts";
import { CodexAdapter } from "../src/provider/Services/CodexAdapter.ts";
import { makeCodexAdapter } from "../src/provider/Layers/CodexAdapter.ts";
import {
NoOpProviderEventLoggers,
ProviderEventLoggers,
} from "../src/provider/Layers/ProviderEventLoggers.ts";
import { ProviderService } from "../src/provider/Services/ProviderService.ts";
import { AnalyticsService } from "../src/telemetry/Services/AnalyticsService.ts";
import { CheckpointReactorLive } from "../src/orchestration/Layers/CheckpointReactor.ts";
@@ -73,6 +74,11 @@ import {
import { deriveServerPaths, ServerConfig } from "../src/config.ts";
import { WorkspaceEntriesLive } from "../src/workspace/Layers/WorkspaceEntries.ts";
import { WorkspacePathsLive } from "../src/workspace/Layers/WorkspacePaths.ts";
import * as GitVcsDriver from "../src/vcs/GitVcsDriver.ts";
import * as VcsDriverRegistry from "../src/vcs/VcsDriverRegistry.ts";
import { VcsStatusBroadcaster } from "../src/vcs/VcsStatusBroadcaster.ts";
import { GitWorkflowService } from "../src/git/GitWorkflowService.ts";
import * as VcsProcess from "../src/vcs/VcsProcess.ts";
function runGit(cwd: string, args: ReadonlyArray<string>) {
return execFileSync("git", args, {
@@ -214,7 +220,7 @@ export interface OrchestrationIntegrationHarness {
}
interface MakeOrchestrationIntegrationHarnessOptions {
readonly provider?: ProviderKind;
readonly provider?: ProviderDriverKind;
readonly realCodex?: boolean;
}
@@ -225,7 +231,7 @@ export const makeOrchestrationIntegrationHarness = (
const path = yield* Path.Path;
const fileSystem = yield* FileSystem.FileSystem;
const provider = options?.provider ?? "codex";
const provider = options?.provider ?? ProviderDriverKind.make("codex");
const useRealCodex = options?.realCodex === true;
const adapterHarness = useRealCodex
? null
@@ -233,13 +239,10 @@ export const makeOrchestrationIntegrationHarness = (
provider,
});
const fakeRegistry = adapterHarness
? Layer.succeed(ProviderAdapterRegistry, {
getByProvider: (resolvedProvider) =>
resolvedProvider === adapterHarness.provider
? Effect.succeed(adapterHarness.adapter)
: Effect.fail(new ProviderUnsupportedError({ provider: resolvedProvider })),
listProviders: () => Effect.succeed([adapterHarness.provider]),
} as typeof ProviderAdapterRegistry.Service)
? Layer.succeed(
ProviderAdapterRegistry,
makeAdapterRegistryMock({ [adapterHarness.provider]: adapterHarness.adapter }),
)
: null;
const rootDir = yield* fileSystem.makeTempDirectoryScoped({
prefix: "t3-orchestration-integration-",
@@ -264,34 +267,33 @@ export const makeOrchestrationIntegrationHarness = (
const realCodexRegistry = Layer.effect(
ProviderAdapterRegistry,
Effect.gen(function* () {
const codexAdapter = yield* CodexAdapter;
return {
getByProvider: (resolvedProvider) =>
resolvedProvider === "codex"
? Effect.succeed(codexAdapter)
: Effect.fail(new ProviderUnsupportedError({ provider: resolvedProvider })),
listProviders: () => Effect.succeed(["codex"] as const),
} as typeof ProviderAdapterRegistry.Service;
const codexSettings = Schema.decodeSync(CodexSettings)({});
const codexAdapter = yield* makeCodexAdapter(codexSettings);
return makeAdapterRegistryMock({
[ProviderDriverKind.make("codex")]: codexAdapter,
});
}),
).pipe(
Layer.provide(makeCodexAdapterLive()),
Layer.provideMerge(ServerConfig.layerTest(workspaceDir, rootDir)),
Layer.provideMerge(NodeServices.layer),
Layer.provideMerge(providerSessionDirectoryLayer),
);
const providerEventLoggersLayer = Layer.succeed(ProviderEventLoggers, NoOpProviderEventLoggers);
const providerLayer = useRealCodex
? makeProviderServiceLive().pipe(
Layer.provide(providerSessionDirectoryLayer),
Layer.provide(realCodexRegistry),
Layer.provide(AnalyticsService.layerTest),
Layer.provide(providerEventLoggersLayer),
)
: makeProviderServiceLive().pipe(
Layer.provide(providerSessionDirectoryLayer),
Layer.provide(fakeRegistry!),
Layer.provide(AnalyticsService.layerTest),
Layer.provide(providerEventLoggersLayer),
);
const checkpointStoreLayer = CheckpointStoreLive.pipe(Layer.provide(GitCoreLive));
const checkpointStoreLayer = CheckpointStoreLive.pipe(Layer.provide(VcsDriverRegistry.layer));
const projectionSnapshotQueryLayer = OrchestrationProjectionSnapshotQueryLive;
const runtimeServicesLayer = Layer.mergeAll(
projectionSnapshotQueryLayer,
@@ -307,31 +309,32 @@ export const makeOrchestrationIntegrationHarness = (
Layer.provideMerge(runtimeServicesLayer),
Layer.provideMerge(serverSettingsLayer),
);
const gitCoreLayer = Layer.succeed(GitCore, {
renameBranch: (input: Parameters<GitCoreShape["renameBranch"]>[0]) =>
const gitWorkflowLayer = Layer.mock(GitWorkflowService)({
renameBranch: (input: Parameters<GitVcsDriver.GitVcsDriverShape["renameBranch"]>[0]) =>
Effect.succeed({ branch: input.newBranch }),
} as unknown as GitCoreShape);
});
const textGenerationLayer = Layer.succeed(TextGeneration, {
generateBranchName: () => Effect.succeed({ branch: "update" }),
generateThreadTitle: () => Effect.succeed({ title: "New thread" }),
} as unknown as TextGenerationShape);
const providerCommandReactorLayer = ProviderCommandReactorLive.pipe(
Layer.provideMerge(runtimeServicesLayer),
Layer.provideMerge(gitCoreLayer),
Layer.provideMerge(gitWorkflowLayer),
Layer.provideMerge(textGenerationLayer),
Layer.provideMerge(serverSettingsLayer),
);
const checkpointReactorLayer = CheckpointReactorLive.pipe(
Layer.provideMerge(runtimeServicesLayer),
Layer.provideMerge(
Layer.succeed(GitStatusBroadcaster, {
Layer.succeed(VcsStatusBroadcaster, {
getStatus: () => Effect.die("getStatus should not be called in this test"),
refreshLocalStatus: () =>
Effect.succeed({
isRepo: true,
hasOriginRemote: false,
isDefaultBranch: true,
branch: "main",
kind: "git",
hasPrimaryRemote: false,
isDefaultRef: true,
refName: "main",
hasWorkingTreeChanges: false,
workingTree: { files: [], insertions: 0, deletions: 0 },
}),
@@ -342,11 +345,12 @@ export const makeOrchestrationIntegrationHarness = (
Layer.provideMerge(
WorkspaceEntriesLive.pipe(
Layer.provide(WorkspacePathsLive),
Layer.provideMerge(gitCoreLayer),
Layer.provideMerge(VcsDriverRegistry.layer),
Layer.provide(NodeServices.layer),
),
),
Layer.provideMerge(WorkspacePathsLive),
Layer.provideMerge(VcsProcess.layer),
);
const orchestrationReactorLayer = OrchestrationReactorLive.pipe(
Layer.provideMerge(runtimeIngestionLayer),
@@ -10,7 +10,7 @@ import {
ProviderTurnStartResult,
ThreadId,
TurnId,
ProviderKind,
ProviderDriverKind,
} from "@t3tools/contracts";
import { Effect, Queue, Stream } from "effect";
@@ -36,7 +36,7 @@ export interface TestTurnResponse {
export type FixtureProviderRuntimeEvent = {
readonly type: string;
readonly eventId: EventId;
readonly provider: ProviderKind;
readonly provider: ProviderDriverKind;
readonly createdAt: string;
readonly threadId: string;
readonly turnId?: string | undefined;
@@ -178,7 +178,7 @@ function normalizeFixtureEvent(rawEvent: Record<string, unknown>): ProviderRunti
export interface TestProviderAdapterHarness {
readonly adapter: ProviderAdapterShape<ProviderAdapterError>;
readonly provider: ProviderKind;
readonly provider: ProviderDriverKind;
readonly queueTurnResponse: (
threadId: ThreadId,
response: TestTurnResponse,
@@ -198,7 +198,7 @@ export interface TestProviderAdapterHarness {
}
interface MakeTestProviderAdapterHarnessOptions {
readonly provider?: ProviderKind;
readonly provider?: ProviderDriverKind;
}
function nowIso(): string {
@@ -206,7 +206,7 @@ function nowIso(): string {
}
function sessionNotFound(
provider: ProviderKind,
provider: ProviderDriverKind,
threadId: ThreadId,
): ProviderAdapterSessionNotFoundError {
return new ProviderAdapterSessionNotFoundError({
@@ -216,7 +216,7 @@ function sessionNotFound(
}
function missingSessionEffect(
provider: ProviderKind,
provider: ProviderDriverKind,
threadId: ThreadId,
): Effect.Effect<never, ProviderAdapterError> {
return Effect.fail(sessionNotFound(provider, threadId));
@@ -224,7 +224,7 @@ function missingSessionEffect(
export const makeTestProviderAdapterHarness = (options?: MakeTestProviderAdapterHarnessOptions) =>
Effect.gen(function* () {
const provider = options?.provider ?? "codex";
const provider = options?.provider ?? ProviderDriverKind.make("codex");
const runtimeEvents = yield* Queue.unbounded<ProviderRuntimeEvent>();
let sessionCount = 0;
const sessions = new Map<ThreadId, SessionState>();
@@ -257,6 +257,9 @@ export const makeTestProviderAdapterHarness = (options?: MakeTestProviderAdapter
const session: ProviderSession = {
provider,
...(input.providerInstanceId !== undefined
? { providerInstanceId: input.providerInstanceId }
: {}),
status: "ready",
runtimeMode: input.runtimeMode,
threadId,
@@ -1,7 +1,7 @@
import { EventId, RuntimeRequestId } from "@t3tools/contracts";
import { EventId, ProviderDriverKind, RuntimeRequestId } from "@t3tools/contracts";
import type { LegacyProviderRuntimeEvent } from "../TestProviderAdapter.integration.ts";
const PROVIDER = "codex" as const;
const PROVIDER = ProviderDriverKind.make("codex");
const SESSION_ID = "fixture-session";
const THREAD_ID = "fixture-thread";
const TURN_ID = "fixture-turn";
@@ -4,14 +4,17 @@ import path from "node:path";
import {
ApprovalRequestId,
CommandId,
defaultInstanceIdForDriver,
DEFAULT_PROVIDER_INTERACTION_MODE,
DEFAULT_MODEL,
DEFAULT_MODEL_BY_PROVIDER,
EventId,
MessageId,
ProjectId,
ProviderKind,
ProviderDriverKind,
ThreadId,
ModelSelection,
ProviderInstanceId,
} from "@t3tools/contracts";
import { assert, it } from "@effect/vitest";
import { Effect, Option, Schema } from "effect";
@@ -39,7 +42,9 @@ const PROJECT_ID = asProjectId("project-1");
const THREAD_ID = ThreadId.make("thread-1");
const FIXTURE_TURN_ID = "fixture-turn";
const APPROVAL_REQUEST_ID = asApprovalRequestId("req-approval-1");
type IntegrationProvider = ProviderKind;
type IntegrationProvider = ProviderDriverKind;
const CODEX_PROVIDER = ProviderDriverKind.make("codex");
const CLAUDE_AGENT_PROVIDER = ProviderDriverKind.make("claudeAgent");
function nowIso() {
return new Date().toISOString();
@@ -74,7 +79,11 @@ function waitForSync<A>(
});
}
function runtimeBase(eventId: string, createdAt: string, provider: IntegrationProvider = "codex") {
function runtimeBase(
eventId: string,
createdAt: string,
provider: IntegrationProvider = CODEX_PROVIDER,
) {
return {
eventId: asEventId(eventId),
provider,
@@ -84,7 +93,7 @@ function runtimeBase(eventId: string, createdAt: string, provider: IntegrationPr
function withHarness<A, E>(
use: (harness: OrchestrationIntegrationHarness) => Effect.Effect<A, E>,
provider: IntegrationProvider = "codex",
provider: IntegrationProvider = CODEX_PROVIDER,
) {
return Effect.acquireUseRelease(
makeOrchestrationIntegrationHarness({ provider }),
@@ -97,7 +106,7 @@ function withRealCodexHarness<A, E>(
use: (harness: OrchestrationIntegrationHarness) => Effect.Effect<A, E>,
) {
return Effect.acquireUseRelease(
makeOrchestrationIntegrationHarness({ provider: "codex", realCodex: true }),
makeOrchestrationIntegrationHarness({ provider: CODEX_PROVIDER, realCodex: true }),
use,
(harness) => harness.dispose,
).pipe(Effect.provide(NodeServices.layer));
@@ -106,8 +115,9 @@ function withRealCodexHarness<A, E>(
const seedProjectAndThread = (harness: OrchestrationIntegrationHarness) =>
Effect.gen(function* () {
const createdAt = nowIso();
const provider = harness.adapterHarness?.provider ?? "codex";
const defaultModel = DEFAULT_MODEL_BY_PROVIDER[provider];
const provider = harness.adapterHarness?.provider ?? CODEX_PROVIDER;
const defaultModel = DEFAULT_MODEL_BY_PROVIDER[provider] ?? DEFAULT_MODEL;
const instanceId = defaultInstanceIdForDriver(provider);
yield* harness.engine.dispatch({
type: "project.create",
@@ -116,7 +126,7 @@ const seedProjectAndThread = (harness: OrchestrationIntegrationHarness) =>
title: "Integration Project",
workspaceRoot: harness.workspaceDir,
defaultModelSelection: {
provider,
instanceId,
model: defaultModel,
},
createdAt,
@@ -129,7 +139,7 @@ const seedProjectAndThread = (harness: OrchestrationIntegrationHarness) =>
projectId: PROJECT_ID,
title: "Integration Thread",
modelSelection: {
provider,
instanceId,
model: defaultModel,
},
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
@@ -265,7 +275,7 @@ it.live.skipIf(!process.env.CODEX_BINARY_PATH)(
title: "Integration Project",
workspaceRoot: harness.workspaceDir,
defaultModelSelection: {
provider: "codex",
instanceId: ProviderInstanceId.make("codex"),
model: "gpt-5.3-codex",
},
createdAt,
@@ -278,7 +288,7 @@ it.live.skipIf(!process.env.CODEX_BINARY_PATH)(
projectId: PROJECT_ID,
title: "Integration Thread",
modelSelection: {
provider: "codex",
instanceId: ProviderInstanceId.make("codex"),
model: "gpt-5.3-codex",
},
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
@@ -912,20 +922,32 @@ it.live("starts a claudeAgent session on first turn when provider is requested",
events: [
{
type: "turn.started",
...runtimeBase("evt-claude-start-1", "2026-02-24T10:10:00.000Z", "claudeAgent"),
...runtimeBase(
"evt-claude-start-1",
"2026-02-24T10:10:00.000Z",
CLAUDE_AGENT_PROVIDER,
),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
},
{
type: "message.delta",
...runtimeBase("evt-claude-start-2", "2026-02-24T10:10:00.050Z", "claudeAgent"),
...runtimeBase(
"evt-claude-start-2",
"2026-02-24T10:10:00.050Z",
CLAUDE_AGENT_PROVIDER,
),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
delta: "Claude first turn.\n",
},
{
type: "turn.completed",
...runtimeBase("evt-claude-start-3", "2026-02-24T10:10:00.100Z", "claudeAgent"),
...runtimeBase(
"evt-claude-start-3",
"2026-02-24T10:10:00.100Z",
CLAUDE_AGENT_PROVIDER,
),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
status: "completed",
@@ -939,7 +961,7 @@ it.live("starts a claudeAgent session on first turn when provider is requested",
messageId: "msg-user-claude-initial",
text: "Use Claude",
modelSelection: {
provider: "claudeAgent",
instanceId: ProviderInstanceId.make("claudeAgent"),
model: "claude-sonnet-4-6",
},
});
@@ -955,7 +977,7 @@ it.live("starts a claudeAgent session on first turn when provider is requested",
);
assert.equal(thread.session?.providerName, "claudeAgent");
}),
"claudeAgent",
CLAUDE_AGENT_PROVIDER,
),
);
@@ -969,20 +991,32 @@ it.live("recovers claudeAgent sessions after provider stopAll using persisted re
events: [
{
type: "turn.started",
...runtimeBase("evt-claude-recover-1", "2026-02-24T10:11:00.000Z", "claudeAgent"),
...runtimeBase(
"evt-claude-recover-1",
"2026-02-24T10:11:00.000Z",
CLAUDE_AGENT_PROVIDER,
),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
},
{
type: "message.delta",
...runtimeBase("evt-claude-recover-2", "2026-02-24T10:11:00.050Z", "claudeAgent"),
...runtimeBase(
"evt-claude-recover-2",
"2026-02-24T10:11:00.050Z",
CLAUDE_AGENT_PROVIDER,
),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
delta: "Turn before restart.\n",
},
{
type: "turn.completed",
...runtimeBase("evt-claude-recover-3", "2026-02-24T10:11:00.100Z", "claudeAgent"),
...runtimeBase(
"evt-claude-recover-3",
"2026-02-24T10:11:00.100Z",
CLAUDE_AGENT_PROVIDER,
),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
status: "completed",
@@ -996,7 +1030,7 @@ it.live("recovers claudeAgent sessions after provider stopAll using persisted re
messageId: "msg-user-claude-recover-1",
text: "Before restart",
modelSelection: {
provider: "claudeAgent",
instanceId: ProviderInstanceId.make("claudeAgent"),
model: "claude-sonnet-4-6",
},
});
@@ -1018,20 +1052,32 @@ it.live("recovers claudeAgent sessions after provider stopAll using persisted re
events: [
{
type: "turn.started",
...runtimeBase("evt-claude-recover-4", "2026-02-24T10:11:01.000Z", "claudeAgent"),
...runtimeBase(
"evt-claude-recover-4",
"2026-02-24T10:11:01.000Z",
CLAUDE_AGENT_PROVIDER,
),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
},
{
type: "message.delta",
...runtimeBase("evt-claude-recover-5", "2026-02-24T10:11:01.050Z", "claudeAgent"),
...runtimeBase(
"evt-claude-recover-5",
"2026-02-24T10:11:01.050Z",
CLAUDE_AGENT_PROVIDER,
),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
delta: "Turn after restart.\n",
},
{
type: "turn.completed",
...runtimeBase("evt-claude-recover-6", "2026-02-24T10:11:01.100Z", "claudeAgent"),
...runtimeBase(
"evt-claude-recover-6",
"2026-02-24T10:11:01.100Z",
CLAUDE_AGENT_PROVIDER,
),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
status: "completed",
@@ -1063,7 +1109,7 @@ it.live("recovers claudeAgent sessions after provider stopAll using persisted re
assert.equal(recoveredThread.session?.providerName, "claudeAgent");
assert.equal(recoveredThread.session?.threadId, "thread-1");
}),
"claudeAgent",
CLAUDE_AGENT_PROVIDER,
),
);
@@ -1077,13 +1123,21 @@ it.live("forwards claudeAgent approval responses to the provider session", () =>
events: [
{
type: "turn.started",
...runtimeBase("evt-claude-approval-1", "2026-02-24T10:12:00.000Z", "claudeAgent"),
...runtimeBase(
"evt-claude-approval-1",
"2026-02-24T10:12:00.000Z",
CLAUDE_AGENT_PROVIDER,
),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
},
{
type: "approval.requested",
...runtimeBase("evt-claude-approval-2", "2026-02-24T10:12:00.050Z", "claudeAgent"),
...runtimeBase(
"evt-claude-approval-2",
"2026-02-24T10:12:00.050Z",
CLAUDE_AGENT_PROVIDER,
),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
requestId: APPROVAL_REQUEST_ID,
@@ -1092,7 +1146,11 @@ it.live("forwards claudeAgent approval responses to the provider session", () =>
},
{
type: "turn.completed",
...runtimeBase("evt-claude-approval-3", "2026-02-24T10:12:00.100Z", "claudeAgent"),
...runtimeBase(
"evt-claude-approval-3",
"2026-02-24T10:12:00.100Z",
CLAUDE_AGENT_PROVIDER,
),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
status: "completed",
@@ -1106,7 +1164,7 @@ it.live("forwards claudeAgent approval responses to the provider session", () =>
messageId: "msg-user-claude-approval",
text: "Need approval",
modelSelection: {
provider: "claudeAgent",
instanceId: ProviderInstanceId.make("claudeAgent"),
model: "claude-sonnet-4-6",
},
});
@@ -1137,7 +1195,7 @@ it.live("forwards claudeAgent approval responses to the provider session", () =>
);
assert.equal(approvalResponses[0]?.decision, "accept");
}),
"claudeAgent",
CLAUDE_AGENT_PROVIDER,
),
);
@@ -1151,20 +1209,32 @@ it.live("forwards thread.turn.interrupt to claudeAgent provider sessions", () =>
events: [
{
type: "turn.started",
...runtimeBase("evt-claude-interrupt-1", "2026-02-24T10:13:00.000Z", "claudeAgent"),
...runtimeBase(
"evt-claude-interrupt-1",
"2026-02-24T10:13:00.000Z",
CLAUDE_AGENT_PROVIDER,
),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
},
{
type: "message.delta",
...runtimeBase("evt-claude-interrupt-2", "2026-02-24T10:13:00.050Z", "claudeAgent"),
...runtimeBase(
"evt-claude-interrupt-2",
"2026-02-24T10:13:00.050Z",
CLAUDE_AGENT_PROVIDER,
),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
delta: "Long running output.\n",
},
{
type: "turn.completed",
...runtimeBase("evt-claude-interrupt-3", "2026-02-24T10:13:00.100Z", "claudeAgent"),
...runtimeBase(
"evt-claude-interrupt-3",
"2026-02-24T10:13:00.100Z",
CLAUDE_AGENT_PROVIDER,
),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
status: "completed",
@@ -1178,7 +1248,7 @@ it.live("forwards thread.turn.interrupt to claudeAgent provider sessions", () =>
messageId: "msg-user-claude-interrupt",
text: "Start long turn",
modelSelection: {
provider: "claudeAgent",
instanceId: ProviderInstanceId.make("claudeAgent"),
model: "claude-sonnet-4-6",
},
});
@@ -1206,7 +1276,7 @@ it.live("forwards thread.turn.interrupt to claudeAgent provider sessions", () =>
);
assert.equal(interruptCalls.length, 1);
}),
"claudeAgent",
CLAUDE_AGENT_PROVIDER,
),
);
@@ -1220,20 +1290,32 @@ it.live("reverts claudeAgent turns and rolls back provider conversation state",
events: [
{
type: "turn.started",
...runtimeBase("evt-claude-revert-1", "2026-02-24T10:14:00.000Z", "claudeAgent"),
...runtimeBase(
"evt-claude-revert-1",
"2026-02-24T10:14:00.000Z",
CLAUDE_AGENT_PROVIDER,
),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
},
{
type: "message.delta",
...runtimeBase("evt-claude-revert-2", "2026-02-24T10:14:00.050Z", "claudeAgent"),
...runtimeBase(
"evt-claude-revert-2",
"2026-02-24T10:14:00.050Z",
CLAUDE_AGENT_PROVIDER,
),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
delta: "README -> v2\n",
},
{
type: "turn.completed",
...runtimeBase("evt-claude-revert-3", "2026-02-24T10:14:00.100Z", "claudeAgent"),
...runtimeBase(
"evt-claude-revert-3",
"2026-02-24T10:14:00.100Z",
CLAUDE_AGENT_PROVIDER,
),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
status: "completed",
@@ -1251,7 +1333,7 @@ it.live("reverts claudeAgent turns and rolls back provider conversation state",
messageId: "msg-user-claude-revert-1",
text: "First Claude edit",
modelSelection: {
provider: "claudeAgent",
instanceId: ProviderInstanceId.make("claudeAgent"),
model: "claude-sonnet-4-6",
},
});
@@ -1266,20 +1348,32 @@ it.live("reverts claudeAgent turns and rolls back provider conversation state",
events: [
{
type: "turn.started",
...runtimeBase("evt-claude-revert-4", "2026-02-24T10:14:01.000Z", "claudeAgent"),
...runtimeBase(
"evt-claude-revert-4",
"2026-02-24T10:14:01.000Z",
CLAUDE_AGENT_PROVIDER,
),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
},
{
type: "message.delta",
...runtimeBase("evt-claude-revert-5", "2026-02-24T10:14:01.050Z", "claudeAgent"),
...runtimeBase(
"evt-claude-revert-5",
"2026-02-24T10:14:01.050Z",
CLAUDE_AGENT_PROVIDER,
),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
delta: "README -> v3\n",
},
{
type: "turn.completed",
...runtimeBase("evt-claude-revert-6", "2026-02-24T10:14:01.100Z", "claudeAgent"),
...runtimeBase(
"evt-claude-revert-6",
"2026-02-24T10:14:01.100Z",
CLAUDE_AGENT_PROVIDER,
),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
status: "completed",
@@ -1330,6 +1424,6 @@ it.live("reverts claudeAgent turns and rolls back provider conversation state",
);
assert.deepEqual(harness.adapterHarness!.getRollbackCalls(THREAD_ID), [1]);
}),
"claudeAgent",
CLAUDE_AGENT_PROVIDER,
),
);
@@ -1,13 +1,17 @@
import type { ProviderRuntimeEvent } from "@t3tools/contracts";
import { ThreadId } from "@t3tools/contracts";
import { ProviderDriverKind, ProviderInstanceId, ThreadId } from "@t3tools/contracts";
import { DEFAULT_SERVER_SETTINGS } from "@t3tools/contracts/settings";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { it, assert } from "@effect/vitest";
import { Effect, FileSystem, Layer, Path, Queue, Stream } from "effect";
import { ProviderUnsupportedError } from "../src/provider/Errors.ts";
import { ProviderAdapterRegistry } from "../src/provider/Services/ProviderAdapterRegistry.ts";
import { makeAdapterRegistryMock } from "../src/provider/testUtils/providerAdapterRegistryMock.ts";
import { ProviderSessionDirectoryLive } from "../src/provider/Layers/ProviderSessionDirectory.ts";
import {
NoOpProviderEventLoggers,
ProviderEventLoggers,
} from "../src/provider/Layers/ProviderEventLoggers.ts";
import { makeProviderServiceLive } from "../src/provider/Layers/ProviderService.ts";
import {
ProviderService,
@@ -29,6 +33,8 @@ import {
codexTurnTextFixture,
} from "./fixtures/providerRuntime.ts";
const codexInstanceId = ProviderInstanceId.make("codex");
const makeWorkspaceDirectory = Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const pathService = yield* Path.Path;
@@ -47,13 +53,9 @@ const makeIntegrationFixture = Effect.gen(function* () {
const cwd = yield* makeWorkspaceDirectory;
const harness = yield* makeTestProviderAdapterHarness();
const registry: typeof ProviderAdapterRegistry.Service = {
getByProvider: (provider) =>
provider === "codex"
? Effect.succeed(harness.adapter)
: Effect.fail(new ProviderUnsupportedError({ provider })),
listProviders: () => Effect.succeed(["codex"]),
};
const registry = makeAdapterRegistryMock({
[ProviderDriverKind.make("codex")]: harness.adapter,
});
const directoryLayer = ProviderSessionDirectoryLive.pipe(
Layer.provide(ProviderSessionRuntimeRepositoryLive),
@@ -64,6 +66,7 @@ const makeIntegrationFixture = Effect.gen(function* () {
Layer.succeed(ProviderAdapterRegistry, registry),
ServerSettingsService.layerTest(DEFAULT_SERVER_SETTINGS),
AnalyticsService.layerTest,
Layer.succeed(ProviderEventLoggers, NoOpProviderEventLoggers),
).pipe(Layer.provide(SqlitePersistenceMemory));
const layer = makeProviderServiceLive().pipe(Layer.provide(shared));
@@ -124,7 +127,8 @@ it.live("replays typed runtime fixture events", () =>
const provider = yield* ProviderService;
const session = yield* provider.startSession(ThreadId.make("thread-integration-typed"), {
threadId: ThreadId.make("thread-integration-typed"),
provider: "codex",
provider: ProviderDriverKind.make("codex"),
providerInstanceId: codexInstanceId,
cwd: fixture.cwd,
runtimeMode: "full-access",
});
@@ -142,6 +146,10 @@ it.live("replays typed runtime fixture events", () =>
observedEvents.map((event) => event.type),
codexTurnTextFixture.map((event) => event.type),
);
assert.deepEqual(
observedEvents.map((event) => event.providerInstanceId),
codexTurnTextFixture.map(() => codexInstanceId),
);
}).pipe(Effect.provide(fixture.layer));
}).pipe(Effect.provide(NodeServices.layer)),
);
@@ -156,7 +164,8 @@ it.live("replays file-changing fixture turn events", () =>
const provider = yield* ProviderService;
const session = yield* provider.startSession(ThreadId.make("thread-integration-tools"), {
threadId: ThreadId.make("thread-integration-tools"),
provider: "codex",
provider: ProviderDriverKind.make("codex"),
providerInstanceId: codexInstanceId,
cwd: fixture.cwd,
runtimeMode: "full-access",
});
@@ -192,7 +201,8 @@ it.live("runs multi-turn tool/approval flow", () =>
const provider = yield* ProviderService;
const session = yield* provider.startSession(ThreadId.make("thread-integration-multi"), {
threadId: ThreadId.make("thread-integration-multi"),
provider: "codex",
provider: ProviderDriverKind.make("codex"),
providerInstanceId: codexInstanceId,
cwd: fixture.cwd,
runtimeMode: "full-access",
});
@@ -243,7 +253,8 @@ it.live("rolls back provider conversation state only", () =>
const provider = yield* ProviderService;
const session = yield* provider.startSession(ThreadId.make("thread-integration-rollback"), {
threadId: ThreadId.make("thread-integration-rollback"),
provider: "codex",
provider: ProviderDriverKind.make("codex"),
providerInstanceId: codexInstanceId,
cwd: fixture.cwd,
runtimeMode: "full-access",
});
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "t3",
"version": "0.0.20",
"version": "0.0.21",
"license": "MIT",
"repository": {
"type": "git",
+2 -5
View File
@@ -1,6 +1,6 @@
import { Schema } from "effect";
import type { ProjectionRepositoryError } from "../persistence/Errors.ts";
import { GitCommandError } from "@t3tools/contracts";
import type { VcsError } from "@t3tools/contracts";
/**
* CheckpointUnavailableError - Expected checkpoint does not exist.
@@ -35,9 +35,6 @@ export class CheckpointInvariantError extends Schema.TaggedErrorClass<Checkpoint
}
}
export type CheckpointStoreError =
| GitCommandError
| CheckpointInvariantError
| CheckpointUnavailableError;
export type CheckpointStoreError = VcsError | CheckpointInvariantError | CheckpointUnavailableError;
export type CheckpointServiceError = CheckpointStoreError | ProjectionRepositoryError;
@@ -8,24 +8,27 @@ import { describe, expect } from "vitest";
import { checkpointRefForThreadTurn } from "../Utils.ts";
import { CheckpointStoreLive } from "./CheckpointStore.ts";
import { CheckpointStore } from "../Services/CheckpointStore.ts";
import { GitCoreLive } from "../../git/Layers/GitCore.ts";
import { GitCore } from "../../git/Services/GitCore.ts";
import { GitCommandError } from "@t3tools/contracts";
import * as VcsDriverRegistry from "../../vcs/VcsDriverRegistry.ts";
import * as VcsProcess from "../../vcs/VcsProcess.ts";
import type { VcsError } from "@t3tools/contracts";
import { ServerConfig } from "../../config.ts";
import { ThreadId } from "@t3tools/contracts";
const ServerConfigLayer = ServerConfig.layerTest(process.cwd(), {
prefix: "t3-checkpoint-store-test-",
});
const GitCoreTestLayer = GitCoreLive.pipe(
Layer.provide(ServerConfigLayer),
Layer.provide(NodeServices.layer),
);
const VcsProcessTestLayer = VcsProcess.layer.pipe(Layer.provide(NodeServices.layer));
const VcsDriverTestLayer = VcsDriverRegistry.layer.pipe(Layer.provide(VcsProcessTestLayer));
const CheckpointStoreTestLayer = CheckpointStoreLive.pipe(
Layer.provide(GitCoreTestLayer),
Layer.provide(NodeServices.layer),
Layer.provideMerge(VcsDriverTestLayer),
Layer.provideMerge(NodeServices.layer),
);
const TestLayer = CheckpointStoreTestLayer.pipe(
Layer.provideMerge(VcsProcessTestLayer),
Layer.provideMerge(VcsDriverTestLayer),
Layer.provideMerge(ServerConfigLayer),
Layer.provideMerge(NodeServices.layer),
);
const TestLayer = Layer.mergeAll(NodeServices.layer, GitCoreTestLayer, CheckpointStoreTestLayer);
function makeTmpDir(
prefix = "checkpoint-store-test-",
@@ -49,11 +52,12 @@ function writeTextFile(
function git(
cwd: string,
args: ReadonlyArray<string>,
): Effect.Effect<string, GitCommandError, GitCore> {
): Effect.Effect<string, VcsError, VcsProcess.VcsProcess> {
return Effect.gen(function* () {
const gitCore = yield* GitCore;
const result = yield* gitCore.execute({
const process = yield* VcsProcess.VcsProcess;
const result = yield* process.run({
operation: "CheckpointStore.test.git",
command: "git",
cwd,
args,
timeoutMs: 10_000,
@@ -66,12 +70,11 @@ function initRepoWithCommit(
cwd: string,
): Effect.Effect<
void,
GitCommandError | PlatformError.PlatformError,
GitCore | FileSystem.FileSystem
VcsError | PlatformError.PlatformError,
VcsProcess.VcsProcess | FileSystem.FileSystem
> {
return Effect.gen(function* () {
const core = yield* GitCore;
yield* core.initRepo({ cwd });
yield* git(cwd, ["init"]);
yield* git(cwd, ["config", "user.email", "[email protected]"]);
yield* git(cwd, ["config", "user.name", "Test"]);
yield* writeTextFile(path.join(cwd, "README.md"), "# test\n");
@@ -14,8 +14,8 @@ import { randomUUID } from "node:crypto";
import { Effect, Layer, FileSystem, Path } from "effect";
import { CheckpointInvariantError } from "../Errors.ts";
import { GitCommandError } from "@t3tools/contracts";
import { GitCore } from "../../git/Services/GitCore.ts";
import { VcsProcessExitError } from "@t3tools/contracts";
import { VcsDriverRegistry } from "../../vcs/VcsDriverRegistry.ts";
import { CheckpointStore, type CheckpointStoreShape } from "../Services/CheckpointStore.ts";
import { CheckpointRef } from "@t3tools/contracts";
@@ -24,10 +24,26 @@ const CHECKPOINT_DIFF_MAX_OUTPUT_BYTES = 10_000_000;
const makeCheckpointStore = Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const git = yield* GitCore;
const vcsRegistry = yield* VcsDriverRegistry;
const vcs = {
execute: (input: {
readonly operation: string;
readonly cwd: string;
readonly args: ReadonlyArray<string>;
readonly stdin?: string;
readonly env?: NodeJS.ProcessEnv;
readonly allowNonZeroExit?: boolean;
readonly timeoutMs?: number;
readonly maxOutputBytes?: number;
readonly truncateOutputAtMaxBytes?: boolean;
}) =>
vcsRegistry
.resolve({ cwd: input.cwd, requestedKind: "git" })
.pipe(Effect.flatMap((handle) => handle.driver.execute(input))),
};
const resolveHeadCommit = (cwd: string): Effect.Effect<string | null, GitCommandError> =>
git
const resolveHeadCommit = (cwd: string) =>
vcs
.execute({
operation: "CheckpointStore.resolveHeadCommit",
cwd,
@@ -36,7 +52,7 @@ const makeCheckpointStore = Effect.gen(function* () {
})
.pipe(
Effect.map((result) => {
if (result.code !== 0) {
if (result.exitCode !== 0) {
return null;
}
const commit = result.stdout.trim();
@@ -44,21 +60,18 @@ const makeCheckpointStore = Effect.gen(function* () {
}),
);
const hasHeadCommit = (cwd: string): Effect.Effect<boolean, GitCommandError> =>
git
const hasHeadCommit = (cwd: string) =>
vcs
.execute({
operation: "CheckpointStore.hasHeadCommit",
cwd,
args: ["rev-parse", "--verify", "HEAD"],
allowNonZeroExit: true,
})
.pipe(Effect.map((result) => result.code === 0));
.pipe(Effect.map((result) => result.exitCode === 0));
const resolveCheckpointCommit = (
cwd: string,
checkpointRef: CheckpointRef,
): Effect.Effect<string | null, GitCommandError> =>
git
const resolveCheckpointCommit = (cwd: string, checkpointRef: CheckpointRef) =>
vcs
.execute({
operation: "CheckpointStore.resolveCheckpointCommit",
cwd,
@@ -67,7 +80,7 @@ const makeCheckpointStore = Effect.gen(function* () {
})
.pipe(
Effect.map((result) => {
if (result.code !== 0) {
if (result.exitCode !== 0) {
return null;
}
const commit = result.stdout.trim();
@@ -76,7 +89,7 @@ const makeCheckpointStore = Effect.gen(function* () {
);
const isGitRepository: CheckpointStoreShape["isGitRepository"] = (cwd) =>
git
vcs
.execute({
operation: "CheckpointStore.isGitRepository",
cwd,
@@ -84,7 +97,7 @@ const makeCheckpointStore = Effect.gen(function* () {
allowNonZeroExit: true,
})
.pipe(
Effect.map((result) => result.code === 0 && result.stdout.trim() === "true"),
Effect.map((result) => result.exitCode === 0 && result.stdout.trim() === "true"),
Effect.catch(() => Effect.succeed(false)),
);
@@ -108,7 +121,7 @@ const makeCheckpointStore = Effect.gen(function* () {
const headExists = yield* hasHeadCommit(input.cwd);
if (headExists) {
yield* git.execute({
yield* vcs.execute({
operation,
cwd: input.cwd,
args: ["read-tree", "HEAD"],
@@ -116,14 +129,14 @@ const makeCheckpointStore = Effect.gen(function* () {
});
}
yield* git.execute({
yield* vcs.execute({
operation,
cwd: input.cwd,
args: ["add", "-A", "--", "."],
env: commitEnv,
});
const writeTreeResult = yield* git.execute({
const writeTreeResult = yield* vcs.execute({
operation,
cwd: input.cwd,
args: ["write-tree"],
@@ -131,16 +144,17 @@ const makeCheckpointStore = Effect.gen(function* () {
});
const treeOid = writeTreeResult.stdout.trim();
if (treeOid.length === 0) {
return yield* new GitCommandError({
return yield* new VcsProcessExitError({
operation,
command: "git write-tree",
cwd: input.cwd,
exitCode: 0,
detail: "git write-tree returned an empty tree oid.",
});
}
const message = `t3 checkpoint ref=${input.checkpointRef}`;
const commitTreeResult = yield* git.execute({
const commitTreeResult = yield* vcs.execute({
operation,
cwd: input.cwd,
args: ["commit-tree", treeOid, "-m", message],
@@ -148,15 +162,16 @@ const makeCheckpointStore = Effect.gen(function* () {
});
const commitOid = commitTreeResult.stdout.trim();
if (commitOid.length === 0) {
return yield* new GitCommandError({
return yield* new VcsProcessExitError({
operation,
command: "git commit-tree",
cwd: input.cwd,
exitCode: 0,
detail: "git commit-tree returned an empty commit oid.",
});
}
yield* git.execute({
yield* vcs.execute({
operation,
cwd: input.cwd,
args: ["update-ref", input.checkpointRef, commitOid],
@@ -197,12 +212,12 @@ const makeCheckpointStore = Effect.gen(function* () {
return false;
}
yield* git.execute({
yield* vcs.execute({
operation,
cwd: input.cwd,
args: ["restore", "--source", commitOid, "--worktree", "--staged", "--", "."],
});
yield* git.execute({
yield* vcs.execute({
operation,
cwd: input.cwd,
args: ["clean", "-fd", "--", "."],
@@ -210,7 +225,7 @@ const makeCheckpointStore = Effect.gen(function* () {
const headExists = yield* hasHeadCommit(input.cwd);
if (headExists) {
yield* git.execute({
yield* vcs.execute({
operation,
cwd: input.cwd,
args: ["reset", "--quiet", "--", "."],
@@ -235,15 +250,16 @@ const makeCheckpointStore = Effect.gen(function* () {
}
if (!fromCommitOid || !toCommitOid) {
return yield* new GitCommandError({
return yield* new VcsProcessExitError({
operation,
command: "git diff",
cwd: input.cwd,
exitCode: 1,
detail: "Checkpoint ref is unavailable for diff operation.",
});
}
const result = yield* git.execute({
const result = yield* vcs.execute({
operation,
cwd: input.cwd,
args: ["diff", "--patch", "--minimal", "--no-color", fromCommitOid, toCommitOid],
@@ -262,7 +278,7 @@ const makeCheckpointStore = Effect.gen(function* () {
yield* Effect.forEach(
input.checkpointRefs,
(checkpointRef) =>
git.execute({
vcs.execute({
operation,
cwd: input.cwd,
args: ["update-ref", "-d", checkpointRef],
@@ -14,23 +14,25 @@ import type {
} from "@t3tools/contracts";
import { GitCommandError, GitHubCliError, TextGenerationError } from "@t3tools/contracts";
import { type GitManagerShape } from "../Services/GitManager.ts";
import { type GitManagerShape } from "./GitManager.ts";
import {
type GitHubCliShape,
type GitHubPullRequestSummary,
GitHubCli,
} from "../Services/GitHubCli.ts";
import { type TextGenerationShape, TextGeneration } from "../Services/TextGeneration.ts";
import { GitCoreLive } from "./GitCore.ts";
import { GitCore } from "../Services/GitCore.ts";
} from "../sourceControl/GitHubCli.ts";
import { type TextGenerationShape, TextGeneration } from "../textGeneration/TextGeneration.ts";
import * as GitVcsDriver from "../vcs/GitVcsDriver.ts";
import * as VcsProcess from "../vcs/VcsProcess.ts";
import * as GitHubSourceControlProvider from "../sourceControl/GitHubSourceControlProvider.ts";
import * as SourceControlProviderRegistry from "../sourceControl/SourceControlProviderRegistry.ts";
import { makeGitManager } from "./GitManager.ts";
import { ServerConfig } from "../../config.ts";
import { ServerSettingsService } from "../../serverSettings.ts";
import { ServerConfig } from "../config.ts";
import { ServerSettingsService } from "../serverSettings.ts";
import {
ProjectSetupScriptRunner,
type ProjectSetupScriptRunnerInput,
type ProjectSetupScriptRunnerShape,
} from "../../project/Services/ProjectSetupScriptRunner.ts";
} from "../project/Services/ProjectSetupScriptRunner.ts";
interface FakeGhScenario {
prListSequence?: string[];
@@ -209,18 +211,27 @@ function runGit(
args: readonly string[],
allowNonZeroExit = false,
): Effect.Effect<
{ readonly code: number; readonly stdout: string; readonly stderr: string },
{
readonly exitCode: GitVcsDriver.ExecuteGitResult["exitCode"];
readonly stdout: string;
readonly stderr: string;
},
GitCommandError,
GitCore
GitVcsDriver.GitVcsDriver
> {
return Effect.gen(function* () {
const gitCore = yield* GitCore;
return yield* gitCore.execute({
const git = yield* GitVcsDriver.GitVcsDriver;
const result = yield* git.execute({
operation: "GitManager.test.runGit",
cwd,
args,
allowNonZeroExit,
});
return {
exitCode: result.exitCode,
stdout: result.stdout,
stderr: result.stderr,
};
});
}
@@ -229,7 +240,7 @@ function initRepo(
): Effect.Effect<
void,
PlatformError.PlatformError | GitCommandError,
FileSystem.FileSystem | Scope.Scope | GitCore
FileSystem.FileSystem | Scope.Scope | GitVcsDriver.GitVcsDriver
> {
return Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
@@ -245,7 +256,7 @@ function initRepo(
function createBareRemote(): Effect.Effect<
string,
PlatformError.PlatformError | GitCommandError,
FileSystem.FileSystem | Scope.Scope | GitCore
FileSystem.FileSystem | Scope.Scope | GitVcsDriver.GitVcsDriver
> {
return Effect.gen(function* () {
const remoteDir = yield* makeTempDir("t3code-git-remote-");
@@ -259,7 +270,7 @@ function configureRemote(
remoteName: string,
remotePath: string,
fetchNamespace: string,
): Effect.Effect<void, GitCommandError, GitCore> {
): Effect.Effect<void, GitCommandError, GitVcsDriver.GitVcsDriver> {
return Effect.gen(function* () {
yield* runGit(cwd, ["config", `remote.${remoteName}.url`, remotePath]);
yield* runGit(cwd, [
@@ -639,13 +650,24 @@ function makeManager(input?: {
const serverSettingsLayer = ServerSettingsService.layerTest();
const gitCoreLayer = GitCoreLive.pipe(
const vcsDriverLayer = GitVcsDriver.layer.pipe(
Layer.provideMerge(VcsProcess.layer),
Layer.provideMerge(NodeServices.layer),
Layer.provideMerge(ServerConfigLayer),
);
const sourceControlRegistryLayer = Layer.effect(
SourceControlProviderRegistry.SourceControlProviderRegistry,
GitHubSourceControlProvider.make().pipe(
Effect.map((provider) =>
SourceControlProviderRegistry.SourceControlProviderRegistry.of({
resolve: () => Effect.succeed(provider),
}),
),
Effect.provide(Layer.succeed(GitHubCli, gitHubCli)),
),
);
const managerLayer = Layer.mergeAll(
Layer.succeed(GitHubCli, gitHubCli),
Layer.succeed(TextGeneration, textGeneration),
Layer.succeed(
ProjectSetupScriptRunner,
@@ -653,9 +675,9 @@ function makeManager(input?: {
runForThread: () => Effect.succeed({ status: "no-script" as const }),
},
),
gitCoreLayer,
vcsDriverLayer,
serverSettingsLayer,
).pipe(Layer.provideMerge(NodeServices.layer));
).pipe(Layer.provideMerge(sourceControlRegistryLayer), Layer.provideMerge(NodeServices.layer));
return makeGitManager().pipe(
Effect.provide(managerLayer),
@@ -665,8 +687,9 @@ function makeManager(input?: {
const asThreadId = (threadId: string) => threadId as ThreadId;
const GitManagerTestLayer = GitCoreLive.pipe(
const GitManagerTestLayer = GitVcsDriver.layer.pipe(
Layer.provide(ServerConfig.layerTest(process.cwd(), { prefix: "t3-git-manager-test-" })),
Layer.provideMerge(VcsProcess.layer),
Layer.provideMerge(NodeServices.layer),
);
@@ -698,15 +721,15 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
const status = yield* manager.status({ cwd: repoDir });
expect(status.isRepo).toBe(true);
expect(status.hasOriginRemote).toBe(true);
expect(status.isDefaultBranch).toBe(false);
expect(status.branch).toBe("feature/status-open-pr");
expect(status.hasPrimaryRemote).toBe(true);
expect(status.isDefaultRef).toBe(false);
expect(status.refName).toBe("feature/status-open-pr");
expect(status.pr).toEqual({
number: 13,
title: "Existing PR",
url: "https://github.com/pingdotgg/codething-mvp/pull/13",
baseBranch: "main",
headBranch: "feature/status-open-pr",
baseRef: "main",
headRef: "feature/status-open-pr",
state: "open",
});
}),
@@ -743,8 +766,8 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
number: 14,
title: "Existing PR title",
url: "https://github.com/pingdotgg/codething-mvp/pull/14",
baseBranch: "main",
headBranch: "feature/status-trimmed-pr",
baseRef: "main",
headRef: "feature/status-trimmed-pr",
state: "open",
});
}),
@@ -794,8 +817,8 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
number: 15,
title: "Valid PR title",
url: "https://github.com/pingdotgg/codething-mvp/pull/15",
baseBranch: "main",
headBranch: "feature/status-valid-pr-entry",
baseRef: "main",
headRef: "feature/status-valid-pr-entry",
state: "open",
});
}),
@@ -843,8 +866,8 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
number: 17,
title: "Merged PR",
url: "https://github.com/pingdotgg/codething-mvp/pull/17",
baseBranch: "main",
headBranch: "feature/status-lowercase-state",
baseRef: "main",
headRef: "feature/status-lowercase-state",
state: "merged",
});
}),
@@ -859,9 +882,9 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
expect(status).toEqual({
isRepo: false,
hasOriginRemote: false,
isDefaultBranch: false,
branch: null,
hasPrimaryRemote: false,
isDefaultRef: false,
refName: null,
hasWorkingTreeChanges: false,
workingTree: {
files: [],
@@ -888,9 +911,9 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
expect(status).toEqual({
isRepo: false,
hasOriginRemote: false,
isDefaultBranch: false,
branch: null,
hasPrimaryRemote: false,
isDefaultRef: false,
refName: null,
hasWorkingTreeChanges: false,
workingTree: {
files: [],
@@ -972,7 +995,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
});
const status = yield* manager.status({ cwd: repoDir });
expect(status.branch).toBe("main");
expect(status.refName).toBe("main");
expect(status.pr).toBeNull();
}),
);
@@ -1026,13 +1049,13 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
});
const status = yield* manager.status({ cwd: repoDir });
expect(status.branch).toBe("t3code/pr-488/statemachine");
expect(status.refName).toBe("t3code/pr-488/statemachine");
expect(status.pr).toEqual({
number: 488,
title: "Rebase this PR on latest main",
url: "https://github.com/pingdotgg/codething-mvp/pull/488",
baseBranch: "main",
headBranch: "statemachine",
baseRef: "main",
headRef: "statemachine",
state: "open",
});
expect(ghCalls).toContain(
@@ -1126,13 +1149,13 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
});
const status = yield* manager.status({ cwd: repoDir });
expect(status.branch).toBe("upstream/effect-atom");
expect(status.refName).toBe("upstream/effect-atom");
expect(status.pr).toEqual({
number: 1618,
title: "Correct PR",
url: "https://github.com/pingdotgg/t3code/pull/1618",
baseBranch: "main",
headBranch: "effect-atom",
baseRef: "main",
headRef: "effect-atom",
state: "open",
});
expect(ghCalls.some((call) => call.includes("pr list --head upstream/effect-atom "))).toBe(
@@ -1176,18 +1199,48 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
});
const status = yield* manager.status({ cwd: repoDir });
expect(status.branch).toBe("feature/status-merged-pr");
expect(status.refName).toBe("feature/status-merged-pr");
expect(status.pr).toEqual({
number: 22,
title: "Merged PR",
url: "https://github.com/pingdotgg/codething-mvp/pull/22",
baseBranch: "main",
headBranch: "feature/status-merged-pr",
baseRef: "main",
headRef: "feature/status-merged-pr",
state: "merged",
});
}),
);
it.effect("status hides merged PRs on the default branch", () =>
Effect.gen(function* () {
const repoDir = yield* makeTempDir("t3code-git-manager-");
yield* initRepo(repoDir);
const { manager } = yield* makeManager({
ghScenario: {
prListSequence: [
JSON.stringify([
{
number: 23,
title: "Merged PR",
url: "https://github.com/pingdotgg/codething-mvp/pull/23",
baseRefName: "feature/status-default-branch-target",
headRefName: "main",
state: "MERGED",
mergedAt: "2026-01-30T10:00:00Z",
updatedAt: "2026-01-30T10:00:00Z",
},
]),
],
},
});
const status = yield* manager.status({ cwd: repoDir });
expect(status.refName).toBe("main");
expect(status.pr).toBeNull();
}),
);
it.effect("status prefers open PR when merged PR has newer updatedAt", () =>
Effect.gen(function* () {
const repoDir = yield* makeTempDir("t3code-git-manager-");
@@ -1223,13 +1276,13 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
});
const status = yield* manager.status({ cwd: repoDir });
expect(status.branch).toBe("feature/status-open-over-merged");
expect(status.refName).toBe("feature/status-open-over-merged");
expect(status.pr).toEqual({
number: 46,
title: "Open PR",
url: "https://github.com/pingdotgg/codething-mvp/pull/46",
baseBranch: "main",
headBranch: "feature/status-open-over-merged",
baseRef: "main",
headRef: "feature/status-open-over-merged",
state: "open",
});
}),
@@ -1254,7 +1307,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
});
const status = yield* manager.status({ cwd: repoDir });
expect(status.branch).toBe("feature/status-no-gh");
expect(status.refName).toBe("feature/status-no-gh");
expect(status.pr).toBeNull();
}),
);
@@ -1678,6 +1731,49 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
}),
);
it.effect("create_pr falls back to main when source control provider detection fails", () =>
Effect.gen(function* () {
const repoDir = yield* makeTempDir("t3code-git-manager-");
yield* initRepo(repoDir);
yield* runGit(repoDir, ["checkout", "-b", "feature/provider-fallback"]);
fs.writeFileSync(path.join(repoDir, "provider-fallback.txt"), "fallback\n");
yield* runGit(repoDir, ["add", "provider-fallback.txt"]);
yield* runGit(repoDir, ["commit", "-m", "Provider fallback"]);
const remoteDir = yield* createBareRemote();
yield* runGit(repoDir, ["remote", "add", "origin", remoteDir]);
const { manager, ghCalls } = yield* makeManager({
ghScenario: {
prListSequence: [
"[]",
JSON.stringify([
{
number: 404,
title: "Provider fallback",
url: "https://github.com/pingdotgg/codething-mvp/pull/404",
baseRefName: "main",
headRefName: "feature/provider-fallback",
},
]),
],
},
});
const result = yield* runStackedAction(manager, {
cwd: repoDir,
action: "create_pr",
});
expect(result.pr.status).toBe("created");
expect(result.pr.number).toBe(404);
expect(
ghCalls.some((call) =>
call.includes("pr create --base main --head feature/provider-fallback"),
),
).toBe(true);
}),
);
it.effect("returns existing PR metadata for commit/push/pr action", () =>
Effect.gen(function* () {
const repoDir = yield* makeTempDir("t3code-git-manager-");
@@ -3089,7 +3185,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
expect.objectContaining({
kind: "phase_started",
phase: "pr",
label: "Creating GitHub pull request...",
label: "Creating pull request...",
}),
]);
}),
@@ -2,29 +2,39 @@ import { randomUUID } from "node:crypto";
import { realpathSync } from "node:fs";
import {
Array as Arr,
Cache,
Context,
DateTime,
Duration,
Effect,
Exit,
FileSystem,
Layer,
Option,
Order,
Path,
Ref,
Result,
} from "effect";
import {
GitActionProgressEvent,
GitActionProgressPhase,
GitCommandError,
GitPreparePullRequestThreadInput,
GitPreparePullRequestThreadResult,
GitPullRequestRefInput,
GitResolvePullRequestResult,
GitRunStackedActionInput,
GitRunStackedActionResult,
GitStackedAction,
type GitStatusLocalResult,
type GitStatusRemoteResult,
VcsStatusInput,
type VcsStatusLocalResult,
type VcsStatusRemoteResult,
VcsStatusResult,
ModelSelection,
} from "@t3tools/contracts";
import {
detectGitHostingProviderFromRemoteUrl,
detectSourceControlProviderFromGitRemoteUrl,
mergeGitStatusParts,
resolveAutoFeatureBranchName,
sanitizeBranchFragment,
@@ -32,24 +42,52 @@ import {
} from "@t3tools/shared/git";
import { GitManagerError } from "@t3tools/contracts";
import {
GitManager,
type GitActionProgressReporter,
type GitManagerShape,
type GitRunStackedActionOptions,
} from "../Services/GitManager.ts";
import { GitCore } from "../Services/GitCore.ts";
import type { GitStatusDetails } from "../Services/GitCore.ts";
import { GitHubCli, type GitHubPullRequestSummary } from "../Services/GitHubCli.ts";
import { TextGeneration } from "../Services/TextGeneration.ts";
import { ProjectSetupScriptRunner } from "../../project/Services/ProjectSetupScriptRunner.ts";
import { extractBranchNameFromRemoteRef } from "../remoteRefs.ts";
import { ServerSettingsService } from "../../serverSettings.ts";
import { TextGeneration } from "../textGeneration/TextGeneration.ts";
import { ProjectSetupScriptRunner } from "../project/Services/ProjectSetupScriptRunner.ts";
import { extractBranchNameFromRemoteRef } from "./remoteRefs.ts";
import { ServerSettingsService } from "../serverSettings.ts";
import type { GitManagerServiceError } from "@t3tools/contracts";
import {
decodeGitHubPullRequestListJson,
formatGitHubJsonDecodeError,
} from "../githubPullRequests.ts";
import { GitVcsDriver, type GitStatusDetails } from "../vcs/GitVcsDriver.ts";
import { SourceControlProviderRegistry } from "../sourceControl/SourceControlProviderRegistry.ts";
import type { ChangeRequest } from "@t3tools/contracts";
export interface GitActionProgressReporter {
readonly publish: (event: GitActionProgressEvent) => Effect.Effect<void, never>;
}
export interface GitRunStackedActionOptions {
readonly actionId?: string;
readonly progressReporter?: GitActionProgressReporter;
}
export interface GitManagerShape {
readonly status: (
input: VcsStatusInput,
) => Effect.Effect<VcsStatusResult, GitManagerServiceError>;
readonly localStatus: (
input: VcsStatusInput,
) => Effect.Effect<VcsStatusLocalResult, GitManagerServiceError>;
readonly remoteStatus: (
input: VcsStatusInput,
) => Effect.Effect<VcsStatusRemoteResult | null, GitManagerServiceError>;
readonly invalidateLocalStatus: (cwd: string) => Effect.Effect<void, never>;
readonly invalidateRemoteStatus: (cwd: string) => Effect.Effect<void, never>;
readonly invalidateStatus: (cwd: string) => Effect.Effect<void, never>;
readonly resolvePullRequest: (
input: GitPullRequestRefInput,
) => Effect.Effect<GitResolvePullRequestResult, GitManagerServiceError>;
readonly preparePullRequestThread: (
input: GitPreparePullRequestThreadInput,
) => Effect.Effect<GitPreparePullRequestThreadResult, GitManagerServiceError>;
readonly runStackedAction: (
input: GitRunStackedActionInput,
options?: GitRunStackedActionOptions,
) => Effect.Effect<GitRunStackedActionResult, GitManagerServiceError>;
}
export class GitManager extends Context.Service<GitManager, GitManagerShape>()(
"t3/git/GitManager",
) {}
const COMMIT_TIMEOUT_MS = 10 * 60_000;
const MAX_PROGRESS_TEXT_LENGTH = 500;
@@ -75,9 +113,14 @@ interface OpenPrInfo {
interface PullRequestInfo extends OpenPrInfo, PullRequestHeadRemoteInfo {
state: "open" | "closed" | "merged";
updatedAt: string | null;
updatedAt: Option.Option<DateTime.Utc>;
}
const pullRequestUpdatedAtDescOrder: Order.Order<PullRequestInfo> = Order.mapInput(
Order.flip(Option.makeOrder(DateTime.Order)),
(pullRequest) => pullRequest.updatedAt,
);
interface ResolvedPullRequest {
number: number;
title: string;
@@ -88,9 +131,9 @@ interface ResolvedPullRequest {
}
interface PullRequestHeadRemoteInfo {
isCrossRepository?: boolean;
headRepositoryNameWithOwner?: string | null;
headRepositoryOwnerLogin?: string | null;
isCrossRepository?: boolean | undefined;
headRepositoryNameWithOwner?: string | null | undefined;
headRepositoryOwnerLogin?: string | null | undefined;
}
interface BranchHeadContext {
@@ -256,7 +299,7 @@ function matchesBranchHeadContext(
return true;
}
function toPullRequestInfo(summary: GitHubPullRequestSummary): PullRequestInfo {
function toPullRequestInfo(summary: ChangeRequest): PullRequestInfo {
return {
number: summary.number,
title: summary.title,
@@ -264,7 +307,7 @@ function toPullRequestInfo(summary: GitHubPullRequestSummary): PullRequestInfo {
baseRefName: summary.baseRefName,
headRefName: summary.headRefName,
state: summary.state ?? "open",
updatedAt: null,
updatedAt: summary.updatedAt,
...(summary.isCrossRepository !== undefined
? { isCrossRepository: summary.isCrossRepository }
: {}),
@@ -422,16 +465,16 @@ function toStatusPr(pr: PullRequestInfo): {
number: number;
title: string;
url: string;
baseBranch: string;
headBranch: string;
baseRef: string;
headRef: string;
state: "open" | "closed" | "merged";
} {
return {
number: pr.number,
title: pr.title,
url: pr.url,
baseBranch: pr.baseRefName,
headBranch: pr.headRefName,
baseRef: pr.baseRefName,
headRef: pr.headRefName,
state: pr.state,
};
}
@@ -475,9 +518,9 @@ function shouldPreferSshRemote(url: string | null): boolean {
}
function toPullRequestHeadRemoteInfo(pr: {
isCrossRepository?: boolean;
headRepositoryNameWithOwner?: string | null;
headRepositoryOwnerLogin?: string | null;
isCrossRepository?: boolean | undefined;
headRepositoryNameWithOwner?: string | null | undefined;
headRepositoryOwnerLogin?: string | null | undefined;
}): PullRequestHeadRemoteInfo {
return {
...(pr.isCrossRepository !== undefined ? { isCrossRepository: pr.isCrossRepository } : {}),
@@ -491,10 +534,12 @@ function toPullRequestHeadRemoteInfo(pr: {
}
export const makeGitManager = Effect.fn("makeGitManager")(function* () {
const gitCore = yield* GitCore;
const gitHubCli = yield* GitHubCli;
const gitCore = yield* GitVcsDriver;
const sourceControlProviders = yield* SourceControlProviderRegistry;
const textGeneration = yield* TextGeneration;
const projectSetupScriptRunner = yield* ProjectSetupScriptRunner;
const sourceControlProvider = (cwd: string) => sourceControlProviders.resolve({ cwd });
const serverSettingsService = yield* ServerSettingsService;
const createProgressEmitter = (
@@ -531,7 +576,7 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
return;
}
const cloneUrls = yield* gitHubCli.getRepositoryCloneUrls({
const cloneUrls = yield* (yield* sourceControlProvider(cwd)).getRepositoryCloneUrls({
cwd,
repository: repositoryNameWithOwner,
});
@@ -586,7 +631,7 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
return;
}
const cloneUrls = yield* gitHubCli.getRepositoryCloneUrls({
const cloneUrls = yield* (yield* sourceControlProvider(cwd)).getRepositoryCloneUrls({
cwd,
repository: repositoryNameWithOwner,
});
@@ -659,14 +704,15 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
: null;
return {
kind: details.isRepo ? ("git" as const) : ("unknown" as const),
isRepo: details.isRepo,
...(hostingProvider ? { hostingProvider } : {}),
hasOriginRemote: details.hasOriginRemote,
isDefaultBranch: details.isDefaultBranch,
branch: details.branch,
...(hostingProvider ? { sourceControlProvider: hostingProvider } : {}),
hasPrimaryRemote: details.hasOriginRemote,
isDefaultRef: details.isDefaultBranch,
refName: details.branch,
hasWorkingTreeChanges: details.hasWorkingTreeChanges,
workingTree: details.workingTree,
} satisfies GitStatusLocalResult;
} satisfies VcsStatusLocalResult;
});
const localStatusResultCache = yield* Cache.makeWith(readLocalStatus, {
capacity: STATUS_RESULT_CACHE_CAPACITY,
@@ -688,7 +734,13 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
branch: details.branch,
upstreamRef: details.upstreamRef,
}).pipe(
Effect.map((latest) => (latest ? toStatusPr(latest) : null)),
Effect.map((latest) => {
if (!latest) return null;
// On the default branch, only surface open PRs.
// Merged/closed matches are usually reverse-merge history, not the thread's PR context.
if (details.isDefaultBranch && latest.state !== "open") return null;
return toStatusPr(latest);
}),
Effect.catch(() => Effect.succeed(null)),
)
: null;
@@ -698,7 +750,7 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
aheadCount: details.aheadCount,
behindCount: details.behindCount,
pr,
} satisfies GitStatusRemoteResult;
} satisfies VcsStatusRemoteResult;
});
const remoteStatusResultCache = yield* Cache.makeWith(readRemoteStatus, {
capacity: STATUS_RESULT_CACHE_CAPACITY,
@@ -722,7 +774,7 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
(yield* readConfigValueNullable(cwd, `remote.${preferredRemoteName}.url`)) ??
(yield* readConfigValueNullable(cwd, "remote.origin.url"));
return remoteUrl ? detectGitHostingProviderFromRemoteUrl(remoteUrl) : null;
return remoteUrl ? detectSourceControlProviderFromGitRemoteUrl(remoteUrl) : null;
});
const resolveRemoteRepositoryContext = Effect.fn("resolveRemoteRepositoryContext")(function* (
@@ -827,9 +879,10 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
>,
) {
for (const headSelector of headContext.headSelectors) {
const pullRequests = yield* gitHubCli.listOpenPullRequests({
const pullRequests = yield* (yield* sourceControlProvider(cwd)).listChangeRequests({
cwd,
headSelector,
state: "open",
limit: 1,
});
const normalizedPullRequests = pullRequests.map(toPullRequestInfo);
@@ -845,7 +898,7 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
baseRefName: firstPullRequest.baseRefName,
headRefName: firstPullRequest.headRefName,
state: "open",
updatedAt: null,
updatedAt: Option.none(),
} satisfies PullRequestInfo;
}
}
@@ -861,46 +914,14 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
const parsedByNumber = new Map<number, PullRequestInfo>();
for (const headSelector of headContext.headSelectors) {
const stdout = yield* gitHubCli
.execute({
cwd,
args: [
"pr",
"list",
"--head",
headSelector,
"--state",
"all",
"--limit",
"20",
"--json",
"number,title,url,baseRefName,headRefName,state,mergedAt,updatedAt,isCrossRepository,headRepository,headRepositoryOwner",
],
})
.pipe(Effect.map((result) => result.stdout));
const pullRequests = yield* (yield* sourceControlProvider(cwd)).listChangeRequests({
cwd,
headSelector,
state: "all",
limit: 20,
});
const raw = stdout.trim();
if (raw.length === 0) {
continue;
}
const pullRequests = yield* Effect.sync(() => decodeGitHubPullRequestListJson(raw)).pipe(
Effect.flatMap((decoded) => {
if (!Result.isSuccess(decoded)) {
return Effect.fail(
gitManagerError(
"findLatestPr",
`GitHub CLI returned invalid PR list JSON: ${formatGitHubJsonDecodeError(decoded.failure)}`,
decoded.failure,
),
);
}
return Effect.succeed(decoded.success);
}),
);
for (const pr of pullRequests) {
for (const pr of pullRequests.map(toPullRequestInfo)) {
if (!matchesBranchHeadContext(pr, headContext)) {
continue;
}
@@ -908,11 +929,7 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
}
}
const parsed = Array.from(parsedByNumber.values()).toSorted((a, b) => {
const left = a.updatedAt ? Date.parse(a.updatedAt) : 0;
const right = b.updatedAt ? Date.parse(b.updatedAt) : 0;
return right - left;
});
const parsed = Arr.sort(parsedByNumber.values(), pullRequestUpdatedAtDescOrder);
const latestOpenPr = parsed.find((pr) => pr.state === "open");
if (latestOpenPr) {
@@ -1029,11 +1046,12 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
}
}
const defaultFromGh = yield* gitHubCli
.getDefaultBranch({ cwd })
.pipe(Effect.catch(() => Effect.succeed(null)));
if (defaultFromGh) {
return defaultFromGh;
const defaultFromProvider = yield* sourceControlProvider(cwd).pipe(
Effect.flatMap((provider) => provider.getDefaultBranch({ cwd })),
Effect.catch(() => Effect.succeed(null)),
);
if (defaultFromProvider) {
return defaultFromProvider;
}
return "main";
@@ -1266,12 +1284,12 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
yield* emit({
kind: "phase_started",
phase: "pr",
label: "Creating GitHub pull request...",
label: "Creating pull request...",
});
yield* gitHubCli
.createPullRequest({
yield* (yield* sourceControlProvider(cwd))
.createChangeRequest({
cwd,
baseBranch,
baseRefName: baseBranch,
headSelector: headContext.preferredHeadSelector,
title: generated.title,
bodyFile,
@@ -1329,8 +1347,8 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
const resolvePullRequest: GitManagerShape["resolvePullRequest"] = Effect.fn("resolvePullRequest")(
function* (input) {
const pullRequest = yield* gitHubCli
.getPullRequest({
const pullRequest = yield* (yield* sourceControlProvider(input.cwd))
.getChangeRequest({
cwd: input.cwd,
reference: normalizePullRequestReference(input.reference),
})
@@ -1364,14 +1382,14 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
return yield* Effect.gen(function* () {
const normalizedReference = normalizePullRequestReference(input.reference);
const rootWorktreePath = canonicalizeExistingPath(input.cwd);
const pullRequestSummary = yield* gitHubCli.getPullRequest({
const pullRequestSummary = yield* (yield* sourceControlProvider(input.cwd)).getChangeRequest({
cwd: input.cwd,
reference: normalizedReference,
});
const pullRequest = toResolvedPullRequest(pullRequestSummary);
if (input.mode === "local") {
yield* gitHubCli.checkoutPullRequest({
yield* (yield* sourceControlProvider(input.cwd)).checkoutChangeRequest({
cwd: input.cwd,
reference: normalizedReference,
force: true,
@@ -1414,9 +1432,9 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
resolvePullRequestWorktreeLocalBranchName(pullRequestWithRemoteInfo);
const findLocalHeadBranch = (cwd: string) =>
gitCore.listBranches({ cwd }).pipe(
gitCore.listRefs({ cwd }).pipe(
Effect.map((result) => {
const localBranch = result.branches.find(
const localBranch = result.refs.find(
(branch) => !branch.isRemote && branch.name === localPullRequestBranch,
);
if (localBranch) {
@@ -1426,7 +1444,7 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
return null;
}
return (
result.branches.find(
result.refs.find(
(branch) =>
!branch.isRemote &&
branch.name === pullRequest.headBranch &&
@@ -1489,7 +1507,7 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
const worktree = yield* gitCore.createWorktree({
cwd: input.cwd,
branch: localPullRequestBranch,
refName: localPullRequestBranch,
path: null,
});
yield* ensureExistingWorktreeUpstream(worktree.worktree.path);
@@ -1497,7 +1515,7 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
return {
pullRequest,
branch: worktree.worktree.branch,
branch: worktree.worktree.refName,
worktreePath: worktree.worktree.path,
};
}).pipe(Effect.ensuring(invalidateStatus(input.cwd)));
@@ -1529,8 +1547,8 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
const existingBranchNames = yield* gitCore.listLocalBranchNames(cwd);
const resolvedBranch = resolveAutoFeatureBranchName(existingBranchNames, preferredBranch);
yield* gitCore.createBranch({ cwd, branch: resolvedBranch });
yield* Effect.scoped(gitCore.checkoutBranch({ cwd, branch: resolvedBranch }));
yield* gitCore.createRef({ cwd, refName: resolvedBranch });
yield* Effect.scoped(gitCore.switchRef({ cwd, refName: resolvedBranch }));
return {
branchStep: { status: "created" as const, name: resolvedBranch },
@@ -1731,4 +1749,4 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
} satisfies GitManagerShape;
});
export const GitManagerLive = Layer.effect(GitManager, makeGitManager());
export const layer = Layer.effect(GitManager, makeGitManager());
+271
View File
@@ -0,0 +1,271 @@
import { Context, Effect, Layer } from "effect";
import {
GitManagerError,
GitCommandError,
type VcsDriverKind,
type VcsSwitchRefInput,
type VcsSwitchRefResult,
type VcsCreateRefInput,
type VcsCreateRefResult,
type VcsCreateWorktreeInput,
type VcsCreateWorktreeResult,
type VcsListRefsInput,
type VcsListRefsResult,
type GitManagerServiceError,
type GitPreparePullRequestThreadInput,
type GitPreparePullRequestThreadResult,
type GitPullRequestRefInput,
type VcsPullResult,
type VcsRemoveWorktreeInput,
type GitResolvePullRequestResult,
type GitRunStackedActionInput,
type GitRunStackedActionResult,
type VcsStatusInput,
type VcsStatusLocalResult,
type VcsStatusRemoteResult,
type VcsStatusResult,
} from "@t3tools/contracts";
import { GitManager, type GitRunStackedActionOptions } from "./GitManager.ts";
import { GitVcsDriver } from "../vcs/GitVcsDriver.ts";
import { VcsDriverRegistry } from "../vcs/VcsDriverRegistry.ts";
import { mergeGitStatusParts } from "@t3tools/shared/git";
export interface GitWorkflowServiceShape {
readonly status: (
input: VcsStatusInput,
) => Effect.Effect<VcsStatusResult, GitManagerServiceError>;
readonly localStatus: (
input: VcsStatusInput,
) => Effect.Effect<VcsStatusLocalResult, GitManagerServiceError>;
readonly remoteStatus: (
input: VcsStatusInput,
) => Effect.Effect<VcsStatusRemoteResult | null, GitManagerServiceError>;
readonly invalidateLocalStatus: (cwd: string) => Effect.Effect<void, never>;
readonly invalidateRemoteStatus: (cwd: string) => Effect.Effect<void, never>;
readonly invalidateStatus: (cwd: string) => Effect.Effect<void, never>;
readonly pullCurrentBranch: (cwd: string) => Effect.Effect<VcsPullResult, GitCommandError>;
readonly runStackedAction: (
input: GitRunStackedActionInput,
options?: GitRunStackedActionOptions,
) => Effect.Effect<GitRunStackedActionResult, GitManagerServiceError>;
readonly resolvePullRequest: (
input: GitPullRequestRefInput,
) => Effect.Effect<GitResolvePullRequestResult, GitManagerServiceError>;
readonly preparePullRequestThread: (
input: GitPreparePullRequestThreadInput,
) => Effect.Effect<GitPreparePullRequestThreadResult, GitManagerServiceError>;
readonly listRefs: (input: VcsListRefsInput) => Effect.Effect<VcsListRefsResult, GitCommandError>;
readonly createWorktree: (
input: VcsCreateWorktreeInput,
) => Effect.Effect<VcsCreateWorktreeResult, GitCommandError>;
readonly removeWorktree: (input: VcsRemoveWorktreeInput) => Effect.Effect<void, GitCommandError>;
readonly createRef: (
input: VcsCreateRefInput,
) => Effect.Effect<VcsCreateRefResult, GitCommandError>;
readonly switchRef: (
input: VcsSwitchRefInput,
) => Effect.Effect<VcsSwitchRefResult, GitCommandError>;
readonly initRepo: (input: { readonly cwd: string }) => Effect.Effect<void, GitCommandError>;
readonly renameBranch: (input: {
readonly cwd: string;
readonly oldBranch: string;
readonly newBranch: string;
}) => Effect.Effect<{ readonly branch: string }, GitManagerServiceError>;
}
export class GitWorkflowService extends Context.Service<
GitWorkflowService,
GitWorkflowServiceShape
>()("t3/git/GitWorkflowService") {}
const unsupportedGitWorkflow = (operation: string, cwd: string, detail: string) =>
new GitManagerError({
operation,
detail: `${detail} (${cwd})`,
});
const unsupportedGitCommand = (operation: string, cwd: string, detail: string) =>
new GitCommandError({
operation,
command: "vcs-route",
cwd,
detail,
});
const emptyWorkingTree = { files: [], insertions: 0, deletions: 0 } as const;
const nonGitLocalStatus = (kind: VcsDriverKind, isRepo: boolean): VcsStatusLocalResult => ({
kind,
isRepo,
hasPrimaryRemote: false,
isDefaultRef: false,
refName: null,
hasWorkingTreeChanges: false,
workingTree: emptyWorkingTree,
});
export const make = Effect.fn("makeGitWorkflowService")(function* () {
const registry = yield* VcsDriverRegistry;
const git = yield* GitVcsDriver;
const gitManager = yield* GitManager;
const ensureGit = Effect.fn("GitWorkflowService.ensureGit")(function* (
operation: string,
cwd: string,
) {
const handle = yield* registry
.resolve({ cwd })
.pipe(
Effect.mapError((error) =>
unsupportedGitWorkflow(
operation,
cwd,
error instanceof Error ? error.message : String(error),
),
),
);
if (handle.kind !== "git") {
return yield* unsupportedGitWorkflow(
operation,
cwd,
`The ${operation} workflow currently supports Git repositories only; detected ${handle.kind}.`,
);
}
});
const ensureGitCommand = Effect.fn("GitWorkflowService.ensureGitCommand")(function* (
operation: string,
cwd: string,
) {
const handle = yield* registry
.resolve({ cwd })
.pipe(
Effect.mapError((error) =>
unsupportedGitCommand(
operation,
cwd,
error instanceof Error ? error.message : String(error),
),
),
);
if (handle.kind !== "git") {
return yield* unsupportedGitCommand(
operation,
cwd,
`The ${operation} command currently supports Git repositories only; detected ${handle.kind}.`,
);
}
});
const routeGitManager =
<Input extends { readonly cwd: string }, Output>(
operation: string,
run: (input: Input) => Effect.Effect<Output, GitManagerServiceError>,
) =>
(input: Input) =>
ensureGit(operation, input.cwd).pipe(Effect.andThen(run(input)));
const localStatus: GitWorkflowServiceShape["localStatus"] = Effect.fn(
"GitWorkflowService.localStatus",
)(function* (input) {
const handle = yield* registry
.detect({ cwd: input.cwd })
.pipe(
Effect.mapError((error) =>
unsupportedGitWorkflow(
"GitWorkflowService.localStatus",
input.cwd,
error instanceof Error ? error.message : String(error),
),
),
);
if (!handle) {
return nonGitLocalStatus("unknown", false);
}
if (handle.kind === "git") {
return yield* gitManager.localStatus(input);
}
return nonGitLocalStatus(handle.kind, true);
});
const remoteStatus: GitWorkflowServiceShape["remoteStatus"] = Effect.fn(
"GitWorkflowService.remoteStatus",
)(function* (input) {
const handle = yield* registry
.detect({ cwd: input.cwd })
.pipe(
Effect.mapError((error) =>
unsupportedGitWorkflow(
"GitWorkflowService.remoteStatus",
input.cwd,
error instanceof Error ? error.message : String(error),
),
),
);
if (handle?.kind === "git") {
return yield* gitManager.remoteStatus(input);
}
return null;
});
const status: GitWorkflowServiceShape["status"] = Effect.fn("GitWorkflowService.status")(
function* (input) {
const [local, remote] = yield* Effect.all([localStatus(input), remoteStatus(input)]);
return mergeGitStatusParts(local, remote);
},
);
return GitWorkflowService.of({
status,
localStatus,
remoteStatus,
invalidateLocalStatus: gitManager.invalidateLocalStatus,
invalidateRemoteStatus: gitManager.invalidateRemoteStatus,
invalidateStatus: gitManager.invalidateStatus,
pullCurrentBranch: (cwd) =>
ensureGitCommand("GitWorkflowService.pullCurrentBranch", cwd).pipe(
Effect.andThen(git.pullCurrentBranch(cwd)),
),
runStackedAction: (input, options) =>
ensureGit("GitWorkflowService.runStackedAction", input.cwd).pipe(
Effect.andThen(gitManager.runStackedAction(input, options)),
),
resolvePullRequest: routeGitManager(
"GitWorkflowService.resolvePullRequest",
gitManager.resolvePullRequest,
),
preparePullRequestThread: routeGitManager(
"GitWorkflowService.preparePullRequestThread",
gitManager.preparePullRequestThread,
),
listRefs: (input) =>
ensureGitCommand("GitWorkflowService.listRefs", input.cwd).pipe(
Effect.andThen(git.listRefs(input)),
),
createWorktree: (input) =>
ensureGitCommand("GitWorkflowService.createWorktree", input.cwd).pipe(
Effect.andThen(git.createWorktree(input)),
),
removeWorktree: (input) =>
ensureGitCommand("GitWorkflowService.removeWorktree", input.cwd).pipe(
Effect.andThen(git.removeWorktree(input)),
),
createRef: (input) =>
ensureGitCommand("GitWorkflowService.createRef", input.cwd).pipe(
Effect.andThen(git.createRef(input)),
),
switchRef: (input) =>
ensureGitCommand("GitWorkflowService.switchRef", input.cwd).pipe(
Effect.andThen(Effect.scoped(git.switchRef(input))),
),
initRepo: (input) => git.initRepo(input),
renameBranch: (input) =>
ensureGit("GitWorkflowService.renameBranch", input.cwd).pipe(
Effect.andThen(git.renameBranch(input)),
),
});
});
export const layer = Layer.effect(GitWorkflowService, make());
@@ -1,306 +0,0 @@
import * as NodeServices from "@effect/platform-node/NodeServices";
import { it } from "@effect/vitest";
import { Effect, FileSystem, Layer, Path } from "effect";
import { createModelSelection } from "@t3tools/shared/model";
import { expect } from "vitest";
import { ServerConfig } from "../../config.ts";
import { TextGeneration } from "../Services/TextGeneration.ts";
import { sanitizeThreadTitle } from "../Utils.ts";
import { ClaudeTextGenerationLive } from "./ClaudeTextGeneration.ts";
import { ServerSettingsService } from "../../serverSettings.ts";
const ClaudeTextGenerationTestLayer = ClaudeTextGenerationLive.pipe(
Layer.provideMerge(ServerSettingsService.layerTest()),
Layer.provideMerge(
ServerConfig.layerTest(process.cwd(), {
prefix: "t3code-claude-text-generation-test-",
}),
),
Layer.provideMerge(NodeServices.layer),
);
function makeFakeClaudeBinary(dir: string) {
return Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const binDir = path.join(dir, "bin");
const claudePath = path.join(binDir, "claude");
yield* fs.makeDirectory(binDir, { recursive: true });
yield* fs.writeFileString(
claudePath,
[
"#!/bin/sh",
'args="$*"',
'stdin_content="$(cat)"',
'if [ -n "$T3_FAKE_CLAUDE_ARGS_MUST_CONTAIN" ]; then',
' printf "%s" "$args" | grep -F -- "$T3_FAKE_CLAUDE_ARGS_MUST_CONTAIN" >/dev/null || {',
' printf "%s\\n" "args missing expected content" >&2',
" exit 2",
" }",
"fi",
'if [ -n "$T3_FAKE_CLAUDE_ARGS_MUST_NOT_CONTAIN" ]; then',
' if printf "%s" "$args" | grep -F -- "$T3_FAKE_CLAUDE_ARGS_MUST_NOT_CONTAIN" >/dev/null; then',
' printf "%s\\n" "args contained forbidden content" >&2',
" exit 3",
" fi",
"fi",
'if [ -n "$T3_FAKE_CLAUDE_STDIN_MUST_CONTAIN" ]; then',
' printf "%s" "$stdin_content" | grep -F -- "$T3_FAKE_CLAUDE_STDIN_MUST_CONTAIN" >/dev/null || {',
' printf "%s\\n" "stdin missing expected content" >&2',
" exit 4",
" }",
"fi",
'if [ -n "$T3_FAKE_CLAUDE_STDERR" ]; then',
' printf "%s\\n" "$T3_FAKE_CLAUDE_STDERR" >&2',
"fi",
'printf "%s" "$T3_FAKE_CLAUDE_OUTPUT"',
'exit "${T3_FAKE_CLAUDE_EXIT_CODE:-0}"',
"",
].join("\n"),
);
yield* fs.chmod(claudePath, 0o755);
return binDir;
});
}
function withFakeClaudeEnv<A, E, R>(
input: {
output: string;
exitCode?: number;
stderr?: string;
argsMustContain?: string;
argsMustNotContain?: string;
stdinMustContain?: string;
},
effect: Effect.Effect<A, E, R>,
) {
return Effect.acquireUseRelease(
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const tempDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3code-claude-text-" });
const binDir = yield* makeFakeClaudeBinary(tempDir);
const previousPath = process.env.PATH;
const previousOutput = process.env.T3_FAKE_CLAUDE_OUTPUT;
const previousExitCode = process.env.T3_FAKE_CLAUDE_EXIT_CODE;
const previousStderr = process.env.T3_FAKE_CLAUDE_STDERR;
const previousArgsMustContain = process.env.T3_FAKE_CLAUDE_ARGS_MUST_CONTAIN;
const previousArgsMustNotContain = process.env.T3_FAKE_CLAUDE_ARGS_MUST_NOT_CONTAIN;
const previousStdinMustContain = process.env.T3_FAKE_CLAUDE_STDIN_MUST_CONTAIN;
yield* Effect.sync(() => {
process.env.PATH = `${binDir}:${previousPath ?? ""}`;
process.env.T3_FAKE_CLAUDE_OUTPUT = input.output;
if (input.exitCode !== undefined) {
process.env.T3_FAKE_CLAUDE_EXIT_CODE = String(input.exitCode);
} else {
delete process.env.T3_FAKE_CLAUDE_EXIT_CODE;
}
if (input.stderr !== undefined) {
process.env.T3_FAKE_CLAUDE_STDERR = input.stderr;
} else {
delete process.env.T3_FAKE_CLAUDE_STDERR;
}
if (input.argsMustContain !== undefined) {
process.env.T3_FAKE_CLAUDE_ARGS_MUST_CONTAIN = input.argsMustContain;
} else {
delete process.env.T3_FAKE_CLAUDE_ARGS_MUST_CONTAIN;
}
if (input.argsMustNotContain !== undefined) {
process.env.T3_FAKE_CLAUDE_ARGS_MUST_NOT_CONTAIN = input.argsMustNotContain;
} else {
delete process.env.T3_FAKE_CLAUDE_ARGS_MUST_NOT_CONTAIN;
}
if (input.stdinMustContain !== undefined) {
process.env.T3_FAKE_CLAUDE_STDIN_MUST_CONTAIN = input.stdinMustContain;
} else {
delete process.env.T3_FAKE_CLAUDE_STDIN_MUST_CONTAIN;
}
});
return {
previousPath,
previousOutput,
previousExitCode,
previousStderr,
previousArgsMustContain,
previousArgsMustNotContain,
previousStdinMustContain,
};
}),
() => effect,
(previous) =>
Effect.sync(() => {
process.env.PATH = previous.previousPath;
if (previous.previousOutput === undefined) {
delete process.env.T3_FAKE_CLAUDE_OUTPUT;
} else {
process.env.T3_FAKE_CLAUDE_OUTPUT = previous.previousOutput;
}
if (previous.previousExitCode === undefined) {
delete process.env.T3_FAKE_CLAUDE_EXIT_CODE;
} else {
process.env.T3_FAKE_CLAUDE_EXIT_CODE = previous.previousExitCode;
}
if (previous.previousStderr === undefined) {
delete process.env.T3_FAKE_CLAUDE_STDERR;
} else {
process.env.T3_FAKE_CLAUDE_STDERR = previous.previousStderr;
}
if (previous.previousArgsMustContain === undefined) {
delete process.env.T3_FAKE_CLAUDE_ARGS_MUST_CONTAIN;
} else {
process.env.T3_FAKE_CLAUDE_ARGS_MUST_CONTAIN = previous.previousArgsMustContain;
}
if (previous.previousArgsMustNotContain === undefined) {
delete process.env.T3_FAKE_CLAUDE_ARGS_MUST_NOT_CONTAIN;
} else {
process.env.T3_FAKE_CLAUDE_ARGS_MUST_NOT_CONTAIN = previous.previousArgsMustNotContain;
}
if (previous.previousStdinMustContain === undefined) {
delete process.env.T3_FAKE_CLAUDE_STDIN_MUST_CONTAIN;
} else {
process.env.T3_FAKE_CLAUDE_STDIN_MUST_CONTAIN = previous.previousStdinMustContain;
}
}),
);
}
it.layer(ClaudeTextGenerationTestLayer)("ClaudeTextGenerationLive", (it) => {
it.effect("forwards Claude thinking settings for Haiku without passing effort", () =>
withFakeClaudeEnv(
{
output: JSON.stringify({
structured_output: {
subject: "Add important change",
body: "",
},
}),
argsMustContain: '--settings {"alwaysThinkingEnabled":false}',
argsMustNotContain: "--effort",
},
Effect.gen(function* () {
const textGeneration = yield* TextGeneration;
const generated = yield* textGeneration.generateCommitMessage({
cwd: process.cwd(),
branch: "feature/claude-effect",
stagedSummary: "M README.md",
stagedPatch: "diff --git a/README.md b/README.md",
modelSelection: {
...createModelSelection("claudeAgent", "claude-haiku-4-5", [
{ id: "thinking", value: false },
{ id: "effort", value: "high" },
]),
},
});
expect(generated.subject).toBe("Add important change");
}),
),
);
it.effect("forwards Claude fast mode and supported effort", () =>
withFakeClaudeEnv(
{
output: JSON.stringify({
structured_output: {
title: "Improve orchestration flow",
body: "Body",
},
}),
argsMustContain: '--effort max --settings {"fastMode":true}',
},
Effect.gen(function* () {
const textGeneration = yield* TextGeneration;
const generated = yield* textGeneration.generatePrContent({
cwd: process.cwd(),
baseBranch: "main",
headBranch: "feature/claude-effect",
commitSummary: "Improve orchestration",
diffSummary: "1 file changed",
diffPatch: "diff --git a/README.md b/README.md",
modelSelection: {
...createModelSelection("claudeAgent", "claude-opus-4-6", [
{ id: "effort", value: "max" },
{ id: "fastMode", value: true },
]),
},
});
expect(generated.title).toBe("Improve orchestration flow");
}),
),
);
it.effect("generates thread titles through the Claude provider", () =>
withFakeClaudeEnv(
{
output: JSON.stringify({
structured_output: {
title:
' "Reconnect failures after restart because the session state does not recover" ',
},
}),
stdinMustContain: "You write concise thread titles for coding conversations.",
},
Effect.gen(function* () {
const textGeneration = yield* TextGeneration;
const generated = yield* textGeneration.generateThreadTitle({
cwd: process.cwd(),
message: "Please investigate reconnect failures after restarting the session.",
modelSelection: {
provider: "claudeAgent",
model: "claude-sonnet-4-6",
},
});
expect(generated.title).toBe(
sanitizeThreadTitle(
'"Reconnect failures after restart because the session state does not recover"',
),
);
}),
),
);
it.effect("falls back when Claude thread title normalization becomes whitespace-only", () =>
withFakeClaudeEnv(
{
output: JSON.stringify({
structured_output: {
title: ' """ """ ',
},
}),
},
Effect.gen(function* () {
const textGeneration = yield* TextGeneration;
const generated = yield* textGeneration.generateThreadTitle({
cwd: process.cwd(),
message: "Name this thread.",
modelSelection: {
provider: "claudeAgent",
model: "claude-sonnet-4-6",
},
});
expect(generated.title).toBe("New thread");
}),
),
);
});
@@ -1,297 +0,0 @@
import * as path from "node:path";
import * as os from "node:os";
import { fileURLToPath } from "node:url";
import { chmodSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { it } from "@effect/vitest";
import { Effect, Layer } from "effect";
import { createModelSelection } from "@t3tools/shared/model";
import { expect } from "vitest";
import { ServerSettingsError } from "@t3tools/contracts";
import { ServerConfig } from "../../config.ts";
import { TextGeneration } from "../Services/TextGeneration.ts";
import { CursorTextGenerationLive } from "./CursorTextGeneration.ts";
import { ServerSettingsService } from "../../serverSettings.ts";
const __dirname = path.dirname(fileURLToPath(import.meta.url));
const mockAgentPath = path.join(__dirname, "../../../scripts/acp-mock-agent.ts");
function shellSingleQuote(value: string): string {
return `'${value.replaceAll("'", `'"'"'`)}'`;
}
const CursorTextGenerationTestLayer = CursorTextGenerationLive.pipe(
Layer.provideMerge(ServerSettingsService.layerTest()),
Layer.provideMerge(
ServerConfig.layerTest(process.cwd(), {
prefix: "t3code-cursor-text-generation-test-",
}),
),
Layer.provideMerge(NodeServices.layer),
);
function makeAcpAgentWrapper(dir: string, env: Record<string, string>): string {
const binDir = path.join(dir, "bin");
const agentPath = path.join(binDir, "agent");
mkdirSync(binDir, { recursive: true });
writeFileSync(
agentPath,
[
"#!/bin/sh",
...Object.entries(env).map(([key, value]) => `export ${key}=${shellSingleQuote(value)}`),
'if [ "$1" != "acp" ]; then',
' printf "%s\\n" "unexpected args: $*" >&2',
" exit 11",
"fi",
`exec bun ${JSON.stringify(mockAgentPath)}`,
"",
].join("\n"),
"utf8",
);
chmodSync(agentPath, 0o755);
return agentPath;
}
function withFakeAcpAgent<A, E, R>(
env: Record<string, string>,
effect: Effect.Effect<A, E, R>,
): Effect.Effect<A, E | ServerSettingsError, R | ServerSettingsService> {
return Effect.gen(function* () {
const tempDir = mkdtempSync(path.join(os.tmpdir(), "t3code-cursor-text-acp-"));
const agentPath = makeAcpAgentWrapper(tempDir, env);
const serverSettings = yield* ServerSettingsService;
const previousSettings = yield* serverSettings.getSettings;
yield* serverSettings.updateSettings({
providers: {
cursor: {
binaryPath: agentPath,
},
},
});
return yield* effect.pipe(
Effect.ensuring(
serverSettings
.updateSettings({
providers: {
cursor: {
binaryPath: previousSettings.providers.cursor.binaryPath,
},
},
})
.pipe(
Effect.catch(() => Effect.void),
Effect.ensuring(
Effect.sync(() => {
rmSync(tempDir, { recursive: true, force: true });
}),
),
Effect.asVoid,
),
),
);
});
}
function waitForFileContent(path: string): Effect.Effect<string> {
return Effect.promise(async () => {
const deadline = Date.now() + 5_000;
for (;;) {
try {
return readFileSync(path, "utf8");
} catch (error) {
if (Date.now() >= deadline) {
throw error instanceof Error ? error : new Error(String(error));
}
}
await new Promise((resolve) => setTimeout(resolve, 25));
}
});
}
it.layer(CursorTextGenerationTestLayer)("CursorTextGenerationLive", (it) => {
it.effect("uses ACP model config options instead of raw CLI model ids", () => {
const requestLogDir = mkdtempSync(path.join(os.tmpdir(), "t3code-cursor-text-log-"));
const requestLogPath = path.join(requestLogDir, "requests.ndjson");
return withFakeAcpAgent(
{
T3_ACP_REQUEST_LOG_PATH: requestLogPath,
T3_ACP_PROMPT_RESPONSE_TEXT: JSON.stringify({
subject: "Add generated commit message",
body: "- verify cursor acp model config path",
}),
},
Effect.gen(function* () {
const textGeneration = yield* TextGeneration;
const generated = yield* textGeneration.generateCommitMessage({
cwd: process.cwd(),
branch: "feature/cursor-text-generation",
stagedSummary: "M apps/server/src/git/Layers/CursorTextGeneration.ts",
stagedPatch:
"diff --git a/apps/server/src/git/Layers/CursorTextGeneration.ts b/apps/server/src/git/Layers/CursorTextGeneration.ts",
modelSelection: {
...createModelSelection("cursor", "gpt-5.4", [
{ id: "reasoning", value: "xhigh" },
{ id: "fastMode", value: true },
{ id: "contextWindow", value: "1m" },
]),
},
});
expect(generated.subject).toBe("Add generated commit message");
expect(generated.body).toBe("- verify cursor acp model config path");
const requests = readFileSync(requestLogPath, "utf8")
.trim()
.split("\n")
.filter((line) => line.length > 0)
.map((line) => JSON.parse(line) as { method?: string; params?: Record<string, unknown> });
expect(
requests.find((request) => request.method === "initialize")?.params?.clientCapabilities,
).toMatchObject({
_meta: {
parameterizedModelPicker: true,
},
});
expect(
requests.some(
(request) =>
request.method === "session/set_config_option" &&
request.params?.configId === "model" &&
request.params?.value === "gpt-5.4",
),
).toBe(true);
expect(
requests.some(
(request) =>
request.method === "session/set_config_option" &&
request.params?.configId === "reasoning" &&
request.params?.value === "extra-high",
),
).toBe(true);
expect(
requests.some(
(request) =>
request.method === "session/set_config_option" &&
request.params?.configId === "context" &&
request.params?.value === "1m",
),
).toBe(true);
expect(
requests.some(
(request) =>
request.method === "session/set_config_option" &&
request.params?.configId === "fast" &&
request.params?.value === "true",
),
).toBe(true);
expect(
requests.find((request) => request.method === "session/prompt")?.params?.prompt,
).toEqual(
expect.arrayContaining([
expect.objectContaining({
type: "text",
text: expect.stringContaining("Staged patch:"),
}),
]),
);
rmSync(requestLogDir, { recursive: true, force: true });
}),
);
});
it.effect("accepts json objects with extra assistant text around them", () =>
withFakeAcpAgent(
{
T3_ACP_PROMPT_RESPONSE_TEXT:
'Sure, here is the JSON:\n```json\n{\n "subject": "Update README dummy comment with attribution and date",\n "body": ""\n}\n```\nDone.',
},
Effect.gen(function* () {
const textGeneration = yield* TextGeneration;
const generated = yield* textGeneration.generateCommitMessage({
cwd: process.cwd(),
branch: "feature/cursor-noisy-json",
stagedSummary: "M README.md",
stagedPatch: "diff --git a/README.md b/README.md",
modelSelection: {
provider: "cursor",
model: "composer-2",
},
});
expect(generated.subject).toBe("Update README dummy comment with attribution and date");
expect(generated.body).toBe("");
}),
),
);
it.effect("generates thread titles through Cursor ACP text generation", () =>
withFakeAcpAgent(
{
T3_ACP_PROMPT_RESPONSE_TEXT: JSON.stringify({
title: '"Trim reconnect spinner status after resume."',
}),
},
Effect.gen(function* () {
const textGeneration = yield* TextGeneration;
const generated = yield* textGeneration.generateThreadTitle({
cwd: process.cwd(),
message: "Fix the reconnect spinner after a resumed session.",
modelSelection: {
provider: "cursor",
model: "composer-2",
},
});
expect(generated.title).toBe("Trim reconnect spinner status after resume.");
}),
),
);
it.effect("closes the ACP child process after text generation completes", () => {
const exitLogDir = mkdtempSync(path.join(os.tmpdir(), "t3code-cursor-text-exit-log-"));
const exitLogPath = path.join(exitLogDir, "exit.log");
return withFakeAcpAgent(
{
T3_ACP_EXIT_LOG_PATH: exitLogPath,
T3_ACP_PROMPT_RESPONSE_TEXT: JSON.stringify({
subject: "Close runtime after generation",
body: "",
}),
},
Effect.gen(function* () {
const textGeneration = yield* TextGeneration;
const generated = yield* textGeneration.generateCommitMessage({
cwd: process.cwd(),
branch: "feature/cursor-runtime-close",
stagedSummary: "M apps/server/src/git/Layers/CursorTextGeneration.ts",
stagedPatch:
"diff --git a/apps/server/src/git/Layers/CursorTextGeneration.ts b/apps/server/src/git/Layers/CursorTextGeneration.ts",
modelSelection: {
provider: "cursor",
model: "composer-2",
},
});
expect(generated.subject).toBe("Close runtime after generation");
const exitLog = yield* waitForFileContent(exitLogPath);
expect(exitLog).toContain("exit:0");
rmSync(exitLogDir, { recursive: true, force: true });
}),
);
});
});
File diff suppressed because it is too large. Load diff
@@ -1,311 +0,0 @@
import { realpathSync } from "node:fs";
import {
Duration,
Effect,
Exit,
Fiber,
Layer,
PubSub,
Ref,
Scope,
Stream,
SynchronizedRef,
} from "effect";
import type {
GitStatusInput,
GitStatusLocalResult,
GitStatusRemoteResult,
GitStatusStreamEvent,
} from "@t3tools/contracts";
import { mergeGitStatusParts } from "@t3tools/shared/git";
import {
GitStatusBroadcaster,
type GitStatusBroadcasterShape,
} from "../Services/GitStatusBroadcaster.ts";
import { GitManager } from "../Services/GitManager.ts";
const GIT_STATUS_REFRESH_INTERVAL = Duration.seconds(30);
interface GitStatusChange {
readonly cwd: string;
readonly event: GitStatusStreamEvent;
}
interface CachedValue<T> {
readonly fingerprint: string;
readonly value: T;
}
interface CachedGitStatus {
readonly local: CachedValue<GitStatusLocalResult> | null;
readonly remote: CachedValue<GitStatusRemoteResult | null> | null;
}
interface ActiveRemotePoller {
readonly fiber: Fiber.Fiber<void, never>;
readonly subscriberCount: number;
}
function normalizeCwd(cwd: string): string {
try {
return realpathSync.native(cwd);
} catch {
return cwd;
}
}
function fingerprintStatusPart(status: unknown): string {
return JSON.stringify(status);
}
export const GitStatusBroadcasterLive = Layer.effect(
GitStatusBroadcaster,
Effect.gen(function* () {
const gitManager = yield* GitManager;
const changesPubSub = yield* Effect.acquireRelease(
PubSub.unbounded<GitStatusChange>(),
(pubsub) => PubSub.shutdown(pubsub),
);
const broadcasterScope = yield* Effect.acquireRelease(Scope.make(), (scope) =>
Scope.close(scope, Exit.void),
);
const cacheRef = yield* Ref.make(new Map<string, CachedGitStatus>());
const pollersRef = yield* SynchronizedRef.make(new Map<string, ActiveRemotePoller>());
const getCachedStatus = Effect.fn("getCachedStatus")(function* (cwd: string) {
return yield* Ref.get(cacheRef).pipe(Effect.map((cache) => cache.get(cwd) ?? null));
});
const updateCachedLocalStatus = Effect.fn("updateCachedLocalStatus")(function* (
cwd: string,
local: GitStatusLocalResult,
options?: { publish?: boolean },
) {
const nextLocal = {
fingerprint: fingerprintStatusPart(local),
value: local,
} satisfies CachedValue<GitStatusLocalResult>;
const shouldPublish = yield* Ref.modify(cacheRef, (cache) => {
const previous = cache.get(cwd) ?? { local: null, remote: null };
const nextCache = new Map(cache);
nextCache.set(cwd, {
...previous,
local: nextLocal,
});
return [previous.local?.fingerprint !== nextLocal.fingerprint, nextCache] as const;
});
if (options?.publish && shouldPublish) {
yield* PubSub.publish(changesPubSub, {
cwd,
event: {
_tag: "localUpdated",
local,
},
});
}
return local;
});
const updateCachedRemoteStatus = Effect.fn("updateCachedRemoteStatus")(function* (
cwd: string,
remote: GitStatusRemoteResult | null,
options?: { publish?: boolean },
) {
const nextRemote = {
fingerprint: fingerprintStatusPart(remote),
value: remote,
} satisfies CachedValue<GitStatusRemoteResult | null>;
const shouldPublish = yield* Ref.modify(cacheRef, (cache) => {
const previous = cache.get(cwd) ?? { local: null, remote: null };
const nextCache = new Map(cache);
nextCache.set(cwd, {
...previous,
remote: nextRemote,
});
return [previous.remote?.fingerprint !== nextRemote.fingerprint, nextCache] as const;
});
if (options?.publish && shouldPublish) {
yield* PubSub.publish(changesPubSub, {
cwd,
event: {
_tag: "remoteUpdated",
remote,
},
});
}
return remote;
});
const loadLocalStatus = Effect.fn("loadLocalStatus")(function* (cwd: string) {
const local = yield* gitManager.localStatus({ cwd });
return yield* updateCachedLocalStatus(cwd, local);
});
const loadRemoteStatus = Effect.fn("loadRemoteStatus")(function* (cwd: string) {
const remote = yield* gitManager.remoteStatus({ cwd });
return yield* updateCachedRemoteStatus(cwd, remote);
});
const getOrLoadLocalStatus = Effect.fn("getOrLoadLocalStatus")(function* (cwd: string) {
const cached = yield* getCachedStatus(cwd);
if (cached?.local) {
return cached.local.value;
}
return yield* loadLocalStatus(cwd);
});
const getOrLoadRemoteStatus = Effect.fn("getOrLoadRemoteStatus")(function* (cwd: string) {
const cached = yield* getCachedStatus(cwd);
if (cached?.remote) {
return cached.remote.value;
}
return yield* loadRemoteStatus(cwd);
});
const getStatus: GitStatusBroadcasterShape["getStatus"] = Effect.fn("getStatus")(function* (
input: GitStatusInput,
) {
const normalizedCwd = normalizeCwd(input.cwd);
const [local, remote] = yield* Effect.all([
getOrLoadLocalStatus(normalizedCwd),
getOrLoadRemoteStatus(normalizedCwd),
]);
return mergeGitStatusParts(local, remote);
});
const refreshLocalStatus: GitStatusBroadcasterShape["refreshLocalStatus"] = Effect.fn(
"refreshLocalStatus",
)(function* (cwd) {
const normalizedCwd = normalizeCwd(cwd);
yield* gitManager.invalidateLocalStatus(normalizedCwd);
const local = yield* gitManager.localStatus({ cwd: normalizedCwd });
return yield* updateCachedLocalStatus(normalizedCwd, local, { publish: true });
});
const refreshRemoteStatus = Effect.fn("refreshRemoteStatus")(function* (cwd: string) {
yield* gitManager.invalidateRemoteStatus(cwd);
const remote = yield* gitManager.remoteStatus({ cwd });
return yield* updateCachedRemoteStatus(cwd, remote, { publish: true });
});
const refreshStatus: GitStatusBroadcasterShape["refreshStatus"] = Effect.fn("refreshStatus")(
function* (cwd) {
const normalizedCwd = normalizeCwd(cwd);
const [local, remote] = yield* Effect.all([
refreshLocalStatus(normalizedCwd),
refreshRemoteStatus(normalizedCwd),
]);
return mergeGitStatusParts(local, remote);
},
);
const makeRemoteRefreshLoop = (cwd: string) => {
const logRefreshFailure = (error: Error) =>
Effect.logWarning("git remote status refresh failed", {
cwd,
detail: error.message,
});
return refreshRemoteStatus(cwd).pipe(
Effect.catch(logRefreshFailure),
Effect.andThen(
Effect.forever(
Effect.sleep(GIT_STATUS_REFRESH_INTERVAL).pipe(
Effect.andThen(refreshRemoteStatus(cwd).pipe(Effect.catch(logRefreshFailure))),
),
),
),
);
};
const retainRemotePoller = Effect.fn("retainRemotePoller")(function* (cwd: string) {
yield* SynchronizedRef.modifyEffect(pollersRef, (activePollers) => {
const existing = activePollers.get(cwd);
if (existing) {
const nextPollers = new Map(activePollers);
nextPollers.set(cwd, {
...existing,
subscriberCount: existing.subscriberCount + 1,
});
return Effect.succeed([undefined, nextPollers] as const);
}
return makeRemoteRefreshLoop(cwd).pipe(
Effect.forkIn(broadcasterScope),
Effect.map((fiber) => {
const nextPollers = new Map(activePollers);
nextPollers.set(cwd, {
fiber,
subscriberCount: 1,
});
return [undefined, nextPollers] as const;
}),
);
});
});
const releaseRemotePoller = Effect.fn("releaseRemotePoller")(function* (cwd: string) {
const pollerToInterrupt = yield* SynchronizedRef.modify(pollersRef, (activePollers) => {
const existing = activePollers.get(cwd);
if (!existing) {
return [null, activePollers] as const;
}
if (existing.subscriberCount > 1) {
const nextPollers = new Map(activePollers);
nextPollers.set(cwd, {
...existing,
subscriberCount: existing.subscriberCount - 1,
});
return [null, nextPollers] as const;
}
const nextPollers = new Map(activePollers);
nextPollers.delete(cwd);
return [existing.fiber, nextPollers] as const;
});
if (pollerToInterrupt) {
yield* Fiber.interrupt(pollerToInterrupt).pipe(Effect.ignore);
}
});
const streamStatus: GitStatusBroadcasterShape["streamStatus"] = (input) =>
Stream.unwrap(
Effect.gen(function* () {
const normalizedCwd = normalizeCwd(input.cwd);
const subscription = yield* PubSub.subscribe(changesPubSub);
const initialLocal = yield* getOrLoadLocalStatus(normalizedCwd);
const initialRemote = (yield* getCachedStatus(normalizedCwd))?.remote?.value ?? null;
yield* retainRemotePoller(normalizedCwd);
const release = releaseRemotePoller(normalizedCwd).pipe(Effect.ignore, Effect.asVoid);
return Stream.concat(
Stream.make({
_tag: "snapshot" as const,
local: initialLocal,
remote: initialRemote,
}),
Stream.fromSubscription(subscription).pipe(
Stream.filter((event) => event.cwd === normalizedCwd),
Stream.map((event) => event.event),
),
).pipe(Stream.ensuring(release));
}),
);
return {
getStatus,
refreshLocalStatus,
refreshStatus,
streamStatus,
} satisfies GitStatusBroadcasterShape;
}),
);
@@ -1,340 +0,0 @@
import * as NodeServices from "@effect/platform-node/NodeServices";
import { it } from "@effect/vitest";
import { Duration, Effect, Layer } from "effect";
import { TestClock } from "effect/testing";
import { NetService } from "@t3tools/shared/Net";
import { beforeEach, expect } from "vitest";
import { ServerConfig } from "../../config.ts";
import { ServerSettingsService } from "../../serverSettings.ts";
import {
OpenCodeRuntime,
OpenCodeRuntimeError,
type OpenCodeRuntimeShape,
} from "../../provider/opencodeRuntime.ts";
import { TextGeneration } from "../Services/TextGeneration.ts";
import { OpenCodeTextGenerationLive } from "./OpenCodeTextGeneration.ts";
const runtimeMock = {
state: {
startCalls: [] as string[],
promptUrls: [] as string[],
authHeaders: [] as Array<string | null>,
closeCalls: [] as string[],
promptResult: undefined as
| { data?: { info?: { error?: unknown }; parts?: Array<{ type: string; text?: string }> } }
| undefined,
},
reset() {
this.state.startCalls.length = 0;
this.state.promptUrls.length = 0;
this.state.authHeaders.length = 0;
this.state.closeCalls.length = 0;
this.state.promptResult = undefined;
},
};
const OpenCodeRuntimeTestDouble: OpenCodeRuntimeShape = {
startOpenCodeServerProcess: ({ binaryPath }) =>
Effect.gen(function* () {
const index = runtimeMock.state.startCalls.length + 1;
const url = `http://127.0.0.1:${4_300 + index}`;
runtimeMock.state.startCalls.push(binaryPath);
// The production runtime binds server lifetime to the caller's scope.
// Mirror that here so the closeCalls probe observes scope close.
yield* Effect.addFinalizer(() =>
Effect.sync(() => {
runtimeMock.state.closeCalls.push(url);
}),
);
return {
url,
exitCode: Effect.never,
};
}),
connectToOpenCodeServer: ({ serverUrl }) =>
Effect.succeed({
url: serverUrl ?? "http://127.0.0.1:4301",
exitCode: null,
external: Boolean(serverUrl),
}),
runOpenCodeCommand: () => Effect.succeed({ stdout: "", stderr: "", code: 0 }),
createOpenCodeSdkClient: ({ baseUrl, serverPassword }) =>
({
session: {
create: async () => ({ data: { id: `${baseUrl}/session` } }),
prompt: async () => {
runtimeMock.state.promptUrls.push(baseUrl);
runtimeMock.state.authHeaders.push(
serverPassword ? `Basic ${btoa(`opencode:${serverPassword}`)}` : null,
);
return (
runtimeMock.state.promptResult ?? {
data: {
parts: [
{
type: "text",
text: JSON.stringify({
subject: "Improve OpenCode reuse",
body: "Reuse one server for the full action.",
}),
},
],
},
}
);
},
},
}) as unknown as ReturnType<OpenCodeRuntimeShape["createOpenCodeSdkClient"]>,
loadOpenCodeInventory: () =>
Effect.fail(
new OpenCodeRuntimeError({
operation: "loadOpenCodeInventory",
detail: "OpenCodeRuntimeTestDouble.loadOpenCodeInventory not used in this test",
cause: null,
}),
),
};
const DEFAULT_TEST_MODEL_SELECTION = {
provider: "opencode" as const,
model: "openai/gpt-5",
};
const OPENCODE_TEXT_GENERATION_IDLE_TTL_MS = 30_000;
const OpenCodeTextGenerationTestLayer = OpenCodeTextGenerationLive.pipe(
Layer.provideMerge(Layer.succeed(OpenCodeRuntime, OpenCodeRuntimeTestDouble)),
Layer.provideMerge(
ServerSettingsService.layerTest({
providers: {
opencode: {
binaryPath: "fake-opencode",
},
},
}),
),
Layer.provideMerge(
ServerConfig.layerTest(process.cwd(), {
prefix: "t3code-opencode-text-generation-test-",
}),
),
Layer.provideMerge(NetService.layer),
Layer.provideMerge(NodeServices.layer),
);
const OpenCodeTextGenerationExistingServerTestLayer = OpenCodeTextGenerationLive.pipe(
Layer.provideMerge(Layer.succeed(OpenCodeRuntime, OpenCodeRuntimeTestDouble)),
Layer.provideMerge(
ServerSettingsService.layerTest({
providers: {
opencode: {
binaryPath: "fake-opencode",
serverUrl: "http://127.0.0.1:9999",
serverPassword: "secret-password",
},
},
}),
),
Layer.provideMerge(
ServerConfig.layerTest(process.cwd(), {
prefix: "t3code-opencode-text-generation-existing-server-test-",
}),
),
Layer.provideMerge(NetService.layer),
Layer.provideMerge(NodeServices.layer),
);
beforeEach(() => {
runtimeMock.reset();
});
const advanceIdleClock = Effect.gen(function* () {
yield* Effect.yieldNow;
yield* TestClock.adjust(Duration.millis(OPENCODE_TEXT_GENERATION_IDLE_TTL_MS + 1));
yield* Effect.yieldNow;
});
it.layer(OpenCodeTextGenerationTestLayer)("OpenCodeTextGenerationLive", (it) => {
it.effect("reuses a warm server across back-to-back requests and closes it after idling", () =>
Effect.gen(function* () {
const textGeneration = yield* TextGeneration;
yield* textGeneration.generateCommitMessage({
cwd: process.cwd(),
branch: "feature/opencode-reuse",
stagedSummary: "M README.md",
stagedPatch: "diff --git a/README.md b/README.md",
modelSelection: DEFAULT_TEST_MODEL_SELECTION,
});
yield* textGeneration.generateCommitMessage({
cwd: process.cwd(),
branch: "feature/opencode-reuse",
stagedSummary: "M README.md",
stagedPatch: "diff --git a/README.md b/README.md",
modelSelection: DEFAULT_TEST_MODEL_SELECTION,
});
expect(runtimeMock.state.startCalls).toEqual(["fake-opencode"]);
expect(runtimeMock.state.promptUrls).toEqual([
"http://127.0.0.1:4301",
"http://127.0.0.1:4301",
]);
expect(runtimeMock.state.closeCalls).toEqual([]);
yield* advanceIdleClock;
expect(runtimeMock.state.closeCalls).toEqual(["http://127.0.0.1:4301"]);
}).pipe(Effect.provide(TestClock.layer())),
);
it.effect("starts a new server after the warm server idles out", () =>
Effect.gen(function* () {
const textGeneration = yield* TextGeneration;
yield* textGeneration.generateCommitMessage({
cwd: process.cwd(),
branch: "feature/opencode-reuse",
stagedSummary: "M README.md",
stagedPatch: "diff --git a/README.md b/README.md",
modelSelection: DEFAULT_TEST_MODEL_SELECTION,
});
yield* advanceIdleClock;
yield* textGeneration.generateCommitMessage({
cwd: process.cwd(),
branch: "feature/opencode-reuse",
stagedSummary: "M README.md",
stagedPatch: "diff --git a/README.md b/README.md",
modelSelection: DEFAULT_TEST_MODEL_SELECTION,
});
expect(runtimeMock.state.startCalls).toEqual(["fake-opencode", "fake-opencode"]);
expect(runtimeMock.state.promptUrls).toEqual([
"http://127.0.0.1:4301",
"http://127.0.0.1:4302",
]);
expect(runtimeMock.state.closeCalls).toEqual(["http://127.0.0.1:4301"]);
}).pipe(Effect.provide(TestClock.layer())),
);
it.effect("returns a typed empty-output error when OpenCode returns no text parts", () =>
Effect.gen(function* () {
runtimeMock.state.promptResult = { data: {} };
const textGeneration = yield* TextGeneration;
const error = yield* textGeneration
.generateCommitMessage({
cwd: process.cwd(),
branch: "feature/opencode-reuse",
stagedSummary: "M README.md",
stagedPatch: "diff --git a/README.md b/README.md",
modelSelection: DEFAULT_TEST_MODEL_SELECTION,
})
.pipe(Effect.flip);
expect(error.message).toContain("OpenCode returned empty output.");
}),
);
it.effect("parses JSON returned as plain text output", () =>
Effect.gen(function* () {
runtimeMock.state.promptResult = {
data: {
parts: [
{
type: "text",
text: 'Here is the result:\n{"subject":"Tighten OpenCode parsing","body":"Handle JSON text output locally."}',
},
],
},
};
const textGeneration = yield* TextGeneration;
const result = yield* textGeneration.generateCommitMessage({
cwd: process.cwd(),
branch: "feature/opencode-reuse",
stagedSummary: "M README.md",
stagedPatch: "diff --git a/README.md b/README.md",
modelSelection: DEFAULT_TEST_MODEL_SELECTION,
});
expect(result).toEqual({
subject: "Tighten OpenCode parsing",
body: "Handle JSON text output locally.",
});
}),
);
it.effect("surfaces the upstream OpenCode structured-output error message", () =>
Effect.gen(function* () {
runtimeMock.state.promptResult = {
data: {
info: {
error: {
name: "StructuredOutputError",
data: {
message: "Model did not produce structured output",
retries: 2,
},
},
},
},
};
const textGeneration = yield* TextGeneration;
const error = yield* textGeneration
.generateCommitMessage({
cwd: process.cwd(),
branch: "feature/opencode-reuse",
stagedSummary: "M README.md",
stagedPatch: "diff --git a/README.md b/README.md",
modelSelection: DEFAULT_TEST_MODEL_SELECTION,
})
.pipe(Effect.flip);
expect(error.message).toContain("Model did not produce structured output");
}),
);
});
it.layer(OpenCodeTextGenerationExistingServerTestLayer)(
"OpenCodeTextGenerationLive with configured server URL",
(it) => {
it.effect("reuses a configured OpenCode server URL without spawning or applying idle TTL", () =>
Effect.gen(function* () {
const textGeneration = yield* TextGeneration;
yield* textGeneration.generateCommitMessage({
cwd: process.cwd(),
branch: "feature/opencode-reuse",
stagedSummary: "M README.md",
stagedPatch: "diff --git a/README.md b/README.md",
modelSelection: DEFAULT_TEST_MODEL_SELECTION,
});
yield* textGeneration.generateCommitMessage({
cwd: process.cwd(),
branch: "feature/opencode-reuse",
stagedSummary: "M README.md",
stagedPatch: "diff --git a/README.md b/README.md",
modelSelection: DEFAULT_TEST_MODEL_SELECTION,
});
expect(runtimeMock.state.startCalls).toEqual([]);
expect(runtimeMock.state.promptUrls).toEqual([
"http://127.0.0.1:9999",
"http://127.0.0.1:9999",
]);
expect(runtimeMock.state.authHeaders).toEqual([
`Basic ${btoa("opencode:secret-password")}`,
`Basic ${btoa("opencode:secret-password")}`,
]);
yield* advanceIdleClock;
expect(runtimeMock.state.closeCalls).toEqual([]);
}).pipe(Effect.provide(TestClock.layer())),
);
},
);
@@ -1,104 +0,0 @@
/**
* RoutingTextGeneration – Dispatches text generation requests to either the
* Codex CLI or Claude CLI implementation based on the provider in each
* request input.
*
* When `modelSelection.provider` is `"claudeAgent"` the request is forwarded to
* the Claude layer; for any other value (including the default `undefined`) it
* falls through to the Codex layer.
*
* @module RoutingTextGeneration
*/
import { Effect, Layer, Context } from "effect";
import { TextGeneration, type TextGenerationShape } from "../Services/TextGeneration.ts";
import { CodexTextGenerationLive } from "./CodexTextGeneration.ts";
import { ClaudeTextGenerationLive } from "./ClaudeTextGeneration.ts";
import { CursorTextGenerationLive } from "./CursorTextGeneration.ts";
import { OpenCodeTextGenerationLive } from "./OpenCodeTextGeneration.ts";
// ---------------------------------------------------------------------------
// Internal service tags so both concrete layers can coexist.
// ---------------------------------------------------------------------------
class CodexTextGen extends Context.Service<CodexTextGen, TextGenerationShape>()(
"t3/git/Layers/RoutingTextGeneration/CodexTextGen",
) {}
class ClaudeTextGen extends Context.Service<ClaudeTextGen, TextGenerationShape>()(
"t3/git/Layers/RoutingTextGeneration/ClaudeTextGen",
) {}
class CursorTextGen extends Context.Service<CursorTextGen, TextGenerationShape>()(
"t3/git/Layers/RoutingTextGeneration/CursorTextGen",
) {}
class OpenCodeTextGen extends Context.Service<OpenCodeTextGen, TextGenerationShape>()(
"t3/git/Layers/RoutingTextGeneration/OpenCodeTextGen",
) {}
// ---------------------------------------------------------------------------
// Routing implementation
// ---------------------------------------------------------------------------
const makeRoutingTextGeneration = Effect.gen(function* () {
const byProvider = {
codex: yield* CodexTextGen,
claudeAgent: yield* ClaudeTextGen,
cursor: yield* CursorTextGen,
opencode: yield* OpenCodeTextGen,
};
return {
generateCommitMessage: (input) =>
byProvider[input.modelSelection.provider].generateCommitMessage(input),
generatePrContent: (input) =>
byProvider[input.modelSelection.provider].generatePrContent(input),
generateBranchName: (input) =>
byProvider[input.modelSelection.provider].generateBranchName(input),
generateThreadTitle: (input) =>
byProvider[input.modelSelection.provider].generateThreadTitle(input),
} satisfies TextGenerationShape;
});
const InternalCodexLayer = Layer.effect(
CodexTextGen,
Effect.gen(function* () {
const svc = yield* TextGeneration;
return svc;
}),
).pipe(Layer.provide(CodexTextGenerationLive));
const InternalClaudeLayer = Layer.effect(
ClaudeTextGen,
Effect.gen(function* () {
const svc = yield* TextGeneration;
return svc;
}),
).pipe(Layer.provide(ClaudeTextGenerationLive));
const InternalCursorLayer = Layer.effect(
CursorTextGen,
Effect.gen(function* () {
const svc = yield* TextGeneration;
return svc;
}),
).pipe(Layer.provide(CursorTextGenerationLive));
const InternalOpenCodeLayer = Layer.effect(
OpenCodeTextGen,
Effect.gen(function* () {
const svc = yield* TextGeneration;
return svc;
}),
).pipe(Layer.provide(OpenCodeTextGenerationLive));
export const RoutingTextGenerationLive = Layer.effect(
TextGeneration,
makeRoutingTextGeneration,
).pipe(
Layer.provide(InternalCodexLayer),
Layer.provide(InternalClaudeLayer),
Layer.provide(InternalCursorLayer),
Layer.provide(InternalOpenCodeLayer),
);
-313
View File
@@ -1,313 +0,0 @@
/**
* GitCore - Effect service contract for low-level Git operations.
*
* Wraps core repository primitives used by higher-level orchestration
* services and WebSocket routes.
*
* @module GitCore
*/
import { Context } from "effect";
import type { Effect } from "effect";
import type {
GitCheckoutInput,
GitCheckoutResult,
GitCreateBranchInput,
GitCreateBranchResult,
GitCreateWorktreeInput,
GitCreateWorktreeResult,
GitInitInput,
GitListBranchesInput,
GitListBranchesResult,
GitPullResult,
GitRemoveWorktreeInput,
GitStatusInput,
GitStatusResult,
} from "@t3tools/contracts";
import type { GitCommandError } from "@t3tools/contracts";
export interface ExecuteGitInput {
readonly operation: string;
readonly cwd: string;
readonly args: ReadonlyArray<string>;
readonly stdin?: string;
readonly env?: NodeJS.ProcessEnv;
readonly allowNonZeroExit?: boolean;
readonly timeoutMs?: number;
readonly maxOutputBytes?: number;
readonly truncateOutputAtMaxBytes?: boolean;
readonly progress?: ExecuteGitProgress;
}
export interface ExecuteGitResult {
readonly code: number;
readonly stdout: string;
readonly stderr: string;
readonly stdoutTruncated: boolean;
readonly stderrTruncated: boolean;
}
export interface GitStatusDetails extends Omit<GitStatusResult, "pr"> {
upstreamRef: string | null;
}
export interface GitPreparedCommitContext {
stagedSummary: string;
stagedPatch: string;
}
export interface ExecuteGitProgress {
readonly onStdoutLine?: (line: string) => Effect.Effect<void, never>;
readonly onStderrLine?: (line: string) => Effect.Effect<void, never>;
readonly onHookStarted?: (hookName: string) => Effect.Effect<void, never>;
readonly onHookFinished?: (input: {
hookName: string;
exitCode: number | null;
durationMs: number | null;
}) => Effect.Effect<void, never>;
}
export interface GitCommitProgress {
readonly onOutputLine?: (input: {
stream: "stdout" | "stderr";
text: string;
}) => Effect.Effect<void, never>;
readonly onHookStarted?: (hookName: string) => Effect.Effect<void, never>;
readonly onHookFinished?: (input: {
hookName: string;
exitCode: number | null;
durationMs: number | null;
}) => Effect.Effect<void, never>;
}
export interface GitCommitOptions {
readonly timeoutMs?: number;
readonly progress?: GitCommitProgress;
}
export interface GitPushResult {
status: "pushed" | "skipped_up_to_date";
branch: string;
upstreamBranch?: string | undefined;
setUpstream?: boolean | undefined;
}
export interface GitRangeContext {
commitSummary: string;
diffSummary: string;
diffPatch: string;
}
export interface GitListWorkspaceFilesResult {
readonly paths: ReadonlyArray<string>;
readonly truncated: boolean;
}
export interface GitRenameBranchInput {
cwd: string;
oldBranch: string;
newBranch: string;
}
export interface GitRenameBranchResult {
branch: string;
}
export interface GitFetchPullRequestBranchInput {
cwd: string;
prNumber: number;
branch: string;
}
export interface GitEnsureRemoteInput {
cwd: string;
preferredName: string;
url: string;
}
export interface GitFetchRemoteBranchInput {
cwd: string;
remoteName: string;
remoteBranch: string;
localBranch: string;
}
export interface GitSetBranchUpstreamInput {
cwd: string;
branch: string;
remoteName: string;
remoteBranch: string;
}
/**
* GitCoreShape - Service API for low-level Git repository interactions.
*/
export interface GitCoreShape {
/**
* Execute a raw Git command.
*/
readonly execute: (input: ExecuteGitInput) => Effect.Effect<ExecuteGitResult, GitCommandError>;
/**
* Read Git status for a repository.
*/
readonly status: (input: GitStatusInput) => Effect.Effect<GitStatusResult, GitCommandError>;
/**
* Read detailed working tree / branch status for a repository.
*/
readonly statusDetails: (cwd: string) => Effect.Effect<GitStatusDetails, GitCommandError>;
/**
* Read detailed working tree / branch status without refreshing remote tracking refs.
*/
readonly statusDetailsLocal: (cwd: string) => Effect.Effect<GitStatusDetails, GitCommandError>;
/**
* Build staged change context for commit generation.
*/
readonly prepareCommitContext: (
cwd: string,
filePaths?: readonly string[],
) => Effect.Effect<GitPreparedCommitContext | null, GitCommandError>;
/**
* Create a commit with provided subject/body.
*/
readonly commit: (
cwd: string,
subject: string,
body: string,
options?: GitCommitOptions,
) => Effect.Effect<{ commitSha: string }, GitCommandError>;
/**
* Push current branch, setting upstream if needed.
*/
readonly pushCurrentBranch: (
cwd: string,
fallbackBranch: string | null,
) => Effect.Effect<GitPushResult, GitCommandError>;
/**
* Collect commit/diff context between base branch and current HEAD.
*/
readonly readRangeContext: (
cwd: string,
baseBranch: string,
) => Effect.Effect<GitRangeContext, GitCommandError>;
/**
* Read a Git config value from the local repository.
*/
readonly readConfigValue: (
cwd: string,
key: string,
) => Effect.Effect<string | null, GitCommandError>;
/**
* Determine whether the provided cwd is inside a git work tree.
*/
readonly isInsideWorkTree: (cwd: string) => Effect.Effect<boolean, GitCommandError>;
/**
* List tracked and untracked workspace file paths relative to cwd.
*/
readonly listWorkspaceFiles: (
cwd: string,
) => Effect.Effect<GitListWorkspaceFilesResult, GitCommandError>;
/**
* Remove gitignored paths from a relative path list.
*/
readonly filterIgnoredPaths: (
cwd: string,
relativePaths: ReadonlyArray<string>,
) => Effect.Effect<ReadonlyArray<string>, GitCommandError>;
/**
* List local + remote branches and branch metadata.
*/
readonly listBranches: (
input: GitListBranchesInput,
) => Effect.Effect<GitListBranchesResult, GitCommandError>;
/**
* Pull current branch from upstream using fast-forward only.
*/
readonly pullCurrentBranch: (cwd: string) => Effect.Effect<GitPullResult, GitCommandError>;
/**
* Create a worktree and branch from a base branch.
*/
readonly createWorktree: (
input: GitCreateWorktreeInput,
) => Effect.Effect<GitCreateWorktreeResult, GitCommandError>;
/**
* Materialize a GitHub pull request head as a local branch without switching checkout.
*/
readonly fetchPullRequestBranch: (
input: GitFetchPullRequestBranchInput,
) => Effect.Effect<void, GitCommandError>;
/**
* Ensure a named remote exists for the provided URL, returning the reused or created remote name.
*/
readonly ensureRemote: (input: GitEnsureRemoteInput) => Effect.Effect<string, GitCommandError>;
/**
* Fetch a remote branch into a local branch without checkout.
*/
readonly fetchRemoteBranch: (
input: GitFetchRemoteBranchInput,
) => Effect.Effect<void, GitCommandError>;
/**
* Set the upstream tracking branch for a local branch.
*/
readonly setBranchUpstream: (
input: GitSetBranchUpstreamInput,
) => Effect.Effect<void, GitCommandError>;
/**
* Remove an existing worktree.
*/
readonly removeWorktree: (input: GitRemoveWorktreeInput) => Effect.Effect<void, GitCommandError>;
/**
* Rename an existing local branch.
*/
readonly renameBranch: (
input: GitRenameBranchInput,
) => Effect.Effect<GitRenameBranchResult, GitCommandError>;
/**
* Create a local branch.
*/
readonly createBranch: (
input: GitCreateBranchInput,
) => Effect.Effect<GitCreateBranchResult, GitCommandError>;
/**
* Checkout an existing branch and refresh its upstream metadata in background.
*/
readonly checkoutBranch: (
input: GitCheckoutInput,
) => Effect.Effect<GitCheckoutResult, GitCommandError>;
/**
* Initialize a repository in the provided directory.
*/
readonly initRepo: (input: GitInitInput) => Effect.Effect<void, GitCommandError>;
/**
* List local branch names (short format).
*/
readonly listLocalBranchNames: (cwd: string) => Effect.Effect<string[], GitCommandError>;
}
/**
* GitCore - Service tag for low-level Git repository operations.
*/
export class GitCore extends Context.Service<GitCore, GitCoreShape>()("t3/git/Services/GitCore") {}
-103
View File
@@ -1,103 +0,0 @@
/**
* GitHubCli - Effect service contract for `gh` process interactions.
*
* Provides thin command execution helpers used by Git workflow orchestration.
*
* @module GitHubCli
*/
import { Context } from "effect";
import type { Effect } from "effect";
import type { ProcessRunResult } from "../../processRunner.ts";
import type { GitHubCliError } from "@t3tools/contracts";
export interface GitHubPullRequestSummary {
readonly number: number;
readonly title: string;
readonly url: string;
readonly baseRefName: string;
readonly headRefName: string;
readonly state?: "open" | "closed" | "merged";
readonly isCrossRepository?: boolean;
readonly headRepositoryNameWithOwner?: string | null;
readonly headRepositoryOwnerLogin?: string | null;
}
export interface GitHubRepositoryCloneUrls {
readonly nameWithOwner: string;
readonly url: string;
readonly sshUrl: string;
}
/**
* GitHubCliShape - Service API for executing GitHub CLI commands.
*/
export interface GitHubCliShape {
/**
* Execute a GitHub CLI command and return full process output.
*/
readonly execute: (input: {
readonly cwd: string;
readonly args: ReadonlyArray<string>;
readonly timeoutMs?: number;
}) => Effect.Effect<ProcessRunResult, GitHubCliError>;
/**
* List open pull requests for a head branch.
*/
readonly listOpenPullRequests: (input: {
readonly cwd: string;
readonly headSelector: string;
readonly limit?: number;
}) => Effect.Effect<ReadonlyArray<GitHubPullRequestSummary>, GitHubCliError>;
/**
* Resolve a pull request by URL, number, or branch-ish identifier.
*/
readonly getPullRequest: (input: {
readonly cwd: string;
readonly reference: string;
}) => Effect.Effect<GitHubPullRequestSummary, GitHubCliError>;
/**
* Resolve clone URLs for a GitHub repository.
*/
readonly getRepositoryCloneUrls: (input: {
readonly cwd: string;
readonly repository: string;
}) => Effect.Effect<GitHubRepositoryCloneUrls, GitHubCliError>;
/**
* Create a pull request from branch context and body file.
*/
readonly createPullRequest: (input: {
readonly cwd: string;
readonly baseBranch: string;
readonly headSelector: string;
readonly title: string;
readonly bodyFile: string;
}) => Effect.Effect<void, GitHubCliError>;
/**
* Resolve repository default branch through GitHub metadata.
*/
readonly getDefaultBranch: (input: {
readonly cwd: string;
}) => Effect.Effect<string | null, GitHubCliError>;
/**
* Checkout a pull request into the current repository worktree.
*/
readonly checkoutPullRequest: (input: {
readonly cwd: string;
readonly reference: string;
readonly force?: boolean;
}) => Effect.Effect<void, GitHubCliError>;
}
/**
* GitHubCli - Service tag for GitHub CLI process execution.
*/
export class GitHubCli extends Context.Service<GitHubCli, GitHubCliShape>()(
"t3/git/Services/GitHubCli",
) {}
-104
View File
@@ -1,104 +0,0 @@
/**
* GitManager - Effect service contract for stacked Git workflows.
*
* Orchestrates status inspection and commit/push/PR flows by composing
* lower-level Git and external tool services.
*
* @module GitManager
*/
import {
GitActionProgressEvent,
GitPreparePullRequestThreadInput,
GitPreparePullRequestThreadResult,
GitPullRequestRefInput,
GitResolvePullRequestResult,
GitRunStackedActionInput,
GitRunStackedActionResult,
GitStatusLocalResult,
GitStatusRemoteResult,
GitStatusInput,
GitStatusResult,
} from "@t3tools/contracts";
import { Context } from "effect";
import type { Effect } from "effect";
import type { GitManagerServiceError } from "@t3tools/contracts";
export interface GitActionProgressReporter {
readonly publish: (event: GitActionProgressEvent) => Effect.Effect<void, never>;
}
export interface GitRunStackedActionOptions {
readonly actionId?: string;
readonly progressReporter?: GitActionProgressReporter;
}
/**
* GitManagerShape - Service API for high-level Git workflow actions.
*/
export interface GitManagerShape {
/**
* Read current repository Git status plus open PR metadata when available.
*/
readonly status: (
input: GitStatusInput,
) => Effect.Effect<GitStatusResult, GitManagerServiceError>;
/**
* Read local repository status without remote hosting enrichment.
*/
readonly localStatus: (
input: GitStatusInput,
) => Effect.Effect<GitStatusLocalResult, GitManagerServiceError>;
/**
* Read remote tracking / PR status for a repository.
*/
readonly remoteStatus: (
input: GitStatusInput,
) => Effect.Effect<GitStatusRemoteResult | null, GitManagerServiceError>;
/**
* Clear any cached local status snapshot for a repository.
*/
readonly invalidateLocalStatus: (cwd: string) => Effect.Effect<void, never>;
/**
* Clear any cached remote status snapshot for a repository.
*/
readonly invalidateRemoteStatus: (cwd: string) => Effect.Effect<void, never>;
/**
* Clear any cached status snapshot for a repository so the next read is fresh.
*/
readonly invalidateStatus: (cwd: string) => Effect.Effect<void, never>;
/**
* Resolve a pull request by URL/number against the current repository.
*/
readonly resolvePullRequest: (
input: GitPullRequestRefInput,
) => Effect.Effect<GitResolvePullRequestResult, GitManagerServiceError>;
/**
* Prepare a new thread workspace from a pull request in local or worktree mode.
*/
readonly preparePullRequestThread: (
input: GitPreparePullRequestThreadInput,
) => Effect.Effect<GitPreparePullRequestThreadResult, GitManagerServiceError>;
/**
* Run a Git action (`commit`, `push`, `create_pr`, `commit_push`, `commit_push_pr`).
* When `featureBranch` is set, creates and checks out a feature branch first.
*/
readonly runStackedAction: (
input: GitRunStackedActionInput,
options?: GitRunStackedActionOptions,
) => Effect.Effect<GitRunStackedActionResult, GitManagerServiceError>;
}
/**
* GitManager - Service tag for stacked Git workflow orchestration.
*/
export class GitManager extends Context.Service<GitManager, GitManagerShape>()(
"t3/git/Services/GitManager",
) {}
@@ -1,27 +0,0 @@
import { Context } from "effect";
import type { Effect, Stream } from "effect";
import type {
GitManagerServiceError,
GitStatusInput,
GitStatusLocalResult,
GitStatusResult,
GitStatusStreamEvent,
} from "@t3tools/contracts";
export interface GitStatusBroadcasterShape {
readonly getStatus: (
input: GitStatusInput,
) => Effect.Effect<GitStatusResult, GitManagerServiceError>;
readonly refreshLocalStatus: (
cwd: string,
) => Effect.Effect<GitStatusLocalResult, GitManagerServiceError>;
readonly refreshStatus: (cwd: string) => Effect.Effect<GitStatusResult, GitManagerServiceError>;
readonly streamStatus: (
input: GitStatusInput,
) => Stream.Stream<GitStatusStreamEvent, GitManagerServiceError>;
}
export class GitStatusBroadcaster extends Context.Service<
GitStatusBroadcaster,
GitStatusBroadcasterShape
>()("t3/git/Services/GitStatusBroadcaster") {}
-165
View File
@@ -1,171 +1,6 @@
/**
* Shared utilities for text generation layers (Codex, Claude, etc.).
*
* @module textGenerationUtils
*/
import { Schema } from "effect";
import { TextGenerationError } from "@t3tools/contracts";
import { existsSync } from "node:fs";
import { join } from "node:path";
export function isGitRepository(cwd: string): boolean {
return existsSync(join(cwd, ".git"));
}
/** Convert an Effect Schema to a flat JSON Schema object, inlining `$defs` when present. */
export function toJsonSchemaObject(schema: Schema.Top): unknown {
const document = Schema.toJsonSchemaDocument(schema);
if (document.definitions && Object.keys(document.definitions).length > 0) {
return { ...document.schema, $defs: document.definitions };
}
return document.schema;
}
/** Truncate a text section to `maxChars`, appending a `[truncated]` marker when needed. */
export function limitSection(value: string, maxChars: number): string {
if (value.length <= maxChars) return value;
const truncated = value.slice(0, maxChars);
return `${truncated}\n\n[truncated]`;
}
export function extractJsonObject(raw: string): string {
const trimmed = raw.trim();
if (trimmed.length === 0) {
return trimmed;
}
const start = trimmed.indexOf("{");
if (start < 0) {
return trimmed;
}
let depth = 0;
let inString = false;
let escaping = false;
for (let index = start; index < trimmed.length; index += 1) {
const char = trimmed[index];
if (inString) {
if (escaping) {
escaping = false;
} else if (char === "\\") {
escaping = true;
} else if (char === '"') {
inString = false;
}
continue;
}
if (char === '"') {
inString = true;
continue;
}
if (char === "{") {
depth += 1;
continue;
}
if (char === "}") {
depth -= 1;
if (depth === 0) {
return trimmed.slice(start, index + 1);
}
}
}
return trimmed.slice(start);
}
/** Normalise a raw commit subject to imperative-mood, ≤72 chars, no trailing period. */
export function sanitizeCommitSubject(raw: string): string {
const singleLine = raw.trim().split(/\r?\n/g)[0]?.trim() ?? "";
const withoutTrailingPeriod = singleLine.replace(/[.]+$/g, "").trim();
if (withoutTrailingPeriod.length === 0) {
return "Update project files";
}
if (withoutTrailingPeriod.length <= 72) {
return withoutTrailingPeriod;
}
return withoutTrailingPeriod.slice(0, 72).trimEnd();
}
/** Normalise a raw PR title to a single line with a sensible fallback. */
export function sanitizePrTitle(raw: string): string {
const singleLine = raw.trim().split(/\r?\n/g)[0]?.trim() ?? "";
if (singleLine.length > 0) {
return singleLine;
}
return "Update project changes";
}
/** Normalise a raw thread title to a compact single-line sidebar-safe label. */
export function sanitizeThreadTitle(raw: string): string {
const normalized = raw
.trim()
.split(/\r?\n/g)[0]
?.trim()
.replace(/^['"`]+|['"`]+$/g, "")
.trim()
.replace(/\s+/g, " ");
if (!normalized || normalized.trim().length === 0) {
return "New thread";
}
if (normalized.length <= 50) {
return normalized;
}
return `${normalized.slice(0, 47).trimEnd()}...`;
}
/** CLI name to human-readable label, e.g. "codex" → "Codex CLI (`codex`)" */
function cliLabel(cliName: string): string {
const capitalized = cliName.charAt(0).toUpperCase() + cliName.slice(1);
return `${capitalized} CLI (\`${cliName}\`)`;
}
/**
* Normalize an unknown error from a CLI text generation process into a
* typed `TextGenerationError`. Parameterized by CLI name so both Codex
* and Claude (and future providers) can share the same logic.
*/
export function normalizeCliError(
cliName: string,
operation: string,
error: unknown,
fallback: string,
): TextGenerationError {
if (Schema.is(TextGenerationError)(error)) {
return error;
}
if (error instanceof Error) {
const lower = error.message.toLowerCase();
if (
error.message.includes(`Command not found: ${cliName}`) ||
lower.includes(`spawn ${cliName}`) ||
lower.includes("enoent")
) {
return new TextGenerationError({
operation,
detail: `${cliLabel(cliName)} is required but not available on PATH.`,
cause: error,
});
}
return new TextGenerationError({
operation,
detail: `${fallback}: ${error.message}`,
cause: error,
});
}
return new TextGenerationError({
operation,
detail: fallback,
cause: error,
});
}
+4 -5
View File
@@ -1,4 +1,4 @@
import { Cause, Exit, Result, Schema } from "effect";
import { Cause, DateTime, Exit, Option, Result, Schema } from "effect";
import { PositiveInt, TrimmedNonEmptyString } from "@t3tools/contracts";
import { decodeJsonResult, formatSchemaError } from "@t3tools/shared/schemaJson";
@@ -9,7 +9,7 @@ export interface NormalizedGitHubPullRequestRecord {
readonly baseRefName: string;
readonly headRefName: string;
readonly state: "open" | "closed" | "merged";
readonly updatedAt: string | null;
readonly updatedAt: Option.Option<DateTime.Utc>;
readonly isCrossRepository?: boolean;
readonly headRepositoryNameWithOwner?: string | null;
readonly headRepositoryOwnerLogin?: string | null;
@@ -23,7 +23,7 @@ const GitHubPullRequestSchema = Schema.Struct({
headRefName: TrimmedNonEmptyString,
state: Schema.optional(Schema.NullOr(Schema.String)),
mergedAt: Schema.optional(Schema.NullOr(Schema.String)),
updatedAt: Schema.optional(Schema.NullOr(Schema.String)),
updatedAt: Schema.optional(Schema.OptionFromNullOr(Schema.DateTimeUtcFromString)),
isCrossRepository: Schema.optional(Schema.Boolean),
headRepository: Schema.optional(
Schema.NullOr(
@@ -80,8 +80,7 @@ function normalizeGitHubPullRequestRecord(
baseRefName: raw.baseRefName,
headRefName: raw.headRefName,
state: normalizeGitHubPullRequestState(raw),
updatedAt:
typeof raw.updatedAt === "string" && raw.updatedAt.trim().length > 0 ? raw.updatedAt : null,
updatedAt: raw.updatedAt ?? Option.none(),
...(typeof raw.isCrossRepository === "boolean"
? { isCrossRepository: raw.isCrossRepository }
: {}),
@@ -1,4 +1,5 @@
import { assert, describe, it } from "@effect/vitest";
import { ProviderDriverKind } from "@t3tools/contracts";
import { Effect, Metric } from "effect";
import { withMetrics } from "./Metrics.ts";
@@ -75,10 +76,11 @@ describe("withMetrics", () => {
Effect.gen(function* () {
const counter = Metric.counter("with_metrics_lazy_total");
const timer = Metric.timer("with_metrics_lazy_duration");
let provider = "unknown";
let provider = ProviderDriverKind.make("unknown");
const lazyInittedProvider = ProviderDriverKind.make("codex");
yield* Effect.sync(() => {
provider = "codex";
provider = lazyInittedProvider;
}).pipe(
withMetrics({
counter,
@@ -93,7 +95,7 @@ describe("withMetrics", () => {
const snapshots = yield* Metric.snapshot;
assert.equal(
hasMetricSnapshot(snapshots, "with_metrics_lazy_total", {
provider: "codex",
provider: lazyInittedProvider,
operation: "lazy",
outcome: "success",
}),
@@ -101,7 +103,7 @@ describe("withMetrics", () => {
);
assert.equal(
hasMetricSnapshot(snapshots, "with_metrics_lazy_duration", {
provider: "codex",
provider: lazyInittedProvider,
operation: "lazy",
}),
true,
@@ -3,7 +3,12 @@ import os from "node:os";
import path from "node:path";
import { execFileSync } from "node:child_process";
import type { ProviderKind, ProviderRuntimeEvent, ProviderSession } from "@t3tools/contracts";
import {
ProviderDriverKind,
ProviderRuntimeEvent,
ProviderSession,
ProviderInstanceId,
} from "@t3tools/contracts";
import {
CommandId,
DEFAULT_PROVIDER_INTERACTION_MODE,
@@ -19,8 +24,9 @@ import { afterEach, describe, expect, it, vi } from "vitest";
import { CheckpointStoreLive } from "../../checkpointing/Layers/CheckpointStore.ts";
import { CheckpointStore } from "../../checkpointing/Services/CheckpointStore.ts";
import { GitCoreLive } from "../../git/Layers/GitCore.ts";
import { GitStatusBroadcaster } from "../../git/Services/GitStatusBroadcaster.ts";
import * as VcsDriverRegistry from "../../vcs/VcsDriverRegistry.ts";
import * as VcsProcess from "../../vcs/VcsProcess.ts";
import { VcsStatusBroadcaster } from "../../vcs/VcsStatusBroadcaster.ts";
import { RepositoryIdentityResolverLive } from "../../project/Layers/RepositoryIdentityResolver.ts";
import { CheckpointReactorLive } from "./CheckpointReactor.ts";
import { OrchestrationEngineLive } from "./OrchestrationEngine.ts";
@@ -50,7 +56,7 @@ const asTurnId = (value: string): TurnId => TurnId.make(value);
type LegacyProviderRuntimeEvent = {
readonly type: string;
readonly eventId: EventId;
readonly provider: ProviderKind;
readonly provider: ProviderDriverKind;
readonly createdAt: string;
readonly threadId: ThreadId;
readonly turnId?: string | undefined;
@@ -64,7 +70,7 @@ function createProviderServiceHarness(
cwd: string,
hasSession = true,
sessionCwd = cwd,
providerName: ProviderSession["provider"] = "codex",
providerName: ProviderSession["provider"] = ProviderDriverKind.make("codex"),
) {
const now = new Date().toISOString();
const runtimeEventPubSub = Effect.runSync(PubSub.unbounded<ProviderRuntimeEvent>());
@@ -97,6 +103,17 @@ function createProviderServiceHarness(
stopSession: () => unsupported(),
listSessions,
getCapabilities: () => Effect.succeed({ sessionModelSwitch: "in-session" }),
getInstanceInfo: (instanceId) =>
Effect.succeed({
instanceId,
driverKind: ProviderDriverKind.make(providerName),
displayName: undefined,
enabled: true,
continuationIdentity: {
driverKind: ProviderDriverKind.make(providerName),
continuationKey: `${providerName}:instance:${instanceId}`,
},
}),
rollbackConversation,
get streamEvents() {
return Stream.fromPubSub(runtimeEventPubSub);
@@ -243,7 +260,7 @@ describe("CheckpointReactor", () => {
readonly projectWorkspaceRoot?: string;
readonly threadWorktreePath?: string | null;
readonly providerSessionCwd?: string;
readonly providerName?: ProviderKind;
readonly providerName?: ProviderDriverKind;
readonly gitStatusRefreshCalls?: Array<string>;
}) {
const cwd = createGitRepository();
@@ -252,7 +269,7 @@ describe("CheckpointReactor", () => {
cwd,
options?.hasSession ?? true,
options?.providerSessionCwd ?? cwd,
options?.providerName ?? "codex",
options?.providerName ?? ProviderDriverKind.make("codex"),
);
const orchestrationLayer = OrchestrationEngineLive.pipe(
Layer.provide(OrchestrationProjectionSnapshotQueryLive),
@@ -266,7 +283,7 @@ describe("CheckpointReactor", () => {
const ServerConfigLayer = ServerConfig.layerTest(process.cwd(), {
prefix: "t3-checkpoint-reactor-test-",
});
const gitStatusBroadcasterLayer = Layer.succeed(GitStatusBroadcaster, {
const vcsStatusBroadcasterLayer = Layer.succeed(VcsStatusBroadcaster, {
getStatus: () => Effect.die("getStatus should not be called in this test"),
refreshLocalStatus: (cwd: string) =>
Effect.sync(() => {
@@ -274,9 +291,10 @@ describe("CheckpointReactor", () => {
}).pipe(
Effect.as({
isRepo: true,
hasOriginRemote: false,
isDefaultBranch: true,
branch: "main",
kind: "git",
hasPrimaryRemote: false,
isDefaultRef: true,
refName: "main",
hasWorkingTreeChanges: false,
workingTree: { files: [], insertions: 0, deletions: 0 },
}),
@@ -289,11 +307,16 @@ describe("CheckpointReactor", () => {
Layer.provideMerge(orchestrationLayer),
Layer.provideMerge(RuntimeReceiptBusLive),
Layer.provideMerge(Layer.succeed(ProviderService, provider.service)),
Layer.provideMerge(gitStatusBroadcasterLayer),
Layer.provideMerge(CheckpointStoreLive),
Layer.provideMerge(WorkspaceEntriesLive.pipe(Layer.provide(WorkspacePathsLive))),
Layer.provideMerge(vcsStatusBroadcasterLayer),
Layer.provideMerge(CheckpointStoreLive.pipe(Layer.provide(VcsDriverRegistry.layer))),
Layer.provideMerge(
WorkspaceEntriesLive.pipe(
Layer.provide(WorkspacePathsLive),
Layer.provideMerge(VcsDriverRegistry.layer),
),
),
Layer.provideMerge(WorkspacePathsLive),
Layer.provideMerge(GitCoreLive),
Layer.provideMerge(VcsProcess.layer),
Layer.provideMerge(ServerConfigLayer),
Layer.provideMerge(NodeServices.layer),
);
@@ -315,7 +338,7 @@ describe("CheckpointReactor", () => {
title: "Test Project",
workspaceRoot: options?.projectWorkspaceRoot ?? cwd,
defaultModelSelection: {
provider: "codex",
instanceId: ProviderInstanceId.make("codex"),
model: "gpt-5-codex",
},
createdAt,
@@ -329,7 +352,7 @@ describe("CheckpointReactor", () => {
projectId: asProjectId("project-1"),
title: "Thread",
modelSelection: {
provider: "codex",
instanceId: ProviderInstanceId.make("codex"),
model: "gpt-5-codex",
},
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
@@ -396,7 +419,7 @@ describe("CheckpointReactor", () => {
harness.provider.emit({
type: "turn.started",
eventId: EventId.make("evt-turn-started-1"),
provider: "codex",
provider: ProviderDriverKind.make("codex"),
createdAt: new Date().toISOString(),
threadId: ThreadId.make("thread-1"),
@@ -411,7 +434,7 @@ describe("CheckpointReactor", () => {
harness.provider.emit({
type: "turn.completed",
eventId: EventId.make("evt-turn-completed-1"),
provider: "codex",
provider: ProviderDriverKind.make("codex"),
createdAt: new Date().toISOString(),
threadId: ThreadId.make("thread-1"),
@@ -457,7 +480,7 @@ describe("CheckpointReactor", () => {
harness.provider.emit({
type: "turn.completed",
eventId: EventId.make("evt-turn-completed-refresh-local-status"),
provider: "codex",
provider: ProviderDriverKind.make("codex"),
createdAt: new Date().toISOString(),
threadId: ThreadId.make("thread-1"),
turnId: asTurnId("turn-refresh-local-status"),
@@ -494,7 +517,7 @@ describe("CheckpointReactor", () => {
harness.provider.emit({
type: "turn.started",
eventId: EventId.make("evt-turn-started-main"),
provider: "codex",
provider: ProviderDriverKind.make("codex"),
createdAt: new Date().toISOString(),
threadId: ThreadId.make("thread-1"),
@@ -510,7 +533,7 @@ describe("CheckpointReactor", () => {
harness.provider.emit({
type: "turn.completed",
eventId: EventId.make("evt-turn-completed-aux"),
provider: "codex",
provider: ProviderDriverKind.make("codex"),
createdAt: new Date().toISOString(),
threadId: ThreadId.make("thread-1"),
@@ -526,7 +549,7 @@ describe("CheckpointReactor", () => {
harness.provider.emit({
type: "turn.completed",
eventId: EventId.make("evt-turn-completed-main"),
provider: "codex",
provider: ProviderDriverKind.make("codex"),
createdAt: new Date().toISOString(),
threadId: ThreadId.make("thread-1"),
@@ -544,7 +567,7 @@ describe("CheckpointReactor", () => {
it("captures pre-turn and completion checkpoints for claude runtime events", async () => {
const harness = await createHarness({
seedFilesystemCheckpoints: false,
providerName: "claudeAgent",
providerName: ProviderDriverKind.make("claudeAgent"),
});
const createdAt = new Date().toISOString();
@@ -569,7 +592,7 @@ describe("CheckpointReactor", () => {
harness.provider.emit({
type: "turn.started",
eventId: EventId.make("evt-turn-started-claude-1"),
provider: "claudeAgent",
provider: ProviderDriverKind.make("claudeAgent"),
createdAt: new Date().toISOString(),
threadId: ThreadId.make("thread-1"),
turnId: asTurnId("turn-claude-1"),
@@ -583,7 +606,7 @@ describe("CheckpointReactor", () => {
harness.provider.emit({
type: "turn.completed",
eventId: EventId.make("evt-turn-completed-claude-1"),
provider: "claudeAgent",
provider: ProviderDriverKind.make("claudeAgent"),
createdAt: new Date().toISOString(),
threadId: ThreadId.make("thread-1"),
turnId: asTurnId("turn-claude-1"),
@@ -627,7 +650,7 @@ describe("CheckpointReactor", () => {
harness.provider.emit({
type: "turn.completed",
eventId: EventId.make("evt-turn-completed-missing-baseline"),
provider: "codex",
provider: ProviderDriverKind.make("codex"),
createdAt: new Date().toISOString(),
threadId: ThreadId.make("thread-1"),
@@ -716,7 +739,7 @@ describe("CheckpointReactor", () => {
harness.provider.emit({
type: "turn.completed",
eventId: EventId.make("evt-turn-completed-missing-provider-cwd"),
provider: "codex",
provider: ProviderDriverKind.make("codex"),
createdAt: new Date().toISOString(),
threadId: ThreadId.make("thread-1"),
@@ -762,7 +785,7 @@ describe("CheckpointReactor", () => {
harness.provider.emit({
type: "checkpoint.captured",
eventId: EventId.make("evt-checkpoint-captured-3"),
provider: "codex",
provider: ProviderDriverKind.make("codex"),
createdAt: new Date().toISOString(),
threadId: ThreadId.make("thread-1"),
@@ -812,7 +835,7 @@ describe("CheckpointReactor", () => {
harness.provider.emit({
type: "turn.completed",
eventId: EventId.make("evt-runtime-capture-failure"),
provider: "codex",
provider: ProviderDriverKind.make("codex"),
createdAt: new Date().toISOString(),
threadId: ThreadId.make("thread-1"),
@@ -823,7 +846,7 @@ describe("CheckpointReactor", () => {
harness.provider.emit({
type: "turn.started",
eventId: EventId.make("evt-turn-started-after-runtime-failure"),
provider: "codex",
provider: ProviderDriverKind.make("codex"),
createdAt: new Date().toISOString(),
threadId: ThreadId.make("thread-1"),
@@ -918,7 +941,7 @@ describe("CheckpointReactor", () => {
});
it("executes provider revert and emits thread.reverted for claude sessions", async () => {
const harness = await createHarness({ providerName: "claudeAgent" });
const harness = await createHarness({ providerName: ProviderDriverKind.make("claudeAgent") });
const createdAt = new Date().toISOString();
await Effect.runPromise(
@@ -24,7 +24,7 @@ import { RuntimeReceiptBus } from "../Services/RuntimeReceiptBus.ts";
import type { CheckpointStoreError } from "../../checkpointing/Errors.ts";
import type { OrchestrationDispatchError } from "../Errors.ts";
import { isGitRepository } from "../../git/Utils.ts";
import { GitStatusBroadcaster } from "../../git/Services/GitStatusBroadcaster.ts";
import { VcsStatusBroadcaster } from "../../vcs/VcsStatusBroadcaster.ts";
import { WorkspaceEntries } from "../../workspace/Services/WorkspaceEntries.ts";
type ReactorInput =
@@ -70,7 +70,7 @@ const make = Effect.gen(function* () {
const checkpointStore = yield* CheckpointStore;
const receiptBus = yield* RuntimeReceiptBus;
const workspaceEntries = yield* WorkspaceEntries;
const gitStatusBroadcaster = yield* GitStatusBroadcaster;
const vcsStatusBroadcaster = yield* VcsStatusBroadcaster;
const appendRevertFailureActivity = (input: {
readonly threadId: ThreadId;
@@ -508,7 +508,7 @@ const make = Effect.gen(function* () {
return;
}
yield* gitStatusBroadcaster.refreshLocalStatus(sessionRuntime.value.cwd).pipe(
yield* vcsStatusBroadcaster.refreshLocalStatus(sessionRuntime.value.cwd).pipe(
Effect.catch((error) =>
Effect.logWarning("failed to refresh local git status after turn completion", {
threadId: event.threadId,
@@ -7,6 +7,7 @@ import {
ThreadId,
TurnId,
type OrchestrationEvent,
ProviderInstanceId,
} from "@t3tools/contracts";
import { Effect, Layer, ManagedRuntime, Metric, Option, Queue, Stream } from "effect";
import { describe, expect, it } from "vitest";
@@ -104,7 +105,7 @@ describe("OrchestrationEngine", () => {
title: "Bootstrap Project",
workspaceRoot: "/tmp/project-bootstrap",
defaultModelSelection: {
provider: "codex" as const,
instanceId: ProviderInstanceId.make("codex"),
model: "gpt-5-codex",
},
scripts: [],
@@ -119,7 +120,7 @@ describe("OrchestrationEngine", () => {
projectId: asProjectId("project-bootstrap"),
title: "Bootstrap Thread",
modelSelection: {
provider: "codex" as const,
instanceId: ProviderInstanceId.make("codex"),
model: "gpt-5-codex",
},
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
@@ -198,7 +199,7 @@ describe("OrchestrationEngine", () => {
title: "Project 1",
workspaceRoot: "/tmp/project-1",
defaultModelSelection: {
provider: "codex",
instanceId: ProviderInstanceId.make("codex"),
model: "gpt-5-codex",
},
createdAt,
@@ -212,7 +213,7 @@ describe("OrchestrationEngine", () => {
projectId: asProjectId("project-1"),
title: "Thread",
modelSelection: {
provider: "codex",
instanceId: ProviderInstanceId.make("codex"),
model: "gpt-5-codex",
},
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
@@ -258,7 +259,7 @@ describe("OrchestrationEngine", () => {
title: "Project Archive",
workspaceRoot: "/tmp/project-archive",
defaultModelSelection: {
provider: "codex",
instanceId: ProviderInstanceId.make("codex"),
model: "gpt-5-codex",
},
createdAt,
@@ -272,7 +273,7 @@ describe("OrchestrationEngine", () => {
projectId: asProjectId("project-archive"),
title: "Archive me",
modelSelection: {
provider: "codex",
instanceId: ProviderInstanceId.make("codex"),
model: "gpt-5-codex",
},
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
@@ -325,7 +326,7 @@ describe("OrchestrationEngine", () => {
title: "Replay Project",
workspaceRoot: "/tmp/project-replay",
defaultModelSelection: {
provider: "codex",
instanceId: ProviderInstanceId.make("codex"),
model: "gpt-5-codex",
},
createdAt,
@@ -339,7 +340,7 @@ describe("OrchestrationEngine", () => {
projectId: asProjectId("project-replay"),
title: "replay",
modelSelection: {
provider: "codex",
instanceId: ProviderInstanceId.make("codex"),
model: "gpt-5-codex",
},
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
@@ -383,7 +384,7 @@ describe("OrchestrationEngine", () => {
title: "Stream Project",
workspaceRoot: "/tmp/project-stream",
defaultModelSelection: {
provider: "codex",
instanceId: ProviderInstanceId.make("codex"),
model: "gpt-5-codex",
},
createdAt,
@@ -407,7 +408,7 @@ describe("OrchestrationEngine", () => {
projectId: asProjectId("project-stream"),
title: "domain-stream",
modelSelection: {
provider: "codex",
instanceId: ProviderInstanceId.make("codex"),
model: "gpt-5-codex",
},
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
@@ -444,7 +445,7 @@ describe("OrchestrationEngine", () => {
title: "Ack Project",
workspaceRoot: "/tmp/project-ack",
defaultModelSelection: {
provider: "codex",
instanceId: ProviderInstanceId.make("codex"),
model: "gpt-5-codex",
},
createdAt,
@@ -459,7 +460,7 @@ describe("OrchestrationEngine", () => {
projectId: asProjectId("project-ack"),
title: "Ack Thread",
modelSelection: {
provider: "codex",
instanceId: ProviderInstanceId.make("codex"),
model: "gpt-5-codex",
},
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
@@ -496,7 +497,7 @@ describe("OrchestrationEngine", () => {
projectId: asProjectId("project-missing"),
title: "Missing Project Thread",
modelSelection: {
provider: "codex",
instanceId: ProviderInstanceId.make("codex"),
model: "gpt-5-codex",
},
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
@@ -533,7 +534,7 @@ describe("OrchestrationEngine", () => {
title: "Turn Diff Project",
workspaceRoot: "/tmp/project-turn-diff",
defaultModelSelection: {
provider: "codex",
instanceId: ProviderInstanceId.make("codex"),
model: "gpt-5-codex",
},
createdAt,
@@ -547,7 +548,7 @@ describe("OrchestrationEngine", () => {
projectId: asProjectId("project-turn-diff"),
title: "Turn diff thread",
modelSelection: {
provider: "codex",
instanceId: ProviderInstanceId.make("codex"),
model: "gpt-5-codex",
},
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
@@ -652,7 +653,7 @@ describe("OrchestrationEngine", () => {
title: "Flaky Project",
workspaceRoot: "/tmp/project-flaky",
defaultModelSelection: {
provider: "codex",
instanceId: ProviderInstanceId.make("codex"),
model: "gpt-5-codex",
},
createdAt,
@@ -668,7 +669,7 @@ describe("OrchestrationEngine", () => {
projectId: asProjectId("project-flaky"),
title: "flaky-fail",
modelSelection: {
provider: "codex",
instanceId: ProviderInstanceId.make("codex"),
model: "gpt-5-codex",
},
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
@@ -688,7 +689,7 @@ describe("OrchestrationEngine", () => {
projectId: asProjectId("project-flaky"),
title: "flaky-ok",
modelSelection: {
provider: "codex",
instanceId: ProviderInstanceId.make("codex"),
model: "gpt-5-codex",
},
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
@@ -747,7 +748,7 @@ describe("OrchestrationEngine", () => {
title: "Atomic Project",
workspaceRoot: "/tmp/project-atomic",
defaultModelSelection: {
provider: "codex",
instanceId: ProviderInstanceId.make("codex"),
model: "gpt-5-codex",
},
createdAt,
@@ -761,7 +762,7 @@ describe("OrchestrationEngine", () => {
projectId: asProjectId("project-atomic"),
title: "atomic",
modelSelection: {
provider: "codex",
instanceId: ProviderInstanceId.make("codex"),
model: "gpt-5-codex",
},
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
@@ -890,7 +891,7 @@ describe("OrchestrationEngine", () => {
title: "Sync Project",
workspaceRoot: "/tmp/project-sync",
defaultModelSelection: {
provider: "codex",
instanceId: ProviderInstanceId.make("codex"),
model: "gpt-5-codex",
},
createdAt,
@@ -904,7 +905,7 @@ describe("OrchestrationEngine", () => {
projectId: asProjectId("project-sync"),
title: "sync-before",
modelSelection: {
provider: "codex",
instanceId: ProviderInstanceId.make("codex"),
model: "gpt-5-codex",
},
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
@@ -975,7 +976,7 @@ describe("OrchestrationEngine", () => {
title: "Duplicate Project",
workspaceRoot: "/tmp/project-duplicate",
defaultModelSelection: {
provider: "codex",
instanceId: ProviderInstanceId.make("codex"),
model: "gpt-5-codex",
},
createdAt,
@@ -990,7 +991,7 @@ describe("OrchestrationEngine", () => {
projectId: asProjectId("project-duplicate"),
title: "duplicate",
modelSelection: {
provider: "codex",
instanceId: ProviderInstanceId.make("codex"),
model: "gpt-5-codex",
},
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
@@ -1010,7 +1011,7 @@ describe("OrchestrationEngine", () => {
projectId: asProjectId("project-duplicate"),
title: "duplicate",
modelSelection: {
provider: "codex",
instanceId: ProviderInstanceId.make("codex"),
model: "gpt-5-codex",
},
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
@@ -7,6 +7,7 @@ import {
ProjectId,
ThreadId,
TurnId,
ProviderInstanceId,
} from "@t3tools/contracts";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { assert, it } from "@effect/vitest";
@@ -92,7 +93,7 @@ it.layer(BaseTestLayer)("OrchestrationProjectionPipeline", (it) => {
projectId: ProjectId.make("project-1"),
title: "Thread 1",
modelSelection: {
provider: "codex",
instanceId: ProviderInstanceId.make("codex"),
model: "gpt-5-codex",
},
runtimeMode: "full-access",
@@ -364,7 +365,7 @@ it.layer(BaseTestLayer)("OrchestrationProjectionPipeline", (it) => {
projectId: ProjectId.make("project-clear-attachments"),
title: "Thread Clear Attachments",
modelSelection: {
provider: "codex",
instanceId: ProviderInstanceId.make("codex"),
model: "gpt-5-codex",
},
runtimeMode: "full-access",
@@ -492,7 +493,7 @@ it.layer(
projectId: ProjectId.make("project-overwrite"),
title: "Thread Overwrite",
modelSelection: {
provider: "codex",
instanceId: ProviderInstanceId.make("codex"),
model: "gpt-5-codex",
},
runtimeMode: "full-access",
@@ -640,7 +641,7 @@ it.layer(
projectId: ProjectId.make("project-rollback"),
title: "Thread Rollback",
modelSelection: {
provider: "codex",
instanceId: ProviderInstanceId.make("codex"),
model: "gpt-5-codex",
},
runtimeMode: "full-access",
@@ -769,7 +770,7 @@ it.layer(
projectId: ProjectId.make("project-revert-files"),
title: "Thread Revert Files",
modelSelection: {
provider: "codex",
instanceId: ProviderInstanceId.make("codex"),
model: "gpt-5-codex",
},
runtimeMode: "full-access",
@@ -977,7 +978,7 @@ it.layer(Layer.fresh(makeProjectionPipelinePrefixedTestLayer("t3-projection-atta
projectId: ProjectId.make("project-delete-files"),
title: "Thread Delete Files",
modelSelection: {
provider: "codex",
instanceId: ProviderInstanceId.make("codex"),
model: "gpt-5-codex",
},
runtimeMode: "full-access",
@@ -1140,7 +1141,7 @@ it.layer(BaseTestLayer)("OrchestrationProjectionPipeline", (it) => {
projectId: ProjectId.make("project-a"),
title: "Thread A",
modelSelection: {
provider: "codex",
instanceId: ProviderInstanceId.make("codex"),
model: "gpt-5-codex",
},
runtimeMode: "full-access",
@@ -1267,7 +1268,7 @@ it.layer(BaseTestLayer)("OrchestrationProjectionPipeline", (it) => {
projectId: ProjectId.make("project-empty"),
title: "Thread Empty",
modelSelection: {
provider: "codex",
instanceId: ProviderInstanceId.make("codex"),
model: "gpt-5-codex",
},
runtimeMode: "full-access",
@@ -1407,7 +1408,7 @@ it.layer(BaseTestLayer)("OrchestrationProjectionPipeline", (it) => {
projectId: ProjectId.make("project-conflict"),
title: "Thread Conflict",
modelSelection: {
provider: "codex",
instanceId: ProviderInstanceId.make("codex"),
model: "gpt-5-codex",
},
runtimeMode: "full-access",
@@ -1551,7 +1552,7 @@ it.layer(BaseTestLayer)("OrchestrationProjectionPipeline", (it) => {
projectId: ProjectId.make("project-stale-approval"),
title: "Thread Stale Approval",
modelSelection: {
provider: "codex",
instanceId: ProviderInstanceId.make("codex"),
model: "gpt-5-codex",
},
runtimeMode: "approval-required",
@@ -1694,7 +1695,7 @@ it.layer(BaseTestLayer)("OrchestrationProjectionPipeline", (it) => {
projectId: ProjectId.make("project-nonstale-approval"),
title: "Thread Non-Stale Approval",
modelSelection: {
provider: "codex",
instanceId: ProviderInstanceId.make("codex"),
model: "gpt-5-codex",
},
runtimeMode: "approval-required",
@@ -1874,7 +1875,7 @@ it.layer(BaseTestLayer)("OrchestrationProjectionPipeline", (it) => {
projectId: ProjectId.make("project-revert"),
title: "Thread Revert",
modelSelection: {
provider: "codex",
instanceId: ProviderInstanceId.make("codex"),
model: "gpt-5-codex",
},
runtimeMode: "full-access",
@@ -2195,7 +2196,7 @@ engineLayer("OrchestrationProjectionPipeline via engine dispatch", (it) => {
title: "Live Project",
workspaceRoot: "/tmp/project-live",
defaultModelSelection: {
provider: "codex",
instanceId: ProviderInstanceId.make("codex"),
model: "gpt-5-codex",
},
createdAt,
@@ -2233,7 +2234,7 @@ engineLayer("OrchestrationProjectionPipeline via engine dispatch", (it) => {
title: "Scripts Project",
workspaceRoot: "/tmp/project-scripts",
defaultModelSelection: {
provider: "codex",
instanceId: ProviderInstanceId.make("codex"),
model: "gpt-5-codex",
},
createdAt,
@@ -2253,7 +2254,7 @@ engineLayer("OrchestrationProjectionPipeline via engine dispatch", (it) => {
},
],
defaultModelSelection: {
provider: "codex",
instanceId: ProviderInstanceId.make("codex"),
model: "gpt-5",
},
});
@@ -2272,7 +2273,7 @@ engineLayer("OrchestrationProjectionPipeline via engine dispatch", (it) => {
{
scriptsJson:
'[{"id":"script-1","name":"Build","command":"bun run build","icon":"build","runOnWorktreeCreate":false}]',
defaultModelSelection: '{"provider":"codex","model":"gpt-5"}',
defaultModelSelection: '{"instanceId":"codex","model":"gpt-5"}',
},
]);
}),
@@ -945,6 +945,7 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
threadId: event.payload.threadId,
status: event.payload.session.status,
providerName: event.payload.session.providerName,
providerInstanceId: event.payload.session.providerInstanceId ?? null,
runtimeMode: event.payload.session.runtimeMode,
activeTurnId: event.payload.session.activeTurnId,
lastError: event.payload.session.lastError,
@@ -1,4 +1,12 @@
import { CheckpointRef, EventId, MessageId, ProjectId, ThreadId, TurnId } from "@t3tools/contracts";
import {
CheckpointRef,
EventId,
MessageId,
ProjectId,
ThreadId,
TurnId,
ProviderInstanceId,
} from "@t3tools/contracts";
import { assert, it } from "@effect/vitest";
import { Effect, Layer } from "effect";
import * as SqlClient from "effect/unstable/sql/SqlClient";
@@ -252,7 +260,7 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
workspaceRoot: "/tmp/project-1",
repositoryIdentity: null,
defaultModelSelection: {
provider: "codex",
instanceId: ProviderInstanceId.make("codex"),
model: "gpt-5-codex",
},
scripts: [
@@ -275,7 +283,7 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
projectId: asProjectId("project-1"),
title: "Thread 1",
modelSelection: {
provider: "codex",
instanceId: ProviderInstanceId.make("codex"),
model: "gpt-5-codex",
},
interactionMode: "default",
@@ -363,7 +371,7 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
workspaceRoot: "/tmp/project-1",
repositoryIdentity: null,
defaultModelSelection: {
provider: "codex",
instanceId: ProviderInstanceId.make("codex"),
model: "gpt-5-codex",
},
scripts: [
@@ -385,7 +393,7 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
projectId: asProjectId("project-1"),
title: "Thread 1",
modelSelection: {
provider: "codex",
instanceId: ProviderInstanceId.make("codex"),
model: "gpt-5-codex",
},
interactionMode: "default",
@@ -195,6 +195,7 @@ function mapSessionRow(
threadId: row.threadId,
status: row.status,
providerName: row.providerName,
...(row.providerInstanceId !== null ? { providerInstanceId: row.providerInstanceId } : {}),
runtimeMode: row.runtimeMode,
activeTurnId: row.activeTurnId,
lastError: row.lastError,
@@ -350,6 +351,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
thread_id AS "threadId",
status,
provider_name AS "providerName",
provider_instance_id AS "providerInstanceId",
provider_session_id AS "providerSessionId",
provider_thread_id AS "providerThreadId",
runtime_mode AS "runtimeMode",
@@ -608,6 +610,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
thread_id AS "threadId",
status,
provider_name AS "providerName",
provider_instance_id AS "providerInstanceId",
runtime_mode AS "runtimeMode",
active_turn_id AS "activeTurnId",
last_error AS "lastError",
@@ -879,6 +882,9 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
threadId: row.threadId,
status: row.status,
providerName: row.providerName,
...(row.providerInstanceId !== null
? { providerInstanceId: row.providerInstanceId }
: {}),
runtimeMode: row.runtimeMode,
activeTurnId: row.activeTurnId,
lastError: row.lastError,
@@ -2,7 +2,13 @@ import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import type { ModelSelection, ProviderRuntimeEvent, ProviderSession } from "@t3tools/contracts";
import {
ModelSelection,
ProviderRuntimeEvent,
ProviderSession,
ProviderDriverKind,
ProviderInstanceId,
} from "@t3tools/contracts";
import { createModelSelection } from "@t3tools/shared/model";
import {
ApprovalRequestId,
@@ -27,21 +33,22 @@ import {
ProviderService,
type ProviderServiceShape,
} from "../../provider/Services/ProviderService.ts";
import { GitCore, type GitCoreShape } from "../../git/Services/GitCore.ts";
import {
GitStatusBroadcaster,
type GitStatusBroadcasterShape,
} from "../../git/Services/GitStatusBroadcaster.ts";
import { TextGeneration, type TextGenerationShape } from "../../git/Services/TextGeneration.ts";
import { TextGeneration, type TextGenerationShape } from "../../textGeneration/TextGeneration.ts";
import { RepositoryIdentityResolverLive } from "../../project/Layers/RepositoryIdentityResolver.ts";
import { OrchestrationEngineLive } from "./OrchestrationEngine.ts";
import { OrchestrationProjectionPipelineLive } from "./ProjectionPipeline.ts";
import { OrchestrationProjectionSnapshotQueryLive } from "./ProjectionSnapshotQuery.ts";
import { ProviderCommandReactorLive } from "./ProviderCommandReactor.ts";
import {
providerErrorLabel,
providerErrorLabelFromInstanceHint,
ProviderCommandReactorLive,
} from "./ProviderCommandReactor.ts";
import { OrchestrationEngineService } from "../Services/OrchestrationEngine.ts";
import { ProviderCommandReactor } from "../Services/ProviderCommandReactor.ts";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { ServerSettingsService } from "../../serverSettings.ts";
import { VcsStatusBroadcaster } from "../../vcs/VcsStatusBroadcaster.ts";
import { GitWorkflowService, type GitWorkflowServiceShape } from "../../git/GitWorkflowService.ts";
const asProjectId = (value: string): ProjectId => ProjectId.make(value);
const asApprovalRequestId = (value: string): ApprovalRequestId => ApprovalRequestId.make(value);
@@ -98,6 +105,30 @@ describe("ProviderCommandReactor", () => {
createdBaseDirs.clear();
});
describe("provider error attribution", () => {
it("uses the current provider instance slug when current instance lookup fails", () => {
expect(
providerErrorLabelFromInstanceHint({
instanceId: "codex_personal",
modelSelectionInstanceId: "codex",
sessionProvider: "codex",
}),
).toBe("codex_personal");
});
it("uses the desired provider instance slug when desired instance lookup fails", () => {
expect(
providerErrorLabelFromInstanceHint({
instanceId: "claude_openrouter",
}),
).toBe("claude_openrouter");
});
it("uses the unknown driver kind when the resolved driver is not registered locally", () => {
expect(providerErrorLabel("third_party_driver")).toBe("third_party_driver");
});
});
async function createHarness(input?: {
readonly baseDir?: string;
readonly threadModelSelection?: ModelSelection;
@@ -112,7 +143,7 @@ describe("ProviderCommandReactor", () => {
let nextSessionIndex = 1;
const runtimeSessions: Array<ProviderSession> = [];
const modelSelection = input?.threadModelSelection ?? {
provider: "codex",
instanceId: ProviderInstanceId.make("codex"),
model: "gpt-5-codex",
};
const startSession = vi.fn((_: unknown, input: unknown) => {
@@ -128,8 +159,24 @@ describe("ProviderCommandReactor", () => {
typeof input.threadId === "string"
? ThreadId.make(input.threadId)
: ThreadId.make(`thread-${sessionIndex}`);
const inputModelSelection =
typeof input === "object" && input !== null && "modelSelection" in input
? (input.modelSelection as ModelSelection | undefined)
: undefined;
const providerInstanceId =
typeof input === "object" && input !== null && "providerInstanceId" in input
? (input.providerInstanceId as ProviderInstanceId | undefined)
: inputModelSelection?.instanceId;
const provider =
typeof input === "object" &&
input !== null &&
"provider" in input &&
typeof input.provider === "string"
? (input.provider as ProviderSession["provider"])
: ProviderDriverKind.make(inputModelSelection?.instanceId ?? modelSelection.instanceId);
const session: ProviderSession = {
provider: modelSelection.provider,
provider,
...(providerInstanceId ? { providerInstanceId } : {}),
status: "ready" as const,
runtimeMode:
typeof input === "object" &&
@@ -138,7 +185,15 @@ describe("ProviderCommandReactor", () => {
(input.runtimeMode === "approval-required" || input.runtimeMode === "full-access")
? input.runtimeMode
: "full-access",
...(modelSelection.model !== undefined ? { model: modelSelection.model } : {}),
...(typeof input === "object" &&
input !== null &&
"cwd" in input &&
typeof input.cwd === "string"
? { cwd: input.cwd }
: {}),
...((inputModelSelection?.model ?? modelSelection.model)
? { model: inputModelSelection?.model ?? modelSelection.model }
: {}),
threadId,
resumeCursor: resumeCursor ?? { opaque: `resume-${sessionIndex}` },
createdAt: now,
@@ -185,9 +240,10 @@ describe("ProviderCommandReactor", () => {
const refreshStatus = vi.fn((_: string) =>
Effect.succeed({
isRepo: true,
hasOriginRemote: true,
isDefaultBranch: false,
branch: "renamed-branch",
kind: "git" as const,
hasPrimaryRemote: true,
isDefaultRef: false,
refName: "renamed-branch",
hasWorkingTreeChanges: false,
workingTree: {
files: [],
@@ -230,6 +286,25 @@ describe("ProviderCommandReactor", () => {
Effect.succeed({
sessionModelSwitch: input?.sessionModelSwitch ?? "in-session",
}),
getInstanceInfo: (instanceId) => {
const raw = String(instanceId);
const driverKind = ProviderDriverKind.make(
raw.startsWith("claude") ? "claudeAgent" : raw.startsWith("codex") ? "codex" : raw,
);
return Effect.succeed({
instanceId,
driverKind,
displayName: undefined,
enabled: true,
continuationIdentity: {
driverKind,
continuationKey:
driverKind === ProviderDriverKind.make("codex")
? "codex:home:/shared-codex"
: `${driverKind}:instance:${instanceId}`,
},
});
},
rollbackConversation: () => unsupported(),
get streamEvents() {
return Stream.fromPubSub(runtimeEventPubSub);
@@ -247,15 +322,19 @@ describe("ProviderCommandReactor", () => {
const layer = ProviderCommandReactorLive.pipe(
Layer.provideMerge(orchestrationLayer),
Layer.provideMerge(Layer.succeed(ProviderService, service)),
Layer.provideMerge(Layer.succeed(GitCore, { renameBranch } as unknown as GitCoreShape)),
Layer.provideMerge(
Layer.succeed(GitStatusBroadcaster, {
Layer.mock(GitWorkflowService)({
renameBranch,
} satisfies Partial<GitWorkflowServiceShape>),
),
Layer.provideMerge(
Layer.succeed(VcsStatusBroadcaster, {
getStatus: () => Effect.die("getStatus should not be called in this test"),
refreshLocalStatus: () =>
Effect.die("refreshLocalStatus should not be called in this test"),
refreshStatus,
streamStatus: () => Stream.die("streamStatus should not be called in this test"),
} satisfies GitStatusBroadcasterShape),
}),
),
Layer.provideMerge(
Layer.mock(TextGeneration, {
@@ -314,6 +393,7 @@ describe("ProviderCommandReactor", () => {
refreshStatus,
generateBranchName,
generateThreadTitle,
runtimeSessions,
stateDir,
drain,
};
@@ -346,7 +426,7 @@ describe("ProviderCommandReactor", () => {
expect(harness.startSession.mock.calls[0]?.[1]).toMatchObject({
cwd: "/tmp/provider-project",
modelSelection: {
provider: "codex",
instanceId: ProviderInstanceId.make("codex"),
model: "gpt-5-codex",
},
runtimeMode: "approval-required",
@@ -568,7 +648,7 @@ describe("ProviderCommandReactor", () => {
text: "hello fast mode",
attachments: [],
},
modelSelection: createModelSelection("codex", "gpt-5.3-codex", [
modelSelection: createModelSelection(ProviderInstanceId.make("codex"), "gpt-5.3-codex", [
{ id: "reasoningEffort", value: "high" },
{ id: "fastMode", value: true },
]),
@@ -581,14 +661,14 @@ describe("ProviderCommandReactor", () => {
await waitFor(() => harness.startSession.mock.calls.length === 1);
await waitFor(() => harness.sendTurn.mock.calls.length === 1);
expect(harness.startSession.mock.calls[0]?.[1]).toMatchObject({
modelSelection: createModelSelection("codex", "gpt-5.3-codex", [
modelSelection: createModelSelection(ProviderInstanceId.make("codex"), "gpt-5.3-codex", [
{ id: "reasoningEffort", value: "high" },
{ id: "fastMode", value: true },
]),
});
expect(harness.sendTurn.mock.calls[0]?.[0]).toMatchObject({
threadId: ThreadId.make("thread-1"),
modelSelection: createModelSelection("codex", "gpt-5.3-codex", [
modelSelection: createModelSelection(ProviderInstanceId.make("codex"), "gpt-5.3-codex", [
{ id: "reasoningEffort", value: "high" },
{ id: "fastMode", value: true },
]),
@@ -597,7 +677,10 @@ describe("ProviderCommandReactor", () => {
it("forwards claude effort options through session start and turn send", async () => {
const harness = await createHarness({
threadModelSelection: { provider: "claudeAgent", model: "claude-sonnet-4-6" },
threadModelSelection: {
instanceId: ProviderInstanceId.make("claudeAgent"),
model: "claude-sonnet-4-6",
},
});
const now = new Date().toISOString();
@@ -612,9 +695,11 @@ describe("ProviderCommandReactor", () => {
text: "hello with effort",
attachments: [],
},
modelSelection: createModelSelection("claudeAgent", "claude-sonnet-4-6", [
{ id: "effort", value: "max" },
]),
modelSelection: createModelSelection(
ProviderInstanceId.make("claudeAgent"),
"claude-sonnet-4-6",
[{ id: "effort", value: "max" }],
),
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "approval-required",
createdAt: now,
@@ -624,21 +709,28 @@ describe("ProviderCommandReactor", () => {
await waitFor(() => harness.startSession.mock.calls.length === 1);
await waitFor(() => harness.sendTurn.mock.calls.length === 1);
expect(harness.startSession.mock.calls[0]?.[1]).toMatchObject({
modelSelection: createModelSelection("claudeAgent", "claude-sonnet-4-6", [
{ id: "effort", value: "max" },
]),
modelSelection: createModelSelection(
ProviderInstanceId.make("claudeAgent"),
"claude-sonnet-4-6",
[{ id: "effort", value: "max" }],
),
});
expect(harness.sendTurn.mock.calls[0]?.[0]).toMatchObject({
threadId: ThreadId.make("thread-1"),
modelSelection: createModelSelection("claudeAgent", "claude-sonnet-4-6", [
{ id: "effort", value: "max" },
]),
modelSelection: createModelSelection(
ProviderInstanceId.make("claudeAgent"),
"claude-sonnet-4-6",
[{ id: "effort", value: "max" }],
),
});
});
it("forwards claude fast mode options through session start and turn send", async () => {
const harness = await createHarness({
threadModelSelection: { provider: "claudeAgent", model: "claude-opus-4-6" },
threadModelSelection: {
instanceId: ProviderInstanceId.make("claudeAgent"),
model: "claude-opus-4-6",
},
});
const now = new Date().toISOString();
@@ -653,9 +745,11 @@ describe("ProviderCommandReactor", () => {
text: "hello with fast mode",
attachments: [],
},
modelSelection: createModelSelection("claudeAgent", "claude-opus-4-6", [
{ id: "fastMode", value: true },
]),
modelSelection: createModelSelection(
ProviderInstanceId.make("claudeAgent"),
"claude-opus-4-6",
[{ id: "fastMode", value: true }],
),
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "approval-required",
createdAt: now,
@@ -665,15 +759,19 @@ describe("ProviderCommandReactor", () => {
await waitFor(() => harness.startSession.mock.calls.length === 1);
await waitFor(() => harness.sendTurn.mock.calls.length === 1);
expect(harness.startSession.mock.calls[0]?.[1]).toMatchObject({
modelSelection: createModelSelection("claudeAgent", "claude-opus-4-6", [
{ id: "fastMode", value: true },
]),
modelSelection: createModelSelection(
ProviderInstanceId.make("claudeAgent"),
"claude-opus-4-6",
[{ id: "fastMode", value: true }],
),
});
expect(harness.sendTurn.mock.calls[0]?.[0]).toMatchObject({
threadId: ThreadId.make("thread-1"),
modelSelection: createModelSelection("claudeAgent", "claude-opus-4-6", [
{ id: "fastMode", value: true },
]),
modelSelection: createModelSelection(
ProviderInstanceId.make("claudeAgent"),
"claude-opus-4-6",
[{ id: "fastMode", value: true }],
),
});
});
@@ -760,15 +858,15 @@ describe("ProviderCommandReactor", () => {
expect(harness.sendTurn.mock.calls[1]?.[0]).toMatchObject({
threadId: ThreadId.make("thread-1"),
modelSelection: {
provider: "codex",
instanceId: ProviderInstanceId.make("codex"),
model: "gpt-5-codex",
},
});
});
it("rejects a first turn when requested provider conflicts with the thread model", async () => {
it("starts a first turn on the requested provider instance even when it differs from the thread model", async () => {
const harness = await createHarness({
threadModelSelection: { provider: "codex", model: "gpt-5-codex" },
threadModelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5-codex" },
});
const now = new Date().toISOString();
@@ -784,7 +882,7 @@ describe("ProviderCommandReactor", () => {
attachments: [],
},
modelSelection: {
provider: "claudeAgent",
instanceId: ProviderInstanceId.make("claudeAgent"),
model: "claude-opus-4-6",
},
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
@@ -793,29 +891,25 @@ describe("ProviderCommandReactor", () => {
}),
);
await waitFor(async () => {
const readModel = await Effect.runPromise(harness.engine.getReadModel());
const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
return (
thread?.activities.some((activity) => activity.kind === "provider.turn.start.failed") ??
false
);
});
await waitFor(() => harness.sendTurn.mock.calls.length === 1);
expect(harness.startSession).not.toHaveBeenCalled();
expect(harness.sendTurn).not.toHaveBeenCalled();
expect(harness.startSession).toHaveBeenCalledTimes(1);
expect(harness.startSession.mock.calls[0]?.[1]).toMatchObject({
provider: ProviderDriverKind.make("claudeAgent"),
providerInstanceId: ProviderInstanceId.make("claudeAgent"),
modelSelection: {
instanceId: ProviderInstanceId.make("claudeAgent"),
model: "claude-opus-4-6",
},
});
const readModel = await Effect.runPromise(harness.engine.getReadModel());
const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
expect(thread?.session).toBeNull();
expect(thread?.session?.providerName).toBe("claudeAgent");
expect(thread?.session?.providerInstanceId).toBe(ProviderInstanceId.make("claudeAgent"));
expect(
thread?.activities.find((activity) => activity.kind === "provider.turn.start.failed"),
).toMatchObject({
summary: "Provider turn start failed",
payload: {
detail: expect.stringContaining("cannot switch to 'claudeAgent'"),
},
});
).toBeUndefined();
});
it("reuses the same provider session when runtime mode is unchanged", async () => {
@@ -864,9 +958,147 @@ describe("ProviderCommandReactor", () => {
expect(harness.stopSession.mock.calls.length).toBe(0);
});
it("restarts an existing Codex thread on a compatible requested instance", async () => {
const harness = await createHarness();
const now = new Date().toISOString();
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.turn.start",
commandId: CommandId.make("cmd-turn-start-compatible-codex-1"),
threadId: ThreadId.make("thread-1"),
message: {
messageId: asMessageId("user-message-compatible-codex-1"),
role: "user",
text: "first",
attachments: [],
},
modelSelection: {
instanceId: ProviderInstanceId.make("codex"),
model: "gpt-5-codex",
},
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "approval-required",
createdAt: now,
}),
);
await waitFor(() => harness.sendTurn.mock.calls.length === 1);
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.turn.start",
commandId: CommandId.make("cmd-turn-start-compatible-codex-2"),
threadId: ThreadId.make("thread-1"),
message: {
messageId: asMessageId("user-message-compatible-codex-2"),
role: "user",
text: "second",
attachments: [],
},
modelSelection: {
instanceId: ProviderInstanceId.make("codex_work"),
model: "gpt-5-codex",
},
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "approval-required",
createdAt: new Date().toISOString(),
}),
);
await waitFor(() => harness.sendTurn.mock.calls.length === 2);
expect(harness.startSession).toHaveBeenCalledTimes(2);
expect(harness.startSession.mock.calls[1]?.[1]).toMatchObject({
provider: ProviderDriverKind.make("codex"),
providerInstanceId: ProviderInstanceId.make("codex_work"),
resumeCursor: { opaque: "resume-1" },
});
const readModel = await Effect.runPromise(harness.engine.getReadModel());
const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
expect(thread?.session?.providerInstanceId).toBe(ProviderInstanceId.make("codex_work"));
});
it("restarts the provider session when the thread workspace changes", async () => {
const harness = await createHarness({
threadModelSelection: {
instanceId: ProviderInstanceId.make("claudeAgent"),
model: "claude-sonnet-4-6",
},
});
const now = new Date().toISOString();
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.turn.start",
commandId: CommandId.make("cmd-turn-start-workspace-1"),
threadId: ThreadId.make("thread-1"),
message: {
messageId: asMessageId("user-message-workspace-1"),
role: "user",
text: "first in project root",
attachments: [],
},
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "approval-required",
createdAt: now,
}),
);
await waitFor(() => harness.startSession.mock.calls.length === 1);
await waitFor(() => harness.sendTurn.mock.calls.length === 1);
expect(harness.startSession.mock.calls[0]?.[1]).toMatchObject({
cwd: "/tmp/provider-project",
});
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.meta.update",
commandId: CommandId.make("cmd-thread-worktree-change"),
threadId: ThreadId.make("thread-1"),
worktreePath: "/tmp/provider-project-worktree",
}),
);
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.turn.start",
commandId: CommandId.make("cmd-turn-start-workspace-2"),
threadId: ThreadId.make("thread-1"),
message: {
messageId: asMessageId("user-message-workspace-2"),
role: "user",
text: "second in worktree",
attachments: [],
},
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "approval-required",
createdAt: now,
}),
);
await waitFor(() => harness.startSession.mock.calls.length === 2);
await waitFor(() => harness.sendTurn.mock.calls.length === 2);
expect(harness.stopSession.mock.calls.length).toBe(0);
expect(harness.startSession.mock.calls[1]?.[1]).toMatchObject({
threadId: ThreadId.make("thread-1"),
cwd: "/tmp/provider-project-worktree",
resumeCursor: { opaque: "resume-1" },
modelSelection: {
instanceId: ProviderInstanceId.make("claudeAgent"),
model: "claude-sonnet-4-6",
},
runtimeMode: "approval-required",
});
});
it("restarts claude sessions when claude effort changes", async () => {
const harness = await createHarness({
threadModelSelection: { provider: "claudeAgent", model: "claude-sonnet-4-6" },
threadModelSelection: {
instanceId: ProviderInstanceId.make("claudeAgent"),
model: "claude-sonnet-4-6",
},
});
const now = new Date().toISOString();
@@ -881,9 +1113,11 @@ describe("ProviderCommandReactor", () => {
text: "first claude turn",
attachments: [],
},
modelSelection: createModelSelection("claudeAgent", "claude-sonnet-4-6", [
{ id: "effort", value: "medium" },
]),
modelSelection: createModelSelection(
ProviderInstanceId.make("claudeAgent"),
"claude-sonnet-4-6",
[{ id: "effort", value: "medium" }],
),
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "approval-required",
createdAt: now,
@@ -904,9 +1138,11 @@ describe("ProviderCommandReactor", () => {
text: "second claude turn",
attachments: [],
},
modelSelection: createModelSelection("claudeAgent", "claude-sonnet-4-6", [
{ id: "effort", value: "max" },
]),
modelSelection: createModelSelection(
ProviderInstanceId.make("claudeAgent"),
"claude-sonnet-4-6",
[{ id: "effort", value: "max" }],
),
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "approval-required",
createdAt: now,
@@ -917,9 +1153,11 @@ describe("ProviderCommandReactor", () => {
await waitFor(() => harness.sendTurn.mock.calls.length === 2);
expect(harness.startSession.mock.calls[1]?.[1]).toMatchObject({
resumeCursor: { opaque: "resume-1" },
modelSelection: createModelSelection("claudeAgent", "claude-sonnet-4-6", [
{ id: "effort", value: "max" },
]),
modelSelection: createModelSelection(
ProviderInstanceId.make("claudeAgent"),
"claude-sonnet-4-6",
[{ id: "effort", value: "max" }],
),
});
});
@@ -1010,7 +1248,10 @@ describe("ProviderCommandReactor", () => {
it("does not inject derived model options when restarting claude on runtime mode changes", async () => {
const harness = await createHarness({
threadModelSelection: { provider: "claudeAgent", model: "claude-opus-4-6" },
threadModelSelection: {
instanceId: ProviderInstanceId.make("claudeAgent"),
model: "claude-opus-4-6",
},
});
const now = new Date().toISOString();
@@ -1046,7 +1287,7 @@ describe("ProviderCommandReactor", () => {
expect(harness.startSession.mock.calls[0]?.[1]).toMatchObject({
modelSelection: {
provider: "claudeAgent",
instanceId: ProviderInstanceId.make("claudeAgent"),
model: "claude-opus-4-6",
},
runtimeMode: "approval-required",
@@ -1154,7 +1395,7 @@ describe("ProviderCommandReactor", () => {
attachments: [],
},
modelSelection: {
provider: "claudeAgent",
instanceId: ProviderInstanceId.make("claudeAgent"),
model: "claude-opus-4-6",
},
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
@@ -1190,6 +1431,72 @@ describe("ProviderCommandReactor", () => {
});
});
it("rejects cross-driver provider changes after the existing thread session has stopped", async () => {
const harness = await createHarness();
const now = new Date().toISOString();
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.session.set",
commandId: CommandId.make("cmd-session-set-stopped-provider-switch"),
threadId: ThreadId.make("thread-1"),
session: {
threadId: ThreadId.make("thread-1"),
status: "stopped",
providerName: "codex",
providerInstanceId: ProviderInstanceId.make("codex"),
runtimeMode: "approval-required",
activeTurnId: null,
lastError: null,
updatedAt: now,
},
createdAt: now,
}),
);
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.turn.start",
commandId: CommandId.make("cmd-turn-start-stopped-provider-switch"),
threadId: ThreadId.make("thread-1"),
message: {
messageId: asMessageId("user-message-stopped-provider-switch"),
role: "user",
text: "continue with claude",
attachments: [],
},
modelSelection: {
instanceId: ProviderInstanceId.make("claudeAgent"),
model: "claude-opus-4-6",
},
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "approval-required",
createdAt: now,
}),
);
await waitFor(async () => {
const readModel = await Effect.runPromise(harness.engine.getReadModel());
const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
return (
thread?.activities.some((activity) => activity.kind === "provider.turn.start.failed") ??
false
);
});
expect(harness.startSession.mock.calls.length).toBe(0);
expect(harness.sendTurn.mock.calls.length).toBe(0);
const readModel = await Effect.runPromise(harness.engine.getReadModel());
const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
expect(
thread?.activities.find((activity) => activity.kind === "provider.turn.start.failed"),
).toMatchObject({
payload: {
detail: expect.stringContaining("cannot switch to 'claudeAgent'"),
},
});
});
it("reacts to thread.turn.interrupt-requested by calling provider interrupt", async () => {
const harness = await createHarness();
const now = new Date().toISOString();
@@ -1273,7 +1580,7 @@ describe("ProviderCommandReactor", () => {
expect(harness.startSession.mock.calls[0]?.[1]).toMatchObject({
threadId: ThreadId.make("thread-1"),
modelSelection: {
provider: "codex",
instanceId: ProviderInstanceId.make("codex"),
model: "gpt-5-codex",
},
runtimeMode: "approval-required",
@@ -1283,6 +1590,77 @@ describe("ProviderCommandReactor", () => {
});
});
it("rejects active runtime sessions that are missing provider instance ids", async () => {
const harness = await createHarness();
const now = new Date().toISOString();
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.session.set",
commandId: CommandId.make("cmd-session-set-missing-instance"),
threadId: ThreadId.make("thread-1"),
session: {
threadId: ThreadId.make("thread-1"),
status: "ready",
providerName: "codex",
runtimeMode: "approval-required",
activeTurnId: null,
lastError: null,
updatedAt: now,
},
createdAt: now,
}),
);
harness.runtimeSessions.push({
provider: ProviderDriverKind.make("codex"),
status: "ready",
runtimeMode: "approval-required",
threadId: ThreadId.make("thread-1"),
cwd: "/tmp/provider-project",
resumeCursor: { opaque: "resume-without-instance" },
createdAt: now,
updatedAt: now,
});
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.turn.start",
commandId: CommandId.make("cmd-turn-start-missing-instance"),
threadId: ThreadId.make("thread-1"),
message: {
messageId: asMessageId("user-message-missing-instance"),
role: "user",
text: "resume codex",
attachments: [],
},
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "approval-required",
createdAt: now,
}),
);
await waitFor(async () => {
const readModel = await Effect.runPromise(harness.engine.getReadModel());
const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
return (
thread?.activities.some((activity) => activity.kind === "provider.turn.start.failed") ??
false
);
});
expect(harness.startSession.mock.calls.length).toBe(0);
expect(harness.sendTurn.mock.calls.length).toBe(0);
const readModel = await Effect.runPromise(harness.engine.getReadModel());
const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
expect(
thread?.activities.find((activity) => activity.kind === "provider.turn.start.failed"),
).toMatchObject({
payload: {
detail: expect.stringContaining("without a provider instance id"),
},
});
});
it("reacts to thread.approval.respond by forwarding provider approval response", async () => {
const harness = await createHarness();
const now = new Date().toISOString();
@@ -1375,7 +1753,7 @@ describe("ProviderCommandReactor", () => {
harness.respondToRequest.mockImplementation(() =>
Effect.fail(
new ProviderAdapterRequestError({
provider: "codex",
provider: ProviderDriverKind.make("codex"),
method: "session/request_permission",
detail: "Unknown pending permission request: approval-request-1",
}),
@@ -1470,7 +1848,7 @@ describe("ProviderCommandReactor", () => {
harness.respondToUserInput.mockImplementation(() =>
Effect.fail(
new ProviderAdapterRequestError({
provider: "claudeAgent",
provider: ProviderDriverKind.make("claudeAgent"),
method: "item/tool/respondToUserInput",
detail: "Unknown pending user-input request: user-input-request-1",
}),
@@ -1586,6 +1964,7 @@ describe("ProviderCommandReactor", () => {
threadId: ThreadId.make("thread-1"),
status: "ready",
providerName: "codex",
providerInstanceId: ProviderInstanceId.make("codex_work"),
runtimeMode: "approval-required",
activeTurnId: null,
lastError: null,
@@ -1610,6 +1989,7 @@ describe("ProviderCommandReactor", () => {
expect(thread?.session).not.toBeNull();
expect(thread?.session?.status).toBe("stopped");
expect(thread?.session?.threadId).toBe("thread-1");
expect(thread?.session?.providerInstanceId).toBe(ProviderInstanceId.make("codex_work"));
expect(thread?.session?.activeTurnId).toBeNull();
});
});
@@ -4,7 +4,7 @@ import {
EventId,
type ModelSelection,
type OrchestrationEvent,
ProviderKind,
ProviderDriverKind,
type OrchestrationSession,
ThreadId,
type ProviderSession,
@@ -16,12 +16,10 @@ import { Cache, Cause, Duration, Effect, Equal, Layer, Option, Schema, Stream }
import { makeDrainableWorker } from "@t3tools/shared/DrainableWorker";
import { resolveThreadWorkspaceCwd } from "../../checkpointing/Utils.ts";
import { GitCore } from "../../git/Services/GitCore.ts";
import { GitStatusBroadcaster } from "../../git/Services/GitStatusBroadcaster.ts";
import { increment, orchestrationEventsProcessedTotal } from "../../observability/Metrics.ts";
import { ProviderAdapterRequestError } from "../../provider/Errors.ts";
import type { ProviderServiceError } from "../../provider/Errors.ts";
import { TextGeneration } from "../../git/Services/TextGeneration.ts";
import { TextGeneration } from "../../textGeneration/TextGeneration.ts";
import { ProviderService } from "../../provider/Services/ProviderService.ts";
import { OrchestrationEngineService } from "../Services/OrchestrationEngine.ts";
import {
@@ -29,6 +27,8 @@ import {
type ProviderCommandReactorShape,
} from "../Services/ProviderCommandReactor.ts";
import { ServerSettingsService } from "../../serverSettings.ts";
import { VcsStatusBroadcaster } from "../../vcs/VcsStatusBroadcaster.ts";
import { GitWorkflowService } from "../../git/GitWorkflowService.ts";
type ProviderIntentEvent = Extract<
OrchestrationEvent,
@@ -77,6 +77,21 @@ const HANDLED_TURN_START_KEY_TTL = Duration.minutes(30);
const DEFAULT_RUNTIME_MODE: RuntimeMode = "full-access";
const DEFAULT_THREAD_TITLE = "New thread";
export function providerErrorLabel(value: string | undefined): string {
const normalized = value?.trim();
return normalized && normalized.length > 0 ? normalized : "unknown";
}
export function providerErrorLabelFromInstanceHint(input: {
readonly instanceId?: string | undefined;
readonly modelSelectionInstanceId?: string | undefined;
readonly sessionProvider?: string | undefined;
}): string {
return providerErrorLabel(
input.instanceId ?? input.modelSelectionInstanceId ?? input.sessionProvider,
);
}
function canReplaceThreadTitle(currentTitle: string, titleSeed?: string): boolean {
const trimmedCurrentTitle = currentTitle.trim();
if (trimmedCurrentTitle === DEFAULT_THREAD_TITLE) {
@@ -153,8 +168,8 @@ function buildGeneratedWorktreeBranchName(raw: string): string {
const make = Effect.gen(function* () {
const orchestrationEngine = yield* OrchestrationEngineService;
const providerService = yield* ProviderService;
const git = yield* GitCore;
const gitStatusBroadcaster = yield* GitStatusBroadcaster;
const gitWorkflow = yield* GitWorkflowService;
const vcsStatusBroadcaster = yield* VcsStatusBroadcaster;
const textGeneration = yield* TextGeneration;
const serverSettingsService = yield* ServerSettingsService;
const handledTurnStartKeys = yield* Cache.make<string, true>({
@@ -271,42 +286,108 @@ const make = Effect.gen(function* () {
}
const desiredRuntimeMode = thread.runtimeMode;
const currentProvider: ProviderKind | undefined = Schema.is(ProviderKind)(
thread.session?.providerName,
)
? thread.session.providerName
: undefined;
const requestedModelSelection = options?.modelSelection;
const threadProvider: ProviderKind = currentProvider ?? thread.modelSelection.provider;
if (
requestedModelSelection !== undefined &&
requestedModelSelection.provider !== threadProvider
) {
return yield* new ProviderAdapterRequestError({
provider: threadProvider,
method: "thread.turn.start",
detail: `Thread '${threadId}' is bound to provider '${threadProvider}' and cannot switch to '${requestedModelSelection.provider}'.`,
});
}
const preferredProvider: ProviderKind = threadProvider;
const desiredModelSelection = requestedModelSelection ?? thread.modelSelection;
const effectiveCwd = resolveThreadWorkspaceCwd({
thread,
projects: readModel.projects,
});
const resolveActiveSession = (threadId: ThreadId) =>
providerService
.listSessions()
.pipe(Effect.map((sessions) => sessions.find((session) => session.threadId === threadId)));
const activeSession = yield* resolveActiveSession(threadId);
const activeThreadSession =
thread.session !== null && thread.session.status !== "stopped" && activeSession
? thread.session
: null;
if (
activeThreadSession !== null &&
activeSession !== undefined &&
(activeThreadSession.providerInstanceId === undefined ||
activeSession.providerInstanceId === undefined)
) {
return yield* new ProviderAdapterRequestError({
provider: providerErrorLabel(activeThreadSession.providerName ?? undefined),
method: "thread.turn.start",
detail: `Thread '${threadId}' has an active provider session without a provider instance id.`,
});
}
const currentInstanceId =
activeThreadSession !== null &&
activeSession !== undefined &&
activeSession.providerInstanceId !== undefined
? activeSession.providerInstanceId
: thread.modelSelection.instanceId;
const desiredModelSelection = requestedModelSelection ?? thread.modelSelection;
const desiredInstanceId = desiredModelSelection.instanceId;
const currentInfo = yield* providerService.getInstanceInfo(currentInstanceId).pipe(
Effect.mapError(
() =>
new ProviderAdapterRequestError({
provider: providerErrorLabelFromInstanceHint({
instanceId: String(currentInstanceId),
modelSelectionInstanceId: String(thread.modelSelection.instanceId),
sessionProvider: thread.session?.providerName ?? undefined,
}),
method: "thread.turn.start",
detail: `Thread '${threadId}' references unknown provider instance '${currentInstanceId}'. The instance is not configured in this build.`,
}),
),
);
const desiredInfo = yield* providerService.getInstanceInfo(desiredInstanceId).pipe(
Effect.mapError(
() =>
new ProviderAdapterRequestError({
provider: providerErrorLabelFromInstanceHint({
instanceId: String(desiredModelSelection.instanceId),
}),
method: "thread.turn.start",
detail: `Requested provider instance '${desiredInstanceId}' is not configured in this build.`,
}),
),
);
const desiredDriverKind = desiredInfo.driverKind;
if (!Schema.is(ProviderDriverKind)(desiredDriverKind)) {
return yield* new ProviderAdapterRequestError({
provider: providerErrorLabel(String(desiredDriverKind)),
method: "thread.turn.start",
detail: `Requested provider instance '${desiredInstanceId}' uses unknown provider driver '${desiredDriverKind}'. The driver is not installed in this build.`,
});
}
const preferredProvider: ProviderDriverKind = desiredDriverKind;
if (
thread.session !== null &&
requestedModelSelection !== undefined &&
requestedModelSelection.instanceId !== currentInstanceId
) {
if (currentInfo.driverKind !== desiredInfo.driverKind) {
return yield* new ProviderAdapterRequestError({
provider: preferredProvider,
method: "thread.turn.start",
detail: `Thread '${threadId}' is bound to driver '${currentInfo.driverKind}' and cannot switch to '${desiredInfo.driverKind}'.`,
});
}
if (
currentInfo.continuationIdentity.continuationKey !==
desiredInfo.continuationIdentity.continuationKey
) {
return yield* new ProviderAdapterRequestError({
provider: preferredProvider,
method: "thread.turn.start",
detail: `Thread '${threadId}' cannot switch from instance '${currentInstanceId}' to '${desiredInstanceId}' because their provider resume state is incompatible.`,
});
}
}
const effectiveCwd = resolveThreadWorkspaceCwd({
thread,
projects: readModel.projects,
});
const startProviderSession = (input?: {
readonly resumeCursor?: unknown;
readonly provider?: ProviderKind;
readonly provider?: ProviderDriverKind;
}) =>
providerService.startSession(threadId, {
threadId,
...(preferredProvider ? { provider: preferredProvider } : {}),
providerInstanceId: desiredInstanceId,
...(effectiveCwd ? { cwd: effectiveCwd } : {}),
modelSelection: desiredModelSelection,
...(input?.resumeCursor !== undefined ? { resumeCursor: input.resumeCursor } : {}),
@@ -314,42 +395,55 @@ const make = Effect.gen(function* () {
});
const bindSessionToThread = (session: ProviderSession) =>
setThreadSession({
threadId,
session: {
Effect.gen(function* () {
if (session.providerInstanceId === undefined) {
return yield* new ProviderAdapterRequestError({
provider: providerErrorLabel(session.provider),
method: "thread.turn.start",
detail: `Provider session '${session.threadId}' started without a provider instance id.`,
});
}
yield* setThreadSession({
threadId,
status: mapProviderSessionStatusToOrchestrationStatus(session.status),
providerName: session.provider,
runtimeMode: desiredRuntimeMode,
// Provider turn ids are not orchestration turn ids.
activeTurnId: null,
lastError: session.lastError ?? null,
updatedAt: session.updatedAt,
},
createdAt,
session: {
threadId,
status: mapProviderSessionStatusToOrchestrationStatus(session.status),
providerName: session.provider,
providerInstanceId: session.providerInstanceId,
runtimeMode: desiredRuntimeMode,
// Provider turn ids are not orchestration turn ids.
activeTurnId: null,
lastError: session.lastError ?? null,
updatedAt: session.updatedAt,
},
createdAt,
});
});
const activeSession = yield* resolveActiveSession(threadId);
const existingSessionThreadId =
thread.session && thread.session.status !== "stopped" && activeSession ? thread.id : null;
if (existingSessionThreadId) {
const runtimeModeChanged = thread.runtimeMode !== thread.session?.runtimeMode;
const sessionModelSwitch =
currentProvider === undefined
? "in-session"
: (yield* providerService.getCapabilities(currentProvider)).sessionModelSwitch;
const cwdChanged = effectiveCwd !== activeSession?.cwd;
const sessionModelSwitch = (yield* providerService.getCapabilities(desiredInstanceId))
.sessionModelSwitch;
const modelChanged =
requestedModelSelection !== undefined &&
requestedModelSelection.model !== activeSession?.model;
const instanceChanged =
requestedModelSelection !== undefined &&
activeSession?.providerInstanceId !== requestedModelSelection.instanceId;
const shouldRestartForModelChange = modelChanged && sessionModelSwitch === "unsupported";
const previousModelSelection = threadModelSelections.get(threadId);
const shouldRestartForModelSelectionChange =
currentProvider === "claudeAgent" &&
preferredProvider === "claudeAgent" &&
requestedModelSelection !== undefined &&
!Equal.equals(previousModelSelection, requestedModelSelection);
if (
!runtimeModeChanged &&
!cwdChanged &&
!instanceChanged &&
!shouldRestartForModelChange &&
!shouldRestartForModelSelectionChange
) {
@@ -362,12 +456,18 @@ const make = Effect.gen(function* () {
yield* Effect.logInfo("provider command reactor restarting provider session", {
threadId,
existingSessionThreadId,
currentProvider,
desiredProvider: desiredModelSelection.provider,
currentProvider: activeSession?.provider,
currentInstanceId,
desiredInstanceId,
desiredProvider: desiredModelSelection.instanceId,
currentRuntimeMode: thread.session?.runtimeMode,
desiredRuntimeMode: thread.runtimeMode,
runtimeModeChanged,
previousCwd: activeSession?.cwd,
desiredCwd: effectiveCwd,
cwdChanged,
modelChanged,
instanceChanged,
shouldRestartForModelChange,
shouldRestartForModelSelectionChange,
hasResumeCursor: resumeCursor !== undefined,
@@ -381,6 +481,7 @@ const make = Effect.gen(function* () {
restartedSessionThreadId: restartedSession.threadId,
provider: restartedSession.provider,
runtimeMode: restartedSession.runtimeMode,
cwd: restartedSession.cwd,
});
yield* bindSessionToThread(restartedSession);
return restartedSession.threadId;
@@ -423,7 +524,14 @@ const make = Effect.gen(function* () {
const sessionModelSwitch =
activeSession === undefined
? "in-session"
: (yield* providerService.getCapabilities(activeSession.provider)).sessionModelSwitch;
: activeSession.providerInstanceId === undefined
? yield* new ProviderAdapterRequestError({
provider: providerErrorLabel(activeSession.provider),
method: "thread.turn.start",
detail: `Active provider session '${activeSession.threadId}' is missing a provider instance id.`,
})
: (yield* providerService.getCapabilities(activeSession.providerInstanceId))
.sessionModelSwitch;
const requestedModelSelection =
input.modelSelection ?? threadModelSelections.get(input.threadId) ?? thread.modelSelection;
const modelForTurn =
@@ -479,7 +587,7 @@ const make = Effect.gen(function* () {
const targetBranch = buildGeneratedWorktreeBranchName(generated.branch);
if (targetBranch === oldBranch) return;
const renamed = yield* git.renameBranch({ cwd, oldBranch, newBranch: targetBranch });
const renamed = yield* gitWorkflow.renameBranch({ cwd, oldBranch, newBranch: targetBranch });
yield* orchestrationEngine.dispatch({
type: "thread.meta.update",
commandId: serverCommandId("worktree-branch-rename"),
@@ -487,7 +595,7 @@ const make = Effect.gen(function* () {
branch: renamed.branch,
worktreePath: cwd,
});
yield* gitStatusBroadcaster.refreshStatus(cwd).pipe(Effect.ignoreCause({ log: true }));
yield* vcsStatusBroadcaster.refreshStatus(cwd).pipe(Effect.ignoreCause({ log: true }));
}).pipe(
Effect.catchCause((cause) =>
Effect.logWarning("provider command reactor failed to generate or rename worktree branch", {
@@ -794,6 +902,9 @@ const make = Effect.gen(function* () {
threadId: thread.id,
status: "stopped",
providerName: thread.session?.providerName ?? null,
...(thread.session?.providerInstanceId !== undefined
? { providerInstanceId: thread.session.providerInstanceId }
: {}),
runtimeMode: thread.session?.runtimeMode ?? DEFAULT_RUNTIME_MODE,
activeTurnId: null,
lastError: thread.session?.lastError ?? null,
@@ -2,10 +2,12 @@ import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import type {
import {
OrchestrationReadModel,
ProviderDriverKind,
ProviderRuntimeEvent,
ProviderSession,
ProviderInstanceId,
} from "@t3tools/contracts";
import {
ApprovalRequestId,
@@ -98,6 +100,19 @@ function createProviderServiceHarness() {
stopSession: () => unsupported(),
listSessions: () => Effect.succeed([...runtimeSessions]),
getCapabilities: () => Effect.succeed({ sessionModelSwitch: "in-session" }),
getInstanceInfo: (instanceId) => {
const driverKind = ProviderDriverKind.make(String(instanceId));
return Effect.succeed({
instanceId,
driverKind,
displayName: undefined,
enabled: true,
continuationIdentity: {
driverKind,
continuationKey: `${driverKind}:instance:${instanceId}`,
},
});
},
rollbackConversation: () => unsupported(),
get streamEvents() {
return Stream.fromPubSub(runtimeEventPubSub);
@@ -232,7 +247,7 @@ describe("ProviderRuntimeIngestion", () => {
title: "Provider Project",
workspaceRoot,
defaultModelSelection: {
provider: "codex",
instanceId: ProviderInstanceId.make("codex"),
model: "gpt-5-codex",
},
createdAt,
@@ -246,7 +261,7 @@ describe("ProviderRuntimeIngestion", () => {
projectId: asProjectId("project-1"),
title: "Thread",
modelSelection: {
provider: "codex",
instanceId: ProviderInstanceId.make("codex"),
model: "gpt-5-codex",
},
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
@@ -274,7 +289,7 @@ describe("ProviderRuntimeIngestion", () => {
}),
);
provider.setSession({
provider: "codex",
provider: ProviderDriverKind.make("codex"),
status: "ready",
runtimeMode: "approval-required",
threadId: ThreadId.make("thread-1"),
@@ -297,7 +312,7 @@ describe("ProviderRuntimeIngestion", () => {
harness.emit({
type: "turn.started",
eventId: asEventId("evt-turn-started"),
provider: "codex",
provider: ProviderDriverKind.make("codex"),
threadId: asThreadId("thread-1"),
createdAt: now,
turnId: asTurnId("turn-1"),
@@ -311,7 +326,7 @@ describe("ProviderRuntimeIngestion", () => {
harness.emit({
type: "turn.completed",
eventId: asEventId("evt-turn-completed"),
provider: "codex",
provider: ProviderDriverKind.make("codex"),
threadId: asThreadId("thread-1"),
createdAt: new Date().toISOString(),
turnId: asTurnId("turn-1"),
@@ -339,7 +354,7 @@ describe("ProviderRuntimeIngestion", () => {
harness.emit({
type: "session.state.changed",
eventId: asEventId("evt-session-state-waiting"),
provider: "codex",
provider: ProviderDriverKind.make("codex"),
threadId: asThreadId("thread-1"),
createdAt: waitingAt,
payload: {
@@ -358,7 +373,7 @@ describe("ProviderRuntimeIngestion", () => {
harness.emit({
type: "session.state.changed",
eventId: asEventId("evt-session-state-error"),
provider: "codex",
provider: ProviderDriverKind.make("codex"),
threadId: asThreadId("thread-1"),
createdAt: new Date().toISOString(),
payload: {
@@ -380,7 +395,7 @@ describe("ProviderRuntimeIngestion", () => {
harness.emit({
type: "session.state.changed",
eventId: asEventId("evt-session-state-stopped"),
provider: "codex",
provider: ProviderDriverKind.make("codex"),
threadId: asThreadId("thread-1"),
createdAt: new Date().toISOString(),
payload: {
@@ -401,7 +416,7 @@ describe("ProviderRuntimeIngestion", () => {
harness.emit({
type: "session.state.changed",
eventId: asEventId("evt-session-state-ready"),
provider: "codex",
provider: ProviderDriverKind.make("codex"),
threadId: asThreadId("thread-1"),
createdAt: new Date().toISOString(),
payload: {
@@ -427,7 +442,7 @@ describe("ProviderRuntimeIngestion", () => {
harness.emit({
type: "turn.started",
eventId: asEventId("evt-turn-started-midturn-lifecycle"),
provider: "codex",
provider: ProviderDriverKind.make("codex"),
createdAt: now,
threadId: asThreadId("thread-1"),
turnId: asTurnId("turn-midturn-lifecycle"),
@@ -443,14 +458,14 @@ describe("ProviderRuntimeIngestion", () => {
harness.emit({
type: "thread.started",
eventId: asEventId("evt-thread-started-midturn-lifecycle"),
provider: "codex",
provider: ProviderDriverKind.make("codex"),
createdAt: new Date().toISOString(),
threadId: asThreadId("thread-1"),
});
harness.emit({
type: "session.started",
eventId: asEventId("evt-session-started-midturn-lifecycle"),
provider: "codex",
provider: ProviderDriverKind.make("codex"),
createdAt: new Date().toISOString(),
threadId: asThreadId("thread-1"),
});
@@ -464,7 +479,7 @@ describe("ProviderRuntimeIngestion", () => {
harness.emit({
type: "turn.completed",
eventId: asEventId("evt-turn-completed-midturn-lifecycle"),
provider: "codex",
provider: ProviderDriverKind.make("codex"),
createdAt: new Date().toISOString(),
threadId: asThreadId("thread-1"),
turnId: asTurnId("turn-midturn-lifecycle"),
@@ -502,7 +517,7 @@ describe("ProviderRuntimeIngestion", () => {
harness.emit({
type: "turn.started",
eventId: asEventId("evt-turn-started-claude-placeholder"),
provider: "claudeAgent",
provider: ProviderDriverKind.make("claudeAgent"),
createdAt: new Date().toISOString(),
threadId: asThreadId("thread-1"),
turnId: asTurnId("turn-claude-placeholder"),
@@ -518,7 +533,7 @@ describe("ProviderRuntimeIngestion", () => {
harness.emit({
type: "turn.completed",
eventId: asEventId("evt-turn-completed-claude-placeholder"),
provider: "claudeAgent",
provider: ProviderDriverKind.make("claudeAgent"),
createdAt: new Date().toISOString(),
threadId: asThreadId("thread-1"),
turnId: asTurnId("turn-claude-placeholder"),
@@ -538,7 +553,7 @@ describe("ProviderRuntimeIngestion", () => {
harness.emit({
type: "turn.started",
eventId: asEventId("evt-turn-started-primary"),
provider: "codex",
provider: ProviderDriverKind.make("codex"),
createdAt: now,
threadId: asThreadId("thread-1"),
turnId: asTurnId("turn-primary"),
@@ -553,7 +568,7 @@ describe("ProviderRuntimeIngestion", () => {
harness.emit({
type: "turn.completed",
eventId: asEventId("evt-turn-completed-aux"),
provider: "codex",
provider: ProviderDriverKind.make("codex"),
createdAt: new Date().toISOString(),
threadId: asThreadId("thread-1"),
turnId: asTurnId("turn-aux"),
@@ -569,7 +584,7 @@ describe("ProviderRuntimeIngestion", () => {
harness.emit({
type: "turn.completed",
eventId: asEventId("evt-turn-completed-primary"),
provider: "codex",
provider: ProviderDriverKind.make("codex"),
createdAt: new Date().toISOString(),
threadId: asThreadId("thread-1"),
turnId: asTurnId("turn-primary"),
@@ -589,7 +604,7 @@ describe("ProviderRuntimeIngestion", () => {
harness.emit({
type: "turn.started",
eventId: asEventId("evt-turn-started-guarded"),
provider: "codex",
provider: ProviderDriverKind.make("codex"),
createdAt: now,
threadId: asThreadId("thread-1"),
turnId: asTurnId("turn-guarded-main"),
@@ -605,7 +620,7 @@ describe("ProviderRuntimeIngestion", () => {
harness.emit({
type: "turn.completed",
eventId: asEventId("evt-turn-completed-guarded-other"),
provider: "codex",
provider: ProviderDriverKind.make("codex"),
createdAt: new Date().toISOString(),
threadId: asThreadId("thread-1"),
turnId: asTurnId("turn-guarded-other"),
@@ -621,7 +636,7 @@ describe("ProviderRuntimeIngestion", () => {
harness.emit({
type: "turn.completed",
eventId: asEventId("evt-turn-completed-guarded-main"),
provider: "codex",
provider: ProviderDriverKind.make("codex"),
createdAt: new Date().toISOString(),
threadId: asThreadId("thread-1"),
turnId: asTurnId("turn-guarded-main"),
@@ -641,7 +656,7 @@ describe("ProviderRuntimeIngestion", () => {
harness.emit({
type: "content.delta",
eventId: asEventId("evt-message-delta-1"),
provider: "codex",
provider: ProviderDriverKind.make("codex"),
createdAt: now,
threadId: asThreadId("thread-1"),
turnId: asTurnId("turn-2"),
@@ -654,7 +669,7 @@ describe("ProviderRuntimeIngestion", () => {
harness.emit({
type: "content.delta",
eventId: asEventId("evt-message-delta-2"),
provider: "codex",
provider: ProviderDriverKind.make("codex"),
createdAt: now,
threadId: asThreadId("thread-1"),
turnId: asTurnId("turn-2"),
@@ -667,7 +682,7 @@ describe("ProviderRuntimeIngestion", () => {
harness.emit({
type: "item.completed",
eventId: asEventId("evt-message-completed"),
provider: "codex",
provider: ProviderDriverKind.make("codex"),
createdAt: now,
threadId: asThreadId("thread-1"),
turnId: asTurnId("turn-2"),
@@ -698,7 +713,7 @@ describe("ProviderRuntimeIngestion", () => {
harness.emit({
type: "item.completed",
eventId: asEventId("evt-assistant-item-completed-no-delta"),
provider: "codex",
provider: ProviderDriverKind.make("codex"),
createdAt: now,
threadId: asThreadId("thread-1"),
turnId: asTurnId("turn-no-delta"),
@@ -730,7 +745,7 @@ describe("ProviderRuntimeIngestion", () => {
harness.emit({
type: "item.completed",
eventId: asEventId("evt-tool-completed-with-data"),
provider: "cursor",
provider: ProviderDriverKind.make("cursor"),
createdAt: now,
threadId: asThreadId("thread-1"),
turnId: asTurnId("turn-tool-completed"),
@@ -786,7 +801,7 @@ describe("ProviderRuntimeIngestion", () => {
harness.emit({
type: "item.completed",
eventId: asEventId("evt-command-completed"),
provider: "cursor",
provider: ProviderDriverKind.make("cursor"),
createdAt: now,
threadId: asThreadId("thread-1"),
turnId: asTurnId("turn-command-completed"),
@@ -828,7 +843,7 @@ describe("ProviderRuntimeIngestion", () => {
harness.emit({
type: "item.completed",
eventId: asEventId("evt-read-path-completed"),
provider: "cursor",
provider: ProviderDriverKind.make("cursor"),
createdAt: now,
threadId: asThreadId("thread-1"),
turnId: asTurnId("turn-read-path"),
@@ -870,7 +885,7 @@ describe("ProviderRuntimeIngestion", () => {
harness.emit({
type: "turn.proposed.completed",
eventId: asEventId("evt-plan-item-completed"),
provider: "codex",
provider: ProviderDriverKind.make("codex"),
createdAt: now,
threadId: asThreadId("thread-1"),
turnId: asTurnId("turn-plan-final"),
@@ -909,7 +924,7 @@ describe("ProviderRuntimeIngestion", () => {
projectId: asProjectId("project-1"),
title: "Plan Source",
modelSelection: {
provider: "codex",
instanceId: ProviderInstanceId.make("codex"),
model: "gpt-5-codex",
},
interactionMode: "plan",
@@ -944,7 +959,7 @@ describe("ProviderRuntimeIngestion", () => {
projectId: asProjectId("project-1"),
title: "Plan Target",
modelSelection: {
provider: "codex",
instanceId: ProviderInstanceId.make("codex"),
model: "gpt-5-codex",
},
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
@@ -972,7 +987,7 @@ describe("ProviderRuntimeIngestion", () => {
}),
);
harness.setProviderSession({
provider: "codex",
provider: ProviderDriverKind.make("codex"),
status: "ready",
runtimeMode: "approval-required",
threadId: targetThreadId,
@@ -984,7 +999,7 @@ describe("ProviderRuntimeIngestion", () => {
harness.emit({
type: "turn.proposed.completed",
eventId: asEventId("evt-plan-source-completed"),
provider: "codex",
provider: ProviderDriverKind.make("codex"),
createdAt,
threadId: sourceThreadId,
turnId: sourceTurnId,
@@ -1054,7 +1069,7 @@ describe("ProviderRuntimeIngestion", () => {
harness.emit({
type: "turn.started",
eventId: asEventId("evt-plan-target-started"),
provider: "codex",
provider: ProviderDriverKind.make("codex"),
createdAt: new Date().toISOString(),
threadId: targetThreadId,
turnId: targetTurnId,
@@ -1096,7 +1111,7 @@ describe("ProviderRuntimeIngestion", () => {
projectId: asProjectId("project-1"),
title: "Plan Source",
modelSelection: {
provider: "codex",
instanceId: ProviderInstanceId.make("codex"),
model: "gpt-5-codex",
},
interactionMode: "plan",
@@ -1124,7 +1139,7 @@ describe("ProviderRuntimeIngestion", () => {
}),
);
harness.setProviderSession({
provider: "codex",
provider: ProviderDriverKind.make("codex"),
status: "running",
runtimeMode: "approval-required",
threadId: targetThreadId,
@@ -1136,7 +1151,7 @@ describe("ProviderRuntimeIngestion", () => {
harness.emit({
type: "turn.started",
eventId: asEventId("evt-turn-started-already-running"),
provider: "codex",
provider: ProviderDriverKind.make("codex"),
createdAt,
threadId: targetThreadId,
turnId: activeTurnId,
@@ -1153,7 +1168,7 @@ describe("ProviderRuntimeIngestion", () => {
harness.emit({
type: "turn.proposed.completed",
eventId: asEventId("evt-plan-source-completed-guarded"),
provider: "codex",
provider: ProviderDriverKind.make("codex"),
createdAt,
threadId: sourceThreadId,
turnId: sourceTurnId,
@@ -1206,7 +1221,7 @@ describe("ProviderRuntimeIngestion", () => {
harness.emit({
type: "turn.started",
eventId: asEventId("evt-turn-started-stale-plan-implementation"),
provider: "codex",
provider: ProviderDriverKind.make("codex"),
createdAt: new Date().toISOString(),
threadId: targetThreadId,
turnId: staleTurnId,
@@ -1249,7 +1264,7 @@ describe("ProviderRuntimeIngestion", () => {
projectId: asProjectId("project-1"),
title: "Plan Source",
modelSelection: {
provider: "codex",
instanceId: ProviderInstanceId.make("codex"),
model: "gpt-5-codex",
},
interactionMode: "plan",
@@ -1284,7 +1299,7 @@ describe("ProviderRuntimeIngestion", () => {
projectId: asProjectId("project-1"),
title: "Plan Target",
modelSelection: {
provider: "codex",
instanceId: ProviderInstanceId.make("codex"),
model: "gpt-5-codex",
},
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
@@ -1315,7 +1330,7 @@ describe("ProviderRuntimeIngestion", () => {
harness.emit({
type: "turn.proposed.completed",
eventId: asEventId("evt-plan-source-completed-unrelated"),
provider: "codex",
provider: ProviderDriverKind.make("codex"),
createdAt,
threadId: sourceThreadId,
turnId: sourceTurnId,
@@ -1366,7 +1381,7 @@ describe("ProviderRuntimeIngestion", () => {
);
harness.setProviderSession({
provider: "codex",
provider: ProviderDriverKind.make("codex"),
status: "running",
runtimeMode: "approval-required",
threadId: targetThreadId,
@@ -1378,7 +1393,7 @@ describe("ProviderRuntimeIngestion", () => {
harness.emit({
type: "turn.started",
eventId: asEventId("evt-turn-started-unrelated-plan-implementation"),
provider: "codex",
provider: ProviderDriverKind.make("codex"),
createdAt: new Date().toISOString(),
threadId: targetThreadId,
turnId: replayedTurnId,
@@ -1405,7 +1420,7 @@ describe("ProviderRuntimeIngestion", () => {
harness.emit({
type: "turn.started",
eventId: asEventId("evt-turn-started-plan-buffer"),
provider: "codex",
provider: ProviderDriverKind.make("codex"),
createdAt: now,
threadId: asThreadId("thread-1"),
turnId: asTurnId("turn-plan-buffer"),
@@ -1420,7 +1435,7 @@ describe("ProviderRuntimeIngestion", () => {
harness.emit({
type: "turn.proposed.delta",
eventId: asEventId("evt-plan-delta-1"),
provider: "codex",
provider: ProviderDriverKind.make("codex"),
createdAt: now,
threadId: asThreadId("thread-1"),
turnId: asTurnId("turn-plan-buffer"),
@@ -1431,7 +1446,7 @@ describe("ProviderRuntimeIngestion", () => {
harness.emit({
type: "turn.proposed.delta",
eventId: asEventId("evt-plan-delta-2"),
provider: "codex",
provider: ProviderDriverKind.make("codex"),
createdAt: now,
threadId: asThreadId("thread-1"),
turnId: asTurnId("turn-plan-buffer"),
@@ -1442,7 +1457,7 @@ describe("ProviderRuntimeIngestion", () => {
harness.emit({
type: "turn.completed",
eventId: asEventId("evt-turn-completed-plan-buffer"),
provider: "codex",
provider: ProviderDriverKind.make("codex"),
createdAt: now,
threadId: asThreadId("thread-1"),
turnId: asTurnId("turn-plan-buffer"),
@@ -1471,7 +1486,7 @@ describe("ProviderRuntimeIngestion", () => {
harness.emit({
type: "turn.started",
eventId: asEventId("evt-turn-started-buffered"),
provider: "codex",
provider: ProviderDriverKind.make("codex"),
createdAt: now,
threadId: asThreadId("thread-1"),
turnId: asTurnId("turn-buffered"),
@@ -1485,7 +1500,7 @@ describe("ProviderRuntimeIngestion", () => {
harness.emit({
type: "content.delta",
eventId: asEventId("evt-message-delta-buffered"),
provider: "codex",
provider: ProviderDriverKind.make("codex"),
createdAt: now,
threadId: asThreadId("thread-1"),
turnId: asTurnId("turn-buffered"),
@@ -1508,7 +1523,7 @@ describe("ProviderRuntimeIngestion", () => {
harness.emit({
type: "item.completed",
eventId: asEventId("evt-message-completed-buffered"),
provider: "codex",
provider: ProviderDriverKind.make("codex"),
createdAt: now,
threadId: asThreadId("thread-1"),
turnId: asTurnId("turn-buffered"),
@@ -1539,7 +1554,7 @@ describe("ProviderRuntimeIngestion", () => {
harness.emit({
type: "turn.started",
eventId: asEventId("evt-turn-started-buffered-request-flush"),
provider: "codex",
provider: ProviderDriverKind.make("codex"),
createdAt: now,
threadId: asThreadId("thread-1"),
turnId: asTurnId("turn-buffered-request-flush"),
@@ -1554,7 +1569,7 @@ describe("ProviderRuntimeIngestion", () => {
harness.emit({
type: "content.delta",
eventId: asEventId("evt-message-delta-buffered-request-flush"),
provider: "codex",
provider: ProviderDriverKind.make("codex"),
createdAt: now,
threadId: asThreadId("thread-1"),
turnId: asTurnId("turn-buffered-request-flush"),
@@ -1567,7 +1582,7 @@ describe("ProviderRuntimeIngestion", () => {
harness.emit({
type: "request.opened",
eventId: asEventId("evt-request-opened-buffered-request-flush"),
provider: "codex",
provider: ProviderDriverKind.make("codex"),
createdAt: now,
threadId: asThreadId("thread-1"),
turnId: asTurnId("turn-buffered-request-flush"),
@@ -1599,7 +1614,7 @@ describe("ProviderRuntimeIngestion", () => {
harness.emit({
type: "turn.started",
eventId: asEventId("evt-turn-started-buffered-user-input-flush"),
provider: "codex",
provider: ProviderDriverKind.make("codex"),
createdAt: now,
threadId: asThreadId("thread-1"),
turnId: asTurnId("turn-buffered-user-input-flush"),
@@ -1614,7 +1629,7 @@ describe("ProviderRuntimeIngestion", () => {
harness.emit({
type: "content.delta",
eventId: asEventId("evt-message-delta-buffered-user-input-flush"),
provider: "codex",
provider: ProviderDriverKind.make("codex"),
createdAt: now,
threadId: asThreadId("thread-1"),
turnId: asTurnId("turn-buffered-user-input-flush"),
@@ -1627,7 +1642,7 @@ describe("ProviderRuntimeIngestion", () => {
harness.emit({
type: "user-input.requested",
eventId: asEventId("evt-user-input-requested-buffered-user-input-flush"),
provider: "codex",
provider: ProviderDriverKind.make("codex"),
createdAt: now,
threadId: asThreadId("thread-1"),
turnId: asTurnId("turn-buffered-user-input-flush"),
@@ -1667,7 +1682,7 @@ describe("ProviderRuntimeIngestion", () => {
harness.emit({
type: "turn.started",
eventId: asEventId("evt-turn-started-buffered-whitespace-request"),
provider: "codex",
provider: ProviderDriverKind.make("codex"),
createdAt: startedAt,
threadId: asThreadId("thread-1"),
turnId: asTurnId("turn-buffered-whitespace-request"),
@@ -1682,7 +1697,7 @@ describe("ProviderRuntimeIngestion", () => {
harness.emit({
type: "content.delta",
eventId: asEventId("evt-message-delta-buffered-whitespace-request"),
provider: "codex",
provider: ProviderDriverKind.make("codex"),
createdAt: startedAt,
threadId: asThreadId("thread-1"),
turnId: asTurnId("turn-buffered-whitespace-request"),
@@ -1695,7 +1710,7 @@ describe("ProviderRuntimeIngestion", () => {
harness.emit({
type: "request.opened",
eventId: asEventId("evt-request-opened-buffered-whitespace-request"),
provider: "codex",
provider: ProviderDriverKind.make("codex"),
createdAt: pausedAt,
threadId: asThreadId("thread-1"),
turnId: asTurnId("turn-buffered-whitespace-request"),
@@ -1729,7 +1744,7 @@ describe("ProviderRuntimeIngestion", () => {
harness.emit({
type: "turn.started",
eventId: asEventId("evt-turn-started-buffered-request-append"),
provider: "codex",
provider: ProviderDriverKind.make("codex"),
createdAt: startedAt,
threadId: asThreadId("thread-1"),
turnId: asTurnId("turn-buffered-request-append"),
@@ -1744,7 +1759,7 @@ describe("ProviderRuntimeIngestion", () => {
harness.emit({
type: "content.delta",
eventId: asEventId("evt-message-delta-buffered-request-append-initial"),
provider: "codex",
provider: ProviderDriverKind.make("codex"),
createdAt: startedAt,
threadId: asThreadId("thread-1"),
turnId: asTurnId("turn-buffered-request-append"),
@@ -1757,7 +1772,7 @@ describe("ProviderRuntimeIngestion", () => {
harness.emit({
type: "request.opened",
eventId: asEventId("evt-request-opened-buffered-request-append"),
provider: "codex",
provider: ProviderDriverKind.make("codex"),
createdAt: pausedAt,
threadId: asThreadId("thread-1"),
turnId: asTurnId("turn-buffered-request-append"),
@@ -1780,7 +1795,7 @@ describe("ProviderRuntimeIngestion", () => {
harness.emit({
type: "content.delta",
eventId: asEventId("evt-message-delta-buffered-request-append-followup"),
provider: "codex",
provider: ProviderDriverKind.make("codex"),
createdAt: resumedAt,
threadId: asThreadId("thread-1"),
turnId: asTurnId("turn-buffered-request-append"),
@@ -1793,7 +1808,7 @@ describe("ProviderRuntimeIngestion", () => {
harness.emit({
type: "item.completed",
eventId: asEventId("evt-message-completed-buffered-request-append"),
provider: "codex",
provider: ProviderDriverKind.make("codex"),
createdAt: completedAt,
threadId: asThreadId("thread-1"),
turnId: asTurnId("turn-buffered-request-append"),
@@ -1861,7 +1876,7 @@ describe("ProviderRuntimeIngestion", () => {
harness.emit({
type: "turn.started",
eventId: asEventId("evt-turn-started-streaming-request-segment"),
provider: "codex",
provider: ProviderDriverKind.make("codex"),
createdAt: startedAt,
threadId: asThreadId("thread-1"),
turnId: asTurnId("turn-streaming-request-segment"),
@@ -1876,7 +1891,7 @@ describe("ProviderRuntimeIngestion", () => {
harness.emit({
type: "content.delta",
eventId: asEventId("evt-message-delta-streaming-request-segment-initial"),
provider: "codex",
provider: ProviderDriverKind.make("codex"),
createdAt: startedAt,
threadId: asThreadId("thread-1"),
turnId: asTurnId("turn-streaming-request-segment"),
@@ -1889,7 +1904,7 @@ describe("ProviderRuntimeIngestion", () => {
harness.emit({
type: "request.opened",
eventId: asEventId("evt-request-opened-streaming-request-segment"),
provider: "codex",
provider: ProviderDriverKind.make("codex"),
createdAt: pausedAt,
threadId: asThreadId("thread-1"),
turnId: asTurnId("turn-streaming-request-segment"),
@@ -1912,7 +1927,7 @@ describe("ProviderRuntimeIngestion", () => {
harness.emit({
type: "content.delta",
eventId: asEventId("evt-message-delta-streaming-request-segment-followup"),
provider: "codex",
provider: ProviderDriverKind.make("codex"),
createdAt: resumedAt,
threadId: asThreadId("thread-1"),
turnId: asTurnId("turn-streaming-request-segment"),
@@ -1925,7 +1940,7 @@ describe("ProviderRuntimeIngestion", () => {
harness.emit({
type: "item.completed",
eventId: asEventId("evt-message-completed-streaming-request-segment"),
provider: "codex",
provider: ProviderDriverKind.make("codex"),
createdAt: completedAt,
threadId: asThreadId("thread-1"),
turnId: asTurnId("turn-streaming-request-segment"),
@@ -1983,7 +1998,7 @@ describe("ProviderRuntimeIngestion", () => {
harness.emit({
type: "turn.started",
eventId: asEventId("evt-turn-started-streaming-mode"),
provider: "codex",
provider: ProviderDriverKind.make("codex"),
createdAt: now,
threadId: asThreadId("thread-1"),
turnId: asTurnId("turn-streaming-mode"),
@@ -1998,7 +2013,7 @@ describe("ProviderRuntimeIngestion", () => {
harness.emit({
type: "content.delta",
eventId: asEventId("evt-message-delta-streaming-mode"),
provider: "codex",
provider: ProviderDriverKind.make("codex"),
createdAt: now,
threadId: asThreadId("thread-1"),
turnId: asTurnId("turn-streaming-mode"),
@@ -2025,7 +2040,7 @@ describe("ProviderRuntimeIngestion", () => {
harness.emit({
type: "item.completed",
eventId: asEventId("evt-message-completed-streaming-mode"),
provider: "codex",
provider: ProviderDriverKind.make("codex"),
createdAt: now,
threadId: asThreadId("thread-1"),
turnId: asTurnId("turn-streaming-mode"),
@@ -2058,7 +2073,7 @@ describe("ProviderRuntimeIngestion", () => {
harness.emit({
type: "turn.started",
eventId: asEventId("evt-turn-started-buffer-spill"),
provider: "codex",
provider: ProviderDriverKind.make("codex"),
createdAt: now,
threadId: asThreadId("thread-1"),
turnId: asTurnId("turn-buffer-spill"),
@@ -2073,7 +2088,7 @@ describe("ProviderRuntimeIngestion", () => {
harness.emit({
type: "content.delta",
eventId: asEventId("evt-message-delta-buffer-spill"),
provider: "codex",
provider: ProviderDriverKind.make("codex"),
createdAt: now,
threadId: asThreadId("thread-1"),
turnId: asTurnId("turn-buffer-spill"),
@@ -2086,7 +2101,7 @@ describe("ProviderRuntimeIngestion", () => {
harness.emit({
type: "item.completed",
eventId: asEventId("evt-message-completed-buffer-spill"),
provider: "codex",
provider: ProviderDriverKind.make("codex"),
createdAt: now,
threadId: asThreadId("thread-1"),
turnId: asTurnId("turn-buffer-spill"),
@@ -2118,7 +2133,7 @@ describe("ProviderRuntimeIngestion", () => {
harness.emit({
type: "turn.started",
eventId: asEventId("evt-turn-started-for-complete-dedup"),
provider: "codex",
provider: ProviderDriverKind.make("codex"),
createdAt: now,
threadId: asThreadId("thread-1"),
turnId: asTurnId("turn-complete-dedup"),
@@ -2134,7 +2149,7 @@ describe("ProviderRuntimeIngestion", () => {
harness.emit({
type: "content.delta",
eventId: asEventId("evt-message-delta-for-complete-dedup"),
provider: "codex",
provider: ProviderDriverKind.make("codex"),
createdAt: now,
threadId: asThreadId("thread-1"),
turnId: asTurnId("turn-complete-dedup"),
@@ -2147,7 +2162,7 @@ describe("ProviderRuntimeIngestion", () => {
harness.emit({
type: "item.completed",
eventId: asEventId("evt-message-completed-for-complete-dedup"),
provider: "codex",
provider: ProviderDriverKind.make("codex"),
createdAt: now,
threadId: asThreadId("thread-1"),
turnId: asTurnId("turn-complete-dedup"),
@@ -2160,7 +2175,7 @@ describe("ProviderRuntimeIngestion", () => {
harness.emit({
type: "turn.completed",
eventId: asEventId("evt-turn-completed-for-complete-dedup"),
provider: "codex",
provider: ProviderDriverKind.make("codex"),
createdAt: now,
threadId: asThreadId("thread-1"),
turnId: asTurnId("turn-complete-dedup"),
@@ -2204,7 +2219,7 @@ describe("ProviderRuntimeIngestion", () => {
harness.emit({
type: "request.opened",
eventId: asEventId("evt-request-opened"),
provider: "codex",
provider: ProviderDriverKind.make("codex"),
createdAt: now,
threadId: asThreadId("thread-1"),
requestId: ApprovalRequestId.make("req-open"),
@@ -2217,7 +2232,7 @@ describe("ProviderRuntimeIngestion", () => {
harness.emit({
type: "request.resolved",
eventId: asEventId("evt-request-resolved"),
provider: "codex",
provider: ProviderDriverKind.make("codex"),
createdAt: now,
threadId: asThreadId("thread-1"),
requestId: ApprovalRequestId.make("req-open"),
@@ -2270,7 +2285,7 @@ describe("ProviderRuntimeIngestion", () => {
harness.emit({
type: "runtime.error",
eventId: asEventId("evt-runtime-error"),
provider: "codex",
provider: ProviderDriverKind.make("codex"),
createdAt: now,
threadId: asThreadId("thread-1"),
turnId: asTurnId("turn-3"),
@@ -2297,7 +2312,7 @@ describe("ProviderRuntimeIngestion", () => {
harness.emit({
type: "runtime.error",
eventId: asEventId("evt-runtime-error-activity"),
provider: "codex",
provider: ProviderDriverKind.make("codex"),
createdAt: now,
threadId: asThreadId("thread-1"),
turnId: asTurnId("turn-runtime-error-activity"),
@@ -2328,7 +2343,7 @@ describe("ProviderRuntimeIngestion", () => {
harness.emit({
type: "turn.started",
eventId: asEventId("evt-warning-turn-started"),
provider: "codex",
provider: ProviderDriverKind.make("codex"),
createdAt: now,
threadId: asThreadId("thread-1"),
turnId: asTurnId("turn-warning"),
@@ -2338,7 +2353,7 @@ describe("ProviderRuntimeIngestion", () => {
harness.emit({
type: "runtime.warning",
eventId: asEventId("evt-warning-runtime"),
provider: "codex",
provider: ProviderDriverKind.make("codex"),
createdAt: now,
threadId: asThreadId("thread-1"),
turnId: asTurnId("turn-warning"),
@@ -2372,7 +2387,7 @@ describe("ProviderRuntimeIngestion", () => {
harness.emit({
type: "session.started",
eventId: asEventId("evt-session-started"),
provider: "codex",
provider: ProviderDriverKind.make("codex"),
createdAt: now,
threadId: asThreadId("thread-1"),
message: "session started",
@@ -2380,14 +2395,14 @@ describe("ProviderRuntimeIngestion", () => {
harness.emit({
type: "thread.started",
eventId: asEventId("evt-thread-started"),
provider: "codex",
provider: ProviderDriverKind.make("codex"),
createdAt: now,
threadId: asThreadId("thread-1"),
});
harness.emit({
type: "item.started",
eventId: asEventId("evt-tool-started"),
provider: "codex",
provider: ProviderDriverKind.make("codex"),
createdAt: now,
threadId: asThreadId("thread-1"),
turnId: asTurnId("turn-9"),
@@ -2424,7 +2439,7 @@ describe("ProviderRuntimeIngestion", () => {
harness.emit({
type: "thread.metadata.updated",
eventId: asEventId("evt-thread-metadata-updated"),
provider: "codex",
provider: ProviderDriverKind.make("codex"),
createdAt: now,
threadId: asThreadId("thread-1"),
payload: {
@@ -2436,7 +2451,7 @@ describe("ProviderRuntimeIngestion", () => {
harness.emit({
type: "turn.plan.updated",
eventId: asEventId("evt-turn-plan-updated"),
provider: "codex",
provider: ProviderDriverKind.make("codex"),
createdAt: now,
threadId: asThreadId("thread-1"),
turnId: asTurnId("turn-p1"),
@@ -2452,7 +2467,7 @@ describe("ProviderRuntimeIngestion", () => {
harness.emit({
type: "item.updated",
eventId: asEventId("evt-item-updated"),
provider: "codex",
provider: ProviderDriverKind.make("codex"),
createdAt: now,
threadId: asThreadId("thread-1"),
turnId: asTurnId("turn-p1"),
@@ -2469,7 +2484,7 @@ describe("ProviderRuntimeIngestion", () => {
harness.emit({
type: "runtime.warning",
eventId: asEventId("evt-runtime-warning"),
provider: "codex",
provider: ProviderDriverKind.make("codex"),
createdAt: now,
threadId: asThreadId("thread-1"),
turnId: asTurnId("turn-p1"),
@@ -2482,7 +2497,7 @@ describe("ProviderRuntimeIngestion", () => {
harness.emit({
type: "turn.diff.updated",
eventId: asEventId("evt-turn-diff-updated"),
provider: "codex",
provider: ProviderDriverKind.make("codex"),
createdAt: now,
threadId: asThreadId("thread-1"),
turnId: asTurnId("turn-p1"),
@@ -2558,7 +2573,7 @@ describe("ProviderRuntimeIngestion", () => {
harness.emit({
type: "thread.token-usage.updated",
eventId: asEventId("evt-thread-token-usage-updated"),
provider: "codex",
provider: ProviderDriverKind.make("codex"),
createdAt: now,
threadId: asThreadId("thread-1"),
payload: {
@@ -2610,7 +2625,7 @@ describe("ProviderRuntimeIngestion", () => {
harness.emit({
type: "thread.token-usage.updated",
eventId: asEventId("evt-thread-token-usage-updated-camel"),
provider: "codex",
provider: ProviderDriverKind.make("codex"),
createdAt: now,
threadId: asThreadId("thread-1"),
payload: {
@@ -2663,7 +2678,7 @@ describe("ProviderRuntimeIngestion", () => {
harness.emit({
type: "thread.token-usage.updated",
eventId: asEventId("evt-thread-token-usage-updated-claude-window"),
provider: "claudeAgent",
provider: ProviderDriverKind.make("claudeAgent"),
createdAt: now,
threadId: asThreadId("thread-1"),
payload: {
@@ -2707,7 +2722,7 @@ describe("ProviderRuntimeIngestion", () => {
harness.emit({
type: "thread.state.changed",
eventId: asEventId("evt-thread-compacted"),
provider: "codex",
provider: ProviderDriverKind.make("codex"),
createdAt: now,
threadId: asThreadId("thread-1"),
turnId: asTurnId("turn-1"),
@@ -2737,7 +2752,7 @@ describe("ProviderRuntimeIngestion", () => {
harness.emit({
type: "task.started",
eventId: asEventId("evt-task-started"),
provider: "codex",
provider: ProviderDriverKind.make("codex"),
createdAt: now,
threadId: asThreadId("thread-1"),
turnId: asTurnId("turn-task-1"),
@@ -2750,7 +2765,7 @@ describe("ProviderRuntimeIngestion", () => {
harness.emit({
type: "task.progress",
eventId: asEventId("evt-task-progress"),
provider: "codex",
provider: ProviderDriverKind.make("codex"),
createdAt: now,
threadId: asThreadId("thread-1"),
turnId: asTurnId("turn-task-1"),
@@ -2764,7 +2779,7 @@ describe("ProviderRuntimeIngestion", () => {
harness.emit({
type: "task.completed",
eventId: asEventId("evt-task-completed"),
provider: "codex",
provider: ProviderDriverKind.make("codex"),
createdAt: now,
threadId: asThreadId("thread-1"),
turnId: asTurnId("turn-task-1"),
@@ -2777,7 +2792,7 @@ describe("ProviderRuntimeIngestion", () => {
harness.emit({
type: "turn.proposed.completed",
eventId: asEventId("evt-task-proposed-plan-completed"),
provider: "codex",
provider: ProviderDriverKind.make("codex"),
createdAt: now,
threadId: asThreadId("thread-1"),
turnId: asTurnId("turn-task-1"),
@@ -2840,7 +2855,7 @@ describe("ProviderRuntimeIngestion", () => {
harness.emit({
type: "user-input.requested",
eventId: asEventId("evt-user-input-requested"),
provider: "codex",
provider: ProviderDriverKind.make("codex"),
createdAt: now,
threadId: asThreadId("thread-1"),
turnId: asTurnId("turn-user-input"),
@@ -2865,7 +2880,7 @@ describe("ProviderRuntimeIngestion", () => {
harness.emit({
type: "user-input.resolved",
eventId: asEventId("evt-user-input-resolved"),
provider: "codex",
provider: ProviderDriverKind.make("codex"),
createdAt: new Date().toISOString(),
threadId: asThreadId("thread-1"),
turnId: asTurnId("turn-user-input"),
@@ -2913,7 +2928,7 @@ describe("ProviderRuntimeIngestion", () => {
harness.emit({
type: "content.delta",
eventId: asEventId("evt-invalid-delta"),
provider: "codex",
provider: ProviderDriverKind.make("codex"),
createdAt: now,
threadId: asThreadId("thread-1"),
turnId: asTurnId("turn-invalid"),
@@ -2927,7 +2942,7 @@ describe("ProviderRuntimeIngestion", () => {
harness.emit({
type: "runtime.error",
eventId: asEventId("evt-runtime-error-after-failure"),
provider: "codex",
provider: ProviderDriverKind.make("codex"),
createdAt: new Date().toISOString(),
threadId: asThreadId("thread-1"),
turnId: asTurnId("turn-after-failure"),
@@ -1211,6 +1211,9 @@ const make = Effect.gen(function* () {
threadId: thread.id,
status,
providerName: event.provider,
...(event.providerInstanceId !== undefined
? { providerInstanceId: event.providerInstanceId }
: {}),
runtimeMode: thread.session?.runtimeMode ?? "full-access",
activeTurnId: nextActiveTurnId,
lastError,
@@ -1456,6 +1459,9 @@ const make = Effect.gen(function* () {
threadId: thread.id,
status: "error",
providerName: event.provider,
...(event.providerInstanceId !== undefined
? { providerInstanceId: event.providerInstanceId }
: {}),
runtimeMode: thread.session?.runtimeMode ?? "full-access",
activeTurnId: eventTurnId ?? null,
lastError: runtimeErrorMessage,
@@ -7,6 +7,7 @@ import {
ThreadId,
type OrchestrationCommand,
type OrchestrationReadModel,
ProviderInstanceId,
} from "@t3tools/contracts";
import { Effect } from "effect";
@@ -29,7 +30,7 @@ const readModel: OrchestrationReadModel = {
title: "Project A",
workspaceRoot: "/tmp/project-a",
defaultModelSelection: {
provider: "codex",
instanceId: ProviderInstanceId.make("codex"),
model: "gpt-5-codex",
},
scripts: [],
@@ -42,7 +43,7 @@ const readModel: OrchestrationReadModel = {
title: "Project B",
workspaceRoot: "/tmp/project-b",
defaultModelSelection: {
provider: "codex",
instanceId: ProviderInstanceId.make("codex"),
model: "gpt-5-codex",
},
scripts: [],
@@ -57,7 +58,7 @@ const readModel: OrchestrationReadModel = {
projectId: ProjectId.make("project-a"),
title: "Thread A",
modelSelection: {
provider: "codex",
instanceId: ProviderInstanceId.make("codex"),
model: "gpt-5-codex",
},
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
@@ -80,7 +81,7 @@ const readModel: OrchestrationReadModel = {
projectId: ProjectId.make("project-b"),
title: "Thread B",
modelSelection: {
provider: "codex",
instanceId: ProviderInstanceId.make("codex"),
model: "gpt-5-codex",
},
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
@@ -157,7 +158,7 @@ describe("commandInvariants", () => {
projectId: ProjectId.make("project-a"),
title: "new",
modelSelection: {
provider: "codex",
instanceId: ProviderInstanceId.make("codex"),
model: "gpt-5-codex",
},
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
@@ -181,7 +182,7 @@ describe("commandInvariants", () => {
projectId: ProjectId.make("project-a"),
title: "dup",
modelSelection: {
provider: "codex",
instanceId: ProviderInstanceId.make("codex"),
model: "gpt-5-codex",
},
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
@@ -7,6 +7,7 @@ import {
type OrchestrationCommand,
type OrchestrationEvent,
type OrchestrationReadModel,
ProviderInstanceId,
} from "@t3tools/contracts";
import { Effect } from "effect";
import { describe, expect, it } from "vitest";
@@ -63,7 +64,7 @@ async function seedReadModel(): Promise<OrchestrationReadModel> {
projectId: asProjectId("project-delete"),
title: "Thread Delete 1",
modelSelection: {
provider: "codex",
instanceId: ProviderInstanceId.make("codex"),
model: "gpt-5-codex",
},
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
@@ -93,7 +94,7 @@ async function seedReadModel(): Promise<OrchestrationReadModel> {
projectId: asProjectId("project-delete"),
title: "Thread Delete 2",
modelSelection: {
provider: "codex",
instanceId: ProviderInstanceId.make("codex"),
model: "gpt-5-codex",
},
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
@@ -5,6 +5,7 @@ import {
MessageId,
ProjectId,
ThreadId,
ProviderInstanceId,
} from "@t3tools/contracts";
import { createModelSelection } from "@t3tools/shared/model";
import { describe, expect, it } from "vitest";
@@ -138,7 +139,7 @@ describe("decider project scripts", () => {
projectId: asProjectId("project-1"),
title: "Thread",
modelSelection: {
provider: "codex",
instanceId: ProviderInstanceId.make("codex"),
model: "gpt-5-codex",
},
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
@@ -163,7 +164,7 @@ describe("decider project scripts", () => {
text: "hello",
attachments: [],
},
modelSelection: createModelSelection("codex", "gpt-5.3-codex", [
modelSelection: createModelSelection(ProviderInstanceId.make("codex"), "gpt-5.3-codex", [
{ id: "reasoningEffort", value: "high" },
{ id: "fastMode", value: true },
]),
@@ -188,7 +189,7 @@ describe("decider project scripts", () => {
expect(turnStartEvent.payload).toMatchObject({
threadId: ThreadId.make("thread-1"),
messageId: asMessageId("message-user-1"),
modelSelection: createModelSelection("codex", "gpt-5.3-codex", [
modelSelection: createModelSelection(ProviderInstanceId.make("codex"), "gpt-5.3-codex", [
{ id: "reasoningEffort", value: "high" },
{ id: "fastMode", value: true },
]),
@@ -239,7 +240,7 @@ describe("decider project scripts", () => {
projectId: asProjectId("project-1"),
title: "Thread",
modelSelection: {
provider: "codex",
instanceId: ProviderInstanceId.make("codex"),
model: "gpt-5-codex",
},
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
@@ -321,7 +322,7 @@ describe("decider project scripts", () => {
projectId: asProjectId("project-1"),
title: "Thread",
modelSelection: {
provider: "codex",
instanceId: ProviderInstanceId.make("codex"),
model: "gpt-5-codex",
},
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
+11 -10
View File
@@ -2,6 +2,7 @@ import {
CommandId,
EventId,
ProjectId,
ProviderDriverKind,
ThreadId,
type OrchestrationEvent,
} from "@t3tools/contracts";
@@ -57,7 +58,7 @@ describe("orchestration projector", () => {
projectId: "project-1",
title: "demo",
modelSelection: {
provider: "codex",
provider: ProviderDriverKind.make("codex"),
model: "gpt-5-codex",
},
runtimeMode: "full-access",
@@ -77,7 +78,7 @@ describe("orchestration projector", () => {
projectId: "project-1",
title: "demo",
modelSelection: {
provider: "codex",
instanceId: "codex",
model: "gpt-5-codex",
},
runtimeMode: "full-access",
@@ -118,7 +119,7 @@ describe("orchestration projector", () => {
projectId: "project-1",
title: "demo",
modelSelection: {
provider: "codex",
provider: ProviderDriverKind.make("codex"),
model: "gpt-5-codex",
},
branch: null,
@@ -150,7 +151,7 @@ describe("orchestration projector", () => {
projectId: "project-1",
title: "demo",
modelSelection: {
provider: "codex",
provider: ProviderDriverKind.make("codex"),
model: "gpt-5-codex",
},
runtimeMode: "full-access",
@@ -253,7 +254,7 @@ describe("orchestration projector", () => {
projectId: "project-1",
title: "demo",
modelSelection: {
provider: "codex",
provider: ProviderDriverKind.make("codex"),
model: "gpt-5.3-codex",
},
runtimeMode: "full-access",
@@ -319,7 +320,7 @@ describe("orchestration projector", () => {
projectId: "project-1",
title: "demo",
modelSelection: {
provider: "codex",
provider: ProviderDriverKind.make("codex"),
model: "gpt-5.3-codex",
},
runtimeMode: "full-access",
@@ -376,7 +377,7 @@ describe("orchestration projector", () => {
projectId: "project-1",
title: "demo",
modelSelection: {
provider: "codex",
provider: ProviderDriverKind.make("codex"),
model: "gpt-5.3-codex",
},
runtimeMode: "full-access",
@@ -463,7 +464,7 @@ describe("orchestration projector", () => {
projectId: "project-1",
title: "demo",
modelSelection: {
provider: "codex",
provider: ProviderDriverKind.make("codex"),
model: "gpt-5.3-codex",
},
runtimeMode: "full-access",
@@ -678,7 +679,7 @@ describe("orchestration projector", () => {
projectId: "project-1",
title: "demo",
modelSelection: {
provider: "codex",
provider: ProviderDriverKind.make("codex"),
model: "gpt-5.3-codex",
},
runtimeMode: "full-access",
@@ -831,7 +832,7 @@ describe("orchestration projector", () => {
projectId: "project-1",
title: "capped",
modelSelection: {
provider: "codex",
provider: ProviderDriverKind.make("codex"),
model: "gpt-5-codex",
},
runtimeMode: "full-access",
@@ -1,4 +1,4 @@
import { ProjectId, ThreadId } from "@t3tools/contracts";
import { ProjectId, ThreadId, ProviderInstanceId } from "@t3tools/contracts";
import { assert, it } from "@effect/vitest";
import { Effect, Layer, Option } from "effect";
import * as SqlClient from "effect/unstable/sql/SqlClient";
@@ -28,7 +28,7 @@ projectionRepositoriesLayer("Projection repositories", (it) => {
title: "Null options project",
workspaceRoot: "/tmp/project-null-options",
defaultModelSelection: {
provider: "codex",
instanceId: ProviderInstanceId.make("codex"),
model: "gpt-5.4",
},
scripts: [],
@@ -52,7 +52,7 @@ projectionRepositoriesLayer("Projection repositories", (it) => {
assert.strictEqual(
row.defaultModelSelection,
JSON.stringify({
provider: "codex",
instanceId: ProviderInstanceId.make("codex"),
model: "gpt-5.4",
}),
);
@@ -61,7 +61,7 @@ projectionRepositoriesLayer("Projection repositories", (it) => {
projectId: ProjectId.make("project-null-options"),
});
assert.deepStrictEqual(Option.getOrNull(persisted)?.defaultModelSelection, {
provider: "codex",
instanceId: ProviderInstanceId.make("codex"),
model: "gpt-5.4",
});
}),
@@ -77,7 +77,7 @@ projectionRepositoriesLayer("Projection repositories", (it) => {
projectId: ProjectId.make("project-null-options"),
title: "Null options thread",
modelSelection: {
provider: "claudeAgent",
instanceId: ProviderInstanceId.make("claudeAgent"),
model: "claude-opus-4-6",
},
runtimeMode: "full-access",
@@ -110,7 +110,7 @@ projectionRepositoriesLayer("Projection repositories", (it) => {
assert.strictEqual(
row.modelSelection,
JSON.stringify({
provider: "claudeAgent",
instanceId: ProviderInstanceId.make("claudeAgent"),
model: "claude-opus-4-6",
}),
);
@@ -119,7 +119,7 @@ projectionRepositoriesLayer("Projection repositories", (it) => {
threadId: ThreadId.make("thread-null-options"),
});
assert.deepStrictEqual(Option.getOrNull(persisted)?.modelSelection, {
provider: "claudeAgent",
instanceId: ProviderInstanceId.make("claudeAgent"),
model: "claude-opus-4-6",
});
}),
@@ -23,6 +23,7 @@ const makeProjectionThreadSessionRepository = Effect.gen(function* () {
thread_id,
status,
provider_name,
provider_instance_id,
runtime_mode,
active_turn_id,
last_error,
@@ -32,6 +33,7 @@ const makeProjectionThreadSessionRepository = Effect.gen(function* () {
${row.threadId},
${row.status},
${row.providerName},
${row.providerInstanceId},
${row.runtimeMode},
${row.activeTurnId},
${row.lastError},
@@ -41,6 +43,7 @@ const makeProjectionThreadSessionRepository = Effect.gen(function* () {
DO UPDATE SET
status = excluded.status,
provider_name = excluded.provider_name,
provider_instance_id = excluded.provider_instance_id,
runtime_mode = excluded.runtime_mode,
active_turn_id = excluded.active_turn_id,
last_error = excluded.last_error,
@@ -57,6 +60,7 @@ const makeProjectionThreadSessionRepository = Effect.gen(function* () {
thread_id AS "threadId",
status,
provider_name AS "providerName",
provider_instance_id AS "providerInstanceId",
runtime_mode AS "runtimeMode",
active_turn_id AS "activeTurnId",
last_error AS "lastError",
@@ -46,6 +46,7 @@ const makeProviderSessionRuntimeRepository = Effect.gen(function* () {
INSERT INTO provider_session_runtime (
thread_id,
provider_name,
provider_instance_id,
adapter_key,
runtime_mode,
status,
@@ -56,6 +57,7 @@ const makeProviderSessionRuntimeRepository = Effect.gen(function* () {
VALUES (
${runtime.threadId},
${runtime.providerName},
${runtime.providerInstanceId},
${runtime.adapterKey},
${runtime.runtimeMode},
${runtime.status},
@@ -66,6 +68,7 @@ const makeProviderSessionRuntimeRepository = Effect.gen(function* () {
ON CONFLICT (thread_id)
DO UPDATE SET
provider_name = excluded.provider_name,
provider_instance_id = excluded.provider_instance_id,
adapter_key = excluded.adapter_key,
runtime_mode = excluded.runtime_mode,
status = excluded.status,
@@ -83,6 +86,7 @@ const makeProviderSessionRuntimeRepository = Effect.gen(function* () {
SELECT
thread_id AS "threadId",
provider_name AS "providerName",
provider_instance_id AS "providerInstanceId",
adapter_key AS "adapterKey",
runtime_mode AS "runtimeMode",
status,
@@ -102,6 +106,7 @@ const makeProviderSessionRuntimeRepository = Effect.gen(function* () {
SELECT
thread_id AS "threadId",
provider_name AS "providerName",
provider_instance_id AS "providerInstanceId",
adapter_key AS "adapterKey",
runtime_mode AS "runtimeMode",
status,
@@ -39,6 +39,8 @@ import Migration0023 from "./Migrations/023_ProjectionThreadShellSummary.ts";
import Migration0024 from "./Migrations/024_BackfillProjectionThreadShellSummary.ts";
import Migration0025 from "./Migrations/025_CleanupInvalidProjectionPendingApprovals.ts";
import Migration0026 from "./Migrations/026_CanonicalizeModelSelectionOptions.ts";
import Migration0027 from "./Migrations/027_ProviderSessionRuntimeInstanceId.ts";
import Migration0028 from "./Migrations/028_ProjectionThreadSessionInstanceId.ts";
/**
* Migration loader with all migrations defined inline.
@@ -77,6 +79,8 @@ export const migrationEntries = [
[24, "BackfillProjectionThreadShellSummary", Migration0024],
[25, "CleanupInvalidProjectionPendingApprovals", Migration0025],
[26, "CanonicalizeModelSelectionOptions", Migration0026],
[27, "ProviderSessionRuntimeInstanceId", Migration0027],
[28, "ProjectionThreadSessionInstanceId", Migration0028],
] as const;
export const makeMigrationLoader = (throughId?: number) =>
@@ -0,0 +1,74 @@
import { assert, it } from "@effect/vitest";
import { Effect, Layer } from "effect";
import * as SqlClient from "effect/unstable/sql/SqlClient";
import { runMigrations } from "../Migrations.ts";
import * as NodeSqliteClient from "../NodeSqliteClient.ts";
const layer = it.layer(Layer.mergeAll(NodeSqliteClient.layerMemory()));
layer("027_028_ProviderInstanceIdColumns", (it) => {
it.effect("continues when provider_session_runtime was partially migrated", () =>
Effect.gen(function* () {
const sql = yield* SqlClient.SqlClient;
yield* runMigrations({ toMigrationInclusive: 26 });
yield* sql`
ALTER TABLE provider_session_runtime
ADD COLUMN provider_instance_id TEXT
`;
yield* runMigrations({ toMigrationInclusive: 28 });
const migrations = yield* sql<{
readonly migration_id: number;
readonly name: string;
}>`
SELECT migration_id, name
FROM effect_sql_migrations
WHERE migration_id IN (27, 28)
ORDER BY migration_id
`;
assert.deepStrictEqual(migrations, [
{
migration_id: 27,
name: "ProviderSessionRuntimeInstanceId",
},
{
migration_id: 28,
name: "ProjectionThreadSessionInstanceId",
},
]);
const providerSessionColumns = yield* sql<{ readonly name: string }>`
PRAGMA table_info(provider_session_runtime)
`;
assert.ok(providerSessionColumns.some((column) => column.name === "provider_instance_id"));
const projectionThreadSessionColumns = yield* sql<{ readonly name: string }>`
PRAGMA table_info(projection_thread_sessions)
`;
assert.ok(
projectionThreadSessionColumns.some((column) => column.name === "provider_instance_id"),
);
const providerSessionIndexes = yield* sql<{ readonly name: string }>`
PRAGMA index_list(provider_session_runtime)
`;
assert.ok(
providerSessionIndexes.some(
(index) => index.name === "idx_provider_session_runtime_instance",
),
);
const projectionThreadSessionIndexes = yield* sql<{ readonly name: string }>`
PRAGMA index_list(projection_thread_sessions)
`;
assert.ok(
projectionThreadSessionIndexes.some(
(index) => index.name === "idx_projection_thread_sessions_instance",
),
);
}),
);
});
@@ -0,0 +1,38 @@
/**
* Adds the nullable `provider_instance_id` routing column to
* `provider_session_runtime`.
*
* Slice D of the provider-array refactor splits "driver kind" from
* "configured instance". Existing rows have only the driver name in
* `provider_name`; new rows additionally carry the user-defined instance
* routing key. The column remains nullable so legacy rows can still decode;
* the persistence boundary is responsible for materializing a concrete
* instance id before any hot routing path sees the binding.
*
* The column is nullable on purpose — backfilling it during the migration
* would require knowing which configured instance "owned" each historical
* session, and that mapping is ambiguous when the user later configures
* multiple instances of the same driver. Keeping that compatibility at the
* persistence boundary keeps the fallback out of active routing code.
*/
import * as SqlClient from "effect/unstable/sql/SqlClient";
import * as Effect from "effect/Effect";
export default Effect.gen(function* () {
const sql = yield* SqlClient.SqlClient;
const columns = yield* sql<{ readonly name: string }>`
PRAGMA table_info(provider_session_runtime)
`;
if (!columns.some((column) => column.name === "provider_instance_id")) {
yield* sql`
ALTER TABLE provider_session_runtime
ADD COLUMN provider_instance_id TEXT
`;
}
yield* sql`
CREATE INDEX IF NOT EXISTS idx_provider_session_runtime_instance
ON provider_session_runtime(provider_instance_id)
`;
});
@@ -0,0 +1,21 @@
import * as SqlClient from "effect/unstable/sql/SqlClient";
import * as Effect from "effect/Effect";
export default Effect.gen(function* () {
const sql = yield* SqlClient.SqlClient;
const columns = yield* sql<{ readonly name: string }>`
PRAGMA table_info(projection_thread_sessions)
`;
if (!columns.some((column) => column.name === "provider_instance_id")) {
yield* sql`
ALTER TABLE projection_thread_sessions
ADD COLUMN provider_instance_id TEXT
`;
}
yield* sql`
CREATE INDEX IF NOT EXISTS idx_projection_thread_sessions_instance
ON projection_thread_sessions(provider_instance_id)
`;
});
@@ -10,6 +10,7 @@ import {
RuntimeMode,
IsoDateTime,
OrchestrationSessionStatus,
ProviderInstanceId,
ThreadId,
TurnId,
} from "@t3tools/contracts";
@@ -22,6 +23,7 @@ export const ProjectionThreadSession = Schema.Struct({
threadId: ThreadId,
status: OrchestrationSessionStatus,
providerName: Schema.NullOr(Schema.String),
providerInstanceId: Schema.NullOr(ProviderInstanceId),
runtimeMode: RuntimeMode,
activeTurnId: Schema.NullOr(TurnId),
lastError: Schema.NullOr(Schema.String),
@@ -7,6 +7,7 @@
*/
import {
IsoDateTime,
ProviderInstanceId,
ProviderSessionRuntimeStatus,
RuntimeMode,
ThreadId,
@@ -19,6 +20,14 @@ import type { ProviderSessionRuntimeRepositoryError } from "../Errors.ts";
export const ProviderSessionRuntime = Schema.Struct({
threadId: ThreadId,
providerName: Schema.String,
/**
* User-defined routing key for the configured provider instance that
* owns this session. Nullable only at the storage/migration boundary:
* rows persisted before the driver/instance split carry only
* `providerName`. Repository consumers must materialize a concrete
* instance id before routing.
*/
providerInstanceId: Schema.NullOr(ProviderInstanceId),
adapterKey: Schema.String,
runtimeMode: RuntimeMode,
status: ProviderSessionRuntimeStatus,
@@ -1,6 +1,9 @@
import type { RepositoryIdentity } from "@t3tools/contracts";
import { Cache, Duration, Effect, Exit, Layer } from "effect";
import { detectGitHostingProviderFromRemoteUrl, normalizeGitRemoteUrl } from "@t3tools/shared/git";
import {
detectSourceControlProviderFromGitRemoteUrl,
normalizeGitRemoteUrl,
} from "@t3tools/shared/git";
import { runProcess } from "../../processRunner.ts";
import {
@@ -45,7 +48,7 @@ function buildRepositoryIdentity(input: {
readonly rootPath: string;
}): RepositoryIdentity {
const canonicalKey = normalizeGitRemoteUrl(input.remoteUrl);
const hostingProvider = detectGitHostingProviderFromRemoteUrl(input.remoteUrl);
const sourceControlProvider = detectSourceControlProviderFromGitRemoteUrl(input.remoteUrl);
const repositoryPath = canonicalKey.split("/").slice(1).join("/");
const repositoryPathSegments = repositoryPath.split("/").filter((segment) => segment.length > 0);
const [owner] = repositoryPathSegments;
@@ -60,7 +63,7 @@ function buildRepositoryIdentity(input: {
},
rootPath: input.rootPath,
...(repositoryPath ? { displayName: repositoryPath } : {}),
...(hostingProvider ? { provider: hostingProvider.kind } : {}),
...(sourceControlProvider ? { provider: sourceControlProvider.kind } : {}),
...(owner ? { owner } : {}),
...(repositoryName ? { name: repositoryName } : {}),
};
@@ -0,0 +1,157 @@
/**
* ClaudeDriver — `ProviderDriver` for the Claude Agent SDK runtime.
*
* Mirrors `CodexDriver`: a plain value whose `create()` returns one
* `ProviderInstance` bundling `snapshot` / `adapter` / `textGeneration`
* closures captured over the per-instance `ClaudeSettings`.
*
* Unlike Codex, the Claude snapshot probe may invoke a secondary probe
* (`probeClaudeCapabilities`) to read Anthropic account + slash-command
* metadata. That probe is per-instance and keyed by binary + resolved HOME so
* two concurrent Claude instances don't cross-contaminate account metadata.
*
* @module provider/Drivers/ClaudeDriver
*/
import { ClaudeSettings, ProviderDriverKind, type ServerProvider } from "@t3tools/contracts";
import { Cache, Duration, Effect, FileSystem, Path, Schema, Stream } from "effect";
import { ChildProcessSpawner } from "effect/unstable/process";
import { makeClaudeTextGeneration } from "../../textGeneration/ClaudeTextGeneration.ts";
import { ServerConfig } from "../../config.ts";
import { ProviderDriverError } from "../Errors.ts";
import { makeClaudeAdapter } from "../Layers/ClaudeAdapter.ts";
import {
checkClaudeProviderStatus,
makePendingClaudeProvider,
probeClaudeCapabilities,
} from "../Layers/ClaudeProvider.ts";
import { ProviderEventLoggers } from "../Layers/ProviderEventLoggers.ts";
import { makeManagedServerProvider } from "../makeManagedServerProvider.ts";
import {
defaultProviderContinuationIdentity,
type ProviderDriver,
type ProviderInstance,
} from "../ProviderDriver.ts";
import type { ServerProviderDraft } from "../providerSnapshot.ts";
import { mergeProviderInstanceEnvironment } from "../ProviderInstanceEnvironment.ts";
import { makeClaudeCapabilitiesCacheKey, makeClaudeContinuationGroupKey } from "./ClaudeHome.ts";
const DRIVER_KIND = ProviderDriverKind.make("claudeAgent");
const SNAPSHOT_REFRESH_INTERVAL = Duration.minutes(5);
const CAPABILITIES_PROBE_TTL = Duration.minutes(5);
export type ClaudeDriverEnv =
| ChildProcessSpawner.ChildProcessSpawner
| FileSystem.FileSystem
| Path.Path
| ProviderEventLoggers
| ServerConfig;
const withInstanceIdentity =
(input: {
readonly instanceId: ProviderInstance["instanceId"];
readonly displayName: string | undefined;
readonly accentColor: string | undefined;
readonly continuationGroupKey: string;
}) =>
(snapshot: ServerProviderDraft): ServerProvider => ({
...snapshot,
instanceId: input.instanceId,
driver: DRIVER_KIND,
...(input.displayName ? { displayName: input.displayName } : {}),
...(input.accentColor ? { accentColor: input.accentColor } : {}),
continuation: { groupKey: input.continuationGroupKey },
});
export const ClaudeDriver: ProviderDriver<ClaudeSettings, ClaudeDriverEnv> = {
driverKind: DRIVER_KIND,
metadata: {
displayName: "Claude",
supportsMultipleInstances: true,
},
configSchema: ClaudeSettings,
defaultConfig: (): ClaudeSettings => Schema.decodeSync(ClaudeSettings)({}),
create: ({ instanceId, displayName, accentColor, environment, enabled, config }) =>
Effect.gen(function* () {
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
const path = yield* Path.Path;
const eventLoggers = yield* ProviderEventLoggers;
const processEnv = mergeProviderInstanceEnvironment(environment);
const fallbackContinuationIdentity = defaultProviderContinuationIdentity({
driverKind: DRIVER_KIND,
instanceId,
});
const effectiveConfig = { ...config, enabled } satisfies ClaudeSettings;
const continuationGroupKey = yield* makeClaudeContinuationGroupKey(effectiveConfig);
const stampIdentity = withInstanceIdentity({
instanceId,
displayName,
accentColor,
continuationGroupKey,
});
const adapterOptions = {
instanceId,
environment: processEnv,
...(eventLoggers.native ? { nativeEventLogger: eventLoggers.native } : {}),
};
const adapter = yield* makeClaudeAdapter(effectiveConfig, adapterOptions);
const textGeneration = yield* makeClaudeTextGeneration(effectiveConfig, processEnv);
// Per-instance capabilities cache: keyed on binary + resolved HOME so
// account-specific probes never share auth metadata across instances.
const capabilitiesProbeCache = yield* Cache.make({
capacity: 1,
timeToLive: CAPABILITIES_PROBE_TTL,
lookup: () =>
probeClaudeCapabilities(effectiveConfig, processEnv).pipe(
Effect.provideService(Path.Path, path),
),
});
const capabilitiesCacheKey = yield* makeClaudeCapabilitiesCacheKey(effectiveConfig);
const checkProvider = checkClaudeProviderStatus(
effectiveConfig,
() => Cache.get(capabilitiesProbeCache, capabilitiesCacheKey),
processEnv,
).pipe(
Effect.map(stampIdentity),
Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
Effect.provideService(Path.Path, path),
);
const snapshot = yield* makeManagedServerProvider<ClaudeSettings>({
getSettings: Effect.succeed(effectiveConfig),
streamSettings: Stream.never,
haveSettingsChanged: () => false,
initialSnapshot: (settings) => stampIdentity(makePendingClaudeProvider(settings)),
checkProvider,
refreshInterval: SNAPSHOT_REFRESH_INTERVAL,
}).pipe(
Effect.mapError(
(cause) =>
new ProviderDriverError({
driver: DRIVER_KIND,
instanceId,
detail: `Failed to build Claude snapshot: ${cause.message ?? String(cause)}`,
cause,
}),
),
);
return {
instanceId,
driverKind: DRIVER_KIND,
continuationIdentity: {
...fallbackContinuationIdentity,
continuationKey: continuationGroupKey,
},
displayName,
accentColor,
enabled,
snapshot,
adapter,
textGeneration,
} satisfies ProviderInstance;
}),
};
@@ -0,0 +1,52 @@
import * as NodeOS from "node:os";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { describe, expect, it } from "@effect/vitest";
import { Effect, Path } from "effect";
import {
makeClaudeCapabilitiesCacheKey,
makeClaudeContinuationGroupKey,
makeClaudeEnvironment,
resolveClaudeHomePath,
} from "./ClaudeHome.ts";
it.layer(NodeServices.layer)("ClaudeHome", (it) => {
describe("Claude home resolution", () => {
it.effect("uses the process home when no Claude home override is configured", () =>
Effect.gen(function* () {
const path = yield* Path.Path;
const resolved = path.resolve(NodeOS.homedir());
expect(yield* resolveClaudeHomePath({ homePath: "" })).toBe(resolved);
expect(yield* makeClaudeEnvironment({ homePath: "" })).toBe(process.env);
}),
);
it.effect("resolves configured Claude HOME and stamps continuation/cache keys with it", () =>
Effect.gen(function* () {
const path = yield* Path.Path;
const homePath = "~/.claude-work";
const resolved = path.resolve(NodeOS.homedir(), ".claude-work");
expect(yield* resolveClaudeHomePath({ homePath })).toBe(resolved);
expect((yield* makeClaudeEnvironment({ homePath })).HOME).toBe(resolved);
expect(yield* makeClaudeContinuationGroupKey({ homePath })).toBe(`claude:home:${resolved}`);
expect(yield* makeClaudeCapabilitiesCacheKey({ binaryPath: "claude", homePath })).toBe(
`claude\0${resolved}`,
);
}),
);
it.effect("keeps continuation compatible across instances with the same Claude HOME", () =>
Effect.gen(function* () {
const path = yield* Path.Path;
const resolved = path.resolve(NodeOS.homedir());
expect(yield* makeClaudeContinuationGroupKey({ homePath: "" })).toBe(
`claude:home:${resolved}`,
);
}),
);
});
});
@@ -0,0 +1,43 @@
import * as NodeOS from "node:os";
import type { ClaudeSettings } from "@t3tools/contracts";
import { Effect, Path } from "effect";
import { expandHomePath } from "../../pathExpansion.ts";
export const resolveClaudeHomePath = Effect.fn("resolveClaudeHomePath")(function* (
config: Pick<ClaudeSettings, "homePath">,
): Effect.fn.Return<string, never, Path.Path> {
const path = yield* Path.Path;
const homePath = config.homePath.trim();
return path.resolve(homePath.length > 0 ? expandHomePath(homePath) : NodeOS.homedir());
});
export const makeClaudeEnvironment = Effect.fn("makeClaudeEnvironment")(function* (
config: Pick<ClaudeSettings, "homePath">,
baseEnv: NodeJS.ProcessEnv = process.env,
): Effect.fn.Return<NodeJS.ProcessEnv, never, Path.Path> {
const homePath = config.homePath.trim();
if (homePath.length === 0) return baseEnv;
const resolvedHomePath = yield* resolveClaudeHomePath(config);
return {
...baseEnv,
HOME: resolvedHomePath,
};
});
export const makeClaudeContinuationGroupKey = Effect.fn("makeClaudeContinuationGroupKey")(
function* (config: Pick<ClaudeSettings, "homePath">): Effect.fn.Return<string, never, Path.Path> {
const resolvedHomePath = yield* resolveClaudeHomePath(config);
return `claude:home:${resolvedHomePath}`;
},
);
export const makeClaudeCapabilitiesCacheKey = Effect.fn("makeClaudeCapabilitiesCacheKey")(
function* (
config: Pick<ClaudeSettings, "binaryPath" | "homePath">,
): Effect.fn.Return<string, never, Path.Path> {
const resolvedHomePath = yield* resolveClaudeHomePath(config);
return `${config.binaryPath}\0${resolvedHomePath}`;
},
);
@@ -0,0 +1,171 @@
/**
* CodexDriver — first concrete `ProviderDriver` in the new per-instance model.
*
* A driver is a plain value (not a Context.Service) whose `create()` returns
* one `ProviderInstance` bundling:
* - `snapshot` — the live `ServerProviderShape` for this instance;
* - `adapter` — the Codex session/turn/approval runtime;
* - `textGeneration` — commit/PR/branch/title generation via `codex exec`.
*
* Each call to `create()` captures the `codexConfig` argument in closures
* owned by the returned instance. Two instances created with different
* `homePath`s (e.g. `codex_personal` + `codex_work`) therefore run with
* fully independent Codex app-server processes and `CODEX_HOME`
* environments — no shared mutable state.
*
* Resource lifecycle: `create()` runs in a scope handed in by the registry.
* Closing that scope releases the adapter's child processes, the managed
* snapshot's refresh fibre, and the text-generation binaries' transient
* scratch files. The registry uses this to tear down an instance when its
* `providerInstances` entry disappears or its config changes.
*
* @module provider/Drivers/CodexDriver
*/
import { CodexSettings, ProviderDriverKind, type ServerProvider } from "@t3tools/contracts";
import { Duration, Effect, FileSystem, Path, Schema, Stream } from "effect";
import { ChildProcessSpawner } from "effect/unstable/process";
import { makeCodexTextGeneration } from "../../textGeneration/CodexTextGeneration.ts";
import { ServerConfig } from "../../config.ts";
import { ProviderDriverError } from "../Errors.ts";
import { makeCodexAdapter } from "../Layers/CodexAdapter.ts";
import { checkCodexProviderStatus, makePendingCodexProvider } from "../Layers/CodexProvider.ts";
import { ProviderEventLoggers } from "../Layers/ProviderEventLoggers.ts";
import { makeManagedServerProvider } from "../makeManagedServerProvider.ts";
import type { ProviderDriver, ProviderInstance } from "../ProviderDriver.ts";
import type { ServerProviderDraft } from "../providerSnapshot.ts";
import { mergeProviderInstanceEnvironment } from "../ProviderInstanceEnvironment.ts";
import {
codexContinuationIdentity,
materializeCodexShadowHome,
resolveCodexHomeLayout,
} from "./CodexHomeLayout.ts";
const DRIVER_KIND = ProviderDriverKind.make("codex");
const SNAPSHOT_REFRESH_INTERVAL = Duration.minutes(5);
/**
* Services the driver needs to materialize an instance. Surfaced as the
* driver's `R` so the registry layer aggregates these across every
* registered driver and the runtime satisfies them once.
*/
export type CodexDriverEnv =
| ChildProcessSpawner.ChildProcessSpawner
| FileSystem.FileSystem
| Path.Path
| ProviderEventLoggers
| ServerConfig;
/**
* Stamp instance identity onto a `ServerProvider` snapshot produced by the
* driver-kind-only codex helpers. Once `buildServerProvider` in
* `providerSnapshot.ts` is widened to accept `instanceId`/`driver`, this
* wrapper disappears.
*/
const withInstanceIdentity =
(input: {
readonly instanceId: ProviderInstance["instanceId"];
readonly displayName: string | undefined;
readonly accentColor: string | undefined;
readonly continuationGroupKey: string;
}) =>
(snapshot: ServerProviderDraft): ServerProvider => ({
...snapshot,
instanceId: input.instanceId,
driver: DRIVER_KIND,
...(input.displayName ? { displayName: input.displayName } : {}),
...(input.accentColor ? { accentColor: input.accentColor } : {}),
continuation: { groupKey: input.continuationGroupKey },
});
export const CodexDriver: ProviderDriver<CodexSettings, CodexDriverEnv> = {
driverKind: DRIVER_KIND,
metadata: {
displayName: "Codex",
supportsMultipleInstances: true,
},
configSchema: CodexSettings,
defaultConfig: (): CodexSettings => Schema.decodeSync(CodexSettings)({}),
create: ({ instanceId, displayName, accentColor, environment, enabled, config }) =>
Effect.gen(function* () {
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
const eventLoggers = yield* ProviderEventLoggers;
const processEnv = mergeProviderInstanceEnvironment(environment);
const homeLayout = yield* resolveCodexHomeLayout(config);
const continuationIdentity = codexContinuationIdentity(homeLayout);
const stampIdentity = withInstanceIdentity({
instanceId,
displayName,
accentColor,
continuationGroupKey: continuationIdentity.continuationKey,
});
yield* materializeCodexShadowHome(homeLayout).pipe(
Effect.mapError(
(cause) =>
new ProviderDriverError({
driver: DRIVER_KIND,
instanceId,
detail: cause.message,
cause,
}),
),
);
const effectiveConfig = {
...config,
enabled,
homePath: homeLayout.effectiveHomePath ?? "",
} satisfies CodexSettings;
// `makeCodexAdapter` and `makeCodexTextGeneration` have `never` error
// channels at construction time — their failure modes are all on the
// per-operation closures they return. No `mapError` wrapper is needed
// here; the registry only has to worry about snapshot-build and
// spawner-availability failures surfaced from `checkCodexProviderStatus`
// below.
const adapter = yield* makeCodexAdapter(effectiveConfig, {
instanceId,
environment: processEnv,
...(eventLoggers.native ? { nativeEventLogger: eventLoggers.native } : {}),
});
const textGeneration = yield* makeCodexTextGeneration(effectiveConfig, processEnv);
// Build a managed snapshot whose settings never change — mutations come
// in as instance rebuilds from the registry rather than in-place
// updates. Pre-provide `ChildProcessSpawner` so the check fits
// `makeManagedServerProvider.checkProvider`'s `R = never`.
const checkProvider = checkCodexProviderStatus(effectiveConfig, undefined, processEnv).pipe(
Effect.map(stampIdentity),
Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
);
const snapshot = yield* makeManagedServerProvider<CodexSettings>({
getSettings: Effect.succeed(effectiveConfig),
streamSettings: Stream.never,
haveSettingsChanged: () => false,
initialSnapshot: (settings) => stampIdentity(makePendingCodexProvider(settings)),
checkProvider,
refreshInterval: SNAPSHOT_REFRESH_INTERVAL,
}).pipe(
Effect.mapError(
(cause) =>
new ProviderDriverError({
driver: DRIVER_KIND,
instanceId,
detail: `Failed to build Codex snapshot: ${cause.message ?? String(cause)}`,
cause,
}),
),
);
return {
instanceId,
driverKind: DRIVER_KIND,
continuationIdentity,
displayName,
accentColor,
enabled,
snapshot,
adapter,
textGeneration,
} satisfies ProviderInstance;
}),
};
@@ -0,0 +1,209 @@
import * as NodeServices from "@effect/platform-node/NodeServices";
import { describe, expect, it } from "@effect/vitest";
import { Effect, FileSystem, Path, Schema } from "effect";
import { CodexSettings } from "@t3tools/contracts";
import {
CodexShadowHomeError,
materializeCodexShadowHome,
resolveCodexHomeLayout,
} from "./CodexHomeLayout.ts";
const decodeCodexSettings = (input: {
readonly enabled?: boolean;
readonly homePath?: string;
readonly shadowHomePath?: string;
readonly customModels?: readonly string[];
readonly binaryPath?: string;
}): CodexSettings => Schema.decodeSync(CodexSettings)(input);
const makeTempDir = Effect.fn("CodexHomeLayout.test.makeTempDir")(function* (prefix: string) {
const fileSystem = yield* FileSystem.FileSystem;
return yield* fileSystem.makeTempDirectoryScoped({ prefix });
});
const writeTextFile = Effect.fn("CodexHomeLayout.test.writeTextFile")(function* (
filePath: string,
contents: string,
) {
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
yield* fileSystem.makeDirectory(path.dirname(filePath), { recursive: true });
yield* fileSystem.writeFileString(filePath, contents);
});
it.layer(NodeServices.layer)("CodexHomeLayout", (it) => {
describe("resolveCodexHomeLayout", () => {
it.effect("uses direct CODEX_HOME when no shadow home is configured", () =>
Effect.gen(function* () {
const homePath = yield* makeTempDir("t3code-codex-home-");
const layout = yield* resolveCodexHomeLayout(
decodeCodexSettings({
homePath,
}),
);
expect(layout).toMatchObject({
mode: "direct",
sharedHomePath: homePath,
effectiveHomePath: homePath,
continuationKey: `codex:home:${homePath}`,
});
}),
);
it.effect("uses the shared home for continuation and the shadow home for runtime", () =>
Effect.gen(function* () {
const path = yield* Path.Path;
const sharedHome = yield* makeTempDir("t3code-codex-shared-");
const shadowRoot = yield* makeTempDir("t3code-codex-shadow-root-");
const shadowHome = path.join(shadowRoot, "shadow");
const layout = yield* resolveCodexHomeLayout(
decodeCodexSettings({
homePath: sharedHome,
shadowHomePath: shadowHome,
}),
);
expect(layout).toMatchObject({
mode: "authOverlay",
sharedHomePath: sharedHome,
effectiveHomePath: shadowHome,
continuationKey: `codex:home:${sharedHome}`,
});
}),
);
});
describe("materializeCodexShadowHome", () => {
it.effect("materializes a shadow home with shared state links and private auth", () =>
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const sharedHome = yield* makeTempDir("t3code-codex-shared-");
const shadowRoot = yield* makeTempDir("t3code-codex-shadow-root-");
const shadowHome = path.join(shadowRoot, "shadow");
yield* fileSystem.makeDirectory(path.join(sharedHome, "sessions"));
yield* writeTextFile(path.join(sharedHome, "config.toml"), 'model = "gpt-5-codex"\n');
yield* writeTextFile(path.join(sharedHome, "models_cache.json"), '{"models":["shared"]}\n');
yield* writeTextFile(path.join(sharedHome, "auth.json"), '{"shared":true}\n');
yield* fileSystem.makeDirectory(shadowHome, { recursive: true });
yield* writeTextFile(path.join(shadowHome, "auth.json"), '{"shadow":true}\n');
yield* fileSystem.symlink(
path.join(sharedHome, "models_cache.json"),
path.join(shadowHome, "models_cache.json"),
);
const layout = yield* resolveCodexHomeLayout(
decodeCodexSettings({
homePath: sharedHome,
shadowHomePath: shadowHome,
}),
);
yield* materializeCodexShadowHome(layout);
const sessionsTarget = yield* fileSystem.readLink(path.join(shadowHome, "sessions"));
const configTarget = yield* fileSystem.readLink(path.join(shadowHome, "config.toml"));
const modelsCacheExists = yield* fileSystem.exists(
path.join(shadowHome, "models_cache.json"),
);
const authLinkResult = yield* fileSystem
.readLink(path.join(shadowHome, "auth.json"))
.pipe(Effect.result);
const authContents = yield* fileSystem.readFileString(path.join(shadowHome, "auth.json"));
expect(sessionsTarget).toBe(path.join(sharedHome, "sessions"));
expect(configTarget).toBe(path.join(sharedHome, "config.toml"));
expect(modelsCacheExists).toBe(false);
expect(authLinkResult._tag).toBe("Failure");
expect(authContents).toContain("shadow");
}),
);
it.effect("accepts Codex-created shadow-local runtime directories", () =>
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const sharedHome = yield* makeTempDir("t3code-codex-shared-");
const shadowRoot = yield* makeTempDir("t3code-codex-shadow-root-");
const shadowHome = path.join(shadowRoot, "shadow");
yield* fileSystem.makeDirectory(path.join(sharedHome, "log"));
yield* fileSystem.makeDirectory(path.join(sharedHome, "memories"));
yield* fileSystem.makeDirectory(path.join(sharedHome, "tmp"));
yield* writeTextFile(path.join(sharedHome, "config.toml"), 'model = "gpt-5-codex"\n');
yield* writeTextFile(path.join(shadowHome, "auth.json"), '{"shadow":true}\n');
yield* fileSystem.makeDirectory(path.join(shadowHome, "log"), { recursive: true });
yield* fileSystem.makeDirectory(path.join(shadowHome, "memories"), { recursive: true });
yield* fileSystem.makeDirectory(path.join(shadowHome, "tmp"), { recursive: true });
const layout = yield* resolveCodexHomeLayout(
decodeCodexSettings({
homePath: sharedHome,
shadowHomePath: shadowHome,
}),
);
yield* materializeCodexShadowHome(layout);
const configTarget = yield* fileSystem.readLink(path.join(shadowHome, "config.toml"));
const logLinkResult = yield* fileSystem
.readLink(path.join(shadowHome, "log"))
.pipe(Effect.result);
const memoriesLinkResult = yield* fileSystem
.readLink(path.join(shadowHome, "memories"))
.pipe(Effect.result);
const tmpLinkResult = yield* fileSystem
.readLink(path.join(shadowHome, "tmp"))
.pipe(Effect.result);
expect(configTarget).toBe(path.join(sharedHome, "config.toml"));
expect(logLinkResult._tag).toBe("Failure");
expect(memoriesLinkResult._tag).toBe("Failure");
expect(tmpLinkResult._tag).toBe("Failure");
}),
);
it.effect("rejects shadow homes that point at the shared home", () =>
Effect.gen(function* () {
const sharedHome = yield* makeTempDir("t3code-codex-shared-");
const layout = yield* resolveCodexHomeLayout(
decodeCodexSettings({
homePath: sharedHome,
shadowHomePath: sharedHome,
}),
);
const error = yield* materializeCodexShadowHome(layout).pipe(Effect.flip);
expect(error).toBeInstanceOf(CodexShadowHomeError);
}),
);
it.effect("rejects shared entries that already exist in the shadow home as real files", () =>
Effect.gen(function* () {
const path = yield* Path.Path;
const sharedHome = yield* makeTempDir("t3code-codex-shared-");
const shadowRoot = yield* makeTempDir("t3code-codex-shadow-root-");
const shadowHome = path.join(shadowRoot, "shadow");
yield* writeTextFile(path.join(sharedHome, "config.toml"), 'model = "gpt-5-codex"\n');
yield* writeTextFile(path.join(shadowHome, "config.toml"), 'model = "local"\n');
const layout = yield* resolveCodexHomeLayout(
decodeCodexSettings({
homePath: sharedHome,
shadowHomePath: shadowHome,
}),
);
const error = yield* materializeCodexShadowHome(layout).pipe(Effect.flip);
expect(error.detail).toContain("already exists and is not a symlink");
}),
);
});
});
@@ -0,0 +1,263 @@
import * as NodeOS from "node:os";
import { ProviderDriverKind, type CodexSettings } from "@t3tools/contracts";
import { Effect, FileSystem, Path, Schema } from "effect";
import * as PlatformError from "effect/PlatformError";
import { expandHomePath } from "../../pathExpansion.ts";
export interface CodexHomeLayout {
readonly mode: "direct" | "authOverlay";
readonly sharedHomePath: string;
readonly effectiveHomePath: string | undefined;
readonly continuationKey: string;
}
const KNOWN_SHARED_DIRECTORIES = [
"sessions",
"archived_sessions",
"sqlite",
"shell_snapshots",
"worktrees",
"skills",
"plugins",
"cache",
"logs",
] as const;
const PRIVATE_ENTRY_NAMES = new Set(["auth.json", "models_cache.json"]);
const SHADOW_LOCAL_ENTRY_NAMES = new Set(["log", "memories", "tmp"]);
function resolveHomePath(path: Path.Path, value: string | undefined): string {
const expanded =
value && value.trim().length > 0
? expandHomePath(value)
: path.join(NodeOS.homedir(), ".codex");
return path.resolve(expanded);
}
export const resolveCodexHomeLayout = Effect.fn("resolveCodexHomeLayout")(function* (
config: CodexSettings,
): Effect.fn.Return<CodexHomeLayout, never, Path.Path> {
const path = yield* Path.Path;
const sharedHomePath = resolveHomePath(path, config.homePath);
const shadowHomePath = config.shadowHomePath.trim();
if (shadowHomePath.length === 0) {
return {
mode: "direct",
sharedHomePath,
effectiveHomePath: config.homePath.trim().length > 0 ? sharedHomePath : undefined,
continuationKey: `codex:home:${sharedHomePath}`,
};
}
const effectiveHomePath = path.resolve(expandHomePath(shadowHomePath));
return {
mode: "authOverlay",
sharedHomePath,
effectiveHomePath,
continuationKey: `codex:home:${sharedHomePath}`,
};
});
export class CodexShadowHomeError extends Schema.TaggedErrorClass<CodexShadowHomeError>()(
"CodexShadowHomeError",
{
detail: Schema.String,
cause: Schema.optional(Schema.Unknown),
},
) {
override get message(): string {
return this.detail;
}
}
type LinkState =
| {
readonly _tag: "Missing";
}
| {
readonly _tag: "NotSymlink";
}
| {
readonly _tag: "Symlink";
readonly target: string;
};
function toShadowHomeError(cause: unknown): CodexShadowHomeError {
return Schema.is(CodexShadowHomeError)(cause)
? cause
: new CodexShadowHomeError({
detail: "Failed to materialize Codex shadow home.",
cause,
});
}
function normalizeShadowHomeError<A, E, R>(
effect: Effect.Effect<A, E, R>,
): Effect.Effect<A, CodexShadowHomeError, R> {
return effect.pipe(Effect.mapError(toShadowHomeError));
}
function isNotSymlinkError(error: PlatformError.PlatformError): boolean {
const cause = error.reason.cause;
return (
error.reason._tag === "Unknown" &&
typeof cause === "object" &&
cause !== null &&
"code" in cause &&
cause.code === "EINVAL"
);
}
const readLinkState = Effect.fn("CodexHomeLayout.readLinkState")(function* (
fileSystem: FileSystem.FileSystem,
linkPath: string,
): Effect.fn.Return<LinkState, CodexShadowHomeError> {
return yield* fileSystem.readLink(linkPath).pipe(
Effect.map((target): LinkState => ({ _tag: "Symlink", target })),
Effect.catch((error) => {
if (error.reason._tag === "NotFound") {
return Effect.succeed<LinkState>({ _tag: "Missing" });
}
if (isNotSymlinkError(error)) {
return Effect.succeed<LinkState>({ _tag: "NotSymlink" });
}
return Effect.fail(toShadowHomeError(error));
}),
);
});
const removePrivateSymlink = Effect.fn("CodexHomeLayout.removePrivateSymlink")(function* (input: {
readonly fileSystem: FileSystem.FileSystem;
readonly shadowPath: string;
readonly entryName: string;
}): Effect.fn.Return<void, CodexShadowHomeError, Path.Path> {
const path = yield* Path.Path;
const privatePath = path.join(input.shadowPath, input.entryName);
const state = yield* readLinkState(input.fileSystem, privatePath);
if (state._tag === "Symlink") {
yield* normalizeShadowHomeError(input.fileSystem.remove(privatePath));
}
});
const ensureSymlink = Effect.fn("CodexHomeLayout.ensureSymlink")(function* (input: {
readonly fileSystem: FileSystem.FileSystem;
readonly shadowPath: string;
readonly sharedPath: string;
readonly entryName: string;
}): Effect.fn.Return<void, CodexShadowHomeError, Path.Path> {
const path = yield* Path.Path;
const target = path.join(input.sharedPath, input.entryName);
const link = path.join(input.shadowPath, input.entryName);
const state = yield* readLinkState(input.fileSystem, link);
if (state._tag === "NotSymlink") {
return yield* new CodexShadowHomeError({
detail: `Cannot create Codex shadow home because '${link}' already exists and is not a symlink.`,
});
}
if (state._tag === "Missing") {
return yield* normalizeShadowHomeError(input.fileSystem.symlink(target, link));
}
const resolvedExisting = path.resolve(path.dirname(link), state.target);
if (resolvedExisting !== target) {
yield* normalizeShadowHomeError(input.fileSystem.remove(link));
yield* normalizeShadowHomeError(input.fileSystem.symlink(target, link));
}
});
const ensureShadowAuthIsPrivate = Effect.fn("CodexHomeLayout.ensureShadowAuthIsPrivate")(function* (
fileSystem: FileSystem.FileSystem,
shadowPath: string,
): Effect.fn.Return<void, CodexShadowHomeError, Path.Path> {
const path = yield* Path.Path;
const authPath = path.join(shadowPath, "auth.json");
const state = yield* readLinkState(fileSystem, authPath);
if (state._tag === "Symlink") {
return yield* new CodexShadowHomeError({
detail: `Codex shadow auth file '${authPath}' must be a real file, not a symlink.`,
});
}
});
export const materializeCodexShadowHome = Effect.fn("materializeCodexShadowHome")(function* (
layout: CodexHomeLayout,
) {
if (layout.mode !== "authOverlay") return;
const effectiveHomePath = layout.effectiveHomePath;
if (!effectiveHomePath) return;
if (layout.sharedHomePath === effectiveHomePath) {
return yield* new CodexShadowHomeError({
detail: "Codex shadow home path must be different from the shared home path.",
});
}
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
yield* normalizeShadowHomeError(
Effect.all(
[
fileSystem.makeDirectory(layout.sharedHomePath, { recursive: true }),
fileSystem.makeDirectory(effectiveHomePath, { recursive: true }),
...KNOWN_SHARED_DIRECTORIES.map((directory) =>
fileSystem.makeDirectory(path.join(layout.sharedHomePath, directory), {
recursive: true,
}),
),
],
{ concurrency: "unbounded" },
),
);
const sharedEntryNames = yield* normalizeShadowHomeError(
fileSystem.readDirectory(layout.sharedHomePath),
);
const entries = new Set<string>(KNOWN_SHARED_DIRECTORIES);
for (const entryName of sharedEntryNames) {
if (!PRIVATE_ENTRY_NAMES.has(entryName) && !SHADOW_LOCAL_ENTRY_NAMES.has(entryName)) {
entries.add(entryName);
}
}
yield* Effect.forEach(
PRIVATE_ENTRY_NAMES,
(entryName) =>
entryName === "auth.json"
? Effect.void
: removePrivateSymlink({
fileSystem,
shadowPath: effectiveHomePath,
entryName,
}),
{ discard: true },
);
yield* Effect.forEach(
entries,
(entryName) => {
if (PRIVATE_ENTRY_NAMES.has(entryName)) {
return Effect.void;
}
return ensureSymlink({
fileSystem,
shadowPath: effectiveHomePath,
sharedPath: layout.sharedHomePath,
entryName,
});
},
{ discard: true },
);
yield* ensureShadowAuthIsPrivate(fileSystem, effectiveHomePath);
});
export function codexContinuationIdentity(layout: CodexHomeLayout) {
return {
driverKind: ProviderDriverKind.make("codex"),
continuationKey: layout.continuationKey,
};
}
@@ -0,0 +1,148 @@
/**
* CursorDriver — `ProviderDriver` for the Cursor Agent (`agent`) runtime.
*
* Cursor exposes an ACP-based CLI. The driver is still a plain value, but
* its snapshot uses `makeManagedServerProvider`'s optional `enrichSnapshot`
* hook to run the slow ACP model-capability probe in the background without
* blocking the initial `ready`-state publish.
*
* Text generation is supported via the ACP runtime — `makeCursorTextGeneration`
* drives `runtime.prompt` with a structured-output schema and collects the
* agent's `agent_message_chunk` stream into a single JSON blob.
*
* @module provider/Drivers/CursorDriver
*/
import { CursorSettings, ProviderDriverKind, type ServerProvider } from "@t3tools/contracts";
import { Duration, Effect, FileSystem, Path, Schema, Stream } from "effect";
import { ChildProcessSpawner } from "effect/unstable/process";
import { ServerConfig } from "../../config.ts";
import { makeCursorTextGeneration } from "../../textGeneration/CursorTextGeneration.ts";
import { ProviderDriverError } from "../Errors.ts";
import { makeCursorAdapter } from "../Layers/CursorAdapter.ts";
import {
buildInitialCursorProviderSnapshot,
checkCursorProviderStatus,
enrichCursorSnapshot,
} from "../Layers/CursorProvider.ts";
import { ProviderEventLoggers } from "../Layers/ProviderEventLoggers.ts";
import { makeManagedServerProvider } from "../makeManagedServerProvider.ts";
import {
defaultProviderContinuationIdentity,
type ProviderDriver,
type ProviderInstance,
} from "../ProviderDriver.ts";
import type { ServerProviderDraft } from "../providerSnapshot.ts";
import { mergeProviderInstanceEnvironment } from "../ProviderInstanceEnvironment.ts";
const DRIVER_KIND = ProviderDriverKind.make("cursor");
const SNAPSHOT_REFRESH_INTERVAL = Duration.minutes(5);
export type CursorDriverEnv =
| ChildProcessSpawner.ChildProcessSpawner
| FileSystem.FileSystem
| Path.Path
| ProviderEventLoggers
| ServerConfig;
const withInstanceIdentity =
(input: {
readonly instanceId: ProviderInstance["instanceId"];
readonly displayName: string | undefined;
readonly accentColor: string | undefined;
readonly continuationGroupKey: string;
}) =>
(snapshot: ServerProviderDraft): ServerProvider => ({
...snapshot,
instanceId: input.instanceId,
driver: DRIVER_KIND,
...(input.displayName ? { displayName: input.displayName } : {}),
...(input.accentColor ? { accentColor: input.accentColor } : {}),
continuation: { groupKey: input.continuationGroupKey },
});
export const CursorDriver: ProviderDriver<CursorSettings, CursorDriverEnv> = {
driverKind: DRIVER_KIND,
metadata: {
displayName: "Cursor",
supportsMultipleInstances: true,
},
configSchema: CursorSettings,
defaultConfig: (): CursorSettings => Schema.decodeSync(CursorSettings)({}),
create: ({ instanceId, displayName, accentColor, environment, enabled, config }) =>
Effect.gen(function* () {
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const eventLoggers = yield* ProviderEventLoggers;
const processEnv = mergeProviderInstanceEnvironment(environment);
const continuationIdentity = defaultProviderContinuationIdentity({
driverKind: DRIVER_KIND,
instanceId,
});
const stampIdentity = withInstanceIdentity({
instanceId,
displayName,
accentColor,
continuationGroupKey: continuationIdentity.continuationKey,
});
const effectiveConfig = { ...config, enabled } satisfies CursorSettings;
const adapter = yield* makeCursorAdapter(effectiveConfig, {
environment: processEnv,
...(eventLoggers.native ? { nativeEventLogger: eventLoggers.native } : {}),
instanceId,
});
const textGeneration = yield* makeCursorTextGeneration(effectiveConfig, processEnv);
const checkProvider = checkCursorProviderStatus(effectiveConfig, processEnv).pipe(
Effect.map(stampIdentity),
Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
Effect.provideService(FileSystem.FileSystem, fileSystem),
Effect.provideService(Path.Path, path),
);
const snapshot = yield* makeManagedServerProvider<CursorSettings>({
getSettings: Effect.succeed(effectiveConfig),
streamSettings: Stream.never,
haveSettingsChanged: () => false,
initialSnapshot: (settings) => stampIdentity(buildInitialCursorProviderSnapshot(settings)),
checkProvider,
// Preserve the background ACP model-capability probe that used to
// live on `CursorProviderLive`. Only fires when the snapshot reports
// an authenticated, enabled provider with at least one non-custom
// model whose capabilities haven't been captured yet.
enrichSnapshot: ({ settings, snapshot: currentSnapshot, publishSnapshot }) =>
enrichCursorSnapshot({
settings,
environment: processEnv,
snapshot: currentSnapshot,
publishSnapshot,
stampIdentity,
}).pipe(Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner)),
refreshInterval: SNAPSHOT_REFRESH_INTERVAL,
}).pipe(
Effect.mapError(
(cause) =>
new ProviderDriverError({
driver: DRIVER_KIND,
instanceId,
detail: `Failed to build Cursor snapshot: ${cause.message ?? String(cause)}`,
cause,
}),
),
);
return {
instanceId,
driverKind: DRIVER_KIND,
continuationIdentity,
displayName,
accentColor,
enabled,
snapshot,
adapter,
textGeneration,
} satisfies ProviderInstance;
}),
};
@@ -0,0 +1,135 @@
/**
* OpenCodeDriver — `ProviderDriver` for the OpenCode runtime.
*
* Mirrors the Codex / Claude drivers: a plain value whose `create()`
* bundles `snapshot` / `adapter` / `textGeneration` closures over the
* per-instance `OpenCodeSettings`.
*
* Two instances with different `serverUrl`s therefore talk to independent
* OpenCode servers; when no `serverUrl` is set, the adapter + text-generation
* shares spin up their own scoped child processes, and those child
* processes are released when the registry scope closes.
*
* @module provider/Drivers/OpenCodeDriver
*/
import { OpenCodeSettings, ProviderDriverKind, type ServerProvider } from "@t3tools/contracts";
import { Duration, Effect, FileSystem, Path, Schema, Stream } from "effect";
import { ChildProcessSpawner } from "effect/unstable/process";
import { makeOpenCodeTextGeneration } from "../../textGeneration/OpenCodeTextGeneration.ts";
import { ServerConfig } from "../../config.ts";
import { ProviderDriverError } from "../Errors.ts";
import { makeOpenCodeAdapter } from "../Layers/OpenCodeAdapter.ts";
import {
checkOpenCodeProviderStatus,
makePendingOpenCodeProvider,
} from "../Layers/OpenCodeProvider.ts";
import { ProviderEventLoggers } from "../Layers/ProviderEventLoggers.ts";
import { makeManagedServerProvider } from "../makeManagedServerProvider.ts";
import { OpenCodeRuntime } from "../opencodeRuntime.ts";
import {
defaultProviderContinuationIdentity,
type ProviderDriver,
type ProviderInstance,
} from "../ProviderDriver.ts";
import type { ServerProviderDraft } from "../providerSnapshot.ts";
import { mergeProviderInstanceEnvironment } from "../ProviderInstanceEnvironment.ts";
const DRIVER_KIND = ProviderDriverKind.make("opencode");
const SNAPSHOT_REFRESH_INTERVAL = Duration.minutes(5);
export type OpenCodeDriverEnv =
| ChildProcessSpawner.ChildProcessSpawner
| FileSystem.FileSystem
| OpenCodeRuntime
| Path.Path
| ProviderEventLoggers
| ServerConfig;
const withInstanceIdentity =
(input: {
readonly instanceId: ProviderInstance["instanceId"];
readonly displayName: string | undefined;
readonly accentColor: string | undefined;
readonly continuationGroupKey: string;
}) =>
(snapshot: ServerProviderDraft): ServerProvider => ({
...snapshot,
instanceId: input.instanceId,
driver: DRIVER_KIND,
...(input.displayName ? { displayName: input.displayName } : {}),
...(input.accentColor ? { accentColor: input.accentColor } : {}),
continuation: { groupKey: input.continuationGroupKey },
});
export const OpenCodeDriver: ProviderDriver<OpenCodeSettings, OpenCodeDriverEnv> = {
driverKind: DRIVER_KIND,
metadata: {
displayName: "OpenCode",
supportsMultipleInstances: true,
},
configSchema: OpenCodeSettings,
defaultConfig: (): OpenCodeSettings => Schema.decodeSync(OpenCodeSettings)({}),
create: ({ instanceId, displayName, accentColor, environment, enabled, config }) =>
Effect.gen(function* () {
const openCodeRuntime = yield* OpenCodeRuntime;
const serverConfig = yield* ServerConfig;
const eventLoggers = yield* ProviderEventLoggers;
const processEnv = mergeProviderInstanceEnvironment(environment);
const continuationIdentity = defaultProviderContinuationIdentity({
driverKind: DRIVER_KIND,
instanceId,
});
const stampIdentity = withInstanceIdentity({
instanceId,
displayName,
accentColor,
continuationGroupKey: continuationIdentity.continuationKey,
});
const effectiveConfig = { ...config, enabled } satisfies OpenCodeSettings;
const adapter = yield* makeOpenCodeAdapter(effectiveConfig, {
instanceId,
environment: processEnv,
...(eventLoggers.native ? { nativeEventLogger: eventLoggers.native } : {}),
});
const textGeneration = yield* makeOpenCodeTextGeneration(effectiveConfig, processEnv);
const checkProvider = checkOpenCodeProviderStatus(
effectiveConfig,
serverConfig.cwd,
processEnv,
).pipe(Effect.map(stampIdentity), Effect.provideService(OpenCodeRuntime, openCodeRuntime));
const snapshot = yield* makeManagedServerProvider<OpenCodeSettings>({
getSettings: Effect.succeed(effectiveConfig),
streamSettings: Stream.never,
haveSettingsChanged: () => false,
initialSnapshot: (settings) => stampIdentity(makePendingOpenCodeProvider(settings)),
checkProvider,
refreshInterval: SNAPSHOT_REFRESH_INTERVAL,
}).pipe(
Effect.mapError(
(cause) =>
new ProviderDriverError({
driver: DRIVER_KIND,
instanceId,
detail: `Failed to build OpenCode snapshot: ${cause.message ?? String(cause)}`,
cause,
}),
),
);
return {
instanceId,
driverKind: DRIVER_KIND,
continuationIdentity,
displayName,
accentColor,
enabled,
snapshot,
adapter,
textGeneration,
} satisfies ProviderInstance;
}),
};
+41
View File
@@ -116,6 +116,46 @@ export class ProviderUnsupportedError extends Schema.TaggedErrorClass<ProviderUn
}
}
/**
* ProviderInstanceNotFoundError - Lookup against the instance registry failed.
*
* Distinct from `ProviderUnsupportedError`: the driver is registered, but no
* instance with the requested id has been bootstrapped — typically because
* the persisted instance id refers to an instance the user removed from
* settings, or because routing is asked for an instance before the registry
* has finished its first reload.
*/
export class ProviderInstanceNotFoundError extends Schema.TaggedErrorClass<ProviderInstanceNotFoundError>()(
"ProviderInstanceNotFoundError",
{
instanceId: Schema.String,
cause: Schema.optional(Schema.Defect),
},
) {
override get message(): string {
return `No provider instance bound to id '${this.instanceId}'`;
}
}
/**
* ProviderDriverError - A driver `create` call failed before producing an
* instance. Surfaced to the registry, which marks the offending entry as
* an "unavailable" shadow snapshot rather than crashing the server.
*/
export class ProviderDriverError extends Schema.TaggedErrorClass<ProviderDriverError>()(
"ProviderDriverError",
{
driver: Schema.String,
instanceId: Schema.String,
detail: Schema.String,
cause: Schema.optional(Schema.Defect),
},
) {
override get message(): string {
return `Provider driver '${this.driver}' failed to create instance '${this.instanceId}': ${this.detail}`;
}
}
/**
* ProviderSessionNotFoundError - Provider-facing session not found.
*/
@@ -157,6 +197,7 @@ export type ProviderAdapterError =
export type ProviderServiceError =
| ProviderValidationError
| ProviderUnsupportedError
| ProviderInstanceNotFoundError
| ProviderSessionNotFoundError
| ProviderSessionDirectoryPersistenceError
| ProviderAdapterError
@@ -12,21 +12,29 @@ import type {
} from "@anthropic-ai/claude-agent-sdk";
import {
ApprovalRequestId,
ClaudeSettings,
ProviderDriverKind,
ProviderItemId,
ProviderRuntimeEvent,
type RuntimeMode,
ThreadId,
ProviderInstanceId,
} from "@t3tools/contracts";
import { createModelSelection } from "@t3tools/shared/model";
import { assert, describe, it } from "@effect/vitest";
import { Effect, Fiber, Layer, Random, Stream } from "effect";
import { Context, Effect, Fiber, Layer, Random, Schema, Stream } from "effect";
import { attachmentRelativePath } from "../../attachmentStore.ts";
import { ServerConfig } from "../../config.ts";
import { ServerSettingsService } from "../../serverSettings.ts";
import { ProviderAdapterValidationError } from "../Errors.ts";
import { ClaudeAdapter } from "../Services/ClaudeAdapter.ts";
import { makeClaudeAdapterLive, type ClaudeAdapterLiveOptions } from "./ClaudeAdapter.ts";
import type { ClaudeAdapterShape } from "../Services/ClaudeAdapter.ts";
import { makeClaudeAdapter, type ClaudeAdapterLiveOptions } from "./ClaudeAdapter.ts";
// Test-local service tag so the rest of the file can keep using `yield* ClaudeAdapter`.
class ClaudeAdapter extends Context.Service<ClaudeAdapter, ClaudeAdapterShape>()(
"test/ClaudeAdapter",
) {}
class FakeClaudeQuery implements AsyncIterable<SDKMessage> {
private readonly queue: Array<SDKMessage> = [];
@@ -137,6 +145,8 @@ function makeHarness(config?: {
readonly nativeEventLogger?: ClaudeAdapterLiveOptions["nativeEventLogger"];
readonly cwd?: string;
readonly baseDir?: string;
readonly claudeConfig?: Partial<ClaudeSettings>;
readonly instanceId?: ProviderInstanceId;
}) {
const query = new FakeClaudeQuery();
let createInput:
@@ -147,6 +157,7 @@ function makeHarness(config?: {
| undefined;
const adapterOptions: ClaudeAdapterLiveOptions = {
...(config?.instanceId ? { instanceId: config.instanceId } : {}),
createQuery: (input) => {
createInput = input;
return query;
@@ -164,7 +175,13 @@ function makeHarness(config?: {
};
return {
layer: makeClaudeAdapterLive(adapterOptions).pipe(
layer: Layer.effect(
ClaudeAdapter,
Effect.gen(function* () {
const claudeConfig = Schema.decodeSync(ClaudeSettings)(config?.claudeConfig ?? {});
return yield* makeClaudeAdapter(claudeConfig, adapterOptions);
}),
).pipe(
Layer.provideMerge(
ServerConfig.layerTest(
config?.cwd ?? "/tmp/claude-adapter-test",
@@ -247,7 +264,11 @@ describe("ClaudeAdapterLive", () => {
return Effect.gen(function* () {
const adapter = yield* ClaudeAdapter;
const result = yield* adapter
.startSession({ threadId: THREAD_ID, provider: "codex", runtimeMode: "full-access" })
.startSession({
threadId: THREAD_ID,
provider: ProviderDriverKind.make("codex"),
runtimeMode: "full-access",
})
.pipe(Effect.result);
assert.equal(result._tag, "Failure");
@@ -257,7 +278,7 @@ describe("ClaudeAdapterLive", () => {
assert.deepEqual(
result.failure,
new ProviderAdapterValidationError({
provider: "claudeAgent",
provider: ProviderDriverKind.make("claudeAgent"),
operation: "startSession",
issue: "Expected provider 'claudeAgent' but received 'codex'.",
}),
@@ -274,7 +295,7 @@ describe("ClaudeAdapterLive", () => {
const adapter = yield* ClaudeAdapter;
yield* adapter.startSession({
threadId: THREAD_ID,
provider: "claudeAgent",
provider: ProviderDriverKind.make("claudeAgent"),
runtimeMode: "full-access",
});
@@ -294,7 +315,7 @@ describe("ClaudeAdapterLive", () => {
const adapter = yield* ClaudeAdapter;
yield* adapter.startSession({
threadId: THREAD_ID,
provider: "claudeAgent",
provider: ProviderDriverKind.make("claudeAgent"),
runtimeMode: "approval-required",
});
@@ -314,7 +335,7 @@ describe("ClaudeAdapterLive", () => {
const adapter = yield* ClaudeAdapter;
yield* adapter.startSession({
threadId: THREAD_ID,
provider: "claudeAgent",
provider: ProviderDriverKind.make("claudeAgent"),
runtimeMode: "full-access",
});
@@ -333,10 +354,12 @@ describe("ClaudeAdapterLive", () => {
const adapter = yield* ClaudeAdapter;
yield* adapter.startSession({
threadId: THREAD_ID,
provider: "claudeAgent",
modelSelection: createModelSelection("claudeAgent", "claude-opus-4-6", [
{ id: "effort", value: "max" },
]),
provider: ProviderDriverKind.make("claudeAgent"),
modelSelection: createModelSelection(
ProviderInstanceId.make("claudeAgent"),
"claude-opus-4-6",
[{ id: "effort", value: "max" }],
),
runtimeMode: "full-access",
});
@@ -348,15 +371,37 @@ describe("ClaudeAdapterLive", () => {
);
});
it.effect("runs Claude SDK sessions with the configured Claude HOME", () => {
const harness = makeHarness({ claudeConfig: { homePath: "~/.claude-work" } });
return Effect.gen(function* () {
const adapter = yield* ClaudeAdapter;
yield* adapter.startSession({
threadId: THREAD_ID,
provider: ProviderDriverKind.make("claudeAgent"),
modelSelection: createModelSelection(
ProviderInstanceId.make("claudeAgent"),
"claude-opus-4-6",
),
runtimeMode: "full-access",
});
const createInput = harness.getLastCreateQueryInput();
assert.equal(createInput?.options.env?.HOME, path.join(os.homedir(), ".claude-work"));
}).pipe(
Effect.provideService(Random.Random, makeDeterministicRandomService()),
Effect.provide(harness.layer),
);
});
it.effect("maps the Claude Opus 4.7 default effort to the SDK-supported max value", () => {
const harness = makeHarness();
return Effect.gen(function* () {
const adapter = yield* ClaudeAdapter;
yield* adapter.startSession({
threadId: THREAD_ID,
provider: "claudeAgent",
provider: ProviderDriverKind.make("claudeAgent"),
modelSelection: {
provider: "claudeAgent",
instanceId: ProviderInstanceId.make("claudeAgent"),
model: "claude-opus-4-7",
},
runtimeMode: "full-access",
@@ -376,10 +421,12 @@ describe("ClaudeAdapterLive", () => {
const adapter = yield* ClaudeAdapter;
yield* adapter.startSession({
threadId: THREAD_ID,
provider: "claudeAgent",
modelSelection: createModelSelection("claudeAgent", "claude-opus-4-7", [
{ id: "effort", value: "xhigh" },
]),
provider: ProviderDriverKind.make("claudeAgent"),
modelSelection: createModelSelection(
ProviderInstanceId.make("claudeAgent"),
"claude-opus-4-7",
[{ id: "effort", value: "xhigh" }],
),
runtimeMode: "full-access",
});
@@ -397,10 +444,12 @@ describe("ClaudeAdapterLive", () => {
const adapter = yield* ClaudeAdapter;
yield* adapter.startSession({
threadId: THREAD_ID,
provider: "claudeAgent",
modelSelection: createModelSelection("claudeAgent", "claude-sonnet-4-6", [
{ id: "effort", value: "max" },
]),
provider: ProviderDriverKind.make("claudeAgent"),
modelSelection: createModelSelection(
ProviderInstanceId.make("claudeAgent"),
"claude-sonnet-4-6",
[{ id: "effort", value: "max" }],
),
runtimeMode: "full-access",
});
@@ -418,10 +467,12 @@ describe("ClaudeAdapterLive", () => {
const adapter = yield* ClaudeAdapter;
yield* adapter.startSession({
threadId: THREAD_ID,
provider: "claudeAgent",
modelSelection: createModelSelection("claudeAgent", "claude-haiku-4-5", [
{ id: "effort", value: "high" },
]),
provider: ProviderDriverKind.make("claudeAgent"),
modelSelection: createModelSelection(
ProviderInstanceId.make("claudeAgent"),
"claude-haiku-4-5",
[{ id: "effort", value: "high" }],
),
runtimeMode: "full-access",
});
@@ -439,10 +490,12 @@ describe("ClaudeAdapterLive", () => {
const adapter = yield* ClaudeAdapter;
yield* adapter.startSession({
threadId: THREAD_ID,
provider: "claudeAgent",
modelSelection: createModelSelection("claudeAgent", "claude-haiku-4-5", [
{ id: "thinking", value: false },
]),
provider: ProviderDriverKind.make("claudeAgent"),
modelSelection: createModelSelection(
ProviderInstanceId.make("claudeAgent"),
"claude-haiku-4-5",
[{ id: "thinking", value: false }],
),
runtimeMode: "full-access",
});
@@ -462,10 +515,12 @@ describe("ClaudeAdapterLive", () => {
const adapter = yield* ClaudeAdapter;
yield* adapter.startSession({
threadId: THREAD_ID,
provider: "claudeAgent",
modelSelection: createModelSelection("claudeAgent", "claude-sonnet-4-6", [
{ id: "thinking", value: false },
]),
provider: ProviderDriverKind.make("claudeAgent"),
modelSelection: createModelSelection(
ProviderInstanceId.make("claudeAgent"),
"claude-sonnet-4-6",
[{ id: "thinking", value: false }],
),
runtimeMode: "full-access",
});
@@ -483,10 +538,12 @@ describe("ClaudeAdapterLive", () => {
const adapter = yield* ClaudeAdapter;
yield* adapter.startSession({
threadId: THREAD_ID,
provider: "claudeAgent",
modelSelection: createModelSelection("claudeAgent", "claude-opus-4-6", [
{ id: "fastMode", value: true },
]),
provider: ProviderDriverKind.make("claudeAgent"),
modelSelection: createModelSelection(
ProviderInstanceId.make("claudeAgent"),
"claude-opus-4-6",
[{ id: "fastMode", value: true }],
),
runtimeMode: "full-access",
});
@@ -506,10 +563,12 @@ describe("ClaudeAdapterLive", () => {
const adapter = yield* ClaudeAdapter;
yield* adapter.startSession({
threadId: THREAD_ID,
provider: "claudeAgent",
modelSelection: createModelSelection("claudeAgent", "claude-sonnet-4-6", [
{ id: "fastMode", value: true },
]),
provider: ProviderDriverKind.make("claudeAgent"),
modelSelection: createModelSelection(
ProviderInstanceId.make("claudeAgent"),
"claude-sonnet-4-6",
[{ id: "fastMode", value: true }],
),
runtimeMode: "full-access",
});
@@ -527,10 +586,12 @@ describe("ClaudeAdapterLive", () => {
const adapter = yield* ClaudeAdapter;
const session = yield* adapter.startSession({
threadId: THREAD_ID,
provider: "claudeAgent",
modelSelection: createModelSelection("claudeAgent", "claude-sonnet-4-6", [
{ id: "effort", value: "ultrathink" },
]),
provider: ProviderDriverKind.make("claudeAgent"),
modelSelection: createModelSelection(
ProviderInstanceId.make("claudeAgent"),
"claude-sonnet-4-6",
[{ id: "effort", value: "ultrathink" }],
),
runtimeMode: "full-access",
});
@@ -538,9 +599,11 @@ describe("ClaudeAdapterLive", () => {
threadId: session.threadId,
input: "Investigate the edge cases",
attachments: [],
modelSelection: createModelSelection("claudeAgent", "claude-sonnet-4-6", [
{ id: "effort", value: "ultrathink" },
]),
modelSelection: createModelSelection(
ProviderInstanceId.make("claudeAgent"),
"claude-sonnet-4-6",
[{ id: "effort", value: "ultrathink" }],
),
});
const createInput = harness.getLastCreateQueryInput();
@@ -585,7 +648,7 @@ describe("ClaudeAdapterLive", () => {
const session = yield* adapter.startSession({
threadId: THREAD_ID,
provider: "claudeAgent",
provider: ProviderDriverKind.make("claudeAgent"),
runtimeMode: "full-access",
});
@@ -630,9 +693,9 @@ describe("ClaudeAdapterLive", () => {
const session = yield* adapter.startSession({
threadId: THREAD_ID,
provider: "claudeAgent",
provider: ProviderDriverKind.make("claudeAgent"),
modelSelection: {
provider: "claudeAgent",
instanceId: ProviderInstanceId.make("claudeAgent"),
model: "claude-sonnet-4-5",
},
runtimeMode: "full-access",
@@ -807,7 +870,7 @@ describe("ClaudeAdapterLive", () => {
const session = yield* adapter.startSession({
threadId: THREAD_ID,
provider: "claudeAgent",
provider: ProviderDriverKind.make("claudeAgent"),
runtimeMode: "full-access",
});
@@ -986,7 +1049,7 @@ describe("ClaudeAdapterLive", () => {
const session = yield* adapter.startSession({
threadId: THREAD_ID,
provider: "claudeAgent",
provider: ProviderDriverKind.make("claudeAgent"),
runtimeMode: "full-access",
});
@@ -1077,7 +1140,7 @@ describe("ClaudeAdapterLive", () => {
const session = yield* adapter.startSession({
threadId: THREAD_ID,
provider: "claudeAgent",
provider: ProviderDriverKind.make("claudeAgent"),
runtimeMode: "full-access",
});
@@ -1153,7 +1216,7 @@ describe("ClaudeAdapterLive", () => {
const session = yield* adapter.startSession({
threadId: THREAD_ID,
provider: "claudeAgent",
provider: ProviderDriverKind.make("claudeAgent"),
runtimeMode: "full-access",
});
@@ -1219,7 +1282,7 @@ describe("ClaudeAdapterLive", () => {
yield* adapter.startSession({
threadId: THREAD_ID,
provider: "claudeAgent",
provider: ProviderDriverKind.make("claudeAgent"),
runtimeMode: "full-access",
});
@@ -1270,13 +1333,19 @@ describe("ClaudeAdapterLive", () => {
it.effect("closes the previous session before replacing an existing thread session", () => {
const queries: FakeClaudeQuery[] = [];
const layer = makeClaudeAdapterLive({
createQuery: () => {
const query = new FakeClaudeQuery();
queries.push(query);
return query;
},
}).pipe(
const layer = Layer.effect(
ClaudeAdapter,
Effect.gen(function* () {
const claudeConfig = Schema.decodeSync(ClaudeSettings)({});
return yield* makeClaudeAdapter(claudeConfig, {
createQuery: () => {
const query = new FakeClaudeQuery();
queries.push(query);
return query;
},
});
}),
).pipe(
Layer.provideMerge(ServerConfig.layerTest("/tmp/claude-adapter-test", "/tmp")),
Layer.provideMerge(ServerSettingsService.layerTest()),
Layer.provideMerge(NodeServices.layer),
@@ -1292,13 +1361,13 @@ describe("ClaudeAdapterLive", () => {
const firstSession = yield* adapter.startSession({
threadId: THREAD_ID,
provider: "claudeAgent",
provider: ProviderDriverKind.make("claudeAgent"),
runtimeMode: "full-access",
});
const secondSession = yield* adapter.startSession({
threadId: THREAD_ID,
provider: "claudeAgent",
provider: ProviderDriverKind.make("claudeAgent"),
runtimeMode: "full-access",
resumeCursor: firstSession.resumeCursor,
});
@@ -1347,21 +1416,27 @@ describe("ClaudeAdapterLive", () => {
let promptConsumerError: unknown = undefined;
const layer = makeClaudeAdapterLive({
createQuery: (input) => {
// Simulate the SDK consuming the prompt iterable
(async () => {
try {
for await (const _message of input.prompt) {
/* SDK processes user messages */
}
} catch (error) {
promptConsumerError = error;
}
})();
return query;
},
}).pipe(
const layer = Layer.effect(
ClaudeAdapter,
Effect.gen(function* () {
const claudeConfig = Schema.decodeSync(ClaudeSettings)({});
return yield* makeClaudeAdapter(claudeConfig, {
createQuery: (input) => {
// Simulate the SDK consuming the prompt iterable
(async () => {
try {
for await (const _message of input.prompt) {
/* SDK processes user messages */
}
} catch (error) {
promptConsumerError = error;
}
})();
return query;
},
});
}),
).pipe(
Layer.provideMerge(ServerConfig.layerTest("/tmp/claude-adapter-test", "/tmp")),
Layer.provideMerge(ServerSettingsService.layerTest()),
Layer.provideMerge(NodeServices.layer),
@@ -1379,7 +1454,7 @@ describe("ClaudeAdapterLive", () => {
yield* adapter.startSession({
threadId: THREAD_ID,
provider: "claudeAgent",
provider: ProviderDriverKind.make("claudeAgent"),
runtimeMode: "full-access",
});
@@ -1416,7 +1491,7 @@ describe("ClaudeAdapterLive", () => {
yield* adapter.startSession({
threadId: THREAD_ID,
provider: "claudeAgent",
provider: ProviderDriverKind.make("claudeAgent"),
runtimeMode: "full-access",
});
@@ -1463,7 +1538,7 @@ describe("ClaudeAdapterLive", () => {
yield* adapter.startSession({
threadId: THREAD_ID,
provider: "claudeAgent",
provider: ProviderDriverKind.make("claudeAgent"),
runtimeMode: "full-access",
});
@@ -1517,7 +1592,7 @@ describe("ClaudeAdapterLive", () => {
yield* adapter.startSession({
threadId: THREAD_ID,
provider: "claudeAgent",
provider: ProviderDriverKind.make("claudeAgent"),
runtimeMode: "full-access",
});
@@ -1584,7 +1659,7 @@ describe("ClaudeAdapterLive", () => {
yield* adapter.startSession({
threadId: THREAD_ID,
provider: "claudeAgent",
provider: ProviderDriverKind.make("claudeAgent"),
runtimeMode: "full-access",
});
@@ -1649,7 +1724,7 @@ describe("ClaudeAdapterLive", () => {
yield* adapter.startSession({
threadId: THREAD_ID,
provider: "claudeAgent",
provider: ProviderDriverKind.make("claudeAgent"),
runtimeMode: "full-access",
});
@@ -1730,7 +1805,7 @@ describe("ClaudeAdapterLive", () => {
const session = yield* adapter.startSession({
threadId: THREAD_ID,
provider: "claudeAgent",
provider: ProviderDriverKind.make("claudeAgent"),
runtimeMode: "full-access",
});
@@ -1821,7 +1896,7 @@ describe("ClaudeAdapterLive", () => {
const session = yield* adapter.startSession({
threadId: THREAD_ID,
provider: "claudeAgent",
provider: ProviderDriverKind.make("claudeAgent"),
runtimeMode: "full-access",
});
@@ -1987,7 +2062,7 @@ describe("ClaudeAdapterLive", () => {
const session = yield* adapter.startSession({
threadId: THREAD_ID,
provider: "claudeAgent",
provider: ProviderDriverKind.make("claudeAgent"),
runtimeMode: "full-access",
});
@@ -2056,7 +2131,7 @@ describe("ClaudeAdapterLive", () => {
const session = yield* adapter.startSession({
threadId: THREAD_ID,
provider: "claudeAgent",
provider: ProviderDriverKind.make("claudeAgent"),
runtimeMode: "full-access",
});
@@ -2278,7 +2353,7 @@ describe("ClaudeAdapterLive", () => {
const session = yield* adapter.startSession({
threadId: THREAD_ID,
provider: "claudeAgent",
provider: ProviderDriverKind.make("claudeAgent"),
runtimeMode: "full-access",
});
assert.equal(session.threadId, THREAD_ID);
@@ -2351,7 +2426,7 @@ describe("ClaudeAdapterLive", () => {
const session = yield* adapter.startSession({
threadId: THREAD_ID,
provider: "claudeAgent",
provider: ProviderDriverKind.make("claudeAgent"),
runtimeMode: "approval-required",
});
@@ -2460,7 +2535,7 @@ describe("ClaudeAdapterLive", () => {
const session = yield* adapter.startSession({
threadId: THREAD_ID,
provider: "claudeAgent",
provider: ProviderDriverKind.make("claudeAgent"),
runtimeMode: "approval-required",
});
@@ -2533,7 +2608,7 @@ describe("ClaudeAdapterLive", () => {
const session = yield* adapter.startSession({
threadId: RESUME_THREAD_ID,
provider: "claudeAgent",
provider: ProviderDriverKind.make("claudeAgent"),
resumeCursor: {
threadId: "resume-thread-1",
resume: "550e8400-e29b-41d4-a716-446655440000",
@@ -2561,6 +2636,96 @@ describe("ClaudeAdapterLive", () => {
);
});
it.effect("preserves durable resume ids across Claude resume hooks", () => {
const harness = makeHarness();
return Effect.gen(function* () {
const adapter = yield* ClaudeAdapter;
const durableSessionId = "550e8400-e29b-41d4-a716-446655440000";
const transientHookSessionId = "7368d0c7-40a3-4d8a-bcc1-ac80c49f2719";
const runtimeEventsFiber = yield* Stream.take(adapter.streamEvents, 7).pipe(
Stream.runCollect,
Effect.forkChild,
);
yield* adapter.startSession({
threadId: RESUME_THREAD_ID,
provider: ProviderDriverKind.make("claudeAgent"),
resumeCursor: {
threadId: RESUME_THREAD_ID,
resume: durableSessionId,
resumeSessionAt: "assistant-99",
turnCount: 3,
},
runtimeMode: "full-access",
});
harness.query.emit({
type: "system",
subtype: "hook_started",
hook_id: "resume-hook-1",
hook_name: "SessionStart:resume",
hook_event: "SessionStart",
session_id: transientHookSessionId,
uuid: "resume-hook-started",
} as unknown as SDKMessage);
harness.query.emit({
type: "system",
subtype: "hook_response",
hook_id: "resume-hook-1",
hook_name: "SessionStart:resume",
hook_event: "SessionStart",
output: "",
stdout: "",
stderr: "",
outcome: "success",
session_id: transientHookSessionId,
uuid: "resume-hook-response",
} as unknown as SDKMessage);
harness.query.emit({
type: "system",
subtype: "init",
apiKeySource: "none",
claude_code_version: "test",
cwd: "/tmp/claude-adapter-test",
tools: [],
mcp_servers: [],
model: "claude-sonnet-4-5",
permissionMode: "bypassPermissions",
slash_commands: [],
output_style: "default",
skills: [],
plugins: [],
session_id: durableSessionId,
uuid: "resume-init",
} as unknown as SDKMessage);
const runtimeEvents = Array.from(yield* Fiber.join(runtimeEventsFiber));
const threadStartedEvents = runtimeEvents.filter((event) => event.type === "thread.started");
assert.equal(threadStartedEvents.length, 1);
const threadStarted = threadStartedEvents[0];
assert.equal(threadStarted?.type, "thread.started");
if (threadStarted?.type === "thread.started") {
assert.deepEqual(threadStarted.payload, {
providerThreadId: durableSessionId,
});
}
const activeSessions = yield* adapter.listSessions();
const resumeCursor = activeSessions[0]?.resumeCursor as
| {
readonly resume?: string;
}
| undefined;
assert.equal(resumeCursor?.resume, durableSessionId);
}).pipe(
Effect.provideService(Random.Random, makeDeterministicRandomService()),
Effect.provide(harness.layer),
);
});
it.effect("uses an app-generated Claude session id for fresh sessions", () => {
const harness = makeHarness();
return Effect.gen(function* () {
@@ -2568,7 +2733,7 @@ describe("ClaudeAdapterLive", () => {
const session = yield* adapter.startSession({
threadId: THREAD_ID,
provider: "claudeAgent",
provider: ProviderDriverKind.make("claudeAgent"),
runtimeMode: "full-access",
});
@@ -2602,7 +2767,7 @@ describe("ClaudeAdapterLive", () => {
const session = yield* adapter.startSession({
threadId: THREAD_ID,
provider: "claudeAgent",
provider: ProviderDriverKind.make("claudeAgent"),
runtimeMode: "full-access",
});
@@ -2682,14 +2847,14 @@ describe("ClaudeAdapterLive", () => {
const session = yield* adapter.startSession({
threadId: THREAD_ID,
provider: "claudeAgent",
provider: ProviderDriverKind.make("claudeAgent"),
runtimeMode: "full-access",
});
yield* adapter.sendTurn({
threadId: session.threadId,
input: "hello",
modelSelection: {
provider: "claudeAgent",
instanceId: ProviderInstanceId.make("claudeAgent"),
model: "claude-opus-4-6",
},
attachments: [],
@@ -2702,6 +2867,34 @@ describe("ClaudeAdapterLive", () => {
);
});
it.effect("updates model on sendTurn for the adapter's bound custom instance id", () => {
const customInstanceId = ProviderInstanceId.make("claude_openrouter");
const harness = makeHarness({ instanceId: customInstanceId });
return Effect.gen(function* () {
const adapter = yield* ClaudeAdapter;
const session = yield* adapter.startSession({
threadId: THREAD_ID,
provider: ProviderDriverKind.make("claudeAgent"),
runtimeMode: "full-access",
});
yield* adapter.sendTurn({
threadId: session.threadId,
input: "hello",
modelSelection: {
instanceId: customInstanceId,
model: "openai/gpt-5.5",
},
attachments: [],
});
assert.deepEqual(harness.query.setModelCalls, ["openai/gpt-5.5"]);
}).pipe(
Effect.provideService(Random.Random, makeDeterministicRandomService()),
Effect.provide(harness.layer),
);
});
it.effect(
"does not re-set the Claude model when the session already uses the same effective API model",
() => {
@@ -2709,13 +2902,13 @@ describe("ClaudeAdapterLive", () => {
return Effect.gen(function* () {
const adapter = yield* ClaudeAdapter;
const modelSelection = {
provider: "claudeAgent" as const,
instanceId: ProviderInstanceId.make("claudeAgent"),
model: "claude-opus-4-6",
};
const session = yield* adapter.startSession({
threadId: THREAD_ID,
provider: "claudeAgent",
provider: ProviderDriverKind.make("claudeAgent"),
modelSelection,
runtimeMode: "full-access",
});
@@ -2748,23 +2941,25 @@ describe("ClaudeAdapterLive", () => {
const session = yield* adapter.startSession({
threadId: THREAD_ID,
provider: "claudeAgent",
provider: ProviderDriverKind.make("claudeAgent"),
runtimeMode: "full-access",
});
yield* adapter.sendTurn({
threadId: session.threadId,
input: "hello",
modelSelection: createModelSelection("claudeAgent", "claude-opus-4-6", [
{ id: "contextWindow", value: "1m" },
]),
modelSelection: createModelSelection(
ProviderInstanceId.make("claudeAgent"),
"claude-opus-4-6",
[{ id: "contextWindow", value: "1m" }],
),
attachments: [],
});
yield* adapter.sendTurn({
threadId: session.threadId,
input: "hello again",
modelSelection: {
provider: "claudeAgent",
instanceId: ProviderInstanceId.make("claudeAgent"),
model: "claude-opus-4-6",
},
attachments: [],
@@ -2784,7 +2979,7 @@ describe("ClaudeAdapterLive", () => {
const session = yield* adapter.startSession({
threadId: THREAD_ID,
provider: "claudeAgent",
provider: ProviderDriverKind.make("claudeAgent"),
runtimeMode: "full-access",
});
yield* adapter.sendTurn({
@@ -2814,7 +3009,7 @@ describe("ClaudeAdapterLive", () => {
const session = yield* adapter.startSession({
threadId: THREAD_ID,
provider: "claudeAgent",
provider: ProviderDriverKind.make("claudeAgent"),
runtimeMode,
});
@@ -2866,7 +3061,7 @@ describe("ClaudeAdapterLive", () => {
const session = yield* adapter.startSession({
threadId: THREAD_ID,
provider: "claudeAgent",
provider: ProviderDriverKind.make("claudeAgent"),
runtimeMode: "full-access",
});
yield* adapter.sendTurn({
@@ -2889,7 +3084,7 @@ describe("ClaudeAdapterLive", () => {
const session = yield* adapter.startSession({
threadId: THREAD_ID,
provider: "claudeAgent",
provider: ProviderDriverKind.make("claudeAgent"),
runtimeMode: "full-access",
});
@@ -2955,7 +3150,7 @@ describe("ClaudeAdapterLive", () => {
const session = yield* adapter.startSession({
threadId: THREAD_ID,
provider: "claudeAgent",
provider: ProviderDriverKind.make("claudeAgent"),
runtimeMode: "full-access",
});
@@ -3027,7 +3222,7 @@ describe("ClaudeAdapterLive", () => {
// Start session in approval-required mode so canUseTool fires.
const session = yield* adapter.startSession({
threadId: THREAD_ID,
provider: "claudeAgent",
provider: ProviderDriverKind.make("claudeAgent"),
runtimeMode: "approval-required",
});
@@ -3101,6 +3296,9 @@ describe("ClaudeAdapterLive", () => {
assert.equal(typeof requestId, "string");
assert.equal(requestedEvent.value.payload.questions.length, 1);
assert.equal(requestedEvent.value.payload.questions[0]?.question, "Which framework?");
// Regression for #2388: `id` must equal the full question text so the
// UI's draft-answer key matches what the SDK looks up downstream.
assert.equal(requestedEvent.value.payload.questions[0]?.id, "Which framework?");
assert.deepEqual(requestedEvent.value.providerRefs, {
providerItemId: ProviderItemId.make("tool-ask-1"),
});
@@ -3135,6 +3333,34 @@ describe("ClaudeAdapterLive", () => {
assert.deepEqual(updatedInput.answers, { "Which framework?": "React" });
// Original questions should be passed through.
assert.deepEqual(updatedInput.questions, askInput.questions);
// Compatibility check for #2388: the answers shape we hand to the SDK
// must produce a non-empty rendered tool_result on BOTH SDK iteration
// patterns we have seen, so we don't regress the issue and we don't
// break users still on the older Claude CLI.
const sdkAnswers = updatedInput.answers as Record<string, unknown>;
const sdkQuestions = updatedInput.questions as ReadonlyArray<{
readonly question: string;
}>;
// Claude CLI 2.1.119 — key-agnostic Object.entries iteration. Any key
// works here, but it must at least round-trip into a non-empty string.
const v119Rendered = Object.entries(sdkAnswers)
.map(([key, value]) => `"${key}"="${String(value)}"`)
.join(", ");
assert.equal(v119Rendered, '"Which framework?"="React"');
// Claude CLI 2.1.121 — lookup by full question text. This is the path
// that regressed in #2388 when the answers were keyed by `header`.
const v121Rendered = sdkQuestions
.map(({ question }) => {
const answer = sdkAnswers[question];
return answer === undefined ? null : `"${question}"="${String(answer)}"`;
})
.filter((entry): entry is string => entry !== null)
.join(", ");
assert.notEqual(v121Rendered, "", "Expected non-empty SDK 2.1.121 tool_result (#2388)");
assert.equal(v121Rendered, '"Which framework?"="React"');
}).pipe(
Effect.provideService(Random.Random, makeDeterministicRandomService()),
Effect.provide(harness.layer),
@@ -3150,7 +3376,7 @@ describe("ClaudeAdapterLive", () => {
// AskUserQuestion should still go through the user-input flow.
const session = yield* adapter.startSession({
threadId: THREAD_ID,
provider: "claudeAgent",
provider: ProviderDriverKind.make("claudeAgent"),
runtimeMode: "full-access",
});
@@ -3216,7 +3442,7 @@ describe("ClaudeAdapterLive", () => {
const session = yield* adapter.startSession({
threadId: THREAD_ID,
provider: "claudeAgent",
provider: ProviderDriverKind.make("claudeAgent"),
runtimeMode: "approval-required",
});
@@ -3303,7 +3529,7 @@ describe("ClaudeAdapterLive", () => {
const session = yield* adapter.startSession({
threadId: THREAD_ID,
provider: "claudeAgent",
provider: ProviderDriverKind.make("claudeAgent"),
runtimeMode: "full-access",
});
const turn = yield* adapter.sendTurn({
@@ -24,8 +24,11 @@ import {
ApprovalRequestId,
type CanonicalItemType,
type CanonicalRequestType,
type ClaudeSettings,
EventId,
type ProviderApprovalDecision,
ProviderDriverKind,
ProviderInstanceId,
ProviderItemId,
type ProviderRuntimeEvent,
type ProviderRuntimeTurnStatus,
@@ -56,7 +59,7 @@ import {
Exit,
FileSystem,
Fiber,
Layer,
Path,
Queue,
Random,
Ref,
@@ -65,7 +68,7 @@ import {
import { resolveAttachmentPath } from "../../attachmentStore.ts";
import { ServerConfig } from "../../config.ts";
import { ServerSettingsService } from "../../serverSettings.ts";
import { makeClaudeEnvironment } from "../Drivers/ClaudeHome.ts";
import {
getClaudeModelCapabilities,
normalizeClaudeCliEffort,
@@ -80,10 +83,10 @@ import {
ProviderAdapterValidationError,
type ProviderAdapterError,
} from "../Errors.ts";
import { ClaudeAdapter, type ClaudeAdapterShape } from "../Services/ClaudeAdapter.ts";
import { type ClaudeAdapterShape } from "../Services/ClaudeAdapter.ts";
import { type EventNdjsonLogger, makeEventNdjsonLogger } from "./EventNdjsonLogger.ts";
const PROVIDER = "claudeAgent" as const;
const PROVIDER = ProviderDriverKind.make("claudeAgent");
type ClaudeTextStreamKind = Extract<RuntimeContentStreamKind, "assistant_text" | "reasoning_text">;
type ClaudeToolResultStreamKind = Extract<
RuntimeContentStreamKind,
@@ -182,6 +185,8 @@ interface ClaudeQueryRuntime extends AsyncIterable<SDKMessage> {
}
export interface ClaudeAdapterLiveOptions {
readonly instanceId?: ProviderInstanceId;
readonly environment?: NodeJS.ProcessEnv;
readonly createQuery?: (input: {
readonly prompt: AsyncIterable<SDKUserMessage>;
readonly options: ClaudeQueryOptions;
@@ -198,6 +203,18 @@ function isSyntheticClaudeThreadId(value: string): boolean {
return value.startsWith("claude-thread-");
}
function hasDurableClaudeSessionId(message: SDKMessage): boolean {
if (message.type !== "system") {
return true;
}
return (
message.subtype !== "hook_started" &&
message.subtype !== "hook_progress" &&
message.subtype !== "hook_response"
);
}
function toMessage(cause: unknown, fallback: string): string {
if (cause instanceof Error && cause.message.length > 0) {
return cause.message;
@@ -553,13 +570,16 @@ const CLAUDE_SETTING_SOURCES = [
"local",
] as const satisfies ReadonlyArray<SettingSource>;
function buildPromptText(input: ProviderSendTurnInput): string {
function buildPromptText(
input: ProviderSendTurnInput,
boundInstanceId: ProviderInstanceId,
): string {
const rawEffort =
input.modelSelection?.provider === "claudeAgent"
input.modelSelection?.instanceId === boundInstanceId
? getModelSelectionStringOptionValue(input.modelSelection, "effort")
: null;
const claudeModel =
input.modelSelection?.provider === "claudeAgent" ? input.modelSelection.model : undefined;
input.modelSelection?.instanceId === boundInstanceId ? input.modelSelection.model : undefined;
const caps = getClaudeModelCapabilities(claudeModel);
const promptEffort = resolvePromptInjectedEffort(caps, rawEffort);
@@ -599,9 +619,10 @@ const buildUserMessageEffect = Effect.fn("buildUserMessageEffect")(function* (
dependencies: {
readonly fileSystem: FileSystem.FileSystem;
readonly attachmentsDir: string;
readonly boundInstanceId: ProviderInstanceId;
},
) {
const text = buildPromptText(input);
const text = buildPromptText(input, dependencies.boundInstanceId);
const sdkContent: Array<Record<string, unknown>> = [];
if (text.length > 0) {
@@ -951,11 +972,17 @@ function sdkNativeItemId(message: SDKMessage): string | undefined {
return undefined;
}
const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
claudeSettings: ClaudeSettings,
options?: ClaudeAdapterLiveOptions,
) {
const boundInstanceId = options?.instanceId ?? ProviderInstanceId.make("claudeAgent");
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const serverConfig = yield* ServerConfig;
const claudeEnvironment = yield* makeClaudeEnvironment(claudeSettings, options?.environment).pipe(
Effect.provideService(Path.Path, path),
);
const nativeEventLogger =
options?.nativeEventLogger ??
(options?.nativeEventLogPath !== undefined
@@ -977,7 +1004,6 @@ const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
const sessions = new Map<ThreadId, ClaudeSessionContext>();
const runtimeEventQueue = yield* Queue.unbounded<ProviderRuntimeEvent>();
const serverSettingsService = yield* ServerSettingsService;
const nowIso = Effect.map(DateTime.now, DateTime.formatIso);
const nextEventId = Effect.map(Random.nextUUIDv4, (id) => EventId.make(id));
@@ -1249,6 +1275,9 @@ const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
if (typeof message.session_id !== "string" || message.session_id.length === 0) {
return;
}
if (!hasDurableClaudeSessionId(message)) {
return;
}
const nextThreadId = message.session_id;
context.resumeSessionId = message.session_id;
yield* updateResumeCursor(context);
@@ -2534,10 +2563,14 @@ const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
const requestId = ApprovalRequestId.make(yield* Random.nextUUIDv4);
// Parse questions from the SDK's AskUserQuestion input.
// `id` MUST equal the full question text — Claude SDK >= 2.1.121 looks
// up answers by question text in `mapToolResultToToolResultBlockParam`,
// so the key the UI uses to keep its draft answer must match the SDK's
// expected lookup key. See https://github.com/pingdotgg/t3code/issues/2388
const rawQuestions = Array.isArray(toolInput.questions) ? toolInput.questions : [];
const questions: Array<UserInputQuestion> = rawQuestions.map(
(q: Record<string, unknown>, idx: number) => ({
id: typeof q.header === "string" ? q.header : `q-${idx}`,
id: typeof q.question === "string" && q.question.length > 0 ? q.question : `q-${idx}`,
header: typeof q.header === "string" ? q.header : `Question ${idx + 1}`,
question: typeof q.question === "string" ? q.question : "",
options: Array.isArray(q.options)
@@ -2805,22 +2838,10 @@ const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
const canUseTool: CanUseTool = (toolName, toolInput, callbackOptions) =>
runPromise(canUseToolEffect(toolName, toolInput, callbackOptions));
const claudeSettings = yield* serverSettingsService.getSettings.pipe(
Effect.map((settings) => settings.providers.claudeAgent),
Effect.mapError(
(error) =>
new ProviderAdapterProcessError({
provider: PROVIDER,
threadId: input.threadId,
detail: error.message,
cause: error,
}),
),
);
const claudeBinaryPath = claudeSettings.binaryPath;
const extraArgs = parseCliArgs(claudeSettings.launchArgs).flags;
const modelSelection =
input.modelSelection?.provider === "claudeAgent" ? input.modelSelection : undefined;
input.modelSelection?.instanceId === boundInstanceId ? input.modelSelection : undefined;
const caps = getClaudeModelCapabilities(modelSelection?.model);
const descriptors = getProviderOptionDescriptors({ caps });
const apiModelId = modelSelection ? resolveClaudeApiModelId(modelSelection) : undefined;
@@ -2848,7 +2869,6 @@ const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
...(typeof thinking === "boolean" ? { alwaysThinkingEnabled: thinking } : {}),
...(fastMode ? { fastMode: true } : {}),
};
const queryOptions: ClaudeQueryOptions = {
...(input.cwd ? { cwd: input.cwd } : {}),
...(apiModelId ? { model: apiModelId } : {}),
@@ -2870,11 +2890,36 @@ const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
...(newSessionId ? { sessionId: newSessionId } : {}),
includePartialMessages: true,
canUseTool,
env: process.env,
env: claudeEnvironment,
...(input.cwd ? { additionalDirectories: [input.cwd] } : {}),
...(Object.keys(extraArgs).length > 0 ? { extraArgs } : {}),
};
yield* Effect.annotateCurrentSpan({
"provider.kind": PROVIDER,
"provider.thread_id": threadId,
"provider.runtime_mode": input.runtimeMode,
"claude.resume.source":
existingResumeSessionId !== undefined ? "resume-session" : "generated-session",
"claude.resume.thread_id": resumeState?.threadId ?? "",
"claude.resume.session_id": existingResumeSessionId ?? "",
"claude.resume.session_at": resumeState?.resumeSessionAt ?? "",
"claude.resume.turn_count": resumeState?.turnCount ?? -1,
"claude.query.cwd": input.cwd ?? "",
"claude.query.model": apiModelId ?? "",
"claude.query.effort": effectiveEffort ?? "",
"claude.query.permission_mode": permissionMode ?? "",
"claude.query.allow_dangerously_skip_permissions": permissionMode === "bypassPermissions",
"claude.query.resume": existingResumeSessionId ?? "",
"claude.query.session_id": newSessionId ?? "",
"claude.query.include_partial_messages": true,
"claude.query.additional_directories": input.cwd ? [input.cwd] : [],
"claude.query.setting_sources": [...CLAUDE_SETTING_SOURCES],
"claude.query.settings_json": JSON.stringify(settings),
"claude.query.extra_args_json": JSON.stringify(extraArgs),
"claude.query.path_to_executable": claudeBinaryPath,
});
const queryRuntime = yield* Effect.try({
try: () =>
createQuery({
@@ -2893,6 +2938,7 @@ const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
const session: ProviderSession = {
threadId,
provider: PROVIDER,
providerInstanceId: boundInstanceId,
status: "ready",
runtimeMode: input.runtimeMode,
...(input.cwd ? { cwd: input.cwd } : {}),
@@ -3004,7 +3050,9 @@ const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
const sendTurn: ClaudeAdapterShape["sendTurn"] = Effect.fn("sendTurn")(function* (input) {
const context = yield* requireSession(input.threadId);
const modelSelection =
input.modelSelection?.provider === "claudeAgent" ? input.modelSelection : undefined;
input.modelSelection !== undefined && input.modelSelection.instanceId === boundInstanceId
? input.modelSelection
: undefined;
if (context.turnState) {
// Auto-close a stale synthetic turn (from background agent responses
@@ -3078,6 +3126,7 @@ const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
const message = yield* buildUserMessageEffect(input, {
fileSystem,
attachmentsDir: serverConfig.attachmentsDir,
boundInstanceId,
});
yield* Queue.offer(context.promptQueue, {
@@ -3215,9 +3264,3 @@ const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
},
} satisfies ClaudeAdapterShape;
});
export const ClaudeAdapterLive = Layer.effect(ClaudeAdapter, makeClaudeAdapter());
export function makeClaudeAdapterLive(options?: ClaudeAdapterLiveOptions) {
return Layer.effect(ClaudeAdapter, makeClaudeAdapter(options));
}
+132 -354
View File
@@ -1,16 +1,13 @@
import type {
ClaudeSettings,
ClaudeModelSelection,
ModelCapabilities,
ServerProvider,
ServerProviderModel,
ServerProviderAuth,
ServerProviderSlashCommand,
ServerProviderState,
import {
type ClaudeSettings,
type ModelCapabilities,
type ModelSelection,
ProviderDriverKind,
type ServerProviderModel,
type ServerProviderSlashCommand,
} from "@t3tools/contracts";
import { Cache, Duration, Effect, Equal, Layer, Option, Result, Schema, Stream } from "effect";
import { Effect, Option, Path, Result } from "effect";
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
import { decodeJsonResult } from "@t3tools/shared/schemaJson";
import {
createModelCapabilities,
getModelSelectionStringOptionValue,
@@ -27,27 +24,22 @@ import {
buildBooleanOptionDescriptor,
buildSelectOptionDescriptor,
buildServerProvider,
AUTH_PROBE_TIMEOUT_MS,
DEFAULT_TIMEOUT_MS,
detailFromResult,
extractAuthBoolean,
isCommandMissingCause,
parseGenericCliVersion,
providerModelsFromSettings,
spawnAndCollect,
type CommandResult,
type ServerProviderDraft,
} from "../providerSnapshot.ts";
import { compareCliVersions } from "../cliVersion.ts";
import { makeManagedServerProvider } from "../makeManagedServerProvider.ts";
import { ClaudeProvider } from "../Services/ClaudeProvider.ts";
import { ServerSettingsService } from "../../serverSettings.ts";
import { ServerSettingsError } from "@t3tools/contracts";
import { makeClaudeEnvironment } from "../Drivers/ClaudeHome.ts";
const DEFAULT_CLAUDE_MODEL_CAPABILITIES: ModelCapabilities = createModelCapabilities({
optionDescriptors: [],
});
const PROVIDER = "claudeAgent" as const;
const PROVIDER = ProviderDriverKind.make("claudeAgent");
const CLAUDE_PRESENTATION = {
displayName: "Claude",
showInteractionModeToggle: true,
@@ -242,7 +234,7 @@ export function normalizeClaudeCliEffort(effort: string | null | undefined): str
return effort;
}
export function resolveClaudeApiModelId(modelSelection: ClaudeModelSelection): string {
export function resolveClaudeApiModelId(modelSelection: ModelSelection): string {
switch (getModelSelectionStringOptionValue(modelSelection, "contextWindow")) {
case "1m":
return `${modelSelection.model}[1m]`;
@@ -250,181 +242,6 @@ export function resolveClaudeApiModelId(modelSelection: ClaudeModelSelection): s
return modelSelection.model;
}
}
export function parseClaudeAuthStatusFromOutput(result: CommandResult): {
readonly status: Exclude<ServerProviderState, "disabled">;
readonly auth: Pick<ServerProviderAuth, "status">;
readonly message?: string;
} {
const lowerOutput = `${result.stdout}\n${result.stderr}`.toLowerCase();
if (
lowerOutput.includes("unknown command") ||
lowerOutput.includes("unrecognized command") ||
lowerOutput.includes("unexpected argument")
) {
return {
status: "warning",
auth: { status: "unknown" },
message:
"Claude Agent authentication status command is unavailable in this version of Claude.",
};
}
if (
lowerOutput.includes("not logged in") ||
lowerOutput.includes("login required") ||
lowerOutput.includes("authentication required") ||
lowerOutput.includes("run `claude login`") ||
lowerOutput.includes("run claude login")
) {
return {
status: "error",
auth: { status: "unauthenticated" },
message: "Claude is not authenticated. Run `claude auth login` and try again.",
};
}
const parsedAuth = (() => {
const trimmed = result.stdout.trim();
if (!trimmed || (!trimmed.startsWith("{") && !trimmed.startsWith("["))) {
return { attemptedJsonParse: false as const, auth: undefined as boolean | undefined };
}
try {
return {
attemptedJsonParse: true as const,
auth: extractAuthBoolean(JSON.parse(trimmed)),
};
} catch {
return { attemptedJsonParse: false as const, auth: undefined as boolean | undefined };
}
})();
if (parsedAuth.auth === true) {
return { status: "ready", auth: { status: "authenticated" } };
}
if (parsedAuth.auth === false) {
return {
status: "error",
auth: { status: "unauthenticated" },
message: "Claude is not authenticated. Run `claude auth login` and try again.",
};
}
if (parsedAuth.attemptedJsonParse) {
return {
status: "warning",
auth: { status: "unknown" },
message:
"Could not verify Claude authentication status from JSON output (missing auth marker).",
};
}
if (result.code === 0) {
return { status: "ready", auth: { status: "authenticated" } };
}
const detail = detailFromResult(result);
return {
status: "warning",
auth: { status: "unknown" },
message: detail
? `Could not verify Claude authentication status. ${detail}`
: "Could not verify Claude authentication status.",
};
}
// ── Subscription type detection ─────────────────────────────────────
//
// The SDK probe returns typed `AccountInfo.subscriptionType` directly.
// This walker is a best-effort fallback for the `claude auth status`
// JSON output whose shape is not guaranteed.
/** Keys that directly hold a subscription/plan identifier. */
const SUBSCRIPTION_TYPE_KEYS = [
"subscriptionType",
"subscription_type",
"plan",
"tier",
"planType",
"plan_type",
] as const;
/** Keys whose value may be a nested object containing subscription info. */
const SUBSCRIPTION_CONTAINER_KEYS = ["account", "subscription", "user", "billing"] as const;
const AUTH_METHOD_KEYS = ["authMethod", "auth_method"] as const;
const AUTH_METHOD_CONTAINER_KEYS = ["auth", "account", "session"] as const;
/** Lift an unknown value into `Option<string>` if it is a non-empty string. */
const asNonEmptyString = (v: unknown): Option.Option<string> =>
typeof v === "string" && v.length > 0 ? Option.some(v) : Option.none();
/** Lift an unknown value into `Option<Record>` if it is a plain object. */
const asRecord = (v: unknown): Option.Option<Record<string, unknown>> =>
typeof v === "object" && v !== null && !globalThis.Array.isArray(v)
? Option.some(v as Record<string, unknown>)
: Option.none();
/**
* Walk an unknown parsed JSON value looking for a subscription/plan
* identifier, returning the first match as an `Option`.
*/
function findSubscriptionType(value: unknown): Option.Option<string> {
if (globalThis.Array.isArray(value)) {
return Option.firstSomeOf(value.map(findSubscriptionType));
}
return asRecord(value).pipe(
Option.flatMap((record) => {
const direct = Option.firstSomeOf(
SUBSCRIPTION_TYPE_KEYS.map((key) => asNonEmptyString(record[key])),
);
if (Option.isSome(direct)) return direct;
return Option.firstSomeOf(
SUBSCRIPTION_CONTAINER_KEYS.map((key) =>
asRecord(record[key]).pipe(Option.flatMap(findSubscriptionType)),
),
);
}),
);
}
function findAuthMethod(value: unknown): Option.Option<string> {
if (globalThis.Array.isArray(value)) {
return Option.firstSomeOf(value.map(findAuthMethod));
}
return asRecord(value).pipe(
Option.flatMap((record) => {
const direct = Option.firstSomeOf(
AUTH_METHOD_KEYS.map((key) => asNonEmptyString(record[key])),
);
if (Option.isSome(direct)) return direct;
return Option.firstSomeOf(
AUTH_METHOD_CONTAINER_KEYS.map((key) =>
asRecord(record[key]).pipe(Option.flatMap(findAuthMethod)),
),
);
}),
);
}
/**
* Try to extract a subscription type from the `claude auth status` JSON
* output. This is a zero-cost operation on data we already have.
*/
const decodeUnknownJson = decodeJsonResult(Schema.Unknown);
function extractSubscriptionTypeFromOutput(result: CommandResult): string | undefined {
const parsed = decodeUnknownJson(result.stdout.trim());
if (Result.isFailure(parsed)) return undefined;
return Option.getOrUndefined(findSubscriptionType(parsed.success));
}
function extractClaudeAuthMethodFromOutput(result: CommandResult): string | undefined {
const parsed = decodeUnknownJson(result.stdout.trim());
if (Result.isFailure(parsed)) return undefined;
return Option.getOrUndefined(findAuthMethod(parsed.success));
}
function toTitleCaseWords(value: string): string {
return value
@@ -439,11 +256,27 @@ function claudeSubscriptionLabel(subscriptionType: string | undefined): string |
if (!normalized) return undefined;
switch (normalized) {
case "claudemaxsubscription":
return "Max";
case "claudemax5xsubscription":
return "Max 5x";
case "claudemax20xsubscription":
return "Max 20x";
case "claudeenterprisesubscription":
return "Enterprise";
case "claudeteamsubscription":
return "Team";
case "claudeprosubscription":
return "Pro";
case "claudefreesubscription":
return "Free";
case "max":
case "maxplan":
case "max5":
case "max20":
return "Max";
case "max5":
return "Max 5x";
case "max20":
return "Max 20x";
case "enterprise":
return "Enterprise";
case "team":
@@ -460,10 +293,33 @@ function claudeSubscriptionLabel(subscriptionType: string | undefined): string |
function normalizeClaudeAuthMethod(authMethod: string | undefined): string | undefined {
const normalized = authMethod?.toLowerCase().replace(/[\s_-]+/g, "");
if (!normalized) return undefined;
if (normalized === "apikey") return "apiKey";
if (
normalized === "apikey" ||
normalized === "anthropicapikey" ||
normalized === "anthropicauthtoken"
) {
return "apiKey";
}
return undefined;
}
function formatClaudeSubscriptionAuthLabel(subscriptionType: string): string {
const subscriptionLabel =
claudeSubscriptionLabel(subscriptionType) ?? toTitleCaseWords(subscriptionType);
const normalized = subscriptionLabel.toLowerCase().replace(/[\s_-]+/g, "");
if (normalized.startsWith("claude") && normalized.endsWith("subscription")) {
return subscriptionLabel;
}
if (normalized.startsWith("claude")) {
return `${subscriptionLabel} Subscription`;
}
if (normalized.endsWith("subscription")) {
return `Claude ${subscriptionLabel}`;
}
return `Claude ${subscriptionLabel} Subscription`;
}
function claudeAuthMetadata(input: {
readonly subscriptionType: string | undefined;
readonly authMethod: string | undefined;
@@ -476,10 +332,9 @@ function claudeAuthMetadata(input: {
}
if (input.subscriptionType) {
const subscriptionLabel = claudeSubscriptionLabel(input.subscriptionType);
return {
type: input.subscriptionType,
label: `Claude ${subscriptionLabel ?? toTitleCaseWords(input.subscriptionType)} Subscription`,
label: formatClaudeSubscriptionAuthLabel(input.subscriptionType),
};
}
@@ -495,6 +350,13 @@ function nonEmptyProbeString(value: string): string | undefined {
return candidate ? candidate : undefined;
}
type ClaudeCapabilitiesProbe = {
readonly email: string | undefined;
readonly subscriptionType: string | undefined;
readonly tokenSource: string | undefined;
readonly slashCommands: ReadonlyArray<ServerProviderSlashCommand>;
};
function parseClaudeInitializationCommands(
commands: ReadonlyArray<ClaudeSlashCommand> | undefined,
): ReadonlyArray<ServerProviderSlashCommand> {
@@ -580,30 +442,46 @@ function waitForAbortSignal(signal: AbortSignal): Promise<void> {
* This is used as a fallback when `claude auth status` does not include
* subscription type information.
*/
const probeClaudeCapabilities = (binaryPath: string) => {
const probeClaudeCapabilities = (
claudeSettings: ClaudeSettings,
environment: NodeJS.ProcessEnv = process.env,
) => {
const abort = new AbortController();
return Effect.tryPromise(async () => {
const q = claudeQuery({
// Never yield — we only need initialization data, not a conversation.
// This prevents any prompt from reaching the Anthropic API.
// oxlint-disable-next-line require-yield
prompt: (async function* (): AsyncGenerator<SDKUserMessage> {
await waitForAbortSignal(abort.signal);
})(),
options: {
persistSession: false,
pathToClaudeCodeExecutable: binaryPath,
abortController: abort,
settingSources: ["user", "project", "local"],
allowedTools: [],
stderr: () => {},
},
return Effect.gen(function* () {
const claudeEnvironment = yield* makeClaudeEnvironment(claudeSettings, environment);
return yield* Effect.tryPromise(async () => {
const q = claudeQuery({
// Never yield — we only need initialization data, not a conversation.
// This prevents any prompt from reaching the Anthropic API.
// oxlint-disable-next-line require-yield
prompt: (async function* (): AsyncGenerator<SDKUserMessage> {
await waitForAbortSignal(abort.signal);
})(),
options: {
persistSession: false,
pathToClaudeCodeExecutable: claudeSettings.binaryPath,
abortController: abort,
settingSources: ["user", "project", "local"],
allowedTools: [],
env: claudeEnvironment,
stderr: () => {},
},
});
const init = await q.initializationResult();
const account = init.account as
| {
readonly email?: string;
readonly subscriptionType?: string;
readonly tokenSource?: string;
}
| undefined;
return {
email: account?.email,
subscriptionType: account?.subscriptionType,
tokenSource: account?.tokenSource,
slashCommands: parseClaudeInitializationCommands(init.commands),
} satisfies ClaudeCapabilitiesProbe;
});
const init = await q.initializationResult();
return {
subscriptionType: init.account?.subscriptionType,
slashCommands: parseClaudeInitializationCommands(init.commands),
};
}).pipe(
Effect.ensuring(
Effect.sync(() => {
@@ -619,31 +497,30 @@ const probeClaudeCapabilities = (binaryPath: string) => {
);
};
const runClaudeCommand = Effect.fn("runClaudeCommand")(function* (args: ReadonlyArray<string>) {
const claudeSettings = yield* Effect.service(ServerSettingsService).pipe(
Effect.flatMap((service) => service.getSettings),
Effect.map((settings) => settings.providers.claudeAgent),
);
const runClaudeCommand = Effect.fn("runClaudeCommand")(function* (
claudeSettings: ClaudeSettings,
args: ReadonlyArray<string>,
environment: NodeJS.ProcessEnv = process.env,
) {
const claudeEnvironment = yield* makeClaudeEnvironment(claudeSettings, environment);
const command = ChildProcess.make(claudeSettings.binaryPath, [...args], {
env: claudeEnvironment,
shell: process.platform === "win32",
});
return yield* spawnAndCollect(claudeSettings.binaryPath, command);
});
export const checkClaudeProviderStatus = Effect.fn("checkClaudeProviderStatus")(function* (
resolveSubscriptionType?: (binaryPath: string) => Effect.Effect<string | undefined>,
resolveSlashCommands?: (
binaryPath: string,
) => Effect.Effect<ReadonlyArray<ServerProviderSlashCommand> | undefined>,
claudeSettings: ClaudeSettings,
resolveCapabilities?: (
claudeSettings: ClaudeSettings,
) => Effect.Effect<ClaudeCapabilitiesProbe | undefined>,
environment: NodeJS.ProcessEnv = process.env,
): Effect.fn.Return<
ServerProvider,
ServerSettingsError,
ChildProcessSpawner.ChildProcessSpawner | ServerSettingsService
ServerProviderDraft,
never,
ChildProcessSpawner.ChildProcessSpawner | Path.Path
> {
const claudeSettings = yield* Effect.service(ServerSettingsService).pipe(
Effect.flatMap((service) => service.getSettings),
Effect.map((settings) => settings.providers.claudeAgent),
);
const checkedAt = new Date().toISOString();
const allModels = providerModelsFromSettings(
BUILT_IN_MODELS,
@@ -654,7 +531,6 @@ export const checkClaudeProviderStatus = Effect.fn("checkClaudeProviderStatus")(
if (!claudeSettings.enabled) {
return buildServerProvider({
provider: PROVIDER,
presentation: CLAUDE_PRESENTATION,
enabled: false,
checkedAt,
@@ -669,7 +545,7 @@ export const checkClaudeProviderStatus = Effect.fn("checkClaudeProviderStatus")(
});
}
const versionProbe = yield* runClaudeCommand(["--version"]).pipe(
const versionProbe = yield* runClaudeCommand(claudeSettings, ["--version"], environment).pipe(
Effect.timeoutOption(DEFAULT_TIMEOUT_MS),
Effect.result,
);
@@ -677,7 +553,6 @@ export const checkClaudeProviderStatus = Effect.fn("checkClaudeProviderStatus")(
if (Result.isFailure(versionProbe)) {
const error = versionProbe.failure;
return buildServerProvider({
provider: PROVIDER,
presentation: CLAUDE_PRESENTATION,
enabled: claudeSettings.enabled,
checkedAt,
@@ -696,7 +571,6 @@ export const checkClaudeProviderStatus = Effect.fn("checkClaudeProviderStatus")(
if (Option.isNone(versionProbe.success)) {
return buildServerProvider({
provider: PROVIDER,
presentation: CLAUDE_PRESENTATION,
enabled: claudeSettings.enabled,
checkedAt,
@@ -717,7 +591,6 @@ export const checkClaudeProviderStatus = Effect.fn("checkClaudeProviderStatus")(
if (version.code !== 0) {
const detail = detailFromResult(version);
return buildServerProvider({
provider: PROVIDER,
presentation: CLAUDE_PRESENTATION,
enabled: claudeSettings.enabled,
checkedAt,
@@ -744,45 +617,14 @@ export const checkClaudeProviderStatus = Effect.fn("checkClaudeProviderStatus")(
? undefined
: formatClaudeOpus47UpgradeMessage(parsedVersion);
const slashCommands =
(resolveSlashCommands
? yield* resolveSlashCommands(claudeSettings.binaryPath).pipe(
Effect.orElseSucceed(() => undefined),
)
: undefined) ?? [];
const capabilities = resolveCapabilities
? yield* resolveCapabilities(claudeSettings).pipe(Effect.orElseSucceed(() => undefined))
: undefined;
const slashCommands = capabilities?.slashCommands ?? [];
const dedupedSlashCommands = dedupeSlashCommands(slashCommands);
// ── Auth check + subscription detection ────────────────────────────
const authProbe = yield* runClaudeCommand(["auth", "status"]).pipe(
Effect.timeoutOption(AUTH_PROBE_TIMEOUT_MS),
Effect.result,
);
// Determine subscription type from multiple sources (cheapest first):
// 1. `claude auth status` JSON output (may or may not contain it)
// 2. Cached SDK probe (spawns a Claude process on miss, reads
// `initializationResult()` for account metadata, then aborts
// immediately — no API tokens are consumed)
let subscriptionType: string | undefined;
let authMethod: string | undefined;
if (Result.isSuccess(authProbe) && Option.isSome(authProbe.success)) {
subscriptionType = extractSubscriptionTypeFromOutput(authProbe.success.value);
authMethod = extractClaudeAuthMethodFromOutput(authProbe.success.value);
}
if (!subscriptionType && resolveSubscriptionType) {
subscriptionType = yield* resolveSubscriptionType(claudeSettings.binaryPath);
}
// ── Handle auth results (same logic as before, adjusted models) ──
if (Result.isFailure(authProbe)) {
const error = authProbe.failure;
if (!capabilities) {
return buildServerProvider({
provider: PROVIDER,
presentation: CLAUDE_PRESENTATION,
enabled: claudeSettings.enabled,
checkedAt,
@@ -793,36 +635,16 @@ export const checkClaudeProviderStatus = Effect.fn("checkClaudeProviderStatus")(
version: parsedVersion,
status: "warning",
auth: { status: "unknown" },
message:
error instanceof Error
? `Could not verify Claude authentication status: ${error.message}.`
: "Could not verify Claude authentication status.",
message: "Could not verify Claude authentication status from initialization result.",
},
});
}
if (Option.isNone(authProbe.success)) {
return buildServerProvider({
provider: PROVIDER,
presentation: CLAUDE_PRESENTATION,
enabled: claudeSettings.enabled,
checkedAt,
models,
slashCommands: dedupedSlashCommands,
probe: {
installed: true,
version: parsedVersion,
status: "warning",
auth: { status: "unknown" },
message: "Could not verify Claude authentication status. Timed out while running command.",
},
});
}
const parsed = parseClaudeAuthStatusFromOutput(authProbe.success.value);
const authMetadata = claudeAuthMetadata({ subscriptionType, authMethod });
const authMetadata = claudeAuthMetadata({
subscriptionType: capabilities.subscriptionType,
authMethod: capabilities.tokenSource,
});
return buildServerProvider({
provider: PROVIDER,
presentation: CLAUDE_PRESENTATION,
enabled: claudeSettings.enabled,
checkedAt,
@@ -831,21 +653,18 @@ export const checkClaudeProviderStatus = Effect.fn("checkClaudeProviderStatus")(
probe: {
installed: true,
version: parsedVersion,
status: parsed.status,
status: "ready",
auth: {
...parsed.auth,
status: "authenticated",
...(capabilities.email ? { email: capabilities.email } : {}),
...(authMetadata ? authMetadata : {}),
},
...(parsed.message
? { message: parsed.message }
: opus47UpgradeMessage
? { message: opus47UpgradeMessage }
: {}),
...(opus47UpgradeMessage ? { message: opus47UpgradeMessage } : {}),
},
});
});
const makePendingClaudeProvider = (claudeSettings: ClaudeSettings): ServerProvider => {
export const makePendingClaudeProvider = (claudeSettings: ClaudeSettings): ServerProviderDraft => {
const checkedAt = new Date().toISOString();
const models = providerModelsFromSettings(
BUILT_IN_MODELS,
@@ -856,7 +675,6 @@ const makePendingClaudeProvider = (claudeSettings: ClaudeSettings): ServerProvid
if (!claudeSettings.enabled) {
return buildServerProvider({
provider: PROVIDER,
presentation: CLAUDE_PRESENTATION,
enabled: false,
checkedAt,
@@ -872,7 +690,6 @@ const makePendingClaudeProvider = (claudeSettings: ClaudeSettings): ServerProvid
}
return buildServerProvider({
provider: PROVIDER,
presentation: CLAUDE_PRESENTATION,
enabled: true,
checkedAt,
@@ -887,43 +704,4 @@ const makePendingClaudeProvider = (claudeSettings: ClaudeSettings): ServerProvid
});
};
export const ClaudeProviderLive = Layer.effect(
ClaudeProvider,
Effect.gen(function* () {
const serverSettings = yield* ServerSettingsService;
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
const subscriptionProbeCache = yield* Cache.make({
capacity: 1,
timeToLive: Duration.minutes(5),
lookup: (binaryPath: string) => probeClaudeCapabilities(binaryPath),
});
const checkProvider = checkClaudeProviderStatus(
(binaryPath) =>
Cache.get(subscriptionProbeCache, binaryPath).pipe(
Effect.map((probe) => probe?.subscriptionType),
),
(binaryPath) =>
Cache.get(subscriptionProbeCache, binaryPath).pipe(
Effect.map((probe) => probe?.slashCommands),
),
).pipe(
Effect.provideService(ServerSettingsService, serverSettings),
Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
);
return yield* makeManagedServerProvider<ClaudeSettings>({
getSettings: serverSettings.getSettings.pipe(
Effect.map((settings) => settings.providers.claudeAgent),
Effect.orDie,
),
streamSettings: serverSettings.streamChanges.pipe(
Stream.map((settings) => settings.providers.claudeAgent),
),
haveSettingsChanged: (previous, next) => !Equal.equals(previous, next),
initialSnapshot: makePendingClaudeProvider,
checkProvider,
});
}),
);
export { probeClaudeCapabilities };
@@ -4,7 +4,10 @@ import os from "node:os";
import path from "node:path";
import {
ApprovalRequestId,
CodexSettings,
EventId,
ProviderDriverKind,
ProviderInstanceId,
ProviderItemId,
type ProviderApprovalDecision,
type ProviderEvent,
@@ -18,13 +21,13 @@ import { createModelSelection } from "@t3tools/shared/model";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { it, vi } from "@effect/vitest";
import { Effect, Exit, Fiber, Layer, Option, Queue, Scope, Stream } from "effect";
import { Context, Effect, Exit, Fiber, Layer, Option, Queue, Schema, Scope, Stream } from "effect";
import * as CodexErrors from "effect-codex-app-server/errors";
import { ServerConfig } from "../../config.ts";
import { ServerSettingsService } from "../../serverSettings.ts";
import { ProviderAdapterValidationError } from "../Errors.ts";
import { CodexAdapter } from "../Services/CodexAdapter.ts";
import type { CodexAdapterShape } from "../Services/CodexAdapter.ts";
import { ProviderSessionDirectory } from "../Services/ProviderSessionDirectory.ts";
import {
type CodexSessionRuntimeOptions,
@@ -32,7 +35,12 @@ import {
type CodexSessionRuntimeShape,
type CodexThreadSnapshot,
} from "./CodexSessionRuntime.ts";
import { makeCodexAdapterLive } from "./CodexAdapter.ts";
import { makeCodexAdapter } from "./CodexAdapter.ts";
// Test-local service tag so the rest of the file can keep using `yield* CodexAdapter`.
class CodexAdapter extends Context.Service<CodexAdapter, CodexAdapterShape>()(
"test/CodexAdapter",
) {}
const asThreadId = (value: string): ThreadId => ThreadId.make(value);
const asTurnId = (value: string): TurnId => TurnId.make(value);
@@ -45,7 +53,7 @@ class FakeCodexRuntime implements CodexSessionRuntimeShape {
public readonly startImpl = vi.fn(() =>
Promise.resolve({
provider: "codex" as const,
provider: ProviderDriverKind.make("codex"),
status: "ready" as const,
runtimeMode: this.options.runtimeMode,
threadId: this.options.threadId,
@@ -203,7 +211,15 @@ const providerSessionDirectoryTestLayer = Layer.succeed(ProviderSessionDirectory
const validationRuntimeFactory = makeRuntimeFactory();
const validationLayer = it.layer(
makeCodexAdapterLive({ makeRuntime: validationRuntimeFactory.factory }).pipe(
Layer.effect(
CodexAdapter,
Effect.gen(function* () {
const codexConfig = Schema.decodeSync(CodexSettings)({});
return yield* makeCodexAdapter(codexConfig, {
makeRuntime: validationRuntimeFactory.factory,
});
}),
).pipe(
Layer.provideMerge(ServerConfig.layerTest(process.cwd(), process.cwd())),
Layer.provideMerge(ServerSettingsService.layerTest()),
Layer.provideMerge(providerSessionDirectoryTestLayer),
@@ -217,7 +233,7 @@ validationLayer("CodexAdapterLive validation", (it) => {
const adapter = yield* CodexAdapter;
const result = yield* adapter
.startSession({
provider: "claudeAgent",
provider: ProviderDriverKind.make("claudeAgent"),
threadId: asThreadId("thread-1"),
runtimeMode: "full-access",
})
@@ -227,7 +243,7 @@ validationLayer("CodexAdapterLive validation", (it) => {
assert.deepStrictEqual(
result.failure,
new ProviderAdapterValidationError({
provider: "codex",
provider: ProviderDriverKind.make("codex"),
operation: "startSession",
issue: "Expected provider 'codex' but received 'claudeAgent'.",
}),
@@ -241,9 +257,9 @@ validationLayer("CodexAdapterLive validation", (it) => {
const adapter = yield* CodexAdapter;
yield* adapter.startSession({
provider: "codex",
provider: ProviderDriverKind.make("codex"),
threadId: asThreadId("thread-1"),
modelSelection: createModelSelection("codex", "gpt-5.3-codex", [
modelSelection: createModelSelection(ProviderInstanceId.make("codex"), "gpt-5.3-codex", [
{ id: "fastMode", value: true },
]),
runtimeMode: "full-access",
@@ -253,6 +269,7 @@ validationLayer("CodexAdapterLive validation", (it) => {
binaryPath: "codex",
cwd: process.cwd(),
model: "gpt-5.3-codex",
providerInstanceId: ProviderInstanceId.make("codex"),
serviceTier: "fast",
threadId: asThreadId("thread-1"),
runtimeMode: "full-access",
@@ -263,7 +280,15 @@ validationLayer("CodexAdapterLive validation", (it) => {
const sessionRuntimeFactory = makeRuntimeFactory();
const sessionErrorLayer = it.layer(
makeCodexAdapterLive({ makeRuntime: sessionRuntimeFactory.factory }).pipe(
Layer.effect(
CodexAdapter,
Effect.gen(function* () {
const codexConfig = Schema.decodeSync(CodexSettings)({});
return yield* makeCodexAdapter(codexConfig, {
makeRuntime: sessionRuntimeFactory.factory,
});
}),
).pipe(
Layer.provideMerge(ServerConfig.layerTest(process.cwd(), process.cwd())),
Layer.provideMerge(ServerSettingsService.layerTest()),
Layer.provideMerge(providerSessionDirectoryTestLayer),
@@ -294,7 +319,7 @@ sessionErrorLayer("CodexAdapterLive session errors", (it) => {
Effect.gen(function* () {
const adapter = yield* CodexAdapter;
yield* adapter.startSession({
provider: "codex",
provider: ProviderDriverKind.make("codex"),
threadId: asThreadId("sess-missing"),
runtimeMode: "full-access",
});
@@ -306,7 +331,7 @@ sessionErrorLayer("CodexAdapterLive session errors", (it) => {
adapter.sendTurn({
threadId: asThreadId("sess-missing"),
input: "hello",
modelSelection: createModelSelection("codex", "gpt-5.3-codex", [
modelSelection: createModelSelection(ProviderInstanceId.make("codex"), "gpt-5.3-codex", [
{ id: "reasoningEffort", value: "high" },
{ id: "fastMode", value: true },
]),
@@ -322,11 +347,74 @@ sessionErrorLayer("CodexAdapterLive session errors", (it) => {
});
}),
);
it.effect("maps codex model options for the adapter's bound custom instance id", () => {
const customInstanceId = ProviderInstanceId.make("codex_personal");
const customRuntimeFactory = makeRuntimeFactory();
const customLayer = Layer.effect(
CodexAdapter,
Effect.gen(function* () {
const codexConfig = Schema.decodeSync(CodexSettings)({});
return yield* makeCodexAdapter(codexConfig, {
instanceId: customInstanceId,
makeRuntime: customRuntimeFactory.factory,
});
}),
).pipe(
Layer.provideMerge(ServerConfig.layerTest(process.cwd(), process.cwd())),
Layer.provideMerge(ServerSettingsService.layerTest()),
Layer.provideMerge(providerSessionDirectoryTestLayer),
Layer.provideMerge(NodeServices.layer),
);
return Effect.gen(function* () {
const adapter = yield* CodexAdapter;
yield* adapter.startSession({
provider: ProviderDriverKind.make("codex"),
threadId: asThreadId("sess-custom-instance"),
runtimeMode: "full-access",
});
const runtime = customRuntimeFactory.lastRuntime;
assert.ok(runtime);
runtime.sendTurnImpl.mockClear();
yield* Effect.ignore(
adapter.sendTurn({
threadId: asThreadId("sess-custom-instance"),
input: "hello",
modelSelection: createModelSelection(
ProviderInstanceId.make("codex_personal"),
"gpt-5.3-codex",
[
{ id: "reasoningEffort", value: "high" },
{ id: "fastMode", value: true },
],
),
attachments: [],
}),
);
assert.deepStrictEqual(runtime.sendTurnImpl.mock.calls[0]?.[0], {
input: "hello",
model: "gpt-5.3-codex",
effort: "high",
serviceTier: "fast",
});
}).pipe(Effect.provide(customLayer));
});
});
const lifecycleRuntimeFactory = makeRuntimeFactory();
const lifecycleLayer = it.layer(
makeCodexAdapterLive({ makeRuntime: lifecycleRuntimeFactory.factory }).pipe(
Layer.effect(
CodexAdapter,
Effect.gen(function* () {
const codexConfig = Schema.decodeSync(CodexSettings)({});
return yield* makeCodexAdapter(codexConfig, {
makeRuntime: lifecycleRuntimeFactory.factory,
});
}),
).pipe(
Layer.provideMerge(ServerConfig.layerTest(process.cwd(), process.cwd())),
Layer.provideMerge(ServerSettingsService.layerTest()),
Layer.provideMerge(providerSessionDirectoryTestLayer),
@@ -338,7 +426,7 @@ function startLifecycleRuntime() {
return Effect.gen(function* () {
const adapter = yield* CodexAdapter;
yield* adapter.startSession({
provider: "codex",
provider: ProviderDriverKind.make("codex"),
threadId: asThreadId("thread-1"),
runtimeMode: "full-access",
});
@@ -357,7 +445,7 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => {
const event: ProviderEvent = {
id: asEventId("evt-msg-complete"),
kind: "notification",
provider: "codex",
provider: ProviderDriverKind.make("codex"),
createdAt: new Date().toISOString(),
method: "item/completed",
threadId: asThreadId("thread-1"),
@@ -399,7 +487,7 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => {
const event: ProviderEvent = {
id: asEventId("evt-plan-complete"),
kind: "notification",
provider: "codex",
provider: ProviderDriverKind.make("codex"),
createdAt: new Date().toISOString(),
method: "item/completed",
threadId: asThreadId("thread-1"),
@@ -440,7 +528,7 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => {
yield* runtime.emit({
id: asEventId("evt-plan-delta"),
kind: "notification",
provider: "codex",
provider: ProviderDriverKind.make("codex"),
createdAt: new Date().toISOString(),
method: "item/plan/delta",
threadId: asThreadId("thread-1"),
@@ -477,7 +565,7 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => {
const event: ProviderEvent = {
id: asEventId("evt-session-closed"),
kind: "session",
provider: "codex",
provider: ProviderDriverKind.make("codex"),
threadId: asThreadId("thread-1"),
createdAt: new Date().toISOString(),
method: "session/closed",
@@ -508,7 +596,7 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => {
yield* runtime.emit({
id: asEventId("evt-retryable-error"),
kind: "notification",
provider: "codex",
provider: ProviderDriverKind.make("codex"),
threadId: asThreadId("thread-1"),
createdAt: new Date().toISOString(),
method: "error",
@@ -546,7 +634,7 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => {
yield* runtime.emit({
id: asEventId("evt-process-stderr"),
kind: "notification",
provider: "codex",
provider: ProviderDriverKind.make("codex"),
threadId: asThreadId("thread-1"),
createdAt: new Date().toISOString(),
method: "process/stderr",
@@ -580,7 +668,7 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => {
yield* runtime.emit({
id: asEventId("evt-process-stderr-websocket"),
kind: "notification",
provider: "codex",
provider: ProviderDriverKind.make("codex"),
threadId: asThreadId("thread-1"),
createdAt: new Date().toISOString(),
method: "process/stderr",
@@ -616,7 +704,7 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => {
const event: ProviderEvent = {
id: asEventId("evt-request-resolved"),
kind: "notification",
provider: "codex",
provider: ProviderDriverKind.make("codex"),
threadId: asThreadId("thread-1"),
createdAt: new Date().toISOString(),
method: "serverRequest/resolved",
@@ -651,7 +739,7 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => {
const event: ProviderEvent = {
id: asEventId("evt-file-read-request-resolved"),
kind: "notification",
provider: "codex",
provider: ProviderDriverKind.make("codex"),
threadId: asThreadId("thread-1"),
createdAt: new Date().toISOString(),
method: "serverRequest/resolved",
@@ -686,7 +774,7 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => {
const event: ProviderEvent = {
id: asEventId("evt-user-input-empty"),
kind: "notification",
provider: "codex",
provider: ProviderDriverKind.make("codex"),
threadId: asThreadId("thread-1"),
createdAt: new Date().toISOString(),
method: "item/tool/requestUserInput/answered",
@@ -726,7 +814,7 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => {
const event: ProviderEvent = {
id: asEventId("evt-windows-sandbox-failed"),
kind: "notification",
provider: "codex",
provider: ProviderDriverKind.make("codex"),
threadId: asThreadId("thread-1"),
createdAt: new Date().toISOString(),
method: "windowsSandbox/setupCompleted",
@@ -771,7 +859,7 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => {
yield* runtime.emit({
id: asEventId("evt-user-input-requested"),
kind: "request",
provider: "codex",
provider: ProviderDriverKind.make("codex"),
threadId: asThreadId("thread-1"),
createdAt: new Date().toISOString(),
method: "item/tool/requestUserInput",
@@ -798,7 +886,7 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => {
yield* runtime.emit({
id: asEventId("evt-user-input-resolved"),
kind: "notification",
provider: "codex",
provider: ProviderDriverKind.make("codex"),
threadId: asThreadId("thread-1"),
createdAt: new Date().toISOString(),
method: "item/tool/requestUserInput/answered",
@@ -838,7 +926,7 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => {
yield* runtime.emit({
id: asEventId("evt-codex-thread-token-usage-updated"),
kind: "notification",
provider: "codex",
provider: ProviderDriverKind.make("codex"),
threadId: asThreadId("thread-1"),
turnId: asTurnId("turn-1"),
createdAt: new Date().toISOString(),
@@ -897,7 +985,15 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => {
const scopedLifecycleRuntimeFactory = makeScopedRuntimeFactory();
const scopedLifecycleLayer = it.layer(
makeCodexAdapterLive({ makeRuntime: scopedLifecycleRuntimeFactory.factory }).pipe(
Layer.effect(
CodexAdapter,
Effect.gen(function* () {
const codexConfig = Schema.decodeSync(CodexSettings)({});
return yield* makeCodexAdapter(codexConfig, {
makeRuntime: scopedLifecycleRuntimeFactory.factory,
});
}),
).pipe(
Layer.provideMerge(ServerConfig.layerTest(process.cwd(), process.cwd())),
Layer.provideMerge(ServerSettingsService.layerTest()),
Layer.provideMerge(providerSessionDirectoryTestLayer),
@@ -912,7 +1008,7 @@ scopedLifecycleLayer("CodexAdapterLive scoped lifecycle", (it) => {
const adapter = yield* CodexAdapter;
yield* adapter.startSession({
provider: "codex",
provider: ProviderDriverKind.make("codex"),
threadId: asThreadId("thread-stop"),
runtimeMode: "full-access",
});
@@ -933,7 +1029,15 @@ scopedLifecycleLayer("CodexAdapterLive scoped lifecycle", (it) => {
const scopedFailureRuntimeFactory = makeScopedRuntimeFactory({ failConstruction: true });
const scopedFailureLayer = it.layer(
makeCodexAdapterLive({ makeRuntime: scopedFailureRuntimeFactory.factory }).pipe(
Layer.effect(
CodexAdapter,
Effect.gen(function* () {
const codexConfig = Schema.decodeSync(CodexSettings)({});
return yield* makeCodexAdapter(codexConfig, {
makeRuntime: scopedFailureRuntimeFactory.factory,
});
}),
).pipe(
Layer.provideMerge(ServerConfig.layerTest(process.cwd(), process.cwd())),
Layer.provideMerge(ServerSettingsService.layerTest()),
Layer.provideMerge(providerSessionDirectoryTestLayer),
@@ -949,7 +1053,7 @@ scopedFailureLayer("CodexAdapterLive scoped startup failure", (it) => {
const result = yield* adapter
.startSession({
provider: "codex",
provider: ProviderDriverKind.make("codex"),
threadId: asThreadId("thread-fail"),
runtimeMode: "full-access",
})
@@ -974,10 +1078,16 @@ it.effect("flushes managed native logs when the adapter layer shuts down", () =>
let scopeClosed = false;
try {
const layer = makeCodexAdapterLive({
makeRuntime: runtimeFactory.factory,
nativeEventLogPath: basePath,
}).pipe(
const layer = Layer.effect(
CodexAdapter,
Effect.gen(function* () {
const codexConfig = Schema.decodeSync(CodexSettings)({});
return yield* makeCodexAdapter(codexConfig, {
makeRuntime: runtimeFactory.factory,
nativeEventLogPath: basePath,
});
}),
).pipe(
Layer.provideMerge(ServerConfig.layerTest(process.cwd(), process.cwd())),
Layer.provideMerge(ServerSettingsService.layerTest()),
Layer.provideMerge(providerSessionDirectoryTestLayer),
@@ -987,7 +1097,7 @@ it.effect("flushes managed native logs when the adapter layer shuts down", () =>
const adapter = yield* Effect.service(CodexAdapter).pipe(Effect.provide(context));
yield* adapter.startSession({
provider: "codex",
provider: ProviderDriverKind.make("codex"),
threadId: asThreadId("thread-logger"),
runtimeMode: "full-access",
});
@@ -999,7 +1109,7 @@ it.effect("flushes managed native logs when the adapter layer shuts down", () =>
yield* runtime.emit({
id: asEventId("evt-native-log"),
kind: "notification",
provider: "codex",
provider: ProviderDriverKind.make("codex"),
threadId: asThreadId("thread-logger"),
createdAt: new Date().toISOString(),
method: "process/stderr",
+35 -30
View File
@@ -10,7 +10,10 @@
import {
type CanonicalItemType,
type CanonicalRequestType,
type CodexSettings,
ProviderDriverKind,
type ProviderEvent,
ProviderInstanceId,
type ProviderRuntimeEvent,
type ProviderRequestKind,
type ThreadTokenUsageSnapshot,
@@ -21,7 +24,7 @@ import {
ThreadId,
ProviderSendTurnInput,
} from "@t3tools/contracts";
import { Effect, Exit, Fiber, FileSystem, Layer, Queue, Schema, Scope, Stream } from "effect";
import { Effect, Exit, Fiber, FileSystem, Queue, Schema, Scope, Stream } from "effect";
import { ChildProcessSpawner } from "effect/unstable/process";
import * as CodexErrors from "effect-codex-app-server/errors";
import * as EffectCodexSchema from "effect-codex-app-server/schema";
@@ -39,10 +42,9 @@ import {
ProviderAdapterValidationError,
type ProviderAdapterError,
} from "../Errors.ts";
import { CodexAdapter, type CodexAdapterShape } from "../Services/CodexAdapter.ts";
import { type CodexAdapterShape } from "../Services/CodexAdapter.ts";
import { resolveAttachmentPath } from "../../attachmentStore.ts";
import { ServerConfig } from "../../config.ts";
import { ServerSettingsService } from "../../serverSettings.ts";
import {
CodexResumeCursorSchema,
CodexSessionRuntimeThreadIdMissingError,
@@ -53,9 +55,11 @@ import {
} from "./CodexSessionRuntime.ts";
import { type EventNdjsonLogger, makeEventNdjsonLogger } from "./EventNdjsonLogger.ts";
const PROVIDER = "codex" as const;
const PROVIDER = ProviderDriverKind.make("codex");
export interface CodexAdapterLiveOptions {
readonly instanceId?: ProviderInstanceId;
readonly environment?: NodeJS.ProcessEnv;
readonly makeRuntime?: (
options: CodexSessionRuntimeOptions,
) => Effect.Effect<
@@ -1318,9 +1322,20 @@ function mapToRuntimeEvents(
return [];
}
const makeCodexAdapter = Effect.fn("makeCodexAdapter")(function* (
/**
* Build a Codex provider adapter bound to a specific `CodexSettings` payload.
*
* The adapter is a captured closure over `codexConfig` — the `binaryPath` and
* `homePath` are read from that payload, not from `ServerSettingsService`.
* This is what makes multi-instance routing possible: each `ProviderInstance`
* in the registry owns its own closure with its own config, so two Codex
* instances with different `homePath`s cannot step on each other.
*/
export const makeCodexAdapter = Effect.fn("makeCodexAdapter")(function* (
codexConfig: CodexSettings,
options?: CodexAdapterLiveOptions,
) {
const boundInstanceId = options?.instanceId ?? ProviderInstanceId.make("codex");
const fileSystem = yield* FileSystem.FileSystem;
const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
const serverConfig = yield* Effect.service(ServerConfig);
@@ -1333,7 +1348,6 @@ const makeCodexAdapter = Effect.fn("makeCodexAdapter")(function* (
: undefined);
const managedNativeEventLogger =
options?.nativeEventLogger === undefined ? nativeEventLogger : undefined;
const serverSettingsService = yield* ServerSettingsService;
const runtimeEventQueue = yield* Queue.unbounded<ProviderRuntimeEvent>();
const sessions = new Map<ThreadId, CodexAdapterSessionContext>();
@@ -1353,31 +1367,21 @@ const makeCodexAdapter = Effect.fn("makeCodexAdapter")(function* (
yield* Effect.suspend(() => stopSessionInternal(existing));
}
const codexSettings = yield* serverSettingsService.getSettings.pipe(
Effect.map((settings) => settings.providers.codex),
Effect.mapError(
(error) =>
new ProviderAdapterProcessError({
provider: PROVIDER,
threadId: input.threadId,
detail: error.message,
cause: error,
}),
),
);
const runtimeInput: CodexSessionRuntimeOptions = {
threadId: input.threadId,
providerInstanceId: boundInstanceId,
cwd: input.cwd ?? process.cwd(),
binaryPath: codexSettings.binaryPath,
...(codexSettings.homePath ? { homePath: codexSettings.homePath } : {}),
binaryPath: codexConfig.binaryPath,
...(options?.environment ? { environment: options.environment } : {}),
...(codexConfig.homePath ? { homePath: codexConfig.homePath } : {}),
...(Schema.is(CodexResumeCursorSchema)(input.resumeCursor)
? { resumeCursor: input.resumeCursor }
: {}),
runtimeMode: input.runtimeMode,
...(input.modelSelection?.provider === "codex"
...(input.modelSelection?.instanceId === boundInstanceId
? { model: input.modelSelection.model }
: {}),
...(input.modelSelection?.provider === "codex" &&
...(input.modelSelection?.instanceId === boundInstanceId &&
getModelSelectionBooleanOptionValue(input.modelSelection, "fastMode") === true
? { serviceTier: "fast" }
: {}),
@@ -1492,17 +1496,17 @@ const makeCodexAdapter = Effect.fn("makeCodexAdapter")(function* (
const session = yield* requireSession(input.threadId);
const reasoningEffort =
input.modelSelection?.provider === "codex"
input.modelSelection?.instanceId === boundInstanceId
? getModelSelectionStringOptionValue(input.modelSelection, "reasoningEffort")
: undefined;
const fastMode =
input.modelSelection?.provider === "codex"
input.modelSelection?.instanceId === boundInstanceId
? getModelSelectionBooleanOptionValue(input.modelSelection, "fastMode")
: undefined;
return yield* session.runtime
.sendTurn({
...(input.input !== undefined ? { input: input.input } : {}),
...(input.modelSelection?.provider === "codex"
...(input.modelSelection?.instanceId === boundInstanceId
? { model: input.modelSelection.model }
: {}),
...(reasoningEffort
@@ -1676,8 +1680,9 @@ const makeCodexAdapter = Effect.fn("makeCodexAdapter")(function* (
} satisfies CodexAdapterShape;
});
export const CodexAdapterLive = Layer.effect(CodexAdapter, makeCodexAdapter());
export function makeCodexAdapterLive(options?: CodexAdapterLiveOptions) {
return Layer.effect(CodexAdapter, makeCodexAdapter(options));
}
// NOTE: the old `CodexAdapterLive` / `makeCodexAdapterLive` singleton Layer
// exports have been removed as part of the per-instance-driver refactor.
// `makeCodexAdapter(codexConfig, options?)` is now invoked directly by
// `CodexDriver.create()` for each configured instance; downstream consumers
// (server bootstrap, integration harness, this module's tests) will be
// migrated to the registry in a follow-up pass.
@@ -1,15 +1,4 @@
import {
DateTime,
Duration,
Effect,
Equal,
Layer,
Option,
Result,
Schema,
Stream,
Types,
} from "effect";
import { DateTime, Duration, Effect, Layer, Option, Result, Schema, Types } from "effect";
import { ChildProcessSpawner } from "effect/unstable/process";
import * as CodexClient from "effect-codex-app-server/client";
import * as CodexSchema from "effect-codex-app-server/schema";
@@ -27,14 +16,11 @@ import { ServerSettingsError } from "@t3tools/contracts";
import { createModelCapabilities } from "@t3tools/shared/model";
import { makeManagedServerProvider } from "../makeManagedServerProvider.ts";
import { buildServerProvider } from "../providerSnapshot.ts";
import { CodexProvider } from "../Services/CodexProvider.ts";
import { buildServerProvider, type ServerProviderDraft } from "../providerSnapshot.ts";
import { expandHomePath } from "../../pathExpansion.ts";
import { ServerSettingsService } from "../../serverSettings.ts";
import { scopedSafeTeardown } from "./scopedSafeTeardown.ts";
import packageJson from "../../../package.json" with { type: "json" };
const PROVIDER = "codex" as const;
const PROVIDER_PROBE_TIMEOUT_MS = 8_000;
const CODEX_PRESENTATION = {
displayName: "Codex",
@@ -90,6 +76,11 @@ function codexAccountAuthLabel(account: CodexSchema.V2GetAccountResponse["accoun
}
}
function codexAccountEmail(account: CodexSchema.V2GetAccountResponse["account"]) {
if (!account || account.type !== "chatgpt") return undefined;
return account.email;
}
function mapCodexModelCapabilities(
model: CodexSchema.V2ModelListResponse__Model,
): ModelCapabilities {
@@ -245,18 +236,33 @@ export function buildCodexInitializeParams(): CodexSchema.V1InitializeParams {
};
}
// Wrapped with `scopedSafeTeardown("codex-probe")` rather than the usual
// `Effect.scoped` so that a defect from the `Layer.build` finalizer (e.g.
// `ChildProcess.kill` throwing because the `codex app-server` child exited
// early) cannot override a successful probe body. Without this guard the
// defect bubbles past `Effect.result` in `checkCodexProviderStatus`, dies
// `refreshOneSource`, and `providersRef` never receives the snapshot.
const probeCodexAppServerProvider = Effect.fn("probeCodexAppServerProvider")(function* (input: {
readonly binaryPath: string;
readonly homePath?: string;
readonly cwd: string;
readonly customModels?: ReadonlyArray<string>;
readonly environment?: NodeJS.ProcessEnv;
}) {
// `~` is not shell-expanded when env vars are set via `child_process.spawn`,
// so `CODEX_HOME=~/.codex_work` would reach codex verbatim and trip
// "CODEX_HOME points to '~/.codex_work', but that path does not exist".
// Expand here for parity with `CodexTextGeneration`/`CodexSessionRuntime`.
const resolvedHomePath = input.homePath ? expandHomePath(input.homePath) : undefined;
const clientContext = yield* Layer.build(
CodexClient.layerCommand({
command: input.binaryPath,
args: ["app-server"],
cwd: input.cwd,
...(input.homePath ? { env: { CODEX_HOME: expandHomePath(input.homePath) } } : {}),
env: {
...(input.environment ?? process.env),
...(resolvedHomePath ? { CODEX_HOME: resolvedHomePath } : {}),
},
}),
);
const client = yield* Effect.service(CodexClient.CodexAppServerClient).pipe(
@@ -305,7 +311,7 @@ const probeCodexAppServerProvider = Effect.fn("probeCodexAppServerProvider")(fun
models: appendCustomCodexModels(models, input.customModels ?? []),
skills: parseCodexSkillsListResponse(skillsResponse, input.cwd),
} satisfies CodexAppServerProviderSnapshot;
}, Effect.scoped);
}, scopedSafeTeardown("codex-probe"));
const emptyCodexModelsFromSettings = (codexSettings: CodexSettings): ServerProvider["models"] =>
codexSettings.customModels
@@ -318,13 +324,12 @@ const emptyCodexModelsFromSettings = (codexSettings: CodexSettings): ServerProvi
capabilities: null,
}));
const makePendingCodexProvider = (codexSettings: CodexSettings): ServerProvider => {
const makePendingCodexProvider = (codexSettings: CodexSettings): ServerProviderDraft => {
const checkedAt = new Date().toISOString();
const models = emptyCodexModelsFromSettings(codexSettings);
if (!codexSettings.enabled) {
return buildServerProvider({
provider: PROVIDER,
presentation: CODEX_PRESENTATION,
enabled: false,
checkedAt,
@@ -341,7 +346,6 @@ const makePendingCodexProvider = (codexSettings: CodexSettings): ServerProvider
}
return buildServerProvider({
provider: PROVIDER,
presentation: CODEX_PRESENTATION,
enabled: true,
checkedAt,
@@ -363,10 +367,12 @@ function accountProbeStatus(account: CodexAppServerProviderSnapshot["account"]):
readonly message?: string;
} {
const authLabel = codexAccountAuthLabel(account.account);
const authEmail = codexAccountEmail(account.account);
const auth = {
status: account.account ? ("authenticated" as const) : ("unknown" as const),
...(account.account?.type ? { type: account.account?.type } : {}),
...(authLabel ? { label: authLabel } : {}),
...(authEmail ? { email: authEmail } : {}),
} satisfies ServerProvider["auth"];
if (account.account) {
@@ -385,31 +391,29 @@ function accountProbeStatus(account: CodexAppServerProviderSnapshot["account"]):
}
export const checkCodexProviderStatus = Effect.fn("checkCodexProviderStatus")(function* (
codexSettings: CodexSettings,
probe: (input: {
readonly binaryPath: string;
readonly homePath?: string;
readonly cwd: string;
readonly customModels: ReadonlyArray<string>;
readonly environment?: NodeJS.ProcessEnv;
}) => Effect.Effect<
CodexAppServerProviderSnapshot,
CodexErrors.CodexAppServerError,
ChildProcessSpawner.ChildProcessSpawner
> = probeCodexAppServerProvider,
environment: NodeJS.ProcessEnv = process.env,
): Effect.fn.Return<
ServerProvider,
ServerProviderDraft,
ServerSettingsError,
ServerSettingsService | ChildProcessSpawner.ChildProcessSpawner
ChildProcessSpawner.ChildProcessSpawner
> {
const codexSettings = yield* Effect.service(ServerSettingsService).pipe(
Effect.flatMap((service) => service.getSettings),
Effect.map((settings) => settings.providers.codex),
);
const checkedAt = DateTime.formatIso(yield* DateTime.now);
const emptyModels = emptyCodexModelsFromSettings(codexSettings);
if (!codexSettings.enabled) {
return buildServerProvider({
provider: PROVIDER,
presentation: CODEX_PRESENTATION,
enabled: false,
checkedAt,
@@ -430,13 +434,13 @@ export const checkCodexProviderStatus = Effect.fn("checkCodexProviderStatus")(fu
homePath: codexSettings.homePath,
cwd: process.cwd(),
customModels: codexSettings.customModels,
environment,
}).pipe(Effect.timeoutOption(Duration.millis(PROVIDER_PROBE_TIMEOUT_MS)), Effect.result);
if (Result.isFailure(probeResult)) {
const error = probeResult.failure;
const installed = !Schema.is(CodexErrors.CodexAppServerSpawnError)(error);
return buildServerProvider({
provider: PROVIDER,
presentation: CODEX_PRESENTATION,
enabled: codexSettings.enabled,
checkedAt,
@@ -456,7 +460,6 @@ export const checkCodexProviderStatus = Effect.fn("checkCodexProviderStatus")(fu
if (Option.isNone(probeResult.success)) {
return buildServerProvider({
provider: PROVIDER,
presentation: CODEX_PRESENTATION,
enabled: codexSettings.enabled,
checkedAt,
@@ -476,7 +479,6 @@ export const checkCodexProviderStatus = Effect.fn("checkCodexProviderStatus")(fu
const accountStatus = accountProbeStatus(snapshot.account);
return buildServerProvider({
provider: PROVIDER,
presentation: CODEX_PRESENTATION,
enabled: codexSettings.enabled,
checkedAt,
@@ -492,28 +494,11 @@ export const checkCodexProviderStatus = Effect.fn("checkCodexProviderStatus")(fu
});
});
export const CodexProviderLive = Layer.effect(
CodexProvider,
Effect.gen(function* () {
const serverSettings = yield* ServerSettingsService;
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
const checkProvider = checkCodexProviderStatus().pipe(
Effect.provideService(ServerSettingsService, serverSettings),
Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
);
return yield* makeManagedServerProvider<CodexSettings>({
getSettings: serverSettings.getSettings.pipe(
Effect.map((settings) => settings.providers.codex),
Effect.orDie,
),
streamSettings: serverSettings.streamChanges.pipe(
Stream.map((settings) => settings.providers.codex),
),
haveSettingsChanged: (previous, next) => !Equal.equals(previous, next),
initialSnapshot: makePendingCodexProvider,
checkProvider,
refreshInterval: Duration.minutes(5),
});
}),
);
// NOTE: the singleton `CodexProviderLive` Layer has been removed as part of
// the per-instance-driver refactor. `CodexDriver.create()` builds a managed
// snapshot per instance (each with its own `CodexSettings`) and hands the
// resulting `ServerProviderShape` back as `ProviderInstance.snapshot`.
//
// The `makePendingCodexProvider` and `checkCodexProviderStatus` helpers are
// re-exported for use by `CodexDriver`.
export { makePendingCodexProvider };
@@ -1,10 +1,10 @@
import { randomUUID } from "node:crypto";
import {
ApprovalRequestId,
DEFAULT_MODEL_BY_PROVIDER,
DEFAULT_MODEL,
EventId,
ProviderDriverKind,
ProviderItemId,
type ProviderInstanceId,
type ProviderApprovalDecision,
type ProviderEvent,
type ProviderInteractionMode,
@@ -17,7 +17,7 @@ import {
TurnId,
} from "@t3tools/contracts";
import { normalizeModelSlug } from "@t3tools/shared/model";
import { Deferred, Effect, Exit, Layer, Queue, Ref, Scope, Schema, Stream } from "effect";
import { Deferred, Effect, Exit, Layer, Queue, Ref, Scope, Random, Schema, Stream } from "effect";
import * as SchemaIssue from "effect/SchemaIssue";
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
import * as CodexClient from "effect-codex-app-server/client";
@@ -26,13 +26,13 @@ import * as CodexRpc from "effect-codex-app-server/rpc";
import * as EffectCodexSchema from "effect-codex-app-server/schema";
import { buildCodexInitializeParams } from "./CodexProvider.ts";
import { expandHomePath } from "../../pathExpansion.ts";
import {
CODEX_DEFAULT_MODE_DEVELOPER_INSTRUCTIONS,
CODEX_PLAN_MODE_DEVELOPER_INSTRUCTIONS,
} from "../CodexDeveloperInstructions.ts";
import { expandHomePath } from "../../pathExpansion.ts";
const PROVIDER = "codex" as const;
const PROVIDER = ProviderDriverKind.make("codex");
const ANSI_ESCAPE_CHAR = String.fromCharCode(27);
const ANSI_ESCAPE_REGEX = new RegExp(`${ANSI_ESCAPE_CHAR}\\[[0-9;]*m`, "g");
@@ -76,8 +76,10 @@ type CodexThreadItem =
export interface CodexSessionRuntimeOptions {
readonly threadId: ThreadId;
readonly providerInstanceId?: ProviderInstanceId;
readonly binaryPath: string;
readonly homePath?: string;
readonly environment?: NodeJS.ProcessEnv;
readonly cwd: string;
readonly runtimeMode: RuntimeMode;
readonly model?: string;
@@ -87,7 +89,10 @@ export interface CodexSessionRuntimeOptions {
export interface CodexSessionRuntimeSendTurnInput {
readonly input?: string;
readonly attachments?: ReadonlyArray<{ readonly type: "image"; readonly url: string }>;
readonly attachments?: ReadonlyArray<{
readonly type: "image";
readonly url: string;
}>;
readonly model?: string;
readonly serviceTier?: EffectCodexSchema.V2TurnStartParams__ServiceTier | undefined;
readonly effort?: EffectCodexSchema.V2TurnStartParams__ReasoningEffort | undefined;
@@ -303,7 +308,7 @@ function buildCodexCollaborationMode(input: {
if (input.interactionMode === undefined) {
return undefined;
}
const model = normalizeCodexModelSlug(input.model) ?? DEFAULT_MODEL_BY_PROVIDER.codex;
const model = normalizeCodexModelSlug(input.model) ?? DEFAULT_MODEL;
return {
mode: input.interactionMode,
settings: {
@@ -321,7 +326,10 @@ export function buildTurnStartParams(input: {
readonly threadId: string;
readonly runtimeMode: RuntimeMode;
readonly prompt?: string;
readonly attachments?: ReadonlyArray<{ readonly type: "image"; readonly url: string }>;
readonly attachments?: ReadonlyArray<{
readonly type: "image";
readonly url: string;
}>;
readonly model?: string;
readonly serviceTier?: EffectCodexSchema.V2TurnStartParams__ServiceTier;
readonly effort?: EffectCodexSchema.V2TurnStartParams__ReasoningEffort;
@@ -680,13 +688,19 @@ export const makeCodexSessionRuntime = (
const collabReceiverTurnsRef = yield* Ref.make(new Map<string, TurnId>());
const closedRef = yield* Ref.make(false);
// `~` is not shell-expanded when env vars are set via
// `child_process.spawn`; `expandHomePath` lets a configured
// `CODEX_HOME=~/.codex_work` reach codex as an absolute path.
const resolvedHomePath = options.homePath ? expandHomePath(options.homePath) : undefined;
const env = {
...(options.environment ?? process.env),
...(resolvedHomePath ? { CODEX_HOME: resolvedHomePath } : {}),
};
const child = yield* spawner
.spawn(
ChildProcess.make(options.binaryPath, ["app-server"], {
cwd: options.cwd,
...(options.homePath
? { env: { ...process.env, CODEX_HOME: expandHomePath(options.homePath) } }
: {}),
env,
shell: process.platform === "win32",
}),
)
@@ -712,6 +726,7 @@ export const makeCodexSessionRuntime = (
const initialSession = {
provider: PROVIDER,
...(options.providerInstanceId ? { providerInstanceId: options.providerInstanceId } : {}),
status: "connecting",
runtimeMode: options.runtimeMode,
cwd: options.cwd,
@@ -725,13 +740,15 @@ export const makeCodexSessionRuntime = (
const offerEvent = (event: ProviderEvent) => Queue.offer(events, event).pipe(Effect.asVoid);
const emitEvent = (event: Omit<ProviderEvent, "id" | "provider" | "createdAt">) =>
offerEvent({
id: EventId.make(randomUUID()),
provider: PROVIDER,
createdAt: new Date().toISOString(),
...event,
});
Effect.flatMap(Random.nextUUIDv4, (id) =>
offerEvent({
id: EventId.make(id),
provider: PROVIDER,
...(options.providerInstanceId ? { providerInstanceId: options.providerInstanceId } : {}),
createdAt: new Date().toISOString(),
...event,
}),
);
const emitSessionEvent = (method: string, message: string) =>
emitEvent({
kind: "session",
@@ -891,7 +908,7 @@ export const makeCodexSessionRuntime = (
yield* client.handleServerRequest("item/commandExecution/requestApproval", (payload) =>
Effect.gen(function* () {
const requestId = ApprovalRequestId.make(randomUUID());
const requestId = ApprovalRequestId.make(yield* Random.nextUUIDv4);
const turnId = TurnId.make(payload.turnId);
const itemId = ProviderItemId.make(payload.itemId);
const decision = yield* Deferred.make<ProviderApprovalDecision>();
@@ -947,7 +964,7 @@ export const makeCodexSessionRuntime = (
yield* client.handleServerRequest("item/fileChange/requestApproval", (payload) =>
Effect.gen(function* () {
const requestId = ApprovalRequestId.make(randomUUID());
const requestId = ApprovalRequestId.make(yield* Random.nextUUIDv4);
const turnId = TurnId.make(payload.turnId);
const itemId = ProviderItemId.make(payload.itemId);
const decision = yield* Deferred.make<ProviderApprovalDecision>();
@@ -1003,7 +1020,7 @@ export const makeCodexSessionRuntime = (
yield* client.handleServerRequest("item/tool/requestUserInput", (payload) =>
Effect.gen(function* () {
const requestId = ApprovalRequestId.make(randomUUID());
const requestId = ApprovalRequestId.make(yield* Random.nextUUIDv4);
const turnId = TurnId.make(payload.turnId);
const itemId = ProviderItemId.make(payload.itemId);
const answers = yield* Deferred.make<ProviderUserInputAnswers>();
@@ -5,15 +5,27 @@ import { fileURLToPath } from "node:url";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { assert, it } from "@effect/vitest";
import { Deferred, Effect, Fiber, Layer, Stream } from "effect";
import { Context, Deferred, Effect, Fiber, Layer, Schema, Stream } from "effect";
import { createModelSelection } from "@t3tools/shared/model";
import { ApprovalRequestId, type ProviderRuntimeEvent, ThreadId } from "@t3tools/contracts";
import {
ApprovalRequestId,
CursorSettings,
ProviderDriverKind,
type ProviderRuntimeEvent,
ThreadId,
ProviderInstanceId,
} from "@t3tools/contracts";
import { ServerConfig } from "../../config.ts";
import { ServerSettingsService } from "../../serverSettings.ts";
import { CursorAdapter } from "../Services/CursorAdapter.ts";
import { makeCursorAdapterLive } from "./CursorAdapter.ts";
import type { CursorAdapterShape } from "../Services/CursorAdapter.ts";
import { makeCursorAdapter } from "./CursorAdapter.ts";
// Test-local service tag so the rest of the file can keep using `yield* CursorAdapter`.
class CursorAdapter extends Context.Service<CursorAdapter, CursorAdapterShape>()(
"test/CursorAdapter",
) {}
const __dirname = path.dirname(fileURLToPath(import.meta.url));
const mockAgentPath = path.join(__dirname, "../../../scripts/acp-mock-agent.ts");
@@ -91,8 +103,31 @@ async function waitForFileContent(filePath: string, attempts = 40) {
throw new Error(`Timed out waiting for file content at ${filePath}`);
}
// Tests mutate `ServerSettingsService` mid-flight (e.g. setting
// `providers.cursor.binaryPath` to a mock ACP wrapper). The adapter
// captures `cursorSettings` once at construction, so without a resolver
// the mutation is invisible — sessions would spawn the constructor's
// (empty) binary path. Wiring `resolveSettings` through
// `ServerSettingsService.getSettings` makes each session read the latest
// snapshot, matching the old "always read live" behavior that these
// tests assumed.
const makeResolveCursorSettings = Effect.gen(function* () {
const serverSettings = yield* ServerSettingsService;
return serverSettings.getSettings.pipe(
Effect.map((snapshot) => snapshot.providers.cursor),
Effect.orDie,
);
});
const cursorAdapterTestLayer = it.layer(
makeCursorAdapterLive().pipe(
Layer.effect(
CursorAdapter,
Effect.gen(function* () {
const cursorConfig = Schema.decodeSync(CursorSettings)({});
const resolveSettings = yield* makeResolveCursorSettings;
return yield* makeCursorAdapter(cursorConfig, { resolveSettings });
}),
).pipe(
Layer.provideMerge(ServerSettingsService.layerTest()),
Layer.provideMerge(
ServerConfig.layerTest(process.cwd(), {
@@ -120,10 +155,10 @@ cursorAdapterTestLayer("CursorAdapterLive", (it) => {
const session = yield* adapter.startSession({
threadId,
provider: "cursor",
provider: ProviderDriverKind.make("cursor"),
cwd: process.cwd(),
runtimeMode: "full-access",
modelSelection: { provider: "cursor", model: "default" },
modelSelection: { instanceId: ProviderInstanceId.make("cursor"), model: "default" },
});
assert.equal(session.provider, "cursor");
@@ -205,10 +240,10 @@ cursorAdapterTestLayer("CursorAdapterLive", (it) => {
yield* adapter.startSession({
threadId,
provider: "cursor",
provider: ProviderDriverKind.make("cursor"),
cwd: process.cwd(),
runtimeMode: "full-access",
modelSelection: { provider: "cursor", model: "default" },
modelSelection: { instanceId: ProviderInstanceId.make("cursor"), model: "default" },
});
yield* adapter.stopSession(threadId);
@@ -244,17 +279,17 @@ cursorAdapterTestLayer("CursorAdapterLive", (it) => {
[
adapter.startSession({
threadId,
provider: "cursor",
provider: ProviderDriverKind.make("cursor"),
cwd: process.cwd(),
runtimeMode: "full-access",
modelSelection: { provider: "cursor", model: "default" },
modelSelection: { instanceId: ProviderInstanceId.make("cursor"), model: "default" },
}),
adapter.startSession({
threadId,
provider: "cursor",
provider: ProviderDriverKind.make("cursor"),
cwd: process.cwd(),
runtimeMode: "full-access",
modelSelection: { provider: "cursor", model: "default" },
modelSelection: { instanceId: ProviderInstanceId.make("cursor"), model: "default" },
}),
],
{ concurrency: "unbounded" },
@@ -276,7 +311,7 @@ cursorAdapterTestLayer("CursorAdapterLive", (it) => {
const result = yield* adapter
.startSession({
threadId: ThreadId.make("bad-provider"),
provider: "codex",
provider: ProviderDriverKind.make("codex"),
cwd: process.cwd(),
runtimeMode: "full-access",
})
@@ -302,10 +337,10 @@ cursorAdapterTestLayer("CursorAdapterLive", (it) => {
yield* adapter.startSession({
threadId,
provider: "cursor",
provider: ProviderDriverKind.make("cursor"),
cwd: process.cwd(),
runtimeMode: "full-access",
modelSelection: { provider: "cursor", model: "composer-2" },
modelSelection: { instanceId: ProviderInstanceId.make("cursor"), model: "composer-2" },
});
yield* adapter.sendTurn({
@@ -358,7 +393,7 @@ cursorAdapterTestLayer("CursorAdapterLive", (it) => {
providers: { cursor: { binaryPath: wrapperPath } },
});
const modelSelection = createModelSelection("cursor", "gpt-5.4", [
const modelSelection = createModelSelection(ProviderInstanceId.make("cursor"), "gpt-5.4", [
{ id: "reasoning", value: "xhigh" },
{ id: "contextWindow", value: "1m" },
{ id: "fastMode", value: true },
@@ -366,7 +401,7 @@ cursorAdapterTestLayer("CursorAdapterLive", (it) => {
yield* adapter.startSession({
threadId,
provider: "cursor",
provider: ProviderDriverKind.make("cursor"),
cwd: process.cwd(),
runtimeMode: "full-access",
modelSelection,
@@ -460,10 +495,10 @@ cursorAdapterTestLayer("CursorAdapterLive", (it) => {
const program = Effect.gen(function* () {
yield* adapter.startSession({
threadId,
provider: "cursor",
provider: ProviderDriverKind.make("cursor"),
cwd: process.cwd(),
runtimeMode: "approval-required",
modelSelection: { provider: "cursor", model: "default" },
modelSelection: { instanceId: ProviderInstanceId.make("cursor"), model: "default" },
});
const turn = yield* adapter.sendTurn({
@@ -560,7 +595,14 @@ cursorAdapterTestLayer("CursorAdapterLive", (it) => {
);
}).pipe(
Effect.provide(
makeCursorAdapterLive().pipe(
Layer.effect(
CursorAdapter,
Effect.gen(function* () {
const cursorConfig = Schema.decodeSync(CursorSettings)({});
const resolveSettings = yield* makeResolveCursorSettings;
return yield* makeCursorAdapter(cursorConfig, { resolveSettings });
}),
).pipe(
Layer.provideMerge(ServerSettingsService.layerTest()),
Layer.provideMerge(
ServerConfig.layerTest(process.cwd(), {
@@ -615,10 +657,10 @@ cursorAdapterTestLayer("CursorAdapterLive", (it) => {
yield* adapter.startSession({
threadId,
provider: "cursor",
provider: ProviderDriverKind.make("cursor"),
cwd: process.cwd(),
runtimeMode: "full-access",
modelSelection: { provider: "cursor", model: "default" },
modelSelection: { instanceId: ProviderInstanceId.make("cursor"), model: "default" },
});
const turn = yield* adapter.sendTurn({
@@ -714,10 +756,10 @@ cursorAdapterTestLayer("CursorAdapterLive", (it) => {
yield* adapter.startSession({
threadId,
provider: "cursor",
provider: ProviderDriverKind.make("cursor"),
cwd: process.cwd(),
runtimeMode: "full-access",
modelSelection: { provider: "cursor", model: "default" },
modelSelection: { instanceId: ProviderInstanceId.make("cursor"), model: "default" },
});
const turn = yield* adapter.sendTurn({
@@ -836,10 +878,10 @@ cursorAdapterTestLayer("CursorAdapterLive", (it) => {
yield* adapter.startSession({
threadId,
provider: "cursor",
provider: ProviderDriverKind.make("cursor"),
cwd: process.cwd(),
runtimeMode: "approval-required",
modelSelection: { provider: "cursor", model: "default" },
modelSelection: { instanceId: ProviderInstanceId.make("cursor"), model: "default" },
});
const sendTurnFiber = yield* adapter
@@ -906,10 +948,10 @@ cursorAdapterTestLayer("CursorAdapterLive", (it) => {
yield* adapter.startSession({
threadId,
provider: "cursor",
provider: ProviderDriverKind.make("cursor"),
cwd: process.cwd(),
runtimeMode: "approval-required",
modelSelection: { provider: "cursor", model: "default" },
modelSelection: { instanceId: ProviderInstanceId.make("cursor"), model: "default" },
});
const sendTurnFiber = yield* adapter
@@ -949,10 +991,10 @@ cursorAdapterTestLayer("CursorAdapterLive", (it) => {
yield* adapter.startSession({
threadId,
provider: "cursor",
provider: ProviderDriverKind.make("cursor"),
cwd: process.cwd(),
runtimeMode: "full-access",
modelSelection: { provider: "cursor", model: "default" },
modelSelection: { instanceId: ProviderInstanceId.make("cursor"), model: "default" },
});
const sendTurnFiber = yield* adapter
@@ -992,10 +1034,10 @@ cursorAdapterTestLayer("CursorAdapterLive", (it) => {
yield* adapter.startSession({
threadId,
provider: "cursor",
provider: ProviderDriverKind.make("cursor"),
cwd: process.cwd(),
runtimeMode: "full-access",
modelSelection: { provider: "cursor", model: "default" },
modelSelection: { instanceId: ProviderInstanceId.make("cursor"), model: "default" },
});
const sendTurnFiber = yield* adapter
@@ -1035,10 +1077,10 @@ cursorAdapterTestLayer("CursorAdapterLive", (it) => {
yield* adapter.startSession({
threadId,
provider: "cursor",
provider: ProviderDriverKind.make("cursor"),
cwd: process.cwd(),
runtimeMode: "full-access",
modelSelection: { provider: "cursor", model: "default" },
modelSelection: { instanceId: ProviderInstanceId.make("cursor"), model: "default" },
});
const firstEvents = Array.from(yield* Fiber.join(firstConsumer));
@@ -1073,10 +1115,10 @@ cursorAdapterTestLayer("CursorAdapterLive", (it) => {
yield* adapter.startSession({
threadId,
provider: "cursor",
provider: ProviderDriverKind.make("cursor"),
cwd: process.cwd(),
runtimeMode: "full-access",
modelSelection: { provider: "cursor", model: "composer-2" },
modelSelection: { instanceId: ProviderInstanceId.make("cursor"), model: "composer-2" },
});
yield* adapter.sendTurn({
@@ -1089,7 +1131,7 @@ cursorAdapterTestLayer("CursorAdapterLive", (it) => {
threadId,
input: "second turn after switching model",
attachments: [],
modelSelection: createModelSelection("cursor", "composer-2", [
modelSelection: createModelSelection(ProviderInstanceId.make("cursor"), "composer-2", [
{ id: "fastMode", value: true },
]),
});
@@ -1136,17 +1178,17 @@ cursorAdapterTestLayer("CursorAdapterLive", (it) => {
yield* adapter.startSession({
threadId,
provider: "cursor",
provider: ProviderDriverKind.make("cursor"),
cwd: process.cwd(),
runtimeMode: "full-access",
modelSelection: { provider: "cursor", model: "composer-2" },
modelSelection: { instanceId: ProviderInstanceId.make("cursor"), model: "composer-2" },
});
yield* adapter.sendTurn({
threadId,
input: "first turn with fast mode",
attachments: [],
modelSelection: createModelSelection("cursor", "composer-2", [
modelSelection: createModelSelection(ProviderInstanceId.make("cursor"), "composer-2", [
{ id: "fastMode", value: true },
]),
});
@@ -1155,7 +1197,7 @@ cursorAdapterTestLayer("CursorAdapterLive", (it) => {
threadId,
input: "second turn without fast mode",
attachments: [],
modelSelection: createModelSelection("cursor", "composer-2", [
modelSelection: createModelSelection(ProviderInstanceId.make("cursor"), "composer-2", [
{ id: "fastMode", value: false },
]),
});
@@ -1174,4 +1216,91 @@ cursorAdapterTestLayer("CursorAdapterLive", (it) => {
yield* adapter.stopSession(threadId);
}),
);
it.effect(
"applies fast mode on the first turn when modelSelection uses a non-default instance id",
() => {
const customInstanceId = ProviderInstanceId.make("cursor_secondary");
// Custom-instance cases can't share the suite-level `CursorAdapter`
// layer because that one binds `instanceId: "cursor"`. We build a
// fresh layer graph — including a fresh `ServerSettingsService` — so
// mid-test `updateSettings` calls target the same service instance the
// adapter's `resolveSettings` reads from, and so the outer
// `yield* ServerSettingsService` sees the same snapshot as well.
const customAdapterLayer = Layer.effect(
CursorAdapter,
Effect.gen(function* () {
const cursorConfig = Schema.decodeSync(CursorSettings)({});
const resolveSettings = yield* makeResolveCursorSettings;
return yield* makeCursorAdapter(cursorConfig, {
instanceId: customInstanceId,
resolveSettings,
});
}),
).pipe(
Layer.provideMerge(ServerSettingsService.layerTest()),
Layer.provideMerge(
ServerConfig.layerTest(process.cwd(), {
prefix: "t3code-cursor-adapter-custom-instance-",
}),
),
Layer.provideMerge(NodeServices.layer),
);
return Effect.gen(function* () {
const adapter = yield* CursorAdapter;
const serverSettings = yield* ServerSettingsService;
const threadId = ThreadId.make("cursor-fast-mode-custom-instance");
const tempDir = yield* Effect.promise(() => mkdtemp(path.join(os.tmpdir(), "cursor-acp-")));
const requestLogPath = path.join(tempDir, "requests.ndjson");
const argvLogPath = path.join(tempDir, "argv.txt");
yield* Effect.promise(() => writeFile(requestLogPath, "", "utf8"));
const wrapperPath = yield* Effect.promise(() =>
makeProbeWrapper(requestLogPath, argvLogPath),
);
yield* serverSettings.updateSettings({
providers: { cursor: { binaryPath: wrapperPath } },
});
yield* adapter.startSession({
threadId,
provider: ProviderDriverKind.make("cursor"),
cwd: process.cwd(),
runtimeMode: "full-access",
modelSelection: {
instanceId: customInstanceId,
model: "composer-2",
},
});
yield* adapter.sendTurn({
threadId,
input: "first turn with fast mode",
attachments: [],
modelSelection: {
...createModelSelection(ProviderInstanceId.make("cursor"), "composer-2", [
{ id: "fastMode", value: true },
]),
instanceId: customInstanceId,
},
});
const requests = yield* Effect.promise(() => readJsonLines(requestLogPath));
const fastConfigRequests = requests.filter(
(entry) =>
entry.method === "session/set_config_option" &&
(entry.params as Record<string, unknown> | undefined)?.configId === "fast",
);
assert.isAbove(
fastConfigRequests.length,
0,
"fast mode should apply when instance id matches the adapter binding",
);
const lastFastConfig = fastConfigRequests[fastConfigRequests.length - 1];
assert.equal((lastFastConfig?.params as Record<string, unknown>)?.value, "true");
yield* adapter.stopSession(threadId);
}).pipe(Effect.provide(customAdapterLayer));
},
);
});
@@ -7,6 +7,7 @@ import * as nodePath from "node:path";
import {
ApprovalRequestId,
type CursorSettings,
type ProviderOptionSelection,
EventId,
type ProviderApprovalDecision,
@@ -14,6 +15,8 @@ import {
type ProviderRuntimeEvent,
type ProviderSession,
type ProviderUserInputAnswers,
ProviderDriverKind,
ProviderInstanceId,
RuntimeRequestId,
type RuntimeMode,
type ThreadId,
@@ -26,7 +29,6 @@ import {
Exit,
Fiber,
FileSystem,
Layer,
Option,
PubSub,
Random,
@@ -40,7 +42,6 @@ import type * as EffectAcpSchema from "effect-acp/schema";
import { resolveAttachmentPath } from "../../attachmentStore.ts";
import { ServerConfig } from "../../config.ts";
import { ServerSettingsService } from "../../serverSettings.ts";
import {
ProviderAdapterProcessError,
ProviderAdapterRequestError,
@@ -72,19 +73,37 @@ import {
extractPlanMarkdown,
extractTodosAsPlan,
} from "../acp/CursorAcpExtension.ts";
import { CursorAdapter, type CursorAdapterShape } from "../Services/CursorAdapter.ts";
import { type CursorAdapterShape } from "../Services/CursorAdapter.ts";
import { resolveCursorAcpBaseModelId } from "./CursorProvider.ts";
import { type EventNdjsonLogger, makeEventNdjsonLogger } from "./EventNdjsonLogger.ts";
const PROVIDER = "cursor" as const;
const PROVIDER = ProviderDriverKind.make("cursor");
const CURSOR_RESUME_VERSION = 1 as const;
const ACP_PLAN_MODE_ALIASES = ["plan", "architect"];
const ACP_IMPLEMENT_MODE_ALIASES = ["code", "agent", "default", "chat", "implement"];
const ACP_APPROVAL_MODE_ALIASES = ["ask"];
export interface CursorAdapterLiveOptions {
readonly environment?: NodeJS.ProcessEnv;
readonly nativeEventLogPath?: string;
readonly nativeEventLogger?: EventNdjsonLogger;
/**
* Selections are honored when `modelSelection.instanceId` matches this value.
* Defaults to the legacy built-in instance id (`cursor`).
*/
readonly instanceId?: typeof ProviderInstanceId.Type;
/**
* Optional per-session settings resolver. When provided the adapter yields
* this effect at the start of every session and uses the result instead of
* the `cursorSettings` captured at construction.
*
* Production instances bind settings to the instance scope (the hydration
* layer rebuilds the adapter on config change) and leave this undefined.
* Test suites that mutate `ServerSettingsService` mid-flight — e.g. to
* swap `binaryPath` to a mock ACP wrapper — pass a resolver that reads
* the latest snapshot so the closure isn't stale.
*/
readonly resolveSettings?: Effect.Effect<CursorSettings>;
}
interface PendingApproval {
@@ -280,12 +299,15 @@ function selectAutoApprovedPermissionOption(
return undefined;
}
function makeCursorAdapter(options?: CursorAdapterLiveOptions) {
export function makeCursorAdapter(
cursorSettings: CursorSettings,
options?: CursorAdapterLiveOptions,
) {
return Effect.gen(function* () {
const boundInstanceId = options?.instanceId ?? ProviderInstanceId.make("cursor");
const fileSystem = yield* FileSystem.FileSystem;
const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
const serverConfig = yield* Effect.service(ServerConfig);
const serverSettingsService = yield* ServerSettingsService;
const nativeEventLogger =
options?.nativeEventLogger ??
(options?.nativeEventLogPath !== undefined
@@ -440,25 +462,12 @@ function makeCursorAdapter(options?: CursorAdapterLiveOptions) {
const cwd = nodePath.resolve(input.cwd.trim());
const cursorModelSelection =
input.modelSelection?.provider === "cursor" ? input.modelSelection : undefined;
input.modelSelection?.instanceId === boundInstanceId ? input.modelSelection : undefined;
const existing = sessions.get(input.threadId);
if (existing && !existing.stopped) {
yield* stopSessionInternal(existing);
}
const cursorSettings = yield* serverSettingsService.getSettings.pipe(
Effect.map((settings) => settings.providers.cursor),
Effect.mapError(
(error) =>
new ProviderAdapterProcessError({
provider: PROVIDER,
threadId: input.threadId,
detail: error.message,
cause: error,
}),
),
);
const pendingApprovals = new Map<ApprovalRequestId, PendingApproval>();
const pendingUserInputs = new Map<ApprovalRequestId, PendingUserInput>();
const sessionScope = yield* Scope.make("sequential");
@@ -475,8 +484,21 @@ function makeCursorAdapter(options?: CursorAdapterLiveOptions) {
threadId: input.threadId,
});
// Resolve the CursorSettings used to spawn the ACP child. Production
// leaves `options.resolveSettings` undefined so we use the value
// captured at adapter construction — per-instance isolation is
// enforced by the hydration layer rebuilding this adapter whenever
// its config changes. Tests set `resolveSettings` to pull the latest
// snapshot from `ServerSettingsService` so that mid-suite
// `updateSettings({ providers: { cursor: { binaryPath } } })` calls
// actually take effect when the next session spawns.
const effectiveCursorSettings = options?.resolveSettings
? yield* options.resolveSettings
: cursorSettings;
const acp = yield* makeCursorAcpRuntime({
cursorSettings,
cursorSettings: effectiveCursorSettings,
...(options?.environment ? { environment: options.environment } : {}),
childProcessSpawner,
cwd,
...(resumeSessionId ? { resumeSessionId } : {}),
@@ -666,6 +688,7 @@ function makeCursorAdapter(options?: CursorAdapterLiveOptions) {
const now = yield* nowIso;
const session: ProviderSession = {
provider: PROVIDER,
providerInstanceId: boundInstanceId,
status: "ready",
runtimeMode: input.runtimeMode,
cwd,
@@ -815,7 +838,7 @@ function makeCursorAdapter(options?: CursorAdapterLiveOptions) {
const ctx = yield* requireSession(input.threadId);
const turnId = TurnId.make(crypto.randomUUID());
const turnModelSelection =
input.modelSelection?.provider === "cursor" ? input.modelSelection : undefined;
input.modelSelection?.instanceId === boundInstanceId ? input.modelSelection : undefined;
const model = turnModelSelection?.model ?? ctx.session.model;
const resolvedModel = resolveCursorAcpBaseModelId(model);
yield* applyRequestedSessionConfiguration({
@@ -1049,9 +1072,3 @@ function makeCursorAdapter(options?: CursorAdapterLiveOptions) {
} satisfies CursorAdapterShape;
});
}
export const CursorAdapterLive = Layer.effect(CursorAdapter, makeCursorAdapter());
export function makeCursorAdapterLive(opts?: CursorAdapterLiveOptions) {
return Layer.effect(CursorAdapter, makeCursorAdapter(opts));
}
@@ -1,10 +1,7 @@
import * as path from "node:path";
import * as os from "node:os";
import { chmod, mkdtemp, readFile, writeFile } from "node:fs/promises";
import { fileURLToPath } from "node:url";
import * as NodeOS from "node:os";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { Effect } from "effect";
import { Effect, FileSystem, Path } from "effect";
import { describe, expect, it } from "vitest";
import type * as EffectAcpSchema from "effect-acp/schema";
import type { CursorSettings, ServerProviderModel } from "@t3tools/contracts";
@@ -14,6 +11,7 @@ import {
buildCursorProviderSnapshot,
buildCursorCapabilitiesFromConfigOptions,
buildCursorDiscoveredModelsFromConfigOptions,
checkCursorProviderStatus,
discoverCursorModelCapabilitiesViaAcp,
discoverCursorModelsViaAcp,
getCursorFallbackModels,
@@ -25,8 +23,14 @@ import {
resolveCursorAcpConfigUpdates,
} from "./CursorProvider.ts";
const __dirname = path.dirname(fileURLToPath(import.meta.url));
const mockAgentPath = path.join(__dirname, "../../../scripts/acp-mock-agent.ts");
const runNode = <A, E>(
effect: Effect.Effect<A, E, FileSystem.FileSystem | Path.Path>,
): Promise<A> => Effect.runPromise(effect.pipe(Effect.provide(NodeServices.layer)));
const resolveMockAgentPath = Effect.fn("resolveMockAgentPath")(function* () {
const path = yield* Path.Path;
return yield* path.fromFileUrl(new URL("../../../scripts/acp-mock-agent.ts", import.meta.url));
});
function selectDescriptor(
id: string,
@@ -53,8 +57,16 @@ function booleanDescriptor(id: string, label: string, currentValue?: boolean) {
};
}
async function makeMockAgentWrapper(extraEnv?: Record<string, string>) {
const dir = await mkdtemp(path.join(os.tmpdir(), "cursor-provider-mock-"));
const makeMockAgentWrapper = Effect.fn("makeMockAgentWrapper")(function* (
extraEnv?: Record<string, string>,
) {
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const mockAgentPath = yield* resolveMockAgentPath();
const dir = yield* fileSystem.makeTempDirectory({
directory: NodeOS.tmpdir(),
prefix: "cursor-provider-mock-",
});
const wrapperPath = path.join(dir, "fake-agent.sh");
const envExports = Object.entries(extraEnv ?? {})
.map(([key, value]) => `export ${key}=${JSON.stringify(value)}`)
@@ -63,23 +75,80 @@ async function makeMockAgentWrapper(extraEnv?: Record<string, string>) {
${envExports}
exec ${JSON.stringify("bun")} ${JSON.stringify(mockAgentPath)} "$@"
`;
await writeFile(wrapperPath, script, "utf8");
await chmod(wrapperPath, 0o755);
yield* fileSystem.writeFileString(wrapperPath, script);
yield* fileSystem.chmod(wrapperPath, 0o755);
return wrapperPath;
}
});
async function waitForFileContent(filePath: string, attempts = 40): Promise<string> {
const makeMockAgentWithAboutWrapper = Effect.fn("makeMockAgentWithAboutWrapper")(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const mockAgentPath = yield* resolveMockAgentPath();
const dir = yield* fileSystem.makeTempDirectory({
directory: NodeOS.tmpdir(),
prefix: "cursor-provider-about-mock-",
});
const wrapperPath = path.join(dir, "fake-agent.sh");
const script = `#!/bin/sh
if [ "$1" = "about" ]; then
printf 'CLI Version 2026.04.09-f2b0fcd\\n'
printf 'User Email [email protected]\\n'
exit 0
fi
exec ${JSON.stringify("bun")} ${JSON.stringify(mockAgentPath)} "$@"
`;
yield* fileSystem.writeFileString(wrapperPath, script);
yield* fileSystem.chmod(wrapperPath, 0o755);
return wrapperPath;
});
const waitForFileContent = Effect.fn("waitForFileContent")(function* (
filePath: string,
attempts = 40,
) {
const fileSystem = yield* FileSystem.FileSystem;
for (let attempt = 0; attempt < attempts; attempt += 1) {
try {
const content = await readFile(filePath, "utf8");
const content = yield* fileSystem
.readFileString(filePath)
.pipe(Effect.catch(() => Effect.void));
if (content !== undefined) {
if (content.trim().length > 0) {
return content;
}
} catch {}
await new Promise((resolve) => setTimeout(resolve, 50));
}
yield* Effect.sleep("50 millis");
}
throw new Error(`Timed out waiting for file content at ${filePath}`);
}
return yield* Effect.fail(new Error(`Timed out waiting for file content at ${filePath}`));
});
const makeProviderStatusEnvFixture = Effect.fn("makeProviderStatusEnvFixture")(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const tempDir = yield* fileSystem.makeTempDirectory({
directory: NodeOS.tmpdir(),
prefix: "cursor-provider-status-env-",
});
return {
requestLogPath: path.join(tempDir, "requests.ndjson"),
wrapperPath: yield* makeMockAgentWithAboutWrapper(),
};
});
const makeExitLogFixture = Effect.fn("makeExitLogFixture")(function* (prefix: string) {
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const tempDir = yield* fileSystem.makeTempDirectory({
directory: NodeOS.tmpdir(),
prefix,
});
const exitLogPath = path.join(tempDir, "exit.log");
return {
exitLogPath,
wrapperPath: yield* makeMockAgentWrapper({
T3_ACP_EXIT_LOG_PATH: exitLogPath,
}),
};
});
const parameterizedGpt54ConfigOptions = [
{
@@ -428,9 +497,38 @@ describe("buildCursorDiscoveredModelsFromConfigOptions", () => {
});
});
describe("checkCursorProviderStatus", () => {
it("passes the injected environment to ACP model discovery", async () => {
const { requestLogPath, wrapperPath } = await runNode(makeProviderStatusEnvFixture());
const provider = await Effect.runPromise(
checkCursorProviderStatus(
{
enabled: true,
binaryPath: wrapperPath,
apiEndpoint: "",
customModels: [],
},
{
...process.env,
T3_ACP_REQUEST_LOG_PATH: requestLogPath,
},
).pipe(Effect.provide(NodeServices.layer)),
);
expect(provider.models.map((model) => model.slug)).toEqual([
"default",
"composer-2",
"gpt-5.4",
"claude-opus-4-6",
]);
await expect(runNode(waitForFileContent(requestLogPath))).resolves.toContain("initialize");
});
});
describe("discoverCursorModelsViaAcp", () => {
it("keeps the ACP probe runtime alive long enough to discover models", async () => {
const wrapperPath = await makeMockAgentWrapper();
const wrapperPath = await runNode(makeMockAgentWrapper());
const models = await Effect.runPromise(
discoverCursorModelsViaAcp({
@@ -450,11 +548,9 @@ describe("discoverCursorModelsViaAcp", () => {
});
it("closes the ACP probe runtime after discovery completes", async () => {
const tempDir = await mkdtemp(path.join(os.tmpdir(), "cursor-provider-exit-log-"));
const exitLogPath = path.join(tempDir, "exit.log");
const wrapperPath = await makeMockAgentWrapper({
T3_ACP_EXIT_LOG_PATH: exitLogPath,
});
const { exitLogPath, wrapperPath } = await runNode(
makeExitLogFixture("cursor-provider-exit-log-"),
);
await Effect.runPromise(
discoverCursorModelsViaAcp({
@@ -465,18 +561,16 @@ describe("discoverCursorModelsViaAcp", () => {
}).pipe(Effect.provide(NodeServices.layer)),
);
const exitLog = await waitForFileContent(exitLogPath);
const exitLog = await runNode(waitForFileContent(exitLogPath));
expect(exitLog).toContain("SIGTERM");
});
});
describe("discoverCursorModelCapabilitiesViaAcp", () => {
it("closes all ACP probe runtimes after capability enrichment completes", async () => {
const tempDir = await mkdtemp(path.join(os.tmpdir(), "cursor-capabilities-exit-log-"));
const exitLogPath = path.join(tempDir, "exit.log");
const wrapperPath = await makeMockAgentWrapper({
T3_ACP_EXIT_LOG_PATH: exitLogPath,
});
const { exitLogPath, wrapperPath } = await runNode(
makeExitLogFixture("cursor-capabilities-exit-log-"),
);
const existingModels: ReadonlyArray<ServerProviderModel> = [
{ slug: "default", name: "Auto", isCustom: false, capabilities: emptyCapabilities },
{ slug: "composer-2", name: "Composer 2", isCustom: false, capabilities: emptyCapabilities },
@@ -508,7 +602,7 @@ describe("discoverCursorModelCapabilitiesViaAcp", () => {
"claude-opus-4-6",
]);
const exitLog = await waitForFileContent(exitLogPath);
const exitLog = await runNode(waitForFileContent(exitLogPath));
expect(exitLog.match(/SIGTERM/g)?.length ?? 0).toBe(4);
});
});
@@ -530,6 +624,7 @@ describe("parseCursorAboutOutput", () => {
status: "ready",
auth: {
status: "authenticated",
email: "[email protected]",
type: "Team",
label: "Cursor Team Subscription",
},
+359 -320
View File
@@ -1,6 +1,4 @@
import * as nodeFs from "node:fs";
import * as nodeOs from "node:os";
import * as nodePath from "node:path";
import type {
CursorSettings,
@@ -10,10 +8,10 @@ import type {
ServerProviderAuth,
ServerProviderModel,
ServerProviderState,
ServerSettingsError,
} from "@t3tools/contracts";
import { ProviderDriverKind } from "@t3tools/contracts";
import type * as EffectAcpSchema from "effect-acp/schema";
import { Cause, Effect, Equal, Exit, Layer, Option, Result, Stream } from "effect";
import { Cause, Effect, Exit, FileSystem, Layer, Option, Path, Result } from "effect";
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
import {
createModelCapabilities,
@@ -29,13 +27,11 @@ import {
isCommandMissingCause,
providerModelsFromSettings,
type CommandResult,
type ServerProviderDraft,
} from "../providerSnapshot.ts";
import { makeManagedServerProvider } from "../makeManagedServerProvider.ts";
import { CursorProvider } from "../Services/CursorProvider.ts";
import { AcpSessionRuntime } from "../acp/AcpSessionRuntime.ts";
import { ServerSettingsService } from "../../serverSettings.ts";
const PROVIDER = "cursor" as const;
const PROVIDER = ProviderDriverKind.make("cursor");
const CURSOR_PRESENTATION = {
displayName: "Cursor",
badgeLabel: "Early Access",
@@ -48,7 +44,6 @@ const EMPTY_CAPABILITIES: ModelCapabilities = createModelCapabilities({
const CURSOR_ACP_MODEL_DISCOVERY_TIMEOUT_MS = 15_000;
const CURSOR_ACP_MODEL_CAPABILITY_TIMEOUT = "4 seconds";
const CURSOR_ACP_MODEL_DISCOVERY_CONCURRENCY = 4;
const CURSOR_REFRESH_INTERVAL = "1 hour";
const CURSOR_PARAMETERIZED_MODEL_PICKER_MIN_VERSION_DATE = 2026_04_08;
export const CURSOR_PARAMETERIZED_MODEL_PICKER_CAPABILITIES = {
_meta: {
@@ -56,13 +51,14 @@ export const CURSOR_PARAMETERIZED_MODEL_PICKER_CAPABILITIES = {
},
} satisfies NonNullable<EffectAcpSchema.InitializeRequest["clientCapabilities"]>;
function buildInitialCursorProviderSnapshot(cursorSettings: CursorSettings): ServerProvider {
export function buildInitialCursorProviderSnapshot(
cursorSettings: CursorSettings,
): ServerProviderDraft {
const checkedAt = new Date().toISOString();
const models = getCursorFallbackModels(cursorSettings);
if (!cursorSettings.enabled) {
return buildServerProvider({
provider: PROVIDER,
presentation: CURSOR_PRESENTATION,
enabled: false,
checkedAt,
@@ -78,7 +74,6 @@ function buildInitialCursorProviderSnapshot(cursorSettings: CursorSettings): Ser
}
return buildServerProvider({
provider: PROVIDER,
presentation: CURSOR_PRESENTATION,
enabled: true,
checkedAt,
@@ -112,7 +107,12 @@ function flattenSessionConfigSelectOptions(
}
return configOption.options.flatMap((entry) =>
"value" in entry
? [{ value: entry.value.trim(), name: entry.name.trim() } satisfies CursorSessionSelectOption]
? [
{
value: entry.value.trim(),
name: entry.name.trim(),
} satisfies CursorSessionSelectOption,
]
: entry.options.map(
(option) =>
({
@@ -392,7 +392,10 @@ export function buildCursorDiscoveredModelsFromConfigOptions(
);
}
const makeCursorAcpProbeRuntime = (cursorSettings: CursorSettings) =>
const makeCursorAcpProbeRuntime = (
cursorSettings: CursorSettings,
environment: NodeJS.ProcessEnv = process.env,
) =>
Effect.gen(function* () {
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
const acpContext = yield* Layer.build(
@@ -404,6 +407,7 @@ const makeCursorAcpProbeRuntime = (cursorSettings: CursorSettings) =>
"acp",
],
cwd: process.cwd(),
env: environment,
},
cwd: process.cwd(),
clientInfo: { name: "t3-code-provider-probe", version: "0.0.0" },
@@ -417,7 +421,12 @@ const makeCursorAcpProbeRuntime = (cursorSettings: CursorSettings) =>
const withCursorAcpProbeRuntime = <A, E, R>(
cursorSettings: CursorSettings,
useRuntime: (acp: AcpSessionRuntime["Service"]) => Effect.Effect<A, E, R>,
) => makeCursorAcpProbeRuntime(cursorSettings).pipe(Effect.flatMap(useRuntime), Effect.scoped);
environment: NodeJS.ProcessEnv = process.env,
) =>
makeCursorAcpProbeRuntime(cursorSettings, environment).pipe(
Effect.flatMap(useRuntime),
Effect.scoped,
);
function normalizeCursorConfigOptionToken(value: string | null | undefined): string {
return (
@@ -460,12 +469,18 @@ export function resolveCursorAcpBaseModelId(model: string | null | undefined): s
export function resolveCursorAcpConfigUpdates(
configOptions: ReadonlyArray<EffectAcpSchema.SessionConfigOption> | null | undefined,
selections: ReadonlyArray<ProviderOptionSelection> | null | undefined,
): ReadonlyArray<{ readonly configId: string; readonly value: string | boolean }> {
): ReadonlyArray<{
readonly configId: string;
readonly value: string | boolean;
}> {
if (!configOptions || configOptions.length === 0) {
return [];
}
const updates: Array<{ readonly configId: string; readonly value: string | boolean }> = [];
const updates: Array<{
readonly configId: string;
readonly value: string | boolean;
}> = [];
const reasoningOption = findCursorEffortConfigOption(configOptions);
const requestedReasoning = normalizeCursorReasoningValue(
@@ -525,43 +540,129 @@ export function resolveCursorAcpConfigUpdates(
return updates;
}
export const discoverCursorModelsViaAcp = (cursorSettings: CursorSettings) =>
withCursorAcpProbeRuntime(cursorSettings, (acp) =>
Effect.map(acp.start(), (started) =>
buildCursorDiscoveredModelsFromConfigOptions(started.sessionSetupResult.configOptions ?? []),
),
export const discoverCursorModelsViaAcp = (
cursorSettings: CursorSettings,
environment: NodeJS.ProcessEnv = process.env,
) =>
withCursorAcpProbeRuntime(
cursorSettings,
(acp) =>
Effect.map(acp.start(), (started) =>
buildCursorDiscoveredModelsFromConfigOptions(
started.sessionSetupResult.configOptions ?? [],
),
),
environment,
);
export const discoverCursorModelCapabilitiesViaAcp = (
cursorSettings: CursorSettings,
existingModels: ReadonlyArray<ServerProviderModel>,
environment: NodeJS.ProcessEnv = process.env,
) =>
withCursorAcpProbeRuntime(cursorSettings, (acp) =>
Effect.gen(function* () {
const started = yield* acp.start();
const initialConfigOptions = started.sessionSetupResult.configOptions ?? [];
const modelOption = findCursorModelConfigOption(initialConfigOptions);
const modelChoices = flattenSessionConfigSelectOptions(modelOption);
if (!modelOption || modelChoices.length === 0) {
return [];
}
withCursorAcpProbeRuntime(
cursorSettings,
(acp) =>
Effect.gen(function* () {
const started = yield* acp.start();
const initialConfigOptions = started.sessionSetupResult.configOptions ?? [];
const modelOption = findCursorModelConfigOption(initialConfigOptions);
const modelChoices = flattenSessionConfigSelectOptions(modelOption);
if (!modelOption || modelChoices.length === 0) {
return [];
}
const currentModelValue =
modelOption.type === "select" ? modelOption.currentValue?.trim() || undefined : undefined;
const capabilitiesBySlug = new Map<string, ModelCapabilities>();
if (currentModelValue) {
capabilitiesBySlug.set(
currentModelValue,
buildCursorCapabilitiesFromConfigOptions(initialConfigOptions),
const currentModelValue =
modelOption.type === "select" ? modelOption.currentValue?.trim() || undefined : undefined;
const capabilitiesBySlug = new Map<string, ModelCapabilities>();
if (currentModelValue) {
capabilitiesBySlug.set(
currentModelValue,
buildCursorCapabilitiesFromConfigOptions(initialConfigOptions),
);
}
const targetModelSlugs = new Set(
existingModels
.filter((model) => !model.isCustom && !hasCursorModelCapabilities(model))
.map((model) => model.slug),
);
}
if (targetModelSlugs.size === 0) {
return buildCursorDiscoveredModels(
modelChoices.map((modelChoice) => ({
slug: modelChoice.value.trim(),
name: modelChoice.name.trim(),
capabilities: capabilitiesBySlug.get(modelChoice.value.trim()) ?? EMPTY_CAPABILITIES,
})),
);
}
const probedCapabilities = yield* Effect.forEach(
modelChoices,
(modelChoice) => {
const modelSlug = modelChoice.value.trim();
if (
!modelSlug ||
!targetModelSlugs.has(modelSlug) ||
capabilitiesBySlug.has(modelSlug)
) {
return Effect.void.pipe(
Effect.as<readonly [string, ModelCapabilities] | undefined>(undefined),
);
}
return withCursorAcpProbeRuntime(
cursorSettings,
(probeAcp) =>
Effect.gen(function* () {
const probeStarted = yield* probeAcp.start();
const probeConfigOptions = probeStarted.sessionSetupResult.configOptions ?? [];
const probeModelOption = findCursorModelConfigOption(probeConfigOptions);
const probeCurrentModelValue =
probeModelOption?.type === "select"
? probeModelOption.currentValue?.trim() || undefined
: undefined;
yield* Effect.annotateCurrentSpan({
"cursor.acp.model.value": modelSlug,
"cursor.acp.model.currentValue": probeCurrentModelValue,
"cursor.acp.config_option_id": probeModelOption?.id ?? modelOption.id,
});
const nextConfigOptions =
probeCurrentModelValue === modelSlug
? probeConfigOptions
: yield* probeAcp
.setConfigOption(probeModelOption?.id ?? modelOption.id, modelSlug)
.pipe(
Effect.map((response) => response.configOptions ?? probeConfigOptions),
);
return [
modelSlug,
buildCursorCapabilitiesFromConfigOptions(nextConfigOptions),
] as const;
}),
environment,
).pipe(
Effect.timeout(CURSOR_ACP_MODEL_CAPABILITY_TIMEOUT),
Effect.retry({ times: 3 }),
Effect.withSpan("cursor-acp-model-capability-probe"),
Effect.catchCause((cause) =>
Effect.logWarning("Cursor ACP capability probe failed", {
modelSlug,
cause: Cause.pretty(cause),
}),
),
);
},
{ concurrency: CURSOR_ACP_MODEL_DISCOVERY_CONCURRENCY },
);
for (const entry of probedCapabilities) {
if (!entry) {
continue;
}
capabilitiesBySlug.set(entry[0], entry[1]);
}
const targetModelSlugs = new Set(
existingModels
.filter((model) => !model.isCustom && !hasCursorModelCapabilities(model))
.map((model) => model.slug),
);
if (targetModelSlugs.size === 0) {
return buildCursorDiscoveredModels(
modelChoices.map((modelChoice) => ({
slug: modelChoice.value.trim(),
@@ -569,73 +670,8 @@ export const discoverCursorModelCapabilitiesViaAcp = (
capabilities: capabilitiesBySlug.get(modelChoice.value.trim()) ?? EMPTY_CAPABILITIES,
})),
);
}
const probedCapabilities = yield* Effect.forEach(
modelChoices,
(modelChoice) => {
const modelSlug = modelChoice.value.trim();
if (!modelSlug || !targetModelSlugs.has(modelSlug) || capabilitiesBySlug.has(modelSlug)) {
return Effect.void.pipe(
Effect.as<readonly [string, ModelCapabilities] | undefined>(undefined),
);
}
return withCursorAcpProbeRuntime(cursorSettings, (probeAcp) =>
Effect.gen(function* () {
const probeStarted = yield* probeAcp.start();
const probeConfigOptions = probeStarted.sessionSetupResult.configOptions ?? [];
const probeModelOption = findCursorModelConfigOption(probeConfigOptions);
const probeCurrentModelValue =
probeModelOption?.type === "select"
? probeModelOption.currentValue?.trim() || undefined
: undefined;
yield* Effect.annotateCurrentSpan({
"cursor.acp.model.value": modelSlug,
"cursor.acp.model.currentValue": probeCurrentModelValue,
"cursor.acp.config_option_id": probeModelOption?.id ?? modelOption.id,
});
const nextConfigOptions =
probeCurrentModelValue === modelSlug
? probeConfigOptions
: yield* probeAcp
.setConfigOption(probeModelOption?.id ?? modelOption.id, modelSlug)
.pipe(Effect.map((response) => response.configOptions ?? probeConfigOptions));
return [
modelSlug,
buildCursorCapabilitiesFromConfigOptions(nextConfigOptions),
] as const;
}),
).pipe(
Effect.timeout(CURSOR_ACP_MODEL_CAPABILITY_TIMEOUT),
Effect.retry({ times: 3 }),
Effect.withSpan("cursor-acp-model-capability-probe"),
Effect.catchCause((cause) =>
Effect.logWarning("Cursor ACP capability probe failed", {
modelSlug,
cause: Cause.pretty(cause),
}),
),
);
},
{ concurrency: CURSOR_ACP_MODEL_DISCOVERY_CONCURRENCY },
);
for (const entry of probedCapabilities) {
if (!entry) {
continue;
}
capabilitiesBySlug.set(entry[0], entry[1]);
}
return buildCursorDiscoveredModels(
modelChoices.map((modelChoice) => ({
slug: modelChoice.value.trim(),
name: modelChoice.name.trim(),
capabilities: capabilitiesBySlug.get(modelChoice.value.trim()) ?? EMPTY_CAPABILITIES,
})),
);
}).pipe(Effect.withSpan("cursor-acp-model-capability-discovery", {})),
}).pipe(Effect.withSpan("cursor-acp-model-capability-discovery", {})),
environment,
);
export function getCursorFallbackModels(
@@ -683,10 +719,9 @@ export function buildCursorProviderSnapshot(input: {
readonly parsed: CursorAboutResult;
readonly discoveredModels?: ReadonlyArray<ServerProviderModel>;
readonly discoveryWarning?: string;
}): ServerProvider {
}): ServerProviderDraft {
const message = joinProviderMessages(input.parsed.message, input.discoveryWarning);
return buildServerProvider({
provider: PROVIDER,
presentation: CURSOR_PRESENTATION,
enabled: input.cursorSettings.enabled,
checkedAt: input.checkedAt,
@@ -811,14 +846,13 @@ function isCursorAboutJsonFormatUnsupported(result: CommandResult): boolean {
);
}
function readCursorCliConfigChannel(): string | undefined {
try {
const configPath = nodePath.join(nodeOs.homedir(), ".cursor", "cli-config.json");
return parseCursorCliConfigChannel(nodeFs.readFileSync(configPath, "utf8"));
} catch {
return undefined;
}
}
const readCursorCliConfigChannel = Effect.fn("readCursorCliConfigChannel")(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const configPath = path.join(nodeOs.homedir(), ".cursor", "cli-config.json");
const raw = yield* fileSystem.readFileString(configPath).pipe(Effect.orElseSucceed(() => ""));
return parseCursorCliConfigChannel(raw);
});
export function getCursorParameterizedModelPickerUnsupportedMessage(input: {
readonly version: string | null | undefined;
@@ -934,6 +968,7 @@ export function parseCursorAboutOutput(result: CommandResult): CursorAboutResult
status: "ready",
auth: {
status: "authenticated",
email: userEmail,
...authMetadata,
},
};
@@ -989,17 +1024,22 @@ export function parseCursorAboutOutput(result: CommandResult): CursorAboutResult
}
// Any non-empty email value means authenticated.
return { version, status: "ready", auth: { status: "authenticated" } };
return {
version,
status: "ready",
auth: { status: "authenticated", email: userEmail },
};
}
const runCursorCommand = (args: ReadonlyArray<string>) =>
const runCursorCommand = (
cursorSettings: CursorSettings,
args: ReadonlyArray<string>,
environment: NodeJS.ProcessEnv = process.env,
) =>
Effect.gen(function* () {
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
const cursorSettings = yield* Effect.service(ServerSettingsService).pipe(
Effect.flatMap((service) => service.getSettings),
Effect.map((settings) => settings.providers.cursor),
);
const command = ChildProcess.make(cursorSettings.binaryPath, [...args], {
env: environment,
shell: process.platform === "win32",
});
@@ -1016,203 +1056,202 @@ const runCursorCommand = (args: ReadonlyArray<string>) =>
return { stdout, stderr, code: exitCode } satisfies CommandResult;
}).pipe(Effect.scoped);
const runCursorAboutCommand = Effect.gen(function* () {
const jsonResult = yield* runCursorCommand(["about", "--format", "json"]);
if (!isCursorAboutJsonFormatUnsupported(jsonResult)) {
return jsonResult;
const runCursorAboutCommand = (
cursorSettings: CursorSettings,
environment: NodeJS.ProcessEnv = process.env,
) =>
Effect.gen(function* () {
const jsonResult = yield* runCursorCommand(
cursorSettings,
["about", "--format", "json"],
environment,
);
if (!isCursorAboutJsonFormatUnsupported(jsonResult)) {
return jsonResult;
}
return yield* runCursorCommand(cursorSettings, ["about"], environment);
});
export const checkCursorProviderStatus = Effect.fn("checkCursorProviderStatus")(function* (
cursorSettings: CursorSettings,
environment: NodeJS.ProcessEnv = process.env,
): Effect.fn.Return<
ServerProviderDraft,
never,
ChildProcessSpawner.ChildProcessSpawner | FileSystem.FileSystem | Path.Path
> {
const checkedAt = new Date().toISOString();
const fallbackModels = getCursorFallbackModels(cursorSettings);
if (!cursorSettings.enabled) {
return buildServerProvider({
presentation: CURSOR_PRESENTATION,
enabled: false,
checkedAt,
models: fallbackModels,
probe: {
installed: false,
version: null,
status: "warning",
auth: { status: "unknown" },
message: "Cursor is disabled in T3 Code settings.",
},
});
}
return yield* runCursorCommand(["about"]);
// Single `agent about` probe: returns version + auth status in one call.
const aboutProbe = yield* runCursorAboutCommand(cursorSettings, environment).pipe(
Effect.timeoutOption(ABOUT_TIMEOUT_MS),
Effect.result,
);
if (Result.isFailure(aboutProbe)) {
const error = aboutProbe.failure;
return buildServerProvider({
presentation: CURSOR_PRESENTATION,
enabled: cursorSettings.enabled,
checkedAt,
models: fallbackModels,
probe: {
installed: !isCommandMissingCause(error),
version: null,
status: "error",
auth: { status: "unknown" },
message: isCommandMissingCause(error)
? "Cursor Agent CLI (`agent`) is not installed or not on PATH."
: `Failed to execute Cursor Agent CLI health check: ${error instanceof Error ? error.message : String(error)}.`,
},
});
}
if (Option.isNone(aboutProbe.success)) {
return buildServerProvider({
presentation: CURSOR_PRESENTATION,
enabled: cursorSettings.enabled,
checkedAt,
models: fallbackModels,
probe: {
installed: true,
version: null,
status: "error",
auth: { status: "unknown" },
message: "Cursor Agent CLI is installed but timed out while running `agent about`.",
},
});
}
const parsed = parseCursorAboutOutput(aboutProbe.success.value);
const cursorCliConfigChannel = yield* readCursorCliConfigChannel();
const parameterizedModelPickerUnsupportedMessage =
getCursorParameterizedModelPickerUnsupportedMessage({
version: parsed.version,
channel: cursorCliConfigChannel,
});
if (parameterizedModelPickerUnsupportedMessage) {
return buildServerProvider({
presentation: CURSOR_PRESENTATION,
enabled: cursorSettings.enabled,
checkedAt,
models: fallbackModels,
probe: {
installed: true,
version: parsed.version,
status: "error",
auth: parsed.auth,
message:
parsed.auth.status === "unauthenticated" && parsed.message
? `${parameterizedModelPickerUnsupportedMessage} ${parsed.message}`
: parameterizedModelPickerUnsupportedMessage,
},
});
}
let discoveredModels = Option.none<ReadonlyArray<ServerProviderModel>>();
let discoveryWarning: string | undefined;
if (parsed.auth.status !== "unauthenticated") {
const discoveryExit = yield* Effect.exit(
discoverCursorModelsViaAcp(cursorSettings, environment).pipe(
Effect.timeoutOption(CURSOR_ACP_MODEL_DISCOVERY_TIMEOUT_MS),
),
);
if (Exit.isFailure(discoveryExit)) {
yield* Effect.logWarning("Cursor ACP model discovery failed", {
cause: Cause.pretty(discoveryExit.cause),
});
discoveryWarning = "Cursor ACP model discovery failed. Check server logs for details.";
} else if (Option.isNone(discoveryExit.value)) {
discoveryWarning = `Cursor ACP model discovery timed out after ${CURSOR_ACP_MODEL_DISCOVERY_TIMEOUT_MS}ms.`;
} else if (discoveryExit.value.value.length === 0) {
discoveryWarning = "Cursor ACP model discovery returned no built-in models.";
} else {
discoveredModels = discoveryExit.value;
}
}
return buildCursorProviderSnapshot({
checkedAt,
cursorSettings,
parsed,
discoveredModels: Option.getOrElse(
Option.filter(discoveredModels, (models) => models.length > 0),
() => [] as const,
),
...(discoveryWarning ? { discoveryWarning } : {}),
});
});
export const checkCursorProviderStatus = Effect.fn("checkCursorProviderStatus")(
function* (): Effect.fn.Return<
ServerProvider,
ServerSettingsError,
ChildProcessSpawner.ChildProcessSpawner | ServerSettingsService
> {
const cursorSettings = yield* Effect.service(ServerSettingsService).pipe(
Effect.flatMap((service) => service.getSettings),
Effect.map((settings) => settings.providers.cursor),
);
const checkedAt = new Date().toISOString();
const fallbackModels = getCursorFallbackModels(cursorSettings);
export function hasUncapturedCursorModels(snapshot: Pick<ServerProvider, "models">): boolean {
return snapshot.models.some((model) => !model.isCustom && !hasCursorModelCapabilities(model));
}
if (!cursorSettings.enabled) {
return buildServerProvider({
provider: PROVIDER,
presentation: CURSOR_PRESENTATION,
enabled: false,
checkedAt,
models: fallbackModels,
probe: {
installed: false,
version: null,
status: "warning",
auth: { status: "unknown" },
message: "Cursor is disabled in T3 Code settings.",
},
});
}
/**
* Background capability enrichment for a Cursor snapshot.
*
* Used by `CursorDriver` as the `makeManagedServerProvider.enrichSnapshot`
* hook: runs the slow ACP per-model capability probe, and republishes the
* snapshot through `publishSnapshot` when new capabilities arrive. Skips
* the probe when the provider is disabled, unauthenticated, or has no
* uncaptured models. Keeps `EMPTY_CAPABILITIES` and the `PROVIDER` literal
* private to this module.
*/
export const enrichCursorSnapshot = (input: {
readonly settings: CursorSettings;
readonly environment?: NodeJS.ProcessEnv;
readonly snapshot: ServerProvider;
readonly publishSnapshot: (snapshot: ServerProvider) => Effect.Effect<void>;
readonly stampIdentity?: (snapshot: ServerProvider) => ServerProvider;
}): Effect.Effect<void, never, ChildProcessSpawner.ChildProcessSpawner> => {
const { settings, snapshot, publishSnapshot } = input;
const stampIdentity = input.stampIdentity ?? ((value) => value);
// Single `agent about` probe: returns version + auth status in one call.
const aboutProbe = yield* runCursorAboutCommand.pipe(
Effect.timeoutOption(ABOUT_TIMEOUT_MS),
Effect.result,
);
if (
!settings.enabled ||
snapshot.auth.status === "unauthenticated" ||
!hasUncapturedCursorModels(snapshot)
) {
return Effect.void;
}
if (Result.isFailure(aboutProbe)) {
const error = aboutProbe.failure;
return buildServerProvider({
provider: PROVIDER,
presentation: CURSOR_PRESENTATION,
enabled: cursorSettings.enabled,
checkedAt,
models: fallbackModels,
probe: {
installed: !isCommandMissingCause(error),
version: null,
status: "error",
auth: { status: "unknown" },
message: isCommandMissingCause(error)
? "Cursor Agent CLI (`agent`) is not installed or not on PATH."
: `Failed to execute Cursor Agent CLI health check: ${error instanceof Error ? error.message : String(error)}.`,
},
});
}
if (Option.isNone(aboutProbe.success)) {
return buildServerProvider({
provider: PROVIDER,
presentation: CURSOR_PRESENTATION,
enabled: cursorSettings.enabled,
checkedAt,
models: fallbackModels,
probe: {
installed: true,
version: null,
status: "error",
auth: { status: "unknown" },
message: "Cursor Agent CLI is installed but timed out while running `agent about`.",
},
});
}
const parsed = parseCursorAboutOutput(aboutProbe.success.value);
const parameterizedModelPickerUnsupportedMessage =
getCursorParameterizedModelPickerUnsupportedMessage({
version: parsed.version,
channel: readCursorCliConfigChannel(),
});
if (parameterizedModelPickerUnsupportedMessage) {
return buildServerProvider({
provider: PROVIDER,
presentation: CURSOR_PRESENTATION,
enabled: cursorSettings.enabled,
checkedAt,
models: fallbackModels,
probe: {
installed: true,
version: parsed.version,
status: "error",
auth: parsed.auth,
message:
parsed.auth.status === "unauthenticated" && parsed.message
? `${parameterizedModelPickerUnsupportedMessage} ${parsed.message}`
: parameterizedModelPickerUnsupportedMessage,
},
});
}
let discoveredModels = Option.none<ReadonlyArray<ServerProviderModel>>();
let discoveryWarning: string | undefined;
if (parsed.auth.status !== "unauthenticated") {
const discoveryExit = yield* Effect.exit(
discoverCursorModelsViaAcp(cursorSettings).pipe(
Effect.timeoutOption(CURSOR_ACP_MODEL_DISCOVERY_TIMEOUT_MS),
),
);
if (Exit.isFailure(discoveryExit)) {
yield* Effect.logWarning("Cursor ACP model discovery failed", {
cause: Cause.pretty(discoveryExit.cause),
});
discoveryWarning = "Cursor ACP model discovery failed. Check server logs for details.";
} else if (Option.isNone(discoveryExit.value)) {
discoveryWarning = `Cursor ACP model discovery timed out after ${CURSOR_ACP_MODEL_DISCOVERY_TIMEOUT_MS}ms.`;
} else if (discoveryExit.value.value.length === 0) {
discoveryWarning = "Cursor ACP model discovery returned no built-in models.";
} else {
discoveredModels = discoveryExit.value;
return discoverCursorModelCapabilitiesViaAcp(settings, snapshot.models, input.environment).pipe(
Effect.flatMap((discoveredModels) => {
if (discoveredModels.length === 0) {
return Effect.void;
}
}
return buildCursorProviderSnapshot({
checkedAt,
cursorSettings,
parsed,
discoveredModels: Option.getOrElse(
Option.filter(discoveredModels, (models) => models.length > 0),
() => [] as const,
),
...(discoveryWarning ? { discoveryWarning } : {}),
});
},
);
export const CursorProviderLive = Layer.effect(
CursorProvider,
Effect.gen(function* () {
const serverSettings = yield* ServerSettingsService;
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
const checkProvider = checkCursorProviderStatus().pipe(
Effect.provideService(ServerSettingsService, serverSettings),
Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
);
return yield* makeManagedServerProvider<CursorSettings>({
getSettings: serverSettings.getSettings.pipe(
Effect.map((settings) => settings.providers.cursor),
Effect.orDie,
),
streamSettings: serverSettings.streamChanges.pipe(
Stream.map((settings) => settings.providers.cursor),
),
haveSettingsChanged: (previous, next) => !Equal.equals(previous, next),
initialSnapshot: buildInitialCursorProviderSnapshot,
checkProvider,
enrichSnapshot: ({ settings, snapshot, publishSnapshot }) => {
if (
!settings.enabled ||
snapshot.auth.status === "unauthenticated" ||
!snapshot.models.some((model) => !model.isCustom && !hasCursorModelCapabilities(model))
) {
return Effect.void;
}
return discoverCursorModelCapabilitiesViaAcp(settings, snapshot.models).pipe(
Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
Effect.flatMap((discoveredModels) => {
if (discoveredModels.length === 0) {
return Effect.void;
}
return publishSnapshot({
...snapshot,
models: providerModelsFromSettings(
discoveredModels,
PROVIDER,
settings.customModels,
EMPTY_CAPABILITIES,
),
});
}),
Effect.catchCause((cause) =>
Effect.logWarning("Cursor ACP background capability enrichment failed", {
models: snapshot.models.map((model) => model.slug),
cause: Cause.pretty(cause),
}).pipe(Effect.asVoid),
return publishSnapshot(
stampIdentity({
...snapshot,
models: providerModelsFromSettings(
discoveredModels,
PROVIDER,
settings.customModels,
EMPTY_CAPABILITIES,
),
);
},
refreshInterval: CURSOR_REFRESH_INTERVAL,
});
}),
);
}),
);
}),
Effect.catchCause((cause) =>
Effect.logWarning("Cursor ACP background capability enrichment failed", {
models: snapshot.models.map((model) => model.slug),
cause: Cause.pretty(cause),
}).pipe(Effect.asVoid),
),
);
};
@@ -2,14 +2,20 @@ import assert from "node:assert/strict";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { it } from "@effect/vitest";
import { Effect, Layer, Option } from "effect";
import { Context, Effect, Exit, Fiber, Layer, Option, Schema, Scope, Stream } from "effect";
import { beforeEach } from "vitest";
import { ThreadId } from "@t3tools/contracts";
import {
OpenCodeSettings,
ProviderDriverKind,
ProviderInstanceId,
ThreadId,
} from "@t3tools/contracts";
import { createModelSelection } from "@t3tools/shared/model";
import { ServerConfig } from "../../config.ts";
import { ServerSettingsService } from "../../serverSettings.ts";
import { ProviderSessionDirectory } from "../Services/ProviderSessionDirectory.ts";
import { OpenCodeAdapter } from "../Services/OpenCodeAdapter.ts";
import type { OpenCodeAdapterShape } from "../Services/OpenCodeAdapter.ts";
import {
OpenCodeRuntime,
OpenCodeRuntimeError,
@@ -17,10 +23,15 @@ import {
} from "../opencodeRuntime.ts";
import {
appendOpenCodeAssistantTextDelta,
makeOpenCodeAdapterLive,
makeOpenCodeAdapter,
mergeOpenCodeAssistantText,
} from "./OpenCodeAdapter.ts";
// Test-local service tag so the rest of the file can keep using `yield* OpenCodeAdapter`.
class OpenCodeAdapter extends Context.Service<OpenCodeAdapter, OpenCodeAdapterShape>()(
"test/OpenCodeAdapter",
) {}
const asThreadId = (value: string): ThreadId => ThreadId.make(value);
type MessageEntry = {
@@ -39,6 +50,7 @@ const runtimeMock = {
abortCalls: [] as string[],
closeCalls: [] as string[],
revertCalls: [] as Array<{ sessionID: string; messageID?: string }>,
promptCalls: [] as Array<unknown>,
promptAsyncError: null as Error | null,
closeError: null as Error | null,
messages: [] as MessageEntry[],
@@ -51,6 +63,7 @@ const runtimeMock = {
this.state.abortCalls.length = 0;
this.state.closeCalls.length = 0;
this.state.revertCalls.length = 0;
this.state.promptCalls.length = 0;
this.state.promptAsyncError = null;
this.state.closeError = null;
this.state.messages = [];
@@ -111,7 +124,8 @@ const OpenCodeRuntimeTestDouble: OpenCodeRuntimeShape = {
abort: async ({ sessionID }: { sessionID: string }) => {
runtimeMock.state.abortCalls.push(sessionID);
},
promptAsync: async () => {
promptAsync: async (input: unknown) => {
runtimeMock.state.promptCalls.push(input);
if (runtimeMock.state.promptAsyncError) {
throw runtimeMock.state.promptAsyncError;
}
@@ -165,7 +179,24 @@ const providerSessionDirectoryTestLayer = Layer.succeed(ProviderSessionDirectory
listBindings: () => Effect.succeed([]),
});
const OpenCodeAdapterTestLayer = makeOpenCodeAdapterLive().pipe(
// The adapter now receives its settings as a plain argument (the old design
// read from `ServerSettingsService` internally). The test-only
// `ServerSettingsService` below is still kept because other dependencies in
// the layer graph reach for it — but the routing values the assertions
// probe (serverUrl, serverPassword) must be threaded directly through the
// decoded `OpenCodeSettings`.
const openCodeAdapterTestSettings = Schema.decodeSync(OpenCodeSettings)({
binaryPath: "fake-opencode",
serverUrl: "http://127.0.0.1:9999",
serverPassword: "secret-password",
});
const OpenCodeAdapterTestLayer = Layer.effect(
OpenCodeAdapter,
Effect.gen(function* () {
return yield* makeOpenCodeAdapter(openCodeAdapterTestSettings);
}),
).pipe(
Layer.provideMerge(Layer.succeed(OpenCodeRuntime, OpenCodeRuntimeTestDouble)),
Layer.provideMerge(ServerConfig.layerTest(process.cwd(), process.cwd())),
Layer.provideMerge(
@@ -196,7 +227,7 @@ it.layer(OpenCodeAdapterTestLayer)("OpenCodeAdapterLive", (it) => {
const adapter = yield* OpenCodeAdapter;
const session = yield* adapter.startSession({
provider: "opencode",
provider: ProviderDriverKind.make("opencode"),
threadId: asThreadId("thread-opencode"),
runtimeMode: "full-access",
});
@@ -215,7 +246,7 @@ it.layer(OpenCodeAdapterTestLayer)("OpenCodeAdapterLive", (it) => {
Effect.gen(function* () {
const adapter = yield* OpenCodeAdapter;
yield* adapter.startSession({
provider: "opencode",
provider: ProviderDriverKind.make("opencode"),
threadId: asThreadId("thread-opencode"),
runtimeMode: "full-access",
});
@@ -230,16 +261,42 @@ it.layer(OpenCodeAdapterTestLayer)("OpenCodeAdapterLive", (it) => {
}),
);
it.effect("emits one session.exited event when stopping a session", () =>
Effect.gen(function* () {
const adapter = yield* OpenCodeAdapter;
const threadId = asThreadId("thread-opencode-stop-event");
const eventsFiber = yield* adapter.streamEvents.pipe(
Stream.filter((event) => event.threadId === threadId),
Stream.take(3),
Stream.runCollect,
Effect.forkChild,
);
yield* adapter.startSession({
provider: ProviderDriverKind.make("opencode"),
threadId,
runtimeMode: "full-access",
});
yield* adapter.stopSession(threadId);
const events = Array.from(yield* Fiber.join(eventsFiber).pipe(Effect.timeout("1 second")));
assert.deepEqual(
events.map((event) => event.type),
["session.started", "thread.started", "session.exited"],
);
}),
);
it.effect("clears session state even when cleanup finalizers throw", () =>
Effect.gen(function* () {
const adapter = yield* OpenCodeAdapter;
yield* adapter.startSession({
provider: "opencode",
provider: ProviderDriverKind.make("opencode"),
threadId: asThreadId("thread-stop-all-a"),
runtimeMode: "full-access",
});
yield* adapter.startSession({
provider: "opencode",
provider: ProviderDriverKind.make("opencode"),
threadId: asThreadId("thread-stop-all-b"),
runtimeMode: "full-access",
});
@@ -261,11 +318,44 @@ it.layer(OpenCodeAdapterTestLayer)("OpenCodeAdapterLive", (it) => {
}),
);
it.effect("completes streamEvents when the adapter scope closes", () =>
Effect.gen(function* () {
const scope = yield* Scope.make("sequential");
let scopeClosed = false;
try {
const adapterLayer = Layer.effect(
OpenCodeAdapter,
makeOpenCodeAdapter(openCodeAdapterTestSettings),
).pipe(
Layer.provideMerge(Layer.succeed(OpenCodeRuntime, OpenCodeRuntimeTestDouble)),
Layer.provideMerge(ServerConfig.layerTest(process.cwd(), process.cwd())),
Layer.provideMerge(ServerSettingsService.layerTest()),
Layer.provideMerge(providerSessionDirectoryTestLayer),
Layer.provideMerge(NodeServices.layer),
);
const context = yield* Layer.buildWithScope(adapterLayer, scope);
const adapter = yield* Effect.service(OpenCodeAdapter).pipe(Effect.provide(context));
const eventsFiber = yield* adapter.streamEvents.pipe(Stream.runCollect, Effect.forkChild);
yield* Scope.close(scope, Exit.void);
scopeClosed = true;
const exit = yield* Fiber.await(eventsFiber).pipe(Effect.timeout("1 second"));
assert.equal(Exit.hasInterrupts(exit), true);
} finally {
if (!scopeClosed) {
yield* Scope.close(scope, Exit.void).pipe(Effect.ignore);
}
}
}),
);
it.effect("rolls back session state when sendTurn fails before OpenCode accepts the prompt", () =>
Effect.gen(function* () {
const adapter = yield* OpenCodeAdapter;
yield* adapter.startSession({
provider: "opencode",
provider: ProviderDriverKind.make("opencode"),
threadId: asThreadId("thread-send-turn-failure"),
runtimeMode: "full-access",
});
@@ -276,7 +366,7 @@ it.layer(OpenCodeAdapterTestLayer)("OpenCodeAdapterLive", (it) => {
threadId: asThreadId("thread-send-turn-failure"),
input: "Fix it",
modelSelection: {
provider: "opencode",
instanceId: ProviderInstanceId.make("opencode"),
model: "openai/gpt-5",
},
})
@@ -299,12 +389,158 @@ it.layer(OpenCodeAdapterTestLayer)("OpenCodeAdapterLive", (it) => {
}),
);
it.effect("passes agent and variant options for the adapter's bound custom instance id", () => {
const customInstanceId = ProviderInstanceId.make("opencode_zen");
const adapterLayer = Layer.effect(
OpenCodeAdapter,
Effect.gen(function* () {
return yield* makeOpenCodeAdapter(openCodeAdapterTestSettings, {
instanceId: customInstanceId,
});
}),
).pipe(
Layer.provideMerge(Layer.succeed(OpenCodeRuntime, OpenCodeRuntimeTestDouble)),
Layer.provideMerge(ServerConfig.layerTest(process.cwd(), process.cwd())),
Layer.provideMerge(ServerSettingsService.layerTest()),
Layer.provideMerge(providerSessionDirectoryTestLayer),
Layer.provideMerge(NodeServices.layer),
);
return Effect.gen(function* () {
const adapter = yield* OpenCodeAdapter;
yield* adapter.startSession({
provider: ProviderDriverKind.make("opencode"),
threadId: asThreadId("thread-custom-instance"),
runtimeMode: "full-access",
});
yield* adapter.sendTurn({
threadId: asThreadId("thread-custom-instance"),
input: "Fix it",
modelSelection: createModelSelection(
ProviderInstanceId.make("opencode_zen"),
"anthropic/claude-sonnet-4-5",
[
{ id: "agent", value: "github-copilot" },
{ id: "variant", value: "high" },
],
),
});
assert.deepEqual(runtimeMock.state.promptCalls.at(-1), {
sessionID: "http://127.0.0.1:9999/session",
model: {
providerID: "anthropic",
modelID: "claude-sonnet-4-5",
},
agent: "github-copilot",
variant: "high",
parts: [{ type: "text", text: "Fix it" }],
});
}).pipe(Effect.provide(adapterLayer));
});
it.effect("uses the bound custom instance id for fallback sendTurn model selection", () => {
const customInstanceId = ProviderInstanceId.make("opencode_zen");
const adapterLayer = Layer.effect(
OpenCodeAdapter,
Effect.gen(function* () {
return yield* makeOpenCodeAdapter(openCodeAdapterTestSettings, {
instanceId: customInstanceId,
});
}),
).pipe(
Layer.provideMerge(Layer.succeed(OpenCodeRuntime, OpenCodeRuntimeTestDouble)),
Layer.provideMerge(ServerConfig.layerTest(process.cwd(), process.cwd())),
Layer.provideMerge(ServerSettingsService.layerTest()),
Layer.provideMerge(providerSessionDirectoryTestLayer),
Layer.provideMerge(NodeServices.layer),
);
return Effect.gen(function* () {
const adapter = yield* OpenCodeAdapter;
const threadId = asThreadId("thread-custom-instance-fallback-model");
yield* adapter.startSession({
provider: ProviderDriverKind.make("opencode"),
threadId,
runtimeMode: "full-access",
modelSelection: createModelSelection(
ProviderInstanceId.make("opencode_zen"),
"anthropic/claude-sonnet-4-5",
),
});
yield* adapter.sendTurn({
threadId,
input: "Fix it",
});
assert.deepEqual(runtimeMock.state.promptCalls.at(-1), {
sessionID: "http://127.0.0.1:9999/session",
model: {
providerID: "anthropic",
modelID: "claude-sonnet-4-5",
},
parts: [{ type: "text", text: "Fix it" }],
});
}).pipe(Effect.provide(adapterLayer));
});
it.effect("rejects sendTurn model selections for another instance id", () => {
const customInstanceId = ProviderInstanceId.make("opencode_zen");
const adapterLayer = Layer.effect(
OpenCodeAdapter,
Effect.gen(function* () {
return yield* makeOpenCodeAdapter(openCodeAdapterTestSettings, {
instanceId: customInstanceId,
});
}),
).pipe(
Layer.provideMerge(Layer.succeed(OpenCodeRuntime, OpenCodeRuntimeTestDouble)),
Layer.provideMerge(ServerConfig.layerTest(process.cwd(), process.cwd())),
Layer.provideMerge(ServerSettingsService.layerTest()),
Layer.provideMerge(providerSessionDirectoryTestLayer),
Layer.provideMerge(NodeServices.layer),
);
return Effect.gen(function* () {
const adapter = yield* OpenCodeAdapter;
const threadId = asThreadId("thread-custom-instance-wrong-selection");
yield* adapter.startSession({
provider: ProviderDriverKind.make("opencode"),
threadId,
runtimeMode: "full-access",
});
const error = yield* adapter
.sendTurn({
threadId,
input: "Fix it",
modelSelection: createModelSelection(
ProviderInstanceId.make("opencode"),
"anthropic/claude-sonnet-4-5",
),
})
.pipe(Effect.flip);
assert.equal(error._tag, "ProviderAdapterValidationError");
if (error._tag !== "ProviderAdapterValidationError") {
throw new Error("Unexpected error type");
}
assert.equal(
error.issue,
"OpenCode model selection is bound to instance 'opencode', expected 'opencode_zen'.",
);
assert.deepEqual(runtimeMock.state.promptCalls, []);
}).pipe(Effect.provide(adapterLayer));
});
it.effect("reverts the full thread when rollback removes every assistant turn", () =>
Effect.gen(function* () {
const adapter = yield* OpenCodeAdapter;
const threadId = asThreadId("thread-rollback-all");
yield* adapter.startSession({
provider: "opencode",
provider: ProviderDriverKind.make("opencode"),
threadId,
runtimeMode: "full-access",
});
@@ -396,9 +632,14 @@ it.layer(OpenCodeAdapterTestLayer)("OpenCodeAdapterLive", (it) => {
close: () => Effect.void,
};
const adapterLayer = makeOpenCodeAdapterLive({
nativeEventLogger,
}).pipe(
const adapterLayer = Layer.effect(
OpenCodeAdapter,
Effect.gen(function* () {
return yield* makeOpenCodeAdapter(openCodeAdapterTestSettings, {
nativeEventLogger,
});
}),
).pipe(
Layer.provideMerge(Layer.succeed(OpenCodeRuntime, OpenCodeRuntimeTestDouble)),
Layer.provideMerge(ServerConfig.layerTest(process.cwd(), process.cwd())),
Layer.provideMerge(
@@ -419,7 +660,7 @@ it.layer(OpenCodeAdapterTestLayer)("OpenCodeAdapterLive", (it) => {
const session = yield* Effect.gen(function* () {
const adapter = yield* OpenCodeAdapter;
const started = yield* adapter.startSession({
provider: "opencode",
provider: ProviderDriverKind.make("opencode"),
threadId: asThreadId("thread-native-log"),
runtimeMode: "full-access",
});
@@ -475,9 +716,12 @@ it.layer(OpenCodeAdapterTestLayer)("OpenCodeAdapterLive", (it) => {
close: () => Effect.void,
};
const adapterLayer = makeOpenCodeAdapterLive({
nativeEventLogger,
}).pipe(
const adapterLayer = Layer.effect(
OpenCodeAdapter,
makeOpenCodeAdapter(openCodeAdapterTestSettings, {
nativeEventLogger,
}),
).pipe(
Layer.provideMerge(Layer.succeed(OpenCodeRuntime, OpenCodeRuntimeTestDouble)),
Layer.provideMerge(ServerConfig.layerTest(process.cwd(), process.cwd())),
Layer.provideMerge(
@@ -504,7 +748,7 @@ it.layer(OpenCodeAdapterTestLayer)("OpenCodeAdapterLive", (it) => {
const { sessions, closeCallsDuringRun } = yield* Effect.gen(function* () {
const adapter = yield* OpenCodeAdapter;
yield* adapter.startSession({
provider: "opencode",
provider: ProviderDriverKind.make("opencode"),
threadId: asThreadId("thread-native-log-failure"),
runtimeMode: "full-access",
});
File diff suppressed because it is too large. Load diff
@@ -2,27 +2,36 @@ import assert from "node:assert/strict";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { it } from "@effect/vitest";
import { Effect, Layer } from "effect";
import { Effect, Layer, Schema } from "effect";
import { beforeEach } from "vitest";
import { OpenCodeSettings } from "@t3tools/contracts";
import { ServerConfig } from "../../config.ts";
import { ServerSettingsService } from "../../serverSettings.ts";
import { OpenCodeProvider } from "../Services/OpenCodeProvider.ts";
import {
OpenCodeRuntime,
OpenCodeRuntimeError,
type OpenCodeRuntimeShape,
} from "../opencodeRuntime.ts";
import { OpenCodeProviderLive } from "./OpenCodeProvider.ts";
import { checkOpenCodeProviderStatus } from "./OpenCodeProvider.ts";
import type { OpenCodeInventory } from "../opencodeRuntime.ts";
const DEFAULT_VERSION_STDOUT = "opencode 1.14.19\n";
/**
* The legacy `OpenCodeProviderLive` Layer + `OpenCodeProvider` service tag
* are deleted. The snapshot-producing logic they wrapped now lives in the
* standalone `checkOpenCodeProviderStatus(settings, cwd)` Effect, which
* drivers call directly when building their per-instance snapshot
* `ServerProviderShape`. Tests mirror that shape: build a settings payload,
* invoke the check, assert on the returned snapshot.
*/
const runtimeMock = {
state: {
runVersionError: null as Error | null,
versionStdout: DEFAULT_VERSION_STDOUT,
inventoryError: null as Error | null,
closeCalls: 0,
inventory: {
providerList: { connected: [] as string[], all: [] as unknown[], default: {} },
agents: [] as unknown[],
@@ -32,6 +41,7 @@ const runtimeMock = {
this.state.runVersionError = null;
this.state.versionStdout = DEFAULT_VERSION_STDOUT;
this.state.inventoryError = null;
this.state.closeCalls = 0;
this.state.inventory = {
providerList: { connected: [], all: [] as unknown[], default: {} },
agents: [] as unknown[],
@@ -46,10 +56,19 @@ const OpenCodeRuntimeTestDouble: OpenCodeRuntimeShape = {
exitCode: Effect.never,
}),
connectToOpenCodeServer: ({ serverUrl }) =>
Effect.succeed({
url: serverUrl ?? "http://127.0.0.1:4301",
exitCode: null,
external: Boolean(serverUrl),
Effect.gen(function* () {
if (!serverUrl) {
yield* Effect.addFinalizer(() =>
Effect.sync(() => {
runtimeMock.state.closeCalls += 1;
}),
);
}
return {
url: serverUrl ?? "http://127.0.0.1:4301",
exitCode: null,
external: Boolean(serverUrl),
};
}),
runOpenCodeCommand: () =>
runtimeMock.state.runVersionError
@@ -79,20 +98,26 @@ beforeEach(() => {
runtimeMock.reset();
});
const makeTestLayer = (settingsOverrides?: Parameters<typeof ServerSettingsService.layerTest>[0]) =>
OpenCodeProviderLive.pipe(
Layer.provideMerge(Layer.succeed(OpenCodeRuntime, OpenCodeRuntimeTestDouble)),
Layer.provideMerge(ServerConfig.layerTest(process.cwd(), process.cwd())),
Layer.provideMerge(ServerSettingsService.layerTest(settingsOverrides)),
Layer.provideMerge(NodeServices.layer),
);
const testLayer = Layer.succeed(OpenCodeRuntime, OpenCodeRuntimeTestDouble).pipe(
Layer.provideMerge(ServerConfig.layerTest(process.cwd(), process.cwd())),
Layer.provideMerge(NodeServices.layer),
);
it.layer(makeTestLayer())("OpenCodeProviderLive", (it) => {
const makeOpenCodeSettings = (overrides?: Partial<OpenCodeSettings>): OpenCodeSettings =>
Schema.decodeSync(OpenCodeSettings)({
enabled: true,
binaryPath: "opencode",
serverUrl: "",
serverPassword: "",
customModels: [],
...overrides,
});
it.layer(testLayer)("checkOpenCodeProviderStatus", (it) => {
it.effect("shows a codex-style missing binary message", () =>
Effect.gen(function* () {
runtimeMock.state.runVersionError = new Error("spawn opencode ENOENT");
const provider = yield* OpenCodeProvider;
const snapshot = yield* provider.refresh;
const snapshot = yield* checkOpenCodeProviderStatus(makeOpenCodeSettings(), process.cwd());
assert.equal(snapshot.status, "error");
assert.equal(snapshot.installed, false);
@@ -103,8 +128,7 @@ it.layer(makeTestLayer())("OpenCodeProviderLive", (it) => {
it.effect("hides generic Effect.tryPromise text for local CLI probe failures", () =>
Effect.gen(function* () {
runtimeMock.state.runVersionError = new Error("An error occurred in Effect.tryPromise");
const provider = yield* OpenCodeProvider;
const snapshot = yield* provider.refresh;
const snapshot = yield* checkOpenCodeProviderStatus(makeOpenCodeSettings(), process.cwd());
assert.equal(snapshot.status, "error");
assert.equal(snapshot.installed, true);
@@ -112,33 +136,6 @@ it.layer(makeTestLayer())("OpenCodeProviderLive", (it) => {
}),
);
it.effect("refuses to probe when opencode is older than the required minimum", () =>
Effect.gen(function* () {
runtimeMock.state.versionStdout = "opencode 1.4.7\n";
const provider = yield* OpenCodeProvider;
const snapshot = yield* provider.refresh;
assert.equal(snapshot.status, "error");
assert.equal(snapshot.installed, true);
assert.equal(snapshot.version, "1.4.7");
assert.ok(snapshot.message?.includes("1.14.19"));
assert.ok(snapshot.message?.toLowerCase().includes("upgrade"));
}),
);
it.effect("refuses to probe when opencode --version output is unparseable", () =>
Effect.gen(function* () {
runtimeMock.state.versionStdout = "garbled binary output\n";
const provider = yield* OpenCodeProvider;
const snapshot = yield* provider.refresh;
assert.equal(snapshot.status, "error");
assert.equal(snapshot.installed, true);
assert.equal(snapshot.version, null);
assert.ok(snapshot.message?.includes("1.14.19"));
}),
);
it.effect("emits OpenCode variant defaults so trait picker can resolve a visible selection", () =>
Effect.gen(function* () {
runtimeMock.state.inventory = {
@@ -171,8 +168,7 @@ it.layer(makeTestLayer())("OpenCodeProviderLive", (it) => {
],
};
const provider = yield* OpenCodeProvider;
const snapshot = yield* provider.refresh;
const snapshot = yield* checkOpenCodeProviderStatus(makeOpenCodeSettings(), process.cwd());
const model = snapshot.models.find((entry) => entry.slug === "openai/gpt-5.4");
assert.ok(model);
@@ -180,31 +176,41 @@ it.layer(makeTestLayer())("OpenCodeProviderLive", (it) => {
(descriptor) => descriptor.id === "variant" && descriptor.type === "select",
);
assert.ok(variantDescriptor && variantDescriptor.type === "select");
assert.equal(variantDescriptor.options.find((option) => option.isDefault)?.id, "medium");
assert.equal(
variantDescriptor.options.find((option) => option.isDefault === true)?.id,
"medium",
);
const agentDescriptor = model.capabilities?.optionDescriptors?.find(
(descriptor) => descriptor.id === "agent" && descriptor.type === "select",
);
assert.ok(agentDescriptor && agentDescriptor.type === "select");
assert.equal(agentDescriptor.options.find((option) => option.isDefault)?.id, "build");
assert.equal(
agentDescriptor.options.find((option) => option.isDefault === true)?.id,
"build",
);
}),
);
it.effect("closes the local OpenCode server scope after provider refresh", () =>
Effect.gen(function* () {
yield* checkOpenCodeProviderStatus(makeOpenCodeSettings(), process.cwd());
assert.equal(runtimeMock.state.closeCalls, 1);
}),
);
});
it.layer(
makeTestLayer({
providers: {
opencode: {
serverUrl: "http://127.0.0.1:9999",
serverPassword: "secret-password",
},
},
}),
)("OpenCodeProviderLive with configured server URL", (it) => {
it.layer(testLayer)("checkOpenCodeProviderStatus with configured server URL", (it) => {
it.effect("surfaces a friendly auth error for configured servers", () =>
Effect.gen(function* () {
runtimeMock.state.inventoryError = new Error("401 Unauthorized");
const provider = yield* OpenCodeProvider;
const snapshot = yield* provider.refresh;
const snapshot = yield* checkOpenCodeProviderStatus(
makeOpenCodeSettings({
serverUrl: "http://127.0.0.1:9999",
serverPassword: "secret-password",
}),
process.cwd(),
);
assert.equal(snapshot.status, "error");
assert.equal(snapshot.installed, true);
@@ -220,8 +226,13 @@ it.layer(
runtimeMock.state.inventoryError = new Error(
"fetch failed: connect ECONNREFUSED 127.0.0.1:9999",
);
const provider = yield* OpenCodeProvider;
const snapshot = yield* provider.refresh;
const snapshot = yield* checkOpenCodeProviderStatus(
makeOpenCodeSettings({
serverUrl: "http://127.0.0.1:9999",
serverPassword: "secret-password",
}),
process.cwd(),
);
assert.equal(snapshot.status, "error");
assert.equal(snapshot.installed, true);
@@ -1,24 +1,21 @@
import type {
ModelCapabilities,
OpenCodeSettings,
ServerProvider,
ServerProviderModel,
import {
ProviderDriverKind,
type ModelCapabilities,
type OpenCodeSettings,
type ServerProviderModel,
} from "@t3tools/contracts";
import { Cause, Data, Effect, Equal, Layer, Stream } from "effect";
import { Cause, Data, Effect } from "effect";
import { createModelCapabilities } from "@t3tools/shared/model";
import { ServerConfig } from "../../config.ts";
import { ServerSettingsService } from "../../serverSettings.ts";
import { makeManagedServerProvider } from "../makeManagedServerProvider.ts";
import {
buildServerProvider,
nonEmptyTrimmed,
parseGenericCliVersion,
providerModelsFromSettings,
type ServerProviderDraft,
} from "../providerSnapshot.ts";
import { compareCliVersions } from "../cliVersion.ts";
import { OpenCodeProvider } from "../Services/OpenCodeProvider.ts";
import {
OpenCodeRuntime,
openCodeRuntimeErrorDetail,
@@ -26,7 +23,7 @@ import {
} from "../opencodeRuntime.ts";
import type { Agent, ProviderListResponse } from "@opencode-ai/sdk/v2";
const PROVIDER = "opencode" as const;
const PROVIDER = ProviderDriverKind.make("opencode");
const OPENCODE_PRESENTATION = {
displayName: "OpenCode",
showInteractionModeToggle: false,
@@ -251,7 +248,9 @@ function flattenOpenCodeModels(input: OpenCodeInventory): ReadonlyArray<ServerPr
return models.toSorted((left, right) => left.name.localeCompare(right.name));
}
const makePendingOpenCodeProvider = (openCodeSettings: OpenCodeSettings): ServerProvider => {
export const makePendingOpenCodeProvider = (
openCodeSettings: OpenCodeSettings,
): ServerProviderDraft => {
const checkedAt = new Date().toISOString();
const models = providerModelsFromSettings(
[],
@@ -262,7 +261,6 @@ const makePendingOpenCodeProvider = (openCodeSettings: OpenCodeSettings): Server
if (!openCodeSettings.enabled) {
return buildServerProvider({
provider: PROVIDER,
presentation: OPENCODE_PRESENTATION,
enabled: false,
checkedAt,
@@ -281,7 +279,6 @@ const makePendingOpenCodeProvider = (openCodeSettings: OpenCodeSettings): Server
}
return buildServerProvider({
provider: PROVIDER,
presentation: OPENCODE_PRESENTATION,
enabled: true,
checkedAt,
@@ -296,210 +293,179 @@ const makePendingOpenCodeProvider = (openCodeSettings: OpenCodeSettings): Server
});
};
export const OpenCodeProviderLive = Layer.effect(
OpenCodeProvider,
Effect.gen(function* () {
const serverSettings = yield* ServerSettingsService;
const serverConfig = yield* ServerConfig;
const openCodeRuntime = yield* OpenCodeRuntime;
export const checkOpenCodeProviderStatus = Effect.fn("checkOpenCodeProviderStatus")(function* (
openCodeSettings: OpenCodeSettings,
cwd: string,
environment: NodeJS.ProcessEnv = process.env,
): Effect.fn.Return<ServerProviderDraft, never, OpenCodeRuntime> {
const openCodeRuntime = yield* OpenCodeRuntime;
const checkedAt = new Date().toISOString();
const customModels = openCodeSettings.customModels;
const isExternalServer = openCodeSettings.serverUrl.trim().length > 0;
const checkOpenCodeProviderStatus = Effect.fn("checkOpenCodeProviderStatus")(function* (input: {
readonly settings: OpenCodeSettings;
readonly cwd: string;
}): Effect.fn.Return<ServerProvider, never> {
const checkedAt = new Date().toISOString();
const customModels = input.settings.customModels;
const isExternalServer = input.settings.serverUrl.trim().length > 0;
const fallback = (cause: unknown, version: string | null = null) => {
const failure = formatOpenCodeProbeError({
cause,
isExternalServer,
serverUrl: input.settings.serverUrl,
});
return buildServerProvider({
provider: PROVIDER,
presentation: OPENCODE_PRESENTATION,
enabled: input.settings.enabled,
checkedAt,
models: providerModelsFromSettings(
[],
PROVIDER,
customModels,
DEFAULT_OPENCODE_MODEL_CAPABILITIES,
),
probe: {
installed: failure.installed,
version,
status: "error",
auth: { status: "unknown" },
message: failure.message,
},
});
};
if (!input.settings.enabled) {
return buildServerProvider({
provider: PROVIDER,
presentation: OPENCODE_PRESENTATION,
enabled: false,
checkedAt,
models: providerModelsFromSettings(
[],
PROVIDER,
customModels,
DEFAULT_OPENCODE_MODEL_CAPABILITIES,
),
probe: {
installed: false,
version: null,
status: "warning",
auth: { status: "unknown" },
message: isExternalServer
? "OpenCode is disabled in T3 Code settings. A server URL is configured."
: "OpenCode is disabled in T3 Code settings.",
},
});
}
let version: string | null = null;
if (!isExternalServer) {
const versionExit = yield* Effect.exit(
openCodeRuntime
.runOpenCodeCommand({
binaryPath: input.settings.binaryPath,
args: ["--version"],
})
.pipe(
Effect.mapError(
(cause) =>
new OpenCodeProbeError({ cause, detail: openCodeRuntimeErrorDetail(cause) }),
),
),
);
if (versionExit._tag === "Failure") {
return fallback(Cause.squash(versionExit.cause));
}
version = parseGenericCliVersion(versionExit.value.stdout) ?? null;
if (!version) {
return fallback(
new Error(
`Unable to determine OpenCode version from \`opencode --version\` output. T3 Code requires OpenCode v${MINIMUM_OPENCODE_VERSION} or newer.`,
),
null,
);
}
if (compareCliVersions(version, MINIMUM_OPENCODE_VERSION) < 0) {
return buildServerProvider({
provider: PROVIDER,
presentation: OPENCODE_PRESENTATION,
enabled: input.settings.enabled,
checkedAt,
models: providerModelsFromSettings(
[],
PROVIDER,
customModels,
DEFAULT_OPENCODE_MODEL_CAPABILITIES,
),
probe: {
installed: true,
version,
status: "error",
auth: { status: "unknown" },
message: `OpenCode v${version} is too old. Upgrade to v${MINIMUM_OPENCODE_VERSION} or newer.`,
},
});
}
}
const inventoryExit = yield* Effect.exit(
Effect.scoped(
Effect.gen(function* () {
const server = yield* openCodeRuntime
.connectToOpenCodeServer({
binaryPath: input.settings.binaryPath,
serverUrl: input.settings.serverUrl,
})
.pipe(
Effect.mapError(
(cause) =>
new OpenCodeProbeError({ cause, detail: openCodeRuntimeErrorDetail(cause) }),
),
);
return yield* openCodeRuntime
.loadOpenCodeInventory(
openCodeRuntime.createOpenCodeSdkClient({
baseUrl: server.url,
directory: input.cwd,
...(isExternalServer && input.settings.serverPassword
? { serverPassword: input.settings.serverPassword }
: {}),
}),
)
.pipe(
Effect.mapError(
(cause) =>
new OpenCodeProbeError({ cause, detail: openCodeRuntimeErrorDetail(cause) }),
),
);
}),
),
);
if (inventoryExit._tag === "Failure") {
return fallback(Cause.squash(inventoryExit.cause), version);
}
const models = providerModelsFromSettings(
flattenOpenCodeModels(inventoryExit.value),
const fallback = (cause: unknown, version: string | null = null) => {
const failure = formatOpenCodeProbeError({
cause,
isExternalServer,
serverUrl: openCodeSettings.serverUrl,
});
return buildServerProvider({
presentation: OPENCODE_PRESENTATION,
enabled: openCodeSettings.enabled,
checkedAt,
models: providerModelsFromSettings(
[],
PROVIDER,
customModels,
DEFAULT_OPENCODE_MODEL_CAPABILITIES,
),
probe: {
installed: failure.installed,
version,
status: "error",
auth: { status: "unknown" },
message: failure.message,
},
});
};
if (!openCodeSettings.enabled) {
return buildServerProvider({
presentation: OPENCODE_PRESENTATION,
enabled: false,
checkedAt,
models: providerModelsFromSettings(
[],
PROVIDER,
customModels,
DEFAULT_OPENCODE_MODEL_CAPABILITIES,
),
probe: {
installed: false,
version: null,
status: "warning",
auth: { status: "unknown" },
message: isExternalServer
? "OpenCode is disabled in T3 Code settings. A server URL is configured."
: "OpenCode is disabled in T3 Code settings.",
},
});
}
let version: string | null = null;
if (!isExternalServer) {
const versionExit = yield* Effect.exit(
openCodeRuntime
.runOpenCodeCommand({
binaryPath: openCodeSettings.binaryPath,
args: ["--version"],
environment,
})
.pipe(
Effect.mapError(
(cause) => new OpenCodeProbeError({ cause, detail: openCodeRuntimeErrorDetail(cause) }),
),
),
);
if (versionExit._tag === "Failure") {
return fallback(Cause.squash(versionExit.cause));
}
version = parseGenericCliVersion(versionExit.value.stdout) ?? null;
if (!version) {
return fallback(
new Error(
`Unable to determine OpenCode version from \`opencode --version\` output. T3 Code requires OpenCode v${MINIMUM_OPENCODE_VERSION} or newer.`,
),
null,
);
const connectedCount = inventoryExit.value.providerList.connected.length;
}
if (compareCliVersions(version, MINIMUM_OPENCODE_VERSION) < 0) {
return buildServerProvider({
provider: PROVIDER,
presentation: OPENCODE_PRESENTATION,
enabled: true,
enabled: openCodeSettings.enabled,
checkedAt,
models,
models: providerModelsFromSettings(
[],
PROVIDER,
customModels,
DEFAULT_OPENCODE_MODEL_CAPABILITIES,
),
probe: {
installed: true,
version,
status: connectedCount > 0 ? "ready" : "warning",
auth: {
status: connectedCount > 0 ? "authenticated" : "unknown",
type: "opencode",
},
message:
connectedCount > 0
? `${connectedCount} upstream provider${connectedCount === 1 ? "" : "s"} connected through ${isExternalServer ? "the configured OpenCode server" : "OpenCode"}.`
: isExternalServer
? "Connected to the configured OpenCode server, but it did not report any connected upstream providers."
: "OpenCode is available, but it did not report any connected upstream providers.",
status: "error",
auth: { status: "unknown" },
message: `OpenCode v${version} is too old. Upgrade to v${MINIMUM_OPENCODE_VERSION} or newer.`,
},
});
});
}
}
const getProviderSettings = serverSettings.getSettings.pipe(
Effect.map((settings) => settings.providers.opencode),
);
const inventoryExit = yield* Effect.exit(
Effect.scoped(
Effect.gen(function* () {
const server = yield* openCodeRuntime
.connectToOpenCodeServer({
binaryPath: openCodeSettings.binaryPath,
serverUrl: openCodeSettings.serverUrl,
environment,
})
.pipe(
Effect.mapError(
(cause) =>
new OpenCodeProbeError({ cause, detail: openCodeRuntimeErrorDetail(cause) }),
),
);
return yield* openCodeRuntime
.loadOpenCodeInventory(
openCodeRuntime.createOpenCodeSdkClient({
baseUrl: server.url,
directory: cwd,
...(isExternalServer && openCodeSettings.serverPassword
? { serverPassword: openCodeSettings.serverPassword }
: {}),
}),
)
.pipe(
Effect.mapError(
(cause) =>
new OpenCodeProbeError({ cause, detail: openCodeRuntimeErrorDetail(cause) }),
),
);
}),
),
);
if (inventoryExit._tag === "Failure") {
return fallback(Cause.squash(inventoryExit.cause), version);
}
return yield* makeManagedServerProvider<OpenCodeSettings>({
getSettings: getProviderSettings.pipe(Effect.orDie),
streamSettings: serverSettings.streamChanges.pipe(
Stream.map((settings) => settings.providers.opencode),
),
haveSettingsChanged: (previous, next) => !Equal.equals(previous, next),
initialSnapshot: makePendingOpenCodeProvider,
checkProvider: getProviderSettings.pipe(
Effect.flatMap((settings) =>
checkOpenCodeProviderStatus({
settings,
cwd: serverConfig.cwd,
}),
),
),
});
}),
);
const models = providerModelsFromSettings(
flattenOpenCodeModels(inventoryExit.value),
PROVIDER,
customModels,
DEFAULT_OPENCODE_MODEL_CAPABILITIES,
);
const connectedCount = inventoryExit.value.providerList.connected.length;
return buildServerProvider({
presentation: OPENCODE_PRESENTATION,
enabled: true,
checkedAt,
models,
probe: {
installed: true,
version,
status: connectedCount > 0 ? "ready" : "warning",
auth: {
status: connectedCount > 0 ? "authenticated" : "unknown",
type: "opencode",
},
message:
connectedCount > 0
? `${connectedCount} upstream provider${connectedCount === 1 ? "" : "s"} connected through ${isExternalServer ? "the configured OpenCode server" : "OpenCode"}.`
: isExternalServer
? "Connected to the configured OpenCode server, but it did not report any connected upstream providers."
: "OpenCode is available, but it did not report any connected upstream providers.",
},
});
});
@@ -1,24 +1,30 @@
import type { ProviderKind } from "@t3tools/contracts";
import {
defaultInstanceIdForDriver,
ProviderDriverKind,
type ServerProvider,
} from "@t3tools/contracts";
import { it, assert, vi } from "@effect/vitest";
import { assertFailure } from "@effect/vitest/utils";
import { Effect, Layer, Stream } from "effect";
import { Effect, Layer, PubSub, Stream } from "effect";
import { ClaudeAdapter } from "../Services/ClaudeAdapter.ts";
import type { ClaudeAdapterShape } from "../Services/ClaudeAdapter.ts";
import { CodexAdapter } from "../Services/CodexAdapter.ts";
import type { CodexAdapterShape } from "../Services/CodexAdapter.ts";
import { CursorAdapter } from "../Services/CursorAdapter.ts";
import type { CursorAdapterShape } from "../Services/CursorAdapter.ts";
import { OpenCodeAdapter } from "../Services/OpenCodeAdapter.ts";
import type { OpenCodeAdapterShape } from "../Services/OpenCodeAdapter.ts";
import { ProviderAdapterRegistry } from "../Services/ProviderAdapterRegistry.ts";
import { ProviderInstanceRegistry } from "../Services/ProviderInstanceRegistry.ts";
import type { ProviderInstance } from "../ProviderDriver.ts";
import type { TextGenerationShape } from "../../textGeneration/TextGeneration.ts";
import { ProviderAdapterRegistryLive } from "./ProviderAdapterRegistry.ts";
import { ProviderUnsupportedError } from "../Errors.ts";
import * as NodeServices from "@effect/platform-node/NodeServices";
const CODEX_DRIVER = ProviderDriverKind.make("codex");
const CLAUDE_AGENT_DRIVER = ProviderDriverKind.make("claudeAgent");
const OPENCODE_DRIVER = ProviderDriverKind.make("opencode");
const CURSOR_DRIVER = ProviderDriverKind.make("cursor");
const fakeCodexAdapter: CodexAdapterShape = {
provider: "codex",
provider: CODEX_DRIVER,
capabilities: { sessionModelSwitch: "in-session" },
startSession: vi.fn(),
sendTurn: vi.fn(),
@@ -35,7 +41,7 @@ const fakeCodexAdapter: CodexAdapterShape = {
};
const fakeClaudeAdapter: ClaudeAdapterShape = {
provider: "claudeAgent",
provider: CLAUDE_AGENT_DRIVER,
capabilities: { sessionModelSwitch: "in-session" },
startSession: vi.fn(),
sendTurn: vi.fn(),
@@ -52,7 +58,7 @@ const fakeClaudeAdapter: ClaudeAdapterShape = {
};
const fakeOpenCodeAdapter: OpenCodeAdapterShape = {
provider: "opencode",
provider: OPENCODE_DRIVER,
capabilities: { sessionModelSwitch: "in-session" },
startSession: vi.fn(),
sendTurn: vi.fn(),
@@ -69,7 +75,7 @@ const fakeOpenCodeAdapter: OpenCodeAdapterShape = {
};
const fakeCursorAdapter: CursorAdapterShape = {
provider: "cursor",
provider: CURSOR_DRIVER,
capabilities: { sessionModelSwitch: "in-session" },
startSession: vi.fn(),
sendTurn: vi.fn(),
@@ -85,44 +91,94 @@ const fakeCursorAdapter: CursorAdapterShape = {
streamEvents: Stream.empty,
};
const layer = it.layer(
Layer.mergeAll(
Layer.provide(
ProviderAdapterRegistryLive,
Layer.mergeAll(
Layer.succeed(CodexAdapter, fakeCodexAdapter),
Layer.succeed(ClaudeAdapter, fakeClaudeAdapter),
Layer.succeed(OpenCodeAdapter, fakeOpenCodeAdapter),
Layer.succeed(CursorAdapter, fakeCursorAdapter),
),
),
NodeServices.layer,
),
// ProviderAdapterRegistryLive is now a facade over ProviderInstanceRegistry —
// it walks `listInstances` once at boot and surfaces the default-instance
// adapter keyed by its driver kind. To test the facade we supply four fake
// instances whose `instanceId === defaultInstanceIdForDriver(driverKind)` so
// they pass the default-instance filter.
const makeFakeInstance = (
driverKindString: "codex" | "claudeAgent" | "cursor" | "opencode",
adapter: ProviderInstance["adapter"],
): ProviderInstance => {
const driverKind = ProviderDriverKind.make(driverKindString);
return {
instanceId: defaultInstanceIdForDriver(driverKind),
driverKind,
continuationIdentity: {
driverKind,
continuationKey: `${driverKind}:instance:${defaultInstanceIdForDriver(driverKind)}`,
},
displayName: undefined,
enabled: true,
snapshot: {
getSnapshot: Effect.succeed({} as unknown as ServerProvider),
refresh: Effect.succeed({} as unknown as ServerProvider),
streamChanges: Stream.empty,
},
adapter,
textGeneration: {} as unknown as TextGenerationShape,
};
};
const fakeInstances: ReadonlyArray<ProviderInstance> = [
makeFakeInstance("codex", fakeCodexAdapter),
makeFakeInstance("claudeAgent", fakeClaudeAdapter),
makeFakeInstance("opencode", fakeOpenCodeAdapter),
makeFakeInstance("cursor", fakeCursorAdapter),
];
const fakeInstanceRegistryLayer = Layer.succeed(ProviderInstanceRegistry, {
getInstance: (instanceId) =>
Effect.succeed(fakeInstances.find((instance) => instance.instanceId === instanceId)),
listInstances: Effect.succeed(fakeInstances),
listUnavailable: Effect.succeed([]),
streamChanges: Stream.empty,
// Tests never drive changes through this fake; acquire a throwaway
// subscription on an unused PubSub so the shape is satisfied.
subscribeChanges: Effect.flatMap(PubSub.unbounded<void>(), (pubsub) => PubSub.subscribe(pubsub)),
});
const layer = Layer.mergeAll(
Layer.provide(ProviderAdapterRegistryLive, fakeInstanceRegistryLayer),
NodeServices.layer,
);
layer("ProviderAdapterRegistryLive", (it) => {
it.effect("resolves a registered provider adapter", () =>
it.layer(layer)("ProviderAdapterRegistryLive", (it) => {
it("resolves adapters and routing metadata from provider instances", () =>
Effect.gen(function* () {
const registry = yield* ProviderAdapterRegistry;
const codex = yield* registry.getByProvider("codex");
const claude = yield* registry.getByProvider("claudeAgent");
const openCode = yield* registry.getByProvider("opencode");
const cursor = yield* registry.getByProvider("cursor");
assert.equal(codex, fakeCodexAdapter);
assert.equal(claude, fakeClaudeAdapter);
assert.equal(openCode, fakeOpenCodeAdapter);
assert.equal(cursor, fakeCursorAdapter);
const claudeInstanceId = defaultInstanceIdForDriver(CLAUDE_AGENT_DRIVER);
const adapter = yield* registry.getByInstance(claudeInstanceId);
assert.strictEqual(adapter, fakeClaudeAdapter);
const info = yield* registry.getInstanceInfo(claudeInstanceId);
assert.deepStrictEqual(info, {
instanceId: claudeInstanceId,
driverKind: CLAUDE_AGENT_DRIVER,
displayName: undefined,
accentColor: undefined,
enabled: true,
continuationIdentity: {
driverKind: CLAUDE_AGENT_DRIVER,
continuationKey: "claudeAgent:instance:claudeAgent",
},
});
const instances = yield* registry.listInstances();
assert.deepStrictEqual(instances, [
defaultInstanceIdForDriver(CODEX_DRIVER),
claudeInstanceId,
defaultInstanceIdForDriver(OPENCODE_DRIVER),
defaultInstanceIdForDriver(CURSOR_DRIVER),
]);
const providers = yield* registry.listProviders();
assert.deepEqual(providers, ["codex", "claudeAgent", "opencode", "cursor"]);
}),
);
it.effect("fails with ProviderUnsupportedError for unknown providers", () =>
Effect.gen(function* () {
const registry = yield* ProviderAdapterRegistry;
const adapter = yield* registry.getByProvider("unknown" as ProviderKind).pipe(Effect.result);
assertFailure(adapter, new ProviderUnsupportedError({ provider: "unknown" }));
}),
);
assert.deepStrictEqual(providers, [
CODEX_DRIVER,
CLAUDE_AGENT_DRIVER,
OPENCODE_DRIVER,
CURSOR_DRIVER,
]);
}));
});
@@ -1,59 +1,101 @@
/**
* ProviderAdapterRegistryLive - In-memory provider adapter lookup layer.
* ProviderAdapterRegistryLive — facade over `ProviderInstanceRegistry`.
*
* Binds provider kinds (codex/claudeAgent/...) to concrete adapter services.
* This layer only performs adapter lookup; it does not route session-scoped
* calls or own provider lifecycle workflows.
* `ProviderAdapterRegistry` historically mapped one `ProviderDriverKind` to one
* adapter via the four `<X>AdapterLive` singleton Layers. The per-instance
* refactor moved adapter construction inside each `ProviderDriver.create()`:
* adapters are now bundled on the `ProviderInstance` that the
* `ProviderInstanceRegistry` owns.
*
* This facade fulfills the `ProviderAdapterRegistryShape` contract by doing
* dynamic look-ups against `ProviderInstanceRegistry` on every call. That
* means settings-driven hot-reload shows up here automatically — adding a
* new instance via settings makes `getByInstance` resolve immediately
* without rebuilding the facade.
*
* @module ProviderAdapterRegistryLive
*/
import {
defaultInstanceIdForDriver,
ProviderInstanceId,
type ProviderDriverKind,
} from "@t3tools/contracts";
import { Effect, Layer } from "effect";
import { ProviderUnsupportedError, type ProviderAdapterError } from "../Errors.ts";
import type { ProviderAdapterShape } from "../Services/ProviderAdapter.ts";
import { ProviderUnsupportedError } from "../Errors.ts";
import { ProviderInstanceRegistry } from "../Services/ProviderInstanceRegistry.ts";
import {
ProviderAdapterRegistry,
type ProviderAdapterRegistryShape,
} from "../Services/ProviderAdapterRegistry.ts";
import { ClaudeAdapter } from "../Services/ClaudeAdapter.ts";
import { CodexAdapter } from "../Services/CodexAdapter.ts";
import { CursorAdapter } from "../Services/CursorAdapter.ts";
import { OpenCodeAdapter } from "../Services/OpenCodeAdapter.ts";
import { createBuiltInAdapterList } from "../builtInProviderCatalog.ts";
export interface ProviderAdapterRegistryLiveOptions {
readonly adapters?: ReadonlyArray<ProviderAdapterShape<ProviderAdapterError>>;
}
const makeProviderAdapterRegistry = Effect.fn("makeProviderAdapterRegistry")(function* () {
const registry = yield* ProviderInstanceRegistry;
const makeProviderAdapterRegistry = Effect.fn("makeProviderAdapterRegistry")(function* (
options?: ProviderAdapterRegistryLiveOptions,
) {
const cursorAdapterOption = yield* Effect.serviceOption(CursorAdapter);
const adapters =
options?.adapters !== undefined
? options.adapters
: createBuiltInAdapterList({
codex: yield* CodexAdapter,
claudeAgent: yield* ClaudeAdapter,
opencode: yield* OpenCodeAdapter,
...(cursorAdapterOption._tag === "Some" ? { cursor: cursorAdapterOption.value } : {}),
});
const byProvider = new Map(adapters.map((adapter) => [adapter.provider, adapter]));
const getByInstance: ProviderAdapterRegistryShape["getByInstance"] = (instanceId) =>
registry.getInstance(instanceId).pipe(
Effect.flatMap((instance) =>
instance === undefined
? Effect.fail(
new ProviderUnsupportedError({
provider: instanceId,
}),
)
: Effect.succeed(instance.adapter),
),
);
const getByProvider: ProviderAdapterRegistryShape["getByProvider"] = (provider) => {
const adapter = byProvider.get(provider);
if (!adapter) {
return Effect.fail(new ProviderUnsupportedError({ provider }));
}
return Effect.succeed(adapter);
};
const getInstanceInfo: ProviderAdapterRegistryShape["getInstanceInfo"] = (instanceId) =>
registry.getInstance(instanceId).pipe(
Effect.flatMap((instance) =>
instance === undefined
? Effect.fail(
new ProviderUnsupportedError({
provider: instanceId,
}),
)
: Effect.succeed({
instanceId: instance.instanceId,
driverKind: instance.driverKind,
displayName: instance.displayName,
accentColor: instance.accentColor,
enabled: instance.enabled,
continuationIdentity: instance.continuationIdentity,
}),
),
);
const listInstances: ProviderAdapterRegistryShape["listInstances"] = () =>
registry.listInstances.pipe(
Effect.map((instances) => instances.map((instance) => instance.instanceId)),
);
const listProviders: ProviderAdapterRegistryShape["listProviders"] = () =>
Effect.sync(() => Array.from(byProvider.keys()));
registry.listInstances.pipe(
Effect.map((instances) => {
const kinds = new Set<ProviderDriverKind>();
for (const instance of instances) {
const defaultId = defaultInstanceIdForDriver(instance.driverKind);
if (instance.instanceId === defaultId) {
// Only the default-instance rows show up through the legacy
// shim — custom instances like `codex_personal` have no
// `ProviderDriverKind` equivalent.
kinds.add(instance.driverKind);
}
}
return Array.from(kinds);
}),
);
return {
getByProvider,
getByInstance,
getInstanceInfo,
listInstances,
listProviders,
// Proxy directly — the facade has no state of its own; the instance
// registry already coalesces adds/removes/rebuilds into one emission.
streamChanges: registry.streamChanges,
subscribeChanges: registry.subscribeChanges,
} satisfies ProviderAdapterRegistryShape;
});
@@ -61,3 +103,14 @@ export const ProviderAdapterRegistryLive = Layer.effect(
ProviderAdapterRegistry,
makeProviderAdapterRegistry(),
);
// Exposed for tests that want to build a facade over a pre-assembled
// `ProviderInstanceRegistry` without pulling in the whole boot graph.
export { makeProviderAdapterRegistry };
// Re-export for consumers that need the accessor shape. The service tag
// itself lives in `Services/ProviderAdapterRegistry.ts`.
export { ProviderAdapterRegistry } from "../Services/ProviderAdapterRegistry.ts";
// Re-export for consumers (including tests) that construct a
// `ProviderInstanceId` before calling `getByInstance`.
export { ProviderInstanceId };
@@ -0,0 +1,83 @@
/**
* ProviderEventLoggers — single observability service that owns the two
* shared NDJSON streams the provider runtime writes:
*
* - `native` — provider-protocol events as the SDK emits them, written
* from inside each `<X>Adapter` factory.
* - `canonical` — runtime events after `ProviderService` has normalized
* them onto `ProviderRuntimeEvent`.
*
* Why a service tag and not constructor options?
*
* - Adapters are now constructed *inside* drivers (`<X>Driver.create()`),
* not at the boot Layer. There is no longer a single `make<X>AdapterLive(options)`
* call site where we can hand an `EventNdjsonLogger` in by hand.
* - Multiple driver instances per kind (`codex_personal`, `codex_work`)
* should share one underlying log writer per stream — opening N writers
* against the same rotating file would race the rotation logic. Owning
* the loggers on a single tag keeps that invariant intact.
* - Tests can swap one (or both) loggers with in-memory recorders by
* `Layer.succeed(ProviderEventLoggers, { native, canonical })` instead of
* juggling per-Layer option threading.
*
* Both fields are optional. `makeEventNdjsonLogger` returns `undefined` when
* the target directory cannot be created; we forward that as `undefined`
* rather than failing the boot Layer, matching the previous best-effort
* behavior of `server.ts`.
*
* @module provider/Layers/ProviderEventLoggers
*/
import { Context, Effect, Layer } from "effect";
import { ServerConfig } from "../../config.ts";
import { type EventNdjsonLogger, makeEventNdjsonLogger } from "./EventNdjsonLogger.ts";
export interface ProviderEventLoggersShape {
readonly native: EventNdjsonLogger | undefined;
readonly canonical: EventNdjsonLogger | undefined;
}
/**
* Shared logger pair for native + canonical provider event streams.
*
* Service value is intentionally a struct of two optional loggers rather
* than two parallel tags. Construction site is one place
* (`ProviderEventLoggersLive`); consumers (drivers, `ProviderService`) read
* one tag and pluck the field they need.
*/
export class ProviderEventLoggers extends Context.Service<
ProviderEventLoggers,
ProviderEventLoggersShape
>()("t3/provider/ProviderEventLoggers") {}
/**
* Constant value used by tests / boot layers that want to opt out of native
* + canonical logging entirely. Keeps the tag non-optional in the type
* system while letting the runtime treat absence as a no-op.
*/
export const NoOpProviderEventLoggers: ProviderEventLoggersShape = {
native: undefined,
canonical: undefined,
};
/**
* Live Layer that builds both loggers from `ServerConfig.providerEventLogPath`.
* If the directory create fails for either stream, the corresponding field
* is `undefined` and writes from that stream become no-ops downstream.
*/
export const ProviderEventLoggersLive = Layer.effect(
ProviderEventLoggers,
Effect.gen(function* () {
const { providerEventLogPath } = yield* ServerConfig;
const native = yield* makeEventNdjsonLogger(providerEventLogPath, {
stream: "native",
});
const canonical = yield* makeEventNdjsonLogger(providerEventLogPath, {
stream: "canonical",
});
return {
native,
canonical,
} satisfies ProviderEventLoggersShape;
}),
);
@@ -0,0 +1,176 @@
/**
* ProviderInstanceRegistryHydration — derive a `ProviderInstanceConfigMap`
* from `ServerSettings` and keep `ProviderInstanceRegistry` in sync with it.
*
* The server still reads two shapes:
*
* 1. `settings.providerInstances` — the new driver-agnostic map the
* registry expects. Keyed by `ProviderInstanceId`, values are
* `ProviderInstanceConfig` envelopes.
* 2. `settings.providers.<kind>` — the legacy single-instance-per-driver
* fields (`providers.codex`, `providers.claudeAgent`, …). These are
* the source of truth for every deployment that hasn't been migrated
* yet to an explicit `providerInstances` entry.
*
* This module bridges (2) into (1) and wires the resulting map into a
* mutable registry. For every built-in driver whose id is not already
* present in `providerInstances` (keyed on
* `defaultInstanceIdForDriver(driverKind)` — literally the driver kind as a
* routing slug), we synthesize an envelope from the legacy field. The
* registry decodes both flavours through the same `configSchema` and ends
* up with one uniform `ProviderInstance` per entry.
*
* Explicit `providerInstances` entries always win — users can already
* override the legacy `providers.<kind>` blob by authoring a
* `providerInstances.codex` entry with a matching driver, and we don't
* want the synthesized envelope to silently stomp their config.
*
* Hot-reload
* ----------
* On layer build we:
* 1. Read the current `ServerSettings` once and use it to seed the
* registry's initial state via `ProviderInstanceRegistryMutableLayer`.
* 2. Fork a daemon fiber (lifetime tied to the layer's scope) that
* subscribes to `ServerSettingsService.streamChanges` and calls
* `ProviderInstanceRegistryMutator.reconcile` on every emission.
*
* Failures inside the watcher are logged and swallowed so a single bad
* settings emission cannot kill the registry. Unknown drivers and invalid
* configs already round-trip through the registry's own "unavailable"
* shadow bucket.
*
* @module provider/Layers/ProviderInstanceRegistryHydration
*/
import {
defaultInstanceIdForDriver,
type ProviderInstanceConfig,
type ProviderInstanceConfigMap,
ServerSettings,
} from "@t3tools/contracts";
import { Effect, Layer, Stream } from "effect";
import { ServerSettingsService } from "../../serverSettings.ts";
import { BUILT_IN_DRIVERS, type BuiltInDriversEnv } from "../builtInDrivers.ts";
import { ProviderInstanceRegistry } from "../Services/ProviderInstanceRegistry.ts";
import { ProviderInstanceRegistryMutator } from "../Services/ProviderInstanceRegistryMutator.ts";
import { ProviderInstanceRegistryMutableLayer } from "./ProviderInstanceRegistryLive.ts";
/**
* Synthesize a `ProviderInstanceConfigMap` from a `ServerSettings` snapshot.
*
* Strategy:
* 1. Copy all explicit `settings.providerInstances` entries verbatim.
* 2. For each built-in driver whose `defaultInstanceIdForDriver(id)` key
* is *not* already in the explicit map, synthesize an entry from the
* matching legacy `settings.providers.<kind>` blob.
*
* The returned map is the input the registry consumes; pure & exported
* separately so the hydration logic can be exercised by unit tests
* without layering.
*/
export const deriveProviderInstanceConfigMap = (
settings: ServerSettings,
): ProviderInstanceConfigMap => {
const merged: Record<string, ProviderInstanceConfig> = { ...settings.providerInstances };
for (const driver of BUILT_IN_DRIVERS) {
const instanceId = defaultInstanceIdForDriver(driver.driverKind);
if (instanceId in merged) {
// Explicit `providerInstances` entry for this slot — user-authored
// config always wins over the legacy mirror.
continue;
}
// Only built-in drivers have a legacy mirror; the registry's
// `providers` struct is keyed on the same literal slug as
// `driverKind`. Access is dynamic (the driver kind is a branded string),
// but it's constrained to `keyof settings.providers` by the union of
// built-in driver kinds.
const legacyKey = driver.driverKind as keyof ServerSettings["providers"];
const legacyConfig = settings.providers[legacyKey];
if (legacyConfig === undefined) {
continue;
}
merged[instanceId] = {
driver: driver.driverKind,
config: legacyConfig,
};
}
return merged as ProviderInstanceConfigMap;
};
/**
* Layer that consumes `ProviderInstanceRegistryMutator` and forks a
* settings-watcher fiber. The fiber's lifetime is tied to the enclosing
* layer scope (process lifetime in production), so it is interrupted on
* shutdown without leaking.
*
* Errors inside the watcher are logged and swallowed — the registry's own
* "unavailable" bucket already absorbs unknown drivers and invalid
* configs, so the only way the watcher could fail is a settings stream
* tear-down, which logs and exits cleanly.
*/
const SettingsWatcherLive: Layer.Layer<
never,
never,
ProviderInstanceRegistryMutator | ServerSettingsService
> = Layer.effectDiscard(
Effect.gen(function* () {
const mutator = yield* ProviderInstanceRegistryMutator;
const serverSettings = yield* ServerSettingsService;
yield* serverSettings.streamChanges.pipe(
Stream.runForEach((next) =>
mutator
.reconcile(deriveProviderInstanceConfigMap(next))
.pipe(
Effect.catchCause((cause) =>
Effect.logError("ProviderInstanceRegistry reconcile failed", cause),
),
),
),
Effect.forkScoped,
);
}),
);
/**
* Hydrate `ProviderInstanceRegistry` from `ServerSettings` and keep it in
* sync with subsequent `streamChanges` emissions.
*
* The Layer's two halves:
* - `ProviderInstanceRegistryMutableLayer` produces the registry +
* mutator from the initial config map. Its scope owns every
* per-instance child scope created during reconcile.
* - `SettingsWatcherLive` consumes the mutator and runs a daemon fiber
* in the same scope.
*
* Composing via `Layer.provideMerge` makes the watcher's deps available
* from the mutable layer while still surfacing the registry as an output.
* The mutator tag is technically also exposed; only this module imports
* it, so the visibility leak is harmless in practice.
*/
export const ProviderInstanceRegistryHydrationLive: Layer.Layer<
ProviderInstanceRegistry,
never,
BuiltInDriversEnv | ServerSettingsService
> = Layer.unwrap(
Effect.gen(function* () {
const serverSettings = yield* ServerSettingsService;
const initialSettings: ServerSettings | undefined = yield* serverSettings.getSettings.pipe(
Effect.orElseSucceed(() => undefined),
);
const initialConfigMap =
initialSettings === undefined
? ({} as ProviderInstanceConfigMap)
: deriveProviderInstanceConfigMap(initialSettings);
const mutableLayer = ProviderInstanceRegistryMutableLayer({
drivers: BUILT_IN_DRIVERS,
configMap: initialConfigMap,
});
return SettingsWatcherLive.pipe(Layer.provideMerge(mutableLayer));
}),
) as Layer.Layer<ProviderInstanceRegistry, never, BuiltInDriversEnv | ServerSettingsService>;
@@ -0,0 +1,357 @@
/**
* Multi-instance validation slices for `ProviderInstanceRegistryLive`.
*
* Two axes of the driver/registry refactor are exercised here:
*
* 1. **Same driver, many instances** — the "multi-instance codex slice"
* describe block below configures two independent `codex` instances and
* asserts each gets its own closures and identity. This is the
* multi-codex capability the refactor exists to unlock.
*
* 2. **Many drivers, one registry** — the "all drivers slice" describe
* block below configures one instance of every shipped driver
* (`codex`, `claudeAgent`, `cursor`, `opencode`) in a single
* `ProviderInstanceConfigMap` and asserts the registry boots them all
* without cross-contamination. This proves the driver SPI is uniform
* across every provider — any driver plugs into the registry through
* the same `ProviderDriver` value contract.
*
* Every instance in these tests is configured with `enabled: false` so the
* provider-status checks short-circuit to pending/disabled snapshots
* without trying to spawn real `codex` / `claude` / `agent` / `opencode`
* binaries. That keeps the assertions focused on registry routing
* behaviour rather than the runtime details of each provider.
*/
import { describe, expect, it } from "@effect/vitest";
import * as NodeServices from "@effect/platform-node/NodeServices";
import {
type ClaudeSettings,
type CodexSettings,
type CursorSettings,
type OpenCodeSettings,
ProviderDriverKind,
type ProviderInstanceConfigMap,
ProviderInstanceId,
} from "@t3tools/contracts";
import { Effect, Layer } from "effect";
import { ServerConfig } from "../../config.ts";
import { ClaudeDriver } from "../Drivers/ClaudeDriver.ts";
import { CodexDriver } from "../Drivers/CodexDriver.ts";
import { CursorDriver } from "../Drivers/CursorDriver.ts";
import { OpenCodeDriver } from "../Drivers/OpenCodeDriver.ts";
import { OpenCodeRuntimeLive } from "../opencodeRuntime.ts";
import { NoOpProviderEventLoggers, ProviderEventLoggers } from "./ProviderEventLoggers.ts";
import { makeProviderInstanceRegistry } from "./ProviderInstanceRegistryLive.ts";
const makeCodexConfig = (overrides: Partial<CodexSettings>): CodexSettings => ({
enabled: false,
binaryPath: "codex",
homePath: "",
shadowHomePath: "",
customModels: [],
...overrides,
});
const makeClaudeConfig = (overrides: Partial<ClaudeSettings>): ClaudeSettings => ({
enabled: false,
binaryPath: "claude",
homePath: "",
customModels: [],
launchArgs: "",
...overrides,
});
const makeCursorConfig = (overrides: Partial<CursorSettings>): CursorSettings => ({
enabled: false,
binaryPath: "agent",
apiEndpoint: "",
customModels: [],
...overrides,
});
const makeOpenCodeConfig = (overrides: Partial<OpenCodeSettings>): OpenCodeSettings => ({
enabled: false,
binaryPath: "opencode",
serverUrl: "",
serverPassword: "",
customModels: [],
...overrides,
});
describe("ProviderInstanceRegistryLive — multi-instance codex slice", () => {
// `ServerConfig.layerTest` needs `FileSystem` to materialize its scratch
// directory. `Layer.merge` just unions requirements, so we have to push
// `NodeServices.layer` through `Layer.provideMerge` to satisfy that
// dependency while still surfacing NodeServices to the test body (the
// codex driver's `create` yields `ChildProcessSpawner` directly).
const testLayer = ServerConfig.layerTest(process.cwd(), {
prefix: "provider-instance-registry-test",
}).pipe(
Layer.provideMerge(NodeServices.layer),
Layer.provideMerge(Layer.succeed(ProviderEventLoggers, NoOpProviderEventLoggers)),
);
it.live("boots two independent codex instances from a ProviderInstanceConfigMap", () =>
Effect.gen(function* () {
const personalId = ProviderInstanceId.make("codex_personal");
const workId = ProviderInstanceId.make("codex_work");
const codexDriverKind = ProviderDriverKind.make("codex");
const configMap: ProviderInstanceConfigMap = {
[personalId]: {
driver: codexDriverKind,
displayName: "Codex (personal)",
enabled: false,
config: makeCodexConfig({
binaryPath: "/opt/codex-personal/bin/codex",
homePath: "/home/julius/.codex_personal",
customModels: ["personal-preview"],
}),
},
[workId]: {
driver: codexDriverKind,
displayName: "Codex (work)",
enabled: false,
config: makeCodexConfig({
binaryPath: "/opt/codex-work/bin/codex",
homePath: "/home/julius/.codex",
customModels: ["work-preview"],
}),
},
};
const { registry } = yield* makeProviderInstanceRegistry({
drivers: [CodexDriver],
configMap,
});
const instances = yield* registry.listInstances;
expect(instances.map((instance) => instance.instanceId).toSorted()).toEqual(
[personalId, workId].toSorted(),
);
expect(instances.every((instance) => instance.driverKind === codexDriverKind)).toBe(true);
expect(instances.map((instance) => instance.displayName).toSorted()).toEqual(
["Codex (personal)", "Codex (work)"].toSorted(),
);
// Each instance must be retrievable by id and carry its *own* closures.
const personal = yield* registry.getInstance(personalId);
const work = yield* registry.getInstance(workId);
expect(personal).toBeDefined();
expect(work).toBeDefined();
expect(personal!.adapter).not.toBe(work!.adapter);
expect(personal!.textGeneration).not.toBe(work!.textGeneration);
expect(personal!.snapshot).not.toBe(work!.snapshot);
// Snapshots identify themselves by instanceId + driver — this is
// what makes per-instance routing distinguishable downstream.
const personalSnapshot = yield* personal!.snapshot.getSnapshot;
expect(personalSnapshot.instanceId).toBe(personalId);
expect(personalSnapshot.driver).toBe(codexDriverKind);
expect(personalSnapshot.enabled).toBe(false);
expect(personalSnapshot.continuation?.groupKey).toBe(
"codex:home:/home/julius/.codex_personal",
);
const workSnapshot = yield* work!.snapshot.getSnapshot;
expect(workSnapshot.instanceId).toBe(workId);
expect(workSnapshot.driver).toBe(codexDriverKind);
expect(workSnapshot.enabled).toBe(false);
expect(workSnapshot.continuation?.groupKey).toBe("codex:home:/home/julius/.codex");
// Nothing goes to the unavailable bucket — both drivers are registered.
const unavailable = yield* registry.listUnavailable;
expect(unavailable).toEqual([]);
}).pipe(Effect.provide(testLayer)),
);
it.live(
"shadows instances whose driver is not registered in this build without failing boot",
() =>
Effect.gen(function* () {
const codexId = ProviderInstanceId.make("codex_main");
const ghostId = ProviderInstanceId.make("ghost_main");
const configMap: ProviderInstanceConfigMap = {
[codexId]: {
driver: ProviderDriverKind.make("codex"),
enabled: false,
config: makeCodexConfig({}),
},
[ghostId]: {
driver: ProviderDriverKind.make("ghostDriver"),
displayName: "A fork-only driver we don't ship",
enabled: false,
config: { arbitrary: "payload", preserved: true },
},
};
const { registry } = yield* makeProviderInstanceRegistry({
drivers: [CodexDriver],
configMap,
});
const instances = yield* registry.listInstances;
expect(instances).toHaveLength(1);
expect(instances[0]!.instanceId).toBe(codexId);
const unavailable = yield* registry.listUnavailable;
expect(unavailable).toHaveLength(1);
const ghost = unavailable[0]!;
expect(ghost.instanceId).toBe(ghostId);
expect(ghost.driver).toBe("ghostDriver");
expect(ghost.availability).toBe("unavailable");
expect(ghost.unavailableReason).toMatch(/ghostDriver/);
}).pipe(Effect.provide(testLayer)),
);
});
describe("ProviderInstanceRegistryLive — all drivers slice", () => {
// All four drivers need `NodeServices` (ChildProcessSpawner + FileSystem +
// Path). `OpenCodeDriver.create` additionally yields `OpenCodeRuntime`
// at construction time, so we wire `OpenCodeRuntimeLive` into the stack.
// `OpenCodeRuntimeLive` bundles its own `NetService.layer` via
// `Layer.provide`, so the only external requirement it still exposes is
// `ChildProcessSpawner` — resolved here by piping it through
// `provideMerge(NodeServices.layer)`.
//
// The nested `provideMerge`s read bottom-up: `NodeServices.layer`
// provides `OpenCodeRuntimeLive`'s deps while keeping its own outputs
// surfaced; that merged layer then provides `ServerConfig.layerTest`'s
// `FileSystem` dep while keeping everything else surfaced to the test.
const infraLayer = OpenCodeRuntimeLive.pipe(Layer.provideMerge(NodeServices.layer));
const testLayer = ServerConfig.layerTest(process.cwd(), {
prefix: "provider-instance-registry-all-drivers-test",
}).pipe(
Layer.provideMerge(infraLayer),
Layer.provideMerge(Layer.succeed(ProviderEventLoggers, NoOpProviderEventLoggers)),
);
it.live("boots one instance of every shipped driver from a single config map", () =>
Effect.gen(function* () {
const codexId = ProviderInstanceId.make("codex_default");
const claudeId = ProviderInstanceId.make("claude_default");
const cursorId = ProviderInstanceId.make("cursor_default");
const openCodeId = ProviderInstanceId.make("opencode_default");
const codexDriverKind = ProviderDriverKind.make("codex");
const claudeDriverKind = ProviderDriverKind.make("claudeAgent");
const cursorDriverKind = ProviderDriverKind.make("cursor");
const openCodeDriverKind = ProviderDriverKind.make("opencode");
const configMap: ProviderInstanceConfigMap = {
[codexId]: {
driver: codexDriverKind,
displayName: "Codex",
enabled: false,
config: makeCodexConfig({ homePath: "/home/julius/.codex" }),
},
[claudeId]: {
driver: claudeDriverKind,
displayName: "Claude",
enabled: false,
config: makeClaudeConfig({
homePath: "/home/julius/.claude-work",
launchArgs: "--verbose",
}),
},
[cursorId]: {
driver: cursorDriverKind,
displayName: "Cursor",
enabled: false,
config: makeCursorConfig({}),
},
[openCodeId]: {
driver: openCodeDriverKind,
displayName: "OpenCode",
enabled: false,
config: makeOpenCodeConfig({}),
},
};
const { registry } = yield* makeProviderInstanceRegistry({
drivers: [CodexDriver, ClaudeDriver, CursorDriver, OpenCodeDriver],
configMap,
});
// Every configured instance must materialize — none downgraded to a
// shadow snapshot, because every driver in the map is registered.
const unavailable = yield* registry.listUnavailable;
expect(unavailable).toEqual([]);
const instances = yield* registry.listInstances;
expect(instances).toHaveLength(4);
expect(instances.map((instance) => instance.instanceId).toSorted()).toEqual(
[codexId, claudeId, cursorId, openCodeId].toSorted(),
);
// Instance lookup by id resolves each instance to its own bundle —
// this is how rest-of-server routes turn/session calls in the new
// model. Each driver's bundle carries its advertised `driverKind`.
const codex = yield* registry.getInstance(codexId);
const claude = yield* registry.getInstance(claudeId);
const cursor = yield* registry.getInstance(cursorId);
const openCode = yield* registry.getInstance(openCodeId);
expect(codex?.driverKind).toBe(codexDriverKind);
expect(claude?.driverKind).toBe(claudeDriverKind);
expect(cursor?.driverKind).toBe(cursorDriverKind);
expect(openCode?.driverKind).toBe(openCodeDriverKind);
expect(codex?.displayName).toBe("Codex");
expect(claude?.displayName).toBe("Claude");
expect(cursor?.displayName).toBe("Cursor");
expect(openCode?.displayName).toBe("OpenCode");
// Every instance owns its own set of closures — no sharing across
// drivers. `adapter` / `textGeneration` / `snapshot` are all
// distinct references even when two instances happen to share a
// trait (e.g. Cursor + others all use a stub-or-real
// `textGeneration`; they must still be different object values).
const adapters = [codex!.adapter, claude!.adapter, cursor!.adapter, openCode!.adapter];
expect(new Set(adapters).size).toBe(adapters.length);
const textGenerations = [
codex!.textGeneration,
claude!.textGeneration,
cursor!.textGeneration,
openCode!.textGeneration,
];
expect(new Set(textGenerations).size).toBe(textGenerations.length);
const snapshots = [codex!.snapshot, claude!.snapshot, cursor!.snapshot, openCode!.snapshot];
expect(new Set(snapshots).size).toBe(snapshots.length);
// Snapshots identify themselves by `instanceId` + `driver` so
// downstream aggregation in `ProviderRegistry` can tell instances
// apart even when two share a driver. With `enabled: false`, the
// check short-circuits and we get a disabled/pending snapshot back
// — that's enough signal to validate the stamping wrapper without
// spawning real binaries.
const codexSnapshot = yield* codex!.snapshot.getSnapshot;
expect(codexSnapshot.instanceId).toBe(codexId);
expect(codexSnapshot.driver).toBe(codexDriverKind);
expect(codexSnapshot.enabled).toBe(false);
expect(codexSnapshot.continuation?.groupKey).toBe("codex:home:/home/julius/.codex");
const claudeSnapshot = yield* claude!.snapshot.getSnapshot;
expect(claudeSnapshot.instanceId).toBe(claudeId);
expect(claudeSnapshot.driver).toBe(claudeDriverKind);
expect(claudeSnapshot.enabled).toBe(false);
expect(claudeSnapshot.continuation?.groupKey).toBe("claude:home:/home/julius/.claude-work");
const cursorSnapshot = yield* cursor!.snapshot.getSnapshot;
expect(cursorSnapshot.instanceId).toBe(cursorId);
expect(cursorSnapshot.driver).toBe(cursorDriverKind);
expect(cursorSnapshot.enabled).toBe(false);
expect(cursorSnapshot.continuation?.groupKey).toBe(
`${cursorDriverKind}:instance:${cursorId}`,
);
const openCodeSnapshot = yield* openCode!.snapshot.getSnapshot;
expect(openCodeSnapshot.instanceId).toBe(openCodeId);
expect(openCodeSnapshot.driver).toBe(openCodeDriverKind);
expect(openCodeSnapshot.enabled).toBe(false);
expect(openCodeSnapshot.continuation?.groupKey).toBe(
`${openCodeDriverKind}:instance:${openCodeId}`,
);
}).pipe(Effect.provide(testLayer)),
);
});
@@ -0,0 +1,434 @@
/**
* ProviderInstanceRegistryLive — runtime implementation of
* `ProviderInstanceRegistry` plus its sibling mutator.
*
* Materializes every entry in a `ProviderInstanceConfigMap`:
*
* - When the entry's `driver` matches a registered driver, the registry
* decodes the opaque `config` envelope through `driver.configSchema`
* and calls `driver.create()` inside a fresh child scope. The
* resulting `ProviderInstance` is stored keyed by instance id,
* alongside its scope so the entry can be torn down independently.
* - When the entry's `driver` is unknown to this build (fork, rollback,
* in-flight PR branch), the registry emits an `"unavailable"` shadow
* `ServerProvider` snapshot instead of failing. This is what makes
* downgrades and fork-hopping safe per the
* `forward/backward compatibility invariant` in
* `packages/contracts/src/providerInstance.ts`.
* - When the entry's config fails schema decode, the registry logs and
* emits a shadow snapshot with the schema detail — same bucket as an
* unknown driver.
*
* Unlike the pre-Slice-D layer, the registry now holds mutable state
* (`Ref`s + `PubSub`) and exposes an internal mutator
* (`ProviderInstanceRegistryMutator`) whose `reconcile` method diffs a
* fresh config map against the live state, tearing down removed instances
* and building new ones without disturbing unaffected instances.
*
* Every live instance runs inside its own child `Scope`. The registry's
* own scope owns all child scopes via finalizers, so closing the registry
* tears every instance down in reverse order; closing a single instance
* (via `reconcile` removing it) leaves the rest untouched.
*
* @module provider/Layers/ProviderInstanceRegistryLive
*/
import {
defaultInstanceIdForDriver,
ProviderInstanceId,
type ProviderInstanceConfig,
type ProviderInstanceConfigMap,
type ProviderDriverKind,
type ServerProvider,
} from "@t3tools/contracts";
import { Context, Effect, Equal, Exit, Layer, PubSub, Ref, Schema, Scope, Stream } from "effect";
import { buildUnavailableProviderSnapshot } from "../unavailableProviderSnapshot.ts";
import {
ProviderInstanceRegistry,
type ProviderInstanceRegistryShape,
} from "../Services/ProviderInstanceRegistry.ts";
import {
ProviderInstanceRegistryMutator,
type ProviderInstanceRegistryMutatorShape,
} from "../Services/ProviderInstanceRegistryMutator.ts";
import type { AnyProviderDriver, ProviderInstance } from "../ProviderDriver.ts";
/**
* Live registry entry: the materialized `ProviderInstance` + the fresh
* child scope its `create` effect ran in + the original `entry` envelope
* so `reconcile` can cheaply detect "no-op" updates.
*/
interface LiveEntry {
readonly instance: ProviderInstance;
readonly scope: Scope.Closeable;
readonly entry: ProviderInstanceConfig;
}
/**
* Internal state shared between the public registry service and the
* mutator service. Both services are thin shells around these refs.
*/
interface RegistryState {
readonly entries: Ref.Ref<ReadonlyMap<ProviderInstanceId, LiveEntry>>;
readonly unavailable: Ref.Ref<ReadonlyMap<ProviderInstanceId, ServerProvider>>;
readonly changes: PubSub.PubSub<void>;
}
/**
* Structural equality on `ProviderInstanceConfig` envelopes. Used by
* `reconcile` to skip rebuilds when settings arrive unchanged. Config
* payloads are opaque `unknown` at the envelope layer; `Equal.equals`
* falls back to structural equality for plain records, which matches how
* the schema decode output is constructed.
*/
const entryEqual = (a: ProviderInstanceConfig, b: ProviderInstanceConfig): boolean =>
Equal.equals(a, b);
const decodedConfigEnabled = (config: unknown): boolean | undefined => {
if (!config || typeof config !== "object" || globalThis.Array.isArray(config)) {
return undefined;
}
const enabled = (config as { readonly enabled?: unknown }).enabled;
return typeof enabled === "boolean" ? enabled : undefined;
};
/**
* Build one live entry from a raw config envelope. Returns either a
* `LiveEntry` plus undefined unavailable shadow, or a shadow snapshot and
* undefined entry — callers dispatch to the appropriate Ref bucket.
*/
const buildEntry = <R>(input: {
readonly driversById: ReadonlyMap<ProviderDriverKind, AnyProviderDriver<R>>;
readonly parentScope: Scope.Scope;
readonly instanceId: ProviderInstanceId;
readonly rawInstanceId: string;
readonly entry: ProviderInstanceConfig;
}): Effect.Effect<
| { readonly kind: "live"; readonly live: LiveEntry }
| { readonly kind: "unavailable"; readonly snapshot: ServerProvider },
never,
R
> =>
Effect.gen(function* () {
const { driversById, parentScope, instanceId, rawInstanceId, entry } = input;
const driver = driversById.get(entry.driver);
if (!driver) {
return {
kind: "unavailable" as const,
snapshot: buildUnavailableProviderSnapshot({
driverKind: entry.driver,
instanceId,
displayName: entry.displayName,
accentColor: entry.accentColor,
reason: `Driver '${entry.driver}' is not registered in this build.`,
}),
};
}
const decoder = Schema.decodeUnknownEffect(driver.configSchema);
const decodeResult = yield* decoder(entry.config ?? driver.defaultConfig()).pipe(Effect.result);
if (decodeResult._tag === "Failure") {
const issue = decodeResult.failure;
const detail = issue.message ?? String(issue);
yield* Effect.logError("Failed to decode provider instance config", {
instanceId: rawInstanceId,
driver: entry.driver,
detail,
});
return {
kind: "unavailable" as const,
snapshot: buildUnavailableProviderSnapshot({
driverKind: entry.driver,
instanceId,
displayName: entry.displayName,
accentColor: entry.accentColor,
reason: `Invalid config for instance '${rawInstanceId}': ${detail}`,
}),
};
}
const typedConfig = decodeResult.success;
const childScope = yield* Scope.make();
// Attach the child scope to the registry's parent scope: if the
// registry scope closes, each surviving instance's child scope is
// closed through this finalizer. `reconcile` manually closes the
// child scope on remove/replace; subsequent close via the parent's
// finalizer is a no-op because `Scope.close` is idempotent.
yield* Scope.addFinalizer(parentScope, Scope.close(childScope, Exit.void).pipe(Effect.ignore));
const createResult = yield* driver
.create({
instanceId,
displayName: entry.displayName,
accentColor: entry.accentColor,
environment: entry.environment ?? [],
enabled: entry.enabled ?? decodedConfigEnabled(typedConfig) ?? true,
config: typedConfig,
})
.pipe(Effect.provideService(Scope.Scope, childScope), Effect.result);
if (createResult._tag === "Failure") {
yield* Effect.logError("Failed to create provider instance", {
instanceId: rawInstanceId,
driver: entry.driver,
detail: createResult.failure.detail,
});
yield* Scope.close(childScope, Exit.void).pipe(Effect.ignore);
return {
kind: "unavailable" as const,
snapshot: buildUnavailableProviderSnapshot({
driverKind: entry.driver,
instanceId,
displayName: entry.displayName,
accentColor: entry.accentColor,
reason: `Driver '${entry.driver}' failed to create instance: ${createResult.failure.detail}`,
}),
};
}
return {
kind: "live" as const,
live: {
instance: createResult.success,
scope: childScope,
entry,
},
};
});
/**
* Reconcile-only implementation of the mutator. Exposed to the hydration
* layer; never called directly by the rest of the server.
*/
const makeReconcile = <R>(input: {
readonly state: RegistryState;
readonly driversById: ReadonlyMap<ProviderDriverKind, AnyProviderDriver<R>>;
readonly parentScope: Scope.Scope;
}): ((configMap: ProviderInstanceConfigMap) => Effect.Effect<void, never, R>) => {
const { state, driversById, parentScope } = input;
return (configMap: ProviderInstanceConfigMap) =>
Effect.gen(function* () {
const previousEntries = yield* Ref.get(state.entries);
const previousUnavailable = yield* Ref.get(state.unavailable);
const nextRaw = Object.entries(configMap);
const nextKeys = new Set<ProviderInstanceId>(
nextRaw.map(([raw]) => ProviderInstanceId.make(raw)),
);
// 1. Close scopes for instances that disappeared or whose config
// changed. Do this BEFORE creating replacements so ids map 1-to-1
// to live scopes at all times.
const removedIds: Array<ProviderInstanceId> = [];
const replacedIds = new Set<ProviderInstanceId>();
for (const [instanceId, live] of previousEntries) {
if (!nextKeys.has(instanceId)) {
removedIds.push(instanceId);
continue;
}
const nextEntry = configMap[instanceId];
if (nextEntry !== undefined && !entryEqual(live.entry, nextEntry)) {
replacedIds.add(instanceId);
}
}
for (const id of [...removedIds, ...replacedIds]) {
const live = previousEntries.get(id);
if (live) {
yield* Scope.close(live.scope, Exit.void).pipe(Effect.ignore);
}
}
// 2. Build additions and replacements. Walk `nextRaw` so the final
// entry order follows settings-author order.
const builtEntries = new Map<ProviderInstanceId, LiveEntry>();
const builtUnavailable = new Map<ProviderInstanceId, ServerProvider>();
let orderChanged = false;
const previousOrder = [...previousEntries.keys()];
const nextOrder: Array<ProviderInstanceId> = [];
for (const [rawInstanceId, entry] of nextRaw) {
const instanceId = ProviderInstanceId.make(rawInstanceId);
nextOrder.push(instanceId);
const existing = previousEntries.get(instanceId);
if (existing !== undefined && !replacedIds.has(instanceId)) {
// No-op update: keep the existing live entry and scope.
builtEntries.set(instanceId, existing);
continue;
}
const result = yield* buildEntry({
driversById,
parentScope,
instanceId,
rawInstanceId,
entry,
});
if (result.kind === "live") {
builtEntries.set(instanceId, result.live);
} else {
builtUnavailable.set(instanceId, result.snapshot);
}
}
if (previousOrder.length === nextOrder.length) {
for (let i = 0; i < previousOrder.length; i++) {
if (previousOrder[i] !== nextOrder[i]) {
orderChanged = true;
break;
}
}
} else {
orderChanged = true;
}
const entriesChanged =
orderChanged ||
removedIds.length > 0 ||
replacedIds.size > 0 ||
builtEntries.size !== previousEntries.size;
const unavailableChanged =
builtUnavailable.size !== previousUnavailable.size ||
[...builtUnavailable].some(([id, snapshot]) => {
const prev = previousUnavailable.get(id);
return prev === undefined || !Equal.equals(prev, snapshot);
}) ||
[...previousUnavailable].some(([id]) => !builtUnavailable.has(id));
yield* Ref.set(state.entries, builtEntries);
yield* Ref.set(state.unavailable, builtUnavailable);
if (entriesChanged || unavailableChanged) {
yield* PubSub.publish(state.changes, undefined);
}
});
};
/**
* Build the registry's runtime state from a concrete configMap. Returns a
* record containing:
*
* - `registry`: the read-only `ProviderInstanceRegistryShape` to expose
* under `ProviderInstanceRegistry`.
* - `mutator`: the `ProviderInstanceRegistryMutatorShape` to expose
* under `ProviderInstanceRegistryMutator`.
* - `reconcile`: the raw reconcile function, provided for convenience so
* boot-time layers can hydrate an initial map before publishing the
* services.
*
* The scope that this effect runs in owns every per-instance child scope
* created during `reconcile`. Closing that scope closes every live
* instance.
*/
export const makeProviderInstanceRegistry = <R>(input: {
readonly drivers: ReadonlyArray<AnyProviderDriver<R>>;
readonly configMap: ProviderInstanceConfigMap;
}): Effect.Effect<
{
readonly registry: ProviderInstanceRegistryShape;
readonly mutator: ProviderInstanceRegistryMutatorShape;
},
never,
R | Scope.Scope
> =>
Effect.gen(function* () {
const driversById = new Map<ProviderDriverKind, AnyProviderDriver<R>>(
input.drivers.map((driver) => [driver.driverKind, driver]),
);
// Capture the enclosing scope so per-instance child scopes can be
// attached to it at `reconcile` time. Without this, `reconcile`
// called later (e.g. from the hydration layer) would attach child
// scopes to the *caller's* scope instead of the registry's.
const parentScope = yield* Scope.Scope;
// Capture the driver R context at construction time so `reconcile`
// can be invoked later without re-providing driver dependencies.
// The service tag's declared `reconcile: Effect<void>` hides R from
// consumers — we materialize that here.
const driverContext = yield* Effect.context<R>();
const entries = yield* Ref.make<ReadonlyMap<ProviderInstanceId, LiveEntry>>(new Map());
const unavailable = yield* Ref.make<ReadonlyMap<ProviderInstanceId, ServerProvider>>(new Map());
const changes = yield* PubSub.unbounded<void>();
yield* Effect.addFinalizer(() => PubSub.shutdown(changes));
const state: RegistryState = { entries, unavailable, changes };
const reconcileWithR = makeReconcile({ state, driversById, parentScope });
const reconcile: ProviderInstanceRegistryMutatorShape["reconcile"] = (configMap) =>
reconcileWithR(configMap).pipe(Effect.provideContext(driverContext));
// Hydrate the initial configMap synchronously so callers can read
// `listInstances` immediately after this effect completes.
yield* reconcile(input.configMap);
const registry: ProviderInstanceRegistryShape = {
getInstance: (id) => Ref.get(entries).pipe(Effect.map((map) => map.get(id)?.instance)),
listInstances: Ref.get(entries).pipe(
Effect.map(
(map) =>
Array.from(map.values(), (live) => live.instance) as ReadonlyArray<ProviderInstance>,
),
),
listUnavailable: Ref.get(unavailable).pipe(
Effect.map((map) => Array.from(map.values()) as ReadonlyArray<ServerProvider>),
),
// Getters: each read constructs a fresh Stream / Effect descriptor
// so multiple consumers don't share a single already-started
// Channel or subscription. Matches the pattern `ProviderRegistry`
// uses for its own `streamChanges`.
get streamChanges() {
return Stream.fromPubSub(changes);
},
// Synchronous subscribe — callers that need to consume changes
// from a forked fibre must acquire the subscription in their own
// fibre first (via `yield* registry.subscribeChanges`) and only
// then fork a consumer loop on `Stream.fromSubscription(...)` /
// `PubSub.take(...)`. See the shape docs for the race this avoids.
get subscribeChanges() {
return PubSub.subscribe(changes);
},
};
const mutator: ProviderInstanceRegistryMutatorShape = { reconcile };
return { registry, mutator };
});
/**
* Assemble a `ProviderInstanceRegistry` Layer bound to a fixed set of
* drivers and a pre-resolved `ProviderInstanceConfigMap`. Used by tests
* that want explicit control over the registry's source-of-truth without
* wiring up the settings watcher.
*
* Only exposes the public registry tag — hot-reload consumers should use
* `ProviderInstanceRegistryMutableLayer` (below) or the hydration layer.
*/
export const ProviderInstanceRegistryLayer = <R>(input: {
readonly drivers: ReadonlyArray<AnyProviderDriver<R>>;
readonly configMap: ProviderInstanceConfigMap;
}): Layer.Layer<ProviderInstanceRegistry, never, R> =>
Layer.effect(
ProviderInstanceRegistry,
makeProviderInstanceRegistry(input).pipe(Effect.map((built) => built.registry)),
) as Layer.Layer<ProviderInstanceRegistry, never, R>;
/**
* Layer variant that also exposes the mutator tag. Consumed by
* `ProviderInstanceRegistryHydrationLive` to reconcile on settings
* changes. Tests that exercise the mutator directly can pair this Layer
* with a test-local `ServerSettingsService`.
*/
export const ProviderInstanceRegistryMutableLayer = <R>(input: {
readonly drivers: ReadonlyArray<AnyProviderDriver<R>>;
readonly configMap: ProviderInstanceConfigMap;
}): Layer.Layer<ProviderInstanceRegistry | ProviderInstanceRegistryMutator, never, R> =>
Layer.effectContext(
makeProviderInstanceRegistry(input).pipe(
Effect.map(({ registry, mutator }) =>
Context.make(ProviderInstanceRegistry, registry).pipe(
Context.add(ProviderInstanceRegistryMutator, mutator),
),
),
),
) as Layer.Layer<ProviderInstanceRegistry | ProviderInstanceRegistryMutator, never, R>;
export { defaultInstanceIdForDriver };
File diff suppressed because it is too large. Load diff
@@ -1,39 +1,63 @@
/**
* ProviderRegistryLive - Aggregates provider-specific snapshot services.
* ProviderRegistryLive — aggregates per-instance snapshot streams into a
* single materialized list.
*
* Historically this Layer composed four per-kind Live Layers
* (`CodexProviderLive`, `ClaudeProviderLive`, …) that each exposed a
* `ServerProviderShape`. Those Lives were deleted during the driver /
* instance refactor — every driver now carries its `snapshot: ServerProviderShape`
* bundled onto the `ProviderInstance` the registry produces.
*
* Each configured instance (including multi-instance setups like
* `codex_personal` + `codex_work`) contributes one `ProviderSnapshotSource`,
* keyed by `instanceId`. Instances whose driver is unavailable or whose
* config failed to decode are merged from `instanceRegistry.listUnavailable`
* as shadow snapshots so the UI can render their exact unavailable reason.
*
* Cache paths on disk are now keyed by `instanceId`. Because
* `defaultInstanceIdForDriver(kind) === kind` for built-in kinds, existing
* `<kind>.json` files remain the on-disk location for that driver's default
* instance. Identity-less legacy cache contents are ignored and replaced by
* the first live refresh.
*
* @module ProviderRegistryLive
*/
import type { ProviderKind, ServerProvider } from "@t3tools/contracts";
import { Effect, Equal, FileSystem, Layer, Path, PubSub, Ref, Stream } from "effect";
import {
defaultInstanceIdForDriver,
ProviderDriverKind,
type ProviderInstanceId,
type ServerProvider,
} from "@t3tools/contracts";
import { Cause, Effect, Equal, FileSystem, Layer, Path, PubSub, Ref, Stream } from "effect";
import * as Semaphore from "effect/Semaphore";
import { ServerConfig } from "../../config.ts";
import { ClaudeProviderLive } from "./ClaudeProvider.ts";
import { CodexProviderLive } from "./CodexProvider.ts";
import { CursorProviderLive } from "./CursorProvider.ts";
import { OpenCodeProviderLive } from "./OpenCodeProvider.ts";
import { ClaudeProvider } from "../Services/ClaudeProvider.ts";
import { CodexProvider } from "../Services/CodexProvider.ts";
import { CursorProvider } from "../Services/CursorProvider.ts";
import { OpenCodeProvider } from "../Services/OpenCodeProvider.ts";
import { ProviderInstanceRegistry } from "../Services/ProviderInstanceRegistry.ts";
import { ProviderRegistry, type ProviderRegistryShape } from "../Services/ProviderRegistry.ts";
import { OpenCodeRuntimeLive } from "../opencodeRuntime.ts";
import {
hydrateCachedProvider,
PROVIDER_CACHE_IDS,
isCachedProviderCorrelated,
orderProviderSnapshots,
readProviderStatusCache,
resolveProviderStatusCachePath,
writeProviderStatusCache,
} from "../providerStatusCache.ts";
import { createBuiltInProviderSources } from "../builtInProviderCatalog.ts";
import type { ProviderInstance } from "../ProviderDriver.ts";
import type { ProviderSnapshotSource } from "../builtInProviderCatalog.ts";
const loadProviders = (
providerSources: ReadonlyArray<ProviderSnapshotSource>,
): Effect.Effect<ReadonlyArray<ServerProvider>> =>
Effect.forEach(providerSources, (providerSource) => providerSource.getSnapshot, {
concurrency: "unbounded",
});
Effect.forEach(
providerSources,
(providerSource) =>
providerSource.getSnapshot.pipe(
Effect.flatMap((snapshot) => correlateSnapshotWithSource(providerSource, snapshot)),
),
{
concurrency: "unbounded",
},
);
const hasModelCapabilities = (model: ServerProvider["models"][number]): boolean =>
(model.capabilities?.optionDescriptors?.length ?? 0) > 0;
@@ -77,63 +101,123 @@ export const haveProvidersChanged = (
nextProviders: ReadonlyArray<ServerProvider>,
): boolean => !Equal.equals(previousProviders, nextProviders);
const ProviderRegistryLiveBase = Layer.effect(
const correlateSnapshotWithSource = (
source: ProviderSnapshotSource,
snapshot: ServerProvider,
): Effect.Effect<ServerProvider> => {
if (snapshot.instanceId !== source.instanceId) {
return Effect.die(
new Error(
`Provider snapshot instance mismatch: source '${source.instanceId}' emitted '${snapshot.instanceId}'.`,
),
);
}
if (snapshot.driver !== source.driverKind) {
return Effect.die(
new Error(
`Provider snapshot driver mismatch for instance '${source.instanceId}': source '${source.driverKind}' emitted '${snapshot.driver}'.`,
),
);
}
return Effect.succeed(snapshot);
};
/**
* Key a snapshot for aggregation and persistence. Snapshot sources
* must be correlated by instance id before reaching this map; missing
* identities are defects, not runtime routing fallbacks.
*/
const snapshotInstanceKey = (provider: ServerProvider): ProviderInstanceId => {
return provider.instanceId;
};
// Project a live `ProviderInstance` into the aggregator's consumption
// shape. Each call re-captures the instance's `snapshot` closures, so
// after `ProviderInstanceRegistry` rebuilds an instance (e.g. because
// its settings changed), a fresh source rides the new PubSub instead
// of a closed one.
const buildSnapshotSource = (instance: ProviderInstance): ProviderSnapshotSource => ({
instanceId: instance.instanceId,
driverKind: instance.driverKind,
getSnapshot: instance.snapshot.getSnapshot,
refresh: instance.snapshot.refresh,
streamChanges: instance.snapshot.streamChanges,
});
export const ProviderRegistryLive = Layer.effect(
ProviderRegistry,
Effect.gen(function* () {
const codexProvider = yield* CodexProvider;
const claudeProvider = yield* ClaudeProvider;
const openCodeProvider = yield* OpenCodeProvider;
const instanceRegistry = yield* ProviderInstanceRegistry;
const config = yield* ServerConfig;
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const cursorProvider = yield* CursorProvider;
const providerSources = createBuiltInProviderSources({
codex: codexProvider,
claudeAgent: claudeProvider,
opencode: openCodeProvider,
cursor: cursorProvider,
}) satisfies ReadonlyArray<ProviderSnapshotSource>;
const activeProviders = PROVIDER_CACHE_IDS;
// Aggregator PubSub — consumers (WS gateway, etc.) subscribe here for
// coalesced updates across every instance.
const changesPubSub = yield* Effect.acquireRelease(
PubSub.unbounded<ReadonlyArray<ServerProvider>>(),
PubSub.shutdown,
);
const fallbackProviders = yield* loadProviders(providerSources);
const cachePathByProvider = new Map(
activeProviders.map(
(provider) =>
[
provider,
resolveProviderStatusCachePath({
cacheDir: config.providerStatusCacheDir,
provider,
}),
] as const,
),
);
const fallbackByProvider = new Map(
fallbackProviders.map((provider) => [provider.provider, provider] as const),
);
// Boot-only: hydrate `providersRef` from the on-disk per-instance
// cache so the UI has something to render during the first refresh.
// Instances added post-boot skip this path; their first entry in
// `providersRef` comes from the reactive `syncLiveSources` pass
// below.
const bootInstances = yield* instanceRegistry.listInstances;
const bootSources = bootInstances.map(buildSnapshotSource);
const fallbackProviders = yield* loadProviders(bootSources);
const fallbackByInstance = new Map<ProviderInstanceId, ServerProvider>();
for (let index = 0; index < fallbackProviders.length; index++) {
const provider = fallbackProviders[index];
const source = bootSources[index];
if (provider === undefined || source === undefined) {
continue;
}
fallbackByInstance.set(source.instanceId, provider);
}
const cachedProviders = yield* Effect.forEach(
activeProviders,
(provider) => {
const filePath = cachePathByProvider.get(provider)!;
const fallbackProvider = fallbackByProvider.get(provider)!;
return readProviderStatusCache(filePath).pipe(
Effect.provideService(FileSystem.FileSystem, fileSystem),
Effect.map((cachedProvider) =>
cachedProvider === undefined
? undefined
: hydrateCachedProvider({
cachedProvider,
fallbackProvider,
}),
),
);
},
bootSources,
(source) =>
Effect.gen(function* () {
// One cache file per configured instance. For the default
// instance of a built-in kind the path equals `<kind>.json` —
// identical to the legacy filename. We still require the cache
// payload to carry matching instance id + driver kind; old
// identity-less payloads are discarded and the awaited refresh
// below repopulates the cache.
const filePath = yield* resolveProviderStatusCachePath({
cacheDir: config.providerStatusCacheDir,
instanceId: source.instanceId,
}).pipe(Effect.provideService(Path.Path, path));
const fallbackProvider = fallbackByInstance.get(source.instanceId);
if (fallbackProvider === undefined) {
return undefined;
}
return yield* readProviderStatusCache(filePath).pipe(
Effect.provideService(FileSystem.FileSystem, fileSystem),
Effect.flatMap((cachedProvider) => {
if (cachedProvider === undefined) {
return Effect.void.pipe(Effect.as(undefined as ServerProvider | undefined));
}
const correlation = {
cachedProvider,
fallbackProvider,
} as const;
if (!isCachedProviderCorrelated(correlation)) {
return Effect.logWarning("provider status cache identity mismatch, ignoring", {
path: filePath,
instanceId: source.instanceId,
cachedInstanceId: cachedProvider.instanceId ?? null,
driver: source.driverKind,
cachedDriver: cachedProvider.driver ?? null,
}).pipe(Effect.as(undefined as ServerProvider | undefined));
}
return Effect.succeed(hydrateCachedProvider(correlation));
}),
);
}),
{ concurrency: "unbounded" },
).pipe(
Effect.map((providers) =>
@@ -144,34 +228,64 @@ const ProviderRegistryLiveBase = Layer.effect(
);
const providersRef = yield* Ref.make<ReadonlyArray<ServerProvider>>(cachedProviders);
// Live-source registry — the dynamic counterpart to the boot-time
// `bootSources`. Keyed by `instanceId`; the stored `ProviderInstance`
// reference is used for identity equality so "no-op" reconciles
// (settings unchanged) skip re-subscribing + re-probing.
const liveSubsRef = yield* Ref.make<ReadonlyMap<ProviderInstanceId, ProviderInstance>>(
new Map(),
);
// Serialize `syncLiveSources` so a rapid burst of reconciles doesn't
// interleave two passes clobbering each other's fiber bookkeeping.
const syncSemaphore = yield* Semaphore.make(1);
const getLiveSources: Effect.Effect<ReadonlyArray<ProviderSnapshotSource>> = Ref.get(
liveSubsRef,
).pipe(Effect.map((map) => Array.from(map.values(), buildSnapshotSource)));
const persistProvider = (provider: ServerProvider) =>
writeProviderStatusCache({
filePath: cachePathByProvider.get(provider.provider)!,
provider,
}).pipe(
Effect.provideService(FileSystem.FileSystem, fileSystem),
Effect.provideService(Path.Path, path),
Effect.tapError(Effect.logError),
Effect.ignore,
);
Effect.gen(function* () {
// Persist every instance — the file name is the instance id, so
// multi-instance setups (e.g. `codex_personal`, `codex_work`) each
// get their own cache. We resolve the path fresh so snapshots
// produced by newly-added instances post-boot still land on disk
// without the aggregator holding a stale `cachePathByInstance`
// entry.
const key = snapshotInstanceKey(provider);
const filePath = yield* resolveProviderStatusCachePath({
cacheDir: config.providerStatusCacheDir,
instanceId: key,
}).pipe(Effect.provideService(Path.Path, path));
yield* writeProviderStatusCache({ filePath, provider }).pipe(
Effect.provideService(FileSystem.FileSystem, fileSystem),
Effect.provideService(Path.Path, path),
Effect.tapError(Effect.logError),
Effect.ignore,
);
});
const upsertProviders = Effect.fn("upsertProviders")(function* (
nextProviders: ReadonlyArray<ServerProvider>,
options?: {
readonly publish?: boolean;
readonly persist?: boolean;
readonly replace?: boolean;
},
) {
const [previousProviders, providers] = yield* Ref.modify(
providersRef,
(previousProviders) => {
const mergedProviders = new Map(
previousProviders.map((provider) => [provider.provider, provider] as const),
previousProviders.map((provider) => [snapshotInstanceKey(provider), provider] as const),
);
for (const provider of nextProviders) {
const key = snapshotInstanceKey(provider);
mergedProviders.set(
provider.provider,
mergeProviderSnapshot(mergedProviders.get(provider.provider), provider),
key,
options?.replace === true
? provider
: mergeProviderSnapshot(mergedProviders.get(key), provider),
);
}
@@ -181,10 +295,12 @@ const ProviderRegistryLiveBase = Layer.effect(
);
if (haveProvidersChanged(previousProviders, providers)) {
yield* Effect.forEach(nextProviders, persistProvider, {
concurrency: "unbounded",
discard: true,
});
if (options?.persist !== false) {
yield* Effect.forEach(nextProviders, persistProvider, {
concurrency: "unbounded",
discard: true,
});
}
if (options?.publish !== false) {
yield* PubSub.publish(changesPubSub, providers);
}
@@ -202,64 +318,246 @@ const ProviderRegistryLiveBase = Layer.effect(
return yield* upsertProviders([provider], options);
});
const refresh = Effect.fn("refresh")(function* (provider?: ProviderKind) {
if (provider) {
const providerSource = providerSources.find((candidate) => candidate.provider === provider);
if (!providerSource) {
return yield* Ref.get(providersRef);
}
return yield* providerSource.refresh.pipe(
Effect.flatMap((nextProvider) => syncProvider(nextProvider)),
);
}
return yield* Effect.forEach(
providerSources,
(providerSource) => providerSource.refresh.pipe(Effect.flatMap(syncProvider)),
{
concurrency: "unbounded",
discard: true,
},
).pipe(Effect.andThen(Ref.get(providersRef)));
const refreshOneSource = Effect.fn("refreshOneSource")(function* (
providerSource: ProviderSnapshotSource,
) {
return yield* providerSource.refresh.pipe(
Effect.flatMap((nextProvider) =>
correlateSnapshotWithSource(providerSource, nextProvider).pipe(
Effect.flatMap(syncProvider),
),
),
);
});
yield* Effect.forEach(
providerSources,
(providerSource) =>
Stream.runForEach(providerSource.streamChanges, (provider) => syncProvider(provider)).pipe(
Effect.forkScoped,
),
{
const refreshAll = Effect.fn("refreshAll")(function* () {
const sources = yield* getLiveSources;
return yield* Effect.forEach(sources, (source) => refreshOneSource(source), {
concurrency: "unbounded",
discard: true,
},
}).pipe(Effect.andThen(Ref.get(providersRef)));
});
const refresh = Effect.fn("refresh")(function* (provider?: ProviderDriverKind) {
if (provider === undefined) {
return yield* refreshAll();
}
// Kind-scoped refreshes target the default instance for that driver.
const defaultInstanceId = defaultInstanceIdForDriver(provider);
const sources = yield* getLiveSources;
const providerSource = sources.find(
(candidate) => candidate.instanceId === defaultInstanceId,
);
if (!providerSource) {
return yield* Ref.get(providersRef);
}
return yield* refreshOneSource(providerSource);
});
const refreshInstance = Effect.fn("refreshInstance")(function* (
instanceId: ProviderInstanceId,
) {
const sources = yield* getLiveSources;
const providerSource = sources.find((candidate) => candidate.instanceId === instanceId);
if (!providerSource) {
return yield* Ref.get(providersRef);
}
return yield* refreshOneSource(providerSource);
});
/**
* Diff the aggregator's live-source set against the current
* `ProviderInstanceRegistry` and:
* - subscribe to each newly-added or rebuilt instance's
* `streamChanges` (so periodic + enrichment refreshes land in
* `providersRef`);
* - force-refresh each newly-added/rebuilt instance and feed the
* result directly into `providersRef`, bypassing the PubSub
* attachment race that otherwise drops the initial probe;
* - prune `providersRef` of instances that no longer exist.
*
* Initial refreshes are awaited in parallel rather than forked, so
* callers (layer build; `streamChanges` watcher) see fully-probed
* state on return. This matters for layer build in particular:
* consumers reading `getProviders` immediately after layer build
* expect the probe to have already landed.
*
* Per-instance subscription fibers are not tracked explicitly. When
* a rebuilt instance's old child scope closes, its PubSub shuts
* down and our `Stream.runForEach` fiber exits naturally.
*/
const syncLiveSources = syncSemaphore.withPermits(1)(
Effect.gen(function* () {
const instances = yield* instanceRegistry.listInstances;
const unavailableProviders = yield* instanceRegistry.listUnavailable;
const nextByInstance = new Map<ProviderInstanceId, ProviderInstance>(
instances.map((instance) => [instance.instanceId, instance] as const),
);
const knownInstanceIds = new Set<ProviderInstanceId>(nextByInstance.keys());
for (const provider of unavailableProviders) {
knownInstanceIds.add(snapshotInstanceKey(provider));
}
const previousSubs = yield* Ref.get(liveSubsRef);
// Carry over subscriptions for instances whose identity is
// unchanged (reconcile treated them as no-op). Instances that
// disappeared, or were rebuilt with a different reference,
// fall through to the "newly-added" branch below.
const carriedOver = new Map<ProviderInstanceId, ProviderInstance>();
for (const [instanceId, previousInstance] of previousSubs) {
const nextInstance = nextByInstance.get(instanceId);
if (nextInstance !== undefined && nextInstance === previousInstance) {
carriedOver.set(instanceId, previousInstance);
}
}
// Collect new/rebuilt instances in `nextByInstance` insertion
// order (which preserves settings-author order).
const newlyAdded: Array<readonly [ProviderInstanceId, ProviderInstance]> = [];
for (const [instanceId, instance] of nextByInstance) {
if (carriedOver.has(instanceId)) {
continue;
}
newlyAdded.push([instanceId, instance] as const);
}
// Fork long-lived subscriptions to each new/rebuilt instance's
// change stream BEFORE kicking off refreshes — if the driver's
// own initial probe (line 140 in `makeManagedServerProvider`)
// wins the refreshSemaphore race, its PubSub publish must land
// in an active subscriber or the result is dropped.
for (const [, instance] of newlyAdded) {
const source = buildSnapshotSource(instance);
yield* Stream.runForEach(source.streamChanges, (provider) =>
correlateSnapshotWithSource(source, provider).pipe(Effect.flatMap(syncProvider)),
).pipe(Effect.forkScoped);
}
// Force-refresh every new/rebuilt instance in parallel and wait
// for them all to complete. The refresh's result is piped
// directly into `syncProvider`, so `providersRef` is populated
// deterministically by the time this block returns — regardless
// of PubSub subscription timing. Failures are logged and
// swallowed so one bad driver can't wedge the whole registry.
yield* Effect.forEach(
newlyAdded,
([, instance]) =>
refreshOneSource(buildSnapshotSource(instance)).pipe(Effect.ignoreCause({ log: true })),
{ concurrency: "unbounded", discard: true },
);
yield* upsertProviders(unavailableProviders, {
persist: false,
replace: true,
});
const nextSubs = new Map(carriedOver);
for (const [instanceId, instance] of newlyAdded) {
nextSubs.set(instanceId, instance);
}
yield* Ref.set(liveSubsRef, nextSubs);
// Drop aggregator state for instances that have disappeared —
// otherwise the UI would keep rendering ghosts.
const [previousProviders, providers] = yield* Ref.modify(
providersRef,
(previousProviders) => {
const providers = orderProviderSnapshots(
previousProviders.filter((provider) =>
knownInstanceIds.has(snapshotInstanceKey(provider)),
),
);
return [[previousProviders, providers] as const, providers];
},
);
if (haveProvidersChanged(previousProviders, providers)) {
yield* PubSub.publish(changesPubSub, providers);
}
}),
);
yield* loadProviders(providerSources).pipe(
Effect.flatMap((providers) => upsertProviders(providers, { publish: false })),
const syncLiveSourcesAndContinue = syncLiveSources.pipe(
Effect.catchCause((cause) => {
if (Cause.hasInterruptsOnly(cause)) {
return Effect.interrupt;
}
return Effect.logError(
"provider registry instance sync failed; keeping subscription alive",
{
cause: Cause.pretty(cause),
},
);
}),
);
// Seed `providersRef` with the boot-time fallback snapshots so
// consumers calling `getProviders` immediately after layer build see
// a populated list — even before the first `syncLiveSources` refresh
// resolves. Cached snapshots (already in `providersRef`) merge with
// these via `upsertProviders` so on-disk state wins where present
// and pending fallbacks fill the gaps.
yield* upsertProviders(fallbackProviders, { publish: false });
// Subscribe to registry mutations BEFORE running the initial sync.
// `subscribeChanges` acquires the dequeue synchronously in this
// fibre; the subscription is active the instant this `yield*`
// returns. Forking the consumer loop later cannot lose a publish
// because no publish can reach a not-yet-subscribed dequeue.
//
// (Contrast with the pre-fix code that did
// `Stream.runForEach(instanceRegistry.streamChanges, …).pipe(Effect.forkScoped)`.
// `Stream.fromPubSub` defers `PubSub.subscribe` to stream start,
// and `forkScoped` only schedules the fibre — so a reconcile that
// published between "fibre scheduled" and "fibre starts running"
// was dropped, which made any settings change that replaced an
// instance never propagate to the aggregator's `providersRef`.)
// Subscribe to registry mutations BEFORE running the initial sync.
// `subscribeChanges` acquires the `PubSub.Subscription` synchronously
// in this fibre; the subscription is registered with the PubSub the
// instant this `yield*` returns, so any subsequent publish is
// buffered in the subscription regardless of when the consumer
// fibre below actually starts running.
//
// (Contrast with the pre-fix code that did
// `Stream.runForEach(instanceRegistry.streamChanges, …).pipe(Effect.forkScoped)`.
// `instanceRegistry.streamChanges` is `Stream.fromPubSub(changes)`,
// which defers `PubSub.subscribe` to stream start. `forkScoped` only
// schedules the consumer fibre — so a reconcile that published
// between "fibre scheduled" and "fibre starts running + subscribes"
// was dropped, which made any settings change that replaced an
// instance never propagate to the aggregator's `providersRef`.)
const instanceChanges = yield* instanceRegistry.subscribeChanges;
// Initial sync: subscribe + kick off refreshes for every instance
// present at boot. Run synchronously so consumers pulling immediately
// after the layer build see the correct aggregator state.
yield* syncLiveSources;
// React to registry mutations — instance added / removed / rebuilt.
// `Stream.fromSubscription` builds a stream over the pre-acquired
// subscription rather than subscribing on stream start, which is
// what closes the race.
yield* Stream.runForEach(
Stream.fromSubscription(instanceChanges),
() => syncLiveSourcesAndContinue,
).pipe(Effect.forkScoped);
const recoverRefreshFailure = Effect.fn("recoverRefreshFailure")(function* (
cause: Cause.Cause<unknown>,
) {
if (Cause.hasInterruptsOnly(cause)) {
return yield* Effect.interrupt;
}
yield* Effect.logError("provider registry refresh failed; preserving cached providers", {
cause: Cause.pretty(cause),
});
return yield* Ref.get(providersRef);
});
return {
getProviders: Ref.get(providersRef),
refresh: (provider?: ProviderKind) =>
refresh(provider).pipe(
Effect.tapError(Effect.logError),
Effect.orElseSucceed(() => [] as ReadonlyArray<ServerProvider>),
),
refresh: (provider?: ProviderDriverKind) =>
refresh(provider).pipe(Effect.catchCause(recoverRefreshFailure)),
refreshInstance: (instanceId: ProviderInstanceId) =>
refreshInstance(instanceId).pipe(Effect.catchCause(recoverRefreshFailure)),
get streamChanges() {
return Stream.fromPubSub(changesPubSub);
},
} satisfies ProviderRegistryShape;
}),
);
export const ProviderRegistryLive = Layer.unwrap(
Effect.sync(() =>
ProviderRegistryLiveBase.pipe(
Layer.provideMerge(CursorProviderLive),
Layer.provideMerge(CodexProviderLive),
Layer.provideMerge(ClaudeProviderLive),
Layer.provideMerge(OpenCodeProviderLive),
Layer.provideMerge(OpenCodeRuntimeLive),
),
),
);
File diff suppressed because it is too large. Load diff
+336 -100
View File
@@ -19,10 +19,12 @@ import {
ProviderSendTurnInput,
ProviderSessionStartInput,
ProviderStopSessionInput,
type ProviderInstanceId,
type ProviderDriverKind,
type ProviderRuntimeEvent,
type ProviderSession,
} from "@t3tools/contracts";
import { Effect, Layer, Option, PubSub, Schema, SchemaIssue, Stream } from "effect";
import { Cause, Effect, Layer, Option, PubSub, Ref, Schema, SchemaIssue, Stream } from "effect";
import {
increment,
@@ -34,19 +36,24 @@ import {
providerTurnMetricAttributes,
withMetrics,
} from "../../observability/Metrics.ts";
import { ProviderValidationError } from "../Errors.ts";
import { type ProviderAdapterError, ProviderValidationError } from "../Errors.ts";
import type { ProviderAdapterShape } from "../Services/ProviderAdapter.ts";
import { ProviderAdapterRegistry } from "../Services/ProviderAdapterRegistry.ts";
import { ProviderService, type ProviderServiceShape } from "../Services/ProviderService.ts";
import {
ProviderSessionDirectory,
type ProviderRuntimeBinding,
} from "../Services/ProviderSessionDirectory.ts";
import { type EventNdjsonLogger, makeEventNdjsonLogger } from "./EventNdjsonLogger.ts";
import { type EventNdjsonLogger } from "./EventNdjsonLogger.ts";
import { ProviderEventLoggers } from "./ProviderEventLoggers.ts";
import { AnalyticsService } from "../../telemetry/Services/AnalyticsService.ts";
import { ServerSettingsService } from "../../serverSettings.ts";
/**
* Hook for tests that want to override the canonical event logger pulled
* from `ProviderEventLoggers`. Production wiring leaves this undefined and
* reads the logger off the tag.
*/
export interface ProviderServiceLiveOptions {
readonly canonicalEventLogPath?: string;
readonly canonicalEventLogger?: EventNdjsonLogger;
}
@@ -141,18 +148,53 @@ function readPersistedCwd(
return trimmed.length > 0 ? trimmed : undefined;
}
const dieOnMissingBindingInstanceId = (
operation: string,
payload: {
readonly providerInstanceId?: ProviderInstanceId | undefined;
readonly provider?: ProviderDriverKind | undefined;
},
): ProviderInstanceId => {
if (payload.providerInstanceId !== undefined) {
return payload.providerInstanceId;
}
throw new Error(
payload.provider
? `${operation}: provider instance id is required for provider '${payload.provider}'.`
: `${operation}: provider instance id is required.`,
);
};
const correlateRuntimeEventWithInstance = (
source: {
readonly instanceId: ProviderInstanceId;
readonly provider: ProviderDriverKind;
},
event: ProviderRuntimeEvent,
): ProviderRuntimeEvent => {
if (event.provider !== source.provider) {
throw new Error(
`ProviderService.streamEvents: provider instance '${source.instanceId}' is backed by driver '${source.provider}' but emitted driver '${event.provider}'.`,
);
}
if (event.providerInstanceId !== undefined && event.providerInstanceId !== source.instanceId) {
throw new Error(
`ProviderService.streamEvents: provider instance '${source.instanceId}' emitted event for instance '${event.providerInstanceId}'.`,
);
}
return { ...event, providerInstanceId: source.instanceId };
};
const makeProviderService = Effect.fn("makeProviderService")(function* (
options?: ProviderServiceLiveOptions,
) {
const analytics = yield* Effect.service(AnalyticsService);
const serverSettings = yield* ServerSettingsService;
const canonicalEventLogger =
options?.canonicalEventLogger ??
(options?.canonicalEventLogPath !== undefined
? yield* makeEventNdjsonLogger(options.canonicalEventLogPath, {
stream: "canonical",
})
: undefined);
const eventLoggers = yield* ProviderEventLoggers;
// Options-provided logger wins (test overrides); otherwise we take whatever
// the `ProviderEventLoggers` tag exposes — `undefined` means "no canonical
// log writer is attached", which downstream code already handles as a
// no-op.
const canonicalEventLogger = options?.canonicalEventLogger ?? eventLoggers.canonical;
const registry = yield* ProviderAdapterRegistry;
const directory = yield* ProviderSessionDirectory;
@@ -169,6 +211,24 @@ const makeProviderService = Effect.fn("makeProviderService")(function* (
Effect.asVoid,
);
const requireBindingInstanceId = (
operation: string,
payload: {
readonly providerInstanceId?: ProviderInstanceId | undefined;
readonly provider?: ProviderDriverKind | undefined;
},
): Effect.Effect<ProviderInstanceId, ProviderValidationError> =>
payload.providerInstanceId !== undefined
? Effect.succeed(payload.providerInstanceId)
: Effect.fail(
toValidationError(
operation,
payload.provider
? `Provider instance id is required for provider '${payload.provider}'.`
: "Provider instance id is required.",
),
);
const upsertSessionBinding = (
session: ProviderSession,
threadId: ThreadId,
@@ -178,38 +238,106 @@ const makeProviderService = Effect.fn("makeProviderService")(function* (
readonly lastRuntimeEventAt?: string;
},
) =>
directory.upsert({
threadId,
provider: session.provider,
runtimeMode: session.runtimeMode,
status: toRuntimeStatus(session),
...(session.resumeCursor !== undefined ? { resumeCursor: session.resumeCursor } : {}),
runtimePayload: toRuntimePayloadFromSession(session, extra),
Effect.gen(function* () {
const providerInstanceId = yield* requireBindingInstanceId(
"ProviderService.upsertSessionBinding",
session,
);
yield* directory.upsert({
threadId,
provider: session.provider,
providerInstanceId,
runtimeMode: session.runtimeMode,
status: toRuntimeStatus(session),
...(session.resumeCursor !== undefined ? { resumeCursor: session.resumeCursor } : {}),
runtimePayload: toRuntimePayloadFromSession(session, extra),
});
});
const providers = yield* registry.listProviders();
const adapters = yield* Effect.forEach(providers, (provider) => registry.getByProvider(provider));
const processRuntimeEvent = (event: ProviderRuntimeEvent): Effect.Effect<void> =>
increment(providerRuntimeEventsTotal, {
provider: event.provider,
eventType: event.type,
}).pipe(Effect.andThen(publishRuntimeEvent(event)));
const processRuntimeEvent = (
source: {
readonly instanceId: ProviderInstanceId;
readonly provider: ProviderDriverKind;
},
event: ProviderRuntimeEvent,
): Effect.Effect<void> =>
Effect.sync(() => correlateRuntimeEventWithInstance(source, event)).pipe(
Effect.flatMap((canonicalEvent) =>
increment(providerRuntimeEventsTotal, {
provider: canonicalEvent.provider,
eventType: canonicalEvent.type,
}).pipe(Effect.andThen(publishRuntimeEvent(canonicalEvent))),
),
);
yield* Effect.forEach(adapters, (adapter) =>
Stream.runForEach(adapter.streamEvents, processRuntimeEvent).pipe(Effect.forkScoped),
).pipe(Effect.asVoid);
// `subscribedAdapters` is our source-of-truth for "which instance adapters
// are currently wired into the runtime event bus". It both tracks the set
// of live subscriptions (so `reconcileInstanceSubscriptions` can diff and
// fork only the *new* or *rebuilt* ones) and serves as the dynamic adapter
// list consumed by `stopStaleSessionsForThread`, `listSessions`, and
// `runStopAll` — replacing the pre-Slice-D startup snapshot so hot-added
// instances become visible to those call sites as soon as settings edits
// land.
const subscribedAdapters = yield* Ref.make(
new Map<ProviderInstanceId, ProviderAdapterShape<ProviderAdapterError>>(),
);
const getAdapterEntries = Ref.get(subscribedAdapters).pipe(
Effect.map((map) => Array.from(map.entries())),
);
// Rebuild the map of id → adapter from the registry and fork a new event
// subscription for every instance that is either brand new or whose adapter
// identity changed (indicating the underlying `ProviderInstance` was torn
// down and rebuilt by `ProviderInstanceRegistry.reconcile`). Orphaned
// fibers for removed/replaced instances exit on their own because their
// adapter's `streamEvents` source terminates when the old scope closes.
const reconcileInstanceSubscriptions = Effect.gen(function* () {
const previous = yield* Ref.get(subscribedAdapters);
const currentIds = yield* registry.listInstances();
const next = new Map<ProviderInstanceId, ProviderAdapterShape<ProviderAdapterError>>();
for (const id of currentIds) {
const adapterOption = yield* registry
.getByInstance(id)
.pipe(Effect.tapError(Effect.logWarning), Effect.option);
if (Option.isNone(adapterOption)) continue;
const adapter = adapterOption.value;
next.set(id, adapter);
if (previous.get(id) !== adapter) {
yield* Stream.runForEach(adapter.streamEvents, (event) =>
processRuntimeEvent(
{
instanceId: id,
provider: adapter.provider,
},
event,
),
).pipe(Effect.forkScoped);
}
}
yield* Ref.set(subscribedAdapters, next);
});
const instanceChanges = yield* registry.subscribeChanges;
yield* reconcileInstanceSubscriptions;
yield* Stream.runForEach(
Stream.fromSubscription(instanceChanges),
() => reconcileInstanceSubscriptions,
).pipe(Effect.forkScoped);
const recoverSessionForThread = Effect.fn("recoverSessionForThread")(function* (input: {
readonly binding: ProviderRuntimeBinding;
readonly operation: string;
}) {
const bindingInstanceId = yield* requireBindingInstanceId(input.operation, input.binding);
yield* Effect.annotateCurrentSpan({
"provider.operation": "recover-session",
"provider.kind": input.binding.provider,
"provider.instance_id": bindingInstanceId,
"provider.thread_id": input.binding.threadId,
});
return yield* Effect.gen(function* () {
const adapter = yield* registry.getByProvider(input.binding.provider);
const adapter = yield* registry.getByInstance(bindingInstanceId);
const hasResumeCursor =
input.binding.resumeCursor !== null && input.binding.resumeCursor !== undefined;
const hasActiveSession = yield* adapter.hasSession(input.binding.threadId);
@@ -219,7 +347,10 @@ const makeProviderService = Effect.fn("makeProviderService")(function* (
(session) => session.threadId === input.binding.threadId,
);
if (existing) {
yield* upsertSessionBinding(existing, input.binding.threadId);
yield* upsertSessionBinding(
{ ...existing, providerInstanceId: bindingInstanceId },
input.binding.threadId,
);
yield* analytics.record("provider.session.recovered", {
provider: existing.provider,
strategy: "adopt-existing",
@@ -242,6 +373,7 @@ const makeProviderService = Effect.fn("makeProviderService")(function* (
const resumed = yield* adapter.startSession({
threadId: input.binding.threadId,
provider: input.binding.provider,
providerInstanceId: bindingInstanceId,
...(persistedCwd ? { cwd: persistedCwd } : {}),
...(persistedModelSelection ? { modelSelection: persistedModelSelection } : {}),
...(hasResumeCursor ? { resumeCursor: input.binding.resumeCursor } : {}),
@@ -254,7 +386,10 @@ const makeProviderService = Effect.fn("makeProviderService")(function* (
);
}
yield* upsertSessionBinding(resumed, input.binding.threadId);
yield* upsertSessionBinding(
{ ...resumed, providerInstanceId: bindingInstanceId },
input.binding.threadId,
);
yield* analytics.record("provider.session.recovered", {
provider: resumed.provider,
strategy: "resume-thread",
@@ -284,29 +419,49 @@ const makeProviderService = Effect.fn("makeProviderService")(function* (
`Cannot route thread '${input.threadId}' because no persisted provider binding exists.`,
);
}
const adapter = yield* registry.getByProvider(binding.provider);
const instanceId = yield* requireBindingInstanceId(input.operation, binding);
const adapter = yield* registry.getByInstance(instanceId);
const hasRequestedSession = yield* adapter.hasSession(input.threadId);
if (hasRequestedSession) {
return { adapter, threadId: input.threadId, isActive: true } as const;
return {
adapter,
instanceId,
threadId: input.threadId,
isActive: true,
} as const;
}
if (!input.allowRecovery) {
return { adapter, threadId: input.threadId, isActive: false } as const;
return {
adapter,
instanceId,
threadId: input.threadId,
isActive: false,
} as const;
}
const recovered = yield* recoverSessionForThread({ binding, operation: input.operation });
return { adapter: recovered.adapter, threadId: input.threadId, isActive: true } as const;
const recovered = yield* recoverSessionForThread({
binding,
operation: input.operation,
});
return {
adapter: recovered.adapter,
instanceId,
threadId: input.threadId,
isActive: true,
} as const;
});
const stopStaleSessionsForThread = Effect.fn("stopStaleSessionsForThread")(function* (input: {
readonly threadId: ThreadId;
readonly currentProvider: ProviderSession["provider"];
readonly currentInstanceId: ProviderInstanceId;
}) {
const currentAdapters = yield* getAdapterEntries;
yield* Effect.forEach(
adapters,
(adapter) =>
adapter.provider === input.currentProvider
currentAdapters,
([instanceId, adapter]) =>
instanceId === input.currentInstanceId
? Effect.void
: Effect.gen(function* () {
const hasSession = yield* adapter.hasSession(input.threadId);
@@ -341,42 +496,73 @@ const makeProviderService = Effect.fn("makeProviderService")(function* (
payload: rawInput,
});
const input = {
...parsed,
threadId,
provider: parsed.provider ?? "codex",
};
const resolvedInstanceId = yield* requireBindingInstanceId(
"ProviderService.startSession",
parsed,
);
let metricProvider = parsed.provider ?? String(resolvedInstanceId);
yield* Effect.annotateCurrentSpan({
"provider.operation": "start-session",
"provider.kind": input.provider,
"provider.instance_id": resolvedInstanceId,
"provider.thread_id": threadId,
"provider.runtime_mode": input.runtimeMode,
"provider.runtime_mode": parsed.runtimeMode,
});
return yield* Effect.gen(function* () {
const settings = yield* serverSettings.getSettings.pipe(
Effect.mapError((error) =>
toValidationError(
"ProviderService.startSession",
`Failed to load provider settings: ${error.message}`,
error,
),
),
);
if (!settings.providers[input.provider].enabled) {
const instanceInfo = yield* registry.getInstanceInfo(resolvedInstanceId);
const resolvedProvider = instanceInfo.driverKind;
metricProvider = resolvedProvider;
if (parsed.provider !== undefined && parsed.provider !== resolvedProvider) {
return yield* toValidationError(
"ProviderService.startSession",
`Provider '${input.provider}' is disabled in T3 Code settings.`,
`Provider instance '${resolvedInstanceId}' belongs to driver '${resolvedProvider}', not '${parsed.provider}'.`,
);
}
const input = {
...parsed,
threadId,
provider: resolvedProvider,
};
if (!instanceInfo.enabled) {
return yield* toValidationError(
"ProviderService.startSession",
`Provider instance '${resolvedInstanceId}' is disabled in T3 Code settings.`,
);
}
const persistedBinding = Option.getOrUndefined(yield* directory.getBinding(threadId));
const effectiveResumeCursor =
input.resumeCursor ??
(persistedBinding?.provider === input.provider
(persistedBinding?.providerInstanceId === resolvedInstanceId
? persistedBinding.resumeCursor
: undefined);
const adapter = yield* registry.getByProvider(input.provider);
const effectiveCwd =
input.cwd ??
(persistedBinding?.providerInstanceId === resolvedInstanceId
? readPersistedCwd(persistedBinding.runtimePayload)
: undefined);
yield* Effect.annotateCurrentSpan({
"provider.kind": resolvedProvider,
"provider.resume_cursor.source":
input.resumeCursor !== undefined
? "request"
: effectiveResumeCursor !== undefined &&
persistedBinding?.providerInstanceId === resolvedInstanceId
? "persisted"
: "none",
"provider.resume_cursor.present": effectiveResumeCursor !== undefined,
"provider.cwd.source":
input.cwd !== undefined
? "request"
: effectiveCwd !== undefined &&
persistedBinding?.providerInstanceId === resolvedInstanceId
? "persisted"
: "none",
"provider.cwd.effective": effectiveCwd ?? "",
});
const adapter = yield* registry.getByInstance(resolvedInstanceId);
const session = yield* adapter.startSession({
...input,
providerInstanceId: resolvedInstanceId,
...(effectiveCwd !== undefined ? { cwd: effectiveCwd } : {}),
...(effectiveResumeCursor !== undefined ? { resumeCursor: effectiveResumeCursor } : {}),
});
@@ -386,31 +572,36 @@ const makeProviderService = Effect.fn("makeProviderService")(function* (
`Adapter/provider mismatch: requested '${adapter.provider}', received '${session.provider}'.`,
);
}
const sessionWithInstance = {
...session,
providerInstanceId: resolvedInstanceId,
};
yield* stopStaleSessionsForThread({
threadId,
currentProvider: adapter.provider,
currentInstanceId: resolvedInstanceId,
});
yield* upsertSessionBinding(session, threadId, {
yield* upsertSessionBinding(sessionWithInstance, threadId, {
modelSelection: input.modelSelection,
});
yield* analytics.record("provider.session.started", {
provider: session.provider,
provider: sessionWithInstance.provider,
runtimeMode: input.runtimeMode,
hasResumeCursor: session.resumeCursor !== undefined,
hasCwd: typeof input.cwd === "string" && input.cwd.trim().length > 0,
hasResumeCursor: sessionWithInstance.resumeCursor !== undefined,
hasCwd: typeof effectiveCwd === "string" && effectiveCwd.trim().length > 0,
hasModel:
typeof input.modelSelection?.model === "string" &&
input.modelSelection.model.trim().length > 0,
});
return session;
return sessionWithInstance;
}).pipe(
withMetrics({
counter: providerSessionsTotal,
attributes: providerMetricAttributes(input.provider, {
operation: "start",
}),
attributes: () =>
providerMetricAttributes(metricProvider, {
operation: "start",
}),
}),
);
},
@@ -457,6 +648,7 @@ const makeProviderService = Effect.fn("makeProviderService")(function* (
yield* directory.upsert({
threadId: input.threadId,
provider: routed.adapter.provider,
providerInstanceId: routed.instanceId,
status: "running",
...(turn.resumeCursor !== undefined ? { resumeCursor: turn.resumeCursor } : {}),
runtimePayload: {
@@ -625,6 +817,7 @@ const makeProviderService = Effect.fn("makeProviderService")(function* (
yield* directory.upsert({
threadId: input.threadId,
provider: routed.adapter.provider,
providerInstanceId: routed.instanceId,
status: "stopped",
runtimePayload: {
activeTurnId: null,
@@ -647,8 +840,16 @@ const makeProviderService = Effect.fn("makeProviderService")(function* (
const listSessions: ProviderServiceShape["listSessions"] = Effect.fn("listSessions")(
function* () {
const sessionsByProvider = yield* Effect.forEach(adapters, (adapter) =>
adapter.listSessions(),
const currentAdapters = yield* getAdapterEntries;
const sessionsByProvider = yield* Effect.forEach(currentAdapters, ([instanceId, adapter]) =>
adapter.listSessions().pipe(
Effect.map((sessions) =>
sessions.map((session) => ({
...session,
providerInstanceId: instanceId,
})),
),
),
);
const activeSessions = sessionsByProvider.flatMap((sessions) => sessions);
const persistedBindings = yield* directory.listThreadIds().pipe(
@@ -672,29 +873,54 @@ const makeProviderService = Effect.fn("makeProviderService")(function* (
}
}
return activeSessions.map((session) => {
const sessions: ProviderSession[] = [];
for (const session of activeSessions) {
const binding = bindingsByThreadId.get(session.threadId);
if (!binding) {
return session;
sessions.push(session);
continue;
}
const overrides: {
resumeCursor?: ProviderSession["resumeCursor"];
runtimeMode?: ProviderSession["runtimeMode"];
providerInstanceId?: ProviderSession["providerInstanceId"];
} = {};
overrides.providerInstanceId = dieOnMissingBindingInstanceId(
"ProviderService.listSessions",
binding,
);
if (binding.provider !== session.provider) {
return yield* Effect.die(
new Error(
`ProviderService.listSessions: thread '${session.threadId}' is active on provider '${session.provider}' but persisted binding names provider '${binding.provider}'.`,
),
);
}
if (overrides.providerInstanceId !== session.providerInstanceId) {
return yield* Effect.die(
new Error(
`ProviderService.listSessions: thread '${session.threadId}' is active on provider instance '${session.providerInstanceId}' but persisted binding names '${overrides.providerInstanceId}'.`,
),
);
}
if (session.resumeCursor === undefined && binding.resumeCursor !== undefined) {
overrides.resumeCursor = binding.resumeCursor;
}
if (binding.runtimeMode !== undefined) {
overrides.runtimeMode = binding.runtimeMode;
}
return Object.assign({}, session, overrides);
});
sessions.push(Object.assign({}, session, overrides));
}
return sessions;
},
);
const getCapabilities: ProviderServiceShape["getCapabilities"] = (provider) =>
registry.getByProvider(provider).pipe(Effect.map((adapter) => adapter.capabilities));
const getCapabilities: ProviderServiceShape["getCapabilities"] = (instanceId) =>
registry.getByInstance(instanceId).pipe(Effect.map((adapter) => adapter.capabilities));
const getInstanceInfo: ProviderServiceShape["getInstanceInfo"] = (instanceId) =>
registry.getInstanceInfo(instanceId);
const rollbackConversation: ProviderServiceShape["rollbackConversation"] = Effect.fn(
"rollbackConversation",
@@ -739,8 +965,16 @@ const makeProviderService = Effect.fn("makeProviderService")(function* (
const runStopAll = Effect.fn("runStopAll")(function* () {
const threadIds = yield* directory.listThreadIds();
const activeSessions = yield* Effect.forEach(adapters, (adapter) =>
adapter.listSessions(),
const currentAdapters = yield* getAdapterEntries;
const activeSessions = yield* Effect.forEach(currentAdapters, ([instanceId, adapter]) =>
adapter.listSessions().pipe(
Effect.map((sessions) =>
sessions.map((session) => ({
...session,
providerInstanceId: instanceId,
})),
),
),
).pipe(Effect.map((sessionsByAdapter) => sessionsByAdapter.flatMap((sessions) => sessions)));
yield* Effect.forEach(activeSessions, (session) =>
upsertSessionBinding(session, session.threadId, {
@@ -748,23 +982,22 @@ const makeProviderService = Effect.fn("makeProviderService")(function* (
lastRuntimeEventAt: new Date().toISOString(),
}),
).pipe(Effect.asVoid);
yield* Effect.forEach(adapters, (adapter) => adapter.stopAll()).pipe(Effect.asVoid);
yield* Effect.forEach(threadIds, (threadId) =>
directory.getProvider(threadId).pipe(
Effect.flatMap((provider) =>
directory.upsert({
threadId,
provider,
status: "stopped",
runtimePayload: {
activeTurnId: null,
lastRuntimeEvent: "provider.stopAll",
lastRuntimeEventAt: new Date().toISOString(),
},
}),
),
),
).pipe(Effect.asVoid);
yield* Effect.forEach(currentAdapters, ([, adapter]) => adapter.stopAll()).pipe(Effect.asVoid);
const bindings = yield* directory.listBindings().pipe(Effect.orElseSucceed(() => []));
yield* Effect.forEach(bindings, (binding) => {
const providerInstanceId = dieOnMissingBindingInstanceId("ProviderService.stopAll", binding);
return directory.upsert({
threadId: binding.threadId,
provider: binding.provider,
providerInstanceId,
status: "stopped",
runtimePayload: {
activeTurnId: null,
lastRuntimeEvent: "provider.stopAll",
lastRuntimeEventAt: new Date().toISOString(),
},
});
}).pipe(Effect.asVoid);
yield* analytics.record("provider.sessions.stopped_all", {
sessionCount: threadIds.length,
});
@@ -772,8 +1005,10 @@ const makeProviderService = Effect.fn("makeProviderService")(function* (
});
yield* Effect.addFinalizer(() =>
Effect.catch(runStopAll(), (cause) =>
Effect.logWarning("failed to stop provider service", { cause }),
runStopAll().pipe(
Effect.catchCause((cause) =>
Effect.logWarning("failed to stop provider service", { cause: Cause.pretty(cause) }),
),
),
);
@@ -786,6 +1021,7 @@ const makeProviderService = Effect.fn("makeProviderService")(function* (
stopSession,
listSessions,
getCapabilities,
getInstanceInfo,
rollbackConversation,
// Each access creates a fresh PubSub subscription so that multiple
// consumers (ProviderRuntimeIngestion, CheckpointReactor, etc.) each
@@ -3,7 +3,7 @@ import os from "node:os";
import path from "node:path";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { ThreadId } from "@t3tools/contracts";
import { ProviderDriverKind, ThreadId } from "@t3tools/contracts";
import { it, assert } from "@effect/vitest";
import { assertSome } from "@effect/vitest/utils";
import { Effect, Layer, Option } from "effect";
@@ -38,7 +38,7 @@ it.layer(makeDirectoryLayer(SqlitePersistenceMemory))("ProviderSessionDirectoryL
const initialThreadId = ThreadId.make("thread-1");
yield* directory.upsert({
provider: "codex",
provider: ProviderDriverKind.make("codex"),
threadId: initialThreadId,
});
@@ -47,7 +47,7 @@ it.layer(makeDirectoryLayer(SqlitePersistenceMemory))("ProviderSessionDirectoryL
const resolvedBinding = yield* directory.getBinding(initialThreadId);
assertSome(resolvedBinding, {
threadId: initialThreadId,
provider: "codex",
provider: ProviderDriverKind.make("codex"),
});
if (Option.isSome(resolvedBinding)) {
assert.equal(resolvedBinding.value.threadId, initialThreadId);
@@ -56,7 +56,7 @@ it.layer(makeDirectoryLayer(SqlitePersistenceMemory))("ProviderSessionDirectoryL
const nextThreadId = ThreadId.make("thread-2");
yield* directory.upsert({
provider: "codex",
provider: ProviderDriverKind.make("codex"),
threadId: nextThreadId,
});
const updatedBinding = yield* directory.getBinding(nextThreadId);
@@ -85,7 +85,7 @@ it.layer(makeDirectoryLayer(SqlitePersistenceMemory))("ProviderSessionDirectoryL
const threadId = ThreadId.make("thread-runtime");
yield* directory.upsert({
provider: "codex",
provider: ProviderDriverKind.make("codex"),
threadId,
status: "starting",
resumeCursor: {
@@ -98,7 +98,7 @@ it.layer(makeDirectoryLayer(SqlitePersistenceMemory))("ProviderSessionDirectoryL
});
yield* directory.upsert({
provider: "codex",
provider: ProviderDriverKind.make("codex"),
threadId,
status: "running",
runtimePayload: {
@@ -133,6 +133,7 @@ it.layer(makeDirectoryLayer(SqlitePersistenceMemory))("ProviderSessionDirectoryL
yield* runtimeRepository.upsert({
threadId: newerThreadId,
providerName: "codex",
providerInstanceId: null,
adapterKey: "codex",
runtimeMode: "full-access",
status: "running",
@@ -148,6 +149,7 @@ it.layer(makeDirectoryLayer(SqlitePersistenceMemory))("ProviderSessionDirectoryL
yield* runtimeRepository.upsert({
threadId: olderThreadId,
providerName: "claudeAgent",
providerInstanceId: null,
adapterKey: "claudeAgent",
runtimeMode: "approval-required",
status: "starting",
@@ -165,7 +167,7 @@ it.layer(makeDirectoryLayer(SqlitePersistenceMemory))("ProviderSessionDirectoryL
assert.deepEqual(bindings, [
{
threadId: olderThreadId,
provider: "claudeAgent",
provider: ProviderDriverKind.make("claudeAgent"),
adapterKey: "claudeAgent",
runtimeMode: "approval-required",
status: "starting",
@@ -179,7 +181,7 @@ it.layer(makeDirectoryLayer(SqlitePersistenceMemory))("ProviderSessionDirectoryL
},
{
threadId: newerThreadId,
provider: "codex",
provider: ProviderDriverKind.make("codex"),
adapterKey: "codex",
runtimeMode: "full-access",
status: "running",
@@ -203,6 +205,7 @@ it.layer(makeDirectoryLayer(SqlitePersistenceMemory))("ProviderSessionDirectoryL
yield* runtimeRepository.upsert({
threadId,
providerName: "claudeAgent",
providerInstanceId: null,
adapterKey: "claudeAgent",
runtimeMode: "full-access",
status: "running",
@@ -212,7 +215,7 @@ it.layer(makeDirectoryLayer(SqlitePersistenceMemory))("ProviderSessionDirectoryL
});
yield* directory.upsert({
provider: "codex",
provider: ProviderDriverKind.make("codex"),
threadId,
});
@@ -235,7 +238,7 @@ it.layer(makeDirectoryLayer(SqlitePersistenceMemory))("ProviderSessionDirectoryL
yield* Effect.gen(function* () {
const directory = yield* ProviderSessionDirectory;
yield* directory.upsert({
provider: "codex",
provider: ProviderDriverKind.make("codex"),
threadId,
});
}).pipe(Effect.provide(directoryLayer));
@@ -249,7 +252,7 @@ it.layer(makeDirectoryLayer(SqlitePersistenceMemory))("ProviderSessionDirectoryL
const resolvedBinding = yield* directory.getBinding(threadId);
assertSome(resolvedBinding, {
threadId,
provider: "codex",
provider: ProviderDriverKind.make("codex"),
});
if (Option.isSome(resolvedBinding)) {
assert.equal(resolvedBinding.value.threadId, threadId);
@@ -1,4 +1,4 @@
import { ProviderKind, type ThreadId } from "@t3tools/contracts";
import { defaultInstanceIdForDriver, ProviderDriverKind, type ThreadId } from "@t3tools/contracts";
import { Effect, Layer, Option, Schema } from "effect";
import type { ProviderSessionRuntime } from "../../persistence/Services/ProviderSessionRuntime.ts";
@@ -20,11 +20,11 @@ function toPersistenceError(operation: string) {
});
}
function decodeProviderKind(
function decodeProviderDriverKind(
providerName: string,
operation: string,
): Effect.Effect<ProviderKind, ProviderSessionDirectoryPersistenceError> {
return Schema.decodeUnknownEffect(ProviderKind)(providerName).pipe(
): Effect.Effect<ProviderDriverKind, ProviderSessionDirectoryPersistenceError> {
return Schema.decodeUnknownEffect(ProviderDriverKind)(providerName).pipe(
Effect.mapError(
(cause) =>
new ProviderSessionDirectoryPersistenceError({
@@ -57,12 +57,17 @@ function toRuntimeBinding(
runtime: ProviderSessionRuntime,
operation: string,
): Effect.Effect<ProviderRuntimeBindingWithMetadata, ProviderSessionDirectoryPersistenceError> {
return decodeProviderKind(runtime.providerName, operation).pipe(
return decodeProviderDriverKind(runtime.providerName, operation).pipe(
Effect.map(
(provider) =>
({
threadId: runtime.threadId,
provider,
// Migration boundary only: rows written before the instance split
// have a null provider_instance_id. Promote them as they leave
// persistence so hot routing code never has to infer an instance
// from a driver kind.
providerInstanceId: runtime.providerInstanceId ?? defaultInstanceIdForDriver(provider),
adapterKey: runtime.adapterKey,
runtimeMode: runtime.runtimeMode,
status: runtime.status,
@@ -108,10 +113,19 @@ const makeProviderSessionDirectory = Effect.gen(function* () {
const now = new Date().toISOString();
const providerChanged =
existingRuntime !== undefined && existingRuntime.providerName !== binding.provider;
const providerInstanceId =
binding.providerInstanceId ?? (!providerChanged ? existingRuntime?.providerInstanceId : null);
if (providerInstanceId === null || providerInstanceId === undefined) {
return yield* new ProviderValidationError({
operation: "ProviderSessionDirectory.upsert",
issue: "providerInstanceId is required for provider session runtime bindings.",
});
}
yield* repository
.upsert({
threadId: resolvedThreadId,
providerName: binding.provider,
providerInstanceId,
adapterKey:
binding.adapterKey ??
(providerChanged ? binding.provider : (existingRuntime?.adapterKey ?? binding.provider)),
@@ -1,5 +1,11 @@
import * as NodeServices from "@effect/platform-node/NodeServices";
import { ProjectId, ThreadId, TurnId } from "@t3tools/contracts";
import {
ProjectId,
ThreadId,
TurnId,
ProviderDriverKind,
ProviderInstanceId,
} from "@t3tools/contracts";
import { Effect, Exit, Layer, ManagedRuntime, Option, Scope, Stream } from "effect";
import { afterEach, describe, expect, it, vi } from "vitest";
@@ -17,7 +23,7 @@ import { ProviderSessionDirectoryLive } from "./ProviderSessionDirectory.ts";
import { makeProviderSessionReaperLive } from "./ProviderSessionReaper.ts";
const defaultModelSelection = {
provider: "codex",
instanceId: ProviderInstanceId.make("codex"),
model: "gpt-5-codex",
} as const;
@@ -140,6 +146,19 @@ describe("ProviderSessionReaper", () => {
stopSession,
listSessions: () => Effect.succeed([]),
getCapabilities: () => Effect.succeed({ sessionModelSwitch: "in-session" }),
getInstanceInfo: (instanceId) => {
const driverKind = ProviderDriverKind.make(String(instanceId));
return Effect.succeed({
instanceId,
driverKind,
displayName: undefined,
enabled: true,
continuationIdentity: {
driverKind,
continuationKey: `${driverKind}:instance:${instanceId}`,
},
});
},
rollbackConversation: () => unsupported(),
streamEvents: Stream.empty,
};
@@ -197,6 +216,7 @@ describe("ProviderSessionReaper", () => {
repository.upsert({
threadId,
providerName: "claudeAgent",
providerInstanceId: null,
adapterKey: "claudeAgent",
runtimeMode: "full-access",
status: "running",
@@ -244,6 +264,7 @@ describe("ProviderSessionReaper", () => {
repository.upsert({
threadId,
providerName: "claudeAgent",
providerInstanceId: null,
adapterKey: "claudeAgent",
runtimeMode: "full-access",
status: "running",
@@ -290,6 +311,7 @@ describe("ProviderSessionReaper", () => {
repository.upsert({
threadId,
providerName: "claudeAgent",
providerInstanceId: null,
adapterKey: "claudeAgent",
runtimeMode: "full-access",
status: "running",
@@ -336,6 +358,7 @@ describe("ProviderSessionReaper", () => {
repository.upsert({
threadId,
providerName: "claudeAgent",
providerInstanceId: null,
adapterKey: "claudeAgent",
runtimeMode: "full-access",
status: "stopped",
@@ -404,6 +427,7 @@ describe("ProviderSessionReaper", () => {
repository.upsert({
threadId: failedThreadId,
providerName: "claudeAgent",
providerInstanceId: null,
adapterKey: "claudeAgent",
runtimeMode: "full-access",
status: "running",
@@ -418,6 +442,7 @@ describe("ProviderSessionReaper", () => {
repository.upsert({
threadId: reapedThreadId,
providerName: "codex",
providerInstanceId: null,
adapterKey: "codex",
runtimeMode: "full-access",
status: "running",
@@ -483,6 +508,7 @@ describe("ProviderSessionReaper", () => {
repository.upsert({
threadId: defectThreadId,
providerName: "claudeAgent",
providerInstanceId: null,
adapterKey: "claudeAgent",
runtimeMode: "full-access",
status: "running",
@@ -497,6 +523,7 @@ describe("ProviderSessionReaper", () => {
repository.upsert({
threadId: reapedThreadId,
providerName: "codex",
providerInstanceId: null,
adapterKey: "codex",
runtimeMode: "full-access",
status: "running",
@@ -0,0 +1,94 @@
import { it } from "@effect/vitest";
import { Cause, Effect, Exit } from "effect";
import { describe, expect } from "vitest";
import { scopedSafeTeardown } from "./scopedSafeTeardown.ts";
describe("scopedSafeTeardown", () => {
it.effect("returns the body's value when teardown is clean", () =>
Effect.gen(function* () {
const finalizers: string[] = [];
const wrapped = Effect.gen(function* () {
yield* Effect.addFinalizer(() =>
Effect.sync(() => {
finalizers.push("clean");
}),
);
return "body-ok";
}).pipe(scopedSafeTeardown("test"));
const value = yield* wrapped;
expect(value).toBe("body-ok");
expect(finalizers).toEqual(["clean"]);
}),
);
it.effect("preserves body success when a finalizer dies", () =>
// The production failure mode: `Layer.build(...)` registers a finalizer
// that kills a subprocess; if the kill fails, the defect would otherwise
// override a successful probe body.
Effect.gen(function* () {
const finalizers: string[] = [];
const wrapped = Effect.gen(function* () {
yield* Effect.addFinalizer(() =>
Effect.sync(() => {
finalizers.push("ran-before-die");
}),
);
yield* Effect.addFinalizer(() =>
Effect.die(new Error("simulated subprocess kill failure")),
);
return "body-ok";
}).pipe(scopedSafeTeardown("test"));
const value = yield* wrapped;
expect(value).toBe("body-ok");
// The clean finalizer still ran; teardown defect was logged + swallowed.
expect(finalizers).toEqual(["ran-before-die"]);
}),
);
it.effect("preserves typed body failures even when teardown is clean", () =>
Effect.gen(function* () {
class BodyError {
readonly _tag = "BodyError" as const;
}
const wrapped = Effect.gen(function* () {
yield* Effect.addFinalizer(() => Effect.void);
return yield* Effect.fail(new BodyError());
}).pipe(scopedSafeTeardown("test"));
const exit = yield* Effect.exit(wrapped);
expect(Exit.isFailure(exit)).toBe(true);
if (Exit.isFailure(exit)) {
// Body's typed failure should surface, not a defect.
const squashed = Cause.squash(exit.cause);
expect(squashed).toBeInstanceOf(BodyError);
}
}),
);
it.effect("prefers the body's typed failure over a teardown defect", () =>
// Even when both the body fails AND teardown defects, the body's typed
// failure is what callers see. This matters because `Effect.result` /
// `.pipe(Effect.exit)` in callers expects a typed Failure, not a Die.
Effect.gen(function* () {
class BodyError {
readonly _tag = "BodyError" as const;
}
const wrapped = Effect.gen(function* () {
yield* Effect.addFinalizer(() =>
Effect.die(new Error("simulated subprocess kill failure")),
);
return yield* Effect.fail(new BodyError());
}).pipe(scopedSafeTeardown("test"));
const exit = yield* Effect.exit(wrapped);
expect(Exit.isFailure(exit)).toBe(true);
if (Exit.isFailure(exit)) {
const squashed = Cause.squash(exit.cause);
expect(squashed).toBeInstanceOf(BodyError);
}
}),
);
});
@@ -0,0 +1,61 @@
/**
* scopedSafeTeardown — run a scope-requiring effect so that finalizer
* failures during scope close cannot override the body's Exit.
*
* Motivation
* ----------
* The obvious pattern is `body.pipe(Effect.scoped)`: provide a fresh
* Scope, run the body, close the scope with the body's Exit. If a
* finalizer (e.g. `ChildProcess.kill` from an effect-codex-app-server
* spawn) dies during that close, the combined Exit becomes the
* finalizer's defect — even when the body already succeeded.
*
* Concretely this bit us in the Codex provider probe: a successful
* `initialize` → `account/read` → `skills/list` → `model/list`
* round-trip produced a `CodexAppServerProviderSnapshot`, but the
* `Layer.build(CodexClient.layerCommand(...))` finalizer then failed to
* kill the `codex app-server` subprocess with a `PlatformError`. The
* defect bubbled past `Effect.result` in `checkCodexProviderStatus`,
* died `refreshOneSource`, and `providersRef` never saw the snapshot.
*
* Strategy
* --------
* 1. Make a fresh scope manually.
* 2. Run the body against that scope, capturing its Exit via
* `Effect.exit`.
* 3. Close the scope, catching any cause (typed failure *or* defect)
* with a log.
* 4. Replay the captured Exit so typed body failures still surface and
* successes still return their value.
*
* The helper deliberately logs teardown causes at `Warning` level —
* silently swallowing them is dangerous because they usually indicate a
* real bug in a downstream Layer's finalizer.
*
* @module provider/Layers/scopedSafeTeardown
*/
import { Effect, Exit, Scope } from "effect";
/**
* Run `effect` with a freshly made `Scope.Scope`, guaranteeing that
* teardown failures cannot override the body's Exit.
*
* Shape matches `Effect.scoped`: takes an effect whose env includes
* `Scope.Scope`, returns one whose env excludes it.
*
* @param label Short label for the warning log emitted when teardown
* fails. Use something like `"codex-probe"`.
*/
export const scopedSafeTeardown =
(label: string) =>
<A, E, R>(effect: Effect.Effect<A, E, R>): Effect.Effect<A, E, Exclude<R, Scope.Scope>> =>
Effect.gen(function* () {
const scope = yield* Scope.make();
const bodyExit = yield* effect.pipe(Effect.provideService(Scope.Scope, scope), Effect.exit);
yield* Scope.close(scope, Exit.void).pipe(
Effect.catchCause((cause) =>
Effect.logWarning(`${label} teardown errored; preserving body result`, cause),
),
);
return yield* bodyExit;
}) as Effect.Effect<A, E, Exclude<R, Scope.Scope>>;
+167
View File
@@ -0,0 +1,167 @@
/**
* ProviderDriver / ProviderInstance — driver SPI as plain values.
*
* `ProviderDriver` is a record, not a Context.Service. The thing it produces
* (`ProviderInstance`) is also a record — three captured closures
* (`snapshot`, `adapter`, `textGeneration`), an id, and a driver kind. There
* are intentionally no per-driver Context tags because tags are
* singleton-per-runtime and we need many instances of the same driver.
*
* The only Effect service involved is `ProviderInstanceRegistry`, which
* owns the live `Map<InstanceId, ProviderInstance>` and is itself a
* singleton.
*
* Driver factories are functions of `(typed config, env)` where:
* - `typed config` is decoded once by the registry via `configSchema`,
* so drivers never deal with raw `unknown`.
* - `env` flows through Effect's R channel. Each driver declares the
* subset of infrastructure services it needs (FileSystem,
* ChildProcessSpawner, …) on its `create` return type; the registry
* layer's R is the union of those, and the runtime layer satisfies it.
*
* @module provider/ProviderDriver
*/
import type {
ProviderDriverKind,
ProviderInstanceEnvironment,
ProviderInstanceId,
} from "@t3tools/contracts";
import type { Effect, Schema, Scope } from "effect";
import type { TextGenerationShape } from "../textGeneration/TextGeneration.ts";
import type { ProviderAdapterError, ProviderDriverError } from "./Errors.ts";
import type { ProviderAdapterShape } from "./Services/ProviderAdapter.ts";
import type { ServerProviderShape } from "./Services/ServerProvider.ts";
/**
* Static metadata advertised by a driver. Used for default presentation
* and (later) settings UI. Doesn't need to be Effect-typed because nothing
* about it is dynamic — drivers are registered at startup.
*/
export interface ProviderDriverMetadata {
/** Human-readable name for the driver itself (e.g. "Codex"). */
readonly displayName: string;
/**
* Whether the driver may be instantiated more than once concurrently.
* Defaults to `true`. Set to `false` for drivers that wrap a global
* resource (e.g. a single desktop app socket) — the registry then
* rejects multi-instance configurations with a clear error.
*/
readonly supportsMultipleInstances?: boolean;
}
/**
* One materialized provider instance. Held by the registry, looked up by
* `instanceId`, torn down by closing the scope it was created in.
*
* The three "shape" fields are captured closures owned by this instance —
* stopping one instance cannot affect another, and starting a second
* instance of the same driver does not reach into the first instance's
* state.
*/
export interface ProviderInstance {
readonly instanceId: ProviderInstanceId;
readonly driverKind: ProviderDriverKind;
readonly continuationIdentity: ProviderContinuationIdentity;
readonly displayName: string | undefined;
readonly accentColor?: string | undefined;
readonly enabled: boolean;
readonly snapshot: ServerProviderShape;
readonly adapter: ProviderAdapterShape<ProviderAdapterError>;
readonly textGeneration: TextGenerationShape;
}
export interface ProviderContinuationIdentity {
readonly driverKind: ProviderDriverKind;
readonly continuationKey: string;
}
export function defaultProviderContinuationIdentity(input: {
readonly driverKind: ProviderDriverKind;
readonly instanceId: ProviderInstanceId;
}): ProviderContinuationIdentity {
return {
driverKind: input.driverKind,
continuationKey: `${input.driverKind}:instance:${input.instanceId}`,
};
}
/**
* Inputs the registry passes to a driver's `create` function.
*
* `config` is the typed payload — already decoded by the registry through
* `driver.configSchema`. Drivers never decode their own raw envelope.
*/
export interface ProviderDriverCreateInput<Config> {
readonly instanceId: ProviderInstanceId;
readonly displayName: string | undefined;
readonly accentColor?: string | undefined;
readonly environment: ProviderInstanceEnvironment;
readonly enabled: boolean;
readonly config: Config;
}
/**
* Driver SPI — registered as a plain value, not a Layer.
*
* `Config` is whatever the driver decoded from
* `ProviderInstanceConfig.config`. `R` is the union of infrastructure
* services the driver depends on; the registry layer aggregates `R` across
* all registered drivers and the runtime supplies them.
*
* `create` is responsible for *all* per-instance state — process handles,
* pubsub topics, refs, file watchers — and must release them when its
* scope closes. Two calls to `create` with different `instanceId` /
* `config` MUST yield instances with no shared mutable state.
*/
export interface ProviderDriver<Config, R = never> {
readonly driverKind: ProviderDriverKind;
readonly metadata: ProviderDriverMetadata;
/**
* Decoder for the opaque `ProviderInstanceConfig.config` envelope. The
* registry runs this exactly once per (re)load of an instance; a decode
* failure is surfaced as `ProviderDriverError` and downgraded to an
* unavailable shadow snapshot.
*
* The `Encoded` parameter is intentionally left as `unknown` (not
* `Config`) so schemas with `withDecodingDefault` / transformations — where
* the encoded shape differs from the decoded shape — satisfy the SPI
* without casts. The registry only ever decodes `unknown` envelopes here,
* so the precise encoded type is irrelevant at this boundary.
*
* Using `Codec` rather than `Schema` pins `DecodingServices = never` — if
* we used `Schema<Config>`, the erased `any` in `AnyProviderDriver` would
* widen `DecodingServices` to `unknown` and poison the R channel of every
* caller of `decodeUnknownEffect`.
*/
readonly configSchema: Schema.Codec<Config, unknown>;
/**
* Default config payload used when the legacy
* `ServerSettings.providers.<kind>` entry is empty or when the driver
* is auto-bootstrapped without user configuration. Returning a typed
* default keeps the migration path simple — no special-casing needed
* to construct a "blank" instance.
*/
readonly defaultConfig: () => Config;
/**
* Materialize one instance. The returned effect runs in a scope owned
* by the registry; closing that scope releases every resource the
* driver opened. Failures become unavailable shadow snapshots — the
* driver MUST NOT throw defects.
*/
readonly create: (
input: ProviderDriverCreateInput<Config>,
) => Effect.Effect<ProviderInstance, ProviderDriverError, R | Scope.Scope>;
}
/**
* Heterogeneous-array convenience: the registry stores drivers as
* `ReadonlyArray<AnyProviderDriver<R>>` where `R` is the union of all
* registered drivers' env requirements.
*/
// `any` here intentionally erases the per-driver Config; the registry
// already decoded it before invoking `create`, so downstream code never
// needs the original `Config` type. Using `unknown` instead would force
// `create` callers into casts since `unknown` is not assignable to a
// concrete `Config` from inside the driver body.
export type AnyProviderDriver<R = never> = ProviderDriver<any, R>;
@@ -0,0 +1,21 @@
import { describe, expect, it } from "vitest";
import { mergeProviderInstanceEnvironment } from "./ProviderInstanceEnvironment.ts";
describe("mergeProviderInstanceEnvironment", () => {
it("overrides inherited environment values and preserves empty strings", () => {
expect(
mergeProviderInstanceEnvironment(
[
{ name: "OPENROUTER_API_KEY", value: "sk-or-test", sensitive: true },
{ name: "ANTHROPIC_API_KEY", value: "", sensitive: false },
],
{ ANTHROPIC_API_KEY: "inherited", PATH: "/bin" },
),
).toMatchObject({
OPENROUTER_API_KEY: "sk-or-test",
ANTHROPIC_API_KEY: "",
PATH: "/bin",
});
});
});
@@ -0,0 +1,16 @@
import type { ProviderInstanceEnvironment } from "@t3tools/contracts";
export function mergeProviderInstanceEnvironment(
environment: ProviderInstanceEnvironment | undefined,
baseEnv: NodeJS.ProcessEnv = process.env,
): NodeJS.ProcessEnv {
if (!environment || environment.length === 0) {
return baseEnv;
}
const next: NodeJS.ProcessEnv = { ...baseEnv };
for (const variable of environment) {
next[variable.name] = variable.value;
}
return next;
}
Loaded 100 of 327 files, more files were not shown because too many files have changed in this diff. Show more