Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
04ffe3b247 | ||
|
|
df5009c70b | ||
|
|
454d97f0cf | ||
|
|
4acb6e91ca | ||
|
|
45745a247a |
No files matched your search
@@ -8,7 +8,7 @@ on:
|
||||
|
||||
jobs:
|
||||
quality:
|
||||
name: Lint, Typecheck, Test, Browser Test, Build
|
||||
name: Lint, Typecheck, Test, Build
|
||||
runs-on: blacksmith-4vcpu-ubuntu-2404
|
||||
steps:
|
||||
- name: Checkout
|
||||
@@ -34,14 +34,6 @@ jobs:
|
||||
restore-keys: |
|
||||
${{ runner.os }}-bun-${{ hashFiles('bun.lock') }}-
|
||||
|
||||
- name: Cache Playwright browsers
|
||||
uses: actions/cache@v4
|
||||
with:
|
||||
path: ~/.cache/ms-playwright
|
||||
key: ${{ runner.os }}-playwright-${{ hashFiles('bun.lock') }}
|
||||
restore-keys: |
|
||||
${{ runner.os }}-playwright-
|
||||
|
||||
- name: Install dependencies
|
||||
run: bun install --frozen-lockfile
|
||||
|
||||
@@ -54,14 +46,6 @@ jobs:
|
||||
- name: Test
|
||||
run: bun run test
|
||||
|
||||
- name: Install browser test runtime
|
||||
run: |
|
||||
cd apps/web
|
||||
bunx playwright install --with-deps chromium
|
||||
|
||||
- name: Browser test
|
||||
run: bun run --cwd apps/web test:browser
|
||||
|
||||
- name: Build desktop pipeline
|
||||
run: bun run build:desktop
|
||||
|
||||
|
||||
@@ -22,10 +22,12 @@ jobs:
|
||||
outputs:
|
||||
version: ${{ steps.release_meta.outputs.version }}
|
||||
tag: ${{ steps.release_meta.outputs.tag }}
|
||||
ref: ${{ github.sha }}
|
||||
ref: ${{ steps.release_ref.outputs.value }}
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
fetch-depth: 0
|
||||
|
||||
- id: release_meta
|
||||
name: Resolve release version
|
||||
@@ -56,6 +58,32 @@ jobs:
|
||||
with:
|
||||
node-version-file: package.json
|
||||
|
||||
- name: Update version strings
|
||||
if: github.event_name == 'workflow_dispatch'
|
||||
env:
|
||||
RELEASE_VERSION: ${{ steps.release_meta.outputs.version }}
|
||||
run: |
|
||||
node --input-type=module -e '
|
||||
import { readFileSync, writeFileSync } from "node:fs";
|
||||
|
||||
const files = [
|
||||
"apps/server/package.json",
|
||||
"apps/desktop/package.json",
|
||||
"apps/web/package.json",
|
||||
"packages/contracts/package.json",
|
||||
];
|
||||
|
||||
for (const file of files) {
|
||||
const packageJson = JSON.parse(readFileSync(file, "utf8"));
|
||||
packageJson.version = process.env.RELEASE_VERSION;
|
||||
writeFileSync(file, `${JSON.stringify(packageJson, null, 2)}\n`);
|
||||
}
|
||||
'
|
||||
|
||||
- name: Refresh lockfile
|
||||
if: github.event_name == 'workflow_dispatch'
|
||||
run: bun install
|
||||
|
||||
- name: Install dependencies
|
||||
run: bun install --frozen-lockfile
|
||||
|
||||
@@ -68,6 +96,39 @@ jobs:
|
||||
- name: Test
|
||||
run: bun run test
|
||||
|
||||
- name: Commit and push release version + tag
|
||||
if: github.event_name == 'workflow_dispatch'
|
||||
shell: bash
|
||||
env:
|
||||
RELEASE_TAG: ${{ steps.release_meta.outputs.tag }}
|
||||
run: |
|
||||
if git ls-remote --exit-code --tags origin "$RELEASE_TAG" >/dev/null 2>&1; then
|
||||
echo "Tag $RELEASE_TAG already exists on origin." >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
git config user.name "github-actions[bot]"
|
||||
git config user.email "41898282+github-actions[bot]@users.noreply.github.com"
|
||||
|
||||
if ! git diff --quiet -- apps/server/package.json apps/desktop/package.json apps/web/package.json packages/contracts/package.json bun.lock; then
|
||||
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" -m "Co-authored-by: codex <[email protected]>"
|
||||
fi
|
||||
|
||||
git tag "$RELEASE_TAG"
|
||||
git push origin "HEAD:${GITHUB_REF_NAME}"
|
||||
git push origin "refs/tags/$RELEASE_TAG"
|
||||
|
||||
- id: release_ref
|
||||
name: Resolve source ref
|
||||
shell: bash
|
||||
run: |
|
||||
if [[ "${GITHUB_EVENT_NAME}" == "workflow_dispatch" ]]; then
|
||||
echo "value=refs/tags/${{ steps.release_meta.outputs.tag }}" >> "$GITHUB_OUTPUT"
|
||||
else
|
||||
echo "value=${GITHUB_SHA}" >> "$GITHUB_OUTPUT"
|
||||
fi
|
||||
|
||||
build:
|
||||
name: Build ${{ matrix.label }}
|
||||
needs: preflight
|
||||
@@ -257,10 +318,8 @@ jobs:
|
||||
uses: softprops/action-gh-release@v2
|
||||
with:
|
||||
tag_name: ${{ needs.preflight.outputs.tag }}
|
||||
target_commitish: ${{ needs.preflight.outputs.ref }}
|
||||
name: T3 Code v${{ needs.preflight.outputs.version }}
|
||||
generate_release_notes: true
|
||||
make_latest: true
|
||||
files: |
|
||||
release-assets/*.dmg
|
||||
release-assets/*.zip
|
||||
@@ -269,82 +328,3 @@ jobs:
|
||||
release-assets/*.blockmap
|
||||
release-assets/latest*.yml
|
||||
fail_on_unmatched_files: true
|
||||
|
||||
finalize:
|
||||
name: Finalize release
|
||||
needs: [preflight, release]
|
||||
runs-on: ubuntu-24.04
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
ref: main
|
||||
fetch-depth: 0
|
||||
|
||||
- name: Setup Bun
|
||||
uses: oven-sh/setup-bun@v2
|
||||
with:
|
||||
bun-version-file: package.json
|
||||
|
||||
- name: Setup Node
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version-file: package.json
|
||||
|
||||
- id: update_versions
|
||||
name: Update version strings
|
||||
env:
|
||||
RELEASE_VERSION: ${{ needs.preflight.outputs.version }}
|
||||
run: |
|
||||
node --input-type=module -e '
|
||||
import { appendFileSync, readFileSync, writeFileSync } from "node:fs";
|
||||
|
||||
const files = [
|
||||
"apps/server/package.json",
|
||||
"apps/desktop/package.json",
|
||||
"apps/web/package.json",
|
||||
"packages/contracts/package.json",
|
||||
];
|
||||
|
||||
let changed = false;
|
||||
for (const file of files) {
|
||||
const packageJson = JSON.parse(readFileSync(file, "utf8"));
|
||||
if (packageJson.version !== process.env.RELEASE_VERSION) {
|
||||
packageJson.version = process.env.RELEASE_VERSION;
|
||||
writeFileSync(file, `${JSON.stringify(packageJson, null, 2)}\n`);
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
|
||||
if (!changed) {
|
||||
console.log("All package.json versions already match release version.");
|
||||
}
|
||||
|
||||
appendFileSync(process.env.GITHUB_OUTPUT, `changed=${changed}\n`);
|
||||
'
|
||||
|
||||
- name: Format package.json files
|
||||
if: steps.update_versions.outputs.changed == 'true'
|
||||
run: bunx oxfmt apps/server/package.json apps/desktop/package.json apps/web/package.json packages/contracts/package.json
|
||||
|
||||
- name: Refresh lockfile
|
||||
if: steps.update_versions.outputs.changed == 'true'
|
||||
run: bun install
|
||||
|
||||
- name: Commit and push version bump
|
||||
if: steps.update_versions.outputs.changed == 'true'
|
||||
shell: bash
|
||||
env:
|
||||
RELEASE_TAG: ${{ needs.preflight.outputs.tag }}
|
||||
run: |
|
||||
if git diff --quiet -- apps/server/package.json apps/desktop/package.json apps/web/package.json packages/contracts/package.json bun.lock; then
|
||||
echo "No version changes to commit."
|
||||
exit 0
|
||||
fi
|
||||
|
||||
git config user.name "github-actions[bot]"
|
||||
git config user.email "41898282+github-actions[bot]@users.noreply.github.com"
|
||||
|
||||
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
|
||||
+1
-4
@@ -11,7 +11,4 @@ packages/*/dist
|
||||
build/
|
||||
.logs/
|
||||
release/
|
||||
.t3
|
||||
apps/web/.playwright
|
||||
apps/web/playwright-report
|
||||
apps/web/src/components/__screenshots__
|
||||
.t3
|
||||
@@ -0,0 +1,546 @@
|
||||
# Plan: Claude Code Integration (Orchestration Architecture)
|
||||
|
||||
## Why this plan was rewritten
|
||||
|
||||
The previous plan targeted a pre-orchestration architecture (`ProviderManager`, provider-native WS event methods, and direct provider UI wiring). The current app now routes everything through:
|
||||
|
||||
1. `orchestration.dispatchCommand` (client intent)
|
||||
2. `OrchestrationEngine` (decide + persist + publish domain events)
|
||||
3. `ProviderCommandReactor` (domain intent -> `ProviderService`)
|
||||
4. `ProviderService` (adapter routing + canonical runtime stream)
|
||||
5. `ProviderRuntimeIngestion` (provider runtime -> internal orchestration commands)
|
||||
6. `orchestration.domainEvent` (single push channel consumed by web)
|
||||
|
||||
Claude integration must plug into this path instead of reintroducing legacy provider-specific flows.
|
||||
|
||||
---
|
||||
|
||||
## Current constraints to design around
|
||||
|
||||
1. Provider runtime ingestion expects canonical `ProviderRuntimeEvent` shapes, not provider-native payloads.
|
||||
2. `ProviderService.startSession` currently defaults to `provider: "codex"` unless explicitly provided.
|
||||
3. `thread.turn.start` has no provider field today, so first-turn provider selection cannot be explicitly requested.
|
||||
4. `ProviderService` requires adapter `startSession()` to return a `ProviderSession` with `threadId`.
|
||||
5. Checkpoint revert currently calls `providerService.rollbackConversation()`, so Claude adapter needs a rollback strategy compatible with current reactor behavior.
|
||||
6. Web currently marks Claude as unavailable (`"Claude Code (soon)"`) and model picker is Codex-only.
|
||||
|
||||
---
|
||||
|
||||
## Architecture target
|
||||
|
||||
Add Claude as a first-class provider adapter that emits canonical runtime events and works with existing orchestration reactors without adding new WS channels or bypass paths.
|
||||
|
||||
Key decisions:
|
||||
|
||||
1. Keep orchestration provider-agnostic; adapt Claude inside adapter/layer boundaries.
|
||||
2. Use the existing canonical runtime stream (`ProviderRuntimeEvent`) as the only ingestion contract.
|
||||
3. Keep provider session routing in `ProviderService` and `ProviderSessionDirectory`.
|
||||
4. Add explicit provider selection to turn-start intent so first turn can start Claude session intentionally.
|
||||
|
||||
---
|
||||
|
||||
## Phase 1: Contracts and command shape updates
|
||||
|
||||
### 1.1 Provider-aware model contract
|
||||
|
||||
Update `packages/contracts/src/model.ts` so model resolution can be provider-aware instead of Codex-only.
|
||||
|
||||
Expected outcomes:
|
||||
|
||||
1. Introduce provider-scoped model lists (Codex + Claude).
|
||||
2. Add helpers that resolve model by provider.
|
||||
3. Preserve backwards compatibility for existing Codex defaults.
|
||||
|
||||
### 1.2 Turn-start provider intent
|
||||
|
||||
Update `packages/contracts/src/orchestration.ts`:
|
||||
|
||||
1. Add optional `provider: ProviderKind` to `ThreadTurnStartCommand`.
|
||||
2. Carry provider through `ThreadTurnStartRequestedPayload`.
|
||||
3. Keep existing command valid when provider is omitted.
|
||||
|
||||
This removes the implicit “Codex unless session already exists” behavior as the only path.
|
||||
|
||||
### 1.3 Provider session start input for Claude runtime knobs
|
||||
|
||||
Update `packages/contracts/src/provider.ts`:
|
||||
|
||||
1. Extend `ProviderSessionStartInput` with optional Claude-specific fields (for example `claudeBinaryPath`, `permissionMode`, `maxThinkingTokens`).
|
||||
2. Keep fields optional so current call sites remain valid.
|
||||
3. Continue using generic `resumeThreadId` + `resumeCursor` as the cross-provider recovery mechanism.
|
||||
|
||||
### 1.4 Contract tests
|
||||
|
||||
Update/add tests in `packages/contracts/src/*.test.ts` for:
|
||||
|
||||
1. New command payload shape.
|
||||
2. Provider-aware model resolution behavior.
|
||||
3. Backward compatibility of existing command/schema decoding.
|
||||
|
||||
---
|
||||
|
||||
## Phase 2: Claude adapter implementation
|
||||
|
||||
### 2.1 Add adapter service + layer
|
||||
|
||||
Create:
|
||||
|
||||
1. `apps/server/src/provider/Services/ClaudeCodeAdapter.ts`
|
||||
2. `apps/server/src/provider/Layers/ClaudeCodeAdapter.ts`
|
||||
|
||||
Adapter must implement `ProviderAdapterShape<ProviderAdapterError>`.
|
||||
|
||||
### 2.1.a SDK dependency and baseline config
|
||||
|
||||
Add server dependency:
|
||||
|
||||
1. `@anthropic-ai/claude-agent-sdk`
|
||||
|
||||
Baseline adapter options to support from day one:
|
||||
|
||||
1. `cwd`
|
||||
2. `model`
|
||||
3. `pathToClaudeCodeExecutable` (from `claudeBinaryPath`)
|
||||
4. `permissionMode`
|
||||
5. `maxThinkingTokens`
|
||||
6. `resume`
|
||||
7. `resumeSessionAt`
|
||||
8. `includePartialMessages`
|
||||
9. `canUseTool`
|
||||
10. `hooks`
|
||||
11. `env` and `additionalDirectories` (if needed for sandbox/workspace parity)
|
||||
|
||||
### 2.2 Claude runtime bridge
|
||||
|
||||
Implement a Claude runtime bridge (either directly in adapter layer or via dedicated manager file) that wraps Agent SDK query lifecycle.
|
||||
|
||||
Required capabilities:
|
||||
|
||||
1. Long-lived session context per adapter session.
|
||||
2. Multi-turn input queue.
|
||||
3. Interrupt support.
|
||||
4. Approval request/response bridge.
|
||||
5. Resume support via `resumeThreadId` / `resumeCursor`.
|
||||
|
||||
#### 2.2.a Agent SDK details to preserve
|
||||
|
||||
The adapter should explicitly rely on these SDK capabilities:
|
||||
|
||||
1. `query()` returns an async iterable message stream and control methods (`interrupt`, `setModel`, `setPermissionMode`, `setMaxThinkingTokens`, account/status helpers).
|
||||
2. Multi-turn input is supported via async-iterable prompt input.
|
||||
3. Tool approval decisions are provided via `canUseTool`.
|
||||
4. Resume support uses `resume` and optional `resumeSessionAt`.
|
||||
5. Hooks can be used for lifecycle signals (`Stop`, `PostToolUse`, etc.) when we need adapter-originated checkpoint/runtime events.
|
||||
|
||||
#### 2.2.b Effect-native session lifecycle skeleton
|
||||
|
||||
```ts
|
||||
import { query } from "@anthropic-ai/claude-agent-sdk";
|
||||
import { Effect } from "effect";
|
||||
|
||||
const acquireSession = (input: ProviderSessionStartInput) =>
|
||||
Effect.acquireRelease(
|
||||
Effect.tryPromise({
|
||||
try: async () => {
|
||||
const abortController = new AbortController();
|
||||
const result = query({
|
||||
prompt: makePromptAsyncIterable(input.sessionId),
|
||||
options: {
|
||||
cwd: input.cwd,
|
||||
model: input.model,
|
||||
permissionMode: input.permissionMode,
|
||||
maxThinkingTokens: input.maxThinkingTokens,
|
||||
pathToClaudeCodeExecutable: input.claudeBinaryPath,
|
||||
resume: input.resumeThreadId,
|
||||
resumeSessionAt: readResumeCursor(input.resumeCursor),
|
||||
signal: abortController.signal,
|
||||
includePartialMessages: true,
|
||||
canUseTool: makeCanUseTool(input.sessionId),
|
||||
hooks: makeClaudeHooks(input.sessionId),
|
||||
},
|
||||
});
|
||||
return { abortController, result };
|
||||
},
|
||||
catch: (cause) =>
|
||||
new ProviderAdapterProcessError({
|
||||
provider: "claudeCode",
|
||||
sessionId: "pending",
|
||||
detail: "Failed to start Claude runtime session.",
|
||||
cause,
|
||||
}),
|
||||
}),
|
||||
({ abortController }) => Effect.sync(() => abortController.abort()),
|
||||
);
|
||||
```
|
||||
|
||||
#### 2.2.c AsyncIterable -> Effect Stream integration
|
||||
|
||||
Preferred when available in the pinned Effect version:
|
||||
|
||||
```ts
|
||||
const sdkMessageStream = Stream.fromAsyncIterable(
|
||||
session.result,
|
||||
(cause) =>
|
||||
new ProviderAdapterProcessError({
|
||||
provider: "claudeCode",
|
||||
sessionId,
|
||||
detail: "Claude runtime stream failed.",
|
||||
cause,
|
||||
}),
|
||||
);
|
||||
```
|
||||
|
||||
Portable fallback (already aligned with current server patterns):
|
||||
|
||||
```ts
|
||||
const queue = yield* Queue.unbounded<ClaudeSdkMessage>();
|
||||
yield* Effect.forkScoped(
|
||||
Effect.tryPromise({
|
||||
try: async () => {
|
||||
for await (const message of session.result) {
|
||||
Queue.offerAllUnsafe(queue, [message]);
|
||||
}
|
||||
},
|
||||
catch: (cause) =>
|
||||
new ProviderAdapterProcessError({
|
||||
provider: "claudeCode",
|
||||
sessionId,
|
||||
detail: "Claude runtime stream pump failed.",
|
||||
cause,
|
||||
}),
|
||||
}),
|
||||
);
|
||||
const sdkMessageStream = Stream.fromQueue(queue);
|
||||
```
|
||||
|
||||
#### 2.2.d Multi-turn prompt queue pattern (Effect)
|
||||
|
||||
Use an Effect queue as the single input boundary:
|
||||
|
||||
```ts
|
||||
const promptQueue = yield* Queue.unbounded<ClaudePromptEnvelope>();
|
||||
|
||||
const prompt: AsyncIterable<ClaudePromptEnvelope> = {
|
||||
[Symbol.asyncIterator]() {
|
||||
return {
|
||||
next: async () => {
|
||||
const item = await Effect.runPromise(Queue.take(promptQueue));
|
||||
if (item.type === "terminate") {
|
||||
return { done: true, value: undefined };
|
||||
}
|
||||
return { done: false, value: item };
|
||||
},
|
||||
};
|
||||
},
|
||||
};
|
||||
```
|
||||
|
||||
`sendTurn()` enqueues a user envelope, while `stopSession()` enqueues terminate and aborts.
|
||||
|
||||
#### 2.2.e Approval bridge with `canUseTool`
|
||||
|
||||
Map SDK approval checks to existing orchestration approval flows:
|
||||
|
||||
```ts
|
||||
const canUseTool = async (toolName: string, toolInput: Record<string, unknown>) => {
|
||||
if (approvalModeIsFullAccess(sessionId)) {
|
||||
return { behavior: "allow", updatedInput: toolInput };
|
||||
}
|
||||
|
||||
const requestId = ApprovalRequestId.makeUnsafe(crypto.randomUUID());
|
||||
emitRuntimeEvent({
|
||||
type: "approval.requested",
|
||||
provider: "claudeCode",
|
||||
sessionId,
|
||||
requestId,
|
||||
requestKind: classifyTool(toolName),
|
||||
detail: summarizeToolRequest(toolName, toolInput),
|
||||
// ... eventId/createdAt
|
||||
});
|
||||
|
||||
const decision = await waitForApprovalDecision(requestId);
|
||||
emitRuntimeEvent({
|
||||
type: "approval.resolved",
|
||||
provider: "claudeCode",
|
||||
sessionId,
|
||||
requestId,
|
||||
decision,
|
||||
// ... eventId/createdAt
|
||||
});
|
||||
|
||||
return decision === "accept" || decision === "acceptForSession"
|
||||
? { behavior: "allow", updatedInput: toolInput }
|
||||
: { behavior: "deny", message: "User declined tool execution." };
|
||||
};
|
||||
```
|
||||
|
||||
#### 2.2.f Hooks and checkpoint signals
|
||||
|
||||
If Claude hooks provide cleaner turn boundaries, convert them into canonical runtime events (`turn.completed` and optionally `checkpoint.captured`) so `CheckpointReactor` remains unchanged:
|
||||
|
||||
```ts
|
||||
hooks: {
|
||||
Stop: [
|
||||
{
|
||||
matcher: {},
|
||||
hooks: [
|
||||
async () => {
|
||||
emitRuntimeEvent({
|
||||
type: "checkpoint.captured",
|
||||
provider: "claudeCode",
|
||||
sessionId,
|
||||
threadId,
|
||||
turnId: activeTurnId,
|
||||
turnCount: nextTurnCount(),
|
||||
// ... eventId/createdAt
|
||||
});
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
}
|
||||
```
|
||||
|
||||
#### 2.2.g Runtime control method wiring
|
||||
|
||||
Adapter should expose SDK controls through existing service methods and runtime payload updates:
|
||||
|
||||
1. `interruptTurn()` -> `result.interrupt()`
|
||||
2. Model override on send turn -> `result.setModel(model)` before enqueuing prompt
|
||||
3. Runtime mode changes -> `result.setPermissionMode(mode)` if we support live mode switching
|
||||
4. Thinking budget updates -> `result.setMaxThinkingTokens(tokens)` when configured
|
||||
|
||||
### 2.3 Canonical event mapping
|
||||
|
||||
Map Claude SDK events to `ProviderRuntimeEvent`:
|
||||
|
||||
1. `session.started` / `session.exited`
|
||||
2. `turn.started` / `turn.completed`
|
||||
3. `message.delta` / `message.completed`
|
||||
4. `tool.started` / `tool.completed`
|
||||
5. `approval.requested` / `approval.resolved`
|
||||
6. `runtime.error`
|
||||
|
||||
No provider-native event methods should leak beyond the adapter boundary.
|
||||
|
||||
Reference mapping table:
|
||||
|
||||
| Claude SDK message/callback | Canonical runtime event(s) | Notes |
|
||||
|---|---|---|
|
||||
| assistant partial text | `message.delta` | Emit deltas only (do not resend full content each chunk). |
|
||||
| assistant final message | `message.completed` | Must include stable `itemId` for dedupe/finalize behavior. |
|
||||
| result (success) | `turn.completed` (`status: "completed"`) | This is the main turn boundary for checkpointing. |
|
||||
| result (interrupted/cancelled) | `turn.completed` (`status: "interrupted"`/`"cancelled"`) | Preserve state semantics used by ingestion + UI. |
|
||||
| result (error) | `runtime.error` and `turn.completed` (`status: "failed"`) | Include concise error message. |
|
||||
| tool start | `tool.started` | Set `toolKind` using shared classifier (`command`, `file-change`, `other`). |
|
||||
| tool result | `tool.completed` | Include detail summary used by activity feed. |
|
||||
| canUseTool prompt | `approval.requested` | Source of request id shown in UI. |
|
||||
| approval decision returned | `approval.resolved` | Must correlate using same request id. |
|
||||
| session initialization | `session.started`, optional `thread.started` | Ensure `threadId` is emitted early and consistently. |
|
||||
| process exit/close | `session.exited` | Required for session status projection cleanup. |
|
||||
|
||||
### 2.4 Session/thread/resume identifiers
|
||||
|
||||
Define explicit adapter semantics:
|
||||
|
||||
1. `sessionId`: adapter-owned stable session id.
|
||||
2. `threadId`: Claude conversation/session identifier returned as `ProviderThreadId`.
|
||||
3. `resumeCursor`: provider-specific cursor (for example message id) needed for precise recovery/rollback.
|
||||
|
||||
### 2.5 Rollback/read strategy
|
||||
|
||||
Implement `readThread()` and `rollbackThread()` in a way compatible with `CheckpointReactor`.
|
||||
|
||||
Preferred:
|
||||
|
||||
1. Track per-turn resume cursors and reconstruct session state on rollback.
|
||||
2. Keep adapter `sessionId` stable across internal rehydration/restart.
|
||||
|
||||
Fallback (explicitly documented if chosen):
|
||||
|
||||
1. Filesystem revert succeeds even when conversation rewind is partial.
|
||||
2. Reactor behavior is updated to surface a clear warning activity instead of silent drift.
|
||||
|
||||
### 2.6 Adapter unit tests
|
||||
|
||||
Add tests mirroring Codex adapter coverage:
|
||||
|
||||
1. Provider validation (`provider === "claudeCode"`).
|
||||
2. Event mapping to canonical runtime events.
|
||||
3. Approval request lifecycle.
|
||||
4. Resume/recovery behavior.
|
||||
5. Rollback behavior.
|
||||
|
||||
---
|
||||
|
||||
## Phase 3: Register adapter in runtime composition
|
||||
|
||||
### 3.1 Adapter registry wiring
|
||||
|
||||
Update:
|
||||
|
||||
1. `apps/server/src/provider/Layers/ProviderAdapterRegistry.ts`
|
||||
|
||||
Register both Codex and Claude adapters.
|
||||
|
||||
### 3.2 Server layer composition
|
||||
|
||||
Update:
|
||||
|
||||
1. `apps/server/src/serverLayers.ts`
|
||||
|
||||
Provide `ClaudeCodeAdapterLive` alongside Codex in `makeServerProviderLayer()`.
|
||||
|
||||
### 3.3 Composition tests
|
||||
|
||||
Update integration tests to ensure:
|
||||
|
||||
1. Registry exposes Claude provider.
|
||||
2. Provider service can route Claude sessions.
|
||||
|
||||
---
|
||||
|
||||
## Phase 4: Orchestration command/reactor updates
|
||||
|
||||
### 4.1 Decider propagation
|
||||
|
||||
Update `apps/server/src/orchestration/decider.ts`:
|
||||
|
||||
1. Carry optional `provider` from `thread.turn.start` command into `thread.turn-start-requested` event payload.
|
||||
|
||||
### 4.2 ProviderCommandReactor provider selection
|
||||
|
||||
Update `apps/server/src/orchestration/Layers/ProviderCommandReactor.ts`:
|
||||
|
||||
1. Prefer provider from turn-start event payload when starting a new session.
|
||||
2. Fallback to existing thread session provider when payload omitted.
|
||||
3. Fallback to default provider only when neither is present.
|
||||
|
||||
Switch behavior policy (explicit in implementation):
|
||||
|
||||
1. If active session provider differs from requested provider, stop and recreate session before sending turn.
|
||||
2. Keep current provider when request omits provider.
|
||||
|
||||
### 4.3 Reactor/invariant tests
|
||||
|
||||
Update/add tests in:
|
||||
|
||||
1. `apps/server/src/orchestration/Layers/ProviderCommandReactor.test.ts`
|
||||
2. `apps/server/src/orchestration/*.test.ts` as needed
|
||||
|
||||
Validate first-turn provider choice, provider switching semantics, and backward compatibility when provider is omitted.
|
||||
|
||||
---
|
||||
|
||||
## Phase 5: Web provider UX enablement
|
||||
|
||||
### 5.1 Enable Claude option
|
||||
|
||||
Update `apps/web/src/session-logic.ts`:
|
||||
|
||||
1. Mark Claude provider option as available.
|
||||
|
||||
### 5.2 Provider selection in composer
|
||||
|
||||
Update `apps/web/src/components/ChatView.tsx`:
|
||||
|
||||
1. Add provider picker near model/runtime controls.
|
||||
2. Include selected provider in `thread.turn.start` command payload.
|
||||
3. Keep selected provider sticky per thread in client state (or derive from active session provider when present).
|
||||
|
||||
### 5.3 Provider-aware model picker
|
||||
|
||||
Update model picker usage so model options reflect selected provider.
|
||||
|
||||
### 5.4 Web tests
|
||||
|
||||
Update/add tests for:
|
||||
|
||||
1. Provider picker interactions.
|
||||
2. Turn-start command includes provider.
|
||||
3. Model list switches by provider.
|
||||
|
||||
---
|
||||
|
||||
## Phase 6: Checkpoint and revert compatibility
|
||||
|
||||
### 6.1 Validate checkpoint reactor expectations
|
||||
|
||||
Exercise `apps/server/src/orchestration/Layers/CheckpointReactor.ts` flows with Claude:
|
||||
|
||||
1. Turn baseline capture.
|
||||
2. Turn completion checkpoint capture.
|
||||
3. Revert + provider rollback coordination.
|
||||
|
||||
### 6.2 Policy for partial rollback support
|
||||
|
||||
If Claude cannot support full conversation rewind at parity with Codex:
|
||||
|
||||
1. Document behavior clearly.
|
||||
2. Emit explicit thread activity for degraded rollback behavior.
|
||||
3. Ensure filesystem state remains correct and predictable.
|
||||
|
||||
### 6.3 Checkpoint tests
|
||||
|
||||
Add/update tests in checkpoint + provider service integration suites for Claude revert behavior.
|
||||
|
||||
---
|
||||
|
||||
## Phase 7: End-to-end hardening and observability
|
||||
|
||||
### 7.1 Integration tests
|
||||
|
||||
Add integration coverage for:
|
||||
|
||||
1. `thread.turn.start` with `provider: "claudeCode"` from fresh thread.
|
||||
2. Session recovery after restart (provider session alias/recovery path).
|
||||
3. Approval request/respond flow.
|
||||
4. Interrupt behavior.
|
||||
5. Revert flow with rollback.
|
||||
|
||||
### 7.2 WS behavior regression check
|
||||
|
||||
Ensure no contract regressions:
|
||||
|
||||
1. Client still consumes only `orchestration.domainEvent`.
|
||||
2. No new provider-specific WS channels introduced.
|
||||
|
||||
### 7.3 Logging
|
||||
|
||||
Confirm both native and canonical provider logs remain useful with multi-adapter setup:
|
||||
|
||||
1. `provider-native.ndjson`
|
||||
2. `provider-canonical.ndjson`
|
||||
|
||||
---
|
||||
|
||||
## File checklist
|
||||
|
||||
Likely files to touch:
|
||||
|
||||
1. `packages/contracts/src/model.ts`
|
||||
2. `packages/contracts/src/orchestration.ts`
|
||||
3. `packages/contracts/src/provider.ts`
|
||||
4. `apps/server/src/provider/Services/ClaudeCodeAdapter.ts` (new)
|
||||
5. `apps/server/src/provider/Layers/ClaudeCodeAdapter.ts` (new)
|
||||
6. `apps/server/src/provider/Layers/ProviderAdapterRegistry.ts`
|
||||
7. `apps/server/src/serverLayers.ts`
|
||||
8. `apps/server/src/orchestration/decider.ts`
|
||||
9. `apps/server/src/orchestration/Layers/ProviderCommandReactor.ts`
|
||||
10. `apps/web/src/session-logic.ts`
|
||||
11. `apps/web/src/components/ChatView.tsx`
|
||||
12. Related tests under `packages/contracts/src`, `apps/server/src/provider/Layers`, `apps/server/src/orchestration/Layers`, `apps/server/integration`, and `apps/web/src`.
|
||||
|
||||
---
|
||||
|
||||
## Delivery order
|
||||
|
||||
1. Contracts for provider selection + models.
|
||||
2. Claude adapter + unit tests.
|
||||
3. Registry/layer wiring.
|
||||
4. Reactor updates for provider-aware session start.
|
||||
5. Web provider picker + provider-aware models.
|
||||
6. Checkpoint/revert compatibility.
|
||||
7. End-to-end integration tests and stabilization.
|
||||
|
||||
This order keeps risk isolated and maintains a working orchestrated path at each stage.
|
||||
@@ -1,327 +0,0 @@
|
||||
# Plan: Cursor ACP (`agent acp`) Provider Integration
|
||||
|
||||
## Goal
|
||||
|
||||
Add Cursor as a first-class provider in T3 Code using ACP (`agent acp`) over JSON-RPC 2.0 stdio, with robust session lifecycle handling and canonical `ProviderRuntimeEvent` projection.
|
||||
|
||||
---
|
||||
|
||||
## 1) Exploration Findings (from live ACP probes)
|
||||
|
||||
### 1.1 Core invocation and transport
|
||||
|
||||
1. Binary is `agent` on PATH (`2026.02.27-e7d2ef6` observed).
|
||||
2. ACP server command is `agent acp`.
|
||||
3. Transport is newline-delimited JSON-RPC 2.0 over stdio.
|
||||
4. Messages:
|
||||
- client -> server: requests and responses to server-initiated requests
|
||||
- server -> client: responses, notifications (`session/update`), and server requests (`session/request_permission`)
|
||||
|
||||
### 1.2 Handshake and session calls observed
|
||||
|
||||
1. `initialize` returns:
|
||||
- `protocolVersion`
|
||||
- `agentCapabilities` (`loadSession`, `mcpCapabilities`, `promptCapabilities`)
|
||||
- `authMethods` (includes `cursor_login`)
|
||||
2. `authenticate { methodId: "cursor_login" }` returns `{}` when logged in.
|
||||
3. `session/new` returns:
|
||||
- `sessionId`
|
||||
- `modes` (`agent`, `plan`, `ask`)
|
||||
4. `session/load` works and requires `sessionId`, `cwd`, `mcpServers`.
|
||||
5. `session/prompt` returns terminal response `{ stopReason: "end_turn" | "cancelled" }`.
|
||||
|
||||
Important sequence note:
|
||||
1. ACP currently allows `session/new` even without explicit `initialize`/`authenticate` when local auth already exists.
|
||||
2. For adapter consistency and forward compatibility, we should still send `initialize` and `authenticate` during startup.
|
||||
|
||||
### 1.3 `session/update` event families observed
|
||||
|
||||
Observed `params.update.sessionUpdate` values:
|
||||
|
||||
1. `available_commands_update`
|
||||
2. `agent_thought_chunk`
|
||||
3. `agent_message_chunk`
|
||||
4. `tool_call`
|
||||
5. `tool_call_update`
|
||||
|
||||
Observed payload behavior:
|
||||
|
||||
1. `agent_*_chunk` provides `content: { type: "text", text: string }`.
|
||||
2. `tool_call` may be emitted multiple times for same `toolCallId`:
|
||||
- initial generic form (`title: "Terminal"`, `rawInput: {}`)
|
||||
- enriched form (`title: "\`pwd\`"`, `rawInput: { command: "pwd" }`)
|
||||
3. `tool_call_update` statuses observed:
|
||||
- `in_progress`
|
||||
- `completed`
|
||||
4. `tool_call_update` on completion may include `rawOutput`:
|
||||
- terminal: `{ exitCode, stdout, stderr }`
|
||||
- search/find: `{ totalFiles, truncated }`
|
||||
|
||||
### 1.4 Permission flow observed
|
||||
|
||||
1. ACP server sends `session/request_permission` (JSON-RPC request with `id`).
|
||||
2. Request shape includes:
|
||||
- `params.sessionId`
|
||||
- `params.toolCall`
|
||||
- `params.options` (`allow-once`, `allow-always`, `reject-once`)
|
||||
3. Client must respond on same `id` with:
|
||||
- `{ outcome: { outcome: "selected", optionId: "<one-option-id>" } }`
|
||||
4. Reject path still results in tool lifecycle completion events (`tool_call_update status: completed`), typically without `rawOutput`.
|
||||
|
||||
### 1.5 Error and capability quirks
|
||||
|
||||
1. `session/cancel` currently returns:
|
||||
- JSON-RPC error `-32601` Method not found
|
||||
2. Error shape examples:
|
||||
- unknown auth method: `-32602`
|
||||
- `session/load` missing/invalid params: `-32602`
|
||||
- `session/prompt` unknown session: `-32603` with details
|
||||
3. Parallel prompts on same session are effectively single-flight:
|
||||
- second prompt can cause first to complete with `stopReason: "cancelled"`.
|
||||
4. `session/new` accepts a `model` field (no explicit echo in response).
|
||||
|
||||
Probe artifacts:
|
||||
1. `.tmp/acp-probe/*/transcript.ndjson`
|
||||
2. `.tmp/acp-probe/*/summary.json`
|
||||
3. `scripts/cursor-acp-probe.mjs`
|
||||
|
||||
---
|
||||
|
||||
## 2) Integration Constraints for T3
|
||||
|
||||
1. T3 adapter contract still requires:
|
||||
- `startSession`, `sendTurn`, `interruptTurn`, `respondToRequest`, `readThread`, `rollbackThread`, `stopSession`, `listSessions`, `hasSession`, `stopAll`, `streamEvents`.
|
||||
2. Orchestration consumes canonical `ProviderRuntimeEvent` only.
|
||||
3. `ProviderCommandReactor` provider precedence fix remains required (respect explicit provider on turn start).
|
||||
4. ACP now supports external permission decisions, so Cursor can participate in T3 approval UX via adapter-managed request/response plumbing.
|
||||
|
||||
---
|
||||
|
||||
## 3) Proposed Architecture
|
||||
|
||||
### 3.1 New server components
|
||||
|
||||
1. `apps/server/src/provider/Services/CursorAdapter.ts` (service contract/tag + ACP event schemas).
|
||||
2. `apps/server/src/provider/Layers/CursorAdapter.ts` (single implementation unit; owns ACP process lifecycle, JSON-RPC routing, runtime projection).
|
||||
3. No manager indirection; keep logic in layer implementation.
|
||||
|
||||
### 3.2 Session model
|
||||
|
||||
1. One long-lived ACP child process per T3 Cursor provider session.
|
||||
2. Track:
|
||||
- `providerSessionId` (T3 synthetic ID)
|
||||
- `acpSessionId` (from `session/new` or restored via `session/load`)
|
||||
- `cwd`, `model`, in-flight turn state
|
||||
- pending permission requests by JSON-RPC request id
|
||||
3. Resume support:
|
||||
- persist `acpSessionId` in provider resume metadata and call `session/load` on reattach.
|
||||
|
||||
### 3.3 Command strategy
|
||||
|
||||
1. `startSession`:
|
||||
- spawn `agent acp`
|
||||
- `initialize`
|
||||
- `authenticate(cursor_login)` (best-effort, typed failure handling)
|
||||
- `session/new` or `session/load`
|
||||
2. `sendTurn`:
|
||||
- send `session/prompt { sessionId, prompt: [...] }`
|
||||
- consume streaming `session/update` notifications until terminal prompt response
|
||||
3. `interruptTurn`:
|
||||
- no native `session/cancel` today; implement fallback:
|
||||
- terminate ACP process + restart + `session/load` for subsequent turns
|
||||
- mark in-flight turn as interrupted/failed in canonical events
|
||||
4. `respondToRequest`:
|
||||
- map T3 approval decision -> ACP `optionId`
|
||||
- reply to exact JSON-RPC request id from `session/request_permission`
|
||||
|
||||
### 3.4 Effect-first implementation style (required)
|
||||
|
||||
1. Keep logic inside `CursorAdapterLive`.
|
||||
2. Use Effect primitives:
|
||||
- `Queue` + `Stream.fromQueue` for event fan-out
|
||||
- `Ref` / `Ref.Synchronized` for session/process/request state
|
||||
- scoped fibers for stdout/stderr read loops
|
||||
3. Typed JSON decode at boundary:
|
||||
- request/response envelopes
|
||||
- `session/update` union schema
|
||||
- permission-request schema
|
||||
4. Keep adapter errors in typed error algebra with explicit mapping at process/protocol boundaries.
|
||||
|
||||
---
|
||||
|
||||
## 4) Canonical Event Mapping Plan (ACP -> ProviderRuntimeEvent)
|
||||
|
||||
1. `session/update: agent_message_chunk`
|
||||
- emit `message.delta` for assistant stream
|
||||
2. prompt terminal response (`session/prompt` result `stopReason: end_turn`)
|
||||
- emit `message.completed` + `turn.completed`
|
||||
3. `session/update: agent_thought_chunk`
|
||||
- initial mapping: emit thinking activity (or ignore if we keep current canonical surface minimal)
|
||||
4. `session/update: tool_call`
|
||||
- first-seen `toolCallId` emits `tool.started`
|
||||
- subsequent `tool_call` for same ID treated as metadata update (no duplicate started event)
|
||||
5. `session/update: tool_call_update`
|
||||
- `in_progress`: optional progress activity
|
||||
- `completed`: emit `tool.completed` with summarized `rawOutput` when present
|
||||
6. `session/request_permission`
|
||||
- emit `approval.requested` with mapped options
|
||||
- when client decision sent, emit `approval.resolved`
|
||||
7. protocol/process error
|
||||
- emit `runtime.error`
|
||||
- fail active turn/session as appropriate
|
||||
|
||||
Synthetic IDs:
|
||||
1. `turnId`: T3-generated UUID per `sendTurn`.
|
||||
2. `itemId`:
|
||||
- assistant stream: `${turnId}:assistant`
|
||||
- tools: `${turnId}:${toolCallId}`
|
||||
|
||||
---
|
||||
|
||||
## 5) Approval, Resume, and Rollback Behavior
|
||||
|
||||
### 5.1 Approvals
|
||||
|
||||
1. Cursor ACP permission requests are externally controllable; implement full `respondToRequest` path in v1.
|
||||
2. Decision mapping:
|
||||
- allow once -> `allow-once`
|
||||
- allow always -> `allow-always`
|
||||
- reject -> `reject-once`
|
||||
|
||||
### 5.2 Resume
|
||||
|
||||
1. `session/load` is available and should be first-class for adapter restart/reconnect.
|
||||
2. Must send required params: `sessionId`, `cwd`, `mcpServers`.
|
||||
|
||||
### 5.3 Rollback / thread read
|
||||
|
||||
1. ACP currently has no observed rollback API.
|
||||
2. Plan for v1:
|
||||
- `readThread`: adapter-maintained snapshot projection
|
||||
- `rollbackThread`: explicit unsupported error
|
||||
3. Product guard:
|
||||
- disable checkpoint revert for Cursor threads in UI until rollback exists.
|
||||
|
||||
---
|
||||
|
||||
## 6) Required Contract and Runtime Changes
|
||||
|
||||
### 6.1 Contracts
|
||||
|
||||
1. Add `cursor` to `ProviderKind`.
|
||||
2. Add Cursor provider start options (`providerOptions.cursor`), ACP-oriented:
|
||||
- optional `binaryPath`
|
||||
- optional auth/mode knobs if needed later
|
||||
3. Extend model options for Cursor list and traits mapping.
|
||||
4. Add schemas for ACP-native event union in Cursor adapter service file.
|
||||
|
||||
### 6.2 Server orchestration and registry
|
||||
|
||||
1. Register `CursorAdapter` in provider registry and server layer wiring.
|
||||
2. Update provider-kind persistence decoding for `cursor`.
|
||||
3. Fix `ProviderCommandReactor` precedence to honor explicit provider in turn-start command.
|
||||
|
||||
### 6.3 Web
|
||||
|
||||
1. Cursor in provider picker and model picker (already partially done).
|
||||
2. Trait controls map to concrete Cursor model identifiers.
|
||||
3. Surface unsupported rollback behavior in UX.
|
||||
|
||||
---
|
||||
|
||||
## 7) Implementation Phases
|
||||
|
||||
### Phase A: ACP process and protocol skeleton
|
||||
|
||||
1. Implement ACP process lifecycle in `CursorAdapterLive`.
|
||||
2. Implement JSON-RPC request/response multiplexer.
|
||||
3. Implement `initialize`/`authenticate`/`session/new|load` flow.
|
||||
4. Wire `streamEvents` from ACP notifications.
|
||||
|
||||
### Phase B: Runtime projection and approvals
|
||||
|
||||
1. Map `session/update` variants to canonical runtime events.
|
||||
2. Implement permission-request bridging to `respondToRequest`.
|
||||
3. Implement dedupe for repeated `tool_call` on same `toolCallId`.
|
||||
|
||||
### Phase C: Turn control and interruption
|
||||
|
||||
1. Implement single in-flight prompt protection per session.
|
||||
2. Implement interruption fallback (process restart + reload) because `session/cancel` unavailable.
|
||||
3. Ensure clean state recovery on ACP process crash.
|
||||
|
||||
### Phase D: Orchestration + UX polish
|
||||
|
||||
1. Provider routing precedence fix.
|
||||
2. Cursor-specific UX notes for unsupported rollback.
|
||||
3. End-to-end smoke and event log validation.
|
||||
|
||||
---
|
||||
|
||||
## 8) Test Plan
|
||||
|
||||
Follow project rule: backend external-service integrations tested via layered fakes, not by mocking core business logic.
|
||||
|
||||
### 8.1 Unit tests (`CursorAdapter`)
|
||||
|
||||
1. JSON-RPC envelope parsing:
|
||||
- response matching by id
|
||||
- server request handling (`session/request_permission`)
|
||||
- notification decode (`session/update`)
|
||||
2. Event projection:
|
||||
- `agent_message_chunk` / `agent_thought_chunk`
|
||||
- `tool_call` + `tool_call_update` dedupe/lifecycle
|
||||
- permission request -> approval events
|
||||
3. Error mapping:
|
||||
- unknown session
|
||||
- method-not-found (`session/cancel`)
|
||||
- invalid params
|
||||
|
||||
### 8.2 Provider service/routing tests
|
||||
|
||||
1. Registry resolves `cursor`.
|
||||
2. Session directory persistence reads/writes `cursor`.
|
||||
3. ProviderService fan-out ordering with Cursor ACP events.
|
||||
|
||||
### 8.3 Orchestration tests
|
||||
|
||||
1. `thread.turn.start` with `provider: cursor` routes to Cursor adapter.
|
||||
2. approval response command maps to ACP permission response.
|
||||
3. checkpoint revert on Cursor thread returns controlled unsupported failure.
|
||||
|
||||
### 8.4 Optional live smoke
|
||||
|
||||
1. Env-gated ACP smoke:
|
||||
- start session
|
||||
- run prompt
|
||||
- observe deltas + completion
|
||||
- exercise permission request path with one tool call
|
||||
|
||||
---
|
||||
|
||||
## 9) Operational Notes
|
||||
|
||||
1. Keep one in-flight turn per ACP session.
|
||||
2. Keep per-session ACP process logs/NDJSON artifacts for debugging.
|
||||
3. Treat `session/cancel` as unsupported until Cursor ships it; avoid relying on it.
|
||||
4. Preserve resume metadata (`acpSessionId`) for crash recovery.
|
||||
|
||||
---
|
||||
|
||||
## 10) Open Questions
|
||||
|
||||
1. Should we call `authenticate` always, or only after auth-required errors?
|
||||
2. Should model selection be passed at `session/new` only, or can/should we support model switching mid-session if ACP adds API?
|
||||
3. For interruption UX, do we expose “hard interrupt” semantics (process restart) explicitly?
|
||||
|
||||
---
|
||||
|
||||
## 11) Delivery Checklist
|
||||
|
||||
1. Plan/documentation switched from headless `agent -p` to ACP `agent acp`.
|
||||
2. Contracts updated (`ProviderKind`, Cursor options, model/trait mapping).
|
||||
3. Cursor ACP adapter layer implemented and registered.
|
||||
4. Provider precedence fixed in orchestration router.
|
||||
5. Approval response path wired through ACP permission requests.
|
||||
6. Tests added for protocol decode, projection, approval flow, and routing.
|
||||
7. Lint + tests green.
|
||||
@@ -0,0 +1,64 @@
|
||||
import path from "path";
|
||||
import fs from "fs";
|
||||
|
||||
const FAVICON_CANDIDATES = [
|
||||
"favicon.svg", "favicon.ico", "favicon.png",
|
||||
"public/favicon.svg", "public/favicon.ico", "public/favicon.png",
|
||||
"app/favicon.ico", "app/favicon.png", "app/icon.svg", "app/icon.png", "app/icon.ico",
|
||||
"src/favicon.ico", "src/favicon.svg", "src/app/favicon.ico", "src/app/icon.svg", "src/app/icon.png",
|
||||
];
|
||||
|
||||
const ICON_SOURCE_FILES = [
|
||||
"index.html", "public/index.html",
|
||||
"app/routes/__root.tsx", "src/routes/__root.tsx",
|
||||
"app/root.tsx", "src/root.tsx", "src/index.html",
|
||||
];
|
||||
|
||||
const LINK_ICON_HTML_RE = /<link[^>]*rel=["'](?:icon|shortcut icon)["'][^>]*href=["']([^"'?]+)/i;
|
||||
const LINK_ICON_OBJ_RE = /rel:\s*["'](?:icon|shortcut icon)["'][^}]*href:\s*["']([^"'?]+)/i;
|
||||
|
||||
function test(projectCwd) {
|
||||
console.log("--- Testing:", projectCwd, "---");
|
||||
|
||||
for (const c of FAVICON_CANDIDATES) {
|
||||
const full = path.join(projectCwd, c);
|
||||
if (fs.existsSync(full) && fs.statSync(full).isFile()) {
|
||||
console.log(" Phase 1 FOUND:", c);
|
||||
return;
|
||||
}
|
||||
}
|
||||
console.log(" Phase 1: no match");
|
||||
|
||||
for (const sf of ICON_SOURCE_FILES) {
|
||||
const full = path.join(projectCwd, sf);
|
||||
if (!fs.existsSync(full)) continue;
|
||||
const content = fs.readFileSync(full, "utf8");
|
||||
const href = content.match(LINK_ICON_HTML_RE)?.[1] || content.match(LINK_ICON_OBJ_RE)?.[1];
|
||||
if (href) {
|
||||
const clean = href.replace(/^\//, "");
|
||||
const tryPaths = [path.join(projectCwd, "public", clean), path.join(projectCwd, clean)];
|
||||
for (const p of tryPaths) {
|
||||
if (fs.existsSync(p)) {
|
||||
console.log(" Phase 2 FOUND:", sf, "->", href, "->", p);
|
||||
return;
|
||||
}
|
||||
}
|
||||
console.log(" Phase 2 href found but file missing:", href);
|
||||
}
|
||||
}
|
||||
console.log(" Phase 2: no match");
|
||||
}
|
||||
|
||||
function getTestPaths() {
|
||||
const cliPaths = process.argv.slice(2).map((p) => p.trim()).filter(Boolean);
|
||||
if (cliPaths.length > 0) return cliPaths;
|
||||
|
||||
const envPaths = process.env.TEST_PATHS?.split(path.delimiter).map((p) => p.trim()).filter(Boolean);
|
||||
if (envPaths?.length) return envPaths;
|
||||
|
||||
return [process.cwd()];
|
||||
}
|
||||
|
||||
for (const p of getTestPaths()) {
|
||||
test(path.resolve(p));
|
||||
}
|
||||
@@ -1,9 +1,8 @@
|
||||
# AGENTS.md
|
||||
# CLAUDE.md
|
||||
|
||||
## Task Completion Requirements
|
||||
|
||||
- Both `bun lint` and `bun typecheck` must pass before considering tasks completed.
|
||||
- NEVER run `bun test`. Always use `bun run test` (runs Vitest).
|
||||
|
||||
## Project Snapshot
|
||||
|
||||
|
||||
@@ -0,0 +1,582 @@
|
||||
# Orchestration Interface Spec (Required State)
|
||||
|
||||
Status: Required target architecture (not a description of current behavior).
|
||||
|
||||
## 1. Identifier Schema (Branded)
|
||||
|
||||
All identifiers are branded and never plain `string` in schema definitions.
|
||||
|
||||
```ts
|
||||
const ThreadId = Schema.String.pipe(Schema.brand("ThreadId"));
|
||||
const ProjectId = Schema.String.pipe(Schema.brand("ProjectId"));
|
||||
const CommandId = Schema.String.pipe(Schema.brand("CommandId"));
|
||||
const EventId = Schema.String.pipe(Schema.brand("EventId"));
|
||||
const MessageId = Schema.String.pipe(Schema.brand("MessageId"));
|
||||
const TurnId = Schema.String.pipe(Schema.brand("TurnId"));
|
||||
|
||||
const ProviderSessionId = Schema.String.pipe(Schema.brand("ProviderSessionId"));
|
||||
const ProviderThreadId = Schema.String.pipe(Schema.brand("ProviderThreadId"));
|
||||
const ProviderTurnId = Schema.String.pipe(Schema.brand("ProviderTurnId"));
|
||||
const ProviderItemId = Schema.String.pipe(Schema.brand("ProviderItemId"));
|
||||
const ApprovalRequestId = Schema.String.pipe(Schema.brand("ApprovalRequestId"));
|
||||
|
||||
const CheckpointRef = Schema.String.pipe(Schema.brand("CheckpointRef"));
|
||||
```
|
||||
|
||||
Rules:
|
||||
|
||||
- `ThreadId` is app/orchestration thread identity.
|
||||
- `ProviderThreadId` is provider runtime thread identity.
|
||||
- They are never assigned to each other.
|
||||
- `ProviderSessionId` is internal server/provider routing identity; clients do not send it.
|
||||
- use e.g. `ThreadId.make(randomUUID())` to create new entity ids at the source (e.g. client create thread id and send to server, provider adapter creates the provider thread id from the codex app server etc)
|
||||
|
||||
## 2. Client Commands (Domain Commands)
|
||||
|
||||
All commands are sent through one RPC: `orchestration.dispatchCommand`.
|
||||
|
||||
Output for every command: `DispatchResultSchema = { sequence: number }`.
|
||||
|
||||
### 2.1 Client-Dispatchable Commands
|
||||
|
||||
1. `project.create`
|
||||
|
||||
- Input:
|
||||
- `commandId: CommandId`
|
||||
- `projectId: ProjectId`
|
||||
- `title: string`
|
||||
- `workspaceRoot: string`
|
||||
- `defaultModel?: string`
|
||||
- `createdAt: IsoDateTime`
|
||||
- Output: `DispatchResult`
|
||||
|
||||
2. `project.meta.update`
|
||||
|
||||
- Input:
|
||||
- `commandId: CommandId`
|
||||
- `projectId: ProjectId`
|
||||
- optional `{ title, workspaceRoot, defaultModel, scripts }`
|
||||
- Output: `DispatchResult`
|
||||
|
||||
3. `project.delete`
|
||||
|
||||
- Input: `commandId`, `projectId`
|
||||
- Output: `DispatchResult`
|
||||
|
||||
4. `thread.create`
|
||||
|
||||
- Input:
|
||||
- `commandId: CommandId`
|
||||
- `threadId: ThreadId`
|
||||
- `projectId: ProjectId`
|
||||
- `title: string`
|
||||
- `model: string`
|
||||
- `branch: string | null`
|
||||
- `worktreePath: string | null`
|
||||
- `createdAt: IsoDateTime`
|
||||
- Output: `DispatchResult`
|
||||
|
||||
5. `thread.delete`
|
||||
|
||||
- Input: `commandId`, `threadId`
|
||||
- Output: `DispatchResult`
|
||||
|
||||
6. `thread.meta.update`
|
||||
|
||||
- Input: `commandId`, `threadId`, optional `{ title, model, branch, worktreePath }`
|
||||
- Output: `DispatchResult`
|
||||
|
||||
7. `thread.turn.start`
|
||||
|
||||
- Input:
|
||||
- `commandId`
|
||||
- `threadId`
|
||||
- `message`:
|
||||
- `messageId: MessageId`
|
||||
- `role: "user"`
|
||||
- `text: string`
|
||||
- `attachments: ChatAttachment[]` (schema-shared)
|
||||
- `model?: string`
|
||||
- `effort?: string`
|
||||
- `createdAt`
|
||||
- Output: `DispatchResult`
|
||||
|
||||
8. `thread.turn.interrupt`
|
||||
|
||||
- Input: `commandId`, `threadId`, optional `turnId: TurnId`, `createdAt`
|
||||
- Output: `DispatchResult`
|
||||
|
||||
9. `thread.approval.respond`
|
||||
|
||||
- Input:
|
||||
- `commandId`
|
||||
- `threadId`
|
||||
- `requestId: ApprovalRequestId`
|
||||
- `decision: "accept" | "acceptForSession" | "decline" | "cancel"`
|
||||
- `createdAt`
|
||||
- Output: `DispatchResult`
|
||||
|
||||
10. `thread.checkpoint.revert`
|
||||
|
||||
- Input: `commandId`, `threadId`, `turnCount: number`, `createdAt`
|
||||
- Output: `DispatchResult`
|
||||
|
||||
11. `thread.session.stop`
|
||||
|
||||
- Input: `commandId`, `threadId`, `createdAt`
|
||||
- Output: `DispatchResult`
|
||||
|
||||
### 2.2 Internal-Only Commands (Not Client Dispatchable)
|
||||
|
||||
1. `thread.session.set`
|
||||
|
||||
- Server-owned projection update for session lifecycle.
|
||||
|
||||
2. `thread.message.assistant.delta`
|
||||
|
||||
- Server-owned incremental assistant content append.
|
||||
|
||||
3. `thread.message.assistant.complete`
|
||||
|
||||
- Server-owned assistant message completion marker.
|
||||
|
||||
4. `thread.turn.diff.complete`
|
||||
|
||||
- Server-owned checkpoint diff summary write.
|
||||
|
||||
5. `thread.activity.append`
|
||||
|
||||
- Server-owned activity feed append.
|
||||
|
||||
## 3. Client RPC (Required)
|
||||
|
||||
These are the required client-facing RPC methods.
|
||||
|
||||
1. `orchestration.getSnapshot`
|
||||
|
||||
- Input: `{}`
|
||||
- Output: `OrchestrationReadModel`
|
||||
|
||||
2. `orchestration.dispatchCommand`
|
||||
|
||||
- Input: `ClientOrchestrationCommand` (`Schema.Union` of all client-dispatchable commands)
|
||||
- Output: `DispatchResult`
|
||||
|
||||
3. `orchestration.getTurnDiff`
|
||||
|
||||
- Input:
|
||||
- `threadId: ThreadId`
|
||||
- `fromTurnCount: number`
|
||||
- `toTurnCount: number`
|
||||
- Output:
|
||||
- `threadId: ThreadId`
|
||||
- `fromTurnCount: number`
|
||||
- `toTurnCount: number`
|
||||
- `diff: string`
|
||||
|
||||
4. `orchestration.replayEvents` (optional operational/debug API)
|
||||
|
||||
- Input: `{ fromSequenceExclusive: number }`
|
||||
- Output: `OrchestrationEvent[]`
|
||||
|
||||
### 3.1 RPC To Remove
|
||||
|
||||
Remove from client boundary:
|
||||
|
||||
- `providers.startSession`
|
||||
- `providers.sendTurn`
|
||||
- `providers.interruptTurn`
|
||||
- `providers.respondToRequest`
|
||||
- `providers.stopSession`
|
||||
- `providers.listCheckpoints`
|
||||
- `providers.getCheckpointDiff`
|
||||
- `providers.revertToCheckpoint`
|
||||
|
||||
Rationale:
|
||||
|
||||
- Session/turn/checkpoint control belongs to orchestrator command path.
|
||||
- Snapshot already includes checkpoint summaries (`checkpoints`); only full textual diff needs explicit query RPC.
|
||||
|
||||
## 4. Server Orchestrator Command <-> Event Schemas
|
||||
|
||||
Each command deterministically yields one or more domain events that are persisted to the event store.
|
||||
|
||||
1. `project.create` -> `project.created`
|
||||
2. `project.meta.update` -> `project.meta-updated`
|
||||
3. `project.delete` -> `project.deleted`
|
||||
4. `thread.create` -> `thread.created`
|
||||
5. `thread.delete` -> `thread.deleted`
|
||||
6. `thread.meta.update` -> `thread.meta-updated`
|
||||
7. `thread.turn.start` ->
|
||||
|
||||
- `thread.message-sent` (user message append)
|
||||
- `thread.turn-start-requested`
|
||||
- then (async side effect success) `thread.session-set` + provider-driven message/turn events
|
||||
|
||||
8. `thread.turn.interrupt` -> `thread.turn-interrupt-requested`
|
||||
9. `thread.approval.respond` -> `thread.approval-response-requested`
|
||||
10. `thread.checkpoint.revert` -> `thread.checkpoint-revert-requested` then `thread.reverted`
|
||||
11. `thread.session.stop` -> `thread.session-stop-requested` then `thread.session-set`
|
||||
|
||||
Internal command/event path:
|
||||
|
||||
- `thread.session.set` -> `thread.session-set`
|
||||
- `thread.message.assistant.delta` -> `thread.message-sent` (assistant streaming)
|
||||
- `thread.message.assistant.complete` -> `thread.message-sent` (streaming false)
|
||||
- `thread.turn.diff.complete` -> `thread.turn-diff-completed`
|
||||
- `thread.activity.append` -> `thread.activity-appended`
|
||||
|
||||
## 5. Orchestration Events <-> Generic Provider Events <-> Raw Provider Events
|
||||
|
||||
Required mapping pipeline:
|
||||
|
||||
`Raw Provider Event (adapter-specific)`
|
||||
-> `GenericProviderRuntimeEvent` (provider-agnostic schema)
|
||||
-> `Internal Orchestration Command`
|
||||
-> `Orchestration Domain Event`
|
||||
|
||||
### 5.1 Mapping Table for Codex Adapter
|
||||
|
||||
1. Raw `thread/started`
|
||||
|
||||
- Generic: `thread.started`
|
||||
- Internal command: `thread.session.set` (attach `ProviderThreadId`, status `ready|running`)
|
||||
- Domain event: `thread.session-set`
|
||||
|
||||
2. Raw `turn/started`
|
||||
|
||||
- Generic: `turn.started`
|
||||
- Internal command: `thread.session.set` (status `running`, active turn)
|
||||
- Domain event: `thread.session-set`
|
||||
|
||||
3. Raw `item/agentMessage/delta`
|
||||
|
||||
- Generic: `message.delta`
|
||||
- Internal command: `thread.message.assistant.delta`
|
||||
- Domain event: `thread.message-sent` (assistant, streaming)
|
||||
|
||||
4. Raw `item/completed` (agent message)
|
||||
|
||||
- Generic: `message.completed`
|
||||
- Internal command: `thread.message.assistant.complete`
|
||||
- Domain event: `thread.message-sent` (assistant, completed)
|
||||
|
||||
5. Raw `turn/completed`
|
||||
|
||||
- Generic: `turn.completed`
|
||||
- Internal commands:
|
||||
- `thread.session.set` (ready/error)
|
||||
- `thread.activity.append` (optional summary)
|
||||
- Domain events: `thread.session-set`, `thread.activity-appended`
|
||||
|
||||
6. Raw approval request
|
||||
|
||||
- Generic: `approval.requested`
|
||||
- Internal command: `thread.activity.append` (typed `requestId`, `requestKind`)
|
||||
- Domain event: `thread.activity-appended`
|
||||
|
||||
7. Raw approval decision ack
|
||||
|
||||
- Generic: `approval.resolved`
|
||||
- Internal command: `thread.activity.append`
|
||||
- Domain event: `thread.activity-appended`
|
||||
|
||||
8. Raw tool start/complete
|
||||
|
||||
- Generic: `tool.started` / `tool.completed`
|
||||
- Internal command: `thread.activity.append`
|
||||
- Domain event: `thread.activity-appended`
|
||||
|
||||
9. Checkpoint capture (server-produced)
|
||||
|
||||
- Generic: `checkpoint.captured`
|
||||
- Internal command: `thread.turn.diff.complete`
|
||||
- Domain event: `thread.turn-diff-completed`
|
||||
|
||||
10. Raw/runtime error
|
||||
|
||||
- Generic: `runtime.error`
|
||||
- Internal commands:
|
||||
- `thread.session.set` (status `error`)
|
||||
- `thread.activity.append` (`tone=error`)
|
||||
- Domain events: `thread.session-set`, `thread.activity-appended`
|
||||
|
||||
## 6. Schema Section (Boundary + Reuse)
|
||||
|
||||
### 6.1 Shared Schemas (contracts package)
|
||||
|
||||
Expose to both web and server:
|
||||
|
||||
- `OrchestrationReadModelSchema`
|
||||
- `ClientOrchestrationCommandSchema`
|
||||
- `OrchestrationEventSchema`
|
||||
- `OrchestrationRpcSchemas` (`getSnapshot`, `dispatchCommand`, `getTurnDiff`, optional replay)
|
||||
- `GenericProviderRuntimeEventSchema` (used for diagnostics/ingestion tests)
|
||||
- Shared message/activity/checkpoint summary schemas used in snapshot
|
||||
|
||||
### 6.2 Server-Internal Schemas
|
||||
|
||||
Not exposed to web:
|
||||
|
||||
- `InternalOrchestrationCommandSchema`
|
||||
- Adapter raw-event schemas and provider-specific payload schemas
|
||||
- Provider session directory records and persistence-only row schemas
|
||||
- Git service cache/query schemas (non-orchestration read model)
|
||||
|
||||
### 6.3 Reuse Requirements
|
||||
|
||||
- Snapshot checkpoint summary schema is source of truth for checkpoint list UI.
|
||||
- `getTurnDiff` response reuses `ThreadId`/turn count brands and textual `diff` only.
|
||||
- Activity schemas are reused for approval/tool/runtime annotations; no separate UI-only structure.
|
||||
- Session schema must include both `threadId: ThreadId` and optional `providerThreadId: ProviderThreadId` (explicitly distinct).
|
||||
|
||||
## 7. Persistence Model (Required)
|
||||
|
||||
This section defines required persisted tables, the canonical persisted event envelope, and required projected/read tables.
|
||||
|
||||
### 7.1 Write-Side Persisted Tables
|
||||
|
||||
1. `orchestration_events` (append-only event store)
|
||||
|
||||
- `sequence: number` (global monotonic sequence, primary key)
|
||||
- `eventId: EventId` (unique)
|
||||
- `aggregateKind: "project" | "thread"`
|
||||
- `streamId: ProjectId | ThreadId` (aggregate stream id)
|
||||
- `streamVersion: number` (per-aggregate monotonic version)
|
||||
- `eventType: OrchestrationEventType`
|
||||
- `occurredAt: IsoDateTime`
|
||||
- `commandId: CommandId | null`
|
||||
- `causationEventId: EventId | null`
|
||||
- `correlationId: CommandId | null`
|
||||
- `actorKind: "client" | "server" | "provider"`
|
||||
- `payload: OrchestrationEventPayload` (type-validated by `eventType`)
|
||||
- `metadata: OrchestrationEventMetadata`
|
||||
|
||||
2. `orchestration_command_receipts` (idempotency + ack replay)
|
||||
|
||||
- `commandId: CommandId` (primary key)
|
||||
- `aggregateKind: "project" | "thread"`
|
||||
- `aggregateId: ProjectId | ThreadId`
|
||||
- `acceptedAt: IsoDateTime`
|
||||
- `resultSequence: number`
|
||||
- `status: "accepted" | "rejected"`
|
||||
- `error: string | null`
|
||||
|
||||
3. `checkpoint_diff_blobs` (large plaintext diffs; separate from summaries)
|
||||
|
||||
- `threadId: ThreadId`
|
||||
- `fromTurnCount: number`
|
||||
- `toTurnCount: number`
|
||||
- `diff: string`
|
||||
- `createdAt: IsoDateTime`
|
||||
- unique key: `(threadId, fromTurnCount, toTurnCount)`
|
||||
|
||||
4. `provider_session_runtime` (server-internal adapter resume state)
|
||||
|
||||
- `providerSessionId: ProviderSessionId` (primary key)
|
||||
- `threadId: ThreadId`
|
||||
- `providerName: string`
|
||||
- `adapterKey: string`
|
||||
- `providerThreadId: ProviderThreadId | null`
|
||||
- `status: "starting" | "running" | "stopped" | "error"`
|
||||
- `lastSeenAt: IsoDateTime`
|
||||
- `resumeCursor: JsonValue | null` (adapter-specific opaque state)
|
||||
- `runtimePayload: JsonValue | null` (adapter-specific opaque state)
|
||||
|
||||
### 7.2 Canonical Persisted Event Schema
|
||||
|
||||
`OrchestrationPersistedEventSchema` (full envelope):
|
||||
|
||||
```ts
|
||||
type OrchestrationPersistedEvent = {
|
||||
sequence: number;
|
||||
eventId: EventId;
|
||||
aggregateKind: "project" | "thread";
|
||||
streamId: ProjectId | ThreadId;
|
||||
streamVersion: number;
|
||||
eventType: OrchestrationEventType;
|
||||
occurredAt: IsoDateTime;
|
||||
commandId: CommandId | null;
|
||||
causationEventId: EventId | null;
|
||||
correlationId: CommandId | null;
|
||||
actorKind: "client" | "server" | "provider";
|
||||
payload: OrchestrationEventPayload;
|
||||
metadata: {
|
||||
providerSessionId?: ProviderSessionId;
|
||||
providerThreadId?: ProviderThreadId;
|
||||
providerTurnId?: ProviderTurnId;
|
||||
providerItemId?: ProviderItemId;
|
||||
adapterKey?: string;
|
||||
requestId?: ApprovalRequestId;
|
||||
ingestedAt?: IsoDateTime;
|
||||
};
|
||||
};
|
||||
```
|
||||
|
||||
Rules:
|
||||
|
||||
- `payload` must be schema-discriminated by `eventType`.
|
||||
- provider identifiers only appear in `metadata` and provider-specific payload sub-shapes; they do not replace `ThreadId`.
|
||||
- `streamVersion` is concurrency guard for aggregate writes.
|
||||
|
||||
### 7.3 Required Projected Tables (Read Models)
|
||||
|
||||
1. `projection_projects`
|
||||
|
||||
- `projectId: ProjectId` (primary key)
|
||||
- `title: string`
|
||||
- `workspaceRoot: string`
|
||||
- `defaultModel: string | null`
|
||||
- `scripts: ProjectScript[]`
|
||||
- `createdAt: IsoDateTime`
|
||||
- `updatedAt: IsoDateTime`
|
||||
- `deletedAt: IsoDateTime | null`
|
||||
|
||||
2. `projection_threads`
|
||||
|
||||
- `threadId: ThreadId` (primary key)
|
||||
- `projectId: ProjectId`
|
||||
- `title: string`
|
||||
- `model: string`
|
||||
- `branch: string | null`
|
||||
- `worktreePath: string | null`
|
||||
- `latestTurnId: TurnId | null`
|
||||
- `createdAt: IsoDateTime`
|
||||
- `updatedAt: IsoDateTime`
|
||||
- `deletedAt: IsoDateTime | null`
|
||||
|
||||
3. `projection_thread_messages`
|
||||
|
||||
- `messageId: MessageId` (primary key)
|
||||
- `threadId: ThreadId`
|
||||
- `turnId: TurnId | null`
|
||||
- `role: "user" | "assistant" | "system"`
|
||||
- `text: string`
|
||||
- `isStreaming: boolean`
|
||||
- `createdAt: IsoDateTime`
|
||||
- `updatedAt: IsoDateTime`
|
||||
|
||||
4. `projection_thread_activities`
|
||||
|
||||
- `activityId: EventId` (primary key; derived from source event)
|
||||
- `threadId: ThreadId`
|
||||
- `turnId: TurnId | null`
|
||||
- `tone: "info" | "tool" | "approval" | "error"`
|
||||
- `kind: string`
|
||||
- `summary: string`
|
||||
- `payload: JsonValue`
|
||||
- `createdAt: IsoDateTime`
|
||||
|
||||
5. `projection_thread_sessions`
|
||||
|
||||
- `threadId: ThreadId` (primary key)
|
||||
- `status: "idle" | "starting" | "running" | "ready" | "interrupted" | "stopped" | "error"`
|
||||
- `providerName: string | null`
|
||||
- `providerSessionId: ProviderSessionId | null`
|
||||
- `providerThreadId: ProviderThreadId | null`
|
||||
- `activeTurnId: TurnId | null`
|
||||
- `lastError: string | null`
|
||||
- `updatedAt: IsoDateTime`
|
||||
|
||||
6. `projection_thread_turns`
|
||||
|
||||
- `turnId: TurnId` (primary key)
|
||||
- `threadId: ThreadId`
|
||||
- `turnCount: number`
|
||||
- `status: "running" | "completed" | "interrupted" | "error"`
|
||||
- `userMessageId: MessageId | null`
|
||||
- `assistantMessageId: MessageId | null`
|
||||
- `startedAt: IsoDateTime`
|
||||
- `completedAt: IsoDateTime | null`
|
||||
|
||||
7. `projection_checkpoints`
|
||||
|
||||
- `threadId: ThreadId`
|
||||
- `turnId: TurnId`
|
||||
- `checkpointTurnCount: number`
|
||||
- `checkpointRef: CheckpointRef`
|
||||
- `status: "ready" | "missing" | "error"`
|
||||
- `files: JsonArray` (typed as file diff summary schema)
|
||||
- `assistantMessageId: MessageId | null`
|
||||
- `completedAt: IsoDateTime`
|
||||
- unique key: `(threadId, checkpointTurnCount)`
|
||||
|
||||
8. `projection_pending_approvals`
|
||||
|
||||
- `requestId: ApprovalRequestId` (primary key)
|
||||
- `threadId: ThreadId`
|
||||
- `turnId: TurnId | null`
|
||||
- `status: "pending" | "resolved"`
|
||||
- `decision: "accept" | "acceptForSession" | "decline" | "cancel" | null`
|
||||
- `createdAt: IsoDateTime`
|
||||
- `resolvedAt: IsoDateTime | null`
|
||||
|
||||
9. `projection_state`
|
||||
|
||||
- `projector: string` (primary key; e.g. `threads`, `messages`, `sessions`)
|
||||
- `lastAppliedSequence: number`
|
||||
- `updatedAt: IsoDateTime`
|
||||
|
||||
Projection consistency rules:
|
||||
|
||||
- Every projector applies read-model row updates and `projection_state.lastAppliedSequence` in the same database transaction.
|
||||
- Optional debug field on projection rows: `lastEventSequence: number` (not required for correctness).
|
||||
|
||||
### 7.4 Snapshot and RPC Requirements
|
||||
|
||||
1. `orchestration.getSnapshot` is fully served from projection tables and returns `snapshotSequence: number`.
|
||||
2. Snapshot must include `projects[]` from `projection_projects`.
|
||||
3. Thread snapshot must include `checkpoints[]` from `projection_checkpoints`:
|
||||
|
||||
- `turnId: TurnId`
|
||||
- `completedAt: IsoDateTime`
|
||||
- `status`
|
||||
- `files[]` (`path`, `kind`, `additions`, `deletions`)
|
||||
- `checkpointRef: CheckpointRef`
|
||||
- `assistantMessageId?: MessageId`
|
||||
- `checkpointTurnCount: number`
|
||||
|
||||
4. Client does not require `listCheckpoints` RPC:
|
||||
|
||||
- checkpoint list comes from snapshot projections
|
||||
- full diff text comes from `orchestration.getTurnDiff` backed by `checkpoint_diff_blobs`
|
||||
|
||||
5. Provider session identity is not a client routing key:
|
||||
|
||||
- client acts on `ThreadId`
|
||||
- server resolves provider session internally via `projection_thread_sessions`
|
||||
|
||||
6. `snapshotSequence` is derived from `projection_state`:
|
||||
|
||||
- if snapshot depends on multiple projectors, use the minimum `lastAppliedSequence` across those projectors.
|
||||
|
||||
7. Event subscription handoff contract:
|
||||
|
||||
- client performs `getSnapshot` and reads `snapshotSequence`
|
||||
- client subscribes/replays with `fromSequenceExclusive = snapshotSequence`
|
||||
- server guarantees no gap between snapshot visibility and subsequent event stream from that sequence.
|
||||
|
||||
### 7.5 External Derived State (Non-Orchestration)
|
||||
|
||||
1. Current git/worktree state is not projected from orchestration events.
|
||||
2. If persisted, it belongs in a separate git cache/read model (for example `git_state_cache`) owned by a git service.
|
||||
3. Orchestration may embed git metadata only when captured as a domain fact (for example checkpoint metadata at turn completion).
|
||||
4. Any RPC for current git status should be outside orchestration RPC (for example `git.getThreadState`).
|
||||
|
||||
### 7.6 Existing Repository Placement
|
||||
|
||||
1. `ProjectsRepository`
|
||||
|
||||
- Fits as projection/query access on top of `projection_projects` plus orchestration command dispatch for writes.
|
||||
- Must not bypass command->event append path for mutations.
|
||||
|
||||
2. `CheckpointsRepository`
|
||||
|
||||
- Fits as projection/query access on top of `projection_checkpoints` plus `checkpoint_diff_blobs` (or git-service on-demand diff implementation).
|
||||
- Represents the same concept as prior `turn_diff_summary`; canonical naming is `checkpoint`.
|
||||
- Must not be an independent source of truth outside orchestration events.
|
||||
|
||||
3. `ProviderSessionsRepository`
|
||||
|
||||
- Fits as server-internal runtime persistence on top of `provider_session_runtime`, with domain-visible state projected into `projection_thread_sessions`.
|
||||
- Not part of client RPC/domain aggregate boundary.
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@t3tools/desktop",
|
||||
"version": "0.0.0-alpha.20",
|
||||
"version": "0.0.0-alpha.18",
|
||||
"private": true,
|
||||
"main": "dist-electron/main.js",
|
||||
"scripts": {
|
||||
|
||||
@@ -37,8 +37,6 @@ import { ProviderUnsupportedError } from "../src/provider/Errors.ts";
|
||||
import { ProviderAdapterRegistry } from "../src/provider/Services/ProviderAdapterRegistry.ts";
|
||||
import { ProviderSessionDirectoryLive } from "../src/provider/Layers/ProviderSessionDirectory.ts";
|
||||
import { makeProviderServiceLive } from "../src/provider/Layers/ProviderService.ts";
|
||||
import { makeCodexAdapterLive } from "../src/provider/Layers/CodexAdapter.ts";
|
||||
import { CodexAdapter } from "../src/provider/Services/CodexAdapter.ts";
|
||||
import { ProviderService } from "../src/provider/Services/ProviderService.ts";
|
||||
import { CheckpointReactorLive } from "../src/orchestration/Layers/CheckpointReactor.ts";
|
||||
import { OrchestrationEngineLive } from "../src/orchestration/Layers/OrchestrationEngine.ts";
|
||||
@@ -187,264 +185,229 @@ export interface OrchestrationIntegrationHarness {
|
||||
readonly dispose: Effect.Effect<void, never>;
|
||||
}
|
||||
|
||||
interface MakeOrchestrationIntegrationHarnessOptions {
|
||||
readonly provider?: "codex" | "claudeCode";
|
||||
readonly realCodex?: boolean;
|
||||
}
|
||||
export const makeOrchestrationIntegrationHarness = Effect.gen(function* () {
|
||||
const sleep = (ms: number) => Effect.sleep(ms);
|
||||
const adapterHarness = yield* makeTestProviderAdapterHarness;
|
||||
|
||||
export const makeOrchestrationIntegrationHarness = (
|
||||
options?: MakeOrchestrationIntegrationHarnessOptions,
|
||||
) =>
|
||||
Effect.gen(function* () {
|
||||
const sleep = (ms: number) => Effect.sleep(ms);
|
||||
const provider = options?.provider ?? "codex";
|
||||
const useRealCodex = options?.realCodex === true;
|
||||
const adapterHarness = useRealCodex
|
||||
? null
|
||||
: yield* makeTestProviderAdapterHarness({
|
||||
provider,
|
||||
});
|
||||
const fakeRegistry = adapterHarness
|
||||
? Layer.succeed(ProviderAdapterRegistry, {
|
||||
getByProvider: (resolvedProvider) =>
|
||||
resolvedProvider === adapterHarness.provider
|
||||
? Effect.succeed(adapterHarness.adapter)
|
||||
: Effect.fail(new ProviderUnsupportedError({ provider: resolvedProvider })),
|
||||
listProviders: () => Effect.succeed([adapterHarness.provider]),
|
||||
} as typeof ProviderAdapterRegistry.Service)
|
||||
: null;
|
||||
const rootDir = fs.mkdtempSync(path.join(os.tmpdir(), "t3-orchestration-integration-"));
|
||||
const workspaceDir = path.join(rootDir, "workspace");
|
||||
const stateDir = path.join(rootDir, "state");
|
||||
const dbPath = path.join(stateDir, "state.sqlite");
|
||||
fs.mkdirSync(workspaceDir, { recursive: true });
|
||||
fs.mkdirSync(stateDir, { recursive: true });
|
||||
initializeGitWorkspace(workspaceDir);
|
||||
const rootDir = fs.mkdtempSync(path.join(os.tmpdir(), "t3-orchestration-integration-"));
|
||||
const workspaceDir = path.join(rootDir, "workspace");
|
||||
const stateDir = path.join(rootDir, "state");
|
||||
const dbPath = path.join(stateDir, "state.sqlite");
|
||||
fs.mkdirSync(workspaceDir, { recursive: true });
|
||||
fs.mkdirSync(stateDir, { recursive: true });
|
||||
initializeGitWorkspace(workspaceDir);
|
||||
|
||||
const persistenceLayer = makeSqlitePersistenceLive(dbPath);
|
||||
const orchestrationLayer = OrchestrationEngineLive.pipe(
|
||||
Layer.provide(OrchestrationProjectionPipelineLive),
|
||||
Layer.provide(OrchestrationEventStoreLive),
|
||||
Layer.provide(OrchestrationCommandReceiptRepositoryLive),
|
||||
);
|
||||
const providerSessionDirectoryLayer = ProviderSessionDirectoryLive.pipe(
|
||||
Layer.provide(ProviderSessionRuntimeRepositoryLive),
|
||||
);
|
||||
const realCodexRegistry = Layer.effect(
|
||||
ProviderAdapterRegistry,
|
||||
Effect.gen(function* () {
|
||||
const codexAdapter = yield* CodexAdapter;
|
||||
return {
|
||||
getByProvider: (resolvedProvider) =>
|
||||
resolvedProvider === "codex"
|
||||
? Effect.succeed(codexAdapter)
|
||||
: Effect.fail(new ProviderUnsupportedError({ provider: resolvedProvider })),
|
||||
listProviders: () => Effect.succeed(["codex"] as const),
|
||||
} as typeof ProviderAdapterRegistry.Service;
|
||||
}),
|
||||
).pipe(
|
||||
Layer.provide(makeCodexAdapterLive()),
|
||||
Layer.provideMerge(ServerConfig.layerTest(workspaceDir, stateDir)),
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
Layer.provideMerge(providerSessionDirectoryLayer),
|
||||
);
|
||||
const providerLayer = useRealCodex
|
||||
? makeProviderServiceLive().pipe(
|
||||
Layer.provide(providerSessionDirectoryLayer),
|
||||
Layer.provide(realCodexRegistry),
|
||||
)
|
||||
: makeProviderServiceLive().pipe(
|
||||
Layer.provide(providerSessionDirectoryLayer),
|
||||
Layer.provide(fakeRegistry!),
|
||||
);
|
||||
const registry: typeof ProviderAdapterRegistry.Service = {
|
||||
getByProvider: (provider) =>
|
||||
provider === "codex"
|
||||
? Effect.succeed(adapterHarness.adapter)
|
||||
: Effect.fail(new ProviderUnsupportedError({ provider })),
|
||||
listProviders: () => Effect.succeed(["codex"]),
|
||||
};
|
||||
|
||||
const runtimeServicesLayer = Layer.mergeAll(
|
||||
orchestrationLayer,
|
||||
OrchestrationProjectionSnapshotQueryLive,
|
||||
ProjectionCheckpointRepositoryLive,
|
||||
ProjectionPendingApprovalRepositoryLive,
|
||||
CheckpointStoreLive,
|
||||
providerLayer,
|
||||
);
|
||||
const runtimeIngestionLayer = ProviderRuntimeIngestionLive.pipe(
|
||||
Layer.provideMerge(runtimeServicesLayer),
|
||||
);
|
||||
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: null }),
|
||||
} as unknown as TextGenerationShape);
|
||||
const providerCommandReactorLayer = ProviderCommandReactorLive.pipe(
|
||||
Layer.provideMerge(runtimeServicesLayer),
|
||||
Layer.provideMerge(gitCoreLayer),
|
||||
Layer.provideMerge(textGenerationLayer),
|
||||
);
|
||||
const checkpointReactorLayer = CheckpointReactorLive.pipe(
|
||||
Layer.provideMerge(runtimeServicesLayer),
|
||||
);
|
||||
const orchestrationReactorLayer = OrchestrationReactorLive.pipe(
|
||||
Layer.provideMerge(runtimeIngestionLayer),
|
||||
Layer.provideMerge(providerCommandReactorLayer),
|
||||
Layer.provideMerge(checkpointReactorLayer),
|
||||
);
|
||||
const layer = orchestrationReactorLayer.pipe(
|
||||
Layer.provide(persistenceLayer),
|
||||
Layer.provideMerge(ServerConfig.layerTest(workspaceDir, stateDir)),
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
);
|
||||
const persistenceLayer = makeSqlitePersistenceLive(dbPath);
|
||||
const orchestrationLayer = OrchestrationEngineLive.pipe(
|
||||
Layer.provide(OrchestrationProjectionPipelineLive),
|
||||
Layer.provide(OrchestrationEventStoreLive),
|
||||
Layer.provide(OrchestrationCommandReceiptRepositoryLive),
|
||||
);
|
||||
const providerSessionDirectoryLayer = ProviderSessionDirectoryLive.pipe(
|
||||
Layer.provide(ProviderSessionRuntimeRepositoryLive),
|
||||
);
|
||||
const providerLayer = makeProviderServiceLive().pipe(
|
||||
Layer.provide(providerSessionDirectoryLayer),
|
||||
Layer.provide(Layer.succeed(ProviderAdapterRegistry, registry)),
|
||||
);
|
||||
|
||||
const runtime = ManagedRuntime.make(layer);
|
||||
const engine = yield* tryRuntimePromise("load OrchestrationEngine service", () =>
|
||||
runtime.runPromise(Effect.service(OrchestrationEngineService)),
|
||||
).pipe(Effect.orDie);
|
||||
const reactor = yield* tryRuntimePromise("load OrchestrationReactor service", () =>
|
||||
runtime.runPromise(Effect.service(OrchestrationReactor)),
|
||||
).pipe(Effect.orDie);
|
||||
const snapshotQuery = yield* tryRuntimePromise("load ProjectionSnapshotQuery service", () =>
|
||||
runtime.runPromise(Effect.service(ProjectionSnapshotQuery)),
|
||||
).pipe(Effect.orDie);
|
||||
const providerService = yield* tryRuntimePromise("load ProviderService service", () =>
|
||||
runtime.runPromise(Effect.service(ProviderService)),
|
||||
).pipe(Effect.orDie);
|
||||
const checkpointStore = yield* tryRuntimePromise("load CheckpointStore service", () =>
|
||||
runtime.runPromise(Effect.service(CheckpointStore)),
|
||||
).pipe(Effect.orDie);
|
||||
const checkpointRepository = yield* tryRuntimePromise(
|
||||
"load ProjectionCheckpointRepository service",
|
||||
() => runtime.runPromise(Effect.service(ProjectionCheckpointRepository)),
|
||||
).pipe(Effect.orDie);
|
||||
const pendingApprovalRepository = yield* tryRuntimePromise(
|
||||
"load ProjectionPendingApprovalRepository service",
|
||||
() => runtime.runPromise(Effect.service(ProjectionPendingApprovalRepository)),
|
||||
).pipe(Effect.orDie);
|
||||
const runtimeServicesLayer = Layer.mergeAll(
|
||||
orchestrationLayer,
|
||||
OrchestrationProjectionSnapshotQueryLive,
|
||||
ProjectionCheckpointRepositoryLive,
|
||||
ProjectionPendingApprovalRepositoryLive,
|
||||
CheckpointStoreLive,
|
||||
providerLayer,
|
||||
);
|
||||
const runtimeIngestionLayer = ProviderRuntimeIngestionLive.pipe(
|
||||
Layer.provideMerge(runtimeServicesLayer),
|
||||
);
|
||||
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: null }),
|
||||
} as unknown as TextGenerationShape);
|
||||
const providerCommandReactorLayer = ProviderCommandReactorLive.pipe(
|
||||
Layer.provideMerge(runtimeServicesLayer),
|
||||
Layer.provideMerge(gitCoreLayer),
|
||||
Layer.provideMerge(textGenerationLayer),
|
||||
);
|
||||
const checkpointReactorLayer = CheckpointReactorLive.pipe(
|
||||
Layer.provideMerge(runtimeServicesLayer),
|
||||
);
|
||||
const orchestrationReactorLayer = OrchestrationReactorLive.pipe(
|
||||
Layer.provideMerge(runtimeIngestionLayer),
|
||||
Layer.provideMerge(providerCommandReactorLayer),
|
||||
Layer.provideMerge(checkpointReactorLayer),
|
||||
);
|
||||
const layer = orchestrationReactorLayer.pipe(
|
||||
Layer.provide(persistenceLayer),
|
||||
Layer.provideMerge(ServerConfig.layerTest(workspaceDir, stateDir)),
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
);
|
||||
|
||||
const scope = yield* Scope.make("sequential");
|
||||
yield* tryRuntimePromise("start OrchestrationReactor", () =>
|
||||
runtime.runPromise(reactor.start.pipe(Scope.provide(scope))),
|
||||
).pipe(Effect.orDie);
|
||||
yield* sleep(10);
|
||||
const runtime = ManagedRuntime.make(layer);
|
||||
const engine = yield* tryRuntimePromise("load OrchestrationEngine service", () =>
|
||||
runtime.runPromise(Effect.service(OrchestrationEngineService)),
|
||||
).pipe(Effect.orDie);
|
||||
const reactor = yield* tryRuntimePromise("load OrchestrationReactor service", () =>
|
||||
runtime.runPromise(Effect.service(OrchestrationReactor)),
|
||||
).pipe(Effect.orDie);
|
||||
const snapshotQuery = yield* tryRuntimePromise("load ProjectionSnapshotQuery service", () =>
|
||||
runtime.runPromise(Effect.service(ProjectionSnapshotQuery)),
|
||||
).pipe(Effect.orDie);
|
||||
const providerService = yield* tryRuntimePromise("load ProviderService service", () =>
|
||||
runtime.runPromise(Effect.service(ProviderService)),
|
||||
).pipe(Effect.orDie);
|
||||
const checkpointStore = yield* tryRuntimePromise("load CheckpointStore service", () =>
|
||||
runtime.runPromise(Effect.service(CheckpointStore)),
|
||||
).pipe(Effect.orDie);
|
||||
const checkpointRepository = yield* tryRuntimePromise(
|
||||
"load ProjectionCheckpointRepository service",
|
||||
() => runtime.runPromise(Effect.service(ProjectionCheckpointRepository)),
|
||||
).pipe(Effect.orDie);
|
||||
const pendingApprovalRepository = yield* tryRuntimePromise(
|
||||
"load ProjectionPendingApprovalRepository service",
|
||||
() => runtime.runPromise(Effect.service(ProjectionPendingApprovalRepository)),
|
||||
).pipe(Effect.orDie);
|
||||
|
||||
const waitForThread: OrchestrationIntegrationHarness["waitForThread"] = (
|
||||
threadId,
|
||||
predicate,
|
||||
timeoutMs,
|
||||
) =>
|
||||
waitFor(
|
||||
snapshotQuery
|
||||
.getSnapshot()
|
||||
.pipe(
|
||||
Effect.map(
|
||||
(snapshot) => snapshot.threads.find((thread) => thread.id === threadId) ?? null,
|
||||
),
|
||||
const scope = yield* Scope.make("sequential");
|
||||
yield* tryRuntimePromise("start OrchestrationReactor", () =>
|
||||
runtime.runPromise(reactor.start.pipe(Scope.provide(scope))),
|
||||
).pipe(Effect.orDie);
|
||||
yield* sleep(10);
|
||||
|
||||
const waitForThread: OrchestrationIntegrationHarness["waitForThread"] = (
|
||||
threadId,
|
||||
predicate,
|
||||
timeoutMs,
|
||||
) =>
|
||||
waitFor(
|
||||
snapshotQuery
|
||||
.getSnapshot()
|
||||
.pipe(
|
||||
Effect.map(
|
||||
(snapshot) => snapshot.threads.find((thread) => thread.id === threadId) ?? null,
|
||||
),
|
||||
(thread): thread is OrchestrationThread => thread !== null && predicate(thread),
|
||||
`projected thread '${threadId}'`,
|
||||
timeoutMs,
|
||||
) as Effect.Effect<OrchestrationThread, never>;
|
||||
|
||||
const waitForDomainEvent: OrchestrationIntegrationHarness["waitForDomainEvent"] = (
|
||||
predicate,
|
||||
timeoutMs,
|
||||
) =>
|
||||
waitFor(
|
||||
Stream.runCollect(engine.readEvents(0)).pipe(
|
||||
Effect.map((chunk): ReadonlyArray<OrchestrationEvent> => Array.from(chunk)),
|
||||
),
|
||||
(events) => events.some(predicate),
|
||||
"domain event",
|
||||
timeoutMs,
|
||||
);
|
||||
|
||||
const waitForPendingApproval: OrchestrationIntegrationHarness["waitForPendingApproval"] = (
|
||||
requestId,
|
||||
predicate,
|
||||
(thread): thread is OrchestrationThread => thread !== null && predicate(thread),
|
||||
`projected thread '${threadId}'`,
|
||||
timeoutMs,
|
||||
) =>
|
||||
waitFor(
|
||||
pendingApprovalRepository
|
||||
.getByRequestId({ requestId: ApprovalRequestId.makeUnsafe(requestId) })
|
||||
.pipe(
|
||||
Effect.map((row) =>
|
||||
Option.match(row, {
|
||||
onNone: () => null,
|
||||
onSome: (value) => ({
|
||||
status: value.status,
|
||||
decision: value.decision,
|
||||
resolvedAt: value.resolvedAt,
|
||||
}),
|
||||
) as Effect.Effect<OrchestrationThread, never>;
|
||||
|
||||
const waitForDomainEvent: OrchestrationIntegrationHarness["waitForDomainEvent"] = (
|
||||
predicate,
|
||||
timeoutMs,
|
||||
) =>
|
||||
waitFor(
|
||||
Stream.runCollect(engine.readEvents(0)).pipe(
|
||||
Effect.map((chunk): ReadonlyArray<OrchestrationEvent> => Array.from(chunk)),
|
||||
),
|
||||
(events) => events.some(predicate),
|
||||
"domain event",
|
||||
timeoutMs,
|
||||
);
|
||||
|
||||
const waitForPendingApproval: OrchestrationIntegrationHarness["waitForPendingApproval"] = (
|
||||
requestId,
|
||||
predicate,
|
||||
timeoutMs,
|
||||
) =>
|
||||
waitFor(
|
||||
pendingApprovalRepository
|
||||
.getByRequestId({ requestId: ApprovalRequestId.makeUnsafe(requestId) })
|
||||
.pipe(
|
||||
Effect.map((row) =>
|
||||
Option.match(row, {
|
||||
onNone: () => null,
|
||||
onSome: (value) => ({
|
||||
status: value.status,
|
||||
decision: value.decision,
|
||||
resolvedAt: value.resolvedAt,
|
||||
}),
|
||||
),
|
||||
}),
|
||||
),
|
||||
(
|
||||
row,
|
||||
): row is {
|
||||
readonly status: "pending" | "resolved";
|
||||
readonly decision: "accept" | "acceptForSession" | "decline" | "cancel" | null;
|
||||
readonly resolvedAt: string | null;
|
||||
} => row !== null && predicate(row),
|
||||
`pending approval '${requestId}'`,
|
||||
timeoutMs,
|
||||
) as Effect.Effect<
|
||||
{
|
||||
readonly status: "pending" | "resolved";
|
||||
readonly decision: "accept" | "acceptForSession" | "decline" | "cancel" | null;
|
||||
readonly resolvedAt: string | null;
|
||||
},
|
||||
never
|
||||
>;
|
||||
|
||||
let disposed = false;
|
||||
const dispose = Effect.gen(function* () {
|
||||
if (disposed) {
|
||||
return;
|
||||
}
|
||||
disposed = true;
|
||||
|
||||
const shutdown = Effect.gen(function* () {
|
||||
const stopAllExit = yield* Effect.exit(
|
||||
Effect.promise(() => runtime.runPromise(providerService.stopAll())),
|
||||
);
|
||||
const closeScopeExit = yield* Effect.exit(Scope.close(scope, Exit.void));
|
||||
const disposeRuntimeExit = yield* Effect.exit(Effect.promise(() => runtime.dispose()));
|
||||
|
||||
const failureCause = Exit.isFailure(stopAllExit)
|
||||
? stopAllExit.cause
|
||||
: Exit.isFailure(closeScopeExit)
|
||||
? closeScopeExit.cause
|
||||
: Exit.isFailure(disposeRuntimeExit)
|
||||
? disposeRuntimeExit.cause
|
||||
: null;
|
||||
|
||||
if (failureCause) {
|
||||
return yield* Effect.failCause(failureCause);
|
||||
}
|
||||
});
|
||||
|
||||
yield* shutdown.pipe(
|
||||
Effect.ensuring(
|
||||
Effect.sync(() => {
|
||||
fs.rmSync(rootDir, { recursive: true, force: true });
|
||||
}),
|
||||
),
|
||||
(
|
||||
row,
|
||||
): row is {
|
||||
readonly status: "pending" | "resolved";
|
||||
readonly decision: "accept" | "acceptForSession" | "decline" | "cancel" | null;
|
||||
readonly resolvedAt: string | null;
|
||||
} => row !== null && predicate(row),
|
||||
`pending approval '${requestId}'`,
|
||||
timeoutMs,
|
||||
) as Effect.Effect<
|
||||
{
|
||||
readonly status: "pending" | "resolved";
|
||||
readonly decision: "accept" | "acceptForSession" | "decline" | "cancel" | null;
|
||||
readonly resolvedAt: string | null;
|
||||
},
|
||||
never
|
||||
>;
|
||||
|
||||
let disposed = false;
|
||||
const dispose = Effect.gen(function* () {
|
||||
if (disposed) {
|
||||
return;
|
||||
}
|
||||
disposed = true;
|
||||
|
||||
const shutdown = Effect.gen(function* () {
|
||||
const stopAllExit = yield* Effect.exit(
|
||||
Effect.promise(() => runtime.runPromise(providerService.stopAll())),
|
||||
);
|
||||
const closeScopeExit = yield* Effect.exit(
|
||||
Effect.promise(() => Effect.runPromise(Scope.close(scope, Exit.void))),
|
||||
);
|
||||
const disposeRuntimeExit = yield* Effect.exit(Effect.promise(() => runtime.dispose()));
|
||||
|
||||
const failureCause = Exit.isFailure(stopAllExit)
|
||||
? stopAllExit.cause
|
||||
: Exit.isFailure(closeScopeExit)
|
||||
? closeScopeExit.cause
|
||||
: Exit.isFailure(disposeRuntimeExit)
|
||||
? disposeRuntimeExit.cause
|
||||
: null;
|
||||
|
||||
if (failureCause) {
|
||||
return yield* Effect.failCause(failureCause);
|
||||
}
|
||||
});
|
||||
|
||||
return {
|
||||
rootDir,
|
||||
workspaceDir,
|
||||
dbPath,
|
||||
adapterHarness: adapterHarness as TestProviderAdapterHarness,
|
||||
engine,
|
||||
snapshotQuery,
|
||||
providerService,
|
||||
checkpointStore,
|
||||
checkpointRepository,
|
||||
pendingApprovalRepository,
|
||||
waitForThread,
|
||||
waitForDomainEvent,
|
||||
waitForPendingApproval,
|
||||
dispose,
|
||||
} satisfies OrchestrationIntegrationHarness;
|
||||
yield* shutdown.pipe(
|
||||
Effect.ensuring(
|
||||
Effect.sync(() => {
|
||||
fs.rmSync(rootDir, { recursive: true, force: true });
|
||||
}),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
return {
|
||||
rootDir,
|
||||
workspaceDir,
|
||||
dbPath,
|
||||
adapterHarness,
|
||||
engine,
|
||||
snapshotQuery,
|
||||
providerService,
|
||||
checkpointStore,
|
||||
checkpointRepository,
|
||||
pendingApprovalRepository,
|
||||
waitForThread,
|
||||
waitForDomainEvent,
|
||||
waitForPendingApproval,
|
||||
dispose,
|
||||
} satisfies OrchestrationIntegrationHarness;
|
||||
});
|
||||
@@ -5,11 +5,11 @@ import {
|
||||
EventId,
|
||||
ProviderApprovalDecision,
|
||||
ProviderRuntimeEvent,
|
||||
RuntimeSessionId,
|
||||
ProviderSession,
|
||||
ProviderSessionId,
|
||||
ProviderThreadId,
|
||||
ProviderTurnId,
|
||||
ProviderTurnStartResult,
|
||||
ThreadId,
|
||||
TurnId,
|
||||
} from "@t3tools/contracts";
|
||||
import { Effect, Queue, Stream } from "effect";
|
||||
|
||||
@@ -25,29 +25,13 @@ import type {
|
||||
} from "../src/provider/Services/ProviderAdapter.ts";
|
||||
|
||||
export interface TestTurnResponse {
|
||||
readonly events: ReadonlyArray<FixtureProviderRuntimeEvent>;
|
||||
readonly events: ReadonlyArray<ProviderRuntimeEvent>;
|
||||
readonly mutateWorkspace?: (input: {
|
||||
readonly cwd: string;
|
||||
readonly turnCount: number;
|
||||
}) => Effect.Effect<void, never>;
|
||||
}
|
||||
|
||||
export type FixtureProviderRuntimeEvent = {
|
||||
readonly type: string;
|
||||
readonly eventId: EventId;
|
||||
readonly provider: "codex" | "claudeCode" | "cursor";
|
||||
readonly createdAt: string;
|
||||
readonly threadId: string;
|
||||
readonly turnId?: string | undefined;
|
||||
readonly itemId?: string | undefined;
|
||||
readonly requestId?: string | undefined;
|
||||
readonly payload?: unknown | undefined;
|
||||
readonly [key: string]: unknown;
|
||||
};
|
||||
|
||||
// Temporary alias while fixtures migrate to the new name.
|
||||
export type LegacyProviderRuntimeEvent = FixtureProviderRuntimeEvent;
|
||||
|
||||
interface SessionState {
|
||||
readonly session: ProviderSession;
|
||||
snapshot: ProviderThreadSnapshot;
|
||||
@@ -56,217 +40,82 @@ interface SessionState {
|
||||
readonly rollbackCalls: Array<number>;
|
||||
}
|
||||
|
||||
function isRecord(value: unknown): value is Record<string, unknown> {
|
||||
return typeof value === "object" && value !== null;
|
||||
}
|
||||
|
||||
function normalizeTurnState(value: unknown): "completed" | "failed" | "interrupted" | "cancelled" {
|
||||
if (
|
||||
value === "completed" ||
|
||||
value === "failed" ||
|
||||
value === "interrupted" ||
|
||||
value === "cancelled"
|
||||
) {
|
||||
return value;
|
||||
}
|
||||
return "completed";
|
||||
}
|
||||
|
||||
function mapRequestType(requestKind: unknown):
|
||||
| "command_execution_approval"
|
||||
| "file_change_approval"
|
||||
| "unknown" {
|
||||
if (requestKind === "command") {
|
||||
return "command_execution_approval";
|
||||
}
|
||||
if (requestKind === "file-change") {
|
||||
return "file_change_approval";
|
||||
}
|
||||
return "unknown";
|
||||
}
|
||||
|
||||
function mapItemType(toolKind: unknown): "command_execution" | "file_change" | "unknown" {
|
||||
if (toolKind === "command") {
|
||||
return "command_execution";
|
||||
}
|
||||
if (toolKind === "file-change") {
|
||||
return "file_change";
|
||||
}
|
||||
return "unknown";
|
||||
}
|
||||
|
||||
function normalizeFixtureEvent(rawEvent: Record<string, unknown>): ProviderRuntimeEvent {
|
||||
const type = typeof rawEvent.type === "string" ? rawEvent.type : "";
|
||||
switch (type) {
|
||||
case "turn.started":
|
||||
return {
|
||||
...rawEvent,
|
||||
type: "turn.started",
|
||||
payload: isRecord(rawEvent.payload) ? rawEvent.payload : {},
|
||||
} as ProviderRuntimeEvent;
|
||||
case "turn.completed":
|
||||
return {
|
||||
...rawEvent,
|
||||
type: "turn.completed",
|
||||
payload: isRecord(rawEvent.payload)
|
||||
? rawEvent.payload
|
||||
: {
|
||||
state: normalizeTurnState(rawEvent.status),
|
||||
},
|
||||
} as ProviderRuntimeEvent;
|
||||
case "message.delta":
|
||||
return {
|
||||
...rawEvent,
|
||||
type: "content.delta",
|
||||
payload: {
|
||||
streamKind: "assistant_text",
|
||||
delta: typeof rawEvent.delta === "string" ? rawEvent.delta : "",
|
||||
},
|
||||
} as ProviderRuntimeEvent;
|
||||
case "message.completed":
|
||||
return {
|
||||
...rawEvent,
|
||||
type: "item.completed",
|
||||
payload: {
|
||||
itemType: "assistant_message",
|
||||
...(typeof rawEvent.detail === "string" ? { detail: rawEvent.detail } : {}),
|
||||
},
|
||||
} as ProviderRuntimeEvent;
|
||||
case "tool.started":
|
||||
return {
|
||||
...rawEvent,
|
||||
type: "item.started",
|
||||
payload: {
|
||||
itemType: mapItemType(rawEvent.toolKind),
|
||||
...(typeof rawEvent.title === "string" ? { title: rawEvent.title } : {}),
|
||||
...(typeof rawEvent.detail === "string" ? { detail: rawEvent.detail } : {}),
|
||||
},
|
||||
} as ProviderRuntimeEvent;
|
||||
case "tool.completed":
|
||||
return {
|
||||
...rawEvent,
|
||||
type: "item.completed",
|
||||
payload: {
|
||||
itemType: mapItemType(rawEvent.toolKind),
|
||||
status: "completed",
|
||||
...(typeof rawEvent.title === "string" ? { title: rawEvent.title } : {}),
|
||||
...(typeof rawEvent.detail === "string" ? { detail: rawEvent.detail } : {}),
|
||||
},
|
||||
} as ProviderRuntimeEvent;
|
||||
case "approval.requested":
|
||||
return {
|
||||
...rawEvent,
|
||||
type: "request.opened",
|
||||
payload: {
|
||||
requestType: mapRequestType(rawEvent.requestKind),
|
||||
...(typeof rawEvent.detail === "string" ? { detail: rawEvent.detail } : {}),
|
||||
},
|
||||
} as ProviderRuntimeEvent;
|
||||
case "approval.resolved":
|
||||
return {
|
||||
...rawEvent,
|
||||
type: "request.resolved",
|
||||
payload: {
|
||||
requestType: mapRequestType(rawEvent.requestKind),
|
||||
...(typeof rawEvent.decision === "string" ? { decision: rawEvent.decision } : {}),
|
||||
},
|
||||
} as ProviderRuntimeEvent;
|
||||
default:
|
||||
return rawEvent as ProviderRuntimeEvent;
|
||||
}
|
||||
}
|
||||
|
||||
export interface TestProviderAdapterHarness {
|
||||
readonly adapter: ProviderAdapterShape<ProviderAdapterError>;
|
||||
readonly provider: "codex" | "claudeCode";
|
||||
readonly queueTurnResponse: (
|
||||
threadId: ThreadId,
|
||||
sessionId: string,
|
||||
response: TestTurnResponse,
|
||||
) => Effect.Effect<void, ProviderAdapterSessionNotFoundError>;
|
||||
readonly queueTurnResponseForNextSession: (
|
||||
response: TestTurnResponse,
|
||||
) => Effect.Effect<void, never>;
|
||||
readonly getStartCount: () => number;
|
||||
readonly getRollbackCalls: (threadId: ThreadId) => ReadonlyArray<number>;
|
||||
readonly getInterruptCalls: (threadId: ThreadId) => ReadonlyArray<TurnId | undefined>;
|
||||
readonly listActiveSessionIds: () => ReadonlyArray<ThreadId>;
|
||||
readonly getApprovalResponses: (threadId: ThreadId) => ReadonlyArray<{
|
||||
readonly threadId: ThreadId;
|
||||
readonly getRollbackCalls: (sessionId: string) => ReadonlyArray<number>;
|
||||
readonly getApprovalResponses: (sessionId: string) => ReadonlyArray<{
|
||||
readonly sessionId: ProviderSessionId;
|
||||
readonly requestId: ApprovalRequestId;
|
||||
readonly decision: ProviderApprovalDecision;
|
||||
}>;
|
||||
}
|
||||
|
||||
interface MakeTestProviderAdapterHarnessOptions {
|
||||
readonly provider?: "codex" | "claudeCode";
|
||||
}
|
||||
const PROVIDER = "codex" as const;
|
||||
|
||||
function nowIso(): string {
|
||||
return new Date().toISOString();
|
||||
}
|
||||
|
||||
function sessionNotFound(
|
||||
provider: "codex" | "claudeCode",
|
||||
threadId: ThreadId,
|
||||
): ProviderAdapterSessionNotFoundError {
|
||||
function sessionNotFound(sessionId: string): ProviderAdapterSessionNotFoundError {
|
||||
return new ProviderAdapterSessionNotFoundError({
|
||||
provider,
|
||||
threadId: String(threadId),
|
||||
provider: PROVIDER,
|
||||
sessionId,
|
||||
});
|
||||
}
|
||||
|
||||
function missingSessionEffect(
|
||||
provider: "codex" | "claudeCode",
|
||||
threadId: ThreadId,
|
||||
): Effect.Effect<never, ProviderAdapterError> {
|
||||
return Effect.fail(sessionNotFound(provider, threadId));
|
||||
function missingSessionEffect(sessionId: string): Effect.Effect<never, ProviderAdapterError> {
|
||||
return Effect.fail(sessionNotFound(sessionId));
|
||||
}
|
||||
|
||||
export const makeTestProviderAdapterHarness = (options?: MakeTestProviderAdapterHarnessOptions) =>
|
||||
Effect.gen(function* () {
|
||||
const provider = options?.provider ?? "codex";
|
||||
const runtimeEvents = yield* Queue.unbounded<ProviderRuntimeEvent>();
|
||||
let sessionCount = 0;
|
||||
const sessions = new Map<ThreadId, SessionState>();
|
||||
const queuedResponsesForNextSession: TestTurnResponse[] = [];
|
||||
const interruptCallsBySession = new Map<ThreadId, Array<TurnId | undefined>>();
|
||||
const approvalResponsesBySession = new Map<
|
||||
ThreadId,
|
||||
Array<{
|
||||
readonly threadId: ThreadId;
|
||||
readonly requestId: ApprovalRequestId;
|
||||
readonly decision: ProviderApprovalDecision;
|
||||
}>
|
||||
>();
|
||||
export const makeTestProviderAdapterHarness = Effect.gen(function* () {
|
||||
const runtimeEvents = yield* Queue.unbounded<ProviderRuntimeEvent>();
|
||||
let sessionCount = 0;
|
||||
const sessions = new Map<string, SessionState>();
|
||||
const queuedResponsesForNextSession: TestTurnResponse[] = [];
|
||||
const approvalResponsesBySession = new Map<
|
||||
string,
|
||||
Array<{
|
||||
readonly sessionId: ProviderSessionId;
|
||||
readonly requestId: ApprovalRequestId;
|
||||
readonly decision: ProviderApprovalDecision;
|
||||
}>
|
||||
>();
|
||||
|
||||
const emit = (event: ProviderRuntimeEvent) => Queue.offer(runtimeEvents, event);
|
||||
|
||||
const startSession: ProviderAdapterShape<ProviderAdapterError>["startSession"] = (input) =>
|
||||
Effect.gen(function* () {
|
||||
if (input.provider !== undefined && input.provider !== provider) {
|
||||
if (input.provider !== undefined && input.provider !== PROVIDER) {
|
||||
return yield* new ProviderAdapterValidationError({
|
||||
provider,
|
||||
provider: PROVIDER,
|
||||
operation: "startSession",
|
||||
issue: `Expected provider '${provider}' but received '${input.provider}'.`,
|
||||
issue: `Expected provider '${PROVIDER}' but received '${input.provider}'.`,
|
||||
});
|
||||
}
|
||||
|
||||
sessionCount += 1;
|
||||
const threadId = input.threadId;
|
||||
const sessionId = ProviderSessionId.makeUnsafe(`test-session-${sessionCount}`);
|
||||
const threadId = ProviderThreadId.makeUnsafe(`test-thread-${sessionCount}`);
|
||||
const createdAt = nowIso();
|
||||
|
||||
const session: ProviderSession = {
|
||||
provider,
|
||||
sessionId,
|
||||
provider: PROVIDER,
|
||||
status: "ready",
|
||||
runtimeMode: input.runtimeMode,
|
||||
threadId,
|
||||
cwd: input.cwd,
|
||||
resumeCursor: input.resumeCursor ?? { threadId: String(threadId), seed: sessionCount },
|
||||
createdAt,
|
||||
updatedAt: createdAt,
|
||||
};
|
||||
|
||||
sessions.set(threadId, {
|
||||
sessions.set(sessionId, {
|
||||
session,
|
||||
snapshot: {
|
||||
threadId,
|
||||
@@ -282,21 +131,21 @@ export const makeTestProviderAdapterHarness = (options?: MakeTestProviderAdapter
|
||||
|
||||
const sendTurn: ProviderAdapterShape<ProviderAdapterError>["sendTurn"] = (input) =>
|
||||
Effect.gen(function* () {
|
||||
const state = sessions.get(input.threadId);
|
||||
const state = sessions.get(input.sessionId);
|
||||
if (!state) {
|
||||
return yield* missingSessionEffect(provider, input.threadId);
|
||||
return yield* missingSessionEffect(input.sessionId);
|
||||
}
|
||||
|
||||
state.turnCount += 1;
|
||||
const turnCount = state.turnCount;
|
||||
const turnId = TurnId.makeUnsafe(`turn-${turnCount}`);
|
||||
const turnId = ProviderTurnId.makeUnsafe(`turn-${turnCount}`);
|
||||
|
||||
const response = state.queuedResponses.shift();
|
||||
if (!response) {
|
||||
return yield* new ProviderAdapterValidationError({
|
||||
provider,
|
||||
provider: PROVIDER,
|
||||
operation: "sendTurn",
|
||||
issue: `No queued turn response for thread ${input.threadId}.`,
|
||||
issue: `No queued turn response for session ${input.sessionId}.`,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -306,27 +155,20 @@ export const makeTestProviderAdapterHarness = (options?: MakeTestProviderAdapter
|
||||
const rawEvent: Record<string, unknown> = {
|
||||
...(fixtureEvent as Record<string, unknown>),
|
||||
eventId: randomUUID(),
|
||||
provider,
|
||||
sessionId: RuntimeSessionId.makeUnsafe(String(input.threadId)),
|
||||
provider: PROVIDER,
|
||||
sessionId: input.sessionId,
|
||||
createdAt: nowIso(),
|
||||
};
|
||||
rawEvent.threadId = state.snapshot.threadId;
|
||||
if (Object.hasOwn(rawEvent, "threadId")) {
|
||||
rawEvent.threadId = state.snapshot.threadId;
|
||||
}
|
||||
if (Object.hasOwn(rawEvent, "turnId")) {
|
||||
rawEvent.turnId = turnId;
|
||||
}
|
||||
|
||||
const runtimeEvent = normalizeFixtureEvent(rawEvent);
|
||||
const runtimeType = (runtimeEvent as { type: string }).type;
|
||||
if (runtimeType === "content.delta") {
|
||||
const payload = runtimeEvent.payload as { delta?: unknown } | undefined;
|
||||
if (typeof payload?.delta === "string") {
|
||||
assistantDeltas.push(payload.delta);
|
||||
}
|
||||
} else if (runtimeType === "message.delta") {
|
||||
const legacyDelta = (runtimeEvent as { delta?: unknown }).delta;
|
||||
if (typeof legacyDelta === "string") {
|
||||
assistantDeltas.push(legacyDelta);
|
||||
}
|
||||
const runtimeEvent = rawEvent as ProviderRuntimeEvent;
|
||||
if (runtimeEvent.type === "message.delta") {
|
||||
assistantDeltas.push(runtimeEvent.delta);
|
||||
}
|
||||
if (runtimeEvent.type === "turn.completed") {
|
||||
deferredTurnCompletedEvents.push(runtimeEvent);
|
||||
@@ -364,13 +206,12 @@ export const makeTestProviderAdapterHarness = (options?: MakeTestProviderAdapter
|
||||
yield* emit({
|
||||
type: "turn.completed",
|
||||
eventId: EventId.makeUnsafe(randomUUID()),
|
||||
provider,
|
||||
provider: PROVIDER,
|
||||
sessionId: input.sessionId,
|
||||
createdAt: nowIso(),
|
||||
threadId: state.snapshot.threadId,
|
||||
turnId,
|
||||
payload: {
|
||||
state: "completed",
|
||||
},
|
||||
status: "completed",
|
||||
});
|
||||
} else {
|
||||
for (const completedEvent of deferredTurnCompletedEvents) {
|
||||
@@ -385,71 +226,58 @@ export const makeTestProviderAdapterHarness = (options?: MakeTestProviderAdapter
|
||||
});
|
||||
|
||||
const interruptTurn: ProviderAdapterShape<ProviderAdapterError>["interruptTurn"] = (
|
||||
threadId,
|
||||
turnId,
|
||||
) =>
|
||||
sessions.has(threadId)
|
||||
? Effect.sync(() => {
|
||||
const existing = interruptCallsBySession.get(threadId) ?? [];
|
||||
existing.push(turnId);
|
||||
interruptCallsBySession.set(threadId, existing);
|
||||
})
|
||||
: missingSessionEffect(provider, threadId);
|
||||
sessionId,
|
||||
_turnId,
|
||||
) => (sessions.has(sessionId) ? Effect.void : missingSessionEffect(sessionId));
|
||||
|
||||
const respondToRequest: ProviderAdapterShape<ProviderAdapterError>["respondToRequest"] = (
|
||||
threadId,
|
||||
sessionId,
|
||||
requestId,
|
||||
decision,
|
||||
) =>
|
||||
sessions.has(threadId)
|
||||
sessions.has(sessionId)
|
||||
? Effect.sync(() => {
|
||||
const existing = approvalResponsesBySession.get(threadId) ?? [];
|
||||
const existing = approvalResponsesBySession.get(sessionId) ?? [];
|
||||
existing.push({
|
||||
threadId,
|
||||
sessionId,
|
||||
requestId,
|
||||
decision,
|
||||
});
|
||||
approvalResponsesBySession.set(threadId, existing);
|
||||
approvalResponsesBySession.set(sessionId, existing);
|
||||
})
|
||||
: missingSessionEffect(provider, threadId);
|
||||
: missingSessionEffect(sessionId);
|
||||
|
||||
const respondToUserInput: ProviderAdapterShape<ProviderAdapterError>["respondToUserInput"] = (
|
||||
threadId,
|
||||
_requestId,
|
||||
_answers,
|
||||
) => (sessions.has(threadId) ? Effect.void : missingSessionEffect(provider, threadId));
|
||||
|
||||
const stopSession: ProviderAdapterShape<ProviderAdapterError>["stopSession"] = (threadId) =>
|
||||
const stopSession: ProviderAdapterShape<ProviderAdapterError>["stopSession"] = (sessionId) =>
|
||||
Effect.sync(() => {
|
||||
sessions.delete(threadId);
|
||||
sessions.delete(sessionId);
|
||||
});
|
||||
|
||||
const listSessions: ProviderAdapterShape<ProviderAdapterError>["listSessions"] = () =>
|
||||
Effect.sync(() => Array.from(sessions.values(), (state) => state.session));
|
||||
|
||||
const hasSession: ProviderAdapterShape<ProviderAdapterError>["hasSession"] = (threadId) =>
|
||||
Effect.succeed(sessions.has(threadId));
|
||||
const hasSession: ProviderAdapterShape<ProviderAdapterError>["hasSession"] = (sessionId) =>
|
||||
Effect.succeed(sessions.has(sessionId));
|
||||
|
||||
const readThread: ProviderAdapterShape<ProviderAdapterError>["readThread"] = (threadId) => {
|
||||
const state = sessions.get(threadId);
|
||||
const readThread: ProviderAdapterShape<ProviderAdapterError>["readThread"] = (sessionId) => {
|
||||
const state = sessions.get(sessionId);
|
||||
if (!state) {
|
||||
return missingSessionEffect(provider, threadId);
|
||||
return missingSessionEffect(sessionId);
|
||||
}
|
||||
return Effect.succeed(state.snapshot);
|
||||
};
|
||||
|
||||
const rollbackThread: ProviderAdapterShape<ProviderAdapterError>["rollbackThread"] = (
|
||||
threadId,
|
||||
sessionId,
|
||||
numTurns,
|
||||
) => {
|
||||
const state = sessions.get(threadId);
|
||||
const state = sessions.get(sessionId);
|
||||
if (!state) {
|
||||
return missingSessionEffect(provider, threadId);
|
||||
return missingSessionEffect(sessionId);
|
||||
}
|
||||
if (!Number.isInteger(numTurns) || numTurns < 0 || numTurns > state.snapshot.turns.length) {
|
||||
return Effect.fail(
|
||||
new ProviderAdapterValidationError({
|
||||
provider,
|
||||
provider: PROVIDER,
|
||||
operation: "rollbackThread",
|
||||
issue: "numTurns must be an integer between 0 and current turn count.",
|
||||
}),
|
||||
@@ -473,15 +301,11 @@ export const makeTestProviderAdapterHarness = (options?: MakeTestProviderAdapter
|
||||
});
|
||||
|
||||
const adapter: ProviderAdapterShape<ProviderAdapterError> = {
|
||||
provider,
|
||||
capabilities: {
|
||||
sessionModelSwitch: "in-session",
|
||||
},
|
||||
provider: PROVIDER,
|
||||
startSession,
|
||||
sendTurn,
|
||||
interruptTurn,
|
||||
respondToRequest,
|
||||
respondToUserInput,
|
||||
stopSession,
|
||||
listSessions,
|
||||
hasSession,
|
||||
@@ -492,16 +316,16 @@ export const makeTestProviderAdapterHarness = (options?: MakeTestProviderAdapter
|
||||
};
|
||||
|
||||
const queueTurnResponse = (
|
||||
threadId: ThreadId,
|
||||
sessionId: string,
|
||||
response: TestTurnResponse,
|
||||
): Effect.Effect<void, ProviderAdapterSessionNotFoundError> =>
|
||||
Effect.sync(() => sessions.get(threadId)).pipe(
|
||||
Effect.sync(() => sessions.get(sessionId)).pipe(
|
||||
Effect.flatMap((state) =>
|
||||
state
|
||||
? Effect.sync(() => {
|
||||
state.queuedResponses.push(response);
|
||||
})
|
||||
: Effect.fail(sessionNotFound(provider, threadId)),
|
||||
: Effect.fail(sessionNotFound(sessionId)),
|
||||
),
|
||||
);
|
||||
|
||||
@@ -512,35 +336,22 @@ export const makeTestProviderAdapterHarness = (options?: MakeTestProviderAdapter
|
||||
queuedResponsesForNextSession.push(response);
|
||||
});
|
||||
|
||||
const getRollbackCalls = (threadId: ThreadId): ReadonlyArray<number> => {
|
||||
const state = sessions.get(threadId);
|
||||
const getRollbackCalls = (sessionId: string): ReadonlyArray<number> => {
|
||||
const state = sessions.get(sessionId);
|
||||
if (!state) {
|
||||
return [];
|
||||
}
|
||||
return [...state.rollbackCalls];
|
||||
};
|
||||
|
||||
const getStartCount = (): number => sessionCount;
|
||||
|
||||
const getInterruptCalls = (threadId: ThreadId): ReadonlyArray<TurnId | undefined> => {
|
||||
const calls = interruptCallsBySession.get(threadId);
|
||||
if (!calls) {
|
||||
return [];
|
||||
}
|
||||
return [...calls];
|
||||
};
|
||||
|
||||
const listActiveSessionIds = (): ReadonlyArray<ThreadId> =>
|
||||
Array.from(sessions.values(), (state) => state.session.threadId);
|
||||
|
||||
const getApprovalResponses = (
|
||||
threadId: ThreadId,
|
||||
sessionId: string,
|
||||
): ReadonlyArray<{
|
||||
readonly threadId: ThreadId;
|
||||
readonly sessionId: ProviderSessionId;
|
||||
readonly requestId: ApprovalRequestId;
|
||||
readonly decision: ProviderApprovalDecision;
|
||||
}> => {
|
||||
const responses = approvalResponsesBySession.get(threadId);
|
||||
const responses = approvalResponsesBySession.get(sessionId);
|
||||
if (!responses) {
|
||||
return [];
|
||||
}
|
||||
@@ -549,13 +360,9 @@ export const makeTestProviderAdapterHarness = (options?: MakeTestProviderAdapter
|
||||
|
||||
return {
|
||||
adapter,
|
||||
provider,
|
||||
queueTurnResponse,
|
||||
queueTurnResponseForNextSession,
|
||||
getStartCount,
|
||||
getRollbackCalls,
|
||||
getInterruptCalls,
|
||||
listActiveSessionIds,
|
||||
getApprovalResponses,
|
||||
} satisfies TestProviderAdapterHarness;
|
||||
});
|
||||
@@ -1,16 +1,22 @@
|
||||
import { EventId, RuntimeRequestId } from "@t3tools/contracts";
|
||||
import type { LegacyProviderRuntimeEvent } from "../TestProviderAdapter.integration.ts";
|
||||
import {
|
||||
ApprovalRequestId,
|
||||
EventId,
|
||||
ProviderSessionId,
|
||||
ProviderThreadId,
|
||||
ProviderTurnId,
|
||||
type ProviderRuntimeEvent,
|
||||
} from "@t3tools/contracts";
|
||||
|
||||
const PROVIDER = "codex" as const;
|
||||
const SESSION_ID = "fixture-session";
|
||||
const THREAD_ID = "fixture-thread";
|
||||
const TURN_ID = "fixture-turn";
|
||||
const REQUEST_ID = RuntimeRequestId.makeUnsafe("req-1");
|
||||
const SESSION_ID = ProviderSessionId.makeUnsafe("fixture-session");
|
||||
const THREAD_ID = ProviderThreadId.makeUnsafe("fixture-thread");
|
||||
const TURN_ID = ProviderTurnId.makeUnsafe("fixture-turn");
|
||||
const REQUEST_ID = ApprovalRequestId.makeUnsafe("req-1");
|
||||
|
||||
function baseEvent(
|
||||
eventId: string,
|
||||
createdAt: string,
|
||||
): Pick<LegacyProviderRuntimeEvent, "eventId" | "provider" | "sessionId" | "createdAt"> {
|
||||
): Pick<ProviderRuntimeEvent, "eventId" | "provider" | "sessionId" | "createdAt"> {
|
||||
return {
|
||||
eventId: EventId.makeUnsafe(eventId),
|
||||
provider: PROVIDER,
|
||||
@@ -25,38 +31,29 @@ export const codexTurnTextFixture = [
|
||||
...baseEvent("evt-1", "2026-02-23T00:00:00.000Z"),
|
||||
threadId: THREAD_ID,
|
||||
turnId: TURN_ID,
|
||||
payload: {},
|
||||
},
|
||||
{
|
||||
type: "content.delta",
|
||||
type: "message.delta",
|
||||
...baseEvent("evt-2", "2026-02-23T00:00:00.100Z"),
|
||||
threadId: THREAD_ID,
|
||||
turnId: TURN_ID,
|
||||
payload: {
|
||||
streamKind: "assistant_text",
|
||||
delta: "I will make a small update.\n",
|
||||
},
|
||||
delta: "I will make a small update.\n",
|
||||
},
|
||||
{
|
||||
type: "content.delta",
|
||||
type: "message.delta",
|
||||
...baseEvent("evt-3", "2026-02-23T00:00:00.200Z"),
|
||||
threadId: THREAD_ID,
|
||||
turnId: TURN_ID,
|
||||
payload: {
|
||||
streamKind: "assistant_text",
|
||||
delta: "Done.\n",
|
||||
},
|
||||
delta: "Done.\n",
|
||||
},
|
||||
{
|
||||
type: "turn.completed",
|
||||
...baseEvent("evt-4", "2026-02-23T00:00:00.300Z"),
|
||||
threadId: THREAD_ID,
|
||||
turnId: TURN_ID,
|
||||
payload: {
|
||||
state: "completed",
|
||||
},
|
||||
status: "completed",
|
||||
},
|
||||
] satisfies ReadonlyArray<LegacyProviderRuntimeEvent>;
|
||||
] satisfies ReadonlyArray<ProviderRuntimeEvent>;
|
||||
|
||||
export const codexTurnToolFixture = [
|
||||
{
|
||||
@@ -64,51 +61,40 @@ export const codexTurnToolFixture = [
|
||||
...baseEvent("evt-11", "2026-02-23T00:01:00.000Z"),
|
||||
threadId: THREAD_ID,
|
||||
turnId: TURN_ID,
|
||||
payload: {},
|
||||
},
|
||||
{
|
||||
type: "item.started",
|
||||
type: "tool.started",
|
||||
...baseEvent("evt-12", "2026-02-23T00:01:00.100Z"),
|
||||
threadId: THREAD_ID,
|
||||
turnId: TURN_ID,
|
||||
payload: {
|
||||
itemType: "command_execution",
|
||||
title: "Command run",
|
||||
detail: "echo integration",
|
||||
},
|
||||
toolKind: "command",
|
||||
title: "Command run",
|
||||
detail: "echo integration",
|
||||
},
|
||||
{
|
||||
type: "item.completed",
|
||||
type: "tool.completed",
|
||||
...baseEvent("evt-13", "2026-02-23T00:01:00.200Z"),
|
||||
threadId: THREAD_ID,
|
||||
turnId: TURN_ID,
|
||||
payload: {
|
||||
itemType: "command_execution",
|
||||
status: "completed",
|
||||
title: "Command run",
|
||||
detail: "echo integration",
|
||||
},
|
||||
toolKind: "command",
|
||||
title: "Command run",
|
||||
detail: "echo integration",
|
||||
},
|
||||
{
|
||||
type: "content.delta",
|
||||
type: "message.delta",
|
||||
...baseEvent("evt-14", "2026-02-23T00:01:00.300Z"),
|
||||
threadId: THREAD_ID,
|
||||
turnId: TURN_ID,
|
||||
payload: {
|
||||
streamKind: "assistant_text",
|
||||
delta: "Applied the requested edit.\n",
|
||||
},
|
||||
delta: "Applied the requested edit.\n",
|
||||
},
|
||||
{
|
||||
type: "turn.completed",
|
||||
...baseEvent("evt-15", "2026-02-23T00:01:00.400Z"),
|
||||
threadId: THREAD_ID,
|
||||
turnId: TURN_ID,
|
||||
payload: {
|
||||
state: "completed",
|
||||
},
|
||||
status: "completed",
|
||||
},
|
||||
] satisfies ReadonlyArray<LegacyProviderRuntimeEvent>;
|
||||
] satisfies ReadonlyArray<ProviderRuntimeEvent>;
|
||||
|
||||
export const codexTurnApprovalFixture = [
|
||||
{
|
||||
@@ -116,47 +102,37 @@ export const codexTurnApprovalFixture = [
|
||||
...baseEvent("evt-21", "2026-02-23T00:02:00.000Z"),
|
||||
threadId: THREAD_ID,
|
||||
turnId: TURN_ID,
|
||||
payload: {},
|
||||
},
|
||||
{
|
||||
type: "request.opened",
|
||||
type: "approval.requested",
|
||||
...baseEvent("evt-22", "2026-02-23T00:02:00.100Z"),
|
||||
threadId: THREAD_ID,
|
||||
turnId: TURN_ID,
|
||||
requestId: REQUEST_ID,
|
||||
payload: {
|
||||
requestType: "command_execution_approval",
|
||||
detail: "Please approve command",
|
||||
},
|
||||
requestKind: "command",
|
||||
detail: "Please approve command",
|
||||
},
|
||||
{
|
||||
type: "request.resolved",
|
||||
type: "approval.resolved",
|
||||
...baseEvent("evt-23", "2026-02-23T00:02:00.200Z"),
|
||||
threadId: THREAD_ID,
|
||||
turnId: TURN_ID,
|
||||
requestId: REQUEST_ID,
|
||||
payload: {
|
||||
requestType: "command_execution_approval",
|
||||
decision: "accept",
|
||||
},
|
||||
requestKind: "command",
|
||||
decision: "accept",
|
||||
},
|
||||
{
|
||||
type: "content.delta",
|
||||
type: "message.delta",
|
||||
...baseEvent("evt-24", "2026-02-23T00:02:00.300Z"),
|
||||
threadId: THREAD_ID,
|
||||
turnId: TURN_ID,
|
||||
payload: {
|
||||
streamKind: "assistant_text",
|
||||
delta: "Approval received and command executed.\n",
|
||||
},
|
||||
delta: "Approval received and command executed.\n",
|
||||
},
|
||||
{
|
||||
type: "turn.completed",
|
||||
...baseEvent("evt-25", "2026-02-23T00:02:00.400Z"),
|
||||
threadId: THREAD_ID,
|
||||
turnId: TURN_ID,
|
||||
payload: {
|
||||
state: "completed",
|
||||
},
|
||||
status: "completed",
|
||||
},
|
||||
] satisfies ReadonlyArray<LegacyProviderRuntimeEvent>;
|
||||
] satisfies ReadonlyArray<ProviderRuntimeEvent>;
|
||||
@@ -4,10 +4,12 @@ import path from "node:path";
|
||||
import {
|
||||
ApprovalRequestId,
|
||||
CommandId,
|
||||
DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
EventId,
|
||||
MessageId,
|
||||
ProjectId,
|
||||
ProviderSessionId,
|
||||
ProviderThreadId,
|
||||
ProviderTurnId,
|
||||
ThreadId,
|
||||
} from "@t3tools/contracts";
|
||||
import { assert, it } from "@effect/vitest";
|
||||
@@ -25,14 +27,19 @@ import { checkpointRefForThreadTurn } from "../src/checkpointing/Utils.ts";
|
||||
const asMessageId = (value: string): MessageId => MessageId.makeUnsafe(value);
|
||||
const asProjectId = (value: string): ProjectId => ProjectId.makeUnsafe(value);
|
||||
const asEventId = (value: string): EventId => EventId.makeUnsafe(value);
|
||||
const asProviderSessionId = (value: string): ProviderSessionId =>
|
||||
ProviderSessionId.makeUnsafe(value);
|
||||
const asProviderThreadId = (value: string): ProviderThreadId => ProviderThreadId.makeUnsafe(value);
|
||||
const asProviderTurnId = (value: string): ProviderTurnId => ProviderTurnId.makeUnsafe(value);
|
||||
const asApprovalRequestId = (value: string): ApprovalRequestId =>
|
||||
ApprovalRequestId.makeUnsafe(value);
|
||||
|
||||
const PROJECT_ID = asProjectId("project-1");
|
||||
const THREAD_ID = ThreadId.makeUnsafe("thread-1");
|
||||
const FIXTURE_TURN_ID = "fixture-turn";
|
||||
const FIXTURE_SESSION_ID = asProviderSessionId("fixture-session");
|
||||
const FIXTURE_THREAD_ID = asProviderThreadId("fixture-thread");
|
||||
const FIXTURE_TURN_ID = asProviderTurnId("fixture-turn");
|
||||
const APPROVAL_REQUEST_ID = asApprovalRequestId("req-approval-1");
|
||||
type IntegrationProvider = "codex" | "claudeCode";
|
||||
|
||||
function nowIso() {
|
||||
return new Date().toISOString();
|
||||
@@ -69,30 +76,18 @@ function waitForSync<A>(
|
||||
});
|
||||
}
|
||||
|
||||
function runtimeBase(eventId: string, createdAt: string, provider: IntegrationProvider = "codex") {
|
||||
function runtimeBase(eventId: string, createdAt: string) {
|
||||
return {
|
||||
eventId: asEventId(eventId),
|
||||
provider,
|
||||
provider: "codex" as const,
|
||||
sessionId: FIXTURE_SESSION_ID,
|
||||
createdAt,
|
||||
};
|
||||
}
|
||||
|
||||
function withHarness<A, E>(
|
||||
use: (harness: OrchestrationIntegrationHarness) => Effect.Effect<A, E>,
|
||||
provider: IntegrationProvider = "codex",
|
||||
) {
|
||||
function withHarness<A, E>(use: (harness: OrchestrationIntegrationHarness) => Effect.Effect<A, E>) {
|
||||
return Effect.acquireUseRelease(
|
||||
makeOrchestrationIntegrationHarness({ provider }),
|
||||
use,
|
||||
(harness) => harness.dispose,
|
||||
);
|
||||
}
|
||||
|
||||
function withRealCodexHarness<A, E>(
|
||||
use: (harness: OrchestrationIntegrationHarness) => Effect.Effect<A, E>,
|
||||
) {
|
||||
return Effect.acquireUseRelease(
|
||||
makeOrchestrationIntegrationHarness({ provider: "codex", realCodex: true }),
|
||||
makeOrchestrationIntegrationHarness,
|
||||
use,
|
||||
(harness) => harness.dispose,
|
||||
);
|
||||
@@ -119,8 +114,6 @@ const seedProjectAndThread = (harness: OrchestrationIntegrationHarness) =>
|
||||
projectId: PROJECT_ID,
|
||||
title: "Integration Thread",
|
||||
model: "gpt-5-codex",
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "approval-required",
|
||||
branch: null,
|
||||
worktreePath: harness.workspaceDir,
|
||||
createdAt,
|
||||
@@ -132,7 +125,6 @@ const startTurn = (input: {
|
||||
readonly commandId: string;
|
||||
readonly messageId: string;
|
||||
readonly text: string;
|
||||
readonly provider?: IntegrationProvider;
|
||||
}) =>
|
||||
input.harness.engine.dispatch({
|
||||
type: "thread.turn.start",
|
||||
@@ -144,9 +136,8 @@ const startTurn = (input: {
|
||||
text: input.text,
|
||||
attachments: [],
|
||||
},
|
||||
...(input.provider !== undefined ? { provider: input.provider } : {}),
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "approval-required",
|
||||
approvalPolicy: "on-request",
|
||||
sandboxMode: "workspace-write",
|
||||
createdAt: nowIso(),
|
||||
});
|
||||
|
||||
@@ -160,20 +151,20 @@ it.live("runs a single turn end-to-end and persists checkpoint state in sqlite +
|
||||
{
|
||||
type: "turn.started",
|
||||
...runtimeBase("evt-single-1", "2026-02-24T10:00:00.000Z"),
|
||||
threadId: THREAD_ID,
|
||||
threadId: FIXTURE_THREAD_ID,
|
||||
turnId: FIXTURE_TURN_ID,
|
||||
},
|
||||
{
|
||||
type: "message.delta",
|
||||
...runtimeBase("evt-single-2", "2026-02-24T10:00:00.100Z"),
|
||||
threadId: THREAD_ID,
|
||||
threadId: FIXTURE_THREAD_ID,
|
||||
turnId: FIXTURE_TURN_ID,
|
||||
delta: "Single turn response.\n",
|
||||
},
|
||||
{
|
||||
type: "turn.completed",
|
||||
...runtimeBase("evt-single-3", "2026-02-24T10:00:00.200Z"),
|
||||
threadId: THREAD_ID,
|
||||
threadId: FIXTURE_THREAD_ID,
|
||||
turnId: FIXTURE_TURN_ID,
|
||||
status: "completed",
|
||||
},
|
||||
@@ -220,95 +211,6 @@ it.live("runs a single turn end-to-end and persists checkpoint state in sqlite +
|
||||
),
|
||||
);
|
||||
|
||||
it.live.skipIf(!process.env.CODEX_BINARY_PATH)(
|
||||
"keeps the same Codex provider thread across runtime mode switches",
|
||||
() =>
|
||||
withRealCodexHarness((harness) =>
|
||||
Effect.gen(function* () {
|
||||
const createdAt = nowIso();
|
||||
|
||||
yield* harness.engine.dispatch({
|
||||
type: "project.create",
|
||||
commandId: CommandId.makeUnsafe("cmd-project-create-real-codex"),
|
||||
projectId: PROJECT_ID,
|
||||
title: "Integration Project",
|
||||
workspaceRoot: harness.workspaceDir,
|
||||
defaultModel: "gpt-5.3-codex",
|
||||
createdAt,
|
||||
});
|
||||
|
||||
yield* harness.engine.dispatch({
|
||||
type: "thread.create",
|
||||
commandId: CommandId.makeUnsafe("cmd-thread-create-real-codex"),
|
||||
threadId: THREAD_ID,
|
||||
projectId: PROJECT_ID,
|
||||
title: "Integration Thread",
|
||||
model: "gpt-5.3-codex",
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "full-access",
|
||||
branch: null,
|
||||
worktreePath: harness.workspaceDir,
|
||||
createdAt,
|
||||
});
|
||||
|
||||
yield* harness.engine.dispatch({
|
||||
type: "thread.turn.start",
|
||||
commandId: CommandId.makeUnsafe("cmd-turn-start-real-codex-1"),
|
||||
threadId: THREAD_ID,
|
||||
message: {
|
||||
messageId: asMessageId("msg-real-codex-1"),
|
||||
role: "user",
|
||||
text: "Reply with exactly ALPHA.",
|
||||
attachments: [],
|
||||
},
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "full-access",
|
||||
createdAt: nowIso(),
|
||||
});
|
||||
|
||||
const firstThread = yield* harness.waitForThread(
|
||||
THREAD_ID,
|
||||
(entry) =>
|
||||
entry.session?.status === "ready" &&
|
||||
entry.session.providerName === "codex" &&
|
||||
entry.messages.some(
|
||||
(message) => message.role === "assistant" && message.streaming === false,
|
||||
),
|
||||
180_000,
|
||||
);
|
||||
assert.equal(firstThread.session?.threadId, "thread-1");
|
||||
|
||||
yield* harness.engine.dispatch({
|
||||
type: "thread.turn.start",
|
||||
commandId: CommandId.makeUnsafe("cmd-turn-start-real-codex-2"),
|
||||
threadId: THREAD_ID,
|
||||
message: {
|
||||
messageId: asMessageId("msg-real-codex-2"),
|
||||
role: "user",
|
||||
text: "Reply with exactly BETA.",
|
||||
attachments: [],
|
||||
},
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "approval-required",
|
||||
createdAt: nowIso(),
|
||||
});
|
||||
|
||||
const secondThread = yield* harness.waitForThread(
|
||||
THREAD_ID,
|
||||
(entry) =>
|
||||
entry.session?.status === "ready" &&
|
||||
entry.session.providerName === "codex" &&
|
||||
entry.session.runtimeMode === "approval-required" &&
|
||||
entry.messages.some(
|
||||
(message) => message.role === "assistant" && message.text.includes("BETA"),
|
||||
),
|
||||
180_000,
|
||||
);
|
||||
assert.equal(secondThread.session?.threadId, "thread-1");
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
it.live("runs multi-turn file edits and persists checkpoint diffs", () =>
|
||||
withHarness((harness) =>
|
||||
Effect.gen(function* () {
|
||||
@@ -319,13 +221,13 @@ it.live("runs multi-turn file edits and persists checkpoint diffs", () =>
|
||||
{
|
||||
type: "turn.started",
|
||||
...runtimeBase("evt-multi-1", "2026-02-24T10:01:00.000Z"),
|
||||
threadId: THREAD_ID,
|
||||
threadId: FIXTURE_THREAD_ID,
|
||||
turnId: FIXTURE_TURN_ID,
|
||||
},
|
||||
{
|
||||
type: "tool.started",
|
||||
...runtimeBase("evt-multi-2", "2026-02-24T10:01:00.100Z"),
|
||||
threadId: THREAD_ID,
|
||||
threadId: FIXTURE_THREAD_ID,
|
||||
turnId: FIXTURE_TURN_ID,
|
||||
toolKind: "command",
|
||||
title: "Edit file",
|
||||
@@ -334,7 +236,7 @@ it.live("runs multi-turn file edits and persists checkpoint diffs", () =>
|
||||
{
|
||||
type: "tool.completed",
|
||||
...runtimeBase("evt-multi-3", "2026-02-24T10:01:00.200Z"),
|
||||
threadId: THREAD_ID,
|
||||
threadId: FIXTURE_THREAD_ID,
|
||||
turnId: FIXTURE_TURN_ID,
|
||||
toolKind: "command",
|
||||
title: "Edit file",
|
||||
@@ -343,14 +245,14 @@ it.live("runs multi-turn file edits and persists checkpoint diffs", () =>
|
||||
{
|
||||
type: "message.delta",
|
||||
...runtimeBase("evt-multi-4", "2026-02-24T10:01:00.300Z"),
|
||||
threadId: THREAD_ID,
|
||||
threadId: FIXTURE_THREAD_ID,
|
||||
turnId: FIXTURE_TURN_ID,
|
||||
delta: "Updated README to v2.\n",
|
||||
},
|
||||
{
|
||||
type: "turn.completed",
|
||||
...runtimeBase("evt-multi-5", "2026-02-24T10:01:00.400Z"),
|
||||
threadId: THREAD_ID,
|
||||
threadId: FIXTURE_THREAD_ID,
|
||||
turnId: FIXTURE_TURN_ID,
|
||||
status: "completed",
|
||||
},
|
||||
@@ -368,30 +270,35 @@ it.live("runs multi-turn file edits and persists checkpoint diffs", () =>
|
||||
text: "Make first edit",
|
||||
});
|
||||
|
||||
yield* harness.waitForThread(
|
||||
const firstTurnThread = yield* harness.waitForThread(
|
||||
THREAD_ID,
|
||||
(entry) => entry.checkpoints.length === 1 && entry.session?.threadId === "thread-1",
|
||||
(entry) => entry.checkpoints.length === 1 && entry.session?.providerSessionId !== null,
|
||||
);
|
||||
const sessionId = firstTurnThread.session?.providerSessionId;
|
||||
assert.equal(sessionId !== null, true);
|
||||
if (!sessionId) {
|
||||
return;
|
||||
}
|
||||
|
||||
yield* harness.adapterHarness.queueTurnResponse(THREAD_ID, {
|
||||
yield* harness.adapterHarness.queueTurnResponse(sessionId, {
|
||||
events: [
|
||||
{
|
||||
type: "turn.started",
|
||||
...runtimeBase("evt-multi-6", "2026-02-24T10:02:00.000Z"),
|
||||
threadId: THREAD_ID,
|
||||
threadId: FIXTURE_THREAD_ID,
|
||||
turnId: FIXTURE_TURN_ID,
|
||||
},
|
||||
{
|
||||
type: "message.delta",
|
||||
...runtimeBase("evt-multi-7", "2026-02-24T10:02:00.100Z"),
|
||||
threadId: THREAD_ID,
|
||||
threadId: FIXTURE_THREAD_ID,
|
||||
turnId: FIXTURE_TURN_ID,
|
||||
delta: "Updated README to v3.\n",
|
||||
},
|
||||
{
|
||||
type: "turn.completed",
|
||||
...runtimeBase("evt-multi-8", "2026-02-24T10:02:00.200Z"),
|
||||
threadId: THREAD_ID,
|
||||
threadId: FIXTURE_THREAD_ID,
|
||||
turnId: FIXTURE_TURN_ID,
|
||||
status: "completed",
|
||||
},
|
||||
@@ -478,13 +385,13 @@ it.live("tracks approval requests and resolves pending approvals on user respons
|
||||
{
|
||||
type: "turn.started",
|
||||
...runtimeBase("evt-approval-1", "2026-02-24T10:03:00.000Z"),
|
||||
threadId: THREAD_ID,
|
||||
threadId: FIXTURE_THREAD_ID,
|
||||
turnId: FIXTURE_TURN_ID,
|
||||
},
|
||||
{
|
||||
type: "approval.requested",
|
||||
...runtimeBase("evt-approval-2", "2026-02-24T10:03:00.100Z"),
|
||||
threadId: THREAD_ID,
|
||||
threadId: FIXTURE_THREAD_ID,
|
||||
turnId: FIXTURE_TURN_ID,
|
||||
requestId: APPROVAL_REQUEST_ID,
|
||||
requestKind: "command",
|
||||
@@ -493,7 +400,7 @@ it.live("tracks approval requests and resolves pending approvals on user respons
|
||||
{
|
||||
type: "turn.completed",
|
||||
...runtimeBase("evt-approval-3", "2026-02-24T10:03:00.200Z"),
|
||||
threadId: THREAD_ID,
|
||||
threadId: FIXTURE_THREAD_ID,
|
||||
turnId: FIXTURE_TURN_ID,
|
||||
status: "completed",
|
||||
},
|
||||
@@ -537,8 +444,9 @@ it.live("tracks approval requests and resolves pending approvals on user respons
|
||||
assert.equal(resolvedRow.status, "resolved");
|
||||
assert.equal(resolvedRow.decision, "accept");
|
||||
|
||||
const providerSessionId = thread.session?.providerSessionId ?? "test-session-1";
|
||||
const approvalResponses = yield* waitForSync(
|
||||
() => harness.adapterHarness.getApprovalResponses(THREAD_ID),
|
||||
() => harness.adapterHarness.getApprovalResponses(providerSessionId),
|
||||
(responses) => responses.length === 1,
|
||||
"provider approval response",
|
||||
);
|
||||
@@ -559,37 +467,30 @@ it.live("records failed turn runtime state and checkpoint status as error", () =
|
||||
{
|
||||
type: "turn.started",
|
||||
...runtimeBase("evt-failure-1", "2026-02-24T10:04:00.000Z"),
|
||||
threadId: THREAD_ID,
|
||||
threadId: FIXTURE_THREAD_ID,
|
||||
turnId: FIXTURE_TURN_ID,
|
||||
},
|
||||
{
|
||||
type: "content.delta",
|
||||
type: "message.delta",
|
||||
...runtimeBase("evt-failure-2", "2026-02-24T10:04:00.100Z"),
|
||||
threadId: THREAD_ID,
|
||||
threadId: FIXTURE_THREAD_ID,
|
||||
turnId: FIXTURE_TURN_ID,
|
||||
payload: {
|
||||
streamKind: "assistant_text",
|
||||
delta: "Partial output before failure.\n",
|
||||
},
|
||||
delta: "Partial output before failure.\n",
|
||||
},
|
||||
{
|
||||
type: "runtime.error",
|
||||
...runtimeBase("evt-failure-3", "2026-02-24T10:04:00.200Z"),
|
||||
threadId: THREAD_ID,
|
||||
threadId: FIXTURE_THREAD_ID,
|
||||
turnId: FIXTURE_TURN_ID,
|
||||
payload: {
|
||||
message: "Sandbox command failed.",
|
||||
},
|
||||
message: "Sandbox command failed.",
|
||||
},
|
||||
{
|
||||
type: "turn.completed",
|
||||
...runtimeBase("evt-failure-4", "2026-02-24T10:04:00.300Z"),
|
||||
threadId: THREAD_ID,
|
||||
threadId: FIXTURE_THREAD_ID,
|
||||
turnId: FIXTURE_TURN_ID,
|
||||
payload: {
|
||||
state: "failed",
|
||||
errorMessage: "Sandbox command failed.",
|
||||
},
|
||||
status: "failed",
|
||||
errorMessage: "Sandbox command failed.",
|
||||
},
|
||||
],
|
||||
});
|
||||
@@ -638,13 +539,13 @@ it.live("reverts to an earlier checkpoint and trims checkpoint projections + git
|
||||
{
|
||||
type: "turn.started",
|
||||
...runtimeBase("evt-revert-1", "2026-02-24T10:05:00.000Z"),
|
||||
threadId: THREAD_ID,
|
||||
threadId: FIXTURE_THREAD_ID,
|
||||
turnId: FIXTURE_TURN_ID,
|
||||
},
|
||||
{
|
||||
type: "tool.started",
|
||||
...runtimeBase("evt-revert-1-tool-started", "2026-02-24T10:05:00.025Z"),
|
||||
threadId: THREAD_ID,
|
||||
threadId: FIXTURE_THREAD_ID,
|
||||
turnId: FIXTURE_TURN_ID,
|
||||
toolKind: "command",
|
||||
title: "Edit file",
|
||||
@@ -653,7 +554,7 @@ it.live("reverts to an earlier checkpoint and trims checkpoint projections + git
|
||||
{
|
||||
type: "tool.completed",
|
||||
...runtimeBase("evt-revert-1-tool-completed", "2026-02-24T10:05:00.035Z"),
|
||||
threadId: THREAD_ID,
|
||||
threadId: FIXTURE_THREAD_ID,
|
||||
turnId: FIXTURE_TURN_ID,
|
||||
toolKind: "command",
|
||||
title: "Edit file",
|
||||
@@ -662,14 +563,14 @@ it.live("reverts to an earlier checkpoint and trims checkpoint projections + git
|
||||
{
|
||||
type: "message.delta",
|
||||
...runtimeBase("evt-revert-1a", "2026-02-24T10:05:00.050Z"),
|
||||
threadId: THREAD_ID,
|
||||
threadId: FIXTURE_THREAD_ID,
|
||||
turnId: FIXTURE_TURN_ID,
|
||||
delta: "Updated README to v2.\n",
|
||||
},
|
||||
{
|
||||
type: "turn.completed",
|
||||
...runtimeBase("evt-revert-2", "2026-02-24T10:05:00.100Z"),
|
||||
threadId: THREAD_ID,
|
||||
threadId: FIXTURE_THREAD_ID,
|
||||
turnId: FIXTURE_TURN_ID,
|
||||
status: "completed",
|
||||
},
|
||||
@@ -686,23 +587,28 @@ it.live("reverts to an earlier checkpoint and trims checkpoint projections + git
|
||||
text: "First edit",
|
||||
});
|
||||
|
||||
yield* harness.waitForThread(
|
||||
const firstTurnThread = yield* harness.waitForThread(
|
||||
THREAD_ID,
|
||||
(entry) => entry.session?.threadId === "thread-1" && entry.checkpoints.length === 1,
|
||||
(entry) => entry.session?.providerSessionId !== null && entry.checkpoints.length === 1,
|
||||
);
|
||||
const sessionId = firstTurnThread.session?.providerSessionId;
|
||||
assert.equal(sessionId !== null, true);
|
||||
if (!sessionId) {
|
||||
return;
|
||||
}
|
||||
|
||||
yield* harness.adapterHarness.queueTurnResponse(THREAD_ID, {
|
||||
yield* harness.adapterHarness.queueTurnResponse(sessionId, {
|
||||
events: [
|
||||
{
|
||||
type: "turn.started",
|
||||
...runtimeBase("evt-revert-3", "2026-02-24T10:05:01.000Z"),
|
||||
threadId: THREAD_ID,
|
||||
threadId: FIXTURE_THREAD_ID,
|
||||
turnId: FIXTURE_TURN_ID,
|
||||
},
|
||||
{
|
||||
type: "tool.started",
|
||||
...runtimeBase("evt-revert-3-tool-started", "2026-02-24T10:05:01.025Z"),
|
||||
threadId: THREAD_ID,
|
||||
threadId: FIXTURE_THREAD_ID,
|
||||
turnId: FIXTURE_TURN_ID,
|
||||
toolKind: "command",
|
||||
title: "Edit file",
|
||||
@@ -711,7 +617,7 @@ it.live("reverts to an earlier checkpoint and trims checkpoint projections + git
|
||||
{
|
||||
type: "tool.completed",
|
||||
...runtimeBase("evt-revert-3-tool-completed", "2026-02-24T10:05:01.035Z"),
|
||||
threadId: THREAD_ID,
|
||||
threadId: FIXTURE_THREAD_ID,
|
||||
turnId: FIXTURE_TURN_ID,
|
||||
toolKind: "command",
|
||||
title: "Edit file",
|
||||
@@ -720,14 +626,14 @@ it.live("reverts to an earlier checkpoint and trims checkpoint projections + git
|
||||
{
|
||||
type: "message.delta",
|
||||
...runtimeBase("evt-revert-3a", "2026-02-24T10:05:01.050Z"),
|
||||
threadId: THREAD_ID,
|
||||
threadId: FIXTURE_THREAD_ID,
|
||||
turnId: FIXTURE_TURN_ID,
|
||||
delta: "Updated README to v3.\n",
|
||||
},
|
||||
{
|
||||
type: "turn.completed",
|
||||
...runtimeBase("evt-revert-4", "2026-02-24T10:05:01.100Z"),
|
||||
threadId: THREAD_ID,
|
||||
threadId: FIXTURE_THREAD_ID,
|
||||
turnId: FIXTURE_TURN_ID,
|
||||
status: "completed",
|
||||
},
|
||||
@@ -796,7 +702,7 @@ it.live("reverts to an earlier checkpoint and trims checkpoint projections + git
|
||||
gitRefExists(harness.workspaceDir, checkpointRefForThreadTurn(THREAD_ID, 2)),
|
||||
false,
|
||||
);
|
||||
assert.deepEqual(harness.adapterHarness.getRollbackCalls(THREAD_ID), [1]);
|
||||
assert.deepEqual(harness.adapterHarness.getRollbackCalls(sessionId), [1]);
|
||||
|
||||
const checkpointRows = yield* harness.checkpointRepository.listByThreadId({
|
||||
threadId: THREAD_ID,
|
||||
@@ -842,416 +748,3 @@ it.live(
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
it.live("starts a claudeCode session on first turn when provider is requested", () =>
|
||||
withHarness(
|
||||
(harness) =>
|
||||
Effect.gen(function* () {
|
||||
yield* seedProjectAndThread(harness);
|
||||
|
||||
yield* harness.adapterHarness.queueTurnResponseForNextSession({
|
||||
events: [
|
||||
{
|
||||
type: "turn.started",
|
||||
...runtimeBase("evt-claude-start-1", "2026-02-24T10:10:00.000Z", "claudeCode"),
|
||||
threadId: THREAD_ID,
|
||||
turnId: FIXTURE_TURN_ID,
|
||||
},
|
||||
{
|
||||
type: "message.delta",
|
||||
...runtimeBase("evt-claude-start-2", "2026-02-24T10:10:00.050Z", "claudeCode"),
|
||||
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", "claudeCode"),
|
||||
threadId: THREAD_ID,
|
||||
turnId: FIXTURE_TURN_ID,
|
||||
status: "completed",
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
yield* startTurn({
|
||||
harness,
|
||||
commandId: "cmd-turn-start-claude-initial",
|
||||
messageId: "msg-user-claude-initial",
|
||||
text: "Use Claude",
|
||||
provider: "claudeCode",
|
||||
});
|
||||
|
||||
const thread = yield* harness.waitForThread(
|
||||
THREAD_ID,
|
||||
(entry) =>
|
||||
entry.session?.providerName === "claudeCode" &&
|
||||
entry.session.status === "ready" &&
|
||||
entry.messages.some(
|
||||
(message) => message.role === "assistant" && message.text === "Claude first turn.\n",
|
||||
),
|
||||
);
|
||||
assert.equal(thread.session?.providerName, "claudeCode");
|
||||
}),
|
||||
"claudeCode",
|
||||
),
|
||||
);
|
||||
|
||||
it.live("recovers claudeCode sessions after provider stopAll using persisted resume state", () =>
|
||||
withHarness(
|
||||
(harness) =>
|
||||
Effect.gen(function* () {
|
||||
yield* seedProjectAndThread(harness);
|
||||
|
||||
yield* harness.adapterHarness.queueTurnResponseForNextSession({
|
||||
events: [
|
||||
{
|
||||
type: "turn.started",
|
||||
...runtimeBase("evt-claude-recover-1", "2026-02-24T10:11:00.000Z", "claudeCode"),
|
||||
threadId: THREAD_ID,
|
||||
turnId: FIXTURE_TURN_ID,
|
||||
},
|
||||
{
|
||||
type: "message.delta",
|
||||
...runtimeBase("evt-claude-recover-2", "2026-02-24T10:11:00.050Z", "claudeCode"),
|
||||
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", "claudeCode"),
|
||||
threadId: THREAD_ID,
|
||||
turnId: FIXTURE_TURN_ID,
|
||||
status: "completed",
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
yield* startTurn({
|
||||
harness,
|
||||
commandId: "cmd-turn-start-claude-recover-1",
|
||||
messageId: "msg-user-claude-recover-1",
|
||||
text: "Before restart",
|
||||
provider: "claudeCode",
|
||||
});
|
||||
|
||||
yield* harness.waitForThread(
|
||||
THREAD_ID,
|
||||
(entry) => entry.latestTurn?.turnId === "turn-1" && entry.session?.threadId === "thread-1",
|
||||
);
|
||||
|
||||
yield* harness.providerService.stopAll();
|
||||
yield* waitForSync(
|
||||
() => harness.adapterHarness.listActiveSessionIds(),
|
||||
(sessionIds) => sessionIds.length === 0,
|
||||
"provider stopAll",
|
||||
);
|
||||
|
||||
yield* harness.adapterHarness.queueTurnResponseForNextSession({
|
||||
events: [
|
||||
{
|
||||
type: "turn.started",
|
||||
...runtimeBase("evt-claude-recover-4", "2026-02-24T10:11:01.000Z", "claudeCode"),
|
||||
threadId: THREAD_ID,
|
||||
turnId: FIXTURE_TURN_ID,
|
||||
},
|
||||
{
|
||||
type: "message.delta",
|
||||
...runtimeBase("evt-claude-recover-5", "2026-02-24T10:11:01.050Z", "claudeCode"),
|
||||
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", "claudeCode"),
|
||||
threadId: THREAD_ID,
|
||||
turnId: FIXTURE_TURN_ID,
|
||||
status: "completed",
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
yield* startTurn({
|
||||
harness,
|
||||
commandId: "cmd-turn-start-claude-recover-2",
|
||||
messageId: "msg-user-claude-recover-2",
|
||||
text: "After restart",
|
||||
});
|
||||
yield* waitForSync(
|
||||
() => harness.adapterHarness.getStartCount(),
|
||||
(count) => count === 2,
|
||||
"claude provider recovery start",
|
||||
);
|
||||
|
||||
const recoveredThread = yield* harness.waitForThread(
|
||||
THREAD_ID,
|
||||
(entry) =>
|
||||
entry.session?.providerName === "claudeCode" &&
|
||||
entry.messages.some(
|
||||
(message) => message.role === "user" && message.text === "After restart",
|
||||
) &&
|
||||
!entry.activities.some((activity) => activity.kind === "provider.turn.start.failed"),
|
||||
);
|
||||
assert.equal(recoveredThread.session?.providerName, "claudeCode");
|
||||
assert.equal(recoveredThread.session?.threadId, "thread-1");
|
||||
}),
|
||||
"claudeCode",
|
||||
),
|
||||
);
|
||||
|
||||
it.live("forwards claudeCode approval responses to the provider session", () =>
|
||||
withHarness(
|
||||
(harness) =>
|
||||
Effect.gen(function* () {
|
||||
yield* seedProjectAndThread(harness);
|
||||
|
||||
yield* harness.adapterHarness.queueTurnResponseForNextSession({
|
||||
events: [
|
||||
{
|
||||
type: "turn.started",
|
||||
...runtimeBase("evt-claude-approval-1", "2026-02-24T10:12:00.000Z", "claudeCode"),
|
||||
threadId: THREAD_ID,
|
||||
turnId: FIXTURE_TURN_ID,
|
||||
},
|
||||
{
|
||||
type: "approval.requested",
|
||||
...runtimeBase("evt-claude-approval-2", "2026-02-24T10:12:00.050Z", "claudeCode"),
|
||||
threadId: THREAD_ID,
|
||||
turnId: FIXTURE_TURN_ID,
|
||||
requestId: APPROVAL_REQUEST_ID,
|
||||
requestKind: "command",
|
||||
detail: "Approve Claude tool call",
|
||||
},
|
||||
{
|
||||
type: "turn.completed",
|
||||
...runtimeBase("evt-claude-approval-3", "2026-02-24T10:12:00.100Z", "claudeCode"),
|
||||
threadId: THREAD_ID,
|
||||
turnId: FIXTURE_TURN_ID,
|
||||
status: "completed",
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
yield* startTurn({
|
||||
harness,
|
||||
commandId: "cmd-turn-start-claude-approval",
|
||||
messageId: "msg-user-claude-approval",
|
||||
text: "Need approval",
|
||||
provider: "claudeCode",
|
||||
});
|
||||
|
||||
const thread = yield* harness.waitForThread(THREAD_ID, (entry) =>
|
||||
entry.activities.some((activity) => activity.kind === "approval.requested"),
|
||||
);
|
||||
assert.equal(thread.session?.threadId, "thread-1");
|
||||
|
||||
yield* harness.engine.dispatch({
|
||||
type: "thread.approval.respond",
|
||||
commandId: CommandId.makeUnsafe("cmd-claude-approval-respond"),
|
||||
threadId: THREAD_ID,
|
||||
requestId: APPROVAL_REQUEST_ID,
|
||||
decision: "accept",
|
||||
createdAt: nowIso(),
|
||||
});
|
||||
|
||||
yield* harness.waitForPendingApproval(
|
||||
"req-approval-1",
|
||||
(row) => row.status === "resolved" && row.decision === "accept",
|
||||
);
|
||||
|
||||
const approvalResponses = yield* waitForSync(
|
||||
() => harness.adapterHarness.getApprovalResponses(THREAD_ID),
|
||||
(responses) => responses.length === 1,
|
||||
"claude provider approval response",
|
||||
);
|
||||
assert.equal(approvalResponses[0]?.decision, "accept");
|
||||
}),
|
||||
"claudeCode",
|
||||
),
|
||||
);
|
||||
|
||||
it.live("forwards thread.turn.interrupt to claudeCode provider sessions", () =>
|
||||
withHarness(
|
||||
(harness) =>
|
||||
Effect.gen(function* () {
|
||||
yield* seedProjectAndThread(harness);
|
||||
|
||||
yield* harness.adapterHarness.queueTurnResponseForNextSession({
|
||||
events: [
|
||||
{
|
||||
type: "turn.started",
|
||||
...runtimeBase("evt-claude-interrupt-1", "2026-02-24T10:13:00.000Z", "claudeCode"),
|
||||
threadId: THREAD_ID,
|
||||
turnId: FIXTURE_TURN_ID,
|
||||
},
|
||||
{
|
||||
type: "message.delta",
|
||||
...runtimeBase("evt-claude-interrupt-2", "2026-02-24T10:13:00.050Z", "claudeCode"),
|
||||
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", "claudeCode"),
|
||||
threadId: THREAD_ID,
|
||||
turnId: FIXTURE_TURN_ID,
|
||||
status: "completed",
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
yield* startTurn({
|
||||
harness,
|
||||
commandId: "cmd-turn-start-claude-interrupt",
|
||||
messageId: "msg-user-claude-interrupt",
|
||||
text: "Start long turn",
|
||||
provider: "claudeCode",
|
||||
});
|
||||
|
||||
const thread = yield* harness.waitForThread(
|
||||
THREAD_ID,
|
||||
(entry) => entry.session?.threadId === "thread-1",
|
||||
);
|
||||
assert.equal(thread.session?.threadId, "thread-1");
|
||||
|
||||
yield* harness.engine.dispatch({
|
||||
type: "thread.turn.interrupt",
|
||||
commandId: CommandId.makeUnsafe("cmd-turn-interrupt-claude"),
|
||||
threadId: THREAD_ID,
|
||||
createdAt: nowIso(),
|
||||
});
|
||||
yield* harness.waitForDomainEvent((event) => event.type === "thread.turn-interrupt-requested");
|
||||
|
||||
const interruptCalls = yield* waitForSync(
|
||||
() => harness.adapterHarness.getInterruptCalls(THREAD_ID),
|
||||
(calls) => calls.length === 1,
|
||||
"claude provider interrupt call",
|
||||
);
|
||||
assert.equal(interruptCalls.length, 1);
|
||||
}),
|
||||
"claudeCode",
|
||||
),
|
||||
);
|
||||
|
||||
it.live("reverts claudeCode turns and rolls back provider conversation state", () =>
|
||||
withHarness(
|
||||
(harness) =>
|
||||
Effect.gen(function* () {
|
||||
yield* seedProjectAndThread(harness);
|
||||
|
||||
yield* harness.adapterHarness.queueTurnResponseForNextSession({
|
||||
events: [
|
||||
{
|
||||
type: "turn.started",
|
||||
...runtimeBase("evt-claude-revert-1", "2026-02-24T10:14:00.000Z", "claudeCode"),
|
||||
threadId: THREAD_ID,
|
||||
turnId: FIXTURE_TURN_ID,
|
||||
},
|
||||
{
|
||||
type: "message.delta",
|
||||
...runtimeBase("evt-claude-revert-2", "2026-02-24T10:14:00.050Z", "claudeCode"),
|
||||
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", "claudeCode"),
|
||||
threadId: THREAD_ID,
|
||||
turnId: FIXTURE_TURN_ID,
|
||||
status: "completed",
|
||||
},
|
||||
],
|
||||
mutateWorkspace: ({ cwd }) =>
|
||||
Effect.sync(() => {
|
||||
fs.writeFileSync(path.join(cwd, "README.md"), "v2\n", "utf8");
|
||||
}),
|
||||
});
|
||||
|
||||
yield* startTurn({
|
||||
harness,
|
||||
commandId: "cmd-turn-start-claude-revert-1",
|
||||
messageId: "msg-user-claude-revert-1",
|
||||
text: "First Claude edit",
|
||||
provider: "claudeCode",
|
||||
});
|
||||
|
||||
yield* harness.waitForThread(
|
||||
THREAD_ID,
|
||||
(entry) => entry.latestTurn?.turnId === "turn-1" && entry.session?.threadId === "thread-1",
|
||||
);
|
||||
|
||||
yield* harness.adapterHarness.queueTurnResponse(THREAD_ID, {
|
||||
events: [
|
||||
{
|
||||
type: "turn.started",
|
||||
...runtimeBase("evt-claude-revert-4", "2026-02-24T10:14:01.000Z", "claudeCode"),
|
||||
threadId: THREAD_ID,
|
||||
turnId: FIXTURE_TURN_ID,
|
||||
},
|
||||
{
|
||||
type: "message.delta",
|
||||
...runtimeBase("evt-claude-revert-5", "2026-02-24T10:14:01.050Z", "claudeCode"),
|
||||
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", "claudeCode"),
|
||||
threadId: THREAD_ID,
|
||||
turnId: FIXTURE_TURN_ID,
|
||||
status: "completed",
|
||||
},
|
||||
],
|
||||
mutateWorkspace: ({ cwd }) =>
|
||||
Effect.sync(() => {
|
||||
fs.writeFileSync(path.join(cwd, "README.md"), "v3\n", "utf8");
|
||||
}),
|
||||
});
|
||||
|
||||
yield* startTurn({
|
||||
harness,
|
||||
commandId: "cmd-turn-start-claude-revert-2",
|
||||
messageId: "msg-user-claude-revert-2",
|
||||
text: "Second Claude edit",
|
||||
});
|
||||
|
||||
yield* harness.waitForThread(
|
||||
THREAD_ID,
|
||||
(entry) =>
|
||||
entry.latestTurn?.turnId === "turn-2" &&
|
||||
entry.checkpoints.length === 2 &&
|
||||
entry.session?.providerName === "claudeCode",
|
||||
);
|
||||
|
||||
yield* harness.engine.dispatch({
|
||||
type: "thread.checkpoint.revert",
|
||||
commandId: CommandId.makeUnsafe("cmd-checkpoint-revert-claude"),
|
||||
threadId: THREAD_ID,
|
||||
turnCount: 1,
|
||||
createdAt: nowIso(),
|
||||
});
|
||||
|
||||
const revertedThread = yield* harness.waitForThread(
|
||||
THREAD_ID,
|
||||
(entry) =>
|
||||
entry.checkpoints.length === 1 && entry.checkpoints[0]?.checkpointTurnCount === 1,
|
||||
);
|
||||
assert.equal(revertedThread.checkpoints[0]?.checkpointTurnCount, 1);
|
||||
assert.equal(
|
||||
gitRefExists(harness.workspaceDir, checkpointRefForThreadTurn(THREAD_ID, 1)),
|
||||
true,
|
||||
);
|
||||
assert.equal(
|
||||
gitRefExists(harness.workspaceDir, checkpointRefForThreadTurn(THREAD_ID, 2)),
|
||||
false,
|
||||
);
|
||||
assert.deepEqual(harness.adapterHarness.getRollbackCalls(THREAD_ID), [1]);
|
||||
}),
|
||||
"claudeCode",
|
||||
),
|
||||
);
|
||||
@@ -1,4 +1,4 @@
|
||||
import type { ProviderRuntimeEvent } from "@t3tools/contracts";
|
||||
import type { ProviderRuntimeEvent, ProviderSessionId } from "@t3tools/contracts";
|
||||
import { ThreadId } from "@t3tools/contracts";
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { it, assert } from "@effect/vitest";
|
||||
@@ -42,7 +42,7 @@ interface IntegrationFixture {
|
||||
|
||||
const makeIntegrationFixture = Effect.gen(function* () {
|
||||
const cwd = yield* makeWorkspaceDirectory;
|
||||
const harness = yield* makeTestProviderAdapterHarness();
|
||||
const harness = yield* makeTestProviderAdapterHarness;
|
||||
|
||||
const registry: typeof ProviderAdapterRegistry.Service = {
|
||||
getByProvider: (provider) =>
|
||||
@@ -93,18 +93,18 @@ const collectEventsDuring = <A, E, R>(
|
||||
const runTurn = (input: {
|
||||
readonly provider: ProviderServiceShape;
|
||||
readonly harness: TestProviderAdapterHarness;
|
||||
readonly threadId: ThreadId;
|
||||
readonly sessionId: ProviderSessionId;
|
||||
readonly userText: string;
|
||||
readonly response: TestTurnResponse;
|
||||
}) =>
|
||||
Effect.gen(function* () {
|
||||
yield* input.harness.queueTurnResponse(input.threadId, input.response);
|
||||
yield* input.harness.queueTurnResponse(input.sessionId, input.response);
|
||||
|
||||
return yield* collectEventsDuring(
|
||||
input.provider.streamEvents,
|
||||
input.response.events.length,
|
||||
input.provider.sendTurn({
|
||||
threadId: input.threadId,
|
||||
sessionId: input.sessionId,
|
||||
input: input.userText,
|
||||
attachments: [],
|
||||
}),
|
||||
@@ -120,10 +120,8 @@ it.effect("replays typed runtime fixture events", () =>
|
||||
const session = yield* provider.startSession(
|
||||
ThreadId.makeUnsafe("thread-integration-typed"),
|
||||
{
|
||||
threadId: ThreadId.makeUnsafe("thread-integration-typed"),
|
||||
provider: "codex",
|
||||
cwd: fixture.cwd,
|
||||
runtimeMode: "full-access",
|
||||
},
|
||||
);
|
||||
assert.equal((session.threadId ?? "").length > 0, true);
|
||||
@@ -131,7 +129,7 @@ it.effect("replays typed runtime fixture events", () =>
|
||||
const observedEvents = yield* runTurn({
|
||||
provider,
|
||||
harness: fixture.harness,
|
||||
threadId: session.threadId,
|
||||
sessionId: session.sessionId,
|
||||
userText: "hello",
|
||||
response: { events: codexTurnTextFixture },
|
||||
});
|
||||
@@ -155,10 +153,8 @@ it.effect("replays file-changing fixture turn events", () =>
|
||||
const session = yield* provider.startSession(
|
||||
ThreadId.makeUnsafe("thread-integration-tools"),
|
||||
{
|
||||
threadId: ThreadId.makeUnsafe("thread-integration-tools"),
|
||||
provider: "codex",
|
||||
cwd: fixture.cwd,
|
||||
runtimeMode: "full-access",
|
||||
},
|
||||
);
|
||||
assert.equal((session.threadId ?? "").length > 0, true);
|
||||
@@ -166,7 +162,7 @@ it.effect("replays file-changing fixture turn events", () =>
|
||||
const observedEvents = yield* runTurn({
|
||||
provider,
|
||||
harness: fixture.harness,
|
||||
threadId: session.threadId,
|
||||
sessionId: session.sessionId,
|
||||
userText: "make a small change",
|
||||
response: {
|
||||
events: codexTurnToolFixture,
|
||||
@@ -194,10 +190,8 @@ it.effect("runs multi-turn tool/approval flow", () =>
|
||||
const session = yield* provider.startSession(
|
||||
ThreadId.makeUnsafe("thread-integration-multi"),
|
||||
{
|
||||
threadId: ThreadId.makeUnsafe("thread-integration-multi"),
|
||||
provider: "codex",
|
||||
cwd: fixture.cwd,
|
||||
runtimeMode: "full-access",
|
||||
},
|
||||
);
|
||||
assert.equal((session.threadId ?? "").length > 0, true);
|
||||
@@ -205,7 +199,7 @@ it.effect("runs multi-turn tool/approval flow", () =>
|
||||
const firstTurnEvents = yield* runTurn({
|
||||
provider,
|
||||
harness: fixture.harness,
|
||||
threadId: session.threadId,
|
||||
sessionId: session.sessionId,
|
||||
userText: "turn 1",
|
||||
response: {
|
||||
events: codexTurnToolFixture,
|
||||
@@ -221,7 +215,7 @@ it.effect("runs multi-turn tool/approval flow", () =>
|
||||
const secondTurnEvents = yield* runTurn({
|
||||
provider,
|
||||
harness: fixture.harness,
|
||||
threadId: session.threadId,
|
||||
sessionId: session.sessionId,
|
||||
userText: "turn 2 approval",
|
||||
response: {
|
||||
events: codexTurnApprovalFixture,
|
||||
@@ -248,10 +242,8 @@ it.effect("rolls back provider conversation state only", () =>
|
||||
const session = yield* provider.startSession(
|
||||
ThreadId.makeUnsafe("thread-integration-rollback"),
|
||||
{
|
||||
threadId: ThreadId.makeUnsafe("thread-integration-rollback"),
|
||||
provider: "codex",
|
||||
cwd: fixture.cwd,
|
||||
runtimeMode: "full-access",
|
||||
},
|
||||
);
|
||||
assert.equal((session.threadId ?? "").length > 0, true);
|
||||
@@ -259,7 +251,7 @@ it.effect("rolls back provider conversation state only", () =>
|
||||
yield* runTurn({
|
||||
provider,
|
||||
harness: fixture.harness,
|
||||
threadId: session.threadId,
|
||||
sessionId: session.sessionId,
|
||||
userText: "turn 1",
|
||||
response: {
|
||||
events: codexTurnToolFixture,
|
||||
@@ -271,7 +263,7 @@ it.effect("rolls back provider conversation state only", () =>
|
||||
yield* runTurn({
|
||||
provider,
|
||||
harness: fixture.harness,
|
||||
threadId: session.threadId,
|
||||
sessionId: session.sessionId,
|
||||
userText: "turn 2 approval",
|
||||
response: {
|
||||
events: codexTurnApprovalFixture,
|
||||
@@ -281,11 +273,11 @@ it.effect("rolls back provider conversation state only", () =>
|
||||
});
|
||||
|
||||
yield* provider.rollbackConversation({
|
||||
threadId: session.threadId,
|
||||
sessionId: session.sessionId,
|
||||
numTurns: 1,
|
||||
});
|
||||
|
||||
const rollbackCalls = fixture.harness.getRollbackCalls(session.threadId);
|
||||
const rollbackCalls = fixture.harness.getRollbackCalls(session.sessionId);
|
||||
assert.deepEqual(rollbackCalls, [1]);
|
||||
|
||||
const readme = yield* readFileString(join(fixture.cwd, "README.md"));
|
||||
|
||||
@@ -1,11 +1,6 @@
|
||||
{
|
||||
"name": "t3",
|
||||
"version": "0.0.0-alpha.20",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "https://github.com/pingdotgg/t3code",
|
||||
"directory": "apps/server"
|
||||
},
|
||||
"version": "0.0.0-alpha.18",
|
||||
"bin": {
|
||||
"t3": "./dist/index.mjs"
|
||||
},
|
||||
|
||||
@@ -111,8 +111,6 @@ const publishCmd = Command.make(
|
||||
const version = Option.getOrElse(config.appVersion, () => serverPackageJson.version);
|
||||
const pkg = {
|
||||
name: serverPackageJson.name,
|
||||
repository: serverPackageJson.repository,
|
||||
bin: serverPackageJson.bin,
|
||||
type: serverPackageJson.type,
|
||||
version,
|
||||
engines: serverPackageJson.engines,
|
||||
|
||||
@@ -1,66 +0,0 @@
|
||||
import * as NodeRuntime from "@effect/platform-node/NodeRuntime";
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import path from "node:path";
|
||||
|
||||
import { Effect, FileSystem, Layer, Logger, ServiceMap } from "effect";
|
||||
|
||||
import { makeEventNdjsonLogger } from "../src/provider/Layers/EventNdjsonLogger.ts";
|
||||
|
||||
class LogDir extends ServiceMap.Service<LogDir, string>()("t3/scripts/logger-scope-repro/LogDir") {}
|
||||
|
||||
const main = Effect.gen(function* () {
|
||||
const logdir = yield* LogDir;
|
||||
const providerLogPath = path.join(logdir, "provider");
|
||||
|
||||
yield* Effect.logInfo(`providerLogPath=${providerLogPath}`);
|
||||
|
||||
const providerLogger = yield* makeEventNdjsonLogger(providerLogPath, {
|
||||
stream: "native",
|
||||
batchWindowMs: 10,
|
||||
});
|
||||
|
||||
yield* Effect.logInfo("before provider write");
|
||||
|
||||
if (providerLogger) {
|
||||
yield* providerLogger.write(
|
||||
{
|
||||
kind: "probe",
|
||||
message: "provider-only event",
|
||||
},
|
||||
"thread-123" as never,
|
||||
);
|
||||
}
|
||||
|
||||
yield* Effect.logInfo("after provider write");
|
||||
yield* Effect.sleep("50 millis");
|
||||
|
||||
if (providerLogger) {
|
||||
yield* providerLogger.close();
|
||||
}
|
||||
yield* Effect.logInfo("after provider close");
|
||||
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const logContents = yield* fs
|
||||
.readDirectory(logdir, { recursive: true })
|
||||
.pipe(
|
||||
Effect.flatMap((entries) =>
|
||||
Effect.all(entries.map((entry) => fs.readFileString(path.join(logdir, entry)))),
|
||||
),
|
||||
);
|
||||
yield* Effect.logInfo(`logContents=${logContents}`);
|
||||
});
|
||||
|
||||
Effect.gen(function* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const logdir = path.join(process.cwd(), "logtest");
|
||||
yield* fs.makeDirectory(logdir);
|
||||
|
||||
const fileLogger = yield* Logger.formatSimple.pipe(
|
||||
Logger.toFile(path.join(logdir, "global.log")),
|
||||
);
|
||||
const dualLogger = Logger.layer([fileLogger, Logger.consolePretty()]);
|
||||
|
||||
const mainLayer = Layer.mergeAll(dualLogger, Layer.succeed(LogDir, logdir));
|
||||
|
||||
yield* main.pipe(Effect.provide(mainLayer));
|
||||
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer), NodeRuntime.runMain);
|
||||
@@ -1,6 +1,5 @@
|
||||
import {
|
||||
CheckpointRef,
|
||||
DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
ProjectId,
|
||||
ThreadId,
|
||||
TurnId,
|
||||
@@ -44,8 +43,6 @@ function makeSnapshot(input: {
|
||||
projectId: input.projectId,
|
||||
title: "Thread",
|
||||
model: "gpt-5-codex",
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "full-access",
|
||||
branch: null,
|
||||
worktreePath: input.worktreePath,
|
||||
latestTurn: {
|
||||
@@ -61,7 +58,6 @@ function makeSnapshot(input: {
|
||||
deletedAt: null,
|
||||
messages: [],
|
||||
activities: [],
|
||||
proposedPlans: [],
|
||||
checkpoints: [
|
||||
{
|
||||
turnId: TurnId.makeUnsafe("turn-1"),
|
||||
|
||||
@@ -1,30 +1,50 @@
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
import { ApprovalRequestId, ThreadId } from "@t3tools/contracts";
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { Cause } from "effect";
|
||||
import { ManagedRuntime, ServiceMap } from "effect";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { ProviderSessionId } from "@t3tools/contracts";
|
||||
|
||||
import {
|
||||
buildCodexInitializeParams,
|
||||
CODEX_PLAN_MODE_DEVELOPER_INSTRUCTIONS,
|
||||
CodexAppServerManager,
|
||||
classifyCodexStderrLine,
|
||||
isRecoverableThreadResumeError,
|
||||
messageFromCodexProcessCause,
|
||||
normalizeCodexModelSlug,
|
||||
} from "./codexAppServerManager";
|
||||
|
||||
const asThreadId = (value: string): ThreadId => ThreadId.makeUnsafe(value);
|
||||
const asSessionId = (value: string): ProviderSessionId => ProviderSessionId.makeUnsafe(value);
|
||||
|
||||
let runtime: ManagedRuntime.ManagedRuntime<NodeServices.NodeServices, never> | null = null;
|
||||
let services: ServiceMap.ServiceMap<NodeServices.NodeServices> | null = null;
|
||||
|
||||
beforeEach(async () => {
|
||||
runtime = ManagedRuntime.make(NodeServices.layer);
|
||||
services = await runtime.services();
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
services = null;
|
||||
if (runtime) {
|
||||
await runtime.dispose();
|
||||
}
|
||||
runtime = null;
|
||||
});
|
||||
|
||||
function createManager() {
|
||||
if (!services) {
|
||||
throw new Error("Test runtime services not initialized.");
|
||||
}
|
||||
return new CodexAppServerManager(services);
|
||||
}
|
||||
|
||||
function createSendTurnHarness() {
|
||||
const manager = new CodexAppServerManager();
|
||||
const manager = createManager();
|
||||
const context = {
|
||||
session: {
|
||||
sessionId: "sess_1",
|
||||
provider: "codex",
|
||||
status: "ready",
|
||||
threadId: "thread_1",
|
||||
resumeCursor: { threadId: "thread_1" },
|
||||
createdAt: "2026-02-10T00:00:00.000Z",
|
||||
updatedAt: "2026-02-10T00:00:00.000Z",
|
||||
},
|
||||
@@ -54,14 +74,13 @@ function createSendTurnHarness() {
|
||||
}
|
||||
|
||||
function createThreadControlHarness() {
|
||||
const manager = new CodexAppServerManager();
|
||||
const manager = createManager();
|
||||
const context = {
|
||||
session: {
|
||||
sessionId: "sess_1",
|
||||
provider: "codex",
|
||||
status: "ready",
|
||||
threadId: "thread_1",
|
||||
resumeCursor: { threadId: "thread_1" },
|
||||
createdAt: "2026-02-10T00:00:00.000Z",
|
||||
updatedAt: "2026-02-10T00:00:00.000Z",
|
||||
},
|
||||
@@ -84,46 +103,6 @@ function createThreadControlHarness() {
|
||||
return { manager, context, requireSession, sendRequest, updateSession };
|
||||
}
|
||||
|
||||
function createPendingUserInputHarness() {
|
||||
const manager = new CodexAppServerManager();
|
||||
const context = {
|
||||
session: {
|
||||
sessionId: "sess_1",
|
||||
provider: "codex",
|
||||
status: "ready",
|
||||
threadId: "thread_1",
|
||||
resumeCursor: { threadId: "thread_1" },
|
||||
createdAt: "2026-02-10T00:00:00.000Z",
|
||||
updatedAt: "2026-02-10T00:00:00.000Z",
|
||||
},
|
||||
pendingUserInputs: new Map([
|
||||
[
|
||||
ApprovalRequestId.makeUnsafe("req-user-input-1"),
|
||||
{
|
||||
requestId: ApprovalRequestId.makeUnsafe("req-user-input-1"),
|
||||
jsonRpcId: 42,
|
||||
threadId: asThreadId("thread_1"),
|
||||
},
|
||||
],
|
||||
]),
|
||||
};
|
||||
|
||||
const requireSession = vi
|
||||
.spyOn(
|
||||
manager as unknown as { requireSession: (sessionId: string) => unknown },
|
||||
"requireSession",
|
||||
)
|
||||
.mockReturnValue(context);
|
||||
const writeMessage = vi
|
||||
.spyOn(manager as unknown as { writeMessage: (...args: unknown[]) => void }, "writeMessage")
|
||||
.mockImplementation(() => {});
|
||||
const emitEvent = vi
|
||||
.spyOn(manager as unknown as { emitEvent: (...args: unknown[]) => void }, "emitEvent")
|
||||
.mockImplementation(() => {});
|
||||
|
||||
return { manager, context, requireSession, writeMessage, emitEvent };
|
||||
}
|
||||
|
||||
describe("classifyCodexStderrLine", () => {
|
||||
it("ignores empty lines", () => {
|
||||
expect(classifyCodexStderrLine(" ")).toBeNull();
|
||||
@@ -194,22 +173,15 @@ describe("isRecoverableThreadResumeError", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("startSession", () => {
|
||||
it("enables Codex experimental api capabilities during initialize", () => {
|
||||
expect(buildCodexInitializeParams()).toEqual({
|
||||
clientInfo: {
|
||||
name: "t3code_desktop",
|
||||
title: "T3 Code Desktop",
|
||||
version: "0.1.0",
|
||||
},
|
||||
capabilities: {
|
||||
experimentalApi: true,
|
||||
},
|
||||
});
|
||||
describe("messageFromCodexProcessCause", () => {
|
||||
it("extracts the underlying error message from an effect cause", () => {
|
||||
expect(messageFromCodexProcessCause(Cause.fail(new Error("boom")))).toBe("boom");
|
||||
});
|
||||
});
|
||||
|
||||
describe("startSession", () => {
|
||||
it("emits session/startFailed when resolving cwd throws before process launch", async () => {
|
||||
const manager = new CodexAppServerManager();
|
||||
const manager = createManager();
|
||||
const events: Array<{ method: string; kind: string; message?: string }> = [];
|
||||
manager.on("event", (event) => {
|
||||
events.push({
|
||||
@@ -225,9 +197,7 @@ describe("startSession", () => {
|
||||
try {
|
||||
await expect(
|
||||
manager.startSession({
|
||||
threadId: asThreadId("thread-1"),
|
||||
provider: "codex",
|
||||
runtimeMode: "full-access",
|
||||
}),
|
||||
).rejects.toThrow("cwd missing");
|
||||
expect(events).toHaveLength(1);
|
||||
@@ -249,7 +219,7 @@ describe("sendTurn", () => {
|
||||
createSendTurnHarness();
|
||||
|
||||
const result = await manager.sendTurn({
|
||||
threadId: asThreadId("thread_1"),
|
||||
sessionId: asSessionId("sess_1"),
|
||||
input: "Inspect this image",
|
||||
attachments: [
|
||||
{
|
||||
@@ -259,15 +229,16 @@ describe("sendTurn", () => {
|
||||
],
|
||||
model: "gpt-5.3",
|
||||
effort: "high",
|
||||
serviceTier: "fast",
|
||||
});
|
||||
|
||||
expect(result).toEqual({
|
||||
threadId: "thread_1",
|
||||
turnId: "turn_1",
|
||||
resumeCursor: { threadId: "thread_1" },
|
||||
resumeCursor: {
|
||||
threadId: "thread_1",
|
||||
},
|
||||
});
|
||||
expect(requireSession).toHaveBeenCalledWith("thread_1");
|
||||
expect(requireSession).toHaveBeenCalledWith("sess_1");
|
||||
expect(sendRequest).toHaveBeenCalledWith(context, "turn/start", {
|
||||
threadId: "thread_1",
|
||||
input: [
|
||||
@@ -283,12 +254,13 @@ describe("sendTurn", () => {
|
||||
],
|
||||
model: "gpt-5.3-codex",
|
||||
effort: "high",
|
||||
serviceTier: "fast",
|
||||
});
|
||||
expect(updateSession).toHaveBeenCalledWith(context, {
|
||||
status: "running",
|
||||
activeTurnId: "turn_1",
|
||||
resumeCursor: { threadId: "thread_1" },
|
||||
resumeCursor: {
|
||||
threadId: "thread_1",
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
@@ -296,7 +268,7 @@ describe("sendTurn", () => {
|
||||
const { manager, context, sendRequest } = createSendTurnHarness();
|
||||
|
||||
await manager.sendTurn({
|
||||
threadId: asThreadId("thread_1"),
|
||||
sessionId: asSessionId("sess_1"),
|
||||
attachments: [
|
||||
{
|
||||
type: "image",
|
||||
@@ -316,42 +288,12 @@ describe("sendTurn", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it("passes Codex plan mode as a collaboration preset on turn/start", async () => {
|
||||
const { manager, context, sendRequest } = createSendTurnHarness();
|
||||
|
||||
await manager.sendTurn({
|
||||
threadId: asThreadId("thread_1"),
|
||||
input: "Plan the work",
|
||||
interactionMode: "plan",
|
||||
});
|
||||
|
||||
expect(sendRequest).toHaveBeenCalledWith(context, "turn/start", {
|
||||
threadId: "thread_1",
|
||||
input: [
|
||||
{
|
||||
type: "text",
|
||||
text: "Plan the work",
|
||||
text_elements: [],
|
||||
},
|
||||
],
|
||||
model: "gpt-5.3-codex",
|
||||
collaborationMode: {
|
||||
mode: "plan",
|
||||
settings: {
|
||||
model: "gpt-5.3-codex",
|
||||
reasoning_effort: "medium",
|
||||
developer_instructions: CODEX_PLAN_MODE_DEVELOPER_INSTRUCTIONS,
|
||||
},
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it("rejects empty turn input", async () => {
|
||||
const { manager } = createSendTurnHarness();
|
||||
|
||||
await expect(
|
||||
manager.sendTurn({
|
||||
threadId: asThreadId("thread_1"),
|
||||
sessionId: asSessionId("sess_1"),
|
||||
}),
|
||||
).rejects.toThrow("Turn input must include text or attachments.");
|
||||
});
|
||||
@@ -372,9 +314,9 @@ describe("thread checkpoint control", () => {
|
||||
},
|
||||
});
|
||||
|
||||
const result = await manager.readThread(asThreadId("thread_1"));
|
||||
const result = await manager.readThread(asSessionId("sess_1"));
|
||||
|
||||
expect(requireSession).toHaveBeenCalledWith("thread_1");
|
||||
expect(requireSession).toHaveBeenCalledWith("sess_1");
|
||||
expect(sendRequest).toHaveBeenCalledWith(context, "thread/read", {
|
||||
threadId: "thread_1",
|
||||
includeTurns: true,
|
||||
@@ -402,7 +344,7 @@ describe("thread checkpoint control", () => {
|
||||
],
|
||||
});
|
||||
|
||||
const result = await manager.readThread(asThreadId("thread_1"));
|
||||
const result = await manager.readThread(asSessionId("sess_1"));
|
||||
|
||||
expect(sendRequest).toHaveBeenCalledWith(context, "thread/read", {
|
||||
threadId: "thread_1",
|
||||
@@ -428,7 +370,7 @@ describe("thread checkpoint control", () => {
|
||||
},
|
||||
});
|
||||
|
||||
const result = await manager.rollbackThread(asThreadId("thread_1"), 2);
|
||||
const result = await manager.rollbackThread(asSessionId("sess_1"), 2);
|
||||
|
||||
expect(sendRequest).toHaveBeenCalledWith(context, "thread/rollback", {
|
||||
threadId: "thread_1",
|
||||
@@ -444,129 +386,3 @@ describe("thread checkpoint control", () => {
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("respondToUserInput", () => {
|
||||
it("serializes canonical answers to Codex native answer objects", async () => {
|
||||
const { manager, context, requireSession, writeMessage, emitEvent } =
|
||||
createPendingUserInputHarness();
|
||||
|
||||
await manager.respondToUserInput(
|
||||
asThreadId("thread_1"),
|
||||
ApprovalRequestId.makeUnsafe("req-user-input-1"),
|
||||
{
|
||||
scope: "All request methods",
|
||||
compat: "Keep current envelope",
|
||||
},
|
||||
);
|
||||
|
||||
expect(requireSession).toHaveBeenCalledWith("thread_1");
|
||||
expect(writeMessage).toHaveBeenCalledWith(context, {
|
||||
id: 42,
|
||||
result: {
|
||||
answers: {
|
||||
scope: { answers: ["All request methods"] },
|
||||
compat: { answers: ["Keep current envelope"] },
|
||||
},
|
||||
},
|
||||
});
|
||||
expect(emitEvent).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
method: "item/tool/requestUserInput/answered",
|
||||
payload: {
|
||||
requestId: "req-user-input-1",
|
||||
answers: {
|
||||
scope: { answers: ["All request methods"] },
|
||||
compat: { answers: ["Keep current envelope"] },
|
||||
},
|
||||
},
|
||||
}),
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe.skipIf(!process.env.CODEX_BINARY_PATH)("startSession live Codex resume", () => {
|
||||
it(
|
||||
"keeps prior thread history when resuming with a changed runtime mode",
|
||||
async () => {
|
||||
const workspaceDir = mkdtempSync(path.join(os.tmpdir(), "codex-live-resume-"));
|
||||
writeFileSync(path.join(workspaceDir, "README.md"), "hello\n", "utf8");
|
||||
|
||||
const manager = new CodexAppServerManager();
|
||||
|
||||
try {
|
||||
const firstSession = await manager.startSession({
|
||||
threadId: asThreadId("thread-live"),
|
||||
provider: "codex",
|
||||
cwd: workspaceDir,
|
||||
runtimeMode: "full-access",
|
||||
providerOptions: {
|
||||
codex: {
|
||||
...(process.env.CODEX_BINARY_PATH
|
||||
? { binaryPath: process.env.CODEX_BINARY_PATH }
|
||||
: {}),
|
||||
...(process.env.CODEX_HOME_PATH
|
||||
? { homePath: process.env.CODEX_HOME_PATH }
|
||||
: {}),
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const firstTurn = await manager.sendTurn({
|
||||
threadId: firstSession.threadId,
|
||||
input: `Reply with exactly the word ALPHA ${randomUUID()}`,
|
||||
});
|
||||
|
||||
expect(firstTurn.threadId).toBe(firstSession.threadId);
|
||||
|
||||
await vi.waitFor(async () => {
|
||||
const snapshot = await manager.readThread(firstSession.threadId);
|
||||
expect(snapshot.turns.length).toBeGreaterThan(0);
|
||||
}, { timeout: 120_000, interval: 1_000 });
|
||||
|
||||
const firstSnapshot = await manager.readThread(firstSession.threadId);
|
||||
const originalThreadId = firstSnapshot.threadId;
|
||||
const originalTurnCount = firstSnapshot.turns.length;
|
||||
|
||||
manager.stopSession(firstSession.threadId);
|
||||
|
||||
const resumedSession = await manager.startSession({
|
||||
threadId: firstSession.threadId,
|
||||
provider: "codex",
|
||||
cwd: workspaceDir,
|
||||
runtimeMode: "approval-required",
|
||||
resumeCursor: firstSession.resumeCursor,
|
||||
providerOptions: {
|
||||
codex: {
|
||||
...(process.env.CODEX_BINARY_PATH
|
||||
? { binaryPath: process.env.CODEX_BINARY_PATH }
|
||||
: {}),
|
||||
...(process.env.CODEX_HOME_PATH
|
||||
? { homePath: process.env.CODEX_HOME_PATH }
|
||||
: {}),
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
expect(resumedSession.threadId).toBe(originalThreadId);
|
||||
|
||||
const resumedSnapshotBeforeTurn = await manager.readThread(resumedSession.threadId);
|
||||
expect(resumedSnapshotBeforeTurn.threadId).toBe(originalThreadId);
|
||||
expect(resumedSnapshotBeforeTurn.turns.length).toBeGreaterThanOrEqual(originalTurnCount);
|
||||
|
||||
await manager.sendTurn({
|
||||
threadId: resumedSession.threadId,
|
||||
input: `Reply with exactly the word BETA ${randomUUID()}`,
|
||||
});
|
||||
|
||||
await vi.waitFor(async () => {
|
||||
const snapshot = await manager.readThread(resumedSession.threadId);
|
||||
expect(snapshot.turns.length).toBeGreaterThan(originalTurnCount);
|
||||
}, { timeout: 120_000, interval: 1_000 });
|
||||
} finally {
|
||||
manager.stopAll();
|
||||
rmSync(workspaceDir, { recursive: true, force: true });
|
||||
}
|
||||
},
|
||||
180_000,
|
||||
);
|
||||
});
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,12 +1,12 @@
|
||||
import { randomUUID } from "node:crypto";
|
||||
|
||||
import { Effect, FileSystem, Layer, Option, Path, Schema, Stream } from "effect";
|
||||
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
|
||||
import { Effect, FileSystem, Layer, Path, Schema } from "effect";
|
||||
|
||||
import { sanitizeBranchFragment, sanitizeFeatureBranchName } from "@t3tools/shared/git";
|
||||
|
||||
import { resolveAttachmentPath } from "../../attachmentStore.ts";
|
||||
import { ServerConfig } from "../../config.ts";
|
||||
import { runProcess } from "../../processRunner.ts";
|
||||
import { TextGenerationError } from "../Errors.ts";
|
||||
import {
|
||||
type BranchNameGenerationInput,
|
||||
@@ -98,31 +98,12 @@ function sanitizePrTitle(raw: string): string {
|
||||
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);
|
||||
|
||||
type MaterializedImageAttachments = {
|
||||
readonly imagePaths: ReadonlyArray<string>;
|
||||
};
|
||||
|
||||
const readStreamAsString = <E>(
|
||||
operation: string,
|
||||
stream: Stream.Stream<Uint8Array, E>,
|
||||
): Effect.Effect<string, TextGenerationError> =>
|
||||
Effect.gen(function* () {
|
||||
let text = "";
|
||||
yield* Stream.runForEach(stream, (chunk) =>
|
||||
Effect.sync(() => {
|
||||
text += Buffer.from(chunk).toString("utf8");
|
||||
}),
|
||||
).pipe(
|
||||
Effect.mapError((cause) =>
|
||||
normalizeCodexError(operation, cause, "Failed to collect process output"),
|
||||
),
|
||||
);
|
||||
return text;
|
||||
});
|
||||
|
||||
const tempDir = process.env.TMPDIR ?? process.env.TEMP ?? process.env.TMP ?? "/tmp";
|
||||
|
||||
const writeTempFile = (
|
||||
@@ -203,68 +184,59 @@ const makeCodexTextGeneration = Effect.gen(function* () {
|
||||
);
|
||||
const outputPath = yield* writeTempFile(operation, "codex-output", "");
|
||||
|
||||
const runCodexCommand = Effect.gen(function* () {
|
||||
const command = ChildProcess.make(
|
||||
"codex",
|
||||
[
|
||||
"exec",
|
||||
"--ephemeral",
|
||||
"-s",
|
||||
"read-only",
|
||||
"--model",
|
||||
CODEX_MODEL,
|
||||
"--config",
|
||||
`model_reasoning_effort="${CODEX_REASONING_EFFORT}"`,
|
||||
"--output-schema",
|
||||
schemaPath,
|
||||
"--output-last-message",
|
||||
outputPath,
|
||||
...imagePaths.flatMap((imagePath) => ["--image", imagePath]),
|
||||
"-",
|
||||
],
|
||||
{
|
||||
cwd,
|
||||
shell: process.platform === "win32",
|
||||
stdin: {
|
||||
stream: Stream.make(new TextEncoder().encode(prompt)),
|
||||
const runCodexCommand = Effect.tryPromise({
|
||||
try: async () => {
|
||||
const result = await runProcess(
|
||||
"codex",
|
||||
[
|
||||
"exec",
|
||||
"--ephemeral",
|
||||
"-s",
|
||||
"read-only",
|
||||
"--model",
|
||||
CODEX_MODEL,
|
||||
"--config",
|
||||
`model_reasoning_effort="${CODEX_REASONING_EFFORT}"`,
|
||||
"--output-schema",
|
||||
schemaPath,
|
||||
"--output-last-message",
|
||||
outputPath,
|
||||
...imagePaths.flatMap((imagePath) => ["--image", imagePath]),
|
||||
"-",
|
||||
],
|
||||
{
|
||||
cwd,
|
||||
stdin: prompt,
|
||||
allowNonZeroExit: true,
|
||||
timeoutMs: CODEX_TIMEOUT_MS,
|
||||
maxBufferBytes: 1_000_000,
|
||||
outputMode: "truncate",
|
||||
},
|
||||
},
|
||||
);
|
||||
|
||||
const child = yield* commandSpawner
|
||||
.spawn(command)
|
||||
.pipe(
|
||||
Effect.mapError((cause) =>
|
||||
normalizeCodexError(operation, cause, "Failed to spawn Codex CLI process"),
|
||||
),
|
||||
);
|
||||
|
||||
const [stdout, stderr, exitCode] = yield* Effect.all(
|
||||
[
|
||||
readStreamAsString(operation, child.stdout),
|
||||
readStreamAsString(operation, child.stderr),
|
||||
child.exitCode.pipe(
|
||||
Effect.map((value) => Number(value)),
|
||||
Effect.mapError((cause) =>
|
||||
normalizeCodexError(operation, cause, "Failed to read Codex CLI exit code"),
|
||||
),
|
||||
),
|
||||
],
|
||||
{ concurrency: "unbounded" },
|
||||
);
|
||||
if (result.timedOut) {
|
||||
throw new TextGenerationError({ operation, detail: "Codex CLI request timed out." });
|
||||
}
|
||||
|
||||
if (exitCode !== 0) {
|
||||
const stderrDetail = stderr.trim();
|
||||
const stdoutDetail = stdout.trim();
|
||||
const detail = stderrDetail.length > 0 ? stderrDetail : stdoutDetail;
|
||||
return yield* new TextGenerationError({
|
||||
operation,
|
||||
detail:
|
||||
detail.length > 0
|
||||
? `Codex CLI command failed: ${detail}`
|
||||
: `Codex CLI command failed with code ${exitCode}.`,
|
||||
});
|
||||
}
|
||||
const stdout = result.stdout;
|
||||
const stderr = result.stderr;
|
||||
const exitCode = result.code ?? 0;
|
||||
|
||||
if (exitCode !== 0) {
|
||||
const stderrDetail = stderr.trim();
|
||||
const stdoutDetail = stdout.trim();
|
||||
const detail = stderrDetail.length > 0 ? stderrDetail : stdoutDetail;
|
||||
throw new TextGenerationError({
|
||||
operation,
|
||||
detail:
|
||||
detail.length > 0
|
||||
? `Codex CLI command failed: ${detail}`
|
||||
: `Codex CLI command failed with code ${exitCode}.`,
|
||||
});
|
||||
}
|
||||
},
|
||||
catch: (error) =>
|
||||
normalizeCodexError(operation, error, "Failed to execute Codex CLI process"),
|
||||
});
|
||||
|
||||
const cleanup = Effect.all(
|
||||
@@ -275,19 +247,7 @@ const makeCodexTextGeneration = Effect.gen(function* () {
|
||||
).pipe(Effect.asVoid);
|
||||
|
||||
return yield* Effect.gen(function* () {
|
||||
yield* runCodexCommand.pipe(
|
||||
Effect.scoped,
|
||||
Effect.timeoutOption(CODEX_TIMEOUT_MS),
|
||||
Effect.flatMap(
|
||||
Option.match({
|
||||
onNone: () =>
|
||||
Effect.fail(
|
||||
new TextGenerationError({ operation, detail: "Codex CLI request timed out." }),
|
||||
),
|
||||
onSome: () => Effect.void,
|
||||
}),
|
||||
),
|
||||
);
|
||||
yield* runCodexCommand;
|
||||
|
||||
return yield* fileSystem.readFileString(outputPath).pipe(
|
||||
Effect.mapError(
|
||||
|
||||
@@ -3,7 +3,7 @@ import { it, assert } from "@effect/vitest";
|
||||
import { Effect, Layer, Schema } from "effect";
|
||||
|
||||
import { GitCommandError } from "../Errors.ts";
|
||||
import { GitServiceLive } from "./GitService.ts";
|
||||
import { GitServiceLive, normalizeGitProcessResult } from "./GitService.ts";
|
||||
import { GitService } from "../Services/GitService.ts";
|
||||
|
||||
const layer = it.layer(Layer.provideMerge(GitServiceLive, NodeServices.layer));
|
||||
@@ -56,4 +56,31 @@ layer("GitServiceLive", (it) => {
|
||||
}
|
||||
}),
|
||||
);
|
||||
|
||||
it("normalizeGitProcessResult fails when git exits without a code", () => {
|
||||
try {
|
||||
void normalizeGitProcessResult(
|
||||
{
|
||||
operation: "GitProcess.test.signal",
|
||||
cwd: process.cwd(),
|
||||
args: ["status"],
|
||||
},
|
||||
{},
|
||||
{
|
||||
code: null,
|
||||
signal: "SIGTERM",
|
||||
stdout: "",
|
||||
stderr: "",
|
||||
timedOut: false,
|
||||
},
|
||||
);
|
||||
assert.fail("Expected normalizeGitProcessResult to throw.");
|
||||
} catch (error) {
|
||||
assert.equal(Schema.is(GitCommandError)(error), true);
|
||||
if (!Schema.is(GitCommandError)(error)) {
|
||||
return;
|
||||
}
|
||||
assert.equal(error.detail, "git status terminated by signal SIGTERM.");
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -1,13 +1,13 @@
|
||||
/**
|
||||
* Git process helpers - Effect-native git execution with typed errors.
|
||||
* Git process helpers - runtime-aware git execution with typed errors.
|
||||
*
|
||||
* Centralizes child-process git invocation for server modules. This module
|
||||
* only executes git commands and reports structured failures.
|
||||
*
|
||||
* @module GitServiceLive
|
||||
*/
|
||||
import { Effect, Layer, Option, Schema, Stream } from "effect";
|
||||
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
|
||||
import { Effect, Layer, Schema } from "effect";
|
||||
import { runProcess } from "../../processRunner.ts";
|
||||
import { GitCommandError } from "../Errors.ts";
|
||||
import {
|
||||
ExecuteGitInput,
|
||||
@@ -39,37 +39,60 @@ function toGitCommandError(
|
||||
});
|
||||
}
|
||||
|
||||
const collectOutput = Effect.fn(function* <E>(
|
||||
input: Pick<ExecuteGitInput, "operation" | "cwd" | "args">,
|
||||
stream: Stream.Stream<Uint8Array, E>,
|
||||
maxOutputBytes: number,
|
||||
): Effect.fn.Return<string, GitCommandError> {
|
||||
const decoder = new TextDecoder();
|
||||
let bytes = 0;
|
||||
let text = "";
|
||||
export function normalizeGitProcessResult(
|
||||
commandInput: Pick<ExecuteGitInput, "operation" | "cwd" | "args">,
|
||||
input: Pick<ExecuteGitInput, "allowNonZeroExit">,
|
||||
result: {
|
||||
readonly stdout: string;
|
||||
readonly stderr: string;
|
||||
readonly code: number | null;
|
||||
readonly signal: NodeJS.Signals | null;
|
||||
readonly timedOut: boolean;
|
||||
},
|
||||
): ExecuteGitResult {
|
||||
if (result.timedOut) {
|
||||
throw new GitCommandError({
|
||||
operation: commandInput.operation,
|
||||
command: quoteGitCommand(commandInput.args),
|
||||
cwd: commandInput.cwd,
|
||||
detail: `${quoteGitCommand(commandInput.args)} timed out.`,
|
||||
});
|
||||
}
|
||||
|
||||
yield* Stream.runForEach(stream, (chunk) =>
|
||||
Effect.gen(function* () {
|
||||
bytes += chunk.byteLength;
|
||||
if (bytes > maxOutputBytes) {
|
||||
return yield* new GitCommandError({
|
||||
operation: input.operation,
|
||||
command: quoteGitCommand(input.args),
|
||||
cwd: input.cwd,
|
||||
detail: `${quoteGitCommand(input.args)} output exceeded ${maxOutputBytes} bytes and was truncated.`,
|
||||
});
|
||||
}
|
||||
text += decoder.decode(chunk, { stream: true });
|
||||
}),
|
||||
).pipe(Effect.mapError(toGitCommandError(input, "output stream failed.")));
|
||||
if (result.code === null) {
|
||||
throw new GitCommandError({
|
||||
operation: commandInput.operation,
|
||||
command: quoteGitCommand(commandInput.args),
|
||||
cwd: commandInput.cwd,
|
||||
detail:
|
||||
result.signal !== null
|
||||
? `${quoteGitCommand(commandInput.args)} terminated by signal ${result.signal}.`
|
||||
: `${quoteGitCommand(commandInput.args)} terminated before reporting an exit code.`,
|
||||
});
|
||||
}
|
||||
|
||||
text += decoder.decode();
|
||||
return text;
|
||||
});
|
||||
const exitCode = result.code;
|
||||
if (!input.allowNonZeroExit && exitCode !== 0) {
|
||||
const trimmedStderr = result.stderr.trim();
|
||||
throw new GitCommandError({
|
||||
operation: commandInput.operation,
|
||||
command: quoteGitCommand(commandInput.args),
|
||||
cwd: commandInput.cwd,
|
||||
detail:
|
||||
trimmedStderr.length > 0
|
||||
? `${quoteGitCommand(commandInput.args)} failed: ${trimmedStderr}`
|
||||
: `${quoteGitCommand(commandInput.args)} failed with code ${exitCode}.`,
|
||||
});
|
||||
}
|
||||
|
||||
const makeGitService = Effect.gen(function* () {
|
||||
const commandSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||
return {
|
||||
code: exitCode,
|
||||
stdout: result.stdout,
|
||||
stderr: result.stderr,
|
||||
} satisfies ExecuteGitResult;
|
||||
}
|
||||
|
||||
const makeGitService = Effect.sync(() => {
|
||||
const execute: GitServiceShape["execute"] = Effect.fnUntraced(function* (input) {
|
||||
const commandInput = {
|
||||
...input,
|
||||
@@ -78,62 +101,21 @@ const makeGitService = Effect.gen(function* () {
|
||||
const timeoutMs = input.timeoutMs ?? DEFAULT_TIMEOUT_MS;
|
||||
const maxOutputBytes = input.maxOutputBytes ?? DEFAULT_MAX_OUTPUT_BYTES;
|
||||
|
||||
const commandEffect = Effect.gen(function* () {
|
||||
const child = yield* commandSpawner
|
||||
.spawn(
|
||||
ChildProcess.make("git", commandInput.args, {
|
||||
cwd: commandInput.cwd,
|
||||
...(input.env ? { env: input.env } : {}),
|
||||
}),
|
||||
)
|
||||
.pipe(Effect.mapError(toGitCommandError(commandInput, "failed to spawn.")));
|
||||
|
||||
const [stdout, stderr, exitCode] = yield* Effect.all(
|
||||
[
|
||||
collectOutput(commandInput, child.stdout, maxOutputBytes),
|
||||
collectOutput(commandInput, child.stderr, maxOutputBytes),
|
||||
child.exitCode.pipe(
|
||||
Effect.map((value) => Number(value)),
|
||||
Effect.mapError(toGitCommandError(commandInput, "failed to report exit code.")),
|
||||
),
|
||||
],
|
||||
{ concurrency: "unbounded" },
|
||||
);
|
||||
|
||||
if (!input.allowNonZeroExit && exitCode !== 0) {
|
||||
const trimmedStderr = stderr.trim();
|
||||
return yield* new GitCommandError({
|
||||
operation: commandInput.operation,
|
||||
command: quoteGitCommand(commandInput.args),
|
||||
return yield* Effect.tryPromise({
|
||||
try: async () => {
|
||||
const result = await runProcess("git", commandInput.args, {
|
||||
cwd: commandInput.cwd,
|
||||
detail:
|
||||
trimmedStderr.length > 0
|
||||
? `${quoteGitCommand(commandInput.args)} failed: ${trimmedStderr}`
|
||||
: `${quoteGitCommand(commandInput.args)} failed with code ${exitCode}.`,
|
||||
...(input.env ? { env: input.env } : {}),
|
||||
timeoutMs,
|
||||
allowNonZeroExit: true,
|
||||
maxBufferBytes: maxOutputBytes,
|
||||
outputMode: "error",
|
||||
});
|
||||
}
|
||||
|
||||
return { code: exitCode, stdout, stderr } satisfies ExecuteGitResult;
|
||||
return normalizeGitProcessResult(commandInput, input, result);
|
||||
},
|
||||
catch: toGitCommandError(commandInput, "failed to run."),
|
||||
});
|
||||
|
||||
return yield* commandEffect.pipe(
|
||||
Effect.scoped,
|
||||
Effect.timeoutOption(timeoutMs),
|
||||
Effect.flatMap((result) =>
|
||||
Option.match(result, {
|
||||
onNone: () =>
|
||||
Effect.fail(
|
||||
new GitCommandError({
|
||||
operation: commandInput.operation,
|
||||
command: quoteGitCommand(commandInput.args),
|
||||
cwd: commandInput.cwd,
|
||||
detail: `${quoteGitCommand(commandInput.args)} timed out.`,
|
||||
}),
|
||||
),
|
||||
onSome: Effect.succeed,
|
||||
}),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
return {
|
||||
|
||||
@@ -77,7 +77,7 @@ beforeEach(() => {
|
||||
findAvailablePort.mockImplementation((preferred: number) => Effect.succeed(preferred));
|
||||
});
|
||||
|
||||
it.layer(testLayer)("server CLI command", (it) => {
|
||||
it.layer(testLayer)("server cli", (it) => {
|
||||
it.effect("parses all CLI flags and wires scoped start/stop", () =>
|
||||
Effect.gen(function* () {
|
||||
yield* runCli([
|
||||
|
||||
+26
-22
@@ -10,7 +10,6 @@ import { Config, Data, Effect, FileSystem, Layer, Option, Path, Schema, ServiceM
|
||||
import { Command, Flag } from "effect/unstable/cli";
|
||||
import { NetService } from "@t3tools/shared/Net";
|
||||
|
||||
// Dummy comment.
|
||||
import {
|
||||
DEFAULT_PORT,
|
||||
resolveStaticDir,
|
||||
@@ -24,7 +23,6 @@ import * as SqlitePersistence from "./persistence/Layers/Sqlite";
|
||||
import { makeServerProviderLayer, makeServerRuntimeServicesLayer } from "./serverLayers";
|
||||
import { ProviderHealthLive } from "./provider/Layers/ProviderHealth";
|
||||
import { Server } from "./wsServer";
|
||||
import { ServerLoggerLive } from "./serverLogger";
|
||||
|
||||
export class StartupError extends Data.TaggedError("StartupError")<{
|
||||
readonly message: string;
|
||||
@@ -121,9 +119,6 @@ const CliEnvConfig = Config.all({
|
||||
),
|
||||
});
|
||||
|
||||
const resolveBooleanFlag = (flag: Option.Option<boolean>, envValue: boolean) =>
|
||||
Option.getOrElse(Option.filter(flag, Boolean), () => envValue);
|
||||
|
||||
const ServerConfigLive = (input: CliInput) =>
|
||||
Layer.effect(
|
||||
ServerConfig,
|
||||
@@ -155,16 +150,25 @@ const ServerConfigLive = (input: CliInput) =>
|
||||
Option.getOrUndefined(input.stateDir) ?? env.stateDir,
|
||||
);
|
||||
const devUrl = Option.getOrElse(input.devUrl, () => env.devUrl);
|
||||
const noBrowser = resolveBooleanFlag(input.noBrowser, env.noBrowser ?? mode === "desktop");
|
||||
const noBrowser = Option.match(input.noBrowser, {
|
||||
// effect/cli boolean flags parse to `false` when absent; in that case
|
||||
// we still want env/mode fallbacks to apply.
|
||||
onSome: (value) => (value ? true : (env.noBrowser ?? mode === "desktop")),
|
||||
onNone: () => env.noBrowser ?? mode === "desktop",
|
||||
});
|
||||
const authToken = Option.getOrUndefined(input.authToken) ?? env.authToken;
|
||||
const autoBootstrapProjectFromCwd = resolveBooleanFlag(
|
||||
input.autoBootstrapProjectFromCwd,
|
||||
env.autoBootstrapProjectFromCwd ?? mode === "web",
|
||||
);
|
||||
const logWebSocketEvents = resolveBooleanFlag(
|
||||
input.logWebSocketEvents,
|
||||
env.logWebSocketEvents ?? Boolean(devUrl),
|
||||
);
|
||||
const autoBootstrapProjectFromCwd = Option.match(input.autoBootstrapProjectFromCwd, {
|
||||
// effect/cli boolean flags parse to `false` when absent; in that case
|
||||
// we still want env/mode fallbacks to apply.
|
||||
onSome: (value) => (value ? true : (env.autoBootstrapProjectFromCwd ?? mode === "web")),
|
||||
onNone: () => env.autoBootstrapProjectFromCwd ?? mode === "web",
|
||||
});
|
||||
const logWebSocketEvents = Option.match(input.logWebSocketEvents, {
|
||||
// effect/cli boolean flags parse to `false` when absent; in that case
|
||||
// we still want env/dev fallbacks to apply.
|
||||
onSome: (value) => (value ? true : (env.logWebSocketEvents ?? Boolean(devUrl))),
|
||||
onNone: () => env.logWebSocketEvents ?? Boolean(devUrl),
|
||||
});
|
||||
const staticDir = devUrl ? undefined : yield* cliConfig.resolveStaticDir;
|
||||
const { join } = yield* Path.Path;
|
||||
const keybindingsConfigPath = join(stateDir, "keybindings.json");
|
||||
@@ -173,7 +177,7 @@ const ServerConfigLive = (input: CliInput) =>
|
||||
env.host ??
|
||||
(mode === "desktop" ? "127.0.0.1" : undefined);
|
||||
|
||||
const config: ServerConfigShape = {
|
||||
return {
|
||||
mode,
|
||||
port,
|
||||
cwd: cliConfig.cwd,
|
||||
@@ -187,8 +191,6 @@ const ServerConfigLive = (input: CliInput) =>
|
||||
autoBootstrapProjectFromCwd,
|
||||
logWebSocketEvents,
|
||||
} satisfies ServerConfigShape;
|
||||
|
||||
return config;
|
||||
}),
|
||||
);
|
||||
|
||||
@@ -198,7 +200,6 @@ const LayerLive = (input: CliInput) =>
|
||||
Layer.provideMerge(makeServerProviderLayer()),
|
||||
Layer.provideMerge(ProviderHealthLive),
|
||||
Layer.provideMerge(SqlitePersistence.layerConfig),
|
||||
Layer.provideMerge(ServerLoggerLive),
|
||||
Layer.provideMerge(ServerConfigLive(input)),
|
||||
);
|
||||
|
||||
@@ -233,11 +234,14 @@ const makeServerProgram = (input: CliInput) =>
|
||||
config.host && !isWildcardHost(config.host)
|
||||
? `http://${formatHostForUrl(config.host)}:${config.port}`
|
||||
: localUrl;
|
||||
const { authToken, devUrl, ...safeConfig } = config;
|
||||
yield* Effect.logInfo("T3 Code running", {
|
||||
...safeConfig,
|
||||
devUrl: devUrl?.toString(),
|
||||
authEnabled: Boolean(authToken),
|
||||
url: bindUrl,
|
||||
localUrl,
|
||||
bindHost: config.host ?? "default",
|
||||
cwd: config.cwd,
|
||||
mode: config.mode,
|
||||
stateDir: config.stateDir,
|
||||
authEnabled: Boolean(config.authToken),
|
||||
});
|
||||
|
||||
if (!config.noBrowser) {
|
||||
|
||||
+201
-13
@@ -7,6 +7,7 @@ import { assert, describe, it } from "@effect/vitest";
|
||||
import {
|
||||
isCommandAvailable,
|
||||
launchDetached,
|
||||
resolveBrowserLaunch,
|
||||
resolveAvailableEditors,
|
||||
resolveEditorLaunch,
|
||||
} from "./open";
|
||||
@@ -18,7 +19,7 @@ describe("resolveEditorLaunch", () => {
|
||||
Effect.gen(function* () {
|
||||
const cursorLaunch = yield* resolveEditorLaunch(
|
||||
{ cwd: "/tmp/workspace", editor: "cursor" },
|
||||
"darwin",
|
||||
{ platform: "darwin" },
|
||||
);
|
||||
assert.deepEqual(cursorLaunch, {
|
||||
command: "cursor",
|
||||
@@ -27,7 +28,7 @@ describe("resolveEditorLaunch", () => {
|
||||
|
||||
const vscodeLaunch = yield* resolveEditorLaunch(
|
||||
{ cwd: "/tmp/workspace", editor: "vscode" },
|
||||
"darwin",
|
||||
{ platform: "darwin" },
|
||||
);
|
||||
assert.deepEqual(vscodeLaunch, {
|
||||
command: "code",
|
||||
@@ -36,7 +37,7 @@ describe("resolveEditorLaunch", () => {
|
||||
|
||||
const zedLaunch = yield* resolveEditorLaunch(
|
||||
{ cwd: "/tmp/workspace", editor: "zed" },
|
||||
"darwin",
|
||||
{ platform: "darwin" },
|
||||
);
|
||||
assert.deepEqual(zedLaunch, {
|
||||
command: "zed",
|
||||
@@ -49,7 +50,7 @@ describe("resolveEditorLaunch", () => {
|
||||
Effect.gen(function* () {
|
||||
const lineOnly = yield* resolveEditorLaunch(
|
||||
{ cwd: "/tmp/workspace/AGENTS.md:48", editor: "cursor" },
|
||||
"darwin",
|
||||
{ platform: "darwin" },
|
||||
);
|
||||
assert.deepEqual(lineOnly, {
|
||||
command: "cursor",
|
||||
@@ -58,7 +59,7 @@ describe("resolveEditorLaunch", () => {
|
||||
|
||||
const lineAndColumn = yield* resolveEditorLaunch(
|
||||
{ cwd: "/tmp/workspace/src/open.ts:71:5", editor: "cursor" },
|
||||
"darwin",
|
||||
{ platform: "darwin" },
|
||||
);
|
||||
assert.deepEqual(lineAndColumn, {
|
||||
command: "cursor",
|
||||
@@ -67,7 +68,7 @@ describe("resolveEditorLaunch", () => {
|
||||
|
||||
const vscodeLineAndColumn = yield* resolveEditorLaunch(
|
||||
{ cwd: "/tmp/workspace/src/open.ts:71:5", editor: "vscode" },
|
||||
"darwin",
|
||||
{ platform: "darwin" },
|
||||
);
|
||||
assert.deepEqual(vscodeLineAndColumn, {
|
||||
command: "code",
|
||||
@@ -76,7 +77,7 @@ describe("resolveEditorLaunch", () => {
|
||||
|
||||
const zedLineAndColumn = yield* resolveEditorLaunch(
|
||||
{ cwd: "/tmp/workspace/src/open.ts:71:5", editor: "zed" },
|
||||
"darwin",
|
||||
{ platform: "darwin" },
|
||||
);
|
||||
assert.deepEqual(zedLineAndColumn, {
|
||||
command: "zed",
|
||||
@@ -89,7 +90,7 @@ describe("resolveEditorLaunch", () => {
|
||||
Effect.gen(function* () {
|
||||
const launch1 = yield* resolveEditorLaunch(
|
||||
{ cwd: "/tmp/workspace", editor: "file-manager" },
|
||||
"darwin",
|
||||
{ platform: "darwin" },
|
||||
);
|
||||
assert.deepEqual(launch1, {
|
||||
command: "open",
|
||||
@@ -98,7 +99,7 @@ describe("resolveEditorLaunch", () => {
|
||||
|
||||
const launch2 = yield* resolveEditorLaunch(
|
||||
{ cwd: "C:\\workspace", editor: "file-manager" },
|
||||
"win32",
|
||||
{ platform: "win32" },
|
||||
);
|
||||
assert.deepEqual(launch2, {
|
||||
command: "explorer",
|
||||
@@ -107,7 +108,7 @@ describe("resolveEditorLaunch", () => {
|
||||
|
||||
const launch3 = yield* resolveEditorLaunch(
|
||||
{ cwd: "/tmp/workspace", editor: "file-manager" },
|
||||
"linux",
|
||||
{ platform: "linux" },
|
||||
);
|
||||
assert.deepEqual(launch3, {
|
||||
command: "xdg-open",
|
||||
@@ -115,6 +116,112 @@ describe("resolveEditorLaunch", () => {
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("prefers linux editor shims in wsl-hosted mode when available", () =>
|
||||
Effect.gen(function* () {
|
||||
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "t3-open-wsl-linux-editor-"));
|
||||
try {
|
||||
fs.writeFileSync(path.join(dir, "code"), "#!/bin/sh\n", { mode: 0o755 });
|
||||
const launch = yield* resolveEditorLaunch(
|
||||
{ cwd: "/home/julius/project/src/open.ts:71:5", editor: "vscode" },
|
||||
{
|
||||
platform: "linux",
|
||||
runtimeEnvironment: {
|
||||
platform: "linux",
|
||||
pathStyle: "posix",
|
||||
isWsl: true,
|
||||
windowsInteropMode: "wsl-hosted",
|
||||
wslDistroName: "Ubuntu",
|
||||
},
|
||||
env: {
|
||||
PATH: dir,
|
||||
},
|
||||
},
|
||||
);
|
||||
assert.deepEqual(launch, {
|
||||
command: "code",
|
||||
args: ["--goto", "/home/julius/project/src/open.ts:71:5"],
|
||||
});
|
||||
} finally {
|
||||
fs.rmSync(dir, { recursive: true, force: true });
|
||||
}
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("falls back to windows editor executables in wsl-hosted mode", () =>
|
||||
Effect.gen(function* () {
|
||||
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "t3-open-wsl-win-editor-"));
|
||||
try {
|
||||
fs.writeFileSync(path.join(dir, "code.exe"), "MZ", { mode: 0o755 });
|
||||
const launch = yield* resolveEditorLaunch(
|
||||
{ cwd: "/home/julius/project/src/open.ts:71:5", editor: "vscode" },
|
||||
{
|
||||
platform: "linux",
|
||||
runtimeEnvironment: {
|
||||
platform: "linux",
|
||||
pathStyle: "posix",
|
||||
isWsl: true,
|
||||
windowsInteropMode: "wsl-hosted",
|
||||
wslDistroName: "Ubuntu",
|
||||
},
|
||||
env: {
|
||||
PATH: dir,
|
||||
},
|
||||
translateWslPathToWindows: (target) =>
|
||||
target.replace(
|
||||
"/home/julius/project",
|
||||
"\\\\wsl.localhost\\Ubuntu\\home\\julius\\project",
|
||||
),
|
||||
},
|
||||
);
|
||||
assert.deepEqual(launch, {
|
||||
command: "code.exe",
|
||||
args: [
|
||||
"--goto",
|
||||
"\\\\wsl.localhost\\Ubuntu\\home\\julius\\project/src/open.ts:71:5",
|
||||
],
|
||||
});
|
||||
} finally {
|
||||
fs.rmSync(dir, { recursive: true, force: true });
|
||||
}
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("translates file-manager targets for wsl-hosted mode", () =>
|
||||
Effect.gen(function* () {
|
||||
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "t3-open-wsl-file-manager-"));
|
||||
try {
|
||||
fs.writeFileSync(path.join(dir, "explorer.exe"), "MZ", { mode: 0o755 });
|
||||
const launch = yield* resolveEditorLaunch(
|
||||
{ cwd: "/home/julius/project/src/open.ts:71:5", editor: "file-manager" },
|
||||
{
|
||||
platform: "linux",
|
||||
runtimeEnvironment: {
|
||||
platform: "linux",
|
||||
pathStyle: "posix",
|
||||
isWsl: true,
|
||||
windowsInteropMode: "wsl-hosted",
|
||||
wslDistroName: "Ubuntu",
|
||||
},
|
||||
env: {
|
||||
PATH: dir,
|
||||
},
|
||||
translateWslPathToWindows: (target) =>
|
||||
target.replace(
|
||||
"/home/julius/project",
|
||||
"\\\\wsl.localhost\\Ubuntu\\home\\julius\\project",
|
||||
),
|
||||
},
|
||||
);
|
||||
assert.deepEqual(launch, {
|
||||
command: "explorer.exe",
|
||||
args: ["\\\\wsl.localhost\\Ubuntu\\home\\julius\\project/src/open.ts"],
|
||||
});
|
||||
} finally {
|
||||
fs.rmSync(dir, { recursive: true, force: true });
|
||||
}
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
describe("launchDetached", () => {
|
||||
@@ -210,13 +317,94 @@ describe("resolveAvailableEditors", () => {
|
||||
try {
|
||||
fs.writeFileSync(path.join(dir, "cursor.CMD"), "@echo off\r\n", "utf8");
|
||||
fs.writeFileSync(path.join(dir, "explorer.EXE"), "MZ", "utf8");
|
||||
const editors = resolveAvailableEditors("win32", {
|
||||
PATH: dir,
|
||||
PATHEXT: ".COM;.EXE;.BAT;.CMD",
|
||||
const editors = resolveAvailableEditors({
|
||||
platform: "win32",
|
||||
env: {
|
||||
PATH: dir,
|
||||
PATHEXT: ".COM;.EXE;.BAT;.CMD",
|
||||
},
|
||||
});
|
||||
assert.deepEqual(editors, ["cursor", "file-manager"]);
|
||||
} finally {
|
||||
fs.rmSync(dir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
it("accepts windows editor executables in wsl-hosted mode", () => {
|
||||
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "t3-editors-wsl-"));
|
||||
try {
|
||||
fs.writeFileSync(path.join(dir, "code.exe"), "MZ", { mode: 0o755 });
|
||||
fs.writeFileSync(path.join(dir, "explorer.exe"), "MZ", { mode: 0o755 });
|
||||
const editors = resolveAvailableEditors({
|
||||
platform: "linux",
|
||||
runtimeEnvironment: {
|
||||
platform: "linux",
|
||||
pathStyle: "posix",
|
||||
isWsl: true,
|
||||
windowsInteropMode: "wsl-hosted",
|
||||
wslDistroName: "Ubuntu",
|
||||
},
|
||||
env: {
|
||||
PATH: dir,
|
||||
},
|
||||
});
|
||||
assert.deepEqual(editors, ["vscode", "file-manager"]);
|
||||
} finally {
|
||||
fs.rmSync(dir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe("resolveBrowserLaunch", () => {
|
||||
it("prefers wslview in wsl-hosted mode", () => {
|
||||
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "t3-browser-wsl-"));
|
||||
try {
|
||||
fs.writeFileSync(path.join(dir, "wslview"), "#!/bin/sh\n", { mode: 0o755 });
|
||||
const launch = resolveBrowserLaunch("http://localhost:3773", {
|
||||
platform: "linux",
|
||||
runtimeEnvironment: {
|
||||
platform: "linux",
|
||||
pathStyle: "posix",
|
||||
isWsl: true,
|
||||
windowsInteropMode: "wsl-hosted",
|
||||
wslDistroName: "Ubuntu",
|
||||
},
|
||||
env: {
|
||||
PATH: dir,
|
||||
},
|
||||
});
|
||||
assert.deepEqual(launch, {
|
||||
command: "wslview",
|
||||
args: ["http://localhost:3773"],
|
||||
});
|
||||
} finally {
|
||||
fs.rmSync(dir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
it("falls back to explorer.exe in wsl-hosted mode", () => {
|
||||
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "t3-browser-wsl-explorer-"));
|
||||
try {
|
||||
fs.writeFileSync(path.join(dir, "explorer.exe"), "MZ", { mode: 0o755 });
|
||||
const launch = resolveBrowserLaunch("http://localhost:3773", {
|
||||
platform: "linux",
|
||||
runtimeEnvironment: {
|
||||
platform: "linux",
|
||||
pathStyle: "posix",
|
||||
isWsl: true,
|
||||
windowsInteropMode: "wsl-hosted",
|
||||
wslDistroName: "Ubuntu",
|
||||
},
|
||||
env: {
|
||||
PATH: dir,
|
||||
},
|
||||
});
|
||||
assert.deepEqual(launch, {
|
||||
command: "explorer.exe",
|
||||
args: ["http://localhost:3773"],
|
||||
});
|
||||
} finally {
|
||||
fs.rmSync(dir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
});
|
||||
+235
-43
@@ -6,12 +6,13 @@
|
||||
*
|
||||
* @module Open
|
||||
*/
|
||||
import { spawn } from "node:child_process";
|
||||
import { accessSync, constants, statSync } from "node:fs";
|
||||
import { extname, join } from "node:path";
|
||||
|
||||
import { EDITORS, type EditorId } from "@t3tools/contracts";
|
||||
import { EDITORS, type EditorId, type ServerRuntimeEnvironment } from "@t3tools/contracts";
|
||||
import { ServiceMap, Schema, Effect, Layer } from "effect";
|
||||
import { spawnDetachedProcess, spawnProcessSync } from "./processRunner";
|
||||
import { detectServerRuntimeEnvironment } from "./runtimeEnvironment";
|
||||
|
||||
// ==============================
|
||||
// Definitions
|
||||
@@ -37,7 +38,24 @@ interface CommandAvailabilityOptions {
|
||||
readonly env?: NodeJS.ProcessEnv;
|
||||
}
|
||||
|
||||
interface ResolveOpenOptions extends CommandAvailabilityOptions {
|
||||
readonly runtimeEnvironment?: ServerRuntimeEnvironment;
|
||||
readonly translateWslPathToWindows?: (target: string) => string;
|
||||
}
|
||||
|
||||
const LINE_COLUMN_SUFFIX_PATTERN = /:\d+(?::\d+)?$/;
|
||||
const WINDOWS_ABSOLUTE_PATH_PATTERN = /^[A-Za-z]:[\\/]/;
|
||||
const WINDOWS_UNC_PATH_PATTERN = /^\\\\/;
|
||||
|
||||
function detectRuntimeEnvironment(options: ResolveOpenOptions): ServerRuntimeEnvironment {
|
||||
return (
|
||||
options.runtimeEnvironment ??
|
||||
detectServerRuntimeEnvironment({
|
||||
...(options.platform !== undefined ? { platform: options.platform } : {}),
|
||||
...(options.env !== undefined ? { env: options.env } : {}),
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
function shouldUseGotoFlag(editorId: EditorId, target: string): boolean {
|
||||
return (editorId === "cursor" || editorId === "vscode") && LINE_COLUMN_SUFFIX_PATTERN.test(target);
|
||||
@@ -160,14 +178,20 @@ export function isCommandAvailable(
|
||||
}
|
||||
|
||||
export function resolveAvailableEditors(
|
||||
platform: NodeJS.Platform = process.platform,
|
||||
env: NodeJS.ProcessEnv = process.env,
|
||||
options: ResolveOpenOptions = {},
|
||||
): ReadonlyArray<EditorId> {
|
||||
const platform = options.platform ?? process.platform;
|
||||
const env = options.env ?? process.env;
|
||||
const runtimeEnvironment = detectRuntimeEnvironment({ ...options, platform, env });
|
||||
const available: EditorId[] = [];
|
||||
|
||||
for (const editor of EDITORS) {
|
||||
const command = editor.command ?? fileManagerCommandForPlatform(platform);
|
||||
if (isCommandAvailable(command, { platform, env })) {
|
||||
const launch = resolveOpenCommand(editor.id, {
|
||||
platform,
|
||||
env,
|
||||
runtimeEnvironment,
|
||||
});
|
||||
if (launch.some((entry) => isCommandAvailable(entry, { platform, env }))) {
|
||||
available.push(editor.id);
|
||||
}
|
||||
}
|
||||
@@ -201,60 +225,223 @@ export class Open extends ServiceMap.Service<Open, OpenShape>()("t3/open") {}
|
||||
// Implementations
|
||||
// ==============================
|
||||
|
||||
function splitPathAndPosition(value: string): {
|
||||
path: string;
|
||||
line: string | undefined;
|
||||
column: string | undefined;
|
||||
} {
|
||||
let path = value;
|
||||
let column: string | undefined;
|
||||
let line: string | undefined;
|
||||
|
||||
const columnMatch = path.match(/:(\d+)$/);
|
||||
if (!columnMatch?.[1]) {
|
||||
return { path, line: undefined, column: undefined };
|
||||
}
|
||||
|
||||
column = columnMatch[1];
|
||||
path = path.slice(0, -columnMatch[0].length);
|
||||
|
||||
const lineMatch = path.match(/:(\d+)$/);
|
||||
if (lineMatch?.[1]) {
|
||||
line = lineMatch[1];
|
||||
path = path.slice(0, -lineMatch[0].length);
|
||||
} else {
|
||||
line = column;
|
||||
column = undefined;
|
||||
}
|
||||
|
||||
return { path, line, column };
|
||||
}
|
||||
|
||||
function stripLineColumnSuffix(value: string): string {
|
||||
const { path } = splitPathAndPosition(value);
|
||||
return path;
|
||||
}
|
||||
|
||||
function formatPathWithPosition(input: {
|
||||
readonly path: string;
|
||||
readonly line?: string;
|
||||
readonly column?: string;
|
||||
}): string {
|
||||
if (!input.line) {
|
||||
return input.path;
|
||||
}
|
||||
return `${input.path}:${input.line}${input.column ? `:${input.column}` : ""}`;
|
||||
}
|
||||
|
||||
function isWindowsPath(value: string): boolean {
|
||||
return WINDOWS_ABSOLUTE_PATH_PATTERN.test(value) || WINDOWS_UNC_PATH_PATTERN.test(value);
|
||||
}
|
||||
|
||||
function defaultTranslateWslPathToWindows(target: string): string {
|
||||
const parsed = splitPathAndPosition(target);
|
||||
if (parsed.path.length === 0 || !parsed.path.startsWith("/") || isWindowsPath(parsed.path)) {
|
||||
return target;
|
||||
}
|
||||
|
||||
const result = spawnProcessSync("wslpath", ["-w", parsed.path], {
|
||||
encoding: "utf8",
|
||||
stdio: ["ignore", "pipe", "pipe"],
|
||||
});
|
||||
if (result.error) {
|
||||
throw result.error;
|
||||
}
|
||||
if (result.status !== 0) {
|
||||
const detail = result.stderr.trim() || result.stdout.trim() || "wslpath failed";
|
||||
throw new Error(detail);
|
||||
}
|
||||
|
||||
const translatedPath = result.stdout.trim();
|
||||
if (translatedPath.length === 0) {
|
||||
throw new Error("wslpath returned an empty path");
|
||||
}
|
||||
|
||||
return formatPathWithPosition({
|
||||
path: translatedPath,
|
||||
...(parsed.line ? { line: parsed.line } : {}),
|
||||
...(parsed.column ? { column: parsed.column } : {}),
|
||||
});
|
||||
}
|
||||
|
||||
function resolveOpenCommand(
|
||||
editorId: EditorId,
|
||||
options: ResolveOpenOptions,
|
||||
): ReadonlyArray<string> {
|
||||
const platform = options.platform ?? process.platform;
|
||||
const env = options.env ?? process.env;
|
||||
const runtimeEnvironment = detectRuntimeEnvironment({ ...options, platform, env });
|
||||
const editorDef = EDITORS.find((editor) => editor.id === editorId);
|
||||
if (!editorDef) {
|
||||
return [];
|
||||
}
|
||||
|
||||
if (editorId === "file-manager") {
|
||||
if (runtimeEnvironment.windowsInteropMode === "wsl-hosted") {
|
||||
return ["explorer.exe", "xdg-open"];
|
||||
}
|
||||
return [fileManagerCommandForPlatform(platform)];
|
||||
}
|
||||
|
||||
if (!editorDef.command) {
|
||||
return [];
|
||||
}
|
||||
|
||||
if (runtimeEnvironment.windowsInteropMode === "wsl-hosted") {
|
||||
return [editorDef.command, `${editorDef.command}.exe`];
|
||||
}
|
||||
|
||||
return [editorDef.command];
|
||||
}
|
||||
|
||||
export function resolveBrowserLaunch(
|
||||
target: string,
|
||||
options: ResolveOpenOptions = {},
|
||||
): EditorLaunch | null {
|
||||
const platform = options.platform ?? process.platform;
|
||||
const env = options.env ?? process.env;
|
||||
const runtimeEnvironment = detectRuntimeEnvironment({ ...options, platform, env });
|
||||
|
||||
if (runtimeEnvironment.windowsInteropMode === "wsl-hosted") {
|
||||
if (isCommandAvailable("wslview", { platform, env })) {
|
||||
return { command: "wslview", args: [target] };
|
||||
}
|
||||
if (isCommandAvailable("explorer.exe", { platform, env })) {
|
||||
return { command: "explorer.exe", args: [target] };
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
export const resolveEditorLaunch = Effect.fnUntraced(function* (
|
||||
input: OpenInEditorInput,
|
||||
platform: NodeJS.Platform = process.platform,
|
||||
options: ResolveOpenOptions = {},
|
||||
): Effect.fn.Return<EditorLaunch, OpenError> {
|
||||
const platform = options.platform ?? process.platform;
|
||||
const env = options.env ?? process.env;
|
||||
const runtimeEnvironment = detectRuntimeEnvironment({ ...options, platform, env });
|
||||
const editorDef = EDITORS.find((editor) => editor.id === input.editor);
|
||||
if (!editorDef) {
|
||||
return yield* new OpenError({ message: `Unknown editor: ${input.editor}` });
|
||||
}
|
||||
|
||||
const translateWslPathToWindows = options.translateWslPathToWindows ?? defaultTranslateWslPathToWindows;
|
||||
|
||||
if (editorDef.command) {
|
||||
return shouldUseGotoFlag(editorDef.id, input.cwd)
|
||||
? { command: editorDef.command, args: ["--goto", input.cwd] }
|
||||
: { command: editorDef.command, args: [input.cwd] };
|
||||
const candidateCommands = resolveOpenCommand(editorDef.id, {
|
||||
platform,
|
||||
env,
|
||||
runtimeEnvironment,
|
||||
});
|
||||
const command =
|
||||
candidateCommands.find((entry) => isCommandAvailable(entry, { platform, env })) ??
|
||||
candidateCommands[0];
|
||||
if (!command) {
|
||||
return yield* new OpenError({ message: `Editor command not found: ${editorDef.command}` });
|
||||
}
|
||||
|
||||
const usesWindowsPath = runtimeEnvironment.windowsInteropMode === "wsl-hosted" && command.endsWith(".exe");
|
||||
const target = usesWindowsPath
|
||||
? yield* Effect.try({
|
||||
try: () => translateWslPathToWindows(input.cwd),
|
||||
catch: (cause) =>
|
||||
new OpenError({
|
||||
message: "Failed to translate WSL path for Windows editor launch",
|
||||
cause,
|
||||
}),
|
||||
})
|
||||
: input.cwd;
|
||||
|
||||
return shouldUseGotoFlag(editorDef.id, target)
|
||||
? { command, args: ["--goto", target] }
|
||||
: { command, args: [target] };
|
||||
}
|
||||
|
||||
if (editorDef.id !== "file-manager") {
|
||||
return yield* new OpenError({ message: `Unsupported editor: ${input.editor}` });
|
||||
}
|
||||
|
||||
return { command: fileManagerCommandForPlatform(platform), args: [input.cwd] };
|
||||
const candidateCommands = resolveOpenCommand(editorDef.id, {
|
||||
platform,
|
||||
env,
|
||||
runtimeEnvironment,
|
||||
});
|
||||
const command =
|
||||
candidateCommands.find((entry) => isCommandAvailable(entry, { platform, env })) ??
|
||||
candidateCommands[0];
|
||||
if (!command) {
|
||||
return yield* new OpenError({ message: "Editor command not found: file-manager" });
|
||||
}
|
||||
|
||||
let target = stripLineColumnSuffix(input.cwd);
|
||||
if (runtimeEnvironment.windowsInteropMode === "wsl-hosted" && command === "explorer.exe") {
|
||||
target = yield* Effect.try({
|
||||
try: () => stripLineColumnSuffix(translateWslPathToWindows(target)),
|
||||
catch: (cause) =>
|
||||
new OpenError({
|
||||
message: "Failed to translate WSL path for Windows file manager launch",
|
||||
cause,
|
||||
}),
|
||||
});
|
||||
}
|
||||
|
||||
return { command, args: [target] };
|
||||
});
|
||||
|
||||
export const launchDetached = (launch: EditorLaunch) =>
|
||||
Effect.gen(function* () {
|
||||
if (!isCommandAvailable(launch.command)) {
|
||||
return yield* new OpenError({ message: `Editor command not found: ${launch.command}` });
|
||||
}
|
||||
|
||||
yield* Effect.callback<void, OpenError>((resume) => {
|
||||
let child;
|
||||
try {
|
||||
child = spawn(launch.command, [...launch.args], {
|
||||
detached: true,
|
||||
stdio: "ignore",
|
||||
shell: process.platform === "win32",
|
||||
});
|
||||
} catch (error) {
|
||||
return resume(
|
||||
Effect.fail(
|
||||
new OpenError({ message: "failed to spawn detached process", cause: error }),
|
||||
),
|
||||
);
|
||||
Effect.tryPromise({
|
||||
try: async () => {
|
||||
if (!isCommandAvailable(launch.command)) {
|
||||
throw new OpenError({ message: `Editor command not found: ${launch.command}` });
|
||||
}
|
||||
|
||||
const handleSpawn = () => {
|
||||
child.unref();
|
||||
resume(Effect.void);
|
||||
};
|
||||
|
||||
child.once("spawn", handleSpawn);
|
||||
child.once("error", (cause) =>
|
||||
resume(Effect.fail(new OpenError({ message: "failed to spawn detached process", cause }))),
|
||||
);
|
||||
});
|
||||
await spawnDetachedProcess(launch.command, [...launch.args]);
|
||||
},
|
||||
catch: (cause) =>
|
||||
Schema.is(OpenError)(cause)
|
||||
? cause
|
||||
: new OpenError({ message: "failed to spawn detached process", cause }),
|
||||
});
|
||||
|
||||
const make = Effect.gen(function* () {
|
||||
@@ -264,11 +451,16 @@ const make = Effect.gen(function* () {
|
||||
});
|
||||
|
||||
return {
|
||||
openBrowser: (target) =>
|
||||
Effect.tryPromise({
|
||||
openBrowser: (target) => {
|
||||
const launch = resolveBrowserLaunch(target);
|
||||
if (launch) {
|
||||
return launchDetached(launch);
|
||||
}
|
||||
return Effect.tryPromise({
|
||||
try: () => open.default(target),
|
||||
catch: (cause) => new OpenError({ message: "Browser auto-open failed", cause }),
|
||||
}),
|
||||
});
|
||||
},
|
||||
openInEditor: (input) => Effect.flatMap(resolveEditorLaunch(input), launchDetached),
|
||||
} satisfies OpenShape;
|
||||
});
|
||||
|
||||
@@ -6,10 +6,12 @@ import { execFileSync } from "node:child_process";
|
||||
import type { ProviderRuntimeEvent, ProviderSession } from "@t3tools/contracts";
|
||||
import {
|
||||
CommandId,
|
||||
DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
EventId,
|
||||
MessageId,
|
||||
ProjectId,
|
||||
ProviderSessionId,
|
||||
ProviderThreadId,
|
||||
ProviderTurnId,
|
||||
ThreadId,
|
||||
TurnId,
|
||||
} from "@t3tools/contracts";
|
||||
@@ -38,43 +40,28 @@ import { checkpointRefForThreadTurn } from "../../checkpointing/Utils.ts";
|
||||
import { ServerConfig } from "../../config.ts";
|
||||
|
||||
const asProjectId = (value: string): ProjectId => ProjectId.makeUnsafe(value);
|
||||
const asSessionId = (value: string): ProviderSessionId => ProviderSessionId.makeUnsafe(value);
|
||||
const asProviderThreadId = (value: string): ProviderThreadId => ProviderThreadId.makeUnsafe(value);
|
||||
const asProviderTurnId = (value: string): ProviderTurnId => ProviderTurnId.makeUnsafe(value);
|
||||
const asTurnId = (value: string): TurnId => TurnId.makeUnsafe(value);
|
||||
|
||||
type LegacyProviderRuntimeEvent = {
|
||||
readonly type: string;
|
||||
readonly eventId: EventId;
|
||||
readonly provider: "codex" | "claudeCode" | "cursor";
|
||||
readonly createdAt: string;
|
||||
readonly threadId: ThreadId;
|
||||
readonly turnId?: string | undefined;
|
||||
readonly itemId?: string | undefined;
|
||||
readonly requestId?: string | undefined;
|
||||
readonly payload?: unknown | undefined;
|
||||
readonly [key: string]: unknown;
|
||||
};
|
||||
|
||||
function createProviderServiceHarness(
|
||||
cwd: string,
|
||||
hasSession = true,
|
||||
sessionCwd = cwd,
|
||||
providerName: "codex" | "claudeCode" = "codex",
|
||||
) {
|
||||
function createProviderServiceHarness(cwd: string, hasSession = true, sessionCwd = cwd) {
|
||||
const now = new Date().toISOString();
|
||||
const runtimeEventPubSub = Effect.runSync(PubSub.unbounded<ProviderRuntimeEvent>());
|
||||
const rollbackConversation = vi.fn(
|
||||
(_input: { readonly threadId: ThreadId; readonly numTurns: number }) => Effect.void,
|
||||
(_input: { readonly sessionId: ProviderSessionId; readonly numTurns: number }) => Effect.void,
|
||||
);
|
||||
|
||||
const unsupported = <A>() =>
|
||||
Effect.die(new Error("Unsupported provider call in test")) as Effect.Effect<A, never>;
|
||||
const listSessions = () =>
|
||||
hasSession
|
||||
? Effect.succeed([
|
||||
? Effect.succeed([
|
||||
{
|
||||
provider: providerName,
|
||||
sessionId: asSessionId("sess-1"),
|
||||
provider: "codex",
|
||||
status: "ready",
|
||||
runtimeMode: "full-access",
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
threadId: asProviderThreadId("provider-thread-1"),
|
||||
cwd: sessionCwd,
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
@@ -86,17 +73,15 @@ function createProviderServiceHarness(
|
||||
sendTurn: () => unsupported(),
|
||||
interruptTurn: () => unsupported(),
|
||||
respondToRequest: () => unsupported(),
|
||||
respondToUserInput: () => unsupported(),
|
||||
stopSession: () => unsupported(),
|
||||
listSessions,
|
||||
getCapabilities: () => Effect.succeed({ sessionModelSwitch: "in-session" }),
|
||||
rollbackConversation,
|
||||
stopAll: () => Effect.void,
|
||||
streamEvents: Stream.fromPubSub(runtimeEventPubSub),
|
||||
};
|
||||
|
||||
const emit = (event: LegacyProviderRuntimeEvent): void => {
|
||||
Effect.runSync(PubSub.publish(runtimeEventPubSub, event as unknown as ProviderRuntimeEvent));
|
||||
const emit = (event: ProviderRuntimeEvent): void => {
|
||||
Effect.runSync(PubSub.publish(runtimeEventPubSub, event));
|
||||
};
|
||||
|
||||
return {
|
||||
@@ -235,7 +220,6 @@ describe("CheckpointReactor", () => {
|
||||
readonly projectWorkspaceRoot?: string;
|
||||
readonly threadWorktreePath?: string | null;
|
||||
readonly providerSessionCwd?: string;
|
||||
readonly providerName?: "codex" | "claudeCode";
|
||||
}) {
|
||||
const cwd = createGitRepository();
|
||||
tempDirs.push(cwd);
|
||||
@@ -243,7 +227,6 @@ describe("CheckpointReactor", () => {
|
||||
cwd,
|
||||
options?.hasSession ?? true,
|
||||
options?.providerSessionCwd ?? cwd,
|
||||
options?.providerName ?? "codex",
|
||||
);
|
||||
const orchestrationLayer = OrchestrationEngineLive.pipe(
|
||||
Layer.provide(OrchestrationProjectionPipelineLive),
|
||||
@@ -288,8 +271,6 @@ describe("CheckpointReactor", () => {
|
||||
projectId: asProjectId("project-1"),
|
||||
title: "Thread",
|
||||
model: "gpt-5-codex",
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "approval-required",
|
||||
branch: null,
|
||||
worktreePath: options?.threadWorktreePath ?? cwd,
|
||||
createdAt,
|
||||
@@ -339,7 +320,10 @@ describe("CheckpointReactor", () => {
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
status: "ready",
|
||||
providerName: "codex",
|
||||
runtimeMode: "approval-required",
|
||||
providerSessionId: asSessionId("sess-1"),
|
||||
providerThreadId: ProviderThreadId.makeUnsafe("provider-thread-1"),
|
||||
approvalPolicy: "on-request",
|
||||
sandboxMode: "workspace-write",
|
||||
activeTurnId: null,
|
||||
lastError: null,
|
||||
updatedAt: createdAt,
|
||||
@@ -352,10 +336,10 @@ describe("CheckpointReactor", () => {
|
||||
type: "turn.started",
|
||||
eventId: EventId.makeUnsafe("evt-turn-started-1"),
|
||||
provider: "codex",
|
||||
|
||||
sessionId: asSessionId("sess-1"),
|
||||
createdAt: new Date().toISOString(),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
turnId: asTurnId("turn-1"),
|
||||
threadId: ProviderThreadId.makeUnsafe("provider-thread-1"),
|
||||
turnId: asProviderTurnId("turn-1"),
|
||||
});
|
||||
await waitForGitRefExists(
|
||||
harness.cwd,
|
||||
@@ -367,11 +351,11 @@ describe("CheckpointReactor", () => {
|
||||
type: "turn.completed",
|
||||
eventId: EventId.makeUnsafe("evt-turn-completed-1"),
|
||||
provider: "codex",
|
||||
|
||||
sessionId: asSessionId("sess-1"),
|
||||
createdAt: new Date().toISOString(),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
turnId: asTurnId("turn-1"),
|
||||
payload: { state: "completed" },
|
||||
threadId: ProviderThreadId.makeUnsafe("provider-thread-1"),
|
||||
turnId: asProviderTurnId("turn-1"),
|
||||
status: "completed",
|
||||
});
|
||||
|
||||
await waitForEvent(harness.engine, (event) => event.type === "thread.turn-diff-completed");
|
||||
@@ -415,7 +399,10 @@ describe("CheckpointReactor", () => {
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
status: "running",
|
||||
providerName: "codex",
|
||||
runtimeMode: "approval-required",
|
||||
providerSessionId: asSessionId("sess-1"),
|
||||
providerThreadId: ProviderThreadId.makeUnsafe("provider-thread-1"),
|
||||
approvalPolicy: "on-request",
|
||||
sandboxMode: "workspace-write",
|
||||
activeTurnId: asTurnId("turn-main"),
|
||||
lastError: null,
|
||||
updatedAt: createdAt,
|
||||
@@ -428,10 +415,10 @@ describe("CheckpointReactor", () => {
|
||||
type: "turn.started",
|
||||
eventId: EventId.makeUnsafe("evt-turn-started-main"),
|
||||
provider: "codex",
|
||||
|
||||
sessionId: asSessionId("sess-1"),
|
||||
createdAt: new Date().toISOString(),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
turnId: asTurnId("turn-main"),
|
||||
threadId: ProviderThreadId.makeUnsafe("provider-thread-1"),
|
||||
turnId: asProviderTurnId("turn-main"),
|
||||
});
|
||||
await waitForGitRefExists(
|
||||
harness.cwd,
|
||||
@@ -444,11 +431,11 @@ describe("CheckpointReactor", () => {
|
||||
type: "turn.completed",
|
||||
eventId: EventId.makeUnsafe("evt-turn-completed-aux"),
|
||||
provider: "codex",
|
||||
|
||||
sessionId: asSessionId("sess-1"),
|
||||
createdAt: new Date().toISOString(),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
turnId: asTurnId("turn-aux"),
|
||||
payload: { state: "completed" },
|
||||
threadId: ProviderThreadId.makeUnsafe("provider-thread-aux"),
|
||||
turnId: asProviderTurnId("turn-aux"),
|
||||
status: "completed",
|
||||
});
|
||||
|
||||
await Effect.runPromise(Effect.sleep("40 millis"));
|
||||
@@ -462,11 +449,11 @@ describe("CheckpointReactor", () => {
|
||||
type: "turn.completed",
|
||||
eventId: EventId.makeUnsafe("evt-turn-completed-main"),
|
||||
provider: "codex",
|
||||
|
||||
sessionId: asSessionId("sess-1"),
|
||||
createdAt: new Date().toISOString(),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
turnId: asTurnId("turn-main"),
|
||||
payload: { state: "completed" },
|
||||
threadId: ProviderThreadId.makeUnsafe("provider-thread-1"),
|
||||
turnId: asProviderTurnId("turn-main"),
|
||||
status: "completed",
|
||||
});
|
||||
|
||||
const thread = await waitForThread(
|
||||
@@ -476,69 +463,6 @@ describe("CheckpointReactor", () => {
|
||||
expect(thread.checkpoints[0]?.checkpointTurnCount).toBe(1);
|
||||
});
|
||||
|
||||
it("captures pre-turn and completion checkpoints for claudeCode runtime events", async () => {
|
||||
const harness = await createHarness({
|
||||
seedFilesystemCheckpoints: false,
|
||||
providerName: "claudeCode",
|
||||
});
|
||||
const createdAt = new Date().toISOString();
|
||||
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.session.set",
|
||||
commandId: CommandId.makeUnsafe("cmd-session-set-capture-claude"),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
session: {
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
status: "ready",
|
||||
providerName: "claudeCode",
|
||||
runtimeMode: "approval-required",
|
||||
activeTurnId: null,
|
||||
lastError: null,
|
||||
updatedAt: createdAt,
|
||||
},
|
||||
createdAt,
|
||||
}),
|
||||
);
|
||||
|
||||
harness.provider.emit({
|
||||
type: "turn.started",
|
||||
eventId: EventId.makeUnsafe("evt-turn-started-claude-1"),
|
||||
provider: "claudeCode",
|
||||
|
||||
createdAt: new Date().toISOString(),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
turnId: asTurnId("turn-claude-1"),
|
||||
});
|
||||
await waitForGitRefExists(
|
||||
harness.cwd,
|
||||
checkpointRefForThreadTurn(ThreadId.makeUnsafe("thread-1"), 0),
|
||||
);
|
||||
|
||||
fs.writeFileSync(path.join(harness.cwd, "README.md"), "v2\n", "utf8");
|
||||
harness.provider.emit({
|
||||
type: "turn.completed",
|
||||
eventId: EventId.makeUnsafe("evt-turn-completed-claude-1"),
|
||||
provider: "claudeCode",
|
||||
|
||||
createdAt: new Date().toISOString(),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
turnId: asTurnId("turn-claude-1"),
|
||||
payload: { state: "completed" },
|
||||
});
|
||||
|
||||
await waitForEvent(harness.engine, (event) => event.type === "thread.turn-diff-completed");
|
||||
const thread = await waitForThread(
|
||||
harness.engine,
|
||||
(entry) => entry.latestTurn?.turnId === "turn-claude-1" && entry.checkpoints.length === 1,
|
||||
);
|
||||
|
||||
expect(thread.checkpoints[0]?.checkpointTurnCount).toBe(1);
|
||||
expect(
|
||||
gitRefExists(harness.cwd, checkpointRefForThreadTurn(ThreadId.makeUnsafe("thread-1"), 1)),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it("appends capture failure activity when turn diff summary cannot be derived", async () => {
|
||||
const harness = await createHarness({ seedFilesystemCheckpoints: false });
|
||||
const createdAt = new Date().toISOString();
|
||||
@@ -552,7 +476,10 @@ describe("CheckpointReactor", () => {
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
status: "ready",
|
||||
providerName: "codex",
|
||||
runtimeMode: "approval-required",
|
||||
providerSessionId: asSessionId("sess-1"),
|
||||
providerThreadId: ProviderThreadId.makeUnsafe("provider-thread-1"),
|
||||
approvalPolicy: "on-request",
|
||||
sandboxMode: "workspace-write",
|
||||
activeTurnId: null,
|
||||
lastError: null,
|
||||
updatedAt: createdAt,
|
||||
@@ -565,11 +492,11 @@ describe("CheckpointReactor", () => {
|
||||
type: "turn.completed",
|
||||
eventId: EventId.makeUnsafe("evt-turn-completed-missing-baseline"),
|
||||
provider: "codex",
|
||||
|
||||
sessionId: asSessionId("sess-1"),
|
||||
createdAt: new Date().toISOString(),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
turnId: asTurnId("turn-missing-baseline"),
|
||||
payload: { state: "completed" },
|
||||
threadId: ProviderThreadId.makeUnsafe("provider-thread-1"),
|
||||
turnId: asProviderTurnId("turn-missing-baseline"),
|
||||
status: "completed",
|
||||
});
|
||||
|
||||
await waitForEvent(harness.engine, (event) => event.type === "thread.turn-diff-completed");
|
||||
@@ -604,8 +531,8 @@ describe("CheckpointReactor", () => {
|
||||
text: "start turn",
|
||||
attachments: [],
|
||||
},
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "approval-required",
|
||||
approvalPolicy: "on-request",
|
||||
sandboxMode: "workspace-write",
|
||||
createdAt: new Date().toISOString(),
|
||||
}),
|
||||
);
|
||||
@@ -640,7 +567,10 @@ describe("CheckpointReactor", () => {
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
status: "running",
|
||||
providerName: "codex",
|
||||
runtimeMode: "approval-required",
|
||||
providerSessionId: asSessionId("sess-missing"),
|
||||
providerThreadId: ProviderThreadId.makeUnsafe("provider-thread-missing"),
|
||||
approvalPolicy: "on-request",
|
||||
sandboxMode: "workspace-write",
|
||||
activeTurnId: asTurnId("turn-missing-cwd"),
|
||||
lastError: null,
|
||||
updatedAt: createdAt,
|
||||
@@ -654,11 +584,11 @@ describe("CheckpointReactor", () => {
|
||||
type: "turn.completed",
|
||||
eventId: EventId.makeUnsafe("evt-turn-completed-missing-provider-cwd"),
|
||||
provider: "codex",
|
||||
|
||||
sessionId: asSessionId("sess-missing"),
|
||||
createdAt: new Date().toISOString(),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
turnId: asTurnId("turn-missing-cwd"),
|
||||
payload: { state: "completed" },
|
||||
threadId: ProviderThreadId.makeUnsafe("provider-thread-missing"),
|
||||
turnId: asProviderTurnId("turn-missing-cwd"),
|
||||
status: "completed",
|
||||
});
|
||||
|
||||
await waitForEvent(harness.engine, (event) => event.type === "thread.turn-diff-completed");
|
||||
@@ -674,7 +604,7 @@ describe("CheckpointReactor", () => {
|
||||
).toBe("v2\n");
|
||||
});
|
||||
|
||||
it("ignores non-v2 checkpoint.captured runtime events", async () => {
|
||||
it("maps runtime checkpoint.captured into thread.turn.diff.complete when missing in read model", async () => {
|
||||
const harness = await createHarness();
|
||||
const createdAt = new Date().toISOString();
|
||||
|
||||
@@ -687,7 +617,10 @@ describe("CheckpointReactor", () => {
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
status: "ready",
|
||||
providerName: "codex",
|
||||
runtimeMode: "approval-required",
|
||||
providerSessionId: asSessionId("sess-1"),
|
||||
providerThreadId: ProviderThreadId.makeUnsafe("provider-thread-1"),
|
||||
approvalPolicy: "on-request",
|
||||
sandboxMode: "workspace-write",
|
||||
activeTurnId: null,
|
||||
lastError: null,
|
||||
updatedAt: createdAt,
|
||||
@@ -700,19 +633,19 @@ describe("CheckpointReactor", () => {
|
||||
type: "checkpoint.captured",
|
||||
eventId: EventId.makeUnsafe("evt-checkpoint-captured-3"),
|
||||
provider: "codex",
|
||||
|
||||
sessionId: asSessionId("sess-1"),
|
||||
createdAt: new Date().toISOString(),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
turnId: asTurnId("turn-3"),
|
||||
threadId: ProviderThreadId.makeUnsafe("provider-thread-1"),
|
||||
turnId: asProviderTurnId("turn-3"),
|
||||
turnCount: 3,
|
||||
status: "completed",
|
||||
});
|
||||
|
||||
await Effect.runPromise(Effect.sleep("40 millis"));
|
||||
const readModel = await Effect.runPromise(harness.engine.getReadModel());
|
||||
const thread = readModel.threads.find((entry) => entry.id === ThreadId.makeUnsafe("thread-1"));
|
||||
expect(thread?.checkpoints.some((checkpoint) => checkpoint.checkpointTurnCount === 3)).toBe(
|
||||
false,
|
||||
const thread = await waitForThread(harness.engine, (entry) =>
|
||||
entry.checkpoints.some((checkpoint) => checkpoint.checkpointTurnCount === 3),
|
||||
);
|
||||
expect(thread.checkpoints.some((checkpoint) => checkpoint.checkpointTurnCount === 3)).toBe(
|
||||
true,
|
||||
);
|
||||
});
|
||||
|
||||
@@ -737,7 +670,10 @@ describe("CheckpointReactor", () => {
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
status: "ready",
|
||||
providerName: "codex",
|
||||
runtimeMode: "approval-required",
|
||||
providerSessionId: asSessionId("sess-1"),
|
||||
providerThreadId: ProviderThreadId.makeUnsafe("provider-thread-1"),
|
||||
approvalPolicy: "on-request",
|
||||
sandboxMode: "workspace-write",
|
||||
activeTurnId: null,
|
||||
lastError: null,
|
||||
updatedAt: createdAt,
|
||||
@@ -747,24 +683,25 @@ describe("CheckpointReactor", () => {
|
||||
);
|
||||
|
||||
harness.provider.emit({
|
||||
type: "turn.completed",
|
||||
type: "checkpoint.captured",
|
||||
eventId: EventId.makeUnsafe("evt-runtime-capture-failure"),
|
||||
provider: "codex",
|
||||
|
||||
sessionId: asSessionId("sess-1"),
|
||||
createdAt: new Date().toISOString(),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
turnId: asTurnId("turn-runtime-failure"),
|
||||
payload: { state: "completed" },
|
||||
threadId: ProviderThreadId.makeUnsafe("provider-thread-1"),
|
||||
turnId: asProviderTurnId("turn-runtime-failure"),
|
||||
turnCount: 1,
|
||||
status: "completed",
|
||||
});
|
||||
|
||||
harness.provider.emit({
|
||||
type: "turn.started",
|
||||
eventId: EventId.makeUnsafe("evt-turn-started-after-runtime-failure"),
|
||||
provider: "codex",
|
||||
|
||||
sessionId: asSessionId("sess-1"),
|
||||
createdAt: new Date().toISOString(),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
turnId: asTurnId("turn-after-runtime-failure"),
|
||||
threadId: ProviderThreadId.makeUnsafe("provider-thread-1"),
|
||||
turnId: asProviderTurnId("turn-after-runtime-failure"),
|
||||
});
|
||||
|
||||
await waitForGitRefExists(
|
||||
@@ -789,7 +726,10 @@ describe("CheckpointReactor", () => {
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
status: "ready",
|
||||
providerName: "codex",
|
||||
runtimeMode: "approval-required",
|
||||
providerSessionId: asSessionId("sess-1"),
|
||||
providerThreadId: ProviderThreadId.makeUnsafe("provider-thread-1"),
|
||||
approvalPolicy: "on-request",
|
||||
sandboxMode: "workspace-write",
|
||||
activeTurnId: null,
|
||||
lastError: null,
|
||||
updatedAt: createdAt,
|
||||
@@ -845,7 +785,7 @@ describe("CheckpointReactor", () => {
|
||||
expect(thread.checkpoints[0]?.checkpointTurnCount).toBe(1);
|
||||
expect(harness.provider.rollbackConversation).toHaveBeenCalledTimes(1);
|
||||
expect(harness.provider.rollbackConversation).toHaveBeenCalledWith({
|
||||
|
||||
sessionId: asSessionId("sess-1"),
|
||||
numTurns: 1,
|
||||
});
|
||||
expect(fs.readFileSync(path.join(harness.cwd, "README.md"), "utf8")).toBe("v2\n");
|
||||
@@ -854,75 +794,6 @@ describe("CheckpointReactor", () => {
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it("executes provider revert and emits thread.reverted for claudeCode sessions", async () => {
|
||||
const harness = await createHarness({ providerName: "claudeCode" });
|
||||
const createdAt = new Date().toISOString();
|
||||
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.session.set",
|
||||
commandId: CommandId.makeUnsafe("cmd-session-set-claude"),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
session: {
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
status: "ready",
|
||||
providerName: "claudeCode",
|
||||
runtimeMode: "approval-required",
|
||||
activeTurnId: null,
|
||||
lastError: null,
|
||||
updatedAt: createdAt,
|
||||
},
|
||||
createdAt,
|
||||
}),
|
||||
);
|
||||
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.turn.diff.complete",
|
||||
commandId: CommandId.makeUnsafe("cmd-diff-claude-1"),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
turnId: asTurnId("turn-claude-1"),
|
||||
completedAt: createdAt,
|
||||
checkpointRef: checkpointRefForThreadTurn(ThreadId.makeUnsafe("thread-1"), 1),
|
||||
status: "ready",
|
||||
files: [],
|
||||
checkpointTurnCount: 1,
|
||||
createdAt,
|
||||
}),
|
||||
);
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.turn.diff.complete",
|
||||
commandId: CommandId.makeUnsafe("cmd-diff-claude-2"),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
turnId: asTurnId("turn-claude-2"),
|
||||
completedAt: createdAt,
|
||||
checkpointRef: checkpointRefForThreadTurn(ThreadId.makeUnsafe("thread-1"), 2),
|
||||
status: "ready",
|
||||
files: [],
|
||||
checkpointTurnCount: 2,
|
||||
createdAt,
|
||||
}),
|
||||
);
|
||||
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.checkpoint.revert",
|
||||
commandId: CommandId.makeUnsafe("cmd-revert-request-claude"),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
turnCount: 1,
|
||||
createdAt,
|
||||
}),
|
||||
);
|
||||
|
||||
await waitForEvent(harness.engine, (event) => event.type === "thread.reverted");
|
||||
expect(harness.provider.rollbackConversation).toHaveBeenCalledTimes(1);
|
||||
expect(harness.provider.rollbackConversation).toHaveBeenCalledWith({
|
||||
|
||||
numTurns: 1,
|
||||
});
|
||||
});
|
||||
|
||||
it("processes consecutive revert requests with deterministic rollback sequencing", async () => {
|
||||
const harness = await createHarness();
|
||||
const createdAt = new Date().toISOString();
|
||||
@@ -936,7 +807,10 @@ describe("CheckpointReactor", () => {
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
status: "ready",
|
||||
providerName: "codex",
|
||||
runtimeMode: "approval-required",
|
||||
providerSessionId: asSessionId("sess-1"),
|
||||
providerThreadId: ProviderThreadId.makeUnsafe("provider-thread-1"),
|
||||
approvalPolicy: "on-request",
|
||||
sandboxMode: "workspace-write",
|
||||
activeTurnId: null,
|
||||
lastError: null,
|
||||
updatedAt: createdAt,
|
||||
@@ -1008,11 +882,11 @@ describe("CheckpointReactor", () => {
|
||||
|
||||
expect(harness.provider.rollbackConversation).toHaveBeenCalledTimes(2);
|
||||
expect(harness.provider.rollbackConversation.mock.calls[0]?.[0]).toEqual({
|
||||
|
||||
sessionId: asSessionId("sess-1"),
|
||||
numTurns: 1,
|
||||
});
|
||||
expect(harness.provider.rollbackConversation.mock.calls[1]?.[0]).toEqual({
|
||||
|
||||
sessionId: asSessionId("sess-1"),
|
||||
numTurns: 1,
|
||||
});
|
||||
});
|
||||
|
||||
@@ -2,6 +2,8 @@ import {
|
||||
CommandId,
|
||||
EventId,
|
||||
MessageId,
|
||||
ProviderSessionId,
|
||||
ProviderThreadId,
|
||||
ThreadId,
|
||||
TurnId,
|
||||
type OrchestrationEvent,
|
||||
@@ -32,7 +34,11 @@ type ReactorInput =
|
||||
};
|
||||
|
||||
function toTurnId(value: string | undefined): TurnId | null {
|
||||
return value === undefined ? null : TurnId.makeUnsafe(String(value));
|
||||
return value === undefined ? null : TurnId.makeUnsafe(value);
|
||||
}
|
||||
|
||||
function toProviderThreadId(value: string | undefined): ProviderThreadId | null {
|
||||
return value === undefined ? null : ProviderThreadId.makeUnsafe(value);
|
||||
}
|
||||
|
||||
function sameId(left: string | null | undefined, right: string | null | undefined): boolean {
|
||||
@@ -89,58 +95,77 @@ const make = Effect.gen(function* () {
|
||||
});
|
||||
|
||||
const appendCaptureFailureActivity = (input: {
|
||||
readonly threadId: ThreadId;
|
||||
readonly sessionId: ProviderSessionId;
|
||||
readonly turnId: TurnId | null;
|
||||
readonly detail: string;
|
||||
readonly createdAt: string;
|
||||
}) =>
|
||||
orchestrationEngine.dispatch({
|
||||
type: "thread.activity.append",
|
||||
commandId: serverCommandId("checkpoint-capture-failure"),
|
||||
threadId: input.threadId,
|
||||
activity: {
|
||||
id: EventId.makeUnsafe(crypto.randomUUID()),
|
||||
tone: "error",
|
||||
kind: "checkpoint.capture.failed",
|
||||
summary: "Checkpoint capture failed",
|
||||
payload: {
|
||||
detail: input.detail,
|
||||
Effect.gen(function* () {
|
||||
const readModel = yield* orchestrationEngine.getReadModel();
|
||||
const thread = readModel.threads.find(
|
||||
(entry) => entry.session?.providerSessionId === input.sessionId,
|
||||
);
|
||||
if (!thread) {
|
||||
return;
|
||||
}
|
||||
yield* orchestrationEngine.dispatch({
|
||||
type: "thread.activity.append",
|
||||
commandId: serverCommandId("checkpoint-capture-failure"),
|
||||
threadId: thread.id,
|
||||
activity: {
|
||||
id: EventId.makeUnsafe(crypto.randomUUID()),
|
||||
tone: "error",
|
||||
kind: "checkpoint.capture.failed",
|
||||
summary: "Checkpoint capture failed",
|
||||
payload: {
|
||||
detail: input.detail,
|
||||
},
|
||||
turnId: input.turnId,
|
||||
createdAt: input.createdAt,
|
||||
},
|
||||
turnId: input.turnId,
|
||||
createdAt: input.createdAt,
|
||||
},
|
||||
createdAt: input.createdAt,
|
||||
});
|
||||
});
|
||||
|
||||
const resolveSessionRuntimeForThread = Effect.fnUntraced(function* (
|
||||
threadId: ThreadId,
|
||||
): Effect.fn.Return<
|
||||
Option.Option<{ readonly threadId: ThreadId; readonly cwd: string }>
|
||||
Option.Option<{ readonly sessionId: ProviderSessionId; readonly cwd: string }>
|
||||
> {
|
||||
const readModel = yield* orchestrationEngine.getReadModel();
|
||||
const thread = readModel.threads.find((entry) => entry.id === threadId);
|
||||
const projectedSessionId = thread?.session?.providerSessionId ?? null;
|
||||
const projectedProviderThreadId = thread?.session?.providerThreadId ?? undefined;
|
||||
|
||||
const sessions = yield* providerService.listSessions();
|
||||
|
||||
const findSessionWithCwd = (
|
||||
session: (typeof sessions)[number] | undefined,
|
||||
): Option.Option<{ readonly threadId: ThreadId; readonly cwd: string }> => {
|
||||
): Option.Option<{ readonly sessionId: ProviderSessionId; readonly cwd: string }> => {
|
||||
if (!session?.cwd) {
|
||||
return Option.none();
|
||||
}
|
||||
return Option.some({ threadId: session.threadId, cwd: session.cwd });
|
||||
return Option.some({ sessionId: session.sessionId, cwd: session.cwd });
|
||||
};
|
||||
|
||||
if (thread) {
|
||||
const projectedSession = sessions.find(
|
||||
(session) => session.threadId === thread.id,
|
||||
);
|
||||
if (projectedSessionId !== null) {
|
||||
const projectedSession = sessions.find((session) => session.sessionId === projectedSessionId);
|
||||
const fromProjected = findSessionWithCwd(projectedSession);
|
||||
if (Option.isSome(fromProjected)) {
|
||||
return fromProjected;
|
||||
}
|
||||
}
|
||||
|
||||
if (projectedProviderThreadId) {
|
||||
const matchedSession = sessions.find(
|
||||
(session) => session.threadId === projectedProviderThreadId,
|
||||
);
|
||||
const fromProviderThread = findSessionWithCwd(matchedSession);
|
||||
if (Option.isSome(fromProviderThread)) {
|
||||
return fromProviderThread;
|
||||
}
|
||||
}
|
||||
|
||||
return Option.none();
|
||||
});
|
||||
|
||||
@@ -153,11 +178,23 @@ const make = Effect.gen(function* () {
|
||||
}
|
||||
|
||||
const readModel = yield* orchestrationEngine.getReadModel();
|
||||
const thread = readModel.threads.find((entry) => entry.id === event.threadId);
|
||||
const thread = readModel.threads.find(
|
||||
(entry) => entry.session?.providerSessionId === event.sessionId,
|
||||
);
|
||||
if (!thread) {
|
||||
return;
|
||||
}
|
||||
|
||||
const projectedProviderThreadId = thread.session?.providerThreadId ?? null;
|
||||
const eventProviderThreadId = toProviderThreadId(event.threadId);
|
||||
if (
|
||||
projectedProviderThreadId !== null &&
|
||||
eventProviderThreadId !== null &&
|
||||
!sameId(projectedProviderThreadId, eventProviderThreadId)
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
// When a primary turn is active, only that turn may produce completion checkpoints.
|
||||
if (thread.session?.activeTurnId && !sameId(thread.session.activeTurnId, turnId)) {
|
||||
return;
|
||||
@@ -229,7 +266,7 @@ const make = Effect.gen(function* () {
|
||||
),
|
||||
Effect.tapError((error) =>
|
||||
appendCaptureFailureActivity({
|
||||
threadId: thread.id,
|
||||
sessionId: event.sessionId,
|
||||
turnId,
|
||||
detail: `Checkpoint captured, but turn diff summary is unavailable: ${error.message}`,
|
||||
createdAt: event.createdAt,
|
||||
@@ -259,7 +296,7 @@ const make = Effect.gen(function* () {
|
||||
turnId,
|
||||
completedAt: now,
|
||||
checkpointRef: targetCheckpointRef,
|
||||
status: checkpointStatusFromRuntime(event.payload.state),
|
||||
status: checkpointStatusFromRuntime(event.status),
|
||||
files,
|
||||
assistantMessageId,
|
||||
checkpointTurnCount: nextTurnCount,
|
||||
@@ -277,7 +314,7 @@ const make = Effect.gen(function* () {
|
||||
summary: "Checkpoint captured",
|
||||
payload: {
|
||||
turnCount: nextTurnCount,
|
||||
status: event.payload.state,
|
||||
...(event.status !== undefined ? { status: event.status } : {}),
|
||||
},
|
||||
turnId,
|
||||
createdAt: now,
|
||||
@@ -296,7 +333,7 @@ const make = Effect.gen(function* () {
|
||||
|
||||
const readModel = yield* orchestrationEngine.getReadModel();
|
||||
const thread = readModel.threads.find(
|
||||
(entry) => entry.id === event.threadId,
|
||||
(entry) => entry.session?.providerSessionId === event.sessionId,
|
||||
);
|
||||
if (!thread) {
|
||||
return;
|
||||
@@ -476,7 +513,7 @@ const make = Effect.gen(function* () {
|
||||
const rolledBackTurns = Math.max(0, currentTurnCount - event.payload.turnCount);
|
||||
if (rolledBackTurns > 0) {
|
||||
yield* providerService.rollbackConversation({
|
||||
threadId: sessionRuntime.value.threadId,
|
||||
sessionId: sessionRuntime.value.sessionId,
|
||||
numTurns: rolledBackTurns,
|
||||
});
|
||||
}
|
||||
@@ -544,7 +581,7 @@ const make = Effect.gen(function* () {
|
||||
yield* captureCheckpointFromTurnCompletion(event).pipe(
|
||||
Effect.catch((error) =>
|
||||
appendCaptureFailureActivity({
|
||||
threadId: event.threadId,
|
||||
sessionId: event.sessionId,
|
||||
turnId,
|
||||
detail: error.message,
|
||||
createdAt: new Date().toISOString(),
|
||||
@@ -553,6 +590,89 @@ const make = Effect.gen(function* () {
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
if (event.type === "checkpoint.captured") {
|
||||
const turnId = toTurnId(event.turnId);
|
||||
if (!turnId) {
|
||||
return;
|
||||
}
|
||||
|
||||
const readModel = yield* orchestrationEngine.getReadModel();
|
||||
const thread = readModel.threads.find(
|
||||
(entry) => entry.session?.providerSessionId === event.sessionId,
|
||||
);
|
||||
if (!thread) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (
|
||||
thread.checkpoints.some(
|
||||
(checkpoint) =>
|
||||
checkpoint.turnId === turnId || checkpoint.checkpointTurnCount === event.turnCount,
|
||||
)
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
const sessionRuntime = yield* resolveSessionRuntimeForThread(thread.id);
|
||||
if (Option.isNone(sessionRuntime)) {
|
||||
return;
|
||||
}
|
||||
|
||||
const fromTurnCount = Math.max(0, event.turnCount - 1);
|
||||
const fromCheckpointRef = checkpointRefForThreadTurn(thread.id, fromTurnCount);
|
||||
const targetCheckpointRef = checkpointRefForThreadTurn(thread.id, event.turnCount);
|
||||
|
||||
const targetExists = yield* checkpointStore.hasCheckpointRef({
|
||||
cwd: sessionRuntime.value.cwd,
|
||||
checkpointRef: targetCheckpointRef,
|
||||
});
|
||||
if (!targetExists) {
|
||||
yield* checkpointStore.captureCheckpoint({
|
||||
cwd: sessionRuntime.value.cwd,
|
||||
checkpointRef: targetCheckpointRef,
|
||||
});
|
||||
}
|
||||
|
||||
const files = yield* checkpointStore
|
||||
.diffCheckpoints({
|
||||
cwd: sessionRuntime.value.cwd,
|
||||
fromCheckpointRef,
|
||||
toCheckpointRef: targetCheckpointRef,
|
||||
fallbackFromToHead: false,
|
||||
})
|
||||
.pipe(
|
||||
Effect.map((diff) =>
|
||||
parseTurnDiffFilesFromUnifiedDiff(diff).map((file) => ({
|
||||
path: file.path,
|
||||
kind: "modified" as const,
|
||||
additions: file.additions,
|
||||
deletions: file.deletions,
|
||||
})),
|
||||
),
|
||||
Effect.catch(() => Effect.succeed([])),
|
||||
);
|
||||
|
||||
const assistantMessageId =
|
||||
thread.messages
|
||||
.toReversed()
|
||||
.find((entry) => entry.role === "assistant" && entry.turnId === turnId)?.id ??
|
||||
MessageId.makeUnsafe(`assistant:${turnId}`);
|
||||
|
||||
yield* orchestrationEngine.dispatch({
|
||||
type: "thread.turn.diff.complete",
|
||||
commandId: serverCommandId("checkpoint-runtime-captured-diff-complete"),
|
||||
threadId: thread.id,
|
||||
turnId,
|
||||
completedAt: event.createdAt,
|
||||
checkpointRef: targetCheckpointRef,
|
||||
status: checkpointStatusFromRuntime(event.status),
|
||||
files,
|
||||
assistantMessageId,
|
||||
checkpointTurnCount: event.turnCount,
|
||||
createdAt: event.createdAt,
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
const processInput = (
|
||||
@@ -597,7 +717,11 @@ const make = Effect.gen(function* () {
|
||||
|
||||
yield* Effect.forkScoped(
|
||||
Stream.runForEach(providerService.streamEvents, (event) => {
|
||||
if (event.type !== "turn.started" && event.type !== "turn.completed") {
|
||||
if (
|
||||
event.type !== "turn.started" &&
|
||||
event.type !== "turn.completed" &&
|
||||
event.type !== "checkpoint.captured"
|
||||
) {
|
||||
return Effect.void;
|
||||
}
|
||||
return Queue.offer(queue, { source: "runtime", event }).pipe(Effect.asVoid);
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
import {
|
||||
CheckpointRef,
|
||||
CommandId,
|
||||
DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
MessageId,
|
||||
ProjectId,
|
||||
ThreadId,
|
||||
@@ -81,8 +80,6 @@ describe("OrchestrationEngine", () => {
|
||||
projectId: asProjectId("project-1"),
|
||||
title: "Thread",
|
||||
model: "gpt-5-codex",
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "approval-required",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
createdAt,
|
||||
@@ -99,8 +96,8 @@ describe("OrchestrationEngine", () => {
|
||||
text: "hello",
|
||||
attachments: [],
|
||||
},
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "approval-required",
|
||||
approvalPolicy: "on-request",
|
||||
sandboxMode: "workspace-write",
|
||||
createdAt,
|
||||
}),
|
||||
);
|
||||
@@ -135,8 +132,6 @@ describe("OrchestrationEngine", () => {
|
||||
projectId: asProjectId("project-replay"),
|
||||
title: "replay",
|
||||
model: "gpt-5-codex",
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "approval-required",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
createdAt,
|
||||
@@ -197,8 +192,6 @@ describe("OrchestrationEngine", () => {
|
||||
projectId: asProjectId("project-stream"),
|
||||
title: "domain-stream",
|
||||
model: "gpt-5-codex",
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "approval-required",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
createdAt,
|
||||
@@ -242,8 +235,6 @@ describe("OrchestrationEngine", () => {
|
||||
projectId: asProjectId("project-turn-diff"),
|
||||
title: "Turn diff thread",
|
||||
model: "gpt-5-codex",
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "approval-required",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
createdAt,
|
||||
@@ -351,8 +342,6 @@ describe("OrchestrationEngine", () => {
|
||||
projectId: asProjectId("project-flaky"),
|
||||
title: "flaky-fail",
|
||||
model: "gpt-5-codex",
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "approval-required",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
createdAt,
|
||||
@@ -368,8 +357,6 @@ describe("OrchestrationEngine", () => {
|
||||
projectId: asProjectId("project-flaky"),
|
||||
title: "flaky-ok",
|
||||
model: "gpt-5-codex",
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "approval-required",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
createdAt,
|
||||
@@ -433,8 +420,6 @@ describe("OrchestrationEngine", () => {
|
||||
projectId: asProjectId("project-atomic"),
|
||||
title: "atomic",
|
||||
model: "gpt-5-codex",
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "approval-required",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
createdAt,
|
||||
@@ -451,8 +436,8 @@ describe("OrchestrationEngine", () => {
|
||||
text: "hello",
|
||||
attachments: [],
|
||||
},
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "approval-required" as const,
|
||||
approvalPolicy: "on-request" as const,
|
||||
sandboxMode: "workspace-write" as const,
|
||||
createdAt,
|
||||
};
|
||||
|
||||
@@ -568,8 +553,6 @@ describe("OrchestrationEngine", () => {
|
||||
projectId: asProjectId("project-sync"),
|
||||
title: "sync-before",
|
||||
model: "gpt-5-codex",
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "approval-required",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
createdAt,
|
||||
@@ -613,8 +596,8 @@ describe("OrchestrationEngine", () => {
|
||||
text: "hello",
|
||||
attachments: [],
|
||||
},
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "approval-required",
|
||||
approvalPolicy: "on-request",
|
||||
sandboxMode: "workspace-write",
|
||||
createdAt: now(),
|
||||
}),
|
||||
),
|
||||
@@ -648,8 +631,6 @@ describe("OrchestrationEngine", () => {
|
||||
projectId: asProjectId("project-duplicate"),
|
||||
title: "duplicate",
|
||||
model: "gpt-5-codex",
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "approval-required",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
createdAt,
|
||||
@@ -665,8 +646,6 @@ describe("OrchestrationEngine", () => {
|
||||
projectId: asProjectId("project-duplicate"),
|
||||
title: "duplicate",
|
||||
model: "gpt-5-codex",
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "approval-required",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
createdAt,
|
||||
|
||||
@@ -4,6 +4,8 @@ import {
|
||||
CorrelationId,
|
||||
EventId,
|
||||
MessageId,
|
||||
ProviderSessionId,
|
||||
ProviderThreadId,
|
||||
ProjectId,
|
||||
ThreadId,
|
||||
TurnId,
|
||||
@@ -102,7 +104,6 @@ projectionLayer("OrchestrationProjectionPipeline", (it) => {
|
||||
projectId: ProjectId.makeUnsafe("project-1"),
|
||||
title: "Thread 1",
|
||||
model: "gpt-5-codex",
|
||||
runtimeMode: "full-access",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
createdAt: now,
|
||||
@@ -373,7 +374,6 @@ projectionLayer("OrchestrationProjectionPipeline", (it) => {
|
||||
projectId: ProjectId.makeUnsafe("project-clear-attachments"),
|
||||
title: "Thread Clear Attachments",
|
||||
model: "gpt-5-codex",
|
||||
runtimeMode: "full-access",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
createdAt: now,
|
||||
@@ -500,7 +500,6 @@ projectionLayer("OrchestrationProjectionPipeline", (it) => {
|
||||
projectId: ProjectId.makeUnsafe("project-overwrite"),
|
||||
title: "Thread Overwrite",
|
||||
model: "gpt-5-codex",
|
||||
runtimeMode: "full-access",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
createdAt: now,
|
||||
@@ -651,7 +650,6 @@ projectionLayer("OrchestrationProjectionPipeline", (it) => {
|
||||
projectId: ProjectId.makeUnsafe("project-rollback"),
|
||||
title: "Thread Rollback",
|
||||
model: "gpt-5-codex",
|
||||
runtimeMode: "full-access",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
createdAt: now,
|
||||
@@ -782,7 +780,6 @@ projectionLayer("OrchestrationProjectionPipeline", (it) => {
|
||||
projectId: ProjectId.makeUnsafe("project-revert-files"),
|
||||
title: "Thread Revert Files",
|
||||
model: "gpt-5-codex",
|
||||
runtimeMode: "full-access",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
createdAt: now,
|
||||
@@ -997,7 +994,6 @@ projectionLayer("OrchestrationProjectionPipeline", (it) => {
|
||||
projectId: ProjectId.makeUnsafe("project-delete-files"),
|
||||
title: "Thread Delete Files",
|
||||
model: "gpt-5-codex",
|
||||
runtimeMode: "full-access",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
createdAt: now,
|
||||
@@ -1160,7 +1156,6 @@ projectionLayer("OrchestrationProjectionPipeline", (it) => {
|
||||
projectId: ProjectId.makeUnsafe("project-a"),
|
||||
title: "Thread A",
|
||||
model: "gpt-5-codex",
|
||||
runtimeMode: "full-access",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
createdAt: now,
|
||||
@@ -1284,7 +1279,6 @@ projectionLayer("OrchestrationProjectionPipeline", (it) => {
|
||||
projectId: ProjectId.makeUnsafe("project-empty"),
|
||||
title: "Thread Empty",
|
||||
model: "gpt-5-codex",
|
||||
runtimeMode: "full-access",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
createdAt: now,
|
||||
@@ -1421,7 +1415,6 @@ projectionLayer("OrchestrationProjectionPipeline", (it) => {
|
||||
projectId: ProjectId.makeUnsafe("project-conflict"),
|
||||
title: "Thread Conflict",
|
||||
model: "gpt-5-codex",
|
||||
runtimeMode: "full-access",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
createdAt: "2026-02-26T13:00:01.000Z",
|
||||
@@ -1562,7 +1555,6 @@ projectionLayer("OrchestrationProjectionPipeline", (it) => {
|
||||
projectId: ProjectId.makeUnsafe("project-revert"),
|
||||
title: "Thread Revert",
|
||||
model: "gpt-5-codex",
|
||||
runtimeMode: "full-access",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
createdAt: "2026-02-26T12:00:01.000Z",
|
||||
@@ -1757,7 +1749,8 @@ it.effect("restores pending turn-start metadata across projection pipeline resta
|
||||
payload: {
|
||||
threadId,
|
||||
messageId,
|
||||
runtimeMode: "approval-required",
|
||||
approvalPolicy: "on-request",
|
||||
sandboxMode: "workspace-write",
|
||||
createdAt: turnStartedAt,
|
||||
},
|
||||
});
|
||||
@@ -1779,14 +1772,20 @@ it.effect("restores pending turn-start metadata across projection pipeline resta
|
||||
commandId: CommandId.makeUnsafe("cmd-restart-2"),
|
||||
causationEventId: null,
|
||||
correlationId: CorrelationId.makeUnsafe("cmd-restart-2"),
|
||||
metadata: {},
|
||||
metadata: {
|
||||
providerSessionId: ProviderSessionId.makeUnsafe("provider-session-restart"),
|
||||
providerThreadId: ProviderThreadId.makeUnsafe("provider-thread-restart"),
|
||||
},
|
||||
payload: {
|
||||
threadId,
|
||||
session: {
|
||||
threadId,
|
||||
status: "running",
|
||||
providerName: "codex",
|
||||
runtimeMode: "approval-required",
|
||||
providerSessionId: ProviderSessionId.makeUnsafe("provider-session-restart"),
|
||||
providerThreadId: ProviderThreadId.makeUnsafe("provider-thread-restart"),
|
||||
approvalPolicy: "on-request",
|
||||
sandboxMode: "workspace-write",
|
||||
activeTurnId: turnId,
|
||||
lastError: null,
|
||||
updatedAt: sessionSetAt,
|
||||
|
||||
@@ -18,10 +18,6 @@ import {
|
||||
type ProjectionThreadMessage,
|
||||
ProjectionThreadMessageRepository,
|
||||
} from "../../persistence/Services/ProjectionThreadMessages.ts";
|
||||
import {
|
||||
type ProjectionThreadProposedPlan,
|
||||
ProjectionThreadProposedPlanRepository,
|
||||
} from "../../persistence/Services/ProjectionThreadProposedPlans.ts";
|
||||
import { ProjectionThreadSessionRepository } from "../../persistence/Services/ProjectionThreadSessions.ts";
|
||||
import {
|
||||
type ProjectionTurn,
|
||||
@@ -33,7 +29,6 @@ import { ProjectionProjectRepositoryLive } from "../../persistence/Layers/Projec
|
||||
import { ProjectionStateRepositoryLive } from "../../persistence/Layers/ProjectionState.ts";
|
||||
import { ProjectionThreadActivityRepositoryLive } from "../../persistence/Layers/ProjectionThreadActivities.ts";
|
||||
import { ProjectionThreadMessageRepositoryLive } from "../../persistence/Layers/ProjectionThreadMessages.ts";
|
||||
import { ProjectionThreadProposedPlanRepositoryLive } from "../../persistence/Layers/ProjectionThreadProposedPlans.ts";
|
||||
import { ProjectionThreadSessionRepositoryLive } from "../../persistence/Layers/ProjectionThreadSessions.ts";
|
||||
import { ProjectionTurnRepositoryLive } from "../../persistence/Layers/ProjectionTurns.ts";
|
||||
import { ProjectionThreadRepositoryLive } from "../../persistence/Layers/ProjectionThreads.ts";
|
||||
@@ -53,7 +48,6 @@ export const ORCHESTRATION_PROJECTOR_NAMES = {
|
||||
projects: "projection.projects",
|
||||
threads: "projection.threads",
|
||||
threadMessages: "projection.thread-messages",
|
||||
threadProposedPlans: "projection.thread-proposed-plans",
|
||||
threadActivities: "projection.thread-activities",
|
||||
threadSessions: "projection.thread-sessions",
|
||||
threadTurns: "projection.thread-turns",
|
||||
@@ -195,26 +189,6 @@ function retainProjectionActivitiesAfterRevert(
|
||||
);
|
||||
}
|
||||
|
||||
function retainProjectionProposedPlansAfterRevert(
|
||||
proposedPlans: ReadonlyArray<ProjectionThreadProposedPlan>,
|
||||
turns: ReadonlyArray<ProjectionTurn>,
|
||||
turnCount: number,
|
||||
): ReadonlyArray<ProjectionThreadProposedPlan> {
|
||||
const retainedTurnIds = new Set<string>(
|
||||
turns
|
||||
.filter(
|
||||
(turn) =>
|
||||
turn.turnId !== null &&
|
||||
turn.checkpointTurnCount !== null &&
|
||||
turn.checkpointTurnCount <= turnCount,
|
||||
)
|
||||
.flatMap((turn) => (turn.turnId === null ? [] : [turn.turnId])),
|
||||
);
|
||||
return proposedPlans.filter(
|
||||
(proposedPlan) => proposedPlan.turnId === null || retainedTurnIds.has(proposedPlan.turnId),
|
||||
);
|
||||
}
|
||||
|
||||
function collectThreadAttachmentRelativePaths(
|
||||
threadId: string,
|
||||
messages: ReadonlyArray<ProjectionThreadMessage>,
|
||||
@@ -346,7 +320,6 @@ const makeOrchestrationProjectionPipeline = Effect.gen(function* () {
|
||||
const projectionProjectRepository = yield* ProjectionProjectRepository;
|
||||
const projectionThreadRepository = yield* ProjectionThreadRepository;
|
||||
const projectionThreadMessageRepository = yield* ProjectionThreadMessageRepository;
|
||||
const projectionThreadProposedPlanRepository = yield* ProjectionThreadProposedPlanRepository;
|
||||
const projectionThreadActivityRepository = yield* ProjectionThreadActivityRepository;
|
||||
const projectionThreadSessionRepository = yield* ProjectionThreadSessionRepository;
|
||||
const projectionTurnRepository = yield* ProjectionTurnRepository;
|
||||
@@ -423,8 +396,6 @@ const makeOrchestrationProjectionPipeline = Effect.gen(function* () {
|
||||
projectId: event.payload.projectId,
|
||||
title: event.payload.title,
|
||||
model: event.payload.model,
|
||||
runtimeMode: event.payload.runtimeMode,
|
||||
interactionMode: event.payload.interactionMode,
|
||||
branch: event.payload.branch,
|
||||
worktreePath: event.payload.worktreePath,
|
||||
latestTurnId: null,
|
||||
@@ -454,36 +425,6 @@ const makeOrchestrationProjectionPipeline = Effect.gen(function* () {
|
||||
return;
|
||||
}
|
||||
|
||||
case "thread.runtime-mode-set": {
|
||||
const existingRow = yield* projectionThreadRepository.getById({
|
||||
threadId: event.payload.threadId,
|
||||
});
|
||||
if (Option.isNone(existingRow)) {
|
||||
return;
|
||||
}
|
||||
yield* projectionThreadRepository.upsert({
|
||||
...existingRow.value,
|
||||
runtimeMode: event.payload.runtimeMode,
|
||||
updatedAt: event.payload.updatedAt,
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
case "thread.interaction-mode-set": {
|
||||
const existingRow = yield* projectionThreadRepository.getById({
|
||||
threadId: event.payload.threadId,
|
||||
});
|
||||
if (Option.isNone(existingRow)) {
|
||||
return;
|
||||
}
|
||||
yield* projectionThreadRepository.upsert({
|
||||
...existingRow.value,
|
||||
interactionMode: event.payload.interactionMode,
|
||||
updatedAt: event.payload.updatedAt,
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
case "thread.deleted": {
|
||||
attachmentSideEffects.deletedThreadIds.add(event.payload.threadId);
|
||||
const existingRow = yield* projectionThreadRepository.getById({
|
||||
@@ -501,7 +442,6 @@ const makeOrchestrationProjectionPipeline = Effect.gen(function* () {
|
||||
}
|
||||
|
||||
case "thread.message-sent":
|
||||
case "thread.proposed-plan-upserted":
|
||||
case "thread.activity-appended": {
|
||||
const existingRow = yield* projectionThreadRepository.getById({
|
||||
threadId: event.payload.threadId,
|
||||
@@ -643,57 +583,6 @@ const makeOrchestrationProjectionPipeline = Effect.gen(function* () {
|
||||
}
|
||||
});
|
||||
|
||||
const applyThreadProposedPlansProjection: ProjectorDefinition["apply"] = (
|
||||
event,
|
||||
_attachmentSideEffects,
|
||||
) =>
|
||||
Effect.gen(function* () {
|
||||
switch (event.type) {
|
||||
case "thread.proposed-plan-upserted":
|
||||
yield* projectionThreadProposedPlanRepository.upsert({
|
||||
planId: event.payload.proposedPlan.id,
|
||||
threadId: event.payload.threadId,
|
||||
turnId: event.payload.proposedPlan.turnId,
|
||||
planMarkdown: event.payload.proposedPlan.planMarkdown,
|
||||
createdAt: event.payload.proposedPlan.createdAt,
|
||||
updatedAt: event.payload.proposedPlan.updatedAt,
|
||||
});
|
||||
return;
|
||||
|
||||
case "thread.reverted": {
|
||||
const existingRows = yield* projectionThreadProposedPlanRepository.listByThreadId({
|
||||
threadId: event.payload.threadId,
|
||||
});
|
||||
if (existingRows.length === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
const existingTurns = yield* projectionTurnRepository.listByThreadId({
|
||||
threadId: event.payload.threadId,
|
||||
});
|
||||
const keptRows = retainProjectionProposedPlansAfterRevert(
|
||||
existingRows,
|
||||
existingTurns,
|
||||
event.payload.turnCount,
|
||||
);
|
||||
if (keptRows.length === existingRows.length) {
|
||||
return;
|
||||
}
|
||||
|
||||
yield* projectionThreadProposedPlanRepository.deleteByThreadId({
|
||||
threadId: event.payload.threadId,
|
||||
});
|
||||
yield* Effect.forEach(keptRows, projectionThreadProposedPlanRepository.upsert, {
|
||||
concurrency: 1,
|
||||
}).pipe(Effect.asVoid);
|
||||
return;
|
||||
}
|
||||
|
||||
default:
|
||||
return;
|
||||
}
|
||||
});
|
||||
|
||||
const applyThreadActivitiesProjection: ProjectorDefinition["apply"] = (
|
||||
event,
|
||||
_attachmentSideEffects,
|
||||
@@ -709,9 +598,6 @@ const makeOrchestrationProjectionPipeline = Effect.gen(function* () {
|
||||
kind: event.payload.activity.kind,
|
||||
summary: event.payload.activity.summary,
|
||||
payload: event.payload.activity.payload,
|
||||
...(event.payload.activity.sequence !== undefined
|
||||
? { sequence: event.payload.activity.sequence }
|
||||
: {}),
|
||||
createdAt: event.payload.activity.createdAt,
|
||||
});
|
||||
return;
|
||||
@@ -760,7 +646,10 @@ const makeOrchestrationProjectionPipeline = Effect.gen(function* () {
|
||||
threadId: event.payload.threadId,
|
||||
status: event.payload.session.status,
|
||||
providerName: event.payload.session.providerName,
|
||||
runtimeMode: event.payload.session.runtimeMode,
|
||||
providerSessionId: event.payload.session.providerSessionId,
|
||||
providerThreadId: event.payload.session.providerThreadId,
|
||||
approvalPolicy: event.payload.session.approvalPolicy,
|
||||
sandboxMode: event.payload.session.sandboxMode,
|
||||
activeTurnId: event.payload.session.activeTurnId,
|
||||
lastError: event.payload.session.lastError,
|
||||
updatedAt: event.payload.session.updatedAt,
|
||||
@@ -1102,10 +991,6 @@ const makeOrchestrationProjectionPipeline = Effect.gen(function* () {
|
||||
name: ORCHESTRATION_PROJECTOR_NAMES.threadMessages,
|
||||
apply: applyThreadMessagesProjection,
|
||||
},
|
||||
{
|
||||
name: ORCHESTRATION_PROJECTOR_NAMES.threadProposedPlans,
|
||||
apply: applyThreadProposedPlansProjection,
|
||||
},
|
||||
{
|
||||
name: ORCHESTRATION_PROJECTOR_NAMES.threadActivities,
|
||||
apply: applyThreadActivitiesProjection,
|
||||
@@ -1225,7 +1110,6 @@ export const OrchestrationProjectionPipelineLive = Layer.effect(
|
||||
Layer.provideMerge(ProjectionProjectRepositoryLive),
|
||||
Layer.provideMerge(ProjectionThreadRepositoryLive),
|
||||
Layer.provideMerge(ProjectionThreadMessageRepositoryLive),
|
||||
Layer.provideMerge(ProjectionThreadProposedPlanRepositoryLive),
|
||||
Layer.provideMerge(ProjectionThreadActivityRepositoryLive),
|
||||
Layer.provideMerge(ProjectionThreadSessionRepositoryLive),
|
||||
Layer.provideMerge(ProjectionTurnRepositoryLive),
|
||||
|
||||
@@ -3,6 +3,8 @@ import {
|
||||
EventId,
|
||||
MessageId,
|
||||
ProjectId,
|
||||
ProviderSessionId,
|
||||
ProviderThreadId,
|
||||
ThreadId,
|
||||
TurnId,
|
||||
} from "@t3tools/contracts";
|
||||
@@ -20,6 +22,9 @@ const asTurnId = (value: string): TurnId => TurnId.makeUnsafe(value);
|
||||
const asMessageId = (value: string): MessageId => MessageId.makeUnsafe(value);
|
||||
const asEventId = (value: string): EventId => EventId.makeUnsafe(value);
|
||||
const asCheckpointRef = (value: string): CheckpointRef => CheckpointRef.makeUnsafe(value);
|
||||
const asProviderSessionId = (value: string): ProviderSessionId =>
|
||||
ProviderSessionId.makeUnsafe(value);
|
||||
const asProviderThreadId = (value: string): ProviderThreadId => ProviderThreadId.makeUnsafe(value);
|
||||
|
||||
const projectionSnapshotLayer = it.layer(
|
||||
OrchestrationProjectionSnapshotQueryLive.pipe(Layer.provideMerge(SqlitePersistenceMemory)),
|
||||
@@ -138,7 +143,8 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
|
||||
provider_name,
|
||||
provider_session_id,
|
||||
provider_thread_id,
|
||||
runtime_mode,
|
||||
approval_policy,
|
||||
sandbox_mode,
|
||||
active_turn_id,
|
||||
last_error,
|
||||
updated_at
|
||||
@@ -149,7 +155,8 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
|
||||
'codex',
|
||||
'provider-session-1',
|
||||
'provider-thread-1',
|
||||
'approval-required',
|
||||
'on-request',
|
||||
'workspace-write',
|
||||
'turn-1',
|
||||
NULL,
|
||||
'2026-02-24T00:00:07.000Z'
|
||||
@@ -234,8 +241,6 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
|
||||
projectId: asProjectId("project-1"),
|
||||
title: "Thread 1",
|
||||
model: "gpt-5-codex",
|
||||
interactionMode: "default",
|
||||
runtimeMode: "full-access",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
latestTurn: {
|
||||
@@ -260,7 +265,6 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
|
||||
updatedAt: "2026-02-24T00:00:05.000Z",
|
||||
},
|
||||
],
|
||||
proposedPlans: [],
|
||||
activities: [
|
||||
{
|
||||
id: asEventId("activity-1"),
|
||||
@@ -287,7 +291,10 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
status: "running",
|
||||
providerName: "codex",
|
||||
runtimeMode: "approval-required",
|
||||
providerSessionId: asProviderSessionId("provider-session-1"),
|
||||
providerThreadId: asProviderThreadId("provider-thread-1"),
|
||||
approvalPolicy: "on-request",
|
||||
sandboxMode: "workspace-write",
|
||||
activeTurnId: asTurnId("turn-1"),
|
||||
lastError: null,
|
||||
updatedAt: "2026-02-24T00:00:07.000Z",
|
||||
|
||||
@@ -2,7 +2,6 @@ import {
|
||||
ChatAttachment,
|
||||
IsoDateTime,
|
||||
MessageId,
|
||||
NonNegativeInt,
|
||||
OrchestrationCheckpointFile,
|
||||
OrchestrationReadModel,
|
||||
ProjectScript,
|
||||
@@ -10,7 +9,6 @@ import {
|
||||
type OrchestrationCheckpointSummary,
|
||||
type OrchestrationLatestTurn,
|
||||
type OrchestrationMessage,
|
||||
type OrchestrationProposedPlan,
|
||||
type OrchestrationProject,
|
||||
type OrchestrationSession,
|
||||
type OrchestrationThread,
|
||||
@@ -31,7 +29,6 @@ import { ProjectionProject } from "../../persistence/Services/ProjectionProjects
|
||||
import { ProjectionState } from "../../persistence/Services/ProjectionState.ts";
|
||||
import { ProjectionThreadActivity } from "../../persistence/Services/ProjectionThreadActivities.ts";
|
||||
import { ProjectionThreadMessage } from "../../persistence/Services/ProjectionThreadMessages.ts";
|
||||
import { ProjectionThreadProposedPlan } from "../../persistence/Services/ProjectionThreadProposedPlans.ts";
|
||||
import { ProjectionThreadSession } from "../../persistence/Services/ProjectionThreadSessions.ts";
|
||||
import { ProjectionThread } from "../../persistence/Services/ProjectionThreads.ts";
|
||||
import { ORCHESTRATION_PROJECTOR_NAMES } from "./ProjectionPipeline.ts";
|
||||
@@ -52,12 +49,10 @@ const ProjectionThreadMessageDbRowSchema = ProjectionThreadMessage.mapFields(
|
||||
attachments: Schema.NullOr(Schema.fromJsonString(Schema.Array(ChatAttachment))),
|
||||
}),
|
||||
);
|
||||
const ProjectionThreadProposedPlanDbRowSchema = ProjectionThreadProposedPlan;
|
||||
const ProjectionThreadDbRowSchema = ProjectionThread;
|
||||
const ProjectionThreadActivityDbRowSchema = ProjectionThreadActivity.mapFields(
|
||||
Struct.assign({
|
||||
payload: Schema.fromJsonString(Schema.Unknown),
|
||||
sequence: Schema.NullOr(NonNegativeInt),
|
||||
}),
|
||||
);
|
||||
const ProjectionThreadSessionDbRowSchema = ProjectionThreadSession;
|
||||
@@ -81,7 +76,6 @@ const REQUIRED_SNAPSHOT_PROJECTORS = [
|
||||
ORCHESTRATION_PROJECTOR_NAMES.projects,
|
||||
ORCHESTRATION_PROJECTOR_NAMES.threads,
|
||||
ORCHESTRATION_PROJECTOR_NAMES.threadMessages,
|
||||
ORCHESTRATION_PROJECTOR_NAMES.threadProposedPlans,
|
||||
ORCHESTRATION_PROJECTOR_NAMES.threadActivities,
|
||||
ORCHESTRATION_PROJECTOR_NAMES.threadSessions,
|
||||
ORCHESTRATION_PROJECTOR_NAMES.checkpoints,
|
||||
@@ -157,8 +151,6 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
project_id AS "projectId",
|
||||
title,
|
||||
model,
|
||||
runtime_mode AS "runtimeMode",
|
||||
interaction_mode AS "interactionMode",
|
||||
branch,
|
||||
worktree_path AS "worktreePath",
|
||||
latest_turn_id AS "latestTurnId",
|
||||
@@ -190,23 +182,6 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
`,
|
||||
});
|
||||
|
||||
const listThreadProposedPlanRows = SqlSchema.findAll({
|
||||
Request: Schema.Void,
|
||||
Result: ProjectionThreadProposedPlanDbRowSchema,
|
||||
execute: () =>
|
||||
sql`
|
||||
SELECT
|
||||
plan_id AS "planId",
|
||||
thread_id AS "threadId",
|
||||
turn_id AS "turnId",
|
||||
plan_markdown AS "planMarkdown",
|
||||
created_at AS "createdAt",
|
||||
updated_at AS "updatedAt"
|
||||
FROM projection_thread_proposed_plans
|
||||
ORDER BY thread_id ASC, created_at ASC, plan_id ASC
|
||||
`,
|
||||
});
|
||||
|
||||
const listThreadActivityRows = SqlSchema.findAll({
|
||||
Request: Schema.Void,
|
||||
Result: ProjectionThreadActivityDbRowSchema,
|
||||
@@ -220,15 +195,9 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
kind,
|
||||
summary,
|
||||
payload_json AS "payload",
|
||||
sequence,
|
||||
created_at AS "createdAt"
|
||||
FROM projection_thread_activities
|
||||
ORDER BY
|
||||
thread_id ASC,
|
||||
CASE WHEN sequence IS NULL THEN 0 ELSE 1 END ASC,
|
||||
sequence ASC,
|
||||
created_at ASC,
|
||||
activity_id ASC
|
||||
ORDER BY thread_id ASC, created_at ASC, activity_id ASC
|
||||
`,
|
||||
});
|
||||
|
||||
@@ -243,7 +212,8 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
provider_name AS "providerName",
|
||||
provider_session_id AS "providerSessionId",
|
||||
provider_thread_id AS "providerThreadId",
|
||||
runtime_mode AS "runtimeMode",
|
||||
approval_policy AS "approvalPolicy",
|
||||
sandbox_mode AS "sandboxMode",
|
||||
active_turn_id AS "activeTurnId",
|
||||
last_error AS "lastError",
|
||||
updated_at AS "updatedAt"
|
||||
@@ -312,7 +282,6 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
projectRows,
|
||||
threadRows,
|
||||
messageRows,
|
||||
proposedPlanRows,
|
||||
activityRows,
|
||||
sessionRows,
|
||||
checkpointRows,
|
||||
@@ -343,14 +312,6 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
),
|
||||
),
|
||||
),
|
||||
listThreadProposedPlanRows(undefined).pipe(
|
||||
Effect.mapError(
|
||||
toPersistenceSqlOrDecodeError(
|
||||
"ProjectionSnapshotQuery.getSnapshot:listThreadProposedPlans:query",
|
||||
"ProjectionSnapshotQuery.getSnapshot:listThreadProposedPlans:decodeRows",
|
||||
),
|
||||
),
|
||||
),
|
||||
listThreadActivityRows(undefined).pipe(
|
||||
Effect.mapError(
|
||||
toPersistenceSqlOrDecodeError(
|
||||
@@ -394,7 +355,6 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
]);
|
||||
|
||||
const messagesByThread = new Map<string, Array<OrchestrationMessage>>();
|
||||
const proposedPlansByThread = new Map<string, Array<OrchestrationProposedPlan>>();
|
||||
const activitiesByThread = new Map<string, Array<OrchestrationThreadActivity>>();
|
||||
const checkpointsByThread = new Map<string, Array<OrchestrationCheckpointSummary>>();
|
||||
const sessionsByThread = new Map<string, OrchestrationSession>();
|
||||
@@ -428,19 +388,6 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
messagesByThread.set(row.threadId, threadMessages);
|
||||
}
|
||||
|
||||
for (const row of proposedPlanRows) {
|
||||
updatedAt = maxIso(updatedAt, row.updatedAt);
|
||||
const threadProposedPlans = proposedPlansByThread.get(row.threadId) ?? [];
|
||||
threadProposedPlans.push({
|
||||
id: row.planId,
|
||||
turnId: row.turnId,
|
||||
planMarkdown: row.planMarkdown,
|
||||
createdAt: row.createdAt,
|
||||
updatedAt: row.updatedAt,
|
||||
});
|
||||
proposedPlansByThread.set(row.threadId, threadProposedPlans);
|
||||
}
|
||||
|
||||
for (const row of activityRows) {
|
||||
updatedAt = maxIso(updatedAt, row.createdAt);
|
||||
const threadActivities = activitiesByThread.get(row.threadId) ?? [];
|
||||
@@ -451,7 +398,6 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
summary: row.summary,
|
||||
payload: row.payload,
|
||||
turnId: row.turnId,
|
||||
...(row.sequence !== null ? { sequence: row.sequence } : {}),
|
||||
createdAt: row.createdAt,
|
||||
});
|
||||
activitiesByThread.set(row.threadId, threadActivities);
|
||||
@@ -506,7 +452,10 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
threadId: row.threadId,
|
||||
status: row.status,
|
||||
providerName: row.providerName,
|
||||
runtimeMode: row.runtimeMode,
|
||||
providerSessionId: row.providerSessionId,
|
||||
providerThreadId: row.providerThreadId,
|
||||
approvalPolicy: row.approvalPolicy,
|
||||
sandboxMode: row.sandboxMode,
|
||||
activeTurnId: row.activeTurnId,
|
||||
lastError: row.lastError,
|
||||
updatedAt: row.updatedAt,
|
||||
@@ -529,8 +478,6 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
projectId: row.projectId,
|
||||
title: row.title,
|
||||
model: row.model,
|
||||
runtimeMode: row.runtimeMode,
|
||||
interactionMode: row.interactionMode,
|
||||
branch: row.branch,
|
||||
worktreePath: row.worktreePath,
|
||||
latestTurn: latestTurnByThread.get(row.threadId) ?? null,
|
||||
@@ -538,7 +485,6 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
updatedAt: row.updatedAt,
|
||||
deletedAt: row.deletedAt,
|
||||
messages: messagesByThread.get(row.threadId) ?? [],
|
||||
proposedPlans: proposedPlansByThread.get(row.threadId) ?? [],
|
||||
activities: activitiesByThread.get(row.threadId) ?? [],
|
||||
checkpoints: checkpointsByThread.get(row.threadId) ?? [],
|
||||
session: sessionsByThread.get(row.threadId) ?? null,
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -3,19 +3,19 @@ import {
|
||||
CommandId,
|
||||
EventId,
|
||||
type OrchestrationEvent,
|
||||
type ProviderModelOptions,
|
||||
type ProviderApprovalPolicy,
|
||||
type ProviderKind,
|
||||
type ProviderSandboxMode,
|
||||
type OrchestrationSession,
|
||||
ThreadId,
|
||||
type ThreadId,
|
||||
type ProviderSession,
|
||||
type RuntimeMode,
|
||||
type ProviderThreadId,
|
||||
type TurnId,
|
||||
} from "@t3tools/contracts";
|
||||
import { Cache, Cause, Duration, Effect, Layer, Option, Queue, Schema, Stream } from "effect";
|
||||
import { Cache, Cause, Duration, Effect, Layer, Option, Queue, Stream } from "effect";
|
||||
|
||||
import { resolveThreadWorkspaceCwd } from "../../checkpointing/Utils.ts";
|
||||
import { GitCore } from "../../git/Services/GitCore.ts";
|
||||
import { ProviderAdapterRequestError } from "../../provider/Errors.ts";
|
||||
import { TextGeneration } from "../../git/Services/TextGeneration.ts";
|
||||
import { ProviderService } from "../../provider/Services/ProviderService.ts";
|
||||
import { OrchestrationEngineService } from "../Services/OrchestrationEngine.ts";
|
||||
@@ -28,11 +28,9 @@ type ProviderIntentEvent = Extract<
|
||||
OrchestrationEvent,
|
||||
{
|
||||
type:
|
||||
| "thread.runtime-mode-set"
|
||||
| "thread.turn-start-requested"
|
||||
| "thread.turn-interrupt-requested"
|
||||
| "thread.approval-response-requested"
|
||||
| "thread.user-input-response-requested"
|
||||
| "thread.session-stop-requested";
|
||||
}
|
||||
>;
|
||||
@@ -68,36 +66,11 @@ const serverCommandId = (tag: string): CommandId =>
|
||||
|
||||
const HANDLED_TURN_START_KEY_MAX = 10_000;
|
||||
const HANDLED_TURN_START_KEY_TTL = Duration.minutes(30);
|
||||
const DEFAULT_RUNTIME_MODE: RuntimeMode = "full-access";
|
||||
const DEFAULT_APPROVAL_POLICY: ProviderApprovalPolicy = "never";
|
||||
const DEFAULT_SANDBOX_MODE: ProviderSandboxMode = "workspace-write";
|
||||
const WORKTREE_BRANCH_PREFIX = "t3code";
|
||||
const TEMP_WORKTREE_BRANCH_PATTERN = new RegExp(`^${WORKTREE_BRANCH_PREFIX}\\/[0-9a-f]{8}$`);
|
||||
|
||||
function toErrorMessage(error: unknown): string {
|
||||
if (error instanceof Error && error.message.trim().length > 0) {
|
||||
return error.message;
|
||||
}
|
||||
try {
|
||||
return JSON.stringify(error);
|
||||
} catch {
|
||||
return String(error);
|
||||
}
|
||||
}
|
||||
|
||||
function isUnknownPendingApprovalRequestError(error: unknown): boolean {
|
||||
if (Schema.is(ProviderAdapterRequestError)(error)) {
|
||||
const detail = error.detail.toLowerCase();
|
||||
return (
|
||||
detail.includes("unknown pending approval request") ||
|
||||
detail.includes("unknown pending permission request")
|
||||
);
|
||||
}
|
||||
const message = toErrorMessage(error).toLowerCase();
|
||||
return (
|
||||
message.includes("unknown pending approval request") ||
|
||||
message.includes("unknown pending permission request")
|
||||
);
|
||||
}
|
||||
|
||||
function isTemporaryWorktreeBranch(branch: string): boolean {
|
||||
return TEMP_WORKTREE_BRANCH_PATTERN.test(branch.trim().toLowerCase());
|
||||
}
|
||||
@@ -149,13 +122,11 @@ const make = Effect.gen(function* () {
|
||||
| "provider.turn.start.failed"
|
||||
| "provider.turn.interrupt.failed"
|
||||
| "provider.approval.respond.failed"
|
||||
| "provider.user-input.respond.failed"
|
||||
| "provider.session.stop.failed";
|
||||
readonly summary: string;
|
||||
readonly detail: string;
|
||||
readonly turnId: TurnId | null;
|
||||
readonly createdAt: string;
|
||||
readonly requestId?: string;
|
||||
}) =>
|
||||
orchestrationEngine.dispatch({
|
||||
type: "thread.activity.append",
|
||||
@@ -168,7 +139,6 @@ const make = Effect.gen(function* () {
|
||||
summary: input.summary,
|
||||
payload: {
|
||||
detail: input.detail,
|
||||
...(input.requestId ? { requestId: input.requestId } : {}),
|
||||
},
|
||||
turnId: input.turnId,
|
||||
createdAt: input.createdAt,
|
||||
@@ -198,9 +168,8 @@ const make = Effect.gen(function* () {
|
||||
threadId: ThreadId,
|
||||
createdAt: string,
|
||||
options?: {
|
||||
readonly provider?: ProviderKind;
|
||||
readonly model?: string;
|
||||
readonly modelOptions?: ProviderModelOptions;
|
||||
readonly approvalPolicy?: ProviderApprovalPolicy;
|
||||
readonly sandboxMode?: ProviderSandboxMode;
|
||||
},
|
||||
) {
|
||||
const readModel = yield* orchestrationEngine.getReadModel();
|
||||
@@ -209,39 +178,27 @@ const make = Effect.gen(function* () {
|
||||
return yield* Effect.die(new Error(`Thread '${threadId}' was not found in read model.`));
|
||||
}
|
||||
|
||||
const desiredRuntimeMode = thread.runtimeMode;
|
||||
const currentProvider: ProviderKind | undefined =
|
||||
thread.session?.providerName === "codex" ||
|
||||
thread.session?.providerName === "claudeCode" ||
|
||||
thread.session?.providerName === "cursor"
|
||||
const desiredApprovalPolicy =
|
||||
options?.approvalPolicy ?? thread.session?.approvalPolicy ?? DEFAULT_APPROVAL_POLICY;
|
||||
const desiredSandboxMode =
|
||||
options?.sandboxMode ?? thread.session?.sandboxMode ?? DEFAULT_SANDBOX_MODE;
|
||||
const preferredProvider: ProviderKind | undefined =
|
||||
thread.session?.providerName === "codex" || thread.session?.providerName === "claudeCode"
|
||||
? thread.session.providerName
|
||||
: undefined;
|
||||
const preferredProvider: ProviderKind | undefined = options?.provider ?? currentProvider;
|
||||
const desiredModel = options?.model ?? thread.model;
|
||||
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?: ProviderKind;
|
||||
}) =>
|
||||
const startProviderSession = (resumeThreadId?: ProviderThreadId | null) =>
|
||||
providerService.startSession(threadId, {
|
||||
threadId,
|
||||
...(input?.provider ?? preferredProvider
|
||||
? { provider: input?.provider ?? preferredProvider }
|
||||
: {}),
|
||||
...(preferredProvider ? { provider: preferredProvider } : {}),
|
||||
...(effectiveCwd ? { cwd: effectiveCwd } : {}),
|
||||
...(desiredModel ? { model: desiredModel } : {}),
|
||||
...(options?.modelOptions !== undefined ? { modelOptions: options.modelOptions } : {}),
|
||||
...(input?.resumeCursor !== undefined ? { resumeCursor: input.resumeCursor } : {}),
|
||||
runtimeMode: desiredRuntimeMode,
|
||||
...(thread.model ? { model: thread.model } : {}),
|
||||
...(resumeThreadId ? { resumeThreadId } : {}),
|
||||
approvalPolicy: desiredApprovalPolicy,
|
||||
sandboxMode: desiredSandboxMode,
|
||||
});
|
||||
|
||||
const bindSessionToThread = (session: ProviderSession) =>
|
||||
@@ -251,7 +208,10 @@ const make = Effect.gen(function* () {
|
||||
threadId,
|
||||
status: mapProviderSessionStatusToOrchestrationStatus(session.status),
|
||||
providerName: session.provider,
|
||||
runtimeMode: desiredRuntimeMode,
|
||||
providerSessionId: session.sessionId,
|
||||
providerThreadId: session.threadId ?? null,
|
||||
approvalPolicy: desiredApprovalPolicy,
|
||||
sandboxMode: desiredSandboxMode,
|
||||
// Provider turn ids are not orchestration turn ids.
|
||||
activeTurnId: null,
|
||||
lastError: session.lastError ?? null,
|
||||
@@ -260,102 +220,66 @@ const make = Effect.gen(function* () {
|
||||
createdAt,
|
||||
});
|
||||
|
||||
const existingSessionThreadId =
|
||||
thread.session && thread.session.status !== "stopped" ? thread.id : null;
|
||||
if (existingSessionThreadId) {
|
||||
const runtimeModeChanged = thread.runtimeMode !== thread.session?.runtimeMode;
|
||||
const providerChanged = options?.provider !== undefined && options.provider !== currentProvider;
|
||||
const activeSession = yield* resolveActiveSession(existingSessionThreadId);
|
||||
const sessionModelSwitch =
|
||||
currentProvider === undefined
|
||||
? "in-session"
|
||||
: (yield* providerService.getCapabilities(currentProvider)).sessionModelSwitch;
|
||||
const modelChanged =
|
||||
options?.model !== undefined && options.model !== activeSession?.model;
|
||||
const shouldRestartForModelChange =
|
||||
modelChanged && sessionModelSwitch === "restart-session";
|
||||
const existingSessionId = thread.session?.providerSessionId;
|
||||
if (existingSessionId) {
|
||||
const approvalPolicyChanged =
|
||||
options?.approvalPolicy !== undefined &&
|
||||
options.approvalPolicy !== thread.session?.approvalPolicy;
|
||||
const sandboxModeChanged =
|
||||
options?.sandboxMode !== undefined && options.sandboxMode !== thread.session?.sandboxMode;
|
||||
|
||||
if (!runtimeModeChanged && !providerChanged && !shouldRestartForModelChange) {
|
||||
return existingSessionThreadId;
|
||||
if (!approvalPolicyChanged && !sandboxModeChanged) {
|
||||
return existingSessionId;
|
||||
}
|
||||
|
||||
const resumeCursor =
|
||||
providerChanged || shouldRestartForModelChange
|
||||
? undefined
|
||||
: (activeSession?.resumeCursor ?? undefined);
|
||||
yield* Effect.logInfo("provider command reactor restarting provider session", {
|
||||
threadId,
|
||||
existingSessionThreadId,
|
||||
currentProvider,
|
||||
desiredProvider: options?.provider ?? currentProvider,
|
||||
currentRuntimeMode: thread.session?.runtimeMode,
|
||||
desiredRuntimeMode: thread.runtimeMode,
|
||||
runtimeModeChanged,
|
||||
providerChanged,
|
||||
modelChanged,
|
||||
shouldRestartForModelChange,
|
||||
hasResumeCursor: resumeCursor !== undefined,
|
||||
});
|
||||
const restartedSession = yield* startProviderSession({
|
||||
...(resumeCursor !== undefined ? { resumeCursor } : {}),
|
||||
...(options?.provider !== undefined ? { provider: options.provider } : {}),
|
||||
});
|
||||
yield* Effect.logInfo("provider command reactor restarted provider session", {
|
||||
threadId,
|
||||
previousSessionId: existingSessionThreadId,
|
||||
restartedSessionThreadId: restartedSession.threadId,
|
||||
provider: restartedSession.provider,
|
||||
runtimeMode: restartedSession.runtimeMode,
|
||||
});
|
||||
const restartedSession = yield* startProviderSession(
|
||||
thread.session?.providerThreadId ?? null,
|
||||
);
|
||||
yield* bindSessionToThread(restartedSession);
|
||||
return restartedSession.threadId;
|
||||
yield* providerService.stopSession({ sessionId: existingSessionId }).pipe(
|
||||
Effect.catchCause((cause) =>
|
||||
Effect.logWarning("provider command reactor failed to stop superseded provider session", {
|
||||
threadId,
|
||||
sessionId: existingSessionId,
|
||||
cause: Cause.pretty(cause),
|
||||
}),
|
||||
),
|
||||
);
|
||||
return restartedSession.sessionId;
|
||||
}
|
||||
|
||||
const startedSession = yield* startProviderSession(
|
||||
options?.provider !== undefined ? { provider: options.provider } : undefined,
|
||||
);
|
||||
const startedSession = yield* startProviderSession();
|
||||
yield* bindSessionToThread(startedSession);
|
||||
return startedSession.threadId;
|
||||
return startedSession.sessionId;
|
||||
});
|
||||
|
||||
const sendTurnForThread = Effect.fnUntraced(function* (input: {
|
||||
readonly threadId: ThreadId;
|
||||
readonly messageText: string;
|
||||
readonly attachments?: ReadonlyArray<ChatAttachment>;
|
||||
readonly provider?: ProviderKind;
|
||||
readonly model?: string;
|
||||
readonly modelOptions?: ProviderModelOptions;
|
||||
readonly interactionMode?: "default" | "plan";
|
||||
readonly effort?: string;
|
||||
readonly approvalPolicy: ProviderApprovalPolicy;
|
||||
readonly sandboxMode: ProviderSandboxMode;
|
||||
readonly createdAt: string;
|
||||
}) {
|
||||
const thread = yield* resolveThread(input.threadId);
|
||||
if (!thread) {
|
||||
return;
|
||||
}
|
||||
yield* ensureSessionForThread(input.threadId, input.createdAt, {
|
||||
...(input.provider !== undefined ? { provider: input.provider } : {}),
|
||||
...(input.model !== undefined ? { model: input.model } : {}),
|
||||
...(input.modelOptions !== undefined ? { modelOptions: input.modelOptions } : {}),
|
||||
const sessionId = yield* ensureSessionForThread(input.threadId, input.createdAt, {
|
||||
approvalPolicy: input.approvalPolicy,
|
||||
sandboxMode: input.sandboxMode,
|
||||
});
|
||||
const normalizedInput = toNonEmptyProviderInput(input.messageText);
|
||||
const normalizedAttachments = input.attachments ?? [];
|
||||
const activeSession = yield* providerService.listSessions().pipe(
|
||||
Effect.map((sessions) => sessions.find((session) => session.threadId === input.threadId)),
|
||||
);
|
||||
const sessionModelSwitch =
|
||||
activeSession === undefined
|
||||
? "in-session"
|
||||
: (yield* providerService.getCapabilities(activeSession.provider)).sessionModelSwitch;
|
||||
const modelForTurn =
|
||||
sessionModelSwitch === "unsupported" ? activeSession?.model : input.model;
|
||||
|
||||
yield* providerService.sendTurn({
|
||||
threadId: input.threadId,
|
||||
sessionId,
|
||||
...(normalizedInput ? { input: normalizedInput } : {}),
|
||||
...(normalizedAttachments.length > 0 ? { attachments: normalizedAttachments } : {}),
|
||||
...(modelForTurn !== undefined ? { model: modelForTurn } : {}),
|
||||
...(input.modelOptions !== undefined ? { modelOptions: input.modelOptions } : {}),
|
||||
...(input.interactionMode !== undefined ? { interactionMode: input.interactionMode } : {}),
|
||||
...(input.model !== undefined ? { model: input.model } : {}),
|
||||
...(input.effort !== undefined ? { effort: input.effort } : {}),
|
||||
});
|
||||
});
|
||||
|
||||
@@ -466,10 +390,10 @@ const make = Effect.gen(function* () {
|
||||
threadId: event.payload.threadId,
|
||||
messageText: message.text,
|
||||
...(message.attachments !== undefined ? { attachments: message.attachments } : {}),
|
||||
...(event.payload.provider !== undefined ? { provider: event.payload.provider } : {}),
|
||||
...(event.payload.model !== undefined ? { model: event.payload.model } : {}),
|
||||
...(event.payload.modelOptions !== undefined ? { modelOptions: event.payload.modelOptions } : {}),
|
||||
interactionMode: event.payload.interactionMode,
|
||||
...(event.payload.effort !== undefined ? { effort: event.payload.effort } : {}),
|
||||
approvalPolicy: event.payload.approvalPolicy,
|
||||
sandboxMode: event.payload.sandboxMode,
|
||||
createdAt: event.payload.createdAt,
|
||||
});
|
||||
});
|
||||
@@ -481,8 +405,8 @@ const make = Effect.gen(function* () {
|
||||
if (!thread) {
|
||||
return;
|
||||
}
|
||||
const hasSession = thread.session && thread.session.status !== "stopped";
|
||||
if (!hasSession) {
|
||||
const sessionId = thread.session?.providerSessionId;
|
||||
if (!sessionId) {
|
||||
return yield* appendProviderFailureActivity({
|
||||
threadId: event.payload.threadId,
|
||||
kind: "provider.turn.interrupt.failed",
|
||||
@@ -494,7 +418,7 @@ const make = Effect.gen(function* () {
|
||||
}
|
||||
|
||||
// Orchestration turn ids are not provider turn ids, so interrupt by session.
|
||||
yield* providerService.interruptTurn({ threadId: event.payload.threadId });
|
||||
yield* providerService.interruptTurn({ sessionId });
|
||||
});
|
||||
|
||||
const processApprovalResponseRequested = Effect.fnUntraced(function* (
|
||||
@@ -504,8 +428,8 @@ const make = Effect.gen(function* () {
|
||||
if (!thread) {
|
||||
return;
|
||||
}
|
||||
const hasSession = thread.session && thread.session.status !== "stopped";
|
||||
if (!hasSession) {
|
||||
const sessionId = thread.session?.providerSessionId;
|
||||
if (!sessionId) {
|
||||
return yield* appendProviderFailureActivity({
|
||||
threadId: event.payload.threadId,
|
||||
kind: "provider.approval.respond.failed",
|
||||
@@ -513,79 +437,14 @@ const make = Effect.gen(function* () {
|
||||
detail: "No active provider session is bound to this thread.",
|
||||
turnId: null,
|
||||
createdAt: event.payload.createdAt,
|
||||
requestId: event.payload.requestId,
|
||||
});
|
||||
}
|
||||
|
||||
yield* providerService
|
||||
.respondToRequest({
|
||||
threadId: event.payload.threadId,
|
||||
requestId: event.payload.requestId,
|
||||
decision: event.payload.decision,
|
||||
})
|
||||
.pipe(
|
||||
Effect.catchCause((cause) =>
|
||||
Effect.gen(function* () {
|
||||
const error = Cause.squash(cause);
|
||||
const detail = toErrorMessage(error);
|
||||
yield* appendProviderFailureActivity({
|
||||
threadId: event.payload.threadId,
|
||||
kind: "provider.approval.respond.failed",
|
||||
summary: "Provider approval response failed",
|
||||
detail,
|
||||
turnId: null,
|
||||
createdAt: event.payload.createdAt,
|
||||
requestId: event.payload.requestId,
|
||||
});
|
||||
|
||||
if (!isUnknownPendingApprovalRequestError(error)) return;
|
||||
}),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
const processUserInputResponseRequested = Effect.fnUntraced(function* (
|
||||
event: Extract<ProviderIntentEvent, { type: "thread.user-input-response-requested" }>,
|
||||
) {
|
||||
const thread = yield* resolveThread(event.payload.threadId);
|
||||
if (!thread) {
|
||||
return;
|
||||
}
|
||||
const hasSession = thread.session && thread.session.status !== "stopped";
|
||||
if (!hasSession) {
|
||||
return yield* appendProviderFailureActivity({
|
||||
threadId: event.payload.threadId,
|
||||
kind: "provider.user-input.respond.failed",
|
||||
summary: "Provider user input response failed",
|
||||
detail: "No active provider session is bound to this thread.",
|
||||
turnId: null,
|
||||
createdAt: event.payload.createdAt,
|
||||
requestId: event.payload.requestId,
|
||||
});
|
||||
}
|
||||
|
||||
yield* providerService
|
||||
.respondToUserInput({
|
||||
threadId: event.payload.threadId,
|
||||
requestId: event.payload.requestId,
|
||||
answers: event.payload.answers,
|
||||
})
|
||||
.pipe(
|
||||
Effect.catchCause((cause) =>
|
||||
Effect.gen(function* () {
|
||||
const error = Cause.squash(cause);
|
||||
yield* appendProviderFailureActivity({
|
||||
threadId: event.payload.threadId,
|
||||
kind: "provider.user-input.respond.failed",
|
||||
summary: "Provider user input response failed",
|
||||
detail: toErrorMessage(error),
|
||||
turnId: null,
|
||||
createdAt: event.payload.createdAt,
|
||||
requestId: event.payload.requestId,
|
||||
});
|
||||
}),
|
||||
),
|
||||
);
|
||||
yield* providerService.respondToRequest({
|
||||
sessionId,
|
||||
requestId: event.payload.requestId,
|
||||
decision: event.payload.decision,
|
||||
});
|
||||
});
|
||||
|
||||
const processSessionStopRequested = Effect.fnUntraced(function* (
|
||||
@@ -597,8 +456,10 @@ const make = Effect.gen(function* () {
|
||||
}
|
||||
|
||||
const now = event.payload.createdAt;
|
||||
if (thread.session && thread.session.status !== "stopped") {
|
||||
yield* providerService.stopSession({ threadId: thread.id });
|
||||
const sessionId = thread.session?.providerSessionId;
|
||||
|
||||
if (sessionId) {
|
||||
yield* providerService.stopSession({ sessionId });
|
||||
}
|
||||
|
||||
yield* setThreadSession({
|
||||
@@ -607,7 +468,10 @@ const make = Effect.gen(function* () {
|
||||
threadId: thread.id,
|
||||
status: "stopped",
|
||||
providerName: thread.session?.providerName ?? null,
|
||||
runtimeMode: thread.session?.runtimeMode ?? DEFAULT_RUNTIME_MODE,
|
||||
providerSessionId: null,
|
||||
providerThreadId: null,
|
||||
approvalPolicy: thread.session?.approvalPolicy ?? DEFAULT_APPROVAL_POLICY,
|
||||
sandboxMode: thread.session?.sandboxMode ?? DEFAULT_SANDBOX_MODE,
|
||||
activeTurnId: null,
|
||||
lastError: thread.session?.lastError ?? null,
|
||||
updatedAt: now,
|
||||
@@ -619,14 +483,6 @@ const make = Effect.gen(function* () {
|
||||
const processDomainEvent = (event: ProviderIntentEvent) =>
|
||||
Effect.gen(function* () {
|
||||
switch (event.type) {
|
||||
case "thread.runtime-mode-set": {
|
||||
const thread = yield* resolveThread(event.payload.threadId);
|
||||
if (!thread?.session || thread.session.status === "stopped") {
|
||||
return;
|
||||
}
|
||||
yield* ensureSessionForThread(event.payload.threadId, event.occurredAt);
|
||||
return;
|
||||
}
|
||||
case "thread.turn-start-requested":
|
||||
yield* processTurnStartRequested(event);
|
||||
return;
|
||||
@@ -636,9 +492,6 @@ const make = Effect.gen(function* () {
|
||||
case "thread.approval-response-requested":
|
||||
yield* processApprovalResponseRequested(event);
|
||||
return;
|
||||
case "thread.user-input-response-requested":
|
||||
yield* processUserInputResponseRequested(event);
|
||||
return;
|
||||
case "thread.session-stop-requested":
|
||||
yield* processSessionStopRequested(event);
|
||||
return;
|
||||
@@ -669,11 +522,9 @@ const make = Effect.gen(function* () {
|
||||
yield* Effect.forkScoped(
|
||||
Stream.runForEach(orchestrationEngine.streamDomainEvents, (event) => {
|
||||
if (
|
||||
event.type !== "thread.runtime-mode-set" &&
|
||||
event.type !== "thread.turn-start-requested" &&
|
||||
event.type !== "thread.turn-interrupt-requested" &&
|
||||
event.type !== "thread.approval-response-requested" &&
|
||||
event.type !== "thread.user-input-response-requested" &&
|
||||
event.type !== "thread.session-stop-requested"
|
||||
) {
|
||||
return Effect.void;
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
@@ -4,11 +4,8 @@ import {
|
||||
ProjectDeletedPayload as ContractsProjectDeletedPayloadSchema,
|
||||
ThreadCreatedPayload as ContractsThreadCreatedPayloadSchema,
|
||||
ThreadMetaUpdatedPayload as ContractsThreadMetaUpdatedPayloadSchema,
|
||||
ThreadRuntimeModeSetPayload as ContractsThreadRuntimeModeSetPayloadSchema,
|
||||
ThreadInteractionModeSetPayload as ContractsThreadInteractionModeSetPayloadSchema,
|
||||
ThreadDeletedPayload as ContractsThreadDeletedPayloadSchema,
|
||||
ThreadMessageSentPayload as ContractsThreadMessageSentPayloadSchema,
|
||||
ThreadProposedPlanUpsertedPayload as ContractsThreadProposedPlanUpsertedPayloadSchema,
|
||||
ThreadSessionSetPayload as ContractsThreadSessionSetPayloadSchema,
|
||||
ThreadTurnDiffCompletedPayload as ContractsThreadTurnDiffCompletedPayloadSchema,
|
||||
ThreadRevertedPayload as ContractsThreadRevertedPayloadSchema,
|
||||
@@ -27,12 +24,9 @@ export const ProjectDeletedPayload = ContractsProjectDeletedPayloadSchema;
|
||||
|
||||
export const ThreadCreatedPayload = ContractsThreadCreatedPayloadSchema;
|
||||
export const ThreadMetaUpdatedPayload = ContractsThreadMetaUpdatedPayloadSchema;
|
||||
export const ThreadRuntimeModeSetPayload = ContractsThreadRuntimeModeSetPayloadSchema;
|
||||
export const ThreadInteractionModeSetPayload = ContractsThreadInteractionModeSetPayloadSchema;
|
||||
export const ThreadDeletedPayload = ContractsThreadDeletedPayloadSchema;
|
||||
|
||||
export const MessageSentPayloadSchema = ContractsThreadMessageSentPayloadSchema;
|
||||
export const ThreadProposedPlanUpsertedPayload = ContractsThreadProposedPlanUpsertedPayloadSchema;
|
||||
export const ThreadSessionSetPayload = ContractsThreadSessionSetPayloadSchema;
|
||||
export const ThreadTurnDiffCompletedPayload = ContractsThreadTurnDiffCompletedPayloadSchema;
|
||||
export const ThreadRevertedPayload = ContractsThreadRevertedPayloadSchema;
|
||||
|
||||
@@ -2,7 +2,6 @@ import { describe, expect, it } from "vitest";
|
||||
import {
|
||||
MessageId,
|
||||
CommandId,
|
||||
DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
ProjectId,
|
||||
ThreadId,
|
||||
type OrchestrationCommand,
|
||||
@@ -51,8 +50,6 @@ const readModel: OrchestrationReadModel = {
|
||||
projectId: ProjectId.makeUnsafe("project-a"),
|
||||
title: "Thread A",
|
||||
model: "gpt-5-codex",
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "full-access",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
createdAt: now,
|
||||
@@ -61,7 +58,6 @@ const readModel: OrchestrationReadModel = {
|
||||
messages: [],
|
||||
session: null,
|
||||
activities: [],
|
||||
proposedPlans: [],
|
||||
checkpoints: [],
|
||||
deletedAt: null,
|
||||
},
|
||||
@@ -70,8 +66,6 @@ const readModel: OrchestrationReadModel = {
|
||||
projectId: ProjectId.makeUnsafe("project-b"),
|
||||
title: "Thread B",
|
||||
model: "gpt-5-codex",
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "full-access",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
createdAt: now,
|
||||
@@ -80,7 +74,6 @@ const readModel: OrchestrationReadModel = {
|
||||
messages: [],
|
||||
session: null,
|
||||
activities: [],
|
||||
proposedPlans: [],
|
||||
checkpoints: [],
|
||||
deletedAt: null,
|
||||
},
|
||||
@@ -97,8 +90,8 @@ const messageSendCommand: OrchestrationCommand = {
|
||||
text: "hello",
|
||||
attachments: [],
|
||||
},
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "approval-required",
|
||||
approvalPolicy: "on-request",
|
||||
sandboxMode: "workspace-write",
|
||||
createdAt: now,
|
||||
};
|
||||
|
||||
@@ -145,8 +138,6 @@ describe("commandInvariants", () => {
|
||||
projectId: ProjectId.makeUnsafe("project-a"),
|
||||
title: "new",
|
||||
model: "gpt-5-codex",
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "full-access",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
createdAt: now,
|
||||
@@ -166,8 +157,6 @@ describe("commandInvariants", () => {
|
||||
projectId: ProjectId.makeUnsafe("project-a"),
|
||||
title: "dup",
|
||||
model: "gpt-5-codex",
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "full-access",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
createdAt: now,
|
||||
|
||||
@@ -1,11 +1,4 @@
|
||||
import {
|
||||
CommandId,
|
||||
DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
EventId,
|
||||
MessageId,
|
||||
ProjectId,
|
||||
ThreadId,
|
||||
} from "@t3tools/contracts";
|
||||
import { CommandId, EventId, MessageId, ProjectId, ThreadId } from "@t3tools/contracts";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { Effect } from "effect";
|
||||
|
||||
@@ -137,8 +130,6 @@ describe("decider project scripts", () => {
|
||||
projectId: asProjectId("project-1"),
|
||||
title: "Thread",
|
||||
model: "gpt-5-codex",
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "approval-required",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
createdAt: now,
|
||||
@@ -159,16 +150,10 @@ describe("decider project scripts", () => {
|
||||
text: "hello",
|
||||
attachments: [],
|
||||
},
|
||||
provider: "codex",
|
||||
model: "gpt-5.3-codex",
|
||||
modelOptions: {
|
||||
codex: {
|
||||
reasoningEffort: "high",
|
||||
fastMode: true,
|
||||
},
|
||||
},
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "approval-required",
|
||||
model: "gpt-5",
|
||||
effort: "high",
|
||||
approvalPolicy: "on-request",
|
||||
sandboxMode: "workspace-write",
|
||||
createdAt: now,
|
||||
},
|
||||
readModel,
|
||||
@@ -189,173 +174,10 @@ describe("decider project scripts", () => {
|
||||
expect(turnStartEvent.payload).toMatchObject({
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
messageId: asMessageId("message-user-1"),
|
||||
provider: "codex",
|
||||
model: "gpt-5.3-codex",
|
||||
modelOptions: {
|
||||
codex: {
|
||||
reasoningEffort: "high",
|
||||
fastMode: true,
|
||||
},
|
||||
},
|
||||
runtimeMode: "approval-required",
|
||||
});
|
||||
});
|
||||
|
||||
it("emits thread.runtime-mode-set from thread.runtime-mode.set", async () => {
|
||||
const now = new Date().toISOString();
|
||||
const initial = createEmptyReadModel(now);
|
||||
const withProject = await Effect.runPromise(
|
||||
projectEvent(initial, {
|
||||
sequence: 1,
|
||||
eventId: asEventId("evt-project-create"),
|
||||
aggregateKind: "project",
|
||||
aggregateId: asProjectId("project-1"),
|
||||
type: "project.created",
|
||||
occurredAt: now,
|
||||
commandId: CommandId.makeUnsafe("cmd-project-create"),
|
||||
causationEventId: null,
|
||||
correlationId: CommandId.makeUnsafe("cmd-project-create"),
|
||||
metadata: {},
|
||||
payload: {
|
||||
projectId: asProjectId("project-1"),
|
||||
title: "Project",
|
||||
workspaceRoot: "/tmp/project",
|
||||
defaultModel: null,
|
||||
scripts: [],
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
},
|
||||
}),
|
||||
);
|
||||
const readModel = await Effect.runPromise(
|
||||
projectEvent(withProject, {
|
||||
sequence: 2,
|
||||
eventId: asEventId("evt-thread-create"),
|
||||
aggregateKind: "thread",
|
||||
aggregateId: ThreadId.makeUnsafe("thread-1"),
|
||||
type: "thread.created",
|
||||
occurredAt: now,
|
||||
commandId: CommandId.makeUnsafe("cmd-thread-create"),
|
||||
causationEventId: null,
|
||||
correlationId: CommandId.makeUnsafe("cmd-thread-create"),
|
||||
metadata: {},
|
||||
payload: {
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
projectId: asProjectId("project-1"),
|
||||
title: "Thread",
|
||||
model: "gpt-5-codex",
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "full-access",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
},
|
||||
}),
|
||||
);
|
||||
|
||||
const result = await Effect.runPromise(
|
||||
decideOrchestrationCommand({
|
||||
command: {
|
||||
type: "thread.runtime-mode.set",
|
||||
commandId: CommandId.makeUnsafe("cmd-runtime-mode-set"),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
runtimeMode: "approval-required",
|
||||
createdAt: now,
|
||||
},
|
||||
readModel,
|
||||
}),
|
||||
);
|
||||
|
||||
const singleResult = Array.isArray(result) ? null : result;
|
||||
if (singleResult === null) {
|
||||
throw new Error("Expected a single runtime-mode-set event.");
|
||||
}
|
||||
expect(singleResult).toMatchObject({
|
||||
type: "thread.runtime-mode-set",
|
||||
payload: {
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
runtimeMode: "approval-required",
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it("emits thread.interaction-mode-set from thread.interaction-mode.set", async () => {
|
||||
const now = new Date().toISOString();
|
||||
const initial = createEmptyReadModel(now);
|
||||
const withProject = await Effect.runPromise(
|
||||
projectEvent(initial, {
|
||||
sequence: 1,
|
||||
eventId: asEventId("evt-project-create"),
|
||||
aggregateKind: "project",
|
||||
aggregateId: asProjectId("project-1"),
|
||||
type: "project.created",
|
||||
occurredAt: now,
|
||||
commandId: CommandId.makeUnsafe("cmd-project-create"),
|
||||
causationEventId: null,
|
||||
correlationId: CommandId.makeUnsafe("cmd-project-create"),
|
||||
metadata: {},
|
||||
payload: {
|
||||
projectId: asProjectId("project-1"),
|
||||
title: "Project",
|
||||
workspaceRoot: "/tmp/project",
|
||||
defaultModel: null,
|
||||
scripts: [],
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
},
|
||||
}),
|
||||
);
|
||||
const readModel = await Effect.runPromise(
|
||||
projectEvent(withProject, {
|
||||
sequence: 2,
|
||||
eventId: asEventId("evt-thread-create"),
|
||||
aggregateKind: "thread",
|
||||
aggregateId: ThreadId.makeUnsafe("thread-1"),
|
||||
type: "thread.created",
|
||||
occurredAt: now,
|
||||
commandId: CommandId.makeUnsafe("cmd-thread-create"),
|
||||
causationEventId: null,
|
||||
correlationId: CommandId.makeUnsafe("cmd-thread-create"),
|
||||
metadata: {},
|
||||
payload: {
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
projectId: asProjectId("project-1"),
|
||||
title: "Thread",
|
||||
model: "gpt-5-codex",
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "approval-required",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
},
|
||||
}),
|
||||
);
|
||||
|
||||
const result = await Effect.runPromise(
|
||||
decideOrchestrationCommand({
|
||||
command: {
|
||||
type: "thread.interaction-mode.set",
|
||||
commandId: CommandId.makeUnsafe("cmd-interaction-mode-set"),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
interactionMode: "plan",
|
||||
createdAt: now,
|
||||
},
|
||||
readModel,
|
||||
}),
|
||||
);
|
||||
|
||||
const singleResult = Array.isArray(result) ? null : result;
|
||||
if (singleResult === null) {
|
||||
throw new Error("Expected a single interaction-mode-set event.");
|
||||
}
|
||||
expect(singleResult).toMatchObject({
|
||||
type: "thread.interaction-mode-set",
|
||||
payload: {
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
interactionMode: "plan",
|
||||
},
|
||||
model: "gpt-5",
|
||||
effort: "high",
|
||||
approvalPolicy: "on-request",
|
||||
sandboxMode: "workspace-write",
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -157,8 +157,6 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
|
||||
projectId: command.projectId,
|
||||
title: command.title,
|
||||
model: command.model,
|
||||
runtimeMode: command.runtimeMode,
|
||||
interactionMode: command.interactionMode,
|
||||
branch: command.branch,
|
||||
worktreePath: command.worktreePath,
|
||||
createdAt: command.createdAt,
|
||||
@@ -215,52 +213,6 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
|
||||
};
|
||||
}
|
||||
|
||||
case "thread.runtime-mode.set": {
|
||||
yield* requireThread({
|
||||
readModel,
|
||||
command,
|
||||
threadId: command.threadId,
|
||||
});
|
||||
const occurredAt = nowIso();
|
||||
return {
|
||||
...withEventBase({
|
||||
aggregateKind: "thread",
|
||||
aggregateId: command.threadId,
|
||||
occurredAt,
|
||||
commandId: command.commandId,
|
||||
}),
|
||||
type: "thread.runtime-mode-set",
|
||||
payload: {
|
||||
threadId: command.threadId,
|
||||
runtimeMode: command.runtimeMode,
|
||||
updatedAt: occurredAt,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
case "thread.interaction-mode.set": {
|
||||
yield* requireThread({
|
||||
readModel,
|
||||
command,
|
||||
threadId: command.threadId,
|
||||
});
|
||||
const occurredAt = nowIso();
|
||||
return {
|
||||
...withEventBase({
|
||||
aggregateKind: "thread",
|
||||
aggregateId: command.threadId,
|
||||
occurredAt,
|
||||
commandId: command.commandId,
|
||||
}),
|
||||
type: "thread.interaction-mode-set",
|
||||
payload: {
|
||||
threadId: command.threadId,
|
||||
interactionMode: command.interactionMode,
|
||||
updatedAt: occurredAt,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
case "thread.turn.start": {
|
||||
yield* requireThread({
|
||||
readModel,
|
||||
@@ -299,16 +251,11 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
|
||||
payload: {
|
||||
threadId: command.threadId,
|
||||
messageId: command.message.messageId,
|
||||
...(command.provider !== undefined ? { provider: command.provider } : {}),
|
||||
...(command.model !== undefined ? { model: command.model } : {}),
|
||||
...(command.modelOptions !== undefined ? { modelOptions: command.modelOptions } : {}),
|
||||
...(command.effort !== undefined ? { effort: command.effort } : {}),
|
||||
assistantDeliveryMode: command.assistantDeliveryMode ?? DEFAULT_ASSISTANT_DELIVERY_MODE,
|
||||
runtimeMode:
|
||||
readModel.threads.find((entry) => entry.id === command.threadId)?.runtimeMode ??
|
||||
command.runtimeMode,
|
||||
interactionMode:
|
||||
readModel.threads.find((entry) => entry.id === command.threadId)?.interactionMode ??
|
||||
command.interactionMode,
|
||||
approvalPolicy: command.approvalPolicy,
|
||||
sandboxMode: command.sandboxMode,
|
||||
createdAt: command.createdAt,
|
||||
},
|
||||
};
|
||||
@@ -363,32 +310,6 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
|
||||
};
|
||||
}
|
||||
|
||||
case "thread.user-input.respond": {
|
||||
yield* requireThread({
|
||||
readModel,
|
||||
command,
|
||||
threadId: command.threadId,
|
||||
});
|
||||
return {
|
||||
...withEventBase({
|
||||
aggregateKind: "thread",
|
||||
aggregateId: command.threadId,
|
||||
occurredAt: command.createdAt,
|
||||
commandId: command.commandId,
|
||||
metadata: {
|
||||
requestId: command.requestId,
|
||||
},
|
||||
}),
|
||||
type: "thread.user-input-response-requested",
|
||||
payload: {
|
||||
threadId: command.threadId,
|
||||
requestId: command.requestId,
|
||||
answers: command.answers,
|
||||
createdAt: command.createdAt,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
case "thread.checkpoint.revert": {
|
||||
yield* requireThread({
|
||||
readModel,
|
||||
@@ -444,7 +365,14 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
|
||||
aggregateId: command.threadId,
|
||||
occurredAt: command.createdAt,
|
||||
commandId: command.commandId,
|
||||
metadata: {},
|
||||
metadata: {
|
||||
...(command.session.providerSessionId !== null
|
||||
? { providerSessionId: command.session.providerSessionId }
|
||||
: {}),
|
||||
...(command.session.providerThreadId !== null
|
||||
? { providerThreadId: command.session.providerThreadId }
|
||||
: {}),
|
||||
},
|
||||
}),
|
||||
type: "thread.session-set",
|
||||
payload: {
|
||||
@@ -508,27 +436,6 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
|
||||
};
|
||||
}
|
||||
|
||||
case "thread.proposed-plan.upsert": {
|
||||
yield* requireThread({
|
||||
readModel,
|
||||
command,
|
||||
threadId: command.threadId,
|
||||
});
|
||||
return {
|
||||
...withEventBase({
|
||||
aggregateKind: "thread",
|
||||
aggregateId: command.threadId,
|
||||
occurredAt: command.createdAt,
|
||||
commandId: command.commandId,
|
||||
}),
|
||||
type: "thread.proposed-plan-upserted",
|
||||
payload: {
|
||||
threadId: command.threadId,
|
||||
proposedPlan: command.proposedPlan,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
case "thread.turn.diff.complete": {
|
||||
yield* requireThread({
|
||||
readModel,
|
||||
|
||||
@@ -57,7 +57,6 @@ describe("orchestration projector", () => {
|
||||
projectId: "project-1",
|
||||
title: "demo",
|
||||
model: "gpt-5-codex",
|
||||
runtimeMode: "full-access",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
createdAt: now,
|
||||
@@ -74,8 +73,6 @@ describe("orchestration projector", () => {
|
||||
projectId: "project-1",
|
||||
title: "demo",
|
||||
model: "gpt-5-codex",
|
||||
runtimeMode: "full-access",
|
||||
interactionMode: "default",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
latestTurn: null,
|
||||
@@ -83,7 +80,6 @@ describe("orchestration projector", () => {
|
||||
updatedAt: now,
|
||||
deletedAt: null,
|
||||
messages: [],
|
||||
proposedPlans: [],
|
||||
activities: [],
|
||||
checkpoints: [],
|
||||
session: null,
|
||||
@@ -139,7 +135,8 @@ describe("orchestration projector", () => {
|
||||
payload: {
|
||||
threadId: "thread-1",
|
||||
messageId: "message-1",
|
||||
runtimeMode: "approval-required",
|
||||
approvalPolicy: "on-request",
|
||||
sandboxMode: "workspace-write",
|
||||
createdAt: "2026-01-01T00:00:00.000Z",
|
||||
},
|
||||
}),
|
||||
@@ -171,7 +168,6 @@ describe("orchestration projector", () => {
|
||||
projectId: "project-1",
|
||||
title: "demo",
|
||||
model: "gpt-5.3-codex",
|
||||
runtimeMode: "full-access",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
createdAt,
|
||||
@@ -199,7 +195,8 @@ describe("orchestration projector", () => {
|
||||
providerName: "codex",
|
||||
providerSessionId: "session-1",
|
||||
providerThreadId: "provider-thread-1",
|
||||
runtimeMode: "approval-required",
|
||||
approvalPolicy: "on-request",
|
||||
sandboxMode: "workspace-write",
|
||||
activeTurnId: "turn-1",
|
||||
lastError: null,
|
||||
updatedAt: startedAt,
|
||||
@@ -214,59 +211,6 @@ describe("orchestration projector", () => {
|
||||
expect(thread?.session?.status).toBe("running");
|
||||
});
|
||||
|
||||
it("updates canonical thread runtime mode from thread.runtime-mode-set", async () => {
|
||||
const createdAt = "2026-02-23T08:00:00.000Z";
|
||||
const updatedAt = "2026-02-23T08:00:05.000Z";
|
||||
const model = createEmptyReadModel(createdAt);
|
||||
|
||||
const afterCreate = await Effect.runPromise(
|
||||
projectEvent(
|
||||
model,
|
||||
makeEvent({
|
||||
sequence: 1,
|
||||
type: "thread.created",
|
||||
aggregateKind: "thread",
|
||||
aggregateId: "thread-1",
|
||||
occurredAt: createdAt,
|
||||
commandId: "cmd-create",
|
||||
payload: {
|
||||
threadId: "thread-1",
|
||||
projectId: "project-1",
|
||||
title: "demo",
|
||||
model: "gpt-5.3-codex",
|
||||
runtimeMode: "full-access",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
createdAt,
|
||||
updatedAt: createdAt,
|
||||
},
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
const afterUpdate = await Effect.runPromise(
|
||||
projectEvent(
|
||||
afterCreate,
|
||||
makeEvent({
|
||||
sequence: 2,
|
||||
type: "thread.runtime-mode-set",
|
||||
aggregateKind: "thread",
|
||||
aggregateId: "thread-1",
|
||||
occurredAt: updatedAt,
|
||||
commandId: "cmd-runtime-mode-set",
|
||||
payload: {
|
||||
threadId: "thread-1",
|
||||
runtimeMode: "approval-required",
|
||||
updatedAt,
|
||||
},
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
expect(afterUpdate.threads[0]?.runtimeMode).toBe("approval-required");
|
||||
expect(afterUpdate.threads[0]?.updatedAt).toBe(updatedAt);
|
||||
});
|
||||
|
||||
it("marks assistant messages completed with non-streaming updates", async () => {
|
||||
const createdAt = "2026-02-23T09:00:00.000Z";
|
||||
const deltaAt = "2026-02-23T09:00:01.000Z";
|
||||
@@ -288,7 +232,6 @@ describe("orchestration projector", () => {
|
||||
projectId: "project-1",
|
||||
title: "demo",
|
||||
model: "gpt-5.3-codex",
|
||||
runtimeMode: "full-access",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
createdAt,
|
||||
@@ -372,7 +315,6 @@ describe("orchestration projector", () => {
|
||||
projectId: "project-1",
|
||||
title: "demo",
|
||||
model: "gpt-5.3-codex",
|
||||
runtimeMode: "full-access",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
createdAt,
|
||||
@@ -584,7 +526,6 @@ describe("orchestration projector", () => {
|
||||
projectId: "project-1",
|
||||
title: "demo",
|
||||
model: "gpt-5.3-codex",
|
||||
runtimeMode: "full-access",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
createdAt,
|
||||
@@ -734,7 +675,6 @@ describe("orchestration projector", () => {
|
||||
projectId: "project-1",
|
||||
title: "capped",
|
||||
model: "gpt-5-codex",
|
||||
runtimeMode: "full-access",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
createdAt,
|
||||
|
||||
@@ -16,10 +16,7 @@ import {
|
||||
ThreadActivityAppendedPayload,
|
||||
ThreadCreatedPayload,
|
||||
ThreadDeletedPayload,
|
||||
ThreadInteractionModeSetPayload,
|
||||
ThreadMetaUpdatedPayload,
|
||||
ThreadProposedPlanUpsertedPayload,
|
||||
ThreadRuntimeModeSetPayload,
|
||||
ThreadRevertedPayload,
|
||||
ThreadSessionSetPayload,
|
||||
ThreadTurnDiffCompletedPayload,
|
||||
@@ -127,32 +124,6 @@ function retainThreadActivitiesAfterRevert(
|
||||
);
|
||||
}
|
||||
|
||||
function retainThreadProposedPlansAfterRevert(
|
||||
proposedPlans: ReadonlyArray<OrchestrationThread["proposedPlans"][number]>,
|
||||
retainedTurnIds: ReadonlySet<string>,
|
||||
): ReadonlyArray<OrchestrationThread["proposedPlans"][number]> {
|
||||
return proposedPlans.filter(
|
||||
(proposedPlan) => proposedPlan.turnId === null || retainedTurnIds.has(proposedPlan.turnId),
|
||||
);
|
||||
}
|
||||
|
||||
function compareThreadActivities(
|
||||
left: OrchestrationThread["activities"][number],
|
||||
right: OrchestrationThread["activities"][number],
|
||||
): number {
|
||||
if (left.sequence !== undefined && right.sequence !== undefined) {
|
||||
if (left.sequence !== right.sequence) {
|
||||
return left.sequence - right.sequence;
|
||||
}
|
||||
} else if (left.sequence !== undefined) {
|
||||
return 1;
|
||||
} else if (right.sequence !== undefined) {
|
||||
return -1;
|
||||
}
|
||||
|
||||
return left.createdAt.localeCompare(right.createdAt) || left.id.localeCompare(right.id);
|
||||
}
|
||||
|
||||
export function createEmptyReadModel(nowIso: string): OrchestrationReadModel {
|
||||
return {
|
||||
snapshotSequence: 0,
|
||||
@@ -253,8 +224,6 @@ export function projectEvent(
|
||||
projectId: payload.projectId,
|
||||
title: payload.title,
|
||||
model: payload.model,
|
||||
runtimeMode: payload.runtimeMode,
|
||||
interactionMode: payload.interactionMode,
|
||||
branch: payload.branch,
|
||||
worktreePath: payload.worktreePath,
|
||||
latestTurn: null,
|
||||
@@ -303,38 +272,6 @@ export function projectEvent(
|
||||
})),
|
||||
);
|
||||
|
||||
case "thread.runtime-mode-set":
|
||||
return decodeForEvent(
|
||||
ThreadRuntimeModeSetPayload,
|
||||
event.payload,
|
||||
event.type,
|
||||
"payload",
|
||||
).pipe(
|
||||
Effect.map((payload) => ({
|
||||
...nextBase,
|
||||
threads: updateThread(nextBase.threads, payload.threadId, {
|
||||
runtimeMode: payload.runtimeMode,
|
||||
updatedAt: payload.updatedAt,
|
||||
}),
|
||||
})),
|
||||
);
|
||||
|
||||
case "thread.interaction-mode-set":
|
||||
return decodeForEvent(
|
||||
ThreadInteractionModeSetPayload,
|
||||
event.payload,
|
||||
event.type,
|
||||
"payload",
|
||||
).pipe(
|
||||
Effect.map((payload) => ({
|
||||
...nextBase,
|
||||
threads: updateThread(nextBase.threads, payload.threadId, {
|
||||
interactionMode: payload.interactionMode,
|
||||
updatedAt: payload.updatedAt,
|
||||
}),
|
||||
})),
|
||||
);
|
||||
|
||||
case "thread.message-sent":
|
||||
return Effect.gen(function* () {
|
||||
const payload = yield* decodeForEvent(
|
||||
@@ -445,38 +382,6 @@ export function projectEvent(
|
||||
};
|
||||
});
|
||||
|
||||
case "thread.proposed-plan-upserted":
|
||||
return Effect.gen(function* () {
|
||||
const payload = yield* decodeForEvent(
|
||||
ThreadProposedPlanUpsertedPayload,
|
||||
event.payload,
|
||||
event.type,
|
||||
"payload",
|
||||
);
|
||||
const thread = nextBase.threads.find((entry) => entry.id === payload.threadId);
|
||||
if (!thread) {
|
||||
return nextBase;
|
||||
}
|
||||
|
||||
const proposedPlans = [
|
||||
...thread.proposedPlans.filter((entry) => entry.id !== payload.proposedPlan.id),
|
||||
payload.proposedPlan,
|
||||
]
|
||||
.toSorted(
|
||||
(left, right) =>
|
||||
left.createdAt.localeCompare(right.createdAt) || left.id.localeCompare(right.id),
|
||||
)
|
||||
.slice(-200);
|
||||
|
||||
return {
|
||||
...nextBase,
|
||||
threads: updateThread(nextBase.threads, payload.threadId, {
|
||||
proposedPlans,
|
||||
updatedAt: event.occurredAt,
|
||||
}),
|
||||
};
|
||||
});
|
||||
|
||||
case "thread.turn-diff-completed":
|
||||
return Effect.gen(function* () {
|
||||
const payload = yield* decodeForEvent(
|
||||
@@ -553,10 +458,6 @@ export function projectEvent(
|
||||
retainedTurnIds,
|
||||
payload.turnCount,
|
||||
).slice(-MAX_THREAD_MESSAGES);
|
||||
const proposedPlans = retainThreadProposedPlansAfterRevert(
|
||||
thread.proposedPlans,
|
||||
retainedTurnIds,
|
||||
).slice(-200);
|
||||
const activities = retainThreadActivitiesAfterRevert(thread.activities, retainedTurnIds);
|
||||
|
||||
const latestCheckpoint = checkpoints.at(-1) ?? null;
|
||||
@@ -577,7 +478,6 @@ export function projectEvent(
|
||||
threads: updateThread(nextBase.threads, payload.threadId, {
|
||||
checkpoints,
|
||||
messages,
|
||||
proposedPlans,
|
||||
activities,
|
||||
latestTurn,
|
||||
updatedAt: event.occurredAt,
|
||||
@@ -603,7 +503,7 @@ export function projectEvent(
|
||||
...thread.activities.filter((entry) => entry.id !== payload.activity.id),
|
||||
payload.activity,
|
||||
]
|
||||
.toSorted(compareThreadActivities)
|
||||
.toSorted((left, right) => left.createdAt.localeCompare(right.createdAt))
|
||||
.slice(-500);
|
||||
|
||||
return {
|
||||
|
||||
@@ -74,6 +74,8 @@ function inferActorKind(
|
||||
return "server";
|
||||
}
|
||||
if (
|
||||
event.metadata.providerSessionId !== undefined ||
|
||||
event.metadata.providerThreadId !== undefined ||
|
||||
event.metadata.providerTurnId !== undefined ||
|
||||
event.metadata.providerItemId !== undefined ||
|
||||
event.metadata.adapterKey !== undefined
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
import * as SqlClient from "effect/unstable/sql/SqlClient";
|
||||
import * as SqlSchema from "effect/unstable/sql/SqlSchema";
|
||||
import { NonNegativeInt } from "@t3tools/contracts";
|
||||
import { Effect, Layer, Schema, Struct } from "effect";
|
||||
|
||||
import { toPersistenceDecodeError, toPersistenceSqlError } from "../Errors.ts";
|
||||
@@ -16,7 +15,6 @@ import {
|
||||
const ProjectionThreadActivityDbRowSchema = ProjectionThreadActivity.mapFields(
|
||||
Struct.assign({
|
||||
payload: Schema.fromJsonString(Schema.Unknown),
|
||||
sequence: Schema.NullOr(NonNegativeInt),
|
||||
}),
|
||||
);
|
||||
|
||||
@@ -31,7 +29,7 @@ const makeProjectionThreadActivityRepository = Effect.gen(function* () {
|
||||
const sql = yield* SqlClient.SqlClient;
|
||||
|
||||
const upsertProjectionThreadActivityRow = SqlSchema.void({
|
||||
Request: ProjectionThreadActivity,
|
||||
Request: ProjectionThreadActivityDbRowSchema,
|
||||
execute: (row) =>
|
||||
sql`
|
||||
INSERT INTO projection_thread_activities (
|
||||
@@ -42,7 +40,6 @@ const makeProjectionThreadActivityRepository = Effect.gen(function* () {
|
||||
kind,
|
||||
summary,
|
||||
payload_json,
|
||||
sequence,
|
||||
created_at
|
||||
)
|
||||
VALUES (
|
||||
@@ -52,8 +49,7 @@ const makeProjectionThreadActivityRepository = Effect.gen(function* () {
|
||||
${row.tone},
|
||||
${row.kind},
|
||||
${row.summary},
|
||||
${JSON.stringify(row.payload)},
|
||||
${row.sequence ?? null},
|
||||
${row.payload},
|
||||
${row.createdAt}
|
||||
)
|
||||
ON CONFLICT (activity_id)
|
||||
@@ -64,7 +60,6 @@ const makeProjectionThreadActivityRepository = Effect.gen(function* () {
|
||||
kind = excluded.kind,
|
||||
summary = excluded.summary,
|
||||
payload_json = excluded.payload_json,
|
||||
sequence = excluded.sequence,
|
||||
created_at = excluded.created_at
|
||||
`,
|
||||
});
|
||||
@@ -82,15 +77,10 @@ const makeProjectionThreadActivityRepository = Effect.gen(function* () {
|
||||
kind,
|
||||
summary,
|
||||
payload_json AS "payload",
|
||||
sequence,
|
||||
created_at AS "createdAt"
|
||||
FROM projection_thread_activities
|
||||
WHERE thread_id = ${threadId}
|
||||
ORDER BY
|
||||
CASE WHEN sequence IS NULL THEN 0 ELSE 1 END ASC,
|
||||
sequence ASC,
|
||||
created_at ASC,
|
||||
activity_id ASC
|
||||
ORDER BY created_at ASC, activity_id ASC
|
||||
`,
|
||||
});
|
||||
|
||||
@@ -121,18 +111,8 @@ const makeProjectionThreadActivityRepository = Effect.gen(function* () {
|
||||
"ProjectionThreadActivityRepository.listByThreadId:decodeRows",
|
||||
),
|
||||
),
|
||||
Effect.map((rows) =>
|
||||
rows.map((row) => ({
|
||||
activityId: row.activityId,
|
||||
threadId: row.threadId,
|
||||
turnId: row.turnId,
|
||||
tone: row.tone,
|
||||
kind: row.kind,
|
||||
summary: row.summary,
|
||||
payload: row.payload,
|
||||
...(row.sequence !== null ? { sequence: row.sequence } : {}),
|
||||
createdAt: row.createdAt,
|
||||
})),
|
||||
Effect.map(
|
||||
(rows) => rows as ReadonlyArray<Schema.Schema.Type<typeof ProjectionThreadActivity>>,
|
||||
),
|
||||
);
|
||||
|
||||
|
||||
@@ -1,104 +0,0 @@
|
||||
import { Effect, Layer } from "effect";
|
||||
import * as SqlClient from "effect/unstable/sql/SqlClient";
|
||||
import * as SqlSchema from "effect/unstable/sql/SqlSchema";
|
||||
|
||||
import { toPersistenceSqlError } from "../Errors.ts";
|
||||
import {
|
||||
DeleteProjectionThreadProposedPlansInput,
|
||||
ListProjectionThreadProposedPlansInput,
|
||||
ProjectionThreadProposedPlan,
|
||||
ProjectionThreadProposedPlanRepository,
|
||||
type ProjectionThreadProposedPlanRepositoryShape,
|
||||
} from "../Services/ProjectionThreadProposedPlans.ts";
|
||||
|
||||
const makeProjectionThreadProposedPlanRepository = Effect.gen(function* () {
|
||||
const sql = yield* SqlClient.SqlClient;
|
||||
|
||||
const upsertProjectionThreadProposedPlanRow = SqlSchema.void({
|
||||
Request: ProjectionThreadProposedPlan,
|
||||
execute: (row) => sql`
|
||||
INSERT INTO projection_thread_proposed_plans (
|
||||
plan_id,
|
||||
thread_id,
|
||||
turn_id,
|
||||
plan_markdown,
|
||||
created_at,
|
||||
updated_at
|
||||
)
|
||||
VALUES (
|
||||
${row.planId},
|
||||
${row.threadId},
|
||||
${row.turnId},
|
||||
${row.planMarkdown},
|
||||
${row.createdAt},
|
||||
${row.updatedAt}
|
||||
)
|
||||
ON CONFLICT (plan_id)
|
||||
DO UPDATE SET
|
||||
thread_id = excluded.thread_id,
|
||||
turn_id = excluded.turn_id,
|
||||
plan_markdown = excluded.plan_markdown,
|
||||
created_at = excluded.created_at,
|
||||
updated_at = excluded.updated_at
|
||||
`,
|
||||
});
|
||||
|
||||
const listProjectionThreadProposedPlanRows = SqlSchema.findAll({
|
||||
Request: ListProjectionThreadProposedPlansInput,
|
||||
Result: ProjectionThreadProposedPlan,
|
||||
execute: ({ threadId }) => sql`
|
||||
SELECT
|
||||
plan_id AS "planId",
|
||||
thread_id AS "threadId",
|
||||
turn_id AS "turnId",
|
||||
plan_markdown AS "planMarkdown",
|
||||
created_at AS "createdAt",
|
||||
updated_at AS "updatedAt"
|
||||
FROM projection_thread_proposed_plans
|
||||
WHERE thread_id = ${threadId}
|
||||
ORDER BY created_at ASC, plan_id ASC
|
||||
`,
|
||||
});
|
||||
|
||||
const deleteProjectionThreadProposedPlanRows = SqlSchema.void({
|
||||
Request: DeleteProjectionThreadProposedPlansInput,
|
||||
execute: ({ threadId }) => sql`
|
||||
DELETE FROM projection_thread_proposed_plans
|
||||
WHERE thread_id = ${threadId}
|
||||
`,
|
||||
});
|
||||
|
||||
const upsert: ProjectionThreadProposedPlanRepositoryShape["upsert"] = (row) =>
|
||||
upsertProjectionThreadProposedPlanRow(row).pipe(
|
||||
Effect.mapError(
|
||||
toPersistenceSqlError("ProjectionThreadProposedPlanRepository.upsert:query"),
|
||||
),
|
||||
);
|
||||
|
||||
const listByThreadId: ProjectionThreadProposedPlanRepositoryShape["listByThreadId"] = (input) =>
|
||||
listProjectionThreadProposedPlanRows(input).pipe(
|
||||
Effect.mapError(
|
||||
toPersistenceSqlError("ProjectionThreadProposedPlanRepository.listByThreadId:query"),
|
||||
),
|
||||
);
|
||||
|
||||
const deleteByThreadId: ProjectionThreadProposedPlanRepositoryShape["deleteByThreadId"] = (
|
||||
input,
|
||||
) =>
|
||||
deleteProjectionThreadProposedPlanRows(input).pipe(
|
||||
Effect.mapError(
|
||||
toPersistenceSqlError("ProjectionThreadProposedPlanRepository.deleteByThreadId:query"),
|
||||
),
|
||||
);
|
||||
|
||||
return {
|
||||
upsert,
|
||||
listByThreadId,
|
||||
deleteByThreadId,
|
||||
} satisfies ProjectionThreadProposedPlanRepositoryShape;
|
||||
});
|
||||
|
||||
export const ProjectionThreadProposedPlanRepositoryLive = Layer.effect(
|
||||
ProjectionThreadProposedPlanRepository,
|
||||
makeProjectionThreadProposedPlanRepository,
|
||||
);
|
||||
@@ -23,7 +23,10 @@ const makeProjectionThreadSessionRepository = Effect.gen(function* () {
|
||||
thread_id,
|
||||
status,
|
||||
provider_name,
|
||||
runtime_mode,
|
||||
provider_session_id,
|
||||
provider_thread_id,
|
||||
approval_policy,
|
||||
sandbox_mode,
|
||||
active_turn_id,
|
||||
last_error,
|
||||
updated_at
|
||||
@@ -32,7 +35,10 @@ const makeProjectionThreadSessionRepository = Effect.gen(function* () {
|
||||
${row.threadId},
|
||||
${row.status},
|
||||
${row.providerName},
|
||||
${row.runtimeMode},
|
||||
${row.providerSessionId},
|
||||
${row.providerThreadId},
|
||||
${row.approvalPolicy},
|
||||
${row.sandboxMode},
|
||||
${row.activeTurnId},
|
||||
${row.lastError},
|
||||
${row.updatedAt}
|
||||
@@ -41,7 +47,10 @@ const makeProjectionThreadSessionRepository = Effect.gen(function* () {
|
||||
DO UPDATE SET
|
||||
status = excluded.status,
|
||||
provider_name = excluded.provider_name,
|
||||
runtime_mode = excluded.runtime_mode,
|
||||
provider_session_id = excluded.provider_session_id,
|
||||
provider_thread_id = excluded.provider_thread_id,
|
||||
approval_policy = excluded.approval_policy,
|
||||
sandbox_mode = excluded.sandbox_mode,
|
||||
active_turn_id = excluded.active_turn_id,
|
||||
last_error = excluded.last_error,
|
||||
updated_at = excluded.updated_at
|
||||
@@ -57,7 +66,10 @@ const makeProjectionThreadSessionRepository = Effect.gen(function* () {
|
||||
thread_id AS "threadId",
|
||||
status,
|
||||
provider_name AS "providerName",
|
||||
runtime_mode AS "runtimeMode",
|
||||
provider_session_id AS "providerSessionId",
|
||||
provider_thread_id AS "providerThreadId",
|
||||
approval_policy AS "approvalPolicy",
|
||||
sandbox_mode AS "sandboxMode",
|
||||
active_turn_id AS "activeTurnId",
|
||||
last_error AS "lastError",
|
||||
updated_at AS "updatedAt"
|
||||
|
||||
@@ -24,8 +24,6 @@ const makeProjectionThreadRepository = Effect.gen(function* () {
|
||||
project_id,
|
||||
title,
|
||||
model,
|
||||
runtime_mode,
|
||||
interaction_mode,
|
||||
branch,
|
||||
worktree_path,
|
||||
latest_turn_id,
|
||||
@@ -38,8 +36,6 @@ const makeProjectionThreadRepository = Effect.gen(function* () {
|
||||
${row.projectId},
|
||||
${row.title},
|
||||
${row.model},
|
||||
${row.runtimeMode},
|
||||
${row.interactionMode},
|
||||
${row.branch},
|
||||
${row.worktreePath},
|
||||
${row.latestTurnId},
|
||||
@@ -52,8 +48,6 @@ const makeProjectionThreadRepository = Effect.gen(function* () {
|
||||
project_id = excluded.project_id,
|
||||
title = excluded.title,
|
||||
model = excluded.model,
|
||||
runtime_mode = excluded.runtime_mode,
|
||||
interaction_mode = excluded.interaction_mode,
|
||||
branch = excluded.branch,
|
||||
worktree_path = excluded.worktree_path,
|
||||
latest_turn_id = excluded.latest_turn_id,
|
||||
@@ -73,8 +67,6 @@ const makeProjectionThreadRepository = Effect.gen(function* () {
|
||||
project_id AS "projectId",
|
||||
title,
|
||||
model,
|
||||
runtime_mode AS "runtimeMode",
|
||||
interaction_mode AS "interactionMode",
|
||||
branch,
|
||||
worktree_path AS "worktreePath",
|
||||
latest_turn_id AS "latestTurnId",
|
||||
@@ -96,8 +88,6 @@ const makeProjectionThreadRepository = Effect.gen(function* () {
|
||||
project_id AS "projectId",
|
||||
title,
|
||||
model,
|
||||
runtime_mode AS "runtimeMode",
|
||||
interaction_mode AS "interactionMode",
|
||||
branch,
|
||||
worktree_path AS "worktreePath",
|
||||
latest_turn_id AS "latestTurnId",
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { ThreadId } from "@t3tools/contracts";
|
||||
import { ProviderSessionId } from "@t3tools/contracts";
|
||||
import * as SqlClient from "effect/unstable/sql/SqlClient";
|
||||
import * as SqlSchema from "effect/unstable/sql/SqlSchema";
|
||||
import { Effect, Layer, Option, Schema, Struct } from "effect";
|
||||
@@ -24,7 +24,7 @@ const ProviderSessionRuntimeDbRowSchema = ProviderSessionRuntime.mapFields(
|
||||
const decodeRuntime = Schema.decodeUnknownEffect(ProviderSessionRuntime);
|
||||
|
||||
const GetRuntimeRequestSchema = Schema.Struct({
|
||||
threadId: ThreadId,
|
||||
providerSessionId: ProviderSessionId,
|
||||
});
|
||||
|
||||
const DeleteRuntimeRequestSchema = GetRuntimeRequestSchema;
|
||||
@@ -44,30 +44,33 @@ const makeProviderSessionRuntimeRepository = Effect.gen(function* () {
|
||||
execute: (runtime) =>
|
||||
sql`
|
||||
INSERT INTO provider_session_runtime (
|
||||
provider_session_id,
|
||||
thread_id,
|
||||
provider_name,
|
||||
adapter_key,
|
||||
runtime_mode,
|
||||
provider_thread_id,
|
||||
status,
|
||||
last_seen_at,
|
||||
resume_cursor_json,
|
||||
runtime_payload_json
|
||||
)
|
||||
VALUES (
|
||||
${runtime.providerSessionId},
|
||||
${runtime.threadId},
|
||||
${runtime.providerName},
|
||||
${runtime.adapterKey},
|
||||
${runtime.runtimeMode},
|
||||
${runtime.providerThreadId},
|
||||
${runtime.status},
|
||||
${runtime.lastSeenAt},
|
||||
${runtime.resumeCursor},
|
||||
${runtime.runtimePayload}
|
||||
)
|
||||
ON CONFLICT (thread_id)
|
||||
ON CONFLICT (provider_session_id)
|
||||
DO UPDATE SET
|
||||
thread_id = excluded.thread_id,
|
||||
provider_name = excluded.provider_name,
|
||||
adapter_key = excluded.adapter_key,
|
||||
runtime_mode = excluded.runtime_mode,
|
||||
provider_thread_id = excluded.provider_thread_id,
|
||||
status = excluded.status,
|
||||
last_seen_at = excluded.last_seen_at,
|
||||
resume_cursor_json = excluded.resume_cursor_json,
|
||||
@@ -75,22 +78,23 @@ const makeProviderSessionRuntimeRepository = Effect.gen(function* () {
|
||||
`,
|
||||
});
|
||||
|
||||
const getRuntimeRowByThreadId = SqlSchema.findOneOption({
|
||||
const getRuntimeRowBySessionId = SqlSchema.findOneOption({
|
||||
Request: GetRuntimeRequestSchema,
|
||||
Result: ProviderSessionRuntimeDbRowSchema,
|
||||
execute: ({ threadId }) =>
|
||||
execute: ({ providerSessionId }) =>
|
||||
sql`
|
||||
SELECT
|
||||
provider_session_id AS "providerSessionId",
|
||||
thread_id AS "threadId",
|
||||
provider_name AS "providerName",
|
||||
adapter_key AS "adapterKey",
|
||||
runtime_mode AS "runtimeMode",
|
||||
provider_thread_id AS "providerThreadId",
|
||||
status,
|
||||
last_seen_at AS "lastSeenAt",
|
||||
resume_cursor_json AS "resumeCursor",
|
||||
runtime_payload_json AS "runtimePayload"
|
||||
FROM provider_session_runtime
|
||||
WHERE thread_id = ${threadId}
|
||||
WHERE provider_session_id = ${providerSessionId}
|
||||
`,
|
||||
});
|
||||
|
||||
@@ -100,25 +104,26 @@ const makeProviderSessionRuntimeRepository = Effect.gen(function* () {
|
||||
execute: () =>
|
||||
sql`
|
||||
SELECT
|
||||
provider_session_id AS "providerSessionId",
|
||||
thread_id AS "threadId",
|
||||
provider_name AS "providerName",
|
||||
adapter_key AS "adapterKey",
|
||||
runtime_mode AS "runtimeMode",
|
||||
provider_thread_id AS "providerThreadId",
|
||||
status,
|
||||
last_seen_at AS "lastSeenAt",
|
||||
resume_cursor_json AS "resumeCursor",
|
||||
runtime_payload_json AS "runtimePayload"
|
||||
FROM provider_session_runtime
|
||||
ORDER BY last_seen_at ASC, thread_id ASC
|
||||
ORDER BY last_seen_at ASC, provider_session_id ASC
|
||||
`,
|
||||
});
|
||||
|
||||
const deleteRuntimeByThreadId = SqlSchema.void({
|
||||
const deleteRuntimeBySessionId = SqlSchema.void({
|
||||
Request: DeleteRuntimeRequestSchema,
|
||||
execute: ({ threadId }) =>
|
||||
execute: ({ providerSessionId }) =>
|
||||
sql`
|
||||
DELETE FROM provider_session_runtime
|
||||
WHERE thread_id = ${threadId}
|
||||
WHERE provider_session_id = ${providerSessionId}
|
||||
`,
|
||||
});
|
||||
|
||||
@@ -132,12 +137,12 @@ const makeProviderSessionRuntimeRepository = Effect.gen(function* () {
|
||||
),
|
||||
);
|
||||
|
||||
const getByThreadId: ProviderSessionRuntimeRepositoryShape["getByThreadId"] = (input) =>
|
||||
getRuntimeRowByThreadId(input).pipe(
|
||||
const getBySessionId: ProviderSessionRuntimeRepositoryShape["getBySessionId"] = (input) =>
|
||||
getRuntimeRowBySessionId(input).pipe(
|
||||
Effect.mapError(
|
||||
toPersistenceSqlOrDecodeError(
|
||||
"ProviderSessionRuntimeRepository.getByThreadId:query",
|
||||
"ProviderSessionRuntimeRepository.getByThreadId:decodeRow",
|
||||
"ProviderSessionRuntimeRepository.getBySessionId:query",
|
||||
"ProviderSessionRuntimeRepository.getBySessionId:decodeRow",
|
||||
),
|
||||
),
|
||||
Effect.flatMap((runtimeRowOption) =>
|
||||
@@ -147,7 +152,7 @@ const makeProviderSessionRuntimeRepository = Effect.gen(function* () {
|
||||
decodeRuntime(row).pipe(
|
||||
Effect.mapError(
|
||||
toPersistenceDecodeError(
|
||||
"ProviderSessionRuntimeRepository.getByThreadId:rowToRuntime",
|
||||
"ProviderSessionRuntimeRepository.getBySessionId:rowToRuntime",
|
||||
),
|
||||
),
|
||||
Effect.map((runtime) => Option.some(runtime)),
|
||||
@@ -178,18 +183,18 @@ const makeProviderSessionRuntimeRepository = Effect.gen(function* () {
|
||||
),
|
||||
);
|
||||
|
||||
const deleteByThreadId: ProviderSessionRuntimeRepositoryShape["deleteByThreadId"] = (input) =>
|
||||
deleteRuntimeByThreadId(input).pipe(
|
||||
const deleteBySessionId: ProviderSessionRuntimeRepositoryShape["deleteBySessionId"] = (input) =>
|
||||
deleteRuntimeBySessionId(input).pipe(
|
||||
Effect.mapError(
|
||||
toPersistenceSqlError("ProviderSessionRuntimeRepository.deleteByThreadId:query"),
|
||||
toPersistenceSqlError("ProviderSessionRuntimeRepository.deleteBySessionId:query"),
|
||||
),
|
||||
);
|
||||
|
||||
return {
|
||||
upsert,
|
||||
getByThreadId,
|
||||
getBySessionId,
|
||||
list,
|
||||
deleteByThreadId,
|
||||
deleteBySessionId,
|
||||
} satisfies ProviderSessionRuntimeRepositoryShape;
|
||||
});
|
||||
|
||||
|
||||
@@ -0,0 +1,225 @@
|
||||
import { ProviderSessionId, ThreadId } from "@t3tools/contracts";
|
||||
import * as SqlClient from "effect/unstable/sql/SqlClient";
|
||||
import * as SqlSchema from "effect/unstable/sql/SqlSchema";
|
||||
import { Effect, Layer, Option, Schema } from "effect";
|
||||
|
||||
import {
|
||||
ProviderSessionRepositoryPersistenceError,
|
||||
ProviderSessionRepositoryValidationError,
|
||||
} from "../Errors.ts";
|
||||
import {
|
||||
ProviderSessionRepository,
|
||||
type ProviderSessionEntry,
|
||||
type ProviderSessionRepositoryShape,
|
||||
} from "../Services/ProviderSessions.ts";
|
||||
|
||||
const ProviderKind = Schema.Literals(["codex", "claudeCode"]);
|
||||
|
||||
const ProviderSessionRowSchema = Schema.Struct({
|
||||
sessionId: ProviderSessionId,
|
||||
provider: ProviderKind,
|
||||
threadId: Schema.NullOr(ThreadId),
|
||||
createdAt: Schema.String,
|
||||
updatedAt: Schema.String,
|
||||
});
|
||||
|
||||
const SessionIdRequestSchema = Schema.Struct({
|
||||
sessionId: ProviderSessionId,
|
||||
});
|
||||
|
||||
const UpsertSessionRequestSchema = Schema.Struct({
|
||||
sessionId: ProviderSessionId,
|
||||
provider: ProviderKind,
|
||||
threadId: Schema.NullOr(ThreadId),
|
||||
});
|
||||
|
||||
function errorMessage(cause: unknown, fallback: string): string {
|
||||
if (cause instanceof Error && cause.message.length > 0) {
|
||||
return cause.message;
|
||||
}
|
||||
return fallback;
|
||||
}
|
||||
|
||||
function toValidationError(
|
||||
operation: string,
|
||||
cause: unknown,
|
||||
): ProviderSessionRepositoryValidationError {
|
||||
return new ProviderSessionRepositoryValidationError({
|
||||
operation,
|
||||
issue: errorMessage(cause, "Invalid provider session repository input."),
|
||||
cause,
|
||||
});
|
||||
}
|
||||
|
||||
function decodeInput<S extends Schema.Top>(schema: S, input: unknown, operation: string) {
|
||||
return Schema.decodeUnknownEffect(schema)(input).pipe(
|
||||
Effect.mapError((cause) => toValidationError(operation, cause)),
|
||||
);
|
||||
}
|
||||
|
||||
function toPersistenceError(
|
||||
operation: string,
|
||||
cause: unknown,
|
||||
): ProviderSessionRepositoryPersistenceError {
|
||||
return new ProviderSessionRepositoryPersistenceError({
|
||||
operation,
|
||||
detail: `Failed to execute ${operation}.`,
|
||||
cause,
|
||||
});
|
||||
}
|
||||
|
||||
function toEntry(row: Schema.Schema.Type<typeof ProviderSessionRowSchema>): ProviderSessionEntry {
|
||||
return {
|
||||
sessionId: row.sessionId,
|
||||
provider: row.provider,
|
||||
...(row.threadId !== null ? { threadId: row.threadId } : {}),
|
||||
createdAt: row.createdAt,
|
||||
updatedAt: row.updatedAt,
|
||||
};
|
||||
}
|
||||
|
||||
const makeProviderSessionRepository = Effect.gen(function* () {
|
||||
const sql = yield* SqlClient.SqlClient;
|
||||
|
||||
const upsertSessionRow = SqlSchema.findOne({
|
||||
Request: UpsertSessionRequestSchema,
|
||||
Result: ProviderSessionRowSchema,
|
||||
execute: (request) =>
|
||||
sql`
|
||||
INSERT INTO provider_sessions (
|
||||
session_id,
|
||||
provider,
|
||||
thread_id,
|
||||
created_at,
|
||||
updated_at
|
||||
)
|
||||
VALUES (
|
||||
${request.sessionId},
|
||||
${request.provider},
|
||||
${request.threadId},
|
||||
CURRENT_TIMESTAMP,
|
||||
CURRENT_TIMESTAMP
|
||||
)
|
||||
ON CONFLICT (session_id)
|
||||
DO UPDATE SET
|
||||
provider = excluded.provider,
|
||||
thread_id = excluded.thread_id,
|
||||
updated_at = CURRENT_TIMESTAMP
|
||||
RETURNING
|
||||
session_id AS "sessionId",
|
||||
provider,
|
||||
thread_id AS "threadId",
|
||||
created_at AS "createdAt",
|
||||
updated_at AS "updatedAt"
|
||||
`,
|
||||
});
|
||||
|
||||
const findSessionRow = SqlSchema.findOneOption({
|
||||
Request: SessionIdRequestSchema,
|
||||
Result: ProviderSessionRowSchema,
|
||||
execute: ({ sessionId }) =>
|
||||
sql`
|
||||
SELECT
|
||||
session_id AS "sessionId",
|
||||
provider,
|
||||
thread_id AS "threadId",
|
||||
created_at AS "createdAt",
|
||||
updated_at AS "updatedAt"
|
||||
FROM provider_sessions
|
||||
WHERE session_id = ${sessionId}
|
||||
`,
|
||||
});
|
||||
|
||||
const listSessionRows = SqlSchema.findAll({
|
||||
Request: Schema.Void,
|
||||
Result: ProviderSessionRowSchema,
|
||||
execute: () =>
|
||||
sql`
|
||||
SELECT
|
||||
session_id AS "sessionId",
|
||||
provider,
|
||||
thread_id AS "threadId",
|
||||
created_at AS "createdAt",
|
||||
updated_at AS "updatedAt"
|
||||
FROM provider_sessions
|
||||
ORDER BY created_at ASC, session_id ASC
|
||||
`,
|
||||
});
|
||||
|
||||
const deleteSessionRow = SqlSchema.void({
|
||||
Request: SessionIdRequestSchema,
|
||||
execute: ({ sessionId }) => sql`DELETE FROM provider_sessions WHERE session_id = ${sessionId}`,
|
||||
});
|
||||
|
||||
const upsertSession: ProviderSessionRepositoryShape["upsertSession"] = (input) =>
|
||||
Effect.gen(function* () {
|
||||
const parsed = yield* decodeInput(
|
||||
UpsertSessionRequestSchema,
|
||||
{
|
||||
sessionId: input.sessionId,
|
||||
provider: input.provider,
|
||||
threadId: input.threadId ?? null,
|
||||
},
|
||||
"ProviderSessionRepository.upsertSession",
|
||||
);
|
||||
|
||||
yield* upsertSessionRow(parsed).pipe(
|
||||
Effect.mapError((cause) =>
|
||||
toPersistenceError("ProviderSessionRepository.upsertSession:query", cause),
|
||||
),
|
||||
Effect.asVoid,
|
||||
);
|
||||
});
|
||||
|
||||
const getSession: ProviderSessionRepositoryShape["getSession"] = (input) =>
|
||||
Effect.gen(function* () {
|
||||
const parsed = yield* decodeInput(
|
||||
SessionIdRequestSchema,
|
||||
{ sessionId: input.sessionId },
|
||||
"ProviderSessionRepository.getSession",
|
||||
);
|
||||
|
||||
const row = yield* findSessionRow(parsed).pipe(
|
||||
Effect.mapError((cause) =>
|
||||
toPersistenceError("ProviderSessionRepository.getSession:query", cause),
|
||||
),
|
||||
);
|
||||
|
||||
return Option.map(row, toEntry);
|
||||
});
|
||||
|
||||
const listSessions: ProviderSessionRepositoryShape["listSessions"] = () =>
|
||||
listSessionRows(undefined).pipe(
|
||||
Effect.mapError((cause) =>
|
||||
toPersistenceError("ProviderSessionRepository.listSessions:query", cause),
|
||||
),
|
||||
Effect.map((rows) => rows.map(toEntry)),
|
||||
);
|
||||
|
||||
const deleteSession: ProviderSessionRepositoryShape["deleteSession"] = (input) =>
|
||||
Effect.gen(function* () {
|
||||
const parsed = yield* decodeInput(
|
||||
SessionIdRequestSchema,
|
||||
{ sessionId: input.sessionId },
|
||||
"ProviderSessionRepository.deleteSession",
|
||||
);
|
||||
|
||||
yield* deleteSessionRow(parsed).pipe(
|
||||
Effect.mapError((cause) =>
|
||||
toPersistenceError("ProviderSessionRepository.deleteSession:query", cause),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
return {
|
||||
upsertSession,
|
||||
getSession,
|
||||
listSessions,
|
||||
deleteSession,
|
||||
} satisfies ProviderSessionRepositoryShape;
|
||||
});
|
||||
|
||||
export const ProviderSessionRepositoryLive = Layer.effect(
|
||||
ProviderSessionRepository,
|
||||
makeProviderSessionRepository,
|
||||
);
|
||||
@@ -19,13 +19,6 @@ import Migration0004 from "./Migrations/004_ProviderSessionRuntime.ts";
|
||||
import Migration0005 from "./Migrations/005_Projections.ts";
|
||||
import Migration0006 from "./Migrations/006_ProjectionThreadSessionRuntimeModeColumns.ts";
|
||||
import Migration0007 from "./Migrations/007_ProjectionThreadMessageAttachments.ts";
|
||||
import Migration0008 from "./Migrations/008_ProjectionThreadActivitySequence.ts";
|
||||
import Migration0009 from "./Migrations/009_ProviderSessionRuntimeMode.ts";
|
||||
import Migration0010 from "./Migrations/010_ProjectionThreadsRuntimeMode.ts";
|
||||
import Migration0011 from "./Migrations/011_OrchestrationThreadCreatedRuntimeMode.ts";
|
||||
import Migration0012 from "./Migrations/012_ProjectionThreadsInteractionMode.ts";
|
||||
import Migration0013 from "./Migrations/013_ProjectionThreadProposedPlans.ts";
|
||||
import { Effect } from "effect";
|
||||
|
||||
/**
|
||||
* Migration loader with all migrations defined inline.
|
||||
@@ -45,12 +38,6 @@ const loader = Migrator.fromRecord({
|
||||
"5_Projections": Migration0005,
|
||||
"6_ProjectionThreadSessionRuntimeModeColumns": Migration0006,
|
||||
"7_ProjectionThreadMessageAttachments": Migration0007,
|
||||
"8_ProjectionThreadActivitySequence": Migration0008,
|
||||
"9_ProviderSessionRuntimeMode": Migration0009,
|
||||
"10_ProjectionThreadsRuntimeMode": Migration0010,
|
||||
"11_OrchestrationThreadCreatedRuntimeMode": Migration0011,
|
||||
"12_ProjectionThreadsInteractionMode": Migration0012,
|
||||
"13_ProjectionThreadProposedPlans": Migration0013,
|
||||
});
|
||||
|
||||
/**
|
||||
@@ -69,11 +56,7 @@ const run = Migrator.make({});
|
||||
*
|
||||
* @returns Effect containing array of executed migrations
|
||||
*/
|
||||
export const runMigrations = Effect.gen(function* () {
|
||||
yield* Effect.log("Running migrations...");
|
||||
yield* run({ loader });
|
||||
yield* Effect.log("Migrations ran successfully");
|
||||
});
|
||||
export const runMigrations = run({ loader });
|
||||
|
||||
/**
|
||||
* Layer that runs migrations when the layer is built.
|
||||
|
||||
@@ -6,10 +6,11 @@ export default Effect.gen(function* () {
|
||||
|
||||
yield* sql`
|
||||
CREATE TABLE IF NOT EXISTS provider_session_runtime (
|
||||
thread_id TEXT PRIMARY KEY,
|
||||
provider_session_id TEXT PRIMARY KEY,
|
||||
thread_id TEXT NOT NULL,
|
||||
provider_name TEXT NOT NULL,
|
||||
adapter_key TEXT NOT NULL,
|
||||
runtime_mode TEXT NOT NULL DEFAULT 'full-access',
|
||||
provider_thread_id TEXT,
|
||||
status TEXT NOT NULL,
|
||||
last_seen_at TEXT NOT NULL,
|
||||
resume_cursor_json TEXT,
|
||||
@@ -17,6 +18,11 @@ export default Effect.gen(function* () {
|
||||
)
|
||||
`;
|
||||
|
||||
yield* sql`
|
||||
CREATE INDEX IF NOT EXISTS idx_provider_session_runtime_thread
|
||||
ON provider_session_runtime(thread_id)
|
||||
`;
|
||||
|
||||
yield* sql`
|
||||
CREATE INDEX IF NOT EXISTS idx_provider_session_runtime_status
|
||||
ON provider_session_runtime(status)
|
||||
|
||||
+15
-4
@@ -1,19 +1,30 @@
|
||||
import * as SqlClient from "effect/unstable/sql/SqlClient";
|
||||
import * as Effect from "effect/Effect";
|
||||
|
||||
const DEFAULT_RUNTIME_MODE = "full-access";
|
||||
const DEFAULT_APPROVAL_POLICY = "never";
|
||||
const DEFAULT_SANDBOX_MODE = "workspace-write";
|
||||
|
||||
export default Effect.gen(function* () {
|
||||
const sql = yield* SqlClient.SqlClient;
|
||||
|
||||
yield* sql`
|
||||
ALTER TABLE projection_thread_sessions
|
||||
ADD COLUMN runtime_mode TEXT NOT NULL DEFAULT 'full-access'
|
||||
ADD COLUMN approval_policy TEXT NOT NULL DEFAULT 'never'
|
||||
`;
|
||||
|
||||
yield* sql`
|
||||
ALTER TABLE projection_thread_sessions
|
||||
ADD COLUMN sandbox_mode TEXT NOT NULL DEFAULT 'workspace-write'
|
||||
`;
|
||||
|
||||
yield* sql`
|
||||
UPDATE projection_thread_sessions
|
||||
SET runtime_mode = ${DEFAULT_RUNTIME_MODE}
|
||||
WHERE runtime_mode IS NULL
|
||||
SET approval_policy = ${DEFAULT_APPROVAL_POLICY}
|
||||
WHERE approval_policy IS NULL
|
||||
`;
|
||||
yield* sql`
|
||||
UPDATE projection_thread_sessions
|
||||
SET sandbox_mode = ${DEFAULT_SANDBOX_MODE}
|
||||
WHERE sandbox_mode IS NULL
|
||||
`;
|
||||
});
|
||||
@@ -1,16 +0,0 @@
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as SqlClient from "effect/unstable/sql/SqlClient";
|
||||
|
||||
export default Effect.gen(function* () {
|
||||
const sql = yield* SqlClient.SqlClient;
|
||||
|
||||
yield* sql`
|
||||
ALTER TABLE projection_thread_activities
|
||||
ADD COLUMN sequence INTEGER
|
||||
`;
|
||||
|
||||
yield* sql`
|
||||
CREATE INDEX IF NOT EXISTS idx_projection_thread_activities_thread_sequence
|
||||
ON projection_thread_activities(thread_id, sequence)
|
||||
`;
|
||||
});
|
||||
@@ -1,6 +0,0 @@
|
||||
import * as SqlClient from "effect/unstable/sql/SqlClient";
|
||||
import * as Effect from "effect/Effect";
|
||||
|
||||
export default Effect.gen(function* () {
|
||||
yield* SqlClient.SqlClient;
|
||||
});
|
||||
@@ -1,17 +0,0 @@
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as SqlClient from "effect/unstable/sql/SqlClient";
|
||||
|
||||
export default Effect.gen(function* () {
|
||||
const sql = yield* SqlClient.SqlClient;
|
||||
|
||||
yield* sql`
|
||||
ALTER TABLE projection_threads
|
||||
ADD COLUMN runtime_mode TEXT NOT NULL DEFAULT 'full-access'
|
||||
`;
|
||||
|
||||
yield* sql`
|
||||
UPDATE projection_threads
|
||||
SET runtime_mode = 'full-access'
|
||||
WHERE runtime_mode IS NULL
|
||||
`;
|
||||
});
|
||||
@@ -1,13 +0,0 @@
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as SqlClient from "effect/unstable/sql/SqlClient";
|
||||
|
||||
export default Effect.gen(function* () {
|
||||
const sql = yield* SqlClient.SqlClient;
|
||||
|
||||
yield* sql`
|
||||
UPDATE orchestration_events
|
||||
SET payload_json = json_set(payload_json, '$.runtimeMode', 'full-access')
|
||||
WHERE event_type = 'thread.created'
|
||||
AND json_type(payload_json, '$.runtimeMode') IS NULL
|
||||
`;
|
||||
});
|
||||
@@ -1,11 +0,0 @@
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as SqlClient from "effect/unstable/sql/SqlClient";
|
||||
|
||||
export default Effect.gen(function* () {
|
||||
const sql = yield* SqlClient.SqlClient;
|
||||
|
||||
yield* sql`
|
||||
ALTER TABLE projection_threads
|
||||
ADD COLUMN interaction_mode TEXT NOT NULL DEFAULT 'default'
|
||||
`;
|
||||
});
|
||||
@@ -1,22 +0,0 @@
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as SqlClient from "effect/unstable/sql/SqlClient";
|
||||
|
||||
export default Effect.gen(function* () {
|
||||
const sql = yield* SqlClient.SqlClient;
|
||||
|
||||
yield* sql`
|
||||
CREATE TABLE IF NOT EXISTS projection_thread_proposed_plans (
|
||||
plan_id TEXT PRIMARY KEY,
|
||||
thread_id TEXT NOT NULL,
|
||||
turn_id TEXT,
|
||||
plan_markdown TEXT NOT NULL,
|
||||
created_at TEXT NOT NULL,
|
||||
updated_at TEXT NOT NULL
|
||||
)
|
||||
`;
|
||||
|
||||
yield* sql`
|
||||
CREATE INDEX IF NOT EXISTS idx_projection_thread_proposed_plans_thread_created
|
||||
ON projection_thread_proposed_plans(thread_id, created_at)
|
||||
`;
|
||||
});
|
||||
@@ -9,7 +9,6 @@
|
||||
import {
|
||||
EventId,
|
||||
IsoDateTime,
|
||||
NonNegativeInt,
|
||||
OrchestrationThreadActivityTone,
|
||||
ThreadId,
|
||||
TurnId,
|
||||
@@ -27,7 +26,6 @@ export const ProjectionThreadActivity = Schema.Struct({
|
||||
kind: Schema.String,
|
||||
summary: Schema.String,
|
||||
payload: Schema.Unknown,
|
||||
sequence: Schema.optional(NonNegativeInt),
|
||||
createdAt: IsoDateTime,
|
||||
});
|
||||
export type ProjectionThreadActivity = typeof ProjectionThreadActivity.Type;
|
||||
@@ -59,8 +57,7 @@ export interface ProjectionThreadActivityRepositoryShape {
|
||||
/**
|
||||
* List projected thread activity rows for a thread.
|
||||
*
|
||||
* Returned in ascending runtime sequence order (or creation order when
|
||||
* sequence is unavailable).
|
||||
* Returned in ascending creation order.
|
||||
*/
|
||||
readonly listByThreadId: (
|
||||
input: ListProjectionThreadActivitiesInput,
|
||||
|
||||
@@ -1,52 +0,0 @@
|
||||
import {
|
||||
IsoDateTime,
|
||||
OrchestrationProposedPlanId,
|
||||
ThreadId,
|
||||
TrimmedNonEmptyString,
|
||||
TurnId,
|
||||
} from "@t3tools/contracts";
|
||||
import { Schema, ServiceMap } from "effect";
|
||||
import type { Effect } from "effect";
|
||||
|
||||
import type { ProjectionRepositoryError } from "../Errors.ts";
|
||||
|
||||
export const ProjectionThreadProposedPlan = Schema.Struct({
|
||||
planId: OrchestrationProposedPlanId,
|
||||
threadId: ThreadId,
|
||||
turnId: Schema.NullOr(TurnId),
|
||||
planMarkdown: TrimmedNonEmptyString,
|
||||
createdAt: IsoDateTime,
|
||||
updatedAt: IsoDateTime,
|
||||
});
|
||||
export type ProjectionThreadProposedPlan = typeof ProjectionThreadProposedPlan.Type;
|
||||
|
||||
export const ListProjectionThreadProposedPlansInput = Schema.Struct({
|
||||
threadId: ThreadId,
|
||||
});
|
||||
export type ListProjectionThreadProposedPlansInput =
|
||||
typeof ListProjectionThreadProposedPlansInput.Type;
|
||||
|
||||
export const DeleteProjectionThreadProposedPlansInput = Schema.Struct({
|
||||
threadId: ThreadId,
|
||||
});
|
||||
export type DeleteProjectionThreadProposedPlansInput =
|
||||
typeof DeleteProjectionThreadProposedPlansInput.Type;
|
||||
|
||||
export interface ProjectionThreadProposedPlanRepositoryShape {
|
||||
readonly upsert: (
|
||||
proposedPlan: ProjectionThreadProposedPlan,
|
||||
) => Effect.Effect<void, ProjectionRepositoryError>;
|
||||
readonly listByThreadId: (
|
||||
input: ListProjectionThreadProposedPlansInput,
|
||||
) => Effect.Effect<ReadonlyArray<ProjectionThreadProposedPlan>, ProjectionRepositoryError>;
|
||||
readonly deleteByThreadId: (
|
||||
input: DeleteProjectionThreadProposedPlansInput,
|
||||
) => Effect.Effect<void, ProjectionRepositoryError>;
|
||||
}
|
||||
|
||||
export class ProjectionThreadProposedPlanRepository extends ServiceMap.Service<
|
||||
ProjectionThreadProposedPlanRepository,
|
||||
ProjectionThreadProposedPlanRepositoryShape
|
||||
>()(
|
||||
"t3/persistence/Services/ProjectionThreadProposedPlans/ProjectionThreadProposedPlanRepository",
|
||||
) {}
|
||||
@@ -7,9 +7,12 @@
|
||||
* @module ProjectionThreadSessionRepository
|
||||
*/
|
||||
import {
|
||||
RuntimeMode,
|
||||
IsoDateTime,
|
||||
OrchestrationSessionStatus,
|
||||
ProviderApprovalPolicy,
|
||||
ProviderSandboxMode,
|
||||
ProviderSessionId,
|
||||
ProviderThreadId,
|
||||
ThreadId,
|
||||
TurnId,
|
||||
} from "@t3tools/contracts";
|
||||
@@ -22,7 +25,10 @@ export const ProjectionThreadSession = Schema.Struct({
|
||||
threadId: ThreadId,
|
||||
status: OrchestrationSessionStatus,
|
||||
providerName: Schema.NullOr(Schema.String),
|
||||
runtimeMode: RuntimeMode,
|
||||
providerSessionId: Schema.NullOr(ProviderSessionId),
|
||||
providerThreadId: Schema.NullOr(ProviderThreadId),
|
||||
approvalPolicy: ProviderApprovalPolicy,
|
||||
sandboxMode: ProviderSandboxMode,
|
||||
activeTurnId: Schema.NullOr(TurnId),
|
||||
lastError: Schema.NullOr(Schema.String),
|
||||
updatedAt: IsoDateTime,
|
||||
|
||||
@@ -6,14 +6,7 @@
|
||||
*
|
||||
* @module ProjectionThreadRepository
|
||||
*/
|
||||
import {
|
||||
IsoDateTime,
|
||||
ProjectId,
|
||||
ProviderInteractionMode,
|
||||
RuntimeMode,
|
||||
ThreadId,
|
||||
TurnId,
|
||||
} from "@t3tools/contracts";
|
||||
import { IsoDateTime, ProjectId, ThreadId, TurnId } from "@t3tools/contracts";
|
||||
import { Option, Schema, ServiceMap } from "effect";
|
||||
import type { Effect } from "effect";
|
||||
|
||||
@@ -24,8 +17,6 @@ export const ProjectionThread = Schema.Struct({
|
||||
projectId: ProjectId,
|
||||
title: Schema.String,
|
||||
model: Schema.String,
|
||||
runtimeMode: RuntimeMode,
|
||||
interactionMode: ProviderInteractionMode,
|
||||
branch: Schema.NullOr(Schema.String),
|
||||
worktreePath: Schema.NullOr(Schema.String),
|
||||
latestTurnId: Schema.NullOr(TurnId),
|
||||
|
||||
@@ -7,8 +7,9 @@
|
||||
*/
|
||||
import {
|
||||
IsoDateTime,
|
||||
ProviderSessionId,
|
||||
ProviderSessionRuntimeStatus,
|
||||
RuntimeMode,
|
||||
ProviderThreadId,
|
||||
ThreadId,
|
||||
} from "@t3tools/contracts";
|
||||
import { Option, Schema, ServiceMap } from "effect";
|
||||
@@ -17,10 +18,11 @@ import type { Effect } from "effect";
|
||||
import type { ProviderSessionRuntimeRepositoryError } from "../Errors.ts";
|
||||
|
||||
export const ProviderSessionRuntime = Schema.Struct({
|
||||
providerSessionId: ProviderSessionId,
|
||||
threadId: ThreadId,
|
||||
providerName: Schema.String,
|
||||
adapterKey: Schema.String,
|
||||
runtimeMode: RuntimeMode,
|
||||
providerThreadId: Schema.NullOr(ProviderThreadId),
|
||||
status: ProviderSessionRuntimeStatus,
|
||||
lastSeenAt: IsoDateTime,
|
||||
resumeCursor: Schema.NullOr(Schema.Unknown),
|
||||
@@ -28,10 +30,14 @@ export const ProviderSessionRuntime = Schema.Struct({
|
||||
});
|
||||
export type ProviderSessionRuntime = typeof ProviderSessionRuntime.Type;
|
||||
|
||||
export const GetProviderSessionRuntimeInput = Schema.Struct({ threadId: ThreadId });
|
||||
export const GetProviderSessionRuntimeInput = Schema.Struct({
|
||||
providerSessionId: ProviderSessionId,
|
||||
});
|
||||
export type GetProviderSessionRuntimeInput = typeof GetProviderSessionRuntimeInput.Type;
|
||||
|
||||
export const DeleteProviderSessionRuntimeInput = Schema.Struct({ threadId: ThreadId });
|
||||
export const DeleteProviderSessionRuntimeInput = Schema.Struct({
|
||||
providerSessionId: ProviderSessionId,
|
||||
});
|
||||
export type DeleteProviderSessionRuntimeInput = typeof DeleteProviderSessionRuntimeInput.Type;
|
||||
|
||||
/**
|
||||
@@ -41,16 +47,16 @@ export interface ProviderSessionRuntimeRepositoryShape {
|
||||
/**
|
||||
* Insert or replace a provider runtime row.
|
||||
*
|
||||
* Upserts by canonical `threadId`, including JSON payload/cursor fields.
|
||||
* Upserts by `providerSessionId`, including JSON payload/cursor fields.
|
||||
*/
|
||||
readonly upsert: (
|
||||
runtime: ProviderSessionRuntime,
|
||||
) => Effect.Effect<void, ProviderSessionRuntimeRepositoryError>;
|
||||
|
||||
/**
|
||||
* Read provider runtime state by canonical thread id.
|
||||
* Read provider runtime state by provider session id.
|
||||
*/
|
||||
readonly getByThreadId: (
|
||||
readonly getBySessionId: (
|
||||
input: GetProviderSessionRuntimeInput,
|
||||
) => Effect.Effect<Option.Option<ProviderSessionRuntime>, ProviderSessionRuntimeRepositoryError>;
|
||||
|
||||
@@ -65,9 +71,9 @@ export interface ProviderSessionRuntimeRepositoryShape {
|
||||
>;
|
||||
|
||||
/**
|
||||
* Delete provider runtime state by canonical thread id.
|
||||
* Delete provider runtime state by provider session id.
|
||||
*/
|
||||
readonly deleteByThreadId: (
|
||||
readonly deleteBySessionId: (
|
||||
input: DeleteProviderSessionRuntimeInput,
|
||||
) => Effect.Effect<void, ProviderSessionRuntimeRepositoryError>;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,81 @@
|
||||
/**
|
||||
* ProviderSessionRepository - Repository interface for provider session lookup.
|
||||
*
|
||||
* Owns persistence operations that map internal sessions to provider kinds and
|
||||
* optional thread ownership.
|
||||
*
|
||||
* @module ProviderSessionRepository
|
||||
*/
|
||||
import type { ProviderKind, ProviderSessionId, ThreadId } from "@t3tools/contracts";
|
||||
import { Option, ServiceMap } from "effect";
|
||||
import type { Effect } from "effect";
|
||||
|
||||
import type { ProviderSessionRepositoryError } from "../Errors.ts";
|
||||
|
||||
export interface ProviderSessionEntry {
|
||||
readonly sessionId: ProviderSessionId;
|
||||
readonly provider: ProviderKind;
|
||||
readonly threadId?: ThreadId;
|
||||
readonly createdAt: string;
|
||||
readonly updatedAt: string;
|
||||
}
|
||||
|
||||
export interface UpsertProviderSessionInput {
|
||||
readonly sessionId: ProviderSessionId;
|
||||
readonly provider: ProviderKind;
|
||||
readonly threadId?: ThreadId;
|
||||
}
|
||||
|
||||
export interface DeleteProviderSessionInput {
|
||||
readonly sessionId: ProviderSessionId;
|
||||
}
|
||||
|
||||
export interface GetProviderSessionInput {
|
||||
readonly sessionId: ProviderSessionId;
|
||||
}
|
||||
|
||||
/**
|
||||
* ProviderSessionRepositoryShape - Service API for provider-session records.
|
||||
*/
|
||||
export interface ProviderSessionRepositoryShape {
|
||||
/**
|
||||
* Insert or replace a provider-session row.
|
||||
*
|
||||
* Upserts by `sessionId`.
|
||||
*/
|
||||
readonly upsertSession: (
|
||||
input: UpsertProviderSessionInput,
|
||||
) => Effect.Effect<void, ProviderSessionRepositoryError>;
|
||||
|
||||
/**
|
||||
* Read a provider-session row by session id.
|
||||
*/
|
||||
readonly getSession: (
|
||||
input: GetProviderSessionInput,
|
||||
) => Effect.Effect<Option.Option<ProviderSessionEntry>, ProviderSessionRepositoryError>;
|
||||
|
||||
/**
|
||||
* List all provider-session rows.
|
||||
*
|
||||
* Returned in deterministic creation order.
|
||||
*/
|
||||
readonly listSessions: () => Effect.Effect<
|
||||
ReadonlyArray<ProviderSessionEntry>,
|
||||
ProviderSessionRepositoryError
|
||||
>;
|
||||
|
||||
/**
|
||||
* Delete a provider-session row by session id.
|
||||
*/
|
||||
readonly deleteSession: (
|
||||
input: DeleteProviderSessionInput,
|
||||
) => Effect.Effect<void, ProviderSessionRepositoryError>;
|
||||
}
|
||||
|
||||
/**
|
||||
* ProviderSessionRepository - Service tag for provider-session persistence.
|
||||
*/
|
||||
export class ProviderSessionRepository extends ServiceMap.Service<
|
||||
ProviderSessionRepository,
|
||||
ProviderSessionRepositoryShape
|
||||
>()("t3/persistence/Services/ProviderSessions/ProviderSessionRepository") {}
|
||||
@@ -1,6 +1,6 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { runProcess } from "./processRunner";
|
||||
import { runProcess, spawnDetachedProcess, spawnProcessSync } from "./processRunner";
|
||||
|
||||
describe("runProcess", () => {
|
||||
it("fails when output exceeds max buffer in default mode", async () => {
|
||||
@@ -20,4 +20,20 @@ describe("runProcess", () => {
|
||||
expect(result.stdoutTruncated).toBe(true);
|
||||
expect(result.stderrTruncated).toBe(false);
|
||||
});
|
||||
|
||||
it("runs sync commands through the shared spawn strategy", () => {
|
||||
const result = spawnProcessSync("node", ["-e", "process.stdout.write('ok')"], {
|
||||
stdio: ["ignore", "pipe", "pipe"],
|
||||
});
|
||||
|
||||
expect(result.error).toBeUndefined();
|
||||
expect(result.status).toBe(0);
|
||||
expect(result.stdout).toBe("ok");
|
||||
});
|
||||
|
||||
it("spawns detached commands through the shared spawn strategy", async () => {
|
||||
await expect(
|
||||
spawnDetachedProcess(process.execPath, ["-e", "process.exit(0)"]),
|
||||
).resolves.toBeUndefined();
|
||||
});
|
||||
});
|
||||
@@ -1,4 +1,44 @@
|
||||
import { type ChildProcess as ChildProcessHandle, spawn, spawnSync } from "node:child_process";
|
||||
import {
|
||||
type ChildProcess as ChildProcessHandle,
|
||||
type ChildProcessWithoutNullStreams,
|
||||
spawn,
|
||||
spawnSync,
|
||||
type StdioOptions,
|
||||
} from "node:child_process";
|
||||
|
||||
import type { ServerRuntimeEnvironment } from "@t3tools/contracts";
|
||||
import { Effect, Exit, Scope } from "effect";
|
||||
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
|
||||
|
||||
import { detectServerRuntimeEnvironment } from "./runtimeEnvironment";
|
||||
|
||||
interface ProcessSpawnBaseOptions {
|
||||
cwd?: string | undefined;
|
||||
env?: NodeJS.ProcessEnv | undefined;
|
||||
runtimeEnvironment?: ServerRuntimeEnvironment | undefined;
|
||||
shell?: boolean | undefined;
|
||||
}
|
||||
|
||||
interface RuntimeShellOptions {
|
||||
runtimeEnvironment?: ServerRuntimeEnvironment | undefined;
|
||||
shell?: boolean | string | undefined;
|
||||
}
|
||||
|
||||
interface ProcessSpawnOptions extends ProcessSpawnBaseOptions {
|
||||
stdio?: StdioOptions | undefined;
|
||||
detached?: boolean | undefined;
|
||||
}
|
||||
|
||||
interface RuntimeCommandOptions extends ChildProcess.CommandOptions {
|
||||
runtimeEnvironment?: ServerRuntimeEnvironment | undefined;
|
||||
}
|
||||
|
||||
interface ProcessSpawnSyncOptions extends ProcessSpawnBaseOptions {
|
||||
stdio?: StdioOptions | undefined;
|
||||
detached?: boolean | undefined;
|
||||
encoding?: BufferEncoding | undefined;
|
||||
input?: string | undefined;
|
||||
}
|
||||
|
||||
export interface ProcessRunOptions {
|
||||
cwd?: string | undefined;
|
||||
@@ -8,6 +48,8 @@ export interface ProcessRunOptions {
|
||||
allowNonZeroExit?: boolean | undefined;
|
||||
maxBufferBytes?: number | undefined;
|
||||
outputMode?: "error" | "truncate" | undefined;
|
||||
runtimeEnvironment?: ServerRuntimeEnvironment | undefined;
|
||||
shell?: boolean | undefined;
|
||||
}
|
||||
|
||||
export interface ProcessRunResult {
|
||||
@@ -24,6 +66,127 @@ function commandLabel(command: string, args: readonly string[]): string {
|
||||
return [command, ...args].join(" ");
|
||||
}
|
||||
|
||||
function resolveRuntimeEnvironment(
|
||||
runtimeEnvironment: ServerRuntimeEnvironment | undefined,
|
||||
): ServerRuntimeEnvironment {
|
||||
return runtimeEnvironment ?? detectServerRuntimeEnvironment();
|
||||
}
|
||||
|
||||
function shouldUseShell(options: RuntimeShellOptions): boolean | string {
|
||||
if (options.shell !== undefined) {
|
||||
return options.shell;
|
||||
}
|
||||
|
||||
return resolveRuntimeEnvironment(options.runtimeEnvironment).platform === "windows";
|
||||
}
|
||||
|
||||
function toSpawnOptions(options: ProcessSpawnOptions) {
|
||||
return {
|
||||
cwd: options.cwd,
|
||||
env: options.env,
|
||||
shell: shouldUseShell(options),
|
||||
...(options.stdio !== undefined ? { stdio: options.stdio } : {}),
|
||||
...(options.detached !== undefined ? { detached: options.detached } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
function toRuntimeCommandOptions(
|
||||
options: RuntimeCommandOptions = {},
|
||||
): ChildProcess.CommandOptions {
|
||||
const { runtimeEnvironment: _, ...rest } = options;
|
||||
return {
|
||||
...rest,
|
||||
shell: options.shell ?? shouldUseShell(options),
|
||||
};
|
||||
}
|
||||
|
||||
export function makeRuntimeCommand(
|
||||
command: string,
|
||||
args: ReadonlyArray<string>,
|
||||
options: RuntimeCommandOptions = {},
|
||||
): ChildProcess.StandardCommand {
|
||||
return ChildProcess.make(command, [...args], toRuntimeCommandOptions(options));
|
||||
}
|
||||
|
||||
interface ManagedChildProcess {
|
||||
readonly scope: Scope.Closeable;
|
||||
readonly handle: ChildProcessSpawner.ChildProcessHandle;
|
||||
}
|
||||
|
||||
export const spawnManagedCommand = (command: ChildProcess.Command) =>
|
||||
Effect.gen(function* () {
|
||||
const scope = yield* Scope.make("sequential");
|
||||
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||
const handle = yield* spawner.spawn(command).pipe(
|
||||
Scope.provide(scope),
|
||||
Effect.tapError(() => Scope.close(scope, Exit.void)),
|
||||
);
|
||||
|
||||
return {
|
||||
scope,
|
||||
handle,
|
||||
} satisfies ManagedChildProcess;
|
||||
});
|
||||
|
||||
function spawnProcess(
|
||||
command: string,
|
||||
args: readonly string[],
|
||||
options: ProcessSpawnOptions = {},
|
||||
): ChildProcessHandle {
|
||||
return spawn(command, args, toSpawnOptions(options));
|
||||
}
|
||||
|
||||
function spawnPipedProcess(
|
||||
command: string,
|
||||
args: readonly string[],
|
||||
options: Omit<ProcessSpawnOptions, "stdio" | "detached"> = {},
|
||||
): ChildProcessWithoutNullStreams {
|
||||
return spawnProcess(command, args, {
|
||||
...options,
|
||||
stdio: "pipe",
|
||||
}) as ChildProcessWithoutNullStreams;
|
||||
}
|
||||
|
||||
export function spawnProcessSync(
|
||||
command: string,
|
||||
args: readonly string[],
|
||||
options: ProcessSpawnSyncOptions = {},
|
||||
) {
|
||||
return spawnSync(command, args, {
|
||||
cwd: options.cwd,
|
||||
env: options.env,
|
||||
shell: shouldUseShell(options),
|
||||
encoding: options.encoding ?? "utf8",
|
||||
...(options.stdio !== undefined ? { stdio: options.stdio } : {}),
|
||||
...(options.detached !== undefined ? { detached: options.detached } : {}),
|
||||
...(options.input !== undefined ? { input: options.input } : {}),
|
||||
});
|
||||
}
|
||||
|
||||
export function spawnDetachedProcess(
|
||||
command: string,
|
||||
args: readonly string[],
|
||||
options: Omit<ProcessSpawnOptions, "stdio" | "detached"> = {},
|
||||
): Promise<void> {
|
||||
return new Promise<void>((resolve, reject) => {
|
||||
const child = spawnProcess(command, args, {
|
||||
...options,
|
||||
detached: true,
|
||||
stdio: "ignore",
|
||||
});
|
||||
|
||||
const handleSpawn = () => {
|
||||
child.unref();
|
||||
resolve();
|
||||
};
|
||||
|
||||
child.once("spawn", handleSpawn);
|
||||
child.once("error", (error) => {
|
||||
reject(normalizeSpawnError(command, args, error));
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
function normalizeSpawnError(command: string, args: readonly string[], error: unknown): Error {
|
||||
if (!(error instanceof Error)) {
|
||||
return new Error(`Failed to run ${commandLabel(command, args)}.`);
|
||||
@@ -37,8 +200,12 @@ function normalizeSpawnError(command: string, args: readonly string[], error: un
|
||||
return new Error(`Failed to run ${commandLabel(command, args)}: ${error.message}`);
|
||||
}
|
||||
|
||||
function isWindowsCommandNotFound(code: number | null, stderr: string): boolean {
|
||||
if (process.platform !== "win32") return false;
|
||||
function isWindowsCommandNotFound(
|
||||
code: number | null,
|
||||
stderr: string,
|
||||
runtimeEnvironment?: ServerRuntimeEnvironment,
|
||||
): boolean {
|
||||
if (resolveRuntimeEnvironment(runtimeEnvironment).platform !== "windows") return false;
|
||||
if (code === 9009) return true;
|
||||
return /is not recognized as an internal or external command/i.test(stderr);
|
||||
}
|
||||
@@ -47,8 +214,9 @@ function normalizeExitError(
|
||||
command: string,
|
||||
args: readonly string[],
|
||||
result: ProcessRunResult,
|
||||
runtimeEnvironment?: ServerRuntimeEnvironment,
|
||||
): Error {
|
||||
if (isWindowsCommandNotFound(result.code, result.stderr)) {
|
||||
if (isWindowsCommandNotFound(result.code, result.stderr, runtimeEnvironment)) {
|
||||
return new Error(`Command not found: ${command}`);
|
||||
}
|
||||
|
||||
@@ -85,11 +253,30 @@ const DEFAULT_MAX_BUFFER_BYTES = 8 * 1024 * 1024;
|
||||
* wrapper, leaving the actual command running. Use `taskkill /T` to kill the
|
||||
* entire process tree instead.
|
||||
*/
|
||||
function killChild(child: ChildProcessHandle, signal: NodeJS.Signals = "SIGTERM"): void {
|
||||
if (process.platform === "win32" && child.pid !== undefined) {
|
||||
function killProcessTree(
|
||||
child: ChildProcessHandle,
|
||||
options: {
|
||||
runtimeEnvironment?: ServerRuntimeEnvironment | undefined;
|
||||
signal?: NodeJS.Signals | undefined;
|
||||
} = {},
|
||||
): void {
|
||||
const signal = options.signal ?? "SIGTERM";
|
||||
if (
|
||||
resolveRuntimeEnvironment(options.runtimeEnvironment).platform === "windows" &&
|
||||
child.pid !== undefined
|
||||
) {
|
||||
try {
|
||||
spawnSync("taskkill", ["/pid", String(child.pid), "/T", "/F"], { stdio: "ignore" });
|
||||
return;
|
||||
const result = spawnProcessSync("taskkill", ["/pid", String(child.pid), "/T", "/F"], {
|
||||
stdio: "ignore",
|
||||
shell: false,
|
||||
runtimeEnvironment: options.runtimeEnvironment,
|
||||
});
|
||||
if (!result.error && result.status === 0) {
|
||||
return;
|
||||
}
|
||||
if (result.error) {
|
||||
throw result.error;
|
||||
}
|
||||
} catch {
|
||||
// fallback to direct kill
|
||||
}
|
||||
@@ -135,12 +322,7 @@ export async function runProcess(
|
||||
const outputMode = options.outputMode ?? "error";
|
||||
|
||||
return new Promise<ProcessRunResult>((resolve, reject) => {
|
||||
const child = spawn(command, args, {
|
||||
cwd: options.cwd,
|
||||
env: options.env,
|
||||
stdio: "pipe",
|
||||
shell: process.platform === "win32",
|
||||
});
|
||||
const child = spawnPipedProcess(command, args, options);
|
||||
|
||||
let stdout = "";
|
||||
let stderr = "";
|
||||
@@ -154,9 +336,15 @@ export async function runProcess(
|
||||
|
||||
const timeoutTimer = setTimeout(() => {
|
||||
timedOut = true;
|
||||
killChild(child, "SIGTERM");
|
||||
killProcessTree(child, {
|
||||
runtimeEnvironment: options.runtimeEnvironment,
|
||||
signal: "SIGTERM",
|
||||
});
|
||||
forceKillTimer = setTimeout(() => {
|
||||
killChild(child, "SIGKILL");
|
||||
killProcessTree(child, {
|
||||
runtimeEnvironment: options.runtimeEnvironment,
|
||||
signal: "SIGKILL",
|
||||
});
|
||||
}, 1_000);
|
||||
}, timeoutMs);
|
||||
|
||||
@@ -171,7 +359,10 @@ export async function runProcess(
|
||||
};
|
||||
|
||||
const fail = (error: Error): void => {
|
||||
killChild(child, "SIGTERM");
|
||||
killProcessTree(child, {
|
||||
runtimeEnvironment: options.runtimeEnvironment,
|
||||
signal: "SIGTERM",
|
||||
});
|
||||
finalize(() => {
|
||||
reject(error);
|
||||
});
|
||||
@@ -244,7 +435,7 @@ export async function runProcess(
|
||||
|
||||
finalize(() => {
|
||||
if (!options.allowNonZeroExit && (timedOut || (code !== null && code !== 0))) {
|
||||
reject(normalizeExitError(command, args, result));
|
||||
reject(normalizeExitError(command, args, result, options.runtimeEnvironment));
|
||||
return;
|
||||
}
|
||||
resolve(result);
|
||||
|
||||
@@ -26,12 +26,12 @@ export class ProviderAdapterSessionNotFoundError extends Schema.TaggedErrorClass
|
||||
"ProviderAdapterSessionNotFoundError",
|
||||
{
|
||||
provider: Schema.String,
|
||||
threadId: Schema.String,
|
||||
sessionId: Schema.String,
|
||||
cause: Schema.optional(Schema.Defect),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Unknown ${this.provider} adapter thread: ${this.threadId}`;
|
||||
return `Unknown ${this.provider} adapter session: ${this.sessionId}`;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -42,12 +42,12 @@ export class ProviderAdapterSessionClosedError extends Schema.TaggedErrorClass<P
|
||||
"ProviderAdapterSessionClosedError",
|
||||
{
|
||||
provider: Schema.String,
|
||||
threadId: Schema.String,
|
||||
sessionId: Schema.String,
|
||||
cause: Schema.optional(Schema.Defect),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `${this.provider} adapter thread is closed: ${this.threadId}`;
|
||||
return `${this.provider} adapter session is closed: ${this.sessionId}`;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -75,13 +75,13 @@ export class ProviderAdapterProcessError extends Schema.TaggedErrorClass<Provide
|
||||
"ProviderAdapterProcessError",
|
||||
{
|
||||
provider: Schema.String,
|
||||
threadId: Schema.String,
|
||||
sessionId: Schema.String,
|
||||
detail: Schema.String,
|
||||
cause: Schema.optional(Schema.Defect),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Provider adapter process error (${this.provider}) for thread ${this.threadId}: ${this.detail}`;
|
||||
return `Provider adapter process error (${this.provider}) for session ${this.sessionId}: ${this.detail}`;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -122,12 +122,12 @@ export class ProviderUnsupportedError extends Schema.TaggedErrorClass<ProviderUn
|
||||
export class ProviderSessionNotFoundError extends Schema.TaggedErrorClass<ProviderSessionNotFoundError>()(
|
||||
"ProviderSessionNotFoundError",
|
||||
{
|
||||
threadId: Schema.String,
|
||||
sessionId: Schema.String,
|
||||
cause: Schema.optional(Schema.Defect),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Unknown provider thread: ${this.threadId}`;
|
||||
return `Unknown provider session: ${this.sessionId}`;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,24 +1,24 @@
|
||||
import assert from "node:assert/strict";
|
||||
import {
|
||||
ApprovalRequestId,
|
||||
EventId,
|
||||
ProviderItemId,
|
||||
type ProviderApprovalDecision,
|
||||
type ProviderEvent,
|
||||
ProviderSessionId,
|
||||
type ProviderSession,
|
||||
type ProviderSessionStartInput,
|
||||
ProviderThreadId,
|
||||
ProviderTurnId,
|
||||
type ProviderTurnStartResult,
|
||||
type ProviderUserInputAnswers,
|
||||
ThreadId,
|
||||
TurnId,
|
||||
} from "@t3tools/contracts";
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { afterAll, it, vi } from "@effect/vitest";
|
||||
import { afterAll, assert, it, vi } from "@effect/vitest";
|
||||
import { assertFailure } from "@effect/vitest/utils";
|
||||
|
||||
import { Effect, Fiber, Layer, Option, Stream } from "effect";
|
||||
|
||||
import {
|
||||
CodexAppServerManager,
|
||||
type CodexAppServerStartSessionInput,
|
||||
type CodexAppServerSendTurnInput,
|
||||
} from "../../codexAppServerManager.ts";
|
||||
import { ServerConfig } from "../../config.ts";
|
||||
@@ -27,20 +27,20 @@ import { CodexAdapter } from "../Services/CodexAdapter.ts";
|
||||
import { ProviderSessionDirectory } from "../Services/ProviderSessionDirectory.ts";
|
||||
import { makeCodexAdapterLive } from "./CodexAdapter.ts";
|
||||
|
||||
const asThreadId = (value: string): ThreadId => ThreadId.makeUnsafe(value);
|
||||
const asTurnId = (value: string): TurnId => TurnId.makeUnsafe(value);
|
||||
const asSessionId = (value: string): ProviderSessionId => ProviderSessionId.makeUnsafe(value);
|
||||
const asTurnId = (value: string): ProviderTurnId => ProviderTurnId.makeUnsafe(value);
|
||||
const asEventId = (value: string): EventId => EventId.makeUnsafe(value);
|
||||
const asItemId = (value: string): ProviderItemId => ProviderItemId.makeUnsafe(value);
|
||||
|
||||
class FakeCodexManager extends CodexAppServerManager {
|
||||
public startSessionImpl = vi.fn(
|
||||
async (input: CodexAppServerStartSessionInput): Promise<ProviderSession> => {
|
||||
async (input: ProviderSessionStartInput): Promise<ProviderSession> => {
|
||||
const now = new Date().toISOString();
|
||||
return {
|
||||
sessionId: asSessionId("sess-1"),
|
||||
provider: "codex",
|
||||
status: "ready",
|
||||
runtimeMode: input.runtimeMode,
|
||||
threadId: input.threadId,
|
||||
threadId: ProviderThreadId.makeUnsafe("thread-1"),
|
||||
cwd: input.cwd,
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
@@ -50,44 +50,36 @@ class FakeCodexManager extends CodexAppServerManager {
|
||||
|
||||
public sendTurnImpl = vi.fn(
|
||||
async (_input: CodexAppServerSendTurnInput): Promise<ProviderTurnStartResult> => ({
|
||||
threadId: asThreadId("thread-1"),
|
||||
threadId: ProviderThreadId.makeUnsafe("thread-1"),
|
||||
turnId: asTurnId("turn-1"),
|
||||
}),
|
||||
);
|
||||
|
||||
public interruptTurnImpl = vi.fn(
|
||||
async (_threadId: ThreadId, _turnId?: TurnId): Promise<void> => undefined,
|
||||
async (_sessionId: ProviderSessionId, _turnId?: ProviderTurnId): Promise<void> => undefined,
|
||||
);
|
||||
|
||||
public readThreadImpl = vi.fn(async (_threadId: ThreadId) => ({
|
||||
threadId: asThreadId("thread-1"),
|
||||
public readThreadImpl = vi.fn(async (_sessionId: ProviderSessionId) => ({
|
||||
threadId: ProviderThreadId.makeUnsafe("thread-1"),
|
||||
turns: [],
|
||||
}));
|
||||
|
||||
public rollbackThreadImpl = vi.fn(async (_threadId: ThreadId, _numTurns: number) => ({
|
||||
threadId: asThreadId("thread-1"),
|
||||
public rollbackThreadImpl = vi.fn(async (_sessionId: ProviderSessionId, _numTurns: number) => ({
|
||||
threadId: ProviderThreadId.makeUnsafe("thread-1"),
|
||||
turns: [],
|
||||
}));
|
||||
|
||||
public respondToRequestImpl = vi.fn(
|
||||
async (
|
||||
_threadId: ThreadId,
|
||||
_sessionId: ProviderSessionId,
|
||||
_requestId: ApprovalRequestId,
|
||||
_decision: ProviderApprovalDecision,
|
||||
): Promise<void> => undefined,
|
||||
);
|
||||
|
||||
public respondToUserInputImpl = vi.fn(
|
||||
async (
|
||||
_threadId: ThreadId,
|
||||
_requestId: ApprovalRequestId,
|
||||
_answers: ProviderUserInputAnswers,
|
||||
): Promise<void> => undefined,
|
||||
);
|
||||
|
||||
public stopAllImpl = vi.fn(() => undefined);
|
||||
|
||||
override startSession(input: CodexAppServerStartSessionInput): Promise<ProviderSession> {
|
||||
override startSession(input: ProviderSessionStartInput): Promise<ProviderSession> {
|
||||
return this.startSessionImpl(input);
|
||||
}
|
||||
|
||||
@@ -95,41 +87,33 @@ class FakeCodexManager extends CodexAppServerManager {
|
||||
return this.sendTurnImpl(input);
|
||||
}
|
||||
|
||||
override interruptTurn(threadId: ThreadId, turnId?: TurnId): Promise<void> {
|
||||
return this.interruptTurnImpl(threadId, turnId);
|
||||
override interruptTurn(sessionId: ProviderSessionId, turnId?: ProviderTurnId): Promise<void> {
|
||||
return this.interruptTurnImpl(sessionId, turnId);
|
||||
}
|
||||
|
||||
override readThread(threadId: ThreadId) {
|
||||
return this.readThreadImpl(threadId);
|
||||
override readThread(sessionId: ProviderSessionId) {
|
||||
return this.readThreadImpl(sessionId);
|
||||
}
|
||||
|
||||
override rollbackThread(threadId: ThreadId, numTurns: number) {
|
||||
return this.rollbackThreadImpl(threadId, numTurns);
|
||||
override rollbackThread(sessionId: ProviderSessionId, numTurns: number) {
|
||||
return this.rollbackThreadImpl(sessionId, numTurns);
|
||||
}
|
||||
|
||||
override respondToRequest(
|
||||
threadId: ThreadId,
|
||||
sessionId: ProviderSessionId,
|
||||
requestId: ApprovalRequestId,
|
||||
decision: ProviderApprovalDecision,
|
||||
): Promise<void> {
|
||||
return this.respondToRequestImpl(threadId, requestId, decision);
|
||||
return this.respondToRequestImpl(sessionId, requestId, decision);
|
||||
}
|
||||
|
||||
override respondToUserInput(
|
||||
threadId: ThreadId,
|
||||
requestId: ApprovalRequestId,
|
||||
answers: ProviderUserInputAnswers,
|
||||
): Promise<void> {
|
||||
return this.respondToUserInputImpl(threadId, requestId, answers);
|
||||
}
|
||||
|
||||
override stopSession(_threadId: ThreadId): void {}
|
||||
override stopSession(_sessionId: ProviderSessionId): void {}
|
||||
|
||||
override listSessions(): ProviderSession[] {
|
||||
return [];
|
||||
}
|
||||
|
||||
override hasSession(_threadId: ThreadId): boolean {
|
||||
override hasSession(_sessionId: ProviderSessionId): boolean {
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -143,8 +127,9 @@ const providerSessionDirectoryTestLayer = Layer.succeed(ProviderSessionDirectory
|
||||
getProvider: () =>
|
||||
Effect.die(new Error("ProviderSessionDirectory.getProvider is not used in test")),
|
||||
getBinding: () => Effect.succeed(Option.none()),
|
||||
getThreadId: () => Effect.succeed(Option.none()),
|
||||
remove: () => Effect.void,
|
||||
listThreadIds: () => Effect.succeed([]),
|
||||
listSessionIds: () => Effect.succeed([]),
|
||||
});
|
||||
|
||||
const validationManager = new FakeCodexManager();
|
||||
@@ -157,30 +142,24 @@ const validationLayer = it.layer(
|
||||
);
|
||||
|
||||
validationLayer("CodexAdapterLive validation", (it) => {
|
||||
it.effect("maps codex model options before starting a session", () =>
|
||||
it.effect("returns validation error for non-codex provider on startSession", () =>
|
||||
Effect.gen(function* () {
|
||||
validationManager.startSessionImpl.mockClear();
|
||||
const adapter = yield* CodexAdapter;
|
||||
const result = yield* adapter
|
||||
.startSession({
|
||||
provider: "claudeCode",
|
||||
})
|
||||
.pipe(Effect.result);
|
||||
|
||||
yield* adapter.startSession({
|
||||
provider: "codex",
|
||||
threadId: asThreadId("thread-1"),
|
||||
model: "gpt-5.3-codex",
|
||||
modelOptions: {
|
||||
codex: {
|
||||
fastMode: true,
|
||||
},
|
||||
},
|
||||
runtimeMode: "full-access",
|
||||
});
|
||||
|
||||
assert.deepStrictEqual(validationManager.startSessionImpl.mock.calls[0]?.[0], {
|
||||
provider: "codex",
|
||||
threadId: asThreadId("thread-1"),
|
||||
model: "gpt-5.3-codex",
|
||||
serviceTier: "fast",
|
||||
runtimeMode: "full-access",
|
||||
});
|
||||
assertFailure(
|
||||
result,
|
||||
new ProviderAdapterValidationError({
|
||||
provider: "codex",
|
||||
operation: "startSession",
|
||||
issue: "Expected provider 'codex' but received 'claudeCode'.",
|
||||
}),
|
||||
);
|
||||
assert.equal(validationManager.startSessionImpl.mock.calls.length, 0);
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -203,7 +182,7 @@ sessionErrorLayer("CodexAdapterLive session errors", (it) => {
|
||||
const adapter = yield* CodexAdapter;
|
||||
const result = yield* adapter
|
||||
.sendTurn({
|
||||
threadId: asThreadId("sess-missing"),
|
||||
sessionId: asSessionId("sess-missing"),
|
||||
input: "hello",
|
||||
attachments: [],
|
||||
})
|
||||
@@ -219,38 +198,8 @@ sessionErrorLayer("CodexAdapterLive session errors", (it) => {
|
||||
return;
|
||||
}
|
||||
assert.equal(result.failure.provider, "codex");
|
||||
assert.equal(result.failure.threadId, "sess-missing");
|
||||
assert.equal(result.failure.cause instanceof Error, true);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("maps codex model options before sending a turn", () =>
|
||||
Effect.gen(function* () {
|
||||
sessionErrorManager.sendTurnImpl.mockClear();
|
||||
const adapter = yield* CodexAdapter;
|
||||
|
||||
yield* Effect.ignore(
|
||||
adapter.sendTurn({
|
||||
threadId: asThreadId("sess-missing"),
|
||||
input: "hello",
|
||||
model: "gpt-5.3-codex",
|
||||
modelOptions: {
|
||||
codex: {
|
||||
reasoningEffort: "high",
|
||||
fastMode: true,
|
||||
},
|
||||
},
|
||||
attachments: [],
|
||||
}),
|
||||
);
|
||||
|
||||
assert.deepStrictEqual(sessionErrorManager.sendTurnImpl.mock.calls[0]?.[0], {
|
||||
threadId: asThreadId("sess-missing"),
|
||||
input: "hello",
|
||||
model: "gpt-5.3-codex",
|
||||
effort: "high",
|
||||
serviceTier: "fast",
|
||||
});
|
||||
assert.equal(result.failure.sessionId, "sess-missing");
|
||||
assert.instanceOf(result.failure.cause, Error);
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -265,7 +214,7 @@ const lifecycleLayer = it.layer(
|
||||
);
|
||||
|
||||
lifecycleLayer("CodexAdapterLive lifecycle", (it) => {
|
||||
it.effect("maps completed agent message items to canonical item.completed events", () =>
|
||||
it.effect("maps completed agent message items to canonical message.completed events", () =>
|
||||
Effect.gen(function* () {
|
||||
const adapter = yield* CodexAdapter;
|
||||
const firstEventFiber = yield* Stream.runHead(adapter.streamEvents).pipe(Effect.forkChild);
|
||||
@@ -274,9 +223,10 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => {
|
||||
id: asEventId("evt-msg-complete"),
|
||||
kind: "notification",
|
||||
provider: "codex",
|
||||
sessionId: asSessionId("sess-1"),
|
||||
createdAt: new Date().toISOString(),
|
||||
method: "item/completed",
|
||||
threadId: asThreadId("thread-1"),
|
||||
threadId: ProviderThreadId.makeUnsafe("thread-1"),
|
||||
turnId: asTurnId("turn-1"),
|
||||
itemId: asItemId("msg_1"),
|
||||
payload: {
|
||||
@@ -294,86 +244,12 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => {
|
||||
if (firstEvent._tag !== "Some") {
|
||||
return;
|
||||
}
|
||||
assert.equal(firstEvent.value.type, "item.completed");
|
||||
if (firstEvent.value.type !== "item.completed") {
|
||||
assert.equal(firstEvent.value.type, "message.completed");
|
||||
if (firstEvent.value.type !== "message.completed") {
|
||||
return;
|
||||
}
|
||||
assert.equal(firstEvent.value.itemId, "msg_1");
|
||||
assert.equal(firstEvent.value.turnId, "turn-1");
|
||||
assert.equal(firstEvent.value.payload.itemType, "assistant_message");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("maps completed plan items to canonical proposed-plan completion events", () =>
|
||||
Effect.gen(function* () {
|
||||
const adapter = yield* CodexAdapter;
|
||||
const firstEventFiber = yield* Stream.runHead(adapter.streamEvents).pipe(Effect.forkChild);
|
||||
|
||||
const event: ProviderEvent = {
|
||||
id: asEventId("evt-plan-complete"),
|
||||
kind: "notification",
|
||||
provider: "codex",
|
||||
createdAt: new Date().toISOString(),
|
||||
method: "item/completed",
|
||||
threadId: asThreadId("thread-1"),
|
||||
turnId: asTurnId("turn-1"),
|
||||
itemId: asItemId("plan_1"),
|
||||
payload: {
|
||||
item: {
|
||||
type: "Plan",
|
||||
id: "plan_1",
|
||||
text: "## Final plan\n\n- one\n- two",
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
lifecycleManager.emit("event", event);
|
||||
const firstEvent = yield* Fiber.join(firstEventFiber);
|
||||
|
||||
assert.equal(firstEvent._tag, "Some");
|
||||
if (firstEvent._tag !== "Some") {
|
||||
return;
|
||||
}
|
||||
assert.equal(firstEvent.value.type, "turn.proposed.completed");
|
||||
if (firstEvent.value.type !== "turn.proposed.completed") {
|
||||
return;
|
||||
}
|
||||
assert.equal(firstEvent.value.turnId, "turn-1");
|
||||
assert.equal(firstEvent.value.payload.planMarkdown, "## Final plan\n\n- one\n- two");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("maps plan deltas to canonical proposed-plan delta events", () =>
|
||||
Effect.gen(function* () {
|
||||
const adapter = yield* CodexAdapter;
|
||||
const firstEventFiber = yield* Stream.runHead(adapter.streamEvents).pipe(Effect.forkChild);
|
||||
|
||||
lifecycleManager.emit("event", {
|
||||
id: asEventId("evt-plan-delta"),
|
||||
kind: "notification",
|
||||
provider: "codex",
|
||||
createdAt: new Date().toISOString(),
|
||||
method: "item/plan/delta",
|
||||
threadId: asThreadId("thread-1"),
|
||||
turnId: asTurnId("turn-1"),
|
||||
itemId: asItemId("plan_1"),
|
||||
payload: {
|
||||
delta: "## Final plan",
|
||||
},
|
||||
} satisfies ProviderEvent);
|
||||
|
||||
const firstEvent = yield* Fiber.join(firstEventFiber);
|
||||
|
||||
assert.equal(firstEvent._tag, "Some");
|
||||
if (firstEvent._tag !== "Some") {
|
||||
return;
|
||||
}
|
||||
assert.equal(firstEvent.value.type, "turn.proposed.delta");
|
||||
if (firstEvent.value.type !== "turn.proposed.delta") {
|
||||
return;
|
||||
}
|
||||
assert.equal(firstEvent.value.turnId, "turn-1");
|
||||
assert.equal(firstEvent.value.payload.delta, "## Final plan");
|
||||
}),
|
||||
);
|
||||
|
||||
@@ -386,7 +262,7 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => {
|
||||
id: asEventId("evt-session-closed"),
|
||||
kind: "session",
|
||||
provider: "codex",
|
||||
threadId: asThreadId("thread-1"),
|
||||
sessionId: asSessionId("sess-1"),
|
||||
createdAt: new Date().toISOString(),
|
||||
method: "session/closed",
|
||||
message: "Session stopped",
|
||||
@@ -403,277 +279,12 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => {
|
||||
if (firstEvent.value.type !== "session.exited") {
|
||||
return;
|
||||
}
|
||||
assert.equal(firstEvent.value.threadId, "thread-1");
|
||||
assert.equal(firstEvent.value.payload.reason, "Session stopped");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("preserves request type when mapping serverRequest/resolved", () =>
|
||||
Effect.gen(function* () {
|
||||
const adapter = yield* CodexAdapter;
|
||||
const firstEventFiber = yield* Stream.runHead(adapter.streamEvents).pipe(Effect.forkChild);
|
||||
|
||||
const event: ProviderEvent = {
|
||||
id: asEventId("evt-request-resolved"),
|
||||
kind: "notification",
|
||||
provider: "codex",
|
||||
threadId: asThreadId("thread-1"),
|
||||
createdAt: new Date().toISOString(),
|
||||
method: "serverRequest/resolved",
|
||||
requestId: ApprovalRequestId.makeUnsafe("req-1"),
|
||||
payload: {
|
||||
request: {
|
||||
method: "item/commandExecution/requestApproval",
|
||||
},
|
||||
decision: "accept",
|
||||
},
|
||||
};
|
||||
|
||||
lifecycleManager.emit("event", event);
|
||||
const firstEvent = yield* Fiber.join(firstEventFiber);
|
||||
|
||||
assert.equal(firstEvent._tag, "Some");
|
||||
if (firstEvent._tag !== "Some") {
|
||||
return;
|
||||
}
|
||||
assert.equal(firstEvent.value.type, "request.resolved");
|
||||
if (firstEvent.value.type !== "request.resolved") {
|
||||
return;
|
||||
}
|
||||
assert.equal(firstEvent.value.payload.requestType, "command_execution_approval");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("maps windowsSandbox/setupCompleted to session state and warning on failure", () =>
|
||||
Effect.gen(function* () {
|
||||
const adapter = yield* CodexAdapter;
|
||||
const eventsFiber = yield* Stream.runCollect(Stream.take(adapter.streamEvents, 2)).pipe(
|
||||
Effect.forkChild,
|
||||
);
|
||||
|
||||
const event: ProviderEvent = {
|
||||
id: asEventId("evt-windows-sandbox-failed"),
|
||||
kind: "notification",
|
||||
provider: "codex",
|
||||
threadId: asThreadId("thread-1"),
|
||||
createdAt: new Date().toISOString(),
|
||||
method: "windowsSandbox/setupCompleted",
|
||||
message: "Sandbox setup failed",
|
||||
payload: {
|
||||
success: false,
|
||||
detail: "unsupported environment",
|
||||
},
|
||||
};
|
||||
|
||||
lifecycleManager.emit("event", event);
|
||||
const events = Array.from(yield* Fiber.join(eventsFiber));
|
||||
|
||||
assert.equal(events.length, 2);
|
||||
|
||||
const firstEvent = events[0];
|
||||
const secondEvent = events[1];
|
||||
|
||||
assert.equal(firstEvent?.type, "session.state.changed");
|
||||
if (firstEvent?.type === "session.state.changed") {
|
||||
assert.equal(firstEvent.payload.state, "error");
|
||||
assert.equal(firstEvent.payload.reason, "Sandbox setup failed");
|
||||
}
|
||||
|
||||
assert.equal(secondEvent?.type, "runtime.warning");
|
||||
if (secondEvent?.type === "runtime.warning") {
|
||||
assert.equal(secondEvent.payload.message, "Sandbox setup failed");
|
||||
}
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect(
|
||||
"maps requestUserInput requests and answered notifications to canonical user-input events",
|
||||
() =>
|
||||
Effect.gen(function* () {
|
||||
const adapter = yield* CodexAdapter;
|
||||
const eventsFiber = yield* Stream.runCollect(Stream.take(adapter.streamEvents, 2)).pipe(
|
||||
Effect.forkChild,
|
||||
);
|
||||
|
||||
lifecycleManager.emit("event", {
|
||||
id: asEventId("evt-user-input-requested"),
|
||||
kind: "request",
|
||||
provider: "codex",
|
||||
threadId: asThreadId("thread-1"),
|
||||
createdAt: new Date().toISOString(),
|
||||
method: "item/tool/requestUserInput",
|
||||
requestId: ApprovalRequestId.makeUnsafe("req-user-input-1"),
|
||||
payload: {
|
||||
questions: [
|
||||
{
|
||||
id: "sandbox_mode",
|
||||
header: "Sandbox",
|
||||
question: "Which mode should be used?",
|
||||
options: [
|
||||
{
|
||||
label: "workspace-write",
|
||||
description: "Allow workspace writes only",
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
} satisfies ProviderEvent);
|
||||
lifecycleManager.emit("event", {
|
||||
id: asEventId("evt-user-input-resolved"),
|
||||
kind: "notification",
|
||||
provider: "codex",
|
||||
threadId: asThreadId("thread-1"),
|
||||
createdAt: new Date().toISOString(),
|
||||
method: "item/tool/requestUserInput/answered",
|
||||
requestId: ApprovalRequestId.makeUnsafe("req-user-input-1"),
|
||||
payload: {
|
||||
answers: {
|
||||
sandbox_mode: {
|
||||
answers: ["workspace-write"],
|
||||
},
|
||||
},
|
||||
},
|
||||
} satisfies ProviderEvent);
|
||||
|
||||
const events = Array.from(yield* Fiber.join(eventsFiber));
|
||||
assert.equal(events[0]?.type, "user-input.requested");
|
||||
if (events[0]?.type === "user-input.requested") {
|
||||
assert.equal(events[0].requestId, "req-user-input-1");
|
||||
assert.equal(events[0].payload.questions[0]?.id, "sandbox_mode");
|
||||
}
|
||||
|
||||
assert.equal(events[1]?.type, "user-input.resolved");
|
||||
if (events[1]?.type === "user-input.resolved") {
|
||||
assert.equal(events[1].requestId, "req-user-input-1");
|
||||
assert.deepEqual(events[1].payload.answers, {
|
||||
sandbox_mode: "workspace-write",
|
||||
});
|
||||
}
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("maps Codex task and reasoning event chunks into canonical runtime events", () =>
|
||||
Effect.gen(function* () {
|
||||
const adapter = yield* CodexAdapter;
|
||||
const eventsFiber = yield* Stream.runCollect(Stream.take(adapter.streamEvents, 5)).pipe(
|
||||
Effect.forkChild,
|
||||
);
|
||||
|
||||
lifecycleManager.emit("event", {
|
||||
id: asEventId("evt-codex-task-started"),
|
||||
kind: "notification",
|
||||
provider: "codex",
|
||||
threadId: asThreadId("thread-1"),
|
||||
createdAt: new Date().toISOString(),
|
||||
method: "codex/event/task_started",
|
||||
payload: {
|
||||
id: "turn-structured-1",
|
||||
msg: {
|
||||
type: "task_started",
|
||||
turn_id: "turn-structured-1",
|
||||
collaboration_mode_kind: "plan",
|
||||
},
|
||||
},
|
||||
} satisfies ProviderEvent);
|
||||
|
||||
lifecycleManager.emit("event", {
|
||||
id: asEventId("evt-codex-agent-reasoning"),
|
||||
kind: "notification",
|
||||
provider: "codex",
|
||||
threadId: asThreadId("thread-1"),
|
||||
createdAt: new Date().toISOString(),
|
||||
method: "codex/event/agent_reasoning",
|
||||
payload: {
|
||||
id: "turn-structured-1",
|
||||
msg: {
|
||||
type: "agent_reasoning",
|
||||
text: "Need to compare both transport layers before finalizing the plan.",
|
||||
},
|
||||
},
|
||||
} satisfies ProviderEvent);
|
||||
|
||||
lifecycleManager.emit("event", {
|
||||
id: asEventId("evt-codex-reasoning-delta"),
|
||||
kind: "notification",
|
||||
provider: "codex",
|
||||
threadId: asThreadId("thread-1"),
|
||||
createdAt: new Date().toISOString(),
|
||||
method: "codex/event/reasoning_content_delta",
|
||||
payload: {
|
||||
id: "turn-structured-1",
|
||||
msg: {
|
||||
type: "reasoning_content_delta",
|
||||
turn_id: "turn-structured-1",
|
||||
item_id: "rs_reasoning_1",
|
||||
delta: "**Compare** transport boundaries",
|
||||
summary_index: 0,
|
||||
},
|
||||
},
|
||||
} satisfies ProviderEvent);
|
||||
|
||||
lifecycleManager.emit("event", {
|
||||
id: asEventId("evt-codex-task-complete"),
|
||||
kind: "notification",
|
||||
provider: "codex",
|
||||
threadId: asThreadId("thread-1"),
|
||||
createdAt: new Date().toISOString(),
|
||||
method: "codex/event/task_complete",
|
||||
payload: {
|
||||
id: "turn-structured-1",
|
||||
msg: {
|
||||
type: "task_complete",
|
||||
turn_id: "turn-structured-1",
|
||||
last_agent_message: "<proposed_plan>\n# Ship it\n</proposed_plan>",
|
||||
},
|
||||
},
|
||||
} satisfies ProviderEvent);
|
||||
|
||||
const events = Array.from(yield* Fiber.join(eventsFiber));
|
||||
|
||||
assert.equal(events[0]?.type, "task.started");
|
||||
if (events[0]?.type === "task.started") {
|
||||
assert.equal(events[0].turnId, "turn-structured-1");
|
||||
assert.equal(events[0].payload.taskId, "turn-structured-1");
|
||||
assert.equal(events[0].payload.taskType, "plan");
|
||||
}
|
||||
|
||||
assert.equal(events[1]?.type, "task.progress");
|
||||
if (events[1]?.type === "task.progress") {
|
||||
assert.equal(events[1].payload.taskId, "turn-structured-1");
|
||||
assert.equal(
|
||||
events[1].payload.description,
|
||||
"Need to compare both transport layers before finalizing the plan.",
|
||||
);
|
||||
}
|
||||
|
||||
assert.equal(events[2]?.type, "content.delta");
|
||||
if (events[2]?.type === "content.delta") {
|
||||
assert.equal(events[2].turnId, "turn-structured-1");
|
||||
assert.equal(events[2].itemId, "rs_reasoning_1");
|
||||
assert.equal(events[2].payload.streamKind, "reasoning_summary_text");
|
||||
assert.equal(events[2].payload.summaryIndex, 0);
|
||||
}
|
||||
|
||||
assert.equal(events[3]?.type, "task.completed");
|
||||
if (events[3]?.type === "task.completed") {
|
||||
assert.equal(events[3].turnId, "turn-structured-1");
|
||||
assert.equal(events[3].payload.taskId, "turn-structured-1");
|
||||
assert.equal(events[3].payload.summary, "<proposed_plan>\n# Ship it\n</proposed_plan>");
|
||||
}
|
||||
|
||||
assert.equal(events[4]?.type, "turn.proposed.completed");
|
||||
if (events[4]?.type === "turn.proposed.completed") {
|
||||
assert.equal(events[4].turnId, "turn-structured-1");
|
||||
assert.equal(events[4].payload.planMarkdown, "# Ship it");
|
||||
}
|
||||
assert.equal(firstEvent.value.sessionId, "sess-1");
|
||||
assert.equal(firstEvent.value.message, "Session stopped");
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
afterAll(() => {
|
||||
if (lifecycleManager.stopAllImpl.mock.calls.length === 0) {
|
||||
lifecycleManager.stopAll();
|
||||
}
|
||||
assert.ok(lifecycleManager.stopAllImpl.mock.calls.length >= 1);
|
||||
assert.equal(lifecycleManager.stopAllImpl.mock.calls.length, 1);
|
||||
});
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,655 +0,0 @@
|
||||
import { EventEmitter } from "node:events";
|
||||
import { PassThrough } from "node:stream";
|
||||
import readline from "node:readline";
|
||||
|
||||
import { ApprovalRequestId, ThreadId } from "@t3tools/contracts";
|
||||
import { assert, describe, it } from "@effect/vitest";
|
||||
import { Effect, Fiber, Stream } from "effect";
|
||||
|
||||
import { ProviderAdapterValidationError } from "../Errors.ts";
|
||||
import { CursorAdapter } from "../Services/CursorAdapter.ts";
|
||||
import { makeCursorAdapterLive } from "./CursorAdapter.ts";
|
||||
|
||||
const THREAD_ID = ThreadId.makeUnsafe("thread-cursor-1");
|
||||
const RESUME_THREAD_ID = ThreadId.makeUnsafe("thread-cursor-resume");
|
||||
const LEGACY_RESUME_THREAD_ID = ThreadId.makeUnsafe("thread-cursor-legacy");
|
||||
|
||||
class FakeCursorAcpProcess extends EventEmitter {
|
||||
readonly stdin = new PassThrough();
|
||||
readonly stdout = new PassThrough();
|
||||
readonly stderr = new PassThrough();
|
||||
readonly requests: Array<{ method: string; params: unknown }> = [];
|
||||
killed = false;
|
||||
|
||||
private readonly input = readline.createInterface({ input: this.stdin });
|
||||
private permissionRequestId = 700;
|
||||
lastPermissionSelection: string | undefined;
|
||||
|
||||
constructor() {
|
||||
super();
|
||||
this.input.on("line", (line) => {
|
||||
const message = JSON.parse(line) as Record<string, unknown>;
|
||||
if (typeof message.method === "string") {
|
||||
this.handleRequest(message);
|
||||
return;
|
||||
}
|
||||
|
||||
if (message.id === this.permissionRequestId) {
|
||||
const optionId =
|
||||
(message.result as { outcome?: { optionId?: unknown } } | undefined)?.outcome?.optionId;
|
||||
if (typeof optionId === "string") {
|
||||
this.lastPermissionSelection = optionId;
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
kill(): boolean {
|
||||
if (this.killed) {
|
||||
return true;
|
||||
}
|
||||
this.killed = true;
|
||||
this.emit("exit", 0, null);
|
||||
return true;
|
||||
}
|
||||
|
||||
emitPermissionRequest(): void {
|
||||
this.emitServerMessage({
|
||||
jsonrpc: "2.0",
|
||||
id: this.permissionRequestId,
|
||||
method: "session/request_permission",
|
||||
params: {
|
||||
sessionId: "acp-session-1",
|
||||
toolCall: {
|
||||
toolCallId: "tool-perm-1",
|
||||
kind: "execute",
|
||||
title: "`pwd`",
|
||||
},
|
||||
options: [
|
||||
{ optionId: "allow-once", kind: "allow_once" },
|
||||
{ optionId: "allow-always", kind: "allow_always" },
|
||||
{ optionId: "reject-once", kind: "reject_once" },
|
||||
],
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
private handleRequest(message: Record<string, unknown>): void {
|
||||
const method = message.method;
|
||||
const id = message.id;
|
||||
if (typeof method !== "string" || (typeof id !== "string" && typeof id !== "number")) {
|
||||
return;
|
||||
}
|
||||
this.requests.push({ method, params: message.params });
|
||||
|
||||
switch (method) {
|
||||
case "initialize": {
|
||||
const protocolVersion = (message.params as { protocolVersion?: unknown } | undefined)
|
||||
?.protocolVersion;
|
||||
if (typeof protocolVersion !== "number") {
|
||||
this.emitServerMessage({
|
||||
jsonrpc: "2.0",
|
||||
id,
|
||||
error: {
|
||||
code: -32602,
|
||||
message: "Invalid params",
|
||||
data: {
|
||||
_errors: [],
|
||||
protocolVersion: {
|
||||
_errors: ["Invalid input: expected number, received undefined"],
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
return;
|
||||
}
|
||||
this.emitServerMessage({
|
||||
jsonrpc: "2.0",
|
||||
id,
|
||||
result: {
|
||||
protocolVersion: 1,
|
||||
agentCapabilities: {
|
||||
loadSession: true,
|
||||
},
|
||||
authMethods: [{ id: "cursor_login" }],
|
||||
},
|
||||
});
|
||||
return;
|
||||
}
|
||||
case "authenticate":
|
||||
this.emitServerMessage({
|
||||
jsonrpc: "2.0",
|
||||
id,
|
||||
result: {},
|
||||
});
|
||||
return;
|
||||
case "session/new":
|
||||
this.emitServerMessage({
|
||||
jsonrpc: "2.0",
|
||||
id,
|
||||
result: {
|
||||
sessionId: "acp-session-1",
|
||||
modes: {
|
||||
currentModeId: "agent",
|
||||
availableModes: [{ id: "agent" }],
|
||||
},
|
||||
},
|
||||
});
|
||||
return;
|
||||
case "session/load":
|
||||
this.emitServerMessage({
|
||||
jsonrpc: "2.0",
|
||||
id,
|
||||
result: {},
|
||||
});
|
||||
return;
|
||||
case "session/set_model":
|
||||
this.emitServerMessage({
|
||||
jsonrpc: "2.0",
|
||||
id,
|
||||
result: {},
|
||||
});
|
||||
return;
|
||||
case "session/prompt": {
|
||||
this.emitServerMessage({
|
||||
jsonrpc: "2.0",
|
||||
method: "session/update",
|
||||
params: {
|
||||
sessionId: "acp-session-1",
|
||||
update: {
|
||||
sessionUpdate: "agent_thought_chunk",
|
||||
content: {
|
||||
type: "text",
|
||||
text: "thinking",
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
this.emitServerMessage({
|
||||
jsonrpc: "2.0",
|
||||
method: "session/update",
|
||||
params: {
|
||||
sessionId: "acp-session-1",
|
||||
update: {
|
||||
sessionUpdate: "agent_message_chunk",
|
||||
content: {
|
||||
type: "text",
|
||||
text: "hello",
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
this.emitServerMessage({
|
||||
jsonrpc: "2.0",
|
||||
method: "session/update",
|
||||
params: {
|
||||
sessionId: "acp-session-1",
|
||||
update: {
|
||||
sessionUpdate: "tool_call",
|
||||
toolCallId: "tool-1",
|
||||
kind: "execute",
|
||||
title: "`pwd`",
|
||||
rawInput: { command: "pwd" },
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
this.emitServerMessage({
|
||||
jsonrpc: "2.0",
|
||||
method: "session/update",
|
||||
params: {
|
||||
sessionId: "acp-session-1",
|
||||
update: {
|
||||
sessionUpdate: "tool_call_update",
|
||||
toolCallId: "tool-1",
|
||||
status: "completed",
|
||||
rawOutput: {
|
||||
exitCode: 0,
|
||||
stdout: "/tmp/project",
|
||||
stderr: "",
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
this.emitServerMessage({
|
||||
jsonrpc: "2.0",
|
||||
id,
|
||||
result: {
|
||||
stopReason: "end_turn",
|
||||
},
|
||||
});
|
||||
return;
|
||||
}
|
||||
case "session/cancel":
|
||||
this.emitServerMessage({
|
||||
jsonrpc: "2.0",
|
||||
id,
|
||||
error: {
|
||||
code: -32601,
|
||||
message: "Method not found",
|
||||
},
|
||||
});
|
||||
return;
|
||||
default:
|
||||
this.emitServerMessage({
|
||||
jsonrpc: "2.0",
|
||||
id,
|
||||
error: {
|
||||
code: -32601,
|
||||
message: `Unhandled method: ${method}`,
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
private emitServerMessage(message: unknown): void {
|
||||
this.stdout.write(`${JSON.stringify(message)}\n`);
|
||||
}
|
||||
}
|
||||
|
||||
describe("CursorAdapterLive", () => {
|
||||
it.effect("returns validation error for non-cursor provider on startSession", () => {
|
||||
const fake = new FakeCursorAcpProcess();
|
||||
const layer = makeCursorAdapterLive({
|
||||
createProcess: () => fake as never,
|
||||
});
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const adapter = yield* CursorAdapter;
|
||||
const result = yield* adapter
|
||||
.startSession({
|
||||
provider: "codex",
|
||||
threadId: THREAD_ID,
|
||||
runtimeMode: "full-access",
|
||||
})
|
||||
.pipe(Effect.result);
|
||||
|
||||
assert.equal(result._tag, "Failure");
|
||||
if (result._tag !== "Failure") {
|
||||
return;
|
||||
}
|
||||
assert.deepEqual(
|
||||
result.failure,
|
||||
new ProviderAdapterValidationError({
|
||||
provider: "cursor",
|
||||
operation: "startSession",
|
||||
issue: "Expected provider 'cursor' but received 'codex'.",
|
||||
}),
|
||||
);
|
||||
}).pipe(Effect.provide(layer));
|
||||
});
|
||||
|
||||
it.effect("maps ACP prompt/update events into canonical runtime events", () => {
|
||||
const fake = new FakeCursorAcpProcess();
|
||||
const layer = makeCursorAdapterLive({
|
||||
createProcess: () => fake as never,
|
||||
});
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const adapter = yield* CursorAdapter;
|
||||
|
||||
const eventsFiber = yield* Stream.take(adapter.streamEvents, 13).pipe(
|
||||
Stream.runCollect,
|
||||
Effect.forkChild,
|
||||
);
|
||||
|
||||
const session = yield* adapter.startSession({
|
||||
provider: "cursor",
|
||||
threadId: THREAD_ID,
|
||||
cwd: "/tmp/project",
|
||||
runtimeMode: "full-access",
|
||||
});
|
||||
|
||||
const turn = yield* adapter.sendTurn({
|
||||
threadId: session.threadId,
|
||||
input: "hello",
|
||||
attachments: [],
|
||||
});
|
||||
|
||||
const events = Array.from(yield* Fiber.join(eventsFiber));
|
||||
assert.deepEqual(
|
||||
events.map((event) => event.type),
|
||||
[
|
||||
"session.configured",
|
||||
"auth.status",
|
||||
"auth.status",
|
||||
"session.started",
|
||||
"thread.started",
|
||||
"session.state.changed",
|
||||
"turn.started",
|
||||
"content.delta",
|
||||
"content.delta",
|
||||
"item.started",
|
||||
"item.completed",
|
||||
"item.completed",
|
||||
"turn.completed",
|
||||
],
|
||||
);
|
||||
|
||||
const turnStarted = events[6];
|
||||
assert.equal(turnStarted?.type, "turn.started");
|
||||
if (turnStarted?.type === "turn.started") {
|
||||
assert.equal(String(turnStarted.turnId), String(turn.turnId));
|
||||
}
|
||||
|
||||
const completion = events[12];
|
||||
assert.equal(completion?.type, "turn.completed");
|
||||
if (completion?.type === "turn.completed") {
|
||||
assert.equal(completion.payload.state, "completed");
|
||||
}
|
||||
}).pipe(Effect.provide(layer));
|
||||
});
|
||||
|
||||
it.effect("passes requested model to ACP process startup", () => {
|
||||
const fake = new FakeCursorAcpProcess();
|
||||
let createProcessInput:
|
||||
| {
|
||||
readonly binaryPath: string;
|
||||
readonly cwd: string;
|
||||
readonly env: NodeJS.ProcessEnv;
|
||||
readonly model?: string;
|
||||
}
|
||||
| undefined;
|
||||
const layer = makeCursorAdapterLive({
|
||||
createProcess: (input) => {
|
||||
createProcessInput = input;
|
||||
return fake as never;
|
||||
},
|
||||
});
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const adapter = yield* CursorAdapter;
|
||||
yield* adapter.startSession({
|
||||
provider: "cursor",
|
||||
threadId: THREAD_ID,
|
||||
model: "composer-1.5",
|
||||
runtimeMode: "full-access",
|
||||
});
|
||||
|
||||
assert.deepEqual(createProcessInput?.model, "composer-1.5");
|
||||
}).pipe(Effect.provide(layer));
|
||||
});
|
||||
|
||||
it.effect("writes provider-native observability records when enabled", () => {
|
||||
const nativeEvents: Array<{
|
||||
event?: {
|
||||
provider?: string;
|
||||
method?: string;
|
||||
threadId?: string;
|
||||
};
|
||||
}> = [];
|
||||
const fake = new FakeCursorAcpProcess();
|
||||
const layer = makeCursorAdapterLive({
|
||||
createProcess: () => fake as never,
|
||||
nativeEventLogger: {
|
||||
filePath: "memory://cursor-native-events",
|
||||
write: (event) => {
|
||||
nativeEvents.push(event as (typeof nativeEvents)[number]);
|
||||
return Effect.void;
|
||||
},
|
||||
close: () => Effect.void,
|
||||
},
|
||||
});
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const adapter = yield* CursorAdapter;
|
||||
const session = yield* adapter.startSession({
|
||||
provider: "cursor",
|
||||
threadId: THREAD_ID,
|
||||
cwd: "/tmp/project",
|
||||
runtimeMode: "full-access",
|
||||
});
|
||||
|
||||
assert.equal(nativeEvents.length > 0, true);
|
||||
assert.equal(nativeEvents.some((record) => record.event?.provider === "cursor"), true);
|
||||
assert.equal(nativeEvents.some((record) => record.event?.threadId === session.threadId), true);
|
||||
assert.equal(nativeEvents.some((record) => record.event?.method === "cursor/acp/response"), true);
|
||||
}).pipe(Effect.provide(layer));
|
||||
});
|
||||
|
||||
it.effect("resumes ACP session using resumeCursor.acpSessionId", () => {
|
||||
const fake = new FakeCursorAcpProcess();
|
||||
const layer = makeCursorAdapterLive({
|
||||
createProcess: () => fake as never,
|
||||
});
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const adapter = yield* CursorAdapter;
|
||||
const session = yield* adapter.startSession({
|
||||
provider: "cursor",
|
||||
threadId: RESUME_THREAD_ID,
|
||||
cwd: "/tmp/project",
|
||||
resumeCursor: {
|
||||
acpSessionId: "acp-session-resume",
|
||||
},
|
||||
runtimeMode: "full-access",
|
||||
});
|
||||
|
||||
const methods = new Set(fake.requests.map((request) => request.method));
|
||||
assert.equal(methods.has("session/load"), true);
|
||||
assert.equal(methods.has("session/new"), false);
|
||||
|
||||
const loadRequest = fake.requests.find((request) => request.method === "session/load");
|
||||
assert.deepEqual(loadRequest?.params, {
|
||||
sessionId: "acp-session-resume",
|
||||
cwd: "/tmp/project",
|
||||
mcpServers: [],
|
||||
});
|
||||
assert.equal(session.threadId, RESUME_THREAD_ID);
|
||||
assert.deepEqual(session.resumeCursor, {
|
||||
acpSessionId: "acp-session-resume",
|
||||
});
|
||||
}).pipe(Effect.provide(layer));
|
||||
});
|
||||
|
||||
it.effect("accepts legacy resumeCursor.sessionId for ACP session resume", () => {
|
||||
const fake = new FakeCursorAcpProcess();
|
||||
const layer = makeCursorAdapterLive({
|
||||
createProcess: () => fake as never,
|
||||
});
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const adapter = yield* CursorAdapter;
|
||||
const session = yield* adapter.startSession({
|
||||
provider: "cursor",
|
||||
threadId: LEGACY_RESUME_THREAD_ID,
|
||||
cwd: "/tmp/project",
|
||||
resumeCursor: {
|
||||
sessionId: "acp-session-legacy",
|
||||
},
|
||||
runtimeMode: "full-access",
|
||||
});
|
||||
|
||||
const loadRequest = fake.requests.find((request) => request.method === "session/load");
|
||||
assert.deepEqual(loadRequest?.params, {
|
||||
sessionId: "acp-session-legacy",
|
||||
cwd: "/tmp/project",
|
||||
mcpServers: [],
|
||||
});
|
||||
assert.equal(session.threadId, LEGACY_RESUME_THREAD_ID);
|
||||
assert.deepEqual(session.resumeCursor, {
|
||||
acpSessionId: "acp-session-legacy",
|
||||
});
|
||||
}).pipe(Effect.provide(layer));
|
||||
});
|
||||
|
||||
it.effect("bridges permission requests to request.opened/request.resolved", () => {
|
||||
const fake = new FakeCursorAcpProcess();
|
||||
const layer = makeCursorAdapterLive({
|
||||
createProcess: () => fake as never,
|
||||
});
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const adapter = yield* CursorAdapter;
|
||||
|
||||
const session = yield* adapter.startSession({
|
||||
provider: "cursor",
|
||||
threadId: THREAD_ID,
|
||||
runtimeMode: "approval-required",
|
||||
});
|
||||
|
||||
// consume startup events
|
||||
yield* Stream.take(adapter.streamEvents, 6).pipe(Stream.runDrain);
|
||||
|
||||
fake.emitPermissionRequest();
|
||||
|
||||
const opened = yield* Stream.runHead(adapter.streamEvents);
|
||||
assert.equal(opened._tag, "Some");
|
||||
if (opened._tag !== "Some") {
|
||||
return;
|
||||
}
|
||||
assert.equal(opened.value.type, "request.opened");
|
||||
if (opened.value.type !== "request.opened") {
|
||||
return;
|
||||
}
|
||||
const runtimeRequestId = opened.value.requestId;
|
||||
assert.equal(typeof runtimeRequestId, "string");
|
||||
if (runtimeRequestId === undefined) {
|
||||
return;
|
||||
}
|
||||
|
||||
yield* adapter.respondToRequest(
|
||||
session.threadId,
|
||||
ApprovalRequestId.makeUnsafe(runtimeRequestId),
|
||||
"acceptForSession",
|
||||
);
|
||||
|
||||
const resolved = yield* Stream.runHead(adapter.streamEvents);
|
||||
assert.equal(resolved._tag, "Some");
|
||||
if (resolved._tag !== "Some") {
|
||||
return;
|
||||
}
|
||||
assert.equal(resolved.value.type, "request.resolved");
|
||||
if (resolved.value.type !== "request.resolved") {
|
||||
return;
|
||||
}
|
||||
assert.equal(resolved.value.payload.decision, "acceptForSession");
|
||||
assert.equal(fake.lastPermissionSelection, "allow-always");
|
||||
}).pipe(Effect.provide(layer));
|
||||
});
|
||||
|
||||
it.effect("auto-approves cursor permission requests when approval policy is never", () => {
|
||||
const fake = new FakeCursorAcpProcess();
|
||||
const layer = makeCursorAdapterLive({
|
||||
createProcess: () => fake as never,
|
||||
});
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const adapter = yield* CursorAdapter;
|
||||
|
||||
yield* adapter.startSession({
|
||||
provider: "cursor",
|
||||
threadId: THREAD_ID,
|
||||
runtimeMode: "full-access",
|
||||
});
|
||||
|
||||
// consume startup events
|
||||
yield* Stream.take(adapter.streamEvents, 6).pipe(Stream.runDrain);
|
||||
|
||||
fake.emitPermissionRequest();
|
||||
|
||||
const resolved = yield* Stream.runHead(adapter.streamEvents);
|
||||
assert.equal(resolved._tag, "Some");
|
||||
if (resolved._tag !== "Some") {
|
||||
return;
|
||||
}
|
||||
|
||||
assert.equal(resolved.value.type, "request.resolved");
|
||||
if (resolved.value.type !== "request.resolved") {
|
||||
return;
|
||||
}
|
||||
|
||||
assert.equal(resolved.value.payload.decision, "acceptForSession");
|
||||
assert.equal(fake.lastPermissionSelection, "allow-always");
|
||||
}).pipe(Effect.provide(layer));
|
||||
});
|
||||
|
||||
it.effect("rejects empty prompt input before starting a turn", () => {
|
||||
const fake = new FakeCursorAcpProcess();
|
||||
const layer = makeCursorAdapterLive({
|
||||
createProcess: () => fake as never,
|
||||
});
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const adapter = yield* CursorAdapter;
|
||||
const session = yield* adapter.startSession({
|
||||
provider: "cursor",
|
||||
threadId: THREAD_ID,
|
||||
runtimeMode: "full-access",
|
||||
});
|
||||
|
||||
yield* Stream.take(adapter.streamEvents, 6).pipe(Stream.runDrain);
|
||||
|
||||
const result = yield* adapter
|
||||
.sendTurn({
|
||||
threadId: session.threadId,
|
||||
input: " ",
|
||||
attachments: [],
|
||||
})
|
||||
.pipe(Effect.result);
|
||||
|
||||
assert.equal(result._tag, "Failure");
|
||||
if (result._tag !== "Failure") {
|
||||
return;
|
||||
}
|
||||
assert.deepEqual(
|
||||
result.failure,
|
||||
new ProviderAdapterValidationError({
|
||||
provider: "cursor",
|
||||
operation: "sendTurn",
|
||||
issue: "Turn input must be non-empty.",
|
||||
}),
|
||||
);
|
||||
|
||||
assert.equal(fake.requests.some((request) => request.method === "session/prompt"), false);
|
||||
}).pipe(Effect.provide(layer));
|
||||
});
|
||||
|
||||
it.effect("keeps tool_call item types consistent through tool_call_update", () => {
|
||||
const fake = new FakeCursorAcpProcess();
|
||||
const layer = makeCursorAdapterLive({
|
||||
createProcess: () => fake as never,
|
||||
});
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const adapter = yield* CursorAdapter;
|
||||
|
||||
const eventsFiber = yield* Stream.take(adapter.streamEvents, 13).pipe(
|
||||
Stream.runCollect,
|
||||
Effect.forkChild,
|
||||
);
|
||||
|
||||
const session = yield* adapter.startSession({
|
||||
provider: "cursor",
|
||||
threadId: THREAD_ID,
|
||||
runtimeMode: "full-access",
|
||||
});
|
||||
|
||||
yield* adapter.sendTurn({
|
||||
threadId: session.threadId,
|
||||
input: "hello",
|
||||
attachments: [],
|
||||
});
|
||||
|
||||
const events = Array.from(yield* Fiber.join(eventsFiber));
|
||||
const started = events.find(
|
||||
(event) => event.type === "item.started" && String(event.itemId) === "tool-1",
|
||||
);
|
||||
const completed = events.find(
|
||||
(event) => event.type === "item.completed" && String(event.itemId) === "tool-1",
|
||||
);
|
||||
|
||||
assert.equal(started?.type, "item.started");
|
||||
assert.equal(completed?.type, "item.completed");
|
||||
if (started?.type !== "item.started" || completed?.type !== "item.completed") {
|
||||
return;
|
||||
}
|
||||
|
||||
assert.equal(started.payload.itemType, "command_execution");
|
||||
assert.equal(completed.payload.itemType, "command_execution");
|
||||
}).pipe(Effect.provide(layer));
|
||||
});
|
||||
});
|
||||
File diff suppressed because it is too large.
Load diff
@@ -5,7 +5,6 @@ import { assertFailure } from "@effect/vitest/utils";
|
||||
import { Effect, Layer, Stream } from "effect";
|
||||
|
||||
import { CodexAdapter, CodexAdapterShape } from "../Services/CodexAdapter.ts";
|
||||
import { CursorAdapter, CursorAdapterShape } from "../Services/CursorAdapter.ts";
|
||||
import { ProviderAdapterRegistry } from "../Services/ProviderAdapterRegistry.ts";
|
||||
import { ProviderAdapterRegistryLive } from "./ProviderAdapterRegistry.ts";
|
||||
import { ProviderUnsupportedError } from "../Errors.ts";
|
||||
@@ -13,12 +12,10 @@ import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
|
||||
const fakeCodexAdapter: CodexAdapterShape = {
|
||||
provider: "codex",
|
||||
capabilities: { sessionModelSwitch: "in-session" },
|
||||
startSession: vi.fn(),
|
||||
sendTurn: vi.fn(),
|
||||
interruptTurn: vi.fn(),
|
||||
respondToRequest: vi.fn(),
|
||||
respondToUserInput: vi.fn(),
|
||||
stopSession: vi.fn(),
|
||||
listSessions: vi.fn(),
|
||||
hasSession: vi.fn(),
|
||||
@@ -28,31 +25,9 @@ const fakeCodexAdapter: CodexAdapterShape = {
|
||||
streamEvents: Stream.empty,
|
||||
};
|
||||
|
||||
const fakeCursorAdapter: CursorAdapterShape = {
|
||||
provider: "cursor",
|
||||
capabilities: { sessionModelSwitch: "unsupported" },
|
||||
startSession: vi.fn(),
|
||||
sendTurn: vi.fn(),
|
||||
interruptTurn: vi.fn(),
|
||||
respondToRequest: vi.fn(),
|
||||
respondToUserInput: vi.fn(),
|
||||
stopSession: vi.fn(),
|
||||
listSessions: vi.fn(),
|
||||
hasSession: vi.fn(),
|
||||
readThread: vi.fn(),
|
||||
rollbackThread: vi.fn(),
|
||||
stopAll: vi.fn(),
|
||||
streamEvents: Stream.empty,
|
||||
};
|
||||
const layer = it.layer(
|
||||
Layer.mergeAll(
|
||||
Layer.provide(
|
||||
ProviderAdapterRegistryLive,
|
||||
Layer.mergeAll(
|
||||
Layer.succeed(CodexAdapter, fakeCodexAdapter),
|
||||
Layer.succeed(CursorAdapter, fakeCursorAdapter),
|
||||
),
|
||||
),
|
||||
Layer.provide(ProviderAdapterRegistryLive, Layer.succeed(CodexAdapter, fakeCodexAdapter)),
|
||||
NodeServices.layer,
|
||||
),
|
||||
);
|
||||
@@ -61,13 +36,11 @@ layer("ProviderAdapterRegistryLive", (it) => {
|
||||
it.effect("resolves a registered provider adapter", () =>
|
||||
Effect.gen(function* () {
|
||||
const registry = yield* ProviderAdapterRegistry;
|
||||
const codex = yield* registry.getByProvider("codex");
|
||||
const cursor = yield* registry.getByProvider("cursor");
|
||||
assert.equal(codex, fakeCodexAdapter);
|
||||
assert.equal(cursor, fakeCursorAdapter);
|
||||
const adapter = yield* registry.getByProvider("codex");
|
||||
assert.equal(adapter, fakeCodexAdapter);
|
||||
|
||||
const providers = yield* registry.listProviders();
|
||||
assert.deepEqual(providers, ["codex", "cursor"]);
|
||||
assert.deepEqual(providers, ["codex"]);
|
||||
}),
|
||||
);
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
/**
|
||||
* ProviderAdapterRegistryLive - In-memory provider adapter lookup layer.
|
||||
*
|
||||
* Binds provider kinds (codex/cursor/...) to concrete adapter services.
|
||||
* Binds provider kinds (codex/claudeCode/...) to concrete adapter services.
|
||||
* This layer only performs adapter lookup; it does not route session-scoped
|
||||
* calls or own provider lifecycle workflows.
|
||||
*
|
||||
@@ -16,7 +16,6 @@ import {
|
||||
type ProviderAdapterRegistryShape,
|
||||
} from "../Services/ProviderAdapterRegistry.ts";
|
||||
import { CodexAdapter } from "../Services/CodexAdapter.ts";
|
||||
import { CursorAdapter } from "../Services/CursorAdapter.ts";
|
||||
|
||||
export interface ProviderAdapterRegistryLiveOptions {
|
||||
readonly adapters?: ReadonlyArray<ProviderAdapterShape<ProviderAdapterError>>;
|
||||
@@ -24,10 +23,7 @@ export interface ProviderAdapterRegistryLiveOptions {
|
||||
|
||||
const makeProviderAdapterRegistry = (options?: ProviderAdapterRegistryLiveOptions) =>
|
||||
Effect.gen(function* () {
|
||||
const adapters =
|
||||
options?.adapters !== undefined
|
||||
? options.adapters
|
||||
: [yield* CodexAdapter, yield* CursorAdapter];
|
||||
const adapters = options?.adapters !== undefined ? options.adapters : [yield* CodexAdapter];
|
||||
const byProvider = new Map(adapters.map((adapter) => [adapter.provider, adapter]));
|
||||
|
||||
const getByProvider: ProviderAdapterRegistryShape["getByProvider"] = (provider) => {
|
||||
|
||||
@@ -1,93 +1,68 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { it } from "@effect/vitest";
|
||||
import { Effect, Layer, Sink, Stream } from "effect";
|
||||
import * as PlatformError from "effect/PlatformError";
|
||||
import { ChildProcessSpawner } from "effect/unstable/process";
|
||||
import { Effect } from "effect";
|
||||
|
||||
import { checkCodexProviderStatus, parseAuthStatusFromOutput } from "./ProviderHealth";
|
||||
|
||||
// ── Test helpers ────────────────────────────────────────────────────
|
||||
|
||||
const encoder = new TextEncoder();
|
||||
|
||||
function mockHandle(result: { stdout: string; stderr: string; code: number }) {
|
||||
return ChildProcessSpawner.makeHandle({
|
||||
pid: ChildProcessSpawner.ProcessId(1),
|
||||
exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(result.code)),
|
||||
isRunning: Effect.succeed(false),
|
||||
kill: () => Effect.void,
|
||||
stdin: Sink.drain,
|
||||
stdout: Stream.make(encoder.encode(result.stdout)),
|
||||
stderr: Stream.make(encoder.encode(result.stderr)),
|
||||
all: Stream.empty,
|
||||
getInputFd: () => Sink.drain,
|
||||
getOutputFd: () => Stream.empty,
|
||||
});
|
||||
}
|
||||
|
||||
function mockSpawnerLayer(
|
||||
handler: (args: ReadonlyArray<string>) => { stdout: string; stderr: string; code: number },
|
||||
function mockRunner(
|
||||
handler: (args: ReadonlyArray<string>) => {
|
||||
stdout: string;
|
||||
stderr: string;
|
||||
code: number | null;
|
||||
timedOut?: boolean;
|
||||
},
|
||||
) {
|
||||
return Layer.succeed(
|
||||
ChildProcessSpawner.ChildProcessSpawner,
|
||||
ChildProcessSpawner.make((command) => {
|
||||
const cmd = command as unknown as { args: ReadonlyArray<string> };
|
||||
return Effect.succeed(mockHandle(handler(cmd.args)));
|
||||
}),
|
||||
);
|
||||
return (args: ReadonlyArray<string>) => Promise.resolve(handler(args));
|
||||
}
|
||||
|
||||
function failingSpawnerLayer(description: string) {
|
||||
return Layer.succeed(
|
||||
ChildProcessSpawner.ChildProcessSpawner,
|
||||
ChildProcessSpawner.make(() =>
|
||||
Effect.fail(
|
||||
PlatformError.systemError({
|
||||
_tag: "NotFound",
|
||||
module: "ChildProcess",
|
||||
method: "spawn",
|
||||
description,
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
function failingRunner(description: string) {
|
||||
return () => Promise.reject(new Error(description));
|
||||
}
|
||||
|
||||
// ── Tests ───────────────────────────────────────────────────────────
|
||||
|
||||
it.effect("returns ready when codex is installed and authenticated", () =>
|
||||
Effect.gen(function* () {
|
||||
const status = yield* checkCodexProviderStatus;
|
||||
assert.strictEqual(status.provider, "codex");
|
||||
assert.strictEqual(status.status, "ready");
|
||||
assert.strictEqual(status.available, true);
|
||||
assert.strictEqual(status.authStatus, "authenticated");
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
mockSpawnerLayer((args) => {
|
||||
const status = yield* checkCodexProviderStatus(
|
||||
mockRunner((args) => {
|
||||
const joined = args.join(" ");
|
||||
if (joined === "--version") return { stdout: "codex 1.0.0\n", stderr: "", code: 0 };
|
||||
if (joined === "login status") return { stdout: "Logged in\n", stderr: "", code: 0 };
|
||||
throw new Error(`Unexpected args: ${joined}`);
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
assert.strictEqual(status.provider, "codex");
|
||||
assert.strictEqual(status.status, "ready");
|
||||
assert.strictEqual(status.available, true);
|
||||
assert.strictEqual(status.authStatus, "authenticated");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("returns unavailable when codex is missing", () =>
|
||||
Effect.gen(function* () {
|
||||
const status = yield* checkCodexProviderStatus;
|
||||
const status = yield* checkCodexProviderStatus(failingRunner("spawn codex ENOENT"));
|
||||
assert.strictEqual(status.provider, "codex");
|
||||
assert.strictEqual(status.status, "error");
|
||||
assert.strictEqual(status.available, false);
|
||||
assert.strictEqual(status.authStatus, "unknown");
|
||||
assert.strictEqual(status.message, "Codex CLI (`codex`) is not installed or not on PATH.");
|
||||
}).pipe(Effect.provide(failingSpawnerLayer("spawn codex ENOENT"))),
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("returns unauthenticated when auth probe reports login required", () =>
|
||||
Effect.gen(function* () {
|
||||
const status = yield* checkCodexProviderStatus;
|
||||
const status = yield* checkCodexProviderStatus(
|
||||
mockRunner((args) => {
|
||||
const joined = args.join(" ");
|
||||
if (joined === "--version") return { stdout: "codex 1.0.0\n", stderr: "", code: 0 };
|
||||
if (joined === "login status") {
|
||||
return { stdout: "", stderr: "Not logged in. Run codex login.", code: 1 };
|
||||
}
|
||||
throw new Error(`Unexpected args: ${joined}`);
|
||||
}),
|
||||
);
|
||||
assert.strictEqual(status.provider, "codex");
|
||||
assert.strictEqual(status.status, "error");
|
||||
assert.strictEqual(status.available, true);
|
||||
@@ -96,25 +71,22 @@ it.effect("returns unauthenticated when auth probe reports login required", () =
|
||||
status.message,
|
||||
"Codex CLI is not authenticated. Run `codex login` and try again.",
|
||||
);
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
mockSpawnerLayer((args) => {
|
||||
const joined = args.join(" ");
|
||||
if (joined === "--version") return { stdout: "codex 1.0.0\n", stderr: "", code: 0 };
|
||||
if (joined === "login status") {
|
||||
return { stdout: "", stderr: "Not logged in. Run codex login.", code: 1 };
|
||||
}
|
||||
throw new Error(`Unexpected args: ${joined}`);
|
||||
}),
|
||||
),
|
||||
),
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect(
|
||||
"returns unauthenticated when login status output includes 'not logged in'",
|
||||
"returns unauthenticated when login status output includes 'not logged in'",
|
||||
() =>
|
||||
Effect.gen(function* () {
|
||||
const status = yield* checkCodexProviderStatus;
|
||||
const status = yield* checkCodexProviderStatus(
|
||||
mockRunner((args) => {
|
||||
const joined = args.join(" ");
|
||||
if (joined === "--version") return { stdout: "codex 1.0.0\n", stderr: "", code: 0 };
|
||||
if (joined === "login status")
|
||||
return { stdout: "Not logged in\n", stderr: "", code: 1 };
|
||||
throw new Error(`Unexpected args: ${joined}`);
|
||||
}),
|
||||
);
|
||||
assert.strictEqual(status.provider, "codex");
|
||||
assert.strictEqual(status.status, "error");
|
||||
assert.strictEqual(status.available, true);
|
||||
@@ -123,22 +95,21 @@ it.effect(
|
||||
status.message,
|
||||
"Codex CLI is not authenticated. Run `codex login` and try again.",
|
||||
);
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
mockSpawnerLayer((args) => {
|
||||
const joined = args.join(" ");
|
||||
if (joined === "--version") return { stdout: "codex 1.0.0\n", stderr: "", code: 0 };
|
||||
if (joined === "login status")
|
||||
return { stdout: "Not logged in\n", stderr: "", code: 1 };
|
||||
throw new Error(`Unexpected args: ${joined}`);
|
||||
}),
|
||||
),
|
||||
),
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("returns warning when login status command is unsupported", () =>
|
||||
Effect.gen(function* () {
|
||||
const status = yield* checkCodexProviderStatus;
|
||||
const status = yield* checkCodexProviderStatus(
|
||||
mockRunner((args) => {
|
||||
const joined = args.join(" ");
|
||||
if (joined === "--version") return { stdout: "codex 1.0.0\n", stderr: "", code: 0 };
|
||||
if (joined === "login status") {
|
||||
return { stdout: "", stderr: "error: unknown command 'login'", code: 2 };
|
||||
}
|
||||
throw new Error(`Unexpected args: ${joined}`);
|
||||
}),
|
||||
);
|
||||
assert.strictEqual(status.provider, "codex");
|
||||
assert.strictEqual(status.status, "warning");
|
||||
assert.strictEqual(status.available, true);
|
||||
@@ -147,20 +118,35 @@ it.effect("returns warning when login status command is unsupported", () =>
|
||||
status.message,
|
||||
"Codex CLI authentication status command is unavailable in this Codex version.",
|
||||
);
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
mockSpawnerLayer((args) => {
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("returns unavailable when codex version probe times out", () =>
|
||||
Effect.gen(function* () {
|
||||
const status = yield* checkCodexProviderStatus(
|
||||
mockRunner((args) => {
|
||||
const joined = args.join(" ");
|
||||
if (joined === "--version") return { stdout: "codex 1.0.0\n", stderr: "", code: 0 };
|
||||
if (joined === "login status") {
|
||||
return { stdout: "", stderr: "error: unknown command 'login'", code: 2 };
|
||||
if (joined === "--version") {
|
||||
return { stdout: "", stderr: "", code: null, timedOut: true };
|
||||
}
|
||||
throw new Error(`Unexpected args: ${joined}`);
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
assert.strictEqual(status.provider, "codex");
|
||||
assert.strictEqual(status.status, "error");
|
||||
assert.strictEqual(status.available, false);
|
||||
assert.strictEqual(status.authStatus, "unknown");
|
||||
assert.strictEqual(status.message, "Codex CLI is installed but failed to run. Timed out while running command.");
|
||||
}),
|
||||
);
|
||||
|
||||
it("parseAuthStatusFromOutput: timed out auth check is warning", () => {
|
||||
const parsed = parseAuthStatusFromOutput({ stdout: "", stderr: "", code: null, timedOut: true });
|
||||
assert.strictEqual(parsed.status, "warning");
|
||||
assert.strictEqual(parsed.authStatus, "unknown");
|
||||
assert.strictEqual(parsed.message, "Timed out while checking Codex authentication status.");
|
||||
});
|
||||
|
||||
// ── Pure function tests ─────────────────────────────────────────────
|
||||
|
||||
it("parseAuthStatusFromOutput: exit code 0 with no auth markers is ready", () => {
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
* Performs one-time provider readiness probes when the server starts and
|
||||
* keeps the resulting snapshot in memory for `server.getConfig`.
|
||||
*
|
||||
* Uses effect's ChildProcessSpawner to run CLI probes natively.
|
||||
* Uses the shared process runner to run CLI probes natively.
|
||||
*
|
||||
* @module ProviderHealthLive
|
||||
*/
|
||||
@@ -13,20 +13,43 @@ import type {
|
||||
ServerProviderStatus,
|
||||
ServerProviderStatusState,
|
||||
} from "@t3tools/contracts";
|
||||
import { Effect, Layer, Option, Result, Stream } from "effect";
|
||||
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
|
||||
import { Data, Effect, Layer, Result } from "effect";
|
||||
|
||||
import { runProcess } from "../../processRunner";
|
||||
import { ProviderHealth, type ProviderHealthShape } from "../Services/ProviderHealth";
|
||||
|
||||
const DEFAULT_TIMEOUT_MS = 4_000;
|
||||
const CODEX_PROVIDER = "codex" as const;
|
||||
|
||||
class ProviderHealthCommandError extends Data.TaggedError("ProviderHealthCommandError")<{
|
||||
readonly message: string;
|
||||
readonly cause?: unknown;
|
||||
}> {}
|
||||
|
||||
// ── Pure helpers ────────────────────────────────────────────────────
|
||||
|
||||
export interface CommandResult {
|
||||
readonly stdout: string;
|
||||
readonly stderr: string;
|
||||
readonly code: number;
|
||||
readonly code: number | null;
|
||||
readonly timedOut?: boolean;
|
||||
}
|
||||
|
||||
function errorMessage(error: unknown): string {
|
||||
if (error instanceof Error) {
|
||||
return error.message;
|
||||
}
|
||||
|
||||
if (
|
||||
error &&
|
||||
typeof error === "object" &&
|
||||
"message" in error &&
|
||||
typeof (error as { message?: unknown }).message === "string"
|
||||
) {
|
||||
return (error as { message: string }).message;
|
||||
}
|
||||
|
||||
return String(error);
|
||||
}
|
||||
|
||||
function nonEmptyTrimmed(value: string | undefined): string | undefined {
|
||||
@@ -36,8 +59,7 @@ function nonEmptyTrimmed(value: string | undefined): string | undefined {
|
||||
}
|
||||
|
||||
function isCommandMissingCause(error: unknown): boolean {
|
||||
if (!(error instanceof Error)) return false;
|
||||
const lower = error.message.toLowerCase();
|
||||
const lower = errorMessage(error).toLowerCase();
|
||||
return (
|
||||
lower.includes("command not found: codex") ||
|
||||
lower.includes("spawn codex enoent") ||
|
||||
@@ -54,6 +76,9 @@ function detailFromResult(
|
||||
if (stderr) return stderr;
|
||||
const stdout = nonEmptyTrimmed(result.stdout);
|
||||
if (stdout) return stdout;
|
||||
if (result.code === null) {
|
||||
return "Command was terminated before reporting an exit code.";
|
||||
}
|
||||
if (result.code !== 0) {
|
||||
return `Command exited with code ${result.code}.`;
|
||||
}
|
||||
@@ -87,6 +112,14 @@ export function parseAuthStatusFromOutput(result: CommandResult): {
|
||||
readonly authStatus: ServerProviderAuthStatus;
|
||||
readonly message?: string;
|
||||
} {
|
||||
if (result.timedOut) {
|
||||
return {
|
||||
status: "warning",
|
||||
authStatus: "unknown",
|
||||
message: "Timed out while checking Codex authentication status.",
|
||||
};
|
||||
}
|
||||
|
||||
const lowerOutput = `${result.stdout}\n${result.stderr}`.toLowerCase();
|
||||
|
||||
if (
|
||||
@@ -162,140 +195,115 @@ export function parseAuthStatusFromOutput(result: CommandResult): {
|
||||
};
|
||||
}
|
||||
|
||||
// ── Effect-native command execution ─────────────────────────────────
|
||||
export type RunProviderHealthCommand = (
|
||||
args: ReadonlyArray<string>,
|
||||
) => Promise<CommandResult>;
|
||||
|
||||
const collectStreamAsString = <E>(stream: Stream.Stream<Uint8Array, E>): Effect.Effect<string, E> =>
|
||||
Stream.runFold(
|
||||
stream,
|
||||
() => "",
|
||||
(acc, chunk) => acc + new TextDecoder().decode(chunk),
|
||||
);
|
||||
const defaultRunCodexCommand: RunProviderHealthCommand = async (args) => {
|
||||
const result = await runProcess("codex", [...args], {
|
||||
allowNonZeroExit: true,
|
||||
timeoutMs: DEFAULT_TIMEOUT_MS,
|
||||
maxBufferBytes: 262_144,
|
||||
outputMode: "truncate",
|
||||
});
|
||||
|
||||
const runCodexCommand = (args: ReadonlyArray<string>) =>
|
||||
Effect.gen(function* () {
|
||||
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||
const command = ChildProcess.make("codex", [...args], {
|
||||
shell: process.platform === "win32",
|
||||
});
|
||||
|
||||
const child = yield* spawner.spawn(command);
|
||||
|
||||
const [stdout, stderr, exitCode] = yield* Effect.all(
|
||||
[
|
||||
collectStreamAsString(child.stdout),
|
||||
collectStreamAsString(child.stderr),
|
||||
child.exitCode.pipe(Effect.map(Number)),
|
||||
],
|
||||
{ concurrency: "unbounded" },
|
||||
);
|
||||
|
||||
return { stdout, stderr, code: exitCode } satisfies CommandResult;
|
||||
}).pipe(Effect.scoped);
|
||||
return {
|
||||
stdout: result.stdout,
|
||||
stderr: result.stderr,
|
||||
code: result.code,
|
||||
timedOut: result.timedOut,
|
||||
} satisfies CommandResult;
|
||||
};
|
||||
|
||||
// ── Health check ────────────────────────────────────────────────────
|
||||
|
||||
export const checkCodexProviderStatus: Effect.Effect<
|
||||
ServerProviderStatus,
|
||||
never,
|
||||
ChildProcessSpawner.ChildProcessSpawner
|
||||
> = Effect.gen(function* () {
|
||||
const checkedAt = new Date().toISOString();
|
||||
export const checkCodexProviderStatus = (
|
||||
runCodexCommand: RunProviderHealthCommand = defaultRunCodexCommand,
|
||||
): Effect.Effect<ServerProviderStatus> =>
|
||||
Effect.gen(function* () {
|
||||
const checkedAt = new Date().toISOString();
|
||||
|
||||
// Probe 1: `codex --version` — is the CLI reachable?
|
||||
const versionProbe = yield* runCodexCommand(["--version"]).pipe(
|
||||
Effect.timeoutOption(DEFAULT_TIMEOUT_MS),
|
||||
Effect.result,
|
||||
);
|
||||
// Probe 1: `codex --version` — is the CLI reachable?
|
||||
const versionProbe = yield* Effect.tryPromise({
|
||||
try: () => runCodexCommand(["--version"]),
|
||||
catch: (error) =>
|
||||
new ProviderHealthCommandError({
|
||||
message: errorMessage(error),
|
||||
...(error !== undefined ? { cause: error } : {}),
|
||||
}),
|
||||
}).pipe(Effect.result);
|
||||
|
||||
if (Result.isFailure(versionProbe)) {
|
||||
const error = versionProbe.failure;
|
||||
if (Result.isFailure(versionProbe)) {
|
||||
const error = versionProbe.failure;
|
||||
return {
|
||||
provider: CODEX_PROVIDER,
|
||||
status: "error" as const,
|
||||
available: false,
|
||||
authStatus: "unknown" as const,
|
||||
checkedAt,
|
||||
message: isCommandMissingCause(error)
|
||||
? "Codex CLI (`codex`) is not installed or not on PATH."
|
||||
: `Failed to execute Codex CLI health check: ${errorMessage(error)}.`,
|
||||
};
|
||||
}
|
||||
|
||||
const version = versionProbe.success;
|
||||
if (version.timedOut || version.code !== 0) {
|
||||
const detail = detailFromResult(version);
|
||||
return {
|
||||
provider: CODEX_PROVIDER,
|
||||
status: "error" as const,
|
||||
available: false,
|
||||
authStatus: "unknown" as const,
|
||||
checkedAt,
|
||||
message: detail
|
||||
? `Codex CLI is installed but failed to run. ${detail}`
|
||||
: "Codex CLI is installed but failed to run.",
|
||||
};
|
||||
}
|
||||
|
||||
// Probe 2: `codex login status` — is the user authenticated?
|
||||
const authProbe = yield* Effect.tryPromise({
|
||||
try: () => runCodexCommand(["login", "status"]),
|
||||
catch: (error) =>
|
||||
new ProviderHealthCommandError({
|
||||
message: errorMessage(error),
|
||||
...(error !== undefined ? { cause: error } : {}),
|
||||
}),
|
||||
}).pipe(Effect.result);
|
||||
|
||||
if (Result.isFailure(authProbe)) {
|
||||
const error = authProbe.failure;
|
||||
return {
|
||||
provider: CODEX_PROVIDER,
|
||||
status: "warning" as const,
|
||||
available: true,
|
||||
authStatus: "unknown" as const,
|
||||
checkedAt,
|
||||
message:
|
||||
errorMessage(error).length > 0
|
||||
? `Could not verify Codex authentication status: ${errorMessage(error)}.`
|
||||
: "Could not verify Codex authentication status.",
|
||||
};
|
||||
}
|
||||
|
||||
const parsed = parseAuthStatusFromOutput(authProbe.success);
|
||||
return {
|
||||
provider: CODEX_PROVIDER,
|
||||
status: "error" as const,
|
||||
available: false,
|
||||
authStatus: "unknown" as const,
|
||||
checkedAt,
|
||||
message: isCommandMissingCause(error)
|
||||
? "Codex CLI (`codex`) is not installed or not on PATH."
|
||||
: `Failed to execute Codex CLI health check: ${error instanceof Error ? error.message : String(error)}.`,
|
||||
};
|
||||
}
|
||||
|
||||
if (Option.isNone(versionProbe.success)) {
|
||||
return {
|
||||
provider: CODEX_PROVIDER,
|
||||
status: "error" as const,
|
||||
available: false,
|
||||
authStatus: "unknown" as const,
|
||||
checkedAt,
|
||||
message: "Codex CLI is installed but failed to run. Timed out while running command.",
|
||||
};
|
||||
}
|
||||
|
||||
const version = versionProbe.success.value;
|
||||
if (version.code !== 0) {
|
||||
const detail = detailFromResult(version);
|
||||
return {
|
||||
provider: CODEX_PROVIDER,
|
||||
status: "error" as const,
|
||||
available: false,
|
||||
authStatus: "unknown" as const,
|
||||
checkedAt,
|
||||
message: detail
|
||||
? `Codex CLI is installed but failed to run. ${detail}`
|
||||
: "Codex CLI is installed but failed to run.",
|
||||
};
|
||||
}
|
||||
|
||||
// Probe 2: `codex login status` — is the user authenticated?
|
||||
const authProbe = yield* runCodexCommand(["login", "status"]).pipe(
|
||||
Effect.timeoutOption(DEFAULT_TIMEOUT_MS),
|
||||
Effect.result,
|
||||
);
|
||||
|
||||
if (Result.isFailure(authProbe)) {
|
||||
const error = authProbe.failure;
|
||||
return {
|
||||
provider: CODEX_PROVIDER,
|
||||
status: "warning" as const,
|
||||
status: parsed.status,
|
||||
available: true,
|
||||
authStatus: "unknown" as const,
|
||||
authStatus: parsed.authStatus,
|
||||
checkedAt,
|
||||
message:
|
||||
error instanceof Error
|
||||
? `Could not verify Codex authentication status: ${error.message}.`
|
||||
: "Could not verify Codex authentication status.",
|
||||
};
|
||||
}
|
||||
|
||||
if (Option.isNone(authProbe.success)) {
|
||||
return {
|
||||
provider: CODEX_PROVIDER,
|
||||
status: "warning" as const,
|
||||
available: true,
|
||||
authStatus: "unknown" as const,
|
||||
checkedAt,
|
||||
message: "Could not verify Codex authentication status. Timed out while running command.",
|
||||
};
|
||||
}
|
||||
|
||||
const parsed = parseAuthStatusFromOutput(authProbe.success.value);
|
||||
return {
|
||||
provider: CODEX_PROVIDER,
|
||||
status: parsed.status,
|
||||
available: true,
|
||||
authStatus: parsed.authStatus,
|
||||
checkedAt,
|
||||
...(parsed.message ? { message: parsed.message } : {}),
|
||||
} satisfies ServerProviderStatus;
|
||||
});
|
||||
...(parsed.message ? { message: parsed.message } : {}),
|
||||
} satisfies ServerProviderStatus;
|
||||
});
|
||||
|
||||
// ── Layer ───────────────────────────────────────────────────────────
|
||||
|
||||
export const ProviderHealthLive = Layer.effect(
|
||||
ProviderHealth,
|
||||
Effect.gen(function* () {
|
||||
const codexStatus = yield* checkCodexProviderStatus;
|
||||
const codexStatus = yield* checkCodexProviderStatus();
|
||||
return {
|
||||
getStatuses: Effect.succeed([codexStatus]),
|
||||
} satisfies ProviderHealthShape;
|
||||
|
||||
@@ -12,10 +12,11 @@ import type {
|
||||
import {
|
||||
ApprovalRequestId,
|
||||
EventId,
|
||||
type ProviderKind,
|
||||
ProviderSessionStartInput,
|
||||
ProviderSessionId,
|
||||
ProviderThreadId,
|
||||
ProviderTurnId,
|
||||
ThreadId,
|
||||
TurnId,
|
||||
} from "@t3tools/contracts";
|
||||
import { it, assert, vi } from "@effect/vitest";
|
||||
import { assertFailure } from "@effect/vitest/utils";
|
||||
@@ -25,8 +26,9 @@ import * as SqlClient from "effect/unstable/sql/SqlClient";
|
||||
|
||||
import {
|
||||
ProviderAdapterSessionNotFoundError,
|
||||
ProviderUnsupportedError,
|
||||
ProviderSessionNotFoundError,
|
||||
ProviderValidationError,
|
||||
ProviderUnsupportedError,
|
||||
type ProviderAdapterError,
|
||||
} from "../Errors.ts";
|
||||
import type { ProviderAdapterShape } from "../Services/ProviderAdapter.ts";
|
||||
@@ -43,42 +45,33 @@ import {
|
||||
SqlitePersistenceMemory,
|
||||
} from "../../persistence/Layers/Sqlite.ts";
|
||||
|
||||
const asSessionId = (value: string): ProviderSessionId => ProviderSessionId.makeUnsafe(value);
|
||||
const asTurnId = (value: string): ProviderTurnId => ProviderTurnId.makeUnsafe(value);
|
||||
const asProviderThreadId = (value: string): ProviderThreadId => ProviderThreadId.makeUnsafe(value);
|
||||
const asRequestId = (value: string): ApprovalRequestId => ApprovalRequestId.makeUnsafe(value);
|
||||
const asEventId = (value: string): EventId => EventId.makeUnsafe(value);
|
||||
const asThreadId = (value: string): ThreadId => ThreadId.makeUnsafe(value);
|
||||
const asTurnId = (value: string): TurnId => TurnId.makeUnsafe(value);
|
||||
|
||||
type LegacyProviderRuntimeEvent = {
|
||||
readonly type: string;
|
||||
readonly eventId: EventId;
|
||||
readonly provider: "codex" | "claudeCode" | "cursor";
|
||||
readonly createdAt: string;
|
||||
readonly threadId: ThreadId;
|
||||
readonly turnId?: string | undefined;
|
||||
readonly itemId?: string | undefined;
|
||||
readonly requestId?: string | undefined;
|
||||
readonly payload?: unknown | undefined;
|
||||
readonly [key: string]: unknown;
|
||||
};
|
||||
|
||||
function makeFakeCodexAdapter(provider: ProviderKind = "codex") {
|
||||
const sessions = new Map<ThreadId, ProviderSession>();
|
||||
function makeFakeCodexAdapter() {
|
||||
const sessions = new Map<ProviderSessionId, ProviderSession>();
|
||||
const runtimeEventPubSub = Effect.runSync(PubSub.unbounded<ProviderRuntimeEvent>());
|
||||
let nextSession = 1;
|
||||
|
||||
const startSession = vi.fn((input: ProviderSessionStartInput) =>
|
||||
Effect.sync(() => {
|
||||
const now = new Date().toISOString();
|
||||
const next = nextSession;
|
||||
const session: ProviderSession = {
|
||||
provider,
|
||||
sessionId: ProviderSessionId.makeUnsafe(`sess-${next}`),
|
||||
provider: "codex",
|
||||
status: "ready",
|
||||
runtimeMode: input.runtimeMode,
|
||||
threadId: input.threadId,
|
||||
resumeCursor: input.resumeCursor ?? { opaque: `cursor-${String(input.threadId)}` },
|
||||
threadId: input.resumeThreadId ?? ProviderThreadId.makeUnsafe(`thread-${next}`),
|
||||
cwd: input.cwd ?? process.cwd(),
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
};
|
||||
sessions.set(session.threadId, session);
|
||||
nextSession += 1;
|
||||
sessions.set(session.sessionId, session);
|
||||
return session;
|
||||
}),
|
||||
);
|
||||
@@ -87,47 +80,39 @@ function makeFakeCodexAdapter(provider: ProviderKind = "codex") {
|
||||
(
|
||||
input: ProviderSendTurnInput,
|
||||
): Effect.Effect<ProviderTurnStartResult, ProviderAdapterError> => {
|
||||
if (!sessions.has(input.threadId)) {
|
||||
if (!sessions.has(input.sessionId)) {
|
||||
return Effect.fail(
|
||||
new ProviderAdapterSessionNotFoundError({
|
||||
provider,
|
||||
threadId: input.threadId,
|
||||
provider: "codex",
|
||||
sessionId: input.sessionId,
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
return Effect.succeed({
|
||||
threadId: input.threadId,
|
||||
turnId: TurnId.makeUnsafe(`turn-${String(input.threadId)}`),
|
||||
threadId: ProviderThreadId.makeUnsafe("thread-1"),
|
||||
turnId: ProviderTurnId.makeUnsafe("turn-1"),
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
const interruptTurn = vi.fn(
|
||||
(_threadId: ThreadId, _turnId?: TurnId): Effect.Effect<void, ProviderAdapterError> =>
|
||||
(_sessionId: string, _turnId?: string): Effect.Effect<void, ProviderAdapterError> =>
|
||||
Effect.void,
|
||||
);
|
||||
|
||||
const respondToRequest = vi.fn(
|
||||
(
|
||||
_threadId: ThreadId,
|
||||
_sessionId: string,
|
||||
_requestId: string,
|
||||
_decision: ProviderApprovalDecision,
|
||||
): Effect.Effect<void, ProviderAdapterError> => Effect.void,
|
||||
);
|
||||
|
||||
const respondToUserInput = vi.fn(
|
||||
(
|
||||
_threadId: ThreadId,
|
||||
_requestId: string,
|
||||
_answers: Record<string, unknown>,
|
||||
): Effect.Effect<void, ProviderAdapterError> => Effect.void,
|
||||
);
|
||||
|
||||
const stopSession = vi.fn(
|
||||
(threadId: ThreadId): Effect.Effect<void, ProviderAdapterError> =>
|
||||
(sessionId: string): Effect.Effect<void, ProviderAdapterError> =>
|
||||
Effect.sync(() => {
|
||||
sessions.delete(threadId);
|
||||
sessions.delete(ProviderSessionId.makeUnsafe(sessionId));
|
||||
}),
|
||||
);
|
||||
|
||||
@@ -137,31 +122,32 @@ function makeFakeCodexAdapter(provider: ProviderKind = "codex") {
|
||||
);
|
||||
|
||||
const hasSession = vi.fn(
|
||||
(threadId: ThreadId): Effect.Effect<boolean> => Effect.succeed(sessions.has(threadId)),
|
||||
(sessionId: string): Effect.Effect<boolean> =>
|
||||
Effect.succeed(sessions.has(ProviderSessionId.makeUnsafe(sessionId))),
|
||||
);
|
||||
|
||||
const readThread = vi.fn(
|
||||
(
|
||||
threadId: ThreadId,
|
||||
_sessionId: ProviderSessionId,
|
||||
): Effect.Effect<
|
||||
{
|
||||
threadId: ThreadId;
|
||||
turns: ReadonlyArray<{ id: TurnId; items: readonly [] }>;
|
||||
threadId: ProviderThreadId;
|
||||
turns: ReadonlyArray<{ id: ProviderTurnId; items: readonly [] }>;
|
||||
},
|
||||
ProviderAdapterError
|
||||
> =>
|
||||
Effect.succeed({
|
||||
threadId,
|
||||
threadId: ProviderThreadId.makeUnsafe("thread-1"),
|
||||
turns: [{ id: asTurnId("turn-1"), items: [] }],
|
||||
}),
|
||||
);
|
||||
|
||||
const rollbackThread = vi.fn(
|
||||
(
|
||||
threadId: ThreadId,
|
||||
_sessionId: ProviderSessionId,
|
||||
_numTurns: number,
|
||||
): Effect.Effect<{ threadId: ThreadId; turns: readonly [] }, ProviderAdapterError> =>
|
||||
Effect.succeed({ threadId, turns: [] }),
|
||||
): Effect.Effect<{ threadId: ProviderThreadId; turns: readonly [] }, ProviderAdapterError> =>
|
||||
Effect.succeed({ threadId: ProviderThreadId.makeUnsafe("thread-1"), turns: [] }),
|
||||
);
|
||||
|
||||
const stopAll = vi.fn(
|
||||
@@ -172,15 +158,11 @@ function makeFakeCodexAdapter(provider: ProviderKind = "codex") {
|
||||
);
|
||||
|
||||
const adapter: ProviderAdapterShape<ProviderAdapterError> = {
|
||||
provider,
|
||||
capabilities: {
|
||||
sessionModelSwitch: "in-session",
|
||||
},
|
||||
provider: "codex",
|
||||
startSession,
|
||||
sendTurn,
|
||||
interruptTurn,
|
||||
respondToRequest,
|
||||
respondToUserInput,
|
||||
stopSession,
|
||||
listSessions,
|
||||
hasSession,
|
||||
@@ -190,8 +172,8 @@ function makeFakeCodexAdapter(provider: ProviderKind = "codex") {
|
||||
streamEvents: Stream.fromPubSub(runtimeEventPubSub),
|
||||
};
|
||||
|
||||
const emit = (event: LegacyProviderRuntimeEvent): void => {
|
||||
Effect.runSync(PubSub.publish(runtimeEventPubSub, event as unknown as ProviderRuntimeEvent));
|
||||
const emit = (event: ProviderRuntimeEvent): void => {
|
||||
Effect.runSync(PubSub.publish(runtimeEventPubSub, event));
|
||||
};
|
||||
|
||||
return {
|
||||
@@ -201,7 +183,6 @@ function makeFakeCodexAdapter(provider: ProviderKind = "codex") {
|
||||
sendTurn,
|
||||
interruptTurn,
|
||||
respondToRequest,
|
||||
respondToUserInput,
|
||||
stopSession,
|
||||
listSessions,
|
||||
hasSession,
|
||||
@@ -216,15 +197,12 @@ const sleep = (ms: number) =>
|
||||
|
||||
function makeProviderServiceLayer() {
|
||||
const codex = makeFakeCodexAdapter();
|
||||
const claude = makeFakeCodexAdapter("claudeCode");
|
||||
const registry: typeof ProviderAdapterRegistry.Service = {
|
||||
getByProvider: (provider) =>
|
||||
provider === "codex"
|
||||
? Effect.succeed(codex.adapter)
|
||||
: provider === "claudeCode"
|
||||
? Effect.succeed(claude.adapter)
|
||||
: Effect.fail(new ProviderUnsupportedError({ provider })),
|
||||
listProviders: () => Effect.succeed(["codex", "claudeCode"]),
|
||||
: Effect.fail(new ProviderUnsupportedError({ provider })),
|
||||
listProviders: () => Effect.succeed(["codex"]),
|
||||
};
|
||||
|
||||
const providerAdapterLayer = Layer.succeed(ProviderAdapterRegistry, registry);
|
||||
@@ -247,7 +225,6 @@ function makeProviderServiceLayer() {
|
||||
|
||||
return {
|
||||
codex,
|
||||
claude,
|
||||
layer,
|
||||
};
|
||||
}
|
||||
@@ -276,6 +253,7 @@ it.effect("ProviderServiceLive keeps persisted resumable sessions on startup", (
|
||||
yield* Effect.gen(function* () {
|
||||
const directory = yield* ProviderSessionDirectory;
|
||||
yield* directory.upsert({
|
||||
sessionId: asSessionId("sess-stale"),
|
||||
provider: "codex",
|
||||
threadId: ThreadId.makeUnsafe("thread-stale"),
|
||||
});
|
||||
@@ -292,13 +270,13 @@ it.effect("ProviderServiceLive keeps persisted resumable sessions on startup", (
|
||||
|
||||
const persistedProvider = yield* Effect.gen(function* () {
|
||||
const directory = yield* ProviderSessionDirectory;
|
||||
return yield* directory.getProvider(asThreadId("thread-stale"));
|
||||
return yield* directory.getProvider(asSessionId("sess-stale"));
|
||||
}).pipe(Effect.provide(directoryLayer));
|
||||
assert.equal(persistedProvider, "codex");
|
||||
|
||||
const runtime = yield* Effect.gen(function* () {
|
||||
const repository = yield* ProviderSessionRuntimeRepository;
|
||||
return yield* repository.getByThreadId({ threadId: asThreadId("thread-stale") });
|
||||
return yield* repository.getBySessionId({ providerSessionId: asSessionId("sess-stale") });
|
||||
}).pipe(Effect.provide(runtimeRepositoryLayer));
|
||||
assert.equal(Option.isSome(runtime), true);
|
||||
|
||||
@@ -346,12 +324,9 @@ it.effect(
|
||||
|
||||
const startedSession = yield* Effect.gen(function* () {
|
||||
const provider = yield* ProviderService;
|
||||
const threadId = asThreadId("thread-1");
|
||||
return yield* provider.startSession(threadId, {
|
||||
return yield* provider.startSession(asThreadId("thread-1"), {
|
||||
provider: "codex",
|
||||
cwd: "/tmp/project",
|
||||
runtimeMode: "full-access",
|
||||
threadId,
|
||||
});
|
||||
}).pipe(Effect.provide(firstProviderLayer));
|
||||
|
||||
@@ -362,12 +337,14 @@ it.effect(
|
||||
|
||||
const persistedAfterStopAll = yield* Effect.gen(function* () {
|
||||
const repository = yield* ProviderSessionRuntimeRepository;
|
||||
return yield* repository.getByThreadId({ threadId: startedSession.threadId });
|
||||
return yield* repository.getBySessionId({
|
||||
providerSessionId: startedSession.sessionId,
|
||||
});
|
||||
}).pipe(Effect.provide(runtimeRepositoryLayer));
|
||||
assert.equal(Option.isSome(persistedAfterStopAll), true);
|
||||
if (Option.isSome(persistedAfterStopAll)) {
|
||||
assert.equal(persistedAfterStopAll.value.status, "stopped");
|
||||
assert.deepEqual(persistedAfterStopAll.value.resumeCursor, startedSession.resumeCursor);
|
||||
assert.equal(persistedAfterStopAll.value.resumeCursor, null);
|
||||
}
|
||||
|
||||
const secondCodex = makeFakeCodexAdapter();
|
||||
@@ -392,26 +369,20 @@ it.effect(
|
||||
yield* Effect.gen(function* () {
|
||||
const provider = yield* ProviderService;
|
||||
yield* provider.rollbackConversation({
|
||||
threadId: startedSession.threadId,
|
||||
sessionId: startedSession.sessionId,
|
||||
numTurns: 1,
|
||||
});
|
||||
}).pipe(Effect.provide(secondProviderLayer));
|
||||
|
||||
assert.equal(secondCodex.startSession.mock.calls.length, 1);
|
||||
const resumedStartInput = secondCodex.startSession.mock.calls[0]?.[0];
|
||||
assert.equal(typeof resumedStartInput === "object" && resumedStartInput !== null, true);
|
||||
if (resumedStartInput && typeof resumedStartInput === "object") {
|
||||
const startPayload = resumedStartInput as {
|
||||
provider?: string;
|
||||
cwd?: string;
|
||||
resumeCursor?: unknown;
|
||||
threadId?: string;
|
||||
};
|
||||
assert.equal(startPayload.provider, "codex");
|
||||
assert.equal(startPayload.cwd, "/tmp/project");
|
||||
assert.deepEqual(startPayload.resumeCursor, startedSession.resumeCursor);
|
||||
assert.equal(startPayload.threadId, startedSession.threadId);
|
||||
}
|
||||
assert.deepEqual(secondCodex.startSession.mock.calls, [
|
||||
[
|
||||
{
|
||||
provider: "codex",
|
||||
cwd: "/tmp/project",
|
||||
resumeThreadId: startedSession.threadId,
|
||||
},
|
||||
],
|
||||
]);
|
||||
assert.equal(secondCodex.rollbackThread.mock.calls.length, 1);
|
||||
const rollbackCall = secondCodex.rollbackThread.mock.calls[0];
|
||||
assert.equal(typeof rollbackCall?.[0], "string");
|
||||
@@ -428,9 +399,7 @@ routing.layer("ProviderServiceLive routing", (it) => {
|
||||
|
||||
const session = yield* provider.startSession(asThreadId("thread-1"), {
|
||||
provider: "codex",
|
||||
threadId: asThreadId("thread-1"),
|
||||
cwd: "/tmp/project",
|
||||
runtimeMode: "full-access",
|
||||
});
|
||||
assert.equal(session.provider, "codex");
|
||||
|
||||
@@ -438,121 +407,70 @@ routing.layer("ProviderServiceLive routing", (it) => {
|
||||
assert.equal(sessions.length, 1);
|
||||
|
||||
yield* provider.sendTurn({
|
||||
threadId: session.threadId,
|
||||
sessionId: session.sessionId,
|
||||
input: "hello",
|
||||
attachments: [],
|
||||
});
|
||||
assert.equal(routing.codex.sendTurn.mock.calls.length, 1);
|
||||
|
||||
yield* provider.interruptTurn({ threadId: session.threadId });
|
||||
assert.deepEqual(routing.codex.interruptTurn.mock.calls, [[session.threadId, undefined]]);
|
||||
yield* provider.interruptTurn({ sessionId: session.sessionId });
|
||||
assert.deepEqual(routing.codex.interruptTurn.mock.calls, [[session.sessionId, undefined]]);
|
||||
|
||||
yield* provider.respondToRequest({
|
||||
threadId: session.threadId,
|
||||
sessionId: session.sessionId,
|
||||
requestId: asRequestId("req-1"),
|
||||
decision: "accept",
|
||||
});
|
||||
assert.deepEqual(routing.codex.respondToRequest.mock.calls, [
|
||||
[session.threadId, asRequestId("req-1"), "accept"],
|
||||
]);
|
||||
|
||||
yield* provider.respondToUserInput({
|
||||
threadId: session.threadId,
|
||||
requestId: asRequestId("req-user-input-1"),
|
||||
answers: {
|
||||
sandbox_mode: "workspace-write",
|
||||
},
|
||||
});
|
||||
assert.deepEqual(routing.codex.respondToUserInput.mock.calls, [
|
||||
[
|
||||
session.threadId,
|
||||
asRequestId("req-user-input-1"),
|
||||
{
|
||||
sandbox_mode: "workspace-write",
|
||||
},
|
||||
],
|
||||
[session.sessionId, asRequestId("req-1"), "accept"],
|
||||
]);
|
||||
|
||||
yield* provider.rollbackConversation({
|
||||
threadId: session.threadId,
|
||||
sessionId: session.sessionId,
|
||||
numTurns: 0,
|
||||
});
|
||||
|
||||
yield* provider.stopSession({ threadId: session.threadId });
|
||||
yield* provider.stopSession({ sessionId: session.sessionId });
|
||||
const sendAfterStop = yield* Effect.result(
|
||||
provider.sendTurn({
|
||||
threadId: session.threadId,
|
||||
sessionId: session.sessionId,
|
||||
input: "after-stop",
|
||||
attachments: [],
|
||||
}),
|
||||
);
|
||||
assertFailure(
|
||||
sendAfterStop,
|
||||
new ProviderValidationError({
|
||||
operation: "ProviderService.sendTurn",
|
||||
issue: `Cannot route thread '${session.threadId}' because no persisted provider binding exists.`,
|
||||
}),
|
||||
new ProviderSessionNotFoundError({ sessionId: session.sessionId }),
|
||||
);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("routes explicit claudeCode provider session starts to the claude adapter", () =>
|
||||
Effect.gen(function* () {
|
||||
const provider = yield* ProviderService;
|
||||
|
||||
const session = yield* provider.startSession(asThreadId("thread-claude"), {
|
||||
provider: "claudeCode",
|
||||
threadId: asThreadId("thread-claude"),
|
||||
cwd: "/tmp/project-claude",
|
||||
runtimeMode: "full-access",
|
||||
});
|
||||
|
||||
assert.equal(session.provider, "claudeCode");
|
||||
assert.equal(routing.claude.startSession.mock.calls.length, 1);
|
||||
const startInput = routing.claude.startSession.mock.calls[0]?.[0];
|
||||
assert.equal(typeof startInput === "object" && startInput !== null, true);
|
||||
if (startInput && typeof startInput === "object") {
|
||||
const startPayload = startInput as { provider?: string; cwd?: string };
|
||||
assert.equal(startPayload.provider, "claudeCode");
|
||||
assert.equal(startPayload.cwd, "/tmp/project-claude");
|
||||
}
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("recovers stale persisted sessions for rollback by resuming thread identity", () =>
|
||||
Effect.gen(function* () {
|
||||
const provider = yield* ProviderService;
|
||||
|
||||
const initial = yield* provider.startSession(asThreadId("thread-1"), {
|
||||
provider: "codex",
|
||||
threadId: asThreadId("thread-1"),
|
||||
cwd: "/tmp/project",
|
||||
runtimeMode: "full-access",
|
||||
});
|
||||
yield* routing.codex.stopSession(initial.threadId);
|
||||
yield* routing.codex.stopSession(initial.sessionId);
|
||||
routing.codex.startSession.mockClear();
|
||||
routing.codex.rollbackThread.mockClear();
|
||||
|
||||
yield* provider.rollbackConversation({
|
||||
threadId: initial.threadId,
|
||||
sessionId: initial.sessionId,
|
||||
numTurns: 1,
|
||||
});
|
||||
|
||||
assert.equal(routing.codex.startSession.mock.calls.length, 1);
|
||||
const resumedStartInput = routing.codex.startSession.mock.calls[0]?.[0];
|
||||
assert.equal(typeof resumedStartInput === "object" && resumedStartInput !== null, true);
|
||||
if (resumedStartInput && typeof resumedStartInput === "object") {
|
||||
const startPayload = resumedStartInput as {
|
||||
provider?: string;
|
||||
cwd?: string;
|
||||
resumeCursor?: unknown;
|
||||
threadId?: string;
|
||||
};
|
||||
assert.equal(startPayload.provider, "codex");
|
||||
assert.equal(startPayload.cwd, "/tmp/project");
|
||||
assert.deepEqual(startPayload.resumeCursor, initial.resumeCursor);
|
||||
assert.equal(startPayload.threadId, initial.threadId);
|
||||
}
|
||||
assert.deepEqual(routing.codex.startSession.mock.calls, [
|
||||
[
|
||||
{
|
||||
provider: "codex",
|
||||
cwd: "/tmp/project",
|
||||
resumeThreadId: initial.threadId,
|
||||
},
|
||||
],
|
||||
]);
|
||||
assert.equal(routing.codex.rollbackThread.mock.calls.length, 1);
|
||||
const rollbackCall = routing.codex.rollbackThread.mock.calls[0];
|
||||
assert.equal(rollbackCall?.[1], 1);
|
||||
@@ -565,9 +483,7 @@ routing.layer("ProviderServiceLive routing", (it) => {
|
||||
|
||||
const initial = yield* provider.startSession(asThreadId("thread-1"), {
|
||||
provider: "codex",
|
||||
threadId: asThreadId("thread-1"),
|
||||
cwd: "/tmp/project-send-turn",
|
||||
runtimeMode: "full-access",
|
||||
});
|
||||
|
||||
yield* provider.stopAll();
|
||||
@@ -575,26 +491,20 @@ routing.layer("ProviderServiceLive routing", (it) => {
|
||||
routing.codex.sendTurn.mockClear();
|
||||
|
||||
yield* provider.sendTurn({
|
||||
threadId: initial.threadId,
|
||||
sessionId: initial.sessionId,
|
||||
input: "resume",
|
||||
attachments: [],
|
||||
});
|
||||
|
||||
assert.equal(routing.codex.startSession.mock.calls.length, 1);
|
||||
const resumedStartInput = routing.codex.startSession.mock.calls[0]?.[0];
|
||||
assert.equal(typeof resumedStartInput === "object" && resumedStartInput !== null, true);
|
||||
if (resumedStartInput && typeof resumedStartInput === "object") {
|
||||
const startPayload = resumedStartInput as {
|
||||
provider?: string;
|
||||
cwd?: string;
|
||||
resumeCursor?: unknown;
|
||||
threadId?: string;
|
||||
};
|
||||
assert.equal(startPayload.provider, "codex");
|
||||
assert.equal(startPayload.cwd, "/tmp/project-send-turn");
|
||||
assert.deepEqual(startPayload.resumeCursor, initial.resumeCursor);
|
||||
assert.equal(startPayload.threadId, initial.threadId);
|
||||
}
|
||||
assert.deepEqual(routing.codex.startSession.mock.calls, [
|
||||
[
|
||||
{
|
||||
provider: "codex",
|
||||
cwd: "/tmp/project-send-turn",
|
||||
resumeThreadId: initial.threadId,
|
||||
},
|
||||
],
|
||||
]);
|
||||
assert.equal(routing.codex.sendTurn.mock.calls.length, 1);
|
||||
}),
|
||||
);
|
||||
@@ -605,13 +515,9 @@ routing.layer("ProviderServiceLive routing", (it) => {
|
||||
|
||||
yield* provider.startSession(asThreadId("thread-1"), {
|
||||
provider: "codex",
|
||||
threadId: asThreadId("thread-1"),
|
||||
runtimeMode: "full-access",
|
||||
});
|
||||
yield* provider.startSession(asThreadId("thread-2"), {
|
||||
provider: "codex",
|
||||
threadId: asThreadId("thread-2"),
|
||||
runtimeMode: "full-access",
|
||||
});
|
||||
|
||||
yield* provider.stopAll();
|
||||
@@ -628,22 +534,20 @@ routing.layer("ProviderServiceLive routing", (it) => {
|
||||
|
||||
const session = yield* provider.startSession(asThreadId("thread-1"), {
|
||||
provider: "codex",
|
||||
threadId: asThreadId("thread-1"),
|
||||
runtimeMode: "full-access",
|
||||
});
|
||||
yield* provider.sendTurn({
|
||||
threadId: session.threadId,
|
||||
sessionId: session.sessionId,
|
||||
input: "hello",
|
||||
attachments: [],
|
||||
});
|
||||
|
||||
const runningRuntime = yield* runtimeRepository.getByThreadId({
|
||||
threadId: session.threadId,
|
||||
const runningRuntime = yield* runtimeRepository.getBySessionId({
|
||||
providerSessionId: session.sessionId,
|
||||
});
|
||||
assert.equal(Option.isSome(runningRuntime), true);
|
||||
if (Option.isSome(runningRuntime)) {
|
||||
assert.equal(runningRuntime.value.status, "running");
|
||||
assert.deepEqual(runningRuntime.value.resumeCursor, session.resumeCursor);
|
||||
assert.equal(runningRuntime.value.resumeCursor, null);
|
||||
const payload = runningRuntime.value.runtimePayload;
|
||||
assert.equal(payload !== null && typeof payload === "object", true);
|
||||
if (payload !== null && typeof payload === "object" && !Array.isArray(payload)) {
|
||||
@@ -656,15 +560,15 @@ routing.layer("ProviderServiceLive routing", (it) => {
|
||||
};
|
||||
assert.equal(runtimePayload.cwd, process.cwd());
|
||||
assert.equal(runtimePayload.model, null);
|
||||
assert.equal(runtimePayload.activeTurnId, `turn-${String(session.threadId)}`);
|
||||
assert.equal(runtimePayload.activeTurnId, "turn-1");
|
||||
assert.equal(runtimePayload.lastError, null);
|
||||
assert.equal(runtimePayload.lastRuntimeEvent, "provider.sendTurn");
|
||||
}
|
||||
}
|
||||
|
||||
yield* provider.stopAll();
|
||||
const stoppedRuntime = yield* runtimeRepository.getByThreadId({
|
||||
threadId: session.threadId,
|
||||
const stoppedRuntime = yield* runtimeRepository.getBySessionId({
|
||||
providerSessionId: session.sessionId,
|
||||
});
|
||||
assert.equal(Option.isSome(stoppedRuntime), true);
|
||||
if (Option.isSome(stoppedRuntime)) {
|
||||
@@ -681,8 +585,6 @@ fanout.layer("ProviderServiceLive fanout", (it) => {
|
||||
const provider = yield* ProviderService;
|
||||
const session = yield* provider.startSession(asThreadId("thread-1"), {
|
||||
provider: "codex",
|
||||
threadId: asThreadId("thread-1"),
|
||||
runtimeMode: "full-access",
|
||||
});
|
||||
|
||||
const eventsRef = yield* Ref.make<Array<ProviderRuntimeEvent>>([]);
|
||||
@@ -691,12 +593,13 @@ fanout.layer("ProviderServiceLive fanout", (it) => {
|
||||
).pipe(Effect.forkChild);
|
||||
yield* sleep(20);
|
||||
|
||||
const completedEvent: LegacyProviderRuntimeEvent = {
|
||||
const completedEvent: ProviderRuntimeEvent = {
|
||||
type: "turn.completed",
|
||||
eventId: asEventId("evt-1"),
|
||||
provider: "codex",
|
||||
sessionId: session.sessionId,
|
||||
createdAt: new Date().toISOString(),
|
||||
threadId: session.threadId,
|
||||
threadId: asProviderThreadId("thread-1"),
|
||||
turnId: asTurnId("turn-1"),
|
||||
status: "completed",
|
||||
};
|
||||
@@ -714,68 +617,11 @@ fanout.layer("ProviderServiceLive fanout", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("fans out canonical runtime events in emission order", () =>
|
||||
Effect.gen(function* () {
|
||||
const provider = yield* ProviderService;
|
||||
const session = yield* provider.startSession(asThreadId("thread-seq"), {
|
||||
provider: "codex",
|
||||
threadId: asThreadId("thread-seq"),
|
||||
runtimeMode: "full-access",
|
||||
});
|
||||
|
||||
const receivedRef = yield* Ref.make<Array<ProviderRuntimeEvent>>([]);
|
||||
const consumer = yield* Stream.take(provider.streamEvents, 3).pipe(
|
||||
Stream.runForEach((event) => Ref.update(receivedRef, (current) => [...current, event])),
|
||||
Effect.forkChild,
|
||||
);
|
||||
yield* sleep(20);
|
||||
|
||||
fanout.codex.emit({
|
||||
type: "tool.started",
|
||||
eventId: asEventId("evt-seq-1"),
|
||||
provider: "codex",
|
||||
createdAt: new Date().toISOString(),
|
||||
threadId: session.threadId,
|
||||
turnId: asTurnId("turn-1"),
|
||||
toolKind: "command",
|
||||
title: "Command run",
|
||||
});
|
||||
fanout.codex.emit({
|
||||
type: "tool.completed",
|
||||
eventId: asEventId("evt-seq-2"),
|
||||
provider: "codex",
|
||||
createdAt: new Date().toISOString(),
|
||||
threadId: session.threadId,
|
||||
turnId: asTurnId("turn-1"),
|
||||
toolKind: "command",
|
||||
title: "Command run",
|
||||
});
|
||||
fanout.codex.emit({
|
||||
type: "turn.completed",
|
||||
eventId: asEventId("evt-seq-3"),
|
||||
provider: "codex",
|
||||
createdAt: new Date().toISOString(),
|
||||
threadId: session.threadId,
|
||||
turnId: asTurnId("turn-1"),
|
||||
status: "completed",
|
||||
});
|
||||
|
||||
yield* Fiber.join(consumer);
|
||||
const received = yield* Ref.get(receivedRef);
|
||||
assert.deepEqual(
|
||||
received.map((event) => event.eventId),
|
||||
[asEventId("evt-seq-1"), asEventId("evt-seq-2"), asEventId("evt-seq-3")],
|
||||
);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("keeps subscriber delivery ordered and isolates failing subscribers", () =>
|
||||
Effect.gen(function* () {
|
||||
const provider = yield* ProviderService;
|
||||
const session = yield* provider.startSession(asThreadId("thread-1"), {
|
||||
provider: "codex",
|
||||
threadId: asThreadId("thread-1"),
|
||||
runtimeMode: "full-access",
|
||||
});
|
||||
|
||||
const receivedByHealthy: string[] = [];
|
||||
@@ -794,13 +640,14 @@ fanout.layer("ProviderServiceLive fanout", (it) => {
|
||||
);
|
||||
yield* sleep(20);
|
||||
|
||||
const events: ReadonlyArray<LegacyProviderRuntimeEvent> = [
|
||||
const events: ReadonlyArray<ProviderRuntimeEvent> = [
|
||||
{
|
||||
type: "tool.completed",
|
||||
eventId: asEventId("evt-ordered-1"),
|
||||
provider: "codex",
|
||||
sessionId: session.sessionId,
|
||||
createdAt: new Date().toISOString(),
|
||||
threadId: session.threadId,
|
||||
threadId: asProviderThreadId("thread-1"),
|
||||
turnId: asTurnId("turn-1"),
|
||||
toolKind: "command",
|
||||
title: "Command run",
|
||||
@@ -810,8 +657,9 @@ fanout.layer("ProviderServiceLive fanout", (it) => {
|
||||
type: "message.delta",
|
||||
eventId: asEventId("evt-ordered-2"),
|
||||
provider: "codex",
|
||||
sessionId: session.sessionId,
|
||||
createdAt: new Date().toISOString(),
|
||||
threadId: session.threadId,
|
||||
threadId: asProviderThreadId("thread-1"),
|
||||
turnId: asTurnId("turn-1"),
|
||||
delta: "hello",
|
||||
},
|
||||
@@ -819,8 +667,9 @@ fanout.layer("ProviderServiceLive fanout", (it) => {
|
||||
type: "turn.completed",
|
||||
eventId: asEventId("evt-ordered-3"),
|
||||
provider: "codex",
|
||||
sessionId: session.sessionId,
|
||||
createdAt: new Date().toISOString(),
|
||||
threadId: session.threadId,
|
||||
threadId: asProviderThreadId("thread-1"),
|
||||
turnId: asTurnId("turn-1"),
|
||||
status: "completed",
|
||||
},
|
||||
@@ -849,9 +698,7 @@ validation.layer("ProviderServiceLive validation", (it) => {
|
||||
|
||||
const failure = yield* Effect.result(
|
||||
provider.startSession(asThreadId("thread-validation"), {
|
||||
threadId: asThreadId("thread-validation"),
|
||||
provider: "invalid-provider",
|
||||
runtimeMode: "full-access",
|
||||
} as never),
|
||||
);
|
||||
|
||||
@@ -868,19 +715,17 @@ validation.layer("ProviderServiceLive validation", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("accepts startSession when adapter has not emitted provider thread id yet", () =>
|
||||
it.effect("fails startSession when adapter returns no threadId", () =>
|
||||
Effect.gen(function* () {
|
||||
const provider = yield* ProviderService;
|
||||
const runtimeRepository = yield* ProviderSessionRuntimeRepository;
|
||||
|
||||
validation.codex.startSession.mockImplementationOnce((input: ProviderSessionStartInput) =>
|
||||
Effect.sync(() => {
|
||||
const now = new Date().toISOString();
|
||||
return {
|
||||
sessionId: asSessionId("sess-missing-thread"),
|
||||
provider: "codex",
|
||||
status: "ready",
|
||||
threadId: input.threadId,
|
||||
runtimeMode: input.runtimeMode,
|
||||
cwd: input.cwd ?? process.cwd(),
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
@@ -888,22 +733,20 @@ validation.layer("ProviderServiceLive validation", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
const session = yield* provider.startSession(asThreadId("thread-missing"), {
|
||||
provider: "codex",
|
||||
threadId: asThreadId("thread-missing"),
|
||||
cwd: "/tmp/project",
|
||||
runtimeMode: "full-access",
|
||||
});
|
||||
const failure = yield* Effect.result(
|
||||
provider.startSession(asThreadId("thread-missing"), {
|
||||
provider: "codex",
|
||||
cwd: "/tmp/project",
|
||||
}),
|
||||
);
|
||||
|
||||
assert.equal(session.threadId, asThreadId("thread-missing"));
|
||||
|
||||
const runtime = yield* runtimeRepository.getByThreadId({
|
||||
threadId: session.threadId,
|
||||
});
|
||||
assert.equal(Option.isSome(runtime), true);
|
||||
if (Option.isSome(runtime)) {
|
||||
assert.equal(runtime.value.threadId, session.threadId);
|
||||
}
|
||||
assertFailure(
|
||||
failure,
|
||||
new ProviderValidationError({
|
||||
operation: "ProviderService.startSession",
|
||||
issue: "Provider 'codex' returned a session without threadId.",
|
||||
}),
|
||||
);
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -11,24 +11,24 @@
|
||||
*/
|
||||
import {
|
||||
NonNegativeInt,
|
||||
ProviderSessionId,
|
||||
ThreadId,
|
||||
ProviderInterruptTurnInput,
|
||||
ProviderRespondToRequestInput,
|
||||
ProviderRespondToUserInputInput,
|
||||
ProviderSendTurnInput,
|
||||
ProviderSessionStartInput,
|
||||
ProviderStopSessionInput,
|
||||
type ProviderRuntimeEvent,
|
||||
type ProviderSession,
|
||||
} from "@t3tools/contracts";
|
||||
import { Effect, Layer, Option, PubSub, Queue, Schema, SchemaIssue, Stream } from "effect";
|
||||
import { Effect, Layer, Option, PubSub, Queue, Ref, Schema, SchemaIssue, Stream } from "effect";
|
||||
|
||||
import { ProviderValidationError } from "../Errors.ts";
|
||||
import { ProviderSessionNotFoundError, ProviderValidationError } from "../Errors.ts";
|
||||
import { ProviderAdapterRegistry } from "../Services/ProviderAdapterRegistry.ts";
|
||||
import { ProviderService, type ProviderServiceShape } from "../Services/ProviderService.ts";
|
||||
import {
|
||||
ProviderSessionDirectory,
|
||||
type ProviderRuntimeBinding,
|
||||
type ProviderSessionBinding,
|
||||
} from "../Services/ProviderSessionDirectory.ts";
|
||||
import { type EventNdjsonLogger, makeEventNdjsonLogger } from "./EventNdjsonLogger.ts";
|
||||
|
||||
@@ -38,7 +38,7 @@ export interface ProviderServiceLiveOptions {
|
||||
}
|
||||
|
||||
const ProviderRollbackConversationInput = Schema.Struct({
|
||||
threadId: ThreadId,
|
||||
sessionId: ProviderSessionId,
|
||||
numTurns: NonNegativeInt,
|
||||
});
|
||||
|
||||
@@ -95,7 +95,7 @@ function toRuntimePayloadFromSession(session: ProviderSession): Record<string, u
|
||||
}
|
||||
|
||||
function readPersistedCwd(
|
||||
runtimePayload: ProviderRuntimeBinding["runtimePayload"],
|
||||
runtimePayload: ProviderSessionBinding["runtimePayload"],
|
||||
): string | undefined {
|
||||
if (!runtimePayload || typeof runtimePayload !== "object" || Array.isArray(runtimePayload)) {
|
||||
return undefined;
|
||||
@@ -120,12 +120,43 @@ const makeProviderService = (options?: ProviderServiceLiveOptions) =>
|
||||
const directory = yield* ProviderSessionDirectory;
|
||||
const runtimeEventQueue = yield* Queue.unbounded<ProviderRuntimeEvent>();
|
||||
const runtimeEventPubSub = yield* PubSub.unbounded<ProviderRuntimeEvent>();
|
||||
const routedSessionAliasesRef = yield* Ref.make<Map<ProviderSessionId, ProviderSessionId>>(
|
||||
new Map(),
|
||||
);
|
||||
|
||||
const canonicalizeRuntimeEventSession = (
|
||||
event: ProviderRuntimeEvent,
|
||||
): Effect.Effect<ProviderRuntimeEvent> =>
|
||||
Ref.get(routedSessionAliasesRef).pipe(
|
||||
Effect.map((aliases) => {
|
||||
for (const [staleSessionId, liveSessionId] of aliases) {
|
||||
if (liveSessionId === event.sessionId) {
|
||||
return {
|
||||
...event,
|
||||
sessionId: staleSessionId,
|
||||
} satisfies ProviderRuntimeEvent;
|
||||
}
|
||||
}
|
||||
return event;
|
||||
}),
|
||||
);
|
||||
|
||||
const publishRuntimeEvent = (event: ProviderRuntimeEvent): Effect.Effect<void> =>
|
||||
Effect.succeed(event).pipe(
|
||||
canonicalizeRuntimeEventSession(event).pipe(
|
||||
Effect.tap((canonicalEvent) =>
|
||||
canonicalEventLogger
|
||||
? canonicalEventLogger.write(canonicalEvent, null)
|
||||
? Effect.flatMap(
|
||||
Effect.catch(
|
||||
directory.getThreadId(canonicalEvent.sessionId).pipe(
|
||||
Effect.map((threadIdOption) =>
|
||||
Option.isSome(threadIdOption) ? threadIdOption.value : null,
|
||||
),
|
||||
),
|
||||
() => Effect.succeed<ThreadId | null>(null),
|
||||
),
|
||||
(orchestrationThreadId) =>
|
||||
canonicalEventLogger.write(canonicalEvent, orchestrationThreadId),
|
||||
)
|
||||
: Effect.void,
|
||||
),
|
||||
Effect.flatMap((canonicalEvent) => PubSub.publish(runtimeEventPubSub, canonicalEvent)),
|
||||
@@ -134,15 +165,64 @@ const makeProviderService = (options?: ProviderServiceLiveOptions) =>
|
||||
|
||||
const upsertSessionBinding = (
|
||||
session: ProviderSession,
|
||||
operation: string,
|
||||
threadId: ThreadId,
|
||||
) =>
|
||||
directory.upsert({
|
||||
threadId,
|
||||
provider: session.provider,
|
||||
runtimeMode: session.runtimeMode,
|
||||
status: toRuntimeStatus(session),
|
||||
...(session.resumeCursor !== undefined ? { resumeCursor: session.resumeCursor } : {}),
|
||||
runtimePayload: toRuntimePayloadFromSession(session),
|
||||
Effect.gen(function* () {
|
||||
const providerThreadId = session.threadId;
|
||||
if (!providerThreadId) {
|
||||
return yield* toValidationError(
|
||||
operation,
|
||||
`Provider '${session.provider}' returned a session without threadId.`,
|
||||
);
|
||||
}
|
||||
|
||||
yield* directory.upsert({
|
||||
sessionId: session.sessionId,
|
||||
provider: session.provider,
|
||||
threadId,
|
||||
providerThreadId,
|
||||
status: toRuntimeStatus(session),
|
||||
...(session.resumeCursor !== undefined ? { resumeCursor: session.resumeCursor } : {}),
|
||||
runtimePayload: toRuntimePayloadFromSession(session),
|
||||
});
|
||||
|
||||
return providerThreadId;
|
||||
});
|
||||
|
||||
const clearAliasKey = (staleSessionId: ProviderSessionId) =>
|
||||
Ref.update(routedSessionAliasesRef, (current) => {
|
||||
if (!current.has(staleSessionId)) {
|
||||
return current;
|
||||
}
|
||||
const next = new Map(current);
|
||||
next.delete(staleSessionId);
|
||||
return next;
|
||||
});
|
||||
|
||||
const clearAliasesReferencing = (sessionId: ProviderSessionId) =>
|
||||
Ref.update(routedSessionAliasesRef, (current) => {
|
||||
let changed = false;
|
||||
const next = new Map<ProviderSessionId, ProviderSessionId>();
|
||||
for (const [key, value] of current) {
|
||||
if (key === sessionId || value === sessionId) {
|
||||
changed = true;
|
||||
continue;
|
||||
}
|
||||
next.set(key, value);
|
||||
}
|
||||
return changed ? next : current;
|
||||
});
|
||||
|
||||
const setAlias = (staleSessionId: ProviderSessionId, liveSessionId: ProviderSessionId) =>
|
||||
Ref.update(routedSessionAliasesRef, (current) => {
|
||||
const existing = current.get(staleSessionId);
|
||||
if (existing === liveSessionId) {
|
||||
return current;
|
||||
}
|
||||
const next = new Map(current);
|
||||
next.set(staleSessionId, liveSessionId);
|
||||
return next;
|
||||
});
|
||||
|
||||
const providers = yield* registry.listProviders();
|
||||
@@ -165,77 +245,163 @@ const makeProviderService = (options?: ProviderServiceLiveOptions) =>
|
||||
).pipe(Effect.asVoid);
|
||||
|
||||
const recoverSessionForThread = (input: {
|
||||
readonly binding: ProviderRuntimeBinding;
|
||||
readonly staleSessionId: ProviderSessionId;
|
||||
readonly binding: ProviderSessionBinding & { readonly threadId: ThreadId };
|
||||
readonly operation: string;
|
||||
}) =>
|
||||
Effect.gen(function* () {
|
||||
const adapter = yield* registry.getByProvider(input.binding.provider);
|
||||
const activeSessions = yield* adapter.listSessions();
|
||||
const resumeThreadId = input.binding.providerThreadId ?? undefined;
|
||||
const hasResumeCursor =
|
||||
input.binding.resumeCursor !== null && input.binding.resumeCursor !== undefined;
|
||||
const hasActiveSession = yield* adapter.hasSession(input.binding.threadId);
|
||||
if (hasActiveSession) {
|
||||
const activeSessions = yield* adapter.listSessions();
|
||||
const existing = activeSessions.find((session) => session.threadId === input.binding.threadId);
|
||||
if (existing) {
|
||||
yield* upsertSessionBinding(existing, input.binding.threadId);
|
||||
return { adapter, session: existing } as const;
|
||||
const existing =
|
||||
resumeThreadId === undefined
|
||||
? undefined
|
||||
: activeSessions.find((session) => session.threadId === resumeThreadId);
|
||||
if (existing) {
|
||||
const existingProviderThreadId = yield* upsertSessionBinding(
|
||||
existing,
|
||||
`${input.operation}:upsertExistingSession`,
|
||||
input.binding.threadId,
|
||||
);
|
||||
yield* directory.upsert({
|
||||
sessionId: input.staleSessionId,
|
||||
provider: existing.provider,
|
||||
threadId: input.binding.threadId,
|
||||
providerThreadId: existingProviderThreadId,
|
||||
...(existing.resumeCursor !== undefined ? { resumeCursor: existing.resumeCursor } : {}),
|
||||
});
|
||||
if (existing.sessionId !== input.staleSessionId) {
|
||||
yield* setAlias(input.staleSessionId, existing.sessionId);
|
||||
} else {
|
||||
yield* clearAliasKey(input.staleSessionId);
|
||||
}
|
||||
return {
|
||||
adapter,
|
||||
sessionId: existing.sessionId,
|
||||
} as const;
|
||||
}
|
||||
|
||||
if (!hasResumeCursor) {
|
||||
if (!resumeThreadId && !hasResumeCursor) {
|
||||
return yield* toValidationError(
|
||||
input.operation,
|
||||
`Cannot recover thread '${input.binding.threadId}' because no provider resume state is persisted.`,
|
||||
`Cannot recover stale session '${input.staleSessionId}' because no provider resume state is persisted.`,
|
||||
);
|
||||
}
|
||||
|
||||
const persistedCwd = readPersistedCwd(input.binding.runtimePayload);
|
||||
|
||||
const resumed = yield* adapter.startSession({
|
||||
threadId: input.binding.threadId,
|
||||
provider: input.binding.provider,
|
||||
...(persistedCwd ? { cwd: persistedCwd } : {}),
|
||||
...(resumeThreadId ? { resumeThreadId } : {}),
|
||||
...(hasResumeCursor ? { resumeCursor: input.binding.resumeCursor } : {}),
|
||||
runtimeMode: input.binding.runtimeMode ?? "full-access",
|
||||
});
|
||||
if (resumed.provider !== adapter.provider) {
|
||||
return yield* toValidationError(
|
||||
input.operation,
|
||||
`Adapter/provider mismatch while recovering thread '${input.binding.threadId}'. Expected '${adapter.provider}', received '${resumed.provider}'.`,
|
||||
`Adapter/provider mismatch while recovering stale session '${input.staleSessionId}'. Expected '${adapter.provider}', received '${resumed.provider}'.`,
|
||||
);
|
||||
}
|
||||
|
||||
yield* upsertSessionBinding(resumed, input.binding.threadId);
|
||||
return { adapter, session: resumed } as const;
|
||||
const resumedProviderThreadId = yield* upsertSessionBinding(
|
||||
resumed,
|
||||
`${input.operation}:upsertRecoveredSession`,
|
||||
input.binding.threadId,
|
||||
);
|
||||
|
||||
yield* directory.upsert({
|
||||
sessionId: input.staleSessionId,
|
||||
provider: resumed.provider,
|
||||
threadId: input.binding.threadId,
|
||||
providerThreadId: resumedProviderThreadId,
|
||||
...(resumed.resumeCursor !== undefined ? { resumeCursor: resumed.resumeCursor } : {}),
|
||||
});
|
||||
|
||||
if (resumed.sessionId !== input.staleSessionId) {
|
||||
yield* setAlias(input.staleSessionId, resumed.sessionId);
|
||||
} else {
|
||||
yield* clearAliasKey(input.staleSessionId);
|
||||
}
|
||||
|
||||
return {
|
||||
adapter,
|
||||
sessionId: resumed.sessionId,
|
||||
} as const;
|
||||
});
|
||||
|
||||
const resolveRoutableSession = (input: {
|
||||
readonly threadId: ThreadId;
|
||||
readonly sessionId: ProviderSessionId;
|
||||
readonly operation: string;
|
||||
readonly allowRecovery: boolean;
|
||||
}) =>
|
||||
Effect.gen(function* () {
|
||||
const bindingOption = yield* directory.getBinding(input.threadId);
|
||||
const bindingOption = yield* directory.getBinding(input.sessionId);
|
||||
const binding = Option.getOrUndefined(bindingOption);
|
||||
if (!binding) {
|
||||
return yield* new ProviderSessionNotFoundError({
|
||||
sessionId: input.sessionId,
|
||||
});
|
||||
}
|
||||
if (!binding.threadId) {
|
||||
return yield* toValidationError(
|
||||
input.operation,
|
||||
`Cannot route thread '${input.threadId}' because no persisted provider binding exists.`,
|
||||
`Cannot route session '${input.sessionId}' because no orchestration thread id is persisted.`,
|
||||
);
|
||||
}
|
||||
const bindingWithThreadId: ProviderSessionBinding & {
|
||||
readonly threadId: ThreadId;
|
||||
} = {
|
||||
...binding,
|
||||
threadId: binding.threadId,
|
||||
};
|
||||
const adapter = yield* registry.getByProvider(binding.provider);
|
||||
|
||||
const hasRequestedSession = yield* adapter.hasSession(input.threadId);
|
||||
const hasRequestedSession = yield* adapter.hasSession(input.sessionId);
|
||||
if (hasRequestedSession) {
|
||||
return { adapter, threadId: input.threadId, isActive: true } as const;
|
||||
yield* clearAliasKey(input.sessionId);
|
||||
return {
|
||||
adapter,
|
||||
sessionId: input.sessionId,
|
||||
isActive: true,
|
||||
} as const;
|
||||
}
|
||||
|
||||
const alias = yield* Ref.get(routedSessionAliasesRef).pipe(
|
||||
Effect.map((aliases) => aliases.get(input.sessionId)),
|
||||
);
|
||||
if (alias) {
|
||||
const aliasIsActive = yield* adapter.hasSession(alias);
|
||||
if (aliasIsActive) {
|
||||
return {
|
||||
adapter,
|
||||
sessionId: alias,
|
||||
isActive: true,
|
||||
} as const;
|
||||
}
|
||||
yield* clearAliasKey(input.sessionId);
|
||||
}
|
||||
|
||||
if (!input.allowRecovery) {
|
||||
return { adapter, threadId: input.threadId, isActive: false } as const;
|
||||
return {
|
||||
adapter,
|
||||
sessionId: input.sessionId,
|
||||
isActive: false,
|
||||
} as const;
|
||||
}
|
||||
|
||||
const recovered = yield* recoverSessionForThread({ binding, operation: input.operation });
|
||||
return { adapter: recovered.adapter, threadId: input.threadId, isActive: true } as const;
|
||||
const recovered = yield* recoverSessionForThread({
|
||||
staleSessionId: input.sessionId,
|
||||
binding: bindingWithThreadId,
|
||||
operation: input.operation,
|
||||
});
|
||||
|
||||
return {
|
||||
adapter: recovered.adapter,
|
||||
sessionId: recovered.sessionId,
|
||||
isActive: true,
|
||||
} as const;
|
||||
});
|
||||
|
||||
const startSession: ProviderServiceShape["startSession"] = (threadId, rawInput) =>
|
||||
@@ -248,8 +414,9 @@ const makeProviderService = (options?: ProviderServiceLiveOptions) =>
|
||||
|
||||
const input = {
|
||||
...parsed,
|
||||
threadId,
|
||||
provider: parsed.provider ?? "codex",
|
||||
approvalPolicy: parsed.approvalPolicy ?? "never",
|
||||
sandboxMode: parsed.sandboxMode ?? "workspace-write",
|
||||
};
|
||||
const adapter = yield* registry.getByProvider(input.provider);
|
||||
const session = yield* adapter.startSession(input);
|
||||
@@ -261,7 +428,7 @@ const makeProviderService = (options?: ProviderServiceLiveOptions) =>
|
||||
);
|
||||
}
|
||||
|
||||
yield* upsertSessionBinding(session, threadId);
|
||||
yield* upsertSessionBinding(session, "ProviderService.startSession", threadId);
|
||||
|
||||
return session;
|
||||
});
|
||||
@@ -285,14 +452,28 @@ const makeProviderService = (options?: ProviderServiceLiveOptions) =>
|
||||
);
|
||||
}
|
||||
const routed = yield* resolveRoutableSession({
|
||||
threadId: input.threadId,
|
||||
sessionId: input.sessionId,
|
||||
operation: "ProviderService.sendTurn",
|
||||
allowRecovery: true,
|
||||
});
|
||||
const turn = yield* routed.adapter.sendTurn(input);
|
||||
const turn = yield* routed.adapter.sendTurn({
|
||||
...input,
|
||||
sessionId: routed.sessionId,
|
||||
});
|
||||
const threadId = yield* directory
|
||||
.getThreadId(input.sessionId)
|
||||
.pipe(Effect.map(Option.getOrUndefined));
|
||||
if (!threadId) {
|
||||
return yield* toValidationError(
|
||||
"ProviderService.sendTurn",
|
||||
`No thread id is tracked for provider session '${input.sessionId}'.`,
|
||||
);
|
||||
}
|
||||
yield* directory.upsert({
|
||||
threadId: input.threadId,
|
||||
sessionId: input.sessionId,
|
||||
provider: routed.adapter.provider,
|
||||
threadId,
|
||||
providerThreadId: turn.threadId,
|
||||
status: "running",
|
||||
...(turn.resumeCursor !== undefined ? { resumeCursor: turn.resumeCursor } : {}),
|
||||
runtimePayload: {
|
||||
@@ -312,11 +493,11 @@ const makeProviderService = (options?: ProviderServiceLiveOptions) =>
|
||||
payload: rawInput,
|
||||
});
|
||||
const routed = yield* resolveRoutableSession({
|
||||
threadId: input.threadId,
|
||||
sessionId: input.sessionId,
|
||||
operation: "ProviderService.interruptTurn",
|
||||
allowRecovery: true,
|
||||
});
|
||||
yield* routed.adapter.interruptTurn(routed.threadId, input.turnId);
|
||||
yield* routed.adapter.interruptTurn(routed.sessionId, input.turnId);
|
||||
});
|
||||
|
||||
const respondToRequest: ProviderServiceShape["respondToRequest"] = (rawInput) =>
|
||||
@@ -327,26 +508,11 @@ const makeProviderService = (options?: ProviderServiceLiveOptions) =>
|
||||
payload: rawInput,
|
||||
});
|
||||
const routed = yield* resolveRoutableSession({
|
||||
threadId: input.threadId,
|
||||
sessionId: input.sessionId,
|
||||
operation: "ProviderService.respondToRequest",
|
||||
allowRecovery: true,
|
||||
});
|
||||
yield* routed.adapter.respondToRequest(routed.threadId, input.requestId, input.decision);
|
||||
});
|
||||
|
||||
const respondToUserInput: ProviderServiceShape["respondToUserInput"] = (rawInput) =>
|
||||
Effect.gen(function* () {
|
||||
const input = yield* decodeInputOrValidationError({
|
||||
operation: "ProviderService.respondToUserInput",
|
||||
schema: ProviderRespondToUserInputInput,
|
||||
payload: rawInput,
|
||||
});
|
||||
const routed = yield* resolveRoutableSession({
|
||||
threadId: input.threadId,
|
||||
operation: "ProviderService.respondToUserInput",
|
||||
allowRecovery: true,
|
||||
});
|
||||
yield* routed.adapter.respondToUserInput(routed.threadId, input.requestId, input.answers);
|
||||
yield* routed.adapter.respondToRequest(routed.sessionId, input.requestId, input.decision);
|
||||
});
|
||||
|
||||
const stopSession: ProviderServiceShape["stopSession"] = (rawInput) =>
|
||||
@@ -357,61 +523,25 @@ const makeProviderService = (options?: ProviderServiceLiveOptions) =>
|
||||
payload: rawInput,
|
||||
});
|
||||
const routed = yield* resolveRoutableSession({
|
||||
threadId: input.threadId,
|
||||
sessionId: input.sessionId,
|
||||
operation: "ProviderService.stopSession",
|
||||
allowRecovery: false,
|
||||
});
|
||||
if (routed.isActive) {
|
||||
yield* routed.adapter.stopSession(routed.threadId);
|
||||
yield* routed.adapter.stopSession(routed.sessionId);
|
||||
}
|
||||
yield* directory.remove(input.threadId);
|
||||
if (routed.sessionId !== input.sessionId) {
|
||||
yield* directory.remove(routed.sessionId);
|
||||
yield* clearAliasesReferencing(routed.sessionId);
|
||||
}
|
||||
yield* directory.remove(input.sessionId);
|
||||
yield* clearAliasesReferencing(input.sessionId);
|
||||
});
|
||||
|
||||
const listSessions: ProviderServiceShape["listSessions"] = () =>
|
||||
Effect.gen(function* () {
|
||||
const sessionsByProvider = yield* Effect.forEach(adapters, (adapter) => adapter.listSessions());
|
||||
const activeSessions = sessionsByProvider.flatMap((sessions) => sessions);
|
||||
const persistedBindings = yield* directory
|
||||
.listThreadIds()
|
||||
.pipe(
|
||||
Effect.flatMap((threadIds) =>
|
||||
Effect.forEach(
|
||||
threadIds,
|
||||
(threadId) =>
|
||||
directory.getBinding(threadId).pipe(
|
||||
Effect.orElseSucceed(() => Option.none<ProviderRuntimeBinding>()),
|
||||
),
|
||||
{ concurrency: "unbounded" },
|
||||
),
|
||||
),
|
||||
Effect.orElseSucceed(() => [] as Array<Option.Option<ProviderRuntimeBinding>>),
|
||||
);
|
||||
const bindingsByThreadId = new Map<ThreadId, ProviderRuntimeBinding>();
|
||||
for (const bindingOption of persistedBindings) {
|
||||
const binding = Option.getOrUndefined(bindingOption);
|
||||
if (binding) {
|
||||
bindingsByThreadId.set(binding.threadId, binding);
|
||||
}
|
||||
}
|
||||
|
||||
return activeSessions.map((session) => {
|
||||
const binding = bindingsByThreadId.get(session.threadId);
|
||||
if (!binding) {
|
||||
return session;
|
||||
}
|
||||
|
||||
return {
|
||||
...session,
|
||||
...(session.resumeCursor === undefined && binding.resumeCursor !== undefined
|
||||
? { resumeCursor: binding.resumeCursor }
|
||||
: {}),
|
||||
...(binding.runtimeMode !== undefined ? { runtimeMode: binding.runtimeMode } : {}),
|
||||
};
|
||||
});
|
||||
});
|
||||
|
||||
const getCapabilities: ProviderServiceShape["getCapabilities"] = (provider) =>
|
||||
registry.getByProvider(provider).pipe(Effect.map((adapter) => adapter.capabilities));
|
||||
Effect.forEach(adapters, (adapter) => adapter.listSessions()).pipe(
|
||||
Effect.map((sessionsByProvider) => sessionsByProvider.flatMap((sessions) => sessions)),
|
||||
);
|
||||
|
||||
const rollbackConversation: ProviderServiceShape["rollbackConversation"] = (rawInput) =>
|
||||
Effect.gen(function* () {
|
||||
@@ -424,22 +554,22 @@ const makeProviderService = (options?: ProviderServiceLiveOptions) =>
|
||||
return;
|
||||
}
|
||||
const routed = yield* resolveRoutableSession({
|
||||
threadId: input.threadId,
|
||||
sessionId: input.sessionId,
|
||||
operation: "ProviderService.rollbackConversation",
|
||||
allowRecovery: true,
|
||||
});
|
||||
yield* routed.adapter.rollbackThread(routed.threadId, input.numTurns);
|
||||
yield* routed.adapter.rollbackThread(routed.sessionId, input.numTurns);
|
||||
});
|
||||
|
||||
const stopAll: ProviderServiceShape["stopAll"] = () =>
|
||||
Effect.gen(function* () {
|
||||
const threadIds = yield* directory.listThreadIds();
|
||||
const sessionIds = yield* directory.listSessionIds();
|
||||
yield* Effect.forEach(adapters, (adapter) => adapter.stopAll()).pipe(Effect.asVoid);
|
||||
yield* Effect.forEach(threadIds, (threadId) =>
|
||||
directory.getProvider(threadId).pipe(
|
||||
yield* Effect.forEach(sessionIds, (sessionId) =>
|
||||
directory.getProvider(sessionId).pipe(
|
||||
Effect.flatMap((provider) =>
|
||||
directory.upsert({
|
||||
threadId,
|
||||
sessionId,
|
||||
provider,
|
||||
status: "stopped",
|
||||
runtimePayload: {
|
||||
@@ -451,6 +581,9 @@ const makeProviderService = (options?: ProviderServiceLiveOptions) =>
|
||||
),
|
||||
),
|
||||
).pipe(Effect.asVoid);
|
||||
// Keep persisted session bindings so stale sessions can be resumed after
|
||||
// process restart via providerThreadId.
|
||||
yield* Ref.set(routedSessionAliasesRef, new Map());
|
||||
});
|
||||
|
||||
return {
|
||||
@@ -458,10 +591,8 @@ const makeProviderService = (options?: ProviderServiceLiveOptions) =>
|
||||
sendTurn,
|
||||
interruptTurn,
|
||||
respondToRequest,
|
||||
respondToUserInput,
|
||||
stopSession,
|
||||
listSessions,
|
||||
getCapabilities,
|
||||
rollbackConversation,
|
||||
stopAll,
|
||||
streamEvents: Stream.fromPubSub(runtimeEventPubSub),
|
||||
|
||||
@@ -3,7 +3,7 @@ import os from "node:os";
|
||||
import path from "node:path";
|
||||
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { ThreadId } from "@t3tools/contracts";
|
||||
import { ProviderSessionId, ProviderThreadId, ThreadId } from "@t3tools/contracts";
|
||||
import { it, assert } from "@effect/vitest";
|
||||
import { assertFailure, assertSome } from "@effect/vitest/utils";
|
||||
import { Effect, Layer, Option } from "effect";
|
||||
@@ -15,7 +15,7 @@ import {
|
||||
} from "../../persistence/Layers/Sqlite.ts";
|
||||
import { ProviderSessionRuntimeRepositoryLive } from "../../persistence/Layers/ProviderSessionRuntime.ts";
|
||||
import { ProviderSessionRuntimeRepository } from "../../persistence/Services/ProviderSessionRuntime.ts";
|
||||
import { ProviderSessionDirectoryPersistenceError } from "../Errors.ts";
|
||||
import { ProviderSessionNotFoundError, ProviderValidationError } from "../Errors.ts";
|
||||
import { ProviderSessionDirectory } from "../Services/ProviderSessionDirectory.ts";
|
||||
import { ProviderSessionDirectoryLive } from "./ProviderSessionDirectory.ts";
|
||||
|
||||
@@ -31,59 +31,74 @@ function makeDirectoryLayer<E, R>(persistenceLayer: Layer.Layer<SqlClient.SqlCli
|
||||
}
|
||||
|
||||
it.layer(makeDirectoryLayer(SqlitePersistenceMemory))("ProviderSessionDirectoryLive", (it) => {
|
||||
it("upserts, reads, and removes thread bindings", () =>
|
||||
it("upserts, reads, and removes session bindings", () =>
|
||||
Effect.gen(function* () {
|
||||
const directory = yield* ProviderSessionDirectory;
|
||||
const runtimeRepository = yield* ProviderSessionRuntimeRepository;
|
||||
|
||||
const sessionId = ProviderSessionId.makeUnsafe("sess-1");
|
||||
const initialThreadId = ThreadId.makeUnsafe("thread-1");
|
||||
|
||||
yield* directory.upsert({
|
||||
sessionId,
|
||||
provider: "codex",
|
||||
threadId: initialThreadId,
|
||||
});
|
||||
|
||||
const provider = yield* directory.getProvider(initialThreadId);
|
||||
const provider = yield* directory.getProvider(sessionId);
|
||||
assert.equal(provider, "codex");
|
||||
const resolvedBinding = yield* directory.getBinding(initialThreadId);
|
||||
assertSome(resolvedBinding, {
|
||||
threadId: initialThreadId,
|
||||
provider: "codex",
|
||||
});
|
||||
if (Option.isSome(resolvedBinding)) {
|
||||
assert.equal(resolvedBinding.value.threadId, initialThreadId);
|
||||
}
|
||||
const resolvedThreadId = yield* directory.getThreadId(sessionId);
|
||||
assertSome(resolvedThreadId, initialThreadId);
|
||||
|
||||
const nextThreadId = ThreadId.makeUnsafe("thread-2");
|
||||
|
||||
yield* directory.upsert({
|
||||
sessionId: sessionId,
|
||||
provider: "codex",
|
||||
threadId: nextThreadId,
|
||||
});
|
||||
const updatedBinding = yield* directory.getBinding(nextThreadId);
|
||||
const updatedThreadId = yield* directory.getThreadId(sessionId);
|
||||
assertSome(updatedThreadId, nextThreadId);
|
||||
const updatedBinding = yield* directory.getBinding(sessionId);
|
||||
assert.equal(Option.isSome(updatedBinding), true);
|
||||
if (Option.isSome(updatedBinding)) {
|
||||
assert.equal(updatedBinding.value.threadId, nextThreadId);
|
||||
assert.equal(updatedBinding.value.providerThreadId, null);
|
||||
}
|
||||
|
||||
const runtime = yield* runtimeRepository.getByThreadId({ threadId: nextThreadId });
|
||||
const runtime = yield* runtimeRepository.getBySessionId({
|
||||
providerSessionId: sessionId,
|
||||
});
|
||||
assert.equal(Option.isSome(runtime), true);
|
||||
if (Option.isSome(runtime)) {
|
||||
assert.equal(runtime.value.threadId, nextThreadId);
|
||||
assert.equal(runtime.value.providerThreadId, null);
|
||||
assert.equal(runtime.value.status, "running");
|
||||
assert.equal(runtime.value.providerName, "codex");
|
||||
assert.equal(runtime.value.adapterKey, "codex");
|
||||
}
|
||||
|
||||
const threadIds = yield* directory.listThreadIds();
|
||||
assert.deepEqual(threadIds, [nextThreadId]);
|
||||
const sessionIds = yield* directory.listSessionIds();
|
||||
assert.deepEqual(sessionIds, [sessionId]);
|
||||
|
||||
yield* directory.remove(nextThreadId);
|
||||
const missingProvider = yield* directory.getProvider(nextThreadId).pipe(Effect.result);
|
||||
yield* directory.remove(sessionId);
|
||||
const missingProvider = yield* directory.getProvider(sessionId).pipe(Effect.result);
|
||||
assertFailure(missingProvider, new ProviderSessionNotFoundError({ sessionId: "sess-1" }));
|
||||
}));
|
||||
|
||||
it("fails upsert when thread id is unavailable", () =>
|
||||
Effect.gen(function* () {
|
||||
const directory = yield* ProviderSessionDirectory;
|
||||
const result = yield* Effect.result(
|
||||
directory.upsert({
|
||||
sessionId: ProviderSessionId.makeUnsafe("sess-no-thread"),
|
||||
provider: "codex",
|
||||
}),
|
||||
);
|
||||
assertFailure(
|
||||
missingProvider,
|
||||
new ProviderSessionDirectoryPersistenceError({
|
||||
operation: "ProviderSessionDirectory.getProvider",
|
||||
detail: `No persisted provider binding found for thread '${nextThreadId}'.`,
|
||||
result,
|
||||
new ProviderValidationError({
|
||||
operation: "ProviderSessionDirectory.upsert",
|
||||
issue: "threadId must be a non-empty string.",
|
||||
}),
|
||||
);
|
||||
}));
|
||||
@@ -93,14 +108,18 @@ it.layer(makeDirectoryLayer(SqlitePersistenceMemory))("ProviderSessionDirectoryL
|
||||
const directory = yield* ProviderSessionDirectory;
|
||||
const runtimeRepository = yield* ProviderSessionRuntimeRepository;
|
||||
|
||||
const sessionId = ProviderSessionId.makeUnsafe("sess-runtime");
|
||||
const threadId = ThreadId.makeUnsafe("thread-runtime");
|
||||
const providerThreadId = ProviderThreadId.makeUnsafe("provider-thread-runtime");
|
||||
|
||||
yield* directory.upsert({
|
||||
sessionId,
|
||||
provider: "codex",
|
||||
threadId,
|
||||
providerThreadId,
|
||||
status: "starting",
|
||||
resumeCursor: {
|
||||
threadId: "provider-thread-runtime",
|
||||
resumeThreadId: "provider-thread-runtime",
|
||||
},
|
||||
runtimePayload: {
|
||||
cwd: "/tmp/project",
|
||||
@@ -109,21 +128,24 @@ it.layer(makeDirectoryLayer(SqlitePersistenceMemory))("ProviderSessionDirectoryL
|
||||
});
|
||||
|
||||
yield* directory.upsert({
|
||||
sessionId,
|
||||
provider: "codex",
|
||||
threadId,
|
||||
status: "running",
|
||||
runtimePayload: {
|
||||
activeTurnId: "turn-1",
|
||||
},
|
||||
});
|
||||
|
||||
const runtime = yield* runtimeRepository.getByThreadId({ threadId });
|
||||
const runtime = yield* runtimeRepository.getBySessionId({
|
||||
providerSessionId: sessionId,
|
||||
});
|
||||
assert.equal(Option.isSome(runtime), true);
|
||||
if (Option.isSome(runtime)) {
|
||||
assert.equal(runtime.value.threadId, threadId);
|
||||
assert.equal(runtime.value.providerThreadId, providerThreadId);
|
||||
assert.equal(runtime.value.status, "running");
|
||||
assert.deepEqual(runtime.value.resumeCursor, {
|
||||
threadId: "provider-thread-runtime",
|
||||
resumeThreadId: providerThreadId,
|
||||
});
|
||||
assert.deepEqual(runtime.value.runtimePayload, {
|
||||
cwd: "/tmp/project",
|
||||
@@ -133,17 +155,52 @@ it.layer(makeDirectoryLayer(SqlitePersistenceMemory))("ProviderSessionDirectoryL
|
||||
}
|
||||
}));
|
||||
|
||||
it("clears providerThreadId when explicitly set to null", () =>
|
||||
Effect.gen(function* () {
|
||||
const directory = yield* ProviderSessionDirectory;
|
||||
const runtimeRepository = yield* ProviderSessionRuntimeRepository;
|
||||
|
||||
const sessionId = ProviderSessionId.makeUnsafe("sess-clear-provider-thread-id");
|
||||
const threadId = ThreadId.makeUnsafe("thread-clear-provider-thread-id");
|
||||
const providerThreadId = ProviderThreadId.makeUnsafe("provider-thread-to-clear");
|
||||
|
||||
yield* directory.upsert({
|
||||
sessionId,
|
||||
provider: "codex",
|
||||
threadId,
|
||||
adapterKey: "custom-adapter",
|
||||
providerThreadId,
|
||||
});
|
||||
|
||||
yield* directory.upsert({
|
||||
sessionId,
|
||||
provider: "codex",
|
||||
providerThreadId: null,
|
||||
});
|
||||
|
||||
const runtime = yield* runtimeRepository.getBySessionId({
|
||||
providerSessionId: sessionId,
|
||||
});
|
||||
assert.equal(Option.isSome(runtime), true);
|
||||
if (Option.isSome(runtime)) {
|
||||
assert.equal(runtime.value.providerThreadId, null);
|
||||
assert.equal(runtime.value.adapterKey, "custom-adapter");
|
||||
}
|
||||
}));
|
||||
|
||||
it("rehydrates persisted mappings across layer restart", () =>
|
||||
Effect.gen(function* () {
|
||||
const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), "t3-provider-directory-"));
|
||||
const dbPath = path.join(tempDir, "orchestration.sqlite");
|
||||
const directoryLayer = makeDirectoryLayer(makeSqlitePersistenceLive(dbPath));
|
||||
|
||||
const sessionId = ProviderSessionId.makeUnsafe("sess-restart");
|
||||
const threadId = ThreadId.makeUnsafe("thread-restart");
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
const directory = yield* ProviderSessionDirectory;
|
||||
yield* directory.upsert({
|
||||
sessionId,
|
||||
provider: "codex",
|
||||
threadId,
|
||||
});
|
||||
@@ -152,17 +209,11 @@ it.layer(makeDirectoryLayer(SqlitePersistenceMemory))("ProviderSessionDirectoryL
|
||||
yield* Effect.gen(function* () {
|
||||
const directory = yield* ProviderSessionDirectory;
|
||||
const sql = yield* SqlClient.SqlClient;
|
||||
const provider = yield* directory.getProvider(threadId);
|
||||
const provider = yield* directory.getProvider(sessionId);
|
||||
assert.equal(provider, "codex");
|
||||
|
||||
const resolvedBinding = yield* directory.getBinding(threadId);
|
||||
assertSome(resolvedBinding, {
|
||||
threadId,
|
||||
provider: "codex",
|
||||
});
|
||||
if (Option.isSome(resolvedBinding)) {
|
||||
assert.equal(resolvedBinding.value.threadId, threadId);
|
||||
}
|
||||
const resolvedThreadId = yield* directory.getThreadId(sessionId);
|
||||
assertSome(resolvedThreadId, threadId);
|
||||
|
||||
const legacyTableRows = yield* sql<{ readonly name: string }>`
|
||||
SELECT name
|
||||
@@ -174,26 +225,4 @@ it.layer(makeDirectoryLayer(SqlitePersistenceMemory))("ProviderSessionDirectoryL
|
||||
|
||||
fs.rmSync(tempDir, { recursive: true, force: true });
|
||||
}));
|
||||
|
||||
it("accepts cursor provider bindings", () =>
|
||||
Effect.gen(function* () {
|
||||
const directory = yield* ProviderSessionDirectory;
|
||||
const threadId = ThreadId.makeUnsafe("thread-cursor");
|
||||
|
||||
yield* directory.upsert({
|
||||
provider: "cursor",
|
||||
threadId,
|
||||
});
|
||||
|
||||
const provider = yield* directory.getProvider(threadId);
|
||||
assert.equal(provider, "cursor");
|
||||
const resolvedBinding = yield* directory.getBinding(threadId);
|
||||
assertSome(resolvedBinding, {
|
||||
threadId,
|
||||
provider: "cursor",
|
||||
});
|
||||
if (Option.isSome(resolvedBinding)) {
|
||||
assert.equal(resolvedBinding.value.threadId, threadId);
|
||||
}
|
||||
}));
|
||||
});
|
||||
@@ -1,14 +1,15 @@
|
||||
import { type ProviderKind, type ThreadId } from "@t3tools/contracts";
|
||||
import { ProviderSessionId, type ProviderKind } from "@t3tools/contracts";
|
||||
import { Effect, Layer, Option } from "effect";
|
||||
|
||||
import { ProviderSessionRuntimeRepository } from "../../persistence/Services/ProviderSessionRuntime.ts";
|
||||
import {
|
||||
ProviderSessionDirectoryPersistenceError,
|
||||
ProviderSessionNotFoundError,
|
||||
ProviderValidationError,
|
||||
} from "../Errors.ts";
|
||||
import {
|
||||
ProviderSessionDirectory,
|
||||
type ProviderRuntimeBinding,
|
||||
type ProviderSessionBinding,
|
||||
type ProviderSessionDirectoryShape,
|
||||
} from "../Services/ProviderSessionDirectory.ts";
|
||||
|
||||
@@ -25,7 +26,7 @@ function decodeProviderKind(
|
||||
providerName: string,
|
||||
operation: string,
|
||||
): Effect.Effect<ProviderKind, ProviderSessionDirectoryPersistenceError> {
|
||||
if (providerName === "codex" || providerName === "claudeCode" || providerName === "cursor") {
|
||||
if (providerName === "codex" || providerName === "claudeCode") {
|
||||
return Effect.succeed(providerName);
|
||||
}
|
||||
return Effect.fail(
|
||||
@@ -48,7 +49,10 @@ function mergeRuntimePayload(
|
||||
return existing ?? null;
|
||||
}
|
||||
if (isRecord(existing) && isRecord(next)) {
|
||||
return { ...existing, ...next };
|
||||
return {
|
||||
...existing,
|
||||
...next,
|
||||
};
|
||||
}
|
||||
return next;
|
||||
}
|
||||
@@ -56,20 +60,21 @@ function mergeRuntimePayload(
|
||||
const makeProviderSessionDirectory = Effect.gen(function* () {
|
||||
const repository = yield* ProviderSessionRuntimeRepository;
|
||||
|
||||
const getBinding = (threadId: ThreadId) =>
|
||||
repository.getByThreadId({ threadId }).pipe(
|
||||
Effect.mapError(toPersistenceError("ProviderSessionDirectory.getBinding:getByThreadId")),
|
||||
const getBinding = (sessionId: ProviderSessionId) =>
|
||||
repository.getBySessionId({ providerSessionId: sessionId }).pipe(
|
||||
Effect.mapError(toPersistenceError("ProviderSessionDirectory.getBinding:getBySessionId")),
|
||||
Effect.flatMap((runtime) =>
|
||||
Option.match(runtime, {
|
||||
onNone: () => Effect.succeed(Option.none<ProviderRuntimeBinding>()),
|
||||
onNone: () => Effect.succeed(Option.none<ProviderSessionBinding>()),
|
||||
onSome: (value) =>
|
||||
decodeProviderKind(value.providerName, "ProviderSessionDirectory.getBinding").pipe(
|
||||
Effect.map((provider) =>
|
||||
Option.some({
|
||||
threadId: value.threadId,
|
||||
sessionId: value.providerSessionId,
|
||||
provider,
|
||||
threadId: value.threadId,
|
||||
adapterKey: value.adapterKey,
|
||||
runtimeMode: value.runtimeMode,
|
||||
providerThreadId: value.providerThreadId,
|
||||
status: value.status,
|
||||
resumeCursor: value.resumeCursor,
|
||||
runtimePayload: value.runtimePayload,
|
||||
@@ -82,8 +87,10 @@ const makeProviderSessionDirectory = Effect.gen(function* () {
|
||||
|
||||
const upsert: ProviderSessionDirectoryShape["upsert"] = Effect.fn(function* (binding) {
|
||||
const existing = yield* repository
|
||||
.getByThreadId({ threadId: binding.threadId })
|
||||
.pipe(Effect.mapError(toPersistenceError("ProviderSessionDirectory.upsert:getByThreadId")));
|
||||
.getBySessionId({
|
||||
providerSessionId: binding.sessionId,
|
||||
})
|
||||
.pipe(Effect.mapError(toPersistenceError("ProviderSessionDirectory.upsert:getBySessionId")));
|
||||
|
||||
const existingRuntime = Option.getOrUndefined(existing);
|
||||
const resolvedThreadId = binding.threadId ?? existingRuntime?.threadId;
|
||||
@@ -97,10 +104,14 @@ const makeProviderSessionDirectory = Effect.gen(function* () {
|
||||
const now = new Date().toISOString();
|
||||
yield* repository
|
||||
.upsert({
|
||||
providerSessionId: binding.sessionId,
|
||||
threadId: resolvedThreadId,
|
||||
providerName: binding.provider,
|
||||
adapterKey: binding.adapterKey ?? existingRuntime?.adapterKey ?? binding.provider,
|
||||
runtimeMode: binding.runtimeMode ?? existingRuntime?.runtimeMode ?? "full-access",
|
||||
providerThreadId:
|
||||
binding.providerThreadId !== undefined
|
||||
? binding.providerThreadId
|
||||
: (existingRuntime?.providerThreadId ?? null),
|
||||
status: binding.status ?? existingRuntime?.status ?? "running",
|
||||
lastSeenAt: now,
|
||||
resumeCursor:
|
||||
@@ -115,39 +126,63 @@ const makeProviderSessionDirectory = Effect.gen(function* () {
|
||||
.pipe(Effect.mapError(toPersistenceError("ProviderSessionDirectory.upsert:upsert")));
|
||||
});
|
||||
|
||||
const getProvider: ProviderSessionDirectoryShape["getProvider"] = (threadId) =>
|
||||
getBinding(threadId).pipe(
|
||||
const getProvider: ProviderSessionDirectoryShape["getProvider"] = (sessionId) =>
|
||||
getBinding(sessionId).pipe(
|
||||
Effect.flatMap((binding) =>
|
||||
Option.match(binding, {
|
||||
onSome: (value) => Effect.succeed(value.provider),
|
||||
onNone: () =>
|
||||
Effect.fail(
|
||||
new ProviderSessionDirectoryPersistenceError({
|
||||
operation: "ProviderSessionDirectory.getProvider",
|
||||
detail: `No persisted provider binding found for thread '${threadId}'.`,
|
||||
}),
|
||||
),
|
||||
onNone: () => Effect.fail(new ProviderSessionNotFoundError({ sessionId })),
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
const remove: ProviderSessionDirectoryShape["remove"] = (threadId) =>
|
||||
repository
|
||||
.deleteByThreadId({ threadId })
|
||||
.pipe(Effect.mapError(toPersistenceError("ProviderSessionDirectory.remove:deleteByThreadId")));
|
||||
const getBindingBySessionId: ProviderSessionDirectoryShape["getBinding"] = (sessionId) =>
|
||||
getBinding(sessionId);
|
||||
|
||||
const listThreadIds: ProviderSessionDirectoryShape["listThreadIds"] = () =>
|
||||
const getThreadId: ProviderSessionDirectoryShape["getThreadId"] = (sessionId) =>
|
||||
getBinding(sessionId).pipe(
|
||||
Effect.flatMap((binding) =>
|
||||
Option.match(binding, {
|
||||
onSome: (value) => Effect.succeed(Option.fromNullishOr(value.threadId)),
|
||||
onNone: () => Effect.fail(new ProviderSessionNotFoundError({ sessionId })),
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
const remove: ProviderSessionDirectoryShape["remove"] = (sessionId) =>
|
||||
repository
|
||||
.deleteBySessionId({ providerSessionId: sessionId })
|
||||
.pipe(
|
||||
Effect.mapError(toPersistenceError("ProviderSessionDirectory.remove:deleteBySessionId")),
|
||||
);
|
||||
|
||||
const listSessionIds: ProviderSessionDirectoryShape["listSessionIds"] = () =>
|
||||
repository.list().pipe(
|
||||
Effect.mapError(toPersistenceError("ProviderSessionDirectory.listThreadIds:list")),
|
||||
Effect.map((rows) => rows.map((row) => row.threadId)),
|
||||
Effect.mapError(toPersistenceError("ProviderSessionDirectory.listSessionIds:list")),
|
||||
Effect.flatMap((rows) =>
|
||||
Effect.forEach(
|
||||
rows,
|
||||
(row) =>
|
||||
decodeProviderKind(row.providerName, "ProviderSessionDirectory.listSessionIds").pipe(
|
||||
Effect.map((provider) => ({
|
||||
sessionId: row.providerSessionId,
|
||||
provider,
|
||||
threadId: row.threadId,
|
||||
})),
|
||||
),
|
||||
{ concurrency: "unbounded" },
|
||||
),
|
||||
),
|
||||
Effect.map((bindings) => bindings.map((binding) => binding.sessionId)),
|
||||
);
|
||||
|
||||
return {
|
||||
upsert,
|
||||
getProvider,
|
||||
getBinding,
|
||||
getBinding: getBindingBySessionId,
|
||||
getThreadId,
|
||||
remove,
|
||||
listThreadIds,
|
||||
listSessionIds,
|
||||
} satisfies ProviderSessionDirectoryShape;
|
||||
});
|
||||
|
||||
|
||||
@@ -1,131 +0,0 @@
|
||||
import { Schema } from "effect";
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
CursorAcpPermissionRequest,
|
||||
CursorAcpSessionPromptResult,
|
||||
CursorAcpSessionUpdateNotification,
|
||||
} from "./CursorAdapter.ts";
|
||||
|
||||
describe("Cursor ACP schemas", () => {
|
||||
it("decodes session/update thought and message chunks", () => {
|
||||
const thought = Schema.decodeUnknownSync(CursorAcpSessionUpdateNotification)({
|
||||
jsonrpc: "2.0",
|
||||
method: "session/update",
|
||||
params: {
|
||||
sessionId: "sess-1",
|
||||
update: {
|
||||
sessionUpdate: "agent_thought_chunk",
|
||||
content: {
|
||||
type: "text",
|
||||
text: "thinking",
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
expect(thought.params.update.sessionUpdate).toBe("agent_thought_chunk");
|
||||
|
||||
const message = Schema.decodeUnknownSync(CursorAcpSessionUpdateNotification)({
|
||||
jsonrpc: "2.0",
|
||||
method: "session/update",
|
||||
params: {
|
||||
sessionId: "sess-1",
|
||||
update: {
|
||||
sessionUpdate: "agent_message_chunk",
|
||||
content: {
|
||||
type: "text",
|
||||
text: "hello",
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
expect(message.params.update.sessionUpdate).toBe("agent_message_chunk");
|
||||
});
|
||||
|
||||
it("decodes tool call lifecycle updates", () => {
|
||||
const started = Schema.decodeUnknownSync(CursorAcpSessionUpdateNotification)({
|
||||
jsonrpc: "2.0",
|
||||
method: "session/update",
|
||||
params: {
|
||||
sessionId: "sess-1",
|
||||
update: {
|
||||
sessionUpdate: "tool_call",
|
||||
toolCallId: "tool-1",
|
||||
title: "Terminal",
|
||||
kind: "execute",
|
||||
status: "pending",
|
||||
rawInput: { command: "pwd" },
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
expect(started.params.update.sessionUpdate).toBe("tool_call");
|
||||
|
||||
const completed = Schema.decodeUnknownSync(CursorAcpSessionUpdateNotification)({
|
||||
jsonrpc: "2.0",
|
||||
method: "session/update",
|
||||
params: {
|
||||
sessionId: "sess-1",
|
||||
update: {
|
||||
sessionUpdate: "tool_call_update",
|
||||
toolCallId: "tool-1",
|
||||
status: "completed",
|
||||
rawOutput: {
|
||||
exitCode: 0,
|
||||
stdout: "ok",
|
||||
stderr: "",
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
expect(completed.params.update.sessionUpdate).toBe("tool_call_update");
|
||||
});
|
||||
|
||||
it("decodes permission requests", () => {
|
||||
const decoded = Schema.decodeUnknownSync(CursorAcpPermissionRequest)({
|
||||
jsonrpc: "2.0",
|
||||
id: 9,
|
||||
method: "session/request_permission",
|
||||
params: {
|
||||
sessionId: "sess-1",
|
||||
toolCall: {
|
||||
toolCallId: "tool-1",
|
||||
kind: "execute",
|
||||
},
|
||||
options: [
|
||||
{ optionId: "allow-once", name: "Allow once", kind: "allow_once" },
|
||||
{ optionId: "reject-once", name: "Reject", kind: "reject_once" },
|
||||
],
|
||||
},
|
||||
});
|
||||
|
||||
expect(decoded.method).toBe("session/request_permission");
|
||||
expect(decoded.params.options).toHaveLength(2);
|
||||
});
|
||||
|
||||
it("decodes prompt completion result payload", () => {
|
||||
const decoded = Schema.decodeUnknownSync(CursorAcpSessionPromptResult)({
|
||||
stopReason: "end_turn",
|
||||
});
|
||||
|
||||
expect(decoded.stopReason).toBe("end_turn");
|
||||
});
|
||||
|
||||
it("rejects unsupported update types", () => {
|
||||
expect(() =>
|
||||
Schema.decodeUnknownSync(CursorAcpSessionUpdateNotification)({
|
||||
jsonrpc: "2.0",
|
||||
method: "session/update",
|
||||
params: {
|
||||
sessionId: "sess-1",
|
||||
update: {
|
||||
sessionUpdate: "unknown_update",
|
||||
},
|
||||
},
|
||||
}),
|
||||
).toThrow();
|
||||
});
|
||||
});
|
||||
@@ -1,110 +0,0 @@
|
||||
/**
|
||||
* CursorAdapter - Cursor ACP implementation of the generic provider adapter contract.
|
||||
*
|
||||
* Defines ACP JSON-RPC schemas used by the Cursor adapter layer.
|
||||
*
|
||||
* @module CursorAdapter
|
||||
*/
|
||||
import { Schema, ServiceMap } from "effect";
|
||||
|
||||
import type { ProviderAdapterError } from "../Errors.ts";
|
||||
import type { ProviderAdapterShape } from "./ProviderAdapter.ts";
|
||||
|
||||
export const CursorAcpJsonRpcId = Schema.Union([Schema.String, Schema.Int]);
|
||||
export type CursorAcpJsonRpcId = typeof CursorAcpJsonRpcId.Type;
|
||||
|
||||
export const CursorAcpTextContent = Schema.Struct({
|
||||
type: Schema.Literal("text"),
|
||||
text: Schema.String,
|
||||
});
|
||||
export type CursorAcpTextContent = typeof CursorAcpTextContent.Type;
|
||||
|
||||
export const CursorAcpSessionUpdate = Schema.Union([
|
||||
Schema.Struct({
|
||||
sessionUpdate: Schema.Literal("available_commands_update"),
|
||||
availableCommands: Schema.Array(
|
||||
Schema.Struct({
|
||||
name: Schema.String,
|
||||
description: Schema.optional(Schema.String),
|
||||
}),
|
||||
),
|
||||
}),
|
||||
Schema.Struct({
|
||||
sessionUpdate: Schema.Literal("agent_thought_chunk"),
|
||||
content: CursorAcpTextContent,
|
||||
}),
|
||||
Schema.Struct({
|
||||
sessionUpdate: Schema.Literal("agent_message_chunk"),
|
||||
content: CursorAcpTextContent,
|
||||
}),
|
||||
Schema.Struct({
|
||||
sessionUpdate: Schema.Literal("tool_call"),
|
||||
toolCallId: Schema.String,
|
||||
title: Schema.optional(Schema.String),
|
||||
kind: Schema.optional(Schema.String),
|
||||
status: Schema.optional(Schema.String),
|
||||
rawInput: Schema.optional(Schema.Unknown),
|
||||
}),
|
||||
Schema.Struct({
|
||||
sessionUpdate: Schema.Literal("tool_call_update"),
|
||||
toolCallId: Schema.String,
|
||||
status: Schema.String,
|
||||
rawOutput: Schema.optional(Schema.Unknown),
|
||||
}),
|
||||
]);
|
||||
export type CursorAcpSessionUpdate = typeof CursorAcpSessionUpdate.Type;
|
||||
|
||||
export const CursorAcpSessionUpdateNotification = Schema.Struct({
|
||||
jsonrpc: Schema.optional(Schema.Literal("2.0")),
|
||||
method: Schema.Literal("session/update"),
|
||||
params: Schema.Struct({
|
||||
sessionId: Schema.String,
|
||||
update: CursorAcpSessionUpdate,
|
||||
}),
|
||||
});
|
||||
export type CursorAcpSessionUpdateNotification = typeof CursorAcpSessionUpdateNotification.Type;
|
||||
|
||||
export const CursorAcpPermissionOption = Schema.Struct({
|
||||
optionId: Schema.String,
|
||||
name: Schema.optional(Schema.String),
|
||||
kind: Schema.optional(Schema.String),
|
||||
});
|
||||
export type CursorAcpPermissionOption = typeof CursorAcpPermissionOption.Type;
|
||||
|
||||
export const CursorAcpPermissionRequest = Schema.Struct({
|
||||
jsonrpc: Schema.optional(Schema.Literal("2.0")),
|
||||
id: CursorAcpJsonRpcId,
|
||||
method: Schema.Literal("session/request_permission"),
|
||||
params: Schema.Struct({
|
||||
sessionId: Schema.String,
|
||||
toolCall: Schema.optional(Schema.Unknown),
|
||||
options: Schema.Array(CursorAcpPermissionOption),
|
||||
}),
|
||||
});
|
||||
export type CursorAcpPermissionRequest = typeof CursorAcpPermissionRequest.Type;
|
||||
|
||||
export const CursorAcpInitializeResult = Schema.Struct({
|
||||
protocolVersion: Schema.optional(Schema.Int),
|
||||
agentCapabilities: Schema.optional(Schema.Unknown),
|
||||
authMethods: Schema.optional(Schema.Array(Schema.Unknown)),
|
||||
});
|
||||
export type CursorAcpInitializeResult = typeof CursorAcpInitializeResult.Type;
|
||||
|
||||
export const CursorAcpSessionNewResult = Schema.Struct({
|
||||
sessionId: Schema.String,
|
||||
modes: Schema.optional(Schema.Unknown),
|
||||
});
|
||||
export type CursorAcpSessionNewResult = typeof CursorAcpSessionNewResult.Type;
|
||||
|
||||
export const CursorAcpSessionPromptResult = Schema.Struct({
|
||||
stopReason: Schema.optional(Schema.String),
|
||||
});
|
||||
export type CursorAcpSessionPromptResult = typeof CursorAcpSessionPromptResult.Type;
|
||||
|
||||
export interface CursorAdapterShape extends ProviderAdapterShape<ProviderAdapterError> {
|
||||
readonly provider: "cursor";
|
||||
}
|
||||
|
||||
export class CursorAdapter extends ServiceMap.Service<CursorAdapter, CursorAdapterShape>()(
|
||||
"t3/provider/Services/CursorAdapter",
|
||||
) {}
|
||||
@@ -11,34 +11,25 @@ import type {
|
||||
ApprovalRequestId,
|
||||
ProviderApprovalDecision,
|
||||
ProviderKind,
|
||||
ProviderUserInputAnswers,
|
||||
ProviderRuntimeEvent,
|
||||
ProviderSendTurnInput,
|
||||
ProviderSession,
|
||||
ProviderSessionId,
|
||||
ProviderSessionStartInput,
|
||||
ThreadId,
|
||||
ProviderThreadId,
|
||||
ProviderTurnId,
|
||||
ProviderTurnStartResult,
|
||||
TurnId,
|
||||
} from "@t3tools/contracts";
|
||||
import type { Effect } from "effect";
|
||||
import type { Stream } from "effect";
|
||||
|
||||
export type ProviderSessionModelSwitchMode = "in-session" | "restart-session" | "unsupported";
|
||||
|
||||
export interface ProviderAdapterCapabilities {
|
||||
/**
|
||||
* Declares whether changing the model on an existing session is supported.
|
||||
*/
|
||||
readonly sessionModelSwitch: ProviderSessionModelSwitchMode;
|
||||
}
|
||||
|
||||
export interface ProviderThreadTurnSnapshot {
|
||||
readonly id: TurnId;
|
||||
readonly id: ProviderTurnId;
|
||||
readonly items: ReadonlyArray<unknown>;
|
||||
}
|
||||
|
||||
export interface ProviderThreadSnapshot {
|
||||
readonly threadId: ThreadId;
|
||||
readonly threadId: ProviderThreadId;
|
||||
readonly turns: ReadonlyArray<ProviderThreadTurnSnapshot>;
|
||||
}
|
||||
|
||||
@@ -47,7 +38,6 @@ export interface ProviderAdapterShape<TError> {
|
||||
* Provider kind implemented by this adapter.
|
||||
*/
|
||||
readonly provider: ProviderKind;
|
||||
readonly capabilities: ProviderAdapterCapabilities;
|
||||
|
||||
/**
|
||||
* Start a provider-backed session.
|
||||
@@ -67,32 +57,23 @@ export interface ProviderAdapterShape<TError> {
|
||||
* Interrupt an active turn.
|
||||
*/
|
||||
readonly interruptTurn: (
|
||||
threadId: ThreadId,
|
||||
turnId?: TurnId,
|
||||
sessionId: ProviderSessionId,
|
||||
turnId?: ProviderTurnId,
|
||||
) => Effect.Effect<void, TError>;
|
||||
|
||||
/**
|
||||
* Respond to an interactive approval request.
|
||||
*/
|
||||
readonly respondToRequest: (
|
||||
threadId: ThreadId,
|
||||
sessionId: ProviderSessionId,
|
||||
requestId: ApprovalRequestId,
|
||||
decision: ProviderApprovalDecision,
|
||||
) => Effect.Effect<void, TError>;
|
||||
|
||||
/**
|
||||
* Respond to a structured user-input request.
|
||||
*/
|
||||
readonly respondToUserInput: (
|
||||
threadId: ThreadId,
|
||||
requestId: ApprovalRequestId,
|
||||
answers: ProviderUserInputAnswers,
|
||||
) => Effect.Effect<void, TError>;
|
||||
|
||||
/**
|
||||
* Stop one provider session.
|
||||
*/
|
||||
readonly stopSession: (threadId: ThreadId) => Effect.Effect<void, TError>;
|
||||
readonly stopSession: (sessionId: ProviderSessionId) => Effect.Effect<void, TError>;
|
||||
|
||||
/**
|
||||
* List currently active provider sessions for this adapter.
|
||||
@@ -102,20 +83,20 @@ export interface ProviderAdapterShape<TError> {
|
||||
/**
|
||||
* Check whether this adapter owns an active session id.
|
||||
*/
|
||||
readonly hasSession: (threadId: ThreadId) => Effect.Effect<boolean>;
|
||||
readonly hasSession: (sessionId: ProviderSessionId) => Effect.Effect<boolean>;
|
||||
|
||||
/**
|
||||
* Read a provider thread snapshot.
|
||||
*/
|
||||
readonly readThread: (
|
||||
threadId: ThreadId,
|
||||
sessionId: ProviderSessionId,
|
||||
) => Effect.Effect<ProviderThreadSnapshot, TError>;
|
||||
|
||||
/**
|
||||
* Roll back a provider thread by N turns.
|
||||
*/
|
||||
readonly rollbackThread: (
|
||||
threadId: ThreadId,
|
||||
sessionId: ProviderSessionId,
|
||||
numTurns: number,
|
||||
) => Effect.Effect<ProviderThreadSnapshot, TError>;
|
||||
|
||||
|
||||
@@ -13,12 +13,11 @@
|
||||
*/
|
||||
import type {
|
||||
ProviderInterruptTurnInput,
|
||||
ProviderKind,
|
||||
ProviderRespondToRequestInput,
|
||||
ProviderRespondToUserInputInput,
|
||||
ProviderRuntimeEvent,
|
||||
ProviderSendTurnInput,
|
||||
ProviderSession,
|
||||
ProviderSessionId,
|
||||
ProviderSessionStartInput,
|
||||
ProviderStopSessionInput,
|
||||
ThreadId,
|
||||
@@ -28,7 +27,6 @@ import { ServiceMap } from "effect";
|
||||
import type { Effect, Stream } from "effect";
|
||||
|
||||
import type { ProviderServiceError } from "../Errors.ts";
|
||||
import type { ProviderAdapterCapabilities } from "./ProviderAdapter.ts";
|
||||
|
||||
/**
|
||||
* ProviderServiceShape - Service API for provider session and turn orchestration.
|
||||
@@ -63,13 +61,6 @@ export interface ProviderServiceShape {
|
||||
input: ProviderRespondToRequestInput,
|
||||
) => Effect.Effect<void, ProviderServiceError>;
|
||||
|
||||
/**
|
||||
* Respond to a provider structured user-input request.
|
||||
*/
|
||||
readonly respondToUserInput: (
|
||||
input: ProviderRespondToUserInputInput,
|
||||
) => Effect.Effect<void, ProviderServiceError>;
|
||||
|
||||
/**
|
||||
* Stop a provider session.
|
||||
*/
|
||||
@@ -84,18 +75,11 @@ export interface ProviderServiceShape {
|
||||
*/
|
||||
readonly listSessions: () => Effect.Effect<ReadonlyArray<ProviderSession>>;
|
||||
|
||||
/**
|
||||
* Read static capabilities for a provider adapter.
|
||||
*/
|
||||
readonly getCapabilities: (
|
||||
provider: ProviderKind,
|
||||
) => Effect.Effect<ProviderAdapterCapabilities, ProviderServiceError>;
|
||||
|
||||
/**
|
||||
* Roll back provider conversation state by a number of turns.
|
||||
*/
|
||||
readonly rollbackConversation: (input: {
|
||||
readonly threadId: ThreadId;
|
||||
readonly sessionId: ProviderSessionId;
|
||||
readonly numTurns: number;
|
||||
}) => Effect.Effect<void, ProviderServiceError>;
|
||||
|
||||
|
||||
@@ -1,7 +1,17 @@
|
||||
/**
|
||||
* ProviderSessionDirectory - Session ownership index across provider adapters.
|
||||
*
|
||||
* Tracks which provider owns each `sessionId` so `ProviderService` can route
|
||||
* session-scoped calls to the correct adapter. It is metadata only and does not
|
||||
* perform provider RPC or checkpoint operations.
|
||||
*
|
||||
* @module ProviderSessionDirectory
|
||||
*/
|
||||
import type {
|
||||
ProviderKind,
|
||||
ProviderSessionId,
|
||||
ProviderSessionRuntimeStatus,
|
||||
RuntimeMode,
|
||||
ProviderThreadId,
|
||||
ThreadId,
|
||||
} from "@t3tools/contracts";
|
||||
import { Option, ServiceMap } from "effect";
|
||||
@@ -9,48 +19,83 @@ import type { Effect } from "effect";
|
||||
|
||||
import type {
|
||||
ProviderSessionDirectoryPersistenceError,
|
||||
ProviderSessionNotFoundError,
|
||||
ProviderValidationError,
|
||||
} from "../Errors.ts";
|
||||
|
||||
export interface ProviderRuntimeBinding {
|
||||
readonly threadId: ThreadId;
|
||||
export interface ProviderSessionBinding {
|
||||
readonly sessionId: ProviderSessionId;
|
||||
readonly provider: ProviderKind;
|
||||
readonly threadId?: ThreadId;
|
||||
readonly adapterKey?: string;
|
||||
readonly providerThreadId?: ProviderThreadId | null;
|
||||
readonly status?: ProviderSessionRuntimeStatus;
|
||||
readonly resumeCursor?: unknown | null;
|
||||
readonly runtimePayload?: unknown | null;
|
||||
readonly runtimeMode?: RuntimeMode;
|
||||
}
|
||||
|
||||
export type ProviderSessionDirectoryReadError = ProviderSessionDirectoryPersistenceError;
|
||||
export type ProviderSessionDirectoryReadError =
|
||||
| ProviderSessionNotFoundError
|
||||
| ProviderSessionDirectoryPersistenceError;
|
||||
|
||||
export type ProviderSessionDirectoryWriteError =
|
||||
| ProviderValidationError
|
||||
| ProviderSessionDirectoryPersistenceError;
|
||||
|
||||
/**
|
||||
* ProviderSessionDirectoryShape - Service API for provider session ownership metadata.
|
||||
*/
|
||||
export interface ProviderSessionDirectoryShape {
|
||||
/**
|
||||
* Record or update ownership for one provider session.
|
||||
*
|
||||
* Preserves existing persisted fields when omitted and shallow-merges
|
||||
* runtime payload objects.
|
||||
*/
|
||||
readonly upsert: (
|
||||
binding: ProviderRuntimeBinding,
|
||||
binding: ProviderSessionBinding,
|
||||
) => Effect.Effect<void, ProviderSessionDirectoryWriteError>;
|
||||
|
||||
/**
|
||||
* Resolve the provider owner for a session id.
|
||||
*/
|
||||
readonly getProvider: (
|
||||
threadId: ThreadId,
|
||||
sessionId: ProviderSessionId,
|
||||
) => Effect.Effect<ProviderKind, ProviderSessionDirectoryReadError>;
|
||||
|
||||
/**
|
||||
* Resolve the full tracked binding for a session id.
|
||||
*/
|
||||
readonly getBinding: (
|
||||
threadId: ThreadId,
|
||||
) => Effect.Effect<Option.Option<ProviderRuntimeBinding>, ProviderSessionDirectoryReadError>;
|
||||
sessionId: ProviderSessionId,
|
||||
) => Effect.Effect<Option.Option<ProviderSessionBinding>, ProviderSessionDirectoryReadError>;
|
||||
|
||||
/**
|
||||
* Resolve the tracked thread id for a session, if known.
|
||||
*/
|
||||
readonly getThreadId: (
|
||||
sessionId: ProviderSessionId,
|
||||
) => Effect.Effect<Option.Option<ThreadId>, ProviderSessionDirectoryReadError>;
|
||||
|
||||
/**
|
||||
* Remove a session binding.
|
||||
*/
|
||||
readonly remove: (
|
||||
threadId: ThreadId,
|
||||
sessionId: ProviderSessionId,
|
||||
) => Effect.Effect<void, ProviderSessionDirectoryPersistenceError>;
|
||||
|
||||
readonly listThreadIds: () => Effect.Effect<
|
||||
ReadonlyArray<ThreadId>,
|
||||
/**
|
||||
* List tracked session ids.
|
||||
*/
|
||||
readonly listSessionIds: () => Effect.Effect<
|
||||
ReadonlyArray<ProviderSessionId>,
|
||||
ProviderSessionDirectoryPersistenceError
|
||||
>;
|
||||
}
|
||||
|
||||
/**
|
||||
* ProviderSessionDirectory - Service tag for session ownership lookup.
|
||||
*/
|
||||
export class ProviderSessionDirectory extends ServiceMap.Service<
|
||||
ProviderSessionDirectory,
|
||||
ProviderSessionDirectoryShape
|
||||
|
||||
@@ -0,0 +1,72 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { detectServerRuntimeEnvironment } from "./runtimeEnvironment";
|
||||
|
||||
describe("detectServerRuntimeEnvironment", () => {
|
||||
it("detects native windows mode", () => {
|
||||
expect(
|
||||
detectServerRuntimeEnvironment({
|
||||
platform: "win32",
|
||||
env: {},
|
||||
osRelease: "10.0.26100",
|
||||
}),
|
||||
).toEqual({
|
||||
platform: "windows",
|
||||
pathStyle: "windows",
|
||||
isWsl: false,
|
||||
windowsInteropMode: "windows-native",
|
||||
wslDistroName: null,
|
||||
});
|
||||
});
|
||||
|
||||
it("detects wsl-hosted mode from environment variables", () => {
|
||||
expect(
|
||||
detectServerRuntimeEnvironment({
|
||||
platform: "linux",
|
||||
env: {
|
||||
WSL_DISTRO_NAME: "Ubuntu-24.04",
|
||||
WSL_INTEROP: "/run/WSL/123_interop",
|
||||
},
|
||||
osRelease: "6.6.87.2-microsoft-standard-WSL2",
|
||||
}),
|
||||
).toEqual({
|
||||
platform: "linux",
|
||||
pathStyle: "posix",
|
||||
isWsl: true,
|
||||
windowsInteropMode: "wsl-hosted",
|
||||
wslDistroName: "Ubuntu-24.04",
|
||||
});
|
||||
});
|
||||
|
||||
it("detects wsl-hosted mode from os release when env is unavailable", () => {
|
||||
expect(
|
||||
detectServerRuntimeEnvironment({
|
||||
platform: "linux",
|
||||
env: {},
|
||||
osRelease: "5.15.167.4-microsoft-standard-WSL2",
|
||||
}),
|
||||
).toEqual({
|
||||
platform: "linux",
|
||||
pathStyle: "posix",
|
||||
isWsl: true,
|
||||
windowsInteropMode: "wsl-hosted",
|
||||
wslDistroName: null,
|
||||
});
|
||||
});
|
||||
|
||||
it("leaves non-wsl posix hosts outside the windows interop modes", () => {
|
||||
expect(
|
||||
detectServerRuntimeEnvironment({
|
||||
platform: "darwin",
|
||||
env: {},
|
||||
osRelease: "24.3.0",
|
||||
}),
|
||||
).toEqual({
|
||||
platform: "macos",
|
||||
pathStyle: "posix",
|
||||
isWsl: false,
|
||||
windowsInteropMode: null,
|
||||
wslDistroName: null,
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,54 @@
|
||||
import os from "node:os";
|
||||
|
||||
import type { ServerRuntimeEnvironment } from "@t3tools/contracts";
|
||||
|
||||
interface DetectServerRuntimeEnvironmentOptions {
|
||||
readonly platform?: NodeJS.Platform;
|
||||
readonly env?: NodeJS.ProcessEnv;
|
||||
readonly osRelease?: string;
|
||||
}
|
||||
|
||||
function normalizePlatform(platform: NodeJS.Platform): ServerRuntimeEnvironment["platform"] {
|
||||
switch (platform) {
|
||||
case "win32":
|
||||
return "windows";
|
||||
case "darwin":
|
||||
return "macos";
|
||||
default:
|
||||
return "linux";
|
||||
}
|
||||
}
|
||||
|
||||
function detectWsl(options: {
|
||||
readonly platform: NodeJS.Platform;
|
||||
readonly env: NodeJS.ProcessEnv;
|
||||
readonly osRelease: string;
|
||||
}): boolean {
|
||||
if (options.platform !== "linux") {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (options.env.WSL_DISTRO_NAME || options.env.WSL_INTEROP) {
|
||||
return true;
|
||||
}
|
||||
|
||||
return options.osRelease.toLowerCase().includes("microsoft");
|
||||
}
|
||||
|
||||
export function detectServerRuntimeEnvironment(
|
||||
options: DetectServerRuntimeEnvironmentOptions = {},
|
||||
): ServerRuntimeEnvironment {
|
||||
const platform = options.platform ?? process.platform;
|
||||
const env = options.env ?? process.env;
|
||||
const osRelease = options.osRelease ?? os.release();
|
||||
const normalizedPlatform = normalizePlatform(platform);
|
||||
const isWsl = detectWsl({ platform, env, osRelease });
|
||||
|
||||
return {
|
||||
platform: normalizedPlatform,
|
||||
pathStyle: normalizedPlatform === "windows" ? "windows" : "posix",
|
||||
isWsl,
|
||||
windowsInteropMode: normalizedPlatform === "windows" ? "windows-native" : isWsl ? "wsl-hosted" : null,
|
||||
wslDistroName: isWsl ? env.WSL_DISTRO_NAME?.trim() || null : null,
|
||||
};
|
||||
}
|
||||
@@ -19,7 +19,6 @@ import { OrchestrationProjectionSnapshotQueryLive } from "./orchestration/Layers
|
||||
import { ProviderRuntimeIngestionLive } from "./orchestration/Layers/ProviderRuntimeIngestion";
|
||||
import { ProviderUnsupportedError } from "./provider/Errors";
|
||||
import { makeCodexAdapterLive } from "./provider/Layers/CodexAdapter";
|
||||
import { makeCursorAdapterLive } from "./provider/Layers/CursorAdapter";
|
||||
import { ProviderAdapterRegistryLive } from "./provider/Layers/ProviderAdapterRegistry";
|
||||
import { makeProviderServiceLive } from "./provider/Layers/ProviderService";
|
||||
import { ProviderSessionDirectoryLive } from "./provider/Layers/ProviderSessionDirectory";
|
||||
@@ -39,7 +38,7 @@ import { NodePtyAdapterLive } from "./terminal/Layers/NodePTY";
|
||||
export function makeServerProviderLayer(): Layer.Layer<
|
||||
ProviderService,
|
||||
ProviderUnsupportedError,
|
||||
SqlClient.SqlClient | ServerConfig | FileSystem.FileSystem
|
||||
SqlClient.SqlClient | ServerConfig | FileSystem.FileSystem | NodeServices.NodeServices
|
||||
> {
|
||||
return Effect.gen(function* () {
|
||||
const { stateDir } = yield* ServerConfig;
|
||||
@@ -57,12 +56,8 @@ export function makeServerProviderLayer(): Layer.Layer<
|
||||
const codexAdapterLayer = makeCodexAdapterLive(
|
||||
nativeEventLogger ? { nativeEventLogger } : undefined,
|
||||
);
|
||||
const cursorAdapterLayer = makeCursorAdapterLive(
|
||||
nativeEventLogger ? { nativeEventLogger } : undefined,
|
||||
);
|
||||
const adapterRegistryLayer = ProviderAdapterRegistryLive.pipe(
|
||||
Layer.provide(codexAdapterLayer),
|
||||
Layer.provide(cursorAdapterLayer),
|
||||
Layer.provideMerge(providerSessionDirectoryLayer),
|
||||
);
|
||||
return makeProviderServiceLive(
|
||||
|
||||
@@ -1,27 +0,0 @@
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
|
||||
import { Effect, Logger, Option } from "effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
|
||||
import { ServerConfig } from "./config";
|
||||
|
||||
export const ServerLoggerLive = Effect.gen(function* () {
|
||||
const config = yield* Effect.serviceOption(ServerConfig);
|
||||
if (Option.isNone(config)) {
|
||||
return Logger.layer([Logger.defaultLogger]);
|
||||
}
|
||||
|
||||
const logDir = path.join(config.value.stateDir, "logs");
|
||||
const logPath = path.join(logDir, "server.log");
|
||||
|
||||
yield* Effect.sync(() => {
|
||||
fs.mkdirSync(logDir, { recursive: true });
|
||||
});
|
||||
|
||||
const fileLogger = Logger.formatSimple.pipe(Logger.toFile(logPath));
|
||||
|
||||
return Logger.layer([Logger.defaultLogger, fileLogger], {
|
||||
mergeWithExisting: false,
|
||||
});
|
||||
}).pipe(Layer.unwrap);
|
||||
@@ -4,6 +4,7 @@ import path from "node:path";
|
||||
|
||||
import {
|
||||
DEFAULT_TERMINAL_ID,
|
||||
type ServerRuntimeEnvironment,
|
||||
type TerminalEvent,
|
||||
type TerminalOpenInput,
|
||||
} from "@t3tools/contracts";
|
||||
@@ -16,7 +17,11 @@ import {
|
||||
type PtyProcess,
|
||||
type PtySpawnInput,
|
||||
} from "../Services/PTY";
|
||||
import { TerminalManagerRuntime } from "./Manager";
|
||||
import {
|
||||
resolveShellCandidates,
|
||||
TerminalManagerRuntime,
|
||||
validateTerminalCwdForRuntime,
|
||||
} from "./Manager";
|
||||
import { Effect, Encoding } from "effect";
|
||||
|
||||
class FakePtyProcess implements PtyProcess {
|
||||
@@ -172,6 +177,7 @@ describe("TerminalManager", () => {
|
||||
options: {
|
||||
shellResolver?: () => string;
|
||||
subprocessChecker?: (terminalPid: number) => Promise<boolean>;
|
||||
runtimeEnvironment?: ServerRuntimeEnvironment;
|
||||
subprocessPollIntervalMs?: number;
|
||||
processKillGraceMs?: number;
|
||||
maxRetainedInactiveSessions?: number;
|
||||
@@ -186,6 +192,7 @@ describe("TerminalManager", () => {
|
||||
ptyAdapter,
|
||||
historyLineLimit,
|
||||
shellResolver: options.shellResolver ?? (() => "/bin/bash"),
|
||||
...(options.runtimeEnvironment ? { runtimeEnvironment: options.runtimeEnvironment } : {}),
|
||||
...(options.subprocessChecker ? { subprocessChecker: options.subprocessChecker } : {}),
|
||||
...(options.subprocessPollIntervalMs
|
||||
? { subprocessPollIntervalMs: options.subprocessPollIntervalMs }
|
||||
@@ -669,4 +676,93 @@ describe("TerminalManager", () => {
|
||||
|
||||
manager.dispose();
|
||||
});
|
||||
|
||||
it("resolves Windows shell candidates from runtime environment instead of host assumptions", () => {
|
||||
const runtimeEnvironment: ServerRuntimeEnvironment = {
|
||||
platform: "windows",
|
||||
pathStyle: "windows",
|
||||
isWsl: false,
|
||||
windowsInteropMode: "windows-native",
|
||||
wslDistroName: null,
|
||||
};
|
||||
|
||||
const candidates = resolveShellCandidates(() => "/bin/bash -l", runtimeEnvironment);
|
||||
|
||||
expect(candidates.map((candidate) => candidate.shell)).toContain("cmd.exe");
|
||||
expect(candidates.map((candidate) => candidate.shell)).toContain("powershell.exe");
|
||||
expect(candidates.map((candidate) => candidate.shell)).not.toContain("/bin/sh");
|
||||
});
|
||||
|
||||
it("resolves POSIX shell candidates for wsl-hosted runtime even when the requested shell is Windows-style", () => {
|
||||
const runtimeEnvironment: ServerRuntimeEnvironment = {
|
||||
platform: "linux",
|
||||
pathStyle: "posix",
|
||||
isWsl: true,
|
||||
windowsInteropMode: "wsl-hosted",
|
||||
wslDistroName: "Ubuntu",
|
||||
};
|
||||
|
||||
const candidates = resolveShellCandidates(() => "powershell.exe", runtimeEnvironment);
|
||||
|
||||
expect(candidates.map((candidate) => candidate.shell)).toContain("powershell.exe");
|
||||
expect(candidates.map((candidate) => candidate.shell)).toContain("/bin/bash");
|
||||
expect(candidates.map((candidate) => candidate.shell)).toContain("sh");
|
||||
});
|
||||
|
||||
it("rejects POSIX cwd values for windows-native terminal runtimes", async () => {
|
||||
const runtimeEnvironment: ServerRuntimeEnvironment = {
|
||||
platform: "windows",
|
||||
pathStyle: "windows",
|
||||
isWsl: false,
|
||||
windowsInteropMode: "windows-native",
|
||||
wslDistroName: null,
|
||||
};
|
||||
const { manager, ptyAdapter } = makeManager(5, { runtimeEnvironment });
|
||||
|
||||
await expect(manager.open(openInput({ cwd: "/home/julius/project" }))).rejects.toThrow(
|
||||
"Terminal cwd does not match Windows runtime path style",
|
||||
);
|
||||
expect(ptyAdapter.spawnInputs).toHaveLength(0);
|
||||
|
||||
manager.dispose();
|
||||
});
|
||||
|
||||
it("rejects Windows cwd values for wsl-hosted terminal runtimes", async () => {
|
||||
const runtimeEnvironment: ServerRuntimeEnvironment = {
|
||||
platform: "linux",
|
||||
pathStyle: "posix",
|
||||
isWsl: true,
|
||||
windowsInteropMode: "wsl-hosted",
|
||||
wslDistroName: "Ubuntu",
|
||||
};
|
||||
const { manager, ptyAdapter } = makeManager(5, { runtimeEnvironment });
|
||||
|
||||
await expect(manager.open(openInput({ cwd: "C:\\Users\\julius\\project" }))).rejects.toThrow(
|
||||
"Terminal cwd does not match POSIX runtime path style",
|
||||
);
|
||||
expect(ptyAdapter.spawnInputs).toHaveLength(0);
|
||||
|
||||
manager.dispose();
|
||||
});
|
||||
|
||||
it("validates cwd compatibility as a pure runtime helper", () => {
|
||||
expect(
|
||||
validateTerminalCwdForRuntime("/repo", {
|
||||
platform: "linux",
|
||||
pathStyle: "posix",
|
||||
isWsl: true,
|
||||
windowsInteropMode: "wsl-hosted",
|
||||
wslDistroName: "Ubuntu",
|
||||
}),
|
||||
).toBeNull();
|
||||
expect(
|
||||
validateTerminalCwdForRuntime("\\\\wsl.localhost\\Ubuntu\\repo", {
|
||||
platform: "linux",
|
||||
pathStyle: "posix",
|
||||
isWsl: true,
|
||||
windowsInteropMode: "wsl-hosted",
|
||||
wslDistroName: "Ubuntu",
|
||||
}),
|
||||
).toContain("POSIX runtime path style");
|
||||
});
|
||||
});
|
||||
@@ -9,12 +9,14 @@ import {
|
||||
TerminalOpenInput,
|
||||
TerminalResizeInput,
|
||||
TerminalWriteInput,
|
||||
type ServerRuntimeEnvironment,
|
||||
type TerminalEvent,
|
||||
type TerminalSessionSnapshot,
|
||||
} from "@t3tools/contracts";
|
||||
import { Effect, Encoding, Layer, Path, Schema } from "effect";
|
||||
|
||||
import { createLogger } from "../../logger";
|
||||
import { detectServerRuntimeEnvironment } from "../../runtimeEnvironment";
|
||||
import { PtyAdapter, PtyAdapterShape, type PtyExitEvent, type PtyProcess } from "../Services/PTY";
|
||||
import { runProcess } from "../../processRunner";
|
||||
import { ServerConfig } from "../../config";
|
||||
@@ -35,6 +37,8 @@ const DEFAULT_MAX_RETAINED_INACTIVE_SESSIONS = 128;
|
||||
const DEFAULT_OPEN_COLS = 120;
|
||||
const DEFAULT_OPEN_ROWS = 30;
|
||||
const TERMINAL_ENV_BLOCKLIST = new Set(["PORT", "ELECTRON_RENDERER_PORT", "ELECTRON_RUN_AS_NODE"]);
|
||||
const WINDOWS_ABSOLUTE_PATH_PATTERN = /^[A-Za-z]:[\\/]/;
|
||||
const WINDOWS_UNC_PATH_PATTERN = /^\\\\/;
|
||||
|
||||
const decodeTerminalOpenInput = Schema.decodeUnknownSync(TerminalOpenInput);
|
||||
const decodeTerminalWriteInput = Schema.decodeUnknownSync(TerminalWriteInput);
|
||||
@@ -44,19 +48,22 @@ const decodeTerminalCloseInput = Schema.decodeUnknownSync(TerminalCloseInput);
|
||||
|
||||
type TerminalSubprocessChecker = (terminalPid: number) => Promise<boolean>;
|
||||
|
||||
function defaultShellResolver(): string {
|
||||
if (process.platform === "win32") {
|
||||
function defaultShellResolver(runtimeEnvironment: ServerRuntimeEnvironment): string {
|
||||
if (runtimeEnvironment.platform === "windows") {
|
||||
return process.env.ComSpec ?? "cmd.exe";
|
||||
}
|
||||
return process.env.SHELL ?? "bash";
|
||||
}
|
||||
|
||||
function normalizeShellCommand(value: string | undefined): string | null {
|
||||
function normalizeShellCommand(
|
||||
value: string | undefined,
|
||||
runtimeEnvironment: ServerRuntimeEnvironment,
|
||||
): string | null {
|
||||
if (!value) return null;
|
||||
const trimmed = value.trim();
|
||||
if (trimmed.length === 0) return null;
|
||||
|
||||
if (process.platform === "win32") {
|
||||
if (runtimeEnvironment.platform === "windows") {
|
||||
return trimmed;
|
||||
}
|
||||
|
||||
@@ -65,10 +72,13 @@ function normalizeShellCommand(value: string | undefined): string | null {
|
||||
return firstToken.replace(/^['"]|['"]$/g, "");
|
||||
}
|
||||
|
||||
function shellCandidateFromCommand(command: string | null): ShellCandidate | null {
|
||||
function shellCandidateFromCommand(
|
||||
command: string | null,
|
||||
runtimeEnvironment: ServerRuntimeEnvironment,
|
||||
): ShellCandidate | null {
|
||||
if (!command || command.length === 0) return null;
|
||||
const shellName = path.basename(command).toLowerCase();
|
||||
if (process.platform !== "win32" && shellName === "zsh") {
|
||||
if (runtimeEnvironment.platform !== "windows" && shellName === "zsh") {
|
||||
return { shell: command, args: ["-o", "nopromptsp"] };
|
||||
}
|
||||
return { shell: command };
|
||||
@@ -92,27 +102,36 @@ function uniqueShellCandidates(candidates: Array<ShellCandidate | null>): ShellC
|
||||
return ordered;
|
||||
}
|
||||
|
||||
function resolveShellCandidates(shellResolver: () => string): ShellCandidate[] {
|
||||
const requested = shellCandidateFromCommand(normalizeShellCommand(shellResolver()));
|
||||
export function resolveShellCandidates(
|
||||
shellResolver: () => string,
|
||||
runtimeEnvironment: ServerRuntimeEnvironment = detectServerRuntimeEnvironment(),
|
||||
): ShellCandidate[] {
|
||||
const requested = shellCandidateFromCommand(
|
||||
normalizeShellCommand(shellResolver(), runtimeEnvironment),
|
||||
runtimeEnvironment,
|
||||
);
|
||||
|
||||
if (process.platform === "win32") {
|
||||
if (runtimeEnvironment.platform === "windows") {
|
||||
return uniqueShellCandidates([
|
||||
requested,
|
||||
shellCandidateFromCommand(process.env.ComSpec ?? null),
|
||||
shellCandidateFromCommand("powershell.exe"),
|
||||
shellCandidateFromCommand("cmd.exe"),
|
||||
shellCandidateFromCommand(process.env.ComSpec ?? null, runtimeEnvironment),
|
||||
shellCandidateFromCommand("powershell.exe", runtimeEnvironment),
|
||||
shellCandidateFromCommand("cmd.exe", runtimeEnvironment),
|
||||
]);
|
||||
}
|
||||
|
||||
return uniqueShellCandidates([
|
||||
requested,
|
||||
shellCandidateFromCommand(normalizeShellCommand(process.env.SHELL)),
|
||||
shellCandidateFromCommand("/bin/zsh"),
|
||||
shellCandidateFromCommand("/bin/bash"),
|
||||
shellCandidateFromCommand("/bin/sh"),
|
||||
shellCandidateFromCommand("zsh"),
|
||||
shellCandidateFromCommand("bash"),
|
||||
shellCandidateFromCommand("sh"),
|
||||
shellCandidateFromCommand(
|
||||
normalizeShellCommand(process.env.SHELL, runtimeEnvironment),
|
||||
runtimeEnvironment,
|
||||
),
|
||||
shellCandidateFromCommand("/bin/zsh", runtimeEnvironment),
|
||||
shellCandidateFromCommand("/bin/bash", runtimeEnvironment),
|
||||
shellCandidateFromCommand("/bin/sh", runtimeEnvironment),
|
||||
shellCandidateFromCommand("zsh", runtimeEnvironment),
|
||||
shellCandidateFromCommand("bash", runtimeEnvironment),
|
||||
shellCandidateFromCommand("sh", runtimeEnvironment),
|
||||
]);
|
||||
}
|
||||
|
||||
@@ -178,6 +197,13 @@ async function checkWindowsSubprocessActivity(terminalPid: number): Promise<bool
|
||||
allowNonZeroExit: true,
|
||||
maxBufferBytes: 32_768,
|
||||
outputMode: "truncate",
|
||||
runtimeEnvironment: {
|
||||
platform: "windows",
|
||||
pathStyle: "windows",
|
||||
isWsl: false,
|
||||
windowsInteropMode: "windows-native",
|
||||
wslDistroName: null,
|
||||
},
|
||||
},
|
||||
);
|
||||
return result.code === 0;
|
||||
@@ -230,14 +256,37 @@ async function checkPosixSubprocessActivity(terminalPid: number): Promise<boolea
|
||||
}
|
||||
}
|
||||
|
||||
async function defaultSubprocessChecker(terminalPid: number): Promise<boolean> {
|
||||
if (!Number.isInteger(terminalPid) || terminalPid <= 0) {
|
||||
return false;
|
||||
function createDefaultSubprocessChecker(runtimeEnvironment: ServerRuntimeEnvironment) {
|
||||
return async (terminalPid: number): Promise<boolean> => {
|
||||
if (!Number.isInteger(terminalPid) || terminalPid <= 0) {
|
||||
return false;
|
||||
}
|
||||
if (runtimeEnvironment.platform === "windows") {
|
||||
return checkWindowsSubprocessActivity(terminalPid);
|
||||
}
|
||||
return checkPosixSubprocessActivity(terminalPid);
|
||||
};
|
||||
}
|
||||
|
||||
function isWindowsPath(value: string): boolean {
|
||||
return WINDOWS_ABSOLUTE_PATH_PATTERN.test(value) || WINDOWS_UNC_PATH_PATTERN.test(value);
|
||||
}
|
||||
|
||||
export function validateTerminalCwdForRuntime(
|
||||
cwd: string,
|
||||
runtimeEnvironment: ServerRuntimeEnvironment = detectServerRuntimeEnvironment(),
|
||||
): string | null {
|
||||
if (runtimeEnvironment.pathStyle === "windows") {
|
||||
if (cwd.startsWith("/")) {
|
||||
return `Terminal cwd does not match Windows runtime path style: ${cwd}`;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
if (process.platform === "win32") {
|
||||
return checkWindowsSubprocessActivity(terminalPid);
|
||||
|
||||
if (isWindowsPath(cwd)) {
|
||||
return `Terminal cwd does not match POSIX runtime path style: ${cwd}`;
|
||||
}
|
||||
return checkPosixSubprocessActivity(terminalPid);
|
||||
return null;
|
||||
}
|
||||
|
||||
function capHistory(history: string, maxLines: number): string {
|
||||
@@ -316,6 +365,7 @@ interface TerminalManagerOptions {
|
||||
ptyAdapter: PtyAdapterShape;
|
||||
shellResolver?: () => string;
|
||||
subprocessChecker?: TerminalSubprocessChecker;
|
||||
runtimeEnvironment?: ServerRuntimeEnvironment;
|
||||
subprocessPollIntervalMs?: number;
|
||||
processKillGraceMs?: number;
|
||||
maxRetainedInactiveSessions?: number;
|
||||
@@ -333,6 +383,7 @@ export class TerminalManagerRuntime extends EventEmitter<TerminalManagerEvents>
|
||||
private readonly threadLocks = new Map<string, Promise<void>>();
|
||||
private readonly persistDebounceMs: number;
|
||||
private readonly subprocessChecker: TerminalSubprocessChecker;
|
||||
private readonly runtimeEnvironment: ServerRuntimeEnvironment;
|
||||
private readonly subprocessPollIntervalMs: number;
|
||||
private readonly processKillGraceMs: number;
|
||||
private readonly maxRetainedInactiveSessions: number;
|
||||
@@ -343,12 +394,15 @@ export class TerminalManagerRuntime extends EventEmitter<TerminalManagerEvents>
|
||||
|
||||
constructor(options: TerminalManagerOptions) {
|
||||
super();
|
||||
this.runtimeEnvironment = options.runtimeEnvironment ?? detectServerRuntimeEnvironment();
|
||||
this.logsDir = options.logsDir ?? path.resolve(process.cwd(), ".logs", "terminals");
|
||||
this.historyLineLimit = options.historyLineLimit ?? DEFAULT_HISTORY_LINE_LIMIT;
|
||||
this.ptyAdapter = options.ptyAdapter;
|
||||
this.shellResolver = options.shellResolver ?? defaultShellResolver;
|
||||
this.shellResolver =
|
||||
options.shellResolver ?? (() => defaultShellResolver(this.runtimeEnvironment));
|
||||
this.persistDebounceMs = DEFAULT_PERSIST_DEBOUNCE_MS;
|
||||
this.subprocessChecker = options.subprocessChecker ?? defaultSubprocessChecker;
|
||||
this.subprocessChecker =
|
||||
options.subprocessChecker ?? createDefaultSubprocessChecker(this.runtimeEnvironment);
|
||||
this.subprocessPollIntervalMs =
|
||||
options.subprocessPollIntervalMs ?? DEFAULT_SUBPROCESS_POLL_INTERVAL_MS;
|
||||
this.processKillGraceMs = options.processKillGraceMs ?? DEFAULT_PROCESS_KILL_GRACE_MS;
|
||||
@@ -589,7 +643,7 @@ export class TerminalManagerRuntime extends EventEmitter<TerminalManagerEvents>
|
||||
let ptyProcess: PtyProcess | null = null;
|
||||
let startedShell: string | null = null;
|
||||
try {
|
||||
const shellCandidates = resolveShellCandidates(this.shellResolver);
|
||||
const shellCandidates = resolveShellCandidates(this.shellResolver, this.runtimeEnvironment);
|
||||
const terminalEnv = createTerminalSpawnEnv(process.env, session.runtimeEnv);
|
||||
let lastSpawnError: unknown = null;
|
||||
|
||||
@@ -1051,6 +1105,11 @@ export class TerminalManagerRuntime extends EventEmitter<TerminalManagerEvents>
|
||||
}
|
||||
|
||||
private async assertValidCwd(cwd: string): Promise<void> {
|
||||
const runtimePathError = validateTerminalCwdForRuntime(cwd, this.runtimeEnvironment);
|
||||
if (runtimePathError) {
|
||||
throw new Error(runtimePathError);
|
||||
}
|
||||
|
||||
let stats: fs.Stats;
|
||||
try {
|
||||
stats = await fs.promises.stat(cwd);
|
||||
@@ -1173,10 +1232,11 @@ export const TerminalManagerLive = Layer.effect(
|
||||
const { stateDir } = yield* ServerConfig;
|
||||
const { join } = yield* Path.Path;
|
||||
const logsDir = join(stateDir, "logs", "terminals");
|
||||
const runtimeEnvironment = detectServerRuntimeEnvironment();
|
||||
|
||||
const ptyAdapter = yield* PtyAdapter;
|
||||
const runtime = yield* Effect.acquireRelease(
|
||||
Effect.sync(() => new TerminalManagerRuntime({ logsDir, ptyAdapter })),
|
||||
Effect.sync(() => new TerminalManagerRuntime({ logsDir, ptyAdapter, runtimeEnvironment })),
|
||||
(r) => Effect.sync(() => r.dispose()),
|
||||
);
|
||||
|
||||
|
||||
@@ -18,8 +18,9 @@ import {
|
||||
ORCHESTRATION_WS_CHANNELS,
|
||||
ORCHESTRATION_WS_METHODS,
|
||||
ProviderItemId,
|
||||
ThreadId,
|
||||
TurnId,
|
||||
ProviderSessionId,
|
||||
ProviderThreadId,
|
||||
ProviderTurnId,
|
||||
WS_CHANNELS,
|
||||
WS_METHODS,
|
||||
type WebSocketResponse,
|
||||
@@ -50,6 +51,7 @@ import type { GitCoreShape } from "./git/Services/GitCore.ts";
|
||||
import { GitCore } from "./git/Services/GitCore.ts";
|
||||
import { GitCommandError, GitManagerError } from "./git/Errors.ts";
|
||||
import { MigrationError } from "@effect/sql-sqlite-bun/SqliteMigrator";
|
||||
import { detectServerRuntimeEnvironment } from "./runtimeEnvironment";
|
||||
|
||||
interface PendingMessages {
|
||||
queue: unknown[];
|
||||
@@ -59,9 +61,11 @@ interface PendingMessages {
|
||||
const pendingBySocket = new WeakMap<WebSocket, PendingMessages>();
|
||||
|
||||
const asEventId = (value: string): EventId => EventId.makeUnsafe(value);
|
||||
const asProviderSessionId = (value: string): ProviderSessionId =>
|
||||
ProviderSessionId.makeUnsafe(value);
|
||||
const asProviderThreadId = (value: string): ProviderThreadId => ProviderThreadId.makeUnsafe(value);
|
||||
const asProviderTurnId = (value: string): ProviderTurnId => ProviderTurnId.makeUnsafe(value);
|
||||
const asProviderItemId = (value: string): ProviderItemId => ProviderItemId.makeUnsafe(value);
|
||||
const asThreadId = (value: string): ThreadId => ThreadId.makeUnsafe(value);
|
||||
const asTurnId = (value: string): TurnId => TurnId.makeUnsafe(value);
|
||||
|
||||
const defaultOpenService: OpenShape = {
|
||||
openBrowser: () => Effect.void,
|
||||
@@ -82,6 +86,8 @@ const defaultProviderHealthService: ProviderHealthShape = {
|
||||
getStatuses: Effect.succeed(defaultProviderStatuses),
|
||||
};
|
||||
|
||||
const defaultRuntimeEnvironment = detectServerRuntimeEnvironment();
|
||||
|
||||
class MockTerminalManager implements TerminalManagerShape {
|
||||
private readonly sessions = new Map<string, TerminalSessionSnapshot>();
|
||||
private readonly listeners = new Set<(event: TerminalEvent) => void>();
|
||||
@@ -757,6 +763,7 @@ describe("WebSocket Server", () => {
|
||||
issues: [],
|
||||
providers: defaultProviderStatuses,
|
||||
availableEditors: expect.any(Array),
|
||||
runtimeEnvironment: defaultRuntimeEnvironment,
|
||||
});
|
||||
expectAvailableEditors((response.result as { availableEditors: unknown }).availableEditors);
|
||||
});
|
||||
@@ -783,6 +790,7 @@ describe("WebSocket Server", () => {
|
||||
issues: [],
|
||||
providers: defaultProviderStatuses,
|
||||
availableEditors: expect.any(Array),
|
||||
runtimeEnvironment: defaultRuntimeEnvironment,
|
||||
});
|
||||
expectAvailableEditors((response.result as { availableEditors: unknown }).availableEditors);
|
||||
|
||||
@@ -819,6 +827,7 @@ describe("WebSocket Server", () => {
|
||||
],
|
||||
providers: defaultProviderStatuses,
|
||||
availableEditors: expect.any(Array),
|
||||
runtimeEnvironment: defaultRuntimeEnvironment,
|
||||
});
|
||||
expectAvailableEditors((response.result as { availableEditors: unknown }).availableEditors);
|
||||
expect(fs.readFileSync(keybindingsPath, "utf8")).toBe("{ not-json");
|
||||
@@ -854,6 +863,7 @@ describe("WebSocket Server", () => {
|
||||
issues: Array<{ kind: string; index?: number; message: string }>;
|
||||
providers: ReadonlyArray<ServerProviderStatus>;
|
||||
availableEditors: unknown;
|
||||
runtimeEnvironment: unknown;
|
||||
};
|
||||
expect(result.cwd).toBe("/my/workspace");
|
||||
expect(result.keybindingsConfigPath).toBe(keybindingsPath);
|
||||
@@ -874,6 +884,7 @@ describe("WebSocket Server", () => {
|
||||
expect(result.keybindings.some((entry) => entry.command === "terminal.new")).toBe(true);
|
||||
expect(result.providers).toEqual(defaultProviderStatuses);
|
||||
expectAvailableEditors(result.availableEditors);
|
||||
expect(result.runtimeEnvironment).toEqual(defaultRuntimeEnvironment);
|
||||
});
|
||||
|
||||
it("pushes server.configUpdated issues when keybindings file changes", async () => {
|
||||
@@ -974,6 +985,7 @@ describe("WebSocket Server", () => {
|
||||
issues: [],
|
||||
providers: defaultProviderStatuses,
|
||||
availableEditors: expect.any(Array),
|
||||
runtimeEnvironment: defaultRuntimeEnvironment,
|
||||
});
|
||||
expectAvailableEditors((response.result as { availableEditors: unknown }).availableEditors);
|
||||
});
|
||||
@@ -1022,6 +1034,7 @@ describe("WebSocket Server", () => {
|
||||
issues: [],
|
||||
providers: defaultProviderStatuses,
|
||||
availableEditors: expect.any(Array),
|
||||
runtimeEnvironment: defaultRuntimeEnvironment,
|
||||
});
|
||||
expectAvailableEditors(
|
||||
(configResponse.result as { availableEditors: unknown }).availableEditors,
|
||||
@@ -1126,8 +1139,6 @@ describe("WebSocket Server", () => {
|
||||
projectId: "project-diff",
|
||||
title: "Diff Thread",
|
||||
model: "gpt-5-codex",
|
||||
runtimeMode: "full-access",
|
||||
interactionMode: "default",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
createdAt,
|
||||
@@ -1145,31 +1156,30 @@ describe("WebSocket Server", () => {
|
||||
|
||||
it("keeps orchestration domain push behavior for provider runtime events", async () => {
|
||||
const runtimeEventPubSub = Effect.runSync(PubSub.unbounded<ProviderRuntimeEvent>());
|
||||
const sessionId = asProviderSessionId("sess-test");
|
||||
const emitRuntimeEvent = (event: ProviderRuntimeEvent) => {
|
||||
Effect.runSync(PubSub.publish(runtimeEventPubSub, event));
|
||||
};
|
||||
const unsupported = () => Effect.die(new Error("Unsupported provider call in test")) as never;
|
||||
const providerService: ProviderServiceShape = {
|
||||
startSession: (threadId) =>
|
||||
startSession: () =>
|
||||
Effect.succeed({
|
||||
sessionId,
|
||||
provider: "codex",
|
||||
status: "ready",
|
||||
runtimeMode: "full-access",
|
||||
threadId,
|
||||
threadId: asProviderThreadId("provider-thread-1"),
|
||||
createdAt: new Date().toISOString(),
|
||||
updatedAt: new Date().toISOString(),
|
||||
}),
|
||||
sendTurn: ({ threadId }) =>
|
||||
sendTurn: () =>
|
||||
Effect.succeed({
|
||||
threadId,
|
||||
turnId: asTurnId("provider-turn-1"),
|
||||
threadId: asProviderThreadId("provider-thread-1"),
|
||||
turnId: asProviderTurnId("provider-turn-1"),
|
||||
}),
|
||||
interruptTurn: () => unsupported(),
|
||||
respondToRequest: () => unsupported(),
|
||||
respondToUserInput: () => unsupported(),
|
||||
stopSession: () => unsupported(),
|
||||
listSessions: () => Effect.succeed([]),
|
||||
getCapabilities: () => Effect.succeed({ sessionModelSwitch: "in-session" }),
|
||||
rollbackConversation: () => unsupported(),
|
||||
stopAll: () => Effect.void,
|
||||
streamEvents: Stream.fromPubSub(runtimeEventPubSub),
|
||||
@@ -1205,8 +1215,6 @@ describe("WebSocket Server", () => {
|
||||
projectId: "project-1",
|
||||
title: "Thread 1",
|
||||
model: "gpt-5-codex",
|
||||
runtimeMode: "full-access",
|
||||
interactionMode: "default",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
createdAt,
|
||||
@@ -1224,8 +1232,8 @@ describe("WebSocket Server", () => {
|
||||
attachments: [],
|
||||
},
|
||||
assistantDeliveryMode: "streaming",
|
||||
runtimeMode: "approval-required",
|
||||
interactionMode: "default",
|
||||
approvalPolicy: "on-request",
|
||||
sandboxMode: "workspace-write",
|
||||
createdAt,
|
||||
});
|
||||
expect(startTurnResponse.error).toBeUndefined();
|
||||
@@ -1235,21 +1243,16 @@ describe("WebSocket Server", () => {
|
||||
return event.type === "thread.session-set";
|
||||
});
|
||||
|
||||
emitRuntimeEvent(
|
||||
{
|
||||
type: "content.delta",
|
||||
eventId: asEventId("evt-ws-runtime-message-delta"),
|
||||
provider: "codex",
|
||||
threadId: asThreadId("thread-1"),
|
||||
createdAt: new Date().toISOString(),
|
||||
turnId: asTurnId("turn-1"),
|
||||
itemId: asProviderItemId("item-1"),
|
||||
payload: {
|
||||
streamKind: "assistant_text",
|
||||
delta: "hello from runtime",
|
||||
},
|
||||
} as unknown as ProviderRuntimeEvent,
|
||||
);
|
||||
emitRuntimeEvent({
|
||||
type: "message.delta",
|
||||
eventId: asEventId("evt-ws-runtime-message-delta"),
|
||||
provider: "codex",
|
||||
sessionId,
|
||||
createdAt: new Date().toISOString(),
|
||||
turnId: asProviderTurnId("turn-1"),
|
||||
itemId: asProviderItemId("item-1"),
|
||||
delta: "hello from runtime",
|
||||
});
|
||||
|
||||
const domainPush = await waitForPush(ws, ORCHESTRATION_WS_CHANNELS.domainEvent, (push) => {
|
||||
const event = push.data as { type?: string; payload?: { messageId?: string; text?: string } };
|
||||
@@ -1525,54 +1528,6 @@ describe("WebSocket Server", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it("supports projects.writeFile within the workspace root", async () => {
|
||||
const workspace = makeTempDir("t3code-ws-write-file-");
|
||||
|
||||
server = await createTestServer({ cwd: "/test" });
|
||||
const addr = server.address();
|
||||
const port = typeof addr === "object" && addr !== null ? addr.port : 0;
|
||||
|
||||
const ws = await connectWs(port);
|
||||
connections.push(ws);
|
||||
await waitForMessage(ws);
|
||||
|
||||
const response = await sendRequest(ws, WS_METHODS.projectsWriteFile, {
|
||||
cwd: workspace,
|
||||
relativePath: "plans/effect-rpc.md",
|
||||
contents: "# Plan\n\n- step 1\n",
|
||||
});
|
||||
|
||||
expect(response.error).toBeUndefined();
|
||||
expect(response.result).toEqual({
|
||||
relativePath: "plans/effect-rpc.md",
|
||||
});
|
||||
expect(fs.readFileSync(path.join(workspace, "plans", "effect-rpc.md"), "utf8")).toBe(
|
||||
"# Plan\n\n- step 1\n",
|
||||
);
|
||||
});
|
||||
|
||||
it("rejects projects.writeFile paths outside the workspace root", async () => {
|
||||
const workspace = makeTempDir("t3code-ws-write-file-reject-");
|
||||
|
||||
server = await createTestServer({ cwd: "/test" });
|
||||
const addr = server.address();
|
||||
const port = typeof addr === "object" && addr !== null ? addr.port : 0;
|
||||
|
||||
const ws = await connectWs(port);
|
||||
connections.push(ws);
|
||||
await waitForMessage(ws);
|
||||
|
||||
const response = await sendRequest(ws, WS_METHODS.projectsWriteFile, {
|
||||
cwd: workspace,
|
||||
relativePath: "../escape.md",
|
||||
contents: "# no\n",
|
||||
});
|
||||
|
||||
expect(response.result).toBeUndefined();
|
||||
expect(response.error?.message).toContain("Workspace file path must stay within the project root.");
|
||||
expect(fs.existsSync(path.join(workspace, "..", "escape.md"))).toBe(false);
|
||||
});
|
||||
|
||||
it("routes git core methods over websocket", async () => {
|
||||
const listBranches = vi.fn(() =>
|
||||
Effect.succeed({
|
||||
|
||||
+33
-103
@@ -12,7 +12,6 @@ import type { Duplex } from "node:stream";
|
||||
import Mime from "@effect/platform-node/Mime";
|
||||
import {
|
||||
CommandId,
|
||||
DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
type ClientOrchestrationCommand,
|
||||
type OrchestrationCommand,
|
||||
ORCHESTRATION_WS_CHANNELS,
|
||||
@@ -60,6 +59,7 @@ import { Open, resolveAvailableEditors } from "./open";
|
||||
import { ServerConfig } from "./config";
|
||||
import { GitCore } from "./git/Services/GitCore.ts";
|
||||
import { tryHandleProjectFaviconRequest } from "./projectFaviconRoute";
|
||||
import { detectServerRuntimeEnvironment } from "./runtimeEnvironment";
|
||||
import {
|
||||
ATTACHMENTS_ROUTE_PREFIX,
|
||||
normalizeAttachmentRelativePath,
|
||||
@@ -147,48 +147,6 @@ function websocketRawToString(raw: unknown): string | null {
|
||||
return null;
|
||||
}
|
||||
|
||||
function toPosixRelativePath(input: string): string {
|
||||
return input.replaceAll("\\", "/");
|
||||
}
|
||||
|
||||
function resolveWorkspaceWritePath(params: {
|
||||
workspaceRoot: string;
|
||||
relativePath: string;
|
||||
path: Path.Path;
|
||||
}): Effect.Effect<{ absolutePath: string; relativePath: string }, RouteRequestError> {
|
||||
const normalizedInputPath = params.relativePath.trim();
|
||||
if (params.path.isAbsolute(normalizedInputPath)) {
|
||||
return Effect.fail(
|
||||
new RouteRequestError({
|
||||
message: "Workspace file path must be relative to the project root.",
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
const absolutePath = params.path.resolve(params.workspaceRoot, normalizedInputPath);
|
||||
const relativeToRoot = toPosixRelativePath(
|
||||
params.path.relative(params.workspaceRoot, absolutePath),
|
||||
);
|
||||
if (
|
||||
relativeToRoot.length === 0 ||
|
||||
relativeToRoot === "." ||
|
||||
relativeToRoot.startsWith("../") ||
|
||||
relativeToRoot === ".." ||
|
||||
params.path.isAbsolute(relativeToRoot)
|
||||
) {
|
||||
return Effect.fail(
|
||||
new RouteRequestError({
|
||||
message: "Workspace file path must stay within the project root.",
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
return Effect.succeed({
|
||||
absolutePath,
|
||||
relativePath: relativeToRoot,
|
||||
});
|
||||
}
|
||||
|
||||
function stripRequestTag<T extends { _tag: string }>(body: T) {
|
||||
return Struct.omit(body, ["_tag"]);
|
||||
}
|
||||
@@ -239,6 +197,7 @@ export const createServer = Effect.fn(function* (): Effect.fn.Return<
|
||||
autoBootstrapProjectFromCwd,
|
||||
} = serverConfig;
|
||||
const availableEditors = resolveAvailableEditors();
|
||||
const runtimeEnvironment = detectServerRuntimeEnvironment();
|
||||
|
||||
const gitManager = yield* GitManager;
|
||||
const terminalManager = yield* TerminalManager;
|
||||
@@ -638,8 +597,6 @@ export const createServer = Effect.fn(function* (): Effect.fn.Return<
|
||||
projectId: bootstrapProjectId,
|
||||
title: "New thread",
|
||||
model: bootstrapProjectDefaultModel,
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "full-access",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
createdAt,
|
||||
@@ -657,33 +614,6 @@ export const createServer = Effect.fn(function* (): Effect.fn.Return<
|
||||
);
|
||||
}
|
||||
|
||||
const runPromise = yield* Effect.map(Effect.services<never>(), Effect.runPromiseWith);
|
||||
yield* Effect.addFinalizer(() =>
|
||||
Effect.catch(liveProviderService.stopAll(), (cause) =>
|
||||
Effect.logWarning("failed to stop provider service", { cause }),
|
||||
),
|
||||
);
|
||||
|
||||
const unsubscribeTerminalEvents = yield* terminalManager.subscribe(
|
||||
(event) => void Effect.runPromise(onTerminalEvent(event)),
|
||||
);
|
||||
yield* Effect.addFinalizer(() => Effect.sync(() => unsubscribeTerminalEvents()));
|
||||
|
||||
yield* NodeHttpServer.make(() => httpServer, listenOptions).pipe(
|
||||
Effect.mapError((cause) => new ServerLifecycleError({ operation: "httpServerListen", cause })),
|
||||
);
|
||||
|
||||
yield* Effect.addFinalizer(() =>
|
||||
Effect.all([
|
||||
closeAllClients,
|
||||
closeWebSocketServer.pipe(
|
||||
Effect.catch((error) =>
|
||||
Effect.logWarning("failed to close web socket server", { cause: error }),
|
||||
),
|
||||
),
|
||||
]),
|
||||
);
|
||||
|
||||
const routeRequest = Effect.fnUntraced(function* (request: WebSocketRequest) {
|
||||
switch (request.body._tag) {
|
||||
case ORCHESTRATION_WS_METHODS.getSnapshot:
|
||||
@@ -728,32 +658,6 @@ export const createServer = Effect.fn(function* (): Effect.fn.Return<
|
||||
});
|
||||
}
|
||||
|
||||
case WS_METHODS.projectsWriteFile: {
|
||||
const body = stripRequestTag(request.body);
|
||||
const target = yield* resolveWorkspaceWritePath({
|
||||
workspaceRoot: body.cwd,
|
||||
relativePath: body.relativePath,
|
||||
path,
|
||||
});
|
||||
yield* fileSystem.makeDirectory(path.dirname(target.absolutePath), { recursive: true }).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new RouteRequestError({
|
||||
message: `Failed to prepare workspace path: ${String(cause)}`,
|
||||
}),
|
||||
),
|
||||
);
|
||||
yield* fileSystem.writeFileString(target.absolutePath, body.contents).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new RouteRequestError({
|
||||
message: `Failed to write workspace file: ${String(cause)}`,
|
||||
}),
|
||||
),
|
||||
);
|
||||
return { relativePath: target.relativePath };
|
||||
}
|
||||
|
||||
case WS_METHODS.shellOpenInEditor: {
|
||||
const body = stripRequestTag(request.body);
|
||||
return yield* openInEditor(body);
|
||||
@@ -843,6 +747,7 @@ export const createServer = Effect.fn(function* (): Effect.fn.Return<
|
||||
issues: keybindingsConfig.issues,
|
||||
providers: providerStatuses,
|
||||
availableEditors,
|
||||
runtimeEnvironment,
|
||||
};
|
||||
|
||||
case WS_METHODS.serverUpsertKeybinding: {
|
||||
@@ -897,7 +802,6 @@ export const createServer = Effect.fn(function* (): Effect.fn.Return<
|
||||
id: request.value.id,
|
||||
result: result.value,
|
||||
});
|
||||
|
||||
ws.send(response);
|
||||
});
|
||||
|
||||
@@ -926,7 +830,7 @@ export const createServer = Effect.fn(function* (): Effect.fn.Return<
|
||||
});
|
||||
|
||||
wss.on("connection", (ws) => {
|
||||
void runPromise(Ref.update(clients, (clients) => clients.add(ws)));
|
||||
void Effect.runPromise(Ref.update(clients, (clients) => clients.add(ws)));
|
||||
|
||||
const segments = cwd.split(/[/\\]/).filter(Boolean);
|
||||
const projectName = segments[segments.length - 1] ?? "project";
|
||||
@@ -945,7 +849,7 @@ export const createServer = Effect.fn(function* (): Effect.fn.Return<
|
||||
ws.send(JSON.stringify(welcome));
|
||||
|
||||
ws.on("message", (raw) => {
|
||||
void runPromise(
|
||||
void Effect.runPromise(
|
||||
handleMessage(ws, raw).pipe(
|
||||
Effect.catch((error) => Effect.logError("Error handling message", error)),
|
||||
),
|
||||
@@ -953,7 +857,7 @@ export const createServer = Effect.fn(function* (): Effect.fn.Return<
|
||||
});
|
||||
|
||||
ws.on("close", () => {
|
||||
void runPromise(
|
||||
void Effect.runPromise(
|
||||
Ref.update(clients, (clients) => {
|
||||
clients.delete(ws);
|
||||
return clients;
|
||||
@@ -962,7 +866,7 @@ export const createServer = Effect.fn(function* (): Effect.fn.Return<
|
||||
});
|
||||
|
||||
ws.on("error", () => {
|
||||
void runPromise(
|
||||
void Effect.runPromise(
|
||||
Ref.update(clients, (clients) => {
|
||||
clients.delete(ws);
|
||||
return clients;
|
||||
@@ -971,6 +875,32 @@ export const createServer = Effect.fn(function* (): Effect.fn.Return<
|
||||
});
|
||||
});
|
||||
|
||||
yield* Effect.addFinalizer(() =>
|
||||
Effect.catch(liveProviderService.stopAll(), (cause) =>
|
||||
Effect.logWarning("failed to stop provider service", { cause }),
|
||||
),
|
||||
);
|
||||
|
||||
const unsubscribeTerminalEvents = yield* terminalManager.subscribe(
|
||||
(event) => void Effect.runPromise(onTerminalEvent(event)),
|
||||
);
|
||||
yield* Effect.addFinalizer(() => Effect.sync(() => unsubscribeTerminalEvents()));
|
||||
|
||||
yield* NodeHttpServer.make(() => httpServer, listenOptions).pipe(
|
||||
Effect.mapError((cause) => new ServerLifecycleError({ operation: "httpServerListen", cause })),
|
||||
);
|
||||
|
||||
yield* Effect.addFinalizer(() =>
|
||||
Effect.all([
|
||||
closeAllClients,
|
||||
closeWebSocketServer.pipe(
|
||||
Effect.catch((error) =>
|
||||
Effect.logWarning("failed to close web socket server", { cause: error }),
|
||||
),
|
||||
),
|
||||
]),
|
||||
);
|
||||
|
||||
return httpServer;
|
||||
});
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@t3tools/web",
|
||||
"version": "0.0.0-alpha.20",
|
||||
"version": "0.0.0-alpha.18",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
@@ -9,9 +9,7 @@
|
||||
"prepare": "effect-language-service patch",
|
||||
"preview": "vite preview",
|
||||
"typecheck": "tsc --noEmit",
|
||||
"test": "vitest run --passWithNoTests",
|
||||
"test:browser": "vitest run --config vitest.browser.config.ts",
|
||||
"test:browser:install": "playwright install --with-deps chromium"
|
||||
"test": "vitest run --passWithNoTests"
|
||||
},
|
||||
"dependencies": {
|
||||
"@base-ui/react": "^1.2.0",
|
||||
@@ -43,14 +41,10 @@
|
||||
"@types/react": "^19.0.0",
|
||||
"@types/react-dom": "^19.0.0",
|
||||
"@vitejs/plugin-react": "^5.1.4",
|
||||
"@vitest/browser-playwright": "^4.0.18",
|
||||
"babel-plugin-react-compiler": "^19.0.0-beta-e552027-20250112",
|
||||
"msw": "^2.12.10",
|
||||
"playwright": "^1.58.2",
|
||||
"tailwindcss": "^4.0.0",
|
||||
"typescript": "catalog:",
|
||||
"vite": "^8.0.0-beta.12",
|
||||
"vitest": "catalog:",
|
||||
"vitest-browser-react": "^2.0.5"
|
||||
"vitest": "catalog:"
|
||||
}
|
||||
}
|
||||
@@ -1,349 +0,0 @@
|
||||
/* eslint-disable */
|
||||
/* tslint:disable */
|
||||
|
||||
/**
|
||||
* Mock Service Worker.
|
||||
* @see https://github.com/mswjs/msw
|
||||
* - Please do NOT modify this file.
|
||||
*/
|
||||
|
||||
const PACKAGE_VERSION = '2.12.10'
|
||||
const INTEGRITY_CHECKSUM = '4db4a41e972cec1b64cc569c66952d82'
|
||||
const IS_MOCKED_RESPONSE = Symbol('isMockedResponse')
|
||||
const activeClientIds = new Set()
|
||||
|
||||
addEventListener('install', function () {
|
||||
self.skipWaiting()
|
||||
})
|
||||
|
||||
addEventListener('activate', function (event) {
|
||||
event.waitUntil(self.clients.claim())
|
||||
})
|
||||
|
||||
addEventListener('message', async function (event) {
|
||||
const clientId = Reflect.get(event.source || {}, 'id')
|
||||
|
||||
if (!clientId || !self.clients) {
|
||||
return
|
||||
}
|
||||
|
||||
const client = await self.clients.get(clientId)
|
||||
|
||||
if (!client) {
|
||||
return
|
||||
}
|
||||
|
||||
const allClients = await self.clients.matchAll({
|
||||
type: 'window',
|
||||
})
|
||||
|
||||
switch (event.data) {
|
||||
case 'KEEPALIVE_REQUEST': {
|
||||
sendToClient(client, {
|
||||
type: 'KEEPALIVE_RESPONSE',
|
||||
})
|
||||
break
|
||||
}
|
||||
|
||||
case 'INTEGRITY_CHECK_REQUEST': {
|
||||
sendToClient(client, {
|
||||
type: 'INTEGRITY_CHECK_RESPONSE',
|
||||
payload: {
|
||||
packageVersion: PACKAGE_VERSION,
|
||||
checksum: INTEGRITY_CHECKSUM,
|
||||
},
|
||||
})
|
||||
break
|
||||
}
|
||||
|
||||
case 'MOCK_ACTIVATE': {
|
||||
activeClientIds.add(clientId)
|
||||
|
||||
sendToClient(client, {
|
||||
type: 'MOCKING_ENABLED',
|
||||
payload: {
|
||||
client: {
|
||||
id: client.id,
|
||||
frameType: client.frameType,
|
||||
},
|
||||
},
|
||||
})
|
||||
break
|
||||
}
|
||||
|
||||
case 'CLIENT_CLOSED': {
|
||||
activeClientIds.delete(clientId)
|
||||
|
||||
const remainingClients = allClients.filter((client) => {
|
||||
return client.id !== clientId
|
||||
})
|
||||
|
||||
// Unregister itself when there are no more clients
|
||||
if (remainingClients.length === 0) {
|
||||
self.registration.unregister()
|
||||
}
|
||||
|
||||
break
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
addEventListener('fetch', function (event) {
|
||||
const requestInterceptedAt = Date.now()
|
||||
|
||||
// Bypass navigation requests.
|
||||
if (event.request.mode === 'navigate') {
|
||||
return
|
||||
}
|
||||
|
||||
// Opening the DevTools triggers the "only-if-cached" request
|
||||
// that cannot be handled by the worker. Bypass such requests.
|
||||
if (
|
||||
event.request.cache === 'only-if-cached' &&
|
||||
event.request.mode !== 'same-origin'
|
||||
) {
|
||||
return
|
||||
}
|
||||
|
||||
// Bypass all requests when there are no active clients.
|
||||
// Prevents the self-unregistered worked from handling requests
|
||||
// after it's been terminated (still remains active until the next reload).
|
||||
if (activeClientIds.size === 0) {
|
||||
return
|
||||
}
|
||||
|
||||
const requestId = crypto.randomUUID()
|
||||
event.respondWith(handleRequest(event, requestId, requestInterceptedAt))
|
||||
})
|
||||
|
||||
/**
|
||||
* @param {FetchEvent} event
|
||||
* @param {string} requestId
|
||||
* @param {number} requestInterceptedAt
|
||||
*/
|
||||
async function handleRequest(event, requestId, requestInterceptedAt) {
|
||||
const client = await resolveMainClient(event)
|
||||
const requestCloneForEvents = event.request.clone()
|
||||
const response = await getResponse(
|
||||
event,
|
||||
client,
|
||||
requestId,
|
||||
requestInterceptedAt,
|
||||
)
|
||||
|
||||
// Send back the response clone for the "response:*" life-cycle events.
|
||||
// Ensure MSW is active and ready to handle the message, otherwise
|
||||
// this message will pend indefinitely.
|
||||
if (client && activeClientIds.has(client.id)) {
|
||||
const serializedRequest = await serializeRequest(requestCloneForEvents)
|
||||
|
||||
// Clone the response so both the client and the library could consume it.
|
||||
const responseClone = response.clone()
|
||||
|
||||
sendToClient(
|
||||
client,
|
||||
{
|
||||
type: 'RESPONSE',
|
||||
payload: {
|
||||
isMockedResponse: IS_MOCKED_RESPONSE in response,
|
||||
request: {
|
||||
id: requestId,
|
||||
...serializedRequest,
|
||||
},
|
||||
response: {
|
||||
type: responseClone.type,
|
||||
status: responseClone.status,
|
||||
statusText: responseClone.statusText,
|
||||
headers: Object.fromEntries(responseClone.headers.entries()),
|
||||
body: responseClone.body,
|
||||
},
|
||||
},
|
||||
},
|
||||
responseClone.body ? [serializedRequest.body, responseClone.body] : [],
|
||||
)
|
||||
}
|
||||
|
||||
return response
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve the main client for the given event.
|
||||
* Client that issues a request doesn't necessarily equal the client
|
||||
* that registered the worker. It's with the latter the worker should
|
||||
* communicate with during the response resolving phase.
|
||||
* @param {FetchEvent} event
|
||||
* @returns {Promise<Client | undefined>}
|
||||
*/
|
||||
async function resolveMainClient(event) {
|
||||
const client = await self.clients.get(event.clientId)
|
||||
|
||||
if (activeClientIds.has(event.clientId)) {
|
||||
return client
|
||||
}
|
||||
|
||||
if (client?.frameType === 'top-level') {
|
||||
return client
|
||||
}
|
||||
|
||||
const allClients = await self.clients.matchAll({
|
||||
type: 'window',
|
||||
})
|
||||
|
||||
return allClients
|
||||
.filter((client) => {
|
||||
// Get only those clients that are currently visible.
|
||||
return client.visibilityState === 'visible'
|
||||
})
|
||||
.find((client) => {
|
||||
// Find the client ID that's recorded in the
|
||||
// set of clients that have registered the worker.
|
||||
return activeClientIds.has(client.id)
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {FetchEvent} event
|
||||
* @param {Client | undefined} client
|
||||
* @param {string} requestId
|
||||
* @param {number} requestInterceptedAt
|
||||
* @returns {Promise<Response>}
|
||||
*/
|
||||
async function getResponse(event, client, requestId, requestInterceptedAt) {
|
||||
// Clone the request because it might've been already used
|
||||
// (i.e. its body has been read and sent to the client).
|
||||
const requestClone = event.request.clone()
|
||||
|
||||
function passthrough() {
|
||||
// Cast the request headers to a new Headers instance
|
||||
// so the headers can be manipulated with.
|
||||
const headers = new Headers(requestClone.headers)
|
||||
|
||||
// Remove the "accept" header value that marked this request as passthrough.
|
||||
// This prevents request alteration and also keeps it compliant with the
|
||||
// user-defined CORS policies.
|
||||
const acceptHeader = headers.get('accept')
|
||||
if (acceptHeader) {
|
||||
const values = acceptHeader.split(',').map((value) => value.trim())
|
||||
const filteredValues = values.filter(
|
||||
(value) => value !== 'msw/passthrough',
|
||||
)
|
||||
|
||||
if (filteredValues.length > 0) {
|
||||
headers.set('accept', filteredValues.join(', '))
|
||||
} else {
|
||||
headers.delete('accept')
|
||||
}
|
||||
}
|
||||
|
||||
return fetch(requestClone, { headers })
|
||||
}
|
||||
|
||||
// Bypass mocking when the client is not active.
|
||||
if (!client) {
|
||||
return passthrough()
|
||||
}
|
||||
|
||||
// Bypass initial page load requests (i.e. static assets).
|
||||
// The absence of the immediate/parent client in the map of the active clients
|
||||
// means that MSW hasn't dispatched the "MOCK_ACTIVATE" event yet
|
||||
// and is not ready to handle requests.
|
||||
if (!activeClientIds.has(client.id)) {
|
||||
return passthrough()
|
||||
}
|
||||
|
||||
// Notify the client that a request has been intercepted.
|
||||
const serializedRequest = await serializeRequest(event.request)
|
||||
const clientMessage = await sendToClient(
|
||||
client,
|
||||
{
|
||||
type: 'REQUEST',
|
||||
payload: {
|
||||
id: requestId,
|
||||
interceptedAt: requestInterceptedAt,
|
||||
...serializedRequest,
|
||||
},
|
||||
},
|
||||
[serializedRequest.body],
|
||||
)
|
||||
|
||||
switch (clientMessage.type) {
|
||||
case 'MOCK_RESPONSE': {
|
||||
return respondWithMock(clientMessage.data)
|
||||
}
|
||||
|
||||
case 'PASSTHROUGH': {
|
||||
return passthrough()
|
||||
}
|
||||
}
|
||||
|
||||
return passthrough()
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {Client} client
|
||||
* @param {any} message
|
||||
* @param {Array<Transferable>} transferrables
|
||||
* @returns {Promise<any>}
|
||||
*/
|
||||
function sendToClient(client, message, transferrables = []) {
|
||||
return new Promise((resolve, reject) => {
|
||||
const channel = new MessageChannel()
|
||||
|
||||
channel.port1.onmessage = (event) => {
|
||||
if (event.data && event.data.error) {
|
||||
return reject(event.data.error)
|
||||
}
|
||||
|
||||
resolve(event.data)
|
||||
}
|
||||
|
||||
client.postMessage(message, [
|
||||
channel.port2,
|
||||
...transferrables.filter(Boolean),
|
||||
])
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {Response} response
|
||||
* @returns {Response}
|
||||
*/
|
||||
function respondWithMock(response) {
|
||||
// Setting response status code to 0 is a no-op.
|
||||
// However, when responding with a "Response.error()", the produced Response
|
||||
// instance will have status code set to 0. Since it's not possible to create
|
||||
// a Response instance with status code 0, handle that use-case separately.
|
||||
if (response.status === 0) {
|
||||
return Response.error()
|
||||
}
|
||||
|
||||
const mockedResponse = new Response(response.body, response)
|
||||
|
||||
Reflect.defineProperty(mockedResponse, IS_MOCKED_RESPONSE, {
|
||||
value: true,
|
||||
enumerable: true,
|
||||
})
|
||||
|
||||
return mockedResponse
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {Request} request
|
||||
*/
|
||||
async function serializeRequest(request) {
|
||||
return {
|
||||
url: request.url,
|
||||
mode: request.mode,
|
||||
method: request.method,
|
||||
headers: Object.fromEntries(request.headers.entries()),
|
||||
cache: request.cache,
|
||||
credentials: request.credentials,
|
||||
destination: request.destination,
|
||||
integrity: request.integrity,
|
||||
redirect: request.redirect,
|
||||
referrer: request.referrer,
|
||||
referrerPolicy: request.referrerPolicy,
|
||||
body: await request.arrayBuffer(),
|
||||
keepalive: request.keepalive,
|
||||
}
|
||||
}
|
||||
@@ -15,25 +15,13 @@ describe("normalizeCustomModelSlugs", () => {
|
||||
]),
|
||||
).toEqual(["custom/internal-model"]);
|
||||
});
|
||||
|
||||
it("normalizes provider-specific aliases for claude and cursor", () => {
|
||||
expect(normalizeCustomModelSlugs(["sonnet"], "claudeCode")).toEqual([]);
|
||||
expect(normalizeCustomModelSlugs(["claude/custom-sonnet"], "claudeCode")).toEqual([
|
||||
"claude/custom-sonnet",
|
||||
]);
|
||||
expect(normalizeCustomModelSlugs(["composer"], "cursor")).toEqual([]);
|
||||
expect(normalizeCustomModelSlugs(["cursor/custom-model"], "cursor")).toEqual([
|
||||
"cursor/custom-model",
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("getAppModelOptions", () => {
|
||||
it("appends saved custom models after the built-in options", () => {
|
||||
const options = getAppModelOptions("codex", ["custom/internal-model"]);
|
||||
const options = getAppModelOptions(["custom/internal-model"]);
|
||||
|
||||
expect(options.map((option) => option.slug)).toEqual([
|
||||
"gpt-5.4",
|
||||
"gpt-5.3-codex",
|
||||
"gpt-5.3-codex-spark",
|
||||
"gpt-5.2-codex",
|
||||
@@ -43,7 +31,7 @@ describe("getAppModelOptions", () => {
|
||||
});
|
||||
|
||||
it("keeps the currently selected custom model available even if it is no longer saved", () => {
|
||||
const options = getAppModelOptions("codex", [], "custom/selected-model");
|
||||
const options = getAppModelOptions([], "custom/selected-model");
|
||||
|
||||
expect(options.at(-1)).toEqual({
|
||||
slug: "custom/selected-model",
|
||||
@@ -51,44 +39,18 @@ describe("getAppModelOptions", () => {
|
||||
isCustom: true,
|
||||
});
|
||||
});
|
||||
|
||||
it("keeps a saved custom provider model available as an exact slug option", () => {
|
||||
const options = getAppModelOptions("claudeCode", ["claude/custom-opus"], "claude/custom-opus");
|
||||
|
||||
expect(options.some((option) => option.slug === "claude/custom-opus" && option.isCustom)).toBe(
|
||||
true,
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("getSlashModelOptions", () => {
|
||||
it("includes saved custom model slugs for /model command suggestions", () => {
|
||||
const options = getSlashModelOptions(
|
||||
"codex",
|
||||
["custom/internal-model"],
|
||||
"",
|
||||
"gpt-5.3-codex",
|
||||
);
|
||||
const options = getSlashModelOptions(["custom/internal-model"], "", "gpt-5.3-codex");
|
||||
|
||||
expect(options.some((option) => option.slug === "custom/internal-model")).toBe(true);
|
||||
});
|
||||
|
||||
it("filters slash-model suggestions across built-in and custom model names", () => {
|
||||
const options = getSlashModelOptions(
|
||||
"codex",
|
||||
["openai/gpt-oss-120b"],
|
||||
"oss",
|
||||
"gpt-5.3-codex",
|
||||
);
|
||||
const options = getSlashModelOptions(["openai/gpt-oss-120b"], "oss", "gpt-5.3-codex");
|
||||
|
||||
expect(options.map((option) => option.slug)).toEqual(["openai/gpt-oss-120b"]);
|
||||
});
|
||||
|
||||
it("includes provider-specific custom slugs in non-codex model lists", () => {
|
||||
const claudeOptions = getAppModelOptions("claudeCode", ["claude/custom-opus"]);
|
||||
const cursorOptions = getAppModelOptions("cursor", ["cursor/custom-model"]);
|
||||
|
||||
expect(claudeOptions.some((option) => option.slug === "claude/custom-opus")).toBe(true);
|
||||
expect(cursorOptions.some((option) => option.slug === "cursor/custom-model")).toBe(true);
|
||||
});
|
||||
});
|
||||
+10
-27
@@ -1,16 +1,11 @@
|
||||
import { useCallback, useSyncExternalStore } from "react";
|
||||
import { Option, Schema } from "effect";
|
||||
import { type ProviderKind } from "@t3tools/contracts";
|
||||
import { getModelOptions, normalizeModelSlug } from "@t3tools/shared/model";
|
||||
import { MODEL_OPTIONS, normalizeModelSlug } from "@t3tools/contracts";
|
||||
|
||||
const APP_SETTINGS_STORAGE_KEY = "t3code:app-settings:v1";
|
||||
const MAX_CUSTOM_MODEL_COUNT = 32;
|
||||
export const MAX_CUSTOM_MODEL_LENGTH = 256;
|
||||
const BUILT_IN_MODEL_SLUGS_BY_PROVIDER: Record<ProviderKind, ReadonlySet<string>> = {
|
||||
codex: new Set(getModelOptions("codex").map((option) => option.slug)),
|
||||
claudeCode: new Set(getModelOptions("claudeCode").map((option) => option.slug)),
|
||||
cursor: new Set(getModelOptions("cursor").map((option) => option.slug)),
|
||||
};
|
||||
const BUILT_IN_MODEL_SLUGS = new Set<string>(MODEL_OPTIONS.map((option) => option.slug));
|
||||
|
||||
const AppSettingsSchema = Schema.Struct({
|
||||
codexBinaryPath: Schema.String.check(Schema.isMaxLength(4096)).pipe(
|
||||
@@ -26,12 +21,6 @@ const AppSettingsSchema = Schema.Struct({
|
||||
customCodexModels: Schema.Array(Schema.String).pipe(
|
||||
Schema.withConstructorDefault(() => Option.some([])),
|
||||
),
|
||||
customClaudeModels: Schema.Array(Schema.String).pipe(
|
||||
Schema.withConstructorDefault(() => Option.some([])),
|
||||
),
|
||||
customCursorModels: Schema.Array(Schema.String).pipe(
|
||||
Schema.withConstructorDefault(() => Option.some([])),
|
||||
),
|
||||
});
|
||||
export type AppSettings = typeof AppSettingsSchema.Type;
|
||||
export interface AppModelOption {
|
||||
@@ -48,18 +37,16 @@ let cachedSnapshot: AppSettings = DEFAULT_APP_SETTINGS;
|
||||
|
||||
export function normalizeCustomModelSlugs(
|
||||
models: Iterable<string | null | undefined>,
|
||||
provider: ProviderKind = "codex",
|
||||
): string[] {
|
||||
): AppSettings["customCodexModels"] {
|
||||
const normalizedModels: string[] = [];
|
||||
const seen = new Set<string>();
|
||||
const builtInModelSlugs = BUILT_IN_MODEL_SLUGS_BY_PROVIDER[provider];
|
||||
|
||||
for (const candidate of models) {
|
||||
const normalized = normalizeModelSlug(candidate, provider);
|
||||
const normalized = normalizeModelSlug(candidate);
|
||||
if (
|
||||
!normalized ||
|
||||
normalized.length > MAX_CUSTOM_MODEL_LENGTH ||
|
||||
builtInModelSlugs.has(normalized) ||
|
||||
BUILT_IN_MODEL_SLUGS.has(normalized) ||
|
||||
seen.has(normalized)
|
||||
) {
|
||||
continue;
|
||||
@@ -78,25 +65,22 @@ export function normalizeCustomModelSlugs(
|
||||
function normalizeAppSettings(settings: AppSettings): AppSettings {
|
||||
return {
|
||||
...settings,
|
||||
customCodexModels: normalizeCustomModelSlugs(settings.customCodexModels, "codex"),
|
||||
customClaudeModels: normalizeCustomModelSlugs(settings.customClaudeModels, "claudeCode"),
|
||||
customCursorModels: normalizeCustomModelSlugs(settings.customCursorModels, "cursor"),
|
||||
customCodexModels: normalizeCustomModelSlugs(settings.customCodexModels),
|
||||
};
|
||||
}
|
||||
|
||||
export function getAppModelOptions(
|
||||
provider: ProviderKind,
|
||||
customModels: readonly string[],
|
||||
selectedModel?: string | null,
|
||||
): AppModelOption[] {
|
||||
const options: AppModelOption[] = getModelOptions(provider).map(({ slug, name }) => ({
|
||||
const options: AppModelOption[] = MODEL_OPTIONS.map(({ slug, name }) => ({
|
||||
slug,
|
||||
name,
|
||||
isCustom: false,
|
||||
}));
|
||||
const seen = new Set(options.map((option) => option.slug));
|
||||
|
||||
for (const slug of normalizeCustomModelSlugs(customModels, provider)) {
|
||||
for (const slug of normalizeCustomModelSlugs(customModels)) {
|
||||
if (seen.has(slug)) {
|
||||
continue;
|
||||
}
|
||||
@@ -109,7 +93,7 @@ export function getAppModelOptions(
|
||||
});
|
||||
}
|
||||
|
||||
const normalizedSelectedModel = normalizeModelSlug(selectedModel, provider);
|
||||
const normalizedSelectedModel = normalizeModelSlug(selectedModel);
|
||||
if (normalizedSelectedModel && !seen.has(normalizedSelectedModel)) {
|
||||
options.push({
|
||||
slug: normalizedSelectedModel,
|
||||
@@ -122,13 +106,12 @@ export function getAppModelOptions(
|
||||
}
|
||||
|
||||
export function getSlashModelOptions(
|
||||
provider: ProviderKind,
|
||||
customModels: readonly string[],
|
||||
query: string,
|
||||
selectedModel?: string | null,
|
||||
): AppModelOption[] {
|
||||
const normalizedQuery = query.trim().toLowerCase();
|
||||
const options = getAppModelOptions(provider, customModels, selectedModel);
|
||||
const options = getAppModelOptions(customModels, selectedModel);
|
||||
if (!normalizedQuery) {
|
||||
return options;
|
||||
}
|
||||
|
||||
@@ -52,7 +52,8 @@ export default function BranchToolbar({
|
||||
const api = readNativeApi();
|
||||
// If the effective cwd is about to change, stop the running session so the
|
||||
// next message creates a new one with the correct cwd.
|
||||
if (serverThread?.session && worktreePath !== activeWorktreePath && api) {
|
||||
const sessionId = serverThread?.session?.sessionId;
|
||||
if (sessionId && worktreePath !== activeWorktreePath && api) {
|
||||
void api.orchestration
|
||||
.dispatchCommand({
|
||||
type: "thread.session.stop",
|
||||
@@ -88,7 +89,7 @@ export default function BranchToolbar({
|
||||
},
|
||||
[
|
||||
activeThreadId,
|
||||
serverThread?.session,
|
||||
serverThread?.session?.sessionId,
|
||||
activeWorktreePath,
|
||||
hasServerThread,
|
||||
setThreadBranchAction,
|
||||
|
||||
@@ -1,711 +0,0 @@
|
||||
// Production CSS is part of the behavior under test because row height depends on it.
|
||||
import "../index.css";
|
||||
|
||||
import {
|
||||
ORCHESTRATION_WS_METHODS,
|
||||
type MessageId,
|
||||
type OrchestrationReadModel,
|
||||
type ProjectId,
|
||||
type ServerConfig,
|
||||
type ThreadId,
|
||||
type WsWelcomePayload,
|
||||
WS_CHANNELS,
|
||||
WS_METHODS,
|
||||
} from "@t3tools/contracts";
|
||||
import { RouterProvider, createMemoryHistory } from "@tanstack/react-router";
|
||||
import { HttpResponse, http, ws } from "msw";
|
||||
import { setupWorker } from "msw/browser";
|
||||
import { page } from "vitest/browser";
|
||||
import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { render } from "vitest-browser-react";
|
||||
|
||||
import { getRouter } from "../router";
|
||||
import { useStore } from "../store";
|
||||
import { estimateTimelineMessageHeight } from "./timelineHeight";
|
||||
|
||||
const THREAD_ID = "thread-browser-test" as ThreadId;
|
||||
const PROJECT_ID = "project-1" as ProjectId;
|
||||
const NOW_ISO = "2026-03-04T12:00:00.000Z";
|
||||
const BASE_TIME_MS = Date.parse(NOW_ISO);
|
||||
const ATTACHMENT_SVG = "<svg xmlns='http://www.w3.org/2000/svg' width='120' height='300'></svg>";
|
||||
|
||||
interface WsRequestEnvelope {
|
||||
id: string;
|
||||
body: {
|
||||
_tag: string;
|
||||
[key: string]: unknown;
|
||||
};
|
||||
}
|
||||
|
||||
interface TestFixture {
|
||||
snapshot: OrchestrationReadModel;
|
||||
serverConfig: ServerConfig;
|
||||
welcome: WsWelcomePayload;
|
||||
}
|
||||
|
||||
let fixture: TestFixture;
|
||||
const wsLink = ws.link(/ws(s)?:\/\/.*/);
|
||||
|
||||
interface ViewportSpec {
|
||||
name: string;
|
||||
width: number;
|
||||
height: number;
|
||||
textTolerancePx: number;
|
||||
attachmentTolerancePx: number;
|
||||
}
|
||||
|
||||
const DEFAULT_VIEWPORT: ViewportSpec = {
|
||||
name: "desktop",
|
||||
width: 960,
|
||||
height: 1_100,
|
||||
textTolerancePx: 44,
|
||||
attachmentTolerancePx: 56,
|
||||
};
|
||||
const TEXT_VIEWPORT_MATRIX = [
|
||||
DEFAULT_VIEWPORT,
|
||||
{ name: "tablet", width: 720, height: 1_024, textTolerancePx: 44, attachmentTolerancePx: 56 },
|
||||
{ name: "mobile", width: 430, height: 932, textTolerancePx: 56, attachmentTolerancePx: 56 },
|
||||
{ name: "narrow", width: 320, height: 700, textTolerancePx: 84, attachmentTolerancePx: 56 },
|
||||
] as const satisfies readonly ViewportSpec[];
|
||||
const ATTACHMENT_VIEWPORT_MATRIX = [
|
||||
DEFAULT_VIEWPORT,
|
||||
{ name: "mobile", width: 430, height: 932, textTolerancePx: 56, attachmentTolerancePx: 56 },
|
||||
{ name: "narrow", width: 320, height: 700, textTolerancePx: 84, attachmentTolerancePx: 56 },
|
||||
] as const satisfies readonly ViewportSpec[];
|
||||
|
||||
interface UserRowMeasurement {
|
||||
measuredRowHeightPx: number;
|
||||
timelineWidthMeasuredPx: number;
|
||||
renderedInVirtualizedRegion: boolean;
|
||||
}
|
||||
|
||||
interface MountedChatView {
|
||||
cleanup: () => Promise<void>;
|
||||
measureUserRow: (targetMessageId: MessageId) => Promise<UserRowMeasurement>;
|
||||
setViewport: (viewport: ViewportSpec) => Promise<void>;
|
||||
}
|
||||
|
||||
function isoAt(offsetSeconds: number): string {
|
||||
return new Date(BASE_TIME_MS + offsetSeconds * 1_000).toISOString();
|
||||
}
|
||||
|
||||
function createBaseServerConfig(): ServerConfig {
|
||||
return {
|
||||
cwd: "/repo/project",
|
||||
keybindingsConfigPath: "/repo/project/.t3code-keybindings.json",
|
||||
keybindings: [],
|
||||
issues: [],
|
||||
providers: [
|
||||
{
|
||||
provider: "codex",
|
||||
status: "ready",
|
||||
available: true,
|
||||
authStatus: "authenticated",
|
||||
checkedAt: NOW_ISO,
|
||||
},
|
||||
],
|
||||
availableEditors: [],
|
||||
};
|
||||
}
|
||||
|
||||
function createUserMessage(options: {
|
||||
id: MessageId;
|
||||
text: string;
|
||||
offsetSeconds: number;
|
||||
attachments?: Array<{
|
||||
type: "image";
|
||||
id: string;
|
||||
name: string;
|
||||
mimeType: string;
|
||||
sizeBytes: number;
|
||||
}>;
|
||||
}) {
|
||||
return {
|
||||
id: options.id,
|
||||
role: "user" as const,
|
||||
text: options.text,
|
||||
...(options.attachments ? { attachments: options.attachments } : {}),
|
||||
turnId: null,
|
||||
streaming: false,
|
||||
createdAt: isoAt(options.offsetSeconds),
|
||||
updatedAt: isoAt(options.offsetSeconds + 1),
|
||||
};
|
||||
}
|
||||
|
||||
function createAssistantMessage(options: { id: MessageId; text: string; offsetSeconds: number }) {
|
||||
return {
|
||||
id: options.id,
|
||||
role: "assistant" as const,
|
||||
text: options.text,
|
||||
turnId: null,
|
||||
streaming: false,
|
||||
createdAt: isoAt(options.offsetSeconds),
|
||||
updatedAt: isoAt(options.offsetSeconds + 1),
|
||||
};
|
||||
}
|
||||
|
||||
function createSnapshotForTargetUser(options: {
|
||||
targetMessageId: MessageId;
|
||||
targetText: string;
|
||||
targetAttachmentCount?: number;
|
||||
}): OrchestrationReadModel {
|
||||
const messages: Array<OrchestrationReadModel["threads"][number]["messages"][number]> = [];
|
||||
|
||||
for (let index = 0; index < 22; index += 1) {
|
||||
const isTarget = index === 3;
|
||||
const userId = `msg-user-${index}` as MessageId;
|
||||
const assistantId = `msg-assistant-${index}` as MessageId;
|
||||
const attachments =
|
||||
isTarget && (options.targetAttachmentCount ?? 0) > 0
|
||||
? Array.from({ length: options.targetAttachmentCount ?? 0 }, (_, attachmentIndex) => ({
|
||||
type: "image" as const,
|
||||
id: `attachment-${attachmentIndex + 1}`,
|
||||
name: `attachment-${attachmentIndex + 1}.png`,
|
||||
mimeType: "image/png",
|
||||
sizeBytes: 128,
|
||||
}))
|
||||
: undefined;
|
||||
|
||||
messages.push(
|
||||
createUserMessage({
|
||||
id: isTarget ? options.targetMessageId : userId,
|
||||
text: isTarget ? options.targetText : `filler user message ${index}`,
|
||||
offsetSeconds: messages.length * 3,
|
||||
...(attachments ? { attachments } : {}),
|
||||
}),
|
||||
);
|
||||
messages.push(
|
||||
createAssistantMessage({
|
||||
id: assistantId,
|
||||
text: `assistant filler ${index}`,
|
||||
offsetSeconds: messages.length * 3,
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
return {
|
||||
snapshotSequence: 1,
|
||||
projects: [
|
||||
{
|
||||
id: PROJECT_ID,
|
||||
title: "Project",
|
||||
workspaceRoot: "/repo/project",
|
||||
defaultModel: "gpt-5",
|
||||
scripts: [],
|
||||
createdAt: NOW_ISO,
|
||||
updatedAt: NOW_ISO,
|
||||
deletedAt: null,
|
||||
},
|
||||
],
|
||||
threads: [
|
||||
{
|
||||
id: THREAD_ID,
|
||||
projectId: PROJECT_ID,
|
||||
title: "Browser test thread",
|
||||
model: "gpt-5",
|
||||
interactionMode: "default",
|
||||
runtimeMode: "full-access",
|
||||
branch: "main",
|
||||
worktreePath: null,
|
||||
latestTurn: null,
|
||||
createdAt: NOW_ISO,
|
||||
updatedAt: NOW_ISO,
|
||||
deletedAt: null,
|
||||
messages,
|
||||
activities: [],
|
||||
proposedPlans: [],
|
||||
checkpoints: [],
|
||||
session: {
|
||||
threadId: THREAD_ID,
|
||||
status: "ready",
|
||||
providerName: "codex",
|
||||
runtimeMode: "full-access",
|
||||
activeTurnId: null,
|
||||
lastError: null,
|
||||
updatedAt: NOW_ISO,
|
||||
},
|
||||
},
|
||||
],
|
||||
updatedAt: NOW_ISO,
|
||||
};
|
||||
}
|
||||
|
||||
function buildFixture(snapshot: OrchestrationReadModel): TestFixture {
|
||||
return {
|
||||
snapshot,
|
||||
serverConfig: createBaseServerConfig(),
|
||||
welcome: {
|
||||
cwd: "/repo/project",
|
||||
projectName: "Project",
|
||||
bootstrapProjectId: PROJECT_ID,
|
||||
bootstrapThreadId: THREAD_ID,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function resolveWsRpc(tag: string): unknown {
|
||||
if (tag === ORCHESTRATION_WS_METHODS.getSnapshot) {
|
||||
return fixture.snapshot;
|
||||
}
|
||||
if (tag === WS_METHODS.serverGetConfig) {
|
||||
return fixture.serverConfig;
|
||||
}
|
||||
if (tag === WS_METHODS.gitListBranches) {
|
||||
return {
|
||||
isRepo: true,
|
||||
branches: [
|
||||
{
|
||||
name: "main",
|
||||
current: true,
|
||||
isDefault: true,
|
||||
worktreePath: null,
|
||||
},
|
||||
],
|
||||
};
|
||||
}
|
||||
if (tag === WS_METHODS.gitStatus) {
|
||||
return {
|
||||
branch: "main",
|
||||
hasWorkingTreeChanges: false,
|
||||
workingTree: {
|
||||
files: [],
|
||||
insertions: 0,
|
||||
deletions: 0,
|
||||
},
|
||||
hasUpstream: true,
|
||||
aheadCount: 0,
|
||||
behindCount: 0,
|
||||
pr: null,
|
||||
};
|
||||
}
|
||||
if (tag === WS_METHODS.projectsSearchEntries) {
|
||||
return {
|
||||
entries: [],
|
||||
truncated: false,
|
||||
};
|
||||
}
|
||||
return {};
|
||||
}
|
||||
|
||||
const worker = setupWorker(
|
||||
wsLink.addEventListener("connection", ({ client }) => {
|
||||
client.send(
|
||||
JSON.stringify({
|
||||
type: "push",
|
||||
channel: WS_CHANNELS.serverWelcome,
|
||||
data: fixture.welcome,
|
||||
}),
|
||||
);
|
||||
client.addEventListener("message", (event) => {
|
||||
const rawData = event.data;
|
||||
if (typeof rawData !== "string") return;
|
||||
let request: WsRequestEnvelope;
|
||||
try {
|
||||
request = JSON.parse(rawData) as WsRequestEnvelope;
|
||||
} catch {
|
||||
return;
|
||||
}
|
||||
const method = request.body?._tag;
|
||||
if (typeof method !== "string") return;
|
||||
client.send(
|
||||
JSON.stringify({
|
||||
id: request.id,
|
||||
result: resolveWsRpc(method),
|
||||
}),
|
||||
);
|
||||
});
|
||||
}),
|
||||
http.get("*/attachments/:attachmentId", () =>
|
||||
HttpResponse.text(ATTACHMENT_SVG, {
|
||||
headers: {
|
||||
"Content-Type": "image/svg+xml",
|
||||
},
|
||||
}),
|
||||
),
|
||||
http.get("*/api/project-favicon", () => new HttpResponse(null, { status: 204 })),
|
||||
);
|
||||
|
||||
async function nextFrame(): Promise<void> {
|
||||
await new Promise<void>((resolve) => {
|
||||
window.requestAnimationFrame(() => resolve());
|
||||
});
|
||||
}
|
||||
|
||||
async function waitForLayout(): Promise<void> {
|
||||
await nextFrame();
|
||||
await nextFrame();
|
||||
await nextFrame();
|
||||
}
|
||||
|
||||
async function setViewport(viewport: ViewportSpec): Promise<void> {
|
||||
await page.viewport(viewport.width, viewport.height);
|
||||
await waitForLayout();
|
||||
}
|
||||
|
||||
async function waitForProductionStyles(): Promise<void> {
|
||||
await vi.waitFor(
|
||||
() => {
|
||||
expect(getComputedStyle(document.documentElement).getPropertyValue("--background").trim()).not.toBe(
|
||||
"",
|
||||
);
|
||||
expect(getComputedStyle(document.body).marginTop).toBe("0px");
|
||||
},
|
||||
{
|
||||
timeout: 4_000,
|
||||
interval: 16,
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
async function waitForElement<T extends Element>(
|
||||
query: () => T | null,
|
||||
errorMessage: string,
|
||||
): Promise<T> {
|
||||
let element: T | null = null;
|
||||
await vi.waitFor(
|
||||
() => {
|
||||
element = query();
|
||||
expect(element, errorMessage).toBeTruthy();
|
||||
},
|
||||
{
|
||||
timeout: 8_000,
|
||||
interval: 16,
|
||||
},
|
||||
);
|
||||
if (!element) {
|
||||
throw new Error(errorMessage);
|
||||
}
|
||||
return element;
|
||||
}
|
||||
|
||||
async function waitForImagesToLoad(scope: ParentNode): Promise<void> {
|
||||
const images = Array.from(scope.querySelectorAll("img"));
|
||||
if (images.length === 0) {
|
||||
return;
|
||||
}
|
||||
await Promise.all(
|
||||
images.map(
|
||||
(image) =>
|
||||
new Promise<void>((resolve) => {
|
||||
if (image.complete) {
|
||||
resolve();
|
||||
return;
|
||||
}
|
||||
image.addEventListener("load", () => resolve(), { once: true });
|
||||
image.addEventListener("error", () => resolve(), { once: true });
|
||||
}),
|
||||
),
|
||||
);
|
||||
await waitForLayout();
|
||||
}
|
||||
|
||||
async function measureUserRow(options: {
|
||||
host: HTMLElement;
|
||||
targetMessageId: MessageId;
|
||||
}): Promise<UserRowMeasurement> {
|
||||
const { host, targetMessageId } = options;
|
||||
const rowSelector = `[data-message-id="${targetMessageId}"][data-message-role="user"]`;
|
||||
|
||||
const scrollContainer = await waitForElement(
|
||||
() => host.querySelector<HTMLDivElement>("div.overflow-y-auto.overscroll-y-contain"),
|
||||
"Unable to find ChatView message scroll container.",
|
||||
);
|
||||
|
||||
let row: HTMLElement | null = null;
|
||||
await vi.waitFor(
|
||||
async () => {
|
||||
scrollContainer.scrollTop = 0;
|
||||
scrollContainer.dispatchEvent(new Event("scroll"));
|
||||
await waitForLayout();
|
||||
row = host.querySelector<HTMLElement>(rowSelector);
|
||||
expect(row, "Unable to locate targeted user message row.").toBeTruthy();
|
||||
},
|
||||
{
|
||||
timeout: 8_000,
|
||||
interval: 16,
|
||||
},
|
||||
);
|
||||
|
||||
await waitForImagesToLoad(row!);
|
||||
scrollContainer.scrollTop = 0;
|
||||
scrollContainer.dispatchEvent(new Event("scroll"));
|
||||
await nextFrame();
|
||||
|
||||
const timelineRoot =
|
||||
row!.closest<HTMLElement>('[data-timeline-root="true"]') ??
|
||||
host.querySelector<HTMLElement>('[data-timeline-root="true"]');
|
||||
if (!(timelineRoot instanceof HTMLElement)) {
|
||||
throw new Error("Unable to locate timeline root container.");
|
||||
}
|
||||
|
||||
let timelineWidthMeasuredPx = 0;
|
||||
let measuredRowHeightPx = 0;
|
||||
let renderedInVirtualizedRegion = false;
|
||||
await vi.waitFor(
|
||||
async () => {
|
||||
scrollContainer.scrollTop = 0;
|
||||
scrollContainer.dispatchEvent(new Event("scroll"));
|
||||
await nextFrame();
|
||||
const measuredRow = host.querySelector<HTMLElement>(rowSelector);
|
||||
expect(measuredRow, "Unable to measure targeted user row height.").toBeTruthy();
|
||||
timelineWidthMeasuredPx = timelineRoot.getBoundingClientRect().width;
|
||||
measuredRowHeightPx = measuredRow!.getBoundingClientRect().height;
|
||||
renderedInVirtualizedRegion = measuredRow!.closest("[data-index]") instanceof HTMLElement;
|
||||
expect(timelineWidthMeasuredPx, "Unable to measure timeline width.").toBeGreaterThan(0);
|
||||
expect(measuredRowHeightPx, "Unable to measure targeted user row height.").toBeGreaterThan(0);
|
||||
},
|
||||
{
|
||||
timeout: 4_000,
|
||||
interval: 16,
|
||||
},
|
||||
);
|
||||
|
||||
return { measuredRowHeightPx, timelineWidthMeasuredPx, renderedInVirtualizedRegion };
|
||||
}
|
||||
|
||||
async function mountChatView(options: {
|
||||
viewport: ViewportSpec;
|
||||
snapshot: OrchestrationReadModel;
|
||||
}): Promise<MountedChatView> {
|
||||
fixture = buildFixture(options.snapshot);
|
||||
await setViewport(options.viewport);
|
||||
await waitForProductionStyles();
|
||||
|
||||
const host = document.createElement("div");
|
||||
host.style.position = "fixed";
|
||||
host.style.inset = "0";
|
||||
host.style.width = "100vw";
|
||||
host.style.height = "100vh";
|
||||
host.style.display = "grid";
|
||||
host.style.overflow = "hidden";
|
||||
document.body.append(host);
|
||||
|
||||
const router = getRouter(
|
||||
createMemoryHistory({
|
||||
initialEntries: [`/${THREAD_ID}`],
|
||||
}),
|
||||
);
|
||||
|
||||
const screen = await render(<RouterProvider router={router} />, {
|
||||
container: host,
|
||||
});
|
||||
|
||||
await waitForLayout();
|
||||
|
||||
return {
|
||||
cleanup: async () => {
|
||||
await screen.unmount();
|
||||
host.remove();
|
||||
},
|
||||
measureUserRow: async (targetMessageId: MessageId) => measureUserRow({ host, targetMessageId }),
|
||||
setViewport: async (viewport: ViewportSpec) => {
|
||||
await setViewport(viewport);
|
||||
await waitForProductionStyles();
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
async function measureUserRowAtViewport(options: {
|
||||
snapshot: OrchestrationReadModel;
|
||||
targetMessageId: MessageId;
|
||||
viewport: ViewportSpec;
|
||||
}): Promise<UserRowMeasurement> {
|
||||
const mounted = await mountChatView({
|
||||
viewport: options.viewport,
|
||||
snapshot: options.snapshot,
|
||||
});
|
||||
|
||||
try {
|
||||
return await mounted.measureUserRow(options.targetMessageId);
|
||||
} finally {
|
||||
await mounted.cleanup();
|
||||
}
|
||||
}
|
||||
|
||||
describe("ChatView timeline estimator parity (full app)", () => {
|
||||
beforeAll(async () => {
|
||||
fixture = buildFixture(
|
||||
createSnapshotForTargetUser({
|
||||
targetMessageId: "msg-user-bootstrap" as MessageId,
|
||||
targetText: "bootstrap",
|
||||
}),
|
||||
);
|
||||
await worker.start({
|
||||
onUnhandledRequest: "bypass",
|
||||
quiet: true,
|
||||
serviceWorker: {
|
||||
url: "/mockServiceWorker.js",
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
await worker.stop();
|
||||
});
|
||||
|
||||
beforeEach(async () => {
|
||||
await setViewport(DEFAULT_VIEWPORT);
|
||||
localStorage.clear();
|
||||
document.body.innerHTML = "";
|
||||
useStore.setState({
|
||||
projects: [],
|
||||
threads: [],
|
||||
threadsHydrated: false,
|
||||
});
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
document.body.innerHTML = "";
|
||||
});
|
||||
|
||||
it.each(TEXT_VIEWPORT_MATRIX)(
|
||||
"keeps long user message estimate close at the $name viewport",
|
||||
async (viewport) => {
|
||||
const userText = "x".repeat(3_200);
|
||||
const targetMessageId = `msg-user-target-long-${viewport.name}` as MessageId;
|
||||
const mounted = await mountChatView({
|
||||
viewport,
|
||||
snapshot: createSnapshotForTargetUser({
|
||||
targetMessageId,
|
||||
targetText: userText,
|
||||
}),
|
||||
});
|
||||
|
||||
try {
|
||||
const { measuredRowHeightPx, timelineWidthMeasuredPx, renderedInVirtualizedRegion } =
|
||||
await mounted.measureUserRow(targetMessageId);
|
||||
|
||||
expect(renderedInVirtualizedRegion).toBe(true);
|
||||
|
||||
const estimatedHeightPx = estimateTimelineMessageHeight(
|
||||
{ role: "user", text: userText, attachments: [] },
|
||||
{ timelineWidthPx: timelineWidthMeasuredPx },
|
||||
);
|
||||
|
||||
expect(Math.abs(measuredRowHeightPx - estimatedHeightPx)).toBeLessThanOrEqual(
|
||||
viewport.textTolerancePx,
|
||||
);
|
||||
} finally {
|
||||
await mounted.cleanup();
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
it("tracks wrapping parity while resizing an existing ChatView across the viewport matrix", async () => {
|
||||
const userText = "x".repeat(3_200);
|
||||
const targetMessageId = "msg-user-target-resize" as MessageId;
|
||||
const mounted = await mountChatView({
|
||||
viewport: TEXT_VIEWPORT_MATRIX[0],
|
||||
snapshot: createSnapshotForTargetUser({
|
||||
targetMessageId,
|
||||
targetText: userText,
|
||||
}),
|
||||
});
|
||||
|
||||
try {
|
||||
const measurements: Array<UserRowMeasurement & { viewport: ViewportSpec; estimatedHeightPx: number }> = [];
|
||||
|
||||
for (const viewport of TEXT_VIEWPORT_MATRIX) {
|
||||
await mounted.setViewport(viewport);
|
||||
const measurement = await mounted.measureUserRow(targetMessageId);
|
||||
const estimatedHeightPx = estimateTimelineMessageHeight(
|
||||
{ role: "user", text: userText, attachments: [] },
|
||||
{ timelineWidthPx: measurement.timelineWidthMeasuredPx },
|
||||
);
|
||||
|
||||
expect(measurement.renderedInVirtualizedRegion).toBe(true);
|
||||
expect(Math.abs(measurement.measuredRowHeightPx - estimatedHeightPx)).toBeLessThanOrEqual(
|
||||
viewport.textTolerancePx,
|
||||
);
|
||||
measurements.push({ ...measurement, viewport, estimatedHeightPx });
|
||||
}
|
||||
|
||||
expect(new Set(measurements.map((measurement) => Math.round(measurement.timelineWidthMeasuredPx))).size).toBeGreaterThanOrEqual(3);
|
||||
|
||||
const byMeasuredWidth = measurements.toSorted(
|
||||
(left, right) => left.timelineWidthMeasuredPx - right.timelineWidthMeasuredPx,
|
||||
);
|
||||
const narrowest = byMeasuredWidth[0]!;
|
||||
const widest = byMeasuredWidth.at(-1)!;
|
||||
expect(narrowest.timelineWidthMeasuredPx).toBeLessThan(widest.timelineWidthMeasuredPx);
|
||||
expect(narrowest.measuredRowHeightPx).toBeGreaterThan(widest.measuredRowHeightPx);
|
||||
expect(narrowest.estimatedHeightPx).toBeGreaterThan(widest.estimatedHeightPx);
|
||||
} finally {
|
||||
await mounted.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
it("tracks additional rendered wrapping when ChatView width narrows between desktop and mobile viewports", async () => {
|
||||
const userText = "x".repeat(2_400);
|
||||
const targetMessageId = "msg-user-target-wrap" as MessageId;
|
||||
const snapshot = createSnapshotForTargetUser({
|
||||
targetMessageId,
|
||||
targetText: userText,
|
||||
});
|
||||
const desktopMeasurement = await measureUserRowAtViewport({
|
||||
viewport: TEXT_VIEWPORT_MATRIX[0],
|
||||
snapshot,
|
||||
targetMessageId,
|
||||
});
|
||||
const mobileMeasurement = await measureUserRowAtViewport({
|
||||
viewport: TEXT_VIEWPORT_MATRIX[2],
|
||||
snapshot,
|
||||
targetMessageId,
|
||||
});
|
||||
|
||||
const estimatedDesktopPx = estimateTimelineMessageHeight(
|
||||
{ role: "user", text: userText, attachments: [] },
|
||||
{ timelineWidthPx: desktopMeasurement.timelineWidthMeasuredPx },
|
||||
);
|
||||
const estimatedMobilePx = estimateTimelineMessageHeight(
|
||||
{ role: "user", text: userText, attachments: [] },
|
||||
{ timelineWidthPx: mobileMeasurement.timelineWidthMeasuredPx },
|
||||
);
|
||||
|
||||
const measuredDeltaPx = mobileMeasurement.measuredRowHeightPx - desktopMeasurement.measuredRowHeightPx;
|
||||
const estimatedDeltaPx = estimatedMobilePx - estimatedDesktopPx;
|
||||
expect(measuredDeltaPx).toBeGreaterThan(0);
|
||||
expect(estimatedDeltaPx).toBeGreaterThan(0);
|
||||
const ratio = estimatedDeltaPx / measuredDeltaPx;
|
||||
expect(ratio).toBeGreaterThan(0.65);
|
||||
expect(ratio).toBeLessThan(1.35);
|
||||
});
|
||||
|
||||
it.each(ATTACHMENT_VIEWPORT_MATRIX)(
|
||||
"keeps user attachment estimate close at the $name viewport",
|
||||
async (viewport) => {
|
||||
const targetMessageId = `msg-user-target-attachments-${viewport.name}` as MessageId;
|
||||
const userText = "message with image attachments";
|
||||
const mounted = await mountChatView({
|
||||
viewport,
|
||||
snapshot: createSnapshotForTargetUser({
|
||||
targetMessageId,
|
||||
targetText: userText,
|
||||
targetAttachmentCount: 3,
|
||||
}),
|
||||
});
|
||||
|
||||
try {
|
||||
const { measuredRowHeightPx, timelineWidthMeasuredPx, renderedInVirtualizedRegion } =
|
||||
await mounted.measureUserRow(targetMessageId);
|
||||
|
||||
expect(renderedInVirtualizedRegion).toBe(true);
|
||||
|
||||
const estimatedHeightPx = estimateTimelineMessageHeight(
|
||||
{
|
||||
role: "user",
|
||||
text: userText,
|
||||
attachments: [{ id: "attachment-1" }, { id: "attachment-2" }, { id: "attachment-3" }],
|
||||
},
|
||||
{ timelineWidthPx: timelineWidthMeasuredPx },
|
||||
);
|
||||
|
||||
expect(Math.abs(measuredRowHeightPx - estimatedHeightPx)).toBeLessThanOrEqual(
|
||||
viewport.attachmentTolerancePx,
|
||||
);
|
||||
} finally {
|
||||
await mounted.cleanup();
|
||||
}
|
||||
},
|
||||
);
|
||||
});
|
||||
Loaded 100 of 156 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user