Compare commits

...
Author SHA1 Message Date
Cursor Agent 02cac6dd61 fix: use Effect.flatMap for decodeJjCurrentChange to route errors to typed channel
decodeJjCurrentChange was throwing VcsOutputDecodeError inside Effect.map,
which causes the error to become an unrecoverable defect rather than a typed
error in the VcsError channel. Changed the function to return an Effect and
use Effect.flatMap at the call site so errors properly land in the typed
error channel as the type signature promises.
2026-05-02 16:47:03 +00:00
Julius Marminge e2e40c24f1 Add typed jj extension surface 2026-05-02 09:34:41 -07:00
Julius Marminge ab974c882a Prefer jj detection and add ignore classifier capability
- Detect jj before git for colocated repositories
- Add ignoreClassifier to VCS capabilities
- Fix trace2 hook exit code reporting
2026-05-02 09:34:41 -07:00
Julius Marminge 29aa1ccaf8 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 09:34:41 -07:00
Julius Marminge c31becadc7 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 09:34:41 -07:00
Julius Marminge 128b432bee Add generic source control provider routing core 2026-05-02 09:33:55 -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
8d1d699f88 Refactor provider model selections to option arrays (#2246)
Co-authored-by: Cursor Agent <[email protected]>
Co-authored-by: cursor[bot] <206951365+cursor[bot]@users.noreply.github.com>
Co-authored-by: codex <[email protected]>
2026-04-23 09:35:40 -04:00
Raul Pereira da Silvaandmacroscopeapp[bot] b0b7b38da1 fix(server): detect localized Windows command errors (#2152)
Co-authored-by: macroscopeapp[bot] <170038800+macroscopeapp[bot]@users.noreply.github.com>
2026-04-23 04:42:19 +00:00
Bas Milius fd3b96b487 Add IntelliJ project icon to the list of possible favicon paths (#1651) 2026-04-23 04:40:27 +00:00
Hauke Schnau aa2d385a62 fix(server): restore CODEX_HOME tilde expansion for Codex launches (#2255) 2026-04-23 00:37:58 -04:00
e25db3a572 Fix provider cache atomic write temp path collisions (#2291)
Co-authored-by: Cursor Agent <[email protected]>
Co-authored-by: Julius Marminge <[email protected]>
2026-04-23 00:33:16 -04:00
Heinz-GandHeinz Gericke b8305afa29 fix: increase Claude auth probe timeout to 10s (#2272)
Co-authored-by: Heinz Gericke <[email protected]>
2026-04-22 01:04:50 +00:00
Julius MarmingeandCursor Agent b7c89cf496 Refresh Codex protocol bindings to be75785504ff152fa6333e380a2d50642f42fba0 (#2276)
Co-authored-by: Cursor Agent <[email protected]>
2026-04-21 15:30:54 -07:00
NoxireandJulius Marminge 3a1daa87ac Add close buttons to toasts (#2023)
Co-authored-by: Julius Marminge <[email protected]>
2026-04-21 08:32:08 -07:00
Mike Olson 055897f0ea fix: enforce opencode >= 1.14.19 and reveal window on Wayland (#2262) 2026-04-21 08:15:41 -07:00
Adin Schmidt 40b3a80034 fix(server): trim OpenCode provider model names (#2252) 2026-04-21 02:45:56 +00:00
Adam Mansfield f6978db605 chore(turbo): pass through PATHEXT (#2184) 2026-04-19 23:35:37 -07:00
Mike Olson de05b0c94e fix(web): restore manual sort drag and keep per-group expand state (#2221) 2026-04-19 23:29:56 -07:00
CraigandJulius Marminge 6d1505c9fb fix: Change right panel sheet to be below title bar / action bar (#2224)
Co-authored-by: Julius Marminge <[email protected]>
2026-04-19 23:25:39 -07:00
Julius MarmingeandClaude Opus 4.7 306ec4bb84 Refactor OpenCode lifecycle and structured output handling (#2218)
Co-authored-by: Claude Opus 4.7 <[email protected]>
2026-04-19 22:56:44 -07:00
Julius Marmingeandcodex 3b98fe3548 effect-codex-app-server (#1942)
Co-authored-by: codex <[email protected]>
2026-04-19 21:46:40 -07:00
Ellie GummereandJulius Marminge 66c326b8c4 Redesign model picker with favorites and search (#2153)
Co-authored-by: Julius Marminge <[email protected]>
2026-04-19 17:43:40 -07:00
8dbcf92a0d fix(server): prevent probeClaudeCapabilities from wasting API requests (#2192)
Co-authored-by: Claude Opus 4.6 <[email protected]>
Co-authored-by: Julius Marminge <[email protected]>
2026-04-20 00:13:20 +00:00
Abdul Azeez 37965da01d fix(server): handle OpenCode text response format in commit message g… (#2202) 2026-04-20 00:12:35 +00:00
Kyle Gottfried 57b59b5bf2 Devcontainer / IDE updates (#2208) 2026-04-19 17:07:12 -07:00
20f346d8ef Expand leading ~ in Codex home paths before exporting CODEX_HOME (#2210)
Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
Co-authored-by: = <=>
2026-04-20 00:06:19 +00:00
Efe Baran Durmaz c83bc5d48a fix(release): use v<semver> tag format for nightly releases (#2186) 2026-04-19 10:58:04 -07:00
Julius Marminge 9df3c64021 Use GitHub App token for release uploads (#2149) 2026-04-17 16:52:56 -07:00
Julius Marminge 8ac57f7944 Guard release workflow jobs on upstream success (#2147) 2026-04-17 16:40:43 -07:00
Julius Marminge 29cb917ac4 Guard release workflow jobs from upstream failures (#2146) 2026-04-17 16:34:19 -07:00
9c64f12ea0 Add ACP support with Cursor provider (#1355)
Co-authored-by: codex <[email protected]>
Co-authored-by: Julius Marminge <[email protected]>
Co-authored-by: Cursor Agent <[email protected]>
Co-authored-by: cursor[bot] <206951365+cursor[bot]@users.noreply.github.com>
2026-04-17 16:21:31 -07:00
Matt Van HornandMatt Van Horn 0f184c28b0 fix(web): use capture-phase keydown listener so CTRL+J toggles terminal from terminal focus on Windows (#2113) (#2142)
Co-authored-by: Matt Van Horn <[email protected]>
2026-04-17 23:07:04 +00:00
Julius Marminge a3b1df5224 Add Claude Opus 4.5 to built-in Claude models (#2143) 2026-04-17 16:02:41 -07:00
4e0c003e78 fix(web): allow deleting non-empty projects from the warning toast (#1264)
Co-authored-by: Julius Marminge <[email protected]>
Co-authored-by: codex <[email protected]>
2026-04-17 15:05:56 -07:00
Utkarsh Patil 60387f67e9 fix: show restore defaults only on General settings (#1710) 2026-04-17 13:49:18 -07:00
ce94feeea1 feat: add opencode provider support (#1758)
Co-authored-by: Julius Marminge <[email protected]>
Co-authored-by: codex <[email protected]>
Co-authored-by: Claude Opus 4.6 <[email protected]>
2026-04-17 13:31:41 -07:00
Ariaj 39ca3ee858 fix(web): bypass xterm for global terminal shortcuts (#1580) 2026-04-17 13:11:04 -07:00
Julius Marminge 52a6067802 Throttle nightly release workflow to every 3 hours (#2134) 2026-04-17 11:39:20 -07:00
721b6b4c6f Preserve provider bindings when stopping sessions (#2125)
Co-authored-by: Julius Marminge <[email protected]>
Co-authored-by: codex <[email protected]>
2026-04-17 11:27:12 -07:00
Julius Marminge 40009735ee Extract backend startup readiness coordination (#2133) 2026-04-17 11:09:26 -07:00
df9d34004f Modernize release workflow runners (#2129)
Co-authored-by: codex <[email protected]>
Co-authored-by: Cursor Agent <[email protected]>
2026-04-17 16:23:02 +00:00
444 changed files with 104396 additions and 18832 deletions

No files matched your search

+1
View File
@@ -0,0 +1 @@
plans/
+11 -4
View File
@@ -2,15 +2,22 @@
"name": "T3 Code Dev",
"image": "debian:bookworm",
"features": {
"ghcr.io/devcontainers-extra/features/bun:1": {},
"ghcr.io/devcontainers/features/git:1": {},
"ghcr.io/devcontainers-extra/features/bun:1": {
"version": "1.3.11"
},
"ghcr.io/devcontainers/features/node:1": {
"version": "24",
"nodeGypDependencies": true
"version": "24.13.1"
},
"ghcr.io/devcontainers/features/python:1": {
"version": "3.12"
"version": "3.10",
"installTools": false
}
},
"overrideFeatureInstallOrder": [
"ghcr.io/devcontainers/features/git",
"ghcr.io/devcontainers-extra/features/bun"
],
"postCreateCommand": {
"bun-install": "bun install --backend=copyfile --frozen-lockfile"
},
+3
View File
@@ -30,3 +30,6 @@ github:Yash-Singh1
github:eggfriedrice24
github:Ymit24
github:shivamhwp
github:jappyjan
github:justsomelegs
github:UtkarshUsername
+143 -7
View File
@@ -4,8 +4,9 @@ on:
push:
tags:
- "v*.*.*"
- "!v*-nightly.*"
schedule:
- cron: "0 9 * * *"
- cron: "0 */3 * * *"
workflow_dispatch:
inputs:
channel:
@@ -26,8 +27,45 @@ permissions:
id-token: write
jobs:
check_changes:
name: Check for changes since last nightly
if: github.event_name == 'schedule'
runs-on: blacksmith-8vcpu-ubuntu-2404
outputs:
has_changes: ${{ steps.check.outputs.has_changes }}
steps:
- name: Checkout
uses: actions/checkout@v6
with:
fetch-depth: 0
- id: check
name: Compare HEAD to last nightly tag
run: |
last_nightly_tag=$(git tag --list 'v*-nightly.*' 'nightly-v*' --sort=-creatordate | head -n 1)
if [[ -z "$last_nightly_tag" ]]; then
echo "No previous nightly tag found. Proceeding with release."
echo "has_changes=true" >> "$GITHUB_OUTPUT"
exit 0
fi
last_nightly_sha=$(git rev-parse "$last_nightly_tag^{commit}")
head_sha=$(git rev-parse HEAD)
if [[ "$last_nightly_sha" == "$head_sha" ]]; then
echo "No changes on main since last nightly release ($last_nightly_tag). Skipping."
echo "has_changes=false" >> "$GITHUB_OUTPUT"
else
echo "Changes detected on main since $last_nightly_tag ($last_nightly_sha → $head_sha). Proceeding."
echo "has_changes=true" >> "$GITHUB_OUTPUT"
fi
preflight:
name: Preflight
needs: [check_changes]
if: |
!failure() && !cancelled() &&
(github.event_name != 'schedule' || needs.check_changes.outputs.has_changes == 'true')
runs-on: blacksmith-8vcpu-ubuntu-2404
timeout-minutes: 10
outputs:
@@ -134,6 +172,7 @@ jobs:
build:
name: Build ${{ matrix.label }}
needs: preflight
if: ${{ !failure() && !cancelled() && needs.preflight.result == 'success' }}
runs-on: ${{ matrix.runner }}
timeout-minutes: 30
strategy:
@@ -156,7 +195,7 @@ jobs:
target: AppImage
arch: x64
- label: Windows x64
runner: windows-2022 # blacksmith-32vcpu-windows-2025
runner: blacksmith-32vcpu-windows-2025
platform: win
target: nsis
arch: x64
@@ -188,6 +227,23 @@ jobs:
- name: Align package versions to release version
run: node scripts/update-release-package-versions.ts "${{ needs.preflight.outputs.version }}"
- name: Install Spectre-mitigated MSVC libs
if: matrix.platform == 'win'
shell: pwsh
run: |
$vswhere = "${env:ProgramFiles(x86)}\Microsoft Visual Studio\Installer\vswhere.exe"
$installPath = & $vswhere -products * -latest -property installationPath
$setupExe = "${env:ProgramFiles(x86)}\Microsoft Visual Studio\Installer\setup.exe"
$proc = Start-Process -FilePath $setupExe `
-ArgumentList "modify", "--installPath", "`"$installPath`"", "--add", `
"Microsoft.VisualStudio.Component.VC.Tools.x86.x64.Spectre", "--quiet", "--norestart" `
-Wait -PassThru -NoNewWindow
if ($null -eq $proc -or $proc.ExitCode -ne 0) {
$code = if ($null -ne $proc) { $proc.ExitCode } else { 1 }
Write-Error "Visual Studio Installer failed with exit code $code"
exit $code
}
- name: Build desktop artifact
shell: bash
env:
@@ -299,6 +355,7 @@ jobs:
publish_cli:
name: Publish CLI to npm
needs: [preflight, build]
if: ${{ !failure() && !cancelled() && needs.preflight.result == 'success' && needs.build.result == 'success' }}
runs-on: ubuntu-24.04 # blacksmith-8vcpu-ubuntu-2404
timeout-minutes: 10
steps:
@@ -319,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
@@ -333,19 +393,36 @@ jobs:
release:
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: blacksmith-8vcpu-ubuntu-2404
timeout-minutes: 10
steps:
- id: app_token
name: Mint release app token
uses: actions/create-github-app-token@v2
with:
app-id: ${{ secrets.RELEASE_APP_ID }}
private-key: ${{ secrets.RELEASE_APP_PRIVATE_KEY }}
owner: ${{ github.repository_owner }}
- 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: Download all desktop artifacts
uses: actions/download-artifact@v8
with:
@@ -412,6 +489,7 @@ jobs:
release-assets/*.blockmap
release-assets/*.yml
fail_on_unmatched_files: true
token: ${{ steps.app_token.outputs.token }}
- name: Publish first release
if: needs.preflight.outputs.previous_tag == ''
@@ -431,10 +509,11 @@ jobs:
release-assets/*.blockmap
release-assets/*.yml
fail_on_unmatched_files: true
token: ${{ steps.app_token.outputs.token }}
finalize:
name: Finalize release
if: needs.preflight.outputs.release_channel == 'stable'
if: ${{ !failure() && !cancelled() && needs.preflight.result == 'success' && needs.release.result == 'success' && needs.preflight.outputs.release_channel == 'stable' }}
needs: [preflight, release]
runs-on: blacksmith-8vcpu-ubuntu-2404
timeout-minutes: 10
@@ -476,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
@@ -486,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'
@@ -509,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 }}"
+9 -1
View File
@@ -13,5 +13,13 @@
"apps/web/src/lib/vendor/qrcodegen.ts",
"*.icon/**"
],
"sortPackageJson": {}
"sortPackageJson": {},
"overrides": [
{
"files": [".devcontainer/devcontainer.json"],
"options": {
"trailingComma": "none"
}
}
]
}
@@ -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`
+1 -1
View File
@@ -5,5 +5,5 @@
"source.fixAll.oxc": "always"
},
"oxc.unusedDisableDirectives": "warn",
"typescript.tsdk": "node_modules/typescript/lib"
"js/ts.tsdk.path": "node_modules/typescript/lib"
}
+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
+3 -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,13 +16,14 @@
},
"dependencies": {
"effect": "catalog:",
"electron": "40.6.0",
"electron": "40.9.3",
"electron-updater": "^6.6.2"
},
"devDependencies": {
"@t3tools/contracts": "workspace:*",
"@t3tools/shared": "workspace:*",
"@types/node": "catalog:",
"effect-acp": "workspace:*",
"tsdown": "catalog:",
"typescript": "catalog:",
"vitest": "catalog:"
@@ -0,0 +1,58 @@
import { describe, expect, it, vi } from "vitest";
import { BackendReadinessAbortedError } from "./backendReadiness.ts";
import { waitForBackendStartupReady } from "./backendStartupReadiness.ts";
describe("waitForBackendStartupReady", () => {
it("falls back to the HTTP probe when no listening signal exists", async () => {
const waitForHttpReady = vi.fn<() => Promise<void>>().mockResolvedValue(undefined);
const cancelHttpWait = vi.fn();
await expect(
waitForBackendStartupReady({
waitForHttpReady,
cancelHttpWait,
}),
).resolves.toBe("http");
expect(waitForHttpReady).toHaveBeenCalledTimes(1);
expect(cancelHttpWait).not.toHaveBeenCalled();
});
it("uses the listening signal and cancels the HTTP probe", async () => {
let rejectHttpWait: ((error: unknown) => void) | null = null;
const waitForHttpReady = vi.fn(
() =>
new Promise<void>((_resolve, reject) => {
rejectHttpWait = reject;
}),
);
const cancelHttpWait = vi.fn(() => {
rejectHttpWait?.(new BackendReadinessAbortedError());
});
await expect(
waitForBackendStartupReady({
listeningPromise: Promise.resolve(),
waitForHttpReady,
cancelHttpWait,
}),
).resolves.toBe("listening");
expect(waitForHttpReady).toHaveBeenCalledTimes(1);
expect(cancelHttpWait).toHaveBeenCalledTimes(1);
});
it("rejects when the listening signal fails before HTTP readiness", async () => {
const error = new Error("backend exited");
const waitForHttpReady = vi.fn(() => new Promise<void>(() => {}));
await expect(
waitForBackendStartupReady({
listeningPromise: Promise.reject(error),
waitForHttpReady,
cancelHttpWait: vi.fn(),
}),
).rejects.toBe(error);
});
});
@@ -0,0 +1,56 @@
import { isBackendReadinessAborted } from "./backendReadiness.ts";
export interface WaitForBackendStartupReadyOptions {
readonly listeningPromise?: Promise<void> | null;
readonly waitForHttpReady: () => Promise<void>;
readonly cancelHttpWait: () => void;
}
export async function waitForBackendStartupReady(
options: WaitForBackendStartupReadyOptions,
): Promise<"listening" | "http"> {
const httpReadyPromise = options.waitForHttpReady();
const listeningPromise = options.listeningPromise;
if (!listeningPromise) {
await httpReadyPromise;
return "http";
}
return await new Promise<"listening" | "http">((resolve, reject) => {
let settled = false;
const settleResolve = (source: "listening" | "http") => {
if (settled) {
return;
}
settled = true;
if (source === "listening") {
options.cancelHttpWait();
}
resolve(source);
};
const settleReject = (error: unknown) => {
if (settled) {
return;
}
settled = true;
reject(error);
};
listeningPromise.then(
() => settleResolve("listening"),
(error) => settleReject(error),
);
httpReadyPromise.then(
() => settleResolve("http"),
(error) => {
if (settled && isBackendReadinessAborted(error)) {
return;
}
settleReject(error);
},
);
});
}
@@ -49,9 +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",
+23 -58
View File
@@ -57,6 +57,7 @@ import { isBackendReadinessAborted, waitForHttpReady } from "./backendReadiness.
import { showDesktopConfirmDialog } from "./confirmDialog.ts";
import { resolveDesktopServerExposure } from "./serverExposure.ts";
import { syncShellEnvironment } from "./syncShellEnvironment.ts";
import { waitForBackendStartupReady } from "./backendStartupReadiness.ts";
import { getAutoUpdateDisabledReason, shouldBroadcastDownloadProgress } from "./updateState.ts";
import { doesVersionMatchDesktopUpdateChannel } from "./updateChannels.ts";
import { ServerListeningDetector } from "./serverListeningDetector.ts";
@@ -74,6 +75,7 @@ import {
} from "./updateMachine.ts";
import { isArm64HostRunningIntelBuild, resolveDesktopRuntimeInfo } from "./runtimeArch.ts";
import { resolveDesktopAppBranding } from "./appBranding.ts";
import { bindFirstRevealTrigger, type RevealSubscription } from "./windowReveal.ts";
syncShellEnvironment();
@@ -459,51 +461,13 @@ function cancelBackendReadinessWait(): void {
}
async function waitForBackendWindowReady(baseUrl: string): Promise<"listening" | "http"> {
const httpReadyPromise = waitForBackendHttpReady(baseUrl, {
timeoutMs: 60_000,
});
const listeningPromise = backendListeningDetector?.promise;
if (!listeningPromise) {
await httpReadyPromise;
return "http";
}
return await new Promise<"listening" | "http">((resolve, reject) => {
let settled = false;
const settleResolve = (source: "listening" | "http") => {
if (settled) {
return;
}
settled = true;
if (source === "listening") {
cancelBackendReadinessWait();
}
resolve(source);
};
const settleReject = (error: unknown) => {
if (settled) {
return;
}
settled = true;
reject(error);
};
listeningPromise.then(
() => settleResolve("listening"),
(error) => settleReject(error),
);
httpReadyPromise.then(
() => settleResolve("http"),
(error) => {
if (settled && isBackendReadinessAborted(error)) {
return;
}
settleReject(error);
},
);
return await waitForBackendStartupReady({
listeningPromise: backendListeningDetector?.promise ?? null,
waitForHttpReady: () =>
waitForBackendHttpReady(baseUrl, {
timeoutMs: 60_000,
}),
cancelHttpWait: cancelBackendReadinessWait,
});
}
@@ -2035,16 +1999,17 @@ function createWindow(): BrowserWindow {
emitUpdateState();
});
let initialRevealScheduled = false;
const revealInitialWindow = () => {
if (initialRevealScheduled) {
return;
}
initialRevealScheduled = true;
revealWindow(window);
};
window.once("ready-to-show", revealInitialWindow);
// On Linux/Wayland with `show: false`, Electron's `ready-to-show` only
// fires after `show()` is called, deadlocking the standard "wait for
// ready, then show" pattern. Add `did-finish-load` as a Linux-only
// fallback so the window still surfaces once the renderer has loaded
// the page. Other platforms keep the no-flash `ready-to-show` path,
// since `did-finish-load` typically fires before the first paint there.
const revealSubscribers: RevealSubscription[] = [(fire) => window.once("ready-to-show", fire)];
if (process.platform === "linux") {
revealSubscribers.push((fire) => window.webContents.once("did-finish-load", fire));
}
bindFirstRevealTrigger(revealSubscribers, () => revealWindow(window));
if (isDevelopment) {
void window.loadURL(resolveDesktopDevServerUrl());
@@ -2119,9 +2084,9 @@ async function bootstrap(): Promise<void> {
if (isDevelopment) {
mainWindow = createWindow();
writeDesktopLogHeader("bootstrap main window created");
void waitForBackendHttpReady(backendHttpUrl)
.then(() => {
writeDesktopLogHeader("bootstrap backend ready");
void waitForBackendWindowReady(backendHttpUrl)
.then((source) => {
writeDesktopLogHeader(`bootstrap backend ready source=${source}`);
})
.catch((error) => {
if (isBackendReadinessAborted(error)) {
+74
View File
@@ -0,0 +1,74 @@
import { EventEmitter } from "node:events";
import { describe, expect, it, vi } from "vitest";
import { bindFirstRevealTrigger } from "./windowReveal.ts";
describe("bindFirstRevealTrigger", () => {
it("reveals when the first trigger fires", () => {
const window = new EventEmitter();
const webContents = new EventEmitter();
const reveal = vi.fn();
bindFirstRevealTrigger(
[
(fire) => window.once("ready-to-show", fire),
(fire) => webContents.once("did-finish-load", fire),
],
reveal,
);
window.emit("ready-to-show");
expect(reveal).toHaveBeenCalledTimes(1);
});
it("reveals when only the fallback trigger fires (Wayland deadlock case)", () => {
const window = new EventEmitter();
const webContents = new EventEmitter();
const reveal = vi.fn();
bindFirstRevealTrigger(
[
(fire) => window.once("ready-to-show", fire),
(fire) => webContents.once("did-finish-load", fire),
],
reveal,
);
webContents.emit("did-finish-load");
expect(reveal).toHaveBeenCalledTimes(1);
});
it("only reveals once when multiple triggers fire", () => {
const window = new EventEmitter();
const webContents = new EventEmitter();
const reveal = vi.fn();
bindFirstRevealTrigger(
[
(fire) => window.once("ready-to-show", fire),
(fire) => webContents.once("did-finish-load", fire),
],
reveal,
);
webContents.emit("did-finish-load");
window.emit("ready-to-show");
expect(reveal).toHaveBeenCalledTimes(1);
});
it("subscribers using `once` ignore re-emitted events after reveal", () => {
const window = new EventEmitter();
const reveal = vi.fn();
bindFirstRevealTrigger([(fire) => window.once("ready-to-show", fire)], reveal);
window.emit("ready-to-show");
window.emit("ready-to-show");
expect(reveal).toHaveBeenCalledTimes(1);
});
});
+28
View File
@@ -0,0 +1,28 @@
export type RevealSubscription = (listener: () => void) => void;
/**
* Wire a reveal callback to fire exactly once, on whichever of the provided
* event subscribers fires first. Each subscriber is responsible for binding
* its own event source.
*
* Used by the desktop main window's first-paint reveal logic. The standard
* Electron pattern is to wait for `ready-to-show` before calling `show()`,
* but on Linux/Wayland with `show: false`, `ready-to-show` only fires after
* `show()` is called, deadlocking that pattern. Subscribing to both
* `ready-to-show` and `did-finish-load` (or any other "renderer is alive"
* signal) lets the window surface reliably across platforms.
*/
export function bindFirstRevealTrigger(
subscribers: readonly RevealSubscription[],
reveal: () => void,
): void {
let revealed = false;
const fire = () => {
if (revealed) return;
revealed = true;
reveal();
};
for (const subscribe of subscribers) {
subscribe(fire);
}
}
+1 -1
View File
@@ -12,7 +12,7 @@ export default defineConfig([
...shared,
entry: ["src/main.ts"],
clean: true,
noExternal: (id) => id.startsWith("@t3tools/"),
noExternal: (id) => id.startsWith("@t3tools/") || id.startsWith("effect-acp"),
},
{
...shared,
@@ -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";
@@ -58,6 +59,7 @@ import {
OrchestrationEngineService,
type OrchestrationEngineShape,
} from "../src/orchestration/Services/OrchestrationEngine.ts";
import { ThreadDeletionReactor } from "../src/orchestration/Services/ThreadDeletionReactor.ts";
import { OrchestrationReactor } from "../src/orchestration/Services/OrchestrationReactor.ts";
import { ProjectionSnapshotQuery } from "../src/orchestration/Services/ProjectionSnapshotQuery.ts";
import {
@@ -72,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, {
@@ -213,7 +220,7 @@ export interface OrchestrationIntegrationHarness {
}
interface MakeOrchestrationIntegrationHarnessOptions {
readonly provider?: ProviderKind;
readonly provider?: ProviderDriverKind;
readonly realCodex?: boolean;
}
@@ -224,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
@@ -232,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-",
@@ -263,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,
@@ -306,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 },
}),
@@ -341,16 +345,23 @@ 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),
Layer.provideMerge(providerCommandReactorLayer),
Layer.provideMerge(checkpointReactorLayer),
Layer.provideMerge(
Layer.succeed(ThreadDeletionReactor, {
start: () => Effect.void,
drain: Effect.void,
}),
),
);
const layer = Layer.empty.pipe(
Layer.provideMerge(runtimeServicesLayer),
@@ -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",
});
+4 -1
View File
@@ -1,6 +1,6 @@
{
"name": "t3",
"version": "0.0.20",
"version": "0.0.21",
"license": "MIT",
"repository": {
"type": "git",
@@ -29,6 +29,7 @@
"@effect/platform-bun": "catalog:",
"@effect/platform-node": "catalog:",
"@effect/sql-sqlite-bun": "catalog:",
"@opencode-ai/sdk": "^1.3.15",
"@pierre/diffs": "^1.1.0-beta.16",
"effect": "catalog:",
"node-pty": "^1.1.0",
@@ -42,6 +43,8 @@
"@t3tools/web": "workspace:*",
"@types/bun": "catalog:",
"@types/node": "catalog:",
"effect-acp": "workspace:*",
"effect-codex-app-server": "workspace:*",
"tsdown": "catalog:",
"typescript": "catalog:",
"vitest": "catalog:"
+590
View File
@@ -0,0 +1,590 @@
#!/usr/bin/env bun
import { appendFileSync } from "node:fs";
import * as Effect from "effect/Effect";
import * as NodeServices from "@effect/platform-node/NodeServices";
import * as NodeRuntime from "@effect/platform-node/NodeRuntime";
import * as EffectAcpAgent from "effect-acp/agent";
import * as AcpError from "effect-acp/errors";
import type * as AcpSchema from "effect-acp/schema";
const requestLogPath = process.env.T3_ACP_REQUEST_LOG_PATH;
const exitLogPath = process.env.T3_ACP_EXIT_LOG_PATH;
const emitToolCalls = process.env.T3_ACP_EMIT_TOOL_CALLS === "1";
const emitInterleavedAssistantToolCalls =
process.env.T3_ACP_EMIT_INTERLEAVED_ASSISTANT_TOOL_CALLS === "1";
const emitGenericToolPlaceholders = process.env.T3_ACP_EMIT_GENERIC_TOOL_PLACEHOLDERS === "1";
const emitAskQuestion = process.env.T3_ACP_EMIT_ASK_QUESTION === "1";
const failSetConfigOption = process.env.T3_ACP_FAIL_SET_CONFIG_OPTION === "1";
const exitOnSetConfigOption = process.env.T3_ACP_EXIT_ON_SET_CONFIG_OPTION === "1";
const promptResponseText = process.env.T3_ACP_PROMPT_RESPONSE_TEXT;
const sessionId = "mock-session-1";
let currentModeId = "ask";
let currentModelId = "default";
let parameterizedModelPicker = false;
let currentReasoning = "medium";
let currentContext = "272k";
let currentFast = false;
const cancelledSessions = new Set<string>();
function logExit(reason: string): void {
if (!exitLogPath) {
return;
}
appendFileSync(exitLogPath, `${reason}\n`, "utf8");
}
process.once("SIGTERM", () => {
logExit("SIGTERM");
process.exit(0);
});
process.once("SIGINT", () => {
logExit("SIGINT");
process.exit(0);
});
process.once("exit", (code) => {
logExit(`exit:${code}`);
});
function configOptions(): ReadonlyArray<AcpSchema.SessionConfigOption> {
if (parameterizedModelPicker) {
const baseOptions: Array<AcpSchema.SessionConfigOption> = [
{
id: "mode",
name: "Mode",
category: "mode",
type: "select",
currentValue: currentModeId,
options: availableModes.map((mode) => ({
value: mode.id,
name: mode.name,
...(mode.description ? { description: mode.description } : {}),
})),
},
{
id: "model",
name: "Model",
category: "model",
type: "select",
currentValue: currentModelId,
options: [
{ value: "default", name: "Auto" },
{ value: "composer-2", name: "Composer 2" },
{ value: "gpt-5.4", name: "GPT-5.4" },
{ value: "claude-opus-4-6", name: "Opus 4.6" },
],
},
];
switch (currentModelId) {
case "gpt-5.4":
return [
...baseOptions,
{
id: "reasoning",
name: "Reasoning",
category: "thought_level",
type: "select",
currentValue: currentReasoning,
options: [
{ value: "none", name: "None" },
{ value: "low", name: "Low" },
{ value: "medium", name: "Medium" },
{ value: "high", name: "High" },
{ value: "extra-high", name: "Extra High" },
],
},
{
id: "context",
name: "Context",
category: "model_config",
type: "select",
currentValue: currentContext,
options: [
{ value: "272k", name: "272K" },
{ value: "1m", name: "1M" },
],
},
{
id: "fast",
name: "Fast",
category: "model_config",
type: "select",
currentValue: String(currentFast),
options: [
{ value: "false", name: "Off" },
{ value: "true", name: "Fast" },
],
},
];
case "composer-2":
return [
...baseOptions,
{
id: "fast",
name: "Fast",
category: "model_config",
type: "select",
currentValue: String(currentFast),
options: [
{ value: "false", name: "Off" },
{ value: "true", name: "Fast" },
],
},
];
case "claude-opus-4-6":
return [
...baseOptions,
{
id: "reasoning",
name: "Reasoning",
category: "thought_level",
type: "select",
currentValue: currentReasoning,
options: [
{ value: "low", name: "Low" },
{ value: "medium", name: "Medium" },
{ value: "high", name: "High" },
],
},
{
id: "thinking",
name: "Thinking",
category: "model_config",
type: "boolean",
currentValue: true,
},
];
default:
return baseOptions;
}
}
return [
{
id: "model",
name: "Model",
category: "model",
type: "select" as const,
currentValue: currentModelId,
options: [
{ value: "default", name: "Auto" },
{ value: "composer-2", name: "Composer 2" },
{ value: "composer-2[fast=true]", name: "Composer 2 Fast" },
{ value: "gpt-5.3-codex[reasoning=medium,fast=false]", name: "Codex 5.3" },
],
},
];
}
const availableModes: ReadonlyArray<AcpSchema.SessionMode> = [
{
id: "ask",
name: "Ask",
description: "Request permission before making any changes",
},
{
id: "architect",
name: "Architect",
description: "Design and plan software systems without implementation",
},
{
id: "code",
name: "Code",
description: "Write and modify code with full tool access",
},
];
function modeState(): AcpSchema.SessionModeState {
return {
currentModeId,
availableModes,
};
}
const program = Effect.gen(function* () {
const agent = yield* EffectAcpAgent.AcpAgent;
yield* agent.handleInitialize((request) =>
Effect.sync(() => {
parameterizedModelPicker =
request.clientCapabilities?._meta?.parameterizedModelPicker === true;
return {
protocolVersion: 1,
agentCapabilities: { loadSession: true },
};
}),
);
yield* agent.handleAuthenticate(() => Effect.succeed({}));
yield* agent.handleCreateSession(() =>
Effect.succeed({
sessionId,
modes: modeState(),
configOptions: configOptions(),
}),
);
yield* agent.handleLoadSession((request) =>
agent.client
.sessionUpdate({
sessionId: String(request.sessionId ?? sessionId),
update: {
sessionUpdate: "user_message_chunk",
content: { type: "text", text: "replay" },
},
})
.pipe(
Effect.as({
modes: modeState(),
configOptions: configOptions(),
}),
),
);
yield* agent.handleSetSessionConfigOption((request) =>
Effect.gen(function* () {
if (exitOnSetConfigOption) {
return yield* Effect.sync(() => {
process.exit(7);
});
}
if (failSetConfigOption) {
return yield* AcpError.AcpRequestError.invalidParams(
"Mock invalid params for session/set_config_option",
{
method: "session/set_config_option",
params: request,
},
);
}
if (request.configId === "mode" && typeof request.value === "string") {
currentModeId = request.value;
}
if (request.configId === "model" && typeof request.value === "string") {
currentModelId = request.value;
}
if (request.configId === "reasoning" && typeof request.value === "string") {
currentReasoning = request.value;
}
if (request.configId === "context" && typeof request.value === "string") {
currentContext = request.value;
}
if (request.configId === "fast") {
currentFast = request.value === true || request.value === "true";
}
return {
configOptions: configOptions(),
};
}),
);
yield* agent.handleCancel(({ sessionId }) =>
Effect.sync(() => {
cancelledSessions.add(String(sessionId ?? "mock-session-1"));
}),
);
yield* agent.handlePrompt((request) =>
Effect.gen(function* () {
const requestedSessionId = String(request.sessionId ?? sessionId);
if (emitInterleavedAssistantToolCalls) {
const toolCallId = "tool-call-1";
yield* agent.client.sessionUpdate({
sessionId: requestedSessionId,
update: {
sessionUpdate: "agent_message_chunk",
content: { type: "text", text: "before tool" },
},
});
yield* agent.client.sessionUpdate({
sessionId: requestedSessionId,
update: {
sessionUpdate: "tool_call",
toolCallId,
title: "Terminal",
kind: "execute",
status: "pending",
rawInput: {
command: ["echo", "hello"],
},
},
});
yield* agent.client.sessionUpdate({
sessionId: requestedSessionId,
update: {
sessionUpdate: "tool_call_update",
toolCallId,
status: "completed",
rawOutput: {
exitCode: 0,
stdout: "hello",
stderr: "",
},
},
});
yield* agent.client.sessionUpdate({
sessionId: requestedSessionId,
update: {
sessionUpdate: "agent_message_chunk",
content: { type: "text", text: "after tool" },
},
});
return { stopReason: "end_turn" };
}
if (emitToolCalls) {
const toolCallId = "tool-call-1";
yield* agent.client.sessionUpdate({
sessionId: requestedSessionId,
update: {
sessionUpdate: "tool_call",
toolCallId,
title: "Terminal",
kind: "execute",
status: "pending",
rawInput: {
command: ["cat", "server/package.json"],
},
},
});
yield* agent.client.sessionUpdate({
sessionId: requestedSessionId,
update: {
sessionUpdate: "tool_call_update",
toolCallId,
status: "in_progress",
},
});
const permission = yield* agent.client.requestPermission({
sessionId: requestedSessionId,
toolCall: {
toolCallId,
title: "`cat server/package.json`",
kind: "execute",
status: "pending",
content: [
{
type: "content",
content: {
type: "text",
text: "Not in allowlist: cat server/package.json",
},
},
],
},
options: [
{ optionId: "allow-once", name: "Allow once", kind: "allow_once" },
{ optionId: "allow-always", name: "Allow always", kind: "allow_always" },
{ optionId: "reject-once", name: "Reject", kind: "reject_once" },
],
});
const cancelled =
cancelledSessions.delete(requestedSessionId) ||
permission.outcome.outcome === "cancelled";
yield* agent.client.sessionUpdate({
sessionId: requestedSessionId,
update: {
sessionUpdate: "tool_call_update",
toolCallId,
title: "Terminal",
kind: "execute",
status: "completed",
rawOutput: {
exitCode: 0,
stdout: '{ "name": "t3" }',
stderr: "",
},
},
});
yield* agent.client.sessionUpdate({
sessionId: requestedSessionId,
update: {
sessionUpdate: "agent_message_chunk",
content: { type: "text", text: "hello from mock" },
},
});
return { stopReason: cancelled ? "cancelled" : "end_turn" };
}
if (emitGenericToolPlaceholders) {
const toolCallId = "tool-call-generic-1";
yield* agent.client.sessionUpdate({
sessionId: requestedSessionId,
update: {
sessionUpdate: "tool_call",
toolCallId,
title: "Read File",
kind: "read",
status: "pending",
rawInput: {},
},
});
yield* agent.client.sessionUpdate({
sessionId: requestedSessionId,
update: {
sessionUpdate: "tool_call_update",
toolCallId,
status: "in_progress",
},
});
yield* agent.client.sessionUpdate({
sessionId: requestedSessionId,
update: {
sessionUpdate: "tool_call_update",
toolCallId,
status: "completed",
rawOutput: {
content: "package.json\n",
},
},
});
return { stopReason: "end_turn" };
}
if (emitAskQuestion) {
yield* agent.client.extRequest("cursor/ask_question", {
toolCallId: "ask-question-tool-call-1",
title: "Question",
questions: [
{
id: "scope",
prompt: "Which scope?",
options: [
{ id: "workspace", label: "Workspace" },
{ id: "session", label: "Session" },
],
},
],
});
return { stopReason: "end_turn" };
}
yield* agent.client.sessionUpdate({
sessionId: requestedSessionId,
update: {
sessionUpdate: "plan",
entries: [
{
content: "Inspect mock ACP state",
priority: "high",
status: "completed",
},
{
content: "Implement the requested change",
priority: "high",
status: "in_progress",
},
],
},
});
yield* agent.client.sessionUpdate({
sessionId: requestedSessionId,
update: {
sessionUpdate: "agent_message_chunk",
content: { type: "text", text: promptResponseText ?? "hello from mock" },
},
});
return { stopReason: "end_turn" };
}),
);
yield* agent.handleUnknownExtRequest((method, params) => {
if (method !== "session/mode/set") {
return Effect.fail(AcpError.AcpRequestError.methodNotFound(method));
}
const nextModeId =
typeof params === "object" &&
params !== null &&
"modeId" in params &&
typeof params.modeId === "string"
? params.modeId
: typeof params === "object" &&
params !== null &&
"mode" in params &&
typeof params.mode === "string"
? params.mode
: undefined;
const requestedSessionId =
typeof params === "object" &&
params !== null &&
"sessionId" in params &&
typeof params.sessionId === "string"
? params.sessionId
: sessionId;
if (typeof nextModeId === "string" && nextModeId.trim()) {
currentModeId = nextModeId.trim();
return agent.client
.sessionUpdate({
sessionId: requestedSessionId,
update: {
sessionUpdate: "current_mode_update",
currentModeId,
},
})
.pipe(Effect.as({}));
}
return Effect.succeed({});
});
return yield* Effect.never;
}).pipe(
Effect.provide(
EffectAcpAgent.layerStdio(
requestLogPath
? {
logIncoming: true,
logger: (event) => {
if (event.direction !== "incoming" || event.stage !== "raw") {
return Effect.void;
}
if (typeof event.payload !== "string") {
return Effect.void;
}
const payload = event.payload;
return Effect.sync(() => {
appendFileSync(
requestLogPath,
payload.endsWith("\n") ? payload : `${payload}\n`,
"utf8",
);
});
},
}
: {},
),
),
Effect.scoped,
Effect.provide(NodeServices.layer),
);
NodeRuntime.runMain(program);
@@ -0,0 +1,435 @@
import { spawn, type ChildProcessWithoutNullStreams } from "node:child_process";
import process from "node:process";
import readline from "node:readline";
type JsonPrimitive = null | boolean | number | string;
type JsonValue = JsonPrimitive | JsonValue[] | { [key: string]: JsonValue };
type JsonRpcId = number | string;
type JsonRpcMessage = {
jsonrpc?: string;
id?: JsonRpcId;
method?: string;
params?: JsonValue;
result?: JsonValue;
error?: JsonValue;
headers?: JsonValue;
};
type SelectLeafOption = {
value: string;
label?: string;
name?: string;
};
type SelectGroupOption = {
label?: string;
name?: string;
options: SelectLeafOption[];
};
type SessionConfigOption = {
id: string;
name?: string;
category?: string;
type?: string;
options?: Array<SelectLeafOption | SelectGroupOption>;
};
type SessionNewResult = {
sessionId: string;
configOptions?: SessionConfigOption[];
};
type SetConfigResult = {
configOptions?: SessionConfigOption[];
};
type PendingRequest = {
method: string;
resolve: (value: JsonValue | undefined) => void;
reject: (error: Error) => void;
};
const targetCwd = process.argv[2] ?? process.cwd();
const targetModel = process.argv[3] ?? "gpt-5.4";
const promptText = process.argv[4] ?? "helo";
const targetReasoning = process.env.CURSOR_REASONING ?? "";
const targetContext = process.env.CURSOR_CONTEXT ?? "";
const targetFast = process.env.CURSOR_FAST ?? "";
const agentBin = process.env.CURSOR_AGENT_BIN ?? "agent";
const promptWaitMs = Number(process.env.CURSOR_PROMPT_WAIT_MS ?? "4000");
const requestTimeoutMs = Number(process.env.CURSOR_REQUEST_TIMEOUT_MS ?? "20000");
function logSection(title: string, value: unknown) {
process.stdout.write(`\n=== ${title} ===\n`);
process.stdout.write(`${JSON.stringify(value, null, 2)}\n`);
}
function fail(message: string): never {
throw new Error(message);
}
function asString(value: JsonValue | undefined): string | null {
return typeof value === "string" ? value : null;
}
function flattenSelectValues(option: SessionConfigOption | undefined): string[] {
if (!option || option.type !== "select" || !Array.isArray(option.options)) {
return [];
}
const values: string[] = [];
for (const entry of option.options) {
if (!entry || typeof entry !== "object") {
continue;
}
if ("value" in entry && typeof entry.value === "string") {
values.push(entry.value);
continue;
}
if ("options" in entry && Array.isArray(entry.options)) {
for (const nested of entry.options) {
if (nested && typeof nested === "object" && typeof nested.value === "string") {
values.push(nested.value);
}
}
}
}
return values;
}
function findConfigOption(
configOptions: SessionConfigOption[],
predicate: (option: SessionConfigOption) => boolean,
): SessionConfigOption | undefined {
return configOptions.find(predicate);
}
function matchesKeyword(option: SessionConfigOption, keyword: string): boolean {
const haystack = `${option.id} ${option.name ?? ""}`.toLowerCase();
return haystack.includes(keyword.toLowerCase());
}
function sleep(ms: number) {
return new Promise<void>((resolve) => {
setTimeout(resolve, ms);
});
}
class JsonRpcChild {
readonly child: ChildProcessWithoutNullStreams;
readonly pending = new Map<JsonRpcId, PendingRequest>();
nextId = 1;
closed = false;
constructor(bin: string, args: string[], cwd: string) {
this.child = spawn(bin, args, {
cwd,
shell: process.platform === "win32",
stdio: ["pipe", "pipe", "pipe"],
env: process.env,
});
this.child.on("exit", (code, signal) => {
this.closed = true;
const detail = `ACP process exited (code=${String(code)}, signal=${String(signal)})`;
for (const pending of this.pending.values()) {
pending.reject(new Error(`${detail} while waiting for ${pending.method}`));
}
this.pending.clear();
});
this.child.on("error", (error) => {
this.closed = true;
for (const pending of this.pending.values()) {
pending.reject(error);
}
this.pending.clear();
});
const stdout = readline.createInterface({ input: this.child.stdout });
stdout.on("line", (line) => {
void this.handleStdoutLine(line);
});
const stderr = readline.createInterface({ input: this.child.stderr });
stderr.on("line", (line) => {
process.stdout.write(`[stderr] ${line}\n`);
});
}
write(message: JsonRpcMessage) {
if (this.closed) {
fail("ACP process is already closed.");
}
const payload = JSON.stringify({
jsonrpc: "2.0",
headers: [],
...message,
});
process.stdout.write(`>>> ${payload}\n`);
this.child.stdin.write(`${payload}\n`);
}
async request(method: string, params: JsonValue, timeoutMs = requestTimeoutMs) {
const id = this.nextId++;
const responsePromise = new Promise<JsonValue | undefined>((resolve, reject) => {
const timeout = setTimeout(() => {
this.pending.delete(id);
reject(new Error(`Timed out waiting for ${method} response after ${timeoutMs}ms.`));
}, timeoutMs);
this.pending.set(id, {
method,
resolve: (value) => {
clearTimeout(timeout);
resolve(value);
},
reject: (error) => {
clearTimeout(timeout);
reject(error);
},
});
});
this.write({
id,
method,
params,
});
return responsePromise;
}
notify(method: string, params: JsonValue) {
this.write({
method,
params,
});
}
respond(id: JsonRpcId, result: JsonValue) {
this.write({
id,
result,
});
}
respondError(id: JsonRpcId, code: number, message: string) {
this.write({
id,
error: {
code,
message,
},
});
}
async handleStdoutLine(line: string) {
if (line.trim().length === 0) {
return;
}
process.stdout.write(`<<< ${line}\n`);
let message: JsonRpcMessage;
try {
message = JSON.parse(line) as JsonRpcMessage;
} catch (error) {
process.stdout.write(`[parse-error] ${(error as Error).message}\n`);
return;
}
if (typeof message.id !== "undefined" && !message.method) {
const pending = this.pending.get(message.id);
if (!pending) {
return;
}
this.pending.delete(message.id);
if (typeof message.error !== "undefined") {
pending.reject(
new Error(`RPC ${pending.method} failed: ${JSON.stringify(message.error, null, 2)}`),
);
return;
}
pending.resolve(message.result);
return;
}
if (message.method === "session/request_permission" && typeof message.id !== "undefined") {
this.respond(message.id, {
outcome: {
outcome: "selected",
optionId: "allow",
},
});
return;
}
if (typeof message.id !== "undefined" && message.id !== "") {
this.respondError(
message.id,
-32601,
`Unhandled server request: ${message.method ?? "unknown"}`,
);
}
}
async close() {
if (this.closed) {
return;
}
this.child.kill("SIGTERM");
await sleep(250);
if (!this.closed) {
this.child.kill("SIGKILL");
}
}
}
async function setSelectOptionIfAdvertised(
rpc: JsonRpcChild,
sessionId: string,
configOptions: SessionConfigOption[],
predicate: (option: SessionConfigOption) => boolean,
value: string,
label: string,
) {
if (value.length === 0) {
return configOptions;
}
const option = findConfigOption(configOptions, predicate);
const values = flattenSelectValues(option);
if (!option || !values.includes(value)) {
logSection(`SKIP_${label}`, {
requestedValue: value,
availableValues: values,
});
return configOptions;
}
const response = (await rpc.request("session/set_config_option", {
sessionId,
configId: option.id,
value,
})) as SetConfigResult | null | undefined;
logSection(`SET_${label}_RESPONSE`, response);
return response?.configOptions ?? configOptions;
}
async function main() {
const rpc = new JsonRpcChild(agentBin, ["acp"], targetCwd);
try {
const initializeResponse = await rpc.request("initialize", {
protocolVersion: 1,
clientCapabilities: {
fs: { readTextFile: false, writeTextFile: false },
terminal: false,
_meta: {
parameterizedModelPicker: true,
},
},
clientInfo: {
name: "cursor-acp-model-mismatch-probe",
version: "0.0.0",
},
});
logSection("INITIALIZE_RESPONSE", initializeResponse);
const authenticateResponse = await rpc.request("authenticate", {
methodId: "cursor_login",
});
logSection("AUTHENTICATE_RESPONSE", authenticateResponse);
const sessionResponse = (await rpc.request("session/new", {
cwd: targetCwd,
mcpServers: [],
})) as SessionNewResult;
logSection("SESSION_NEW_RESPONSE", sessionResponse);
const sessionId = asString(sessionResponse.sessionId);
if (!sessionId) {
fail("session/new did not return a sessionId.");
}
let configOptions = sessionResponse.configOptions ?? [];
const modelConfig = findConfigOption(configOptions, (option) => option.category === "model");
const advertisedModels = flattenSelectValues(modelConfig);
logSection("ADVERTISED_MODEL_VALUES", advertisedModels);
if (!modelConfig || modelConfig.type !== "select") {
fail("Cursor ACP did not expose a select-type model config option.");
}
if (!advertisedModels.includes(targetModel)) {
fail(
`Cursor ACP did not advertise model ${JSON.stringify(targetModel)}. Advertised values: ${advertisedModels.join(", ")}`,
);
}
const setModelResponse = (await rpc.request("session/set_config_option", {
sessionId,
configId: modelConfig.id,
value: targetModel,
})) as SetConfigResult | null | undefined;
logSection("SET_MODEL_RESPONSE", setModelResponse);
configOptions = setModelResponse?.configOptions ?? configOptions;
configOptions = await setSelectOptionIfAdvertised(
rpc,
sessionId,
configOptions,
(option) => option.category === "thought_level",
targetReasoning,
"REASONING",
);
configOptions = await setSelectOptionIfAdvertised(
rpc,
sessionId,
configOptions,
(option) => option.category === "model_config" && matchesKeyword(option, "context"),
targetContext,
"CONTEXT",
);
configOptions = await setSelectOptionIfAdvertised(
rpc,
sessionId,
configOptions,
(option) => option.category === "model_config" && matchesKeyword(option, "fast"),
targetFast,
"FAST",
);
const promptResponse = await rpc.request("session/prompt", {
sessionId,
prompt: [
{
type: "text",
text: promptText,
},
],
});
logSection("PROMPT_RESPONSE", promptResponse);
await sleep(promptWaitMs);
rpc.notify("session/cancel", { sessionId });
} finally {
await rpc.close();
}
}
void main().catch((error: unknown) => {
process.stderr.write(
`${error instanceof Error ? (error.stack ?? error.message) : String(error)}\n`,
);
process.exitCode = 1;
});
+25
View File
@@ -0,0 +1,25 @@
import { Effect, FileSystem, Path } from "effect";
import * as Random from "effect/Random";
export const writeFileStringAtomically = (input: {
readonly filePath: string;
readonly contents: string;
}) =>
Effect.scoped(
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const tempFileId = yield* Random.nextUUIDv4;
const targetDirectory = path.dirname(input.filePath);
yield* fs.makeDirectory(targetDirectory, { recursive: true });
const tempDirectory = yield* fs.makeTempDirectoryScoped({
directory: targetDirectory,
prefix: `${path.basename(input.filePath)}.`,
});
const tempPath = path.join(tempDirectory, `${tempFileId}.tmp`);
yield* fs.writeFileString(tempPath, input.contents);
yield* fs.rename(tempPath, input.filePath);
}),
);
+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,18 +14,36 @@ 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";
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,
@@ -34,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();
@@ -42,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,
@@ -65,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();
@@ -74,7 +89,7 @@ const makeCheckpointStore = Effect.gen(function* () {
);
const isGitRepository: CheckpointStoreShape["isGitRepository"] = (cwd) =>
git
vcs
.execute({
operation: "CheckpointStore.isGitRepository",
cwd,
@@ -82,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)),
);
@@ -106,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"],
@@ -114,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"],
@@ -129,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],
@@ -146,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],
@@ -195,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", "--", "."],
@@ -208,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", "--", "."],
@@ -233,18 +250,20 @@ 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],
maxOutputBytes: CHECKPOINT_DIFF_MAX_OUTPUT_BYTES,
});
return result.stdout;
@@ -259,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],
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
@@ -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,25 @@ 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({
resolveHandle: () => Effect.succeed({ provider, context: null }),
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 +676,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 +688,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 +722,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 +767,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 +818,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 +867,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 +883,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 +912,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 +996,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 +1050,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 +1150,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 +1200,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 +1277,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 +1308,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 +1732,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-");
@@ -2959,6 +3056,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
expect.objectContaining({
kind: "hook_finished",
hookName: "pre-commit",
exitCode: 0,
}),
expect.objectContaining({
kind: "action_finished",
@@ -3089,7 +3187,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,309 +0,0 @@
import * as NodeServices from "@effect/platform-node/NodeServices";
import { it } from "@effect/vitest";
import { Effect, FileSystem, Layer, Path } from "effect";
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: {
provider: "claudeAgent",
model: "claude-haiku-4-5",
options: {
thinking: false,
effort: "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: {
provider: "claudeAgent",
model: "claude-opus-4-6",
options: {
effort: "max",
fastMode: 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");
}),
),
);
});
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,73 +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 TextGenerationProvider,
type TextGenerationShape,
} from "../Services/TextGeneration.ts";
import { CodexTextGenerationLive } from "./CodexTextGeneration.ts";
import { ClaudeTextGenerationLive } from "./ClaudeTextGeneration.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",
) {}
// ---------------------------------------------------------------------------
// Routing implementation
// ---------------------------------------------------------------------------
const makeRoutingTextGeneration = Effect.gen(function* () {
const codex = yield* CodexTextGen;
const claude = yield* ClaudeTextGen;
const route = (provider?: TextGenerationProvider): TextGenerationShape =>
provider === "claudeAgent" ? claude : codex;
return {
generateCommitMessage: (input) =>
route(input.modelSelection.provider).generateCommitMessage(input),
generatePrContent: (input) => route(input.modelSelection.provider).generatePrContent(input),
generateBranchName: (input) => route(input.modelSelection.provider).generateBranchName(input),
generateThreadTitle: (input) => route(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));
export const RoutingTextGenerationLive = Layer.effect(
TextGeneration,
makeRoutingTextGeneration,
).pipe(Layer.provide(InternalCodexLayer), Layer.provide(InternalClaudeLayer));
-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") {}
-117
View File
@@ -1,123 +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]`;
}
/** 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 }
: {}),
+3
View File
@@ -192,6 +192,9 @@ it.layer(NodeServices.layer)("keybindings", (it) => {
assert.equal(defaultsByCommand.get("thread.next"), "mod+shift+]");
assert.equal(defaultsByCommand.get("thread.jump.1"), "mod+1");
assert.equal(defaultsByCommand.get("thread.jump.9"), "mod+9");
assert.equal(defaultsByCommand.get("modelPicker.toggle"), "mod+shift+m");
assert.equal(defaultsByCommand.get("modelPicker.jump.1"), "mod+1");
assert.equal(defaultsByCommand.get("modelPicker.jump.9"), "mod+9");
}),
);
+17 -6
View File
@@ -13,6 +13,7 @@ import {
KeybindingShortcut,
KeybindingWhenNode,
MAX_KEYBINDINGS_COUNT,
MODEL_PICKER_JUMP_KEYBINDING_COMMANDS,
MAX_WHEN_EXPRESSION_DEPTH,
ResolvedKeybindingRule,
ResolvedKeybindingsConfig,
@@ -45,6 +46,7 @@ import {
} from "effect";
import * as Semaphore from "effect/Semaphore";
import { ServerConfig } from "./config.ts";
import { writeFileStringAtomically } from "./atomicWrite.ts";
import { fromLenientJson } from "@t3tools/shared/schemaJson";
type WhenToken =
@@ -65,6 +67,7 @@ export const DEFAULT_KEYBINDINGS: ReadonlyArray<KeybindingRule> = [
{ key: "mod+n", command: "chat.new", when: "!terminalFocus" },
{ key: "mod+shift+o", command: "chat.new", when: "!terminalFocus" },
{ key: "mod+shift+n", command: "chat.newLocal", when: "!terminalFocus" },
{ key: "mod+shift+m", command: "modelPicker.toggle", when: "!terminalFocus" },
{ key: "mod+o", command: "editor.openFavorite" },
{ key: "mod+shift+[", command: "thread.previous" },
{ key: "mod+shift+]", command: "thread.next" },
@@ -72,6 +75,11 @@ export const DEFAULT_KEYBINDINGS: ReadonlyArray<KeybindingRule> = [
key: `mod+${index + 1}`,
command,
})),
...MODEL_PICKER_JUMP_KEYBINDING_COMMANDS.map((command, index) => ({
key: `mod+${index + 1}`,
command,
when: "modelPickerOpen",
})),
];
function normalizeKeyToken(token: string): string {
@@ -663,14 +671,17 @@ const makeKeybindings = Effect.gen(function* () {
});
const writeConfigAtomically = (rules: readonly KeybindingRule[]) => {
const tempPath = `${keybindingsConfigPath}.${process.pid}.${Date.now()}.tmp`;
return Schema.encodeEffect(KeybindingsConfigPrettyJson)(rules).pipe(
Effect.map((encoded) => `${encoded}\n`),
Effect.tap(() => fs.makeDirectory(path.dirname(keybindingsConfigPath), { recursive: true })),
Effect.tap((encoded) => fs.writeFileString(tempPath, encoded)),
Effect.flatMap(() => fs.rename(tempPath, keybindingsConfigPath)),
Effect.ensuring(fs.remove(tempPath, { force: true }).pipe(Effect.ignore({ log: true }))),
Effect.flatMap((encoded) =>
writeFileStringAtomically({
filePath: keybindingsConfigPath,
contents: encoded,
}).pipe(
Effect.provideService(FileSystem.FileSystem, fs),
Effect.provideService(Path.Path, path),
),
),
Effect.mapError(
(cause) =>
new KeybindingsConfigError({
@@ -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,
@@ -4,6 +4,7 @@ import { afterEach, describe, expect, it } from "vitest";
import { CheckpointReactor } from "../Services/CheckpointReactor.ts";
import { ProviderCommandReactor } from "../Services/ProviderCommandReactor.ts";
import { ProviderRuntimeIngestionService } from "../Services/ProviderRuntimeIngestion.ts";
import { ThreadDeletionReactor } from "../Services/ThreadDeletionReactor.ts";
import { OrchestrationReactor } from "../Services/OrchestrationReactor.ts";
import { makeOrchestrationReactor } from "./OrchestrationReactor.ts";
@@ -17,7 +18,7 @@ describe("OrchestrationReactor", () => {
runtime = null;
});
it("starts provider ingestion, provider command, and checkpoint reactors", async () => {
it("starts provider ingestion, provider command, checkpoint, and thread deletion reactors", async () => {
const started: string[] = [];
runtime = ManagedRuntime.make(
@@ -49,10 +50,19 @@ describe("OrchestrationReactor", () => {
drain: Effect.void,
}),
),
Layer.provideMerge(
Layer.succeed(ThreadDeletionReactor, {
start: () => {
started.push("thread-deletion-reactor");
return Effect.void;
},
drain: Effect.void,
}),
),
),
);
const reactor = await runtime.runPromise(Effect.service(OrchestrationReactor));
const reactor = await runtime!.runPromise(Effect.service(OrchestrationReactor));
const scope = await Effect.runPromise(Scope.make("sequential"));
await Effect.runPromise(reactor.start().pipe(Scope.provide(scope)));
@@ -60,6 +70,7 @@ describe("OrchestrationReactor", () => {
"provider-runtime-ingestion",
"provider-command-reactor",
"checkpoint-reactor",
"thread-deletion-reactor",
]);
await Effect.runPromise(Scope.close(scope, Exit.void));
@@ -7,16 +7,19 @@ import {
import { CheckpointReactor } from "../Services/CheckpointReactor.ts";
import { ProviderCommandReactor } from "../Services/ProviderCommandReactor.ts";
import { ProviderRuntimeIngestionService } from "../Services/ProviderRuntimeIngestion.ts";
import { ThreadDeletionReactor } from "../Services/ThreadDeletionReactor.ts";
export const makeOrchestrationReactor = Effect.gen(function* () {
const providerRuntimeIngestion = yield* ProviderRuntimeIngestionService;
const providerCommandReactor = yield* ProviderCommandReactor;
const checkpointReactor = yield* CheckpointReactor;
const threadDeletionReactor = yield* ThreadDeletionReactor;
const start: OrchestrationReactorShape["start"] = Effect.fn("start")(function* () {
yield* providerRuntimeIngestion.start();
yield* providerCommandReactor.start();
yield* checkpointReactor.start();
yield* threadDeletionReactor.start();
});
return {
@@ -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,
File diff suppressed because it is too large. Load diff
@@ -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) {
@@ -89,9 +104,16 @@ function canReplaceThreadTitle(currentTitle: string, titleSeed?: string): boolea
: false;
}
function findProviderAdapterRequestError(
cause: Cause.Cause<ProviderServiceError>,
): ProviderAdapterRequestError | undefined {
const failReason = cause.reasons.find(Cause.isFailReason);
return Schema.is(ProviderAdapterRequestError)(failReason?.error) ? failReason.error : undefined;
}
function isUnknownPendingApprovalRequestError(cause: Cause.Cause<ProviderServiceError>): boolean {
const error = Cause.squash(cause);
if (Schema.is(ProviderAdapterRequestError)(error)) {
const error = findProviderAdapterRequestError(cause);
if (error) {
const detail = error.detail.toLowerCase();
return (
detail.includes("unknown pending approval request") ||
@@ -106,8 +128,8 @@ function isUnknownPendingApprovalRequestError(cause: Cause.Cause<ProviderService
}
function isUnknownPendingUserInputRequestError(cause: Cause.Cause<ProviderServiceError>): boolean {
const error = Cause.squash(cause);
if (Schema.is(ProviderAdapterRequestError)(error)) {
const error = findProviderAdapterRequestError(cause);
if (error) {
return error.detail.toLowerCase().includes("unknown pending user-input request");
}
return Cause.pretty(cause).toLowerCase().includes("unknown pending user-input request");
@@ -146,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>({
@@ -198,6 +220,17 @@ const make = Effect.gen(function* () {
createdAt: input.createdAt,
});
const formatFailureDetail = (cause: Cause.Cause<unknown>): string => {
const failReason = cause.reasons.find(Cause.isFailReason);
const providerError = Schema.is(ProviderAdapterRequestError)(failReason?.error)
? failReason.error
: undefined;
if (providerError) {
return providerError.detail;
}
return Cause.pretty(cause);
};
const setThreadSession = (input: {
readonly threadId: ThreadId;
readonly session: OrchestrationSession;
@@ -211,7 +244,30 @@ const make = Effect.gen(function* () {
createdAt: input.createdAt,
});
const resolveThread = Effect.fn("resolveThread")(function* (threadId: ThreadId) {
const setThreadSessionErrorOnTurnStartFailure = Effect.fnUntraced(function* (input: {
readonly threadId: ThreadId;
readonly detail: string;
readonly createdAt: string;
}) {
const thread = yield* resolveThread(input.threadId);
const session = thread?.session;
if (!session) {
return;
}
yield* setThreadSession({
threadId: input.threadId,
session: {
...session,
status: session.status === "stopped" ? "stopped" : "ready",
activeTurnId: null,
lastError: input.detail,
updatedAt: input.createdAt,
},
createdAt: input.createdAt,
});
});
const resolveThread = Effect.fnUntraced(function* (threadId: ThreadId) {
const readModel = yield* orchestrationEngine.getReadModel();
return readModel.threads.find((entry) => entry.id === threadId);
});
@@ -230,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 = currentProvider ?? 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 } : {}),
@@ -273,66 +395,79 @@ 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 providerChanged =
requestedModelSelection !== undefined &&
requestedModelSelection.provider !== currentProvider;
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 shouldRestartForModelChange = modelChanged && sessionModelSwitch === "restart-session";
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 &&
!providerChanged &&
!cwdChanged &&
!instanceChanged &&
!shouldRestartForModelChange &&
!shouldRestartForModelSelectionChange
) {
return existingSessionThreadId;
}
const resumeCursor =
providerChanged || shouldRestartForModelChange
? undefined
: (activeSession?.resumeCursor ?? undefined);
const resumeCursor = shouldRestartForModelChange
? undefined
: (activeSession?.resumeCursor ?? undefined);
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,
providerChanged,
previousCwd: activeSession?.cwd,
desiredCwd: effectiveCwd,
cwdChanged,
modelChanged,
instanceChanged,
shouldRestartForModelChange,
shouldRestartForModelSelectionChange,
hasResumeCursor: resumeCursor !== undefined,
@@ -346,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;
@@ -356,7 +492,7 @@ const make = Effect.gen(function* () {
return startedSession.threadId;
});
const sendTurnForThread = Effect.fn("sendTurnForThread")(function* (input: {
const buildSendTurnRequestForThread = Effect.fnUntraced(function* (input: {
readonly threadId: ThreadId;
readonly messageText: string;
readonly attachments?: ReadonlyArray<ChatAttachment>;
@@ -366,7 +502,9 @@ const make = Effect.gen(function* () {
}) {
const thread = yield* resolveThread(input.threadId);
if (!thread) {
return;
return yield* Effect.die(
new Error(`Thread '${input.threadId}' was not found in read model.`),
);
}
yield* ensureSessionForThread(
input.threadId,
@@ -386,11 +524,18 @@ 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 =
sessionModelSwitch === "unsupported"
sessionModelSwitch === "unsupported" && input.modelSelection === undefined
? activeSession?.model !== undefined
? {
...requestedModelSelection,
@@ -399,13 +544,13 @@ const make = Effect.gen(function* () {
: requestedModelSelection
: input.modelSelection;
yield* providerService.sendTurn({
return {
threadId: input.threadId,
...(normalizedInput ? { input: normalizedInput } : {}),
...(normalizedAttachments.length > 0 ? { attachments: normalizedAttachments } : {}),
...(modelForTurn !== undefined ? { modelSelection: modelForTurn } : {}),
...(input.interactionMode !== undefined ? { interactionMode: input.interactionMode } : {}),
});
};
});
const maybeGenerateAndRenameWorktreeBranchForFirstTurn = Effect.fn(
@@ -442,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"),
@@ -450,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", {
@@ -564,7 +709,43 @@ const make = Effect.gen(function* () {
}
}
yield* sendTurnForThread({
const handleTurnStartFailure = (cause: Cause.Cause<unknown>) => {
if (Cause.hasInterruptsOnly(cause)) {
return Effect.void;
}
const detail = formatFailureDetail(cause);
return setThreadSessionErrorOnTurnStartFailure({
threadId: event.payload.threadId,
detail,
createdAt: event.payload.createdAt,
}).pipe(
Effect.flatMap(() =>
appendProviderFailureActivity({
threadId: event.payload.threadId,
kind: "provider.turn.start.failed",
summary: "Provider turn start failed",
detail,
turnId: null,
createdAt: event.payload.createdAt,
}),
),
Effect.asVoid,
);
};
const recoverTurnStartFailure = (cause: Cause.Cause<unknown>) =>
handleTurnStartFailure(cause).pipe(
Effect.catchCause((recoveryCause) =>
Effect.logWarning("provider command reactor failed to recover turn start failure", {
eventType: event.type,
threadId: event.payload.threadId,
cause: Cause.pretty(recoveryCause),
originalCause: Cause.pretty(cause),
}),
),
);
const sendTurnRequest = yield* buildSendTurnRequestForThread({
threadId: event.payload.threadId,
messageText: message.text,
...(message.attachments !== undefined ? { attachments: message.attachments } : {}),
@@ -574,17 +755,17 @@ const make = Effect.gen(function* () {
interactionMode: event.payload.interactionMode,
createdAt: event.payload.createdAt,
}).pipe(
Effect.catchCause((cause) =>
appendProviderFailureActivity({
threadId: event.payload.threadId,
kind: "provider.turn.start.failed",
summary: "Provider turn start failed",
detail: Cause.pretty(cause),
turnId: null,
createdAt: event.payload.createdAt,
}),
),
Effect.map(Option.some),
Effect.catchCause((cause) => handleTurnStartFailure(cause).pipe(Effect.as(Option.none()))),
);
if (Option.isNone(sendTurnRequest)) {
return;
}
yield* providerService
.sendTurn(sendTurnRequest.value)
.pipe(Effect.catchCause(recoverTurnStartFailure), Effect.forkScoped);
});
const processTurnInterruptRequested = Effect.fn("processTurnInterruptRequested")(function* (
@@ -721,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,
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,36 @@
import { ThreadId } from "@t3tools/contracts";
import { Cause, Effect, Exit } from "effect";
import { describe, expect, it } from "vitest";
import { logCleanupCauseUnlessInterrupted } from "./ThreadDeletionReactor.ts";
describe("logCleanupCauseUnlessInterrupted", () => {
const threadId = ThreadId.make("thread-deletion-reactor-test");
it("swallows ordinary cleanup failures", async () => {
const exit = await Effect.runPromiseExit(
logCleanupCauseUnlessInterrupted({
effect: Effect.fail("cleanup failed"),
message: "thread deletion cleanup skipped provider session stop",
threadId,
}),
);
expect(Exit.isSuccess(exit)).toBe(true);
});
it("preserves interrupt causes", async () => {
const exit = await Effect.runPromiseExit(
logCleanupCauseUnlessInterrupted({
effect: Effect.interrupt,
message: "thread deletion cleanup skipped provider session stop",
threadId,
}),
);
expect(Exit.isFailure(exit)).toBe(true);
if (Exit.isFailure(exit)) {
expect(Cause.hasInterruptsOnly(exit.cause)).toBe(true);
}
});
});
@@ -0,0 +1,96 @@
import type { OrchestrationEvent } from "@t3tools/contracts";
import { makeDrainableWorker } from "@t3tools/shared/DrainableWorker";
import { Cause, Effect, Layer, Stream } from "effect";
import { ProviderService } from "../../provider/Services/ProviderService.ts";
import { TerminalManager } from "../../terminal/Services/Manager.ts";
import { OrchestrationEngineService } from "../Services/OrchestrationEngine.ts";
import {
ThreadDeletionReactor,
type ThreadDeletionReactorShape,
} from "../Services/ThreadDeletionReactor.ts";
type ThreadDeletedEvent = Extract<OrchestrationEvent, { type: "thread.deleted" }>;
export const logCleanupCauseUnlessInterrupted = <R, E>({
effect,
message,
threadId,
}: {
readonly effect: Effect.Effect<void, E, R>;
readonly message: string;
readonly threadId: ThreadDeletedEvent["payload"]["threadId"];
}): Effect.Effect<void, E, R> =>
effect.pipe(
Effect.catchCause((cause) => {
if (Cause.hasInterruptsOnly(cause)) {
return Effect.failCause(cause);
}
return Effect.logDebug(message, {
threadId,
cause: Cause.pretty(cause),
});
}),
);
const make = Effect.gen(function* () {
const orchestrationEngine = yield* OrchestrationEngineService;
const providerService = yield* ProviderService;
const terminalManager = yield* TerminalManager;
const stopProviderSession = (threadId: ThreadDeletedEvent["payload"]["threadId"]) =>
logCleanupCauseUnlessInterrupted({
effect: providerService.stopSession({ threadId }),
message: "thread deletion cleanup skipped provider session stop",
threadId,
});
const closeThreadTerminals = (threadId: ThreadDeletedEvent["payload"]["threadId"]) =>
logCleanupCauseUnlessInterrupted({
effect: terminalManager.close({ threadId, deleteHistory: true }),
message: "thread deletion cleanup skipped terminal close",
threadId,
});
const processThreadDeleted = Effect.fn("processThreadDeleted")(function* (
event: ThreadDeletedEvent,
) {
const { threadId } = event.payload;
yield* stopProviderSession(threadId);
yield* closeThreadTerminals(threadId);
});
const processThreadDeletedSafely = (event: ThreadDeletedEvent) =>
processThreadDeleted(event).pipe(
Effect.catchCause((cause) => {
if (Cause.hasInterruptsOnly(cause)) {
return Effect.failCause(cause);
}
return Effect.logWarning("thread deletion reactor failed to process event", {
eventType: event.type,
threadId: event.payload.threadId,
cause: Cause.pretty(cause),
});
}),
);
const worker = yield* makeDrainableWorker(processThreadDeletedSafely);
const start: ThreadDeletionReactorShape["start"] = Effect.fn("start")(function* () {
yield* Effect.forkScoped(
Stream.runForEach(orchestrationEngine.streamDomainEvents, (event) => {
if (event.type !== "thread.deleted") {
return Effect.void;
}
return worker.enqueue(event);
}),
);
});
return {
start,
drain: worker.drain,
} satisfies ThreadDeletionReactorShape;
});
export const ThreadDeletionReactorLive = Layer.effect(ThreadDeletionReactor, make);
@@ -0,0 +1,37 @@
/**
* ThreadDeletionReactor - Thread deletion cleanup reactor service interface.
*
* Owns background workers that react to thread deletion domain events and
* perform best-effort runtime cleanup for provider sessions and terminals.
*
* @module ThreadDeletionReactor
*/
import { Context } from "effect";
import type { Effect, Scope } from "effect";
/**
* ThreadDeletionReactorShape - Service API for thread deletion cleanup.
*/
export interface ThreadDeletionReactorShape {
/**
* Start reacting to thread.deleted orchestration domain events.
*
* The returned effect must be run in a scope so all worker fibers can be
* finalized on shutdown.
*/
readonly start: () => Effect.Effect<void, never, Scope.Scope>;
/**
* Resolves when the internal processing queue is empty and idle.
* Intended for test use to replace timing-sensitive sleeps.
*/
readonly drain: Effect.Effect<void>;
}
/**
* ThreadDeletionReactor - Service tag for thread deletion cleanup workers.
*/
export class ThreadDeletionReactor extends Context.Service<
ThreadDeletionReactor,
ThreadDeletionReactorShape
>()("t3/orchestration/Services/ThreadDeletionReactor") {}
@@ -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,
@@ -0,0 +1,227 @@
import {
CommandId,
DEFAULT_PROVIDER_INTERACTION_MODE,
EventId,
ProjectId,
ThreadId,
type OrchestrationCommand,
type OrchestrationEvent,
type OrchestrationReadModel,
ProviderInstanceId,
} from "@t3tools/contracts";
import { Effect } from "effect";
import { describe, expect, it } from "vitest";
import { decideOrchestrationCommand } from "./decider.ts";
import { createEmptyReadModel, projectEvent } from "./projector.ts";
const asCommandId = (value: string): CommandId => CommandId.make(value);
const asEventId = (value: string): EventId => EventId.make(value);
const asProjectId = (value: string): ProjectId => ProjectId.make(value);
const asThreadId = (value: string): ThreadId => ThreadId.make(value);
async function seedReadModel(): Promise<OrchestrationReadModel> {
const now = new Date().toISOString();
const initial = createEmptyReadModel(now);
const withProject = await Effect.runPromise(
projectEvent(initial, {
sequence: 1,
eventId: asEventId("evt-project-create"),
aggregateKind: "project",
aggregateId: asProjectId("project-delete"),
type: "project.created",
occurredAt: now,
commandId: asCommandId("cmd-project-create"),
causationEventId: null,
correlationId: asCommandId("cmd-project-create"),
metadata: {},
payload: {
projectId: asProjectId("project-delete"),
title: "Project Delete",
workspaceRoot: "/tmp/project-delete",
defaultModelSelection: null,
scripts: [],
createdAt: now,
updatedAt: now,
},
}),
);
const withFirstThread = await Effect.runPromise(
projectEvent(withProject, {
sequence: 2,
eventId: asEventId("evt-thread-create-1"),
aggregateKind: "thread",
aggregateId: asThreadId("thread-delete-1"),
type: "thread.created",
occurredAt: now,
commandId: asCommandId("cmd-thread-create-1"),
causationEventId: null,
correlationId: asCommandId("cmd-thread-create-1"),
metadata: {},
payload: {
threadId: asThreadId("thread-delete-1"),
projectId: asProjectId("project-delete"),
title: "Thread Delete 1",
modelSelection: {
instanceId: ProviderInstanceId.make("codex"),
model: "gpt-5-codex",
},
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "approval-required",
branch: null,
worktreePath: null,
createdAt: now,
updatedAt: now,
},
}),
);
return Effect.runPromise(
projectEvent(withFirstThread, {
sequence: 3,
eventId: asEventId("evt-thread-create-2"),
aggregateKind: "thread",
aggregateId: asThreadId("thread-delete-2"),
type: "thread.created",
occurredAt: now,
commandId: asCommandId("cmd-thread-create-2"),
causationEventId: null,
correlationId: asCommandId("cmd-thread-create-2"),
metadata: {},
payload: {
threadId: asThreadId("thread-delete-2"),
projectId: asProjectId("project-delete"),
title: "Thread Delete 2",
modelSelection: {
instanceId: ProviderInstanceId.make("codex"),
model: "gpt-5-codex",
},
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "approval-required",
branch: null,
worktreePath: null,
createdAt: now,
updatedAt: now,
},
}),
);
}
type PlannedEvent = Omit<OrchestrationEvent, "sequence">;
function normalizeDeleteEvent(event: PlannedEvent | ReadonlyArray<PlannedEvent>) {
const events = Array.isArray(event) ? event : [event];
return events.map((entry) => {
switch (entry.type) {
case "thread.deleted":
return {
type: entry.type,
aggregateKind: entry.aggregateKind,
aggregateId: entry.aggregateId,
commandId: entry.commandId,
correlationId: entry.correlationId,
payload: {
threadId: entry.payload.threadId,
},
};
case "project.deleted":
return {
type: entry.type,
aggregateKind: entry.aggregateKind,
aggregateId: entry.aggregateId,
commandId: entry.commandId,
correlationId: entry.correlationId,
payload: {
projectId: entry.payload.projectId,
},
};
default:
return entry;
}
});
}
describe("decider deletion flows", () => {
it("rejects deleting a non-empty project without force", async () => {
const readModel = await seedReadModel();
await expect(
Effect.runPromise(
decideOrchestrationCommand({
command: {
type: "project.delete",
commandId: asCommandId("cmd-project-delete-no-force"),
projectId: asProjectId("project-delete"),
},
readModel,
}),
),
).rejects.toThrow("cannot be deleted without force=true");
});
it("reuses thread.delete semantics when force-deleting a non-empty project", async () => {
const readModel = await seedReadModel();
const projectDeleteCommand: Extract<OrchestrationCommand, { type: "project.delete" }> = {
type: "project.delete",
commandId: asCommandId("cmd-project-delete-force"),
projectId: asProjectId("project-delete"),
force: true,
};
const forcedResult = await Effect.runPromise(
decideOrchestrationCommand({
command: projectDeleteCommand,
readModel,
}),
);
const forcedEvents = Array.isArray(forcedResult) ? forcedResult : [forcedResult];
expect(forcedEvents.map((event) => event.type)).toEqual([
"thread.deleted",
"thread.deleted",
"project.deleted",
]);
let sequentialReadModel = readModel;
let nextSequence = readModel.snapshotSequence;
const sequentialEvents: PlannedEvent[] = [];
for (const nextCommand of [
{
type: "thread.delete",
commandId: projectDeleteCommand.commandId,
threadId: asThreadId("thread-delete-1"),
},
{
type: "thread.delete",
commandId: projectDeleteCommand.commandId,
threadId: asThreadId("thread-delete-2"),
},
{
type: "project.delete",
commandId: projectDeleteCommand.commandId,
projectId: asProjectId("project-delete"),
},
] satisfies ReadonlyArray<OrchestrationCommand>) {
const decided = await Effect.runPromise(
decideOrchestrationCommand({
command: nextCommand,
readModel: sequentialReadModel,
}),
);
const nextEvents = Array.isArray(decided) ? decided : [decided];
sequentialEvents.push(...nextEvents);
for (const nextEvent of nextEvents) {
nextSequence += 1;
sequentialReadModel = await Effect.runPromise(
projectEvent(sequentialReadModel, {
...nextEvent,
sequence: nextSequence,
}),
);
}
}
expect(normalizeDeleteEvent(forcedResult)).toEqual(normalizeDeleteEvent(sequentialEvents));
});
});
@@ -5,7 +5,9 @@ import {
MessageId,
ProjectId,
ThreadId,
ProviderInstanceId,
} from "@t3tools/contracts";
import { createModelSelection } from "@t3tools/shared/model";
import { describe, expect, it } from "vitest";
import { Effect } from "effect";
@@ -137,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,
@@ -162,14 +164,10 @@ describe("decider project scripts", () => {
text: "hello",
attachments: [],
},
modelSelection: {
provider: "codex",
model: "gpt-5.3-codex",
options: {
reasoningEffort: "high",
fastMode: true,
},
},
modelSelection: createModelSelection(ProviderInstanceId.make("codex"), "gpt-5.3-codex", [
{ id: "reasoningEffort", value: "high" },
{ id: "fastMode", value: true },
]),
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "approval-required",
createdAt: now,
@@ -191,14 +189,10 @@ describe("decider project scripts", () => {
expect(turnStartEvent.payload).toMatchObject({
threadId: ThreadId.make("thread-1"),
messageId: asMessageId("message-user-1"),
modelSelection: {
provider: "codex",
model: "gpt-5.3-codex",
options: {
reasoningEffort: "high",
fastMode: true,
},
},
modelSelection: createModelSelection(ProviderInstanceId.make("codex"), "gpt-5.3-codex", [
{ id: "reasoningEffort", value: "high" },
{ id: "fastMode", value: true },
]),
runtimeMode: "approval-required",
});
});
@@ -246,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,
@@ -328,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,
+69 -5
View File
@@ -7,6 +7,7 @@ import { Effect } from "effect";
import { OrchestrationCommandInvariantError } from "./Errors.ts";
import {
listThreadsByProjectId,
requireProject,
requireProjectAbsent,
requireThread,
@@ -14,6 +15,7 @@ import {
requireThreadAbsent,
requireThreadNotArchived,
} from "./commandInvariants.ts";
import { projectEvent } from "./projector.ts";
const nowIso = () => new Date().toISOString();
const defaultMetadata: Omit<OrchestrationEvent, "sequence" | "type" | "payload"> = {
@@ -47,16 +49,49 @@ function withEventBase(
};
}
type PlannedOrchestrationEvent = Omit<OrchestrationEvent, "sequence">;
type DecideOrchestrationCommandResult =
| PlannedOrchestrationEvent
| ReadonlyArray<PlannedOrchestrationEvent>;
const decideCommandSequence = Effect.fn("decideCommandSequence")(function* ({
commands,
readModel,
}: {
readonly commands: ReadonlyArray<OrchestrationCommand>;
readonly readModel: OrchestrationReadModel;
}): Effect.fn.Return<ReadonlyArray<PlannedOrchestrationEvent>, OrchestrationCommandInvariantError> {
let nextReadModel = readModel;
let nextSequence = readModel.snapshotSequence;
const plannedEvents: PlannedOrchestrationEvent[] = [];
for (const nextCommand of commands) {
const decided = yield* decideOrchestrationCommand({
command: nextCommand,
readModel: nextReadModel,
});
const nextEvents = Array.isArray(decided) ? decided : [decided];
for (const nextEvent of nextEvents) {
plannedEvents.push(nextEvent);
nextSequence += 1;
nextReadModel = yield* projectEvent(nextReadModel, {
...nextEvent,
sequence: nextSequence,
}).pipe(Effect.orDie);
}
}
return plannedEvents;
});
export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand")(function* ({
command,
readModel,
}: {
readonly command: OrchestrationCommand;
readonly readModel: OrchestrationReadModel;
}): Effect.fn.Return<
Omit<OrchestrationEvent, "sequence"> | ReadonlyArray<Omit<OrchestrationEvent, "sequence">>,
OrchestrationCommandInvariantError
> {
}): Effect.fn.Return<DecideOrchestrationCommandResult, OrchestrationCommandInvariantError> {
switch (command.type) {
case "project.create": {
yield* requireProjectAbsent({
@@ -119,6 +154,35 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
command,
projectId: command.projectId,
});
const activeThreads = listThreadsByProjectId(readModel, command.projectId).filter(
(thread) => thread.deletedAt === null,
);
if (activeThreads.length > 0 && command.force !== true) {
return yield* new OrchestrationCommandInvariantError({
commandType: command.type,
detail: `Project '${command.projectId}' is not empty and cannot be deleted without force=true.`,
});
}
if (activeThreads.length > 0) {
return yield* decideCommandSequence({
readModel,
commands: [
...activeThreads.map(
(thread): Extract<OrchestrationCommand, { type: "thread.delete" }> => ({
type: "thread.delete",
commandId: command.commandId,
threadId: thread.id,
}),
),
{
type: "project.delete",
commandId: command.commandId,
projectId: command.projectId,
},
],
});
}
const occurredAt = nowIso();
return {
...withEventBase({
@@ -127,7 +191,7 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
occurredAt,
commandId: command.commandId,
}),
type: "project.deleted",
type: "project.deleted" as const,
payload: {
projectId: command.projectId,
deletedAt: occurredAt,
+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",
+33
View File
@@ -0,0 +1,33 @@
import { homedir } from "node:os";
import { join } from "node:path";
import { describe, expect, it } from "vitest";
import { expandHomePath } from "./pathExpansion.ts";
describe("expandHomePath", () => {
it("returns an empty string unchanged", () => {
expect(expandHomePath("")).toBe("");
});
it("returns paths without a leading tilde unchanged", () => {
expect(expandHomePath("/absolute/path")).toBe("/absolute/path");
expect(expandHomePath("relative/path")).toBe("relative/path");
expect(expandHomePath("some~weird~path")).toBe("some~weird~path");
});
it("expands a lone tilde to the home directory", () => {
expect(expandHomePath("~")).toBe(homedir());
});
it("expands ~/ to a subpath of the home directory", () => {
expect(expandHomePath("~/.codex-work")).toBe(join(homedir(), ".codex-work"));
});
it("expands a Windows-style ~\\ prefix", () => {
expect(expandHomePath("~\\.codex")).toBe(join(homedir(), ".codex"));
});
it("does not expand ~user paths", () => {
expect(expandHomePath("~alice/foo")).toBe("~alice/foo");
});
});
+23
View File
@@ -0,0 +1,23 @@
import { homedir } from "node:os";
import { join } from "node:path";
/**
* Expand a leading `~` (or `~/…`, `~\…`) in a user-supplied path to the
* current user's home directory. Spawned processes don't get shell
* expansion, so env vars like `CODEX_HOME=~/.codex-work` would be passed
* verbatim and treated as relative paths by the receiver.
*
* Matches the behavior of the other `expandHomePath` helpers in the
* workspace layers and CLI bootstrap: `~` alone and both `~/` and `~\`
* separators are handled. Returns the input unchanged if it doesn't
* start with `~` or is empty. Does not handle `~user` (other-user)
* expansion.
*/
export function expandHomePath(value: string): string {
if (!value) return value;
if (value === "~") return homedir();
if (value.startsWith("~/") || value.startsWith("~\\")) {
return join(homedir(), value.slice(2));
}
return value;
}
@@ -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,
@@ -38,6 +38,9 @@ import Migration0022 from "./Migrations/022_AuthSessionLastConnectedAt.ts";
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.
@@ -75,6 +78,9 @@ export const migrationEntries = [
[23, "ProjectionThreadShellSummary", Migration0023],
[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,450 @@
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("026_CanonicalizeModelSelectionOptions", (it) => {
it.effect("converts legacy object-shape options into array-shape on projections and events", () =>
Effect.gen(function* () {
const sql = yield* SqlClient.SqlClient;
yield* runMigrations({ toMigrationInclusive: 25 });
yield* sql`
INSERT INTO projection_projects (
project_id,
title,
workspace_root,
default_model_selection_json,
scripts_json,
created_at,
updated_at,
deleted_at
)
VALUES
(
'project-legacy',
'Legacy options project',
'/tmp/legacy',
'{"provider":"claudeAgent","model":"claude-opus-4-6","options":{"effort":"max","fastMode":true}}',
'[]',
'2026-01-01T00:00:00.000Z',
'2026-01-01T00:00:00.000Z',
NULL
),
(
'project-no-options',
'No options project',
'/tmp/no-options',
'{"provider":"codex","model":"gpt-5.4"}',
'[]',
'2026-01-01T00:00:00.000Z',
'2026-01-01T00:00:00.000Z',
NULL
),
(
'project-null-selection',
'Null model selection project',
'/tmp/null-selection',
NULL,
'[]',
'2026-01-01T00:00:00.000Z',
'2026-01-01T00:00:00.000Z',
NULL
),
(
'project-already-array',
'Already-canonical options project',
'/tmp/already-array',
'{"provider":"codex","model":"gpt-5.4","options":[{"id":"reasoningEffort","value":"high"}]}',
'[]',
'2026-01-01T00:00:00.000Z',
'2026-01-01T00:00:00.000Z',
NULL
)
`;
yield* sql`
INSERT INTO projection_threads (
thread_id,
project_id,
title,
model_selection_json,
branch,
worktree_path,
latest_turn_id,
created_at,
updated_at,
archived_at,
latest_user_message_at,
pending_approval_count,
pending_user_input_count,
has_actionable_proposed_plan,
deleted_at,
runtime_mode,
interaction_mode
)
VALUES
(
'thread-legacy',
'project-legacy',
'Legacy thread',
'{"provider":"claudeAgent","model":"claude-opus-4-6","options":{"effort":"max","thinking":false,"contextWindow":"1m"}}',
NULL, NULL, NULL,
'2026-01-01T00:00:00.000Z',
'2026-01-01T00:00:00.000Z',
NULL, NULL, 0, 0, 0, NULL,
'full-access', 'default'
),
(
'thread-empty-options',
'project-legacy',
'Empty options thread',
'{"provider":"codex","model":"gpt-5.4","options":{}}',
NULL, NULL, NULL,
'2026-01-01T00:00:00.000Z',
'2026-01-01T00:00:00.000Z',
NULL, NULL, 0, 0, 0, NULL,
'full-access', 'default'
),
(
'thread-drop-garbage',
'project-legacy',
'Thread with non-scalar entries',
'{"provider":"claudeAgent","model":"claude-opus-4-6","options":{"effort":"high","thinking":{"enabled":true,"budgetTokens":2000},"emptyStr":" ","nullish":null}}',
NULL, NULL, NULL,
'2026-01-01T00:00:00.000Z',
'2026-01-01T00:00:00.000Z',
NULL, NULL, 0, 0, 0, NULL,
'full-access', 'default'
),
(
'thread-no-options',
'project-legacy',
'No options thread',
'{"provider":"codex","model":"gpt-5.4"}',
NULL, NULL, NULL,
'2026-01-01T00:00:00.000Z',
'2026-01-01T00:00:00.000Z',
NULL, NULL, 0, 0, 0, NULL,
'full-access', 'default'
),
(
'thread-already-array',
'project-legacy',
'Already array thread',
'{"provider":"codex","model":"gpt-5.4","options":[{"id":"fastMode","value":true}]}',
NULL, NULL, NULL,
'2026-01-01T00:00:00.000Z',
'2026-01-01T00:00:00.000Z',
NULL, NULL, 0, 0, 0, NULL,
'full-access', 'default'
)
`;
yield* sql`
INSERT INTO orchestration_events (
event_id,
aggregate_kind,
stream_id,
stream_version,
event_type,
occurred_at,
command_id,
causation_event_id,
correlation_id,
actor_kind,
payload_json,
metadata_json
)
VALUES
(
'event-project-created',
'project',
'project-legacy',
1,
'project.created',
'2026-01-01T00:00:00.000Z',
'cmd-pc',
NULL,
'corr-pc',
'user',
'{"projectId":"project-legacy","title":"Project","workspaceRoot":"/tmp/legacy","defaultModelSelection":{"provider":"claudeAgent","model":"claude-opus-4-6","options":{"effort":"max","fastMode":true}},"scripts":[],"createdAt":"2026-01-01T00:00:00.000Z","updatedAt":"2026-01-01T00:00:00.000Z"}',
'{}'
),
(
'event-project-meta-updated',
'project',
'project-legacy',
2,
'project.meta-updated',
'2026-01-01T00:00:00.000Z',
'cmd-pmu',
NULL,
'corr-pmu',
'user',
'{"projectId":"project-legacy","defaultModelSelection":{"provider":"codex","model":"gpt-5.4","options":{"reasoningEffort":"low"}},"updatedAt":"2026-01-01T00:00:00.000Z"}',
'{}'
),
(
'event-project-null-selection',
'project',
'project-legacy',
3,
'project.meta-updated',
'2026-01-01T00:00:00.000Z',
'cmd-null',
NULL,
'corr-null',
'user',
'{"projectId":"project-legacy","defaultModelSelection":null,"updatedAt":"2026-01-01T00:00:00.000Z"}',
'{}'
),
(
'event-thread-created',
'thread',
'thread-legacy',
1,
'thread.created',
'2026-01-01T00:00:00.000Z',
'cmd-tc',
NULL,
'corr-tc',
'user',
'{"threadId":"thread-legacy","projectId":"project-legacy","title":"Thread","modelSelection":{"provider":"claudeAgent","model":"claude-opus-4-6","options":{"effort":"max","thinking":false}},"runtimeMode":"full-access","interactionMode":"default","branch":null,"worktreePath":null,"createdAt":"2026-01-01T00:00:00.000Z","updatedAt":"2026-01-01T00:00:00.000Z"}',
'{}'
),
(
'event-thread-meta-updated',
'thread',
'thread-legacy',
2,
'thread.meta-updated',
'2026-01-01T00:00:00.000Z',
'cmd-tmu',
NULL,
'corr-tmu',
'user',
'{"threadId":"thread-legacy","modelSelection":{"provider":"codex","model":"gpt-5.4","options":{"fastMode":true}},"updatedAt":"2026-01-01T00:00:00.000Z"}',
'{}'
),
(
'event-thread-turn-start',
'thread',
'thread-legacy',
3,
'thread.turn-start-requested',
'2026-01-01T00:00:00.000Z',
'cmd-tts',
NULL,
'corr-tts',
'user',
'{"threadId":"thread-legacy","messageId":"msg-1","modelSelection":{"provider":"claudeAgent","model":"claude-opus-4-6","options":{"effort":"high","contextWindow":"1m"}},"runtimeMode":"full-access","interactionMode":"default","createdAt":"2026-01-01T00:00:00.000Z"}',
'{}'
),
(
'event-thread-already-array',
'thread',
'thread-legacy',
4,
'thread.created',
'2026-01-01T00:00:00.000Z',
'cmd-taa',
NULL,
'corr-taa',
'user',
'{"threadId":"thread-already-array","projectId":"project-legacy","title":"Already Array","modelSelection":{"provider":"codex","model":"gpt-5.4","options":[{"id":"reasoningEffort","value":"medium"}]},"runtimeMode":"full-access","interactionMode":"default","branch":null,"worktreePath":null,"createdAt":"2026-01-01T00:00:00.000Z","updatedAt":"2026-01-01T00:00:00.000Z"}',
'{}'
),
(
'event-activity-append',
'thread',
'thread-legacy',
5,
'thread.activity-appended',
'2026-01-01T00:00:00.000Z',
'cmd-aa',
NULL,
'corr-aa',
'user',
'{"threadId":"thread-legacy","activity":{"id":"a","tone":"info","kind":"k","summary":"s","payload":null,"turnId":null,"createdAt":"2026-01-01T00:00:00.000Z"}}',
'{}'
)
`;
yield* runMigrations({ toMigrationInclusive: 26 });
// Projection projects
const projectRows = yield* sql<{
readonly projectId: string;
readonly defaultModelSelection: string | null;
}>`
SELECT
project_id AS "projectId",
default_model_selection_json AS "defaultModelSelection"
FROM projection_projects
ORDER BY project_id
`;
assert.deepStrictEqual(
projectRows.map((row) => ({
projectId: row.projectId,
selection: row.defaultModelSelection ? JSON.parse(row.defaultModelSelection) : null,
})),
[
{
projectId: "project-already-array",
selection: {
provider: "codex",
model: "gpt-5.4",
options: [{ id: "reasoningEffort", value: "high" }],
},
},
{
projectId: "project-legacy",
selection: {
provider: "claudeAgent",
model: "claude-opus-4-6",
options: [
{ id: "effort", value: "max" },
{ id: "fastMode", value: true },
],
},
},
{
projectId: "project-no-options",
selection: { provider: "codex", model: "gpt-5.4" },
},
{ projectId: "project-null-selection", selection: null },
],
);
// Projection threads
const threadRows = yield* sql<{
readonly threadId: string;
readonly modelSelection: string | null;
}>`
SELECT
thread_id AS "threadId",
model_selection_json AS "modelSelection"
FROM projection_threads
ORDER BY thread_id
`;
assert.deepStrictEqual(
threadRows.map((row) => ({
threadId: row.threadId,
selection: row.modelSelection ? JSON.parse(row.modelSelection) : null,
})),
[
{
threadId: "thread-already-array",
selection: {
provider: "codex",
model: "gpt-5.4",
options: [{ id: "fastMode", value: true }],
},
},
{
threadId: "thread-drop-garbage",
selection: {
provider: "claudeAgent",
model: "claude-opus-4-6",
// Only the scalar string survives; nested object, whitespace
// string, and null are dropped.
options: [{ id: "effort", value: "high" }],
},
},
{
threadId: "thread-empty-options",
selection: { provider: "codex", model: "gpt-5.4", options: [] },
},
{
threadId: "thread-legacy",
selection: {
provider: "claudeAgent",
model: "claude-opus-4-6",
options: [
{ id: "effort", value: "max" },
{ id: "thinking", value: false },
{ id: "contextWindow", value: "1m" },
],
},
},
{
threadId: "thread-no-options",
selection: { provider: "codex", model: "gpt-5.4" },
},
],
);
// Orchestration events
const eventRows = yield* sql<{
readonly eventId: string;
readonly payloadJson: string;
}>`
SELECT event_id AS "eventId", payload_json AS "payloadJson"
FROM orchestration_events
ORDER BY event_id
`;
const payloads = Object.fromEntries(
eventRows.map((row) => [row.eventId, JSON.parse(row.payloadJson)]),
);
assert.deepStrictEqual(payloads["event-project-created"].defaultModelSelection, {
provider: "claudeAgent",
model: "claude-opus-4-6",
options: [
{ id: "effort", value: "max" },
{ id: "fastMode", value: true },
],
});
assert.deepStrictEqual(payloads["event-project-meta-updated"].defaultModelSelection, {
provider: "codex",
model: "gpt-5.4",
options: [{ id: "reasoningEffort", value: "low" }],
});
assert.strictEqual(payloads["event-project-null-selection"].defaultModelSelection, null);
assert.deepStrictEqual(payloads["event-thread-created"].modelSelection, {
provider: "claudeAgent",
model: "claude-opus-4-6",
options: [
{ id: "effort", value: "max" },
{ id: "thinking", value: false },
],
});
assert.deepStrictEqual(payloads["event-thread-meta-updated"].modelSelection, {
provider: "codex",
model: "gpt-5.4",
options: [{ id: "fastMode", value: true }],
});
assert.deepStrictEqual(payloads["event-thread-turn-start"].modelSelection, {
provider: "claudeAgent",
model: "claude-opus-4-6",
options: [
{ id: "effort", value: "high" },
{ id: "contextWindow", value: "1m" },
],
});
// Already-array records are left untouched.
assert.deepStrictEqual(payloads["event-thread-already-array"].modelSelection, {
provider: "codex",
model: "gpt-5.4",
options: [{ id: "reasoningEffort", value: "medium" }],
});
// Events with no modelSelection at all are untouched.
assert.isUndefined(payloads["event-activity-append"].modelSelection);
assert.isUndefined(payloads["event-activity-append"].defaultModelSelection);
}),
);
});
@@ -0,0 +1,138 @@
import * as Effect from "effect/Effect";
import * as SqlClient from "effect/unstable/sql/SqlClient";
/**
* Canonicalize `modelSelection.options` / `defaultModelSelection.options` from
* the legacy object shape (`{ effort: "max", fastMode: true, ... }`) to the
* current array-of-selections shape (`[{ id: "effort", value: "max" }, ...]`).
*
* Migration 016 introduced `modelSelection` with `options` stored as a
* per-provider object. Later the schema was reshaped so that options are a
* generic `Array<{ id, value }>` of user-selected option entries. Stored rows
* from before the reshape still have the object shape and fail to decode.
*
* For each value in the legacy object:
* - string values are kept if non-empty after trim
* - boolean values are always kept (true | false)
* - any other value type (number, null, nested object/array) is dropped,
* matching the permissive client-side normalizer in composerDraftStore.
*
* Touched storage:
* - `projection_threads.model_selection_json.options`
* - `projection_projects.default_model_selection_json.options`
* - `orchestration_events.payload_json.$.modelSelection.options`
* (thread.created | thread.meta-updated | thread.turn-start-requested)
* - `orchestration_events.payload_json.$.defaultModelSelection.options`
* (project.created | project.meta-updated)
*/
export default Effect.gen(function* () {
const sql = yield* SqlClient.SqlClient;
yield* sql`
UPDATE projection_threads
SET model_selection_json = json_set(
model_selection_json,
'$.options',
(
SELECT json_group_array(
json_object(
'id', key,
'value',
CASE type
WHEN 'true' THEN json('true')
WHEN 'false' THEN json('false')
ELSE atom
END
)
)
FROM json_each(json_extract(model_selection_json, '$.options'))
WHERE (type = 'text' AND trim(coalesce(atom, '')) != '')
OR type IN ('true', 'false')
)
)
WHERE model_selection_json IS NOT NULL
AND json_type(model_selection_json, '$.options') = 'object'
`;
yield* sql`
UPDATE projection_projects
SET default_model_selection_json = json_set(
default_model_selection_json,
'$.options',
(
SELECT json_group_array(
json_object(
'id', key,
'value',
CASE type
WHEN 'true' THEN json('true')
WHEN 'false' THEN json('false')
ELSE atom
END
)
)
FROM json_each(json_extract(default_model_selection_json, '$.options'))
WHERE (type = 'text' AND trim(coalesce(atom, '')) != '')
OR type IN ('true', 'false')
)
)
WHERE default_model_selection_json IS NOT NULL
AND json_type(default_model_selection_json, '$.options') = 'object'
`;
yield* sql`
UPDATE orchestration_events
SET payload_json = json_set(
payload_json,
'$.modelSelection.options',
(
SELECT json_group_array(
json_object(
'id', key,
'value',
CASE type
WHEN 'true' THEN json('true')
WHEN 'false' THEN json('false')
ELSE atom
END
)
)
FROM json_each(json_extract(payload_json, '$.modelSelection.options'))
WHERE (type = 'text' AND trim(coalesce(atom, '')) != '')
OR type IN ('true', 'false')
)
)
WHERE event_type IN (
'thread.created',
'thread.meta-updated',
'thread.turn-start-requested'
)
AND json_type(payload_json, '$.modelSelection.options') = 'object'
`;
yield* sql`
UPDATE orchestration_events
SET payload_json = json_set(
payload_json,
'$.defaultModelSelection.options',
(
SELECT json_group_array(
json_object(
'id', key,
'value',
CASE type
WHEN 'true' THEN json('true')
WHEN 'false' THEN json('false')
ELSE atom
END
)
)
FROM json_each(json_extract(payload_json, '$.defaultModelSelection.options'))
WHERE (type = 'text' AND trim(coalesce(atom, '')) != '')
OR type IN ('true', 'false')
)
)
WHERE event_type IN ('project.created', 'project.meta-updated')
AND json_type(payload_json, '$.defaultModelSelection.options') = 'object'
`;
});
@@ -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,
+19 -1
View File
@@ -1,6 +1,6 @@
import { describe, expect, it } from "vitest";
import { runProcess } from "./processRunner.ts";
import { isWindowsCommandNotFound, runProcess } from "./processRunner.ts";
describe("runProcess", () => {
it("fails when output exceeds max buffer in default mode", async () => {
@@ -21,3 +21,21 @@ describe("runProcess", () => {
expect(result.stderrTruncated).toBe(false);
});
});
describe("isWindowsCommandNotFound", () => {
it("matches the localized German cmd.exe error text", () => {
const originalPlatform = process.platform;
Object.defineProperty(process, "platform", { value: "win32", configurable: true });
try {
expect(
isWindowsCommandNotFound(
1,
"wird nicht als interner oder externer Befehl, betriebsfahiges Programm oder Batch-Datei erkannt",
),
).toBe(true);
} finally {
Object.defineProperty(process, "platform", { value: originalPlatform, configurable: true });
}
});
});
+14 -1
View File
@@ -37,10 +37,23 @@ function normalizeSpawnError(command: string, args: readonly string[], error: un
return new Error(`Failed to run ${commandLabel(command, args)}: ${error.message}`);
}
const WINDOWS_COMMAND_NOT_FOUND_PATTERNS = [
/is not recognized as an internal or external command/i,
/n.o . reconhecido como um comando interno/i,
/non . riconosciuto come comando interno o esterno/i,
/n.est pas reconnu en tant que commande interne/i,
/no se reconoce como un comando interno o externo/i,
/wird nicht als interner oder externer befehl/i,
] as const;
function hasWindowsCommandNotFoundMessage(output: string): boolean {
return WINDOWS_COMMAND_NOT_FOUND_PATTERNS.some((pattern) => pattern.test(output));
}
export function isWindowsCommandNotFound(code: number | null, stderr: string): boolean {
if (process.platform !== "win32") return false;
if (code === 9009) return true;
return /is not recognized as an internal or external command/i.test(stderr);
return hasWindowsCommandNotFoundMessage(stderr);
}
function normalizeExitError(
@@ -27,6 +27,7 @@ const FAVICON_CANDIDATES = [
"assets/icon.png",
"assets/logo.svg",
"assets/logo.png",
".idea/icon.svg",
] as const;
// Files that may contain a <link rel="icon"> or icon metadata declaration.
@@ -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,134 @@
export const CODEX_PLAN_MODE_DEVELOPER_INSTRUCTIONS = `<collaboration_mode># Plan Mode (Conversational)
You work in 3 phases, and you should *chat your way* to a great plan before finalizing it. A great plan is very detailed-intent- and implementation-wise-so that it can be handed to another engineer or agent to be implemented right away. It must be **decision complete**, where the implementer does not need to make any decisions.
## Mode rules (strict)
You are in **Plan Mode** until a developer message explicitly ends it.
Plan Mode is not changed by user intent, tone, or imperative language. If a user asks for execution while still in Plan Mode, treat it as a request to **plan the execution**, not perform it.
## Plan Mode vs update_plan tool
Plan Mode is a collaboration mode that can involve requesting user input and eventually issuing a \`<proposed_plan>\` block.
Separately, \`update_plan\` is a checklist/progress/TODOs tool; it does not enter or exit Plan Mode. Do not confuse it with Plan mode or try to use it while in Plan mode. If you try to use \`update_plan\` in Plan mode, it will return an error.
## Execution vs. mutation in Plan Mode
You may explore and execute **non-mutating** actions that improve the plan. You must not perform **mutating** actions.
### Allowed (non-mutating, plan-improving)
Actions that gather truth, reduce ambiguity, or validate feasibility without changing repo-tracked state. Examples:
* Reading or searching files, configs, schemas, types, manifests, and docs
* Static analysis, inspection, and repo exploration
* Dry-run style commands when they do not edit repo-tracked files
* Tests, builds, or checks that may write to caches or build artifacts (for example, \`target/\`, \`.cache/\`, or snapshots) so long as they do not edit repo-tracked files
### Not allowed (mutating, plan-executing)
Actions that implement the plan or change repo-tracked state. Examples:
* Editing or writing files
* Running formatters or linters that rewrite files
* Applying patches, migrations, or codegen that updates repo-tracked files
* Side-effectful commands whose purpose is to carry out the plan rather than refine it
When in doubt: if the action would reasonably be described as "doing the work" rather than "planning the work," do not do it.
## PHASE 1 - Ground in the environment (explore first, ask second)
Begin by grounding yourself in the actual environment. Eliminate unknowns in the prompt by discovering facts, not by asking the user. Resolve all questions that can be answered through exploration or inspection. Identify missing or ambiguous details only if they cannot be derived from the environment. Silent exploration between turns is allowed and encouraged.
Before asking the user any question, perform at least one targeted non-mutating exploration pass (for example: search relevant files, inspect likely entrypoints/configs, confirm current implementation shape), unless no local environment/repo is available.
Exception: you may ask clarifying questions about the user's prompt before exploring, ONLY if there are obvious ambiguities or contradictions in the prompt itself. However, if ambiguity might be resolved by exploring, always prefer exploring first.
Do not ask questions that can be answered from the repo or system (for example, "where is this struct?" or "which UI component should we use?" when exploration can make it clear). Only ask once you have exhausted reasonable non-mutating exploration.
## PHASE 2 - Intent chat (what they actually want)
* Keep asking until you can clearly state: goal + success criteria, audience, in/out of scope, constraints, current state, and the key preferences/tradeoffs.
* Bias toward questions over guessing: if any high-impact ambiguity remains, do NOT plan yet-ask.
## PHASE 3 - Implementation chat (what/how we'll build)
* Once intent is stable, keep asking until the spec is decision complete: approach, interfaces (APIs/schemas/I/O), data flow, edge cases/failure modes, testing + acceptance criteria, rollout/monitoring, and any migrations/compat constraints.
## Asking questions
Critical rules:
* Strongly prefer using the \`request_user_input\` tool to ask any questions.
* Offer only meaningful multiple-choice options; don't include filler choices that are obviously wrong or irrelevant.
* In rare cases where an unavoidable, important question can't be expressed with reasonable multiple-choice options (due to extreme ambiguity), you may ask it directly without the tool.
You SHOULD ask many questions, but each question must:
* materially change the spec/plan, OR
* confirm/lock an assumption, OR
* choose between meaningful tradeoffs.
* not be answerable by non-mutating commands.
Use the \`request_user_input\` tool only for decisions that materially change the plan, for confirming important assumptions, or for information that cannot be discovered via non-mutating exploration.
## Two kinds of unknowns (treat differently)
1. **Discoverable facts** (repo/system truth): explore first.
* Before asking, run targeted searches and check likely sources of truth (configs/manifests/entrypoints/schemas/types/constants).
* Ask only if: multiple plausible candidates; nothing found but you need a missing identifier/context; or ambiguity is actually product intent.
* If asking, present concrete candidates (paths/service names) + recommend one.
* Never ask questions you can answer from your environment (e.g., "where is this struct").
2. **Preferences/tradeoffs** (not discoverable): ask early.
* These are intent or implementation preferences that cannot be derived from exploration.
* Provide 2-4 mutually exclusive options + a recommended default.
* If unanswered, proceed with the recommended option and record it as an assumption in the final plan.
## Finalization rule
Only output the final plan when it is decision complete and leaves no decisions to the implementer.
When you present the official plan, wrap it in a \`<proposed_plan>\` block so the client can render it specially:
1) The opening tag must be on its own line.
2) Start the plan content on the next line (no text on the same line as the tag).
3) The closing tag must be on its own line.
4) Use Markdown inside the block.
5) Keep the tags exactly as \`<proposed_plan>\` and \`</proposed_plan>\` (do not translate or rename them), even if the plan content is in another language.
Example:
<proposed_plan>
plan content
</proposed_plan>
plan content should be human and agent digestible. The final plan must be plan-only and include:
* A clear title
* A brief summary section
* Important changes or additions to public APIs/interfaces/types
* Test cases and scenarios
* Explicit assumptions and defaults chosen where needed
Do not ask "should I proceed?" in the final output. The user can easily switch out of Plan mode and request implementation if you have included a \`<proposed_plan>\` block in your response. Alternatively, they can decide to stay in Plan mode and continue refining the plan.
Only produce at most one \`<proposed_plan>\` block per turn, and only when you are presenting a complete spec.
</collaboration_mode>`;
export const CODEX_DEFAULT_MODE_DEVELOPER_INSTRUCTIONS = `<collaboration_mode># Collaboration Mode: Default
You are now in Default mode. Any previous instructions for other modes (e.g. Plan mode) are no longer active.
Your active mode changes only when new developer instructions with a different \`<collaboration_mode>...</collaboration_mode>\` change it; user requests or tool descriptions do not change mode by themselves. Known mode names are Default and Plan.
## request_user_input availability
The \`request_user_input\` tool is unavailable in Default mode. If you call it while in Default mode, it will return an error.
In Default mode, strongly prefer making reasonable assumptions and executing the user's request rather than stopping to ask questions. If you absolutely must ask a question because the answer cannot be discovered from local context and a reasonable assumption would be risky, ask the user directly with a concise plain-text question. Never write a multiple choice question as a textual assistant message.
</collaboration_mode>`;
@@ -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,20 +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> = [];
@@ -136,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:
@@ -146,6 +157,7 @@ function makeHarness(config?: {
| undefined;
const adapterOptions: ClaudeAdapterLiveOptions = {
...(config?.instanceId ? { instanceId: config.instanceId } : {}),
createQuery: (input) => {
createInput = input;
return query;
@@ -163,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",
@@ -246,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");
@@ -256,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'.",
}),
@@ -273,7 +295,7 @@ describe("ClaudeAdapterLive", () => {
const adapter = yield* ClaudeAdapter;
yield* adapter.startSession({
threadId: THREAD_ID,
provider: "claudeAgent",
provider: ProviderDriverKind.make("claudeAgent"),
runtimeMode: "full-access",
});
@@ -293,7 +315,7 @@ describe("ClaudeAdapterLive", () => {
const adapter = yield* ClaudeAdapter;
yield* adapter.startSession({
threadId: THREAD_ID,
provider: "claudeAgent",
provider: ProviderDriverKind.make("claudeAgent"),
runtimeMode: "approval-required",
});
@@ -313,7 +335,7 @@ describe("ClaudeAdapterLive", () => {
const adapter = yield* ClaudeAdapter;
yield* adapter.startSession({
threadId: THREAD_ID,
provider: "claudeAgent",
provider: ProviderDriverKind.make("claudeAgent"),
runtimeMode: "full-access",
});
@@ -332,14 +354,12 @@ describe("ClaudeAdapterLive", () => {
const adapter = yield* ClaudeAdapter;
yield* adapter.startSession({
threadId: THREAD_ID,
provider: "claudeAgent",
modelSelection: {
provider: "claudeAgent",
model: "claude-opus-4-6",
options: {
effort: "max",
},
},
provider: ProviderDriverKind.make("claudeAgent"),
modelSelection: createModelSelection(
ProviderInstanceId.make("claudeAgent"),
"claude-opus-4-6",
[{ id: "effort", value: "max" }],
),
runtimeMode: "full-access",
});
@@ -351,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",
@@ -379,14 +421,12 @@ describe("ClaudeAdapterLive", () => {
const adapter = yield* ClaudeAdapter;
yield* adapter.startSession({
threadId: THREAD_ID,
provider: "claudeAgent",
modelSelection: {
provider: "claudeAgent",
model: "claude-opus-4-7",
options: {
effort: "xhigh",
},
},
provider: ProviderDriverKind.make("claudeAgent"),
modelSelection: createModelSelection(
ProviderInstanceId.make("claudeAgent"),
"claude-opus-4-7",
[{ id: "effort", value: "xhigh" }],
),
runtimeMode: "full-access",
});
@@ -404,14 +444,12 @@ describe("ClaudeAdapterLive", () => {
const adapter = yield* ClaudeAdapter;
yield* adapter.startSession({
threadId: THREAD_ID,
provider: "claudeAgent",
modelSelection: {
provider: "claudeAgent",
model: "claude-sonnet-4-6",
options: {
effort: "max",
},
},
provider: ProviderDriverKind.make("claudeAgent"),
modelSelection: createModelSelection(
ProviderInstanceId.make("claudeAgent"),
"claude-sonnet-4-6",
[{ id: "effort", value: "max" }],
),
runtimeMode: "full-access",
});
@@ -429,14 +467,12 @@ describe("ClaudeAdapterLive", () => {
const adapter = yield* ClaudeAdapter;
yield* adapter.startSession({
threadId: THREAD_ID,
provider: "claudeAgent",
modelSelection: {
provider: "claudeAgent",
model: "claude-haiku-4-5",
options: {
effort: "high",
},
},
provider: ProviderDriverKind.make("claudeAgent"),
modelSelection: createModelSelection(
ProviderInstanceId.make("claudeAgent"),
"claude-haiku-4-5",
[{ id: "effort", value: "high" }],
),
runtimeMode: "full-access",
});
@@ -454,14 +490,12 @@ describe("ClaudeAdapterLive", () => {
const adapter = yield* ClaudeAdapter;
yield* adapter.startSession({
threadId: THREAD_ID,
provider: "claudeAgent",
modelSelection: {
provider: "claudeAgent",
model: "claude-haiku-4-5",
options: {
thinking: false,
},
},
provider: ProviderDriverKind.make("claudeAgent"),
modelSelection: createModelSelection(
ProviderInstanceId.make("claudeAgent"),
"claude-haiku-4-5",
[{ id: "thinking", value: false }],
),
runtimeMode: "full-access",
});
@@ -481,14 +515,12 @@ describe("ClaudeAdapterLive", () => {
const adapter = yield* ClaudeAdapter;
yield* adapter.startSession({
threadId: THREAD_ID,
provider: "claudeAgent",
modelSelection: {
provider: "claudeAgent",
model: "claude-sonnet-4-6",
options: {
thinking: false,
},
},
provider: ProviderDriverKind.make("claudeAgent"),
modelSelection: createModelSelection(
ProviderInstanceId.make("claudeAgent"),
"claude-sonnet-4-6",
[{ id: "thinking", value: false }],
),
runtimeMode: "full-access",
});
@@ -506,14 +538,12 @@ describe("ClaudeAdapterLive", () => {
const adapter = yield* ClaudeAdapter;
yield* adapter.startSession({
threadId: THREAD_ID,
provider: "claudeAgent",
modelSelection: {
provider: "claudeAgent",
model: "claude-opus-4-6",
options: {
fastMode: true,
},
},
provider: ProviderDriverKind.make("claudeAgent"),
modelSelection: createModelSelection(
ProviderInstanceId.make("claudeAgent"),
"claude-opus-4-6",
[{ id: "fastMode", value: true }],
),
runtimeMode: "full-access",
});
@@ -533,14 +563,12 @@ describe("ClaudeAdapterLive", () => {
const adapter = yield* ClaudeAdapter;
yield* adapter.startSession({
threadId: THREAD_ID,
provider: "claudeAgent",
modelSelection: {
provider: "claudeAgent",
model: "claude-sonnet-4-6",
options: {
fastMode: true,
},
},
provider: ProviderDriverKind.make("claudeAgent"),
modelSelection: createModelSelection(
ProviderInstanceId.make("claudeAgent"),
"claude-sonnet-4-6",
[{ id: "fastMode", value: true }],
),
runtimeMode: "full-access",
});
@@ -558,14 +586,12 @@ describe("ClaudeAdapterLive", () => {
const adapter = yield* ClaudeAdapter;
const session = yield* adapter.startSession({
threadId: THREAD_ID,
provider: "claudeAgent",
modelSelection: {
provider: "claudeAgent",
model: "claude-sonnet-4-6",
options: {
effort: "ultrathink",
},
},
provider: ProviderDriverKind.make("claudeAgent"),
modelSelection: createModelSelection(
ProviderInstanceId.make("claudeAgent"),
"claude-sonnet-4-6",
[{ id: "effort", value: "ultrathink" }],
),
runtimeMode: "full-access",
});
@@ -573,13 +599,11 @@ describe("ClaudeAdapterLive", () => {
threadId: session.threadId,
input: "Investigate the edge cases",
attachments: [],
modelSelection: {
provider: "claudeAgent",
model: "claude-sonnet-4-6",
options: {
effort: "ultrathink",
},
},
modelSelection: createModelSelection(
ProviderInstanceId.make("claudeAgent"),
"claude-sonnet-4-6",
[{ id: "effort", value: "ultrathink" }],
),
});
const createInput = harness.getLastCreateQueryInput();
@@ -624,7 +648,7 @@ describe("ClaudeAdapterLive", () => {
const session = yield* adapter.startSession({
threadId: THREAD_ID,
provider: "claudeAgent",
provider: ProviderDriverKind.make("claudeAgent"),
runtimeMode: "full-access",
});
@@ -669,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",
@@ -846,7 +870,7 @@ describe("ClaudeAdapterLive", () => {
const session = yield* adapter.startSession({
threadId: THREAD_ID,
provider: "claudeAgent",
provider: ProviderDriverKind.make("claudeAgent"),
runtimeMode: "full-access",
});
@@ -1025,7 +1049,7 @@ describe("ClaudeAdapterLive", () => {
const session = yield* adapter.startSession({
threadId: THREAD_ID,
provider: "claudeAgent",
provider: ProviderDriverKind.make("claudeAgent"),
runtimeMode: "full-access",
});
@@ -1116,7 +1140,7 @@ describe("ClaudeAdapterLive", () => {
const session = yield* adapter.startSession({
threadId: THREAD_ID,
provider: "claudeAgent",
provider: ProviderDriverKind.make("claudeAgent"),
runtimeMode: "full-access",
});
@@ -1192,7 +1216,7 @@ describe("ClaudeAdapterLive", () => {
const session = yield* adapter.startSession({
threadId: THREAD_ID,
provider: "claudeAgent",
provider: ProviderDriverKind.make("claudeAgent"),
runtimeMode: "full-access",
});
@@ -1258,7 +1282,7 @@ describe("ClaudeAdapterLive", () => {
yield* adapter.startSession({
threadId: THREAD_ID,
provider: "claudeAgent",
provider: ProviderDriverKind.make("claudeAgent"),
runtimeMode: "full-access",
});
@@ -1309,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),
@@ -1331,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,
});
@@ -1386,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),
@@ -1418,7 +1454,7 @@ describe("ClaudeAdapterLive", () => {
yield* adapter.startSession({
threadId: THREAD_ID,
provider: "claudeAgent",
provider: ProviderDriverKind.make("claudeAgent"),
runtimeMode: "full-access",
});
@@ -1455,7 +1491,7 @@ describe("ClaudeAdapterLive", () => {
yield* adapter.startSession({
threadId: THREAD_ID,
provider: "claudeAgent",
provider: ProviderDriverKind.make("claudeAgent"),
runtimeMode: "full-access",
});
@@ -1502,7 +1538,7 @@ describe("ClaudeAdapterLive", () => {
yield* adapter.startSession({
threadId: THREAD_ID,
provider: "claudeAgent",
provider: ProviderDriverKind.make("claudeAgent"),
runtimeMode: "full-access",
});
@@ -1556,7 +1592,7 @@ describe("ClaudeAdapterLive", () => {
yield* adapter.startSession({
threadId: THREAD_ID,
provider: "claudeAgent",
provider: ProviderDriverKind.make("claudeAgent"),
runtimeMode: "full-access",
});
@@ -1623,7 +1659,7 @@ describe("ClaudeAdapterLive", () => {
yield* adapter.startSession({
threadId: THREAD_ID,
provider: "claudeAgent",
provider: ProviderDriverKind.make("claudeAgent"),
runtimeMode: "full-access",
});
@@ -1688,7 +1724,7 @@ describe("ClaudeAdapterLive", () => {
yield* adapter.startSession({
threadId: THREAD_ID,
provider: "claudeAgent",
provider: ProviderDriverKind.make("claudeAgent"),
runtimeMode: "full-access",
});
@@ -1769,7 +1805,7 @@ describe("ClaudeAdapterLive", () => {
const session = yield* adapter.startSession({
threadId: THREAD_ID,
provider: "claudeAgent",
provider: ProviderDriverKind.make("claudeAgent"),
runtimeMode: "full-access",
});
@@ -1860,7 +1896,7 @@ describe("ClaudeAdapterLive", () => {
const session = yield* adapter.startSession({
threadId: THREAD_ID,
provider: "claudeAgent",
provider: ProviderDriverKind.make("claudeAgent"),
runtimeMode: "full-access",
});
@@ -2026,7 +2062,7 @@ describe("ClaudeAdapterLive", () => {
const session = yield* adapter.startSession({
threadId: THREAD_ID,
provider: "claudeAgent",
provider: ProviderDriverKind.make("claudeAgent"),
runtimeMode: "full-access",
});
@@ -2095,7 +2131,7 @@ describe("ClaudeAdapterLive", () => {
const session = yield* adapter.startSession({
threadId: THREAD_ID,
provider: "claudeAgent",
provider: ProviderDriverKind.make("claudeAgent"),
runtimeMode: "full-access",
});
@@ -2317,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);
@@ -2390,7 +2426,7 @@ describe("ClaudeAdapterLive", () => {
const session = yield* adapter.startSession({
threadId: THREAD_ID,
provider: "claudeAgent",
provider: ProviderDriverKind.make("claudeAgent"),
runtimeMode: "approval-required",
});
@@ -2499,7 +2535,7 @@ describe("ClaudeAdapterLive", () => {
const session = yield* adapter.startSession({
threadId: THREAD_ID,
provider: "claudeAgent",
provider: ProviderDriverKind.make("claudeAgent"),
runtimeMode: "approval-required",
});
@@ -2572,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",
@@ -2600,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* () {
@@ -2607,7 +2733,7 @@ describe("ClaudeAdapterLive", () => {
const session = yield* adapter.startSession({
threadId: THREAD_ID,
provider: "claudeAgent",
provider: ProviderDriverKind.make("claudeAgent"),
runtimeMode: "full-access",
});
@@ -2641,7 +2767,7 @@ describe("ClaudeAdapterLive", () => {
const session = yield* adapter.startSession({
threadId: THREAD_ID,
provider: "claudeAgent",
provider: ProviderDriverKind.make("claudeAgent"),
runtimeMode: "full-access",
});
@@ -2721,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: [],
@@ -2741,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",
() => {
@@ -2748,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",
});
@@ -2787,27 +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: {
provider: "claudeAgent",
model: "claude-opus-4-6",
options: {
contextWindow: "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: [],
@@ -2827,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({
@@ -2857,7 +3009,7 @@ describe("ClaudeAdapterLive", () => {
const session = yield* adapter.startSession({
threadId: THREAD_ID,
provider: "claudeAgent",
provider: ProviderDriverKind.make("claudeAgent"),
runtimeMode,
});
@@ -2909,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({
@@ -2932,7 +3084,7 @@ describe("ClaudeAdapterLive", () => {
const session = yield* adapter.startSession({
threadId: THREAD_ID,
provider: "claudeAgent",
provider: ProviderDriverKind.make("claudeAgent"),
runtimeMode: "full-access",
});
@@ -2998,7 +3150,7 @@ describe("ClaudeAdapterLive", () => {
const session = yield* adapter.startSession({
threadId: THREAD_ID,
provider: "claudeAgent",
provider: ProviderDriverKind.make("claudeAgent"),
runtimeMode: "full-access",
});
@@ -3070,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",
});
@@ -3144,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"),
});
@@ -3178,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),
@@ -3193,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",
});
@@ -3259,7 +3442,7 @@ describe("ClaudeAdapterLive", () => {
const session = yield* adapter.startSession({
threadId: THREAD_ID,
provider: "claudeAgent",
provider: ProviderDriverKind.make("claudeAgent"),
runtimeMode: "approval-required",
});
@@ -3346,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({
+116 -66
View File
@@ -24,8 +24,11 @@ import {
ApprovalRequestId,
type CanonicalItemType,
type CanonicalRequestType,
type ClaudeSettings,
EventId,
type ProviderApprovalDecision,
ProviderDriverKind,
ProviderInstanceId,
ProviderItemId,
type ProviderRuntimeEvent,
type ProviderRuntimeTurnStatus,
@@ -40,13 +43,13 @@ import {
ThreadId,
TurnId,
type UserInputQuestion,
ClaudeAgentEffort,
} from "@t3tools/contracts";
import {
applyClaudePromptEffortPrefix,
resolveApiModelId,
resolveEffort,
trimOrNull,
getModelSelectionBooleanOptionValue,
getModelSelectionStringOptionValue,
getProviderOptionDescriptors,
resolvePromptInjectedEffort,
} from "@t3tools/shared/model";
import {
Cause,
@@ -56,7 +59,7 @@ import {
Exit,
FileSystem,
Fiber,
Layer,
Path,
Queue,
Random,
Ref,
@@ -65,8 +68,13 @@ import {
import { resolveAttachmentPath } from "../../attachmentStore.ts";
import { ServerConfig } from "../../config.ts";
import { ServerSettingsService } from "../../serverSettings.ts";
import { getClaudeModelCapabilities } from "./ClaudeProvider.ts";
import { makeClaudeEnvironment } from "../Drivers/ClaudeHome.ts";
import {
getClaudeModelCapabilities,
normalizeClaudeCliEffort,
resolveClaudeApiModelId,
resolveClaudeEffort,
} from "./ClaudeProvider.ts";
import {
ProviderAdapterProcessError,
ProviderAdapterRequestError,
@@ -75,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,
@@ -177,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;
@@ -193,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;
@@ -216,19 +238,9 @@ function normalizeClaudeStreamMessages(cause: Cause.Cause<Error>): ReadonlyArray
return squashed.length > 0 ? [squashed] : [];
}
function getEffectiveClaudeAgentEffort(
effort: ClaudeAgentEffort | null | undefined,
): ClaudeSdkEffort | null {
if (!effort) {
return null;
}
if (effort === "ultrathink") {
return null;
}
if (effort === "xhigh") {
return "max";
}
return effort;
function getEffectiveClaudeAgentEffort(effort: string | null | undefined): ClaudeSdkEffort | null {
const normalized = normalizeClaudeCliEffort(effort);
return normalized ? (normalized as ClaudeSdkEffort) : null;
}
function isClaudeInterruptedMessage(message: string): boolean {
@@ -558,18 +570,19 @@ 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.options?.effort : null;
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);
// For prompt injection, we check if the raw effort is a prompt-injected level (e.g. "ultrathink").
// resolveEffort strips prompt-injected values (returning the default instead), so we check the raw value directly.
const trimmedEffort = trimOrNull(rawEffort);
const promptEffort =
trimmedEffort && caps.promptInjectedEffortLevels.includes(trimmedEffort) ? trimmedEffort : null;
const promptEffort = resolvePromptInjectedEffort(caps, rawEffort);
return applyClaudePromptEffortPrefix(input.input?.trim() ?? "", promptEffort);
}
@@ -606,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) {
@@ -958,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
@@ -984,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));
@@ -1256,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);
@@ -2541,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)
@@ -2812,31 +2838,27 @@ 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 apiModelId = modelSelection ? resolveApiModelId(modelSelection) : undefined;
const effort = (resolveEffort(caps, modelSelection?.options?.effort) ??
null) as ClaudeAgentEffort | null;
const fastMode = modelSelection?.options?.fastMode === true && caps.supportsFastMode;
const thinking =
typeof modelSelection?.options?.thinking === "boolean" && caps.supportsThinkingToggle
? modelSelection.options.thinking
: undefined;
const descriptors = getProviderOptionDescriptors({ caps });
const apiModelId = modelSelection ? resolveClaudeApiModelId(modelSelection) : undefined;
const rawEffort = getModelSelectionStringOptionValue(modelSelection, "effort");
const effort = resolveClaudeEffort(caps, rawEffort) ?? null;
const fastModeSupported = descriptors.some(
(descriptor) => descriptor.type === "boolean" && descriptor.id === "fastMode",
);
const thinkingSupported = descriptors.some(
(descriptor) => descriptor.type === "boolean" && descriptor.id === "thinking",
);
const fastMode =
getModelSelectionBooleanOptionValue(modelSelection, "fastMode") === true &&
fastModeSupported;
const thinking = thinkingSupported
? getModelSelectionBooleanOptionValue(modelSelection, "thinking")
: undefined;
const effectiveEffort = getEffectiveClaudeAgentEffort(effort);
const runtimeModeToPermission: Record<string, PermissionMode> = {
"auto-accept-edits": "acceptEdits",
@@ -2847,13 +2869,18 @@ 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 } : {}),
pathToClaudeCodeExecutable: claudeBinaryPath,
settingSources: [...CLAUDE_SETTING_SOURCES],
...(effectiveEffort ? { effort: effectiveEffort } : {}),
// The SDK type lags the CLI here: Opus 4.7 accepts `xhigh` even though
// the published `Options["effort"]` union currently stops at `max`.
...(effectiveEffort
? {
effort: effectiveEffort as unknown as NonNullable<ClaudeQueryOptions["effort"]>,
}
: {}),
...(permissionMode ? { permissionMode } : {}),
...(permissionMode === "bypassPermissions"
? { allowDangerouslySkipPermissions: true }
@@ -2863,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({
@@ -2886,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 } : {}),
@@ -2997,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
@@ -3006,7 +3061,7 @@ const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
}
if (modelSelection?.model) {
const apiModelId = resolveApiModelId(modelSelection);
const apiModelId = resolveClaudeApiModelId(modelSelection);
if (context.currentApiModelId !== apiModelId) {
yield* Effect.tryPromise({
try: () => context.query.setModel(apiModelId),
@@ -3071,6 +3126,7 @@ const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
const message = yield* buildUserMessageEffect(input, {
fileSystem,
attachmentsDir: serverConfig.attachmentsDir,
boundInstanceId,
});
yield* Queue.offer(context.promptQueue, {
@@ -3208,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));
}
+306 -400
View File
@@ -1,122 +1,177 @@
import type {
ClaudeSettings,
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,
getProviderOptionCurrentValue,
getProviderOptionDescriptors,
} from "@t3tools/shared/model";
import {
query as claudeQuery,
type SlashCommand as ClaudeSlashCommand,
type SDKUserMessage,
} from "@anthropic-ai/claude-agent-sdk";
import {
buildBooleanOptionDescriptor,
buildSelectOptionDescriptor,
buildServerProvider,
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 = {
reasoningEffortLevels: [],
supportsFastMode: false,
supportsThinkingToggle: false,
contextWindowOptions: [],
promptInjectedEffortLevels: [],
};
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,
} as const;
const MINIMUM_CLAUDE_OPUS_4_7_VERSION = "2.1.111";
const BUILT_IN_MODELS: ReadonlyArray<ServerProviderModel> = [
{
slug: "claude-opus-4-7",
name: "Claude Opus 4.7",
isCustom: false,
capabilities: {
reasoningEffortLevels: [
{ value: "low", label: "Low" },
{ value: "medium", label: "Medium" },
{ value: "high", label: "High" },
{ value: "xhigh", label: "Extra High", isDefault: true },
{ value: "max", label: "Max" },
{ value: "ultrathink", label: "Ultrathink" },
capabilities: createModelCapabilities({
optionDescriptors: [
buildSelectOptionDescriptor({
id: "effort",
label: "Reasoning",
options: [
{ value: "low", label: "Low" },
{ value: "medium", label: "Medium" },
{ value: "high", label: "High" },
{ value: "xhigh", label: "Extra High", isDefault: true },
{ value: "max", label: "Max" },
{ value: "ultrathink", label: "Ultrathink" },
],
promptInjectedValues: ["ultrathink"],
}),
buildSelectOptionDescriptor({
id: "contextWindow",
label: "Context Window",
options: [
{ value: "200k", label: "200k", isDefault: true },
{ value: "1m", label: "1M" },
],
}),
],
supportsFastMode: false,
supportsThinkingToggle: false,
contextWindowOptions: [
{ value: "200k", label: "200k", isDefault: true },
{ value: "1m", label: "1M" },
],
promptInjectedEffortLevels: ["ultrathink"],
} satisfies ModelCapabilities,
}),
},
{
slug: "claude-opus-4-6",
name: "Claude Opus 4.6",
isCustom: false,
capabilities: {
reasoningEffortLevels: [
{ value: "low", label: "Low" },
{ value: "medium", label: "Medium" },
{ value: "high", label: "High", isDefault: true },
{ value: "max", label: "Max" },
{ value: "ultrathink", label: "Ultrathink" },
capabilities: createModelCapabilities({
optionDescriptors: [
buildSelectOptionDescriptor({
id: "effort",
label: "Reasoning",
options: [
{ value: "low", label: "Low" },
{ value: "medium", label: "Medium" },
{ value: "high", label: "High", isDefault: true },
{ value: "max", label: "Max" },
{ value: "ultrathink", label: "Ultrathink" },
],
promptInjectedValues: ["ultrathink"],
}),
buildBooleanOptionDescriptor({
id: "fastMode",
label: "Fast Mode",
}),
buildSelectOptionDescriptor({
id: "contextWindow",
label: "Context Window",
options: [
{ value: "200k", label: "200k", isDefault: true },
{ value: "1m", label: "1M" },
],
}),
],
supportsFastMode: true,
supportsThinkingToggle: false,
contextWindowOptions: [
{ value: "200k", label: "200k", isDefault: true },
{ value: "1m", label: "1M" },
}),
},
{
slug: "claude-opus-4-5",
name: "Claude Opus 4.5",
isCustom: false,
capabilities: createModelCapabilities({
optionDescriptors: [
buildSelectOptionDescriptor({
id: "effort",
label: "Reasoning",
options: [
{ value: "low", label: "Low" },
{ value: "medium", label: "Medium" },
{ value: "high", label: "High", isDefault: true },
{ value: "max", label: "Max" },
],
}),
buildBooleanOptionDescriptor({
id: "fastMode",
label: "Fast Mode",
}),
],
promptInjectedEffortLevels: ["ultrathink"],
} satisfies ModelCapabilities,
}),
},
{
slug: "claude-sonnet-4-6",
name: "Claude Sonnet 4.6",
isCustom: false,
capabilities: {
reasoningEffortLevels: [
{ value: "low", label: "Low" },
{ value: "medium", label: "Medium" },
{ value: "high", label: "High", isDefault: true },
{ value: "ultrathink", label: "Ultrathink" },
capabilities: createModelCapabilities({
optionDescriptors: [
buildSelectOptionDescriptor({
id: "effort",
label: "Reasoning",
options: [
{ value: "low", label: "Low" },
{ value: "medium", label: "Medium" },
{ value: "high", label: "High", isDefault: true },
{ value: "ultrathink", label: "Ultrathink" },
],
promptInjectedValues: ["ultrathink"],
}),
buildSelectOptionDescriptor({
id: "contextWindow",
label: "Context Window",
options: [
{ value: "200k", label: "200k", isDefault: true },
{ value: "1m", label: "1M" },
],
}),
],
supportsFastMode: false,
supportsThinkingToggle: false,
contextWindowOptions: [
{ value: "200k", label: "200k", isDefault: true },
{ value: "1m", label: "1M" },
],
promptInjectedEffortLevels: ["ultrathink"],
} satisfies ModelCapabilities,
}),
},
{
slug: "claude-haiku-4-5",
name: "Claude Haiku 4.5",
isCustom: false,
capabilities: {
reasoningEffortLevels: [],
supportsFastMode: false,
supportsThinkingToggle: true,
contextWindowOptions: [],
promptInjectedEffortLevels: [],
} satisfies ModelCapabilities,
capabilities: createModelCapabilities({
optionDescriptors: [
buildBooleanOptionDescriptor({
id: "thinking",
label: "Thinking",
}),
],
}),
},
];
@@ -146,180 +201,46 @@ export function getClaudeModelCapabilities(model: string | null | undefined): Mo
);
}
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)),
),
);
}),
);
export function resolveClaudeEffort(
caps: ModelCapabilities,
raw: string | null | undefined,
): string | undefined {
const descriptors = getProviderOptionDescriptors({
caps,
...(raw ? { selections: [{ id: "effort", value: raw }] } : {}),
});
const effortDescriptor = descriptors.find((descriptor) => descriptor.id === "effort");
const value = getProviderOptionCurrentValue(effortDescriptor);
return typeof value === "string" ? value : undefined;
}
/**
* Try to extract a subscription type from the `claude auth status` JSON
* output. This is a zero-cost operation on data we already have.
* Normalize a resolved Claude effort value into one suitable for the Claude
* CLI's `--effort` flag.
*
* Mirrors the mapping used when invoking the Claude Agent SDK
* ({@link getEffectiveClaudeAgentEffort} in ClaudeAdapter): the Opus 4.7
* capability `"xhigh"` is rewritten to the accepted CLI value `"max"`, and
* `"ultrathink"` is filtered out because it is a prompt-prefix mode rather
* than a CLI-effort value. Returns `undefined` when no flag should be passed.
*/
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));
export function normalizeClaudeCliEffort(effort: string | null | undefined): string | undefined {
if (!effort || effort === "ultrathink") {
return undefined;
}
if (effort === "xhigh") {
return "max";
}
return effort;
}
function extractClaudeAuthMethodFromOutput(result: CommandResult): string | undefined {
const parsed = decodeUnknownJson(result.stdout.trim());
if (Result.isFailure(parsed)) return undefined;
return Option.getOrUndefined(findAuthMethod(parsed.success));
export function resolveClaudeApiModelId(modelSelection: ModelSelection): string {
switch (getModelSelectionStringOptionValue(modelSelection, "contextWindow")) {
case "1m":
return `${modelSelection.model}[1m]`;
default:
return modelSelection.model;
}
}
function toTitleCaseWords(value: string): string {
@@ -335,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":
@@ -356,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;
@@ -372,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),
};
}
@@ -391,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> {
@@ -454,37 +420,68 @@ function dedupeSlashCommands(
return [...commandsByName.values()];
}
function waitForAbortSignal(signal: AbortSignal): Promise<void> {
if (signal.aborted) {
return Promise.resolve();
}
return new Promise((resolve) => {
signal.addEventListener("abort", () => resolve(), { once: true });
});
}
/**
* Probe account information by spawning a lightweight Claude Agent SDK
* session and reading the initialization result.
*
* The prompt is never sent to the Anthropic API — we abort immediately
* after the local initialization phase completes. This gives us the
* user's subscription type without incurring any token cost.
* We pass a never-yielding AsyncIterable as the prompt so that no user
* message is ever written to the subprocess stdin. This means the Claude
* Code subprocess completes its local initialization IPC (returning
* account info and slash commands) but never starts an API request to
* Anthropic. We read the init data and then abort the subprocess.
*
* 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({
prompt: ".",
options: {
persistSession: false,
pathToClaudeCodeExecutable: binaryPath,
abortController: abort,
maxTurns: 0,
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(() => {
@@ -500,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,
@@ -535,7 +531,7 @@ export const checkClaudeProviderStatus = Effect.fn("checkClaudeProviderStatus")(
if (!claudeSettings.enabled) {
return buildServerProvider({
provider: PROVIDER,
presentation: CLAUDE_PRESENTATION,
enabled: false,
checkedAt,
models: allModels,
@@ -549,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,
);
@@ -557,7 +553,7 @@ 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,
models: allModels,
@@ -575,7 +571,7 @@ export const checkClaudeProviderStatus = Effect.fn("checkClaudeProviderStatus")(
if (Option.isNone(versionProbe.success)) {
return buildServerProvider({
provider: PROVIDER,
presentation: CLAUDE_PRESENTATION,
enabled: claudeSettings.enabled,
checkedAt,
models: allModels,
@@ -595,7 +591,7 @@ 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,
models: allModels,
@@ -621,45 +617,15 @@ 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(DEFAULT_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,
models,
@@ -669,35 +635,17 @@ 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,
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,
models,
@@ -705,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,
@@ -730,7 +675,7 @@ const makePendingClaudeProvider = (claudeSettings: ClaudeSettings): ServerProvid
if (!claudeSettings.enabled) {
return buildServerProvider({
provider: PROVIDER,
presentation: CLAUDE_PRESENTATION,
enabled: false,
checkedAt,
models,
@@ -745,7 +690,7 @@ const makePendingClaudeProvider = (claudeSettings: ClaudeSettings): ServerProvid
}
return buildServerProvider({
provider: PROVIDER,
presentation: CLAUDE_PRESENTATION,
enabled: true,
checkedAt,
models,
@@ -759,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 };
File diff suppressed because it is too large. Load diff
Loaded 100 of 444 files, more files were not shown because too many files have changed in this diff. Show more