Compare commits

..
Author SHA1 Message Date
Julius Marminge e80d4a479c Simplify logical project grouping
- Use the configured grouping mode directly for sidebar and thread buckets
- Add coverage for repository-path grouping splitting root and nested projects
- Remove environment-based bucket splitting from logical key mapping
2026-04-27 11:16:24 -07:00
Julius Marminge e8f48ca8ff Group duplicate clones by repo-relative path
- Treat matching repo-relative paths as the same logical project
- Update grouping test to reflect the new duplicate-clone behavior
2026-04-27 11:12:07 -07:00
Julius Marminge c421b5d054 Stabilize project grouping across environments
- Build logical project key maps to avoid merging duplicate clones in one environment
- Reuse the mapping in chat, sidebar, thread creation, and runtime sync paths
- Add coverage for cross-environment grouping and duplicate clone separation
2026-04-27 10:33:36 -07:00
327 changed files with 12545 additions and 26431 deletions

No files matched your search

-3
View File
@@ -30,6 +30,3 @@ github:Yash-Singh1
github:eggfriedrice24
github:Ymit24
github:shivamhwp
github:jappyjan
github:justsomelegs
github:UtkarshUsername
+7 -67
View File
@@ -30,7 +30,7 @@ jobs:
check_changes:
name: Check for changes since last nightly
if: github.event_name == 'schedule'
runs-on: blacksmith-8vcpu-ubuntu-2404
runs-on: ubuntu-24.04
outputs:
has_changes: ${{ steps.check.outputs.has_changes }}
steps:
@@ -376,16 +376,13 @@ jobs:
registry-url: https://registry.npmjs.org
- name: Install dependencies
run: bun install --frozen-lockfile --filter=t3 --filter=@t3tools/web --filter=@t3tools/scripts
run: bun install --frozen-lockfile
- 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 --filter=t3 run build
run: bun run build --filter=@t3tools/web --filter=t3
- 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
@@ -394,7 +391,7 @@ jobs:
name: Publish GitHub Release
needs: [preflight, build, publish_cli]
if: ${{ !failure() && !cancelled() && needs.preflight.result == 'success' && needs.build.result == 'success' && needs.publish_cli.result == 'success' }}
runs-on: blacksmith-8vcpu-ubuntu-2404
runs-on: ubuntu-24.04 # blacksmith-8vcpu-ubuntu-2404
timeout-minutes: 10
steps:
- id: app_token
@@ -421,7 +418,7 @@ jobs:
node-version-file: package.json
- name: Install dependencies
run: bun install --frozen-lockfile --filter=@t3tools/scripts
run: bun install --frozen-lockfile
- name: Download all desktop artifacts
uses: actions/download-artifact@v8
@@ -555,7 +552,7 @@ jobs:
node-version-file: package.json
- name: Install dependencies
run: bun install --frozen-lockfile --filter=@t3tools/scripts
run: bun install --frozen-lockfile
- id: update_versions
name: Update version strings
@@ -565,7 +562,7 @@ jobs:
- name: Format package.json files
if: steps.update_versions.outputs.changed == 'true'
run: bunx oxfmt@0.40.0 apps/server/package.json apps/desktop/package.json apps/web/package.json packages/contracts/package.json
run: bunx oxfmt 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'
@@ -588,60 +585,3 @@ 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 }}"
@@ -1,216 +0,0 @@
# 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.
@@ -1,268 +0,0 @@
# 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,5 +10,3 @@
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`
+3 -4
View File
@@ -5,12 +5,11 @@ T3 Code is a minimal web GUI for coding agents (currently Codex and Claude, more
## Installation
> [!WARNING]
> T3 Code currently supports Codex, Claude, and OpenCode.
> T3 Code currently supports Codex and Claude.
> Install and authenticate at least one provider before use:
>
> - 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`
> - Codex: install [Codex CLI](https://github.com/openai/codex) and run `codex login`
> - Claude: install Claude Code and run `claude auth login`
### Run without installing
+2 -2
View File
@@ -1,6 +1,6 @@
{
"name": "@t3tools/desktop",
"version": "0.0.21",
"version": "0.0.20",
"private": true,
"type": "module",
"main": "dist-electron/main.cjs",
@@ -16,7 +16,7 @@
},
"dependencies": {
"effect": "catalog:",
"electron": "40.9.3",
"electron": "40.6.0",
"electron-updater": "^6.6.2"
},
"devDependencies": {
@@ -49,12 +49,10 @@ function makeSecretStorage(available: boolean): DesktopSecretStorage {
}
const clientSettings: ClientSettings = {
autoOpenPlanSidebar: false,
confirmThreadArchive: true,
confirmThreadDelete: false,
diffWordWrap: true,
favorites: [],
providerModelPreferences: {},
sidebarProjectGroupingMode: "repository_path",
sidebarProjectGroupingOverrides: {
"environment-1:/tmp/project-a": "separate",
@@ -3,8 +3,7 @@ import { execFileSync } from "node:child_process";
import * as NodeServices from "@effect/platform-node/NodeServices";
import {
ApprovalRequestId,
CodexSettings,
ProviderDriverKind,
ProviderKind,
type OrchestrationEvent,
type OrchestrationThread,
} from "@t3tools/contracts";
@@ -25,7 +24,10 @@ import {
import { CheckpointStoreLive } from "../src/checkpointing/Layers/CheckpointStore.ts";
import { CheckpointStore } from "../src/checkpointing/Services/CheckpointStore.ts";
import { TextGeneration, type TextGenerationShape } from "../src/textGeneration/TextGeneration.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 { OrchestrationCommandReceiptRepositoryLive } from "../src/persistence/Layers/OrchestrationCommandReceipts.ts";
import { OrchestrationEventStoreLive } from "../src/persistence/Layers/OrchestrationEventStore.ts";
import { ProjectionCheckpointRepositoryLive } from "../src/persistence/Layers/ProjectionCheckpoints.ts";
@@ -34,16 +36,13 @@ 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 { makeAdapterRegistryMock } from "../src/provider/testUtils/providerAdapterRegistryMock.ts";
import { ProviderUnsupportedError } from "../src/provider/Errors.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 { makeCodexAdapter } from "../src/provider/Layers/CodexAdapter.ts";
import {
NoOpProviderEventLoggers,
ProviderEventLoggers,
} from "../src/provider/Layers/ProviderEventLoggers.ts";
import { makeCodexAdapterLive } from "../src/provider/Layers/CodexAdapter.ts";
import { CodexAdapter } from "../src/provider/Services/CodexAdapter.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";
@@ -74,11 +73,6 @@ 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, {
@@ -220,7 +214,7 @@ export interface OrchestrationIntegrationHarness {
}
interface MakeOrchestrationIntegrationHarnessOptions {
readonly provider?: ProviderDriverKind;
readonly provider?: ProviderKind;
readonly realCodex?: boolean;
}
@@ -231,7 +225,7 @@ export const makeOrchestrationIntegrationHarness = (
const path = yield* Path.Path;
const fileSystem = yield* FileSystem.FileSystem;
const provider = options?.provider ?? ProviderDriverKind.make("codex");
const provider = options?.provider ?? "codex";
const useRealCodex = options?.realCodex === true;
const adapterHarness = useRealCodex
? null
@@ -239,10 +233,13 @@ export const makeOrchestrationIntegrationHarness = (
provider,
});
const fakeRegistry = adapterHarness
? Layer.succeed(
ProviderAdapterRegistry,
makeAdapterRegistryMock({ [adapterHarness.provider]: adapterHarness.adapter }),
)
? 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)
: null;
const rootDir = yield* fileSystem.makeTempDirectoryScoped({
prefix: "t3-orchestration-integration-",
@@ -267,33 +264,34 @@ export const makeOrchestrationIntegrationHarness = (
const realCodexRegistry = Layer.effect(
ProviderAdapterRegistry,
Effect.gen(function* () {
const codexSettings = Schema.decodeSync(CodexSettings)({});
const codexAdapter = yield* makeCodexAdapter(codexSettings);
return makeAdapterRegistryMock({
[ProviderDriverKind.make("codex")]: codexAdapter,
});
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;
}),
).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(VcsDriverRegistry.layer));
const checkpointStoreLayer = CheckpointStoreLive.pipe(Layer.provide(GitCoreLive));
const projectionSnapshotQueryLayer = OrchestrationProjectionSnapshotQueryLive;
const runtimeServicesLayer = Layer.mergeAll(
projectionSnapshotQueryLayer,
@@ -309,32 +307,31 @@ export const makeOrchestrationIntegrationHarness = (
Layer.provideMerge(runtimeServicesLayer),
Layer.provideMerge(serverSettingsLayer),
);
const gitWorkflowLayer = Layer.mock(GitWorkflowService)({
renameBranch: (input: Parameters<GitVcsDriver.GitVcsDriverShape["renameBranch"]>[0]) =>
const gitCoreLayer = Layer.succeed(GitCore, {
renameBranch: (input: Parameters<GitCoreShape["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(gitWorkflowLayer),
Layer.provideMerge(gitCoreLayer),
Layer.provideMerge(textGenerationLayer),
Layer.provideMerge(serverSettingsLayer),
);
const checkpointReactorLayer = CheckpointReactorLive.pipe(
Layer.provideMerge(runtimeServicesLayer),
Layer.provideMerge(
Layer.succeed(VcsStatusBroadcaster, {
Layer.succeed(GitStatusBroadcaster, {
getStatus: () => Effect.die("getStatus should not be called in this test"),
refreshLocalStatus: () =>
Effect.succeed({
isRepo: true,
kind: "git",
hasPrimaryRemote: false,
isDefaultRef: true,
refName: "main",
hasOriginRemote: false,
isDefaultBranch: true,
branch: "main",
hasWorkingTreeChanges: false,
workingTree: { files: [], insertions: 0, deletions: 0 },
}),
@@ -345,12 +342,11 @@ export const makeOrchestrationIntegrationHarness = (
Layer.provideMerge(
WorkspaceEntriesLive.pipe(
Layer.provide(WorkspacePathsLive),
Layer.provideMerge(VcsDriverRegistry.layer),
Layer.provideMerge(gitCoreLayer),
Layer.provide(NodeServices.layer),
),
),
Layer.provideMerge(WorkspacePathsLive),
Layer.provideMerge(VcsProcess.layer),
);
const orchestrationReactorLayer = OrchestrationReactorLive.pipe(
Layer.provideMerge(runtimeIngestionLayer),
@@ -10,7 +10,7 @@ import {
ProviderTurnStartResult,
ThreadId,
TurnId,
ProviderDriverKind,
ProviderKind,
} 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: ProviderDriverKind;
readonly provider: ProviderKind;
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: ProviderDriverKind;
readonly provider: ProviderKind;
readonly queueTurnResponse: (
threadId: ThreadId,
response: TestTurnResponse,
@@ -198,7 +198,7 @@ export interface TestProviderAdapterHarness {
}
interface MakeTestProviderAdapterHarnessOptions {
readonly provider?: ProviderDriverKind;
readonly provider?: ProviderKind;
}
function nowIso(): string {
@@ -206,7 +206,7 @@ function nowIso(): string {
}
function sessionNotFound(
provider: ProviderDriverKind,
provider: ProviderKind,
threadId: ThreadId,
): ProviderAdapterSessionNotFoundError {
return new ProviderAdapterSessionNotFoundError({
@@ -216,7 +216,7 @@ function sessionNotFound(
}
function missingSessionEffect(
provider: ProviderDriverKind,
provider: ProviderKind,
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 ?? ProviderDriverKind.make("codex");
const provider = options?.provider ?? "codex";
const runtimeEvents = yield* Queue.unbounded<ProviderRuntimeEvent>();
let sessionCount = 0;
const sessions = new Map<ThreadId, SessionState>();
@@ -257,9 +257,6 @@ 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, ProviderDriverKind, RuntimeRequestId } from "@t3tools/contracts";
import { EventId, RuntimeRequestId } from "@t3tools/contracts";
import type { LegacyProviderRuntimeEvent } from "../TestProviderAdapter.integration.ts";
const PROVIDER = ProviderDriverKind.make("codex");
const PROVIDER = "codex" as const;
const SESSION_ID = "fixture-session";
const THREAD_ID = "fixture-thread";
const TURN_ID = "fixture-turn";
@@ -4,17 +4,14 @@ import path from "node:path";
import {
ApprovalRequestId,
CommandId,
defaultInstanceIdForDriver,
DEFAULT_PROVIDER_INTERACTION_MODE,
DEFAULT_MODEL,
DEFAULT_MODEL_BY_PROVIDER,
EventId,
MessageId,
ProjectId,
ProviderDriverKind,
ProviderKind,
ThreadId,
ModelSelection,
ProviderInstanceId,
} from "@t3tools/contracts";
import { assert, it } from "@effect/vitest";
import { Effect, Option, Schema } from "effect";
@@ -42,9 +39,7 @@ 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 = ProviderDriverKind;
const CODEX_PROVIDER = ProviderDriverKind.make("codex");
const CLAUDE_AGENT_PROVIDER = ProviderDriverKind.make("claudeAgent");
type IntegrationProvider = ProviderKind;
function nowIso() {
return new Date().toISOString();
@@ -79,11 +74,7 @@ function waitForSync<A>(
});
}
function runtimeBase(
eventId: string,
createdAt: string,
provider: IntegrationProvider = CODEX_PROVIDER,
) {
function runtimeBase(eventId: string, createdAt: string, provider: IntegrationProvider = "codex") {
return {
eventId: asEventId(eventId),
provider,
@@ -93,7 +84,7 @@ function runtimeBase(
function withHarness<A, E>(
use: (harness: OrchestrationIntegrationHarness) => Effect.Effect<A, E>,
provider: IntegrationProvider = CODEX_PROVIDER,
provider: IntegrationProvider = "codex",
) {
return Effect.acquireUseRelease(
makeOrchestrationIntegrationHarness({ provider }),
@@ -106,7 +97,7 @@ function withRealCodexHarness<A, E>(
use: (harness: OrchestrationIntegrationHarness) => Effect.Effect<A, E>,
) {
return Effect.acquireUseRelease(
makeOrchestrationIntegrationHarness({ provider: CODEX_PROVIDER, realCodex: true }),
makeOrchestrationIntegrationHarness({ provider: "codex", realCodex: true }),
use,
(harness) => harness.dispose,
).pipe(Effect.provide(NodeServices.layer));
@@ -115,9 +106,8 @@ function withRealCodexHarness<A, E>(
const seedProjectAndThread = (harness: OrchestrationIntegrationHarness) =>
Effect.gen(function* () {
const createdAt = nowIso();
const provider = harness.adapterHarness?.provider ?? CODEX_PROVIDER;
const defaultModel = DEFAULT_MODEL_BY_PROVIDER[provider] ?? DEFAULT_MODEL;
const instanceId = defaultInstanceIdForDriver(provider);
const provider = harness.adapterHarness?.provider ?? "codex";
const defaultModel = DEFAULT_MODEL_BY_PROVIDER[provider];
yield* harness.engine.dispatch({
type: "project.create",
@@ -126,7 +116,7 @@ const seedProjectAndThread = (harness: OrchestrationIntegrationHarness) =>
title: "Integration Project",
workspaceRoot: harness.workspaceDir,
defaultModelSelection: {
instanceId,
provider,
model: defaultModel,
},
createdAt,
@@ -139,7 +129,7 @@ const seedProjectAndThread = (harness: OrchestrationIntegrationHarness) =>
projectId: PROJECT_ID,
title: "Integration Thread",
modelSelection: {
instanceId,
provider,
model: defaultModel,
},
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
@@ -275,7 +265,7 @@ it.live.skipIf(!process.env.CODEX_BINARY_PATH)(
title: "Integration Project",
workspaceRoot: harness.workspaceDir,
defaultModelSelection: {
instanceId: ProviderInstanceId.make("codex"),
provider: "codex",
model: "gpt-5.3-codex",
},
createdAt,
@@ -288,7 +278,7 @@ it.live.skipIf(!process.env.CODEX_BINARY_PATH)(
projectId: PROJECT_ID,
title: "Integration Thread",
modelSelection: {
instanceId: ProviderInstanceId.make("codex"),
provider: "codex",
model: "gpt-5.3-codex",
},
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
@@ -922,32 +912,20 @@ 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",
CLAUDE_AGENT_PROVIDER,
),
...runtimeBase("evt-claude-start-1", "2026-02-24T10:10:00.000Z", "claudeAgent"),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
},
{
type: "message.delta",
...runtimeBase(
"evt-claude-start-2",
"2026-02-24T10:10:00.050Z",
CLAUDE_AGENT_PROVIDER,
),
...runtimeBase("evt-claude-start-2", "2026-02-24T10:10:00.050Z", "claudeAgent"),
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",
CLAUDE_AGENT_PROVIDER,
),
...runtimeBase("evt-claude-start-3", "2026-02-24T10:10:00.100Z", "claudeAgent"),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
status: "completed",
@@ -961,7 +939,7 @@ it.live("starts a claudeAgent session on first turn when provider is requested",
messageId: "msg-user-claude-initial",
text: "Use Claude",
modelSelection: {
instanceId: ProviderInstanceId.make("claudeAgent"),
provider: "claudeAgent",
model: "claude-sonnet-4-6",
},
});
@@ -977,7 +955,7 @@ it.live("starts a claudeAgent session on first turn when provider is requested",
);
assert.equal(thread.session?.providerName, "claudeAgent");
}),
CLAUDE_AGENT_PROVIDER,
"claudeAgent",
),
);
@@ -991,32 +969,20 @@ 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",
CLAUDE_AGENT_PROVIDER,
),
...runtimeBase("evt-claude-recover-1", "2026-02-24T10:11:00.000Z", "claudeAgent"),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
},
{
type: "message.delta",
...runtimeBase(
"evt-claude-recover-2",
"2026-02-24T10:11:00.050Z",
CLAUDE_AGENT_PROVIDER,
),
...runtimeBase("evt-claude-recover-2", "2026-02-24T10:11:00.050Z", "claudeAgent"),
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",
CLAUDE_AGENT_PROVIDER,
),
...runtimeBase("evt-claude-recover-3", "2026-02-24T10:11:00.100Z", "claudeAgent"),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
status: "completed",
@@ -1030,7 +996,7 @@ it.live("recovers claudeAgent sessions after provider stopAll using persisted re
messageId: "msg-user-claude-recover-1",
text: "Before restart",
modelSelection: {
instanceId: ProviderInstanceId.make("claudeAgent"),
provider: "claudeAgent",
model: "claude-sonnet-4-6",
},
});
@@ -1052,32 +1018,20 @@ 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",
CLAUDE_AGENT_PROVIDER,
),
...runtimeBase("evt-claude-recover-4", "2026-02-24T10:11:01.000Z", "claudeAgent"),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
},
{
type: "message.delta",
...runtimeBase(
"evt-claude-recover-5",
"2026-02-24T10:11:01.050Z",
CLAUDE_AGENT_PROVIDER,
),
...runtimeBase("evt-claude-recover-5", "2026-02-24T10:11:01.050Z", "claudeAgent"),
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",
CLAUDE_AGENT_PROVIDER,
),
...runtimeBase("evt-claude-recover-6", "2026-02-24T10:11:01.100Z", "claudeAgent"),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
status: "completed",
@@ -1109,7 +1063,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");
}),
CLAUDE_AGENT_PROVIDER,
"claudeAgent",
),
);
@@ -1123,21 +1077,13 @@ 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",
CLAUDE_AGENT_PROVIDER,
),
...runtimeBase("evt-claude-approval-1", "2026-02-24T10:12:00.000Z", "claudeAgent"),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
},
{
type: "approval.requested",
...runtimeBase(
"evt-claude-approval-2",
"2026-02-24T10:12:00.050Z",
CLAUDE_AGENT_PROVIDER,
),
...runtimeBase("evt-claude-approval-2", "2026-02-24T10:12:00.050Z", "claudeAgent"),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
requestId: APPROVAL_REQUEST_ID,
@@ -1146,11 +1092,7 @@ it.live("forwards claudeAgent approval responses to the provider session", () =>
},
{
type: "turn.completed",
...runtimeBase(
"evt-claude-approval-3",
"2026-02-24T10:12:00.100Z",
CLAUDE_AGENT_PROVIDER,
),
...runtimeBase("evt-claude-approval-3", "2026-02-24T10:12:00.100Z", "claudeAgent"),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
status: "completed",
@@ -1164,7 +1106,7 @@ it.live("forwards claudeAgent approval responses to the provider session", () =>
messageId: "msg-user-claude-approval",
text: "Need approval",
modelSelection: {
instanceId: ProviderInstanceId.make("claudeAgent"),
provider: "claudeAgent",
model: "claude-sonnet-4-6",
},
});
@@ -1195,7 +1137,7 @@ it.live("forwards claudeAgent approval responses to the provider session", () =>
);
assert.equal(approvalResponses[0]?.decision, "accept");
}),
CLAUDE_AGENT_PROVIDER,
"claudeAgent",
),
);
@@ -1209,32 +1151,20 @@ 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",
CLAUDE_AGENT_PROVIDER,
),
...runtimeBase("evt-claude-interrupt-1", "2026-02-24T10:13:00.000Z", "claudeAgent"),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
},
{
type: "message.delta",
...runtimeBase(
"evt-claude-interrupt-2",
"2026-02-24T10:13:00.050Z",
CLAUDE_AGENT_PROVIDER,
),
...runtimeBase("evt-claude-interrupt-2", "2026-02-24T10:13:00.050Z", "claudeAgent"),
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",
CLAUDE_AGENT_PROVIDER,
),
...runtimeBase("evt-claude-interrupt-3", "2026-02-24T10:13:00.100Z", "claudeAgent"),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
status: "completed",
@@ -1248,7 +1178,7 @@ it.live("forwards thread.turn.interrupt to claudeAgent provider sessions", () =>
messageId: "msg-user-claude-interrupt",
text: "Start long turn",
modelSelection: {
instanceId: ProviderInstanceId.make("claudeAgent"),
provider: "claudeAgent",
model: "claude-sonnet-4-6",
},
});
@@ -1276,7 +1206,7 @@ it.live("forwards thread.turn.interrupt to claudeAgent provider sessions", () =>
);
assert.equal(interruptCalls.length, 1);
}),
CLAUDE_AGENT_PROVIDER,
"claudeAgent",
),
);
@@ -1290,32 +1220,20 @@ 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",
CLAUDE_AGENT_PROVIDER,
),
...runtimeBase("evt-claude-revert-1", "2026-02-24T10:14:00.000Z", "claudeAgent"),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
},
{
type: "message.delta",
...runtimeBase(
"evt-claude-revert-2",
"2026-02-24T10:14:00.050Z",
CLAUDE_AGENT_PROVIDER,
),
...runtimeBase("evt-claude-revert-2", "2026-02-24T10:14:00.050Z", "claudeAgent"),
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",
CLAUDE_AGENT_PROVIDER,
),
...runtimeBase("evt-claude-revert-3", "2026-02-24T10:14:00.100Z", "claudeAgent"),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
status: "completed",
@@ -1333,7 +1251,7 @@ it.live("reverts claudeAgent turns and rolls back provider conversation state",
messageId: "msg-user-claude-revert-1",
text: "First Claude edit",
modelSelection: {
instanceId: ProviderInstanceId.make("claudeAgent"),
provider: "claudeAgent",
model: "claude-sonnet-4-6",
},
});
@@ -1348,32 +1266,20 @@ 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",
CLAUDE_AGENT_PROVIDER,
),
...runtimeBase("evt-claude-revert-4", "2026-02-24T10:14:01.000Z", "claudeAgent"),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
},
{
type: "message.delta",
...runtimeBase(
"evt-claude-revert-5",
"2026-02-24T10:14:01.050Z",
CLAUDE_AGENT_PROVIDER,
),
...runtimeBase("evt-claude-revert-5", "2026-02-24T10:14:01.050Z", "claudeAgent"),
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",
CLAUDE_AGENT_PROVIDER,
),
...runtimeBase("evt-claude-revert-6", "2026-02-24T10:14:01.100Z", "claudeAgent"),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
status: "completed",
@@ -1424,6 +1330,6 @@ it.live("reverts claudeAgent turns and rolls back provider conversation state",
);
assert.deepEqual(harness.adapterHarness!.getRollbackCalls(THREAD_ID), [1]);
}),
CLAUDE_AGENT_PROVIDER,
"claudeAgent",
),
);
@@ -1,17 +1,13 @@
import type { ProviderRuntimeEvent } from "@t3tools/contracts";
import { ProviderDriverKind, ProviderInstanceId, ThreadId } from "@t3tools/contracts";
import { 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,
@@ -33,8 +29,6 @@ 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;
@@ -53,9 +47,13 @@ const makeIntegrationFixture = Effect.gen(function* () {
const cwd = yield* makeWorkspaceDirectory;
const harness = yield* makeTestProviderAdapterHarness();
const registry = makeAdapterRegistryMock({
[ProviderDriverKind.make("codex")]: harness.adapter,
});
const registry: typeof ProviderAdapterRegistry.Service = {
getByProvider: (provider) =>
provider === "codex"
? Effect.succeed(harness.adapter)
: Effect.fail(new ProviderUnsupportedError({ provider })),
listProviders: () => Effect.succeed(["codex"]),
};
const directoryLayer = ProviderSessionDirectoryLive.pipe(
Layer.provide(ProviderSessionRuntimeRepositoryLive),
@@ -66,7 +64,6 @@ 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));
@@ -127,8 +124,7 @@ 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: ProviderDriverKind.make("codex"),
providerInstanceId: codexInstanceId,
provider: "codex",
cwd: fixture.cwd,
runtimeMode: "full-access",
});
@@ -146,10 +142,6 @@ 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)),
);
@@ -164,8 +156,7 @@ 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: ProviderDriverKind.make("codex"),
providerInstanceId: codexInstanceId,
provider: "codex",
cwd: fixture.cwd,
runtimeMode: "full-access",
});
@@ -201,8 +192,7 @@ 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: ProviderDriverKind.make("codex"),
providerInstanceId: codexInstanceId,
provider: "codex",
cwd: fixture.cwd,
runtimeMode: "full-access",
});
@@ -253,8 +243,7 @@ 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: ProviderDriverKind.make("codex"),
providerInstanceId: codexInstanceId,
provider: "codex",
cwd: fixture.cwd,
runtimeMode: "full-access",
});
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "t3",
"version": "0.0.21",
"version": "0.0.20",
"license": "MIT",
"repository": {
"type": "git",
+5 -2
View File
@@ -1,6 +1,6 @@
import { Schema } from "effect";
import type { ProjectionRepositoryError } from "../persistence/Errors.ts";
import type { VcsError } from "@t3tools/contracts";
import { GitCommandError } from "@t3tools/contracts";
/**
* CheckpointUnavailableError - Expected checkpoint does not exist.
@@ -35,6 +35,9 @@ export class CheckpointInvariantError extends Schema.TaggedErrorClass<Checkpoint
}
}
export type CheckpointStoreError = VcsError | CheckpointInvariantError | CheckpointUnavailableError;
export type CheckpointStoreError =
| GitCommandError
| CheckpointInvariantError
| CheckpointUnavailableError;
export type CheckpointServiceError = CheckpointStoreError | ProjectionRepositoryError;
@@ -8,27 +8,24 @@ import { describe, expect } from "vitest";
import { checkpointRefForThreadTurn } from "../Utils.ts";
import { CheckpointStoreLive } from "./CheckpointStore.ts";
import { CheckpointStore } from "../Services/CheckpointStore.ts";
import * as VcsDriverRegistry from "../../vcs/VcsDriverRegistry.ts";
import * as VcsProcess from "../../vcs/VcsProcess.ts";
import type { VcsError } from "@t3tools/contracts";
import { GitCoreLive } from "../../git/Layers/GitCore.ts";
import { GitCore } from "../../git/Services/GitCore.ts";
import { GitCommandError } 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 VcsProcessTestLayer = VcsProcess.layer.pipe(Layer.provide(NodeServices.layer));
const VcsDriverTestLayer = VcsDriverRegistry.layer.pipe(Layer.provide(VcsProcessTestLayer));
const GitCoreTestLayer = GitCoreLive.pipe(
Layer.provide(ServerConfigLayer),
Layer.provide(NodeServices.layer),
);
const CheckpointStoreTestLayer = CheckpointStoreLive.pipe(
Layer.provideMerge(VcsDriverTestLayer),
Layer.provideMerge(NodeServices.layer),
);
const TestLayer = CheckpointStoreTestLayer.pipe(
Layer.provideMerge(VcsProcessTestLayer),
Layer.provideMerge(VcsDriverTestLayer),
Layer.provideMerge(ServerConfigLayer),
Layer.provideMerge(NodeServices.layer),
Layer.provide(GitCoreTestLayer),
Layer.provide(NodeServices.layer),
);
const TestLayer = Layer.mergeAll(NodeServices.layer, GitCoreTestLayer, CheckpointStoreTestLayer);
function makeTmpDir(
prefix = "checkpoint-store-test-",
@@ -52,12 +49,11 @@ function writeTextFile(
function git(
cwd: string,
args: ReadonlyArray<string>,
): Effect.Effect<string, VcsError, VcsProcess.VcsProcess> {
): Effect.Effect<string, GitCommandError, GitCore> {
return Effect.gen(function* () {
const process = yield* VcsProcess.VcsProcess;
const result = yield* process.run({
const gitCore = yield* GitCore;
const result = yield* gitCore.execute({
operation: "CheckpointStore.test.git",
command: "git",
cwd,
args,
timeoutMs: 10_000,
@@ -70,11 +66,12 @@ function initRepoWithCommit(
cwd: string,
): Effect.Effect<
void,
VcsError | PlatformError.PlatformError,
VcsProcess.VcsProcess | FileSystem.FileSystem
GitCommandError | PlatformError.PlatformError,
GitCore | FileSystem.FileSystem
> {
return Effect.gen(function* () {
yield* git(cwd, ["init"]);
const core = yield* GitCore;
yield* core.initRepo({ cwd });
yield* git(cwd, ["config", "user.email", "[email protected]"]);
yield* git(cwd, ["config", "user.name", "Test"]);
yield* writeTextFile(path.join(cwd, "README.md"), "# test\n");
@@ -14,8 +14,8 @@ import { randomUUID } from "node:crypto";
import { Effect, Layer, FileSystem, Path } from "effect";
import { CheckpointInvariantError } from "../Errors.ts";
import { VcsProcessExitError } from "@t3tools/contracts";
import { VcsDriverRegistry } from "../../vcs/VcsDriverRegistry.ts";
import { GitCommandError } from "@t3tools/contracts";
import { GitCore } from "../../git/Services/GitCore.ts";
import { CheckpointStore, type CheckpointStoreShape } from "../Services/CheckpointStore.ts";
import { CheckpointRef } from "@t3tools/contracts";
@@ -24,26 +24,10 @@ 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 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 git = yield* GitCore;
const resolveHeadCommit = (cwd: string) =>
vcs
const resolveHeadCommit = (cwd: string): Effect.Effect<string | null, GitCommandError> =>
git
.execute({
operation: "CheckpointStore.resolveHeadCommit",
cwd,
@@ -52,7 +36,7 @@ const makeCheckpointStore = Effect.gen(function* () {
})
.pipe(
Effect.map((result) => {
if (result.exitCode !== 0) {
if (result.code !== 0) {
return null;
}
const commit = result.stdout.trim();
@@ -60,18 +44,21 @@ const makeCheckpointStore = Effect.gen(function* () {
}),
);
const hasHeadCommit = (cwd: string) =>
vcs
const hasHeadCommit = (cwd: string): Effect.Effect<boolean, GitCommandError> =>
git
.execute({
operation: "CheckpointStore.hasHeadCommit",
cwd,
args: ["rev-parse", "--verify", "HEAD"],
allowNonZeroExit: true,
})
.pipe(Effect.map((result) => result.exitCode === 0));
.pipe(Effect.map((result) => result.code === 0));
const resolveCheckpointCommit = (cwd: string, checkpointRef: CheckpointRef) =>
vcs
const resolveCheckpointCommit = (
cwd: string,
checkpointRef: CheckpointRef,
): Effect.Effect<string | null, GitCommandError> =>
git
.execute({
operation: "CheckpointStore.resolveCheckpointCommit",
cwd,
@@ -80,7 +67,7 @@ const makeCheckpointStore = Effect.gen(function* () {
})
.pipe(
Effect.map((result) => {
if (result.exitCode !== 0) {
if (result.code !== 0) {
return null;
}
const commit = result.stdout.trim();
@@ -89,7 +76,7 @@ const makeCheckpointStore = Effect.gen(function* () {
);
const isGitRepository: CheckpointStoreShape["isGitRepository"] = (cwd) =>
vcs
git
.execute({
operation: "CheckpointStore.isGitRepository",
cwd,
@@ -97,7 +84,7 @@ const makeCheckpointStore = Effect.gen(function* () {
allowNonZeroExit: true,
})
.pipe(
Effect.map((result) => result.exitCode === 0 && result.stdout.trim() === "true"),
Effect.map((result) => result.code === 0 && result.stdout.trim() === "true"),
Effect.catch(() => Effect.succeed(false)),
);
@@ -121,7 +108,7 @@ const makeCheckpointStore = Effect.gen(function* () {
const headExists = yield* hasHeadCommit(input.cwd);
if (headExists) {
yield* vcs.execute({
yield* git.execute({
operation,
cwd: input.cwd,
args: ["read-tree", "HEAD"],
@@ -129,14 +116,14 @@ const makeCheckpointStore = Effect.gen(function* () {
});
}
yield* vcs.execute({
yield* git.execute({
operation,
cwd: input.cwd,
args: ["add", "-A", "--", "."],
env: commitEnv,
});
const writeTreeResult = yield* vcs.execute({
const writeTreeResult = yield* git.execute({
operation,
cwd: input.cwd,
args: ["write-tree"],
@@ -144,17 +131,16 @@ const makeCheckpointStore = Effect.gen(function* () {
});
const treeOid = writeTreeResult.stdout.trim();
if (treeOid.length === 0) {
return yield* new VcsProcessExitError({
return yield* new GitCommandError({
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* vcs.execute({
const commitTreeResult = yield* git.execute({
operation,
cwd: input.cwd,
args: ["commit-tree", treeOid, "-m", message],
@@ -162,16 +148,15 @@ const makeCheckpointStore = Effect.gen(function* () {
});
const commitOid = commitTreeResult.stdout.trim();
if (commitOid.length === 0) {
return yield* new VcsProcessExitError({
return yield* new GitCommandError({
operation,
command: "git commit-tree",
cwd: input.cwd,
exitCode: 0,
detail: "git commit-tree returned an empty commit oid.",
});
}
yield* vcs.execute({
yield* git.execute({
operation,
cwd: input.cwd,
args: ["update-ref", input.checkpointRef, commitOid],
@@ -212,12 +197,12 @@ const makeCheckpointStore = Effect.gen(function* () {
return false;
}
yield* vcs.execute({
yield* git.execute({
operation,
cwd: input.cwd,
args: ["restore", "--source", commitOid, "--worktree", "--staged", "--", "."],
});
yield* vcs.execute({
yield* git.execute({
operation,
cwd: input.cwd,
args: ["clean", "-fd", "--", "."],
@@ -225,7 +210,7 @@ const makeCheckpointStore = Effect.gen(function* () {
const headExists = yield* hasHeadCommit(input.cwd);
if (headExists) {
yield* vcs.execute({
yield* git.execute({
operation,
cwd: input.cwd,
args: ["reset", "--quiet", "--", "."],
@@ -250,16 +235,15 @@ const makeCheckpointStore = Effect.gen(function* () {
}
if (!fromCommitOid || !toCommitOid) {
return yield* new VcsProcessExitError({
return yield* new GitCommandError({
operation,
command: "git diff",
cwd: input.cwd,
exitCode: 1,
detail: "Checkpoint ref is unavailable for diff operation.",
});
}
const result = yield* vcs.execute({
const result = yield* git.execute({
operation,
cwd: input.cwd,
args: ["diff", "--patch", "--minimal", "--no-color", fromCommitOid, toCommitOid],
@@ -278,7 +262,7 @@ const makeCheckpointStore = Effect.gen(function* () {
yield* Effect.forEach(
input.checkpointRefs,
(checkpointRef) =>
vcs.execute({
git.execute({
operation,
cwd: input.cwd,
args: ["update-ref", "-d", checkpointRef],
-271
View File
@@ -1,271 +0,0 @@
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());
@@ -0,0 +1,306 @@
import * as NodeServices from "@effect/platform-node/NodeServices";
import { it } from "@effect/vitest";
import { Effect, FileSystem, Layer, Path } from "effect";
import { createModelSelection } from "@t3tools/shared/model";
import { expect } from "vitest";
import { ServerConfig } from "../../config.ts";
import { TextGeneration } from "../Services/TextGeneration.ts";
import { sanitizeThreadTitle } from "../Utils.ts";
import { ClaudeTextGenerationLive } from "./ClaudeTextGeneration.ts";
import { ServerSettingsService } from "../../serverSettings.ts";
const ClaudeTextGenerationTestLayer = ClaudeTextGenerationLive.pipe(
Layer.provideMerge(ServerSettingsService.layerTest()),
Layer.provideMerge(
ServerConfig.layerTest(process.cwd(), {
prefix: "t3code-claude-text-generation-test-",
}),
),
Layer.provideMerge(NodeServices.layer),
);
function makeFakeClaudeBinary(dir: string) {
return Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const binDir = path.join(dir, "bin");
const claudePath = path.join(binDir, "claude");
yield* fs.makeDirectory(binDir, { recursive: true });
yield* fs.writeFileString(
claudePath,
[
"#!/bin/sh",
'args="$*"',
'stdin_content="$(cat)"',
'if [ -n "$T3_FAKE_CLAUDE_ARGS_MUST_CONTAIN" ]; then',
' printf "%s" "$args" | grep -F -- "$T3_FAKE_CLAUDE_ARGS_MUST_CONTAIN" >/dev/null || {',
' printf "%s\\n" "args missing expected content" >&2',
" exit 2",
" }",
"fi",
'if [ -n "$T3_FAKE_CLAUDE_ARGS_MUST_NOT_CONTAIN" ]; then',
' if printf "%s" "$args" | grep -F -- "$T3_FAKE_CLAUDE_ARGS_MUST_NOT_CONTAIN" >/dev/null; then',
' printf "%s\\n" "args contained forbidden content" >&2',
" exit 3",
" fi",
"fi",
'if [ -n "$T3_FAKE_CLAUDE_STDIN_MUST_CONTAIN" ]; then',
' printf "%s" "$stdin_content" | grep -F -- "$T3_FAKE_CLAUDE_STDIN_MUST_CONTAIN" >/dev/null || {',
' printf "%s\\n" "stdin missing expected content" >&2',
" exit 4",
" }",
"fi",
'if [ -n "$T3_FAKE_CLAUDE_STDERR" ]; then',
' printf "%s\\n" "$T3_FAKE_CLAUDE_STDERR" >&2',
"fi",
'printf "%s" "$T3_FAKE_CLAUDE_OUTPUT"',
'exit "${T3_FAKE_CLAUDE_EXIT_CODE:-0}"',
"",
].join("\n"),
);
yield* fs.chmod(claudePath, 0o755);
return binDir;
});
}
function withFakeClaudeEnv<A, E, R>(
input: {
output: string;
exitCode?: number;
stderr?: string;
argsMustContain?: string;
argsMustNotContain?: string;
stdinMustContain?: string;
},
effect: Effect.Effect<A, E, R>,
) {
return Effect.acquireUseRelease(
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const tempDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3code-claude-text-" });
const binDir = yield* makeFakeClaudeBinary(tempDir);
const previousPath = process.env.PATH;
const previousOutput = process.env.T3_FAKE_CLAUDE_OUTPUT;
const previousExitCode = process.env.T3_FAKE_CLAUDE_EXIT_CODE;
const previousStderr = process.env.T3_FAKE_CLAUDE_STDERR;
const previousArgsMustContain = process.env.T3_FAKE_CLAUDE_ARGS_MUST_CONTAIN;
const previousArgsMustNotContain = process.env.T3_FAKE_CLAUDE_ARGS_MUST_NOT_CONTAIN;
const previousStdinMustContain = process.env.T3_FAKE_CLAUDE_STDIN_MUST_CONTAIN;
yield* Effect.sync(() => {
process.env.PATH = `${binDir}:${previousPath ?? ""}`;
process.env.T3_FAKE_CLAUDE_OUTPUT = input.output;
if (input.exitCode !== undefined) {
process.env.T3_FAKE_CLAUDE_EXIT_CODE = String(input.exitCode);
} else {
delete process.env.T3_FAKE_CLAUDE_EXIT_CODE;
}
if (input.stderr !== undefined) {
process.env.T3_FAKE_CLAUDE_STDERR = input.stderr;
} else {
delete process.env.T3_FAKE_CLAUDE_STDERR;
}
if (input.argsMustContain !== undefined) {
process.env.T3_FAKE_CLAUDE_ARGS_MUST_CONTAIN = input.argsMustContain;
} else {
delete process.env.T3_FAKE_CLAUDE_ARGS_MUST_CONTAIN;
}
if (input.argsMustNotContain !== undefined) {
process.env.T3_FAKE_CLAUDE_ARGS_MUST_NOT_CONTAIN = input.argsMustNotContain;
} else {
delete process.env.T3_FAKE_CLAUDE_ARGS_MUST_NOT_CONTAIN;
}
if (input.stdinMustContain !== undefined) {
process.env.T3_FAKE_CLAUDE_STDIN_MUST_CONTAIN = input.stdinMustContain;
} else {
delete process.env.T3_FAKE_CLAUDE_STDIN_MUST_CONTAIN;
}
});
return {
previousPath,
previousOutput,
previousExitCode,
previousStderr,
previousArgsMustContain,
previousArgsMustNotContain,
previousStdinMustContain,
};
}),
() => effect,
(previous) =>
Effect.sync(() => {
process.env.PATH = previous.previousPath;
if (previous.previousOutput === undefined) {
delete process.env.T3_FAKE_CLAUDE_OUTPUT;
} else {
process.env.T3_FAKE_CLAUDE_OUTPUT = previous.previousOutput;
}
if (previous.previousExitCode === undefined) {
delete process.env.T3_FAKE_CLAUDE_EXIT_CODE;
} else {
process.env.T3_FAKE_CLAUDE_EXIT_CODE = previous.previousExitCode;
}
if (previous.previousStderr === undefined) {
delete process.env.T3_FAKE_CLAUDE_STDERR;
} else {
process.env.T3_FAKE_CLAUDE_STDERR = previous.previousStderr;
}
if (previous.previousArgsMustContain === undefined) {
delete process.env.T3_FAKE_CLAUDE_ARGS_MUST_CONTAIN;
} else {
process.env.T3_FAKE_CLAUDE_ARGS_MUST_CONTAIN = previous.previousArgsMustContain;
}
if (previous.previousArgsMustNotContain === undefined) {
delete process.env.T3_FAKE_CLAUDE_ARGS_MUST_NOT_CONTAIN;
} else {
process.env.T3_FAKE_CLAUDE_ARGS_MUST_NOT_CONTAIN = previous.previousArgsMustNotContain;
}
if (previous.previousStdinMustContain === undefined) {
delete process.env.T3_FAKE_CLAUDE_STDIN_MUST_CONTAIN;
} else {
process.env.T3_FAKE_CLAUDE_STDIN_MUST_CONTAIN = previous.previousStdinMustContain;
}
}),
);
}
it.layer(ClaudeTextGenerationTestLayer)("ClaudeTextGenerationLive", (it) => {
it.effect("forwards Claude thinking settings for Haiku without passing effort", () =>
withFakeClaudeEnv(
{
output: JSON.stringify({
structured_output: {
subject: "Add important change",
body: "",
},
}),
argsMustContain: '--settings {"alwaysThinkingEnabled":false}',
argsMustNotContain: "--effort",
},
Effect.gen(function* () {
const textGeneration = yield* TextGeneration;
const generated = yield* textGeneration.generateCommitMessage({
cwd: process.cwd(),
branch: "feature/claude-effect",
stagedSummary: "M README.md",
stagedPatch: "diff --git a/README.md b/README.md",
modelSelection: {
...createModelSelection("claudeAgent", "claude-haiku-4-5", [
{ id: "thinking", value: false },
{ id: "effort", value: "high" },
]),
},
});
expect(generated.subject).toBe("Add important change");
}),
),
);
it.effect("forwards Claude fast mode and supported effort", () =>
withFakeClaudeEnv(
{
output: JSON.stringify({
structured_output: {
title: "Improve orchestration flow",
body: "Body",
},
}),
argsMustContain: '--effort max --settings {"fastMode":true}',
},
Effect.gen(function* () {
const textGeneration = yield* TextGeneration;
const generated = yield* textGeneration.generatePrContent({
cwd: process.cwd(),
baseBranch: "main",
headBranch: "feature/claude-effect",
commitSummary: "Improve orchestration",
diffSummary: "1 file changed",
diffPatch: "diff --git a/README.md b/README.md",
modelSelection: {
...createModelSelection("claudeAgent", "claude-opus-4-6", [
{ id: "effort", value: "max" },
{ id: "fastMode", value: true },
]),
},
});
expect(generated.title).toBe("Improve orchestration flow");
}),
),
);
it.effect("generates thread titles through the Claude provider", () =>
withFakeClaudeEnv(
{
output: JSON.stringify({
structured_output: {
title:
' "Reconnect failures after restart because the session state does not recover" ',
},
}),
stdinMustContain: "You write concise thread titles for coding conversations.",
},
Effect.gen(function* () {
const textGeneration = yield* TextGeneration;
const generated = yield* textGeneration.generateThreadTitle({
cwd: process.cwd(),
message: "Please investigate reconnect failures after restarting the session.",
modelSelection: {
provider: "claudeAgent",
model: "claude-sonnet-4-6",
},
});
expect(generated.title).toBe(
sanitizeThreadTitle(
'"Reconnect failures after restart because the session state does not recover"',
),
);
}),
),
);
it.effect("falls back when Claude thread title normalization becomes whitespace-only", () =>
withFakeClaudeEnv(
{
output: JSON.stringify({
structured_output: {
title: ' """ """ ',
},
}),
},
Effect.gen(function* () {
const textGeneration = yield* TextGeneration;
const generated = yield* textGeneration.generateThreadTitle({
cwd: process.cwd(),
message: "Name this thread.",
modelSelection: {
provider: "claudeAgent",
model: "claude-sonnet-4-6",
},
});
expect(generated.title).toBe("New thread");
}),
),
);
});
@@ -7,27 +7,27 @@
*
* @module ClaudeTextGeneration
*/
import { Effect, Option, Schema, Stream } from "effect";
import { Effect, Layer, Option, Schema, Stream } from "effect";
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
import { type ClaudeSettings, type ModelSelection } from "@t3tools/contracts";
import { ClaudeModelSelection } from "@t3tools/contracts";
import { sanitizeBranchFragment, sanitizeFeatureBranchName } from "@t3tools/shared/git";
import { TextGenerationError } from "@t3tools/contracts";
import { type TextGenerationShape } from "./TextGeneration.ts";
import { type TextGenerationShape, TextGeneration } from "../Services/TextGeneration.ts";
import {
buildBranchNamePrompt,
buildCommitMessagePrompt,
buildPrContentPrompt,
buildThreadTitlePrompt,
} from "./TextGenerationPrompts.ts";
} from "../Prompts.ts";
import {
normalizeCliError,
sanitizeCommitSubject,
sanitizePrTitle,
sanitizeThreadTitle,
toJsonSchemaObject,
} from "./TextGenerationUtils.ts";
} from "../Utils.ts";
import {
getModelSelectionStringOptionValue,
getProviderOptionDescriptors,
@@ -37,8 +37,8 @@ import {
normalizeClaudeCliEffort,
resolveClaudeApiModelId,
resolveClaudeEffort,
} from "../provider/Layers/ClaudeProvider.ts";
import { makeClaudeEnvironment } from "../provider/Drivers/ClaudeHome.ts";
} from "../../provider/Layers/ClaudeProvider.ts";
import { ServerSettingsService } from "../../serverSettings.ts";
const CLAUDE_TIMEOUT_MS = 180_000;
@@ -50,12 +50,9 @@ const ClaudeOutputEnvelope = Schema.Struct({
structured_output: Schema.Unknown,
});
export const makeClaudeTextGeneration = Effect.fn("makeClaudeTextGeneration")(function* (
claudeSettings: ClaudeSettings,
environment: NodeJS.ProcessEnv = process.env,
) {
const makeClaudeTextGeneration = Effect.gen(function* () {
const commandSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
const claudeEnvironment = yield* makeClaudeEnvironment(claudeSettings, environment);
const serverSettingsService = yield* Effect.service(ServerSettingsService);
const readStreamAsString = <E>(
operation: string,
@@ -91,7 +88,7 @@ export const makeClaudeTextGeneration = Effect.fn("makeClaudeTextGeneration")(fu
cwd: string;
prompt: string;
outputSchemaJson: S;
modelSelection: ModelSelection;
modelSelection: ClaudeModelSelection;
}): Effect.fn.Return<S["Type"], TextGenerationError, S["DecodingServices"]> {
const jsonSchemaStr = JSON.stringify(toJsonSchemaObject(outputSchemaJson));
const caps = getClaudeModelCapabilities(modelSelection.model);
@@ -114,9 +111,14 @@ export const makeClaudeTextGeneration = Effect.fn("makeClaudeTextGeneration")(fu
...(fastMode ? { fastMode: true } : {}),
};
const claudeSettings = yield* Effect.map(
serverSettingsService.getSettings,
(settings) => settings.providers.claudeAgent,
).pipe(Effect.catch(() => Effect.undefined));
const runClaudeCommand = Effect.fn("runClaudeJson.runClaudeCommand")(function* () {
const command = ChildProcess.make(
claudeSettings.binaryPath || "claude",
claudeSettings?.binaryPath || "claude",
[
"-p",
"--output-format",
@@ -130,7 +132,6 @@ export const makeClaudeTextGeneration = Effect.fn("makeClaudeTextGeneration")(fu
"--dangerously-skip-permissions",
],
{
env: claudeEnvironment,
cwd,
shell: process.platform === "win32",
stdin: {
@@ -231,6 +232,13 @@ export const makeClaudeTextGeneration = Effect.fn("makeClaudeTextGeneration")(fu
includeBranch: input.includeBranch === true,
});
if (input.modelSelection.provider !== "claudeAgent") {
return yield* new TextGenerationError({
operation: "generateCommitMessage",
detail: "Invalid model selection.",
});
}
const generated = yield* runClaudeJson({
operation: "generateCommitMessage",
cwd: input.cwd,
@@ -259,6 +267,13 @@ export const makeClaudeTextGeneration = Effect.fn("makeClaudeTextGeneration")(fu
diffPatch: input.diffPatch,
});
if (input.modelSelection.provider !== "claudeAgent") {
return yield* new TextGenerationError({
operation: "generatePrContent",
detail: "Invalid model selection.",
});
}
const generated = yield* runClaudeJson({
operation: "generatePrContent",
cwd: input.cwd,
@@ -281,6 +296,13 @@ export const makeClaudeTextGeneration = Effect.fn("makeClaudeTextGeneration")(fu
attachments: input.attachments,
});
if (input.modelSelection.provider !== "claudeAgent") {
return yield* new TextGenerationError({
operation: "generateBranchName",
detail: "Invalid model selection.",
});
}
const generated = yield* runClaudeJson({
operation: "generateBranchName",
cwd: input.cwd,
@@ -302,6 +324,13 @@ export const makeClaudeTextGeneration = Effect.fn("makeClaudeTextGeneration")(fu
attachments: input.attachments,
});
if (input.modelSelection.provider !== "claudeAgent") {
return yield* new TextGenerationError({
operation: "generateThreadTitle",
detail: "Invalid model selection.",
});
}
const generated = yield* runClaudeJson({
operation: "generateThreadTitle",
cwd: input.cwd,
@@ -322,3 +351,5 @@ export const makeClaudeTextGeneration = Effect.fn("makeClaudeTextGeneration")(fu
generateThreadTitle,
} satisfies TextGenerationShape;
});
export const ClaudeTextGenerationLive = Layer.effect(TextGeneration, makeClaudeTextGeneration);
@@ -1,24 +1,30 @@
import * as NodeServices from "@effect/platform-node/NodeServices";
import { it } from "@effect/vitest";
import { Effect, FileSystem, Layer, Path, Result, Schema } from "effect";
import { Effect, FileSystem, Layer, Path, Result } from "effect";
import { createModelSelection } from "@t3tools/shared/model";
import { expect } from "vitest";
import { CodexSettings, ProviderInstanceId, TextGenerationError } from "@t3tools/contracts";
import { ServerConfig } from "../../config.ts";
import { CodexTextGenerationLive } from "./CodexTextGeneration.ts";
import { TextGenerationError } from "@t3tools/contracts";
import { TextGeneration } from "../Services/TextGeneration.ts";
import { ServerSettingsService } from "../../serverSettings.ts";
import { ServerConfig } from "../config.ts";
import { type TextGenerationShape } from "./TextGeneration.ts";
import { makeCodexTextGeneration } from "./CodexTextGeneration.ts";
const DEFAULT_TEST_MODEL_SELECTION = {
provider: "codex" as const,
model: "gpt-5.4-mini",
};
const DEFAULT_TEST_MODEL_SELECTION = createModelSelection(
ProviderInstanceId.make("codex"),
"gpt-5.4-mini",
const CodexTextGenerationTestLayer = CodexTextGenerationLive.pipe(
Layer.provideMerge(ServerSettingsService.layerTest()),
Layer.provideMerge(
ServerConfig.layerTest(process.cwd(), {
prefix: "t3code-codex-text-generation-test-",
}),
),
Layer.provideMerge(NodeServices.layer),
);
const CodexTextGenerationTestLayer = ServerConfig.layerTest(process.cwd(), {
prefix: "t3code-codex-text-generation-test-",
}).pipe(Layer.provideMerge(NodeServices.layer));
function makeFakeCodexBinary(
dir: string,
input: {
@@ -156,19 +162,39 @@ function withFakeCodexEnv<A, E, R>(
stdinMustContain?: string;
stdinMustNotContain?: string;
},
effectFn: (textGeneration: TextGenerationShape) => Effect.Effect<A, E, R>,
effect: Effect.Effect<A, E, R>,
) {
return Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const tempDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3code-codex-text-" });
const codexPath = yield* makeFakeCodexBinary(tempDir, input);
const config = Schema.decodeSync(CodexSettings)({ binaryPath: codexPath });
const textGeneration = yield* makeCodexTextGeneration(config);
return yield* effectFn(textGeneration);
}).pipe(Effect.scoped);
return Effect.acquireUseRelease(
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const tempDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3code-codex-text-" });
const codexPath = yield* makeFakeCodexBinary(tempDir, input);
const serverSettings = yield* ServerSettingsService;
const previousSettings = yield* serverSettings.getSettings;
yield* serverSettings.updateSettings({
providers: {
codex: {
binaryPath: codexPath,
},
},
});
return { serverSettings, previousBinaryPath: previousSettings.providers.codex.binaryPath };
}),
() => effect,
({ serverSettings, previousBinaryPath }) =>
serverSettings
.updateSettings({
providers: {
codex: {
binaryPath: previousBinaryPath,
},
},
})
.pipe(Effect.asVoid),
);
}
it.layer(CodexTextGenerationTestLayer)("CodexTextGeneration", (it) => {
it.layer(CodexTextGenerationTestLayer)("CodexTextGenerationLive", (it) => {
it.effect("generates and sanitizes commit messages without branch by default", () =>
withFakeCodexEnv(
{
@@ -179,21 +205,22 @@ it.layer(CodexTextGenerationTestLayer)("CodexTextGeneration", (it) => {
}),
stdinMustNotContain: "branch must be a short semantic git branch fragment",
},
(textGeneration) =>
Effect.gen(function* () {
const generated = yield* textGeneration.generateCommitMessage({
cwd: process.cwd(),
branch: "feature/codex-effect",
stagedSummary: "M README.md",
stagedPatch: "diff --git a/README.md b/README.md",
modelSelection: DEFAULT_TEST_MODEL_SELECTION,
});
Effect.gen(function* () {
const textGeneration = yield* TextGeneration;
expect(generated.subject.length).toBeLessThanOrEqual(72);
expect(generated.subject.endsWith(".")).toBe(false);
expect(generated.body).toBe("- added migration\n- updated tests");
expect(generated.branch).toBeUndefined();
}),
const generated = yield* textGeneration.generateCommitMessage({
cwd: process.cwd(),
branch: "feature/codex-effect",
stagedSummary: "M README.md",
stagedPatch: "diff --git a/README.md b/README.md",
modelSelection: DEFAULT_TEST_MODEL_SELECTION,
});
expect(generated.subject.length).toBeLessThanOrEqual(72);
expect(generated.subject.endsWith(".")).toBe(false);
expect(generated.body).toBe("- added migration\n- updated tests");
expect(generated.branch).toBeUndefined();
}),
),
);
@@ -210,17 +237,20 @@ it.layer(CodexTextGenerationTestLayer)("CodexTextGeneration", (it) => {
requireReasoningEffort: "xhigh",
stdinMustNotContain: "branch must be a short semantic git branch fragment",
},
(textGeneration) =>
textGeneration.generateCommitMessage({
Effect.gen(function* () {
const textGeneration = yield* TextGeneration;
yield* textGeneration.generateCommitMessage({
cwd: process.cwd(),
branch: "feature/codex-effect",
stagedSummary: "M README.md",
stagedPatch: "diff --git a/README.md b/README.md",
modelSelection: createModelSelection(ProviderInstanceId.make("codex"), "gpt-5.4", [
modelSelection: createModelSelection("codex", "gpt-5.4", [
{ id: "reasoningEffort", value: "xhigh" },
{ id: "fastMode", value: true },
]),
}),
});
}),
),
);
@@ -233,14 +263,17 @@ it.layer(CodexTextGenerationTestLayer)("CodexTextGeneration", (it) => {
}),
requireReasoningEffort: "low",
},
(textGeneration) =>
textGeneration.generateCommitMessage({
Effect.gen(function* () {
const textGeneration = yield* TextGeneration;
yield* textGeneration.generateCommitMessage({
cwd: process.cwd(),
branch: "feature/codex-effect",
stagedSummary: "M README.md",
stagedPatch: "diff --git a/README.md b/README.md",
modelSelection: DEFAULT_TEST_MODEL_SELECTION,
}),
});
}),
),
);
@@ -254,20 +287,21 @@ it.layer(CodexTextGenerationTestLayer)("CodexTextGeneration", (it) => {
}),
stdinMustContain: "branch must be a short semantic git branch fragment",
},
(textGeneration) =>
Effect.gen(function* () {
const generated = yield* textGeneration.generateCommitMessage({
cwd: process.cwd(),
branch: "feature/codex-effect",
stagedSummary: "M README.md",
stagedPatch: "diff --git a/README.md b/README.md",
includeBranch: true,
modelSelection: DEFAULT_TEST_MODEL_SELECTION,
});
Effect.gen(function* () {
const textGeneration = yield* TextGeneration;
expect(generated.subject).toBe("Add important change");
expect(generated.branch).toBe("feature/fix/important-system-change");
}),
const generated = yield* textGeneration.generateCommitMessage({
cwd: process.cwd(),
branch: "feature/codex-effect",
stagedSummary: "M README.md",
stagedPatch: "diff --git a/README.md b/README.md",
includeBranch: true,
modelSelection: DEFAULT_TEST_MODEL_SELECTION,
});
expect(generated.subject).toBe("Add important change");
expect(generated.branch).toBe("feature/fix/important-system-change");
}),
),
);
@@ -279,22 +313,23 @@ it.layer(CodexTextGenerationTestLayer)("CodexTextGeneration", (it) => {
body: "\n## Summary\n- improve flow\n\n## Testing\n- bun test\n\n",
}),
},
(textGeneration) =>
Effect.gen(function* () {
const generated = yield* textGeneration.generatePrContent({
cwd: process.cwd(),
baseBranch: "main",
headBranch: "feature/codex-effect",
commitSummary: "feat: improve orchestration flow",
diffSummary: "2 files changed",
diffPatch: "diff --git a/a.ts b/a.ts",
modelSelection: DEFAULT_TEST_MODEL_SELECTION,
});
Effect.gen(function* () {
const textGeneration = yield* TextGeneration;
expect(generated.title).toBe("Improve orchestration flow");
expect(generated.body.startsWith("## Summary")).toBe(true);
expect(generated.body.endsWith("\n\n")).toBe(false);
}),
const generated = yield* textGeneration.generatePrContent({
cwd: process.cwd(),
baseBranch: "main",
headBranch: "feature/codex-effect",
commitSummary: "feat: improve orchestration flow",
diffSummary: "2 files changed",
diffPatch: "diff --git a/a.ts b/a.ts",
modelSelection: DEFAULT_TEST_MODEL_SELECTION,
});
expect(generated.title).toBe("Improve orchestration flow");
expect(generated.body.startsWith("## Summary")).toBe(true);
expect(generated.body.endsWith("\n\n")).toBe(false);
}),
),
);
@@ -306,16 +341,17 @@ it.layer(CodexTextGenerationTestLayer)("CodexTextGeneration", (it) => {
}),
stdinMustNotContain: "Image attachments supplied to the model",
},
(textGeneration) =>
Effect.gen(function* () {
const generated = yield* textGeneration.generateBranchName({
cwd: process.cwd(),
message: "Please update session handling.",
modelSelection: DEFAULT_TEST_MODEL_SELECTION,
});
Effect.gen(function* () {
const textGeneration = yield* TextGeneration;
expect(generated.branch).toBe("feat/session");
}),
const generated = yield* textGeneration.generateBranchName({
cwd: process.cwd(),
message: "Please update session handling.",
modelSelection: DEFAULT_TEST_MODEL_SELECTION,
});
expect(generated.branch).toBe("feat/session");
}),
),
);
@@ -327,16 +363,17 @@ it.layer(CodexTextGenerationTestLayer)("CodexTextGeneration", (it) => {
' "Investigate websocket reconnect regressions after worktree restore" \nignored line',
}),
},
(textGeneration) =>
Effect.gen(function* () {
const generated = yield* textGeneration.generateThreadTitle({
cwd: process.cwd(),
message: "Please investigate websocket reconnect regressions after a worktree restore.",
modelSelection: DEFAULT_TEST_MODEL_SELECTION,
});
Effect.gen(function* () {
const textGeneration = yield* TextGeneration;
expect(generated.title).toBe("Investigate websocket reconnect regressions aft...");
}),
const generated = yield* textGeneration.generateThreadTitle({
cwd: process.cwd(),
message: "Please investigate websocket reconnect regressions after a worktree restore.",
modelSelection: DEFAULT_TEST_MODEL_SELECTION,
});
expect(generated.title).toBe("Investigate websocket reconnect regressions aft...");
}),
),
);
@@ -347,16 +384,17 @@ it.layer(CodexTextGenerationTestLayer)("CodexTextGeneration", (it) => {
title: ' """ """ ',
}),
},
(textGeneration) =>
Effect.gen(function* () {
const generated = yield* textGeneration.generateThreadTitle({
cwd: process.cwd(),
message: "Name this thread.",
modelSelection: DEFAULT_TEST_MODEL_SELECTION,
});
Effect.gen(function* () {
const textGeneration = yield* TextGeneration;
expect(generated.title).toBe("New thread");
}),
const generated = yield* textGeneration.generateThreadTitle({
cwd: process.cwd(),
message: "Name this thread.",
modelSelection: DEFAULT_TEST_MODEL_SELECTION,
});
expect(generated.title).toBe("New thread");
}),
),
);
@@ -367,16 +405,17 @@ it.layer(CodexTextGenerationTestLayer)("CodexTextGeneration", (it) => {
title: ` "' hello world '" `,
}),
},
(textGeneration) =>
Effect.gen(function* () {
const generated = yield* textGeneration.generateThreadTitle({
cwd: process.cwd(),
message: "Name this thread.",
modelSelection: DEFAULT_TEST_MODEL_SELECTION,
});
Effect.gen(function* () {
const textGeneration = yield* TextGeneration;
expect(generated.title).toBe("hello world");
}),
const generated = yield* textGeneration.generateThreadTitle({
cwd: process.cwd(),
message: "Name this thread.",
modelSelection: DEFAULT_TEST_MODEL_SELECTION,
});
expect(generated.title).toBe("hello world");
}),
),
);
@@ -388,16 +427,17 @@ it.layer(CodexTextGenerationTestLayer)("CodexTextGeneration", (it) => {
}),
stdinMustNotContain: "Attachment metadata:",
},
(textGeneration) =>
Effect.gen(function* () {
const generated = yield* textGeneration.generateBranchName({
cwd: process.cwd(),
message: "Fix timeout behavior.",
modelSelection: DEFAULT_TEST_MODEL_SELECTION,
});
Effect.gen(function* () {
const textGeneration = yield* TextGeneration;
expect(generated.branch).toBe("fix/session-timeout");
}),
const generated = yield* textGeneration.generateBranchName({
cwd: process.cwd(),
message: "Fix timeout behavior.",
modelSelection: DEFAULT_TEST_MODEL_SELECTION,
});
expect(generated.branch).toBe("fix/session-timeout");
}),
),
);
@@ -410,17 +450,56 @@ it.layer(CodexTextGenerationTestLayer)("CodexTextGeneration", (it) => {
requireImage: true,
stdinMustContain: "Attachment metadata:",
},
(textGeneration) =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const { attachmentsDir } = yield* ServerConfig;
const attachmentId = `thread-branch-image-${Date.now()}-${Math.random().toString(36).slice(2, 10)}`;
const attachmentPath = path.join(attachmentsDir, `${attachmentId}.png`);
yield* fs.makeDirectory(attachmentsDir, { recursive: true });
yield* fs.writeFile(attachmentPath, Buffer.from("hello"));
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const { attachmentsDir } = yield* ServerConfig;
const attachmentId = `thread-branch-image-${Date.now()}-${Math.random().toString(36).slice(2, 10)}`;
const attachmentPath = path.join(attachmentsDir, `${attachmentId}.png`);
yield* fs.makeDirectory(attachmentsDir, { recursive: true });
yield* fs.writeFile(attachmentPath, Buffer.from("hello"));
const generated = yield* textGeneration.generateBranchName({
const textGeneration = yield* TextGeneration;
const generated = yield* textGeneration.generateBranchName({
modelSelection: DEFAULT_TEST_MODEL_SELECTION,
cwd: process.cwd(),
message: "Fix layout bug from screenshot.",
attachments: [
{
type: "image",
id: attachmentId,
name: "bug.png",
mimeType: "image/png",
sizeBytes: 5,
},
],
});
expect(generated.branch).toBe("fix/ui-regression");
}),
),
);
it.effect("resolves persisted attachment ids to files for codex image inputs", () =>
withFakeCodexEnv(
{
output: JSON.stringify({
branch: "fix/ui-regression",
}),
requireImage: true,
},
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const { attachmentsDir } = yield* ServerConfig;
const attachmentId = `thread-1-${Date.now()}-${Math.random().toString(36).slice(2, 10)}`;
const imagePath = path.join(attachmentsDir, `${attachmentId}.png`);
yield* fs.makeDirectory(attachmentsDir, { recursive: true });
yield* fs.writeFile(imagePath, Buffer.from("hello"));
const textGeneration = yield* TextGeneration;
const generated = yield* textGeneration
.generateBranchName({
modelSelection: DEFAULT_TEST_MODEL_SELECTION,
cwd: process.cwd(),
message: "Fix layout bug from screenshot.",
@@ -433,59 +512,20 @@ it.layer(CodexTextGenerationTestLayer)("CodexTextGeneration", (it) => {
sizeBytes: 5,
},
],
});
expect(generated.branch).toBe("fix/ui-regression");
}),
),
);
it.effect("resolves persisted attachment ids to files for codex image inputs", () =>
withFakeCodexEnv(
{
output: JSON.stringify({
branch: "fix/ui-regression",
}),
requireImage: true,
},
(textGeneration) =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const { attachmentsDir } = yield* ServerConfig;
const attachmentId = `thread-1-${Date.now()}-${Math.random().toString(36).slice(2, 10)}`;
const imagePath = path.join(attachmentsDir, `${attachmentId}.png`);
yield* fs.makeDirectory(attachmentsDir, { recursive: true });
yield* fs.writeFile(imagePath, Buffer.from("hello"));
const generated = yield* textGeneration
.generateBranchName({
modelSelection: DEFAULT_TEST_MODEL_SELECTION,
cwd: process.cwd(),
message: "Fix layout bug from screenshot.",
attachments: [
{
type: "image",
id: attachmentId,
name: "bug.png",
mimeType: "image/png",
sizeBytes: 5,
},
],
})
.pipe(
Effect.tap(() =>
fs.stat(imagePath).pipe(
Effect.map((fileInfo) => {
expect(fileInfo.type).toBe("File");
}),
),
})
.pipe(
Effect.tap(() =>
fs.stat(imagePath).pipe(
Effect.map((fileInfo) => {
expect(fileInfo.type).toBe("File");
}),
),
Effect.ensuring(fs.remove(imagePath).pipe(Effect.catch(() => Effect.void))),
);
),
Effect.ensuring(fs.remove(imagePath).pipe(Effect.catch(() => Effect.void))),
);
expect(generated.branch).toBe("fix/ui-regression");
}),
expect(generated.branch).toBe("fix/ui-regression");
}),
),
);
@@ -497,38 +537,38 @@ it.layer(CodexTextGenerationTestLayer)("CodexTextGeneration", (it) => {
}),
requireImage: true,
},
(textGeneration) =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const { attachmentsDir } = yield* ServerConfig;
const missingAttachmentId = `thread-missing-${Date.now()}-${Math.random().toString(36).slice(2, 10)}`;
const missingPath = path.join(attachmentsDir, `${missingAttachmentId}.png`);
yield* fs.remove(missingPath).pipe(Effect.catch(() => Effect.void));
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const { attachmentsDir } = yield* ServerConfig;
const missingAttachmentId = `thread-missing-${Date.now()}-${Math.random().toString(36).slice(2, 10)}`;
const missingPath = path.join(attachmentsDir, `${missingAttachmentId}.png`);
yield* fs.remove(missingPath).pipe(Effect.catch(() => Effect.void));
const result = yield* textGeneration
.generateBranchName({
modelSelection: DEFAULT_TEST_MODEL_SELECTION,
cwd: process.cwd(),
message: "Fix layout bug from screenshot.",
attachments: [
{
type: "image",
id: missingAttachmentId,
name: "outside.png",
mimeType: "image/png",
sizeBytes: 5,
},
],
})
.pipe(Effect.result);
const textGeneration = yield* TextGeneration;
const result = yield* textGeneration
.generateBranchName({
modelSelection: DEFAULT_TEST_MODEL_SELECTION,
cwd: process.cwd(),
message: "Fix layout bug from screenshot.",
attachments: [
{
type: "image",
id: missingAttachmentId,
name: "outside.png",
mimeType: "image/png",
sizeBytes: 5,
},
],
})
.pipe(Effect.result);
expect(Result.isFailure(result)).toBe(true);
if (Result.isFailure(result)) {
expect(result.failure).toBeInstanceOf(TextGenerationError);
expect(result.failure.message).toContain("missing --image input");
}
}),
expect(Result.isFailure(result)).toBe(true);
if (Result.isFailure(result)) {
expect(result.failure).toBeInstanceOf(TextGenerationError);
expect(result.failure.message).toContain("missing --image input");
}
}),
),
);
@@ -541,22 +581,23 @@ it.layer(CodexTextGenerationTestLayer)("CodexTextGeneration", (it) => {
title: "This is not a branch payload",
}),
},
(textGeneration) =>
Effect.gen(function* () {
const result = yield* textGeneration
.generateBranchName({
cwd: process.cwd(),
message: "Fix websocket reconnect flake",
modelSelection: DEFAULT_TEST_MODEL_SELECTION,
})
.pipe(Effect.result);
Effect.gen(function* () {
const textGeneration = yield* TextGeneration;
expect(Result.isFailure(result)).toBe(true);
if (Result.isFailure(result)) {
expect(result.failure).toBeInstanceOf(TextGenerationError);
expect(result.failure.message).toContain("Codex returned invalid structured output");
}
}),
const result = yield* textGeneration
.generateBranchName({
cwd: process.cwd(),
message: "Fix websocket reconnect flake",
modelSelection: DEFAULT_TEST_MODEL_SELECTION,
})
.pipe(Effect.result);
expect(Result.isFailure(result)).toBe(true);
if (Result.isFailure(result)) {
expect(result.failure).toBeInstanceOf(TextGenerationError);
expect(result.failure.message).toContain("Codex returned invalid structured output");
}
}),
),
);
@@ -567,26 +608,27 @@ it.layer(CodexTextGenerationTestLayer)("CodexTextGeneration", (it) => {
exitCode: 1,
stderr: "codex execution failed",
},
(textGeneration) =>
Effect.gen(function* () {
const result = yield* textGeneration
.generateCommitMessage({
cwd: process.cwd(),
branch: "feature/codex-error",
stagedSummary: "M README.md",
stagedPatch: "diff --git a/README.md b/README.md",
modelSelection: DEFAULT_TEST_MODEL_SELECTION,
})
.pipe(Effect.result);
Effect.gen(function* () {
const textGeneration = yield* TextGeneration;
expect(Result.isFailure(result)).toBe(true);
if (Result.isFailure(result)) {
expect(result.failure).toBeInstanceOf(TextGenerationError);
expect(result.failure.message).toContain(
"Codex CLI command failed: codex execution failed",
);
}
}),
const result = yield* textGeneration
.generateCommitMessage({
cwd: process.cwd(),
branch: "feature/codex-error",
stagedSummary: "M README.md",
stagedPatch: "diff --git a/README.md b/README.md",
modelSelection: DEFAULT_TEST_MODEL_SELECTION,
})
.pipe(Effect.result);
expect(Result.isFailure(result)).toBe(true);
if (Result.isFailure(result)) {
expect(result.failure).toBeInstanceOf(TextGenerationError);
expect(result.failure.message).toContain(
"Codex CLI command failed: codex execution failed",
);
}
}),
),
);
});
@@ -1,31 +1,35 @@
import { Effect, FileSystem, Option, Path, Random, Schema, Scope, Stream } from "effect";
import { randomUUID } from "node:crypto";
import { Effect, FileSystem, Layer, Option, Path, Schema, Scope, Stream } from "effect";
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
import { type CodexSettings, type ModelSelection } from "@t3tools/contracts";
import { CodexModelSelection } from "@t3tools/contracts";
import { sanitizeBranchFragment, sanitizeFeatureBranchName } from "@t3tools/shared/git";
import { resolveAttachmentPath } from "../attachmentStore.ts";
import { ServerConfig } from "../config.ts";
import { expandHomePath } from "../pathExpansion.ts";
import { resolveAttachmentPath } from "../../attachmentStore.ts";
import { ServerConfig } from "../../config.ts";
import { expandHomePath } from "../../pathExpansion.ts";
import { TextGenerationError } from "@t3tools/contracts";
import {
type BranchNameGenerationInput,
type ThreadTitleGenerationResult,
type TextGenerationShape,
} from "./TextGeneration.ts";
TextGeneration,
} from "../Services/TextGeneration.ts";
import {
buildBranchNamePrompt,
buildCommitMessagePrompt,
buildPrContentPrompt,
buildThreadTitlePrompt,
} from "./TextGenerationPrompts.ts";
} from "../Prompts.ts";
import {
normalizeCliError,
sanitizeCommitSubject,
sanitizePrTitle,
sanitizeThreadTitle,
toJsonSchemaObject,
} from "./TextGenerationUtils.ts";
} from "../Utils.ts";
import { ServerSettingsService } from "../../serverSettings.ts";
import {
getModelSelectionBooleanOptionValue,
getModelSelectionStringOptionValue,
@@ -33,18 +37,12 @@ import {
const CODEX_GIT_TEXT_GENERATION_REASONING_EFFORT = "low";
const CODEX_TIMEOUT_MS = 180_000;
/**
* Build a Codex text-generation closure bound to a specific `CodexSettings`
* payload. See `makeCodexAdapter` for the overall per-instance rationale.
*/
export const makeCodexTextGeneration = Effect.fn("makeCodexTextGeneration")(function* (
codexConfig: CodexSettings,
environment: NodeJS.ProcessEnv = process.env,
) {
const makeCodexTextGeneration = Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const commandSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
const serverConfig = yield* Effect.service(ServerConfig);
const serverSettingsService = yield* Effect.service(ServerSettingsService);
type MaterializedImageAttachments = {
readonly imagePaths: ReadonlyArray<string>;
@@ -70,23 +68,21 @@ export const makeCodexTextGeneration = Effect.fn("makeCodexTextGeneration")(func
prefix: string,
content: string,
): Effect.Effect<string, TextGenerationError, Scope.Scope> => {
return Effect.gen(function* () {
const tempFileId = yield* Random.nextUUIDv4;
return yield* fileSystem
.makeTempFileScoped({
prefix: `t3code-${prefix}-${process.pid}-${tempFileId}.tmp`,
})
.pipe(Effect.tap((filePath) => fileSystem.writeFileString(filePath, content)));
}).pipe(
Effect.mapError(
(cause) =>
new TextGenerationError({
operation,
detail: `Failed to write temp file`,
cause,
}),
),
);
return fileSystem
.makeTempFileScoped({
prefix: `t3code-${prefix}-${process.pid}-${randomUUID()}.tmp`,
})
.pipe(
Effect.tap((filePath) => fileSystem.writeFileString(filePath, content)),
Effect.mapError(
(cause) =>
new TextGenerationError({
operation,
detail: `Failed to write temp file`,
cause,
}),
),
);
};
const safeUnlink = (filePath: string): Effect.Effect<void, never> =>
@@ -147,7 +143,7 @@ export const makeCodexTextGeneration = Effect.fn("makeCodexTextGeneration")(func
outputSchemaJson: S;
imagePaths?: ReadonlyArray<string>;
cleanupPaths?: ReadonlyArray<string>;
modelSelection: ModelSelection;
modelSelection: CodexModelSelection;
}): Effect.fn.Return<S["Type"], TextGenerationError, S["DecodingServices"]> {
const schemaPath = yield* writeTempFile(
operation,
@@ -156,12 +152,17 @@ export const makeCodexTextGeneration = Effect.fn("makeCodexTextGeneration")(func
);
const outputPath = yield* writeTempFile(operation, "codex-output", "");
const codexSettings = yield* Effect.map(
serverSettingsService.getSettings,
(settings) => settings.providers.codex,
).pipe(Effect.catch(() => Effect.undefined));
const runCodexCommand = Effect.fn("runCodexJson.runCodexCommand")(function* () {
const reasoningEffort =
getModelSelectionStringOptionValue(modelSelection, "reasoningEffort") ??
CODEX_GIT_TEXT_GENERATION_REASONING_EFFORT;
const command = ChildProcess.make(
codexConfig.binaryPath || "codex",
codexSettings?.binaryPath || "codex",
[
"exec",
"--ephemeral",
@@ -184,8 +185,10 @@ export const makeCodexTextGeneration = Effect.fn("makeCodexTextGeneration")(func
],
{
env: {
...environment,
...(codexConfig.homePath ? { CODEX_HOME: expandHomePath(codexConfig.homePath) } : {}),
...process.env,
...(codexSettings?.homePath
? { CODEX_HOME: expandHomePath(codexSettings.homePath) }
: {}),
},
cwd,
shell: process.platform === "win32",
@@ -285,6 +288,13 @@ export const makeCodexTextGeneration = Effect.fn("makeCodexTextGeneration")(func
includeBranch: input.includeBranch === true,
});
if (input.modelSelection.provider !== "codex") {
return yield* new TextGenerationError({
operation: "generateCommitMessage",
detail: "Invalid model selection.",
});
}
const generated = yield* runCodexJson({
operation: "generateCommitMessage",
cwd: input.cwd,
@@ -313,6 +323,13 @@ export const makeCodexTextGeneration = Effect.fn("makeCodexTextGeneration")(func
diffPatch: input.diffPatch,
});
if (input.modelSelection.provider !== "codex") {
return yield* new TextGenerationError({
operation: "generatePrContent",
detail: "Invalid model selection.",
});
}
const generated = yield* runCodexJson({
operation: "generatePrContent",
cwd: input.cwd,
@@ -339,6 +356,13 @@ export const makeCodexTextGeneration = Effect.fn("makeCodexTextGeneration")(func
attachments: input.attachments,
});
if (input.modelSelection.provider !== "codex") {
return yield* new TextGenerationError({
operation: "generateBranchName",
detail: "Invalid model selection.",
});
}
const generated = yield* runCodexJson({
operation: "generateBranchName",
cwd: input.cwd,
@@ -365,6 +389,13 @@ export const makeCodexTextGeneration = Effect.fn("makeCodexTextGeneration")(func
attachments: input.attachments,
});
if (input.modelSelection.provider !== "codex") {
return yield* new TextGenerationError({
operation: "generateThreadTitle",
detail: "Invalid model selection.",
});
}
const generated = yield* runCodexJson({
operation: "generateThreadTitle",
cwd: input.cwd,
@@ -386,3 +417,5 @@ export const makeCodexTextGeneration = Effect.fn("makeCodexTextGeneration")(func
generateThreadTitle,
} satisfies TextGenerationShape;
});
export const CodexTextGenerationLive = Layer.effect(TextGeneration, makeCodexTextGeneration);
@@ -0,0 +1,297 @@
import * as path from "node:path";
import * as os from "node:os";
import { fileURLToPath } from "node:url";
import { chmodSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { it } from "@effect/vitest";
import { Effect, Layer } from "effect";
import { createModelSelection } from "@t3tools/shared/model";
import { expect } from "vitest";
import { ServerSettingsError } from "@t3tools/contracts";
import { ServerConfig } from "../../config.ts";
import { TextGeneration } from "../Services/TextGeneration.ts";
import { CursorTextGenerationLive } from "./CursorTextGeneration.ts";
import { ServerSettingsService } from "../../serverSettings.ts";
const __dirname = path.dirname(fileURLToPath(import.meta.url));
const mockAgentPath = path.join(__dirname, "../../../scripts/acp-mock-agent.ts");
function shellSingleQuote(value: string): string {
return `'${value.replaceAll("'", `'"'"'`)}'`;
}
const CursorTextGenerationTestLayer = CursorTextGenerationLive.pipe(
Layer.provideMerge(ServerSettingsService.layerTest()),
Layer.provideMerge(
ServerConfig.layerTest(process.cwd(), {
prefix: "t3code-cursor-text-generation-test-",
}),
),
Layer.provideMerge(NodeServices.layer),
);
function makeAcpAgentWrapper(dir: string, env: Record<string, string>): string {
const binDir = path.join(dir, "bin");
const agentPath = path.join(binDir, "agent");
mkdirSync(binDir, { recursive: true });
writeFileSync(
agentPath,
[
"#!/bin/sh",
...Object.entries(env).map(([key, value]) => `export ${key}=${shellSingleQuote(value)}`),
'if [ "$1" != "acp" ]; then',
' printf "%s\\n" "unexpected args: $*" >&2',
" exit 11",
"fi",
`exec bun ${JSON.stringify(mockAgentPath)}`,
"",
].join("\n"),
"utf8",
);
chmodSync(agentPath, 0o755);
return agentPath;
}
function withFakeAcpAgent<A, E, R>(
env: Record<string, string>,
effect: Effect.Effect<A, E, R>,
): Effect.Effect<A, E | ServerSettingsError, R | ServerSettingsService> {
return Effect.gen(function* () {
const tempDir = mkdtempSync(path.join(os.tmpdir(), "t3code-cursor-text-acp-"));
const agentPath = makeAcpAgentWrapper(tempDir, env);
const serverSettings = yield* ServerSettingsService;
const previousSettings = yield* serverSettings.getSettings;
yield* serverSettings.updateSettings({
providers: {
cursor: {
binaryPath: agentPath,
},
},
});
return yield* effect.pipe(
Effect.ensuring(
serverSettings
.updateSettings({
providers: {
cursor: {
binaryPath: previousSettings.providers.cursor.binaryPath,
},
},
})
.pipe(
Effect.catch(() => Effect.void),
Effect.ensuring(
Effect.sync(() => {
rmSync(tempDir, { recursive: true, force: true });
}),
),
Effect.asVoid,
),
),
);
});
}
function waitForFileContent(path: string): Effect.Effect<string> {
return Effect.promise(async () => {
const deadline = Date.now() + 5_000;
for (;;) {
try {
return readFileSync(path, "utf8");
} catch (error) {
if (Date.now() >= deadline) {
throw error instanceof Error ? error : new Error(String(error));
}
}
await new Promise((resolve) => setTimeout(resolve, 25));
}
});
}
it.layer(CursorTextGenerationTestLayer)("CursorTextGenerationLive", (it) => {
it.effect("uses ACP model config options instead of raw CLI model ids", () => {
const requestLogDir = mkdtempSync(path.join(os.tmpdir(), "t3code-cursor-text-log-"));
const requestLogPath = path.join(requestLogDir, "requests.ndjson");
return withFakeAcpAgent(
{
T3_ACP_REQUEST_LOG_PATH: requestLogPath,
T3_ACP_PROMPT_RESPONSE_TEXT: JSON.stringify({
subject: "Add generated commit message",
body: "- verify cursor acp model config path",
}),
},
Effect.gen(function* () {
const textGeneration = yield* TextGeneration;
const generated = yield* textGeneration.generateCommitMessage({
cwd: process.cwd(),
branch: "feature/cursor-text-generation",
stagedSummary: "M apps/server/src/git/Layers/CursorTextGeneration.ts",
stagedPatch:
"diff --git a/apps/server/src/git/Layers/CursorTextGeneration.ts b/apps/server/src/git/Layers/CursorTextGeneration.ts",
modelSelection: {
...createModelSelection("cursor", "gpt-5.4", [
{ id: "reasoning", value: "xhigh" },
{ id: "fastMode", value: true },
{ id: "contextWindow", value: "1m" },
]),
},
});
expect(generated.subject).toBe("Add generated commit message");
expect(generated.body).toBe("- verify cursor acp model config path");
const requests = readFileSync(requestLogPath, "utf8")
.trim()
.split("\n")
.filter((line) => line.length > 0)
.map((line) => JSON.parse(line) as { method?: string; params?: Record<string, unknown> });
expect(
requests.find((request) => request.method === "initialize")?.params?.clientCapabilities,
).toMatchObject({
_meta: {
parameterizedModelPicker: true,
},
});
expect(
requests.some(
(request) =>
request.method === "session/set_config_option" &&
request.params?.configId === "model" &&
request.params?.value === "gpt-5.4",
),
).toBe(true);
expect(
requests.some(
(request) =>
request.method === "session/set_config_option" &&
request.params?.configId === "reasoning" &&
request.params?.value === "extra-high",
),
).toBe(true);
expect(
requests.some(
(request) =>
request.method === "session/set_config_option" &&
request.params?.configId === "context" &&
request.params?.value === "1m",
),
).toBe(true);
expect(
requests.some(
(request) =>
request.method === "session/set_config_option" &&
request.params?.configId === "fast" &&
request.params?.value === "true",
),
).toBe(true);
expect(
requests.find((request) => request.method === "session/prompt")?.params?.prompt,
).toEqual(
expect.arrayContaining([
expect.objectContaining({
type: "text",
text: expect.stringContaining("Staged patch:"),
}),
]),
);
rmSync(requestLogDir, { recursive: true, force: true });
}),
);
});
it.effect("accepts json objects with extra assistant text around them", () =>
withFakeAcpAgent(
{
T3_ACP_PROMPT_RESPONSE_TEXT:
'Sure, here is the JSON:\n```json\n{\n "subject": "Update README dummy comment with attribution and date",\n "body": ""\n}\n```\nDone.',
},
Effect.gen(function* () {
const textGeneration = yield* TextGeneration;
const generated = yield* textGeneration.generateCommitMessage({
cwd: process.cwd(),
branch: "feature/cursor-noisy-json",
stagedSummary: "M README.md",
stagedPatch: "diff --git a/README.md b/README.md",
modelSelection: {
provider: "cursor",
model: "composer-2",
},
});
expect(generated.subject).toBe("Update README dummy comment with attribution and date");
expect(generated.body).toBe("");
}),
),
);
it.effect("generates thread titles through Cursor ACP text generation", () =>
withFakeAcpAgent(
{
T3_ACP_PROMPT_RESPONSE_TEXT: JSON.stringify({
title: '"Trim reconnect spinner status after resume."',
}),
},
Effect.gen(function* () {
const textGeneration = yield* TextGeneration;
const generated = yield* textGeneration.generateThreadTitle({
cwd: process.cwd(),
message: "Fix the reconnect spinner after a resumed session.",
modelSelection: {
provider: "cursor",
model: "composer-2",
},
});
expect(generated.title).toBe("Trim reconnect spinner status after resume.");
}),
),
);
it.effect("closes the ACP child process after text generation completes", () => {
const exitLogDir = mkdtempSync(path.join(os.tmpdir(), "t3code-cursor-text-exit-log-"));
const exitLogPath = path.join(exitLogDir, "exit.log");
return withFakeAcpAgent(
{
T3_ACP_EXIT_LOG_PATH: exitLogPath,
T3_ACP_PROMPT_RESPONSE_TEXT: JSON.stringify({
subject: "Close runtime after generation",
body: "",
}),
},
Effect.gen(function* () {
const textGeneration = yield* TextGeneration;
const generated = yield* textGeneration.generateCommitMessage({
cwd: process.cwd(),
branch: "feature/cursor-runtime-close",
stagedSummary: "M apps/server/src/git/Layers/CursorTextGeneration.ts",
stagedPatch:
"diff --git a/apps/server/src/git/Layers/CursorTextGeneration.ts b/apps/server/src/git/Layers/CursorTextGeneration.ts",
modelSelection: {
provider: "cursor",
model: "composer-2",
},
});
expect(generated.subject).toBe("Close runtime after generation");
const exitLog = yield* waitForFileContent(exitLogPath);
expect(exitLog).toContain("exit:0");
rmSync(exitLogDir, { recursive: true, force: true });
}),
);
});
});
@@ -1,27 +1,32 @@
import { Effect, Option, Ref, Schema } from "effect";
import { Effect, Layer, Option, Ref, Schema } from "effect";
import { ChildProcessSpawner } from "effect/unstable/process";
import { type CursorSettings, type ModelSelection } from "@t3tools/contracts";
import { CursorModelSelection } from "@t3tools/contracts";
import { sanitizeBranchFragment, sanitizeFeatureBranchName } from "@t3tools/shared/git";
import { TextGenerationError } from "@t3tools/contracts";
import { type ThreadTitleGenerationResult, type TextGenerationShape } from "./TextGeneration.ts";
import {
type ThreadTitleGenerationResult,
type TextGenerationShape,
TextGeneration,
} from "../Services/TextGeneration.ts";
import {
buildBranchNamePrompt,
buildCommitMessagePrompt,
buildPrContentPrompt,
buildThreadTitlePrompt,
} from "./TextGenerationPrompts.ts";
} from "../Prompts.ts";
import {
extractJsonObject,
sanitizeCommitSubject,
sanitizePrTitle,
sanitizeThreadTitle,
} from "./TextGenerationUtils.ts";
} from "../Utils.ts";
import {
applyCursorAcpModelSelection,
makeCursorAcpRuntime,
} from "../provider/acp/CursorAcpSupport.ts";
} from "../../provider/acp/CursorAcpSupport.ts";
import { ServerSettingsService } from "../../serverSettings.ts";
const CURSOR_TIMEOUT_MS = 180_000;
@@ -50,15 +55,9 @@ function isTextGenerationError(error: unknown): error is TextGenerationError {
);
}
/**
* Build a Cursor text-generation closure bound to a specific `CursorSettings`
* payload. See `makeCodexAdapter` for the overall per-instance rationale.
*/
export const makeCursorTextGeneration = Effect.fn("makeCursorTextGeneration")(function* (
cursorSettings: CursorSettings,
environment: NodeJS.ProcessEnv = process.env,
) {
const makeCursorTextGeneration = Effect.gen(function* () {
const commandSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
const serverSettingsService = yield* Effect.service(ServerSettingsService);
const runCursorJson = <S extends Schema.Top>({
operation,
@@ -75,13 +74,17 @@ export const makeCursorTextGeneration = Effect.fn("makeCursorTextGeneration")(fu
cwd: string;
prompt: string;
outputSchemaJson: S;
modelSelection: ModelSelection;
modelSelection: CursorModelSelection;
}): Effect.Effect<S["Type"], TextGenerationError, S["DecodingServices"]> =>
Effect.gen(function* () {
const cursorSettings = yield* Effect.map(
serverSettingsService.getSettings,
(settings) => settings.providers.cursor,
).pipe(Effect.catch(() => Effect.undefined));
const outputRef = yield* Ref.make("");
const runtime = yield* makeCursorAcpRuntime({
cursorSettings,
environment,
childProcessSpawner: commandSpawner,
cwd,
clientInfo: { name: "t3-code-git-text", version: "0.0.0" },
@@ -183,6 +186,13 @@ export const makeCursorTextGeneration = Effect.fn("makeCursorTextGeneration")(fu
includeBranch: input.includeBranch === true,
});
if (input.modelSelection.provider !== "cursor") {
return yield* new TextGenerationError({
operation: "generateCommitMessage",
detail: "Invalid model selection.",
});
}
const generated = yield* runCursorJson({
operation: "generateCommitMessage",
cwd: input.cwd,
@@ -211,6 +221,13 @@ export const makeCursorTextGeneration = Effect.fn("makeCursorTextGeneration")(fu
diffPatch: input.diffPatch,
});
if (input.modelSelection.provider !== "cursor") {
return yield* new TextGenerationError({
operation: "generatePrContent",
detail: "Invalid model selection.",
});
}
const generated = yield* runCursorJson({
operation: "generatePrContent",
cwd: input.cwd,
@@ -233,6 +250,13 @@ export const makeCursorTextGeneration = Effect.fn("makeCursorTextGeneration")(fu
attachments: input.attachments,
});
if (input.modelSelection.provider !== "cursor") {
return yield* new TextGenerationError({
operation: "generateBranchName",
detail: "Invalid model selection.",
});
}
const generated = yield* runCursorJson({
operation: "generateBranchName",
cwd: input.cwd,
@@ -254,6 +278,13 @@ export const makeCursorTextGeneration = Effect.fn("makeCursorTextGeneration")(fu
attachments: input.attachments,
});
if (input.modelSelection.provider !== "cursor") {
return yield* new TextGenerationError({
operation: "generateThreadTitle",
detail: "Invalid model selection.",
});
}
const generated = yield* runCursorJson({
operation: "generateThreadTitle",
cwd: input.cwd,
@@ -274,3 +305,5 @@ export const makeCursorTextGeneration = Effect.fn("makeCursorTextGeneration")(fu
generateThreadTitle,
} satisfies TextGenerationShape;
});
export const CursorTextGenerationLive = Layer.effect(TextGeneration, makeCursorTextGeneration);
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
@@ -2,21 +2,22 @@ import { assert, it } from "@effect/vitest";
import { Effect } from "effect";
import { afterEach, expect, vi } from "vitest";
vi.mock("../processRunner", () => ({
vi.mock("../../processRunner", () => ({
runProcess: vi.fn(),
}));
import { runProcess } from "../processRunner.ts";
import * as GitHubCli from "./GitHubCli.ts";
import { runProcess } from "../../processRunner.ts";
import { GitHubCli } from "../Services/GitHubCli.ts";
import { GitHubCliLive } from "./GitHubCli.ts";
const mockedRunProcess = vi.mocked(runProcess);
const layer = it.layer(GitHubCli.layer);
const layer = it.layer(GitHubCliLive);
afterEach(() => {
mockedRunProcess.mockReset();
});
layer("GitHubCli.layer", (it) => {
layer("GitHubCliLive", (it) => {
it.effect("parses pull request view output", () =>
Effect.gen(function* () {
mockedRunProcess.mockResolvedValueOnce({
@@ -43,7 +44,7 @@ layer("GitHubCli.layer", (it) => {
});
const result = yield* Effect.gen(function* () {
const gh = yield* GitHubCli.GitHubCli;
const gh = yield* GitHubCli;
return yield* gh.getPullRequest({
cwd: "/repo",
reference: "#42",
@@ -101,7 +102,7 @@ layer("GitHubCli.layer", (it) => {
});
const result = yield* Effect.gen(function* () {
const gh = yield* GitHubCli.GitHubCli;
const gh = yield* GitHubCli;
return yield* gh.getPullRequest({
cwd: "/repo",
reference: "#42",
@@ -154,7 +155,7 @@ layer("GitHubCli.layer", (it) => {
});
const result = yield* Effect.gen(function* () {
const gh = yield* GitHubCli.GitHubCli;
const gh = yield* GitHubCli;
return yield* gh.listOpenPullRequests({
cwd: "/repo",
headSelector: "feature/pr-list",
@@ -189,7 +190,7 @@ layer("GitHubCli.layer", (it) => {
});
const result = yield* Effect.gen(function* () {
const gh = yield* GitHubCli.GitHubCli;
const gh = yield* GitHubCli;
return yield* gh.getRepositoryCloneUrls({
cwd: "/repo",
repository: "octocat/codething-mvp",
@@ -213,7 +214,7 @@ layer("GitHubCli.layer", (it) => {
);
const error = yield* Effect.gen(function* () {
const gh = yield* GitHubCli.GitHubCli;
const gh = yield* GitHubCli;
return yield* gh.getPullRequest({
cwd: "/repo",
reference: "4888",
@@ -1,81 +1,21 @@
import { Context, Effect, Layer, Result, Schema, SchemaIssue } from "effect";
import { Effect, Layer, Result, Schema, SchemaIssue } from "effect";
import { TrimmedNonEmptyString } from "@t3tools/contracts";
import { GitHubCliError, TrimmedNonEmptyString } from "@t3tools/contracts";
import type { ProcessRunResult } from "../processRunner.ts";
import { runProcess } from "../processRunner.ts";
import { runProcess } from "../../processRunner.ts";
import { GitHubCliError } from "@t3tools/contracts";
import {
GitHubCli,
type GitHubRepositoryCloneUrls,
type GitHubCliShape,
} from "../Services/GitHubCli.ts";
import {
decodeGitHubPullRequestJson,
decodeGitHubPullRequestListJson,
formatGitHubJsonDecodeError,
} from "../git/githubPullRequests.ts";
} from "../githubPullRequests.ts";
const DEFAULT_TIMEOUT_MS = 30_000;
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;
}
export interface GitHubCliShape {
readonly execute: (input: {
readonly cwd: string;
readonly args: ReadonlyArray<string>;
readonly timeoutMs?: number;
}) => Effect.Effect<ProcessRunResult, GitHubCliError>;
readonly listOpenPullRequests: (input: {
readonly cwd: string;
readonly headSelector: string;
readonly limit?: number;
}) => Effect.Effect<ReadonlyArray<GitHubPullRequestSummary>, GitHubCliError>;
readonly getPullRequest: (input: {
readonly cwd: string;
readonly reference: string;
}) => Effect.Effect<GitHubPullRequestSummary, GitHubCliError>;
readonly getRepositoryCloneUrls: (input: {
readonly cwd: string;
readonly repository: string;
}) => Effect.Effect<GitHubRepositoryCloneUrls, GitHubCliError>;
readonly createPullRequest: (input: {
readonly cwd: string;
readonly baseBranch: string;
readonly headSelector: string;
readonly title: string;
readonly bodyFile: string;
}) => Effect.Effect<void, GitHubCliError>;
readonly getDefaultBranch: (input: {
readonly cwd: string;
}) => Effect.Effect<string | null, GitHubCliError>;
readonly checkoutPullRequest: (input: {
readonly cwd: string;
readonly reference: string;
readonly force?: boolean;
}) => Effect.Effect<void, GitHubCliError>;
}
export class GitHubCli extends Context.Service<GitHubCli, GitHubCliShape>()(
"t3/source-control/GitHubCli",
) {}
function normalizeGitHubCliError(operation: "execute" | "stdout", error: unknown): GitHubCliError {
if (error instanceof Error) {
if (error.message.includes("Command not found: gh")) {
@@ -161,7 +101,7 @@ function decodeGitHubJson<S extends Schema.Top>(
);
}
export const make = Effect.sync(() => {
const makeGitHubCli = Effect.sync(() => {
const execute: GitHubCliShape["execute"] = (input) =>
Effect.tryPromise({
try: () =>
@@ -172,7 +112,7 @@ export const make = Effect.sync(() => {
catch: (error) => normalizeGitHubCliError("execute", error),
});
return GitHubCli.of({
const service = {
execute,
listOpenPullRequests: (input) =>
execute({
@@ -292,7 +232,9 @@ export const make = Effect.sync(() => {
cwd: input.cwd,
args: ["pr", "checkout", input.reference, ...(input.force ? ["--force"] : [])],
}).pipe(Effect.asVoid),
});
} satisfies GitHubCliShape;
return service;
});
export const layer = Layer.effect(GitHubCli, make);
export const GitHubCliLive = Layer.effect(GitHubCli, makeGitHubCli);
@@ -14,25 +14,23 @@ import type {
} from "@t3tools/contracts";
import { GitCommandError, GitHubCliError, TextGenerationError } from "@t3tools/contracts";
import { type GitManagerShape } from "./GitManager.ts";
import { type GitManagerShape } from "../Services/GitManager.ts";
import {
type GitHubCliShape,
type GitHubPullRequestSummary,
GitHubCli,
} 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";
} from "../Services/GitHubCli.ts";
import { type TextGenerationShape, TextGeneration } from "../Services/TextGeneration.ts";
import { GitCoreLive } from "./GitCore.ts";
import { GitCore } from "../Services/GitCore.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[];
@@ -211,27 +209,18 @@ function runGit(
args: readonly string[],
allowNonZeroExit = false,
): Effect.Effect<
{
readonly exitCode: GitVcsDriver.ExecuteGitResult["exitCode"];
readonly stdout: string;
readonly stderr: string;
},
{ readonly code: number; readonly stdout: string; readonly stderr: string },
GitCommandError,
GitVcsDriver.GitVcsDriver
GitCore
> {
return Effect.gen(function* () {
const git = yield* GitVcsDriver.GitVcsDriver;
const result = yield* git.execute({
const gitCore = yield* GitCore;
return yield* gitCore.execute({
operation: "GitManager.test.runGit",
cwd,
args,
allowNonZeroExit,
});
return {
exitCode: result.exitCode,
stdout: result.stdout,
stderr: result.stderr,
};
});
}
@@ -240,7 +229,7 @@ function initRepo(
): Effect.Effect<
void,
PlatformError.PlatformError | GitCommandError,
FileSystem.FileSystem | Scope.Scope | GitVcsDriver.GitVcsDriver
FileSystem.FileSystem | Scope.Scope | GitCore
> {
return Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
@@ -256,7 +245,7 @@ function initRepo(
function createBareRemote(): Effect.Effect<
string,
PlatformError.PlatformError | GitCommandError,
FileSystem.FileSystem | Scope.Scope | GitVcsDriver.GitVcsDriver
FileSystem.FileSystem | Scope.Scope | GitCore
> {
return Effect.gen(function* () {
const remoteDir = yield* makeTempDir("t3code-git-remote-");
@@ -270,7 +259,7 @@ function configureRemote(
remoteName: string,
remotePath: string,
fetchNamespace: string,
): Effect.Effect<void, GitCommandError, GitVcsDriver.GitVcsDriver> {
): Effect.Effect<void, GitCommandError, GitCore> {
return Effect.gen(function* () {
yield* runGit(cwd, ["config", `remote.${remoteName}.url`, remotePath]);
yield* runGit(cwd, [
@@ -650,24 +639,13 @@ function makeManager(input?: {
const serverSettingsLayer = ServerSettingsService.layerTest();
const vcsDriverLayer = GitVcsDriver.layer.pipe(
Layer.provideMerge(VcsProcess.layer),
const gitCoreLayer = GitCoreLive.pipe(
Layer.provideMerge(NodeServices.layer),
Layer.provideMerge(ServerConfigLayer),
);
const sourceControlRegistryLayer = Layer.effect(
SourceControlProviderRegistry.SourceControlProviderRegistry,
GitHubSourceControlProvider.make().pipe(
Effect.map((provider) =>
SourceControlProviderRegistry.SourceControlProviderRegistry.of({
resolve: () => Effect.succeed(provider),
}),
),
Effect.provide(Layer.succeed(GitHubCli, gitHubCli)),
),
);
const managerLayer = Layer.mergeAll(
Layer.succeed(GitHubCli, gitHubCli),
Layer.succeed(TextGeneration, textGeneration),
Layer.succeed(
ProjectSetupScriptRunner,
@@ -675,9 +653,9 @@ function makeManager(input?: {
runForThread: () => Effect.succeed({ status: "no-script" as const }),
},
),
vcsDriverLayer,
gitCoreLayer,
serverSettingsLayer,
).pipe(Layer.provideMerge(sourceControlRegistryLayer), Layer.provideMerge(NodeServices.layer));
).pipe(Layer.provideMerge(NodeServices.layer));
return makeGitManager().pipe(
Effect.provide(managerLayer),
@@ -687,9 +665,8 @@ function makeManager(input?: {
const asThreadId = (threadId: string) => threadId as ThreadId;
const GitManagerTestLayer = GitVcsDriver.layer.pipe(
const GitManagerTestLayer = GitCoreLive.pipe(
Layer.provide(ServerConfig.layerTest(process.cwd(), { prefix: "t3-git-manager-test-" })),
Layer.provideMerge(VcsProcess.layer),
Layer.provideMerge(NodeServices.layer),
);
@@ -721,15 +698,15 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
const status = yield* manager.status({ cwd: repoDir });
expect(status.isRepo).toBe(true);
expect(status.hasPrimaryRemote).toBe(true);
expect(status.isDefaultRef).toBe(false);
expect(status.refName).toBe("feature/status-open-pr");
expect(status.hasOriginRemote).toBe(true);
expect(status.isDefaultBranch).toBe(false);
expect(status.branch).toBe("feature/status-open-pr");
expect(status.pr).toEqual({
number: 13,
title: "Existing PR",
url: "https://github.com/pingdotgg/codething-mvp/pull/13",
baseRef: "main",
headRef: "feature/status-open-pr",
baseBranch: "main",
headBranch: "feature/status-open-pr",
state: "open",
});
}),
@@ -766,8 +743,8 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
number: 14,
title: "Existing PR title",
url: "https://github.com/pingdotgg/codething-mvp/pull/14",
baseRef: "main",
headRef: "feature/status-trimmed-pr",
baseBranch: "main",
headBranch: "feature/status-trimmed-pr",
state: "open",
});
}),
@@ -817,8 +794,8 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
number: 15,
title: "Valid PR title",
url: "https://github.com/pingdotgg/codething-mvp/pull/15",
baseRef: "main",
headRef: "feature/status-valid-pr-entry",
baseBranch: "main",
headBranch: "feature/status-valid-pr-entry",
state: "open",
});
}),
@@ -866,8 +843,8 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
number: 17,
title: "Merged PR",
url: "https://github.com/pingdotgg/codething-mvp/pull/17",
baseRef: "main",
headRef: "feature/status-lowercase-state",
baseBranch: "main",
headBranch: "feature/status-lowercase-state",
state: "merged",
});
}),
@@ -882,9 +859,9 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
expect(status).toEqual({
isRepo: false,
hasPrimaryRemote: false,
isDefaultRef: false,
refName: null,
hasOriginRemote: false,
isDefaultBranch: false,
branch: null,
hasWorkingTreeChanges: false,
workingTree: {
files: [],
@@ -911,9 +888,9 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
expect(status).toEqual({
isRepo: false,
hasPrimaryRemote: false,
isDefaultRef: false,
refName: null,
hasOriginRemote: false,
isDefaultBranch: false,
branch: null,
hasWorkingTreeChanges: false,
workingTree: {
files: [],
@@ -995,7 +972,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
});
const status = yield* manager.status({ cwd: repoDir });
expect(status.refName).toBe("main");
expect(status.branch).toBe("main");
expect(status.pr).toBeNull();
}),
);
@@ -1049,13 +1026,13 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
});
const status = yield* manager.status({ cwd: repoDir });
expect(status.refName).toBe("t3code/pr-488/statemachine");
expect(status.branch).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",
baseRef: "main",
headRef: "statemachine",
baseBranch: "main",
headBranch: "statemachine",
state: "open",
});
expect(ghCalls).toContain(
@@ -1149,13 +1126,13 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
});
const status = yield* manager.status({ cwd: repoDir });
expect(status.refName).toBe("upstream/effect-atom");
expect(status.branch).toBe("upstream/effect-atom");
expect(status.pr).toEqual({
number: 1618,
title: "Correct PR",
url: "https://github.com/pingdotgg/t3code/pull/1618",
baseRef: "main",
headRef: "effect-atom",
baseBranch: "main",
headBranch: "effect-atom",
state: "open",
});
expect(ghCalls.some((call) => call.includes("pr list --head upstream/effect-atom "))).toBe(
@@ -1199,48 +1176,18 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
});
const status = yield* manager.status({ cwd: repoDir });
expect(status.refName).toBe("feature/status-merged-pr");
expect(status.branch).toBe("feature/status-merged-pr");
expect(status.pr).toEqual({
number: 22,
title: "Merged PR",
url: "https://github.com/pingdotgg/codething-mvp/pull/22",
baseRef: "main",
headRef: "feature/status-merged-pr",
baseBranch: "main",
headBranch: "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-");
@@ -1276,13 +1223,13 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
});
const status = yield* manager.status({ cwd: repoDir });
expect(status.refName).toBe("feature/status-open-over-merged");
expect(status.branch).toBe("feature/status-open-over-merged");
expect(status.pr).toEqual({
number: 46,
title: "Open PR",
url: "https://github.com/pingdotgg/codething-mvp/pull/46",
baseRef: "main",
headRef: "feature/status-open-over-merged",
baseBranch: "main",
headBranch: "feature/status-open-over-merged",
state: "open",
});
}),
@@ -1307,7 +1254,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
});
const status = yield* manager.status({ cwd: repoDir });
expect(status.refName).toBe("feature/status-no-gh");
expect(status.branch).toBe("feature/status-no-gh");
expect(status.pr).toBeNull();
}),
);
@@ -1731,49 +1678,6 @@ 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-");
@@ -3185,7 +3089,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
expect.objectContaining({
kind: "phase_started",
phase: "pr",
label: "Creating pull request...",
label: "Creating GitHub pull request...",
}),
]);
}),
@@ -2,39 +2,29 @@ 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,
VcsStatusInput,
type VcsStatusLocalResult,
type VcsStatusRemoteResult,
VcsStatusResult,
type GitStatusLocalResult,
type GitStatusRemoteResult,
ModelSelection,
} from "@t3tools/contracts";
import {
detectSourceControlProviderFromGitRemoteUrl,
detectGitHostingProviderFromRemoteUrl,
mergeGitStatusParts,
resolveAutoFeatureBranchName,
sanitizeBranchFragment,
@@ -42,52 +32,24 @@ import {
} from "@t3tools/shared/git";
import { GitManagerError } from "@t3tools/contracts";
import { TextGeneration } from "../textGeneration/TextGeneration.ts";
import { ProjectSetupScriptRunner } from "../project/Services/ProjectSetupScriptRunner.ts";
import { extractBranchNameFromRemoteRef } from "./remoteRefs.ts";
import { ServerSettingsService } from "../serverSettings.ts";
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 type { GitManagerServiceError } from "@t3tools/contracts";
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",
) {}
import {
decodeGitHubPullRequestListJson,
formatGitHubJsonDecodeError,
} from "../githubPullRequests.ts";
const COMMIT_TIMEOUT_MS = 10 * 60_000;
const MAX_PROGRESS_TEXT_LENGTH = 500;
@@ -113,14 +75,9 @@ interface OpenPrInfo {
interface PullRequestInfo extends OpenPrInfo, PullRequestHeadRemoteInfo {
state: "open" | "closed" | "merged";
updatedAt: Option.Option<DateTime.Utc>;
updatedAt: string | null;
}
const pullRequestUpdatedAtDescOrder: Order.Order<PullRequestInfo> = Order.mapInput(
Order.flip(Option.makeOrder(DateTime.Order)),
(pullRequest) => pullRequest.updatedAt,
);
interface ResolvedPullRequest {
number: number;
title: string;
@@ -131,9 +88,9 @@ interface ResolvedPullRequest {
}
interface PullRequestHeadRemoteInfo {
isCrossRepository?: boolean | undefined;
headRepositoryNameWithOwner?: string | null | undefined;
headRepositoryOwnerLogin?: string | null | undefined;
isCrossRepository?: boolean;
headRepositoryNameWithOwner?: string | null;
headRepositoryOwnerLogin?: string | null;
}
interface BranchHeadContext {
@@ -299,7 +256,7 @@ function matchesBranchHeadContext(
return true;
}
function toPullRequestInfo(summary: ChangeRequest): PullRequestInfo {
function toPullRequestInfo(summary: GitHubPullRequestSummary): PullRequestInfo {
return {
number: summary.number,
title: summary.title,
@@ -307,7 +264,7 @@ function toPullRequestInfo(summary: ChangeRequest): PullRequestInfo {
baseRefName: summary.baseRefName,
headRefName: summary.headRefName,
state: summary.state ?? "open",
updatedAt: summary.updatedAt,
updatedAt: null,
...(summary.isCrossRepository !== undefined
? { isCrossRepository: summary.isCrossRepository }
: {}),
@@ -465,16 +422,16 @@ function toStatusPr(pr: PullRequestInfo): {
number: number;
title: string;
url: string;
baseRef: string;
headRef: string;
baseBranch: string;
headBranch: string;
state: "open" | "closed" | "merged";
} {
return {
number: pr.number,
title: pr.title,
url: pr.url,
baseRef: pr.baseRefName,
headRef: pr.headRefName,
baseBranch: pr.baseRefName,
headBranch: pr.headRefName,
state: pr.state,
};
}
@@ -518,9 +475,9 @@ function shouldPreferSshRemote(url: string | null): boolean {
}
function toPullRequestHeadRemoteInfo(pr: {
isCrossRepository?: boolean | undefined;
headRepositoryNameWithOwner?: string | null | undefined;
headRepositoryOwnerLogin?: string | null | undefined;
isCrossRepository?: boolean;
headRepositoryNameWithOwner?: string | null;
headRepositoryOwnerLogin?: string | null;
}): PullRequestHeadRemoteInfo {
return {
...(pr.isCrossRepository !== undefined ? { isCrossRepository: pr.isCrossRepository } : {}),
@@ -534,12 +491,10 @@ function toPullRequestHeadRemoteInfo(pr: {
}
export const makeGitManager = Effect.fn("makeGitManager")(function* () {
const gitCore = yield* GitVcsDriver;
const sourceControlProviders = yield* SourceControlProviderRegistry;
const gitCore = yield* GitCore;
const gitHubCli = yield* GitHubCli;
const textGeneration = yield* TextGeneration;
const projectSetupScriptRunner = yield* ProjectSetupScriptRunner;
const sourceControlProvider = (cwd: string) => sourceControlProviders.resolve({ cwd });
const serverSettingsService = yield* ServerSettingsService;
const createProgressEmitter = (
@@ -576,7 +531,7 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
return;
}
const cloneUrls = yield* (yield* sourceControlProvider(cwd)).getRepositoryCloneUrls({
const cloneUrls = yield* gitHubCli.getRepositoryCloneUrls({
cwd,
repository: repositoryNameWithOwner,
});
@@ -631,7 +586,7 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
return;
}
const cloneUrls = yield* (yield* sourceControlProvider(cwd)).getRepositoryCloneUrls({
const cloneUrls = yield* gitHubCli.getRepositoryCloneUrls({
cwd,
repository: repositoryNameWithOwner,
});
@@ -704,15 +659,14 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
: null;
return {
kind: details.isRepo ? ("git" as const) : ("unknown" as const),
isRepo: details.isRepo,
...(hostingProvider ? { sourceControlProvider: hostingProvider } : {}),
hasPrimaryRemote: details.hasOriginRemote,
isDefaultRef: details.isDefaultBranch,
refName: details.branch,
...(hostingProvider ? { hostingProvider } : {}),
hasOriginRemote: details.hasOriginRemote,
isDefaultBranch: details.isDefaultBranch,
branch: details.branch,
hasWorkingTreeChanges: details.hasWorkingTreeChanges,
workingTree: details.workingTree,
} satisfies VcsStatusLocalResult;
} satisfies GitStatusLocalResult;
});
const localStatusResultCache = yield* Cache.makeWith(readLocalStatus, {
capacity: STATUS_RESULT_CACHE_CAPACITY,
@@ -734,13 +688,7 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
branch: details.branch,
upstreamRef: details.upstreamRef,
}).pipe(
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.map((latest) => (latest ? toStatusPr(latest) : null)),
Effect.catch(() => Effect.succeed(null)),
)
: null;
@@ -750,7 +698,7 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
aheadCount: details.aheadCount,
behindCount: details.behindCount,
pr,
} satisfies VcsStatusRemoteResult;
} satisfies GitStatusRemoteResult;
});
const remoteStatusResultCache = yield* Cache.makeWith(readRemoteStatus, {
capacity: STATUS_RESULT_CACHE_CAPACITY,
@@ -774,7 +722,7 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
(yield* readConfigValueNullable(cwd, `remote.${preferredRemoteName}.url`)) ??
(yield* readConfigValueNullable(cwd, "remote.origin.url"));
return remoteUrl ? detectSourceControlProviderFromGitRemoteUrl(remoteUrl) : null;
return remoteUrl ? detectGitHostingProviderFromRemoteUrl(remoteUrl) : null;
});
const resolveRemoteRepositoryContext = Effect.fn("resolveRemoteRepositoryContext")(function* (
@@ -879,10 +827,9 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
>,
) {
for (const headSelector of headContext.headSelectors) {
const pullRequests = yield* (yield* sourceControlProvider(cwd)).listChangeRequests({
const pullRequests = yield* gitHubCli.listOpenPullRequests({
cwd,
headSelector,
state: "open",
limit: 1,
});
const normalizedPullRequests = pullRequests.map(toPullRequestInfo);
@@ -898,7 +845,7 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
baseRefName: firstPullRequest.baseRefName,
headRefName: firstPullRequest.headRefName,
state: "open",
updatedAt: Option.none(),
updatedAt: null,
} satisfies PullRequestInfo;
}
}
@@ -914,14 +861,46 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
const parsedByNumber = new Map<number, PullRequestInfo>();
for (const headSelector of headContext.headSelectors) {
const pullRequests = yield* (yield* sourceControlProvider(cwd)).listChangeRequests({
cwd,
headSelector,
state: "all",
limit: 20,
});
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));
for (const pr of pullRequests.map(toPullRequestInfo)) {
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) {
if (!matchesBranchHeadContext(pr, headContext)) {
continue;
}
@@ -929,7 +908,11 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
}
}
const parsed = Arr.sort(parsedByNumber.values(), pullRequestUpdatedAtDescOrder);
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 latestOpenPr = parsed.find((pr) => pr.state === "open");
if (latestOpenPr) {
@@ -1046,12 +1029,11 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
}
}
const defaultFromProvider = yield* sourceControlProvider(cwd).pipe(
Effect.flatMap((provider) => provider.getDefaultBranch({ cwd })),
Effect.catch(() => Effect.succeed(null)),
);
if (defaultFromProvider) {
return defaultFromProvider;
const defaultFromGh = yield* gitHubCli
.getDefaultBranch({ cwd })
.pipe(Effect.catch(() => Effect.succeed(null)));
if (defaultFromGh) {
return defaultFromGh;
}
return "main";
@@ -1284,12 +1266,12 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
yield* emit({
kind: "phase_started",
phase: "pr",
label: "Creating pull request...",
label: "Creating GitHub pull request...",
});
yield* (yield* sourceControlProvider(cwd))
.createChangeRequest({
yield* gitHubCli
.createPullRequest({
cwd,
baseRefName: baseBranch,
baseBranch,
headSelector: headContext.preferredHeadSelector,
title: generated.title,
bodyFile,
@@ -1347,8 +1329,8 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
const resolvePullRequest: GitManagerShape["resolvePullRequest"] = Effect.fn("resolvePullRequest")(
function* (input) {
const pullRequest = yield* (yield* sourceControlProvider(input.cwd))
.getChangeRequest({
const pullRequest = yield* gitHubCli
.getPullRequest({
cwd: input.cwd,
reference: normalizePullRequestReference(input.reference),
})
@@ -1382,14 +1364,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* (yield* sourceControlProvider(input.cwd)).getChangeRequest({
const pullRequestSummary = yield* gitHubCli.getPullRequest({
cwd: input.cwd,
reference: normalizedReference,
});
const pullRequest = toResolvedPullRequest(pullRequestSummary);
if (input.mode === "local") {
yield* (yield* sourceControlProvider(input.cwd)).checkoutChangeRequest({
yield* gitHubCli.checkoutPullRequest({
cwd: input.cwd,
reference: normalizedReference,
force: true,
@@ -1432,9 +1414,9 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
resolvePullRequestWorktreeLocalBranchName(pullRequestWithRemoteInfo);
const findLocalHeadBranch = (cwd: string) =>
gitCore.listRefs({ cwd }).pipe(
gitCore.listBranches({ cwd }).pipe(
Effect.map((result) => {
const localBranch = result.refs.find(
const localBranch = result.branches.find(
(branch) => !branch.isRemote && branch.name === localPullRequestBranch,
);
if (localBranch) {
@@ -1444,7 +1426,7 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
return null;
}
return (
result.refs.find(
result.branches.find(
(branch) =>
!branch.isRemote &&
branch.name === pullRequest.headBranch &&
@@ -1507,7 +1489,7 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
const worktree = yield* gitCore.createWorktree({
cwd: input.cwd,
refName: localPullRequestBranch,
branch: localPullRequestBranch,
path: null,
});
yield* ensureExistingWorktreeUpstream(worktree.worktree.path);
@@ -1515,7 +1497,7 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
return {
pullRequest,
branch: worktree.worktree.refName,
branch: worktree.worktree.branch,
worktreePath: worktree.worktree.path,
};
}).pipe(Effect.ensuring(invalidateStatus(input.cwd)));
@@ -1547,8 +1529,8 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
const existingBranchNames = yield* gitCore.listLocalBranchNames(cwd);
const resolvedBranch = resolveAutoFeatureBranchName(existingBranchNames, preferredBranch);
yield* gitCore.createRef({ cwd, refName: resolvedBranch });
yield* Effect.scoped(gitCore.switchRef({ cwd, refName: resolvedBranch }));
yield* gitCore.createBranch({ cwd, branch: resolvedBranch });
yield* Effect.scoped(gitCore.checkoutBranch({ cwd, branch: resolvedBranch }));
return {
branchStep: { status: "created" as const, name: resolvedBranch },
@@ -1749,4 +1731,4 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
} satisfies GitManagerShape;
});
export const layer = Layer.effect(GitManager, makeGitManager());
export const GitManagerLive = Layer.effect(GitManager, makeGitManager());
@@ -1,56 +1,52 @@
import { assert, it } from "@effect/vitest";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { Deferred, Effect, Exit, FileSystem, Layer, Option, Path, Scope, Stream } from "effect";
import { Deferred, Effect, Exit, Layer, Option, Scope, Stream } from "effect";
import type {
VcsStatusLocalResult,
VcsStatusRemoteResult,
VcsStatusResult,
VcsStatusStreamEvent,
GitStatusLocalResult,
GitStatusRemoteResult,
GitStatusResult,
GitStatusStreamEvent,
} from "@t3tools/contracts";
import { describe } from "vitest";
import {
VcsStatusBroadcaster,
layer as VcsStatusBroadcasterLayer,
} from "./VcsStatusBroadcaster.ts";
import { GitWorkflowService, type GitWorkflowServiceShape } from "../git/GitWorkflowService.ts";
import { GitStatusBroadcaster } from "../Services/GitStatusBroadcaster.ts";
import { GitStatusBroadcasterLive } from "./GitStatusBroadcaster.ts";
import { type GitManagerShape, GitManager } from "../Services/GitManager.ts";
const baseLocalStatus: VcsStatusLocalResult = {
kind: "git",
const baseLocalStatus: GitStatusLocalResult = {
isRepo: true,
sourceControlProvider: {
hostingProvider: {
kind: "github",
name: "GitHub",
baseUrl: "https://github.com",
},
hasPrimaryRemote: true,
isDefaultRef: false,
refName: "feature/status-broadcast",
hasOriginRemote: true,
isDefaultBranch: false,
branch: "feature/status-broadcast",
hasWorkingTreeChanges: false,
workingTree: { files: [], insertions: 0, deletions: 0 },
};
const baseRemoteStatus: VcsStatusRemoteResult = {
const baseRemoteStatus: GitStatusRemoteResult = {
hasUpstream: true,
aheadCount: 0,
behindCount: 0,
pr: null,
};
const baseStatus: VcsStatusResult = {
const baseStatus: GitStatusResult = {
...baseLocalStatus,
...baseRemoteStatus,
};
function makeTestLayer(state: {
currentLocalStatus: VcsStatusLocalResult;
currentRemoteStatus: VcsStatusRemoteResult | null;
currentLocalStatus: GitStatusLocalResult;
currentRemoteStatus: GitStatusRemoteResult | null;
localStatusCalls: number;
remoteStatusCalls: number;
localInvalidationCalls: number;
remoteInvalidationCalls: number;
}) {
const gitWorkflowLayer = Layer.mock(GitWorkflowService)({
const gitManager: GitManagerShape = {
localStatus: () =>
Effect.sync(() => {
state.localStatusCalls += 1;
@@ -61,6 +57,7 @@ function makeTestLayer(state: {
state.remoteStatusCalls += 1;
return state.currentRemoteStatus;
}),
status: () => Effect.die("status should not be called in this test"),
invalidateLocalStatus: () =>
Effect.sync(() => {
state.localInvalidationCalls += 1;
@@ -69,16 +66,18 @@ function makeTestLayer(state: {
Effect.sync(() => {
state.remoteInvalidationCalls += 1;
}),
});
invalidateStatus: () => Effect.die("invalidateStatus should not be called in this test"),
resolvePullRequest: () => Effect.die("resolvePullRequest should not be called in this test"),
preparePullRequestThread: () =>
Effect.die("preparePullRequestThread should not be called in this test"),
runStackedAction: () => Effect.die("runStackedAction should not be called in this test"),
};
return VcsStatusBroadcasterLayer.pipe(
Layer.provideMerge(NodeServices.layer),
Layer.provide(gitWorkflowLayer),
);
return GitStatusBroadcasterLive.pipe(Layer.provide(Layer.succeed(GitManager, gitManager)));
}
describe("VcsStatusBroadcaster", () => {
it.effect("reuses the cached VCS status across repeated reads", () => {
describe("GitStatusBroadcasterLive", () => {
it.effect("reuses the cached git status across repeated reads", () => {
const state = {
currentLocalStatus: baseLocalStatus,
currentRemoteStatus: baseRemoteStatus,
@@ -89,7 +88,7 @@ describe("VcsStatusBroadcaster", () => {
};
return Effect.gen(function* () {
const broadcaster = yield* VcsStatusBroadcaster;
const broadcaster = yield* GitStatusBroadcaster;
const first = yield* broadcaster.getStatus({ cwd: "/repo" });
const second = yield* broadcaster.getStatus({ cwd: "/repo" });
@@ -114,12 +113,12 @@ describe("VcsStatusBroadcaster", () => {
};
return Effect.gen(function* () {
const broadcaster = yield* VcsStatusBroadcaster;
const broadcaster = yield* GitStatusBroadcaster;
const initial = yield* broadcaster.getStatus({ cwd: "/repo" });
state.currentLocalStatus = {
...baseLocalStatus,
refName: "feature/updated-status",
branch: "feature/updated-status",
};
state.currentRemoteStatus = {
...baseRemoteStatus,
@@ -155,12 +154,12 @@ describe("VcsStatusBroadcaster", () => {
};
return Effect.gen(function* () {
const broadcaster = yield* VcsStatusBroadcaster;
const broadcaster = yield* GitStatusBroadcaster;
const initial = yield* broadcaster.getStatus({ cwd: "/repo" });
state.currentLocalStatus = {
...baseLocalStatus,
refName: "feature/local-only-refresh",
branch: "feature/local-only-refresh",
hasWorkingTreeChanges: true,
};
@@ -180,66 +179,6 @@ describe("VcsStatusBroadcaster", () => {
}).pipe(Effect.provide(makeTestLayer(state)));
});
it.effect("normalizes symlinked CWDs before cache lookup and workflow calls", () => {
const seenCwds: string[] = [];
const state = {
currentLocalStatus: baseLocalStatus,
currentRemoteStatus: baseRemoteStatus,
localStatusCalls: 0,
remoteStatusCalls: 0,
localInvalidationCalls: 0,
remoteInvalidationCalls: 0,
};
const gitWorkflowLayer = Layer.mock(GitWorkflowService)({
localStatus: (input) =>
Effect.sync(() => {
seenCwds.push(input.cwd);
state.localStatusCalls += 1;
return state.currentLocalStatus;
}),
remoteStatus: (input) =>
Effect.sync(() => {
seenCwds.push(input.cwd);
state.remoteStatusCalls += 1;
return state.currentRemoteStatus;
}),
invalidateLocalStatus: () =>
Effect.sync(() => {
state.localInvalidationCalls += 1;
}),
invalidateRemoteStatus: () =>
Effect.sync(() => {
state.remoteInvalidationCalls += 1;
}),
} satisfies Partial<GitWorkflowServiceShape>);
const testLayer = VcsStatusBroadcasterLayer.pipe(
Layer.provideMerge(NodeServices.layer),
Layer.provide(gitWorkflowLayer),
);
return Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const realDir = yield* fileSystem.makeTempDirectoryScoped({
prefix: "t3-vcs-status-real-",
});
const linkParent = yield* fileSystem.makeTempDirectoryScoped({
prefix: "t3-vcs-status-link-",
});
const linkDir = path.join(linkParent, "repo-link");
yield* fileSystem.symlink(realDir, linkDir);
const realPath = yield* fileSystem.realPath(realDir);
const broadcaster = yield* VcsStatusBroadcaster;
yield* broadcaster.getStatus({ cwd: linkDir });
yield* broadcaster.getStatus({ cwd: realDir });
assert.deepStrictEqual(seenCwds, [realPath, realPath]);
assert.equal(state.localStatusCalls, 1);
assert.equal(state.remoteStatusCalls, 1);
}).pipe(Effect.provide(testLayer));
});
it.effect("streams a local snapshot first and remote updates later", () => {
const state = {
currentLocalStatus: baseLocalStatus,
@@ -251,9 +190,9 @@ describe("VcsStatusBroadcaster", () => {
};
return Effect.gen(function* () {
const broadcaster = yield* VcsStatusBroadcaster;
const snapshotDeferred = yield* Deferred.make<VcsStatusStreamEvent>();
const remoteUpdatedDeferred = yield* Deferred.make<VcsStatusStreamEvent>();
const broadcaster = yield* GitStatusBroadcaster;
const snapshotDeferred = yield* Deferred.make<GitStatusStreamEvent>();
const remoteUpdatedDeferred = yield* Deferred.make<GitStatusStreamEvent>();
yield* Stream.runForEach(broadcaster.streamStatus({ cwd: "/repo" }), (event) => {
if (event._tag === "snapshot") {
return Deferred.succeed(snapshotDeferred, event).pipe(Effect.ignore);
@@ -272,11 +211,11 @@ describe("VcsStatusBroadcaster", () => {
_tag: "snapshot",
local: baseLocalStatus,
remote: null,
} satisfies VcsStatusStreamEvent);
} satisfies GitStatusStreamEvent);
assert.deepStrictEqual(remoteUpdated, {
_tag: "remoteUpdated",
remote: baseRemoteStatus,
} satisfies VcsStatusStreamEvent);
} satisfies GitStatusStreamEvent);
}).pipe(Effect.provide(makeTestLayer(state)));
});
@@ -291,40 +230,47 @@ describe("VcsStatusBroadcaster", () => {
};
let remoteInterruptedDeferred: Deferred.Deferred<void, never> | null = null;
let remoteStartedDeferred: Deferred.Deferred<void, never> | null = null;
const gitWorkflowLayer = Layer.mock(GitWorkflowService)({
localStatus: () =>
Effect.sync(() => {
state.localStatusCalls += 1;
return state.currentLocalStatus;
}),
remoteStatus: () =>
Effect.sync(() => {
state.remoteStatusCalls += 1;
}).pipe(
Effect.andThen(
remoteStartedDeferred
? Deferred.succeed(remoteStartedDeferred, undefined).pipe(Effect.ignore)
: Effect.void,
),
Effect.andThen(Effect.never as Effect.Effect<VcsStatusRemoteResult | null, never>),
Effect.onInterrupt(() =>
remoteInterruptedDeferred
? Deferred.succeed(remoteInterruptedDeferred, undefined).pipe(Effect.ignore)
: Effect.void,
),
),
invalidateLocalStatus: () =>
Effect.sync(() => {
state.localInvalidationCalls += 1;
}),
invalidateRemoteStatus: () =>
Effect.sync(() => {
state.remoteInvalidationCalls += 1;
}),
} satisfies Partial<GitWorkflowServiceShape>);
const testLayer = VcsStatusBroadcasterLayer.pipe(
Layer.provideMerge(NodeServices.layer),
Layer.provide(gitWorkflowLayer),
const testLayer = GitStatusBroadcasterLive.pipe(
Layer.provide(
Layer.succeed(GitManager, {
localStatus: () =>
Effect.sync(() => {
state.localStatusCalls += 1;
return state.currentLocalStatus;
}),
remoteStatus: () =>
Effect.sync(() => {
state.remoteStatusCalls += 1;
}).pipe(
Effect.andThen(
remoteStartedDeferred
? Deferred.succeed(remoteStartedDeferred, undefined).pipe(Effect.ignore)
: Effect.void,
),
Effect.andThen(Effect.never as Effect.Effect<GitStatusRemoteResult | null, never>),
Effect.onInterrupt(() =>
remoteInterruptedDeferred
? Deferred.succeed(remoteInterruptedDeferred, undefined).pipe(Effect.ignore)
: Effect.void,
),
),
status: () => Effect.die("status should not be called in this test"),
invalidateLocalStatus: () =>
Effect.sync(() => {
state.localInvalidationCalls += 1;
}),
invalidateRemoteStatus: () =>
Effect.sync(() => {
state.remoteInvalidationCalls += 1;
}),
invalidateStatus: () => Effect.die("invalidateStatus should not be called in this test"),
resolvePullRequest: () =>
Effect.die("resolvePullRequest should not be called in this test"),
preparePullRequestThread: () =>
Effect.die("preparePullRequestThread should not be called in this test"),
runStackedAction: () => Effect.die("runStackedAction should not be called in this test"),
} satisfies GitManagerShape),
),
);
return Effect.gen(function* () {
@@ -333,9 +279,9 @@ describe("VcsStatusBroadcaster", () => {
remoteInterruptedDeferred = remoteInterrupted;
remoteStartedDeferred = remoteStarted;
const broadcaster = yield* VcsStatusBroadcaster;
const firstSnapshot = yield* Deferred.make<VcsStatusStreamEvent>();
const secondSnapshot = yield* Deferred.make<VcsStatusStreamEvent>();
const broadcaster = yield* GitStatusBroadcaster;
const firstSnapshot = yield* Deferred.make<GitStatusStreamEvent>();
const secondSnapshot = yield* Deferred.make<GitStatusStreamEvent>();
const firstScope = yield* Scope.make();
const secondScope = yield* Scope.make();
yield* Stream.runForEach(broadcaster.streamStatus({ cwd: "/repo" }), (event) =>
@@ -356,11 +302,11 @@ describe("VcsStatusBroadcaster", () => {
assert.equal(state.remoteStatusCalls, 1);
yield* Scope.close(firstScope, Exit.void);
assert.isTrue(Option.isNone(yield* Deferred.poll(remoteInterrupted)));
assert.equal(Option.isNone(yield* Deferred.poll(remoteInterrupted)), true);
yield* Scope.close(secondScope, Exit.void).pipe(Effect.forkScoped);
yield* Deferred.await(remoteInterrupted);
assert.isTrue(Option.isSome(yield* Deferred.poll(remoteInterrupted)));
assert.equal(Option.isSome(yield* Deferred.poll(remoteInterrupted)), true);
}).pipe(Effect.provide(testLayer));
});
});
@@ -0,0 +1,311 @@
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;
}),
);
@@ -0,0 +1,340 @@
import * as NodeServices from "@effect/platform-node/NodeServices";
import { it } from "@effect/vitest";
import { Duration, Effect, Layer } from "effect";
import { TestClock } from "effect/testing";
import { NetService } from "@t3tools/shared/Net";
import { beforeEach, expect } from "vitest";
import { ServerConfig } from "../../config.ts";
import { ServerSettingsService } from "../../serverSettings.ts";
import {
OpenCodeRuntime,
OpenCodeRuntimeError,
type OpenCodeRuntimeShape,
} from "../../provider/opencodeRuntime.ts";
import { TextGeneration } from "../Services/TextGeneration.ts";
import { OpenCodeTextGenerationLive } from "./OpenCodeTextGeneration.ts";
const runtimeMock = {
state: {
startCalls: [] as string[],
promptUrls: [] as string[],
authHeaders: [] as Array<string | null>,
closeCalls: [] as string[],
promptResult: undefined as
| { data?: { info?: { error?: unknown }; parts?: Array<{ type: string; text?: string }> } }
| undefined,
},
reset() {
this.state.startCalls.length = 0;
this.state.promptUrls.length = 0;
this.state.authHeaders.length = 0;
this.state.closeCalls.length = 0;
this.state.promptResult = undefined;
},
};
const OpenCodeRuntimeTestDouble: OpenCodeRuntimeShape = {
startOpenCodeServerProcess: ({ binaryPath }) =>
Effect.gen(function* () {
const index = runtimeMock.state.startCalls.length + 1;
const url = `http://127.0.0.1:${4_300 + index}`;
runtimeMock.state.startCalls.push(binaryPath);
// The production runtime binds server lifetime to the caller's scope.
// Mirror that here so the closeCalls probe observes scope close.
yield* Effect.addFinalizer(() =>
Effect.sync(() => {
runtimeMock.state.closeCalls.push(url);
}),
);
return {
url,
exitCode: Effect.never,
};
}),
connectToOpenCodeServer: ({ serverUrl }) =>
Effect.succeed({
url: serverUrl ?? "http://127.0.0.1:4301",
exitCode: null,
external: Boolean(serverUrl),
}),
runOpenCodeCommand: () => Effect.succeed({ stdout: "", stderr: "", code: 0 }),
createOpenCodeSdkClient: ({ baseUrl, serverPassword }) =>
({
session: {
create: async () => ({ data: { id: `${baseUrl}/session` } }),
prompt: async () => {
runtimeMock.state.promptUrls.push(baseUrl);
runtimeMock.state.authHeaders.push(
serverPassword ? `Basic ${btoa(`opencode:${serverPassword}`)}` : null,
);
return (
runtimeMock.state.promptResult ?? {
data: {
parts: [
{
type: "text",
text: JSON.stringify({
subject: "Improve OpenCode reuse",
body: "Reuse one server for the full action.",
}),
},
],
},
}
);
},
},
}) as unknown as ReturnType<OpenCodeRuntimeShape["createOpenCodeSdkClient"]>,
loadOpenCodeInventory: () =>
Effect.fail(
new OpenCodeRuntimeError({
operation: "loadOpenCodeInventory",
detail: "OpenCodeRuntimeTestDouble.loadOpenCodeInventory not used in this test",
cause: null,
}),
),
};
const DEFAULT_TEST_MODEL_SELECTION = {
provider: "opencode" as const,
model: "openai/gpt-5",
};
const OPENCODE_TEXT_GENERATION_IDLE_TTL_MS = 30_000;
const OpenCodeTextGenerationTestLayer = OpenCodeTextGenerationLive.pipe(
Layer.provideMerge(Layer.succeed(OpenCodeRuntime, OpenCodeRuntimeTestDouble)),
Layer.provideMerge(
ServerSettingsService.layerTest({
providers: {
opencode: {
binaryPath: "fake-opencode",
},
},
}),
),
Layer.provideMerge(
ServerConfig.layerTest(process.cwd(), {
prefix: "t3code-opencode-text-generation-test-",
}),
),
Layer.provideMerge(NetService.layer),
Layer.provideMerge(NodeServices.layer),
);
const OpenCodeTextGenerationExistingServerTestLayer = OpenCodeTextGenerationLive.pipe(
Layer.provideMerge(Layer.succeed(OpenCodeRuntime, OpenCodeRuntimeTestDouble)),
Layer.provideMerge(
ServerSettingsService.layerTest({
providers: {
opencode: {
binaryPath: "fake-opencode",
serverUrl: "http://127.0.0.1:9999",
serverPassword: "secret-password",
},
},
}),
),
Layer.provideMerge(
ServerConfig.layerTest(process.cwd(), {
prefix: "t3code-opencode-text-generation-existing-server-test-",
}),
),
Layer.provideMerge(NetService.layer),
Layer.provideMerge(NodeServices.layer),
);
beforeEach(() => {
runtimeMock.reset();
});
const advanceIdleClock = Effect.gen(function* () {
yield* Effect.yieldNow;
yield* TestClock.adjust(Duration.millis(OPENCODE_TEXT_GENERATION_IDLE_TTL_MS + 1));
yield* Effect.yieldNow;
});
it.layer(OpenCodeTextGenerationTestLayer)("OpenCodeTextGenerationLive", (it) => {
it.effect("reuses a warm server across back-to-back requests and closes it after idling", () =>
Effect.gen(function* () {
const textGeneration = yield* TextGeneration;
yield* textGeneration.generateCommitMessage({
cwd: process.cwd(),
branch: "feature/opencode-reuse",
stagedSummary: "M README.md",
stagedPatch: "diff --git a/README.md b/README.md",
modelSelection: DEFAULT_TEST_MODEL_SELECTION,
});
yield* textGeneration.generateCommitMessage({
cwd: process.cwd(),
branch: "feature/opencode-reuse",
stagedSummary: "M README.md",
stagedPatch: "diff --git a/README.md b/README.md",
modelSelection: DEFAULT_TEST_MODEL_SELECTION,
});
expect(runtimeMock.state.startCalls).toEqual(["fake-opencode"]);
expect(runtimeMock.state.promptUrls).toEqual([
"http://127.0.0.1:4301",
"http://127.0.0.1:4301",
]);
expect(runtimeMock.state.closeCalls).toEqual([]);
yield* advanceIdleClock;
expect(runtimeMock.state.closeCalls).toEqual(["http://127.0.0.1:4301"]);
}).pipe(Effect.provide(TestClock.layer())),
);
it.effect("starts a new server after the warm server idles out", () =>
Effect.gen(function* () {
const textGeneration = yield* TextGeneration;
yield* textGeneration.generateCommitMessage({
cwd: process.cwd(),
branch: "feature/opencode-reuse",
stagedSummary: "M README.md",
stagedPatch: "diff --git a/README.md b/README.md",
modelSelection: DEFAULT_TEST_MODEL_SELECTION,
});
yield* advanceIdleClock;
yield* textGeneration.generateCommitMessage({
cwd: process.cwd(),
branch: "feature/opencode-reuse",
stagedSummary: "M README.md",
stagedPatch: "diff --git a/README.md b/README.md",
modelSelection: DEFAULT_TEST_MODEL_SELECTION,
});
expect(runtimeMock.state.startCalls).toEqual(["fake-opencode", "fake-opencode"]);
expect(runtimeMock.state.promptUrls).toEqual([
"http://127.0.0.1:4301",
"http://127.0.0.1:4302",
]);
expect(runtimeMock.state.closeCalls).toEqual(["http://127.0.0.1:4301"]);
}).pipe(Effect.provide(TestClock.layer())),
);
it.effect("returns a typed empty-output error when OpenCode returns no text parts", () =>
Effect.gen(function* () {
runtimeMock.state.promptResult = { data: {} };
const textGeneration = yield* TextGeneration;
const error = yield* textGeneration
.generateCommitMessage({
cwd: process.cwd(),
branch: "feature/opencode-reuse",
stagedSummary: "M README.md",
stagedPatch: "diff --git a/README.md b/README.md",
modelSelection: DEFAULT_TEST_MODEL_SELECTION,
})
.pipe(Effect.flip);
expect(error.message).toContain("OpenCode returned empty output.");
}),
);
it.effect("parses JSON returned as plain text output", () =>
Effect.gen(function* () {
runtimeMock.state.promptResult = {
data: {
parts: [
{
type: "text",
text: 'Here is the result:\n{"subject":"Tighten OpenCode parsing","body":"Handle JSON text output locally."}',
},
],
},
};
const textGeneration = yield* TextGeneration;
const result = yield* textGeneration.generateCommitMessage({
cwd: process.cwd(),
branch: "feature/opencode-reuse",
stagedSummary: "M README.md",
stagedPatch: "diff --git a/README.md b/README.md",
modelSelection: DEFAULT_TEST_MODEL_SELECTION,
});
expect(result).toEqual({
subject: "Tighten OpenCode parsing",
body: "Handle JSON text output locally.",
});
}),
);
it.effect("surfaces the upstream OpenCode structured-output error message", () =>
Effect.gen(function* () {
runtimeMock.state.promptResult = {
data: {
info: {
error: {
name: "StructuredOutputError",
data: {
message: "Model did not produce structured output",
retries: 2,
},
},
},
},
};
const textGeneration = yield* TextGeneration;
const error = yield* textGeneration
.generateCommitMessage({
cwd: process.cwd(),
branch: "feature/opencode-reuse",
stagedSummary: "M README.md",
stagedPatch: "diff --git a/README.md b/README.md",
modelSelection: DEFAULT_TEST_MODEL_SELECTION,
})
.pipe(Effect.flip);
expect(error.message).toContain("Model did not produce structured output");
}),
);
});
it.layer(OpenCodeTextGenerationExistingServerTestLayer)(
"OpenCodeTextGenerationLive with configured server URL",
(it) => {
it.effect("reuses a configured OpenCode server URL without spawning or applying idle TTL", () =>
Effect.gen(function* () {
const textGeneration = yield* TextGeneration;
yield* textGeneration.generateCommitMessage({
cwd: process.cwd(),
branch: "feature/opencode-reuse",
stagedSummary: "M README.md",
stagedPatch: "diff --git a/README.md b/README.md",
modelSelection: DEFAULT_TEST_MODEL_SELECTION,
});
yield* textGeneration.generateCommitMessage({
cwd: process.cwd(),
branch: "feature/opencode-reuse",
stagedSummary: "M README.md",
stagedPatch: "diff --git a/README.md b/README.md",
modelSelection: DEFAULT_TEST_MODEL_SELECTION,
});
expect(runtimeMock.state.startCalls).toEqual([]);
expect(runtimeMock.state.promptUrls).toEqual([
"http://127.0.0.1:9999",
"http://127.0.0.1:9999",
]);
expect(runtimeMock.state.authHeaders).toEqual([
`Basic ${btoa("opencode:secret-password")}`,
`Basic ${btoa("opencode:secret-password")}`,
]);
yield* advanceIdleClock;
expect(runtimeMock.state.closeCalls).toEqual([]);
}).pipe(Effect.provide(TestClock.layer())),
);
},
);
@@ -1,30 +1,30 @@
import { Effect, Exit, Fiber, Schema, Scope } from "effect";
import { Effect, Exit, Fiber, Layer, Schema, Scope } from "effect";
import * as Semaphore from "effect/Semaphore";
import {
TextGenerationError,
type ChatAttachment,
type ModelSelection,
type OpenCodeSettings,
type OpenCodeModelSelection,
} from "@t3tools/contracts";
import { sanitizeBranchFragment, sanitizeFeatureBranchName } from "@t3tools/shared/git";
import { getModelSelectionStringOptionValue } from "@t3tools/shared/model";
import { ServerConfig } from "../config.ts";
import { resolveAttachmentPath } from "../attachmentStore.ts";
import { ServerConfig } from "../../config.ts";
import { resolveAttachmentPath } from "../../attachmentStore.ts";
import { ServerSettingsService } from "../../serverSettings.ts";
import {
buildBranchNamePrompt,
buildCommitMessagePrompt,
buildPrContentPrompt,
buildThreadTitlePrompt,
} from "./TextGenerationPrompts.ts";
import { type TextGenerationShape } from "./TextGeneration.ts";
} from "../Prompts.ts";
import { type TextGenerationShape, TextGeneration } from "../Services/TextGeneration.ts";
import {
extractJsonObject,
sanitizeCommitSubject,
sanitizePrTitle,
sanitizeThreadTitle,
} from "./TextGenerationUtils.ts";
} from "../Utils.ts";
import {
OpenCodeRuntime,
type OpenCodeServerConnection,
@@ -32,7 +32,7 @@ import {
openCodeRuntimeErrorDetail,
parseOpenCodeModelSlug,
toOpenCodeFileParts,
} from "../provider/opencodeRuntime.ts";
} from "../../provider/opencodeRuntime.ts";
const OPENCODE_TEXT_GENERATION_IDLE_TTL = "30 seconds";
@@ -93,11 +93,9 @@ interface SharedOpenCodeTextGenerationServerState {
idleCloseFiber: Fiber.Fiber<void, never> | null;
}
export const makeOpenCodeTextGeneration = Effect.fn("makeOpenCodeTextGeneration")(function* (
openCodeSettings: OpenCodeSettings,
environment: NodeJS.ProcessEnv = process.env,
) {
const makeOpenCodeTextGeneration = Effect.gen(function* () {
const serverConfig = yield* ServerConfig;
const serverSettingsService = yield* ServerSettingsService;
const openCodeRuntime = yield* OpenCodeRuntime;
const idleFiberScope = yield* Effect.acquireRelease(Scope.make(), (scope) =>
Scope.close(scope, Exit.void),
@@ -204,7 +202,6 @@ export const makeOpenCodeTextGeneration = Effect.fn("makeOpenCodeTextGeneration"
openCodeRuntime
.startOpenCodeServerProcess({
binaryPath: input.binaryPath,
environment,
})
.pipe(
Effect.provideService(Scope.Scope, serverScope),
@@ -270,7 +267,7 @@ export const makeOpenCodeTextGeneration = Effect.fn("makeOpenCodeTextGeneration"
readonly cwd: string;
readonly prompt: string;
readonly outputSchemaJson: S;
readonly modelSelection: ModelSelection;
readonly modelSelection: OpenCodeModelSelection;
readonly attachments?: ReadonlyArray<ChatAttachment> | undefined;
}) {
const parsedModel = parseOpenCodeModelSlug(input.modelSelection.model);
@@ -281,6 +278,26 @@ export const makeOpenCodeTextGeneration = Effect.fn("makeOpenCodeTextGeneration"
});
}
const settings = yield* serverSettingsService.getSettings.pipe(
Effect.map(
(value) =>
value.providers?.opencode ?? {
enabled: true,
binaryPath: "opencode",
serverUrl: "",
serverPassword: "",
customModels: [],
},
),
Effect.orElseSucceed(() => ({
enabled: true,
binaryPath: "opencode",
serverUrl: "",
serverPassword: "",
customModels: [],
})),
);
const fileParts = toOpenCodeFileParts({
attachments: input.attachments,
resolveAttachmentPath: (attachment) =>
@@ -293,8 +310,8 @@ export const makeOpenCodeTextGeneration = Effect.fn("makeOpenCodeTextGeneration"
const client = openCodeRuntime.createOpenCodeSdkClient({
baseUrl: server.url,
directory: input.cwd,
...(openCodeSettings.serverUrl.length > 0 && openCodeSettings.serverPassword
? { serverPassword: openCodeSettings.serverPassword }
...(settings.serverUrl.length > 0 && settings.serverPassword
? { serverPassword: settings.serverPassword }
: {}),
});
const session = await client.session.create({
@@ -337,11 +354,11 @@ export const makeOpenCodeTextGeneration = Effect.fn("makeOpenCodeTextGeneration"
});
const rawOutput =
openCodeSettings.serverUrl.length > 0
? yield* runAgainstServer({ url: openCodeSettings.serverUrl })
settings.serverUrl.length > 0
? yield* runAgainstServer({ url: settings.serverUrl })
: yield* Effect.acquireUseRelease(
acquireSharedServer({
binaryPath: openCodeSettings.binaryPath,
binaryPath: settings.binaryPath,
operation: input.operation,
}),
runAgainstServer,
@@ -366,6 +383,13 @@ export const makeOpenCodeTextGeneration = Effect.fn("makeOpenCodeTextGeneration"
const generateCommitMessage: TextGenerationShape["generateCommitMessage"] = Effect.fn(
"OpenCodeTextGeneration.generateCommitMessage",
)(function* (input) {
if (input.modelSelection.provider !== "opencode") {
return yield* new TextGenerationError({
operation: "generateCommitMessage",
detail: "Invalid model selection.",
});
}
const { prompt, outputSchema } = buildCommitMessagePrompt({
branch: input.branch,
stagedSummary: input.stagedSummary,
@@ -392,6 +416,13 @@ export const makeOpenCodeTextGeneration = Effect.fn("makeOpenCodeTextGeneration"
const generatePrContent: TextGenerationShape["generatePrContent"] = Effect.fn(
"OpenCodeTextGeneration.generatePrContent",
)(function* (input) {
if (input.modelSelection.provider !== "opencode") {
return yield* new TextGenerationError({
operation: "generatePrContent",
detail: "Invalid model selection.",
});
}
const { prompt, outputSchema } = buildPrContentPrompt({
baseBranch: input.baseBranch,
headBranch: input.headBranch,
@@ -416,6 +447,13 @@ export const makeOpenCodeTextGeneration = Effect.fn("makeOpenCodeTextGeneration"
const generateBranchName: TextGenerationShape["generateBranchName"] = Effect.fn(
"OpenCodeTextGeneration.generateBranchName",
)(function* (input) {
if (input.modelSelection.provider !== "opencode") {
return yield* new TextGenerationError({
operation: "generateBranchName",
detail: "Invalid model selection.",
});
}
const { prompt, outputSchema } = buildBranchNamePrompt({
message: input.message,
attachments: input.attachments,
@@ -437,6 +475,13 @@ export const makeOpenCodeTextGeneration = Effect.fn("makeOpenCodeTextGeneration"
const generateThreadTitle: TextGenerationShape["generateThreadTitle"] = Effect.fn(
"OpenCodeTextGeneration.generateThreadTitle",
)(function* (input) {
if (input.modelSelection.provider !== "opencode") {
return yield* new TextGenerationError({
operation: "generateThreadTitle",
detail: "Invalid model selection.",
});
}
const { prompt, outputSchema } = buildThreadTitlePrompt({
message: input.message,
attachments: input.attachments,
@@ -462,3 +507,5 @@ export const makeOpenCodeTextGeneration = Effect.fn("makeOpenCodeTextGeneration"
generateThreadTitle,
} satisfies TextGenerationShape;
});
export const OpenCodeTextGenerationLive = Layer.effect(TextGeneration, makeOpenCodeTextGeneration);
@@ -0,0 +1,104 @@
/**
* RoutingTextGeneration – Dispatches text generation requests to either the
* Codex CLI or Claude CLI implementation based on the provider in each
* request input.
*
* When `modelSelection.provider` is `"claudeAgent"` the request is forwarded to
* the Claude layer; for any other value (including the default `undefined`) it
* falls through to the Codex layer.
*
* @module RoutingTextGeneration
*/
import { Effect, Layer, Context } from "effect";
import { TextGeneration, type TextGenerationShape } from "../Services/TextGeneration.ts";
import { CodexTextGenerationLive } from "./CodexTextGeneration.ts";
import { ClaudeTextGenerationLive } from "./ClaudeTextGeneration.ts";
import { CursorTextGenerationLive } from "./CursorTextGeneration.ts";
import { OpenCodeTextGenerationLive } from "./OpenCodeTextGeneration.ts";
// ---------------------------------------------------------------------------
// Internal service tags so both concrete layers can coexist.
// ---------------------------------------------------------------------------
class CodexTextGen extends Context.Service<CodexTextGen, TextGenerationShape>()(
"t3/git/Layers/RoutingTextGeneration/CodexTextGen",
) {}
class ClaudeTextGen extends Context.Service<ClaudeTextGen, TextGenerationShape>()(
"t3/git/Layers/RoutingTextGeneration/ClaudeTextGen",
) {}
class CursorTextGen extends Context.Service<CursorTextGen, TextGenerationShape>()(
"t3/git/Layers/RoutingTextGeneration/CursorTextGen",
) {}
class OpenCodeTextGen extends Context.Service<OpenCodeTextGen, TextGenerationShape>()(
"t3/git/Layers/RoutingTextGeneration/OpenCodeTextGen",
) {}
// ---------------------------------------------------------------------------
// Routing implementation
// ---------------------------------------------------------------------------
const makeRoutingTextGeneration = Effect.gen(function* () {
const byProvider = {
codex: yield* CodexTextGen,
claudeAgent: yield* ClaudeTextGen,
cursor: yield* CursorTextGen,
opencode: yield* OpenCodeTextGen,
};
return {
generateCommitMessage: (input) =>
byProvider[input.modelSelection.provider].generateCommitMessage(input),
generatePrContent: (input) =>
byProvider[input.modelSelection.provider].generatePrContent(input),
generateBranchName: (input) =>
byProvider[input.modelSelection.provider].generateBranchName(input),
generateThreadTitle: (input) =>
byProvider[input.modelSelection.provider].generateThreadTitle(input),
} satisfies TextGenerationShape;
});
const InternalCodexLayer = Layer.effect(
CodexTextGen,
Effect.gen(function* () {
const svc = yield* TextGeneration;
return svc;
}),
).pipe(Layer.provide(CodexTextGenerationLive));
const InternalClaudeLayer = Layer.effect(
ClaudeTextGen,
Effect.gen(function* () {
const svc = yield* TextGeneration;
return svc;
}),
).pipe(Layer.provide(ClaudeTextGenerationLive));
const InternalCursorLayer = Layer.effect(
CursorTextGen,
Effect.gen(function* () {
const svc = yield* TextGeneration;
return svc;
}),
).pipe(Layer.provide(CursorTextGenerationLive));
const InternalOpenCodeLayer = Layer.effect(
OpenCodeTextGen,
Effect.gen(function* () {
const svc = yield* TextGeneration;
return svc;
}),
).pipe(Layer.provide(OpenCodeTextGenerationLive));
export const RoutingTextGenerationLive = Layer.effect(
TextGeneration,
makeRoutingTextGeneration,
).pipe(
Layer.provide(InternalCodexLayer),
Layer.provide(InternalClaudeLayer),
Layer.provide(InternalCursorLayer),
Layer.provide(InternalOpenCodeLayer),
);
@@ -5,8 +5,8 @@ import {
buildCommitMessagePrompt,
buildPrContentPrompt,
buildThreadTitlePrompt,
} from "./TextGenerationPrompts.ts";
import { normalizeCliError, sanitizeThreadTitle } from "./TextGenerationUtils.ts";
} from "./Prompts.ts";
import { normalizeCliError, sanitizeThreadTitle } from "./Utils.ts";
import { TextGenerationError } from "@t3tools/contracts";
describe("buildCommitMessagePrompt", () => {
@@ -9,13 +9,7 @@
import { Schema } from "effect";
import type { ChatAttachment } from "@t3tools/contracts";
import { limitSection } from "./TextGenerationUtils.ts";
import type { TextGenerationPolicy } from "./TextGenerationPolicy.ts";
function policyInstruction(instruction: string | undefined): ReadonlyArray<string> {
const trimmed = instruction?.trim();
return trimmed ? ["", "Additional instructions:", limitSection(trimmed, 4_000)] : [];
}
import { limitSection } from "./Utils.ts";
// ---------------------------------------------------------------------------
// Commit message
@@ -26,7 +20,6 @@ export interface CommitMessagePromptInput {
stagedSummary: string;
stagedPatch: string;
includeBranch: boolean;
policy?: TextGenerationPolicy | undefined;
}
export function buildCommitMessagePrompt(input: CommitMessagePromptInput) {
@@ -44,7 +37,6 @@ export function buildCommitMessagePrompt(input: CommitMessagePromptInput) {
? ["- branch must be a short semantic git branch fragment for this change"]
: []),
"- capture the primary user-visible or developer-visible change",
...policyInstruction(input.policy?.commitInstructions),
"",
`Branch: ${input.branch ?? "(detached)"}`,
"",
@@ -85,7 +77,6 @@ export interface PrContentPromptInput {
commitSummary: string;
diffSummary: string;
diffPatch: string;
policy?: TextGenerationPolicy | undefined;
}
export function buildPrContentPrompt(input: PrContentPromptInput) {
@@ -97,7 +88,6 @@ export function buildPrContentPrompt(input: PrContentPromptInput) {
"- body must be markdown and include headings '## Summary' and '## Testing'",
"- under Summary, provide short bullet points",
"- under Testing, include bullet points with concrete checks or 'Not run' where appropriate",
...policyInstruction(input.policy?.changeRequestInstructions),
"",
`Base branch: ${input.baseBranch}`,
`Head branch: ${input.headBranch}`,
@@ -127,7 +117,6 @@ export function buildPrContentPrompt(input: PrContentPromptInput) {
export interface BranchNamePromptInput {
message: string;
attachments?: ReadonlyArray<ChatAttachment> | undefined;
policy?: TextGenerationPolicy | undefined;
}
interface PromptFromMessageInput {
@@ -136,7 +125,6 @@ interface PromptFromMessageInput {
rules: ReadonlyArray<string>;
message: string;
attachments?: ReadonlyArray<ChatAttachment> | undefined;
additionalInstructions?: string | undefined;
}
function buildPromptFromMessage(input: PromptFromMessageInput): string {
@@ -152,7 +140,6 @@ function buildPromptFromMessage(input: PromptFromMessageInput): string {
"",
"User message:",
limitSection(input.message, 8_000),
...policyInstruction(input.additionalInstructions),
];
if (attachmentLines.length > 0) {
promptSections.push(
@@ -177,7 +164,6 @@ export function buildBranchNamePrompt(input: BranchNamePromptInput) {
],
message: input.message,
attachments: input.attachments,
additionalInstructions: input.policy?.branchInstructions,
});
const outputSchema = Schema.Struct({
branch: Schema.String,
@@ -193,7 +179,6 @@ export function buildBranchNamePrompt(input: BranchNamePromptInput) {
export interface ThreadTitlePromptInput {
message: string;
attachments?: ReadonlyArray<ChatAttachment> | undefined;
policy?: TextGenerationPolicy | undefined;
}
export function buildThreadTitlePrompt(input: ThreadTitlePromptInput) {
@@ -208,7 +193,6 @@ export function buildThreadTitlePrompt(input: ThreadTitlePromptInput) {
],
message: input.message,
attachments: input.attachments,
additionalInstructions: input.policy?.threadTitleInstructions,
});
const outputSchema = Schema.Struct({
title: Schema.String,
+313
View File
@@ -0,0 +1,313 @@
/**
* 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
@@ -0,0 +1,103 @@
/**
* 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
@@ -0,0 +1,104 @@
/**
* 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",
) {}
@@ -0,0 +1,27 @@
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") {}
@@ -1,13 +1,18 @@
import { Context, Effect, Layer } from "effect";
import type { ChatAttachment, ModelSelection, ProviderInstanceId } from "@t3tools/contracts";
import { TextGenerationError } from "@t3tools/contracts";
/**
* TextGeneration - Effect service contract for AI-generated Git content.
*
* Generates commit messages and pull request titles/bodies from repository
* context prepared by Git services.
*
* @module TextGeneration
*/
import { Context } from "effect";
import type { Effect } from "effect";
import type { ChatAttachment, ModelSelection } from "@t3tools/contracts";
import {
ProviderInstanceRegistry,
type ProviderInstanceRegistryShape,
} from "../provider/Services/ProviderInstanceRegistry.ts";
import type { ProviderInstance } from "../provider/ProviderDriver.ts";
import type { TextGenerationError } from "@t3tools/contracts";
/** Providers that support git text generation (commit messages, PR content, branch names). */
export type TextGenerationProvider = "codex" | "claudeAgent" | "cursor" | "opencode";
export interface CommitMessageGenerationInput {
@@ -114,58 +119,5 @@ export interface TextGenerationShape {
* TextGeneration - Service tag for commit and PR text generation.
*/
export class TextGeneration extends Context.Service<TextGeneration, TextGenerationShape>()(
"t3/text-generation/TextGeneration",
"t3/git/Services/TextGeneration",
) {}
type TextGenerationOp =
| "generateCommitMessage"
| "generatePrContent"
| "generateBranchName"
| "generateThreadTitle";
const resolveInstance = (
registry: ProviderInstanceRegistryShape,
operation: TextGenerationOp,
instanceId: ProviderInstanceId,
): Effect.Effect<ProviderInstance["textGeneration"], TextGenerationError> =>
registry.getInstance(instanceId).pipe(
Effect.flatMap((instance) =>
instance
? Effect.succeed(instance.textGeneration)
: Effect.fail(
new TextGenerationError({
operation,
detail: `No provider instance registered for id '${instanceId}'.`,
}),
),
),
);
export const makeTextGenerationFromRegistry = (
registry: ProviderInstanceRegistryShape,
): TextGenerationShape => ({
generateCommitMessage: (input) =>
resolveInstance(registry, "generateCommitMessage", input.modelSelection.instanceId).pipe(
Effect.flatMap((textGeneration) => textGeneration.generateCommitMessage(input)),
),
generatePrContent: (input) =>
resolveInstance(registry, "generatePrContent", input.modelSelection.instanceId).pipe(
Effect.flatMap((textGeneration) => textGeneration.generatePrContent(input)),
),
generateBranchName: (input) =>
resolveInstance(registry, "generateBranchName", input.modelSelection.instanceId).pipe(
Effect.flatMap((textGeneration) => textGeneration.generateBranchName(input)),
),
generateThreadTitle: (input) =>
resolveInstance(registry, "generateThreadTitle", input.modelSelection.instanceId).pipe(
Effect.flatMap((textGeneration) => textGeneration.generateThreadTitle(input)),
),
});
export const layer = Layer.effect(
TextGeneration,
Effect.gen(function* () {
const registry = yield* ProviderInstanceRegistry;
return makeTextGenerationFromRegistry(registry);
}),
);
+165
View File
@@ -1,6 +1,171 @@
/**
* Shared utilities for text generation layers (Codex, Claude, etc.).
*
* @module textGenerationUtils
*/
import { Schema } from "effect";
import { TextGenerationError } from "@t3tools/contracts";
import { existsSync } from "node:fs";
import { join } from "node:path";
export function isGitRepository(cwd: string): boolean {
return existsSync(join(cwd, ".git"));
}
/** Convert an Effect Schema to a flat JSON Schema object, inlining `$defs` when present. */
export function toJsonSchemaObject(schema: Schema.Top): unknown {
const document = Schema.toJsonSchemaDocument(schema);
if (document.definitions && Object.keys(document.definitions).length > 0) {
return { ...document.schema, $defs: document.definitions };
}
return document.schema;
}
/** Truncate a text section to `maxChars`, appending a `[truncated]` marker when needed. */
export function limitSection(value: string, maxChars: number): string {
if (value.length <= maxChars) return value;
const truncated = value.slice(0, maxChars);
return `${truncated}\n\n[truncated]`;
}
export function extractJsonObject(raw: string): string {
const trimmed = raw.trim();
if (trimmed.length === 0) {
return trimmed;
}
const start = trimmed.indexOf("{");
if (start < 0) {
return trimmed;
}
let depth = 0;
let inString = false;
let escaping = false;
for (let index = start; index < trimmed.length; index += 1) {
const char = trimmed[index];
if (inString) {
if (escaping) {
escaping = false;
} else if (char === "\\") {
escaping = true;
} else if (char === '"') {
inString = false;
}
continue;
}
if (char === '"') {
inString = true;
continue;
}
if (char === "{") {
depth += 1;
continue;
}
if (char === "}") {
depth -= 1;
if (depth === 0) {
return trimmed.slice(start, index + 1);
}
}
}
return trimmed.slice(start);
}
/** Normalise a raw commit subject to imperative-mood, ≤72 chars, no trailing period. */
export function sanitizeCommitSubject(raw: string): string {
const singleLine = raw.trim().split(/\r?\n/g)[0]?.trim() ?? "";
const withoutTrailingPeriod = singleLine.replace(/[.]+$/g, "").trim();
if (withoutTrailingPeriod.length === 0) {
return "Update project files";
}
if (withoutTrailingPeriod.length <= 72) {
return withoutTrailingPeriod;
}
return withoutTrailingPeriod.slice(0, 72).trimEnd();
}
/** Normalise a raw PR title to a single line with a sensible fallback. */
export function sanitizePrTitle(raw: string): string {
const singleLine = raw.trim().split(/\r?\n/g)[0]?.trim() ?? "";
if (singleLine.length > 0) {
return singleLine;
}
return "Update project changes";
}
/** Normalise a raw thread title to a compact single-line sidebar-safe label. */
export function sanitizeThreadTitle(raw: string): string {
const normalized = raw
.trim()
.split(/\r?\n/g)[0]
?.trim()
.replace(/^['"`]+|['"`]+$/g, "")
.trim()
.replace(/\s+/g, " ");
if (!normalized || normalized.trim().length === 0) {
return "New thread";
}
if (normalized.length <= 50) {
return normalized;
}
return `${normalized.slice(0, 47).trimEnd()}...`;
}
/** CLI name to human-readable label, e.g. "codex" → "Codex CLI (`codex`)" */
function cliLabel(cliName: string): string {
const capitalized = cliName.charAt(0).toUpperCase() + cliName.slice(1);
return `${capitalized} CLI (\`${cliName}\`)`;
}
/**
* Normalize an unknown error from a CLI text generation process into a
* typed `TextGenerationError`. Parameterized by CLI name so both Codex
* and Claude (and future providers) can share the same logic.
*/
export function normalizeCliError(
cliName: string,
operation: string,
error: unknown,
fallback: string,
): TextGenerationError {
if (Schema.is(TextGenerationError)(error)) {
return error;
}
if (error instanceof Error) {
const lower = error.message.toLowerCase();
if (
error.message.includes(`Command not found: ${cliName}`) ||
lower.includes(`spawn ${cliName}`) ||
lower.includes("enoent")
) {
return new TextGenerationError({
operation,
detail: `${cliLabel(cliName)} is required but not available on PATH.`,
cause: error,
});
}
return new TextGenerationError({
operation,
detail: `${fallback}: ${error.message}`,
cause: error,
});
}
return new TextGenerationError({
operation,
detail: fallback,
cause: error,
});
}
+5 -4
View File
@@ -1,4 +1,4 @@
import { Cause, DateTime, Exit, Option, Result, Schema } from "effect";
import { Cause, Exit, 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: Option.Option<DateTime.Utc>;
readonly updatedAt: string | null;
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.OptionFromNullOr(Schema.DateTimeUtcFromString)),
updatedAt: Schema.optional(Schema.NullOr(Schema.String)),
isCrossRepository: Schema.optional(Schema.Boolean),
headRepository: Schema.optional(
Schema.NullOr(
@@ -80,7 +80,8 @@ function normalizeGitHubPullRequestRecord(
baseRefName: raw.baseRefName,
headRefName: raw.headRefName,
state: normalizeGitHubPullRequestState(raw),
updatedAt: raw.updatedAt ?? Option.none(),
updatedAt:
typeof raw.updatedAt === "string" && raw.updatedAt.trim().length > 0 ? raw.updatedAt : null,
...(typeof raw.isCrossRepository === "boolean"
? { isCrossRepository: raw.isCrossRepository }
: {}),
@@ -1,5 +1,4 @@
import { assert, describe, it } from "@effect/vitest";
import { ProviderDriverKind } from "@t3tools/contracts";
import { Effect, Metric } from "effect";
import { withMetrics } from "./Metrics.ts";
@@ -76,11 +75,10 @@ describe("withMetrics", () => {
Effect.gen(function* () {
const counter = Metric.counter("with_metrics_lazy_total");
const timer = Metric.timer("with_metrics_lazy_duration");
let provider = ProviderDriverKind.make("unknown");
const lazyInittedProvider = ProviderDriverKind.make("codex");
let provider = "unknown";
yield* Effect.sync(() => {
provider = lazyInittedProvider;
provider = "codex";
}).pipe(
withMetrics({
counter,
@@ -95,7 +93,7 @@ describe("withMetrics", () => {
const snapshots = yield* Metric.snapshot;
assert.equal(
hasMetricSnapshot(snapshots, "with_metrics_lazy_total", {
provider: lazyInittedProvider,
provider: "codex",
operation: "lazy",
outcome: "success",
}),
@@ -103,7 +101,7 @@ describe("withMetrics", () => {
);
assert.equal(
hasMetricSnapshot(snapshots, "with_metrics_lazy_duration", {
provider: lazyInittedProvider,
provider: "codex",
operation: "lazy",
}),
true,
@@ -3,12 +3,7 @@ import os from "node:os";
import path from "node:path";
import { execFileSync } from "node:child_process";
import {
ProviderDriverKind,
ProviderRuntimeEvent,
ProviderSession,
ProviderInstanceId,
} from "@t3tools/contracts";
import type { ProviderKind, ProviderRuntimeEvent, ProviderSession } from "@t3tools/contracts";
import {
CommandId,
DEFAULT_PROVIDER_INTERACTION_MODE,
@@ -24,9 +19,8 @@ import { afterEach, describe, expect, it, vi } from "vitest";
import { CheckpointStoreLive } from "../../checkpointing/Layers/CheckpointStore.ts";
import { CheckpointStore } from "../../checkpointing/Services/CheckpointStore.ts";
import * as VcsDriverRegistry from "../../vcs/VcsDriverRegistry.ts";
import * as VcsProcess from "../../vcs/VcsProcess.ts";
import { VcsStatusBroadcaster } from "../../vcs/VcsStatusBroadcaster.ts";
import { GitCoreLive } from "../../git/Layers/GitCore.ts";
import { GitStatusBroadcaster } from "../../git/Services/GitStatusBroadcaster.ts";
import { RepositoryIdentityResolverLive } from "../../project/Layers/RepositoryIdentityResolver.ts";
import { CheckpointReactorLive } from "./CheckpointReactor.ts";
import { OrchestrationEngineLive } from "./OrchestrationEngine.ts";
@@ -56,7 +50,7 @@ const asTurnId = (value: string): TurnId => TurnId.make(value);
type LegacyProviderRuntimeEvent = {
readonly type: string;
readonly eventId: EventId;
readonly provider: ProviderDriverKind;
readonly provider: ProviderKind;
readonly createdAt: string;
readonly threadId: ThreadId;
readonly turnId?: string | undefined;
@@ -70,7 +64,7 @@ function createProviderServiceHarness(
cwd: string,
hasSession = true,
sessionCwd = cwd,
providerName: ProviderSession["provider"] = ProviderDriverKind.make("codex"),
providerName: ProviderSession["provider"] = "codex",
) {
const now = new Date().toISOString();
const runtimeEventPubSub = Effect.runSync(PubSub.unbounded<ProviderRuntimeEvent>());
@@ -103,17 +97,6 @@ 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);
@@ -260,7 +243,7 @@ describe("CheckpointReactor", () => {
readonly projectWorkspaceRoot?: string;
readonly threadWorktreePath?: string | null;
readonly providerSessionCwd?: string;
readonly providerName?: ProviderDriverKind;
readonly providerName?: ProviderKind;
readonly gitStatusRefreshCalls?: Array<string>;
}) {
const cwd = createGitRepository();
@@ -269,7 +252,7 @@ describe("CheckpointReactor", () => {
cwd,
options?.hasSession ?? true,
options?.providerSessionCwd ?? cwd,
options?.providerName ?? ProviderDriverKind.make("codex"),
options?.providerName ?? "codex",
);
const orchestrationLayer = OrchestrationEngineLive.pipe(
Layer.provide(OrchestrationProjectionSnapshotQueryLive),
@@ -283,7 +266,7 @@ describe("CheckpointReactor", () => {
const ServerConfigLayer = ServerConfig.layerTest(process.cwd(), {
prefix: "t3-checkpoint-reactor-test-",
});
const vcsStatusBroadcasterLayer = Layer.succeed(VcsStatusBroadcaster, {
const gitStatusBroadcasterLayer = Layer.succeed(GitStatusBroadcaster, {
getStatus: () => Effect.die("getStatus should not be called in this test"),
refreshLocalStatus: (cwd: string) =>
Effect.sync(() => {
@@ -291,10 +274,9 @@ describe("CheckpointReactor", () => {
}).pipe(
Effect.as({
isRepo: true,
kind: "git",
hasPrimaryRemote: false,
isDefaultRef: true,
refName: "main",
hasOriginRemote: false,
isDefaultBranch: true,
branch: "main",
hasWorkingTreeChanges: false,
workingTree: { files: [], insertions: 0, deletions: 0 },
}),
@@ -307,16 +289,11 @@ describe("CheckpointReactor", () => {
Layer.provideMerge(orchestrationLayer),
Layer.provideMerge(RuntimeReceiptBusLive),
Layer.provideMerge(Layer.succeed(ProviderService, provider.service)),
Layer.provideMerge(vcsStatusBroadcasterLayer),
Layer.provideMerge(CheckpointStoreLive.pipe(Layer.provide(VcsDriverRegistry.layer))),
Layer.provideMerge(
WorkspaceEntriesLive.pipe(
Layer.provide(WorkspacePathsLive),
Layer.provideMerge(VcsDriverRegistry.layer),
),
),
Layer.provideMerge(gitStatusBroadcasterLayer),
Layer.provideMerge(CheckpointStoreLive),
Layer.provideMerge(WorkspaceEntriesLive.pipe(Layer.provide(WorkspacePathsLive))),
Layer.provideMerge(WorkspacePathsLive),
Layer.provideMerge(VcsProcess.layer),
Layer.provideMerge(GitCoreLive),
Layer.provideMerge(ServerConfigLayer),
Layer.provideMerge(NodeServices.layer),
);
@@ -338,7 +315,7 @@ describe("CheckpointReactor", () => {
title: "Test Project",
workspaceRoot: options?.projectWorkspaceRoot ?? cwd,
defaultModelSelection: {
instanceId: ProviderInstanceId.make("codex"),
provider: "codex",
model: "gpt-5-codex",
},
createdAt,
@@ -352,7 +329,7 @@ describe("CheckpointReactor", () => {
projectId: asProjectId("project-1"),
title: "Thread",
modelSelection: {
instanceId: ProviderInstanceId.make("codex"),
provider: "codex",
model: "gpt-5-codex",
},
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
@@ -419,7 +396,7 @@ describe("CheckpointReactor", () => {
harness.provider.emit({
type: "turn.started",
eventId: EventId.make("evt-turn-started-1"),
provider: ProviderDriverKind.make("codex"),
provider: "codex",
createdAt: new Date().toISOString(),
threadId: ThreadId.make("thread-1"),
@@ -434,7 +411,7 @@ describe("CheckpointReactor", () => {
harness.provider.emit({
type: "turn.completed",
eventId: EventId.make("evt-turn-completed-1"),
provider: ProviderDriverKind.make("codex"),
provider: "codex",
createdAt: new Date().toISOString(),
threadId: ThreadId.make("thread-1"),
@@ -480,7 +457,7 @@ describe("CheckpointReactor", () => {
harness.provider.emit({
type: "turn.completed",
eventId: EventId.make("evt-turn-completed-refresh-local-status"),
provider: ProviderDriverKind.make("codex"),
provider: "codex",
createdAt: new Date().toISOString(),
threadId: ThreadId.make("thread-1"),
turnId: asTurnId("turn-refresh-local-status"),
@@ -517,7 +494,7 @@ describe("CheckpointReactor", () => {
harness.provider.emit({
type: "turn.started",
eventId: EventId.make("evt-turn-started-main"),
provider: ProviderDriverKind.make("codex"),
provider: "codex",
createdAt: new Date().toISOString(),
threadId: ThreadId.make("thread-1"),
@@ -533,7 +510,7 @@ describe("CheckpointReactor", () => {
harness.provider.emit({
type: "turn.completed",
eventId: EventId.make("evt-turn-completed-aux"),
provider: ProviderDriverKind.make("codex"),
provider: "codex",
createdAt: new Date().toISOString(),
threadId: ThreadId.make("thread-1"),
@@ -549,7 +526,7 @@ describe("CheckpointReactor", () => {
harness.provider.emit({
type: "turn.completed",
eventId: EventId.make("evt-turn-completed-main"),
provider: ProviderDriverKind.make("codex"),
provider: "codex",
createdAt: new Date().toISOString(),
threadId: ThreadId.make("thread-1"),
@@ -567,7 +544,7 @@ describe("CheckpointReactor", () => {
it("captures pre-turn and completion checkpoints for claude runtime events", async () => {
const harness = await createHarness({
seedFilesystemCheckpoints: false,
providerName: ProviderDriverKind.make("claudeAgent"),
providerName: "claudeAgent",
});
const createdAt = new Date().toISOString();
@@ -592,7 +569,7 @@ describe("CheckpointReactor", () => {
harness.provider.emit({
type: "turn.started",
eventId: EventId.make("evt-turn-started-claude-1"),
provider: ProviderDriverKind.make("claudeAgent"),
provider: "claudeAgent",
createdAt: new Date().toISOString(),
threadId: ThreadId.make("thread-1"),
turnId: asTurnId("turn-claude-1"),
@@ -606,7 +583,7 @@ describe("CheckpointReactor", () => {
harness.provider.emit({
type: "turn.completed",
eventId: EventId.make("evt-turn-completed-claude-1"),
provider: ProviderDriverKind.make("claudeAgent"),
provider: "claudeAgent",
createdAt: new Date().toISOString(),
threadId: ThreadId.make("thread-1"),
turnId: asTurnId("turn-claude-1"),
@@ -650,7 +627,7 @@ describe("CheckpointReactor", () => {
harness.provider.emit({
type: "turn.completed",
eventId: EventId.make("evt-turn-completed-missing-baseline"),
provider: ProviderDriverKind.make("codex"),
provider: "codex",
createdAt: new Date().toISOString(),
threadId: ThreadId.make("thread-1"),
@@ -739,7 +716,7 @@ describe("CheckpointReactor", () => {
harness.provider.emit({
type: "turn.completed",
eventId: EventId.make("evt-turn-completed-missing-provider-cwd"),
provider: ProviderDriverKind.make("codex"),
provider: "codex",
createdAt: new Date().toISOString(),
threadId: ThreadId.make("thread-1"),
@@ -785,7 +762,7 @@ describe("CheckpointReactor", () => {
harness.provider.emit({
type: "checkpoint.captured",
eventId: EventId.make("evt-checkpoint-captured-3"),
provider: ProviderDriverKind.make("codex"),
provider: "codex",
createdAt: new Date().toISOString(),
threadId: ThreadId.make("thread-1"),
@@ -835,7 +812,7 @@ describe("CheckpointReactor", () => {
harness.provider.emit({
type: "turn.completed",
eventId: EventId.make("evt-runtime-capture-failure"),
provider: ProviderDriverKind.make("codex"),
provider: "codex",
createdAt: new Date().toISOString(),
threadId: ThreadId.make("thread-1"),
@@ -846,7 +823,7 @@ describe("CheckpointReactor", () => {
harness.provider.emit({
type: "turn.started",
eventId: EventId.make("evt-turn-started-after-runtime-failure"),
provider: ProviderDriverKind.make("codex"),
provider: "codex",
createdAt: new Date().toISOString(),
threadId: ThreadId.make("thread-1"),
@@ -941,7 +918,7 @@ describe("CheckpointReactor", () => {
});
it("executes provider revert and emits thread.reverted for claude sessions", async () => {
const harness = await createHarness({ providerName: ProviderDriverKind.make("claudeAgent") });
const harness = await createHarness({ providerName: "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 { VcsStatusBroadcaster } from "../../vcs/VcsStatusBroadcaster.ts";
import { GitStatusBroadcaster } from "../../git/Services/GitStatusBroadcaster.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 vcsStatusBroadcaster = yield* VcsStatusBroadcaster;
const gitStatusBroadcaster = yield* GitStatusBroadcaster;
const appendRevertFailureActivity = (input: {
readonly threadId: ThreadId;
@@ -508,7 +508,7 @@ const make = Effect.gen(function* () {
return;
}
yield* vcsStatusBroadcaster.refreshLocalStatus(sessionRuntime.value.cwd).pipe(
yield* gitStatusBroadcaster.refreshLocalStatus(sessionRuntime.value.cwd).pipe(
Effect.catch((error) =>
Effect.logWarning("failed to refresh local git status after turn completion", {
threadId: event.threadId,
@@ -7,7 +7,6 @@ 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";
@@ -105,7 +104,7 @@ describe("OrchestrationEngine", () => {
title: "Bootstrap Project",
workspaceRoot: "/tmp/project-bootstrap",
defaultModelSelection: {
instanceId: ProviderInstanceId.make("codex"),
provider: "codex" as const,
model: "gpt-5-codex",
},
scripts: [],
@@ -120,7 +119,7 @@ describe("OrchestrationEngine", () => {
projectId: asProjectId("project-bootstrap"),
title: "Bootstrap Thread",
modelSelection: {
instanceId: ProviderInstanceId.make("codex"),
provider: "codex" as const,
model: "gpt-5-codex",
},
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
@@ -199,7 +198,7 @@ describe("OrchestrationEngine", () => {
title: "Project 1",
workspaceRoot: "/tmp/project-1",
defaultModelSelection: {
instanceId: ProviderInstanceId.make("codex"),
provider: "codex",
model: "gpt-5-codex",
},
createdAt,
@@ -213,7 +212,7 @@ describe("OrchestrationEngine", () => {
projectId: asProjectId("project-1"),
title: "Thread",
modelSelection: {
instanceId: ProviderInstanceId.make("codex"),
provider: "codex",
model: "gpt-5-codex",
},
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
@@ -259,7 +258,7 @@ describe("OrchestrationEngine", () => {
title: "Project Archive",
workspaceRoot: "/tmp/project-archive",
defaultModelSelection: {
instanceId: ProviderInstanceId.make("codex"),
provider: "codex",
model: "gpt-5-codex",
},
createdAt,
@@ -273,7 +272,7 @@ describe("OrchestrationEngine", () => {
projectId: asProjectId("project-archive"),
title: "Archive me",
modelSelection: {
instanceId: ProviderInstanceId.make("codex"),
provider: "codex",
model: "gpt-5-codex",
},
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
@@ -326,7 +325,7 @@ describe("OrchestrationEngine", () => {
title: "Replay Project",
workspaceRoot: "/tmp/project-replay",
defaultModelSelection: {
instanceId: ProviderInstanceId.make("codex"),
provider: "codex",
model: "gpt-5-codex",
},
createdAt,
@@ -340,7 +339,7 @@ describe("OrchestrationEngine", () => {
projectId: asProjectId("project-replay"),
title: "replay",
modelSelection: {
instanceId: ProviderInstanceId.make("codex"),
provider: "codex",
model: "gpt-5-codex",
},
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
@@ -384,7 +383,7 @@ describe("OrchestrationEngine", () => {
title: "Stream Project",
workspaceRoot: "/tmp/project-stream",
defaultModelSelection: {
instanceId: ProviderInstanceId.make("codex"),
provider: "codex",
model: "gpt-5-codex",
},
createdAt,
@@ -408,7 +407,7 @@ describe("OrchestrationEngine", () => {
projectId: asProjectId("project-stream"),
title: "domain-stream",
modelSelection: {
instanceId: ProviderInstanceId.make("codex"),
provider: "codex",
model: "gpt-5-codex",
},
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
@@ -445,7 +444,7 @@ describe("OrchestrationEngine", () => {
title: "Ack Project",
workspaceRoot: "/tmp/project-ack",
defaultModelSelection: {
instanceId: ProviderInstanceId.make("codex"),
provider: "codex",
model: "gpt-5-codex",
},
createdAt,
@@ -460,7 +459,7 @@ describe("OrchestrationEngine", () => {
projectId: asProjectId("project-ack"),
title: "Ack Thread",
modelSelection: {
instanceId: ProviderInstanceId.make("codex"),
provider: "codex",
model: "gpt-5-codex",
},
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
@@ -497,7 +496,7 @@ describe("OrchestrationEngine", () => {
projectId: asProjectId("project-missing"),
title: "Missing Project Thread",
modelSelection: {
instanceId: ProviderInstanceId.make("codex"),
provider: "codex",
model: "gpt-5-codex",
},
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
@@ -534,7 +533,7 @@ describe("OrchestrationEngine", () => {
title: "Turn Diff Project",
workspaceRoot: "/tmp/project-turn-diff",
defaultModelSelection: {
instanceId: ProviderInstanceId.make("codex"),
provider: "codex",
model: "gpt-5-codex",
},
createdAt,
@@ -548,7 +547,7 @@ describe("OrchestrationEngine", () => {
projectId: asProjectId("project-turn-diff"),
title: "Turn diff thread",
modelSelection: {
instanceId: ProviderInstanceId.make("codex"),
provider: "codex",
model: "gpt-5-codex",
},
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
@@ -653,7 +652,7 @@ describe("OrchestrationEngine", () => {
title: "Flaky Project",
workspaceRoot: "/tmp/project-flaky",
defaultModelSelection: {
instanceId: ProviderInstanceId.make("codex"),
provider: "codex",
model: "gpt-5-codex",
},
createdAt,
@@ -669,7 +668,7 @@ describe("OrchestrationEngine", () => {
projectId: asProjectId("project-flaky"),
title: "flaky-fail",
modelSelection: {
instanceId: ProviderInstanceId.make("codex"),
provider: "codex",
model: "gpt-5-codex",
},
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
@@ -689,7 +688,7 @@ describe("OrchestrationEngine", () => {
projectId: asProjectId("project-flaky"),
title: "flaky-ok",
modelSelection: {
instanceId: ProviderInstanceId.make("codex"),
provider: "codex",
model: "gpt-5-codex",
},
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
@@ -748,7 +747,7 @@ describe("OrchestrationEngine", () => {
title: "Atomic Project",
workspaceRoot: "/tmp/project-atomic",
defaultModelSelection: {
instanceId: ProviderInstanceId.make("codex"),
provider: "codex",
model: "gpt-5-codex",
},
createdAt,
@@ -762,7 +761,7 @@ describe("OrchestrationEngine", () => {
projectId: asProjectId("project-atomic"),
title: "atomic",
modelSelection: {
instanceId: ProviderInstanceId.make("codex"),
provider: "codex",
model: "gpt-5-codex",
},
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
@@ -891,7 +890,7 @@ describe("OrchestrationEngine", () => {
title: "Sync Project",
workspaceRoot: "/tmp/project-sync",
defaultModelSelection: {
instanceId: ProviderInstanceId.make("codex"),
provider: "codex",
model: "gpt-5-codex",
},
createdAt,
@@ -905,7 +904,7 @@ describe("OrchestrationEngine", () => {
projectId: asProjectId("project-sync"),
title: "sync-before",
modelSelection: {
instanceId: ProviderInstanceId.make("codex"),
provider: "codex",
model: "gpt-5-codex",
},
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
@@ -976,7 +975,7 @@ describe("OrchestrationEngine", () => {
title: "Duplicate Project",
workspaceRoot: "/tmp/project-duplicate",
defaultModelSelection: {
instanceId: ProviderInstanceId.make("codex"),
provider: "codex",
model: "gpt-5-codex",
},
createdAt,
@@ -991,7 +990,7 @@ describe("OrchestrationEngine", () => {
projectId: asProjectId("project-duplicate"),
title: "duplicate",
modelSelection: {
instanceId: ProviderInstanceId.make("codex"),
provider: "codex",
model: "gpt-5-codex",
},
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
@@ -1011,7 +1010,7 @@ describe("OrchestrationEngine", () => {
projectId: asProjectId("project-duplicate"),
title: "duplicate",
modelSelection: {
instanceId: ProviderInstanceId.make("codex"),
provider: "codex",
model: "gpt-5-codex",
},
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
@@ -7,7 +7,6 @@ import {
ProjectId,
ThreadId,
TurnId,
ProviderInstanceId,
} from "@t3tools/contracts";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { assert, it } from "@effect/vitest";
@@ -93,7 +92,7 @@ it.layer(BaseTestLayer)("OrchestrationProjectionPipeline", (it) => {
projectId: ProjectId.make("project-1"),
title: "Thread 1",
modelSelection: {
instanceId: ProviderInstanceId.make("codex"),
provider: "codex",
model: "gpt-5-codex",
},
runtimeMode: "full-access",
@@ -365,7 +364,7 @@ it.layer(BaseTestLayer)("OrchestrationProjectionPipeline", (it) => {
projectId: ProjectId.make("project-clear-attachments"),
title: "Thread Clear Attachments",
modelSelection: {
instanceId: ProviderInstanceId.make("codex"),
provider: "codex",
model: "gpt-5-codex",
},
runtimeMode: "full-access",
@@ -493,7 +492,7 @@ it.layer(
projectId: ProjectId.make("project-overwrite"),
title: "Thread Overwrite",
modelSelection: {
instanceId: ProviderInstanceId.make("codex"),
provider: "codex",
model: "gpt-5-codex",
},
runtimeMode: "full-access",
@@ -641,7 +640,7 @@ it.layer(
projectId: ProjectId.make("project-rollback"),
title: "Thread Rollback",
modelSelection: {
instanceId: ProviderInstanceId.make("codex"),
provider: "codex",
model: "gpt-5-codex",
},
runtimeMode: "full-access",
@@ -770,7 +769,7 @@ it.layer(
projectId: ProjectId.make("project-revert-files"),
title: "Thread Revert Files",
modelSelection: {
instanceId: ProviderInstanceId.make("codex"),
provider: "codex",
model: "gpt-5-codex",
},
runtimeMode: "full-access",
@@ -978,7 +977,7 @@ it.layer(Layer.fresh(makeProjectionPipelinePrefixedTestLayer("t3-projection-atta
projectId: ProjectId.make("project-delete-files"),
title: "Thread Delete Files",
modelSelection: {
instanceId: ProviderInstanceId.make("codex"),
provider: "codex",
model: "gpt-5-codex",
},
runtimeMode: "full-access",
@@ -1141,7 +1140,7 @@ it.layer(BaseTestLayer)("OrchestrationProjectionPipeline", (it) => {
projectId: ProjectId.make("project-a"),
title: "Thread A",
modelSelection: {
instanceId: ProviderInstanceId.make("codex"),
provider: "codex",
model: "gpt-5-codex",
},
runtimeMode: "full-access",
@@ -1268,7 +1267,7 @@ it.layer(BaseTestLayer)("OrchestrationProjectionPipeline", (it) => {
projectId: ProjectId.make("project-empty"),
title: "Thread Empty",
modelSelection: {
instanceId: ProviderInstanceId.make("codex"),
provider: "codex",
model: "gpt-5-codex",
},
runtimeMode: "full-access",
@@ -1408,7 +1407,7 @@ it.layer(BaseTestLayer)("OrchestrationProjectionPipeline", (it) => {
projectId: ProjectId.make("project-conflict"),
title: "Thread Conflict",
modelSelection: {
instanceId: ProviderInstanceId.make("codex"),
provider: "codex",
model: "gpt-5-codex",
},
runtimeMode: "full-access",
@@ -1552,7 +1551,7 @@ it.layer(BaseTestLayer)("OrchestrationProjectionPipeline", (it) => {
projectId: ProjectId.make("project-stale-approval"),
title: "Thread Stale Approval",
modelSelection: {
instanceId: ProviderInstanceId.make("codex"),
provider: "codex",
model: "gpt-5-codex",
},
runtimeMode: "approval-required",
@@ -1695,7 +1694,7 @@ it.layer(BaseTestLayer)("OrchestrationProjectionPipeline", (it) => {
projectId: ProjectId.make("project-nonstale-approval"),
title: "Thread Non-Stale Approval",
modelSelection: {
instanceId: ProviderInstanceId.make("codex"),
provider: "codex",
model: "gpt-5-codex",
},
runtimeMode: "approval-required",
@@ -1875,7 +1874,7 @@ it.layer(BaseTestLayer)("OrchestrationProjectionPipeline", (it) => {
projectId: ProjectId.make("project-revert"),
title: "Thread Revert",
modelSelection: {
instanceId: ProviderInstanceId.make("codex"),
provider: "codex",
model: "gpt-5-codex",
},
runtimeMode: "full-access",
@@ -2196,7 +2195,7 @@ engineLayer("OrchestrationProjectionPipeline via engine dispatch", (it) => {
title: "Live Project",
workspaceRoot: "/tmp/project-live",
defaultModelSelection: {
instanceId: ProviderInstanceId.make("codex"),
provider: "codex",
model: "gpt-5-codex",
},
createdAt,
@@ -2234,7 +2233,7 @@ engineLayer("OrchestrationProjectionPipeline via engine dispatch", (it) => {
title: "Scripts Project",
workspaceRoot: "/tmp/project-scripts",
defaultModelSelection: {
instanceId: ProviderInstanceId.make("codex"),
provider: "codex",
model: "gpt-5-codex",
},
createdAt,
@@ -2254,7 +2253,7 @@ engineLayer("OrchestrationProjectionPipeline via engine dispatch", (it) => {
},
],
defaultModelSelection: {
instanceId: ProviderInstanceId.make("codex"),
provider: "codex",
model: "gpt-5",
},
});
@@ -2273,7 +2272,7 @@ engineLayer("OrchestrationProjectionPipeline via engine dispatch", (it) => {
{
scriptsJson:
'[{"id":"script-1","name":"Build","command":"bun run build","icon":"build","runOnWorktreeCreate":false}]',
defaultModelSelection: '{"instanceId":"codex","model":"gpt-5"}',
defaultModelSelection: '{"provider":"codex","model":"gpt-5"}',
},
]);
}),
@@ -945,7 +945,6 @@ 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,12 +1,4 @@
import {
CheckpointRef,
EventId,
MessageId,
ProjectId,
ThreadId,
TurnId,
ProviderInstanceId,
} from "@t3tools/contracts";
import { CheckpointRef, EventId, MessageId, ProjectId, ThreadId, TurnId } from "@t3tools/contracts";
import { assert, it } from "@effect/vitest";
import { Effect, Layer } from "effect";
import * as SqlClient from "effect/unstable/sql/SqlClient";
@@ -260,7 +252,7 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
workspaceRoot: "/tmp/project-1",
repositoryIdentity: null,
defaultModelSelection: {
instanceId: ProviderInstanceId.make("codex"),
provider: "codex",
model: "gpt-5-codex",
},
scripts: [
@@ -283,7 +275,7 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
projectId: asProjectId("project-1"),
title: "Thread 1",
modelSelection: {
instanceId: ProviderInstanceId.make("codex"),
provider: "codex",
model: "gpt-5-codex",
},
interactionMode: "default",
@@ -371,7 +363,7 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
workspaceRoot: "/tmp/project-1",
repositoryIdentity: null,
defaultModelSelection: {
instanceId: ProviderInstanceId.make("codex"),
provider: "codex",
model: "gpt-5-codex",
},
scripts: [
@@ -393,7 +385,7 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
projectId: asProjectId("project-1"),
title: "Thread 1",
modelSelection: {
instanceId: ProviderInstanceId.make("codex"),
provider: "codex",
model: "gpt-5-codex",
},
interactionMode: "default",
@@ -195,7 +195,6 @@ 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,
@@ -351,7 +350,6 @@ 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",
@@ -610,7 +608,6 @@ 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",
@@ -882,9 +879,6 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
threadId: row.threadId,
status: row.status,
providerName: row.providerName,
...(row.providerInstanceId !== null
? { providerInstanceId: row.providerInstanceId }
: {}),
runtimeMode: row.runtimeMode,
activeTurnId: row.activeTurnId,
lastError: row.lastError,
@@ -2,13 +2,7 @@ import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import {
ModelSelection,
ProviderRuntimeEvent,
ProviderSession,
ProviderDriverKind,
ProviderInstanceId,
} from "@t3tools/contracts";
import type { ModelSelection, ProviderRuntimeEvent, ProviderSession } from "@t3tools/contracts";
import { createModelSelection } from "@t3tools/shared/model";
import {
ApprovalRequestId,
@@ -33,22 +27,21 @@ import {
ProviderService,
type ProviderServiceShape,
} from "../../provider/Services/ProviderService.ts";
import { TextGeneration, type TextGenerationShape } from "../../textGeneration/TextGeneration.ts";
import { GitCore, type GitCoreShape } from "../../git/Services/GitCore.ts";
import {
GitStatusBroadcaster,
type GitStatusBroadcasterShape,
} from "../../git/Services/GitStatusBroadcaster.ts";
import { TextGeneration, type TextGenerationShape } from "../../git/Services/TextGeneration.ts";
import { RepositoryIdentityResolverLive } from "../../project/Layers/RepositoryIdentityResolver.ts";
import { OrchestrationEngineLive } from "./OrchestrationEngine.ts";
import { OrchestrationProjectionPipelineLive } from "./ProjectionPipeline.ts";
import { OrchestrationProjectionSnapshotQueryLive } from "./ProjectionSnapshotQuery.ts";
import {
providerErrorLabel,
providerErrorLabelFromInstanceHint,
ProviderCommandReactorLive,
} from "./ProviderCommandReactor.ts";
import { ProviderCommandReactorLive } from "./ProviderCommandReactor.ts";
import { OrchestrationEngineService } from "../Services/OrchestrationEngine.ts";
import { ProviderCommandReactor } from "../Services/ProviderCommandReactor.ts";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { ServerSettingsService } from "../../serverSettings.ts";
import { VcsStatusBroadcaster } from "../../vcs/VcsStatusBroadcaster.ts";
import { GitWorkflowService, type GitWorkflowServiceShape } from "../../git/GitWorkflowService.ts";
const asProjectId = (value: string): ProjectId => ProjectId.make(value);
const asApprovalRequestId = (value: string): ApprovalRequestId => ApprovalRequestId.make(value);
@@ -105,30 +98,6 @@ describe("ProviderCommandReactor", () => {
createdBaseDirs.clear();
});
describe("provider error attribution", () => {
it("uses the current provider instance slug when current instance lookup fails", () => {
expect(
providerErrorLabelFromInstanceHint({
instanceId: "codex_personal",
modelSelectionInstanceId: "codex",
sessionProvider: "codex",
}),
).toBe("codex_personal");
});
it("uses the desired provider instance slug when desired instance lookup fails", () => {
expect(
providerErrorLabelFromInstanceHint({
instanceId: "claude_openrouter",
}),
).toBe("claude_openrouter");
});
it("uses the unknown driver kind when the resolved driver is not registered locally", () => {
expect(providerErrorLabel("third_party_driver")).toBe("third_party_driver");
});
});
async function createHarness(input?: {
readonly baseDir?: string;
readonly threadModelSelection?: ModelSelection;
@@ -143,7 +112,7 @@ describe("ProviderCommandReactor", () => {
let nextSessionIndex = 1;
const runtimeSessions: Array<ProviderSession> = [];
const modelSelection = input?.threadModelSelection ?? {
instanceId: ProviderInstanceId.make("codex"),
provider: "codex",
model: "gpt-5-codex",
};
const startSession = vi.fn((_: unknown, input: unknown) => {
@@ -159,24 +128,8 @@ describe("ProviderCommandReactor", () => {
typeof input.threadId === "string"
? ThreadId.make(input.threadId)
: ThreadId.make(`thread-${sessionIndex}`);
const inputModelSelection =
typeof input === "object" && input !== null && "modelSelection" in input
? (input.modelSelection as ModelSelection | undefined)
: undefined;
const providerInstanceId =
typeof input === "object" && input !== null && "providerInstanceId" in input
? (input.providerInstanceId as ProviderInstanceId | undefined)
: inputModelSelection?.instanceId;
const provider =
typeof input === "object" &&
input !== null &&
"provider" in input &&
typeof input.provider === "string"
? (input.provider as ProviderSession["provider"])
: ProviderDriverKind.make(inputModelSelection?.instanceId ?? modelSelection.instanceId);
const session: ProviderSession = {
provider,
...(providerInstanceId ? { providerInstanceId } : {}),
provider: modelSelection.provider,
status: "ready" as const,
runtimeMode:
typeof input === "object" &&
@@ -185,15 +138,7 @@ describe("ProviderCommandReactor", () => {
(input.runtimeMode === "approval-required" || input.runtimeMode === "full-access")
? input.runtimeMode
: "full-access",
...(typeof input === "object" &&
input !== null &&
"cwd" in input &&
typeof input.cwd === "string"
? { cwd: input.cwd }
: {}),
...((inputModelSelection?.model ?? modelSelection.model)
? { model: inputModelSelection?.model ?? modelSelection.model }
: {}),
...(modelSelection.model !== undefined ? { model: modelSelection.model } : {}),
threadId,
resumeCursor: resumeCursor ?? { opaque: `resume-${sessionIndex}` },
createdAt: now,
@@ -240,10 +185,9 @@ describe("ProviderCommandReactor", () => {
const refreshStatus = vi.fn((_: string) =>
Effect.succeed({
isRepo: true,
kind: "git" as const,
hasPrimaryRemote: true,
isDefaultRef: false,
refName: "renamed-branch",
hasOriginRemote: true,
isDefaultBranch: false,
branch: "renamed-branch",
hasWorkingTreeChanges: false,
workingTree: {
files: [],
@@ -286,25 +230,6 @@ describe("ProviderCommandReactor", () => {
Effect.succeed({
sessionModelSwitch: input?.sessionModelSwitch ?? "in-session",
}),
getInstanceInfo: (instanceId) => {
const raw = String(instanceId);
const driverKind = ProviderDriverKind.make(
raw.startsWith("claude") ? "claudeAgent" : raw.startsWith("codex") ? "codex" : raw,
);
return Effect.succeed({
instanceId,
driverKind,
displayName: undefined,
enabled: true,
continuationIdentity: {
driverKind,
continuationKey:
driverKind === ProviderDriverKind.make("codex")
? "codex:home:/shared-codex"
: `${driverKind}:instance:${instanceId}`,
},
});
},
rollbackConversation: () => unsupported(),
get streamEvents() {
return Stream.fromPubSub(runtimeEventPubSub);
@@ -322,19 +247,15 @@ describe("ProviderCommandReactor", () => {
const layer = ProviderCommandReactorLive.pipe(
Layer.provideMerge(orchestrationLayer),
Layer.provideMerge(Layer.succeed(ProviderService, service)),
Layer.provideMerge(Layer.succeed(GitCore, { renameBranch } as unknown as GitCoreShape)),
Layer.provideMerge(
Layer.mock(GitWorkflowService)({
renameBranch,
} satisfies Partial<GitWorkflowServiceShape>),
),
Layer.provideMerge(
Layer.succeed(VcsStatusBroadcaster, {
Layer.succeed(GitStatusBroadcaster, {
getStatus: () => Effect.die("getStatus should not be called in this test"),
refreshLocalStatus: () =>
Effect.die("refreshLocalStatus should not be called in this test"),
refreshStatus,
streamStatus: () => Stream.die("streamStatus should not be called in this test"),
}),
} satisfies GitStatusBroadcasterShape),
),
Layer.provideMerge(
Layer.mock(TextGeneration, {
@@ -393,7 +314,6 @@ describe("ProviderCommandReactor", () => {
refreshStatus,
generateBranchName,
generateThreadTitle,
runtimeSessions,
stateDir,
drain,
};
@@ -426,7 +346,7 @@ describe("ProviderCommandReactor", () => {
expect(harness.startSession.mock.calls[0]?.[1]).toMatchObject({
cwd: "/tmp/provider-project",
modelSelection: {
instanceId: ProviderInstanceId.make("codex"),
provider: "codex",
model: "gpt-5-codex",
},
runtimeMode: "approval-required",
@@ -648,7 +568,7 @@ describe("ProviderCommandReactor", () => {
text: "hello fast mode",
attachments: [],
},
modelSelection: createModelSelection(ProviderInstanceId.make("codex"), "gpt-5.3-codex", [
modelSelection: createModelSelection("codex", "gpt-5.3-codex", [
{ id: "reasoningEffort", value: "high" },
{ id: "fastMode", value: true },
]),
@@ -661,14 +581,14 @@ describe("ProviderCommandReactor", () => {
await waitFor(() => harness.startSession.mock.calls.length === 1);
await waitFor(() => harness.sendTurn.mock.calls.length === 1);
expect(harness.startSession.mock.calls[0]?.[1]).toMatchObject({
modelSelection: createModelSelection(ProviderInstanceId.make("codex"), "gpt-5.3-codex", [
modelSelection: createModelSelection("codex", "gpt-5.3-codex", [
{ id: "reasoningEffort", value: "high" },
{ id: "fastMode", value: true },
]),
});
expect(harness.sendTurn.mock.calls[0]?.[0]).toMatchObject({
threadId: ThreadId.make("thread-1"),
modelSelection: createModelSelection(ProviderInstanceId.make("codex"), "gpt-5.3-codex", [
modelSelection: createModelSelection("codex", "gpt-5.3-codex", [
{ id: "reasoningEffort", value: "high" },
{ id: "fastMode", value: true },
]),
@@ -677,10 +597,7 @@ describe("ProviderCommandReactor", () => {
it("forwards claude effort options through session start and turn send", async () => {
const harness = await createHarness({
threadModelSelection: {
instanceId: ProviderInstanceId.make("claudeAgent"),
model: "claude-sonnet-4-6",
},
threadModelSelection: { provider: "claudeAgent", model: "claude-sonnet-4-6" },
});
const now = new Date().toISOString();
@@ -695,11 +612,9 @@ describe("ProviderCommandReactor", () => {
text: "hello with effort",
attachments: [],
},
modelSelection: createModelSelection(
ProviderInstanceId.make("claudeAgent"),
"claude-sonnet-4-6",
[{ id: "effort", value: "max" }],
),
modelSelection: createModelSelection("claudeAgent", "claude-sonnet-4-6", [
{ id: "effort", value: "max" },
]),
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "approval-required",
createdAt: now,
@@ -709,28 +624,21 @@ describe("ProviderCommandReactor", () => {
await waitFor(() => harness.startSession.mock.calls.length === 1);
await waitFor(() => harness.sendTurn.mock.calls.length === 1);
expect(harness.startSession.mock.calls[0]?.[1]).toMatchObject({
modelSelection: createModelSelection(
ProviderInstanceId.make("claudeAgent"),
"claude-sonnet-4-6",
[{ id: "effort", value: "max" }],
),
modelSelection: createModelSelection("claudeAgent", "claude-sonnet-4-6", [
{ id: "effort", value: "max" },
]),
});
expect(harness.sendTurn.mock.calls[0]?.[0]).toMatchObject({
threadId: ThreadId.make("thread-1"),
modelSelection: createModelSelection(
ProviderInstanceId.make("claudeAgent"),
"claude-sonnet-4-6",
[{ id: "effort", value: "max" }],
),
modelSelection: createModelSelection("claudeAgent", "claude-sonnet-4-6", [
{ id: "effort", value: "max" },
]),
});
});
it("forwards claude fast mode options through session start and turn send", async () => {
const harness = await createHarness({
threadModelSelection: {
instanceId: ProviderInstanceId.make("claudeAgent"),
model: "claude-opus-4-6",
},
threadModelSelection: { provider: "claudeAgent", model: "claude-opus-4-6" },
});
const now = new Date().toISOString();
@@ -745,11 +653,9 @@ describe("ProviderCommandReactor", () => {
text: "hello with fast mode",
attachments: [],
},
modelSelection: createModelSelection(
ProviderInstanceId.make("claudeAgent"),
"claude-opus-4-6",
[{ id: "fastMode", value: true }],
),
modelSelection: createModelSelection("claudeAgent", "claude-opus-4-6", [
{ id: "fastMode", value: true },
]),
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "approval-required",
createdAt: now,
@@ -759,19 +665,15 @@ describe("ProviderCommandReactor", () => {
await waitFor(() => harness.startSession.mock.calls.length === 1);
await waitFor(() => harness.sendTurn.mock.calls.length === 1);
expect(harness.startSession.mock.calls[0]?.[1]).toMatchObject({
modelSelection: createModelSelection(
ProviderInstanceId.make("claudeAgent"),
"claude-opus-4-6",
[{ id: "fastMode", value: true }],
),
modelSelection: createModelSelection("claudeAgent", "claude-opus-4-6", [
{ id: "fastMode", value: true },
]),
});
expect(harness.sendTurn.mock.calls[0]?.[0]).toMatchObject({
threadId: ThreadId.make("thread-1"),
modelSelection: createModelSelection(
ProviderInstanceId.make("claudeAgent"),
"claude-opus-4-6",
[{ id: "fastMode", value: true }],
),
modelSelection: createModelSelection("claudeAgent", "claude-opus-4-6", [
{ id: "fastMode", value: true },
]),
});
});
@@ -858,15 +760,15 @@ describe("ProviderCommandReactor", () => {
expect(harness.sendTurn.mock.calls[1]?.[0]).toMatchObject({
threadId: ThreadId.make("thread-1"),
modelSelection: {
instanceId: ProviderInstanceId.make("codex"),
provider: "codex",
model: "gpt-5-codex",
},
});
});
it("starts a first turn on the requested provider instance even when it differs from the thread model", async () => {
it("rejects a first turn when requested provider conflicts with the thread model", async () => {
const harness = await createHarness({
threadModelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5-codex" },
threadModelSelection: { provider: "codex", model: "gpt-5-codex" },
});
const now = new Date().toISOString();
@@ -882,7 +784,7 @@ describe("ProviderCommandReactor", () => {
attachments: [],
},
modelSelection: {
instanceId: ProviderInstanceId.make("claudeAgent"),
provider: "claudeAgent",
model: "claude-opus-4-6",
},
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
@@ -891,25 +793,29 @@ describe("ProviderCommandReactor", () => {
}),
);
await waitFor(() => harness.sendTurn.mock.calls.length === 1);
expect(harness.startSession).toHaveBeenCalledTimes(1);
expect(harness.startSession.mock.calls[0]?.[1]).toMatchObject({
provider: ProviderDriverKind.make("claudeAgent"),
providerInstanceId: ProviderInstanceId.make("claudeAgent"),
modelSelection: {
instanceId: ProviderInstanceId.make("claudeAgent"),
model: "claude-opus-4-6",
},
await waitFor(async () => {
const readModel = await Effect.runPromise(harness.engine.getReadModel());
const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
return (
thread?.activities.some((activity) => activity.kind === "provider.turn.start.failed") ??
false
);
});
expect(harness.startSession).not.toHaveBeenCalled();
expect(harness.sendTurn).not.toHaveBeenCalled();
const readModel = await Effect.runPromise(harness.engine.getReadModel());
const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
expect(thread?.session?.providerName).toBe("claudeAgent");
expect(thread?.session?.providerInstanceId).toBe(ProviderInstanceId.make("claudeAgent"));
expect(thread?.session).toBeNull();
expect(
thread?.activities.find((activity) => activity.kind === "provider.turn.start.failed"),
).toBeUndefined();
).toMatchObject({
summary: "Provider turn start failed",
payload: {
detail: expect.stringContaining("cannot switch to 'claudeAgent'"),
},
});
});
it("reuses the same provider session when runtime mode is unchanged", async () => {
@@ -958,147 +864,9 @@ describe("ProviderCommandReactor", () => {
expect(harness.stopSession.mock.calls.length).toBe(0);
});
it("restarts an existing Codex thread on a compatible requested instance", async () => {
const harness = await createHarness();
const now = new Date().toISOString();
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.turn.start",
commandId: CommandId.make("cmd-turn-start-compatible-codex-1"),
threadId: ThreadId.make("thread-1"),
message: {
messageId: asMessageId("user-message-compatible-codex-1"),
role: "user",
text: "first",
attachments: [],
},
modelSelection: {
instanceId: ProviderInstanceId.make("codex"),
model: "gpt-5-codex",
},
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "approval-required",
createdAt: now,
}),
);
await waitFor(() => harness.sendTurn.mock.calls.length === 1);
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.turn.start",
commandId: CommandId.make("cmd-turn-start-compatible-codex-2"),
threadId: ThreadId.make("thread-1"),
message: {
messageId: asMessageId("user-message-compatible-codex-2"),
role: "user",
text: "second",
attachments: [],
},
modelSelection: {
instanceId: ProviderInstanceId.make("codex_work"),
model: "gpt-5-codex",
},
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "approval-required",
createdAt: new Date().toISOString(),
}),
);
await waitFor(() => harness.sendTurn.mock.calls.length === 2);
expect(harness.startSession).toHaveBeenCalledTimes(2);
expect(harness.startSession.mock.calls[1]?.[1]).toMatchObject({
provider: ProviderDriverKind.make("codex"),
providerInstanceId: ProviderInstanceId.make("codex_work"),
resumeCursor: { opaque: "resume-1" },
});
const readModel = await Effect.runPromise(harness.engine.getReadModel());
const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
expect(thread?.session?.providerInstanceId).toBe(ProviderInstanceId.make("codex_work"));
});
it("restarts the provider session when the thread workspace changes", async () => {
const harness = await createHarness({
threadModelSelection: {
instanceId: ProviderInstanceId.make("claudeAgent"),
model: "claude-sonnet-4-6",
},
});
const now = new Date().toISOString();
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.turn.start",
commandId: CommandId.make("cmd-turn-start-workspace-1"),
threadId: ThreadId.make("thread-1"),
message: {
messageId: asMessageId("user-message-workspace-1"),
role: "user",
text: "first in project root",
attachments: [],
},
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "approval-required",
createdAt: now,
}),
);
await waitFor(() => harness.startSession.mock.calls.length === 1);
await waitFor(() => harness.sendTurn.mock.calls.length === 1);
expect(harness.startSession.mock.calls[0]?.[1]).toMatchObject({
cwd: "/tmp/provider-project",
});
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.meta.update",
commandId: CommandId.make("cmd-thread-worktree-change"),
threadId: ThreadId.make("thread-1"),
worktreePath: "/tmp/provider-project-worktree",
}),
);
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.turn.start",
commandId: CommandId.make("cmd-turn-start-workspace-2"),
threadId: ThreadId.make("thread-1"),
message: {
messageId: asMessageId("user-message-workspace-2"),
role: "user",
text: "second in worktree",
attachments: [],
},
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "approval-required",
createdAt: now,
}),
);
await waitFor(() => harness.startSession.mock.calls.length === 2);
await waitFor(() => harness.sendTurn.mock.calls.length === 2);
expect(harness.stopSession.mock.calls.length).toBe(0);
expect(harness.startSession.mock.calls[1]?.[1]).toMatchObject({
threadId: ThreadId.make("thread-1"),
cwd: "/tmp/provider-project-worktree",
resumeCursor: { opaque: "resume-1" },
modelSelection: {
instanceId: ProviderInstanceId.make("claudeAgent"),
model: "claude-sonnet-4-6",
},
runtimeMode: "approval-required",
});
});
it("restarts claude sessions when claude effort changes", async () => {
const harness = await createHarness({
threadModelSelection: {
instanceId: ProviderInstanceId.make("claudeAgent"),
model: "claude-sonnet-4-6",
},
threadModelSelection: { provider: "claudeAgent", model: "claude-sonnet-4-6" },
});
const now = new Date().toISOString();
@@ -1113,11 +881,9 @@ describe("ProviderCommandReactor", () => {
text: "first claude turn",
attachments: [],
},
modelSelection: createModelSelection(
ProviderInstanceId.make("claudeAgent"),
"claude-sonnet-4-6",
[{ id: "effort", value: "medium" }],
),
modelSelection: createModelSelection("claudeAgent", "claude-sonnet-4-6", [
{ id: "effort", value: "medium" },
]),
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "approval-required",
createdAt: now,
@@ -1138,11 +904,9 @@ describe("ProviderCommandReactor", () => {
text: "second claude turn",
attachments: [],
},
modelSelection: createModelSelection(
ProviderInstanceId.make("claudeAgent"),
"claude-sonnet-4-6",
[{ id: "effort", value: "max" }],
),
modelSelection: createModelSelection("claudeAgent", "claude-sonnet-4-6", [
{ id: "effort", value: "max" },
]),
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "approval-required",
createdAt: now,
@@ -1153,11 +917,9 @@ describe("ProviderCommandReactor", () => {
await waitFor(() => harness.sendTurn.mock.calls.length === 2);
expect(harness.startSession.mock.calls[1]?.[1]).toMatchObject({
resumeCursor: { opaque: "resume-1" },
modelSelection: createModelSelection(
ProviderInstanceId.make("claudeAgent"),
"claude-sonnet-4-6",
[{ id: "effort", value: "max" }],
),
modelSelection: createModelSelection("claudeAgent", "claude-sonnet-4-6", [
{ id: "effort", value: "max" },
]),
});
});
@@ -1248,10 +1010,7 @@ describe("ProviderCommandReactor", () => {
it("does not inject derived model options when restarting claude on runtime mode changes", async () => {
const harness = await createHarness({
threadModelSelection: {
instanceId: ProviderInstanceId.make("claudeAgent"),
model: "claude-opus-4-6",
},
threadModelSelection: { provider: "claudeAgent", model: "claude-opus-4-6" },
});
const now = new Date().toISOString();
@@ -1287,7 +1046,7 @@ describe("ProviderCommandReactor", () => {
expect(harness.startSession.mock.calls[0]?.[1]).toMatchObject({
modelSelection: {
instanceId: ProviderInstanceId.make("claudeAgent"),
provider: "claudeAgent",
model: "claude-opus-4-6",
},
runtimeMode: "approval-required",
@@ -1395,7 +1154,7 @@ describe("ProviderCommandReactor", () => {
attachments: [],
},
modelSelection: {
instanceId: ProviderInstanceId.make("claudeAgent"),
provider: "claudeAgent",
model: "claude-opus-4-6",
},
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
@@ -1431,72 +1190,6 @@ describe("ProviderCommandReactor", () => {
});
});
it("rejects cross-driver provider changes after the existing thread session has stopped", async () => {
const harness = await createHarness();
const now = new Date().toISOString();
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.session.set",
commandId: CommandId.make("cmd-session-set-stopped-provider-switch"),
threadId: ThreadId.make("thread-1"),
session: {
threadId: ThreadId.make("thread-1"),
status: "stopped",
providerName: "codex",
providerInstanceId: ProviderInstanceId.make("codex"),
runtimeMode: "approval-required",
activeTurnId: null,
lastError: null,
updatedAt: now,
},
createdAt: now,
}),
);
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.turn.start",
commandId: CommandId.make("cmd-turn-start-stopped-provider-switch"),
threadId: ThreadId.make("thread-1"),
message: {
messageId: asMessageId("user-message-stopped-provider-switch"),
role: "user",
text: "continue with claude",
attachments: [],
},
modelSelection: {
instanceId: ProviderInstanceId.make("claudeAgent"),
model: "claude-opus-4-6",
},
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "approval-required",
createdAt: now,
}),
);
await waitFor(async () => {
const readModel = await Effect.runPromise(harness.engine.getReadModel());
const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
return (
thread?.activities.some((activity) => activity.kind === "provider.turn.start.failed") ??
false
);
});
expect(harness.startSession.mock.calls.length).toBe(0);
expect(harness.sendTurn.mock.calls.length).toBe(0);
const readModel = await Effect.runPromise(harness.engine.getReadModel());
const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
expect(
thread?.activities.find((activity) => activity.kind === "provider.turn.start.failed"),
).toMatchObject({
payload: {
detail: expect.stringContaining("cannot switch to 'claudeAgent'"),
},
});
});
it("reacts to thread.turn.interrupt-requested by calling provider interrupt", async () => {
const harness = await createHarness();
const now = new Date().toISOString();
@@ -1580,7 +1273,7 @@ describe("ProviderCommandReactor", () => {
expect(harness.startSession.mock.calls[0]?.[1]).toMatchObject({
threadId: ThreadId.make("thread-1"),
modelSelection: {
instanceId: ProviderInstanceId.make("codex"),
provider: "codex",
model: "gpt-5-codex",
},
runtimeMode: "approval-required",
@@ -1590,77 +1283,6 @@ describe("ProviderCommandReactor", () => {
});
});
it("rejects active runtime sessions that are missing provider instance ids", async () => {
const harness = await createHarness();
const now = new Date().toISOString();
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.session.set",
commandId: CommandId.make("cmd-session-set-missing-instance"),
threadId: ThreadId.make("thread-1"),
session: {
threadId: ThreadId.make("thread-1"),
status: "ready",
providerName: "codex",
runtimeMode: "approval-required",
activeTurnId: null,
lastError: null,
updatedAt: now,
},
createdAt: now,
}),
);
harness.runtimeSessions.push({
provider: ProviderDriverKind.make("codex"),
status: "ready",
runtimeMode: "approval-required",
threadId: ThreadId.make("thread-1"),
cwd: "/tmp/provider-project",
resumeCursor: { opaque: "resume-without-instance" },
createdAt: now,
updatedAt: now,
});
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.turn.start",
commandId: CommandId.make("cmd-turn-start-missing-instance"),
threadId: ThreadId.make("thread-1"),
message: {
messageId: asMessageId("user-message-missing-instance"),
role: "user",
text: "resume codex",
attachments: [],
},
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "approval-required",
createdAt: now,
}),
);
await waitFor(async () => {
const readModel = await Effect.runPromise(harness.engine.getReadModel());
const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
return (
thread?.activities.some((activity) => activity.kind === "provider.turn.start.failed") ??
false
);
});
expect(harness.startSession.mock.calls.length).toBe(0);
expect(harness.sendTurn.mock.calls.length).toBe(0);
const readModel = await Effect.runPromise(harness.engine.getReadModel());
const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
expect(
thread?.activities.find((activity) => activity.kind === "provider.turn.start.failed"),
).toMatchObject({
payload: {
detail: expect.stringContaining("without a provider instance id"),
},
});
});
it("reacts to thread.approval.respond by forwarding provider approval response", async () => {
const harness = await createHarness();
const now = new Date().toISOString();
@@ -1753,7 +1375,7 @@ describe("ProviderCommandReactor", () => {
harness.respondToRequest.mockImplementation(() =>
Effect.fail(
new ProviderAdapterRequestError({
provider: ProviderDriverKind.make("codex"),
provider: "codex",
method: "session/request_permission",
detail: "Unknown pending permission request: approval-request-1",
}),
@@ -1848,7 +1470,7 @@ describe("ProviderCommandReactor", () => {
harness.respondToUserInput.mockImplementation(() =>
Effect.fail(
new ProviderAdapterRequestError({
provider: ProviderDriverKind.make("claudeAgent"),
provider: "claudeAgent",
method: "item/tool/respondToUserInput",
detail: "Unknown pending user-input request: user-input-request-1",
}),
@@ -1964,7 +1586,6 @@ describe("ProviderCommandReactor", () => {
threadId: ThreadId.make("thread-1"),
status: "ready",
providerName: "codex",
providerInstanceId: ProviderInstanceId.make("codex_work"),
runtimeMode: "approval-required",
activeTurnId: null,
lastError: null,
@@ -1989,7 +1610,6 @@ describe("ProviderCommandReactor", () => {
expect(thread?.session).not.toBeNull();
expect(thread?.session?.status).toBe("stopped");
expect(thread?.session?.threadId).toBe("thread-1");
expect(thread?.session?.providerInstanceId).toBe(ProviderInstanceId.make("codex_work"));
expect(thread?.session?.activeTurnId).toBeNull();
});
});
@@ -4,7 +4,7 @@ import {
EventId,
type ModelSelection,
type OrchestrationEvent,
ProviderDriverKind,
ProviderKind,
type OrchestrationSession,
ThreadId,
type ProviderSession,
@@ -16,10 +16,12 @@ 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 "../../textGeneration/TextGeneration.ts";
import { TextGeneration } from "../../git/Services/TextGeneration.ts";
import { ProviderService } from "../../provider/Services/ProviderService.ts";
import { OrchestrationEngineService } from "../Services/OrchestrationEngine.ts";
import {
@@ -27,8 +29,6 @@ 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,21 +77,6 @@ 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) {
@@ -168,8 +153,8 @@ function buildGeneratedWorktreeBranchName(raw: string): string {
const make = Effect.gen(function* () {
const orchestrationEngine = yield* OrchestrationEngineService;
const providerService = yield* ProviderService;
const gitWorkflow = yield* GitWorkflowService;
const vcsStatusBroadcaster = yield* VcsStatusBroadcaster;
const git = yield* GitCore;
const gitStatusBroadcaster = yield* GitStatusBroadcaster;
const textGeneration = yield* TextGeneration;
const serverSettingsService = yield* ServerSettingsService;
const handledTurnStartKeys = yield* Cache.make<string, true>({
@@ -286,108 +271,42 @@ 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 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;
const threadProvider: ProviderKind = currentProvider ?? thread.modelSelection.provider;
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
requestedModelSelection.provider !== threadProvider
) {
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.`,
});
}
return yield* new ProviderAdapterRequestError({
provider: threadProvider,
method: "thread.turn.start",
detail: `Thread '${threadId}' is bound to provider '${threadProvider}' and cannot switch to '${requestedModelSelection.provider}'.`,
});
}
const preferredProvider: ProviderKind = threadProvider;
const desiredModelSelection = requestedModelSelection ?? thread.modelSelection;
const effectiveCwd = resolveThreadWorkspaceCwd({
thread,
projects: readModel.projects,
});
const resolveActiveSession = (threadId: ThreadId) =>
providerService
.listSessions()
.pipe(Effect.map((sessions) => sessions.find((session) => session.threadId === threadId)));
const startProviderSession = (input?: {
readonly resumeCursor?: unknown;
readonly provider?: ProviderDriverKind;
readonly provider?: ProviderKind;
}) =>
providerService.startSession(threadId, {
threadId,
...(preferredProvider ? { provider: preferredProvider } : {}),
providerInstanceId: desiredInstanceId,
...(effectiveCwd ? { cwd: effectiveCwd } : {}),
modelSelection: desiredModelSelection,
...(input?.resumeCursor !== undefined ? { resumeCursor: input.resumeCursor } : {}),
@@ -395,55 +314,42 @@ const make = Effect.gen(function* () {
});
const bindSessionToThread = (session: ProviderSession) =>
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({
setThreadSession({
threadId,
session: {
threadId,
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,
});
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,
});
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 cwdChanged = effectiveCwd !== activeSession?.cwd;
const sessionModelSwitch = (yield* providerService.getCapabilities(desiredInstanceId))
.sessionModelSwitch;
const sessionModelSwitch =
currentProvider === undefined
? "in-session"
: (yield* providerService.getCapabilities(currentProvider)).sessionModelSwitch;
const modelChanged =
requestedModelSelection !== undefined &&
requestedModelSelection.model !== activeSession?.model;
const instanceChanged =
requestedModelSelection !== undefined &&
activeSession?.providerInstanceId !== requestedModelSelection.instanceId;
const shouldRestartForModelChange = modelChanged && sessionModelSwitch === "unsupported";
const previousModelSelection = threadModelSelections.get(threadId);
const shouldRestartForModelSelectionChange =
preferredProvider === "claudeAgent" &&
currentProvider === "claudeAgent" &&
requestedModelSelection !== undefined &&
!Equal.equals(previousModelSelection, requestedModelSelection);
if (
!runtimeModeChanged &&
!cwdChanged &&
!instanceChanged &&
!shouldRestartForModelChange &&
!shouldRestartForModelSelectionChange
) {
@@ -456,18 +362,12 @@ const make = Effect.gen(function* () {
yield* Effect.logInfo("provider command reactor restarting provider session", {
threadId,
existingSessionThreadId,
currentProvider: activeSession?.provider,
currentInstanceId,
desiredInstanceId,
desiredProvider: desiredModelSelection.instanceId,
currentProvider,
desiredProvider: desiredModelSelection.provider,
currentRuntimeMode: thread.session?.runtimeMode,
desiredRuntimeMode: thread.runtimeMode,
runtimeModeChanged,
previousCwd: activeSession?.cwd,
desiredCwd: effectiveCwd,
cwdChanged,
modelChanged,
instanceChanged,
shouldRestartForModelChange,
shouldRestartForModelSelectionChange,
hasResumeCursor: resumeCursor !== undefined,
@@ -481,7 +381,6 @@ const make = Effect.gen(function* () {
restartedSessionThreadId: restartedSession.threadId,
provider: restartedSession.provider,
runtimeMode: restartedSession.runtimeMode,
cwd: restartedSession.cwd,
});
yield* bindSessionToThread(restartedSession);
return restartedSession.threadId;
@@ -524,14 +423,7 @@ const make = Effect.gen(function* () {
const sessionModelSwitch =
activeSession === undefined
? "in-session"
: 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;
: (yield* providerService.getCapabilities(activeSession.provider)).sessionModelSwitch;
const requestedModelSelection =
input.modelSelection ?? threadModelSelections.get(input.threadId) ?? thread.modelSelection;
const modelForTurn =
@@ -587,7 +479,7 @@ const make = Effect.gen(function* () {
const targetBranch = buildGeneratedWorktreeBranchName(generated.branch);
if (targetBranch === oldBranch) return;
const renamed = yield* gitWorkflow.renameBranch({ cwd, oldBranch, newBranch: targetBranch });
const renamed = yield* git.renameBranch({ cwd, oldBranch, newBranch: targetBranch });
yield* orchestrationEngine.dispatch({
type: "thread.meta.update",
commandId: serverCommandId("worktree-branch-rename"),
@@ -595,7 +487,7 @@ const make = Effect.gen(function* () {
branch: renamed.branch,
worktreePath: cwd,
});
yield* vcsStatusBroadcaster.refreshStatus(cwd).pipe(Effect.ignoreCause({ log: true }));
yield* gitStatusBroadcaster.refreshStatus(cwd).pipe(Effect.ignoreCause({ log: true }));
}).pipe(
Effect.catchCause((cause) =>
Effect.logWarning("provider command reactor failed to generate or rename worktree branch", {
@@ -902,9 +794,6 @@ const make = Effect.gen(function* () {
threadId: thread.id,
status: "stopped",
providerName: thread.session?.providerName ?? null,
...(thread.session?.providerInstanceId !== undefined
? { providerInstanceId: thread.session.providerInstanceId }
: {}),
runtimeMode: thread.session?.runtimeMode ?? DEFAULT_RUNTIME_MODE,
activeTurnId: null,
lastError: thread.session?.lastError ?? null,
@@ -2,12 +2,10 @@ import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import {
import type {
OrchestrationReadModel,
ProviderDriverKind,
ProviderRuntimeEvent,
ProviderSession,
ProviderInstanceId,
} from "@t3tools/contracts";
import {
ApprovalRequestId,
@@ -100,19 +98,6 @@ function createProviderServiceHarness() {
stopSession: () => unsupported(),
listSessions: () => Effect.succeed([...runtimeSessions]),
getCapabilities: () => Effect.succeed({ sessionModelSwitch: "in-session" }),
getInstanceInfo: (instanceId) => {
const driverKind = ProviderDriverKind.make(String(instanceId));
return Effect.succeed({
instanceId,
driverKind,
displayName: undefined,
enabled: true,
continuationIdentity: {
driverKind,
continuationKey: `${driverKind}:instance:${instanceId}`,
},
});
},
rollbackConversation: () => unsupported(),
get streamEvents() {
return Stream.fromPubSub(runtimeEventPubSub);
@@ -247,7 +232,7 @@ describe("ProviderRuntimeIngestion", () => {
title: "Provider Project",
workspaceRoot,
defaultModelSelection: {
instanceId: ProviderInstanceId.make("codex"),
provider: "codex",
model: "gpt-5-codex",
},
createdAt,
@@ -261,7 +246,7 @@ describe("ProviderRuntimeIngestion", () => {
projectId: asProjectId("project-1"),
title: "Thread",
modelSelection: {
instanceId: ProviderInstanceId.make("codex"),
provider: "codex",
model: "gpt-5-codex",
},
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
@@ -289,7 +274,7 @@ describe("ProviderRuntimeIngestion", () => {
}),
);
provider.setSession({
provider: ProviderDriverKind.make("codex"),
provider: "codex",
status: "ready",
runtimeMode: "approval-required",
threadId: ThreadId.make("thread-1"),
@@ -312,7 +297,7 @@ describe("ProviderRuntimeIngestion", () => {
harness.emit({
type: "turn.started",
eventId: asEventId("evt-turn-started"),
provider: ProviderDriverKind.make("codex"),
provider: "codex",
threadId: asThreadId("thread-1"),
createdAt: now,
turnId: asTurnId("turn-1"),
@@ -326,7 +311,7 @@ describe("ProviderRuntimeIngestion", () => {
harness.emit({
type: "turn.completed",
eventId: asEventId("evt-turn-completed"),
provider: ProviderDriverKind.make("codex"),
provider: "codex",
threadId: asThreadId("thread-1"),
createdAt: new Date().toISOString(),
turnId: asTurnId("turn-1"),
@@ -354,7 +339,7 @@ describe("ProviderRuntimeIngestion", () => {
harness.emit({
type: "session.state.changed",
eventId: asEventId("evt-session-state-waiting"),
provider: ProviderDriverKind.make("codex"),
provider: "codex",
threadId: asThreadId("thread-1"),
createdAt: waitingAt,
payload: {
@@ -373,7 +358,7 @@ describe("ProviderRuntimeIngestion", () => {
harness.emit({
type: "session.state.changed",
eventId: asEventId("evt-session-state-error"),
provider: ProviderDriverKind.make("codex"),
provider: "codex",
threadId: asThreadId("thread-1"),
createdAt: new Date().toISOString(),
payload: {
@@ -395,7 +380,7 @@ describe("ProviderRuntimeIngestion", () => {
harness.emit({
type: "session.state.changed",
eventId: asEventId("evt-session-state-stopped"),
provider: ProviderDriverKind.make("codex"),
provider: "codex",
threadId: asThreadId("thread-1"),
createdAt: new Date().toISOString(),
payload: {
@@ -416,7 +401,7 @@ describe("ProviderRuntimeIngestion", () => {
harness.emit({
type: "session.state.changed",
eventId: asEventId("evt-session-state-ready"),
provider: ProviderDriverKind.make("codex"),
provider: "codex",
threadId: asThreadId("thread-1"),
createdAt: new Date().toISOString(),
payload: {
@@ -442,7 +427,7 @@ describe("ProviderRuntimeIngestion", () => {
harness.emit({
type: "turn.started",
eventId: asEventId("evt-turn-started-midturn-lifecycle"),
provider: ProviderDriverKind.make("codex"),
provider: "codex",
createdAt: now,
threadId: asThreadId("thread-1"),
turnId: asTurnId("turn-midturn-lifecycle"),
@@ -458,14 +443,14 @@ describe("ProviderRuntimeIngestion", () => {
harness.emit({
type: "thread.started",
eventId: asEventId("evt-thread-started-midturn-lifecycle"),
provider: ProviderDriverKind.make("codex"),
provider: "codex",
createdAt: new Date().toISOString(),
threadId: asThreadId("thread-1"),
});
harness.emit({
type: "session.started",
eventId: asEventId("evt-session-started-midturn-lifecycle"),
provider: ProviderDriverKind.make("codex"),
provider: "codex",
createdAt: new Date().toISOString(),
threadId: asThreadId("thread-1"),
});
@@ -479,7 +464,7 @@ describe("ProviderRuntimeIngestion", () => {
harness.emit({
type: "turn.completed",
eventId: asEventId("evt-turn-completed-midturn-lifecycle"),
provider: ProviderDriverKind.make("codex"),
provider: "codex",
createdAt: new Date().toISOString(),
threadId: asThreadId("thread-1"),
turnId: asTurnId("turn-midturn-lifecycle"),
@@ -517,7 +502,7 @@ describe("ProviderRuntimeIngestion", () => {
harness.emit({
type: "turn.started",
eventId: asEventId("evt-turn-started-claude-placeholder"),
provider: ProviderDriverKind.make("claudeAgent"),
provider: "claudeAgent",
createdAt: new Date().toISOString(),
threadId: asThreadId("thread-1"),
turnId: asTurnId("turn-claude-placeholder"),
@@ -533,7 +518,7 @@ describe("ProviderRuntimeIngestion", () => {
harness.emit({
type: "turn.completed",
eventId: asEventId("evt-turn-completed-claude-placeholder"),
provider: ProviderDriverKind.make("claudeAgent"),
provider: "claudeAgent",
createdAt: new Date().toISOString(),
threadId: asThreadId("thread-1"),
turnId: asTurnId("turn-claude-placeholder"),
@@ -553,7 +538,7 @@ describe("ProviderRuntimeIngestion", () => {
harness.emit({
type: "turn.started",
eventId: asEventId("evt-turn-started-primary"),
provider: ProviderDriverKind.make("codex"),
provider: "codex",
createdAt: now,
threadId: asThreadId("thread-1"),
turnId: asTurnId("turn-primary"),
@@ -568,7 +553,7 @@ describe("ProviderRuntimeIngestion", () => {
harness.emit({
type: "turn.completed",
eventId: asEventId("evt-turn-completed-aux"),
provider: ProviderDriverKind.make("codex"),
provider: "codex",
createdAt: new Date().toISOString(),
threadId: asThreadId("thread-1"),
turnId: asTurnId("turn-aux"),
@@ -584,7 +569,7 @@ describe("ProviderRuntimeIngestion", () => {
harness.emit({
type: "turn.completed",
eventId: asEventId("evt-turn-completed-primary"),
provider: ProviderDriverKind.make("codex"),
provider: "codex",
createdAt: new Date().toISOString(),
threadId: asThreadId("thread-1"),
turnId: asTurnId("turn-primary"),
@@ -604,7 +589,7 @@ describe("ProviderRuntimeIngestion", () => {
harness.emit({
type: "turn.started",
eventId: asEventId("evt-turn-started-guarded"),
provider: ProviderDriverKind.make("codex"),
provider: "codex",
createdAt: now,
threadId: asThreadId("thread-1"),
turnId: asTurnId("turn-guarded-main"),
@@ -620,7 +605,7 @@ describe("ProviderRuntimeIngestion", () => {
harness.emit({
type: "turn.completed",
eventId: asEventId("evt-turn-completed-guarded-other"),
provider: ProviderDriverKind.make("codex"),
provider: "codex",
createdAt: new Date().toISOString(),
threadId: asThreadId("thread-1"),
turnId: asTurnId("turn-guarded-other"),
@@ -636,7 +621,7 @@ describe("ProviderRuntimeIngestion", () => {
harness.emit({
type: "turn.completed",
eventId: asEventId("evt-turn-completed-guarded-main"),
provider: ProviderDriverKind.make("codex"),
provider: "codex",
createdAt: new Date().toISOString(),
threadId: asThreadId("thread-1"),
turnId: asTurnId("turn-guarded-main"),
@@ -656,7 +641,7 @@ describe("ProviderRuntimeIngestion", () => {
harness.emit({
type: "content.delta",
eventId: asEventId("evt-message-delta-1"),
provider: ProviderDriverKind.make("codex"),
provider: "codex",
createdAt: now,
threadId: asThreadId("thread-1"),
turnId: asTurnId("turn-2"),
@@ -669,7 +654,7 @@ describe("ProviderRuntimeIngestion", () => {
harness.emit({
type: "content.delta",
eventId: asEventId("evt-message-delta-2"),
provider: ProviderDriverKind.make("codex"),
provider: "codex",
createdAt: now,
threadId: asThreadId("thread-1"),
turnId: asTurnId("turn-2"),
@@ -682,7 +667,7 @@ describe("ProviderRuntimeIngestion", () => {
harness.emit({
type: "item.completed",
eventId: asEventId("evt-message-completed"),
provider: ProviderDriverKind.make("codex"),
provider: "codex",
createdAt: now,
threadId: asThreadId("thread-1"),
turnId: asTurnId("turn-2"),
@@ -713,7 +698,7 @@ describe("ProviderRuntimeIngestion", () => {
harness.emit({
type: "item.completed",
eventId: asEventId("evt-assistant-item-completed-no-delta"),
provider: ProviderDriverKind.make("codex"),
provider: "codex",
createdAt: now,
threadId: asThreadId("thread-1"),
turnId: asTurnId("turn-no-delta"),
@@ -745,7 +730,7 @@ describe("ProviderRuntimeIngestion", () => {
harness.emit({
type: "item.completed",
eventId: asEventId("evt-tool-completed-with-data"),
provider: ProviderDriverKind.make("cursor"),
provider: "cursor",
createdAt: now,
threadId: asThreadId("thread-1"),
turnId: asTurnId("turn-tool-completed"),
@@ -801,7 +786,7 @@ describe("ProviderRuntimeIngestion", () => {
harness.emit({
type: "item.completed",
eventId: asEventId("evt-command-completed"),
provider: ProviderDriverKind.make("cursor"),
provider: "cursor",
createdAt: now,
threadId: asThreadId("thread-1"),
turnId: asTurnId("turn-command-completed"),
@@ -843,7 +828,7 @@ describe("ProviderRuntimeIngestion", () => {
harness.emit({
type: "item.completed",
eventId: asEventId("evt-read-path-completed"),
provider: ProviderDriverKind.make("cursor"),
provider: "cursor",
createdAt: now,
threadId: asThreadId("thread-1"),
turnId: asTurnId("turn-read-path"),
@@ -885,7 +870,7 @@ describe("ProviderRuntimeIngestion", () => {
harness.emit({
type: "turn.proposed.completed",
eventId: asEventId("evt-plan-item-completed"),
provider: ProviderDriverKind.make("codex"),
provider: "codex",
createdAt: now,
threadId: asThreadId("thread-1"),
turnId: asTurnId("turn-plan-final"),
@@ -924,7 +909,7 @@ describe("ProviderRuntimeIngestion", () => {
projectId: asProjectId("project-1"),
title: "Plan Source",
modelSelection: {
instanceId: ProviderInstanceId.make("codex"),
provider: "codex",
model: "gpt-5-codex",
},
interactionMode: "plan",
@@ -959,7 +944,7 @@ describe("ProviderRuntimeIngestion", () => {
projectId: asProjectId("project-1"),
title: "Plan Target",
modelSelection: {
instanceId: ProviderInstanceId.make("codex"),
provider: "codex",
model: "gpt-5-codex",
},
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
@@ -987,7 +972,7 @@ describe("ProviderRuntimeIngestion", () => {
}),
);
harness.setProviderSession({
provider: ProviderDriverKind.make("codex"),
provider: "codex",
status: "ready",
runtimeMode: "approval-required",
threadId: targetThreadId,
@@ -999,7 +984,7 @@ describe("ProviderRuntimeIngestion", () => {
harness.emit({
type: "turn.proposed.completed",
eventId: asEventId("evt-plan-source-completed"),
provider: ProviderDriverKind.make("codex"),
provider: "codex",
createdAt,
threadId: sourceThreadId,
turnId: sourceTurnId,
@@ -1069,7 +1054,7 @@ describe("ProviderRuntimeIngestion", () => {
harness.emit({
type: "turn.started",
eventId: asEventId("evt-plan-target-started"),
provider: ProviderDriverKind.make("codex"),
provider: "codex",
createdAt: new Date().toISOString(),
threadId: targetThreadId,
turnId: targetTurnId,
@@ -1111,7 +1096,7 @@ describe("ProviderRuntimeIngestion", () => {
projectId: asProjectId("project-1"),
title: "Plan Source",
modelSelection: {
instanceId: ProviderInstanceId.make("codex"),
provider: "codex",
model: "gpt-5-codex",
},
interactionMode: "plan",
@@ -1139,7 +1124,7 @@ describe("ProviderRuntimeIngestion", () => {
}),
);
harness.setProviderSession({
provider: ProviderDriverKind.make("codex"),
provider: "codex",
status: "running",
runtimeMode: "approval-required",
threadId: targetThreadId,
@@ -1151,7 +1136,7 @@ describe("ProviderRuntimeIngestion", () => {
harness.emit({
type: "turn.started",
eventId: asEventId("evt-turn-started-already-running"),
provider: ProviderDriverKind.make("codex"),
provider: "codex",
createdAt,
threadId: targetThreadId,
turnId: activeTurnId,
@@ -1168,7 +1153,7 @@ describe("ProviderRuntimeIngestion", () => {
harness.emit({
type: "turn.proposed.completed",
eventId: asEventId("evt-plan-source-completed-guarded"),
provider: ProviderDriverKind.make("codex"),
provider: "codex",
createdAt,
threadId: sourceThreadId,
turnId: sourceTurnId,
@@ -1221,7 +1206,7 @@ describe("ProviderRuntimeIngestion", () => {
harness.emit({
type: "turn.started",
eventId: asEventId("evt-turn-started-stale-plan-implementation"),
provider: ProviderDriverKind.make("codex"),
provider: "codex",
createdAt: new Date().toISOString(),
threadId: targetThreadId,
turnId: staleTurnId,
@@ -1264,7 +1249,7 @@ describe("ProviderRuntimeIngestion", () => {
projectId: asProjectId("project-1"),
title: "Plan Source",
modelSelection: {
instanceId: ProviderInstanceId.make("codex"),
provider: "codex",
model: "gpt-5-codex",
},
interactionMode: "plan",
@@ -1299,7 +1284,7 @@ describe("ProviderRuntimeIngestion", () => {
projectId: asProjectId("project-1"),
title: "Plan Target",
modelSelection: {
instanceId: ProviderInstanceId.make("codex"),
provider: "codex",
model: "gpt-5-codex",
},
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
@@ -1330,7 +1315,7 @@ describe("ProviderRuntimeIngestion", () => {
harness.emit({
type: "turn.proposed.completed",
eventId: asEventId("evt-plan-source-completed-unrelated"),
provider: ProviderDriverKind.make("codex"),
provider: "codex",
createdAt,
threadId: sourceThreadId,
turnId: sourceTurnId,
@@ -1381,7 +1366,7 @@ describe("ProviderRuntimeIngestion", () => {
);
harness.setProviderSession({
provider: ProviderDriverKind.make("codex"),
provider: "codex",
status: "running",
runtimeMode: "approval-required",
threadId: targetThreadId,
@@ -1393,7 +1378,7 @@ describe("ProviderRuntimeIngestion", () => {
harness.emit({
type: "turn.started",
eventId: asEventId("evt-turn-started-unrelated-plan-implementation"),
provider: ProviderDriverKind.make("codex"),
provider: "codex",
createdAt: new Date().toISOString(),
threadId: targetThreadId,
turnId: replayedTurnId,
@@ -1420,7 +1405,7 @@ describe("ProviderRuntimeIngestion", () => {
harness.emit({
type: "turn.started",
eventId: asEventId("evt-turn-started-plan-buffer"),
provider: ProviderDriverKind.make("codex"),
provider: "codex",
createdAt: now,
threadId: asThreadId("thread-1"),
turnId: asTurnId("turn-plan-buffer"),
@@ -1435,7 +1420,7 @@ describe("ProviderRuntimeIngestion", () => {
harness.emit({
type: "turn.proposed.delta",
eventId: asEventId("evt-plan-delta-1"),
provider: ProviderDriverKind.make("codex"),
provider: "codex",
createdAt: now,
threadId: asThreadId("thread-1"),
turnId: asTurnId("turn-plan-buffer"),
@@ -1446,7 +1431,7 @@ describe("ProviderRuntimeIngestion", () => {
harness.emit({
type: "turn.proposed.delta",
eventId: asEventId("evt-plan-delta-2"),
provider: ProviderDriverKind.make("codex"),
provider: "codex",
createdAt: now,
threadId: asThreadId("thread-1"),
turnId: asTurnId("turn-plan-buffer"),
@@ -1457,7 +1442,7 @@ describe("ProviderRuntimeIngestion", () => {
harness.emit({
type: "turn.completed",
eventId: asEventId("evt-turn-completed-plan-buffer"),
provider: ProviderDriverKind.make("codex"),
provider: "codex",
createdAt: now,
threadId: asThreadId("thread-1"),
turnId: asTurnId("turn-plan-buffer"),
@@ -1486,7 +1471,7 @@ describe("ProviderRuntimeIngestion", () => {
harness.emit({
type: "turn.started",
eventId: asEventId("evt-turn-started-buffered"),
provider: ProviderDriverKind.make("codex"),
provider: "codex",
createdAt: now,
threadId: asThreadId("thread-1"),
turnId: asTurnId("turn-buffered"),
@@ -1500,7 +1485,7 @@ describe("ProviderRuntimeIngestion", () => {
harness.emit({
type: "content.delta",
eventId: asEventId("evt-message-delta-buffered"),
provider: ProviderDriverKind.make("codex"),
provider: "codex",
createdAt: now,
threadId: asThreadId("thread-1"),
turnId: asTurnId("turn-buffered"),
@@ -1523,7 +1508,7 @@ describe("ProviderRuntimeIngestion", () => {
harness.emit({
type: "item.completed",
eventId: asEventId("evt-message-completed-buffered"),
provider: ProviderDriverKind.make("codex"),
provider: "codex",
createdAt: now,
threadId: asThreadId("thread-1"),
turnId: asTurnId("turn-buffered"),
@@ -1554,7 +1539,7 @@ describe("ProviderRuntimeIngestion", () => {
harness.emit({
type: "turn.started",
eventId: asEventId("evt-turn-started-buffered-request-flush"),
provider: ProviderDriverKind.make("codex"),
provider: "codex",
createdAt: now,
threadId: asThreadId("thread-1"),
turnId: asTurnId("turn-buffered-request-flush"),
@@ -1569,7 +1554,7 @@ describe("ProviderRuntimeIngestion", () => {
harness.emit({
type: "content.delta",
eventId: asEventId("evt-message-delta-buffered-request-flush"),
provider: ProviderDriverKind.make("codex"),
provider: "codex",
createdAt: now,
threadId: asThreadId("thread-1"),
turnId: asTurnId("turn-buffered-request-flush"),
@@ -1582,7 +1567,7 @@ describe("ProviderRuntimeIngestion", () => {
harness.emit({
type: "request.opened",
eventId: asEventId("evt-request-opened-buffered-request-flush"),
provider: ProviderDriverKind.make("codex"),
provider: "codex",
createdAt: now,
threadId: asThreadId("thread-1"),
turnId: asTurnId("turn-buffered-request-flush"),
@@ -1614,7 +1599,7 @@ describe("ProviderRuntimeIngestion", () => {
harness.emit({
type: "turn.started",
eventId: asEventId("evt-turn-started-buffered-user-input-flush"),
provider: ProviderDriverKind.make("codex"),
provider: "codex",
createdAt: now,
threadId: asThreadId("thread-1"),
turnId: asTurnId("turn-buffered-user-input-flush"),
@@ -1629,7 +1614,7 @@ describe("ProviderRuntimeIngestion", () => {
harness.emit({
type: "content.delta",
eventId: asEventId("evt-message-delta-buffered-user-input-flush"),
provider: ProviderDriverKind.make("codex"),
provider: "codex",
createdAt: now,
threadId: asThreadId("thread-1"),
turnId: asTurnId("turn-buffered-user-input-flush"),
@@ -1642,7 +1627,7 @@ describe("ProviderRuntimeIngestion", () => {
harness.emit({
type: "user-input.requested",
eventId: asEventId("evt-user-input-requested-buffered-user-input-flush"),
provider: ProviderDriverKind.make("codex"),
provider: "codex",
createdAt: now,
threadId: asThreadId("thread-1"),
turnId: asTurnId("turn-buffered-user-input-flush"),
@@ -1682,7 +1667,7 @@ describe("ProviderRuntimeIngestion", () => {
harness.emit({
type: "turn.started",
eventId: asEventId("evt-turn-started-buffered-whitespace-request"),
provider: ProviderDriverKind.make("codex"),
provider: "codex",
createdAt: startedAt,
threadId: asThreadId("thread-1"),
turnId: asTurnId("turn-buffered-whitespace-request"),
@@ -1697,7 +1682,7 @@ describe("ProviderRuntimeIngestion", () => {
harness.emit({
type: "content.delta",
eventId: asEventId("evt-message-delta-buffered-whitespace-request"),
provider: ProviderDriverKind.make("codex"),
provider: "codex",
createdAt: startedAt,
threadId: asThreadId("thread-1"),
turnId: asTurnId("turn-buffered-whitespace-request"),
@@ -1710,7 +1695,7 @@ describe("ProviderRuntimeIngestion", () => {
harness.emit({
type: "request.opened",
eventId: asEventId("evt-request-opened-buffered-whitespace-request"),
provider: ProviderDriverKind.make("codex"),
provider: "codex",
createdAt: pausedAt,
threadId: asThreadId("thread-1"),
turnId: asTurnId("turn-buffered-whitespace-request"),
@@ -1744,7 +1729,7 @@ describe("ProviderRuntimeIngestion", () => {
harness.emit({
type: "turn.started",
eventId: asEventId("evt-turn-started-buffered-request-append"),
provider: ProviderDriverKind.make("codex"),
provider: "codex",
createdAt: startedAt,
threadId: asThreadId("thread-1"),
turnId: asTurnId("turn-buffered-request-append"),
@@ -1759,7 +1744,7 @@ describe("ProviderRuntimeIngestion", () => {
harness.emit({
type: "content.delta",
eventId: asEventId("evt-message-delta-buffered-request-append-initial"),
provider: ProviderDriverKind.make("codex"),
provider: "codex",
createdAt: startedAt,
threadId: asThreadId("thread-1"),
turnId: asTurnId("turn-buffered-request-append"),
@@ -1772,7 +1757,7 @@ describe("ProviderRuntimeIngestion", () => {
harness.emit({
type: "request.opened",
eventId: asEventId("evt-request-opened-buffered-request-append"),
provider: ProviderDriverKind.make("codex"),
provider: "codex",
createdAt: pausedAt,
threadId: asThreadId("thread-1"),
turnId: asTurnId("turn-buffered-request-append"),
@@ -1795,7 +1780,7 @@ describe("ProviderRuntimeIngestion", () => {
harness.emit({
type: "content.delta",
eventId: asEventId("evt-message-delta-buffered-request-append-followup"),
provider: ProviderDriverKind.make("codex"),
provider: "codex",
createdAt: resumedAt,
threadId: asThreadId("thread-1"),
turnId: asTurnId("turn-buffered-request-append"),
@@ -1808,7 +1793,7 @@ describe("ProviderRuntimeIngestion", () => {
harness.emit({
type: "item.completed",
eventId: asEventId("evt-message-completed-buffered-request-append"),
provider: ProviderDriverKind.make("codex"),
provider: "codex",
createdAt: completedAt,
threadId: asThreadId("thread-1"),
turnId: asTurnId("turn-buffered-request-append"),
@@ -1876,7 +1861,7 @@ describe("ProviderRuntimeIngestion", () => {
harness.emit({
type: "turn.started",
eventId: asEventId("evt-turn-started-streaming-request-segment"),
provider: ProviderDriverKind.make("codex"),
provider: "codex",
createdAt: startedAt,
threadId: asThreadId("thread-1"),
turnId: asTurnId("turn-streaming-request-segment"),
@@ -1891,7 +1876,7 @@ describe("ProviderRuntimeIngestion", () => {
harness.emit({
type: "content.delta",
eventId: asEventId("evt-message-delta-streaming-request-segment-initial"),
provider: ProviderDriverKind.make("codex"),
provider: "codex",
createdAt: startedAt,
threadId: asThreadId("thread-1"),
turnId: asTurnId("turn-streaming-request-segment"),
@@ -1904,7 +1889,7 @@ describe("ProviderRuntimeIngestion", () => {
harness.emit({
type: "request.opened",
eventId: asEventId("evt-request-opened-streaming-request-segment"),
provider: ProviderDriverKind.make("codex"),
provider: "codex",
createdAt: pausedAt,
threadId: asThreadId("thread-1"),
turnId: asTurnId("turn-streaming-request-segment"),
@@ -1927,7 +1912,7 @@ describe("ProviderRuntimeIngestion", () => {
harness.emit({
type: "content.delta",
eventId: asEventId("evt-message-delta-streaming-request-segment-followup"),
provider: ProviderDriverKind.make("codex"),
provider: "codex",
createdAt: resumedAt,
threadId: asThreadId("thread-1"),
turnId: asTurnId("turn-streaming-request-segment"),
@@ -1940,7 +1925,7 @@ describe("ProviderRuntimeIngestion", () => {
harness.emit({
type: "item.completed",
eventId: asEventId("evt-message-completed-streaming-request-segment"),
provider: ProviderDriverKind.make("codex"),
provider: "codex",
createdAt: completedAt,
threadId: asThreadId("thread-1"),
turnId: asTurnId("turn-streaming-request-segment"),
@@ -1998,7 +1983,7 @@ describe("ProviderRuntimeIngestion", () => {
harness.emit({
type: "turn.started",
eventId: asEventId("evt-turn-started-streaming-mode"),
provider: ProviderDriverKind.make("codex"),
provider: "codex",
createdAt: now,
threadId: asThreadId("thread-1"),
turnId: asTurnId("turn-streaming-mode"),
@@ -2013,7 +1998,7 @@ describe("ProviderRuntimeIngestion", () => {
harness.emit({
type: "content.delta",
eventId: asEventId("evt-message-delta-streaming-mode"),
provider: ProviderDriverKind.make("codex"),
provider: "codex",
createdAt: now,
threadId: asThreadId("thread-1"),
turnId: asTurnId("turn-streaming-mode"),
@@ -2040,7 +2025,7 @@ describe("ProviderRuntimeIngestion", () => {
harness.emit({
type: "item.completed",
eventId: asEventId("evt-message-completed-streaming-mode"),
provider: ProviderDriverKind.make("codex"),
provider: "codex",
createdAt: now,
threadId: asThreadId("thread-1"),
turnId: asTurnId("turn-streaming-mode"),
@@ -2073,7 +2058,7 @@ describe("ProviderRuntimeIngestion", () => {
harness.emit({
type: "turn.started",
eventId: asEventId("evt-turn-started-buffer-spill"),
provider: ProviderDriverKind.make("codex"),
provider: "codex",
createdAt: now,
threadId: asThreadId("thread-1"),
turnId: asTurnId("turn-buffer-spill"),
@@ -2088,7 +2073,7 @@ describe("ProviderRuntimeIngestion", () => {
harness.emit({
type: "content.delta",
eventId: asEventId("evt-message-delta-buffer-spill"),
provider: ProviderDriverKind.make("codex"),
provider: "codex",
createdAt: now,
threadId: asThreadId("thread-1"),
turnId: asTurnId("turn-buffer-spill"),
@@ -2101,7 +2086,7 @@ describe("ProviderRuntimeIngestion", () => {
harness.emit({
type: "item.completed",
eventId: asEventId("evt-message-completed-buffer-spill"),
provider: ProviderDriverKind.make("codex"),
provider: "codex",
createdAt: now,
threadId: asThreadId("thread-1"),
turnId: asTurnId("turn-buffer-spill"),
@@ -2133,7 +2118,7 @@ describe("ProviderRuntimeIngestion", () => {
harness.emit({
type: "turn.started",
eventId: asEventId("evt-turn-started-for-complete-dedup"),
provider: ProviderDriverKind.make("codex"),
provider: "codex",
createdAt: now,
threadId: asThreadId("thread-1"),
turnId: asTurnId("turn-complete-dedup"),
@@ -2149,7 +2134,7 @@ describe("ProviderRuntimeIngestion", () => {
harness.emit({
type: "content.delta",
eventId: asEventId("evt-message-delta-for-complete-dedup"),
provider: ProviderDriverKind.make("codex"),
provider: "codex",
createdAt: now,
threadId: asThreadId("thread-1"),
turnId: asTurnId("turn-complete-dedup"),
@@ -2162,7 +2147,7 @@ describe("ProviderRuntimeIngestion", () => {
harness.emit({
type: "item.completed",
eventId: asEventId("evt-message-completed-for-complete-dedup"),
provider: ProviderDriverKind.make("codex"),
provider: "codex",
createdAt: now,
threadId: asThreadId("thread-1"),
turnId: asTurnId("turn-complete-dedup"),
@@ -2175,7 +2160,7 @@ describe("ProviderRuntimeIngestion", () => {
harness.emit({
type: "turn.completed",
eventId: asEventId("evt-turn-completed-for-complete-dedup"),
provider: ProviderDriverKind.make("codex"),
provider: "codex",
createdAt: now,
threadId: asThreadId("thread-1"),
turnId: asTurnId("turn-complete-dedup"),
@@ -2219,7 +2204,7 @@ describe("ProviderRuntimeIngestion", () => {
harness.emit({
type: "request.opened",
eventId: asEventId("evt-request-opened"),
provider: ProviderDriverKind.make("codex"),
provider: "codex",
createdAt: now,
threadId: asThreadId("thread-1"),
requestId: ApprovalRequestId.make("req-open"),
@@ -2232,7 +2217,7 @@ describe("ProviderRuntimeIngestion", () => {
harness.emit({
type: "request.resolved",
eventId: asEventId("evt-request-resolved"),
provider: ProviderDriverKind.make("codex"),
provider: "codex",
createdAt: now,
threadId: asThreadId("thread-1"),
requestId: ApprovalRequestId.make("req-open"),
@@ -2285,7 +2270,7 @@ describe("ProviderRuntimeIngestion", () => {
harness.emit({
type: "runtime.error",
eventId: asEventId("evt-runtime-error"),
provider: ProviderDriverKind.make("codex"),
provider: "codex",
createdAt: now,
threadId: asThreadId("thread-1"),
turnId: asTurnId("turn-3"),
@@ -2312,7 +2297,7 @@ describe("ProviderRuntimeIngestion", () => {
harness.emit({
type: "runtime.error",
eventId: asEventId("evt-runtime-error-activity"),
provider: ProviderDriverKind.make("codex"),
provider: "codex",
createdAt: now,
threadId: asThreadId("thread-1"),
turnId: asTurnId("turn-runtime-error-activity"),
@@ -2343,7 +2328,7 @@ describe("ProviderRuntimeIngestion", () => {
harness.emit({
type: "turn.started",
eventId: asEventId("evt-warning-turn-started"),
provider: ProviderDriverKind.make("codex"),
provider: "codex",
createdAt: now,
threadId: asThreadId("thread-1"),
turnId: asTurnId("turn-warning"),
@@ -2353,7 +2338,7 @@ describe("ProviderRuntimeIngestion", () => {
harness.emit({
type: "runtime.warning",
eventId: asEventId("evt-warning-runtime"),
provider: ProviderDriverKind.make("codex"),
provider: "codex",
createdAt: now,
threadId: asThreadId("thread-1"),
turnId: asTurnId("turn-warning"),
@@ -2387,7 +2372,7 @@ describe("ProviderRuntimeIngestion", () => {
harness.emit({
type: "session.started",
eventId: asEventId("evt-session-started"),
provider: ProviderDriverKind.make("codex"),
provider: "codex",
createdAt: now,
threadId: asThreadId("thread-1"),
message: "session started",
@@ -2395,14 +2380,14 @@ describe("ProviderRuntimeIngestion", () => {
harness.emit({
type: "thread.started",
eventId: asEventId("evt-thread-started"),
provider: ProviderDriverKind.make("codex"),
provider: "codex",
createdAt: now,
threadId: asThreadId("thread-1"),
});
harness.emit({
type: "item.started",
eventId: asEventId("evt-tool-started"),
provider: ProviderDriverKind.make("codex"),
provider: "codex",
createdAt: now,
threadId: asThreadId("thread-1"),
turnId: asTurnId("turn-9"),
@@ -2439,7 +2424,7 @@ describe("ProviderRuntimeIngestion", () => {
harness.emit({
type: "thread.metadata.updated",
eventId: asEventId("evt-thread-metadata-updated"),
provider: ProviderDriverKind.make("codex"),
provider: "codex",
createdAt: now,
threadId: asThreadId("thread-1"),
payload: {
@@ -2451,7 +2436,7 @@ describe("ProviderRuntimeIngestion", () => {
harness.emit({
type: "turn.plan.updated",
eventId: asEventId("evt-turn-plan-updated"),
provider: ProviderDriverKind.make("codex"),
provider: "codex",
createdAt: now,
threadId: asThreadId("thread-1"),
turnId: asTurnId("turn-p1"),
@@ -2467,7 +2452,7 @@ describe("ProviderRuntimeIngestion", () => {
harness.emit({
type: "item.updated",
eventId: asEventId("evt-item-updated"),
provider: ProviderDriverKind.make("codex"),
provider: "codex",
createdAt: now,
threadId: asThreadId("thread-1"),
turnId: asTurnId("turn-p1"),
@@ -2484,7 +2469,7 @@ describe("ProviderRuntimeIngestion", () => {
harness.emit({
type: "runtime.warning",
eventId: asEventId("evt-runtime-warning"),
provider: ProviderDriverKind.make("codex"),
provider: "codex",
createdAt: now,
threadId: asThreadId("thread-1"),
turnId: asTurnId("turn-p1"),
@@ -2497,7 +2482,7 @@ describe("ProviderRuntimeIngestion", () => {
harness.emit({
type: "turn.diff.updated",
eventId: asEventId("evt-turn-diff-updated"),
provider: ProviderDriverKind.make("codex"),
provider: "codex",
createdAt: now,
threadId: asThreadId("thread-1"),
turnId: asTurnId("turn-p1"),
@@ -2573,7 +2558,7 @@ describe("ProviderRuntimeIngestion", () => {
harness.emit({
type: "thread.token-usage.updated",
eventId: asEventId("evt-thread-token-usage-updated"),
provider: ProviderDriverKind.make("codex"),
provider: "codex",
createdAt: now,
threadId: asThreadId("thread-1"),
payload: {
@@ -2625,7 +2610,7 @@ describe("ProviderRuntimeIngestion", () => {
harness.emit({
type: "thread.token-usage.updated",
eventId: asEventId("evt-thread-token-usage-updated-camel"),
provider: ProviderDriverKind.make("codex"),
provider: "codex",
createdAt: now,
threadId: asThreadId("thread-1"),
payload: {
@@ -2678,7 +2663,7 @@ describe("ProviderRuntimeIngestion", () => {
harness.emit({
type: "thread.token-usage.updated",
eventId: asEventId("evt-thread-token-usage-updated-claude-window"),
provider: ProviderDriverKind.make("claudeAgent"),
provider: "claudeAgent",
createdAt: now,
threadId: asThreadId("thread-1"),
payload: {
@@ -2722,7 +2707,7 @@ describe("ProviderRuntimeIngestion", () => {
harness.emit({
type: "thread.state.changed",
eventId: asEventId("evt-thread-compacted"),
provider: ProviderDriverKind.make("codex"),
provider: "codex",
createdAt: now,
threadId: asThreadId("thread-1"),
turnId: asTurnId("turn-1"),
@@ -2752,7 +2737,7 @@ describe("ProviderRuntimeIngestion", () => {
harness.emit({
type: "task.started",
eventId: asEventId("evt-task-started"),
provider: ProviderDriverKind.make("codex"),
provider: "codex",
createdAt: now,
threadId: asThreadId("thread-1"),
turnId: asTurnId("turn-task-1"),
@@ -2765,7 +2750,7 @@ describe("ProviderRuntimeIngestion", () => {
harness.emit({
type: "task.progress",
eventId: asEventId("evt-task-progress"),
provider: ProviderDriverKind.make("codex"),
provider: "codex",
createdAt: now,
threadId: asThreadId("thread-1"),
turnId: asTurnId("turn-task-1"),
@@ -2779,7 +2764,7 @@ describe("ProviderRuntimeIngestion", () => {
harness.emit({
type: "task.completed",
eventId: asEventId("evt-task-completed"),
provider: ProviderDriverKind.make("codex"),
provider: "codex",
createdAt: now,
threadId: asThreadId("thread-1"),
turnId: asTurnId("turn-task-1"),
@@ -2792,7 +2777,7 @@ describe("ProviderRuntimeIngestion", () => {
harness.emit({
type: "turn.proposed.completed",
eventId: asEventId("evt-task-proposed-plan-completed"),
provider: ProviderDriverKind.make("codex"),
provider: "codex",
createdAt: now,
threadId: asThreadId("thread-1"),
turnId: asTurnId("turn-task-1"),
@@ -2855,7 +2840,7 @@ describe("ProviderRuntimeIngestion", () => {
harness.emit({
type: "user-input.requested",
eventId: asEventId("evt-user-input-requested"),
provider: ProviderDriverKind.make("codex"),
provider: "codex",
createdAt: now,
threadId: asThreadId("thread-1"),
turnId: asTurnId("turn-user-input"),
@@ -2880,7 +2865,7 @@ describe("ProviderRuntimeIngestion", () => {
harness.emit({
type: "user-input.resolved",
eventId: asEventId("evt-user-input-resolved"),
provider: ProviderDriverKind.make("codex"),
provider: "codex",
createdAt: new Date().toISOString(),
threadId: asThreadId("thread-1"),
turnId: asTurnId("turn-user-input"),
@@ -2928,7 +2913,7 @@ describe("ProviderRuntimeIngestion", () => {
harness.emit({
type: "content.delta",
eventId: asEventId("evt-invalid-delta"),
provider: ProviderDriverKind.make("codex"),
provider: "codex",
createdAt: now,
threadId: asThreadId("thread-1"),
turnId: asTurnId("turn-invalid"),
@@ -2942,7 +2927,7 @@ describe("ProviderRuntimeIngestion", () => {
harness.emit({
type: "runtime.error",
eventId: asEventId("evt-runtime-error-after-failure"),
provider: ProviderDriverKind.make("codex"),
provider: "codex",
createdAt: new Date().toISOString(),
threadId: asThreadId("thread-1"),
turnId: asTurnId("turn-after-failure"),
@@ -1211,9 +1211,6 @@ const make = Effect.gen(function* () {
threadId: thread.id,
status,
providerName: event.provider,
...(event.providerInstanceId !== undefined
? { providerInstanceId: event.providerInstanceId }
: {}),
runtimeMode: thread.session?.runtimeMode ?? "full-access",
activeTurnId: nextActiveTurnId,
lastError,
@@ -1459,9 +1456,6 @@ const make = Effect.gen(function* () {
threadId: thread.id,
status: "error",
providerName: event.provider,
...(event.providerInstanceId !== undefined
? { providerInstanceId: event.providerInstanceId }
: {}),
runtimeMode: thread.session?.runtimeMode ?? "full-access",
activeTurnId: eventTurnId ?? null,
lastError: runtimeErrorMessage,
@@ -7,7 +7,6 @@ import {
ThreadId,
type OrchestrationCommand,
type OrchestrationReadModel,
ProviderInstanceId,
} from "@t3tools/contracts";
import { Effect } from "effect";
@@ -30,7 +29,7 @@ const readModel: OrchestrationReadModel = {
title: "Project A",
workspaceRoot: "/tmp/project-a",
defaultModelSelection: {
instanceId: ProviderInstanceId.make("codex"),
provider: "codex",
model: "gpt-5-codex",
},
scripts: [],
@@ -43,7 +42,7 @@ const readModel: OrchestrationReadModel = {
title: "Project B",
workspaceRoot: "/tmp/project-b",
defaultModelSelection: {
instanceId: ProviderInstanceId.make("codex"),
provider: "codex",
model: "gpt-5-codex",
},
scripts: [],
@@ -58,7 +57,7 @@ const readModel: OrchestrationReadModel = {
projectId: ProjectId.make("project-a"),
title: "Thread A",
modelSelection: {
instanceId: ProviderInstanceId.make("codex"),
provider: "codex",
model: "gpt-5-codex",
},
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
@@ -81,7 +80,7 @@ const readModel: OrchestrationReadModel = {
projectId: ProjectId.make("project-b"),
title: "Thread B",
modelSelection: {
instanceId: ProviderInstanceId.make("codex"),
provider: "codex",
model: "gpt-5-codex",
},
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
@@ -158,7 +157,7 @@ describe("commandInvariants", () => {
projectId: ProjectId.make("project-a"),
title: "new",
modelSelection: {
instanceId: ProviderInstanceId.make("codex"),
provider: "codex",
model: "gpt-5-codex",
},
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
@@ -182,7 +181,7 @@ describe("commandInvariants", () => {
projectId: ProjectId.make("project-a"),
title: "dup",
modelSelection: {
instanceId: ProviderInstanceId.make("codex"),
provider: "codex",
model: "gpt-5-codex",
},
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
@@ -7,7 +7,6 @@ import {
type OrchestrationCommand,
type OrchestrationEvent,
type OrchestrationReadModel,
ProviderInstanceId,
} from "@t3tools/contracts";
import { Effect } from "effect";
import { describe, expect, it } from "vitest";
@@ -64,7 +63,7 @@ async function seedReadModel(): Promise<OrchestrationReadModel> {
projectId: asProjectId("project-delete"),
title: "Thread Delete 1",
modelSelection: {
instanceId: ProviderInstanceId.make("codex"),
provider: "codex",
model: "gpt-5-codex",
},
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
@@ -94,7 +93,7 @@ async function seedReadModel(): Promise<OrchestrationReadModel> {
projectId: asProjectId("project-delete"),
title: "Thread Delete 2",
modelSelection: {
instanceId: ProviderInstanceId.make("codex"),
provider: "codex",
model: "gpt-5-codex",
},
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
@@ -5,7 +5,6 @@ import {
MessageId,
ProjectId,
ThreadId,
ProviderInstanceId,
} from "@t3tools/contracts";
import { createModelSelection } from "@t3tools/shared/model";
import { describe, expect, it } from "vitest";
@@ -139,7 +138,7 @@ describe("decider project scripts", () => {
projectId: asProjectId("project-1"),
title: "Thread",
modelSelection: {
instanceId: ProviderInstanceId.make("codex"),
provider: "codex",
model: "gpt-5-codex",
},
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
@@ -164,7 +163,7 @@ describe("decider project scripts", () => {
text: "hello",
attachments: [],
},
modelSelection: createModelSelection(ProviderInstanceId.make("codex"), "gpt-5.3-codex", [
modelSelection: createModelSelection("codex", "gpt-5.3-codex", [
{ id: "reasoningEffort", value: "high" },
{ id: "fastMode", value: true },
]),
@@ -189,7 +188,7 @@ describe("decider project scripts", () => {
expect(turnStartEvent.payload).toMatchObject({
threadId: ThreadId.make("thread-1"),
messageId: asMessageId("message-user-1"),
modelSelection: createModelSelection(ProviderInstanceId.make("codex"), "gpt-5.3-codex", [
modelSelection: createModelSelection("codex", "gpt-5.3-codex", [
{ id: "reasoningEffort", value: "high" },
{ id: "fastMode", value: true },
]),
@@ -240,7 +239,7 @@ describe("decider project scripts", () => {
projectId: asProjectId("project-1"),
title: "Thread",
modelSelection: {
instanceId: ProviderInstanceId.make("codex"),
provider: "codex",
model: "gpt-5-codex",
},
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
@@ -322,7 +321,7 @@ describe("decider project scripts", () => {
projectId: asProjectId("project-1"),
title: "Thread",
modelSelection: {
instanceId: ProviderInstanceId.make("codex"),
provider: "codex",
model: "gpt-5-codex",
},
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
+10 -11
View File
@@ -2,7 +2,6 @@ import {
CommandId,
EventId,
ProjectId,
ProviderDriverKind,
ThreadId,
type OrchestrationEvent,
} from "@t3tools/contracts";
@@ -58,7 +57,7 @@ describe("orchestration projector", () => {
projectId: "project-1",
title: "demo",
modelSelection: {
provider: ProviderDriverKind.make("codex"),
provider: "codex",
model: "gpt-5-codex",
},
runtimeMode: "full-access",
@@ -78,7 +77,7 @@ describe("orchestration projector", () => {
projectId: "project-1",
title: "demo",
modelSelection: {
instanceId: "codex",
provider: "codex",
model: "gpt-5-codex",
},
runtimeMode: "full-access",
@@ -119,7 +118,7 @@ describe("orchestration projector", () => {
projectId: "project-1",
title: "demo",
modelSelection: {
provider: ProviderDriverKind.make("codex"),
provider: "codex",
model: "gpt-5-codex",
},
branch: null,
@@ -151,7 +150,7 @@ describe("orchestration projector", () => {
projectId: "project-1",
title: "demo",
modelSelection: {
provider: ProviderDriverKind.make("codex"),
provider: "codex",
model: "gpt-5-codex",
},
runtimeMode: "full-access",
@@ -254,7 +253,7 @@ describe("orchestration projector", () => {
projectId: "project-1",
title: "demo",
modelSelection: {
provider: ProviderDriverKind.make("codex"),
provider: "codex",
model: "gpt-5.3-codex",
},
runtimeMode: "full-access",
@@ -320,7 +319,7 @@ describe("orchestration projector", () => {
projectId: "project-1",
title: "demo",
modelSelection: {
provider: ProviderDriverKind.make("codex"),
provider: "codex",
model: "gpt-5.3-codex",
},
runtimeMode: "full-access",
@@ -377,7 +376,7 @@ describe("orchestration projector", () => {
projectId: "project-1",
title: "demo",
modelSelection: {
provider: ProviderDriverKind.make("codex"),
provider: "codex",
model: "gpt-5.3-codex",
},
runtimeMode: "full-access",
@@ -464,7 +463,7 @@ describe("orchestration projector", () => {
projectId: "project-1",
title: "demo",
modelSelection: {
provider: ProviderDriverKind.make("codex"),
provider: "codex",
model: "gpt-5.3-codex",
},
runtimeMode: "full-access",
@@ -679,7 +678,7 @@ describe("orchestration projector", () => {
projectId: "project-1",
title: "demo",
modelSelection: {
provider: ProviderDriverKind.make("codex"),
provider: "codex",
model: "gpt-5.3-codex",
},
runtimeMode: "full-access",
@@ -832,7 +831,7 @@ describe("orchestration projector", () => {
projectId: "project-1",
title: "capped",
modelSelection: {
provider: ProviderDriverKind.make("codex"),
provider: "codex",
model: "gpt-5-codex",
},
runtimeMode: "full-access",
@@ -1,4 +1,4 @@
import { ProjectId, ThreadId, ProviderInstanceId } from "@t3tools/contracts";
import { ProjectId, ThreadId } 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: {
instanceId: ProviderInstanceId.make("codex"),
provider: "codex",
model: "gpt-5.4",
},
scripts: [],
@@ -52,7 +52,7 @@ projectionRepositoriesLayer("Projection repositories", (it) => {
assert.strictEqual(
row.defaultModelSelection,
JSON.stringify({
instanceId: ProviderInstanceId.make("codex"),
provider: "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, {
instanceId: ProviderInstanceId.make("codex"),
provider: "codex",
model: "gpt-5.4",
});
}),
@@ -77,7 +77,7 @@ projectionRepositoriesLayer("Projection repositories", (it) => {
projectId: ProjectId.make("project-null-options"),
title: "Null options thread",
modelSelection: {
instanceId: ProviderInstanceId.make("claudeAgent"),
provider: "claudeAgent",
model: "claude-opus-4-6",
},
runtimeMode: "full-access",
@@ -110,7 +110,7 @@ projectionRepositoriesLayer("Projection repositories", (it) => {
assert.strictEqual(
row.modelSelection,
JSON.stringify({
instanceId: ProviderInstanceId.make("claudeAgent"),
provider: "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, {
instanceId: ProviderInstanceId.make("claudeAgent"),
provider: "claudeAgent",
model: "claude-opus-4-6",
});
}),
@@ -23,7 +23,6 @@ const makeProjectionThreadSessionRepository = Effect.gen(function* () {
thread_id,
status,
provider_name,
provider_instance_id,
runtime_mode,
active_turn_id,
last_error,
@@ -33,7 +32,6 @@ const makeProjectionThreadSessionRepository = Effect.gen(function* () {
${row.threadId},
${row.status},
${row.providerName},
${row.providerInstanceId},
${row.runtimeMode},
${row.activeTurnId},
${row.lastError},
@@ -43,7 +41,6 @@ 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,
@@ -60,7 +57,6 @@ 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,7 +46,6 @@ const makeProviderSessionRuntimeRepository = Effect.gen(function* () {
INSERT INTO provider_session_runtime (
thread_id,
provider_name,
provider_instance_id,
adapter_key,
runtime_mode,
status,
@@ -57,7 +56,6 @@ const makeProviderSessionRuntimeRepository = Effect.gen(function* () {
VALUES (
${runtime.threadId},
${runtime.providerName},
${runtime.providerInstanceId},
${runtime.adapterKey},
${runtime.runtimeMode},
${runtime.status},
@@ -68,7 +66,6 @@ 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,
@@ -86,7 +83,6 @@ 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,
@@ -106,7 +102,6 @@ const makeProviderSessionRuntimeRepository = Effect.gen(function* () {
SELECT
thread_id AS "threadId",
provider_name AS "providerName",
provider_instance_id AS "providerInstanceId",
adapter_key AS "adapterKey",
runtime_mode AS "runtimeMode",
status,
@@ -39,8 +39,6 @@ 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.
@@ -79,8 +77,6 @@ export const migrationEntries = [
[24, "BackfillProjectionThreadShellSummary", Migration0024],
[25, "CleanupInvalidProjectionPendingApprovals", Migration0025],
[26, "CanonicalizeModelSelectionOptions", Migration0026],
[27, "ProviderSessionRuntimeInstanceId", Migration0027],
[28, "ProjectionThreadSessionInstanceId", Migration0028],
] as const;
export const makeMigrationLoader = (throughId?: number) =>
@@ -1,74 +0,0 @@
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",
),
);
}),
);
});
@@ -1,38 +0,0 @@
/**
* 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)
`;
});
@@ -1,21 +0,0 @@
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,7 +10,6 @@ import {
RuntimeMode,
IsoDateTime,
OrchestrationSessionStatus,
ProviderInstanceId,
ThreadId,
TurnId,
} from "@t3tools/contracts";
@@ -23,7 +22,6 @@ 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,7 +7,6 @@
*/
import {
IsoDateTime,
ProviderInstanceId,
ProviderSessionRuntimeStatus,
RuntimeMode,
ThreadId,
@@ -20,14 +19,6 @@ import type { ProviderSessionRuntimeRepositoryError } from "../Errors.ts";
export const ProviderSessionRuntime = Schema.Struct({
threadId: ThreadId,
providerName: Schema.String,
/**
* User-defined routing key for the configured provider instance that
* owns this session. Nullable only at the storage/migration boundary:
* rows persisted before the driver/instance split carry only
* `providerName`. Repository consumers must materialize a concrete
* instance id before routing.
*/
providerInstanceId: Schema.NullOr(ProviderInstanceId),
adapterKey: Schema.String,
runtimeMode: RuntimeMode,
status: ProviderSessionRuntimeStatus,
@@ -1,9 +1,6 @@
import type { RepositoryIdentity } from "@t3tools/contracts";
import { Cache, Duration, Effect, Exit, Layer } from "effect";
import {
detectSourceControlProviderFromGitRemoteUrl,
normalizeGitRemoteUrl,
} from "@t3tools/shared/git";
import { detectGitHostingProviderFromRemoteUrl, normalizeGitRemoteUrl } from "@t3tools/shared/git";
import { runProcess } from "../../processRunner.ts";
import {
@@ -48,7 +45,7 @@ function buildRepositoryIdentity(input: {
readonly rootPath: string;
}): RepositoryIdentity {
const canonicalKey = normalizeGitRemoteUrl(input.remoteUrl);
const sourceControlProvider = detectSourceControlProviderFromGitRemoteUrl(input.remoteUrl);
const hostingProvider = detectGitHostingProviderFromRemoteUrl(input.remoteUrl);
const repositoryPath = canonicalKey.split("/").slice(1).join("/");
const repositoryPathSegments = repositoryPath.split("/").filter((segment) => segment.length > 0);
const [owner] = repositoryPathSegments;
@@ -63,7 +60,7 @@ function buildRepositoryIdentity(input: {
},
rootPath: input.rootPath,
...(repositoryPath ? { displayName: repositoryPath } : {}),
...(sourceControlProvider ? { provider: sourceControlProvider.kind } : {}),
...(hostingProvider ? { provider: hostingProvider.kind } : {}),
...(owner ? { owner } : {}),
...(repositoryName ? { name: repositoryName } : {}),
};
@@ -1,157 +0,0 @@
/**
* 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;
}),
};
@@ -1,52 +0,0 @@
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}`,
);
}),
);
});
});
@@ -1,43 +0,0 @@
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}`;
},
);
@@ -1,171 +0,0 @@
/**
* 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;
}),
};
@@ -1,209 +0,0 @@
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");
}),
);
});
});
@@ -1,263 +0,0 @@
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,
};
}
@@ -1,148 +0,0 @@
/**
* 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;
}),
};
@@ -1,135 +0,0 @@
/**
* 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,46 +116,6 @@ 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.
*/
@@ -197,7 +157,6 @@ export type ProviderAdapterError =
export type ProviderServiceError =
| ProviderValidationError
| ProviderUnsupportedError
| ProviderInstanceNotFoundError
| ProviderSessionNotFoundError
| ProviderSessionDirectoryPersistenceError
| ProviderAdapterError
@@ -12,29 +12,21 @@ 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 { Context, Effect, Fiber, Layer, Random, Schema, Stream } from "effect";
import { Effect, Fiber, Layer, Random, Stream } from "effect";
import { attachmentRelativePath } from "../../attachmentStore.ts";
import { ServerConfig } from "../../config.ts";
import { ServerSettingsService } from "../../serverSettings.ts";
import { ProviderAdapterValidationError } from "../Errors.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",
) {}
import { ClaudeAdapter } from "../Services/ClaudeAdapter.ts";
import { makeClaudeAdapterLive, type ClaudeAdapterLiveOptions } from "./ClaudeAdapter.ts";
class FakeClaudeQuery implements AsyncIterable<SDKMessage> {
private readonly queue: Array<SDKMessage> = [];
@@ -145,8 +137,6 @@ 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:
@@ -157,7 +147,6 @@ function makeHarness(config?: {
| undefined;
const adapterOptions: ClaudeAdapterLiveOptions = {
...(config?.instanceId ? { instanceId: config.instanceId } : {}),
createQuery: (input) => {
createInput = input;
return query;
@@ -175,13 +164,7 @@ function makeHarness(config?: {
};
return {
layer: Layer.effect(
ClaudeAdapter,
Effect.gen(function* () {
const claudeConfig = Schema.decodeSync(ClaudeSettings)(config?.claudeConfig ?? {});
return yield* makeClaudeAdapter(claudeConfig, adapterOptions);
}),
).pipe(
layer: makeClaudeAdapterLive(adapterOptions).pipe(
Layer.provideMerge(
ServerConfig.layerTest(
config?.cwd ?? "/tmp/claude-adapter-test",
@@ -264,11 +247,7 @@ describe("ClaudeAdapterLive", () => {
return Effect.gen(function* () {
const adapter = yield* ClaudeAdapter;
const result = yield* adapter
.startSession({
threadId: THREAD_ID,
provider: ProviderDriverKind.make("codex"),
runtimeMode: "full-access",
})
.startSession({ threadId: THREAD_ID, provider: "codex", runtimeMode: "full-access" })
.pipe(Effect.result);
assert.equal(result._tag, "Failure");
@@ -278,7 +257,7 @@ describe("ClaudeAdapterLive", () => {
assert.deepEqual(
result.failure,
new ProviderAdapterValidationError({
provider: ProviderDriverKind.make("claudeAgent"),
provider: "claudeAgent",
operation: "startSession",
issue: "Expected provider 'claudeAgent' but received 'codex'.",
}),
@@ -295,7 +274,7 @@ describe("ClaudeAdapterLive", () => {
const adapter = yield* ClaudeAdapter;
yield* adapter.startSession({
threadId: THREAD_ID,
provider: ProviderDriverKind.make("claudeAgent"),
provider: "claudeAgent",
runtimeMode: "full-access",
});
@@ -315,7 +294,7 @@ describe("ClaudeAdapterLive", () => {
const adapter = yield* ClaudeAdapter;
yield* adapter.startSession({
threadId: THREAD_ID,
provider: ProviderDriverKind.make("claudeAgent"),
provider: "claudeAgent",
runtimeMode: "approval-required",
});
@@ -335,7 +314,7 @@ describe("ClaudeAdapterLive", () => {
const adapter = yield* ClaudeAdapter;
yield* adapter.startSession({
threadId: THREAD_ID,
provider: ProviderDriverKind.make("claudeAgent"),
provider: "claudeAgent",
runtimeMode: "full-access",
});
@@ -354,12 +333,10 @@ describe("ClaudeAdapterLive", () => {
const adapter = yield* ClaudeAdapter;
yield* adapter.startSession({
threadId: THREAD_ID,
provider: ProviderDriverKind.make("claudeAgent"),
modelSelection: createModelSelection(
ProviderInstanceId.make("claudeAgent"),
"claude-opus-4-6",
[{ id: "effort", value: "max" }],
),
provider: "claudeAgent",
modelSelection: createModelSelection("claudeAgent", "claude-opus-4-6", [
{ id: "effort", value: "max" },
]),
runtimeMode: "full-access",
});
@@ -371,37 +348,15 @@ 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: ProviderDriverKind.make("claudeAgent"),
provider: "claudeAgent",
modelSelection: {
instanceId: ProviderInstanceId.make("claudeAgent"),
provider: "claudeAgent",
model: "claude-opus-4-7",
},
runtimeMode: "full-access",
@@ -421,12 +376,10 @@ describe("ClaudeAdapterLive", () => {
const adapter = yield* ClaudeAdapter;
yield* adapter.startSession({
threadId: THREAD_ID,
provider: ProviderDriverKind.make("claudeAgent"),
modelSelection: createModelSelection(
ProviderInstanceId.make("claudeAgent"),
"claude-opus-4-7",
[{ id: "effort", value: "xhigh" }],
),
provider: "claudeAgent",
modelSelection: createModelSelection("claudeAgent", "claude-opus-4-7", [
{ id: "effort", value: "xhigh" },
]),
runtimeMode: "full-access",
});
@@ -444,12 +397,10 @@ describe("ClaudeAdapterLive", () => {
const adapter = yield* ClaudeAdapter;
yield* adapter.startSession({
threadId: THREAD_ID,
provider: ProviderDriverKind.make("claudeAgent"),
modelSelection: createModelSelection(
ProviderInstanceId.make("claudeAgent"),
"claude-sonnet-4-6",
[{ id: "effort", value: "max" }],
),
provider: "claudeAgent",
modelSelection: createModelSelection("claudeAgent", "claude-sonnet-4-6", [
{ id: "effort", value: "max" },
]),
runtimeMode: "full-access",
});
@@ -467,12 +418,10 @@ describe("ClaudeAdapterLive", () => {
const adapter = yield* ClaudeAdapter;
yield* adapter.startSession({
threadId: THREAD_ID,
provider: ProviderDriverKind.make("claudeAgent"),
modelSelection: createModelSelection(
ProviderInstanceId.make("claudeAgent"),
"claude-haiku-4-5",
[{ id: "effort", value: "high" }],
),
provider: "claudeAgent",
modelSelection: createModelSelection("claudeAgent", "claude-haiku-4-5", [
{ id: "effort", value: "high" },
]),
runtimeMode: "full-access",
});
@@ -490,12 +439,10 @@ describe("ClaudeAdapterLive", () => {
const adapter = yield* ClaudeAdapter;
yield* adapter.startSession({
threadId: THREAD_ID,
provider: ProviderDriverKind.make("claudeAgent"),
modelSelection: createModelSelection(
ProviderInstanceId.make("claudeAgent"),
"claude-haiku-4-5",
[{ id: "thinking", value: false }],
),
provider: "claudeAgent",
modelSelection: createModelSelection("claudeAgent", "claude-haiku-4-5", [
{ id: "thinking", value: false },
]),
runtimeMode: "full-access",
});
@@ -515,12 +462,10 @@ describe("ClaudeAdapterLive", () => {
const adapter = yield* ClaudeAdapter;
yield* adapter.startSession({
threadId: THREAD_ID,
provider: ProviderDriverKind.make("claudeAgent"),
modelSelection: createModelSelection(
ProviderInstanceId.make("claudeAgent"),
"claude-sonnet-4-6",
[{ id: "thinking", value: false }],
),
provider: "claudeAgent",
modelSelection: createModelSelection("claudeAgent", "claude-sonnet-4-6", [
{ id: "thinking", value: false },
]),
runtimeMode: "full-access",
});
@@ -538,12 +483,10 @@ describe("ClaudeAdapterLive", () => {
const adapter = yield* ClaudeAdapter;
yield* adapter.startSession({
threadId: THREAD_ID,
provider: ProviderDriverKind.make("claudeAgent"),
modelSelection: createModelSelection(
ProviderInstanceId.make("claudeAgent"),
"claude-opus-4-6",
[{ id: "fastMode", value: true }],
),
provider: "claudeAgent",
modelSelection: createModelSelection("claudeAgent", "claude-opus-4-6", [
{ id: "fastMode", value: true },
]),
runtimeMode: "full-access",
});
@@ -563,12 +506,10 @@ describe("ClaudeAdapterLive", () => {
const adapter = yield* ClaudeAdapter;
yield* adapter.startSession({
threadId: THREAD_ID,
provider: ProviderDriverKind.make("claudeAgent"),
modelSelection: createModelSelection(
ProviderInstanceId.make("claudeAgent"),
"claude-sonnet-4-6",
[{ id: "fastMode", value: true }],
),
provider: "claudeAgent",
modelSelection: createModelSelection("claudeAgent", "claude-sonnet-4-6", [
{ id: "fastMode", value: true },
]),
runtimeMode: "full-access",
});
@@ -586,12 +527,10 @@ describe("ClaudeAdapterLive", () => {
const adapter = yield* ClaudeAdapter;
const session = yield* adapter.startSession({
threadId: THREAD_ID,
provider: ProviderDriverKind.make("claudeAgent"),
modelSelection: createModelSelection(
ProviderInstanceId.make("claudeAgent"),
"claude-sonnet-4-6",
[{ id: "effort", value: "ultrathink" }],
),
provider: "claudeAgent",
modelSelection: createModelSelection("claudeAgent", "claude-sonnet-4-6", [
{ id: "effort", value: "ultrathink" },
]),
runtimeMode: "full-access",
});
@@ -599,11 +538,9 @@ describe("ClaudeAdapterLive", () => {
threadId: session.threadId,
input: "Investigate the edge cases",
attachments: [],
modelSelection: createModelSelection(
ProviderInstanceId.make("claudeAgent"),
"claude-sonnet-4-6",
[{ id: "effort", value: "ultrathink" }],
),
modelSelection: createModelSelection("claudeAgent", "claude-sonnet-4-6", [
{ id: "effort", value: "ultrathink" },
]),
});
const createInput = harness.getLastCreateQueryInput();
@@ -648,7 +585,7 @@ describe("ClaudeAdapterLive", () => {
const session = yield* adapter.startSession({
threadId: THREAD_ID,
provider: ProviderDriverKind.make("claudeAgent"),
provider: "claudeAgent",
runtimeMode: "full-access",
});
@@ -693,9 +630,9 @@ describe("ClaudeAdapterLive", () => {
const session = yield* adapter.startSession({
threadId: THREAD_ID,
provider: ProviderDriverKind.make("claudeAgent"),
provider: "claudeAgent",
modelSelection: {
instanceId: ProviderInstanceId.make("claudeAgent"),
provider: "claudeAgent",
model: "claude-sonnet-4-5",
},
runtimeMode: "full-access",
@@ -870,7 +807,7 @@ describe("ClaudeAdapterLive", () => {
const session = yield* adapter.startSession({
threadId: THREAD_ID,
provider: ProviderDriverKind.make("claudeAgent"),
provider: "claudeAgent",
runtimeMode: "full-access",
});
@@ -1049,7 +986,7 @@ describe("ClaudeAdapterLive", () => {
const session = yield* adapter.startSession({
threadId: THREAD_ID,
provider: ProviderDriverKind.make("claudeAgent"),
provider: "claudeAgent",
runtimeMode: "full-access",
});
@@ -1140,7 +1077,7 @@ describe("ClaudeAdapterLive", () => {
const session = yield* adapter.startSession({
threadId: THREAD_ID,
provider: ProviderDriverKind.make("claudeAgent"),
provider: "claudeAgent",
runtimeMode: "full-access",
});
@@ -1216,7 +1153,7 @@ describe("ClaudeAdapterLive", () => {
const session = yield* adapter.startSession({
threadId: THREAD_ID,
provider: ProviderDriverKind.make("claudeAgent"),
provider: "claudeAgent",
runtimeMode: "full-access",
});
@@ -1282,7 +1219,7 @@ describe("ClaudeAdapterLive", () => {
yield* adapter.startSession({
threadId: THREAD_ID,
provider: ProviderDriverKind.make("claudeAgent"),
provider: "claudeAgent",
runtimeMode: "full-access",
});
@@ -1333,19 +1270,13 @@ describe("ClaudeAdapterLive", () => {
it.effect("closes the previous session before replacing an existing thread session", () => {
const queries: FakeClaudeQuery[] = [];
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(
const layer = makeClaudeAdapterLive({
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),
@@ -1361,13 +1292,13 @@ describe("ClaudeAdapterLive", () => {
const firstSession = yield* adapter.startSession({
threadId: THREAD_ID,
provider: ProviderDriverKind.make("claudeAgent"),
provider: "claudeAgent",
runtimeMode: "full-access",
});
const secondSession = yield* adapter.startSession({
threadId: THREAD_ID,
provider: ProviderDriverKind.make("claudeAgent"),
provider: "claudeAgent",
runtimeMode: "full-access",
resumeCursor: firstSession.resumeCursor,
});
@@ -1416,27 +1347,21 @@ describe("ClaudeAdapterLive", () => {
let promptConsumerError: unknown = undefined;
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(
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(
Layer.provideMerge(ServerConfig.layerTest("/tmp/claude-adapter-test", "/tmp")),
Layer.provideMerge(ServerSettingsService.layerTest()),
Layer.provideMerge(NodeServices.layer),
@@ -1454,7 +1379,7 @@ describe("ClaudeAdapterLive", () => {
yield* adapter.startSession({
threadId: THREAD_ID,
provider: ProviderDriverKind.make("claudeAgent"),
provider: "claudeAgent",
runtimeMode: "full-access",
});
@@ -1491,7 +1416,7 @@ describe("ClaudeAdapterLive", () => {
yield* adapter.startSession({
threadId: THREAD_ID,
provider: ProviderDriverKind.make("claudeAgent"),
provider: "claudeAgent",
runtimeMode: "full-access",
});
@@ -1538,7 +1463,7 @@ describe("ClaudeAdapterLive", () => {
yield* adapter.startSession({
threadId: THREAD_ID,
provider: ProviderDriverKind.make("claudeAgent"),
provider: "claudeAgent",
runtimeMode: "full-access",
});
@@ -1592,7 +1517,7 @@ describe("ClaudeAdapterLive", () => {
yield* adapter.startSession({
threadId: THREAD_ID,
provider: ProviderDriverKind.make("claudeAgent"),
provider: "claudeAgent",
runtimeMode: "full-access",
});
@@ -1659,7 +1584,7 @@ describe("ClaudeAdapterLive", () => {
yield* adapter.startSession({
threadId: THREAD_ID,
provider: ProviderDriverKind.make("claudeAgent"),
provider: "claudeAgent",
runtimeMode: "full-access",
});
@@ -1724,7 +1649,7 @@ describe("ClaudeAdapterLive", () => {
yield* adapter.startSession({
threadId: THREAD_ID,
provider: ProviderDriverKind.make("claudeAgent"),
provider: "claudeAgent",
runtimeMode: "full-access",
});
@@ -1805,7 +1730,7 @@ describe("ClaudeAdapterLive", () => {
const session = yield* adapter.startSession({
threadId: THREAD_ID,
provider: ProviderDriverKind.make("claudeAgent"),
provider: "claudeAgent",
runtimeMode: "full-access",
});
@@ -1896,7 +1821,7 @@ describe("ClaudeAdapterLive", () => {
const session = yield* adapter.startSession({
threadId: THREAD_ID,
provider: ProviderDriverKind.make("claudeAgent"),
provider: "claudeAgent",
runtimeMode: "full-access",
});
@@ -2062,7 +1987,7 @@ describe("ClaudeAdapterLive", () => {
const session = yield* adapter.startSession({
threadId: THREAD_ID,
provider: ProviderDriverKind.make("claudeAgent"),
provider: "claudeAgent",
runtimeMode: "full-access",
});
@@ -2131,7 +2056,7 @@ describe("ClaudeAdapterLive", () => {
const session = yield* adapter.startSession({
threadId: THREAD_ID,
provider: ProviderDriverKind.make("claudeAgent"),
provider: "claudeAgent",
runtimeMode: "full-access",
});
@@ -2353,7 +2278,7 @@ describe("ClaudeAdapterLive", () => {
const session = yield* adapter.startSession({
threadId: THREAD_ID,
provider: ProviderDriverKind.make("claudeAgent"),
provider: "claudeAgent",
runtimeMode: "full-access",
});
assert.equal(session.threadId, THREAD_ID);
@@ -2426,7 +2351,7 @@ describe("ClaudeAdapterLive", () => {
const session = yield* adapter.startSession({
threadId: THREAD_ID,
provider: ProviderDriverKind.make("claudeAgent"),
provider: "claudeAgent",
runtimeMode: "approval-required",
});
@@ -2535,7 +2460,7 @@ describe("ClaudeAdapterLive", () => {
const session = yield* adapter.startSession({
threadId: THREAD_ID,
provider: ProviderDriverKind.make("claudeAgent"),
provider: "claudeAgent",
runtimeMode: "approval-required",
});
@@ -2608,7 +2533,7 @@ describe("ClaudeAdapterLive", () => {
const session = yield* adapter.startSession({
threadId: RESUME_THREAD_ID,
provider: ProviderDriverKind.make("claudeAgent"),
provider: "claudeAgent",
resumeCursor: {
threadId: "resume-thread-1",
resume: "550e8400-e29b-41d4-a716-446655440000",
@@ -2636,96 +2561,6 @@ 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* () {
@@ -2733,7 +2568,7 @@ describe("ClaudeAdapterLive", () => {
const session = yield* adapter.startSession({
threadId: THREAD_ID,
provider: ProviderDriverKind.make("claudeAgent"),
provider: "claudeAgent",
runtimeMode: "full-access",
});
@@ -2767,7 +2602,7 @@ describe("ClaudeAdapterLive", () => {
const session = yield* adapter.startSession({
threadId: THREAD_ID,
provider: ProviderDriverKind.make("claudeAgent"),
provider: "claudeAgent",
runtimeMode: "full-access",
});
@@ -2847,14 +2682,14 @@ describe("ClaudeAdapterLive", () => {
const session = yield* adapter.startSession({
threadId: THREAD_ID,
provider: ProviderDriverKind.make("claudeAgent"),
provider: "claudeAgent",
runtimeMode: "full-access",
});
yield* adapter.sendTurn({
threadId: session.threadId,
input: "hello",
modelSelection: {
instanceId: ProviderInstanceId.make("claudeAgent"),
provider: "claudeAgent",
model: "claude-opus-4-6",
},
attachments: [],
@@ -2867,34 +2702,6 @@ 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",
() => {
@@ -2902,13 +2709,13 @@ describe("ClaudeAdapterLive", () => {
return Effect.gen(function* () {
const adapter = yield* ClaudeAdapter;
const modelSelection = {
instanceId: ProviderInstanceId.make("claudeAgent"),
provider: "claudeAgent" as const,
model: "claude-opus-4-6",
};
const session = yield* adapter.startSession({
threadId: THREAD_ID,
provider: ProviderDriverKind.make("claudeAgent"),
provider: "claudeAgent",
modelSelection,
runtimeMode: "full-access",
});
@@ -2941,25 +2748,23 @@ describe("ClaudeAdapterLive", () => {
const session = yield* adapter.startSession({
threadId: THREAD_ID,
provider: ProviderDriverKind.make("claudeAgent"),
provider: "claudeAgent",
runtimeMode: "full-access",
});
yield* adapter.sendTurn({
threadId: session.threadId,
input: "hello",
modelSelection: createModelSelection(
ProviderInstanceId.make("claudeAgent"),
"claude-opus-4-6",
[{ id: "contextWindow", value: "1m" }],
),
modelSelection: createModelSelection("claudeAgent", "claude-opus-4-6", [
{ id: "contextWindow", value: "1m" },
]),
attachments: [],
});
yield* adapter.sendTurn({
threadId: session.threadId,
input: "hello again",
modelSelection: {
instanceId: ProviderInstanceId.make("claudeAgent"),
provider: "claudeAgent",
model: "claude-opus-4-6",
},
attachments: [],
@@ -2979,7 +2784,7 @@ describe("ClaudeAdapterLive", () => {
const session = yield* adapter.startSession({
threadId: THREAD_ID,
provider: ProviderDriverKind.make("claudeAgent"),
provider: "claudeAgent",
runtimeMode: "full-access",
});
yield* adapter.sendTurn({
@@ -3009,7 +2814,7 @@ describe("ClaudeAdapterLive", () => {
const session = yield* adapter.startSession({
threadId: THREAD_ID,
provider: ProviderDriverKind.make("claudeAgent"),
provider: "claudeAgent",
runtimeMode,
});
@@ -3061,7 +2866,7 @@ describe("ClaudeAdapterLive", () => {
const session = yield* adapter.startSession({
threadId: THREAD_ID,
provider: ProviderDriverKind.make("claudeAgent"),
provider: "claudeAgent",
runtimeMode: "full-access",
});
yield* adapter.sendTurn({
@@ -3084,7 +2889,7 @@ describe("ClaudeAdapterLive", () => {
const session = yield* adapter.startSession({
threadId: THREAD_ID,
provider: ProviderDriverKind.make("claudeAgent"),
provider: "claudeAgent",
runtimeMode: "full-access",
});
@@ -3150,7 +2955,7 @@ describe("ClaudeAdapterLive", () => {
const session = yield* adapter.startSession({
threadId: THREAD_ID,
provider: ProviderDriverKind.make("claudeAgent"),
provider: "claudeAgent",
runtimeMode: "full-access",
});
@@ -3222,7 +3027,7 @@ describe("ClaudeAdapterLive", () => {
// Start session in approval-required mode so canUseTool fires.
const session = yield* adapter.startSession({
threadId: THREAD_ID,
provider: ProviderDriverKind.make("claudeAgent"),
provider: "claudeAgent",
runtimeMode: "approval-required",
});
@@ -3296,9 +3101,6 @@ 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"),
});
@@ -3333,34 +3135,6 @@ 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),
@@ -3376,7 +3150,7 @@ describe("ClaudeAdapterLive", () => {
// AskUserQuestion should still go through the user-input flow.
const session = yield* adapter.startSession({
threadId: THREAD_ID,
provider: ProviderDriverKind.make("claudeAgent"),
provider: "claudeAgent",
runtimeMode: "full-access",
});
@@ -3442,7 +3216,7 @@ describe("ClaudeAdapterLive", () => {
const session = yield* adapter.startSession({
threadId: THREAD_ID,
provider: ProviderDriverKind.make("claudeAgent"),
provider: "claudeAgent",
runtimeMode: "approval-required",
});
@@ -3529,7 +3303,7 @@ describe("ClaudeAdapterLive", () => {
const session = yield* adapter.startSession({
threadId: THREAD_ID,
provider: ProviderDriverKind.make("claudeAgent"),
provider: "claudeAgent",
runtimeMode: "full-access",
});
const turn = yield* adapter.sendTurn({
@@ -24,11 +24,8 @@ import {
ApprovalRequestId,
type CanonicalItemType,
type CanonicalRequestType,
type ClaudeSettings,
EventId,
type ProviderApprovalDecision,
ProviderDriverKind,
ProviderInstanceId,
ProviderItemId,
type ProviderRuntimeEvent,
type ProviderRuntimeTurnStatus,
@@ -59,7 +56,7 @@ import {
Exit,
FileSystem,
Fiber,
Path,
Layer,
Queue,
Random,
Ref,
@@ -68,7 +65,7 @@ import {
import { resolveAttachmentPath } from "../../attachmentStore.ts";
import { ServerConfig } from "../../config.ts";
import { makeClaudeEnvironment } from "../Drivers/ClaudeHome.ts";
import { ServerSettingsService } from "../../serverSettings.ts";
import {
getClaudeModelCapabilities,
normalizeClaudeCliEffort,
@@ -83,10 +80,10 @@ import {
ProviderAdapterValidationError,
type ProviderAdapterError,
} from "../Errors.ts";
import { type ClaudeAdapterShape } from "../Services/ClaudeAdapter.ts";
import { ClaudeAdapter, type ClaudeAdapterShape } from "../Services/ClaudeAdapter.ts";
import { type EventNdjsonLogger, makeEventNdjsonLogger } from "./EventNdjsonLogger.ts";
const PROVIDER = ProviderDriverKind.make("claudeAgent");
const PROVIDER = "claudeAgent" as const;
type ClaudeTextStreamKind = Extract<RuntimeContentStreamKind, "assistant_text" | "reasoning_text">;
type ClaudeToolResultStreamKind = Extract<
RuntimeContentStreamKind,
@@ -185,8 +182,6 @@ 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;
@@ -203,18 +198,6 @@ 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;
@@ -570,16 +553,13 @@ const CLAUDE_SETTING_SOURCES = [
"local",
] as const satisfies ReadonlyArray<SettingSource>;
function buildPromptText(
input: ProviderSendTurnInput,
boundInstanceId: ProviderInstanceId,
): string {
function buildPromptText(input: ProviderSendTurnInput): string {
const rawEffort =
input.modelSelection?.instanceId === boundInstanceId
input.modelSelection?.provider === "claudeAgent"
? getModelSelectionStringOptionValue(input.modelSelection, "effort")
: null;
const claudeModel =
input.modelSelection?.instanceId === boundInstanceId ? input.modelSelection.model : undefined;
input.modelSelection?.provider === "claudeAgent" ? input.modelSelection.model : undefined;
const caps = getClaudeModelCapabilities(claudeModel);
const promptEffort = resolvePromptInjectedEffort(caps, rawEffort);
@@ -619,10 +599,9 @@ const buildUserMessageEffect = Effect.fn("buildUserMessageEffect")(function* (
dependencies: {
readonly fileSystem: FileSystem.FileSystem;
readonly attachmentsDir: string;
readonly boundInstanceId: ProviderInstanceId;
},
) {
const text = buildPromptText(input, dependencies.boundInstanceId);
const text = buildPromptText(input);
const sdkContent: Array<Record<string, unknown>> = [];
if (text.length > 0) {
@@ -972,17 +951,11 @@ function sdkNativeItemId(message: SDKMessage): string | undefined {
return undefined;
}
export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
claudeSettings: ClaudeSettings,
const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
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
@@ -1004,6 +977,7 @@ export 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));
@@ -1275,9 +1249,6 @@ export 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);
@@ -2563,14 +2534,10 @@ export 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.question === "string" && q.question.length > 0 ? q.question : `q-${idx}`,
id: typeof q.header === "string" ? q.header : `q-${idx}`,
header: typeof q.header === "string" ? q.header : `Question ${idx + 1}`,
question: typeof q.question === "string" ? q.question : "",
options: Array.isArray(q.options)
@@ -2838,10 +2805,22 @@ export 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?.instanceId === boundInstanceId ? input.modelSelection : undefined;
input.modelSelection?.provider === "claudeAgent" ? input.modelSelection : undefined;
const caps = getClaudeModelCapabilities(modelSelection?.model);
const descriptors = getProviderOptionDescriptors({ caps });
const apiModelId = modelSelection ? resolveClaudeApiModelId(modelSelection) : undefined;
@@ -2869,6 +2848,7 @@ export 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 } : {}),
@@ -2890,36 +2870,11 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
...(newSessionId ? { sessionId: newSessionId } : {}),
includePartialMessages: true,
canUseTool,
env: claudeEnvironment,
env: process.env,
...(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({
@@ -2938,7 +2893,6 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
const session: ProviderSession = {
threadId,
provider: PROVIDER,
providerInstanceId: boundInstanceId,
status: "ready",
runtimeMode: input.runtimeMode,
...(input.cwd ? { cwd: input.cwd } : {}),
@@ -3050,9 +3004,7 @@ export 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 !== undefined && input.modelSelection.instanceId === boundInstanceId
? input.modelSelection
: undefined;
input.modelSelection?.provider === "claudeAgent" ? input.modelSelection : undefined;
if (context.turnState) {
// Auto-close a stale synthetic turn (from background agent responses
@@ -3126,7 +3078,6 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
const message = yield* buildUserMessageEffect(input, {
fileSystem,
attachmentsDir: serverConfig.attachmentsDir,
boundInstanceId,
});
yield* Queue.offer(context.promptQueue, {
@@ -3264,3 +3215,9 @@ export 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));
}
+353 -131
View File
@@ -1,13 +1,16 @@
import {
type ClaudeSettings,
type ModelCapabilities,
type ModelSelection,
ProviderDriverKind,
type ServerProviderModel,
type ServerProviderSlashCommand,
import type {
ClaudeSettings,
ClaudeModelSelection,
ModelCapabilities,
ServerProvider,
ServerProviderModel,
ServerProviderAuth,
ServerProviderSlashCommand,
ServerProviderState,
} from "@t3tools/contracts";
import { Effect, Option, Path, Result } from "effect";
import { Cache, Duration, Effect, Equal, Layer, Option, Result, Schema, Stream } from "effect";
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
import { decodeJsonResult } from "@t3tools/shared/schemaJson";
import {
createModelCapabilities,
getModelSelectionStringOptionValue,
@@ -24,22 +27,27 @@ import {
buildBooleanOptionDescriptor,
buildSelectOptionDescriptor,
buildServerProvider,
AUTH_PROBE_TIMEOUT_MS,
DEFAULT_TIMEOUT_MS,
detailFromResult,
extractAuthBoolean,
isCommandMissingCause,
parseGenericCliVersion,
providerModelsFromSettings,
spawnAndCollect,
type ServerProviderDraft,
type CommandResult,
} from "../providerSnapshot.ts";
import { compareCliVersions } from "../cliVersion.ts";
import { makeClaudeEnvironment } from "../Drivers/ClaudeHome.ts";
import { makeManagedServerProvider } from "../makeManagedServerProvider.ts";
import { ClaudeProvider } from "../Services/ClaudeProvider.ts";
import { ServerSettingsService } from "../../serverSettings.ts";
import { ServerSettingsError } from "@t3tools/contracts";
const DEFAULT_CLAUDE_MODEL_CAPABILITIES: ModelCapabilities = createModelCapabilities({
optionDescriptors: [],
});
const PROVIDER = ProviderDriverKind.make("claudeAgent");
const PROVIDER = "claudeAgent" as const;
const CLAUDE_PRESENTATION = {
displayName: "Claude",
showInteractionModeToggle: true,
@@ -234,7 +242,7 @@ export function normalizeClaudeCliEffort(effort: string | null | undefined): str
return effort;
}
export function resolveClaudeApiModelId(modelSelection: ModelSelection): string {
export function resolveClaudeApiModelId(modelSelection: ClaudeModelSelection): string {
switch (getModelSelectionStringOptionValue(modelSelection, "contextWindow")) {
case "1m":
return `${modelSelection.model}[1m]`;
@@ -242,6 +250,181 @@ export function resolveClaudeApiModelId(modelSelection: ModelSelection): string
return modelSelection.model;
}
}
export function parseClaudeAuthStatusFromOutput(result: CommandResult): {
readonly status: Exclude<ServerProviderState, "disabled">;
readonly auth: Pick<ServerProviderAuth, "status">;
readonly message?: string;
} {
const lowerOutput = `${result.stdout}\n${result.stderr}`.toLowerCase();
if (
lowerOutput.includes("unknown command") ||
lowerOutput.includes("unrecognized command") ||
lowerOutput.includes("unexpected argument")
) {
return {
status: "warning",
auth: { status: "unknown" },
message:
"Claude Agent authentication status command is unavailable in this version of Claude.",
};
}
if (
lowerOutput.includes("not logged in") ||
lowerOutput.includes("login required") ||
lowerOutput.includes("authentication required") ||
lowerOutput.includes("run `claude login`") ||
lowerOutput.includes("run claude login")
) {
return {
status: "error",
auth: { status: "unauthenticated" },
message: "Claude is not authenticated. Run `claude auth login` and try again.",
};
}
const parsedAuth = (() => {
const trimmed = result.stdout.trim();
if (!trimmed || (!trimmed.startsWith("{") && !trimmed.startsWith("["))) {
return { attemptedJsonParse: false as const, auth: undefined as boolean | undefined };
}
try {
return {
attemptedJsonParse: true as const,
auth: extractAuthBoolean(JSON.parse(trimmed)),
};
} catch {
return { attemptedJsonParse: false as const, auth: undefined as boolean | undefined };
}
})();
if (parsedAuth.auth === true) {
return { status: "ready", auth: { status: "authenticated" } };
}
if (parsedAuth.auth === false) {
return {
status: "error",
auth: { status: "unauthenticated" },
message: "Claude is not authenticated. Run `claude auth login` and try again.",
};
}
if (parsedAuth.attemptedJsonParse) {
return {
status: "warning",
auth: { status: "unknown" },
message:
"Could not verify Claude authentication status from JSON output (missing auth marker).",
};
}
if (result.code === 0) {
return { status: "ready", auth: { status: "authenticated" } };
}
const detail = detailFromResult(result);
return {
status: "warning",
auth: { status: "unknown" },
message: detail
? `Could not verify Claude authentication status. ${detail}`
: "Could not verify Claude authentication status.",
};
}
// ── Subscription type detection ─────────────────────────────────────
//
// The SDK probe returns typed `AccountInfo.subscriptionType` directly.
// This walker is a best-effort fallback for the `claude auth status`
// JSON output whose shape is not guaranteed.
/** Keys that directly hold a subscription/plan identifier. */
const SUBSCRIPTION_TYPE_KEYS = [
"subscriptionType",
"subscription_type",
"plan",
"tier",
"planType",
"plan_type",
] as const;
/** Keys whose value may be a nested object containing subscription info. */
const SUBSCRIPTION_CONTAINER_KEYS = ["account", "subscription", "user", "billing"] as const;
const AUTH_METHOD_KEYS = ["authMethod", "auth_method"] as const;
const AUTH_METHOD_CONTAINER_KEYS = ["auth", "account", "session"] as const;
/** Lift an unknown value into `Option<string>` if it is a non-empty string. */
const asNonEmptyString = (v: unknown): Option.Option<string> =>
typeof v === "string" && v.length > 0 ? Option.some(v) : Option.none();
/** Lift an unknown value into `Option<Record>` if it is a plain object. */
const asRecord = (v: unknown): Option.Option<Record<string, unknown>> =>
typeof v === "object" && v !== null && !globalThis.Array.isArray(v)
? Option.some(v as Record<string, unknown>)
: Option.none();
/**
* Walk an unknown parsed JSON value looking for a subscription/plan
* identifier, returning the first match as an `Option`.
*/
function findSubscriptionType(value: unknown): Option.Option<string> {
if (globalThis.Array.isArray(value)) {
return Option.firstSomeOf(value.map(findSubscriptionType));
}
return asRecord(value).pipe(
Option.flatMap((record) => {
const direct = Option.firstSomeOf(
SUBSCRIPTION_TYPE_KEYS.map((key) => asNonEmptyString(record[key])),
);
if (Option.isSome(direct)) return direct;
return Option.firstSomeOf(
SUBSCRIPTION_CONTAINER_KEYS.map((key) =>
asRecord(record[key]).pipe(Option.flatMap(findSubscriptionType)),
),
);
}),
);
}
function findAuthMethod(value: unknown): Option.Option<string> {
if (globalThis.Array.isArray(value)) {
return Option.firstSomeOf(value.map(findAuthMethod));
}
return asRecord(value).pipe(
Option.flatMap((record) => {
const direct = Option.firstSomeOf(
AUTH_METHOD_KEYS.map((key) => asNonEmptyString(record[key])),
);
if (Option.isSome(direct)) return direct;
return Option.firstSomeOf(
AUTH_METHOD_CONTAINER_KEYS.map((key) =>
asRecord(record[key]).pipe(Option.flatMap(findAuthMethod)),
),
);
}),
);
}
/**
* Try to extract a subscription type from the `claude auth status` JSON
* output. This is a zero-cost operation on data we already have.
*/
const decodeUnknownJson = decodeJsonResult(Schema.Unknown);
function extractSubscriptionTypeFromOutput(result: CommandResult): string | undefined {
const parsed = decodeUnknownJson(result.stdout.trim());
if (Result.isFailure(parsed)) return undefined;
return Option.getOrUndefined(findSubscriptionType(parsed.success));
}
function extractClaudeAuthMethodFromOutput(result: CommandResult): string | undefined {
const parsed = decodeUnknownJson(result.stdout.trim());
if (Result.isFailure(parsed)) return undefined;
return Option.getOrUndefined(findAuthMethod(parsed.success));
}
function toTitleCaseWords(value: string): string {
return value
@@ -256,27 +439,11 @@ 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":
return "Max";
case "max5":
return "Max 5x";
case "max20":
return "Max 20x";
return "Max";
case "enterprise":
return "Enterprise";
case "team":
@@ -293,33 +460,10 @@ 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" ||
normalized === "anthropicapikey" ||
normalized === "anthropicauthtoken"
) {
return "apiKey";
}
if (normalized === "apikey") 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;
@@ -332,9 +476,10 @@ function claudeAuthMetadata(input: {
}
if (input.subscriptionType) {
const subscriptionLabel = claudeSubscriptionLabel(input.subscriptionType);
return {
type: input.subscriptionType,
label: formatClaudeSubscriptionAuthLabel(input.subscriptionType),
label: `Claude ${subscriptionLabel ?? toTitleCaseWords(input.subscriptionType)} Subscription`,
};
}
@@ -350,13 +495,6 @@ 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> {
@@ -442,46 +580,30 @@ function waitForAbortSignal(signal: AbortSignal): Promise<void> {
* This is used as a fallback when `claude auth status` does not include
* subscription type information.
*/
const probeClaudeCapabilities = (
claudeSettings: ClaudeSettings,
environment: NodeJS.ProcessEnv = process.env,
) => {
const probeClaudeCapabilities = (binaryPath: string) => {
const abort = new AbortController();
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;
return Effect.tryPromise(async () => {
const q = claudeQuery({
// Never yield — we only need initialization data, not a conversation.
// This prevents any prompt from reaching the Anthropic API.
// oxlint-disable-next-line require-yield
prompt: (async function* (): AsyncGenerator<SDKUserMessage> {
await waitForAbortSignal(abort.signal);
})(),
options: {
persistSession: false,
pathToClaudeCodeExecutable: binaryPath,
abortController: abort,
settingSources: ["user", "project", "local"],
allowedTools: [],
stderr: () => {},
},
});
const init = await q.initializationResult();
return {
subscriptionType: init.account?.subscriptionType,
slashCommands: parseClaudeInitializationCommands(init.commands),
};
}).pipe(
Effect.ensuring(
Effect.sync(() => {
@@ -497,30 +619,31 @@ const probeClaudeCapabilities = (
);
};
const runClaudeCommand = Effect.fn("runClaudeCommand")(function* (
claudeSettings: ClaudeSettings,
args: ReadonlyArray<string>,
environment: NodeJS.ProcessEnv = process.env,
) {
const claudeEnvironment = yield* makeClaudeEnvironment(claudeSettings, environment);
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 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* (
claudeSettings: ClaudeSettings,
resolveCapabilities?: (
claudeSettings: ClaudeSettings,
) => Effect.Effect<ClaudeCapabilitiesProbe | undefined>,
environment: NodeJS.ProcessEnv = process.env,
resolveSubscriptionType?: (binaryPath: string) => Effect.Effect<string | undefined>,
resolveSlashCommands?: (
binaryPath: string,
) => Effect.Effect<ReadonlyArray<ServerProviderSlashCommand> | undefined>,
): Effect.fn.Return<
ServerProviderDraft,
never,
ChildProcessSpawner.ChildProcessSpawner | Path.Path
ServerProvider,
ServerSettingsError,
ChildProcessSpawner.ChildProcessSpawner | ServerSettingsService
> {
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,
@@ -531,6 +654,7 @@ export const checkClaudeProviderStatus = Effect.fn("checkClaudeProviderStatus")(
if (!claudeSettings.enabled) {
return buildServerProvider({
provider: PROVIDER,
presentation: CLAUDE_PRESENTATION,
enabled: false,
checkedAt,
@@ -545,7 +669,7 @@ export const checkClaudeProviderStatus = Effect.fn("checkClaudeProviderStatus")(
});
}
const versionProbe = yield* runClaudeCommand(claudeSettings, ["--version"], environment).pipe(
const versionProbe = yield* runClaudeCommand(["--version"]).pipe(
Effect.timeoutOption(DEFAULT_TIMEOUT_MS),
Effect.result,
);
@@ -553,6 +677,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,
@@ -571,6 +696,7 @@ export const checkClaudeProviderStatus = Effect.fn("checkClaudeProviderStatus")(
if (Option.isNone(versionProbe.success)) {
return buildServerProvider({
provider: PROVIDER,
presentation: CLAUDE_PRESENTATION,
enabled: claudeSettings.enabled,
checkedAt,
@@ -591,6 +717,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,
@@ -617,14 +744,45 @@ export const checkClaudeProviderStatus = Effect.fn("checkClaudeProviderStatus")(
? undefined
: formatClaudeOpus47UpgradeMessage(parsedVersion);
const capabilities = resolveCapabilities
? yield* resolveCapabilities(claudeSettings).pipe(Effect.orElseSucceed(() => undefined))
: undefined;
const slashCommands = capabilities?.slashCommands ?? [];
const slashCommands =
(resolveSlashCommands
? yield* resolveSlashCommands(claudeSettings.binaryPath).pipe(
Effect.orElseSucceed(() => undefined),
)
: undefined) ?? [];
const dedupedSlashCommands = dedupeSlashCommands(slashCommands);
if (!capabilities) {
// ── Auth check + subscription detection ────────────────────────────
const authProbe = yield* runClaudeCommand(["auth", "status"]).pipe(
Effect.timeoutOption(AUTH_PROBE_TIMEOUT_MS),
Effect.result,
);
// Determine subscription type from multiple sources (cheapest first):
// 1. `claude auth status` JSON output (may or may not contain it)
// 2. Cached SDK probe (spawns a Claude process on miss, reads
// `initializationResult()` for account metadata, then aborts
// immediately — no API tokens are consumed)
let subscriptionType: string | undefined;
let authMethod: string | undefined;
if (Result.isSuccess(authProbe) && Option.isSome(authProbe.success)) {
subscriptionType = extractSubscriptionTypeFromOutput(authProbe.success.value);
authMethod = extractClaudeAuthMethodFromOutput(authProbe.success.value);
}
if (!subscriptionType && resolveSubscriptionType) {
subscriptionType = yield* resolveSubscriptionType(claudeSettings.binaryPath);
}
// ── Handle auth results (same logic as before, adjusted models) ──
if (Result.isFailure(authProbe)) {
const error = authProbe.failure;
return buildServerProvider({
provider: PROVIDER,
presentation: CLAUDE_PRESENTATION,
enabled: claudeSettings.enabled,
checkedAt,
@@ -635,16 +793,36 @@ export const checkClaudeProviderStatus = Effect.fn("checkClaudeProviderStatus")(
version: parsedVersion,
status: "warning",
auth: { status: "unknown" },
message: "Could not verify Claude authentication status from initialization result.",
message:
error instanceof Error
? `Could not verify Claude authentication status: ${error.message}.`
: "Could not verify Claude authentication status.",
},
});
}
const authMetadata = claudeAuthMetadata({
subscriptionType: capabilities.subscriptionType,
authMethod: capabilities.tokenSource,
});
if (Option.isNone(authProbe.success)) {
return buildServerProvider({
provider: PROVIDER,
presentation: CLAUDE_PRESENTATION,
enabled: claudeSettings.enabled,
checkedAt,
models,
slashCommands: dedupedSlashCommands,
probe: {
installed: true,
version: parsedVersion,
status: "warning",
auth: { status: "unknown" },
message: "Could not verify Claude authentication status. Timed out while running command.",
},
});
}
const parsed = parseClaudeAuthStatusFromOutput(authProbe.success.value);
const authMetadata = claudeAuthMetadata({ subscriptionType, authMethod });
return buildServerProvider({
provider: PROVIDER,
presentation: CLAUDE_PRESENTATION,
enabled: claudeSettings.enabled,
checkedAt,
@@ -653,18 +831,21 @@ export const checkClaudeProviderStatus = Effect.fn("checkClaudeProviderStatus")(
probe: {
installed: true,
version: parsedVersion,
status: "ready",
status: parsed.status,
auth: {
status: "authenticated",
...(capabilities.email ? { email: capabilities.email } : {}),
...parsed.auth,
...(authMetadata ? authMetadata : {}),
},
...(opus47UpgradeMessage ? { message: opus47UpgradeMessage } : {}),
...(parsed.message
? { message: parsed.message }
: opus47UpgradeMessage
? { message: opus47UpgradeMessage }
: {}),
},
});
});
export const makePendingClaudeProvider = (claudeSettings: ClaudeSettings): ServerProviderDraft => {
const makePendingClaudeProvider = (claudeSettings: ClaudeSettings): ServerProvider => {
const checkedAt = new Date().toISOString();
const models = providerModelsFromSettings(
BUILT_IN_MODELS,
@@ -675,6 +856,7 @@ export const makePendingClaudeProvider = (claudeSettings: ClaudeSettings): Serve
if (!claudeSettings.enabled) {
return buildServerProvider({
provider: PROVIDER,
presentation: CLAUDE_PRESENTATION,
enabled: false,
checkedAt,
@@ -690,6 +872,7 @@ export const makePendingClaudeProvider = (claudeSettings: ClaudeSettings): Serve
}
return buildServerProvider({
provider: PROVIDER,
presentation: CLAUDE_PRESENTATION,
enabled: true,
checkedAt,
@@ -704,4 +887,43 @@ export const makePendingClaudeProvider = (claudeSettings: ClaudeSettings): Serve
});
};
export { probeClaudeCapabilities };
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,
});
}),
);
@@ -4,10 +4,7 @@ import os from "node:os";
import path from "node:path";
import {
ApprovalRequestId,
CodexSettings,
EventId,
ProviderDriverKind,
ProviderInstanceId,
ProviderItemId,
type ProviderApprovalDecision,
type ProviderEvent,
@@ -21,13 +18,13 @@ import { createModelSelection } from "@t3tools/shared/model";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { it, vi } from "@effect/vitest";
import { Context, Effect, Exit, Fiber, Layer, Option, Queue, Schema, Scope, Stream } from "effect";
import { Effect, Exit, Fiber, Layer, Option, Queue, Scope, Stream } from "effect";
import * as CodexErrors from "effect-codex-app-server/errors";
import { ServerConfig } from "../../config.ts";
import { ServerSettingsService } from "../../serverSettings.ts";
import { ProviderAdapterValidationError } from "../Errors.ts";
import type { CodexAdapterShape } from "../Services/CodexAdapter.ts";
import { CodexAdapter } from "../Services/CodexAdapter.ts";
import { ProviderSessionDirectory } from "../Services/ProviderSessionDirectory.ts";
import {
type CodexSessionRuntimeOptions,
@@ -35,12 +32,7 @@ import {
type CodexSessionRuntimeShape,
type CodexThreadSnapshot,
} from "./CodexSessionRuntime.ts";
import { makeCodexAdapter } from "./CodexAdapter.ts";
// Test-local service tag so the rest of the file can keep using `yield* CodexAdapter`.
class CodexAdapter extends Context.Service<CodexAdapter, CodexAdapterShape>()(
"test/CodexAdapter",
) {}
import { makeCodexAdapterLive } from "./CodexAdapter.ts";
const asThreadId = (value: string): ThreadId => ThreadId.make(value);
const asTurnId = (value: string): TurnId => TurnId.make(value);
@@ -53,7 +45,7 @@ class FakeCodexRuntime implements CodexSessionRuntimeShape {
public readonly startImpl = vi.fn(() =>
Promise.resolve({
provider: ProviderDriverKind.make("codex"),
provider: "codex" as const,
status: "ready" as const,
runtimeMode: this.options.runtimeMode,
threadId: this.options.threadId,
@@ -211,15 +203,7 @@ const providerSessionDirectoryTestLayer = Layer.succeed(ProviderSessionDirectory
const validationRuntimeFactory = makeRuntimeFactory();
const validationLayer = it.layer(
Layer.effect(
CodexAdapter,
Effect.gen(function* () {
const codexConfig = Schema.decodeSync(CodexSettings)({});
return yield* makeCodexAdapter(codexConfig, {
makeRuntime: validationRuntimeFactory.factory,
});
}),
).pipe(
makeCodexAdapterLive({ makeRuntime: validationRuntimeFactory.factory }).pipe(
Layer.provideMerge(ServerConfig.layerTest(process.cwd(), process.cwd())),
Layer.provideMerge(ServerSettingsService.layerTest()),
Layer.provideMerge(providerSessionDirectoryTestLayer),
@@ -233,7 +217,7 @@ validationLayer("CodexAdapterLive validation", (it) => {
const adapter = yield* CodexAdapter;
const result = yield* adapter
.startSession({
provider: ProviderDriverKind.make("claudeAgent"),
provider: "claudeAgent",
threadId: asThreadId("thread-1"),
runtimeMode: "full-access",
})
@@ -243,7 +227,7 @@ validationLayer("CodexAdapterLive validation", (it) => {
assert.deepStrictEqual(
result.failure,
new ProviderAdapterValidationError({
provider: ProviderDriverKind.make("codex"),
provider: "codex",
operation: "startSession",
issue: "Expected provider 'codex' but received 'claudeAgent'.",
}),
@@ -257,9 +241,9 @@ validationLayer("CodexAdapterLive validation", (it) => {
const adapter = yield* CodexAdapter;
yield* adapter.startSession({
provider: ProviderDriverKind.make("codex"),
provider: "codex",
threadId: asThreadId("thread-1"),
modelSelection: createModelSelection(ProviderInstanceId.make("codex"), "gpt-5.3-codex", [
modelSelection: createModelSelection("codex", "gpt-5.3-codex", [
{ id: "fastMode", value: true },
]),
runtimeMode: "full-access",
@@ -269,7 +253,6 @@ validationLayer("CodexAdapterLive validation", (it) => {
binaryPath: "codex",
cwd: process.cwd(),
model: "gpt-5.3-codex",
providerInstanceId: ProviderInstanceId.make("codex"),
serviceTier: "fast",
threadId: asThreadId("thread-1"),
runtimeMode: "full-access",
@@ -280,15 +263,7 @@ validationLayer("CodexAdapterLive validation", (it) => {
const sessionRuntimeFactory = makeRuntimeFactory();
const sessionErrorLayer = it.layer(
Layer.effect(
CodexAdapter,
Effect.gen(function* () {
const codexConfig = Schema.decodeSync(CodexSettings)({});
return yield* makeCodexAdapter(codexConfig, {
makeRuntime: sessionRuntimeFactory.factory,
});
}),
).pipe(
makeCodexAdapterLive({ makeRuntime: sessionRuntimeFactory.factory }).pipe(
Layer.provideMerge(ServerConfig.layerTest(process.cwd(), process.cwd())),
Layer.provideMerge(ServerSettingsService.layerTest()),
Layer.provideMerge(providerSessionDirectoryTestLayer),
@@ -319,7 +294,7 @@ sessionErrorLayer("CodexAdapterLive session errors", (it) => {
Effect.gen(function* () {
const adapter = yield* CodexAdapter;
yield* adapter.startSession({
provider: ProviderDriverKind.make("codex"),
provider: "codex",
threadId: asThreadId("sess-missing"),
runtimeMode: "full-access",
});
@@ -331,7 +306,7 @@ sessionErrorLayer("CodexAdapterLive session errors", (it) => {
adapter.sendTurn({
threadId: asThreadId("sess-missing"),
input: "hello",
modelSelection: createModelSelection(ProviderInstanceId.make("codex"), "gpt-5.3-codex", [
modelSelection: createModelSelection("codex", "gpt-5.3-codex", [
{ id: "reasoningEffort", value: "high" },
{ id: "fastMode", value: true },
]),
@@ -347,74 +322,11 @@ sessionErrorLayer("CodexAdapterLive session errors", (it) => {
});
}),
);
it.effect("maps codex model options for the adapter's bound custom instance id", () => {
const customInstanceId = ProviderInstanceId.make("codex_personal");
const customRuntimeFactory = makeRuntimeFactory();
const customLayer = Layer.effect(
CodexAdapter,
Effect.gen(function* () {
const codexConfig = Schema.decodeSync(CodexSettings)({});
return yield* makeCodexAdapter(codexConfig, {
instanceId: customInstanceId,
makeRuntime: customRuntimeFactory.factory,
});
}),
).pipe(
Layer.provideMerge(ServerConfig.layerTest(process.cwd(), process.cwd())),
Layer.provideMerge(ServerSettingsService.layerTest()),
Layer.provideMerge(providerSessionDirectoryTestLayer),
Layer.provideMerge(NodeServices.layer),
);
return Effect.gen(function* () {
const adapter = yield* CodexAdapter;
yield* adapter.startSession({
provider: ProviderDriverKind.make("codex"),
threadId: asThreadId("sess-custom-instance"),
runtimeMode: "full-access",
});
const runtime = customRuntimeFactory.lastRuntime;
assert.ok(runtime);
runtime.sendTurnImpl.mockClear();
yield* Effect.ignore(
adapter.sendTurn({
threadId: asThreadId("sess-custom-instance"),
input: "hello",
modelSelection: createModelSelection(
ProviderInstanceId.make("codex_personal"),
"gpt-5.3-codex",
[
{ id: "reasoningEffort", value: "high" },
{ id: "fastMode", value: true },
],
),
attachments: [],
}),
);
assert.deepStrictEqual(runtime.sendTurnImpl.mock.calls[0]?.[0], {
input: "hello",
model: "gpt-5.3-codex",
effort: "high",
serviceTier: "fast",
});
}).pipe(Effect.provide(customLayer));
});
});
const lifecycleRuntimeFactory = makeRuntimeFactory();
const lifecycleLayer = it.layer(
Layer.effect(
CodexAdapter,
Effect.gen(function* () {
const codexConfig = Schema.decodeSync(CodexSettings)({});
return yield* makeCodexAdapter(codexConfig, {
makeRuntime: lifecycleRuntimeFactory.factory,
});
}),
).pipe(
makeCodexAdapterLive({ makeRuntime: lifecycleRuntimeFactory.factory }).pipe(
Layer.provideMerge(ServerConfig.layerTest(process.cwd(), process.cwd())),
Layer.provideMerge(ServerSettingsService.layerTest()),
Layer.provideMerge(providerSessionDirectoryTestLayer),
@@ -426,7 +338,7 @@ function startLifecycleRuntime() {
return Effect.gen(function* () {
const adapter = yield* CodexAdapter;
yield* adapter.startSession({
provider: ProviderDriverKind.make("codex"),
provider: "codex",
threadId: asThreadId("thread-1"),
runtimeMode: "full-access",
});
@@ -445,7 +357,7 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => {
const event: ProviderEvent = {
id: asEventId("evt-msg-complete"),
kind: "notification",
provider: ProviderDriverKind.make("codex"),
provider: "codex",
createdAt: new Date().toISOString(),
method: "item/completed",
threadId: asThreadId("thread-1"),
@@ -487,7 +399,7 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => {
const event: ProviderEvent = {
id: asEventId("evt-plan-complete"),
kind: "notification",
provider: ProviderDriverKind.make("codex"),
provider: "codex",
createdAt: new Date().toISOString(),
method: "item/completed",
threadId: asThreadId("thread-1"),
@@ -528,7 +440,7 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => {
yield* runtime.emit({
id: asEventId("evt-plan-delta"),
kind: "notification",
provider: ProviderDriverKind.make("codex"),
provider: "codex",
createdAt: new Date().toISOString(),
method: "item/plan/delta",
threadId: asThreadId("thread-1"),
@@ -565,7 +477,7 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => {
const event: ProviderEvent = {
id: asEventId("evt-session-closed"),
kind: "session",
provider: ProviderDriverKind.make("codex"),
provider: "codex",
threadId: asThreadId("thread-1"),
createdAt: new Date().toISOString(),
method: "session/closed",
@@ -596,7 +508,7 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => {
yield* runtime.emit({
id: asEventId("evt-retryable-error"),
kind: "notification",
provider: ProviderDriverKind.make("codex"),
provider: "codex",
threadId: asThreadId("thread-1"),
createdAt: new Date().toISOString(),
method: "error",
@@ -634,7 +546,7 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => {
yield* runtime.emit({
id: asEventId("evt-process-stderr"),
kind: "notification",
provider: ProviderDriverKind.make("codex"),
provider: "codex",
threadId: asThreadId("thread-1"),
createdAt: new Date().toISOString(),
method: "process/stderr",
@@ -668,7 +580,7 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => {
yield* runtime.emit({
id: asEventId("evt-process-stderr-websocket"),
kind: "notification",
provider: ProviderDriverKind.make("codex"),
provider: "codex",
threadId: asThreadId("thread-1"),
createdAt: new Date().toISOString(),
method: "process/stderr",
@@ -704,7 +616,7 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => {
const event: ProviderEvent = {
id: asEventId("evt-request-resolved"),
kind: "notification",
provider: ProviderDriverKind.make("codex"),
provider: "codex",
threadId: asThreadId("thread-1"),
createdAt: new Date().toISOString(),
method: "serverRequest/resolved",
@@ -739,7 +651,7 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => {
const event: ProviderEvent = {
id: asEventId("evt-file-read-request-resolved"),
kind: "notification",
provider: ProviderDriverKind.make("codex"),
provider: "codex",
threadId: asThreadId("thread-1"),
createdAt: new Date().toISOString(),
method: "serverRequest/resolved",
@@ -774,7 +686,7 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => {
const event: ProviderEvent = {
id: asEventId("evt-user-input-empty"),
kind: "notification",
provider: ProviderDriverKind.make("codex"),
provider: "codex",
threadId: asThreadId("thread-1"),
createdAt: new Date().toISOString(),
method: "item/tool/requestUserInput/answered",
@@ -814,7 +726,7 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => {
const event: ProviderEvent = {
id: asEventId("evt-windows-sandbox-failed"),
kind: "notification",
provider: ProviderDriverKind.make("codex"),
provider: "codex",
threadId: asThreadId("thread-1"),
createdAt: new Date().toISOString(),
method: "windowsSandbox/setupCompleted",
@@ -859,7 +771,7 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => {
yield* runtime.emit({
id: asEventId("evt-user-input-requested"),
kind: "request",
provider: ProviderDriverKind.make("codex"),
provider: "codex",
threadId: asThreadId("thread-1"),
createdAt: new Date().toISOString(),
method: "item/tool/requestUserInput",
@@ -886,7 +798,7 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => {
yield* runtime.emit({
id: asEventId("evt-user-input-resolved"),
kind: "notification",
provider: ProviderDriverKind.make("codex"),
provider: "codex",
threadId: asThreadId("thread-1"),
createdAt: new Date().toISOString(),
method: "item/tool/requestUserInput/answered",
@@ -926,7 +838,7 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => {
yield* runtime.emit({
id: asEventId("evt-codex-thread-token-usage-updated"),
kind: "notification",
provider: ProviderDriverKind.make("codex"),
provider: "codex",
threadId: asThreadId("thread-1"),
turnId: asTurnId("turn-1"),
createdAt: new Date().toISOString(),
@@ -985,15 +897,7 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => {
const scopedLifecycleRuntimeFactory = makeScopedRuntimeFactory();
const scopedLifecycleLayer = it.layer(
Layer.effect(
CodexAdapter,
Effect.gen(function* () {
const codexConfig = Schema.decodeSync(CodexSettings)({});
return yield* makeCodexAdapter(codexConfig, {
makeRuntime: scopedLifecycleRuntimeFactory.factory,
});
}),
).pipe(
makeCodexAdapterLive({ makeRuntime: scopedLifecycleRuntimeFactory.factory }).pipe(
Layer.provideMerge(ServerConfig.layerTest(process.cwd(), process.cwd())),
Layer.provideMerge(ServerSettingsService.layerTest()),
Layer.provideMerge(providerSessionDirectoryTestLayer),
@@ -1008,7 +912,7 @@ scopedLifecycleLayer("CodexAdapterLive scoped lifecycle", (it) => {
const adapter = yield* CodexAdapter;
yield* adapter.startSession({
provider: ProviderDriverKind.make("codex"),
provider: "codex",
threadId: asThreadId("thread-stop"),
runtimeMode: "full-access",
});
@@ -1029,15 +933,7 @@ scopedLifecycleLayer("CodexAdapterLive scoped lifecycle", (it) => {
const scopedFailureRuntimeFactory = makeScopedRuntimeFactory({ failConstruction: true });
const scopedFailureLayer = it.layer(
Layer.effect(
CodexAdapter,
Effect.gen(function* () {
const codexConfig = Schema.decodeSync(CodexSettings)({});
return yield* makeCodexAdapter(codexConfig, {
makeRuntime: scopedFailureRuntimeFactory.factory,
});
}),
).pipe(
makeCodexAdapterLive({ makeRuntime: scopedFailureRuntimeFactory.factory }).pipe(
Layer.provideMerge(ServerConfig.layerTest(process.cwd(), process.cwd())),
Layer.provideMerge(ServerSettingsService.layerTest()),
Layer.provideMerge(providerSessionDirectoryTestLayer),
@@ -1053,7 +949,7 @@ scopedFailureLayer("CodexAdapterLive scoped startup failure", (it) => {
const result = yield* adapter
.startSession({
provider: ProviderDriverKind.make("codex"),
provider: "codex",
threadId: asThreadId("thread-fail"),
runtimeMode: "full-access",
})
@@ -1078,16 +974,10 @@ it.effect("flushes managed native logs when the adapter layer shuts down", () =>
let scopeClosed = false;
try {
const layer = Layer.effect(
CodexAdapter,
Effect.gen(function* () {
const codexConfig = Schema.decodeSync(CodexSettings)({});
return yield* makeCodexAdapter(codexConfig, {
makeRuntime: runtimeFactory.factory,
nativeEventLogPath: basePath,
});
}),
).pipe(
const layer = makeCodexAdapterLive({
makeRuntime: runtimeFactory.factory,
nativeEventLogPath: basePath,
}).pipe(
Layer.provideMerge(ServerConfig.layerTest(process.cwd(), process.cwd())),
Layer.provideMerge(ServerSettingsService.layerTest()),
Layer.provideMerge(providerSessionDirectoryTestLayer),
@@ -1097,7 +987,7 @@ it.effect("flushes managed native logs when the adapter layer shuts down", () =>
const adapter = yield* Effect.service(CodexAdapter).pipe(Effect.provide(context));
yield* adapter.startSession({
provider: ProviderDriverKind.make("codex"),
provider: "codex",
threadId: asThreadId("thread-logger"),
runtimeMode: "full-access",
});
@@ -1109,7 +999,7 @@ it.effect("flushes managed native logs when the adapter layer shuts down", () =>
yield* runtime.emit({
id: asEventId("evt-native-log"),
kind: "notification",
provider: ProviderDriverKind.make("codex"),
provider: "codex",
threadId: asThreadId("thread-logger"),
createdAt: new Date().toISOString(),
method: "process/stderr",
+30 -35
View File
@@ -10,10 +10,7 @@
import {
type CanonicalItemType,
type CanonicalRequestType,
type CodexSettings,
ProviderDriverKind,
type ProviderEvent,
ProviderInstanceId,
type ProviderRuntimeEvent,
type ProviderRequestKind,
type ThreadTokenUsageSnapshot,
@@ -24,7 +21,7 @@ import {
ThreadId,
ProviderSendTurnInput,
} from "@t3tools/contracts";
import { Effect, Exit, Fiber, FileSystem, Queue, Schema, Scope, Stream } from "effect";
import { Effect, Exit, Fiber, FileSystem, Layer, Queue, Schema, Scope, Stream } from "effect";
import { ChildProcessSpawner } from "effect/unstable/process";
import * as CodexErrors from "effect-codex-app-server/errors";
import * as EffectCodexSchema from "effect-codex-app-server/schema";
@@ -42,9 +39,10 @@ import {
ProviderAdapterValidationError,
type ProviderAdapterError,
} from "../Errors.ts";
import { type CodexAdapterShape } from "../Services/CodexAdapter.ts";
import { CodexAdapter, type CodexAdapterShape } from "../Services/CodexAdapter.ts";
import { resolveAttachmentPath } from "../../attachmentStore.ts";
import { ServerConfig } from "../../config.ts";
import { ServerSettingsService } from "../../serverSettings.ts";
import {
CodexResumeCursorSchema,
CodexSessionRuntimeThreadIdMissingError,
@@ -55,11 +53,9 @@ import {
} from "./CodexSessionRuntime.ts";
import { type EventNdjsonLogger, makeEventNdjsonLogger } from "./EventNdjsonLogger.ts";
const PROVIDER = ProviderDriverKind.make("codex");
const PROVIDER = "codex" as const;
export interface CodexAdapterLiveOptions {
readonly instanceId?: ProviderInstanceId;
readonly environment?: NodeJS.ProcessEnv;
readonly makeRuntime?: (
options: CodexSessionRuntimeOptions,
) => Effect.Effect<
@@ -1322,20 +1318,9 @@ function mapToRuntimeEvents(
return [];
}
/**
* Build a Codex provider adapter bound to a specific `CodexSettings` payload.
*
* The adapter is a captured closure over `codexConfig` — the `binaryPath` and
* `homePath` are read from that payload, not from `ServerSettingsService`.
* This is what makes multi-instance routing possible: each `ProviderInstance`
* in the registry owns its own closure with its own config, so two Codex
* instances with different `homePath`s cannot step on each other.
*/
export const makeCodexAdapter = Effect.fn("makeCodexAdapter")(function* (
codexConfig: CodexSettings,
const makeCodexAdapter = Effect.fn("makeCodexAdapter")(function* (
options?: CodexAdapterLiveOptions,
) {
const boundInstanceId = options?.instanceId ?? ProviderInstanceId.make("codex");
const fileSystem = yield* FileSystem.FileSystem;
const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
const serverConfig = yield* Effect.service(ServerConfig);
@@ -1348,6 +1333,7 @@ export const makeCodexAdapter = Effect.fn("makeCodexAdapter")(function* (
: undefined);
const managedNativeEventLogger =
options?.nativeEventLogger === undefined ? nativeEventLogger : undefined;
const serverSettingsService = yield* ServerSettingsService;
const runtimeEventQueue = yield* Queue.unbounded<ProviderRuntimeEvent>();
const sessions = new Map<ThreadId, CodexAdapterSessionContext>();
@@ -1367,21 +1353,31 @@ export const makeCodexAdapter = Effect.fn("makeCodexAdapter")(function* (
yield* Effect.suspend(() => stopSessionInternal(existing));
}
const codexSettings = yield* serverSettingsService.getSettings.pipe(
Effect.map((settings) => settings.providers.codex),
Effect.mapError(
(error) =>
new ProviderAdapterProcessError({
provider: PROVIDER,
threadId: input.threadId,
detail: error.message,
cause: error,
}),
),
);
const runtimeInput: CodexSessionRuntimeOptions = {
threadId: input.threadId,
providerInstanceId: boundInstanceId,
cwd: input.cwd ?? process.cwd(),
binaryPath: codexConfig.binaryPath,
...(options?.environment ? { environment: options.environment } : {}),
...(codexConfig.homePath ? { homePath: codexConfig.homePath } : {}),
binaryPath: codexSettings.binaryPath,
...(codexSettings.homePath ? { homePath: codexSettings.homePath } : {}),
...(Schema.is(CodexResumeCursorSchema)(input.resumeCursor)
? { resumeCursor: input.resumeCursor }
: {}),
runtimeMode: input.runtimeMode,
...(input.modelSelection?.instanceId === boundInstanceId
...(input.modelSelection?.provider === "codex"
? { model: input.modelSelection.model }
: {}),
...(input.modelSelection?.instanceId === boundInstanceId &&
...(input.modelSelection?.provider === "codex" &&
getModelSelectionBooleanOptionValue(input.modelSelection, "fastMode") === true
? { serviceTier: "fast" }
: {}),
@@ -1496,17 +1492,17 @@ export const makeCodexAdapter = Effect.fn("makeCodexAdapter")(function* (
const session = yield* requireSession(input.threadId);
const reasoningEffort =
input.modelSelection?.instanceId === boundInstanceId
input.modelSelection?.provider === "codex"
? getModelSelectionStringOptionValue(input.modelSelection, "reasoningEffort")
: undefined;
const fastMode =
input.modelSelection?.instanceId === boundInstanceId
input.modelSelection?.provider === "codex"
? getModelSelectionBooleanOptionValue(input.modelSelection, "fastMode")
: undefined;
return yield* session.runtime
.sendTurn({
...(input.input !== undefined ? { input: input.input } : {}),
...(input.modelSelection?.instanceId === boundInstanceId
...(input.modelSelection?.provider === "codex"
? { model: input.modelSelection.model }
: {}),
...(reasoningEffort
@@ -1680,9 +1676,8 @@ export const makeCodexAdapter = Effect.fn("makeCodexAdapter")(function* (
} satisfies CodexAdapterShape;
});
// NOTE: the old `CodexAdapterLive` / `makeCodexAdapterLive` singleton Layer
// exports have been removed as part of the per-instance-driver refactor.
// `makeCodexAdapter(codexConfig, options?)` is now invoked directly by
// `CodexDriver.create()` for each configured instance; downstream consumers
// (server bootstrap, integration harness, this module's tests) will be
// migrated to the registry in a follow-up pass.
export const CodexAdapterLive = Layer.effect(CodexAdapter, makeCodexAdapter());
export function makeCodexAdapterLive(options?: CodexAdapterLiveOptions) {
return Layer.effect(CodexAdapter, makeCodexAdapter(options));
}
@@ -1,4 +1,15 @@
import { DateTime, Duration, Effect, Layer, Option, Result, Schema, Types } from "effect";
import {
DateTime,
Duration,
Effect,
Equal,
Layer,
Option,
Result,
Schema,
Stream,
Types,
} from "effect";
import { ChildProcessSpawner } from "effect/unstable/process";
import * as CodexClient from "effect-codex-app-server/client";
import * as CodexSchema from "effect-codex-app-server/schema";
@@ -16,11 +27,14 @@ import { ServerSettingsError } from "@t3tools/contracts";
import { createModelCapabilities } from "@t3tools/shared/model";
import { buildServerProvider, type ServerProviderDraft } from "../providerSnapshot.ts";
import { makeManagedServerProvider } from "../makeManagedServerProvider.ts";
import { buildServerProvider } from "../providerSnapshot.ts";
import { CodexProvider } from "../Services/CodexProvider.ts";
import { expandHomePath } from "../../pathExpansion.ts";
import { scopedSafeTeardown } from "./scopedSafeTeardown.ts";
import { ServerSettingsService } from "../../serverSettings.ts";
import packageJson from "../../../package.json" with { type: "json" };
const PROVIDER = "codex" as const;
const PROVIDER_PROBE_TIMEOUT_MS = 8_000;
const CODEX_PRESENTATION = {
displayName: "Codex",
@@ -76,11 +90,6 @@ function codexAccountAuthLabel(account: CodexSchema.V2GetAccountResponse["accoun
}
}
function codexAccountEmail(account: CodexSchema.V2GetAccountResponse["account"]) {
if (!account || account.type !== "chatgpt") return undefined;
return account.email;
}
function mapCodexModelCapabilities(
model: CodexSchema.V2ModelListResponse__Model,
): ModelCapabilities {
@@ -236,33 +245,18 @@ export function buildCodexInitializeParams(): CodexSchema.V1InitializeParams {
};
}
// Wrapped with `scopedSafeTeardown("codex-probe")` rather than the usual
// `Effect.scoped` so that a defect from the `Layer.build` finalizer (e.g.
// `ChildProcess.kill` throwing because the `codex app-server` child exited
// early) cannot override a successful probe body. Without this guard the
// defect bubbles past `Effect.result` in `checkCodexProviderStatus`, dies
// `refreshOneSource`, and `providersRef` never receives the snapshot.
const probeCodexAppServerProvider = Effect.fn("probeCodexAppServerProvider")(function* (input: {
readonly binaryPath: string;
readonly homePath?: string;
readonly cwd: string;
readonly customModels?: ReadonlyArray<string>;
readonly environment?: NodeJS.ProcessEnv;
}) {
// `~` is not shell-expanded when env vars are set via `child_process.spawn`,
// so `CODEX_HOME=~/.codex_work` would reach codex verbatim and trip
// "CODEX_HOME points to '~/.codex_work', but that path does not exist".
// Expand here for parity with `CodexTextGeneration`/`CodexSessionRuntime`.
const resolvedHomePath = input.homePath ? expandHomePath(input.homePath) : undefined;
const clientContext = yield* Layer.build(
CodexClient.layerCommand({
command: input.binaryPath,
args: ["app-server"],
cwd: input.cwd,
env: {
...(input.environment ?? process.env),
...(resolvedHomePath ? { CODEX_HOME: resolvedHomePath } : {}),
},
...(input.homePath ? { env: { CODEX_HOME: expandHomePath(input.homePath) } } : {}),
}),
);
const client = yield* Effect.service(CodexClient.CodexAppServerClient).pipe(
@@ -311,7 +305,7 @@ const probeCodexAppServerProvider = Effect.fn("probeCodexAppServerProvider")(fun
models: appendCustomCodexModels(models, input.customModels ?? []),
skills: parseCodexSkillsListResponse(skillsResponse, input.cwd),
} satisfies CodexAppServerProviderSnapshot;
}, scopedSafeTeardown("codex-probe"));
}, Effect.scoped);
const emptyCodexModelsFromSettings = (codexSettings: CodexSettings): ServerProvider["models"] =>
codexSettings.customModels
@@ -324,12 +318,13 @@ const emptyCodexModelsFromSettings = (codexSettings: CodexSettings): ServerProvi
capabilities: null,
}));
const makePendingCodexProvider = (codexSettings: CodexSettings): ServerProviderDraft => {
const makePendingCodexProvider = (codexSettings: CodexSettings): ServerProvider => {
const checkedAt = new Date().toISOString();
const models = emptyCodexModelsFromSettings(codexSettings);
if (!codexSettings.enabled) {
return buildServerProvider({
provider: PROVIDER,
presentation: CODEX_PRESENTATION,
enabled: false,
checkedAt,
@@ -346,6 +341,7 @@ const makePendingCodexProvider = (codexSettings: CodexSettings): ServerProviderD
}
return buildServerProvider({
provider: PROVIDER,
presentation: CODEX_PRESENTATION,
enabled: true,
checkedAt,
@@ -367,12 +363,10 @@ function accountProbeStatus(account: CodexAppServerProviderSnapshot["account"]):
readonly message?: string;
} {
const authLabel = codexAccountAuthLabel(account.account);
const authEmail = codexAccountEmail(account.account);
const auth = {
status: account.account ? ("authenticated" as const) : ("unknown" as const),
...(account.account?.type ? { type: account.account?.type } : {}),
...(authLabel ? { label: authLabel } : {}),
...(authEmail ? { email: authEmail } : {}),
} satisfies ServerProvider["auth"];
if (account.account) {
@@ -391,29 +385,31 @@ function accountProbeStatus(account: CodexAppServerProviderSnapshot["account"]):
}
export const checkCodexProviderStatus = Effect.fn("checkCodexProviderStatus")(function* (
codexSettings: CodexSettings,
probe: (input: {
readonly binaryPath: string;
readonly homePath?: string;
readonly cwd: string;
readonly customModels: ReadonlyArray<string>;
readonly environment?: NodeJS.ProcessEnv;
}) => Effect.Effect<
CodexAppServerProviderSnapshot,
CodexErrors.CodexAppServerError,
ChildProcessSpawner.ChildProcessSpawner
> = probeCodexAppServerProvider,
environment: NodeJS.ProcessEnv = process.env,
): Effect.fn.Return<
ServerProviderDraft,
ServerProvider,
ServerSettingsError,
ChildProcessSpawner.ChildProcessSpawner
ServerSettingsService | ChildProcessSpawner.ChildProcessSpawner
> {
const codexSettings = yield* Effect.service(ServerSettingsService).pipe(
Effect.flatMap((service) => service.getSettings),
Effect.map((settings) => settings.providers.codex),
);
const checkedAt = DateTime.formatIso(yield* DateTime.now);
const emptyModels = emptyCodexModelsFromSettings(codexSettings);
if (!codexSettings.enabled) {
return buildServerProvider({
provider: PROVIDER,
presentation: CODEX_PRESENTATION,
enabled: false,
checkedAt,
@@ -434,13 +430,13 @@ export const checkCodexProviderStatus = Effect.fn("checkCodexProviderStatus")(fu
homePath: codexSettings.homePath,
cwd: process.cwd(),
customModels: codexSettings.customModels,
environment,
}).pipe(Effect.timeoutOption(Duration.millis(PROVIDER_PROBE_TIMEOUT_MS)), Effect.result);
if (Result.isFailure(probeResult)) {
const error = probeResult.failure;
const installed = !Schema.is(CodexErrors.CodexAppServerSpawnError)(error);
return buildServerProvider({
provider: PROVIDER,
presentation: CODEX_PRESENTATION,
enabled: codexSettings.enabled,
checkedAt,
@@ -460,6 +456,7 @@ export const checkCodexProviderStatus = Effect.fn("checkCodexProviderStatus")(fu
if (Option.isNone(probeResult.success)) {
return buildServerProvider({
provider: PROVIDER,
presentation: CODEX_PRESENTATION,
enabled: codexSettings.enabled,
checkedAt,
@@ -479,6 +476,7 @@ export const checkCodexProviderStatus = Effect.fn("checkCodexProviderStatus")(fu
const accountStatus = accountProbeStatus(snapshot.account);
return buildServerProvider({
provider: PROVIDER,
presentation: CODEX_PRESENTATION,
enabled: codexSettings.enabled,
checkedAt,
@@ -494,11 +492,28 @@ export const checkCodexProviderStatus = Effect.fn("checkCodexProviderStatus")(fu
});
});
// NOTE: the singleton `CodexProviderLive` Layer has been removed as part of
// the per-instance-driver refactor. `CodexDriver.create()` builds a managed
// snapshot per instance (each with its own `CodexSettings`) and hands the
// resulting `ServerProviderShape` back as `ProviderInstance.snapshot`.
//
// The `makePendingCodexProvider` and `checkCodexProviderStatus` helpers are
// re-exported for use by `CodexDriver`.
export { makePendingCodexProvider };
export const CodexProviderLive = Layer.effect(
CodexProvider,
Effect.gen(function* () {
const serverSettings = yield* ServerSettingsService;
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
const checkProvider = checkCodexProviderStatus().pipe(
Effect.provideService(ServerSettingsService, serverSettings),
Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
);
return yield* makeManagedServerProvider<CodexSettings>({
getSettings: serverSettings.getSettings.pipe(
Effect.map((settings) => settings.providers.codex),
Effect.orDie,
),
streamSettings: serverSettings.streamChanges.pipe(
Stream.map((settings) => settings.providers.codex),
),
haveSettingsChanged: (previous, next) => !Equal.equals(previous, next),
initialSnapshot: makePendingCodexProvider,
checkProvider,
refreshInterval: Duration.minutes(5),
});
}),
);
@@ -1,10 +1,10 @@
import { randomUUID } from "node:crypto";
import {
ApprovalRequestId,
DEFAULT_MODEL,
DEFAULT_MODEL_BY_PROVIDER,
EventId,
ProviderDriverKind,
ProviderItemId,
type ProviderInstanceId,
type ProviderApprovalDecision,
type ProviderEvent,
type ProviderInteractionMode,
@@ -17,7 +17,7 @@ import {
TurnId,
} from "@t3tools/contracts";
import { normalizeModelSlug } from "@t3tools/shared/model";
import { Deferred, Effect, Exit, Layer, Queue, Ref, Scope, Random, Schema, Stream } from "effect";
import { Deferred, Effect, Exit, Layer, Queue, Ref, Scope, Schema, Stream } from "effect";
import * as SchemaIssue from "effect/SchemaIssue";
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
import * as CodexClient from "effect-codex-app-server/client";
@@ -26,13 +26,13 @@ import * as CodexRpc from "effect-codex-app-server/rpc";
import * as EffectCodexSchema from "effect-codex-app-server/schema";
import { buildCodexInitializeParams } from "./CodexProvider.ts";
import { expandHomePath } from "../../pathExpansion.ts";
import {
CODEX_DEFAULT_MODE_DEVELOPER_INSTRUCTIONS,
CODEX_PLAN_MODE_DEVELOPER_INSTRUCTIONS,
} from "../CodexDeveloperInstructions.ts";
import { expandHomePath } from "../../pathExpansion.ts";
const PROVIDER = ProviderDriverKind.make("codex");
const PROVIDER = "codex" as const;
const ANSI_ESCAPE_CHAR = String.fromCharCode(27);
const ANSI_ESCAPE_REGEX = new RegExp(`${ANSI_ESCAPE_CHAR}\\[[0-9;]*m`, "g");
@@ -76,10 +76,8 @@ type CodexThreadItem =
export interface CodexSessionRuntimeOptions {
readonly threadId: ThreadId;
readonly providerInstanceId?: ProviderInstanceId;
readonly binaryPath: string;
readonly homePath?: string;
readonly environment?: NodeJS.ProcessEnv;
readonly cwd: string;
readonly runtimeMode: RuntimeMode;
readonly model?: string;
@@ -89,10 +87,7 @@ export interface CodexSessionRuntimeOptions {
export interface CodexSessionRuntimeSendTurnInput {
readonly input?: string;
readonly attachments?: ReadonlyArray<{
readonly type: "image";
readonly url: string;
}>;
readonly attachments?: ReadonlyArray<{ readonly type: "image"; readonly url: string }>;
readonly model?: string;
readonly serviceTier?: EffectCodexSchema.V2TurnStartParams__ServiceTier | undefined;
readonly effort?: EffectCodexSchema.V2TurnStartParams__ReasoningEffort | undefined;
@@ -308,7 +303,7 @@ function buildCodexCollaborationMode(input: {
if (input.interactionMode === undefined) {
return undefined;
}
const model = normalizeCodexModelSlug(input.model) ?? DEFAULT_MODEL;
const model = normalizeCodexModelSlug(input.model) ?? DEFAULT_MODEL_BY_PROVIDER.codex;
return {
mode: input.interactionMode,
settings: {
@@ -326,10 +321,7 @@ export function buildTurnStartParams(input: {
readonly threadId: string;
readonly runtimeMode: RuntimeMode;
readonly prompt?: string;
readonly attachments?: ReadonlyArray<{
readonly type: "image";
readonly url: string;
}>;
readonly attachments?: ReadonlyArray<{ readonly type: "image"; readonly url: string }>;
readonly model?: string;
readonly serviceTier?: EffectCodexSchema.V2TurnStartParams__ServiceTier;
readonly effort?: EffectCodexSchema.V2TurnStartParams__ReasoningEffort;
@@ -688,19 +680,13 @@ export const makeCodexSessionRuntime = (
const collabReceiverTurnsRef = yield* Ref.make(new Map<string, TurnId>());
const closedRef = yield* Ref.make(false);
// `~` is not shell-expanded when env vars are set via
// `child_process.spawn`; `expandHomePath` lets a configured
// `CODEX_HOME=~/.codex_work` reach codex as an absolute path.
const resolvedHomePath = options.homePath ? expandHomePath(options.homePath) : undefined;
const env = {
...(options.environment ?? process.env),
...(resolvedHomePath ? { CODEX_HOME: resolvedHomePath } : {}),
};
const child = yield* spawner
.spawn(
ChildProcess.make(options.binaryPath, ["app-server"], {
cwd: options.cwd,
env,
...(options.homePath
? { env: { ...process.env, CODEX_HOME: expandHomePath(options.homePath) } }
: {}),
shell: process.platform === "win32",
}),
)
@@ -726,7 +712,6 @@ export const makeCodexSessionRuntime = (
const initialSession = {
provider: PROVIDER,
...(options.providerInstanceId ? { providerInstanceId: options.providerInstanceId } : {}),
status: "connecting",
runtimeMode: options.runtimeMode,
cwd: options.cwd,
@@ -740,15 +725,13 @@ export const makeCodexSessionRuntime = (
const offerEvent = (event: ProviderEvent) => Queue.offer(events, event).pipe(Effect.asVoid);
const emitEvent = (event: Omit<ProviderEvent, "id" | "provider" | "createdAt">) =>
Effect.flatMap(Random.nextUUIDv4, (id) =>
offerEvent({
id: EventId.make(id),
provider: PROVIDER,
...(options.providerInstanceId ? { providerInstanceId: options.providerInstanceId } : {}),
createdAt: new Date().toISOString(),
...event,
}),
);
offerEvent({
id: EventId.make(randomUUID()),
provider: PROVIDER,
createdAt: new Date().toISOString(),
...event,
});
const emitSessionEvent = (method: string, message: string) =>
emitEvent({
kind: "session",
@@ -908,7 +891,7 @@ export const makeCodexSessionRuntime = (
yield* client.handleServerRequest("item/commandExecution/requestApproval", (payload) =>
Effect.gen(function* () {
const requestId = ApprovalRequestId.make(yield* Random.nextUUIDv4);
const requestId = ApprovalRequestId.make(randomUUID());
const turnId = TurnId.make(payload.turnId);
const itemId = ProviderItemId.make(payload.itemId);
const decision = yield* Deferred.make<ProviderApprovalDecision>();
@@ -964,7 +947,7 @@ export const makeCodexSessionRuntime = (
yield* client.handleServerRequest("item/fileChange/requestApproval", (payload) =>
Effect.gen(function* () {
const requestId = ApprovalRequestId.make(yield* Random.nextUUIDv4);
const requestId = ApprovalRequestId.make(randomUUID());
const turnId = TurnId.make(payload.turnId);
const itemId = ProviderItemId.make(payload.itemId);
const decision = yield* Deferred.make<ProviderApprovalDecision>();
@@ -1020,7 +1003,7 @@ export const makeCodexSessionRuntime = (
yield* client.handleServerRequest("item/tool/requestUserInput", (payload) =>
Effect.gen(function* () {
const requestId = ApprovalRequestId.make(yield* Random.nextUUIDv4);
const requestId = ApprovalRequestId.make(randomUUID());
const turnId = TurnId.make(payload.turnId);
const itemId = ProviderItemId.make(payload.itemId);
const answers = yield* Deferred.make<ProviderUserInputAnswers>();
@@ -5,27 +5,15 @@ import { fileURLToPath } from "node:url";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { assert, it } from "@effect/vitest";
import { Context, Deferred, Effect, Fiber, Layer, Schema, Stream } from "effect";
import { Deferred, Effect, Fiber, Layer, Stream } from "effect";
import { createModelSelection } from "@t3tools/shared/model";
import {
ApprovalRequestId,
CursorSettings,
ProviderDriverKind,
type ProviderRuntimeEvent,
ThreadId,
ProviderInstanceId,
} from "@t3tools/contracts";
import { ApprovalRequestId, type ProviderRuntimeEvent, ThreadId } from "@t3tools/contracts";
import { ServerConfig } from "../../config.ts";
import { ServerSettingsService } from "../../serverSettings.ts";
import type { CursorAdapterShape } from "../Services/CursorAdapter.ts";
import { makeCursorAdapter } from "./CursorAdapter.ts";
// Test-local service tag so the rest of the file can keep using `yield* CursorAdapter`.
class CursorAdapter extends Context.Service<CursorAdapter, CursorAdapterShape>()(
"test/CursorAdapter",
) {}
import { CursorAdapter } from "../Services/CursorAdapter.ts";
import { makeCursorAdapterLive } from "./CursorAdapter.ts";
const __dirname = path.dirname(fileURLToPath(import.meta.url));
const mockAgentPath = path.join(__dirname, "../../../scripts/acp-mock-agent.ts");
@@ -103,31 +91,8 @@ async function waitForFileContent(filePath: string, attempts = 40) {
throw new Error(`Timed out waiting for file content at ${filePath}`);
}
// Tests mutate `ServerSettingsService` mid-flight (e.g. setting
// `providers.cursor.binaryPath` to a mock ACP wrapper). The adapter
// captures `cursorSettings` once at construction, so without a resolver
// the mutation is invisible — sessions would spawn the constructor's
// (empty) binary path. Wiring `resolveSettings` through
// `ServerSettingsService.getSettings` makes each session read the latest
// snapshot, matching the old "always read live" behavior that these
// tests assumed.
const makeResolveCursorSettings = Effect.gen(function* () {
const serverSettings = yield* ServerSettingsService;
return serverSettings.getSettings.pipe(
Effect.map((snapshot) => snapshot.providers.cursor),
Effect.orDie,
);
});
const cursorAdapterTestLayer = it.layer(
Layer.effect(
CursorAdapter,
Effect.gen(function* () {
const cursorConfig = Schema.decodeSync(CursorSettings)({});
const resolveSettings = yield* makeResolveCursorSettings;
return yield* makeCursorAdapter(cursorConfig, { resolveSettings });
}),
).pipe(
makeCursorAdapterLive().pipe(
Layer.provideMerge(ServerSettingsService.layerTest()),
Layer.provideMerge(
ServerConfig.layerTest(process.cwd(), {
@@ -155,10 +120,10 @@ cursorAdapterTestLayer("CursorAdapterLive", (it) => {
const session = yield* adapter.startSession({
threadId,
provider: ProviderDriverKind.make("cursor"),
provider: "cursor",
cwd: process.cwd(),
runtimeMode: "full-access",
modelSelection: { instanceId: ProviderInstanceId.make("cursor"), model: "default" },
modelSelection: { provider: "cursor", model: "default" },
});
assert.equal(session.provider, "cursor");
@@ -240,10 +205,10 @@ cursorAdapterTestLayer("CursorAdapterLive", (it) => {
yield* adapter.startSession({
threadId,
provider: ProviderDriverKind.make("cursor"),
provider: "cursor",
cwd: process.cwd(),
runtimeMode: "full-access",
modelSelection: { instanceId: ProviderInstanceId.make("cursor"), model: "default" },
modelSelection: { provider: "cursor", model: "default" },
});
yield* adapter.stopSession(threadId);
@@ -279,17 +244,17 @@ cursorAdapterTestLayer("CursorAdapterLive", (it) => {
[
adapter.startSession({
threadId,
provider: ProviderDriverKind.make("cursor"),
provider: "cursor",
cwd: process.cwd(),
runtimeMode: "full-access",
modelSelection: { instanceId: ProviderInstanceId.make("cursor"), model: "default" },
modelSelection: { provider: "cursor", model: "default" },
}),
adapter.startSession({
threadId,
provider: ProviderDriverKind.make("cursor"),
provider: "cursor",
cwd: process.cwd(),
runtimeMode: "full-access",
modelSelection: { instanceId: ProviderInstanceId.make("cursor"), model: "default" },
modelSelection: { provider: "cursor", model: "default" },
}),
],
{ concurrency: "unbounded" },
@@ -311,7 +276,7 @@ cursorAdapterTestLayer("CursorAdapterLive", (it) => {
const result = yield* adapter
.startSession({
threadId: ThreadId.make("bad-provider"),
provider: ProviderDriverKind.make("codex"),
provider: "codex",
cwd: process.cwd(),
runtimeMode: "full-access",
})
@@ -337,10 +302,10 @@ cursorAdapterTestLayer("CursorAdapterLive", (it) => {
yield* adapter.startSession({
threadId,
provider: ProviderDriverKind.make("cursor"),
provider: "cursor",
cwd: process.cwd(),
runtimeMode: "full-access",
modelSelection: { instanceId: ProviderInstanceId.make("cursor"), model: "composer-2" },
modelSelection: { provider: "cursor", model: "composer-2" },
});
yield* adapter.sendTurn({
@@ -393,7 +358,7 @@ cursorAdapterTestLayer("CursorAdapterLive", (it) => {
providers: { cursor: { binaryPath: wrapperPath } },
});
const modelSelection = createModelSelection(ProviderInstanceId.make("cursor"), "gpt-5.4", [
const modelSelection = createModelSelection("cursor", "gpt-5.4", [
{ id: "reasoning", value: "xhigh" },
{ id: "contextWindow", value: "1m" },
{ id: "fastMode", value: true },
@@ -401,7 +366,7 @@ cursorAdapterTestLayer("CursorAdapterLive", (it) => {
yield* adapter.startSession({
threadId,
provider: ProviderDriverKind.make("cursor"),
provider: "cursor",
cwd: process.cwd(),
runtimeMode: "full-access",
modelSelection,
@@ -495,10 +460,10 @@ cursorAdapterTestLayer("CursorAdapterLive", (it) => {
const program = Effect.gen(function* () {
yield* adapter.startSession({
threadId,
provider: ProviderDriverKind.make("cursor"),
provider: "cursor",
cwd: process.cwd(),
runtimeMode: "approval-required",
modelSelection: { instanceId: ProviderInstanceId.make("cursor"), model: "default" },
modelSelection: { provider: "cursor", model: "default" },
});
const turn = yield* adapter.sendTurn({
@@ -595,14 +560,7 @@ cursorAdapterTestLayer("CursorAdapterLive", (it) => {
);
}).pipe(
Effect.provide(
Layer.effect(
CursorAdapter,
Effect.gen(function* () {
const cursorConfig = Schema.decodeSync(CursorSettings)({});
const resolveSettings = yield* makeResolveCursorSettings;
return yield* makeCursorAdapter(cursorConfig, { resolveSettings });
}),
).pipe(
makeCursorAdapterLive().pipe(
Layer.provideMerge(ServerSettingsService.layerTest()),
Layer.provideMerge(
ServerConfig.layerTest(process.cwd(), {
@@ -657,10 +615,10 @@ cursorAdapterTestLayer("CursorAdapterLive", (it) => {
yield* adapter.startSession({
threadId,
provider: ProviderDriverKind.make("cursor"),
provider: "cursor",
cwd: process.cwd(),
runtimeMode: "full-access",
modelSelection: { instanceId: ProviderInstanceId.make("cursor"), model: "default" },
modelSelection: { provider: "cursor", model: "default" },
});
const turn = yield* adapter.sendTurn({
@@ -756,10 +714,10 @@ cursorAdapterTestLayer("CursorAdapterLive", (it) => {
yield* adapter.startSession({
threadId,
provider: ProviderDriverKind.make("cursor"),
provider: "cursor",
cwd: process.cwd(),
runtimeMode: "full-access",
modelSelection: { instanceId: ProviderInstanceId.make("cursor"), model: "default" },
modelSelection: { provider: "cursor", model: "default" },
});
const turn = yield* adapter.sendTurn({
@@ -878,10 +836,10 @@ cursorAdapterTestLayer("CursorAdapterLive", (it) => {
yield* adapter.startSession({
threadId,
provider: ProviderDriverKind.make("cursor"),
provider: "cursor",
cwd: process.cwd(),
runtimeMode: "approval-required",
modelSelection: { instanceId: ProviderInstanceId.make("cursor"), model: "default" },
modelSelection: { provider: "cursor", model: "default" },
});
const sendTurnFiber = yield* adapter
@@ -948,10 +906,10 @@ cursorAdapterTestLayer("CursorAdapterLive", (it) => {
yield* adapter.startSession({
threadId,
provider: ProviderDriverKind.make("cursor"),
provider: "cursor",
cwd: process.cwd(),
runtimeMode: "approval-required",
modelSelection: { instanceId: ProviderInstanceId.make("cursor"), model: "default" },
modelSelection: { provider: "cursor", model: "default" },
});
const sendTurnFiber = yield* adapter
@@ -991,10 +949,10 @@ cursorAdapterTestLayer("CursorAdapterLive", (it) => {
yield* adapter.startSession({
threadId,
provider: ProviderDriverKind.make("cursor"),
provider: "cursor",
cwd: process.cwd(),
runtimeMode: "full-access",
modelSelection: { instanceId: ProviderInstanceId.make("cursor"), model: "default" },
modelSelection: { provider: "cursor", model: "default" },
});
const sendTurnFiber = yield* adapter
@@ -1034,10 +992,10 @@ cursorAdapterTestLayer("CursorAdapterLive", (it) => {
yield* adapter.startSession({
threadId,
provider: ProviderDriverKind.make("cursor"),
provider: "cursor",
cwd: process.cwd(),
runtimeMode: "full-access",
modelSelection: { instanceId: ProviderInstanceId.make("cursor"), model: "default" },
modelSelection: { provider: "cursor", model: "default" },
});
const sendTurnFiber = yield* adapter
@@ -1077,10 +1035,10 @@ cursorAdapterTestLayer("CursorAdapterLive", (it) => {
yield* adapter.startSession({
threadId,
provider: ProviderDriverKind.make("cursor"),
provider: "cursor",
cwd: process.cwd(),
runtimeMode: "full-access",
modelSelection: { instanceId: ProviderInstanceId.make("cursor"), model: "default" },
modelSelection: { provider: "cursor", model: "default" },
});
const firstEvents = Array.from(yield* Fiber.join(firstConsumer));
@@ -1115,10 +1073,10 @@ cursorAdapterTestLayer("CursorAdapterLive", (it) => {
yield* adapter.startSession({
threadId,
provider: ProviderDriverKind.make("cursor"),
provider: "cursor",
cwd: process.cwd(),
runtimeMode: "full-access",
modelSelection: { instanceId: ProviderInstanceId.make("cursor"), model: "composer-2" },
modelSelection: { provider: "cursor", model: "composer-2" },
});
yield* adapter.sendTurn({
@@ -1131,7 +1089,7 @@ cursorAdapterTestLayer("CursorAdapterLive", (it) => {
threadId,
input: "second turn after switching model",
attachments: [],
modelSelection: createModelSelection(ProviderInstanceId.make("cursor"), "composer-2", [
modelSelection: createModelSelection("cursor", "composer-2", [
{ id: "fastMode", value: true },
]),
});
@@ -1178,17 +1136,17 @@ cursorAdapterTestLayer("CursorAdapterLive", (it) => {
yield* adapter.startSession({
threadId,
provider: ProviderDriverKind.make("cursor"),
provider: "cursor",
cwd: process.cwd(),
runtimeMode: "full-access",
modelSelection: { instanceId: ProviderInstanceId.make("cursor"), model: "composer-2" },
modelSelection: { provider: "cursor", model: "composer-2" },
});
yield* adapter.sendTurn({
threadId,
input: "first turn with fast mode",
attachments: [],
modelSelection: createModelSelection(ProviderInstanceId.make("cursor"), "composer-2", [
modelSelection: createModelSelection("cursor", "composer-2", [
{ id: "fastMode", value: true },
]),
});
@@ -1197,7 +1155,7 @@ cursorAdapterTestLayer("CursorAdapterLive", (it) => {
threadId,
input: "second turn without fast mode",
attachments: [],
modelSelection: createModelSelection(ProviderInstanceId.make("cursor"), "composer-2", [
modelSelection: createModelSelection("cursor", "composer-2", [
{ id: "fastMode", value: false },
]),
});
@@ -1216,91 +1174,4 @@ cursorAdapterTestLayer("CursorAdapterLive", (it) => {
yield* adapter.stopSession(threadId);
}),
);
it.effect(
"applies fast mode on the first turn when modelSelection uses a non-default instance id",
() => {
const customInstanceId = ProviderInstanceId.make("cursor_secondary");
// Custom-instance cases can't share the suite-level `CursorAdapter`
// layer because that one binds `instanceId: "cursor"`. We build a
// fresh layer graph — including a fresh `ServerSettingsService` — so
// mid-test `updateSettings` calls target the same service instance the
// adapter's `resolveSettings` reads from, and so the outer
// `yield* ServerSettingsService` sees the same snapshot as well.
const customAdapterLayer = Layer.effect(
CursorAdapter,
Effect.gen(function* () {
const cursorConfig = Schema.decodeSync(CursorSettings)({});
const resolveSettings = yield* makeResolveCursorSettings;
return yield* makeCursorAdapter(cursorConfig, {
instanceId: customInstanceId,
resolveSettings,
});
}),
).pipe(
Layer.provideMerge(ServerSettingsService.layerTest()),
Layer.provideMerge(
ServerConfig.layerTest(process.cwd(), {
prefix: "t3code-cursor-adapter-custom-instance-",
}),
),
Layer.provideMerge(NodeServices.layer),
);
return Effect.gen(function* () {
const adapter = yield* CursorAdapter;
const serverSettings = yield* ServerSettingsService;
const threadId = ThreadId.make("cursor-fast-mode-custom-instance");
const tempDir = yield* Effect.promise(() => mkdtemp(path.join(os.tmpdir(), "cursor-acp-")));
const requestLogPath = path.join(tempDir, "requests.ndjson");
const argvLogPath = path.join(tempDir, "argv.txt");
yield* Effect.promise(() => writeFile(requestLogPath, "", "utf8"));
const wrapperPath = yield* Effect.promise(() =>
makeProbeWrapper(requestLogPath, argvLogPath),
);
yield* serverSettings.updateSettings({
providers: { cursor: { binaryPath: wrapperPath } },
});
yield* adapter.startSession({
threadId,
provider: ProviderDriverKind.make("cursor"),
cwd: process.cwd(),
runtimeMode: "full-access",
modelSelection: {
instanceId: customInstanceId,
model: "composer-2",
},
});
yield* adapter.sendTurn({
threadId,
input: "first turn with fast mode",
attachments: [],
modelSelection: {
...createModelSelection(ProviderInstanceId.make("cursor"), "composer-2", [
{ id: "fastMode", value: true },
]),
instanceId: customInstanceId,
},
});
const requests = yield* Effect.promise(() => readJsonLines(requestLogPath));
const fastConfigRequests = requests.filter(
(entry) =>
entry.method === "session/set_config_option" &&
(entry.params as Record<string, unknown> | undefined)?.configId === "fast",
);
assert.isAbove(
fastConfigRequests.length,
0,
"fast mode should apply when instance id matches the adapter binding",
);
const lastFastConfig = fastConfigRequests[fastConfigRequests.length - 1];
assert.equal((lastFastConfig?.params as Record<string, unknown>)?.value, "true");
yield* adapter.stopSession(threadId);
}).pipe(Effect.provide(customAdapterLayer));
},
);
});
@@ -7,7 +7,6 @@ import * as nodePath from "node:path";
import {
ApprovalRequestId,
type CursorSettings,
type ProviderOptionSelection,
EventId,
type ProviderApprovalDecision,
@@ -15,8 +14,6 @@ import {
type ProviderRuntimeEvent,
type ProviderSession,
type ProviderUserInputAnswers,
ProviderDriverKind,
ProviderInstanceId,
RuntimeRequestId,
type RuntimeMode,
type ThreadId,
@@ -29,6 +26,7 @@ import {
Exit,
Fiber,
FileSystem,
Layer,
Option,
PubSub,
Random,
@@ -42,6 +40,7 @@ import type * as EffectAcpSchema from "effect-acp/schema";
import { resolveAttachmentPath } from "../../attachmentStore.ts";
import { ServerConfig } from "../../config.ts";
import { ServerSettingsService } from "../../serverSettings.ts";
import {
ProviderAdapterProcessError,
ProviderAdapterRequestError,
@@ -73,37 +72,19 @@ import {
extractPlanMarkdown,
extractTodosAsPlan,
} from "../acp/CursorAcpExtension.ts";
import { type CursorAdapterShape } from "../Services/CursorAdapter.ts";
import { CursorAdapter, type CursorAdapterShape } from "../Services/CursorAdapter.ts";
import { resolveCursorAcpBaseModelId } from "./CursorProvider.ts";
import { type EventNdjsonLogger, makeEventNdjsonLogger } from "./EventNdjsonLogger.ts";
const PROVIDER = ProviderDriverKind.make("cursor");
const PROVIDER = "cursor" as const;
const CURSOR_RESUME_VERSION = 1 as const;
const ACP_PLAN_MODE_ALIASES = ["plan", "architect"];
const ACP_IMPLEMENT_MODE_ALIASES = ["code", "agent", "default", "chat", "implement"];
const ACP_APPROVAL_MODE_ALIASES = ["ask"];
export interface CursorAdapterLiveOptions {
readonly environment?: NodeJS.ProcessEnv;
readonly nativeEventLogPath?: string;
readonly nativeEventLogger?: EventNdjsonLogger;
/**
* Selections are honored when `modelSelection.instanceId` matches this value.
* Defaults to the legacy built-in instance id (`cursor`).
*/
readonly instanceId?: typeof ProviderInstanceId.Type;
/**
* Optional per-session settings resolver. When provided the adapter yields
* this effect at the start of every session and uses the result instead of
* the `cursorSettings` captured at construction.
*
* Production instances bind settings to the instance scope (the hydration
* layer rebuilds the adapter on config change) and leave this undefined.
* Test suites that mutate `ServerSettingsService` mid-flight — e.g. to
* swap `binaryPath` to a mock ACP wrapper — pass a resolver that reads
* the latest snapshot so the closure isn't stale.
*/
readonly resolveSettings?: Effect.Effect<CursorSettings>;
}
interface PendingApproval {
@@ -299,15 +280,12 @@ function selectAutoApprovedPermissionOption(
return undefined;
}
export function makeCursorAdapter(
cursorSettings: CursorSettings,
options?: CursorAdapterLiveOptions,
) {
function makeCursorAdapter(options?: CursorAdapterLiveOptions) {
return Effect.gen(function* () {
const boundInstanceId = options?.instanceId ?? ProviderInstanceId.make("cursor");
const fileSystem = yield* FileSystem.FileSystem;
const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
const serverConfig = yield* Effect.service(ServerConfig);
const serverSettingsService = yield* ServerSettingsService;
const nativeEventLogger =
options?.nativeEventLogger ??
(options?.nativeEventLogPath !== undefined
@@ -462,12 +440,25 @@ export function makeCursorAdapter(
const cwd = nodePath.resolve(input.cwd.trim());
const cursorModelSelection =
input.modelSelection?.instanceId === boundInstanceId ? input.modelSelection : undefined;
input.modelSelection?.provider === "cursor" ? input.modelSelection : undefined;
const existing = sessions.get(input.threadId);
if (existing && !existing.stopped) {
yield* stopSessionInternal(existing);
}
const cursorSettings = yield* serverSettingsService.getSettings.pipe(
Effect.map((settings) => settings.providers.cursor),
Effect.mapError(
(error) =>
new ProviderAdapterProcessError({
provider: PROVIDER,
threadId: input.threadId,
detail: error.message,
cause: error,
}),
),
);
const pendingApprovals = new Map<ApprovalRequestId, PendingApproval>();
const pendingUserInputs = new Map<ApprovalRequestId, PendingUserInput>();
const sessionScope = yield* Scope.make("sequential");
@@ -484,21 +475,8 @@ export function makeCursorAdapter(
threadId: input.threadId,
});
// Resolve the CursorSettings used to spawn the ACP child. Production
// leaves `options.resolveSettings` undefined so we use the value
// captured at adapter construction — per-instance isolation is
// enforced by the hydration layer rebuilding this adapter whenever
// its config changes. Tests set `resolveSettings` to pull the latest
// snapshot from `ServerSettingsService` so that mid-suite
// `updateSettings({ providers: { cursor: { binaryPath } } })` calls
// actually take effect when the next session spawns.
const effectiveCursorSettings = options?.resolveSettings
? yield* options.resolveSettings
: cursorSettings;
const acp = yield* makeCursorAcpRuntime({
cursorSettings: effectiveCursorSettings,
...(options?.environment ? { environment: options.environment } : {}),
cursorSettings,
childProcessSpawner,
cwd,
...(resumeSessionId ? { resumeSessionId } : {}),
@@ -688,7 +666,6 @@ export function makeCursorAdapter(
const now = yield* nowIso;
const session: ProviderSession = {
provider: PROVIDER,
providerInstanceId: boundInstanceId,
status: "ready",
runtimeMode: input.runtimeMode,
cwd,
@@ -838,7 +815,7 @@ export function makeCursorAdapter(
const ctx = yield* requireSession(input.threadId);
const turnId = TurnId.make(crypto.randomUUID());
const turnModelSelection =
input.modelSelection?.instanceId === boundInstanceId ? input.modelSelection : undefined;
input.modelSelection?.provider === "cursor" ? input.modelSelection : undefined;
const model = turnModelSelection?.model ?? ctx.session.model;
const resolvedModel = resolveCursorAcpBaseModelId(model);
yield* applyRequestedSessionConfiguration({
@@ -1072,3 +1049,9 @@ export function makeCursorAdapter(
} satisfies CursorAdapterShape;
});
}
export const CursorAdapterLive = Layer.effect(CursorAdapter, makeCursorAdapter());
export function makeCursorAdapterLive(opts?: CursorAdapterLiveOptions) {
return Layer.effect(CursorAdapter, makeCursorAdapter(opts));
}
@@ -1,7 +1,10 @@
import * as NodeOS from "node:os";
import * as path from "node:path";
import * as os from "node:os";
import { chmod, mkdtemp, readFile, writeFile } from "node:fs/promises";
import { fileURLToPath } from "node:url";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { Effect, FileSystem, Path } from "effect";
import { Effect } from "effect";
import { describe, expect, it } from "vitest";
import type * as EffectAcpSchema from "effect-acp/schema";
import type { CursorSettings, ServerProviderModel } from "@t3tools/contracts";
@@ -11,7 +14,6 @@ import {
buildCursorProviderSnapshot,
buildCursorCapabilitiesFromConfigOptions,
buildCursorDiscoveredModelsFromConfigOptions,
checkCursorProviderStatus,
discoverCursorModelCapabilitiesViaAcp,
discoverCursorModelsViaAcp,
getCursorFallbackModels,
@@ -23,14 +25,8 @@ import {
resolveCursorAcpConfigUpdates,
} from "./CursorProvider.ts";
const runNode = <A, E>(
effect: Effect.Effect<A, E, FileSystem.FileSystem | Path.Path>,
): Promise<A> => Effect.runPromise(effect.pipe(Effect.provide(NodeServices.layer)));
const resolveMockAgentPath = Effect.fn("resolveMockAgentPath")(function* () {
const path = yield* Path.Path;
return yield* path.fromFileUrl(new URL("../../../scripts/acp-mock-agent.ts", import.meta.url));
});
const __dirname = path.dirname(fileURLToPath(import.meta.url));
const mockAgentPath = path.join(__dirname, "../../../scripts/acp-mock-agent.ts");
function selectDescriptor(
id: string,
@@ -57,16 +53,8 @@ function booleanDescriptor(id: string, label: string, currentValue?: boolean) {
};
}
const makeMockAgentWrapper = Effect.fn("makeMockAgentWrapper")(function* (
extraEnv?: Record<string, string>,
) {
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const mockAgentPath = yield* resolveMockAgentPath();
const dir = yield* fileSystem.makeTempDirectory({
directory: NodeOS.tmpdir(),
prefix: "cursor-provider-mock-",
});
async function makeMockAgentWrapper(extraEnv?: Record<string, string>) {
const dir = await mkdtemp(path.join(os.tmpdir(), "cursor-provider-mock-"));
const wrapperPath = path.join(dir, "fake-agent.sh");
const envExports = Object.entries(extraEnv ?? {})
.map(([key, value]) => `export ${key}=${JSON.stringify(value)}`)
@@ -75,80 +63,23 @@ const makeMockAgentWrapper = Effect.fn("makeMockAgentWrapper")(function* (
${envExports}
exec ${JSON.stringify("bun")} ${JSON.stringify(mockAgentPath)} "$@"
`;
yield* fileSystem.writeFileString(wrapperPath, script);
yield* fileSystem.chmod(wrapperPath, 0o755);
await writeFile(wrapperPath, script, "utf8");
await chmod(wrapperPath, 0o755);
return wrapperPath;
});
}
const makeMockAgentWithAboutWrapper = Effect.fn("makeMockAgentWithAboutWrapper")(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const mockAgentPath = yield* resolveMockAgentPath();
const dir = yield* fileSystem.makeTempDirectory({
directory: NodeOS.tmpdir(),
prefix: "cursor-provider-about-mock-",
});
const wrapperPath = path.join(dir, "fake-agent.sh");
const script = `#!/bin/sh
if [ "$1" = "about" ]; then
printf 'CLI Version 2026.04.09-f2b0fcd\\n'
printf 'User Email [email protected]\\n'
exit 0
fi
exec ${JSON.stringify("bun")} ${JSON.stringify(mockAgentPath)} "$@"
`;
yield* fileSystem.writeFileString(wrapperPath, script);
yield* fileSystem.chmod(wrapperPath, 0o755);
return wrapperPath;
});
const waitForFileContent = Effect.fn("waitForFileContent")(function* (
filePath: string,
attempts = 40,
) {
const fileSystem = yield* FileSystem.FileSystem;
async function waitForFileContent(filePath: string, attempts = 40): Promise<string> {
for (let attempt = 0; attempt < attempts; attempt += 1) {
const content = yield* fileSystem
.readFileString(filePath)
.pipe(Effect.catch(() => Effect.void));
if (content !== undefined) {
try {
const content = await readFile(filePath, "utf8");
if (content.trim().length > 0) {
return content;
}
}
yield* Effect.sleep("50 millis");
} catch {}
await new Promise((resolve) => setTimeout(resolve, 50));
}
return yield* Effect.fail(new Error(`Timed out waiting for file content at ${filePath}`));
});
const makeProviderStatusEnvFixture = Effect.fn("makeProviderStatusEnvFixture")(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const tempDir = yield* fileSystem.makeTempDirectory({
directory: NodeOS.tmpdir(),
prefix: "cursor-provider-status-env-",
});
return {
requestLogPath: path.join(tempDir, "requests.ndjson"),
wrapperPath: yield* makeMockAgentWithAboutWrapper(),
};
});
const makeExitLogFixture = Effect.fn("makeExitLogFixture")(function* (prefix: string) {
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const tempDir = yield* fileSystem.makeTempDirectory({
directory: NodeOS.tmpdir(),
prefix,
});
const exitLogPath = path.join(tempDir, "exit.log");
return {
exitLogPath,
wrapperPath: yield* makeMockAgentWrapper({
T3_ACP_EXIT_LOG_PATH: exitLogPath,
}),
};
});
throw new Error(`Timed out waiting for file content at ${filePath}`);
}
const parameterizedGpt54ConfigOptions = [
{
@@ -497,38 +428,9 @@ describe("buildCursorDiscoveredModelsFromConfigOptions", () => {
});
});
describe("checkCursorProviderStatus", () => {
it("passes the injected environment to ACP model discovery", async () => {
const { requestLogPath, wrapperPath } = await runNode(makeProviderStatusEnvFixture());
const provider = await Effect.runPromise(
checkCursorProviderStatus(
{
enabled: true,
binaryPath: wrapperPath,
apiEndpoint: "",
customModels: [],
},
{
...process.env,
T3_ACP_REQUEST_LOG_PATH: requestLogPath,
},
).pipe(Effect.provide(NodeServices.layer)),
);
expect(provider.models.map((model) => model.slug)).toEqual([
"default",
"composer-2",
"gpt-5.4",
"claude-opus-4-6",
]);
await expect(runNode(waitForFileContent(requestLogPath))).resolves.toContain("initialize");
});
});
describe("discoverCursorModelsViaAcp", () => {
it("keeps the ACP probe runtime alive long enough to discover models", async () => {
const wrapperPath = await runNode(makeMockAgentWrapper());
const wrapperPath = await makeMockAgentWrapper();
const models = await Effect.runPromise(
discoverCursorModelsViaAcp({
@@ -548,9 +450,11 @@ describe("discoverCursorModelsViaAcp", () => {
});
it("closes the ACP probe runtime after discovery completes", async () => {
const { exitLogPath, wrapperPath } = await runNode(
makeExitLogFixture("cursor-provider-exit-log-"),
);
const tempDir = await mkdtemp(path.join(os.tmpdir(), "cursor-provider-exit-log-"));
const exitLogPath = path.join(tempDir, "exit.log");
const wrapperPath = await makeMockAgentWrapper({
T3_ACP_EXIT_LOG_PATH: exitLogPath,
});
await Effect.runPromise(
discoverCursorModelsViaAcp({
@@ -561,16 +465,18 @@ describe("discoverCursorModelsViaAcp", () => {
}).pipe(Effect.provide(NodeServices.layer)),
);
const exitLog = await runNode(waitForFileContent(exitLogPath));
const exitLog = await waitForFileContent(exitLogPath);
expect(exitLog).toContain("SIGTERM");
});
});
describe("discoverCursorModelCapabilitiesViaAcp", () => {
it("closes all ACP probe runtimes after capability enrichment completes", async () => {
const { exitLogPath, wrapperPath } = await runNode(
makeExitLogFixture("cursor-capabilities-exit-log-"),
);
const tempDir = await mkdtemp(path.join(os.tmpdir(), "cursor-capabilities-exit-log-"));
const exitLogPath = path.join(tempDir, "exit.log");
const wrapperPath = await makeMockAgentWrapper({
T3_ACP_EXIT_LOG_PATH: exitLogPath,
});
const existingModels: ReadonlyArray<ServerProviderModel> = [
{ slug: "default", name: "Auto", isCustom: false, capabilities: emptyCapabilities },
{ slug: "composer-2", name: "Composer 2", isCustom: false, capabilities: emptyCapabilities },
@@ -602,7 +508,7 @@ describe("discoverCursorModelCapabilitiesViaAcp", () => {
"claude-opus-4-6",
]);
const exitLog = await runNode(waitForFileContent(exitLogPath));
const exitLog = await waitForFileContent(exitLogPath);
expect(exitLog.match(/SIGTERM/g)?.length ?? 0).toBe(4);
});
});
@@ -624,7 +530,6 @@ describe("parseCursorAboutOutput", () => {
status: "ready",
auth: {
status: "authenticated",
email: "[email protected]",
type: "Team",
label: "Cursor Team Subscription",
},
+321 -360
View File
@@ -1,4 +1,6 @@
import * as nodeFs from "node:fs";
import * as nodeOs from "node:os";
import * as nodePath from "node:path";
import type {
CursorSettings,
@@ -8,10 +10,10 @@ import type {
ServerProviderAuth,
ServerProviderModel,
ServerProviderState,
ServerSettingsError,
} from "@t3tools/contracts";
import { ProviderDriverKind } from "@t3tools/contracts";
import type * as EffectAcpSchema from "effect-acp/schema";
import { Cause, Effect, Exit, FileSystem, Layer, Option, Path, Result } from "effect";
import { Cause, Effect, Equal, Exit, Layer, Option, Result, Stream } from "effect";
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
import {
createModelCapabilities,
@@ -27,11 +29,13 @@ import {
isCommandMissingCause,
providerModelsFromSettings,
type CommandResult,
type ServerProviderDraft,
} from "../providerSnapshot.ts";
import { makeManagedServerProvider } from "../makeManagedServerProvider.ts";
import { CursorProvider } from "../Services/CursorProvider.ts";
import { AcpSessionRuntime } from "../acp/AcpSessionRuntime.ts";
import { ServerSettingsService } from "../../serverSettings.ts";
const PROVIDER = ProviderDriverKind.make("cursor");
const PROVIDER = "cursor" as const;
const CURSOR_PRESENTATION = {
displayName: "Cursor",
badgeLabel: "Early Access",
@@ -44,6 +48,7 @@ const EMPTY_CAPABILITIES: ModelCapabilities = createModelCapabilities({
const CURSOR_ACP_MODEL_DISCOVERY_TIMEOUT_MS = 15_000;
const CURSOR_ACP_MODEL_CAPABILITY_TIMEOUT = "4 seconds";
const CURSOR_ACP_MODEL_DISCOVERY_CONCURRENCY = 4;
const CURSOR_REFRESH_INTERVAL = "1 hour";
const CURSOR_PARAMETERIZED_MODEL_PICKER_MIN_VERSION_DATE = 2026_04_08;
export const CURSOR_PARAMETERIZED_MODEL_PICKER_CAPABILITIES = {
_meta: {
@@ -51,14 +56,13 @@ export const CURSOR_PARAMETERIZED_MODEL_PICKER_CAPABILITIES = {
},
} satisfies NonNullable<EffectAcpSchema.InitializeRequest["clientCapabilities"]>;
export function buildInitialCursorProviderSnapshot(
cursorSettings: CursorSettings,
): ServerProviderDraft {
function buildInitialCursorProviderSnapshot(cursorSettings: CursorSettings): ServerProvider {
const checkedAt = new Date().toISOString();
const models = getCursorFallbackModels(cursorSettings);
if (!cursorSettings.enabled) {
return buildServerProvider({
provider: PROVIDER,
presentation: CURSOR_PRESENTATION,
enabled: false,
checkedAt,
@@ -74,6 +78,7 @@ export function buildInitialCursorProviderSnapshot(
}
return buildServerProvider({
provider: PROVIDER,
presentation: CURSOR_PRESENTATION,
enabled: true,
checkedAt,
@@ -107,12 +112,7 @@ function flattenSessionConfigSelectOptions(
}
return configOption.options.flatMap((entry) =>
"value" in entry
? [
{
value: entry.value.trim(),
name: entry.name.trim(),
} satisfies CursorSessionSelectOption,
]
? [{ value: entry.value.trim(), name: entry.name.trim() } satisfies CursorSessionSelectOption]
: entry.options.map(
(option) =>
({
@@ -392,10 +392,7 @@ export function buildCursorDiscoveredModelsFromConfigOptions(
);
}
const makeCursorAcpProbeRuntime = (
cursorSettings: CursorSettings,
environment: NodeJS.ProcessEnv = process.env,
) =>
const makeCursorAcpProbeRuntime = (cursorSettings: CursorSettings) =>
Effect.gen(function* () {
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
const acpContext = yield* Layer.build(
@@ -407,7 +404,6 @@ const makeCursorAcpProbeRuntime = (
"acp",
],
cwd: process.cwd(),
env: environment,
},
cwd: process.cwd(),
clientInfo: { name: "t3-code-provider-probe", version: "0.0.0" },
@@ -421,12 +417,7 @@ const makeCursorAcpProbeRuntime = (
const withCursorAcpProbeRuntime = <A, E, R>(
cursorSettings: CursorSettings,
useRuntime: (acp: AcpSessionRuntime["Service"]) => Effect.Effect<A, E, R>,
environment: NodeJS.ProcessEnv = process.env,
) =>
makeCursorAcpProbeRuntime(cursorSettings, environment).pipe(
Effect.flatMap(useRuntime),
Effect.scoped,
);
) => makeCursorAcpProbeRuntime(cursorSettings).pipe(Effect.flatMap(useRuntime), Effect.scoped);
function normalizeCursorConfigOptionToken(value: string | null | undefined): string {
return (
@@ -469,18 +460,12 @@ export function resolveCursorAcpBaseModelId(model: string | null | undefined): s
export function resolveCursorAcpConfigUpdates(
configOptions: ReadonlyArray<EffectAcpSchema.SessionConfigOption> | null | undefined,
selections: ReadonlyArray<ProviderOptionSelection> | null | undefined,
): ReadonlyArray<{
readonly configId: string;
readonly value: string | boolean;
}> {
): ReadonlyArray<{ readonly configId: string; readonly value: string | boolean }> {
if (!configOptions || configOptions.length === 0) {
return [];
}
const updates: Array<{
readonly configId: string;
readonly value: string | boolean;
}> = [];
const updates: Array<{ readonly configId: string; readonly value: string | boolean }> = [];
const reasoningOption = findCursorEffortConfigOption(configOptions);
const requestedReasoning = normalizeCursorReasoningValue(
@@ -540,129 +525,43 @@ export function resolveCursorAcpConfigUpdates(
return updates;
}
export const discoverCursorModelsViaAcp = (
cursorSettings: CursorSettings,
environment: NodeJS.ProcessEnv = process.env,
) =>
withCursorAcpProbeRuntime(
cursorSettings,
(acp) =>
Effect.map(acp.start(), (started) =>
buildCursorDiscoveredModelsFromConfigOptions(
started.sessionSetupResult.configOptions ?? [],
),
),
environment,
export const discoverCursorModelsViaAcp = (cursorSettings: CursorSettings) =>
withCursorAcpProbeRuntime(cursorSettings, (acp) =>
Effect.map(acp.start(), (started) =>
buildCursorDiscoveredModelsFromConfigOptions(started.sessionSetupResult.configOptions ?? []),
),
);
export const discoverCursorModelCapabilitiesViaAcp = (
cursorSettings: CursorSettings,
existingModels: ReadonlyArray<ServerProviderModel>,
environment: NodeJS.ProcessEnv = process.env,
) =>
withCursorAcpProbeRuntime(
cursorSettings,
(acp) =>
Effect.gen(function* () {
const started = yield* acp.start();
const initialConfigOptions = started.sessionSetupResult.configOptions ?? [];
const modelOption = findCursorModelConfigOption(initialConfigOptions);
const modelChoices = flattenSessionConfigSelectOptions(modelOption);
if (!modelOption || modelChoices.length === 0) {
return [];
}
withCursorAcpProbeRuntime(cursorSettings, (acp) =>
Effect.gen(function* () {
const started = yield* acp.start();
const initialConfigOptions = started.sessionSetupResult.configOptions ?? [];
const modelOption = findCursorModelConfigOption(initialConfigOptions);
const modelChoices = flattenSessionConfigSelectOptions(modelOption);
if (!modelOption || modelChoices.length === 0) {
return [];
}
const currentModelValue =
modelOption.type === "select" ? modelOption.currentValue?.trim() || undefined : undefined;
const capabilitiesBySlug = new Map<string, ModelCapabilities>();
if (currentModelValue) {
capabilitiesBySlug.set(
currentModelValue,
buildCursorCapabilitiesFromConfigOptions(initialConfigOptions),
);
}
const targetModelSlugs = new Set(
existingModels
.filter((model) => !model.isCustom && !hasCursorModelCapabilities(model))
.map((model) => model.slug),
const currentModelValue =
modelOption.type === "select" ? modelOption.currentValue?.trim() || undefined : undefined;
const capabilitiesBySlug = new Map<string, ModelCapabilities>();
if (currentModelValue) {
capabilitiesBySlug.set(
currentModelValue,
buildCursorCapabilitiesFromConfigOptions(initialConfigOptions),
);
if (targetModelSlugs.size === 0) {
return buildCursorDiscoveredModels(
modelChoices.map((modelChoice) => ({
slug: modelChoice.value.trim(),
name: modelChoice.name.trim(),
capabilities: capabilitiesBySlug.get(modelChoice.value.trim()) ?? EMPTY_CAPABILITIES,
})),
);
}
const probedCapabilities = yield* Effect.forEach(
modelChoices,
(modelChoice) => {
const modelSlug = modelChoice.value.trim();
if (
!modelSlug ||
!targetModelSlugs.has(modelSlug) ||
capabilitiesBySlug.has(modelSlug)
) {
return Effect.void.pipe(
Effect.as<readonly [string, ModelCapabilities] | undefined>(undefined),
);
}
return withCursorAcpProbeRuntime(
cursorSettings,
(probeAcp) =>
Effect.gen(function* () {
const probeStarted = yield* probeAcp.start();
const probeConfigOptions = probeStarted.sessionSetupResult.configOptions ?? [];
const probeModelOption = findCursorModelConfigOption(probeConfigOptions);
const probeCurrentModelValue =
probeModelOption?.type === "select"
? probeModelOption.currentValue?.trim() || undefined
: undefined;
yield* Effect.annotateCurrentSpan({
"cursor.acp.model.value": modelSlug,
"cursor.acp.model.currentValue": probeCurrentModelValue,
"cursor.acp.config_option_id": probeModelOption?.id ?? modelOption.id,
});
const nextConfigOptions =
probeCurrentModelValue === modelSlug
? probeConfigOptions
: yield* probeAcp
.setConfigOption(probeModelOption?.id ?? modelOption.id, modelSlug)
.pipe(
Effect.map((response) => response.configOptions ?? probeConfigOptions),
);
return [
modelSlug,
buildCursorCapabilitiesFromConfigOptions(nextConfigOptions),
] as const;
}),
environment,
).pipe(
Effect.timeout(CURSOR_ACP_MODEL_CAPABILITY_TIMEOUT),
Effect.retry({ times: 3 }),
Effect.withSpan("cursor-acp-model-capability-probe"),
Effect.catchCause((cause) =>
Effect.logWarning("Cursor ACP capability probe failed", {
modelSlug,
cause: Cause.pretty(cause),
}),
),
);
},
{ concurrency: CURSOR_ACP_MODEL_DISCOVERY_CONCURRENCY },
);
for (const entry of probedCapabilities) {
if (!entry) {
continue;
}
capabilitiesBySlug.set(entry[0], entry[1]);
}
}
const targetModelSlugs = new Set(
existingModels
.filter((model) => !model.isCustom && !hasCursorModelCapabilities(model))
.map((model) => model.slug),
);
if (targetModelSlugs.size === 0) {
return buildCursorDiscoveredModels(
modelChoices.map((modelChoice) => ({
slug: modelChoice.value.trim(),
@@ -670,8 +569,73 @@ export const discoverCursorModelCapabilitiesViaAcp = (
capabilities: capabilitiesBySlug.get(modelChoice.value.trim()) ?? EMPTY_CAPABILITIES,
})),
);
}).pipe(Effect.withSpan("cursor-acp-model-capability-discovery", {})),
environment,
}
const probedCapabilities = yield* Effect.forEach(
modelChoices,
(modelChoice) => {
const modelSlug = modelChoice.value.trim();
if (!modelSlug || !targetModelSlugs.has(modelSlug) || capabilitiesBySlug.has(modelSlug)) {
return Effect.void.pipe(
Effect.as<readonly [string, ModelCapabilities] | undefined>(undefined),
);
}
return withCursorAcpProbeRuntime(cursorSettings, (probeAcp) =>
Effect.gen(function* () {
const probeStarted = yield* probeAcp.start();
const probeConfigOptions = probeStarted.sessionSetupResult.configOptions ?? [];
const probeModelOption = findCursorModelConfigOption(probeConfigOptions);
const probeCurrentModelValue =
probeModelOption?.type === "select"
? probeModelOption.currentValue?.trim() || undefined
: undefined;
yield* Effect.annotateCurrentSpan({
"cursor.acp.model.value": modelSlug,
"cursor.acp.model.currentValue": probeCurrentModelValue,
"cursor.acp.config_option_id": probeModelOption?.id ?? modelOption.id,
});
const nextConfigOptions =
probeCurrentModelValue === modelSlug
? probeConfigOptions
: yield* probeAcp
.setConfigOption(probeModelOption?.id ?? modelOption.id, modelSlug)
.pipe(Effect.map((response) => response.configOptions ?? probeConfigOptions));
return [
modelSlug,
buildCursorCapabilitiesFromConfigOptions(nextConfigOptions),
] as const;
}),
).pipe(
Effect.timeout(CURSOR_ACP_MODEL_CAPABILITY_TIMEOUT),
Effect.retry({ times: 3 }),
Effect.withSpan("cursor-acp-model-capability-probe"),
Effect.catchCause((cause) =>
Effect.logWarning("Cursor ACP capability probe failed", {
modelSlug,
cause: Cause.pretty(cause),
}),
),
);
},
{ concurrency: CURSOR_ACP_MODEL_DISCOVERY_CONCURRENCY },
);
for (const entry of probedCapabilities) {
if (!entry) {
continue;
}
capabilitiesBySlug.set(entry[0], entry[1]);
}
return buildCursorDiscoveredModels(
modelChoices.map((modelChoice) => ({
slug: modelChoice.value.trim(),
name: modelChoice.name.trim(),
capabilities: capabilitiesBySlug.get(modelChoice.value.trim()) ?? EMPTY_CAPABILITIES,
})),
);
}).pipe(Effect.withSpan("cursor-acp-model-capability-discovery", {})),
);
export function getCursorFallbackModels(
@@ -719,9 +683,10 @@ export function buildCursorProviderSnapshot(input: {
readonly parsed: CursorAboutResult;
readonly discoveredModels?: ReadonlyArray<ServerProviderModel>;
readonly discoveryWarning?: string;
}): ServerProviderDraft {
}): ServerProvider {
const message = joinProviderMessages(input.parsed.message, input.discoveryWarning);
return buildServerProvider({
provider: PROVIDER,
presentation: CURSOR_PRESENTATION,
enabled: input.cursorSettings.enabled,
checkedAt: input.checkedAt,
@@ -846,13 +811,14 @@ function isCursorAboutJsonFormatUnsupported(result: CommandResult): boolean {
);
}
const readCursorCliConfigChannel = Effect.fn("readCursorCliConfigChannel")(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const configPath = path.join(nodeOs.homedir(), ".cursor", "cli-config.json");
const raw = yield* fileSystem.readFileString(configPath).pipe(Effect.orElseSucceed(() => ""));
return parseCursorCliConfigChannel(raw);
});
function readCursorCliConfigChannel(): string | undefined {
try {
const configPath = nodePath.join(nodeOs.homedir(), ".cursor", "cli-config.json");
return parseCursorCliConfigChannel(nodeFs.readFileSync(configPath, "utf8"));
} catch {
return undefined;
}
}
export function getCursorParameterizedModelPickerUnsupportedMessage(input: {
readonly version: string | null | undefined;
@@ -968,7 +934,6 @@ export function parseCursorAboutOutput(result: CommandResult): CursorAboutResult
status: "ready",
auth: {
status: "authenticated",
email: userEmail,
...authMetadata,
},
};
@@ -1024,22 +989,17 @@ export function parseCursorAboutOutput(result: CommandResult): CursorAboutResult
}
// Any non-empty email value means authenticated.
return {
version,
status: "ready",
auth: { status: "authenticated", email: userEmail },
};
return { version, status: "ready", auth: { status: "authenticated" } };
}
const runCursorCommand = (
cursorSettings: CursorSettings,
args: ReadonlyArray<string>,
environment: NodeJS.ProcessEnv = process.env,
) =>
const runCursorCommand = (args: ReadonlyArray<string>) =>
Effect.gen(function* () {
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
const cursorSettings = yield* Effect.service(ServerSettingsService).pipe(
Effect.flatMap((service) => service.getSettings),
Effect.map((settings) => settings.providers.cursor),
);
const command = ChildProcess.make(cursorSettings.binaryPath, [...args], {
env: environment,
shell: process.platform === "win32",
});
@@ -1056,202 +1016,203 @@ const runCursorCommand = (
return { stdout, stderr, code: exitCode } satisfies CommandResult;
}).pipe(Effect.scoped);
const runCursorAboutCommand = (
cursorSettings: CursorSettings,
environment: NodeJS.ProcessEnv = process.env,
) =>
Effect.gen(function* () {
const jsonResult = yield* runCursorCommand(
cursorSettings,
["about", "--format", "json"],
environment,
);
if (!isCursorAboutJsonFormatUnsupported(jsonResult)) {
return jsonResult;
}
return yield* runCursorCommand(cursorSettings, ["about"], environment);
});
export const checkCursorProviderStatus = Effect.fn("checkCursorProviderStatus")(function* (
cursorSettings: CursorSettings,
environment: NodeJS.ProcessEnv = process.env,
): Effect.fn.Return<
ServerProviderDraft,
never,
ChildProcessSpawner.ChildProcessSpawner | FileSystem.FileSystem | Path.Path
> {
const checkedAt = new Date().toISOString();
const fallbackModels = getCursorFallbackModels(cursorSettings);
if (!cursorSettings.enabled) {
return buildServerProvider({
presentation: CURSOR_PRESENTATION,
enabled: false,
checkedAt,
models: fallbackModels,
probe: {
installed: false,
version: null,
status: "warning",
auth: { status: "unknown" },
message: "Cursor is disabled in T3 Code settings.",
},
});
const runCursorAboutCommand = Effect.gen(function* () {
const jsonResult = yield* runCursorCommand(["about", "--format", "json"]);
if (!isCursorAboutJsonFormatUnsupported(jsonResult)) {
return jsonResult;
}
// Single `agent about` probe: returns version + auth status in one call.
const aboutProbe = yield* runCursorAboutCommand(cursorSettings, environment).pipe(
Effect.timeoutOption(ABOUT_TIMEOUT_MS),
Effect.result,
);
if (Result.isFailure(aboutProbe)) {
const error = aboutProbe.failure;
return buildServerProvider({
presentation: CURSOR_PRESENTATION,
enabled: cursorSettings.enabled,
checkedAt,
models: fallbackModels,
probe: {
installed: !isCommandMissingCause(error),
version: null,
status: "error",
auth: { status: "unknown" },
message: isCommandMissingCause(error)
? "Cursor Agent CLI (`agent`) is not installed or not on PATH."
: `Failed to execute Cursor Agent CLI health check: ${error instanceof Error ? error.message : String(error)}.`,
},
});
}
if (Option.isNone(aboutProbe.success)) {
return buildServerProvider({
presentation: CURSOR_PRESENTATION,
enabled: cursorSettings.enabled,
checkedAt,
models: fallbackModels,
probe: {
installed: true,
version: null,
status: "error",
auth: { status: "unknown" },
message: "Cursor Agent CLI is installed but timed out while running `agent about`.",
},
});
}
const parsed = parseCursorAboutOutput(aboutProbe.success.value);
const cursorCliConfigChannel = yield* readCursorCliConfigChannel();
const parameterizedModelPickerUnsupportedMessage =
getCursorParameterizedModelPickerUnsupportedMessage({
version: parsed.version,
channel: cursorCliConfigChannel,
});
if (parameterizedModelPickerUnsupportedMessage) {
return buildServerProvider({
presentation: CURSOR_PRESENTATION,
enabled: cursorSettings.enabled,
checkedAt,
models: fallbackModels,
probe: {
installed: true,
version: parsed.version,
status: "error",
auth: parsed.auth,
message:
parsed.auth.status === "unauthenticated" && parsed.message
? `${parameterizedModelPickerUnsupportedMessage} ${parsed.message}`
: parameterizedModelPickerUnsupportedMessage,
},
});
}
let discoveredModels = Option.none<ReadonlyArray<ServerProviderModel>>();
let discoveryWarning: string | undefined;
if (parsed.auth.status !== "unauthenticated") {
const discoveryExit = yield* Effect.exit(
discoverCursorModelsViaAcp(cursorSettings, environment).pipe(
Effect.timeoutOption(CURSOR_ACP_MODEL_DISCOVERY_TIMEOUT_MS),
),
);
if (Exit.isFailure(discoveryExit)) {
yield* Effect.logWarning("Cursor ACP model discovery failed", {
cause: Cause.pretty(discoveryExit.cause),
});
discoveryWarning = "Cursor ACP model discovery failed. Check server logs for details.";
} else if (Option.isNone(discoveryExit.value)) {
discoveryWarning = `Cursor ACP model discovery timed out after ${CURSOR_ACP_MODEL_DISCOVERY_TIMEOUT_MS}ms.`;
} else if (discoveryExit.value.value.length === 0) {
discoveryWarning = "Cursor ACP model discovery returned no built-in models.";
} else {
discoveredModels = discoveryExit.value;
}
}
return buildCursorProviderSnapshot({
checkedAt,
cursorSettings,
parsed,
discoveredModels: Option.getOrElse(
Option.filter(discoveredModels, (models) => models.length > 0),
() => [] as const,
),
...(discoveryWarning ? { discoveryWarning } : {}),
});
return yield* runCursorCommand(["about"]);
});
export function hasUncapturedCursorModels(snapshot: Pick<ServerProvider, "models">): boolean {
return snapshot.models.some((model) => !model.isCustom && !hasCursorModelCapabilities(model));
}
export const checkCursorProviderStatus = Effect.fn("checkCursorProviderStatus")(
function* (): Effect.fn.Return<
ServerProvider,
ServerSettingsError,
ChildProcessSpawner.ChildProcessSpawner | ServerSettingsService
> {
const cursorSettings = yield* Effect.service(ServerSettingsService).pipe(
Effect.flatMap((service) => service.getSettings),
Effect.map((settings) => settings.providers.cursor),
);
const checkedAt = new Date().toISOString();
const fallbackModels = getCursorFallbackModels(cursorSettings);
/**
* Background capability enrichment for a Cursor snapshot.
*
* Used by `CursorDriver` as the `makeManagedServerProvider.enrichSnapshot`
* hook: runs the slow ACP per-model capability probe, and republishes the
* snapshot through `publishSnapshot` when new capabilities arrive. Skips
* the probe when the provider is disabled, unauthenticated, or has no
* uncaptured models. Keeps `EMPTY_CAPABILITIES` and the `PROVIDER` literal
* private to this module.
*/
export const enrichCursorSnapshot = (input: {
readonly settings: CursorSettings;
readonly environment?: NodeJS.ProcessEnv;
readonly snapshot: ServerProvider;
readonly publishSnapshot: (snapshot: ServerProvider) => Effect.Effect<void>;
readonly stampIdentity?: (snapshot: ServerProvider) => ServerProvider;
}): Effect.Effect<void, never, ChildProcessSpawner.ChildProcessSpawner> => {
const { settings, snapshot, publishSnapshot } = input;
const stampIdentity = input.stampIdentity ?? ((value) => value);
if (!cursorSettings.enabled) {
return buildServerProvider({
provider: PROVIDER,
presentation: CURSOR_PRESENTATION,
enabled: false,
checkedAt,
models: fallbackModels,
probe: {
installed: false,
version: null,
status: "warning",
auth: { status: "unknown" },
message: "Cursor is disabled in T3 Code settings.",
},
});
}
if (
!settings.enabled ||
snapshot.auth.status === "unauthenticated" ||
!hasUncapturedCursorModels(snapshot)
) {
return Effect.void;
}
// Single `agent about` probe: returns version + auth status in one call.
const aboutProbe = yield* runCursorAboutCommand.pipe(
Effect.timeoutOption(ABOUT_TIMEOUT_MS),
Effect.result,
);
return discoverCursorModelCapabilitiesViaAcp(settings, snapshot.models, input.environment).pipe(
Effect.flatMap((discoveredModels) => {
if (discoveredModels.length === 0) {
return Effect.void;
}
return publishSnapshot(
stampIdentity({
...snapshot,
models: providerModelsFromSettings(
discoveredModels,
PROVIDER,
settings.customModels,
EMPTY_CAPABILITIES,
),
}),
if (Result.isFailure(aboutProbe)) {
const error = aboutProbe.failure;
return buildServerProvider({
provider: PROVIDER,
presentation: CURSOR_PRESENTATION,
enabled: cursorSettings.enabled,
checkedAt,
models: fallbackModels,
probe: {
installed: !isCommandMissingCause(error),
version: null,
status: "error",
auth: { status: "unknown" },
message: isCommandMissingCause(error)
? "Cursor Agent CLI (`agent`) is not installed or not on PATH."
: `Failed to execute Cursor Agent CLI health check: ${error instanceof Error ? error.message : String(error)}.`,
},
});
}
if (Option.isNone(aboutProbe.success)) {
return buildServerProvider({
provider: PROVIDER,
presentation: CURSOR_PRESENTATION,
enabled: cursorSettings.enabled,
checkedAt,
models: fallbackModels,
probe: {
installed: true,
version: null,
status: "error",
auth: { status: "unknown" },
message: "Cursor Agent CLI is installed but timed out while running `agent about`.",
},
});
}
const parsed = parseCursorAboutOutput(aboutProbe.success.value);
const parameterizedModelPickerUnsupportedMessage =
getCursorParameterizedModelPickerUnsupportedMessage({
version: parsed.version,
channel: readCursorCliConfigChannel(),
});
if (parameterizedModelPickerUnsupportedMessage) {
return buildServerProvider({
provider: PROVIDER,
presentation: CURSOR_PRESENTATION,
enabled: cursorSettings.enabled,
checkedAt,
models: fallbackModels,
probe: {
installed: true,
version: parsed.version,
status: "error",
auth: parsed.auth,
message:
parsed.auth.status === "unauthenticated" && parsed.message
? `${parameterizedModelPickerUnsupportedMessage} ${parsed.message}`
: parameterizedModelPickerUnsupportedMessage,
},
});
}
let discoveredModels = Option.none<ReadonlyArray<ServerProviderModel>>();
let discoveryWarning: string | undefined;
if (parsed.auth.status !== "unauthenticated") {
const discoveryExit = yield* Effect.exit(
discoverCursorModelsViaAcp(cursorSettings).pipe(
Effect.timeoutOption(CURSOR_ACP_MODEL_DISCOVERY_TIMEOUT_MS),
),
);
}),
Effect.catchCause((cause) =>
Effect.logWarning("Cursor ACP background capability enrichment failed", {
models: snapshot.models.map((model) => model.slug),
cause: Cause.pretty(cause),
}).pipe(Effect.asVoid),
),
);
};
if (Exit.isFailure(discoveryExit)) {
yield* Effect.logWarning("Cursor ACP model discovery failed", {
cause: Cause.pretty(discoveryExit.cause),
});
discoveryWarning = "Cursor ACP model discovery failed. Check server logs for details.";
} else if (Option.isNone(discoveryExit.value)) {
discoveryWarning = `Cursor ACP model discovery timed out after ${CURSOR_ACP_MODEL_DISCOVERY_TIMEOUT_MS}ms.`;
} else if (discoveryExit.value.value.length === 0) {
discoveryWarning = "Cursor ACP model discovery returned no built-in models.";
} else {
discoveredModels = discoveryExit.value;
}
}
return buildCursorProviderSnapshot({
checkedAt,
cursorSettings,
parsed,
discoveredModels: Option.getOrElse(
Option.filter(discoveredModels, (models) => models.length > 0),
() => [] as const,
),
...(discoveryWarning ? { discoveryWarning } : {}),
});
},
);
export const CursorProviderLive = Layer.effect(
CursorProvider,
Effect.gen(function* () {
const serverSettings = yield* ServerSettingsService;
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
const checkProvider = checkCursorProviderStatus().pipe(
Effect.provideService(ServerSettingsService, serverSettings),
Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
);
return yield* makeManagedServerProvider<CursorSettings>({
getSettings: serverSettings.getSettings.pipe(
Effect.map((settings) => settings.providers.cursor),
Effect.orDie,
),
streamSettings: serverSettings.streamChanges.pipe(
Stream.map((settings) => settings.providers.cursor),
),
haveSettingsChanged: (previous, next) => !Equal.equals(previous, next),
initialSnapshot: buildInitialCursorProviderSnapshot,
checkProvider,
enrichSnapshot: ({ settings, snapshot, publishSnapshot }) => {
if (
!settings.enabled ||
snapshot.auth.status === "unauthenticated" ||
!snapshot.models.some((model) => !model.isCustom && !hasCursorModelCapabilities(model))
) {
return Effect.void;
}
return discoverCursorModelCapabilitiesViaAcp(settings, snapshot.models).pipe(
Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
Effect.flatMap((discoveredModels) => {
if (discoveredModels.length === 0) {
return Effect.void;
}
return publishSnapshot({
...snapshot,
models: providerModelsFromSettings(
discoveredModels,
PROVIDER,
settings.customModels,
EMPTY_CAPABILITIES,
),
});
}),
Effect.catchCause((cause) =>
Effect.logWarning("Cursor ACP background capability enrichment failed", {
models: snapshot.models.map((model) => model.slug),
cause: Cause.pretty(cause),
}).pipe(Effect.asVoid),
),
);
},
refreshInterval: CURSOR_REFRESH_INTERVAL,
});
}),
);
@@ -2,20 +2,14 @@ import assert from "node:assert/strict";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { it } from "@effect/vitest";
import { Context, Effect, Exit, Fiber, Layer, Option, Schema, Scope, Stream } from "effect";
import { Effect, Layer, Option } from "effect";
import { beforeEach } from "vitest";
import {
OpenCodeSettings,
ProviderDriverKind,
ProviderInstanceId,
ThreadId,
} from "@t3tools/contracts";
import { createModelSelection } from "@t3tools/shared/model";
import { ThreadId } from "@t3tools/contracts";
import { ServerConfig } from "../../config.ts";
import { ServerSettingsService } from "../../serverSettings.ts";
import { ProviderSessionDirectory } from "../Services/ProviderSessionDirectory.ts";
import type { OpenCodeAdapterShape } from "../Services/OpenCodeAdapter.ts";
import { OpenCodeAdapter } from "../Services/OpenCodeAdapter.ts";
import {
OpenCodeRuntime,
OpenCodeRuntimeError,
@@ -23,15 +17,10 @@ import {
} from "../opencodeRuntime.ts";
import {
appendOpenCodeAssistantTextDelta,
makeOpenCodeAdapter,
makeOpenCodeAdapterLive,
mergeOpenCodeAssistantText,
} from "./OpenCodeAdapter.ts";
// Test-local service tag so the rest of the file can keep using `yield* OpenCodeAdapter`.
class OpenCodeAdapter extends Context.Service<OpenCodeAdapter, OpenCodeAdapterShape>()(
"test/OpenCodeAdapter",
) {}
const asThreadId = (value: string): ThreadId => ThreadId.make(value);
type MessageEntry = {
@@ -50,7 +39,6 @@ const runtimeMock = {
abortCalls: [] as string[],
closeCalls: [] as string[],
revertCalls: [] as Array<{ sessionID: string; messageID?: string }>,
promptCalls: [] as Array<unknown>,
promptAsyncError: null as Error | null,
closeError: null as Error | null,
messages: [] as MessageEntry[],
@@ -63,7 +51,6 @@ const runtimeMock = {
this.state.abortCalls.length = 0;
this.state.closeCalls.length = 0;
this.state.revertCalls.length = 0;
this.state.promptCalls.length = 0;
this.state.promptAsyncError = null;
this.state.closeError = null;
this.state.messages = [];
@@ -124,8 +111,7 @@ const OpenCodeRuntimeTestDouble: OpenCodeRuntimeShape = {
abort: async ({ sessionID }: { sessionID: string }) => {
runtimeMock.state.abortCalls.push(sessionID);
},
promptAsync: async (input: unknown) => {
runtimeMock.state.promptCalls.push(input);
promptAsync: async () => {
if (runtimeMock.state.promptAsyncError) {
throw runtimeMock.state.promptAsyncError;
}
@@ -179,24 +165,7 @@ const providerSessionDirectoryTestLayer = Layer.succeed(ProviderSessionDirectory
listBindings: () => Effect.succeed([]),
});
// The adapter now receives its settings as a plain argument (the old design
// read from `ServerSettingsService` internally). The test-only
// `ServerSettingsService` below is still kept because other dependencies in
// the layer graph reach for it — but the routing values the assertions
// probe (serverUrl, serverPassword) must be threaded directly through the
// decoded `OpenCodeSettings`.
const openCodeAdapterTestSettings = Schema.decodeSync(OpenCodeSettings)({
binaryPath: "fake-opencode",
serverUrl: "http://127.0.0.1:9999",
serverPassword: "secret-password",
});
const OpenCodeAdapterTestLayer = Layer.effect(
OpenCodeAdapter,
Effect.gen(function* () {
return yield* makeOpenCodeAdapter(openCodeAdapterTestSettings);
}),
).pipe(
const OpenCodeAdapterTestLayer = makeOpenCodeAdapterLive().pipe(
Layer.provideMerge(Layer.succeed(OpenCodeRuntime, OpenCodeRuntimeTestDouble)),
Layer.provideMerge(ServerConfig.layerTest(process.cwd(), process.cwd())),
Layer.provideMerge(
@@ -227,7 +196,7 @@ it.layer(OpenCodeAdapterTestLayer)("OpenCodeAdapterLive", (it) => {
const adapter = yield* OpenCodeAdapter;
const session = yield* adapter.startSession({
provider: ProviderDriverKind.make("opencode"),
provider: "opencode",
threadId: asThreadId("thread-opencode"),
runtimeMode: "full-access",
});
@@ -246,7 +215,7 @@ it.layer(OpenCodeAdapterTestLayer)("OpenCodeAdapterLive", (it) => {
Effect.gen(function* () {
const adapter = yield* OpenCodeAdapter;
yield* adapter.startSession({
provider: ProviderDriverKind.make("opencode"),
provider: "opencode",
threadId: asThreadId("thread-opencode"),
runtimeMode: "full-access",
});
@@ -261,42 +230,16 @@ it.layer(OpenCodeAdapterTestLayer)("OpenCodeAdapterLive", (it) => {
}),
);
it.effect("emits one session.exited event when stopping a session", () =>
Effect.gen(function* () {
const adapter = yield* OpenCodeAdapter;
const threadId = asThreadId("thread-opencode-stop-event");
const eventsFiber = yield* adapter.streamEvents.pipe(
Stream.filter((event) => event.threadId === threadId),
Stream.take(3),
Stream.runCollect,
Effect.forkChild,
);
yield* adapter.startSession({
provider: ProviderDriverKind.make("opencode"),
threadId,
runtimeMode: "full-access",
});
yield* adapter.stopSession(threadId);
const events = Array.from(yield* Fiber.join(eventsFiber).pipe(Effect.timeout("1 second")));
assert.deepEqual(
events.map((event) => event.type),
["session.started", "thread.started", "session.exited"],
);
}),
);
it.effect("clears session state even when cleanup finalizers throw", () =>
Effect.gen(function* () {
const adapter = yield* OpenCodeAdapter;
yield* adapter.startSession({
provider: ProviderDriverKind.make("opencode"),
provider: "opencode",
threadId: asThreadId("thread-stop-all-a"),
runtimeMode: "full-access",
});
yield* adapter.startSession({
provider: ProviderDriverKind.make("opencode"),
provider: "opencode",
threadId: asThreadId("thread-stop-all-b"),
runtimeMode: "full-access",
});
@@ -318,44 +261,11 @@ it.layer(OpenCodeAdapterTestLayer)("OpenCodeAdapterLive", (it) => {
}),
);
it.effect("completes streamEvents when the adapter scope closes", () =>
Effect.gen(function* () {
const scope = yield* Scope.make("sequential");
let scopeClosed = false;
try {
const adapterLayer = Layer.effect(
OpenCodeAdapter,
makeOpenCodeAdapter(openCodeAdapterTestSettings),
).pipe(
Layer.provideMerge(Layer.succeed(OpenCodeRuntime, OpenCodeRuntimeTestDouble)),
Layer.provideMerge(ServerConfig.layerTest(process.cwd(), process.cwd())),
Layer.provideMerge(ServerSettingsService.layerTest()),
Layer.provideMerge(providerSessionDirectoryTestLayer),
Layer.provideMerge(NodeServices.layer),
);
const context = yield* Layer.buildWithScope(adapterLayer, scope);
const adapter = yield* Effect.service(OpenCodeAdapter).pipe(Effect.provide(context));
const eventsFiber = yield* adapter.streamEvents.pipe(Stream.runCollect, Effect.forkChild);
yield* Scope.close(scope, Exit.void);
scopeClosed = true;
const exit = yield* Fiber.await(eventsFiber).pipe(Effect.timeout("1 second"));
assert.equal(Exit.hasInterrupts(exit), true);
} finally {
if (!scopeClosed) {
yield* Scope.close(scope, Exit.void).pipe(Effect.ignore);
}
}
}),
);
it.effect("rolls back session state when sendTurn fails before OpenCode accepts the prompt", () =>
Effect.gen(function* () {
const adapter = yield* OpenCodeAdapter;
yield* adapter.startSession({
provider: ProviderDriverKind.make("opencode"),
provider: "opencode",
threadId: asThreadId("thread-send-turn-failure"),
runtimeMode: "full-access",
});
@@ -366,7 +276,7 @@ it.layer(OpenCodeAdapterTestLayer)("OpenCodeAdapterLive", (it) => {
threadId: asThreadId("thread-send-turn-failure"),
input: "Fix it",
modelSelection: {
instanceId: ProviderInstanceId.make("opencode"),
provider: "opencode",
model: "openai/gpt-5",
},
})
@@ -389,158 +299,12 @@ it.layer(OpenCodeAdapterTestLayer)("OpenCodeAdapterLive", (it) => {
}),
);
it.effect("passes agent and variant options for the adapter's bound custom instance id", () => {
const customInstanceId = ProviderInstanceId.make("opencode_zen");
const adapterLayer = Layer.effect(
OpenCodeAdapter,
Effect.gen(function* () {
return yield* makeOpenCodeAdapter(openCodeAdapterTestSettings, {
instanceId: customInstanceId,
});
}),
).pipe(
Layer.provideMerge(Layer.succeed(OpenCodeRuntime, OpenCodeRuntimeTestDouble)),
Layer.provideMerge(ServerConfig.layerTest(process.cwd(), process.cwd())),
Layer.provideMerge(ServerSettingsService.layerTest()),
Layer.provideMerge(providerSessionDirectoryTestLayer),
Layer.provideMerge(NodeServices.layer),
);
return Effect.gen(function* () {
const adapter = yield* OpenCodeAdapter;
yield* adapter.startSession({
provider: ProviderDriverKind.make("opencode"),
threadId: asThreadId("thread-custom-instance"),
runtimeMode: "full-access",
});
yield* adapter.sendTurn({
threadId: asThreadId("thread-custom-instance"),
input: "Fix it",
modelSelection: createModelSelection(
ProviderInstanceId.make("opencode_zen"),
"anthropic/claude-sonnet-4-5",
[
{ id: "agent", value: "github-copilot" },
{ id: "variant", value: "high" },
],
),
});
assert.deepEqual(runtimeMock.state.promptCalls.at(-1), {
sessionID: "http://127.0.0.1:9999/session",
model: {
providerID: "anthropic",
modelID: "claude-sonnet-4-5",
},
agent: "github-copilot",
variant: "high",
parts: [{ type: "text", text: "Fix it" }],
});
}).pipe(Effect.provide(adapterLayer));
});
it.effect("uses the bound custom instance id for fallback sendTurn model selection", () => {
const customInstanceId = ProviderInstanceId.make("opencode_zen");
const adapterLayer = Layer.effect(
OpenCodeAdapter,
Effect.gen(function* () {
return yield* makeOpenCodeAdapter(openCodeAdapterTestSettings, {
instanceId: customInstanceId,
});
}),
).pipe(
Layer.provideMerge(Layer.succeed(OpenCodeRuntime, OpenCodeRuntimeTestDouble)),
Layer.provideMerge(ServerConfig.layerTest(process.cwd(), process.cwd())),
Layer.provideMerge(ServerSettingsService.layerTest()),
Layer.provideMerge(providerSessionDirectoryTestLayer),
Layer.provideMerge(NodeServices.layer),
);
return Effect.gen(function* () {
const adapter = yield* OpenCodeAdapter;
const threadId = asThreadId("thread-custom-instance-fallback-model");
yield* adapter.startSession({
provider: ProviderDriverKind.make("opencode"),
threadId,
runtimeMode: "full-access",
modelSelection: createModelSelection(
ProviderInstanceId.make("opencode_zen"),
"anthropic/claude-sonnet-4-5",
),
});
yield* adapter.sendTurn({
threadId,
input: "Fix it",
});
assert.deepEqual(runtimeMock.state.promptCalls.at(-1), {
sessionID: "http://127.0.0.1:9999/session",
model: {
providerID: "anthropic",
modelID: "claude-sonnet-4-5",
},
parts: [{ type: "text", text: "Fix it" }],
});
}).pipe(Effect.provide(adapterLayer));
});
it.effect("rejects sendTurn model selections for another instance id", () => {
const customInstanceId = ProviderInstanceId.make("opencode_zen");
const adapterLayer = Layer.effect(
OpenCodeAdapter,
Effect.gen(function* () {
return yield* makeOpenCodeAdapter(openCodeAdapterTestSettings, {
instanceId: customInstanceId,
});
}),
).pipe(
Layer.provideMerge(Layer.succeed(OpenCodeRuntime, OpenCodeRuntimeTestDouble)),
Layer.provideMerge(ServerConfig.layerTest(process.cwd(), process.cwd())),
Layer.provideMerge(ServerSettingsService.layerTest()),
Layer.provideMerge(providerSessionDirectoryTestLayer),
Layer.provideMerge(NodeServices.layer),
);
return Effect.gen(function* () {
const adapter = yield* OpenCodeAdapter;
const threadId = asThreadId("thread-custom-instance-wrong-selection");
yield* adapter.startSession({
provider: ProviderDriverKind.make("opencode"),
threadId,
runtimeMode: "full-access",
});
const error = yield* adapter
.sendTurn({
threadId,
input: "Fix it",
modelSelection: createModelSelection(
ProviderInstanceId.make("opencode"),
"anthropic/claude-sonnet-4-5",
),
})
.pipe(Effect.flip);
assert.equal(error._tag, "ProviderAdapterValidationError");
if (error._tag !== "ProviderAdapterValidationError") {
throw new Error("Unexpected error type");
}
assert.equal(
error.issue,
"OpenCode model selection is bound to instance 'opencode', expected 'opencode_zen'.",
);
assert.deepEqual(runtimeMock.state.promptCalls, []);
}).pipe(Effect.provide(adapterLayer));
});
it.effect("reverts the full thread when rollback removes every assistant turn", () =>
Effect.gen(function* () {
const adapter = yield* OpenCodeAdapter;
const threadId = asThreadId("thread-rollback-all");
yield* adapter.startSession({
provider: ProviderDriverKind.make("opencode"),
provider: "opencode",
threadId,
runtimeMode: "full-access",
});
@@ -632,14 +396,9 @@ it.layer(OpenCodeAdapterTestLayer)("OpenCodeAdapterLive", (it) => {
close: () => Effect.void,
};
const adapterLayer = Layer.effect(
OpenCodeAdapter,
Effect.gen(function* () {
return yield* makeOpenCodeAdapter(openCodeAdapterTestSettings, {
nativeEventLogger,
});
}),
).pipe(
const adapterLayer = makeOpenCodeAdapterLive({
nativeEventLogger,
}).pipe(
Layer.provideMerge(Layer.succeed(OpenCodeRuntime, OpenCodeRuntimeTestDouble)),
Layer.provideMerge(ServerConfig.layerTest(process.cwd(), process.cwd())),
Layer.provideMerge(
@@ -660,7 +419,7 @@ it.layer(OpenCodeAdapterTestLayer)("OpenCodeAdapterLive", (it) => {
const session = yield* Effect.gen(function* () {
const adapter = yield* OpenCodeAdapter;
const started = yield* adapter.startSession({
provider: ProviderDriverKind.make("opencode"),
provider: "opencode",
threadId: asThreadId("thread-native-log"),
runtimeMode: "full-access",
});
@@ -716,12 +475,9 @@ it.layer(OpenCodeAdapterTestLayer)("OpenCodeAdapterLive", (it) => {
close: () => Effect.void,
};
const adapterLayer = Layer.effect(
OpenCodeAdapter,
makeOpenCodeAdapter(openCodeAdapterTestSettings, {
nativeEventLogger,
}),
).pipe(
const adapterLayer = makeOpenCodeAdapterLive({
nativeEventLogger,
}).pipe(
Layer.provideMerge(Layer.succeed(OpenCodeRuntime, OpenCodeRuntimeTestDouble)),
Layer.provideMerge(ServerConfig.layerTest(process.cwd(), process.cwd())),
Layer.provideMerge(
@@ -748,7 +504,7 @@ it.layer(OpenCodeAdapterTestLayer)("OpenCodeAdapterLive", (it) => {
const { sessions, closeCallsDuringRun } = yield* Effect.gen(function* () {
const adapter = yield* OpenCodeAdapter;
yield* adapter.startSession({
provider: ProviderDriverKind.make("opencode"),
provider: "opencode",
threadId: asThreadId("thread-native-log-failure"),
runtimeMode: "full-access",
});
File diff suppressed because it is too large. Load diff
@@ -2,36 +2,27 @@ import assert from "node:assert/strict";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { it } from "@effect/vitest";
import { Effect, Layer, Schema } from "effect";
import { Effect, Layer } from "effect";
import { beforeEach } from "vitest";
import { OpenCodeSettings } from "@t3tools/contracts";
import { ServerConfig } from "../../config.ts";
import { ServerSettingsService } from "../../serverSettings.ts";
import { OpenCodeProvider } from "../Services/OpenCodeProvider.ts";
import {
OpenCodeRuntime,
OpenCodeRuntimeError,
type OpenCodeRuntimeShape,
} from "../opencodeRuntime.ts";
import { checkOpenCodeProviderStatus } from "./OpenCodeProvider.ts";
import { OpenCodeProviderLive } from "./OpenCodeProvider.ts";
import type { OpenCodeInventory } from "../opencodeRuntime.ts";
const DEFAULT_VERSION_STDOUT = "opencode 1.14.19\n";
/**
* The legacy `OpenCodeProviderLive` Layer + `OpenCodeProvider` service tag
* are deleted. The snapshot-producing logic they wrapped now lives in the
* standalone `checkOpenCodeProviderStatus(settings, cwd)` Effect, which
* drivers call directly when building their per-instance snapshot
* `ServerProviderShape`. Tests mirror that shape: build a settings payload,
* invoke the check, assert on the returned snapshot.
*/
const runtimeMock = {
state: {
runVersionError: null as Error | null,
versionStdout: DEFAULT_VERSION_STDOUT,
inventoryError: null as Error | null,
closeCalls: 0,
inventory: {
providerList: { connected: [] as string[], all: [] as unknown[], default: {} },
agents: [] as unknown[],
@@ -41,7 +32,6 @@ const runtimeMock = {
this.state.runVersionError = null;
this.state.versionStdout = DEFAULT_VERSION_STDOUT;
this.state.inventoryError = null;
this.state.closeCalls = 0;
this.state.inventory = {
providerList: { connected: [], all: [] as unknown[], default: {} },
agents: [] as unknown[],
@@ -56,19 +46,10 @@ const OpenCodeRuntimeTestDouble: OpenCodeRuntimeShape = {
exitCode: Effect.never,
}),
connectToOpenCodeServer: ({ serverUrl }) =>
Effect.gen(function* () {
if (!serverUrl) {
yield* Effect.addFinalizer(() =>
Effect.sync(() => {
runtimeMock.state.closeCalls += 1;
}),
);
}
return {
url: serverUrl ?? "http://127.0.0.1:4301",
exitCode: null,
external: Boolean(serverUrl),
};
Effect.succeed({
url: serverUrl ?? "http://127.0.0.1:4301",
exitCode: null,
external: Boolean(serverUrl),
}),
runOpenCodeCommand: () =>
runtimeMock.state.runVersionError
@@ -98,26 +79,20 @@ beforeEach(() => {
runtimeMock.reset();
});
const testLayer = Layer.succeed(OpenCodeRuntime, OpenCodeRuntimeTestDouble).pipe(
Layer.provideMerge(ServerConfig.layerTest(process.cwd(), process.cwd())),
Layer.provideMerge(NodeServices.layer),
);
const makeTestLayer = (settingsOverrides?: Parameters<typeof ServerSettingsService.layerTest>[0]) =>
OpenCodeProviderLive.pipe(
Layer.provideMerge(Layer.succeed(OpenCodeRuntime, OpenCodeRuntimeTestDouble)),
Layer.provideMerge(ServerConfig.layerTest(process.cwd(), process.cwd())),
Layer.provideMerge(ServerSettingsService.layerTest(settingsOverrides)),
Layer.provideMerge(NodeServices.layer),
);
const makeOpenCodeSettings = (overrides?: Partial<OpenCodeSettings>): OpenCodeSettings =>
Schema.decodeSync(OpenCodeSettings)({
enabled: true,
binaryPath: "opencode",
serverUrl: "",
serverPassword: "",
customModels: [],
...overrides,
});
it.layer(testLayer)("checkOpenCodeProviderStatus", (it) => {
it.layer(makeTestLayer())("OpenCodeProviderLive", (it) => {
it.effect("shows a codex-style missing binary message", () =>
Effect.gen(function* () {
runtimeMock.state.runVersionError = new Error("spawn opencode ENOENT");
const snapshot = yield* checkOpenCodeProviderStatus(makeOpenCodeSettings(), process.cwd());
const provider = yield* OpenCodeProvider;
const snapshot = yield* provider.refresh;
assert.equal(snapshot.status, "error");
assert.equal(snapshot.installed, false);
@@ -128,7 +103,8 @@ it.layer(testLayer)("checkOpenCodeProviderStatus", (it) => {
it.effect("hides generic Effect.tryPromise text for local CLI probe failures", () =>
Effect.gen(function* () {
runtimeMock.state.runVersionError = new Error("An error occurred in Effect.tryPromise");
const snapshot = yield* checkOpenCodeProviderStatus(makeOpenCodeSettings(), process.cwd());
const provider = yield* OpenCodeProvider;
const snapshot = yield* provider.refresh;
assert.equal(snapshot.status, "error");
assert.equal(snapshot.installed, true);
@@ -136,6 +112,33 @@ it.layer(testLayer)("checkOpenCodeProviderStatus", (it) => {
}),
);
it.effect("refuses to probe when opencode is older than the required minimum", () =>
Effect.gen(function* () {
runtimeMock.state.versionStdout = "opencode 1.4.7\n";
const provider = yield* OpenCodeProvider;
const snapshot = yield* provider.refresh;
assert.equal(snapshot.status, "error");
assert.equal(snapshot.installed, true);
assert.equal(snapshot.version, "1.4.7");
assert.ok(snapshot.message?.includes("1.14.19"));
assert.ok(snapshot.message?.toLowerCase().includes("upgrade"));
}),
);
it.effect("refuses to probe when opencode --version output is unparseable", () =>
Effect.gen(function* () {
runtimeMock.state.versionStdout = "garbled binary output\n";
const provider = yield* OpenCodeProvider;
const snapshot = yield* provider.refresh;
assert.equal(snapshot.status, "error");
assert.equal(snapshot.installed, true);
assert.equal(snapshot.version, null);
assert.ok(snapshot.message?.includes("1.14.19"));
}),
);
it.effect("emits OpenCode variant defaults so trait picker can resolve a visible selection", () =>
Effect.gen(function* () {
runtimeMock.state.inventory = {
@@ -168,7 +171,8 @@ it.layer(testLayer)("checkOpenCodeProviderStatus", (it) => {
],
};
const snapshot = yield* checkOpenCodeProviderStatus(makeOpenCodeSettings(), process.cwd());
const provider = yield* OpenCodeProvider;
const snapshot = yield* provider.refresh;
const model = snapshot.models.find((entry) => entry.slug === "openai/gpt-5.4");
assert.ok(model);
@@ -176,41 +180,31 @@ it.layer(testLayer)("checkOpenCodeProviderStatus", (it) => {
(descriptor) => descriptor.id === "variant" && descriptor.type === "select",
);
assert.ok(variantDescriptor && variantDescriptor.type === "select");
assert.equal(
variantDescriptor.options.find((option) => option.isDefault === true)?.id,
"medium",
);
assert.equal(variantDescriptor.options.find((option) => option.isDefault)?.id, "medium");
const agentDescriptor = model.capabilities?.optionDescriptors?.find(
(descriptor) => descriptor.id === "agent" && descriptor.type === "select",
);
assert.ok(agentDescriptor && agentDescriptor.type === "select");
assert.equal(
agentDescriptor.options.find((option) => option.isDefault === true)?.id,
"build",
);
}),
);
it.effect("closes the local OpenCode server scope after provider refresh", () =>
Effect.gen(function* () {
yield* checkOpenCodeProviderStatus(makeOpenCodeSettings(), process.cwd());
assert.equal(runtimeMock.state.closeCalls, 1);
assert.equal(agentDescriptor.options.find((option) => option.isDefault)?.id, "build");
}),
);
});
it.layer(testLayer)("checkOpenCodeProviderStatus with configured server URL", (it) => {
it.layer(
makeTestLayer({
providers: {
opencode: {
serverUrl: "http://127.0.0.1:9999",
serverPassword: "secret-password",
},
},
}),
)("OpenCodeProviderLive with configured server URL", (it) => {
it.effect("surfaces a friendly auth error for configured servers", () =>
Effect.gen(function* () {
runtimeMock.state.inventoryError = new Error("401 Unauthorized");
const snapshot = yield* checkOpenCodeProviderStatus(
makeOpenCodeSettings({
serverUrl: "http://127.0.0.1:9999",
serverPassword: "secret-password",
}),
process.cwd(),
);
const provider = yield* OpenCodeProvider;
const snapshot = yield* provider.refresh;
assert.equal(snapshot.status, "error");
assert.equal(snapshot.installed, true);
@@ -226,13 +220,8 @@ it.layer(testLayer)("checkOpenCodeProviderStatus with configured server URL", (i
runtimeMock.state.inventoryError = new Error(
"fetch failed: connect ECONNREFUSED 127.0.0.1:9999",
);
const snapshot = yield* checkOpenCodeProviderStatus(
makeOpenCodeSettings({
serverUrl: "http://127.0.0.1:9999",
serverPassword: "secret-password",
}),
process.cwd(),
);
const provider = yield* OpenCodeProvider;
const snapshot = yield* provider.refresh;
assert.equal(snapshot.status, "error");
assert.equal(snapshot.installed, true);
@@ -1,21 +1,24 @@
import {
ProviderDriverKind,
type ModelCapabilities,
type OpenCodeSettings,
type ServerProviderModel,
import type {
ModelCapabilities,
OpenCodeSettings,
ServerProvider,
ServerProviderModel,
} from "@t3tools/contracts";
import { Cause, Data, Effect } from "effect";
import { Cause, Data, Effect, Equal, Layer, Stream } from "effect";
import { createModelCapabilities } from "@t3tools/shared/model";
import { ServerConfig } from "../../config.ts";
import { ServerSettingsService } from "../../serverSettings.ts";
import { makeManagedServerProvider } from "../makeManagedServerProvider.ts";
import {
buildServerProvider,
nonEmptyTrimmed,
parseGenericCliVersion,
providerModelsFromSettings,
type ServerProviderDraft,
} from "../providerSnapshot.ts";
import { compareCliVersions } from "../cliVersion.ts";
import { OpenCodeProvider } from "../Services/OpenCodeProvider.ts";
import {
OpenCodeRuntime,
openCodeRuntimeErrorDetail,
@@ -23,7 +26,7 @@ import {
} from "../opencodeRuntime.ts";
import type { Agent, ProviderListResponse } from "@opencode-ai/sdk/v2";
const PROVIDER = ProviderDriverKind.make("opencode");
const PROVIDER = "opencode" as const;
const OPENCODE_PRESENTATION = {
displayName: "OpenCode",
showInteractionModeToggle: false,
@@ -248,9 +251,7 @@ function flattenOpenCodeModels(input: OpenCodeInventory): ReadonlyArray<ServerPr
return models.toSorted((left, right) => left.name.localeCompare(right.name));
}
export const makePendingOpenCodeProvider = (
openCodeSettings: OpenCodeSettings,
): ServerProviderDraft => {
const makePendingOpenCodeProvider = (openCodeSettings: OpenCodeSettings): ServerProvider => {
const checkedAt = new Date().toISOString();
const models = providerModelsFromSettings(
[],
@@ -261,6 +262,7 @@ export const makePendingOpenCodeProvider = (
if (!openCodeSettings.enabled) {
return buildServerProvider({
provider: PROVIDER,
presentation: OPENCODE_PRESENTATION,
enabled: false,
checkedAt,
@@ -279,6 +281,7 @@ export const makePendingOpenCodeProvider = (
}
return buildServerProvider({
provider: PROVIDER,
presentation: OPENCODE_PRESENTATION,
enabled: true,
checkedAt,
@@ -293,179 +296,210 @@ export const makePendingOpenCodeProvider = (
});
};
export const checkOpenCodeProviderStatus = Effect.fn("checkOpenCodeProviderStatus")(function* (
openCodeSettings: OpenCodeSettings,
cwd: string,
environment: NodeJS.ProcessEnv = process.env,
): Effect.fn.Return<ServerProviderDraft, never, OpenCodeRuntime> {
const openCodeRuntime = yield* OpenCodeRuntime;
const checkedAt = new Date().toISOString();
const customModels = openCodeSettings.customModels;
const isExternalServer = openCodeSettings.serverUrl.trim().length > 0;
export const OpenCodeProviderLive = Layer.effect(
OpenCodeProvider,
Effect.gen(function* () {
const serverSettings = yield* ServerSettingsService;
const serverConfig = yield* ServerConfig;
const openCodeRuntime = yield* OpenCodeRuntime;
const fallback = (cause: unknown, version: string | null = null) => {
const failure = formatOpenCodeProbeError({
cause,
isExternalServer,
serverUrl: openCodeSettings.serverUrl,
});
return buildServerProvider({
presentation: OPENCODE_PRESENTATION,
enabled: openCodeSettings.enabled,
checkedAt,
models: providerModelsFromSettings(
[],
PROVIDER,
customModels,
DEFAULT_OPENCODE_MODEL_CAPABILITIES,
),
probe: {
installed: failure.installed,
version,
status: "error",
auth: { status: "unknown" },
message: failure.message,
},
});
};
const checkOpenCodeProviderStatus = Effect.fn("checkOpenCodeProviderStatus")(function* (input: {
readonly settings: OpenCodeSettings;
readonly cwd: string;
}): Effect.fn.Return<ServerProvider, never> {
const checkedAt = new Date().toISOString();
const customModels = input.settings.customModels;
const isExternalServer = input.settings.serverUrl.trim().length > 0;
if (!openCodeSettings.enabled) {
return buildServerProvider({
presentation: OPENCODE_PRESENTATION,
enabled: false,
checkedAt,
models: providerModelsFromSettings(
[],
PROVIDER,
customModels,
DEFAULT_OPENCODE_MODEL_CAPABILITIES,
),
probe: {
installed: false,
version: null,
status: "warning",
auth: { status: "unknown" },
message: isExternalServer
? "OpenCode is disabled in T3 Code settings. A server URL is configured."
: "OpenCode is disabled in T3 Code settings.",
},
});
}
let version: string | null = null;
if (!isExternalServer) {
const versionExit = yield* Effect.exit(
openCodeRuntime
.runOpenCodeCommand({
binaryPath: openCodeSettings.binaryPath,
args: ["--version"],
environment,
})
.pipe(
Effect.mapError(
(cause) => new OpenCodeProbeError({ cause, detail: openCodeRuntimeErrorDetail(cause) }),
const fallback = (cause: unknown, version: string | null = null) => {
const failure = formatOpenCodeProbeError({
cause,
isExternalServer,
serverUrl: input.settings.serverUrl,
});
return buildServerProvider({
provider: PROVIDER,
presentation: OPENCODE_PRESENTATION,
enabled: input.settings.enabled,
checkedAt,
models: providerModelsFromSettings(
[],
PROVIDER,
customModels,
DEFAULT_OPENCODE_MODEL_CAPABILITIES,
),
),
);
if (versionExit._tag === "Failure") {
return fallback(Cause.squash(versionExit.cause));
}
version = parseGenericCliVersion(versionExit.value.stdout) ?? null;
probe: {
installed: failure.installed,
version,
status: "error",
auth: { status: "unknown" },
message: failure.message,
},
});
};
if (!version) {
return fallback(
new Error(
`Unable to determine OpenCode version from \`opencode --version\` output. T3 Code requires OpenCode v${MINIMUM_OPENCODE_VERSION} or newer.`,
if (!input.settings.enabled) {
return buildServerProvider({
provider: PROVIDER,
presentation: OPENCODE_PRESENTATION,
enabled: false,
checkedAt,
models: providerModelsFromSettings(
[],
PROVIDER,
customModels,
DEFAULT_OPENCODE_MODEL_CAPABILITIES,
),
probe: {
installed: false,
version: null,
status: "warning",
auth: { status: "unknown" },
message: isExternalServer
? "OpenCode is disabled in T3 Code settings. A server URL is configured."
: "OpenCode is disabled in T3 Code settings.",
},
});
}
let version: string | null = null;
if (!isExternalServer) {
const versionExit = yield* Effect.exit(
openCodeRuntime
.runOpenCodeCommand({
binaryPath: input.settings.binaryPath,
args: ["--version"],
})
.pipe(
Effect.mapError(
(cause) =>
new OpenCodeProbeError({ cause, detail: openCodeRuntimeErrorDetail(cause) }),
),
),
);
if (versionExit._tag === "Failure") {
return fallback(Cause.squash(versionExit.cause));
}
version = parseGenericCliVersion(versionExit.value.stdout) ?? null;
if (!version) {
return fallback(
new Error(
`Unable to determine OpenCode version from \`opencode --version\` output. T3 Code requires OpenCode v${MINIMUM_OPENCODE_VERSION} or newer.`,
),
null,
);
}
if (compareCliVersions(version, MINIMUM_OPENCODE_VERSION) < 0) {
return buildServerProvider({
provider: PROVIDER,
presentation: OPENCODE_PRESENTATION,
enabled: input.settings.enabled,
checkedAt,
models: providerModelsFromSettings(
[],
PROVIDER,
customModels,
DEFAULT_OPENCODE_MODEL_CAPABILITIES,
),
probe: {
installed: true,
version,
status: "error",
auth: { status: "unknown" },
message: `OpenCode v${version} is too old. Upgrade to v${MINIMUM_OPENCODE_VERSION} or newer.`,
},
});
}
}
const inventoryExit = yield* Effect.exit(
Effect.scoped(
Effect.gen(function* () {
const server = yield* openCodeRuntime
.connectToOpenCodeServer({
binaryPath: input.settings.binaryPath,
serverUrl: input.settings.serverUrl,
})
.pipe(
Effect.mapError(
(cause) =>
new OpenCodeProbeError({ cause, detail: openCodeRuntimeErrorDetail(cause) }),
),
);
return yield* openCodeRuntime
.loadOpenCodeInventory(
openCodeRuntime.createOpenCodeSdkClient({
baseUrl: server.url,
directory: input.cwd,
...(isExternalServer && input.settings.serverPassword
? { serverPassword: input.settings.serverPassword }
: {}),
}),
)
.pipe(
Effect.mapError(
(cause) =>
new OpenCodeProbeError({ cause, detail: openCodeRuntimeErrorDetail(cause) }),
),
);
}),
),
null,
);
}
if (compareCliVersions(version, MINIMUM_OPENCODE_VERSION) < 0) {
if (inventoryExit._tag === "Failure") {
return fallback(Cause.squash(inventoryExit.cause), version);
}
const models = providerModelsFromSettings(
flattenOpenCodeModels(inventoryExit.value),
PROVIDER,
customModels,
DEFAULT_OPENCODE_MODEL_CAPABILITIES,
);
const connectedCount = inventoryExit.value.providerList.connected.length;
return buildServerProvider({
provider: PROVIDER,
presentation: OPENCODE_PRESENTATION,
enabled: openCodeSettings.enabled,
enabled: true,
checkedAt,
models: providerModelsFromSettings(
[],
PROVIDER,
customModels,
DEFAULT_OPENCODE_MODEL_CAPABILITIES,
),
models,
probe: {
installed: true,
version,
status: "error",
auth: { status: "unknown" },
message: `OpenCode v${version} is too old. Upgrade to v${MINIMUM_OPENCODE_VERSION} or newer.`,
status: connectedCount > 0 ? "ready" : "warning",
auth: {
status: connectedCount > 0 ? "authenticated" : "unknown",
type: "opencode",
},
message:
connectedCount > 0
? `${connectedCount} upstream provider${connectedCount === 1 ? "" : "s"} connected through ${isExternalServer ? "the configured OpenCode server" : "OpenCode"}.`
: isExternalServer
? "Connected to the configured OpenCode server, but it did not report any connected upstream providers."
: "OpenCode is available, but it did not report any connected upstream providers.",
},
});
}
}
});
const inventoryExit = yield* Effect.exit(
Effect.scoped(
Effect.gen(function* () {
const server = yield* openCodeRuntime
.connectToOpenCodeServer({
binaryPath: openCodeSettings.binaryPath,
serverUrl: openCodeSettings.serverUrl,
environment,
})
.pipe(
Effect.mapError(
(cause) =>
new OpenCodeProbeError({ cause, detail: openCodeRuntimeErrorDetail(cause) }),
),
);
return yield* openCodeRuntime
.loadOpenCodeInventory(
openCodeRuntime.createOpenCodeSdkClient({
baseUrl: server.url,
directory: cwd,
...(isExternalServer && openCodeSettings.serverPassword
? { serverPassword: openCodeSettings.serverPassword }
: {}),
}),
)
.pipe(
Effect.mapError(
(cause) =>
new OpenCodeProbeError({ cause, detail: openCodeRuntimeErrorDetail(cause) }),
),
);
}),
),
);
if (inventoryExit._tag === "Failure") {
return fallback(Cause.squash(inventoryExit.cause), version);
}
const getProviderSettings = serverSettings.getSettings.pipe(
Effect.map((settings) => settings.providers.opencode),
);
const models = providerModelsFromSettings(
flattenOpenCodeModels(inventoryExit.value),
PROVIDER,
customModels,
DEFAULT_OPENCODE_MODEL_CAPABILITIES,
);
const connectedCount = inventoryExit.value.providerList.connected.length;
return buildServerProvider({
presentation: OPENCODE_PRESENTATION,
enabled: true,
checkedAt,
models,
probe: {
installed: true,
version,
status: connectedCount > 0 ? "ready" : "warning",
auth: {
status: connectedCount > 0 ? "authenticated" : "unknown",
type: "opencode",
},
message:
connectedCount > 0
? `${connectedCount} upstream provider${connectedCount === 1 ? "" : "s"} connected through ${isExternalServer ? "the configured OpenCode server" : "OpenCode"}.`
: isExternalServer
? "Connected to the configured OpenCode server, but it did not report any connected upstream providers."
: "OpenCode is available, but it did not report any connected upstream providers.",
},
});
});
return yield* makeManagedServerProvider<OpenCodeSettings>({
getSettings: getProviderSettings.pipe(Effect.orDie),
streamSettings: serverSettings.streamChanges.pipe(
Stream.map((settings) => settings.providers.opencode),
),
haveSettingsChanged: (previous, next) => !Equal.equals(previous, next),
initialSnapshot: makePendingOpenCodeProvider,
checkProvider: getProviderSettings.pipe(
Effect.flatMap((settings) =>
checkOpenCodeProviderStatus({
settings,
cwd: serverConfig.cwd,
}),
),
),
});
}),
);
@@ -1,30 +1,24 @@
import {
defaultInstanceIdForDriver,
ProviderDriverKind,
type ServerProvider,
} from "@t3tools/contracts";
import type { ProviderKind } from "@t3tools/contracts";
import { it, assert, vi } from "@effect/vitest";
import { assertFailure } from "@effect/vitest/utils";
import { Effect, Layer, PubSub, Stream } from "effect";
import { Effect, Layer, Stream } from "effect";
import { ClaudeAdapter } from "../Services/ClaudeAdapter.ts";
import type { ClaudeAdapterShape } from "../Services/ClaudeAdapter.ts";
import { CodexAdapter } from "../Services/CodexAdapter.ts";
import type { CodexAdapterShape } from "../Services/CodexAdapter.ts";
import { CursorAdapter } from "../Services/CursorAdapter.ts";
import type { CursorAdapterShape } from "../Services/CursorAdapter.ts";
import { OpenCodeAdapter } from "../Services/OpenCodeAdapter.ts";
import type { OpenCodeAdapterShape } from "../Services/OpenCodeAdapter.ts";
import { ProviderAdapterRegistry } from "../Services/ProviderAdapterRegistry.ts";
import { ProviderInstanceRegistry } from "../Services/ProviderInstanceRegistry.ts";
import type { ProviderInstance } from "../ProviderDriver.ts";
import type { TextGenerationShape } from "../../textGeneration/TextGeneration.ts";
import { ProviderAdapterRegistryLive } from "./ProviderAdapterRegistry.ts";
import { ProviderUnsupportedError } from "../Errors.ts";
import * as NodeServices from "@effect/platform-node/NodeServices";
const CODEX_DRIVER = ProviderDriverKind.make("codex");
const CLAUDE_AGENT_DRIVER = ProviderDriverKind.make("claudeAgent");
const OPENCODE_DRIVER = ProviderDriverKind.make("opencode");
const CURSOR_DRIVER = ProviderDriverKind.make("cursor");
const fakeCodexAdapter: CodexAdapterShape = {
provider: CODEX_DRIVER,
provider: "codex",
capabilities: { sessionModelSwitch: "in-session" },
startSession: vi.fn(),
sendTurn: vi.fn(),
@@ -41,7 +35,7 @@ const fakeCodexAdapter: CodexAdapterShape = {
};
const fakeClaudeAdapter: ClaudeAdapterShape = {
provider: CLAUDE_AGENT_DRIVER,
provider: "claudeAgent",
capabilities: { sessionModelSwitch: "in-session" },
startSession: vi.fn(),
sendTurn: vi.fn(),
@@ -58,7 +52,7 @@ const fakeClaudeAdapter: ClaudeAdapterShape = {
};
const fakeOpenCodeAdapter: OpenCodeAdapterShape = {
provider: OPENCODE_DRIVER,
provider: "opencode",
capabilities: { sessionModelSwitch: "in-session" },
startSession: vi.fn(),
sendTurn: vi.fn(),
@@ -75,7 +69,7 @@ const fakeOpenCodeAdapter: OpenCodeAdapterShape = {
};
const fakeCursorAdapter: CursorAdapterShape = {
provider: CURSOR_DRIVER,
provider: "cursor",
capabilities: { sessionModelSwitch: "in-session" },
startSession: vi.fn(),
sendTurn: vi.fn(),
@@ -91,94 +85,44 @@ const fakeCursorAdapter: CursorAdapterShape = {
streamEvents: Stream.empty,
};
// ProviderAdapterRegistryLive is now a facade over ProviderInstanceRegistry —
// it walks `listInstances` once at boot and surfaces the default-instance
// adapter keyed by its driver kind. To test the facade we supply four fake
// instances whose `instanceId === defaultInstanceIdForDriver(driverKind)` so
// they pass the default-instance filter.
const makeFakeInstance = (
driverKindString: "codex" | "claudeAgent" | "cursor" | "opencode",
adapter: ProviderInstance["adapter"],
): ProviderInstance => {
const driverKind = ProviderDriverKind.make(driverKindString);
return {
instanceId: defaultInstanceIdForDriver(driverKind),
driverKind,
continuationIdentity: {
driverKind,
continuationKey: `${driverKind}:instance:${defaultInstanceIdForDriver(driverKind)}`,
},
displayName: undefined,
enabled: true,
snapshot: {
getSnapshot: Effect.succeed({} as unknown as ServerProvider),
refresh: Effect.succeed({} as unknown as ServerProvider),
streamChanges: Stream.empty,
},
adapter,
textGeneration: {} as unknown as TextGenerationShape,
};
};
const fakeInstances: ReadonlyArray<ProviderInstance> = [
makeFakeInstance("codex", fakeCodexAdapter),
makeFakeInstance("claudeAgent", fakeClaudeAdapter),
makeFakeInstance("opencode", fakeOpenCodeAdapter),
makeFakeInstance("cursor", fakeCursorAdapter),
];
const fakeInstanceRegistryLayer = Layer.succeed(ProviderInstanceRegistry, {
getInstance: (instanceId) =>
Effect.succeed(fakeInstances.find((instance) => instance.instanceId === instanceId)),
listInstances: Effect.succeed(fakeInstances),
listUnavailable: Effect.succeed([]),
streamChanges: Stream.empty,
// Tests never drive changes through this fake; acquire a throwaway
// subscription on an unused PubSub so the shape is satisfied.
subscribeChanges: Effect.flatMap(PubSub.unbounded<void>(), (pubsub) => PubSub.subscribe(pubsub)),
});
const layer = Layer.mergeAll(
Layer.provide(ProviderAdapterRegistryLive, fakeInstanceRegistryLayer),
NodeServices.layer,
const layer = it.layer(
Layer.mergeAll(
Layer.provide(
ProviderAdapterRegistryLive,
Layer.mergeAll(
Layer.succeed(CodexAdapter, fakeCodexAdapter),
Layer.succeed(ClaudeAdapter, fakeClaudeAdapter),
Layer.succeed(OpenCodeAdapter, fakeOpenCodeAdapter),
Layer.succeed(CursorAdapter, fakeCursorAdapter),
),
),
NodeServices.layer,
),
);
it.layer(layer)("ProviderAdapterRegistryLive", (it) => {
it("resolves adapters and routing metadata from provider instances", () =>
layer("ProviderAdapterRegistryLive", (it) => {
it.effect("resolves a registered provider adapter", () =>
Effect.gen(function* () {
const registry = yield* ProviderAdapterRegistry;
const claudeInstanceId = defaultInstanceIdForDriver(CLAUDE_AGENT_DRIVER);
const adapter = yield* registry.getByInstance(claudeInstanceId);
assert.strictEqual(adapter, fakeClaudeAdapter);
const info = yield* registry.getInstanceInfo(claudeInstanceId);
assert.deepStrictEqual(info, {
instanceId: claudeInstanceId,
driverKind: CLAUDE_AGENT_DRIVER,
displayName: undefined,
accentColor: undefined,
enabled: true,
continuationIdentity: {
driverKind: CLAUDE_AGENT_DRIVER,
continuationKey: "claudeAgent:instance:claudeAgent",
},
});
const instances = yield* registry.listInstances();
assert.deepStrictEqual(instances, [
defaultInstanceIdForDriver(CODEX_DRIVER),
claudeInstanceId,
defaultInstanceIdForDriver(OPENCODE_DRIVER),
defaultInstanceIdForDriver(CURSOR_DRIVER),
]);
const codex = yield* registry.getByProvider("codex");
const claude = yield* registry.getByProvider("claudeAgent");
const openCode = yield* registry.getByProvider("opencode");
const cursor = yield* registry.getByProvider("cursor");
assert.equal(codex, fakeCodexAdapter);
assert.equal(claude, fakeClaudeAdapter);
assert.equal(openCode, fakeOpenCodeAdapter);
assert.equal(cursor, fakeCursorAdapter);
const providers = yield* registry.listProviders();
assert.deepStrictEqual(providers, [
CODEX_DRIVER,
CLAUDE_AGENT_DRIVER,
OPENCODE_DRIVER,
CURSOR_DRIVER,
]);
}));
assert.deepEqual(providers, ["codex", "claudeAgent", "opencode", "cursor"]);
}),
);
it.effect("fails with ProviderUnsupportedError for unknown providers", () =>
Effect.gen(function* () {
const registry = yield* ProviderAdapterRegistry;
const adapter = yield* registry.getByProvider("unknown" as ProviderKind).pipe(Effect.result);
assertFailure(adapter, new ProviderUnsupportedError({ provider: "unknown" }));
}),
);
});
@@ -1,101 +1,59 @@
/**
* ProviderAdapterRegistryLive — facade over `ProviderInstanceRegistry`.
* ProviderAdapterRegistryLive - In-memory provider adapter lookup layer.
*
* `ProviderAdapterRegistry` historically mapped one `ProviderDriverKind` to one
* adapter via the four `<X>AdapterLive` singleton Layers. The per-instance
* refactor moved adapter construction inside each `ProviderDriver.create()`:
* adapters are now bundled on the `ProviderInstance` that the
* `ProviderInstanceRegistry` owns.
*
* This facade fulfills the `ProviderAdapterRegistryShape` contract by doing
* dynamic look-ups against `ProviderInstanceRegistry` on every call. That
* means settings-driven hot-reload shows up here automatically — adding a
* new instance via settings makes `getByInstance` resolve immediately
* without rebuilding the facade.
* Binds provider kinds (codex/claudeAgent/...) to concrete adapter services.
* This layer only performs adapter lookup; it does not route session-scoped
* calls or own provider lifecycle workflows.
*
* @module ProviderAdapterRegistryLive
*/
import {
defaultInstanceIdForDriver,
ProviderInstanceId,
type ProviderDriverKind,
} from "@t3tools/contracts";
import { Effect, Layer } from "effect";
import { ProviderUnsupportedError } from "../Errors.ts";
import { ProviderInstanceRegistry } from "../Services/ProviderInstanceRegistry.ts";
import { ProviderUnsupportedError, type ProviderAdapterError } from "../Errors.ts";
import type { ProviderAdapterShape } from "../Services/ProviderAdapter.ts";
import {
ProviderAdapterRegistry,
type ProviderAdapterRegistryShape,
} from "../Services/ProviderAdapterRegistry.ts";
import { ClaudeAdapter } from "../Services/ClaudeAdapter.ts";
import { CodexAdapter } from "../Services/CodexAdapter.ts";
import { CursorAdapter } from "../Services/CursorAdapter.ts";
import { OpenCodeAdapter } from "../Services/OpenCodeAdapter.ts";
import { createBuiltInAdapterList } from "../builtInProviderCatalog.ts";
const makeProviderAdapterRegistry = Effect.fn("makeProviderAdapterRegistry")(function* () {
const registry = yield* ProviderInstanceRegistry;
export interface ProviderAdapterRegistryLiveOptions {
readonly adapters?: ReadonlyArray<ProviderAdapterShape<ProviderAdapterError>>;
}
const getByInstance: ProviderAdapterRegistryShape["getByInstance"] = (instanceId) =>
registry.getInstance(instanceId).pipe(
Effect.flatMap((instance) =>
instance === undefined
? Effect.fail(
new ProviderUnsupportedError({
provider: instanceId,
}),
)
: Effect.succeed(instance.adapter),
),
);
const makeProviderAdapterRegistry = Effect.fn("makeProviderAdapterRegistry")(function* (
options?: ProviderAdapterRegistryLiveOptions,
) {
const cursorAdapterOption = yield* Effect.serviceOption(CursorAdapter);
const adapters =
options?.adapters !== undefined
? options.adapters
: createBuiltInAdapterList({
codex: yield* CodexAdapter,
claudeAgent: yield* ClaudeAdapter,
opencode: yield* OpenCodeAdapter,
...(cursorAdapterOption._tag === "Some" ? { cursor: cursorAdapterOption.value } : {}),
});
const byProvider = new Map(adapters.map((adapter) => [adapter.provider, adapter]));
const getInstanceInfo: ProviderAdapterRegistryShape["getInstanceInfo"] = (instanceId) =>
registry.getInstance(instanceId).pipe(
Effect.flatMap((instance) =>
instance === undefined
? Effect.fail(
new ProviderUnsupportedError({
provider: instanceId,
}),
)
: Effect.succeed({
instanceId: instance.instanceId,
driverKind: instance.driverKind,
displayName: instance.displayName,
accentColor: instance.accentColor,
enabled: instance.enabled,
continuationIdentity: instance.continuationIdentity,
}),
),
);
const listInstances: ProviderAdapterRegistryShape["listInstances"] = () =>
registry.listInstances.pipe(
Effect.map((instances) => instances.map((instance) => instance.instanceId)),
);
const getByProvider: ProviderAdapterRegistryShape["getByProvider"] = (provider) => {
const adapter = byProvider.get(provider);
if (!adapter) {
return Effect.fail(new ProviderUnsupportedError({ provider }));
}
return Effect.succeed(adapter);
};
const listProviders: ProviderAdapterRegistryShape["listProviders"] = () =>
registry.listInstances.pipe(
Effect.map((instances) => {
const kinds = new Set<ProviderDriverKind>();
for (const instance of instances) {
const defaultId = defaultInstanceIdForDriver(instance.driverKind);
if (instance.instanceId === defaultId) {
// Only the default-instance rows show up through the legacy
// shim — custom instances like `codex_personal` have no
// `ProviderDriverKind` equivalent.
kinds.add(instance.driverKind);
}
}
return Array.from(kinds);
}),
);
Effect.sync(() => Array.from(byProvider.keys()));
return {
getByInstance,
getInstanceInfo,
listInstances,
getByProvider,
listProviders,
// Proxy directly — the facade has no state of its own; the instance
// registry already coalesces adds/removes/rebuilds into one emission.
streamChanges: registry.streamChanges,
subscribeChanges: registry.subscribeChanges,
} satisfies ProviderAdapterRegistryShape;
});
@@ -103,14 +61,3 @@ export const ProviderAdapterRegistryLive = Layer.effect(
ProviderAdapterRegistry,
makeProviderAdapterRegistry(),
);
// Exposed for tests that want to build a facade over a pre-assembled
// `ProviderInstanceRegistry` without pulling in the whole boot graph.
export { makeProviderAdapterRegistry };
// Re-export for consumers that need the accessor shape. The service tag
// itself lives in `Services/ProviderAdapterRegistry.ts`.
export { ProviderAdapterRegistry } from "../Services/ProviderAdapterRegistry.ts";
// Re-export for consumers (including tests) that construct a
// `ProviderInstanceId` before calling `getByInstance`.
export { ProviderInstanceId };
@@ -1,83 +0,0 @@
/**
* ProviderEventLoggers — single observability service that owns the two
* shared NDJSON streams the provider runtime writes:
*
* - `native` — provider-protocol events as the SDK emits them, written
* from inside each `<X>Adapter` factory.
* - `canonical` — runtime events after `ProviderService` has normalized
* them onto `ProviderRuntimeEvent`.
*
* Why a service tag and not constructor options?
*
* - Adapters are now constructed *inside* drivers (`<X>Driver.create()`),
* not at the boot Layer. There is no longer a single `make<X>AdapterLive(options)`
* call site where we can hand an `EventNdjsonLogger` in by hand.
* - Multiple driver instances per kind (`codex_personal`, `codex_work`)
* should share one underlying log writer per stream — opening N writers
* against the same rotating file would race the rotation logic. Owning
* the loggers on a single tag keeps that invariant intact.
* - Tests can swap one (or both) loggers with in-memory recorders by
* `Layer.succeed(ProviderEventLoggers, { native, canonical })` instead of
* juggling per-Layer option threading.
*
* Both fields are optional. `makeEventNdjsonLogger` returns `undefined` when
* the target directory cannot be created; we forward that as `undefined`
* rather than failing the boot Layer, matching the previous best-effort
* behavior of `server.ts`.
*
* @module provider/Layers/ProviderEventLoggers
*/
import { Context, Effect, Layer } from "effect";
import { ServerConfig } from "../../config.ts";
import { type EventNdjsonLogger, makeEventNdjsonLogger } from "./EventNdjsonLogger.ts";
export interface ProviderEventLoggersShape {
readonly native: EventNdjsonLogger | undefined;
readonly canonical: EventNdjsonLogger | undefined;
}
/**
* Shared logger pair for native + canonical provider event streams.
*
* Service value is intentionally a struct of two optional loggers rather
* than two parallel tags. Construction site is one place
* (`ProviderEventLoggersLive`); consumers (drivers, `ProviderService`) read
* one tag and pluck the field they need.
*/
export class ProviderEventLoggers extends Context.Service<
ProviderEventLoggers,
ProviderEventLoggersShape
>()("t3/provider/ProviderEventLoggers") {}
/**
* Constant value used by tests / boot layers that want to opt out of native
* + canonical logging entirely. Keeps the tag non-optional in the type
* system while letting the runtime treat absence as a no-op.
*/
export const NoOpProviderEventLoggers: ProviderEventLoggersShape = {
native: undefined,
canonical: undefined,
};
/**
* Live Layer that builds both loggers from `ServerConfig.providerEventLogPath`.
* If the directory create fails for either stream, the corresponding field
* is `undefined` and writes from that stream become no-ops downstream.
*/
export const ProviderEventLoggersLive = Layer.effect(
ProviderEventLoggers,
Effect.gen(function* () {
const { providerEventLogPath } = yield* ServerConfig;
const native = yield* makeEventNdjsonLogger(providerEventLogPath, {
stream: "native",
});
const canonical = yield* makeEventNdjsonLogger(providerEventLogPath, {
stream: "canonical",
});
return {
native,
canonical,
} satisfies ProviderEventLoggersShape;
}),
);
@@ -1,176 +0,0 @@
/**
* ProviderInstanceRegistryHydration — derive a `ProviderInstanceConfigMap`
* from `ServerSettings` and keep `ProviderInstanceRegistry` in sync with it.
*
* The server still reads two shapes:
*
* 1. `settings.providerInstances` — the new driver-agnostic map the
* registry expects. Keyed by `ProviderInstanceId`, values are
* `ProviderInstanceConfig` envelopes.
* 2. `settings.providers.<kind>` — the legacy single-instance-per-driver
* fields (`providers.codex`, `providers.claudeAgent`, …). These are
* the source of truth for every deployment that hasn't been migrated
* yet to an explicit `providerInstances` entry.
*
* This module bridges (2) into (1) and wires the resulting map into a
* mutable registry. For every built-in driver whose id is not already
* present in `providerInstances` (keyed on
* `defaultInstanceIdForDriver(driverKind)` — literally the driver kind as a
* routing slug), we synthesize an envelope from the legacy field. The
* registry decodes both flavours through the same `configSchema` and ends
* up with one uniform `ProviderInstance` per entry.
*
* Explicit `providerInstances` entries always win — users can already
* override the legacy `providers.<kind>` blob by authoring a
* `providerInstances.codex` entry with a matching driver, and we don't
* want the synthesized envelope to silently stomp their config.
*
* Hot-reload
* ----------
* On layer build we:
* 1. Read the current `ServerSettings` once and use it to seed the
* registry's initial state via `ProviderInstanceRegistryMutableLayer`.
* 2. Fork a daemon fiber (lifetime tied to the layer's scope) that
* subscribes to `ServerSettingsService.streamChanges` and calls
* `ProviderInstanceRegistryMutator.reconcile` on every emission.
*
* Failures inside the watcher are logged and swallowed so a single bad
* settings emission cannot kill the registry. Unknown drivers and invalid
* configs already round-trip through the registry's own "unavailable"
* shadow bucket.
*
* @module provider/Layers/ProviderInstanceRegistryHydration
*/
import {
defaultInstanceIdForDriver,
type ProviderInstanceConfig,
type ProviderInstanceConfigMap,
ServerSettings,
} from "@t3tools/contracts";
import { Effect, Layer, Stream } from "effect";
import { ServerSettingsService } from "../../serverSettings.ts";
import { BUILT_IN_DRIVERS, type BuiltInDriversEnv } from "../builtInDrivers.ts";
import { ProviderInstanceRegistry } from "../Services/ProviderInstanceRegistry.ts";
import { ProviderInstanceRegistryMutator } from "../Services/ProviderInstanceRegistryMutator.ts";
import { ProviderInstanceRegistryMutableLayer } from "./ProviderInstanceRegistryLive.ts";
/**
* Synthesize a `ProviderInstanceConfigMap` from a `ServerSettings` snapshot.
*
* Strategy:
* 1. Copy all explicit `settings.providerInstances` entries verbatim.
* 2. For each built-in driver whose `defaultInstanceIdForDriver(id)` key
* is *not* already in the explicit map, synthesize an entry from the
* matching legacy `settings.providers.<kind>` blob.
*
* The returned map is the input the registry consumes; pure & exported
* separately so the hydration logic can be exercised by unit tests
* without layering.
*/
export const deriveProviderInstanceConfigMap = (
settings: ServerSettings,
): ProviderInstanceConfigMap => {
const merged: Record<string, ProviderInstanceConfig> = { ...settings.providerInstances };
for (const driver of BUILT_IN_DRIVERS) {
const instanceId = defaultInstanceIdForDriver(driver.driverKind);
if (instanceId in merged) {
// Explicit `providerInstances` entry for this slot — user-authored
// config always wins over the legacy mirror.
continue;
}
// Only built-in drivers have a legacy mirror; the registry's
// `providers` struct is keyed on the same literal slug as
// `driverKind`. Access is dynamic (the driver kind is a branded string),
// but it's constrained to `keyof settings.providers` by the union of
// built-in driver kinds.
const legacyKey = driver.driverKind as keyof ServerSettings["providers"];
const legacyConfig = settings.providers[legacyKey];
if (legacyConfig === undefined) {
continue;
}
merged[instanceId] = {
driver: driver.driverKind,
config: legacyConfig,
};
}
return merged as ProviderInstanceConfigMap;
};
/**
* Layer that consumes `ProviderInstanceRegistryMutator` and forks a
* settings-watcher fiber. The fiber's lifetime is tied to the enclosing
* layer scope (process lifetime in production), so it is interrupted on
* shutdown without leaking.
*
* Errors inside the watcher are logged and swallowed — the registry's own
* "unavailable" bucket already absorbs unknown drivers and invalid
* configs, so the only way the watcher could fail is a settings stream
* tear-down, which logs and exits cleanly.
*/
const SettingsWatcherLive: Layer.Layer<
never,
never,
ProviderInstanceRegistryMutator | ServerSettingsService
> = Layer.effectDiscard(
Effect.gen(function* () {
const mutator = yield* ProviderInstanceRegistryMutator;
const serverSettings = yield* ServerSettingsService;
yield* serverSettings.streamChanges.pipe(
Stream.runForEach((next) =>
mutator
.reconcile(deriveProviderInstanceConfigMap(next))
.pipe(
Effect.catchCause((cause) =>
Effect.logError("ProviderInstanceRegistry reconcile failed", cause),
),
),
),
Effect.forkScoped,
);
}),
);
/**
* Hydrate `ProviderInstanceRegistry` from `ServerSettings` and keep it in
* sync with subsequent `streamChanges` emissions.
*
* The Layer's two halves:
* - `ProviderInstanceRegistryMutableLayer` produces the registry +
* mutator from the initial config map. Its scope owns every
* per-instance child scope created during reconcile.
* - `SettingsWatcherLive` consumes the mutator and runs a daemon fiber
* in the same scope.
*
* Composing via `Layer.provideMerge` makes the watcher's deps available
* from the mutable layer while still surfacing the registry as an output.
* The mutator tag is technically also exposed; only this module imports
* it, so the visibility leak is harmless in practice.
*/
export const ProviderInstanceRegistryHydrationLive: Layer.Layer<
ProviderInstanceRegistry,
never,
BuiltInDriversEnv | ServerSettingsService
> = Layer.unwrap(
Effect.gen(function* () {
const serverSettings = yield* ServerSettingsService;
const initialSettings: ServerSettings | undefined = yield* serverSettings.getSettings.pipe(
Effect.orElseSucceed(() => undefined),
);
const initialConfigMap =
initialSettings === undefined
? ({} as ProviderInstanceConfigMap)
: deriveProviderInstanceConfigMap(initialSettings);
const mutableLayer = ProviderInstanceRegistryMutableLayer({
drivers: BUILT_IN_DRIVERS,
configMap: initialConfigMap,
});
return SettingsWatcherLive.pipe(Layer.provideMerge(mutableLayer));
}),
) as Layer.Layer<ProviderInstanceRegistry, never, BuiltInDriversEnv | ServerSettingsService>;
@@ -1,357 +0,0 @@
/**
* Multi-instance validation slices for `ProviderInstanceRegistryLive`.
*
* Two axes of the driver/registry refactor are exercised here:
*
* 1. **Same driver, many instances** — the "multi-instance codex slice"
* describe block below configures two independent `codex` instances and
* asserts each gets its own closures and identity. This is the
* multi-codex capability the refactor exists to unlock.
*
* 2. **Many drivers, one registry** — the "all drivers slice" describe
* block below configures one instance of every shipped driver
* (`codex`, `claudeAgent`, `cursor`, `opencode`) in a single
* `ProviderInstanceConfigMap` and asserts the registry boots them all
* without cross-contamination. This proves the driver SPI is uniform
* across every provider — any driver plugs into the registry through
* the same `ProviderDriver` value contract.
*
* Every instance in these tests is configured with `enabled: false` so the
* provider-status checks short-circuit to pending/disabled snapshots
* without trying to spawn real `codex` / `claude` / `agent` / `opencode`
* binaries. That keeps the assertions focused on registry routing
* behaviour rather than the runtime details of each provider.
*/
import { describe, expect, it } from "@effect/vitest";
import * as NodeServices from "@effect/platform-node/NodeServices";
import {
type ClaudeSettings,
type CodexSettings,
type CursorSettings,
type OpenCodeSettings,
ProviderDriverKind,
type ProviderInstanceConfigMap,
ProviderInstanceId,
} from "@t3tools/contracts";
import { Effect, Layer } from "effect";
import { ServerConfig } from "../../config.ts";
import { ClaudeDriver } from "../Drivers/ClaudeDriver.ts";
import { CodexDriver } from "../Drivers/CodexDriver.ts";
import { CursorDriver } from "../Drivers/CursorDriver.ts";
import { OpenCodeDriver } from "../Drivers/OpenCodeDriver.ts";
import { OpenCodeRuntimeLive } from "../opencodeRuntime.ts";
import { NoOpProviderEventLoggers, ProviderEventLoggers } from "./ProviderEventLoggers.ts";
import { makeProviderInstanceRegistry } from "./ProviderInstanceRegistryLive.ts";
const makeCodexConfig = (overrides: Partial<CodexSettings>): CodexSettings => ({
enabled: false,
binaryPath: "codex",
homePath: "",
shadowHomePath: "",
customModels: [],
...overrides,
});
const makeClaudeConfig = (overrides: Partial<ClaudeSettings>): ClaudeSettings => ({
enabled: false,
binaryPath: "claude",
homePath: "",
customModels: [],
launchArgs: "",
...overrides,
});
const makeCursorConfig = (overrides: Partial<CursorSettings>): CursorSettings => ({
enabled: false,
binaryPath: "agent",
apiEndpoint: "",
customModels: [],
...overrides,
});
const makeOpenCodeConfig = (overrides: Partial<OpenCodeSettings>): OpenCodeSettings => ({
enabled: false,
binaryPath: "opencode",
serverUrl: "",
serverPassword: "",
customModels: [],
...overrides,
});
describe("ProviderInstanceRegistryLive — multi-instance codex slice", () => {
// `ServerConfig.layerTest` needs `FileSystem` to materialize its scratch
// directory. `Layer.merge` just unions requirements, so we have to push
// `NodeServices.layer` through `Layer.provideMerge` to satisfy that
// dependency while still surfacing NodeServices to the test body (the
// codex driver's `create` yields `ChildProcessSpawner` directly).
const testLayer = ServerConfig.layerTest(process.cwd(), {
prefix: "provider-instance-registry-test",
}).pipe(
Layer.provideMerge(NodeServices.layer),
Layer.provideMerge(Layer.succeed(ProviderEventLoggers, NoOpProviderEventLoggers)),
);
it.live("boots two independent codex instances from a ProviderInstanceConfigMap", () =>
Effect.gen(function* () {
const personalId = ProviderInstanceId.make("codex_personal");
const workId = ProviderInstanceId.make("codex_work");
const codexDriverKind = ProviderDriverKind.make("codex");
const configMap: ProviderInstanceConfigMap = {
[personalId]: {
driver: codexDriverKind,
displayName: "Codex (personal)",
enabled: false,
config: makeCodexConfig({
binaryPath: "/opt/codex-personal/bin/codex",
homePath: "/home/julius/.codex_personal",
customModels: ["personal-preview"],
}),
},
[workId]: {
driver: codexDriverKind,
displayName: "Codex (work)",
enabled: false,
config: makeCodexConfig({
binaryPath: "/opt/codex-work/bin/codex",
homePath: "/home/julius/.codex",
customModels: ["work-preview"],
}),
},
};
const { registry } = yield* makeProviderInstanceRegistry({
drivers: [CodexDriver],
configMap,
});
const instances = yield* registry.listInstances;
expect(instances.map((instance) => instance.instanceId).toSorted()).toEqual(
[personalId, workId].toSorted(),
);
expect(instances.every((instance) => instance.driverKind === codexDriverKind)).toBe(true);
expect(instances.map((instance) => instance.displayName).toSorted()).toEqual(
["Codex (personal)", "Codex (work)"].toSorted(),
);
// Each instance must be retrievable by id and carry its *own* closures.
const personal = yield* registry.getInstance(personalId);
const work = yield* registry.getInstance(workId);
expect(personal).toBeDefined();
expect(work).toBeDefined();
expect(personal!.adapter).not.toBe(work!.adapter);
expect(personal!.textGeneration).not.toBe(work!.textGeneration);
expect(personal!.snapshot).not.toBe(work!.snapshot);
// Snapshots identify themselves by instanceId + driver — this is
// what makes per-instance routing distinguishable downstream.
const personalSnapshot = yield* personal!.snapshot.getSnapshot;
expect(personalSnapshot.instanceId).toBe(personalId);
expect(personalSnapshot.driver).toBe(codexDriverKind);
expect(personalSnapshot.enabled).toBe(false);
expect(personalSnapshot.continuation?.groupKey).toBe(
"codex:home:/home/julius/.codex_personal",
);
const workSnapshot = yield* work!.snapshot.getSnapshot;
expect(workSnapshot.instanceId).toBe(workId);
expect(workSnapshot.driver).toBe(codexDriverKind);
expect(workSnapshot.enabled).toBe(false);
expect(workSnapshot.continuation?.groupKey).toBe("codex:home:/home/julius/.codex");
// Nothing goes to the unavailable bucket — both drivers are registered.
const unavailable = yield* registry.listUnavailable;
expect(unavailable).toEqual([]);
}).pipe(Effect.provide(testLayer)),
);
it.live(
"shadows instances whose driver is not registered in this build without failing boot",
() =>
Effect.gen(function* () {
const codexId = ProviderInstanceId.make("codex_main");
const ghostId = ProviderInstanceId.make("ghost_main");
const configMap: ProviderInstanceConfigMap = {
[codexId]: {
driver: ProviderDriverKind.make("codex"),
enabled: false,
config: makeCodexConfig({}),
},
[ghostId]: {
driver: ProviderDriverKind.make("ghostDriver"),
displayName: "A fork-only driver we don't ship",
enabled: false,
config: { arbitrary: "payload", preserved: true },
},
};
const { registry } = yield* makeProviderInstanceRegistry({
drivers: [CodexDriver],
configMap,
});
const instances = yield* registry.listInstances;
expect(instances).toHaveLength(1);
expect(instances[0]!.instanceId).toBe(codexId);
const unavailable = yield* registry.listUnavailable;
expect(unavailable).toHaveLength(1);
const ghost = unavailable[0]!;
expect(ghost.instanceId).toBe(ghostId);
expect(ghost.driver).toBe("ghostDriver");
expect(ghost.availability).toBe("unavailable");
expect(ghost.unavailableReason).toMatch(/ghostDriver/);
}).pipe(Effect.provide(testLayer)),
);
});
describe("ProviderInstanceRegistryLive — all drivers slice", () => {
// All four drivers need `NodeServices` (ChildProcessSpawner + FileSystem +
// Path). `OpenCodeDriver.create` additionally yields `OpenCodeRuntime`
// at construction time, so we wire `OpenCodeRuntimeLive` into the stack.
// `OpenCodeRuntimeLive` bundles its own `NetService.layer` via
// `Layer.provide`, so the only external requirement it still exposes is
// `ChildProcessSpawner` — resolved here by piping it through
// `provideMerge(NodeServices.layer)`.
//
// The nested `provideMerge`s read bottom-up: `NodeServices.layer`
// provides `OpenCodeRuntimeLive`'s deps while keeping its own outputs
// surfaced; that merged layer then provides `ServerConfig.layerTest`'s
// `FileSystem` dep while keeping everything else surfaced to the test.
const infraLayer = OpenCodeRuntimeLive.pipe(Layer.provideMerge(NodeServices.layer));
const testLayer = ServerConfig.layerTest(process.cwd(), {
prefix: "provider-instance-registry-all-drivers-test",
}).pipe(
Layer.provideMerge(infraLayer),
Layer.provideMerge(Layer.succeed(ProviderEventLoggers, NoOpProviderEventLoggers)),
);
it.live("boots one instance of every shipped driver from a single config map", () =>
Effect.gen(function* () {
const codexId = ProviderInstanceId.make("codex_default");
const claudeId = ProviderInstanceId.make("claude_default");
const cursorId = ProviderInstanceId.make("cursor_default");
const openCodeId = ProviderInstanceId.make("opencode_default");
const codexDriverKind = ProviderDriverKind.make("codex");
const claudeDriverKind = ProviderDriverKind.make("claudeAgent");
const cursorDriverKind = ProviderDriverKind.make("cursor");
const openCodeDriverKind = ProviderDriverKind.make("opencode");
const configMap: ProviderInstanceConfigMap = {
[codexId]: {
driver: codexDriverKind,
displayName: "Codex",
enabled: false,
config: makeCodexConfig({ homePath: "/home/julius/.codex" }),
},
[claudeId]: {
driver: claudeDriverKind,
displayName: "Claude",
enabled: false,
config: makeClaudeConfig({
homePath: "/home/julius/.claude-work",
launchArgs: "--verbose",
}),
},
[cursorId]: {
driver: cursorDriverKind,
displayName: "Cursor",
enabled: false,
config: makeCursorConfig({}),
},
[openCodeId]: {
driver: openCodeDriverKind,
displayName: "OpenCode",
enabled: false,
config: makeOpenCodeConfig({}),
},
};
const { registry } = yield* makeProviderInstanceRegistry({
drivers: [CodexDriver, ClaudeDriver, CursorDriver, OpenCodeDriver],
configMap,
});
// Every configured instance must materialize — none downgraded to a
// shadow snapshot, because every driver in the map is registered.
const unavailable = yield* registry.listUnavailable;
expect(unavailable).toEqual([]);
const instances = yield* registry.listInstances;
expect(instances).toHaveLength(4);
expect(instances.map((instance) => instance.instanceId).toSorted()).toEqual(
[codexId, claudeId, cursorId, openCodeId].toSorted(),
);
// Instance lookup by id resolves each instance to its own bundle —
// this is how rest-of-server routes turn/session calls in the new
// model. Each driver's bundle carries its advertised `driverKind`.
const codex = yield* registry.getInstance(codexId);
const claude = yield* registry.getInstance(claudeId);
const cursor = yield* registry.getInstance(cursorId);
const openCode = yield* registry.getInstance(openCodeId);
expect(codex?.driverKind).toBe(codexDriverKind);
expect(claude?.driverKind).toBe(claudeDriverKind);
expect(cursor?.driverKind).toBe(cursorDriverKind);
expect(openCode?.driverKind).toBe(openCodeDriverKind);
expect(codex?.displayName).toBe("Codex");
expect(claude?.displayName).toBe("Claude");
expect(cursor?.displayName).toBe("Cursor");
expect(openCode?.displayName).toBe("OpenCode");
// Every instance owns its own set of closures — no sharing across
// drivers. `adapter` / `textGeneration` / `snapshot` are all
// distinct references even when two instances happen to share a
// trait (e.g. Cursor + others all use a stub-or-real
// `textGeneration`; they must still be different object values).
const adapters = [codex!.adapter, claude!.adapter, cursor!.adapter, openCode!.adapter];
expect(new Set(adapters).size).toBe(adapters.length);
const textGenerations = [
codex!.textGeneration,
claude!.textGeneration,
cursor!.textGeneration,
openCode!.textGeneration,
];
expect(new Set(textGenerations).size).toBe(textGenerations.length);
const snapshots = [codex!.snapshot, claude!.snapshot, cursor!.snapshot, openCode!.snapshot];
expect(new Set(snapshots).size).toBe(snapshots.length);
// Snapshots identify themselves by `instanceId` + `driver` so
// downstream aggregation in `ProviderRegistry` can tell instances
// apart even when two share a driver. With `enabled: false`, the
// check short-circuits and we get a disabled/pending snapshot back
// — that's enough signal to validate the stamping wrapper without
// spawning real binaries.
const codexSnapshot = yield* codex!.snapshot.getSnapshot;
expect(codexSnapshot.instanceId).toBe(codexId);
expect(codexSnapshot.driver).toBe(codexDriverKind);
expect(codexSnapshot.enabled).toBe(false);
expect(codexSnapshot.continuation?.groupKey).toBe("codex:home:/home/julius/.codex");
const claudeSnapshot = yield* claude!.snapshot.getSnapshot;
expect(claudeSnapshot.instanceId).toBe(claudeId);
expect(claudeSnapshot.driver).toBe(claudeDriverKind);
expect(claudeSnapshot.enabled).toBe(false);
expect(claudeSnapshot.continuation?.groupKey).toBe("claude:home:/home/julius/.claude-work");
const cursorSnapshot = yield* cursor!.snapshot.getSnapshot;
expect(cursorSnapshot.instanceId).toBe(cursorId);
expect(cursorSnapshot.driver).toBe(cursorDriverKind);
expect(cursorSnapshot.enabled).toBe(false);
expect(cursorSnapshot.continuation?.groupKey).toBe(
`${cursorDriverKind}:instance:${cursorId}`,
);
const openCodeSnapshot = yield* openCode!.snapshot.getSnapshot;
expect(openCodeSnapshot.instanceId).toBe(openCodeId);
expect(openCodeSnapshot.driver).toBe(openCodeDriverKind);
expect(openCodeSnapshot.enabled).toBe(false);
expect(openCodeSnapshot.continuation?.groupKey).toBe(
`${openCodeDriverKind}:instance:${openCodeId}`,
);
}).pipe(Effect.provide(testLayer)),
);
});
@@ -1,434 +0,0 @@
/**
* ProviderInstanceRegistryLive — runtime implementation of
* `ProviderInstanceRegistry` plus its sibling mutator.
*
* Materializes every entry in a `ProviderInstanceConfigMap`:
*
* - When the entry's `driver` matches a registered driver, the registry
* decodes the opaque `config` envelope through `driver.configSchema`
* and calls `driver.create()` inside a fresh child scope. The
* resulting `ProviderInstance` is stored keyed by instance id,
* alongside its scope so the entry can be torn down independently.
* - When the entry's `driver` is unknown to this build (fork, rollback,
* in-flight PR branch), the registry emits an `"unavailable"` shadow
* `ServerProvider` snapshot instead of failing. This is what makes
* downgrades and fork-hopping safe per the
* `forward/backward compatibility invariant` in
* `packages/contracts/src/providerInstance.ts`.
* - When the entry's config fails schema decode, the registry logs and
* emits a shadow snapshot with the schema detail — same bucket as an
* unknown driver.
*
* Unlike the pre-Slice-D layer, the registry now holds mutable state
* (`Ref`s + `PubSub`) and exposes an internal mutator
* (`ProviderInstanceRegistryMutator`) whose `reconcile` method diffs a
* fresh config map against the live state, tearing down removed instances
* and building new ones without disturbing unaffected instances.
*
* Every live instance runs inside its own child `Scope`. The registry's
* own scope owns all child scopes via finalizers, so closing the registry
* tears every instance down in reverse order; closing a single instance
* (via `reconcile` removing it) leaves the rest untouched.
*
* @module provider/Layers/ProviderInstanceRegistryLive
*/
import {
defaultInstanceIdForDriver,
ProviderInstanceId,
type ProviderInstanceConfig,
type ProviderInstanceConfigMap,
type ProviderDriverKind,
type ServerProvider,
} from "@t3tools/contracts";
import { Context, Effect, Equal, Exit, Layer, PubSub, Ref, Schema, Scope, Stream } from "effect";
import { buildUnavailableProviderSnapshot } from "../unavailableProviderSnapshot.ts";
import {
ProviderInstanceRegistry,
type ProviderInstanceRegistryShape,
} from "../Services/ProviderInstanceRegistry.ts";
import {
ProviderInstanceRegistryMutator,
type ProviderInstanceRegistryMutatorShape,
} from "../Services/ProviderInstanceRegistryMutator.ts";
import type { AnyProviderDriver, ProviderInstance } from "../ProviderDriver.ts";
/**
* Live registry entry: the materialized `ProviderInstance` + the fresh
* child scope its `create` effect ran in + the original `entry` envelope
* so `reconcile` can cheaply detect "no-op" updates.
*/
interface LiveEntry {
readonly instance: ProviderInstance;
readonly scope: Scope.Closeable;
readonly entry: ProviderInstanceConfig;
}
/**
* Internal state shared between the public registry service and the
* mutator service. Both services are thin shells around these refs.
*/
interface RegistryState {
readonly entries: Ref.Ref<ReadonlyMap<ProviderInstanceId, LiveEntry>>;
readonly unavailable: Ref.Ref<ReadonlyMap<ProviderInstanceId, ServerProvider>>;
readonly changes: PubSub.PubSub<void>;
}
/**
* Structural equality on `ProviderInstanceConfig` envelopes. Used by
* `reconcile` to skip rebuilds when settings arrive unchanged. Config
* payloads are opaque `unknown` at the envelope layer; `Equal.equals`
* falls back to structural equality for plain records, which matches how
* the schema decode output is constructed.
*/
const entryEqual = (a: ProviderInstanceConfig, b: ProviderInstanceConfig): boolean =>
Equal.equals(a, b);
const decodedConfigEnabled = (config: unknown): boolean | undefined => {
if (!config || typeof config !== "object" || globalThis.Array.isArray(config)) {
return undefined;
}
const enabled = (config as { readonly enabled?: unknown }).enabled;
return typeof enabled === "boolean" ? enabled : undefined;
};
/**
* Build one live entry from a raw config envelope. Returns either a
* `LiveEntry` plus undefined unavailable shadow, or a shadow snapshot and
* undefined entry — callers dispatch to the appropriate Ref bucket.
*/
const buildEntry = <R>(input: {
readonly driversById: ReadonlyMap<ProviderDriverKind, AnyProviderDriver<R>>;
readonly parentScope: Scope.Scope;
readonly instanceId: ProviderInstanceId;
readonly rawInstanceId: string;
readonly entry: ProviderInstanceConfig;
}): Effect.Effect<
| { readonly kind: "live"; readonly live: LiveEntry }
| { readonly kind: "unavailable"; readonly snapshot: ServerProvider },
never,
R
> =>
Effect.gen(function* () {
const { driversById, parentScope, instanceId, rawInstanceId, entry } = input;
const driver = driversById.get(entry.driver);
if (!driver) {
return {
kind: "unavailable" as const,
snapshot: buildUnavailableProviderSnapshot({
driverKind: entry.driver,
instanceId,
displayName: entry.displayName,
accentColor: entry.accentColor,
reason: `Driver '${entry.driver}' is not registered in this build.`,
}),
};
}
const decoder = Schema.decodeUnknownEffect(driver.configSchema);
const decodeResult = yield* decoder(entry.config ?? driver.defaultConfig()).pipe(Effect.result);
if (decodeResult._tag === "Failure") {
const issue = decodeResult.failure;
const detail = issue.message ?? String(issue);
yield* Effect.logError("Failed to decode provider instance config", {
instanceId: rawInstanceId,
driver: entry.driver,
detail,
});
return {
kind: "unavailable" as const,
snapshot: buildUnavailableProviderSnapshot({
driverKind: entry.driver,
instanceId,
displayName: entry.displayName,
accentColor: entry.accentColor,
reason: `Invalid config for instance '${rawInstanceId}': ${detail}`,
}),
};
}
const typedConfig = decodeResult.success;
const childScope = yield* Scope.make();
// Attach the child scope to the registry's parent scope: if the
// registry scope closes, each surviving instance's child scope is
// closed through this finalizer. `reconcile` manually closes the
// child scope on remove/replace; subsequent close via the parent's
// finalizer is a no-op because `Scope.close` is idempotent.
yield* Scope.addFinalizer(parentScope, Scope.close(childScope, Exit.void).pipe(Effect.ignore));
const createResult = yield* driver
.create({
instanceId,
displayName: entry.displayName,
accentColor: entry.accentColor,
environment: entry.environment ?? [],
enabled: entry.enabled ?? decodedConfigEnabled(typedConfig) ?? true,
config: typedConfig,
})
.pipe(Effect.provideService(Scope.Scope, childScope), Effect.result);
if (createResult._tag === "Failure") {
yield* Effect.logError("Failed to create provider instance", {
instanceId: rawInstanceId,
driver: entry.driver,
detail: createResult.failure.detail,
});
yield* Scope.close(childScope, Exit.void).pipe(Effect.ignore);
return {
kind: "unavailable" as const,
snapshot: buildUnavailableProviderSnapshot({
driverKind: entry.driver,
instanceId,
displayName: entry.displayName,
accentColor: entry.accentColor,
reason: `Driver '${entry.driver}' failed to create instance: ${createResult.failure.detail}`,
}),
};
}
return {
kind: "live" as const,
live: {
instance: createResult.success,
scope: childScope,
entry,
},
};
});
/**
* Reconcile-only implementation of the mutator. Exposed to the hydration
* layer; never called directly by the rest of the server.
*/
const makeReconcile = <R>(input: {
readonly state: RegistryState;
readonly driversById: ReadonlyMap<ProviderDriverKind, AnyProviderDriver<R>>;
readonly parentScope: Scope.Scope;
}): ((configMap: ProviderInstanceConfigMap) => Effect.Effect<void, never, R>) => {
const { state, driversById, parentScope } = input;
return (configMap: ProviderInstanceConfigMap) =>
Effect.gen(function* () {
const previousEntries = yield* Ref.get(state.entries);
const previousUnavailable = yield* Ref.get(state.unavailable);
const nextRaw = Object.entries(configMap);
const nextKeys = new Set<ProviderInstanceId>(
nextRaw.map(([raw]) => ProviderInstanceId.make(raw)),
);
// 1. Close scopes for instances that disappeared or whose config
// changed. Do this BEFORE creating replacements so ids map 1-to-1
// to live scopes at all times.
const removedIds: Array<ProviderInstanceId> = [];
const replacedIds = new Set<ProviderInstanceId>();
for (const [instanceId, live] of previousEntries) {
if (!nextKeys.has(instanceId)) {
removedIds.push(instanceId);
continue;
}
const nextEntry = configMap[instanceId];
if (nextEntry !== undefined && !entryEqual(live.entry, nextEntry)) {
replacedIds.add(instanceId);
}
}
for (const id of [...removedIds, ...replacedIds]) {
const live = previousEntries.get(id);
if (live) {
yield* Scope.close(live.scope, Exit.void).pipe(Effect.ignore);
}
}
// 2. Build additions and replacements. Walk `nextRaw` so the final
// entry order follows settings-author order.
const builtEntries = new Map<ProviderInstanceId, LiveEntry>();
const builtUnavailable = new Map<ProviderInstanceId, ServerProvider>();
let orderChanged = false;
const previousOrder = [...previousEntries.keys()];
const nextOrder: Array<ProviderInstanceId> = [];
for (const [rawInstanceId, entry] of nextRaw) {
const instanceId = ProviderInstanceId.make(rawInstanceId);
nextOrder.push(instanceId);
const existing = previousEntries.get(instanceId);
if (existing !== undefined && !replacedIds.has(instanceId)) {
// No-op update: keep the existing live entry and scope.
builtEntries.set(instanceId, existing);
continue;
}
const result = yield* buildEntry({
driversById,
parentScope,
instanceId,
rawInstanceId,
entry,
});
if (result.kind === "live") {
builtEntries.set(instanceId, result.live);
} else {
builtUnavailable.set(instanceId, result.snapshot);
}
}
if (previousOrder.length === nextOrder.length) {
for (let i = 0; i < previousOrder.length; i++) {
if (previousOrder[i] !== nextOrder[i]) {
orderChanged = true;
break;
}
}
} else {
orderChanged = true;
}
const entriesChanged =
orderChanged ||
removedIds.length > 0 ||
replacedIds.size > 0 ||
builtEntries.size !== previousEntries.size;
const unavailableChanged =
builtUnavailable.size !== previousUnavailable.size ||
[...builtUnavailable].some(([id, snapshot]) => {
const prev = previousUnavailable.get(id);
return prev === undefined || !Equal.equals(prev, snapshot);
}) ||
[...previousUnavailable].some(([id]) => !builtUnavailable.has(id));
yield* Ref.set(state.entries, builtEntries);
yield* Ref.set(state.unavailable, builtUnavailable);
if (entriesChanged || unavailableChanged) {
yield* PubSub.publish(state.changes, undefined);
}
});
};
/**
* Build the registry's runtime state from a concrete configMap. Returns a
* record containing:
*
* - `registry`: the read-only `ProviderInstanceRegistryShape` to expose
* under `ProviderInstanceRegistry`.
* - `mutator`: the `ProviderInstanceRegistryMutatorShape` to expose
* under `ProviderInstanceRegistryMutator`.
* - `reconcile`: the raw reconcile function, provided for convenience so
* boot-time layers can hydrate an initial map before publishing the
* services.
*
* The scope that this effect runs in owns every per-instance child scope
* created during `reconcile`. Closing that scope closes every live
* instance.
*/
export const makeProviderInstanceRegistry = <R>(input: {
readonly drivers: ReadonlyArray<AnyProviderDriver<R>>;
readonly configMap: ProviderInstanceConfigMap;
}): Effect.Effect<
{
readonly registry: ProviderInstanceRegistryShape;
readonly mutator: ProviderInstanceRegistryMutatorShape;
},
never,
R | Scope.Scope
> =>
Effect.gen(function* () {
const driversById = new Map<ProviderDriverKind, AnyProviderDriver<R>>(
input.drivers.map((driver) => [driver.driverKind, driver]),
);
// Capture the enclosing scope so per-instance child scopes can be
// attached to it at `reconcile` time. Without this, `reconcile`
// called later (e.g. from the hydration layer) would attach child
// scopes to the *caller's* scope instead of the registry's.
const parentScope = yield* Scope.Scope;
// Capture the driver R context at construction time so `reconcile`
// can be invoked later without re-providing driver dependencies.
// The service tag's declared `reconcile: Effect<void>` hides R from
// consumers — we materialize that here.
const driverContext = yield* Effect.context<R>();
const entries = yield* Ref.make<ReadonlyMap<ProviderInstanceId, LiveEntry>>(new Map());
const unavailable = yield* Ref.make<ReadonlyMap<ProviderInstanceId, ServerProvider>>(new Map());
const changes = yield* PubSub.unbounded<void>();
yield* Effect.addFinalizer(() => PubSub.shutdown(changes));
const state: RegistryState = { entries, unavailable, changes };
const reconcileWithR = makeReconcile({ state, driversById, parentScope });
const reconcile: ProviderInstanceRegistryMutatorShape["reconcile"] = (configMap) =>
reconcileWithR(configMap).pipe(Effect.provideContext(driverContext));
// Hydrate the initial configMap synchronously so callers can read
// `listInstances` immediately after this effect completes.
yield* reconcile(input.configMap);
const registry: ProviderInstanceRegistryShape = {
getInstance: (id) => Ref.get(entries).pipe(Effect.map((map) => map.get(id)?.instance)),
listInstances: Ref.get(entries).pipe(
Effect.map(
(map) =>
Array.from(map.values(), (live) => live.instance) as ReadonlyArray<ProviderInstance>,
),
),
listUnavailable: Ref.get(unavailable).pipe(
Effect.map((map) => Array.from(map.values()) as ReadonlyArray<ServerProvider>),
),
// Getters: each read constructs a fresh Stream / Effect descriptor
// so multiple consumers don't share a single already-started
// Channel or subscription. Matches the pattern `ProviderRegistry`
// uses for its own `streamChanges`.
get streamChanges() {
return Stream.fromPubSub(changes);
},
// Synchronous subscribe — callers that need to consume changes
// from a forked fibre must acquire the subscription in their own
// fibre first (via `yield* registry.subscribeChanges`) and only
// then fork a consumer loop on `Stream.fromSubscription(...)` /
// `PubSub.take(...)`. See the shape docs for the race this avoids.
get subscribeChanges() {
return PubSub.subscribe(changes);
},
};
const mutator: ProviderInstanceRegistryMutatorShape = { reconcile };
return { registry, mutator };
});
/**
* Assemble a `ProviderInstanceRegistry` Layer bound to a fixed set of
* drivers and a pre-resolved `ProviderInstanceConfigMap`. Used by tests
* that want explicit control over the registry's source-of-truth without
* wiring up the settings watcher.
*
* Only exposes the public registry tag — hot-reload consumers should use
* `ProviderInstanceRegistryMutableLayer` (below) or the hydration layer.
*/
export const ProviderInstanceRegistryLayer = <R>(input: {
readonly drivers: ReadonlyArray<AnyProviderDriver<R>>;
readonly configMap: ProviderInstanceConfigMap;
}): Layer.Layer<ProviderInstanceRegistry, never, R> =>
Layer.effect(
ProviderInstanceRegistry,
makeProviderInstanceRegistry(input).pipe(Effect.map((built) => built.registry)),
) as Layer.Layer<ProviderInstanceRegistry, never, R>;
/**
* Layer variant that also exposes the mutator tag. Consumed by
* `ProviderInstanceRegistryHydrationLive` to reconcile on settings
* changes. Tests that exercise the mutator directly can pair this Layer
* with a test-local `ServerSettingsService`.
*/
export const ProviderInstanceRegistryMutableLayer = <R>(input: {
readonly drivers: ReadonlyArray<AnyProviderDriver<R>>;
readonly configMap: ProviderInstanceConfigMap;
}): Layer.Layer<ProviderInstanceRegistry | ProviderInstanceRegistryMutator, never, R> =>
Layer.effectContext(
makeProviderInstanceRegistry(input).pipe(
Effect.map(({ registry, mutator }) =>
Context.make(ProviderInstanceRegistry, registry).pipe(
Context.add(ProviderInstanceRegistryMutator, mutator),
),
),
),
) as Layer.Layer<ProviderInstanceRegistry | ProviderInstanceRegistryMutator, never, R>;
export { defaultInstanceIdForDriver };
Loaded 100 of 327 files, more files were not shown because too many files have changed in this diff. Show more