This commit is contained in:
Yash Singh committed 2026-03-06 18:02:44 -06:00
commit 31f82efd2e
181 files changed
+15757 -5537

No files matched your search

+21
View File
@@ -0,0 +1,21 @@
# Architecture
T3 Code runs as a **Node.js WebSocket server** that wraps `codex app-server` (JSON-RPC over stdio) and serves a React web app.
```
┌─────────────────────────────────┐
│ Browser (React + Vite) │
│ Connected via WebSocket │
└──────────┬──────────────────────┘
│ ws://localhost:3773
┌──────────▼──────────────────────┐
│ apps/server (Node.js) │
│ WebSocket + HTTP static server │
│ ProviderManager │
│ CodexAppServerManager │
└──────────┬──────────────────────┘
│ JSON-RPC over stdio
┌──────────▼──────────────────────┐
│ codex app-server │
└─────────────────────────────────┘
```
+6
View File
@@ -0,0 +1,6 @@
# CI quality gates
- `.github/workflows/ci.yml` runs `bun run lint`, `bun run typecheck`, and `bun run test` on pull requests and pushes to `main`.
- `.github/workflows/release.yml` builds macOS (`arm64` and `x64`), Linux (`x64`), and Windows (`x64`) desktop artifacts from a single `v*.*.*` tag and publishes one GitHub release.
- The release workflow auto-enables signing only when secrets are present: Apple credentials for macOS and Azure Trusted Signing credentials for Windows. Without secrets, it still releases unsigned artifacts.
- See `docs/release.md` for full release/signing setup checklist.
+5
View File
@@ -0,0 +1,5 @@
# Codex prerequisites
- Install Codex CLI so `codex` is on your PATH.
- Authenticate Codex before running T3 Code (for example via API key or ChatGPT auth supported by Codex).
- T3 Code starts the server via `codex app-server` per session.
+14
View File
@@ -0,0 +1,14 @@
# Provider architecture
The web app communicates with the server via WebSocket using a simple JSON-RPC-style protocol:
- **Request/Response**: `{ id, method, params }` → `{ id, result }` or `{ id, error }`
- **Push events**: `{ type: "push", channel, data }` for orchestration read-model updates
Methods mirror the `NativeApi` interface defined in `@t3tools/contracts`:
- `providers.startSession`, `providers.sendTurn`, `providers.interruptTurn`
- `providers.respondToRequest`, `providers.stopSession`
- `shell.openInEditor`, `server.getConfig`
Codex is the only implemented provider. `claudeCode` is reserved in contracts/UI.
+22
View File
@@ -0,0 +1,22 @@
# Quick start
```bash
# Development (with hot reload)
bun run dev
# Desktop development
bun run dev:desktop
# Desktop development on an isolated port set
T3CODE_DEV_INSTANCE=feature-xyz bun run dev:desktop
# Production
bun run build
bun run start
# Build a shareable macOS .dmg (arm64 by default)
bun run dist:desktop:dmg
# Or from any project directory after publishing:
npx t3
```
+6
View File
@@ -0,0 +1,6 @@
# Runtime modes
T3 Code has a global runtime mode switch in the chat toolbar:
- **Full access** (default): starts sessions with `approvalPolicy: never` and `sandboxMode: danger-full-access`.
- **Supervised**: starts sessions with `approvalPolicy: on-request` and `sandboxMode: workspace-write`, then prompts in-app for command/file approvals.
+42
View File
@@ -0,0 +1,42 @@
# Scripts
- `bun run dev` — Starts contracts, server, and web in `turbo watch` mode.
- `bun run dev:server` — Starts just the WebSocket server (uses Bun TypeScript execution).
- `bun run dev:web` — Starts just the Vite dev server for the web app.
- Dev commands default `T3CODE_STATE_DIR` to `~/.t3/dev` to keep dev state isolated from desktop/prod state.
- Override server CLI-equivalent flags from root dev commands with `--`, for example:
`bun run dev -- --state-dir ~/.t3/another-dev-state`
- `bun run start` — Runs the production server (serves built web app as static files).
- `bun run build` — Builds contracts, web app, and server through Turbo.
- `bun run typecheck` — Strict TypeScript checks for all packages.
- `bun run test` — Runs workspace tests.
- `bun run dist:desktop:artifact -- --platform <mac|linux|win> --target <target> --arch <arch>` — Builds a desktop artifact for a specific platform/target/arch.
- `bun run dist:desktop:dmg` — Builds a shareable macOS `.dmg` into `./release`.
- `bun run dist:desktop:dmg:x64` — Builds an Intel macOS `.dmg`.
- `bun run dist:desktop:linux` — Builds a Linux AppImage into `./release`.
- `bun run dist:desktop:win` — Builds a Windows NSIS installer into `./release`.
## Desktop `.dmg` packaging notes
- Default build is unsigned/not notarized for local sharing.
- The DMG build uses `assets/macos-icon-1024.png` as the production app icon source.
- Desktop production windows load the bundled UI from `t3://app/index.html` (not a `127.0.0.1` document URL).
- Desktop packaging includes `apps/server/dist` (the `t3` backend) and starts it on loopback with an auth token for WebSocket/API traffic.
- Your tester can still open it on macOS by right-clicking the app and choosing **Open** on first launch.
- To keep staging files for debugging package contents, run: `bun run dist:desktop:dmg -- --keep-stage`
- To allow code-signing/notarization when configured in CI/secrets, add: `--signed`.
- Windows `--signed` uses Azure Trusted Signing and expects:
`AZURE_TRUSTED_SIGNING_ENDPOINT`, `AZURE_TRUSTED_SIGNING_ACCOUNT_NAME`,
`AZURE_TRUSTED_SIGNING_CERTIFICATE_PROFILE_NAME`, and `AZURE_TRUSTED_SIGNING_PUBLISHER_NAME`.
- Azure authentication env vars are also required (for example service principal with secret):
`AZURE_TENANT_ID`, `AZURE_CLIENT_ID`, `AZURE_CLIENT_SECRET`.
## Running multiple dev instances
Set `T3CODE_DEV_INSTANCE` to any value to deterministically shift all dev ports together.
- Default ports: server `3773`, web `5733`
- Shifted ports: `base + offset` (offset is hashed from `T3CODE_DEV_INSTANCE`)
- Example: `T3CODE_DEV_INSTANCE=branch-a bun run dev:desktop`
If you want full control instead of hashing, set `T3CODE_PORT_OFFSET` to a numeric offset.
+6
View File
@@ -0,0 +1,6 @@
# Workspace layout
- `/apps/server`: Node.js WebSocket server. Wraps Codex app-server, serves the built web app, and opens the browser on start.
- `/apps/web`: React + Vite UI. Session control, conversation, and provider event rendering. Connects to the server via WebSocket.
- `/apps/desktop`: Electron shell. Spawns a desktop-scoped `t3` backend process and loads the shared web app.
- `/packages/contracts`: Shared Zod schemas and TypeScript contracts for provider events, WebSocket protocol, and model/session types.
+1
View File
@@ -5,6 +5,7 @@ node_modules
*.log
*.tsbuildinfo
apps/*/dist
.astro
packages/*/dist
.env
.env.local
-546
View File
@@ -1,546 +0,0 @@
# 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.
-64
View File
@@ -1,64 +0,0 @@
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));
}
+2 -1
View File
@@ -1,8 +1,9 @@
# CLAUDE.md
# AGENTS.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
+21
View File
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2026 T3 Tools Inc.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+10 -122
View File
@@ -2,135 +2,23 @@
T3 Code is a minimal web GUI for coding agents. Currently Codex-first, with Claude Code support coming soon.
Run `npx t3` in any project directory to launch the web interface.
Run `bun run dev:desktop` to launch the Electron desktop app in this monorepo.
## How to use
## Architecture
T3 Code runs as a **Node.js WebSocket server** that wraps `codex app-server` (JSON-RPC over stdio) and serves a React web app.
```
┌─────────────────────────────────┐
│ Browser (React + Vite) │
│ Connected via WebSocket │
└──────────┬──────────────────────┘
│ ws://localhost:3773
┌──────────▼──────────────────────┐
│ apps/server (Node.js) │
│ WebSocket + HTTP static server │
│ ProviderManager │
│ CodexAppServerManager │
└──────────┬──────────────────────┘
│ JSON-RPC over stdio
┌──────────▼──────────────────────┐
│ codex app-server │
└─────────────────────────────────┘
```
## Workspace layout
- `/apps/server`: Node.js WebSocket server. Wraps Codex app-server, serves the built web app, and opens the browser on start.
- `/apps/web`: React + Vite UI. Session control, conversation, and provider event rendering. Connects to the server via WebSocket.
- `/apps/desktop`: Electron shell. Spawns a desktop-scoped `t3` backend process and loads the shared web app.
- `/packages/contracts`: Shared Zod schemas and TypeScript contracts for provider events, WebSocket protocol, and model/session types.
## Codex prerequisites
- Install Codex CLI so `codex` is on your PATH.
- Authenticate Codex before running T3 Code (for example via API key or ChatGPT auth supported by Codex).
- T3 Code starts the server via `codex app-server` per session.
## Quick start
> [!WARNING]
> You need to have [Codex CLI](https://github.com/openai/codex) installed and authorized for T3 Code to work.
```bash
# Development (with hot reload)
bun run dev
# Desktop development
bun run dev:desktop
# Desktop development on an isolated port set
T3CODE_DEV_INSTANCE=feature-xyz bun run dev:desktop
# Production
bun run build
bun run start
# Build a shareable macOS .dmg (arm64 by default)
bun run dist:desktop:dmg
# Or from any project directory after publishing:
npx t3
npx t3@alpha
```
## Scripts
Use can also just install the desktop app (it's cooler).
- `bun run dev` — Starts contracts, server, and web in `turbo watch` mode.
- `bun run dev:server` — Starts just the WebSocket server (uses Bun TypeScript execution).
- `bun run dev:web` — Starts just the Vite dev server for the web app.
- Dev commands default `T3CODE_STATE_DIR` to `~/.t3/dev` to keep dev state isolated from desktop/prod state.
- Override server CLI-equivalent flags from root dev commands with `--`, for example:
`bun run dev -- --state-dir ~/.t3/another-dev-state`
- `bun run start` — Runs the production server (serves built web app as static files).
- `bun run build` — Builds contracts, web app, and server through Turbo.
- `bun run typecheck` — Strict TypeScript checks for all packages.
- `bun run test` — Runs workspace tests.
- `bun run dist:desktop:artifact -- --platform <mac|linux|win> --target <target> --arch <arch>` — Builds a desktop artifact for a specific platform/target/arch.
- `bun run dist:desktop:dmg` — Builds a shareable macOS `.dmg` into `./release`.
- `bun run dist:desktop:dmg:x64` — Builds an Intel macOS `.dmg`.
- `bun run dist:desktop:linux` — Builds a Linux AppImage into `./release`.
- `bun run dist:desktop:win` — Builds a Windows NSIS installer into `./release`.
Install the [desktop app from the Releases page](https://github.com/pingdotgg/t3code/releases)
### Desktop `.dmg` packaging notes
## Some notes
- Default build is unsigned/not notarized for local sharing.
- The DMG build uses `assets/macos-icon-1024.png` as the production app icon source.
- Desktop production windows load the bundled UI from `t3://app/index.html` (not a `127.0.0.1` document URL).
- Desktop packaging includes `apps/server/dist` (the `t3` backend) and starts it on loopback with an auth token for WebSocket/API traffic.
- Your tester can still open it on macOS by right-clicking the app and choosing **Open** on first launch.
- To keep staging files for debugging package contents, run: `bun run dist:desktop:dmg -- --keep-stage`
- To allow code-signing/notarization when configured in CI/secrets, add: `--signed`.
- Windows `--signed` uses Azure Trusted Signing and expects:
`AZURE_TRUSTED_SIGNING_ENDPOINT`, `AZURE_TRUSTED_SIGNING_ACCOUNT_NAME`,
`AZURE_TRUSTED_SIGNING_CERTIFICATE_PROFILE_NAME`, and `AZURE_TRUSTED_SIGNING_PUBLISHER_NAME`.
- Azure authentication env vars are also required (for example service principal with secret):
`AZURE_TENANT_ID`, `AZURE_CLIENT_ID`, `AZURE_CLIENT_SECRET`.
We are very very early in this project. Expect bugs.
### Running multiple dev instances
We are not accepting contributions yet.
Set `T3CODE_DEV_INSTANCE` to any value to deterministically shift all dev ports together.
- Default ports: server `3773`, web `5733`
- Shifted ports: `base + offset` (offset is hashed from `T3CODE_DEV_INSTANCE`)
- Example: `T3CODE_DEV_INSTANCE=branch-a bun run dev:desktop`
If you want full control instead of hashing, set `T3CODE_PORT_OFFSET` to a numeric offset.
## Runtime modes
T3 Code has a global runtime mode switch in the chat toolbar:
- **Full access** (default): starts sessions with `approvalPolicy: never` and `sandboxMode: danger-full-access`.
- **Supervised**: starts sessions with `approvalPolicy: on-request` and `sandboxMode: workspace-write`, then prompts in-app for command/file approvals.
## Provider architecture
The web app communicates with the server via WebSocket using a simple JSON-RPC-style protocol:
- **Request/Response**: `{ id, method, params }` → `{ id, result }` or `{ id, error }`
- **Push events**: `{ type: "push", channel, data }` for orchestration read-model updates
Methods mirror the `NativeApi` interface defined in `@t3tools/contracts`:
- `providers.startSession`, `providers.sendTurn`, `providers.interruptTurn`
- `providers.respondToRequest`, `providers.stopSession`
- `shell.openInEditor`, `server.getConfig`
Codex is the only implemented provider. `claudeCode` is reserved in contracts/UI.
## CI quality gates
- `.github/workflows/ci.yml` runs `bun run lint`, `bun run typecheck`, and `bun run test` on pull requests and pushes to `main`.
- `.github/workflows/release.yml` builds macOS (`arm64` and `x64`), Linux (`x64`), and Windows (`x64`) desktop artifacts from a single `v*.*.*` tag and publishes one GitHub release.
- The release workflow auto-enables signing only when secrets are present: Apple credentials for macOS and Azure Trusted Signing credentials for Windows. Without secrets, it still releases unsigned artifacts.
- See `docs/release.md` for full release/signing setup checklist.
Discord link coming soon.
-582
View File
@@ -1,582 +0,0 @@
# 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 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@t3tools/desktop",
"version": "0.0.0-alpha.20",
"version": "0.0.0-alpha.22",
"private": true,
"main": "dist-electron/main.js",
"scripts": {
+7
View File
@@ -0,0 +1,7 @@
import { defineConfig } from "astro/config";
export default defineConfig({
server: {
port: Number(process.env.PORT ?? 4173),
},
});
+19
View File
@@ -0,0 +1,19 @@
{
"name": "@t3tools/marketing",
"version": "0.0.0",
"private": true,
"type": "module",
"scripts": {
"dev": "astro dev",
"build": "astro build",
"preview": "astro preview",
"typecheck": "astro check"
},
"dependencies": {
"astro": "^5.7.13"
},
"devDependencies": {
"@astrojs/check": "^0.9.4",
"typescript": "catalog:"
}
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 279 KiB

File renamed without changes.

Before

Width:  |  Height:  |  Size: 1.1 MiB

After

Width:  |  Height:  |  Size: 1.1 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 652 KiB

+326
View File
@@ -0,0 +1,326 @@
---
---
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta name="description" content="T3 Code — The best way to code with AI." />
<link rel="preconnect" href="https://fonts.googleapis.com" />
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
<link
href="https://fonts.googleapis.com/css2?family=DM+Sans:opsz,[email protected],400;9..40,500;9..40,600&display=swap"
rel="stylesheet"
/>
<link rel="icon" href="/favicon.ico" />
<link rel="icon" type="image/png" href="/icon.png" />
<title>T3 Code</title>
</head>
<body>
<div class="page">
<nav class="nav">
<a href="/" class="nav-brand">
<img src="/icon.png" alt="T3" class="nav-icon" />
</a>
<a
href="https://github.com/pingdotgg/t3code"
target="_blank"
rel="noopener noreferrer"
class="nav-github"
>
GitHub
<span class="nav-github-arrow" aria-hidden="true">&#8599;</span>
</a>
</nav>
<main class="main">
<h1 class="tagline">T3 Code is the best way to code with AI.</h1>
<a
href="https://github.com/pingdotgg/t3code/releases"
target="_blank"
rel="noopener noreferrer"
class="hero-button"
>
Download now
</a>
<div class="screenshot-wrap">
<img src="/screenshot.jpeg" alt="T3 Code" class="screenshot" />
</div>
</main>
<footer class="footer">
<span class="footer-copy">&copy; {new Date().getFullYear()} T3 Tools Inc</span>
<div class="footer-links">
<a href="https://github.com/pingdotgg/t3code" target="_blank" rel="noopener noreferrer">GitHub</a>
<a href="https://discord.gg/jn4EGJjrvv" target="_blank" rel="noopener noreferrer">Discord</a>
</div>
</footer>
</div>
</body>
</html>
<style>
:root {
--bg: #09090b;
--fg: #fafafa;
--fg-muted: #a1a1aa;
--fg-dim: #71717a;
--border: rgba(255, 255, 255, 0.08);
}
* {
box-sizing: border-box;
margin: 0;
padding: 0;
}
html {
color-scheme: dark;
}
body {
background: var(--bg);
color: var(--fg);
font-family: "DM Sans", -apple-system, BlinkMacSystemFont, system-ui, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
min-height: 100vh;
overflow-x: hidden;
}
body::after {
content: "";
position: fixed;
inset: 0;
pointer-events: none;
opacity: 0.035;
background-image: url("data:image/svg+xml,%3Csvg viewBox='0 0 256 256' xmlns='http://www.w3.org/2000/svg'%3E%3Cfilter id='n'%3E%3CfeTurbulence type='fractalNoise' baseFrequency='0.9' numOctaves='4' stitchTiles='stitch'/%3E%3C/filter%3E%3Crect width='100%25' height='100%25' filter='url(%23n)'/%3E%3C/svg%3E");
background-repeat: repeat;
background-size: 256px 256px;
z-index: 9999;
}
a {
color: inherit;
text-decoration: none;
}
img {
display: block;
max-width: 100%;
}
/* ── Page ── */
.page {
min-height: 100vh;
display: flex;
flex-direction: column;
overflow-x: hidden;
}
/* ── Navbar ── */
.nav {
display: flex;
align-items: center;
justify-content: space-between;
padding: 1.5rem 2.5rem;
opacity: 0.5;
transition: opacity 0.4s ease;
}
.nav:hover {
opacity: 1;
}
.nav-brand {
display: flex;
align-items: center;
}
.nav-icon {
width: 28px;
height: 28px;
border-radius: 6px;
}
.nav-github {
display: flex;
align-items: center;
gap: 0.35rem;
color: var(--fg-muted);
font-size: 0.875rem;
transition: color 0.3s ease;
}
.nav-github:hover {
color: var(--fg);
}
.nav-github-arrow {
display: inline-block;
transition: transform 0.3s ease;
}
.nav-github:hover .nav-github-arrow {
transform: translateX(2px) translateY(-1px);
}
/* ── Main content ── */
.main {
flex: 1;
display: flex;
flex-direction: column;
align-items: center;
padding-top: 10vh;
}
/* ── Tagline ── */
.tagline {
font-weight: 500;
font-size: clamp(2rem, 5vw, 3.5rem);
letter-spacing: -0.035em;
line-height: 1.15;
text-align: center;
margin: 0 0 6vh;
opacity: 0;
animation: fade-in 1s ease-out forwards;
}
/* ── Hero button ── */
.hero-button {
display: inline-block;
background: #fafafa;
color: #09090b;
padding: 0.75rem 2rem;
border-radius: 999px;
font-weight: 600;
font-size: 0.9rem;
margin-bottom: 5vh;
opacity: 0;
animation: fade-in 1s ease-out 0.15s forwards;
transition: transform 0.25s ease, box-shadow 0.25s ease;
}
.hero-button:hover {
transform: scale(1.03);
box-shadow: 0 0 24px rgba(255, 255, 255, 0.08);
}
.hero-button:active {
transform: scale(0.98);
}
/* ── Screenshot ── */
.screenshot-wrap {
margin: 0 auto;
width: min(95vw, 1400px);
opacity: 0;
transform: scale(0.98);
animation: screenshot-in 1s ease-out 0.15s forwards;
}
.screenshot {
width: 100%;
display: block;
border-radius: 16px;
border: 1px solid rgba(255, 255, 255, 0.06);
mask-image: linear-gradient(to bottom, black 80%, transparent 100%);
-webkit-mask-image: linear-gradient(to bottom, black 80%, transparent 100%);
}
.screenshot-wrap::after {
content: "";
display: block;
width: 100%;
height: 120px;
background: inherit;
margin-top: -1px;
opacity: 0.04;
transform: scaleY(-1);
mask-image: linear-gradient(to bottom, black 0%, transparent 60%);
-webkit-mask-image: linear-gradient(to bottom, black 0%, transparent 60%);
pointer-events: none;
}
/* ── Footer ── */
.footer {
display: flex;
align-items: center;
justify-content: space-between;
padding: 1.5rem 2.5rem;
font-size: 0.8rem;
color: var(--fg-dim);
}
.footer-links {
display: flex;
gap: 1.25rem;
}
.footer-links a {
color: var(--fg-dim);
transition: color 0.3s ease;
}
.footer-links a:hover {
color: var(--fg);
}
/* ── Animations ── */
@keyframes fade-in {
from {
opacity: 0;
transform: translateY(8px);
}
to {
opacity: 1;
transform: translateY(0);
}
}
@keyframes screenshot-in {
from {
opacity: 0;
transform: scale(0.98);
}
to {
opacity: 1;
transform: scale(1);
}
}
/* ── Mobile ── */
@media (max-width: 640px) {
.nav {
padding: 1.25rem 1.25rem;
}
.main {
padding-top: 7vh;
}
.tagline {
margin-bottom: 4vh;
}
.screenshot-wrap {
width: 95vw;
}
.footer {
padding: 1.25rem;
}
}
</style>
+3
View File
@@ -0,0 +1,3 @@
{
"extends": "astro/tsconfigs/strict"
}
@@ -37,7 +37,10 @@ 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 { AnalyticsService } from "../src/telemetry/Services/AnalyticsService.ts";
import { CheckpointReactorLive } from "../src/orchestration/Layers/CheckpointReactor.ts";
import { OrchestrationEngineLive } from "../src/orchestration/Layers/OrchestrationEngine.ts";
import { OrchestrationProjectionPipelineLive } from "../src/orchestration/Layers/ProjectionPipeline.ts";
@@ -150,7 +153,7 @@ export interface OrchestrationIntegrationHarness {
readonly rootDir: string;
readonly workspaceDir: string;
readonly dbPath: string;
readonly adapterHarness: TestProviderAdapterHarness;
readonly adapterHarness: TestProviderAdapterHarness | null;
readonly engine: OrchestrationEngineShape;
readonly snapshotQuery: ProjectionSnapshotQuery["Service"];
readonly providerService: ProviderService["Service"];
@@ -185,229 +188,261 @@ export interface OrchestrationIntegrationHarness {
readonly dispose: Effect.Effect<void, never>;
}
export const makeOrchestrationIntegrationHarness = Effect.gen(function* () {
const sleep = (ms: number) => Effect.sleep(ms);
const adapterHarness = yield* makeTestProviderAdapterHarness;
interface MakeOrchestrationIntegrationHarnessOptions {
readonly provider?: "codex";
readonly realCodex?: boolean;
}
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);
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 registry: typeof ProviderAdapterRegistry.Service = {
getByProvider: (provider) =>
provider === "codex"
? Effect.succeed(adapterHarness.adapter)
: Effect.fail(new ProviderUnsupportedError({ provider })),
listProviders: () => Effect.succeed(["codex"]),
};
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),
Layer.provide(AnalyticsService.layerTest),
)
: makeProviderServiceLive().pipe(
Layer.provide(providerSessionDirectoryLayer),
Layer.provide(fakeRegistry!),
Layer.provide(AnalyticsService.layerTest),
);
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 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 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 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 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 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}'`,
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 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,
) as Effect.Effect<
{
readonly status: "pending" | "resolved";
readonly decision: "accept" | "acceptForSession" | "decline" | "cancel" | null;
readonly resolvedAt: string | null;
},
never
>;
) =>
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>;
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 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 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)
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 closeScopeExit = yield* Effect.exit(Scope.close(scope, Exit.void));
const disposeRuntimeExit = yield* Effect.exit(Effect.promise(() => runtime.dispose()));
const failureCause = Exit.isFailure(closeScopeExit)
? closeScopeExit.cause
: Exit.isFailure(disposeRuntimeExit)
? disposeRuntimeExit.cause
: null;
if (failureCause) {
return yield* Effect.failCause(failureCause);
}
if (failureCause) {
return yield* Effect.failCause(failureCause);
}
});
yield* shutdown.pipe(
Effect.ensuring(
Effect.sync(() => {
fs.rmSync(rootDir, { recursive: true, force: true });
}),
),
);
});
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;
});
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,13 +25,29 @@ import type {
} from "../src/provider/Services/ProviderAdapter.ts";
export interface TestTurnResponse {
readonly events: ReadonlyArray<ProviderRuntimeEvent>;
readonly events: ReadonlyArray<FixtureProviderRuntimeEvent>;
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";
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;
@@ -40,82 +56,217 @@ 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";
readonly queueTurnResponse: (
sessionId: string,
threadId: ThreadId,
response: TestTurnResponse,
) => Effect.Effect<void, ProviderAdapterSessionNotFoundError>;
readonly queueTurnResponseForNextSession: (
response: TestTurnResponse,
) => Effect.Effect<void, never>;
readonly getRollbackCalls: (sessionId: string) => ReadonlyArray<number>;
readonly getApprovalResponses: (sessionId: string) => ReadonlyArray<{
readonly sessionId: ProviderSessionId;
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 requestId: ApprovalRequestId;
readonly decision: ProviderApprovalDecision;
}>;
}
const PROVIDER = "codex" as const;
interface MakeTestProviderAdapterHarnessOptions {
readonly provider?: "codex";
}
function nowIso(): string {
return new Date().toISOString();
}
function sessionNotFound(sessionId: string): ProviderAdapterSessionNotFoundError {
function sessionNotFound(
provider: "codex",
threadId: ThreadId,
): ProviderAdapterSessionNotFoundError {
return new ProviderAdapterSessionNotFoundError({
provider: PROVIDER,
sessionId,
provider,
threadId: String(threadId),
});
}
function missingSessionEffect(sessionId: string): Effect.Effect<never, ProviderAdapterError> {
return Effect.fail(sessionNotFound(sessionId));
function missingSessionEffect(
provider: "codex",
threadId: ThreadId,
): Effect.Effect<never, ProviderAdapterError> {
return Effect.fail(sessionNotFound(provider, threadId));
}
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;
}>
>();
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;
}>
>();
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 sessionId = ProviderSessionId.makeUnsafe(`test-session-${sessionCount}`);
const threadId = ProviderThreadId.makeUnsafe(`test-thread-${sessionCount}`);
const threadId = input.threadId;
const createdAt = nowIso();
const session: ProviderSession = {
sessionId,
provider: PROVIDER,
provider,
status: "ready",
runtimeMode: input.runtimeMode,
threadId,
cwd: input.cwd,
resumeCursor: input.resumeCursor ?? { threadId: String(threadId), seed: sessionCount },
createdAt,
updatedAt: createdAt,
};
sessions.set(sessionId, {
sessions.set(threadId, {
session,
snapshot: {
threadId,
@@ -131,21 +282,21 @@ export const makeTestProviderAdapterHarness = Effect.gen(function* () {
const sendTurn: ProviderAdapterShape<ProviderAdapterError>["sendTurn"] = (input) =>
Effect.gen(function* () {
const state = sessions.get(input.sessionId);
const state = sessions.get(input.threadId);
if (!state) {
return yield* missingSessionEffect(input.sessionId);
return yield* missingSessionEffect(provider, input.threadId);
}
state.turnCount += 1;
const turnCount = state.turnCount;
const turnId = ProviderTurnId.makeUnsafe(`turn-${turnCount}`);
const turnId = TurnId.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 session ${input.sessionId}.`,
issue: `No queued turn response for thread ${input.threadId}.`,
});
}
@@ -155,20 +306,27 @@ export const makeTestProviderAdapterHarness = Effect.gen(function* () {
const rawEvent: Record<string, unknown> = {
...(fixtureEvent as Record<string, unknown>),
eventId: randomUUID(),
provider: PROVIDER,
sessionId: input.sessionId,
provider,
sessionId: RuntimeSessionId.makeUnsafe(String(input.threadId)),
createdAt: nowIso(),
};
if (Object.hasOwn(rawEvent, "threadId")) {
rawEvent.threadId = state.snapshot.threadId;
}
rawEvent.threadId = state.snapshot.threadId;
if (Object.hasOwn(rawEvent, "turnId")) {
rawEvent.turnId = turnId;
}
const runtimeEvent = rawEvent as ProviderRuntimeEvent;
if (runtimeEvent.type === "message.delta") {
assistantDeltas.push(runtimeEvent.delta);
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);
}
}
if (runtimeEvent.type === "turn.completed") {
deferredTurnCompletedEvents.push(runtimeEvent);
@@ -206,12 +364,13 @@ export const makeTestProviderAdapterHarness = Effect.gen(function* () {
yield* emit({
type: "turn.completed",
eventId: EventId.makeUnsafe(randomUUID()),
provider: PROVIDER,
sessionId: input.sessionId,
provider,
createdAt: nowIso(),
threadId: state.snapshot.threadId,
turnId,
status: "completed",
payload: {
state: "completed",
},
});
} else {
for (const completedEvent of deferredTurnCompletedEvents) {
@@ -226,58 +385,71 @@ export const makeTestProviderAdapterHarness = Effect.gen(function* () {
});
const interruptTurn: ProviderAdapterShape<ProviderAdapterError>["interruptTurn"] = (
sessionId,
_turnId,
) => (sessions.has(sessionId) ? Effect.void : missingSessionEffect(sessionId));
threadId,
turnId,
) =>
sessions.has(threadId)
? Effect.sync(() => {
const existing = interruptCallsBySession.get(threadId) ?? [];
existing.push(turnId);
interruptCallsBySession.set(threadId, existing);
})
: missingSessionEffect(provider, threadId);
const respondToRequest: ProviderAdapterShape<ProviderAdapterError>["respondToRequest"] = (
sessionId,
threadId,
requestId,
decision,
) =>
sessions.has(sessionId)
sessions.has(threadId)
? Effect.sync(() => {
const existing = approvalResponsesBySession.get(sessionId) ?? [];
const existing = approvalResponsesBySession.get(threadId) ?? [];
existing.push({
sessionId,
threadId,
requestId,
decision,
});
approvalResponsesBySession.set(sessionId, existing);
approvalResponsesBySession.set(threadId, existing);
})
: missingSessionEffect(sessionId);
: missingSessionEffect(provider, threadId);
const stopSession: ProviderAdapterShape<ProviderAdapterError>["stopSession"] = (sessionId) =>
const respondToUserInput: ProviderAdapterShape<ProviderAdapterError>["respondToUserInput"] = (
threadId,
_requestId,
_answers,
) => (sessions.has(threadId) ? Effect.void : missingSessionEffect(provider, threadId));
const stopSession: ProviderAdapterShape<ProviderAdapterError>["stopSession"] = (threadId) =>
Effect.sync(() => {
sessions.delete(sessionId);
sessions.delete(threadId);
});
const listSessions: ProviderAdapterShape<ProviderAdapterError>["listSessions"] = () =>
Effect.sync(() => Array.from(sessions.values(), (state) => state.session));
const hasSession: ProviderAdapterShape<ProviderAdapterError>["hasSession"] = (sessionId) =>
Effect.succeed(sessions.has(sessionId));
const hasSession: ProviderAdapterShape<ProviderAdapterError>["hasSession"] = (threadId) =>
Effect.succeed(sessions.has(threadId));
const readThread: ProviderAdapterShape<ProviderAdapterError>["readThread"] = (sessionId) => {
const state = sessions.get(sessionId);
const readThread: ProviderAdapterShape<ProviderAdapterError>["readThread"] = (threadId) => {
const state = sessions.get(threadId);
if (!state) {
return missingSessionEffect(sessionId);
return missingSessionEffect(provider, threadId);
}
return Effect.succeed(state.snapshot);
};
const rollbackThread: ProviderAdapterShape<ProviderAdapterError>["rollbackThread"] = (
sessionId,
threadId,
numTurns,
) => {
const state = sessions.get(sessionId);
const state = sessions.get(threadId);
if (!state) {
return missingSessionEffect(sessionId);
return missingSessionEffect(provider, threadId);
}
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.",
}),
@@ -301,11 +473,15 @@ export const makeTestProviderAdapterHarness = Effect.gen(function* () {
});
const adapter: ProviderAdapterShape<ProviderAdapterError> = {
provider: PROVIDER,
provider,
capabilities: {
sessionModelSwitch: "in-session",
},
startSession,
sendTurn,
interruptTurn,
respondToRequest,
respondToUserInput,
stopSession,
listSessions,
hasSession,
@@ -316,16 +492,16 @@ export const makeTestProviderAdapterHarness = Effect.gen(function* () {
};
const queueTurnResponse = (
sessionId: string,
threadId: ThreadId,
response: TestTurnResponse,
): Effect.Effect<void, ProviderAdapterSessionNotFoundError> =>
Effect.sync(() => sessions.get(sessionId)).pipe(
Effect.sync(() => sessions.get(threadId)).pipe(
Effect.flatMap((state) =>
state
? Effect.sync(() => {
state.queuedResponses.push(response);
})
: Effect.fail(sessionNotFound(sessionId)),
: Effect.fail(sessionNotFound(provider, threadId)),
),
);
@@ -336,22 +512,35 @@ export const makeTestProviderAdapterHarness = Effect.gen(function* () {
queuedResponsesForNextSession.push(response);
});
const getRollbackCalls = (sessionId: string): ReadonlyArray<number> => {
const state = sessions.get(sessionId);
const getRollbackCalls = (threadId: ThreadId): ReadonlyArray<number> => {
const state = sessions.get(threadId);
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 = (
sessionId: string,
threadId: ThreadId,
): ReadonlyArray<{
readonly sessionId: ProviderSessionId;
readonly threadId: ThreadId;
readonly requestId: ApprovalRequestId;
readonly decision: ProviderApprovalDecision;
}> => {
const responses = approvalResponsesBySession.get(sessionId);
const responses = approvalResponsesBySession.get(threadId);
if (!responses) {
return [];
}
@@ -360,9 +549,13 @@ export const makeTestProviderAdapterHarness = Effect.gen(function* () {
return {
adapter,
provider,
queueTurnResponse,
queueTurnResponseForNextSession,
getStartCount,
getRollbackCalls,
getInterruptCalls,
listActiveSessionIds,
getApprovalResponses,
} satisfies TestProviderAdapterHarness;
});
@@ -1,22 +1,16 @@
import {
ApprovalRequestId,
EventId,
ProviderSessionId,
ProviderThreadId,
ProviderTurnId,
type ProviderRuntimeEvent,
} from "@t3tools/contracts";
import { EventId, RuntimeRequestId } from "@t3tools/contracts";
import type { LegacyProviderRuntimeEvent } from "../TestProviderAdapter.integration.ts";
const PROVIDER = "codex" as const;
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");
const SESSION_ID = "fixture-session";
const THREAD_ID = "fixture-thread";
const TURN_ID = "fixture-turn";
const REQUEST_ID = RuntimeRequestId.makeUnsafe("req-1");
function baseEvent(
eventId: string,
createdAt: string,
): Pick<ProviderRuntimeEvent, "eventId" | "provider" | "sessionId" | "createdAt"> {
): Pick<LegacyProviderRuntimeEvent, "eventId" | "provider" | "sessionId" | "createdAt"> {
return {
eventId: EventId.makeUnsafe(eventId),
provider: PROVIDER,
@@ -31,29 +25,38 @@ export const codexTurnTextFixture = [
...baseEvent("evt-1", "2026-02-23T00:00:00.000Z"),
threadId: THREAD_ID,
turnId: TURN_ID,
payload: {},
},
{
type: "message.delta",
type: "content.delta",
...baseEvent("evt-2", "2026-02-23T00:00:00.100Z"),
threadId: THREAD_ID,
turnId: TURN_ID,
delta: "I will make a small update.\n",
payload: {
streamKind: "assistant_text",
delta: "I will make a small update.\n",
},
},
{
type: "message.delta",
type: "content.delta",
...baseEvent("evt-3", "2026-02-23T00:00:00.200Z"),
threadId: THREAD_ID,
turnId: TURN_ID,
delta: "Done.\n",
payload: {
streamKind: "assistant_text",
delta: "Done.\n",
},
},
{
type: "turn.completed",
...baseEvent("evt-4", "2026-02-23T00:00:00.300Z"),
threadId: THREAD_ID,
turnId: TURN_ID,
status: "completed",
payload: {
state: "completed",
},
},
] satisfies ReadonlyArray<ProviderRuntimeEvent>;
] satisfies ReadonlyArray<LegacyProviderRuntimeEvent>;
export const codexTurnToolFixture = [
{
@@ -61,40 +64,51 @@ export const codexTurnToolFixture = [
...baseEvent("evt-11", "2026-02-23T00:01:00.000Z"),
threadId: THREAD_ID,
turnId: TURN_ID,
payload: {},
},
{
type: "tool.started",
type: "item.started",
...baseEvent("evt-12", "2026-02-23T00:01:00.100Z"),
threadId: THREAD_ID,
turnId: TURN_ID,
toolKind: "command",
title: "Command run",
detail: "echo integration",
payload: {
itemType: "command_execution",
title: "Command run",
detail: "echo integration",
},
},
{
type: "tool.completed",
type: "item.completed",
...baseEvent("evt-13", "2026-02-23T00:01:00.200Z"),
threadId: THREAD_ID,
turnId: TURN_ID,
toolKind: "command",
title: "Command run",
detail: "echo integration",
payload: {
itemType: "command_execution",
status: "completed",
title: "Command run",
detail: "echo integration",
},
},
{
type: "message.delta",
type: "content.delta",
...baseEvent("evt-14", "2026-02-23T00:01:00.300Z"),
threadId: THREAD_ID,
turnId: TURN_ID,
delta: "Applied the requested edit.\n",
payload: {
streamKind: "assistant_text",
delta: "Applied the requested edit.\n",
},
},
{
type: "turn.completed",
...baseEvent("evt-15", "2026-02-23T00:01:00.400Z"),
threadId: THREAD_ID,
turnId: TURN_ID,
status: "completed",
payload: {
state: "completed",
},
},
] satisfies ReadonlyArray<ProviderRuntimeEvent>;
] satisfies ReadonlyArray<LegacyProviderRuntimeEvent>;
export const codexTurnApprovalFixture = [
{
@@ -102,37 +116,47 @@ export const codexTurnApprovalFixture = [
...baseEvent("evt-21", "2026-02-23T00:02:00.000Z"),
threadId: THREAD_ID,
turnId: TURN_ID,
payload: {},
},
{
type: "approval.requested",
type: "request.opened",
...baseEvent("evt-22", "2026-02-23T00:02:00.100Z"),
threadId: THREAD_ID,
turnId: TURN_ID,
requestId: REQUEST_ID,
requestKind: "command",
detail: "Please approve command",
payload: {
requestType: "command_execution_approval",
detail: "Please approve command",
},
},
{
type: "approval.resolved",
type: "request.resolved",
...baseEvent("evt-23", "2026-02-23T00:02:00.200Z"),
threadId: THREAD_ID,
turnId: TURN_ID,
requestId: REQUEST_ID,
requestKind: "command",
decision: "accept",
payload: {
requestType: "command_execution_approval",
decision: "accept",
},
},
{
type: "message.delta",
type: "content.delta",
...baseEvent("evt-24", "2026-02-23T00:02:00.300Z"),
threadId: THREAD_ID,
turnId: TURN_ID,
delta: "Approval received and command executed.\n",
payload: {
streamKind: "assistant_text",
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,
status: "completed",
payload: {
state: "completed",
},
},
] satisfies ReadonlyArray<ProviderRuntimeEvent>;
] satisfies ReadonlyArray<LegacyProviderRuntimeEvent>;
@@ -4,12 +4,10 @@ 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";
@@ -27,19 +25,14 @@ 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_SESSION_ID = asProviderSessionId("fixture-session");
const FIXTURE_THREAD_ID = asProviderThreadId("fixture-thread");
const FIXTURE_TURN_ID = asProviderTurnId("fixture-turn");
const FIXTURE_TURN_ID = "fixture-turn";
const APPROVAL_REQUEST_ID = asApprovalRequestId("req-approval-1");
type IntegrationProvider = "codex";
function nowIso() {
return new Date().toISOString();
@@ -76,18 +69,30 @@ function waitForSync<A>(
});
}
function runtimeBase(eventId: string, createdAt: string) {
function runtimeBase(eventId: string, createdAt: string, provider: IntegrationProvider = "codex") {
return {
eventId: asEventId(eventId),
provider: "codex" as const,
sessionId: FIXTURE_SESSION_ID,
provider,
createdAt,
};
}
function withHarness<A, E>(use: (harness: OrchestrationIntegrationHarness) => Effect.Effect<A, E>) {
function withHarness<A, E>(
use: (harness: OrchestrationIntegrationHarness) => Effect.Effect<A, E>,
provider: IntegrationProvider = "codex",
) {
return Effect.acquireUseRelease(
makeOrchestrationIntegrationHarness,
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 }),
use,
(harness) => harness.dispose,
);
@@ -114,6 +119,8 @@ 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,
@@ -125,6 +132,7 @@ const startTurn = (input: {
readonly commandId: string;
readonly messageId: string;
readonly text: string;
readonly provider?: IntegrationProvider;
}) =>
input.harness.engine.dispatch({
type: "thread.turn.start",
@@ -136,8 +144,9 @@ const startTurn = (input: {
text: input.text,
attachments: [],
},
approvalPolicy: "on-request",
sandboxMode: "workspace-write",
...(input.provider !== undefined ? { provider: input.provider } : {}),
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "approval-required",
createdAt: nowIso(),
});
@@ -151,27 +160,27 @@ 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: FIXTURE_THREAD_ID,
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
},
{
type: "message.delta",
...runtimeBase("evt-single-2", "2026-02-24T10:00:00.100Z"),
threadId: FIXTURE_THREAD_ID,
threadId: 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: FIXTURE_THREAD_ID,
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
status: "completed",
},
],
};
yield* harness.adapterHarness.queueTurnResponseForNextSession(turnResponse);
yield* harness.adapterHarness!.queueTurnResponseForNextSession(turnResponse);
yield* startTurn({
harness,
commandId: "cmd-turn-start-single",
@@ -211,23 +220,112 @@ 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* () {
yield* seedProjectAndThread(harness);
yield* harness.adapterHarness.queueTurnResponseForNextSession({
yield* harness.adapterHarness!.queueTurnResponseForNextSession({
events: [
{
type: "turn.started",
...runtimeBase("evt-multi-1", "2026-02-24T10:01:00.000Z"),
threadId: FIXTURE_THREAD_ID,
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
},
{
type: "tool.started",
...runtimeBase("evt-multi-2", "2026-02-24T10:01:00.100Z"),
threadId: FIXTURE_THREAD_ID,
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
toolKind: "command",
title: "Edit file",
@@ -236,7 +334,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: FIXTURE_THREAD_ID,
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
toolKind: "command",
title: "Edit file",
@@ -245,14 +343,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: FIXTURE_THREAD_ID,
threadId: 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: FIXTURE_THREAD_ID,
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
status: "completed",
},
@@ -270,35 +368,30 @@ it.live("runs multi-turn file edits and persists checkpoint diffs", () =>
text: "Make first edit",
});
const firstTurnThread = yield* harness.waitForThread(
yield* harness.waitForThread(
THREAD_ID,
(entry) => entry.checkpoints.length === 1 && entry.session?.providerSessionId !== null,
(entry) => entry.checkpoints.length === 1 && entry.session?.threadId === "thread-1",
);
const sessionId = firstTurnThread.session?.providerSessionId;
assert.equal(sessionId !== null, true);
if (!sessionId) {
return;
}
yield* harness.adapterHarness.queueTurnResponse(sessionId, {
yield* harness.adapterHarness!.queueTurnResponse(THREAD_ID, {
events: [
{
type: "turn.started",
...runtimeBase("evt-multi-6", "2026-02-24T10:02:00.000Z"),
threadId: FIXTURE_THREAD_ID,
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
},
{
type: "message.delta",
...runtimeBase("evt-multi-7", "2026-02-24T10:02:00.100Z"),
threadId: FIXTURE_THREAD_ID,
threadId: 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: FIXTURE_THREAD_ID,
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
status: "completed",
},
@@ -380,18 +473,18 @@ it.live("tracks approval requests and resolves pending approvals on user respons
Effect.gen(function* () {
yield* seedProjectAndThread(harness);
yield* harness.adapterHarness.queueTurnResponseForNextSession({
yield* harness.adapterHarness!.queueTurnResponseForNextSession({
events: [
{
type: "turn.started",
...runtimeBase("evt-approval-1", "2026-02-24T10:03:00.000Z"),
threadId: FIXTURE_THREAD_ID,
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
},
{
type: "approval.requested",
...runtimeBase("evt-approval-2", "2026-02-24T10:03:00.100Z"),
threadId: FIXTURE_THREAD_ID,
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
requestId: APPROVAL_REQUEST_ID,
requestKind: "command",
@@ -400,7 +493,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: FIXTURE_THREAD_ID,
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
status: "completed",
},
@@ -444,9 +537,8 @@ 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(providerSessionId),
() => harness.adapterHarness!.getApprovalResponses(THREAD_ID),
(responses) => responses.length === 1,
"provider approval response",
);
@@ -462,35 +554,42 @@ it.live("records failed turn runtime state and checkpoint status as error", () =
Effect.gen(function* () {
yield* seedProjectAndThread(harness);
yield* harness.adapterHarness.queueTurnResponseForNextSession({
yield* harness.adapterHarness!.queueTurnResponseForNextSession({
events: [
{
type: "turn.started",
...runtimeBase("evt-failure-1", "2026-02-24T10:04:00.000Z"),
threadId: FIXTURE_THREAD_ID,
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
},
{
type: "message.delta",
type: "content.delta",
...runtimeBase("evt-failure-2", "2026-02-24T10:04:00.100Z"),
threadId: FIXTURE_THREAD_ID,
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
delta: "Partial output before failure.\n",
payload: {
streamKind: "assistant_text",
delta: "Partial output before failure.\n",
},
},
{
type: "runtime.error",
...runtimeBase("evt-failure-3", "2026-02-24T10:04:00.200Z"),
threadId: FIXTURE_THREAD_ID,
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
message: "Sandbox command failed.",
payload: {
message: "Sandbox command failed.",
},
},
{
type: "turn.completed",
...runtimeBase("evt-failure-4", "2026-02-24T10:04:00.300Z"),
threadId: FIXTURE_THREAD_ID,
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
status: "failed",
errorMessage: "Sandbox command failed.",
payload: {
state: "failed",
errorMessage: "Sandbox command failed.",
},
},
],
});
@@ -534,18 +633,18 @@ it.live("reverts to an earlier checkpoint and trims checkpoint projections + git
Effect.gen(function* () {
yield* seedProjectAndThread(harness);
yield* harness.adapterHarness.queueTurnResponseForNextSession({
yield* harness.adapterHarness!.queueTurnResponseForNextSession({
events: [
{
type: "turn.started",
...runtimeBase("evt-revert-1", "2026-02-24T10:05:00.000Z"),
threadId: FIXTURE_THREAD_ID,
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
},
{
type: "tool.started",
...runtimeBase("evt-revert-1-tool-started", "2026-02-24T10:05:00.025Z"),
threadId: FIXTURE_THREAD_ID,
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
toolKind: "command",
title: "Edit file",
@@ -554,7 +653,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: FIXTURE_THREAD_ID,
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
toolKind: "command",
title: "Edit file",
@@ -563,14 +662,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: FIXTURE_THREAD_ID,
threadId: 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: FIXTURE_THREAD_ID,
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
status: "completed",
},
@@ -587,28 +686,23 @@ it.live("reverts to an earlier checkpoint and trims checkpoint projections + git
text: "First edit",
});
const firstTurnThread = yield* harness.waitForThread(
yield* harness.waitForThread(
THREAD_ID,
(entry) => entry.session?.providerSessionId !== null && entry.checkpoints.length === 1,
(entry) => entry.session?.threadId === "thread-1" && entry.checkpoints.length === 1,
);
const sessionId = firstTurnThread.session?.providerSessionId;
assert.equal(sessionId !== null, true);
if (!sessionId) {
return;
}
yield* harness.adapterHarness.queueTurnResponse(sessionId, {
yield* harness.adapterHarness!.queueTurnResponse(THREAD_ID, {
events: [
{
type: "turn.started",
...runtimeBase("evt-revert-3", "2026-02-24T10:05:01.000Z"),
threadId: FIXTURE_THREAD_ID,
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
},
{
type: "tool.started",
...runtimeBase("evt-revert-3-tool-started", "2026-02-24T10:05:01.025Z"),
threadId: FIXTURE_THREAD_ID,
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
toolKind: "command",
title: "Edit file",
@@ -617,7 +711,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: FIXTURE_THREAD_ID,
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
toolKind: "command",
title: "Edit file",
@@ -626,14 +720,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: FIXTURE_THREAD_ID,
threadId: 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: FIXTURE_THREAD_ID,
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
status: "completed",
},
@@ -702,7 +796,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(sessionId), [1]);
assert.deepEqual(harness.adapterHarness!.getRollbackCalls(THREAD_ID), [1]);
const checkpointRows = yield* harness.checkpointRepository.listByThreadId({
threadId: THREAD_ID,
@@ -1,4 +1,4 @@
import type { ProviderRuntimeEvent, ProviderSessionId } from "@t3tools/contracts";
import type { ProviderRuntimeEvent } from "@t3tools/contracts";
import { ThreadId } from "@t3tools/contracts";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { it, assert } from "@effect/vitest";
@@ -12,6 +12,7 @@ import {
ProviderService,
type ProviderServiceShape,
} from "../src/provider/Services/ProviderService.ts";
import { AnalyticsService } from "../src/telemetry/Services/AnalyticsService.ts";
import { SqlitePersistenceMemory } from "../src/persistence/Layers/Sqlite.ts";
import { ProviderSessionRuntimeRepositoryLive } from "../src/persistence/Layers/ProviderSessionRuntime.ts";
@@ -42,7 +43,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) =>
@@ -59,6 +60,7 @@ const makeIntegrationFixture = Effect.gen(function* () {
const shared = Layer.mergeAll(
directoryLayer,
Layer.succeed(ProviderAdapterRegistry, registry),
AnalyticsService.layerTest,
).pipe(Layer.provide(SqlitePersistenceMemory));
const layer = makeProviderServiceLive().pipe(Layer.provide(shared));
@@ -93,18 +95,18 @@ const collectEventsDuring = <A, E, R>(
const runTurn = (input: {
readonly provider: ProviderServiceShape;
readonly harness: TestProviderAdapterHarness;
readonly sessionId: ProviderSessionId;
readonly threadId: ThreadId;
readonly userText: string;
readonly response: TestTurnResponse;
}) =>
Effect.gen(function* () {
yield* input.harness.queueTurnResponse(input.sessionId, input.response);
yield* input.harness.queueTurnResponse(input.threadId, input.response);
return yield* collectEventsDuring(
input.provider.streamEvents,
input.response.events.length,
input.provider.sendTurn({
sessionId: input.sessionId,
threadId: input.threadId,
input: input.userText,
attachments: [],
}),
@@ -120,8 +122,10 @@ 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);
@@ -129,7 +133,7 @@ it.effect("replays typed runtime fixture events", () =>
const observedEvents = yield* runTurn({
provider,
harness: fixture.harness,
sessionId: session.sessionId,
threadId: session.threadId,
userText: "hello",
response: { events: codexTurnTextFixture },
});
@@ -153,8 +157,10 @@ 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);
@@ -162,7 +168,7 @@ it.effect("replays file-changing fixture turn events", () =>
const observedEvents = yield* runTurn({
provider,
harness: fixture.harness,
sessionId: session.sessionId,
threadId: session.threadId,
userText: "make a small change",
response: {
events: codexTurnToolFixture,
@@ -190,8 +196,10 @@ 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);
@@ -199,7 +207,7 @@ it.effect("runs multi-turn tool/approval flow", () =>
const firstTurnEvents = yield* runTurn({
provider,
harness: fixture.harness,
sessionId: session.sessionId,
threadId: session.threadId,
userText: "turn 1",
response: {
events: codexTurnToolFixture,
@@ -215,7 +223,7 @@ it.effect("runs multi-turn tool/approval flow", () =>
const secondTurnEvents = yield* runTurn({
provider,
harness: fixture.harness,
sessionId: session.sessionId,
threadId: session.threadId,
userText: "turn 2 approval",
response: {
events: codexTurnApprovalFixture,
@@ -242,8 +250,10 @@ 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);
@@ -251,7 +261,7 @@ it.effect("rolls back provider conversation state only", () =>
yield* runTurn({
provider,
harness: fixture.harness,
sessionId: session.sessionId,
threadId: session.threadId,
userText: "turn 1",
response: {
events: codexTurnToolFixture,
@@ -263,7 +273,7 @@ it.effect("rolls back provider conversation state only", () =>
yield* runTurn({
provider,
harness: fixture.harness,
sessionId: session.sessionId,
threadId: session.threadId,
userText: "turn 2 approval",
response: {
events: codexTurnApprovalFixture,
@@ -273,11 +283,11 @@ it.effect("rolls back provider conversation state only", () =>
});
yield* provider.rollbackConversation({
sessionId: session.sessionId,
threadId: session.threadId,
numTurns: 1,
});
const rollbackCalls = fixture.harness.getRollbackCalls(session.sessionId);
const rollbackCalls = fixture.harness.getRollbackCalls(session.threadId);
assert.deepEqual(rollbackCalls, [1]);
const readme = yield* readFileString(join(fixture.cwd, "README.md"));
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "t3",
"version": "0.0.0-alpha.20",
"version": "0.0.0-alpha.22",
"repository": {
"type": "git",
"url": "https://github.com/pingdotgg/t3code",
+95 -6
View File
@@ -6,6 +6,7 @@ import { Data, Effect, FileSystem, Logger, Option, Path } from "effect";
import { Command, Flag } from "effect/unstable/cli";
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
import { DEVELOPMENT_ICON_OVERRIDES, PUBLISH_ICON_OVERRIDES } from "../../../scripts/lib/brand-assets.ts";
import { resolveCatalogDependencies } from "../../../scripts/lib/resolve-catalog.ts";
import rootPackageJson from "../../../package.json" with { type: "json" };
import serverPackageJson from "../package.json" with { type: "json" };
@@ -31,6 +32,84 @@ const runCommand = Effect.fn("runCommand")(function* (command: ChildProcess.Comm
}
});
interface PublishIconBackup {
readonly targetPath: string;
readonly backupPath: string;
}
const applyPublishIconOverrides = Effect.fn("applyPublishIconOverrides")(function* (
repoRoot: string,
serverDir: string,
) {
const path = yield* Path.Path;
const fs = yield* FileSystem.FileSystem;
const backups: PublishIconBackup[] = [];
for (const override of PUBLISH_ICON_OVERRIDES) {
const sourcePath = path.join(repoRoot, override.sourceRelativePath);
const targetPath = path.join(serverDir, override.targetRelativePath);
const backupPath = `${targetPath}.publish-bak`;
if (!(yield* fs.exists(sourcePath))) {
return yield* new CliError({
message: `Missing publish icon source: ${sourcePath}`,
});
}
if (!(yield* fs.exists(targetPath))) {
return yield* new CliError({
message: `Missing publish icon target: ${targetPath}. Run the build subcommand first.`,
});
}
yield* fs.copyFile(targetPath, backupPath);
yield* fs.copyFile(sourcePath, targetPath);
backups.push({ targetPath, backupPath });
}
yield* Effect.log("[cli] Applied publish icon overrides to dist/client");
return backups as ReadonlyArray<PublishIconBackup>;
});
const restorePublishIconOverrides = Effect.fn("restorePublishIconOverrides")(function* (
backups: ReadonlyArray<PublishIconBackup>,
) {
const fs = yield* FileSystem.FileSystem;
for (const backup of backups) {
if (!(yield* fs.exists(backup.backupPath))) {
continue;
}
yield* fs.rename(backup.backupPath, backup.targetPath);
}
});
const applyDevelopmentIconOverrides = Effect.fn("applyDevelopmentIconOverrides")(function* (
repoRoot: string,
serverDir: string,
) {
const path = yield* Path.Path;
const fs = yield* FileSystem.FileSystem;
for (const override of DEVELOPMENT_ICON_OVERRIDES) {
const sourcePath = path.join(repoRoot, override.sourceRelativePath);
const targetPath = path.join(serverDir, override.targetRelativePath);
if (!(yield* fs.exists(sourcePath))) {
return yield* new CliError({
message: `Missing development icon source: ${sourcePath}`,
});
}
if (!(yield* fs.exists(targetPath))) {
return yield* new CliError({
message: `Missing development icon target: ${targetPath}. Build web first.`,
});
}
yield* fs.copyFile(sourcePath, targetPath);
}
yield* Effect.log("[cli] Applied development icon overrides to dist/client");
});
// ---------------------------------------------------------------------------
// build subcommand
// ---------------------------------------------------------------------------
@@ -61,6 +140,7 @@ const buildCmd = Command.make(
if (yield* fs.exists(webDist)) {
yield* fs.copy(webDist, clientTarget);
yield* applyDevelopmentIconOverrides(repoRoot, serverDir);
yield* Effect.log("[cli] Bundled web app into dist/client");
} else {
yield* Effect.logWarning("[cli] Web dist not found — skipping client bundle.");
@@ -104,10 +184,8 @@ const publishCmd = Command.make(
yield* Effect.acquireUseRelease(
// Acquire: backup package.json, resolve catalog: deps, strip devDependencies/scripts
Effect.gen(function* () {
const original = yield* fs.readFileString(packageJsonPath);
yield* fs.writeFileString(backupPath, original);
// Build package.json for publish
// Resolve catalog dependencies before any file mutations. If this throws,
// acquire fails and no release hook runs, so filesystem must still be untouched.
const version = Option.getOrElse(config.appVersion, () => serverPackageJson.version);
const pkg = {
name: serverPackageJson.name,
@@ -120,15 +198,19 @@ const publishCmd = Command.make(
dependencies: serverPackageJson.dependencies as Record<string, unknown>,
};
// Resolve catalog: entries in production dependencies
pkg.dependencies = resolveCatalogDependencies(
pkg.dependencies,
rootPackageJson.workspaces.catalog,
"apps/server dependencies",
);
const original = yield* fs.readFileString(packageJsonPath);
yield* fs.writeFileString(backupPath, original);
yield* fs.writeFileString(packageJsonPath, `${JSON.stringify(pkg, null, 2)}\n`);
yield* Effect.log("[cli] Resolved package.json for publish");
const iconBackups = yield* applyPublishIconOverrides(repoRoot, serverDir);
return { iconBackups };
}),
// Use: npm publish
() =>
@@ -147,8 +229,15 @@ const publishCmd = Command.make(
);
}),
// Release: restore
() =>
(resource: { readonly iconBackups: ReadonlyArray<PublishIconBackup> }) =>
Effect.gen(function* () {
yield* restorePublishIconOverrides(resource.iconBackups).pipe(
Effect.catch((error) =>
Effect.logError(
`[cli] Failed to restore publish icon overrides: ${String(error)}`,
),
),
);
yield* fs.rename(backupPath, packageJsonPath);
if (config.verbose) yield* Effect.log("[cli] Restored original package.json");
}),
@@ -1,5 +1,6 @@
import {
CheckpointRef,
DEFAULT_PROVIDER_INTERACTION_MODE,
ProjectId,
ThreadId,
TurnId,
@@ -43,6 +44,8 @@ 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: {
@@ -58,6 +61,7 @@ function makeSnapshot(input: {
deletedAt: null,
messages: [],
activities: [],
proposedPlans: [],
checkpoints: [
{
turnId: TurnId.makeUnsafe("turn-1"),
+446 -18
View File
@@ -1,26 +1,42 @@
import { describe, expect, it, vi } from "vitest";
import { ProviderSessionId } from "@t3tools/contracts";
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 {
buildCodexInitializeParams,
CODEX_DEFAULT_MODE_DEVELOPER_INSTRUCTIONS,
CODEX_PLAN_MODE_DEVELOPER_INSTRUCTIONS,
CodexAppServerManager,
classifyCodexStderrLine,
isRecoverableThreadResumeError,
normalizeCodexModelSlug,
readCodexAccountSnapshot,
resolveCodexModelForAccount,
} from "./codexAppServerManager";
const asSessionId = (value: string): ProviderSessionId => ProviderSessionId.makeUnsafe(value);
const asThreadId = (value: string): ThreadId => ThreadId.makeUnsafe(value);
function createSendTurnHarness() {
const manager = new CodexAppServerManager();
const context = {
session: {
sessionId: "sess_1",
provider: "codex",
status: "ready",
threadId: "thread_1",
runtimeMode: "full-access",
model: "gpt-5.3-codex",
resumeCursor: { threadId: "thread_1" },
createdAt: "2026-02-10T00:00:00.000Z",
updatedAt: "2026-02-10T00:00:00.000Z",
},
account: {
type: "unknown",
planType: null,
sparkEnabled: true,
},
};
const requireSession = vi
@@ -50,10 +66,12 @@ function createThreadControlHarness() {
const manager = new CodexAppServerManager();
const context = {
session: {
sessionId: "sess_1",
provider: "codex",
status: "ready",
threadId: "thread_1",
runtimeMode: "full-access",
model: "gpt-5.3-codex",
resumeCursor: { threadId: "thread_1" },
createdAt: "2026-02-10T00:00:00.000Z",
updatedAt: "2026-02-10T00:00:00.000Z",
},
@@ -76,6 +94,47 @@ function createThreadControlHarness() {
return { manager, context, requireSession, sendRequest, updateSession };
}
function createPendingUserInputHarness() {
const manager = new CodexAppServerManager();
const context = {
session: {
provider: "codex",
status: "ready",
threadId: "thread_1",
runtimeMode: "full-access",
model: "gpt-5.3-codex",
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();
@@ -146,7 +205,84 @@ describe("isRecoverableThreadResumeError", () => {
});
});
describe("readCodexAccountSnapshot", () => {
it("disables spark for chatgpt plus accounts", () => {
expect(
readCodexAccountSnapshot({
type: "chatgpt",
email: "[email protected]",
planType: "plus",
}),
).toEqual({
type: "chatgpt",
planType: "plus",
sparkEnabled: false,
});
});
it("keeps spark enabled for chatgpt pro accounts", () => {
expect(
readCodexAccountSnapshot({
type: "chatgpt",
email: "[email protected]",
planType: "pro",
}),
).toEqual({
type: "chatgpt",
planType: "pro",
sparkEnabled: true,
});
});
it("keeps spark enabled for api key accounts", () => {
expect(
readCodexAccountSnapshot({
type: "apiKey",
}),
).toEqual({
type: "apiKey",
planType: null,
sparkEnabled: true,
});
});
});
describe("resolveCodexModelForAccount", () => {
it("falls back from spark to default for unsupported chatgpt plans", () => {
expect(
resolveCodexModelForAccount("gpt-5.3-codex-spark", {
type: "chatgpt",
planType: "plus",
sparkEnabled: false,
}),
).toBe("gpt-5.3-codex");
});
it("keeps spark for supported plans", () => {
expect(
resolveCodexModelForAccount("gpt-5.3-codex-spark", {
type: "chatgpt",
planType: "pro",
sparkEnabled: true,
}),
).toBe("gpt-5.3-codex-spark");
});
});
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,
},
});
});
it("emits session/startFailed when resolving cwd throws before process launch", async () => {
const manager = new CodexAppServerManager();
const events: Array<{ method: string; kind: string; message?: string }> = [];
@@ -164,7 +300,9 @@ describe("startSession", () => {
try {
await expect(
manager.startSession({
threadId: asThreadId("thread-1"),
provider: "codex",
runtimeMode: "full-access",
}),
).rejects.toThrow("cwd missing");
expect(events).toHaveLength(1);
@@ -186,7 +324,7 @@ describe("sendTurn", () => {
createSendTurnHarness();
const result = await manager.sendTurn({
sessionId: asSessionId("sess_1"),
threadId: asThreadId("thread_1"),
input: "Inspect this image",
attachments: [
{
@@ -195,17 +333,16 @@ describe("sendTurn", () => {
},
],
model: "gpt-5.3",
serviceTier: "fast",
effort: "high",
});
expect(result).toEqual({
threadId: "thread_1",
turnId: "turn_1",
resumeCursor: {
threadId: "thread_1",
},
resumeCursor: { threadId: "thread_1" },
});
expect(requireSession).toHaveBeenCalledWith("sess_1");
expect(requireSession).toHaveBeenCalledWith("thread_1");
expect(sendRequest).toHaveBeenCalledWith(context, "turn/start", {
threadId: "thread_1",
input: [
@@ -220,14 +357,13 @@ describe("sendTurn", () => {
},
],
model: "gpt-5.3-codex",
serviceTier: "fast",
effort: "high",
});
expect(updateSession).toHaveBeenCalledWith(context, {
status: "running",
activeTurnId: "turn_1",
resumeCursor: {
threadId: "thread_1",
},
resumeCursor: { threadId: "thread_1" },
});
});
@@ -235,7 +371,7 @@ describe("sendTurn", () => {
const { manager, context, sendRequest } = createSendTurnHarness();
await manager.sendTurn({
sessionId: asSessionId("sess_1"),
threadId: asThreadId("thread_1"),
attachments: [
{
type: "image",
@@ -252,6 +388,98 @@ describe("sendTurn", () => {
url: "data:image/png;base64,BBBB",
},
],
model: "gpt-5.3-codex",
});
});
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("passes Codex default mode as a collaboration preset on turn/start", async () => {
const { manager, context, sendRequest } = createSendTurnHarness();
await manager.sendTurn({
threadId: asThreadId("thread_1"),
input: "PLEASE IMPLEMENT THIS PLAN:\n- step 1",
interactionMode: "default",
});
expect(sendRequest).toHaveBeenCalledWith(context, "turn/start", {
threadId: "thread_1",
input: [
{
type: "text",
text: "PLEASE IMPLEMENT THIS PLAN:\n- step 1",
text_elements: [],
},
],
model: "gpt-5.3-codex",
collaborationMode: {
mode: "default",
settings: {
model: "gpt-5.3-codex",
reasoning_effort: "medium",
developer_instructions: CODEX_DEFAULT_MODE_DEVELOPER_INSTRUCTIONS,
},
},
});
});
it("keeps the session model when interaction mode is set without an explicit model", async () => {
const { manager, context, sendRequest } = createSendTurnHarness();
context.session.model = "gpt-5.2-codex";
await manager.sendTurn({
threadId: asThreadId("thread_1"),
input: "Plan this with my current session model",
interactionMode: "plan",
});
expect(sendRequest).toHaveBeenCalledWith(context, "turn/start", {
threadId: "thread_1",
input: [
{
type: "text",
text: "Plan this with my current session model",
text_elements: [],
},
],
model: "gpt-5.2-codex",
collaborationMode: {
mode: "plan",
settings: {
model: "gpt-5.2-codex",
reasoning_effort: "medium",
developer_instructions: CODEX_PLAN_MODE_DEVELOPER_INSTRUCTIONS,
},
},
});
});
@@ -260,7 +488,7 @@ describe("sendTurn", () => {
await expect(
manager.sendTurn({
sessionId: asSessionId("sess_1"),
threadId: asThreadId("thread_1"),
}),
).rejects.toThrow("Turn input must include text or attachments.");
});
@@ -281,9 +509,9 @@ describe("thread checkpoint control", () => {
},
});
const result = await manager.readThread(asSessionId("sess_1"));
const result = await manager.readThread(asThreadId("thread_1"));
expect(requireSession).toHaveBeenCalledWith("sess_1");
expect(requireSession).toHaveBeenCalledWith("thread_1");
expect(sendRequest).toHaveBeenCalledWith(context, "thread/read", {
threadId: "thread_1",
includeTurns: true,
@@ -311,7 +539,7 @@ describe("thread checkpoint control", () => {
],
});
const result = await manager.readThread(asSessionId("sess_1"));
const result = await manager.readThread(asThreadId("thread_1"));
expect(sendRequest).toHaveBeenCalledWith(context, "thread/read", {
threadId: "thread_1",
@@ -337,7 +565,7 @@ describe("thread checkpoint control", () => {
},
});
const result = await manager.rollbackThread(asSessionId("sess_1"), 2);
const result = await manager.rollbackThread(asThreadId("thread_1"), 2);
expect(sendRequest).toHaveBeenCalledWith(context, "thread/rollback", {
threadId: "thread_1",
@@ -353,3 +581,203 @@ 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"] },
},
},
}),
);
});
it("preserves explicit empty multi-select answers", async () => {
const { manager, context, requireSession, writeMessage, emitEvent } =
createPendingUserInputHarness();
await manager.respondToUserInput(
asThreadId("thread_1"),
ApprovalRequestId.makeUnsafe("req-user-input-1"),
{
scope: [],
},
);
expect(requireSession).toHaveBeenCalledWith("thread_1");
expect(writeMessage).toHaveBeenCalledWith(context, {
id: 42,
result: {
answers: {
scope: { answers: [] },
},
},
});
expect(emitEvent).toHaveBeenCalledWith(
expect.objectContaining({
method: "item/tool/requestUserInput/answered",
payload: {
requestId: "req-user-input-1",
answers: {
scope: { answers: [] },
},
},
}),
);
});
it("tracks file-read approval requests with the correct method", () => {
const manager = new CodexAppServerManager();
const context = {
session: {
sessionId: "sess_1",
provider: "codex",
status: "ready",
threadId: asThreadId("thread_1"),
resumeCursor: { threadId: "thread_1" },
createdAt: "2026-02-10T00:00:00.000Z",
updatedAt: "2026-02-10T00:00:00.000Z",
},
pendingApprovals: new Map(),
pendingUserInputs: new Map(),
};
type ApprovalRequestContext = {
session: typeof context.session;
pendingApprovals: typeof context.pendingApprovals;
pendingUserInputs: typeof context.pendingUserInputs;
};
(
manager as unknown as {
handleServerRequest: (
context: ApprovalRequestContext,
request: Record<string, unknown>,
) => void;
}
).handleServerRequest(context, {
jsonrpc: "2.0",
id: 42,
method: "item/fileRead/requestApproval",
params: {},
});
const request = Array.from(context.pendingApprovals.values())[0];
expect(request?.requestKind).toBe("file-read");
expect(request?.method).toBe("item/fileRead/requestApproval");
});
});
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
+2
View File
@@ -9,6 +9,7 @@ import { Command } from "effect/unstable/cli";
import { version } from "../package.json" with { type: "json" };
import { ServerLive } from "./wsServer";
import { NetService } from "@t3tools/shared/Net";
import { FetchHttpClient } from "effect/unstable/http";
const RuntimeLayer = Layer.empty.pipe(
Layer.provideMerge(CliConfig.layer),
@@ -16,6 +17,7 @@ const RuntimeLayer = Layer.empty.pipe(
Layer.provideMerge(OpenLive),
Layer.provideMerge(NetService.layer),
Layer.provideMerge(NodeServices.layer),
Layer.provideMerge(FetchHttpClient.layer),
);
Command.run(t3Cli, { version }).pipe(Effect.provide(RuntimeLayer), NodeRuntime.runMain);
+45 -2
View File
@@ -1,16 +1,20 @@
import * as Http from "node:http";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { assert, it, vi } from "@effect/vitest";
import type { OrchestrationReadModel } from "@t3tools/contracts";
import * as ConfigProvider from "effect/ConfigProvider";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Command from "effect/unstable/cli/Command";
import { FetchHttpClient } from "effect/unstable/http";
import { beforeEach } from "vitest";
import { NetService } from "@t3tools/shared/Net";
import { CliConfig, t3Cli, type CliConfigShape } from "./main";
import { CliConfig, recordStartupHeartbeat, t3Cli, type CliConfigShape } from "./main";
import { ServerConfig, type ServerConfigShape } from "./config";
import { Open, type OpenShape } from "./open";
import { ProjectionSnapshotQuery } from "./orchestration/Services/ProjectionSnapshotQuery";
import { AnalyticsService } from "./telemetry/Services/AnalyticsService";
import { Server, type ServerShape } from "./wsServer";
const start = vi.fn(() => undefined);
@@ -47,6 +51,8 @@ const testLayer = Layer.mergeAll(
openBrowser: (_target: string) => Effect.void,
openInEditor: () => Effect.void,
} satisfies OpenShape),
AnalyticsService.layerTest,
FetchHttpClient.layer,
NodeServices.layer,
);
@@ -77,7 +83,7 @@ beforeEach(() => {
findAvailablePort.mockImplementation((preferred: number) => Effect.succeed(preferred));
});
it.layer(testLayer)("server cli", (it) => {
it.layer(testLayer)("server CLI command", (it) => {
it.effect("parses all CLI flags and wires scoped start/stop", () =>
Effect.gen(function* () {
yield* runCli([
@@ -227,6 +233,43 @@ it.layer(testLayer)("server cli", (it) => {
}),
);
it.effect("records a startup heartbeat with thread/project counts", () =>
Effect.gen(function* () {
const recordTelemetry = vi.fn(
(_event: string, _properties?: Readonly<Record<string, unknown>>) => Effect.void,
);
const getSnapshot = vi.fn(() =>
Effect.succeed({
snapshotSequence: 2,
projects: [{} as OrchestrationReadModel["projects"][number]],
threads: [
{} as OrchestrationReadModel["threads"][number],
{} as OrchestrationReadModel["threads"][number],
],
updatedAt: new Date(1).toISOString(),
} satisfies OrchestrationReadModel),
);
yield* recordStartupHeartbeat.pipe(
Effect.provideService(ProjectionSnapshotQuery, {
getSnapshot,
}),
Effect.provideService(AnalyticsService, {
record: recordTelemetry,
flush: Effect.void,
}),
);
assert.deepEqual(recordTelemetry.mock.calls[0], [
"server.boot.heartbeat",
{
threadCount: 2,
projectCount: 1,
},
]);
}),
);
it.effect("does not start server for invalid --mode values", () =>
Effect.gen(function* () {
yield* runCli(["--mode", "invalid"]);
+51 -27
View File
@@ -9,7 +9,6 @@
import { Config, Data, Effect, FileSystem, Layer, Option, Path, Schema, ServiceMap } from "effect";
import { Command, Flag } from "effect/unstable/cli";
import { NetService } from "@t3tools/shared/Net";
import {
DEFAULT_PORT,
resolveStaticDir,
@@ -21,8 +20,12 @@ import { fixPath, resolveStateDir } from "./os-jank";
import { Open } from "./open";
import * as SqlitePersistence from "./persistence/Layers/Sqlite";
import { makeServerProviderLayer, makeServerRuntimeServicesLayer } from "./serverLayers";
import { ProjectionSnapshotQuery } from "./orchestration/Services/ProjectionSnapshotQuery";
import { ProviderHealthLive } from "./provider/Layers/ProviderHealth";
import { Server } from "./wsServer";
import { ServerLoggerLive } from "./serverLogger";
import { AnalyticsServiceLayerLive } from "./telemetry/Layers/AnalyticsService";
import { AnalyticsService } from "./telemetry/Services/AnalyticsService";
export class StartupError extends Data.TaggedError("StartupError")<{
readonly message: string;
@@ -119,6 +122,9 @@ 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,
@@ -150,25 +156,16 @@ const ServerConfigLive = (input: CliInput) =>
Option.getOrUndefined(input.stateDir) ?? env.stateDir,
);
const devUrl = Option.getOrElse(input.devUrl, () => env.devUrl);
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 noBrowser = resolveBooleanFlag(input.noBrowser, env.noBrowser ?? mode === "desktop");
const authToken = Option.getOrUndefined(input.authToken) ?? env.authToken;
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 autoBootstrapProjectFromCwd = resolveBooleanFlag(
input.autoBootstrapProjectFromCwd,
env.autoBootstrapProjectFromCwd ?? mode === "web",
);
const logWebSocketEvents = resolveBooleanFlag(
input.logWebSocketEvents,
env.logWebSocketEvents ?? Boolean(devUrl),
);
const staticDir = devUrl ? undefined : yield* cliConfig.resolveStaticDir;
const { join } = yield* Path.Path;
const keybindingsConfigPath = join(stateDir, "keybindings.json");
@@ -177,7 +174,7 @@ const ServerConfigLive = (input: CliInput) =>
env.host ??
(mode === "desktop" ? "127.0.0.1" : undefined);
return {
const config: ServerConfigShape = {
mode,
port,
cwd: cliConfig.cwd,
@@ -191,6 +188,8 @@ const ServerConfigLive = (input: CliInput) =>
autoBootstrapProjectFromCwd,
logWebSocketEvents,
} satisfies ServerConfigShape;
return config;
}),
);
@@ -200,6 +199,8 @@ const LayerLive = (input: CliInput) =>
Layer.provideMerge(makeServerProviderLayer()),
Layer.provideMerge(ProviderHealthLive),
Layer.provideMerge(SqlitePersistence.layerConfig),
Layer.provideMerge(ServerLoggerLive),
Layer.provideMerge(AnalyticsServiceLayerLive),
Layer.provideMerge(ServerConfigLive(input)),
);
@@ -209,6 +210,31 @@ const isWildcardHost = (host: string | undefined): boolean =>
const formatHostForUrl = (host: string): string =>
host.includes(":") && !host.startsWith("[") ? `[${host}]` : host;
export const recordStartupHeartbeat = Effect.gen(function* () {
const analytics = yield* AnalyticsService;
const projectionSnapshotQuery = yield* ProjectionSnapshotQuery;
const { threadCount, projectCount } = yield* projectionSnapshotQuery.getSnapshot().pipe(
Effect.map((snapshot) => ({
threadCount: snapshot.threads.length,
projectCount: snapshot.projects.length,
})),
Effect.catch((cause) =>
Effect.logWarning("failed to gather startup snapshot for telemetry", { cause }).pipe(
Effect.as({
threadCount: 0,
projectCount: 0,
}),
),
),
);
yield* analytics.record("server.boot.heartbeat", {
threadCount,
projectCount,
});
});
const makeServerProgram = (input: CliInput) =>
Effect.gen(function* () {
const cliConfig = yield* CliConfig;
@@ -228,20 +254,18 @@ const makeServerProgram = (input: CliInput) =>
}
yield* start;
yield* Effect.forkChild(recordStartupHeartbeat);
const localUrl = `http://localhost:${config.port}`;
const bindUrl =
config.host && !isWildcardHost(config.host)
? `http://${formatHostForUrl(config.host)}:${config.port}`
: localUrl;
const { authToken, devUrl, ...safeConfig } = config;
yield* Effect.logInfo("T3 Code running", {
url: bindUrl,
localUrl,
bindHost: config.host ?? "default",
cwd: config.cwd,
mode: config.mode,
stateDir: config.stateDir,
authEnabled: Boolean(config.authToken),
...safeConfig,
devUrl: devUrl?.toString(),
authEnabled: Boolean(authToken),
});
if (!config.noBrowser) {
@@ -6,12 +6,10 @@ 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";
@@ -40,28 +38,43 @@ 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);
function createProviderServiceHarness(cwd: string, hasSession = true, sessionCwd = cwd) {
type LegacyProviderRuntimeEvent = {
readonly type: string;
readonly eventId: EventId;
readonly provider: "codex";
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: ProviderSession["provider"] = "codex",
) {
const now = new Date().toISOString();
const runtimeEventPubSub = Effect.runSync(PubSub.unbounded<ProviderRuntimeEvent>());
const rollbackConversation = vi.fn(
(_input: { readonly sessionId: ProviderSessionId; readonly numTurns: number }) => Effect.void,
(_input: { readonly threadId: ThreadId; 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([
{
sessionId: asSessionId("sess-1"),
provider: "codex",
provider: providerName,
status: "ready",
threadId: asProviderThreadId("provider-thread-1"),
runtimeMode: "full-access",
threadId: ThreadId.makeUnsafe("thread-1"),
cwd: sessionCwd,
createdAt: now,
updatedAt: now,
@@ -73,15 +86,16 @@ function createProviderServiceHarness(cwd: string, hasSession = true, sessionCwd
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: ProviderRuntimeEvent): void => {
Effect.runSync(PubSub.publish(runtimeEventPubSub, event));
const emit = (event: LegacyProviderRuntimeEvent): void => {
Effect.runSync(PubSub.publish(runtimeEventPubSub, event as unknown as ProviderRuntimeEvent));
};
return {
@@ -227,6 +241,7 @@ describe("CheckpointReactor", () => {
cwd,
options?.hasSession ?? true,
options?.providerSessionCwd ?? cwd,
"codex",
);
const orchestrationLayer = OrchestrationEngineLive.pipe(
Layer.provide(OrchestrationProjectionPipelineLive),
@@ -271,6 +286,8 @@ 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,
@@ -320,10 +337,7 @@ describe("CheckpointReactor", () => {
threadId: ThreadId.makeUnsafe("thread-1"),
status: "ready",
providerName: "codex",
providerSessionId: asSessionId("sess-1"),
providerThreadId: ProviderThreadId.makeUnsafe("provider-thread-1"),
approvalPolicy: "on-request",
sandboxMode: "workspace-write",
runtimeMode: "approval-required",
activeTurnId: null,
lastError: null,
updatedAt: createdAt,
@@ -336,10 +350,10 @@ describe("CheckpointReactor", () => {
type: "turn.started",
eventId: EventId.makeUnsafe("evt-turn-started-1"),
provider: "codex",
sessionId: asSessionId("sess-1"),
createdAt: new Date().toISOString(),
threadId: ProviderThreadId.makeUnsafe("provider-thread-1"),
turnId: asProviderTurnId("turn-1"),
threadId: ThreadId.makeUnsafe("thread-1"),
turnId: asTurnId("turn-1"),
});
await waitForGitRefExists(
harness.cwd,
@@ -351,11 +365,11 @@ describe("CheckpointReactor", () => {
type: "turn.completed",
eventId: EventId.makeUnsafe("evt-turn-completed-1"),
provider: "codex",
sessionId: asSessionId("sess-1"),
createdAt: new Date().toISOString(),
threadId: ProviderThreadId.makeUnsafe("provider-thread-1"),
turnId: asProviderTurnId("turn-1"),
status: "completed",
threadId: ThreadId.makeUnsafe("thread-1"),
turnId: asTurnId("turn-1"),
payload: { state: "completed" },
});
await waitForEvent(harness.engine, (event) => event.type === "thread.turn-diff-completed");
@@ -399,10 +413,7 @@ describe("CheckpointReactor", () => {
threadId: ThreadId.makeUnsafe("thread-1"),
status: "running",
providerName: "codex",
providerSessionId: asSessionId("sess-1"),
providerThreadId: ProviderThreadId.makeUnsafe("provider-thread-1"),
approvalPolicy: "on-request",
sandboxMode: "workspace-write",
runtimeMode: "approval-required",
activeTurnId: asTurnId("turn-main"),
lastError: null,
updatedAt: createdAt,
@@ -415,10 +426,10 @@ describe("CheckpointReactor", () => {
type: "turn.started",
eventId: EventId.makeUnsafe("evt-turn-started-main"),
provider: "codex",
sessionId: asSessionId("sess-1"),
createdAt: new Date().toISOString(),
threadId: ProviderThreadId.makeUnsafe("provider-thread-1"),
turnId: asProviderTurnId("turn-main"),
threadId: ThreadId.makeUnsafe("thread-1"),
turnId: asTurnId("turn-main"),
});
await waitForGitRefExists(
harness.cwd,
@@ -431,11 +442,11 @@ describe("CheckpointReactor", () => {
type: "turn.completed",
eventId: EventId.makeUnsafe("evt-turn-completed-aux"),
provider: "codex",
sessionId: asSessionId("sess-1"),
createdAt: new Date().toISOString(),
threadId: ProviderThreadId.makeUnsafe("provider-thread-aux"),
turnId: asProviderTurnId("turn-aux"),
status: "completed",
threadId: ThreadId.makeUnsafe("thread-1"),
turnId: asTurnId("turn-aux"),
payload: { state: "completed" },
});
await Effect.runPromise(Effect.sleep("40 millis"));
@@ -449,11 +460,11 @@ describe("CheckpointReactor", () => {
type: "turn.completed",
eventId: EventId.makeUnsafe("evt-turn-completed-main"),
provider: "codex",
sessionId: asSessionId("sess-1"),
createdAt: new Date().toISOString(),
threadId: ProviderThreadId.makeUnsafe("provider-thread-1"),
turnId: asProviderTurnId("turn-main"),
status: "completed",
threadId: ThreadId.makeUnsafe("thread-1"),
turnId: asTurnId("turn-main"),
payload: { state: "completed" },
});
const thread = await waitForThread(
@@ -476,10 +487,7 @@ describe("CheckpointReactor", () => {
threadId: ThreadId.makeUnsafe("thread-1"),
status: "ready",
providerName: "codex",
providerSessionId: asSessionId("sess-1"),
providerThreadId: ProviderThreadId.makeUnsafe("provider-thread-1"),
approvalPolicy: "on-request",
sandboxMode: "workspace-write",
runtimeMode: "approval-required",
activeTurnId: null,
lastError: null,
updatedAt: createdAt,
@@ -492,11 +500,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: ProviderThreadId.makeUnsafe("provider-thread-1"),
turnId: asProviderTurnId("turn-missing-baseline"),
status: "completed",
threadId: ThreadId.makeUnsafe("thread-1"),
turnId: asTurnId("turn-missing-baseline"),
payload: { state: "completed" },
});
await waitForEvent(harness.engine, (event) => event.type === "thread.turn-diff-completed");
@@ -531,8 +539,8 @@ describe("CheckpointReactor", () => {
text: "start turn",
attachments: [],
},
approvalPolicy: "on-request",
sandboxMode: "workspace-write",
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "approval-required",
createdAt: new Date().toISOString(),
}),
);
@@ -567,10 +575,7 @@ describe("CheckpointReactor", () => {
threadId: ThreadId.makeUnsafe("thread-1"),
status: "running",
providerName: "codex",
providerSessionId: asSessionId("sess-missing"),
providerThreadId: ProviderThreadId.makeUnsafe("provider-thread-missing"),
approvalPolicy: "on-request",
sandboxMode: "workspace-write",
runtimeMode: "approval-required",
activeTurnId: asTurnId("turn-missing-cwd"),
lastError: null,
updatedAt: createdAt,
@@ -584,11 +589,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: ProviderThreadId.makeUnsafe("provider-thread-missing"),
turnId: asProviderTurnId("turn-missing-cwd"),
status: "completed",
threadId: ThreadId.makeUnsafe("thread-1"),
turnId: asTurnId("turn-missing-cwd"),
payload: { state: "completed" },
});
await waitForEvent(harness.engine, (event) => event.type === "thread.turn-diff-completed");
@@ -604,7 +609,7 @@ describe("CheckpointReactor", () => {
).toBe("v2\n");
});
it("maps runtime checkpoint.captured into thread.turn.diff.complete when missing in read model", async () => {
it("ignores non-v2 checkpoint.captured runtime events", async () => {
const harness = await createHarness();
const createdAt = new Date().toISOString();
@@ -617,10 +622,7 @@ describe("CheckpointReactor", () => {
threadId: ThreadId.makeUnsafe("thread-1"),
status: "ready",
providerName: "codex",
providerSessionId: asSessionId("sess-1"),
providerThreadId: ProviderThreadId.makeUnsafe("provider-thread-1"),
approvalPolicy: "on-request",
sandboxMode: "workspace-write",
runtimeMode: "approval-required",
activeTurnId: null,
lastError: null,
updatedAt: createdAt,
@@ -633,19 +635,19 @@ describe("CheckpointReactor", () => {
type: "checkpoint.captured",
eventId: EventId.makeUnsafe("evt-checkpoint-captured-3"),
provider: "codex",
sessionId: asSessionId("sess-1"),
createdAt: new Date().toISOString(),
threadId: ProviderThreadId.makeUnsafe("provider-thread-1"),
turnId: asProviderTurnId("turn-3"),
threadId: ThreadId.makeUnsafe("thread-1"),
turnId: asTurnId("turn-3"),
turnCount: 3,
status: "completed",
});
const thread = await waitForThread(harness.engine, (entry) =>
entry.checkpoints.some((checkpoint) => checkpoint.checkpointTurnCount === 3),
);
expect(thread.checkpoints.some((checkpoint) => checkpoint.checkpointTurnCount === 3)).toBe(
true,
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,
);
});
@@ -670,10 +672,7 @@ describe("CheckpointReactor", () => {
threadId: ThreadId.makeUnsafe("thread-1"),
status: "ready",
providerName: "codex",
providerSessionId: asSessionId("sess-1"),
providerThreadId: ProviderThreadId.makeUnsafe("provider-thread-1"),
approvalPolicy: "on-request",
sandboxMode: "workspace-write",
runtimeMode: "approval-required",
activeTurnId: null,
lastError: null,
updatedAt: createdAt,
@@ -683,25 +682,24 @@ describe("CheckpointReactor", () => {
);
harness.provider.emit({
type: "checkpoint.captured",
type: "turn.completed",
eventId: EventId.makeUnsafe("evt-runtime-capture-failure"),
provider: "codex",
sessionId: asSessionId("sess-1"),
createdAt: new Date().toISOString(),
threadId: ProviderThreadId.makeUnsafe("provider-thread-1"),
turnId: asProviderTurnId("turn-runtime-failure"),
turnCount: 1,
status: "completed",
threadId: ThreadId.makeUnsafe("thread-1"),
turnId: asTurnId("turn-runtime-failure"),
payload: { state: "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: ProviderThreadId.makeUnsafe("provider-thread-1"),
turnId: asProviderTurnId("turn-after-runtime-failure"),
threadId: ThreadId.makeUnsafe("thread-1"),
turnId: asTurnId("turn-after-runtime-failure"),
});
await waitForGitRefExists(
@@ -726,10 +724,7 @@ describe("CheckpointReactor", () => {
threadId: ThreadId.makeUnsafe("thread-1"),
status: "ready",
providerName: "codex",
providerSessionId: asSessionId("sess-1"),
providerThreadId: ProviderThreadId.makeUnsafe("provider-thread-1"),
approvalPolicy: "on-request",
sandboxMode: "workspace-write",
runtimeMode: "approval-required",
activeTurnId: null,
lastError: null,
updatedAt: createdAt,
@@ -785,7 +780,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"),
threadId: ThreadId.makeUnsafe("thread-1"),
numTurns: 1,
});
expect(fs.readFileSync(path.join(harness.cwd, "README.md"), "utf8")).toBe("v2\n");
@@ -807,10 +802,7 @@ describe("CheckpointReactor", () => {
threadId: ThreadId.makeUnsafe("thread-1"),
status: "ready",
providerName: "codex",
providerSessionId: asSessionId("sess-1"),
providerThreadId: ProviderThreadId.makeUnsafe("provider-thread-1"),
approvalPolicy: "on-request",
sandboxMode: "workspace-write",
runtimeMode: "approval-required",
activeTurnId: null,
lastError: null,
updatedAt: createdAt,
@@ -882,11 +874,11 @@ describe("CheckpointReactor", () => {
expect(harness.provider.rollbackConversation).toHaveBeenCalledTimes(2);
expect(harness.provider.rollbackConversation.mock.calls[0]?.[0]).toEqual({
sessionId: asSessionId("sess-1"),
threadId: ThreadId.makeUnsafe("thread-1"),
numTurns: 1,
});
expect(harness.provider.rollbackConversation.mock.calls[1]?.[0]).toEqual({
sessionId: asSessionId("sess-1"),
threadId: ThreadId.makeUnsafe("thread-1"),
numTurns: 1,
});
});
@@ -2,8 +2,6 @@ import {
CommandId,
EventId,
MessageId,
ProviderSessionId,
ProviderThreadId,
ThreadId,
TurnId,
type OrchestrationEvent,
@@ -34,11 +32,7 @@ type ReactorInput =
};
function toTurnId(value: string | undefined): TurnId | null {
return value === undefined ? null : TurnId.makeUnsafe(value);
}
function toProviderThreadId(value: string | undefined): ProviderThreadId | null {
return value === undefined ? null : ProviderThreadId.makeUnsafe(value);
return value === undefined ? null : TurnId.makeUnsafe(String(value));
}
function sameId(left: string | null | undefined, right: string | null | undefined): boolean {
@@ -95,77 +89,58 @@ const make = Effect.gen(function* () {
});
const appendCaptureFailureActivity = (input: {
readonly sessionId: ProviderSessionId;
readonly threadId: ThreadId;
readonly turnId: TurnId | null;
readonly detail: string;
readonly createdAt: string;
}) =>
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,
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,
},
turnId: input.turnId,
createdAt: input.createdAt,
});
},
createdAt: input.createdAt,
});
const resolveSessionRuntimeForThread = Effect.fnUntraced(function* (
threadId: ThreadId,
): Effect.fn.Return<
Option.Option<{ readonly sessionId: ProviderSessionId; readonly cwd: string }>
Option.Option<{ readonly threadId: ThreadId; 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 sessionId: ProviderSessionId; readonly cwd: string }> => {
): Option.Option<{ readonly threadId: ThreadId; readonly cwd: string }> => {
if (!session?.cwd) {
return Option.none();
}
return Option.some({ sessionId: session.sessionId, cwd: session.cwd });
return Option.some({ threadId: session.threadId, cwd: session.cwd });
};
if (projectedSessionId !== null) {
const projectedSession = sessions.find((session) => session.sessionId === projectedSessionId);
if (thread) {
const projectedSession = sessions.find(
(session) => session.threadId === thread.id,
);
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();
});
@@ -178,23 +153,11 @@ const make = Effect.gen(function* () {
}
const readModel = yield* orchestrationEngine.getReadModel();
const thread = readModel.threads.find(
(entry) => entry.session?.providerSessionId === event.sessionId,
);
const thread = readModel.threads.find((entry) => entry.id === event.threadId);
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;
@@ -266,7 +229,7 @@ const make = Effect.gen(function* () {
),
Effect.tapError((error) =>
appendCaptureFailureActivity({
sessionId: event.sessionId,
threadId: thread.id,
turnId,
detail: `Checkpoint captured, but turn diff summary is unavailable: ${error.message}`,
createdAt: event.createdAt,
@@ -296,7 +259,7 @@ const make = Effect.gen(function* () {
turnId,
completedAt: now,
checkpointRef: targetCheckpointRef,
status: checkpointStatusFromRuntime(event.status),
status: checkpointStatusFromRuntime(event.payload.state),
files,
assistantMessageId,
checkpointTurnCount: nextTurnCount,
@@ -314,7 +277,7 @@ const make = Effect.gen(function* () {
summary: "Checkpoint captured",
payload: {
turnCount: nextTurnCount,
...(event.status !== undefined ? { status: event.status } : {}),
status: event.payload.state,
},
turnId,
createdAt: now,
@@ -333,7 +296,7 @@ const make = Effect.gen(function* () {
const readModel = yield* orchestrationEngine.getReadModel();
const thread = readModel.threads.find(
(entry) => entry.session?.providerSessionId === event.sessionId,
(entry) => entry.id === event.threadId,
);
if (!thread) {
return;
@@ -513,7 +476,7 @@ const make = Effect.gen(function* () {
const rolledBackTurns = Math.max(0, currentTurnCount - event.payload.turnCount);
if (rolledBackTurns > 0) {
yield* providerService.rollbackConversation({
sessionId: sessionRuntime.value.sessionId,
threadId: sessionRuntime.value.threadId,
numTurns: rolledBackTurns,
});
}
@@ -581,7 +544,7 @@ const make = Effect.gen(function* () {
yield* captureCheckpointFromTurnCompletion(event).pipe(
Effect.catch((error) =>
appendCaptureFailureActivity({
sessionId: event.sessionId,
threadId: event.threadId,
turnId,
detail: error.message,
createdAt: new Date().toISOString(),
@@ -590,89 +553,6 @@ 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 = (
@@ -717,11 +597,7 @@ const make = Effect.gen(function* () {
yield* Effect.forkScoped(
Stream.runForEach(providerService.streamEvents, (event) => {
if (
event.type !== "turn.started" &&
event.type !== "turn.completed" &&
event.type !== "checkpoint.captured"
) {
if (event.type !== "turn.started" && event.type !== "turn.completed") {
return Effect.void;
}
return Queue.offer(queue, { source: "runtime", event }).pipe(Effect.asVoid);
@@ -1,6 +1,7 @@
import {
CheckpointRef,
CommandId,
DEFAULT_PROVIDER_INTERACTION_MODE,
MessageId,
ProjectId,
ThreadId,
@@ -80,6 +81,8 @@ 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,
@@ -96,8 +99,8 @@ describe("OrchestrationEngine", () => {
text: "hello",
attachments: [],
},
approvalPolicy: "on-request",
sandboxMode: "workspace-write",
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "approval-required",
createdAt,
}),
);
@@ -133,6 +136,8 @@ describe("OrchestrationEngine", () => {
projectId: asProjectId("project-branch-seed"),
title: "Branch of Thread",
model: "gpt-5-codex",
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "approval-required",
branch: "feature/source",
worktreePath: null,
seedMessages: [
@@ -205,6 +210,8 @@ 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,
@@ -265,6 +272,8 @@ 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,
@@ -308,6 +317,8 @@ 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,
@@ -415,6 +426,8 @@ 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,
@@ -430,6 +443,8 @@ 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,
@@ -493,6 +508,8 @@ 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,
@@ -509,8 +526,8 @@ describe("OrchestrationEngine", () => {
text: "hello",
attachments: [],
},
approvalPolicy: "on-request" as const,
sandboxMode: "workspace-write" as const,
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "approval-required" as const,
createdAt,
};
@@ -626,6 +643,8 @@ 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,
@@ -669,8 +688,8 @@ describe("OrchestrationEngine", () => {
text: "hello",
attachments: [],
},
approvalPolicy: "on-request",
sandboxMode: "workspace-write",
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "approval-required",
createdAt: now(),
}),
),
@@ -704,6 +723,8 @@ 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,
@@ -719,6 +740,8 @@ 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,8 +4,6 @@ import {
CorrelationId,
EventId,
MessageId,
ProviderSessionId,
ProviderThreadId,
ProjectId,
ThreadId,
TurnId,
@@ -104,6 +102,7 @@ projectionLayer("OrchestrationProjectionPipeline", (it) => {
projectId: ProjectId.makeUnsafe("project-1"),
title: "Thread 1",
model: "gpt-5-codex",
runtimeMode: "full-access",
branch: null,
worktreePath: null,
createdAt: now,
@@ -374,6 +373,7 @@ 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,6 +500,7 @@ projectionLayer("OrchestrationProjectionPipeline", (it) => {
projectId: ProjectId.makeUnsafe("project-overwrite"),
title: "Thread Overwrite",
model: "gpt-5-codex",
runtimeMode: "full-access",
branch: null,
worktreePath: null,
createdAt: now,
@@ -650,6 +651,7 @@ projectionLayer("OrchestrationProjectionPipeline", (it) => {
projectId: ProjectId.makeUnsafe("project-rollback"),
title: "Thread Rollback",
model: "gpt-5-codex",
runtimeMode: "full-access",
branch: null,
worktreePath: null,
createdAt: now,
@@ -780,6 +782,7 @@ 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,
@@ -994,6 +997,7 @@ 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,
@@ -1156,6 +1160,7 @@ projectionLayer("OrchestrationProjectionPipeline", (it) => {
projectId: ProjectId.makeUnsafe("project-a"),
title: "Thread A",
model: "gpt-5-codex",
runtimeMode: "full-access",
branch: null,
worktreePath: null,
createdAt: now,
@@ -1279,6 +1284,7 @@ projectionLayer("OrchestrationProjectionPipeline", (it) => {
projectId: ProjectId.makeUnsafe("project-empty"),
title: "Thread Empty",
model: "gpt-5-codex",
runtimeMode: "full-access",
branch: null,
worktreePath: null,
createdAt: now,
@@ -1415,6 +1421,7 @@ 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",
@@ -1555,6 +1562,7 @@ 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",
@@ -1749,8 +1757,7 @@ it.effect("restores pending turn-start metadata across projection pipeline resta
payload: {
threadId,
messageId,
approvalPolicy: "on-request",
sandboxMode: "workspace-write",
runtimeMode: "approval-required",
createdAt: turnStartedAt,
},
});
@@ -1772,20 +1779,14 @@ 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: {
providerSessionId: ProviderSessionId.makeUnsafe("provider-session-restart"),
providerThreadId: ProviderThreadId.makeUnsafe("provider-thread-restart"),
},
metadata: {},
payload: {
threadId,
session: {
threadId,
status: "running",
providerName: "codex",
providerSessionId: ProviderSessionId.makeUnsafe("provider-session-restart"),
providerThreadId: ProviderThreadId.makeUnsafe("provider-thread-restart"),
approvalPolicy: "on-request",
sandboxMode: "workspace-write",
runtimeMode: "approval-required",
activeTurnId: turnId,
lastError: null,
updatedAt: sessionSetAt,
@@ -18,6 +18,10 @@ 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,
@@ -29,6 +33,7 @@ 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";
@@ -48,6 +53,7 @@ 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",
@@ -189,6 +195,26 @@ 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>,
@@ -320,6 +346,7 @@ 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;
@@ -396,6 +423,8 @@ 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,
@@ -425,6 +454,36 @@ 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({
@@ -442,6 +501,7 @@ 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,
@@ -583,6 +643,57 @@ 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,
@@ -598,6 +709,9 @@ 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;
@@ -646,10 +760,7 @@ const makeOrchestrationProjectionPipeline = Effect.gen(function* () {
threadId: event.payload.threadId,
status: event.payload.session.status,
providerName: event.payload.session.providerName,
providerSessionId: event.payload.session.providerSessionId,
providerThreadId: event.payload.session.providerThreadId,
approvalPolicy: event.payload.session.approvalPolicy,
sandboxMode: event.payload.session.sandboxMode,
runtimeMode: event.payload.session.runtimeMode,
activeTurnId: event.payload.session.activeTurnId,
lastError: event.payload.session.lastError,
updatedAt: event.payload.session.updatedAt,
@@ -991,6 +1102,10 @@ 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,
@@ -1110,6 +1225,7 @@ 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,8 +3,6 @@ import {
EventId,
MessageId,
ProjectId,
ProviderSessionId,
ProviderThreadId,
ThreadId,
TurnId,
} from "@t3tools/contracts";
@@ -22,9 +20,6 @@ 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)),
@@ -143,8 +138,7 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
provider_name,
provider_session_id,
provider_thread_id,
approval_policy,
sandbox_mode,
runtime_mode,
active_turn_id,
last_error,
updated_at
@@ -155,8 +149,7 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
'codex',
'provider-session-1',
'provider-thread-1',
'on-request',
'workspace-write',
'approval-required',
'turn-1',
NULL,
'2026-02-24T00:00:07.000Z'
@@ -241,6 +234,8 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
projectId: asProjectId("project-1"),
title: "Thread 1",
model: "gpt-5-codex",
interactionMode: "default",
runtimeMode: "full-access",
branch: null,
worktreePath: null,
latestTurn: {
@@ -265,6 +260,7 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
updatedAt: "2026-02-24T00:00:05.000Z",
},
],
proposedPlans: [],
activities: [
{
id: asEventId("activity-1"),
@@ -291,10 +287,7 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
threadId: ThreadId.makeUnsafe("thread-1"),
status: "running",
providerName: "codex",
providerSessionId: asProviderSessionId("provider-session-1"),
providerThreadId: asProviderThreadId("provider-thread-1"),
approvalPolicy: "on-request",
sandboxMode: "workspace-write",
runtimeMode: "approval-required",
activeTurnId: asTurnId("turn-1"),
lastError: null,
updatedAt: "2026-02-24T00:00:07.000Z",
@@ -2,6 +2,7 @@ import {
ChatAttachment,
IsoDateTime,
MessageId,
NonNegativeInt,
OrchestrationCheckpointFile,
OrchestrationReadModel,
ProjectScript,
@@ -9,6 +10,7 @@ import {
type OrchestrationCheckpointSummary,
type OrchestrationLatestTurn,
type OrchestrationMessage,
type OrchestrationProposedPlan,
type OrchestrationProject,
type OrchestrationSession,
type OrchestrationThread,
@@ -29,6 +31,7 @@ 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";
@@ -49,10 +52,12 @@ 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;
@@ -76,6 +81,7 @@ 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,
@@ -151,6 +157,8 @@ 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",
@@ -182,6 +190,23 @@ 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,
@@ -195,9 +220,15 @@ 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, created_at ASC, activity_id ASC
ORDER BY
thread_id ASC,
CASE WHEN sequence IS NULL THEN 0 ELSE 1 END ASC,
sequence ASC,
created_at ASC,
activity_id ASC
`,
});
@@ -212,8 +243,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
provider_name AS "providerName",
provider_session_id AS "providerSessionId",
provider_thread_id AS "providerThreadId",
approval_policy AS "approvalPolicy",
sandbox_mode AS "sandboxMode",
runtime_mode AS "runtimeMode",
active_turn_id AS "activeTurnId",
last_error AS "lastError",
updated_at AS "updatedAt"
@@ -282,6 +312,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
projectRows,
threadRows,
messageRows,
proposedPlanRows,
activityRows,
sessionRows,
checkpointRows,
@@ -312,6 +343,14 @@ 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(
@@ -355,6 +394,7 @@ 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>();
@@ -388,6 +428,19 @@ 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) ?? [];
@@ -398,6 +451,7 @@ 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);
@@ -452,10 +506,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
threadId: row.threadId,
status: row.status,
providerName: row.providerName,
providerSessionId: row.providerSessionId,
providerThreadId: row.providerThreadId,
approvalPolicy: row.approvalPolicy,
sandboxMode: row.sandboxMode,
runtimeMode: row.runtimeMode,
activeTurnId: row.activeTurnId,
lastError: row.lastError,
updatedAt: row.updatedAt,
@@ -478,6 +529,8 @@ 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,
@@ -485,6 +538,7 @@ 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,
@@ -2,15 +2,14 @@ import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import type { ProviderRuntimeEvent } from "@t3tools/contracts";
import type { ProviderRuntimeEvent, ProviderSession } from "@t3tools/contracts";
import {
ApprovalRequestId,
CommandId,
DEFAULT_PROVIDER_INTERACTION_MODE,
EventId,
MessageId,
ProjectId,
ProviderSessionId,
ProviderThreadId,
ProviderTurnId,
ThreadId,
TurnId,
} from "@t3tools/contracts";
@@ -19,6 +18,7 @@ import { afterEach, describe, expect, it, vi } from "vitest";
import { ServerConfig } from "../../config.ts";
import { TextGenerationError } from "../../git/Errors.ts";
import { ProviderAdapterRequestError } from "../../provider/Errors.ts";
import { OrchestrationEventStoreLive } from "../../persistence/Layers/OrchestrationEventStore.ts";
import { OrchestrationCommandReceiptRepositoryLive } from "../../persistence/Layers/OrchestrationCommandReceipts.ts";
import { SqlitePersistenceMemory } from "../../persistence/Layers/Sqlite.ts";
@@ -36,17 +36,15 @@ import { ProviderCommandReactor } from "../Services/ProviderCommandReactor.ts";
import * as NodeServices from "@effect/platform-node/NodeServices";
const asProjectId = (value: string): ProjectId => ProjectId.makeUnsafe(value);
const asSessionId = (value: string): ProviderSessionId => ProviderSessionId.makeUnsafe(value);
const asProviderTurnId = (value: string): ProviderTurnId => ProviderTurnId.makeUnsafe(value);
const asApprovalRequestId = (value: string): ApprovalRequestId =>
ApprovalRequestId.makeUnsafe(value);
const asMessageId = (value: string): MessageId => MessageId.makeUnsafe(value);
const asTurnId = (value: string): TurnId => TurnId.makeUnsafe(value);
async function waitFor(predicate: () => boolean, timeoutMs = 2000): Promise<void> {
async function waitFor(predicate: () => boolean | Promise<boolean>, timeoutMs = 2000): Promise<void> {
const deadline = Date.now() + timeoutMs;
const poll = async (): Promise<void> => {
if (predicate()) {
if (await predicate()) {
return;
}
if (Date.now() >= deadline) {
@@ -88,36 +86,93 @@ describe("ProviderCommandReactor", () => {
createdStateDirs.add(stateDir);
const runtimeEventPubSub = Effect.runSync(PubSub.unbounded<ProviderRuntimeEvent>());
let nextSessionIndex = 1;
const startSession = vi.fn((_: unknown, __: unknown) => {
const runtimeSessions: Array<ProviderSession> = [];
const startSession = vi.fn((_: unknown, input: unknown) => {
const sessionIndex = nextSessionIndex++;
return Effect.succeed({
sessionId: asSessionId(`sess-${sessionIndex}`),
provider: "codex" as const,
const provider =
typeof input === "object" &&
input !== null &&
"provider" in input &&
input.provider === "codex"
? input.provider
: "codex";
const resumeCursor =
typeof input === "object" && input !== null && "resumeCursor" in input
? input.resumeCursor
: undefined;
const model =
typeof input === "object" && input !== null && "model" in input && typeof input.model === "string"
? input.model
: undefined;
const threadId =
typeof input === "object" &&
input !== null &&
"threadId" in input &&
typeof input.threadId === "string"
? ThreadId.makeUnsafe(input.threadId)
: ThreadId.makeUnsafe(`thread-${sessionIndex}`);
const session: ProviderSession = {
provider,
status: "ready" as const,
threadId: ProviderThreadId.makeUnsafe(`provider-thread-${sessionIndex}`),
runtimeMode:
typeof input === "object" &&
input !== null &&
"runtimeMode" in input &&
(input.runtimeMode === "approval-required" || input.runtimeMode === "full-access")
? input.runtimeMode
: "full-access",
...(model !== undefined ? { model } : {}),
threadId,
resumeCursor: resumeCursor ?? { opaque: `cursor-${sessionIndex}` },
createdAt: now,
updatedAt: now,
});
};
runtimeSessions.push(session);
return Effect.succeed(session);
});
const sendTurn = vi.fn((_: unknown) =>
Effect.succeed({
threadId: ProviderThreadId.makeUnsafe("provider-thread-1"),
turnId: asProviderTurnId("provider-turn-1"),
threadId: ThreadId.makeUnsafe("thread-1"),
turnId: asTurnId("turn-1"),
}),
);
const interruptTurn = vi.fn((_: unknown) => Effect.void);
const respondToRequest = vi.fn((_: unknown) => Effect.void);
const stopSession = vi.fn((_: unknown) => Effect.void);
const renameBranch = vi.fn((_: unknown) =>
Effect.succeed({
branch: "t3code/generated-name",
const respondToRequest = vi.fn<ProviderServiceShape["respondToRequest"]>(() => Effect.void);
const respondToUserInput = vi.fn<ProviderServiceShape["respondToUserInput"]>(() => Effect.void);
const stopSession = vi.fn((input: unknown) =>
Effect.sync(() => {
const threadId =
typeof input === "object" && input !== null && "threadId" in input
? (input as { threadId?: ThreadId }).threadId
: undefined;
if (!threadId) {
return;
}
const index = runtimeSessions.findIndex((session) => session.threadId === threadId);
if (index >= 0) {
runtimeSessions.splice(index, 1);
}
}),
);
const generateBranchName = vi.fn<TextGenerationShape["generateBranchName"]>(() =>
const renameBranch = vi.fn((input: unknown) =>
Effect.succeed({
branch: "generated-name",
branch:
typeof input === "object" &&
input !== null &&
"newBranch" in input &&
typeof input.newBranch === "string"
? input.newBranch
: "renamed-branch",
}),
);
const generateBranchName = vi.fn(() =>
Effect.fail(
new TextGenerationError({
operation: "generateBranchName",
detail: "disabled in test harness",
}),
),
);
const unsupported = () => Effect.die(new Error("Unsupported provider call in test")) as never;
const service: ProviderServiceShape = {
@@ -125,10 +180,14 @@ describe("ProviderCommandReactor", () => {
sendTurn: sendTurn as ProviderServiceShape["sendTurn"],
interruptTurn: interruptTurn as ProviderServiceShape["interruptTurn"],
respondToRequest: respondToRequest as ProviderServiceShape["respondToRequest"],
respondToUserInput: respondToUserInput as ProviderServiceShape["respondToUserInput"],
stopSession: stopSession as ProviderServiceShape["stopSession"],
listSessions: () => Effect.succeed([]),
listSessions: () => Effect.succeed(runtimeSessions),
getCapabilities: (provider) =>
Effect.succeed({
sessionModelSwitch: provider === "codex" ? "in-session" : "in-session",
}),
rollbackConversation: () => unsupported(),
stopAll: () => Effect.void,
streamEvents: Stream.fromPubSub(runtimeEventPubSub),
};
@@ -175,6 +234,8 @@ describe("ProviderCommandReactor", () => {
projectId: asProjectId("project-1"),
title: "Thread",
model: "gpt-5-codex",
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "approval-required",
branch: null,
worktreePath: null,
createdAt: now,
@@ -187,6 +248,7 @@ describe("ProviderCommandReactor", () => {
sendTurn,
interruptTurn,
respondToRequest,
respondToUserInput,
stopSession,
renameBranch,
generateBranchName,
@@ -209,8 +271,8 @@ describe("ProviderCommandReactor", () => {
text: "hello reactor",
attachments: [],
},
approvalPolicy: "on-request",
sandboxMode: "workspace-write",
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "approval-required",
createdAt: now,
}),
);
@@ -221,256 +283,103 @@ describe("ProviderCommandReactor", () => {
expect(harness.startSession.mock.calls[0]?.[1]).toMatchObject({
cwd: "/tmp/provider-project",
model: "gpt-5-codex",
approvalPolicy: "on-request",
sandboxMode: "workspace-write",
runtimeMode: "approval-required",
});
const readModel = await Effect.runPromise(harness.engine.getReadModel());
const thread = readModel.threads.find((entry) => entry.id === ThreadId.makeUnsafe("thread-1"));
expect(thread?.session?.providerSessionId).toBe("sess-1");
expect(thread?.session?.approvalPolicy).toBe("on-request");
expect(thread?.session?.sandboxMode).toBe("workspace-write");
expect(thread?.session?.threadId).toBe("thread-1");
expect(thread?.session?.runtimeMode).toBe("approval-required");
});
it("generates and renames temporary worktree branch on first turn", async () => {
it("forwards codex model options through session start and turn send", async () => {
const harness = await createHarness();
const now = new Date().toISOString();
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.meta.update",
commandId: CommandId.makeUnsafe("cmd-thread-meta-set-temp-branch"),
threadId: ThreadId.makeUnsafe("thread-1"),
branch: "t3code/89abc123",
worktreePath: "/tmp/provider-project/.t3/worktrees/t3code-89abc123",
}),
);
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.turn.start",
commandId: CommandId.makeUnsafe("cmd-turn-start-worktree-rename"),
commandId: CommandId.makeUnsafe("cmd-turn-start-fast"),
threadId: ThreadId.makeUnsafe("thread-1"),
message: {
messageId: asMessageId("user-message-worktree-rename"),
messageId: asMessageId("user-message-fast"),
role: "user",
text: "Fix visual bug from screenshot",
attachments: [
{
type: "image",
id: "thread-1-att-rename",
name: "bug.png",
mimeType: "image/png",
sizeBytes: 5,
},
],
text: "hello fast mode",
attachments: [],
},
approvalPolicy: "on-request",
sandboxMode: "workspace-write",
provider: "codex",
model: "gpt-5.3-codex",
modelOptions: {
codex: {
reasoningEffort: "high",
fastMode: true,
},
},
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "approval-required",
createdAt: now,
}),
);
await waitFor(() => harness.generateBranchName.mock.calls.length === 1);
await waitFor(() => harness.renameBranch.mock.calls.length === 1);
expect(harness.generateBranchName.mock.calls[0]?.[0]).toEqual({
cwd: "/tmp/provider-project/.t3/worktrees/t3code-89abc123",
message: "Fix visual bug from screenshot",
attachments: [
{
type: "image",
id: "thread-1-att-rename",
name: "bug.png",
mimeType: "image/png",
sizeBytes: 5,
},
],
});
expect(harness.renameBranch.mock.calls[0]?.[0]).toEqual({
cwd: "/tmp/provider-project/.t3/worktrees/t3code-89abc123",
oldBranch: "t3code/89abc123",
newBranch: "t3code/generated-name",
});
await waitFor(() => {
const readModel = Effect.runSync(harness.engine.getReadModel());
const thread = readModel.threads.find(
(entry) => entry.id === ThreadId.makeUnsafe("thread-1"),
);
return thread?.branch === "t3code/generated-name";
});
});
it("passes persisted attachment references to branch generation and turn start", async () => {
const harness = await createHarness();
const now = new Date().toISOString();
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.meta.update",
commandId: CommandId.makeUnsafe("cmd-thread-meta-set-temp-branch-persisted"),
threadId: ThreadId.makeUnsafe("thread-1"),
branch: "t3code/abcdef12",
worktreePath: "/tmp/provider-project/.t3/worktrees/t3code-abcdef12",
}),
);
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.turn.start",
commandId: CommandId.makeUnsafe("cmd-turn-start-persisted-attachments"),
threadId: ThreadId.makeUnsafe("thread-1"),
message: {
messageId: asMessageId("user-message-persisted-attachments"),
role: "user",
text: "Fix visual bug from screenshot",
attachments: [
{
type: "image",
id: "thread-1-att-persisted",
name: "bug.png",
mimeType: "image/png",
sizeBytes: 5,
},
],
},
approvalPolicy: "on-request",
sandboxMode: "workspace-write",
createdAt: now,
}),
);
await waitFor(() => harness.generateBranchName.mock.calls.length === 1);
await waitFor(() => harness.startSession.mock.calls.length === 1);
await waitFor(() => harness.sendTurn.mock.calls.length === 1);
expect(harness.generateBranchName.mock.calls[0]?.[0]).toEqual({
cwd: "/tmp/provider-project/.t3/worktrees/t3code-abcdef12",
message: "Fix visual bug from screenshot",
attachments: [
{
type: "image",
id: "thread-1-att-persisted",
name: "bug.png",
mimeType: "image/png",
sizeBytes: 5,
expect(harness.startSession.mock.calls[0]?.[1]).toMatchObject({
model: "gpt-5.3-codex",
modelOptions: {
codex: {
reasoningEffort: "high",
fastMode: true,
},
],
},
});
expect(harness.sendTurn.mock.calls[0]?.[0]).toMatchObject({
attachments: [
{
type: "image",
id: "thread-1-att-persisted",
name: "bug.png",
mimeType: "image/png",
sizeBytes: 5,
threadId: ThreadId.makeUnsafe("thread-1"),
model: "gpt-5.3-codex",
modelOptions: {
codex: {
reasoningEffort: "high",
fastMode: true,
},
],
},
});
});
it("skips worktree branch generation after the first user turn", async () => {
it("forwards plan interaction mode to the provider turn request", async () => {
const harness = await createHarness();
const now = new Date().toISOString();
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.meta.update",
commandId: CommandId.makeUnsafe("cmd-thread-meta-set-temp-branch-2"),
type: "thread.interaction-mode.set",
commandId: CommandId.makeUnsafe("cmd-interaction-mode-set-plan"),
threadId: ThreadId.makeUnsafe("thread-1"),
branch: "t3code/1234abcd",
worktreePath: "/tmp/provider-project/.t3/worktrees/t3code-1234abcd",
interactionMode: "plan",
createdAt: now,
}),
);
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.turn.start",
commandId: CommandId.makeUnsafe("cmd-turn-start-first"),
commandId: CommandId.makeUnsafe("cmd-turn-start-plan"),
threadId: ThreadId.makeUnsafe("thread-1"),
message: {
messageId: asMessageId("user-message-first"),
messageId: asMessageId("user-message-plan"),
role: "user",
text: "first",
text: "plan this change",
attachments: [],
},
approvalPolicy: "on-request",
sandboxMode: "workspace-write",
interactionMode: "plan",
runtimeMode: "approval-required",
createdAt: now,
}),
);
await waitFor(() => harness.generateBranchName.mock.calls.length === 1);
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.turn.start",
commandId: CommandId.makeUnsafe("cmd-turn-start-second"),
threadId: ThreadId.makeUnsafe("thread-1"),
message: {
messageId: asMessageId("user-message-second"),
role: "user",
text: "second",
attachments: [],
},
approvalPolicy: "on-request",
sandboxMode: "workspace-write",
createdAt: now,
}),
);
await waitFor(() => harness.sendTurn.mock.calls.length === 2);
expect(harness.generateBranchName.mock.calls.length).toBe(1);
expect(harness.renameBranch.mock.calls.length).toBe(1);
});
it("skips worktree rename when branch-name generation fails", async () => {
const harness = await createHarness();
const now = new Date().toISOString();
harness.generateBranchName.mockImplementationOnce(() =>
Effect.fail(
new TextGenerationError({
operation: "generateBranchName",
detail: "model returned invalid payload",
}),
),
);
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.meta.update",
commandId: CommandId.makeUnsafe("cmd-thread-meta-set-temp-branch-null"),
threadId: ThreadId.makeUnsafe("thread-1"),
branch: "t3code/0000abcd",
worktreePath: "/tmp/provider-project/.t3/worktrees/t3code-0000abcd",
}),
);
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.turn.start",
commandId: CommandId.makeUnsafe("cmd-turn-start-null-branch"),
threadId: ThreadId.makeUnsafe("thread-1"),
message: {
messageId: asMessageId("user-message-null-branch"),
role: "user",
text: "Fix visual regression",
attachments: [],
},
approvalPolicy: "on-request",
sandboxMode: "workspace-write",
createdAt: now,
}),
);
await waitFor(() => harness.generateBranchName.mock.calls.length === 1);
await Effect.runPromise(Effect.sleep("20 millis"));
expect(harness.renameBranch.mock.calls.length).toBe(0);
const readModel = await Effect.runPromise(harness.engine.getReadModel());
const thread = readModel.threads.find((entry) => entry.id === ThreadId.makeUnsafe("thread-1"));
expect(thread?.branch).toBe("t3code/0000abcd");
await waitFor(() => harness.sendTurn.mock.calls.length === 1);
expect(harness.sendTurn.mock.calls[0]?.[0]).toMatchObject({
threadId: ThreadId.makeUnsafe("thread-1"),
interactionMode: "plan",
});
});
it("reuses the same provider session when runtime mode is unchanged", async () => {
@@ -488,8 +397,8 @@ describe("ProviderCommandReactor", () => {
text: "first",
attachments: [],
},
approvalPolicy: "on-request",
sandboxMode: "workspace-write",
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "approval-required",
createdAt: now,
}),
);
@@ -508,8 +417,8 @@ describe("ProviderCommandReactor", () => {
text: "second",
attachments: [],
},
approvalPolicy: "on-request",
sandboxMode: "workspace-write",
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "approval-required",
createdAt: now,
}),
);
@@ -519,10 +428,20 @@ describe("ProviderCommandReactor", () => {
expect(harness.stopSession.mock.calls.length).toBe(0);
});
it("restarts the provider session when runtime mode changes", async () => {
it("restarts the provider session when runtime mode is updated on the thread", async () => {
const harness = await createHarness();
const now = new Date().toISOString();
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.runtime-mode.set",
commandId: CommandId.makeUnsafe("cmd-runtime-mode-set-initial-full-access"),
threadId: ThreadId.makeUnsafe("thread-1"),
runtimeMode: "full-access",
createdAt: now,
}),
);
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.turn.start",
@@ -534,8 +453,8 @@ describe("ProviderCommandReactor", () => {
text: "first",
attachments: [],
},
approvalPolicy: "never",
sandboxMode: "danger-full-access",
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "full-access",
createdAt: now,
}),
);
@@ -543,6 +462,22 @@ describe("ProviderCommandReactor", () => {
await waitFor(() => harness.startSession.mock.calls.length === 1);
await waitFor(() => harness.sendTurn.mock.calls.length === 1);
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.runtime-mode.set",
commandId: CommandId.makeUnsafe("cmd-runtime-mode-set-1"),
threadId: ThreadId.makeUnsafe("thread-1"),
runtimeMode: "approval-required",
createdAt: now,
}),
);
await waitFor(async () => {
const readModel = await Effect.runPromise(harness.engine.getReadModel());
const thread = readModel.threads.find((entry) => entry.id === ThreadId.makeUnsafe("thread-1"));
return thread?.runtimeMode === "approval-required";
});
await waitFor(() => harness.startSession.mock.calls.length === 2);
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.turn.start",
@@ -554,37 +489,44 @@ describe("ProviderCommandReactor", () => {
text: "second",
attachments: [],
},
approvalPolicy: "on-request",
sandboxMode: "workspace-write",
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "full-access",
createdAt: now,
}),
);
await waitFor(() => harness.stopSession.mock.calls.length === 1);
await waitFor(() => harness.startSession.mock.calls.length === 2);
await waitFor(() => harness.sendTurn.mock.calls.length === 2);
expect(harness.stopSession.mock.calls[0]?.[0]).toEqual({ sessionId: asSessionId("sess-1") });
expect(harness.stopSession.mock.calls.length).toBe(0);
expect(harness.startSession.mock.calls[1]?.[1]).toMatchObject({
resumeThreadId: ProviderThreadId.makeUnsafe("provider-thread-1"),
approvalPolicy: "on-request",
sandboxMode: "workspace-write",
threadId: ThreadId.makeUnsafe("thread-1"),
resumeCursor: { opaque: "cursor-1" },
runtimeMode: "approval-required",
});
expect(harness.sendTurn.mock.calls[1]?.[0]).toMatchObject({
sessionId: asSessionId("sess-2"),
threadId: ThreadId.makeUnsafe("thread-1"),
});
const readModel = await Effect.runPromise(harness.engine.getReadModel());
const thread = readModel.threads.find((entry) => entry.id === ThreadId.makeUnsafe("thread-1"));
expect(thread?.session?.providerSessionId).toBe("sess-2");
expect(thread?.session?.approvalPolicy).toBe("on-request");
expect(thread?.session?.sandboxMode).toBe("workspace-write");
expect(thread?.session?.threadId).toBe("thread-1");
expect(thread?.session?.runtimeMode).toBe("approval-required");
});
it("does not stop the active session when restart fails before rebind", async () => {
const harness = await createHarness();
const now = new Date().toISOString();
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.runtime-mode.set",
commandId: CommandId.makeUnsafe("cmd-runtime-mode-set-initial-full-access-2"),
threadId: ThreadId.makeUnsafe("thread-1"),
runtimeMode: "full-access",
createdAt: now,
}),
);
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.turn.start",
@@ -596,8 +538,8 @@ describe("ProviderCommandReactor", () => {
text: "first",
attachments: [],
},
approvalPolicy: "never",
sandboxMode: "danger-full-access",
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "full-access",
createdAt: now,
}),
);
@@ -611,21 +553,19 @@ describe("ProviderCommandReactor", () => {
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.turn.start",
commandId: CommandId.makeUnsafe("cmd-turn-start-restart-failure-2"),
type: "thread.runtime-mode.set",
commandId: CommandId.makeUnsafe("cmd-runtime-mode-set-restart-failure"),
threadId: ThreadId.makeUnsafe("thread-1"),
message: {
messageId: asMessageId("user-message-restart-failure-2"),
role: "user",
text: "second",
attachments: [],
},
approvalPolicy: "on-request",
sandboxMode: "workspace-write",
runtimeMode: "approval-required",
createdAt: now,
}),
);
await waitFor(async () => {
const readModel = await Effect.runPromise(harness.engine.getReadModel());
const thread = readModel.threads.find((entry) => entry.id === ThreadId.makeUnsafe("thread-1"));
return thread?.runtimeMode === "approval-required";
});
await waitFor(() => harness.startSession.mock.calls.length === 2);
await Effect.runPromise(Effect.sleep("30 millis"));
@@ -634,9 +574,8 @@ describe("ProviderCommandReactor", () => {
const readModel = await Effect.runPromise(harness.engine.getReadModel());
const thread = readModel.threads.find((entry) => entry.id === ThreadId.makeUnsafe("thread-1"));
expect(thread?.session?.providerSessionId).toBe("sess-1");
expect(thread?.session?.approvalPolicy).toBe("never");
expect(thread?.session?.sandboxMode).toBe("danger-full-access");
expect(thread?.session?.threadId).toBe("thread-1");
expect(thread?.session?.runtimeMode).toBe("full-access");
});
it("reacts to thread.turn.interrupt-requested by calling provider interrupt", async () => {
@@ -652,10 +591,7 @@ describe("ProviderCommandReactor", () => {
threadId: ThreadId.makeUnsafe("thread-1"),
status: "running",
providerName: "codex",
providerSessionId: asSessionId("sess-1"),
providerThreadId: ProviderThreadId.makeUnsafe("provider-thread-1"),
approvalPolicy: "on-request",
sandboxMode: "workspace-write",
runtimeMode: "approval-required",
activeTurnId: asTurnId("turn-1"),
lastError: null,
updatedAt: now,
@@ -676,7 +612,7 @@ describe("ProviderCommandReactor", () => {
await waitFor(() => harness.interruptTurn.mock.calls.length === 1);
expect(harness.interruptTurn.mock.calls[0]?.[0]).toEqual({
sessionId: "sess-1",
threadId: "thread-1",
});
});
@@ -693,10 +629,7 @@ describe("ProviderCommandReactor", () => {
threadId: ThreadId.makeUnsafe("thread-1"),
status: "running",
providerName: "codex",
providerSessionId: asSessionId("sess-1"),
providerThreadId: ProviderThreadId.makeUnsafe("provider-thread-1"),
approvalPolicy: "on-request",
sandboxMode: "workspace-write",
runtimeMode: "approval-required",
activeTurnId: null,
lastError: null,
updatedAt: now,
@@ -718,12 +651,149 @@ describe("ProviderCommandReactor", () => {
await waitFor(() => harness.respondToRequest.mock.calls.length === 1);
expect(harness.respondToRequest.mock.calls[0]?.[0]).toEqual({
sessionId: "sess-1",
threadId: "thread-1",
requestId: "approval-request-1",
decision: "accept",
});
});
it("reacts to thread.user-input.respond by forwarding structured user input answers", async () => {
const harness = await createHarness();
const now = new Date().toISOString();
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.session.set",
commandId: CommandId.makeUnsafe("cmd-session-set-for-user-input"),
threadId: ThreadId.makeUnsafe("thread-1"),
session: {
threadId: ThreadId.makeUnsafe("thread-1"),
status: "running",
providerName: "codex",
runtimeMode: "approval-required",
activeTurnId: null,
lastError: null,
updatedAt: now,
},
createdAt: now,
}),
);
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.user-input.respond",
commandId: CommandId.makeUnsafe("cmd-user-input-respond"),
threadId: ThreadId.makeUnsafe("thread-1"),
requestId: asApprovalRequestId("user-input-request-1"),
answers: {
sandbox_mode: "workspace-write",
},
createdAt: now,
}),
);
await waitFor(() => harness.respondToUserInput.mock.calls.length === 1);
expect(harness.respondToUserInput.mock.calls[0]?.[0]).toEqual({
threadId: "thread-1",
requestId: "user-input-request-1",
answers: {
sandbox_mode: "workspace-write",
},
});
});
it("surfaces stale provider approval request failures without faking approval resolution", async () => {
const harness = await createHarness();
const now = new Date().toISOString();
harness.respondToRequest.mockImplementation(() =>
Effect.fail(
new ProviderAdapterRequestError({
provider: "codex",
method: "session/request_permission",
detail: "Unknown pending permission request: approval-request-1",
}),
),
);
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.session.set",
commandId: CommandId.makeUnsafe("cmd-session-set-for-approval-error"),
threadId: ThreadId.makeUnsafe("thread-1"),
session: {
threadId: ThreadId.makeUnsafe("thread-1"),
status: "running",
providerName: "codex",
runtimeMode: "approval-required",
activeTurnId: null,
lastError: null,
updatedAt: now,
},
createdAt: now,
}),
);
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.activity.append",
commandId: CommandId.makeUnsafe("cmd-approval-requested"),
threadId: ThreadId.makeUnsafe("thread-1"),
activity: {
id: EventId.makeUnsafe("activity-approval-requested"),
tone: "approval",
kind: "approval.requested",
summary: "Command approval requested",
payload: {
requestId: "approval-request-1",
requestKind: "command",
},
turnId: null,
createdAt: now,
},
createdAt: now,
}),
);
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.approval.respond",
commandId: CommandId.makeUnsafe("cmd-approval-respond-stale"),
threadId: ThreadId.makeUnsafe("thread-1"),
requestId: asApprovalRequestId("approval-request-1"),
decision: "acceptForSession",
createdAt: now,
}),
);
await waitFor(async () => {
const readModel = await Effect.runPromise(harness.engine.getReadModel());
const thread = readModel.threads.find((entry) => entry.id === ThreadId.makeUnsafe("thread-1"));
if (!thread) return false;
return thread.activities.some((activity) => activity.kind === "provider.approval.respond.failed");
});
const readModel = await Effect.runPromise(harness.engine.getReadModel());
const thread = readModel.threads.find((entry) => entry.id === ThreadId.makeUnsafe("thread-1"));
expect(thread).toBeDefined();
const failureActivity = thread?.activities.find(
(activity) => activity.kind === "provider.approval.respond.failed",
);
expect(failureActivity).toBeDefined();
expect(failureActivity?.payload).toMatchObject({
requestId: "approval-request-1",
});
const resolvedActivity = thread?.activities.find(
(activity) =>
activity.kind === "approval.resolved" &&
typeof activity.payload === "object" &&
activity.payload !== null &&
(activity.payload as Record<string, unknown>).requestId === "approval-request-1",
);
expect(resolvedActivity).toBeUndefined();
});
it("reacts to thread.session.stop by stopping provider session and clearing thread session state", async () => {
const harness = await createHarness();
const now = new Date().toISOString();
@@ -737,10 +807,7 @@ describe("ProviderCommandReactor", () => {
threadId: ThreadId.makeUnsafe("thread-1"),
status: "ready",
providerName: "codex",
providerSessionId: asSessionId("sess-1"),
providerThreadId: ProviderThreadId.makeUnsafe("provider-thread-1"),
approvalPolicy: "on-request",
sandboxMode: "workspace-write",
runtimeMode: "approval-required",
activeTurnId: null,
lastError: null,
updatedAt: now,
@@ -763,8 +830,7 @@ describe("ProviderCommandReactor", () => {
const thread = readModel.threads.find((entry) => entry.id === ThreadId.makeUnsafe("thread-1"));
expect(thread?.session).not.toBeNull();
expect(thread?.session?.status).toBe("stopped");
expect(thread?.session?.providerSessionId).toBeNull();
expect(thread?.session?.providerThreadId).toBeNull();
expect(thread?.session?.threadId).toBe("thread-1");
expect(thread?.session?.activeTurnId).toBeNull();
});
});
@@ -3,19 +3,20 @@ import {
CommandId,
EventId,
type OrchestrationEvent,
type ProviderApprovalPolicy,
type ProviderModelOptions,
type ProviderKind,
type ProviderSandboxMode,
type ProviderServiceTier,
type OrchestrationSession,
type ThreadId,
ThreadId,
type ProviderSession,
type ProviderThreadId,
type RuntimeMode,
type TurnId,
} from "@t3tools/contracts";
import { Cache, Cause, Duration, Effect, Layer, Option, Queue, Stream } from "effect";
import { Cache, Cause, Duration, Effect, Layer, Option, Queue, Schema, 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,9 +29,11 @@ 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";
}
>;
@@ -66,11 +69,36 @@ const serverCommandId = (tag: string): CommandId =>
const HANDLED_TURN_START_KEY_MAX = 10_000;
const HANDLED_TURN_START_KEY_TTL = Duration.minutes(30);
const DEFAULT_APPROVAL_POLICY: ProviderApprovalPolicy = "never";
const DEFAULT_SANDBOX_MODE: ProviderSandboxMode = "workspace-write";
const DEFAULT_RUNTIME_MODE: RuntimeMode = "full-access";
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());
}
@@ -122,11 +150,13 @@ 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",
@@ -139,6 +169,7 @@ const make = Effect.gen(function* () {
summary: input.summary,
payload: {
detail: input.detail,
...(input.requestId ? { requestId: input.requestId } : {}),
},
turnId: input.turnId,
createdAt: input.createdAt,
@@ -168,8 +199,10 @@ const make = Effect.gen(function* () {
threadId: ThreadId,
createdAt: string,
options?: {
readonly approvalPolicy?: ProviderApprovalPolicy;
readonly sandboxMode?: ProviderSandboxMode;
readonly provider?: ProviderKind;
readonly model?: string;
readonly modelOptions?: ProviderModelOptions;
readonly serviceTier?: ProviderServiceTier | null;
},
) {
const readModel = yield* orchestrationEngine.getReadModel();
@@ -178,27 +211,36 @@ const make = Effect.gen(function* () {
return yield* Effect.die(new Error(`Thread '${threadId}' was not found in read model.`));
}
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 desiredRuntimeMode = thread.runtimeMode;
const currentProvider: ProviderKind | undefined =
thread.session?.providerName === "codex" ? 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 startProviderSession = (resumeThreadId?: ProviderThreadId | null) =>
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;
}) =>
providerService.startSession(threadId, {
...(preferredProvider ? { provider: preferredProvider } : {}),
threadId,
...(input?.provider ?? preferredProvider
? { provider: input?.provider ?? preferredProvider }
: {}),
...(effectiveCwd ? { cwd: effectiveCwd } : {}),
...(thread.model ? { model: thread.model } : {}),
...(resumeThreadId ? { resumeThreadId } : {}),
approvalPolicy: desiredApprovalPolicy,
sandboxMode: desiredSandboxMode,
...(desiredModel ? { model: desiredModel } : {}),
...(options?.serviceTier !== undefined ? { serviceTier: options.serviceTier } : {}),
...(options?.modelOptions !== undefined ? { modelOptions: options.modelOptions } : {}),
...(input?.resumeCursor !== undefined ? { resumeCursor: input.resumeCursor } : {}),
runtimeMode: desiredRuntimeMode,
});
const bindSessionToThread = (session: ProviderSession) =>
@@ -208,10 +250,7 @@ const make = Effect.gen(function* () {
threadId,
status: mapProviderSessionStatusToOrchestrationStatus(session.status),
providerName: session.provider,
providerSessionId: session.sessionId,
providerThreadId: session.threadId ?? null,
approvalPolicy: desiredApprovalPolicy,
sandboxMode: desiredSandboxMode,
runtimeMode: desiredRuntimeMode,
// Provider turn ids are not orchestration turn ids.
activeTurnId: null,
lastError: session.lastError ?? null,
@@ -220,66 +259,105 @@ const make = Effect.gen(function* () {
createdAt,
});
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;
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";
if (!approvalPolicyChanged && !sandboxModeChanged) {
return existingSessionId;
if (!runtimeModeChanged && !providerChanged && !shouldRestartForModelChange) {
return existingSessionThreadId;
}
const restartedSession = yield* startProviderSession(
thread.session?.providerThreadId ?? null,
);
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,
});
yield* bindSessionToThread(restartedSession);
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;
return restartedSession.threadId;
}
const startedSession = yield* startProviderSession();
const startedSession = yield* startProviderSession(
options?.provider !== undefined ? { provider: options.provider } : undefined,
);
yield* bindSessionToThread(startedSession);
return startedSession.sessionId;
return startedSession.threadId;
});
const sendTurnForThread = Effect.fnUntraced(function* (input: {
readonly threadId: ThreadId;
readonly messageText: string;
readonly attachments?: ReadonlyArray<ChatAttachment>;
readonly provider?: ProviderKind;
readonly model?: string;
readonly effort?: string;
readonly approvalPolicy: ProviderApprovalPolicy;
readonly sandboxMode: ProviderSandboxMode;
readonly serviceTier?: ProviderServiceTier | null;
readonly modelOptions?: ProviderModelOptions;
readonly interactionMode?: "default" | "plan";
readonly createdAt: string;
}) {
const thread = yield* resolveThread(input.threadId);
if (!thread) {
return;
}
const sessionId = yield* ensureSessionForThread(input.threadId, input.createdAt, {
approvalPolicy: input.approvalPolicy,
sandboxMode: input.sandboxMode,
yield* ensureSessionForThread(input.threadId, input.createdAt, {
...(input.provider !== undefined ? { provider: input.provider } : {}),
...(input.model !== undefined ? { model: input.model } : {}),
...(input.serviceTier !== undefined ? { serviceTier: input.serviceTier } : {}),
...(input.modelOptions !== undefined ? { modelOptions: input.modelOptions } : {}),
});
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({
sessionId,
threadId: input.threadId,
...(normalizedInput ? { input: normalizedInput } : {}),
...(normalizedAttachments.length > 0 ? { attachments: normalizedAttachments } : {}),
...(input.model !== undefined ? { model: input.model } : {}),
...(input.effort !== undefined ? { effort: input.effort } : {}),
...(modelForTurn !== undefined ? { model: modelForTurn } : {}),
...(input.serviceTier !== undefined ? { serviceTier: input.serviceTier } : {}),
...(input.modelOptions !== undefined ? { modelOptions: input.modelOptions } : {}),
...(input.interactionMode !== undefined ? { interactionMode: input.interactionMode } : {}),
});
});
@@ -390,10 +468,11 @@ 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.effort !== undefined ? { effort: event.payload.effort } : {}),
approvalPolicy: event.payload.approvalPolicy,
sandboxMode: event.payload.sandboxMode,
...(event.payload.serviceTier !== undefined ? { serviceTier: event.payload.serviceTier } : {}),
...(event.payload.modelOptions !== undefined ? { modelOptions: event.payload.modelOptions } : {}),
interactionMode: event.payload.interactionMode,
createdAt: event.payload.createdAt,
});
});
@@ -405,8 +484,8 @@ const make = Effect.gen(function* () {
if (!thread) {
return;
}
const sessionId = thread.session?.providerSessionId;
if (!sessionId) {
const hasSession = thread.session && thread.session.status !== "stopped";
if (!hasSession) {
return yield* appendProviderFailureActivity({
threadId: event.payload.threadId,
kind: "provider.turn.interrupt.failed",
@@ -418,7 +497,7 @@ const make = Effect.gen(function* () {
}
// Orchestration turn ids are not provider turn ids, so interrupt by session.
yield* providerService.interruptTurn({ sessionId });
yield* providerService.interruptTurn({ threadId: event.payload.threadId });
});
const processApprovalResponseRequested = Effect.fnUntraced(function* (
@@ -428,8 +507,8 @@ const make = Effect.gen(function* () {
if (!thread) {
return;
}
const sessionId = thread.session?.providerSessionId;
if (!sessionId) {
const hasSession = thread.session && thread.session.status !== "stopped";
if (!hasSession) {
return yield* appendProviderFailureActivity({
threadId: event.payload.threadId,
kind: "provider.approval.respond.failed",
@@ -437,14 +516,79 @@ 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({
sessionId,
requestId: event.payload.requestId,
decision: event.payload.decision,
});
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,
});
}),
),
);
});
const processSessionStopRequested = Effect.fnUntraced(function* (
@@ -456,10 +600,8 @@ const make = Effect.gen(function* () {
}
const now = event.payload.createdAt;
const sessionId = thread.session?.providerSessionId;
if (sessionId) {
yield* providerService.stopSession({ sessionId });
if (thread.session && thread.session.status !== "stopped") {
yield* providerService.stopSession({ threadId: thread.id });
}
yield* setThreadSession({
@@ -468,10 +610,7 @@ const make = Effect.gen(function* () {
threadId: thread.id,
status: "stopped",
providerName: thread.session?.providerName ?? null,
providerSessionId: null,
providerThreadId: null,
approvalPolicy: thread.session?.approvalPolicy ?? DEFAULT_APPROVAL_POLICY,
sandboxMode: thread.session?.sandboxMode ?? DEFAULT_SANDBOX_MODE,
runtimeMode: thread.session?.runtimeMode ?? DEFAULT_RUNTIME_MODE,
activeTurnId: null,
lastError: thread.session?.lastError ?? null,
updatedAt: now,
@@ -483,6 +622,14 @@ 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;
@@ -492,6 +639,9 @@ 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;
@@ -522,9 +672,11 @@ 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
+6
View File
@@ -4,8 +4,11 @@ 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,
@@ -24,9 +27,12 @@ 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,6 +2,7 @@ import { describe, expect, it } from "vitest";
import {
MessageId,
CommandId,
DEFAULT_PROVIDER_INTERACTION_MODE,
ProjectId,
ThreadId,
type OrchestrationCommand,
@@ -50,6 +51,8 @@ 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,
@@ -58,6 +61,7 @@ const readModel: OrchestrationReadModel = {
messages: [],
session: null,
activities: [],
proposedPlans: [],
checkpoints: [],
deletedAt: null,
},
@@ -66,6 +70,8 @@ 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,
@@ -74,6 +80,7 @@ const readModel: OrchestrationReadModel = {
messages: [],
session: null,
activities: [],
proposedPlans: [],
checkpoints: [],
deletedAt: null,
},
@@ -90,8 +97,8 @@ const messageSendCommand: OrchestrationCommand = {
text: "hello",
attachments: [],
},
approvalPolicy: "on-request",
sandboxMode: "workspace-write",
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "approval-required",
createdAt: now,
};
@@ -138,6 +145,8 @@ 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,
@@ -157,6 +166,8 @@ 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,4 +1,11 @@
import { CommandId, EventId, MessageId, ProjectId, ThreadId } from "@t3tools/contracts";
import {
CommandId,
DEFAULT_PROVIDER_INTERACTION_MODE,
EventId,
MessageId,
ProjectId,
ThreadId,
} from "@t3tools/contracts";
import { describe, expect, it } from "vitest";
import { Effect } from "effect";
@@ -130,6 +137,8 @@ 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,
@@ -150,10 +159,16 @@ describe("decider project scripts", () => {
text: "hello",
attachments: [],
},
model: "gpt-5",
effort: "high",
approvalPolicy: "on-request",
sandboxMode: "workspace-write",
provider: "codex",
model: "gpt-5.3-codex",
modelOptions: {
codex: {
reasoningEffort: "high",
fastMode: true,
},
},
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "approval-required",
createdAt: now,
},
readModel,
@@ -174,10 +189,173 @@ describe("decider project scripts", () => {
expect(turnStartEvent.payload).toMatchObject({
threadId: ThreadId.makeUnsafe("thread-1"),
messageId: asMessageId("message-user-1"),
model: "gpt-5",
effort: "high",
approvalPolicy: "on-request",
sandboxMode: "workspace-write",
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",
},
});
});
});
+105 -11
View File
@@ -157,6 +157,8 @@ 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,
@@ -239,6 +241,52 @@ 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,
@@ -277,11 +325,17 @@ 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.effort !== undefined ? { effort: command.effort } : {}),
...(command.serviceTier !== undefined ? { serviceTier: command.serviceTier } : {}),
...(command.modelOptions !== undefined ? { modelOptions: command.modelOptions } : {}),
assistantDeliveryMode: command.assistantDeliveryMode ?? DEFAULT_ASSISTANT_DELIVERY_MODE,
approvalPolicy: command.approvalPolicy,
sandboxMode: command.sandboxMode,
runtimeMode:
readModel.threads.find((entry) => entry.id === command.threadId)?.runtimeMode ??
command.runtimeMode,
interactionMode:
readModel.threads.find((entry) => entry.id === command.threadId)?.interactionMode ??
command.interactionMode,
createdAt: command.createdAt,
},
};
@@ -336,6 +390,32 @@ 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,
@@ -391,14 +471,7 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
aggregateId: command.threadId,
occurredAt: command.createdAt,
commandId: command.commandId,
metadata: {
...(command.session.providerSessionId !== null
? { providerSessionId: command.session.providerSessionId }
: {}),
...(command.session.providerThreadId !== null
? { providerThreadId: command.session.providerThreadId }
: {}),
},
metadata: {},
}),
type: "thread.session-set",
payload: {
@@ -462,6 +535,27 @@ 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,6 +57,7 @@ describe("orchestration projector", () => {
projectId: "project-1",
title: "demo",
model: "gpt-5-codex",
runtimeMode: "full-access",
branch: null,
worktreePath: null,
createdAt: now,
@@ -73,6 +74,8 @@ describe("orchestration projector", () => {
projectId: "project-1",
title: "demo",
model: "gpt-5-codex",
runtimeMode: "full-access",
interactionMode: "default",
branch: null,
worktreePath: null,
latestTurn: null,
@@ -80,6 +83,7 @@ describe("orchestration projector", () => {
updatedAt: now,
deletedAt: null,
messages: [],
proposedPlans: [],
activities: [],
checkpoints: [],
session: null,
@@ -135,8 +139,7 @@ describe("orchestration projector", () => {
payload: {
threadId: "thread-1",
messageId: "message-1",
approvalPolicy: "on-request",
sandboxMode: "workspace-write",
runtimeMode: "approval-required",
createdAt: "2026-01-01T00:00:00.000Z",
},
}),
@@ -168,6 +171,7 @@ describe("orchestration projector", () => {
projectId: "project-1",
title: "demo",
model: "gpt-5.3-codex",
runtimeMode: "full-access",
branch: null,
worktreePath: null,
createdAt,
@@ -195,8 +199,7 @@ describe("orchestration projector", () => {
providerName: "codex",
providerSessionId: "session-1",
providerThreadId: "provider-thread-1",
approvalPolicy: "on-request",
sandboxMode: "workspace-write",
runtimeMode: "approval-required",
activeTurnId: "turn-1",
lastError: null,
updatedAt: startedAt,
@@ -211,6 +214,59 @@ 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";
@@ -232,6 +288,7 @@ describe("orchestration projector", () => {
projectId: "project-1",
title: "demo",
model: "gpt-5.3-codex",
runtimeMode: "full-access",
branch: null,
worktreePath: null,
createdAt,
@@ -315,6 +372,7 @@ describe("orchestration projector", () => {
projectId: "project-1",
title: "demo",
model: "gpt-5.3-codex",
runtimeMode: "full-access",
branch: null,
worktreePath: null,
createdAt,
@@ -526,6 +584,7 @@ describe("orchestration projector", () => {
projectId: "project-1",
title: "demo",
model: "gpt-5.3-codex",
runtimeMode: "full-access",
branch: null,
worktreePath: null,
createdAt,
@@ -675,6 +734,7 @@ describe("orchestration projector", () => {
projectId: "project-1",
title: "capped",
model: "gpt-5-codex",
runtimeMode: "full-access",
branch: null,
worktreePath: null,
createdAt,
+101 -1
View File
@@ -16,7 +16,10 @@ import {
ThreadActivityAppendedPayload,
ThreadCreatedPayload,
ThreadDeletedPayload,
ThreadInteractionModeSetPayload,
ThreadMetaUpdatedPayload,
ThreadProposedPlanUpsertedPayload,
ThreadRuntimeModeSetPayload,
ThreadRevertedPayload,
ThreadSessionSetPayload,
ThreadTurnDiffCompletedPayload,
@@ -124,6 +127,32 @@ 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,
@@ -224,6 +253,8 @@ 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,
@@ -272,6 +303,38 @@ 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(
@@ -382,6 +445,38 @@ 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(
@@ -458,6 +553,10 @@ 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;
@@ -478,6 +577,7 @@ export function projectEvent(
threads: updateThread(nextBase.threads, payload.threadId, {
checkpoints,
messages,
proposedPlans,
activities,
latestTurn,
updatedAt: event.occurredAt,
@@ -503,7 +603,7 @@ export function projectEvent(
...thread.activities.filter((entry) => entry.id !== payload.activity.id),
payload.activity,
]
.toSorted((left, right) => left.createdAt.localeCompare(right.createdAt))
.toSorted(compareThreadActivities)
.slice(-500);
return {
@@ -74,8 +74,6 @@ 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,5 +1,6 @@
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";
@@ -15,6 +16,7 @@ import {
const ProjectionThreadActivityDbRowSchema = ProjectionThreadActivity.mapFields(
Struct.assign({
payload: Schema.fromJsonString(Schema.Unknown),
sequence: Schema.NullOr(NonNegativeInt),
}),
);
@@ -29,7 +31,7 @@ const makeProjectionThreadActivityRepository = Effect.gen(function* () {
const sql = yield* SqlClient.SqlClient;
const upsertProjectionThreadActivityRow = SqlSchema.void({
Request: ProjectionThreadActivityDbRowSchema,
Request: ProjectionThreadActivity,
execute: (row) =>
sql`
INSERT INTO projection_thread_activities (
@@ -40,6 +42,7 @@ const makeProjectionThreadActivityRepository = Effect.gen(function* () {
kind,
summary,
payload_json,
sequence,
created_at
)
VALUES (
@@ -49,7 +52,8 @@ const makeProjectionThreadActivityRepository = Effect.gen(function* () {
${row.tone},
${row.kind},
${row.summary},
${row.payload},
${JSON.stringify(row.payload)},
${row.sequence ?? null},
${row.createdAt}
)
ON CONFLICT (activity_id)
@@ -60,6 +64,7 @@ const makeProjectionThreadActivityRepository = Effect.gen(function* () {
kind = excluded.kind,
summary = excluded.summary,
payload_json = excluded.payload_json,
sequence = excluded.sequence,
created_at = excluded.created_at
`,
});
@@ -77,10 +82,15 @@ 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 created_at ASC, activity_id ASC
ORDER BY
CASE WHEN sequence IS NULL THEN 0 ELSE 1 END ASC,
sequence ASC,
created_at ASC,
activity_id ASC
`,
});
@@ -111,8 +121,18 @@ const makeProjectionThreadActivityRepository = Effect.gen(function* () {
"ProjectionThreadActivityRepository.listByThreadId:decodeRows",
),
),
Effect.map(
(rows) => rows as ReadonlyArray<Schema.Schema.Type<typeof ProjectionThreadActivity>>,
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,
})),
),
);
@@ -0,0 +1,104 @@
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,10 +23,7 @@ const makeProjectionThreadSessionRepository = Effect.gen(function* () {
thread_id,
status,
provider_name,
provider_session_id,
provider_thread_id,
approval_policy,
sandbox_mode,
runtime_mode,
active_turn_id,
last_error,
updated_at
@@ -35,10 +32,7 @@ const makeProjectionThreadSessionRepository = Effect.gen(function* () {
${row.threadId},
${row.status},
${row.providerName},
${row.providerSessionId},
${row.providerThreadId},
${row.approvalPolicy},
${row.sandboxMode},
${row.runtimeMode},
${row.activeTurnId},
${row.lastError},
${row.updatedAt}
@@ -47,10 +41,7 @@ const makeProjectionThreadSessionRepository = Effect.gen(function* () {
DO UPDATE SET
status = excluded.status,
provider_name = excluded.provider_name,
provider_session_id = excluded.provider_session_id,
provider_thread_id = excluded.provider_thread_id,
approval_policy = excluded.approval_policy,
sandbox_mode = excluded.sandbox_mode,
runtime_mode = excluded.runtime_mode,
active_turn_id = excluded.active_turn_id,
last_error = excluded.last_error,
updated_at = excluded.updated_at
@@ -66,10 +57,7 @@ const makeProjectionThreadSessionRepository = Effect.gen(function* () {
thread_id AS "threadId",
status,
provider_name AS "providerName",
provider_session_id AS "providerSessionId",
provider_thread_id AS "providerThreadId",
approval_policy AS "approvalPolicy",
sandbox_mode AS "sandboxMode",
runtime_mode AS "runtimeMode",
active_turn_id AS "activeTurnId",
last_error AS "lastError",
updated_at AS "updatedAt"
@@ -24,6 +24,8 @@ const makeProjectionThreadRepository = Effect.gen(function* () {
project_id,
title,
model,
runtime_mode,
interaction_mode,
branch,
worktree_path,
latest_turn_id,
@@ -36,6 +38,8 @@ const makeProjectionThreadRepository = Effect.gen(function* () {
${row.projectId},
${row.title},
${row.model},
${row.runtimeMode},
${row.interactionMode},
${row.branch},
${row.worktreePath},
${row.latestTurnId},
@@ -48,6 +52,8 @@ 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,
@@ -67,6 +73,8 @@ 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",
@@ -88,6 +96,8 @@ 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 { ProviderSessionId } from "@t3tools/contracts";
import { 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, Struct } from "effect";
@@ -24,7 +24,7 @@ const ProviderSessionRuntimeDbRowSchema = ProviderSessionRuntime.mapFields(
const decodeRuntime = Schema.decodeUnknownEffect(ProviderSessionRuntime);
const GetRuntimeRequestSchema = Schema.Struct({
providerSessionId: ProviderSessionId,
threadId: ThreadId,
});
const DeleteRuntimeRequestSchema = GetRuntimeRequestSchema;
@@ -44,33 +44,30 @@ const makeProviderSessionRuntimeRepository = Effect.gen(function* () {
execute: (runtime) =>
sql`
INSERT INTO provider_session_runtime (
provider_session_id,
thread_id,
provider_name,
adapter_key,
provider_thread_id,
runtime_mode,
status,
last_seen_at,
resume_cursor_json,
runtime_payload_json
)
VALUES (
${runtime.providerSessionId},
${runtime.threadId},
${runtime.providerName},
${runtime.adapterKey},
${runtime.providerThreadId},
${runtime.runtimeMode},
${runtime.status},
${runtime.lastSeenAt},
${runtime.resumeCursor},
${runtime.runtimePayload}
)
ON CONFLICT (provider_session_id)
ON CONFLICT (thread_id)
DO UPDATE SET
thread_id = excluded.thread_id,
provider_name = excluded.provider_name,
adapter_key = excluded.adapter_key,
provider_thread_id = excluded.provider_thread_id,
runtime_mode = excluded.runtime_mode,
status = excluded.status,
last_seen_at = excluded.last_seen_at,
resume_cursor_json = excluded.resume_cursor_json,
@@ -78,23 +75,22 @@ const makeProviderSessionRuntimeRepository = Effect.gen(function* () {
`,
});
const getRuntimeRowBySessionId = SqlSchema.findOneOption({
const getRuntimeRowByThreadId = SqlSchema.findOneOption({
Request: GetRuntimeRequestSchema,
Result: ProviderSessionRuntimeDbRowSchema,
execute: ({ providerSessionId }) =>
execute: ({ threadId }) =>
sql`
SELECT
provider_session_id AS "providerSessionId",
thread_id AS "threadId",
provider_name AS "providerName",
adapter_key AS "adapterKey",
provider_thread_id AS "providerThreadId",
runtime_mode AS "runtimeMode",
status,
last_seen_at AS "lastSeenAt",
resume_cursor_json AS "resumeCursor",
runtime_payload_json AS "runtimePayload"
FROM provider_session_runtime
WHERE provider_session_id = ${providerSessionId}
WHERE thread_id = ${threadId}
`,
});
@@ -104,26 +100,25 @@ 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",
provider_thread_id AS "providerThreadId",
runtime_mode AS "runtimeMode",
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, provider_session_id ASC
ORDER BY last_seen_at ASC, thread_id ASC
`,
});
const deleteRuntimeBySessionId = SqlSchema.void({
const deleteRuntimeByThreadId = SqlSchema.void({
Request: DeleteRuntimeRequestSchema,
execute: ({ providerSessionId }) =>
execute: ({ threadId }) =>
sql`
DELETE FROM provider_session_runtime
WHERE provider_session_id = ${providerSessionId}
WHERE thread_id = ${threadId}
`,
});
@@ -137,12 +132,12 @@ const makeProviderSessionRuntimeRepository = Effect.gen(function* () {
),
);
const getBySessionId: ProviderSessionRuntimeRepositoryShape["getBySessionId"] = (input) =>
getRuntimeRowBySessionId(input).pipe(
const getByThreadId: ProviderSessionRuntimeRepositoryShape["getByThreadId"] = (input) =>
getRuntimeRowByThreadId(input).pipe(
Effect.mapError(
toPersistenceSqlOrDecodeError(
"ProviderSessionRuntimeRepository.getBySessionId:query",
"ProviderSessionRuntimeRepository.getBySessionId:decodeRow",
"ProviderSessionRuntimeRepository.getByThreadId:query",
"ProviderSessionRuntimeRepository.getByThreadId:decodeRow",
),
),
Effect.flatMap((runtimeRowOption) =>
@@ -152,7 +147,7 @@ const makeProviderSessionRuntimeRepository = Effect.gen(function* () {
decodeRuntime(row).pipe(
Effect.mapError(
toPersistenceDecodeError(
"ProviderSessionRuntimeRepository.getBySessionId:rowToRuntime",
"ProviderSessionRuntimeRepository.getByThreadId:rowToRuntime",
),
),
Effect.map((runtime) => Option.some(runtime)),
@@ -183,18 +178,18 @@ const makeProviderSessionRuntimeRepository = Effect.gen(function* () {
),
);
const deleteBySessionId: ProviderSessionRuntimeRepositoryShape["deleteBySessionId"] = (input) =>
deleteRuntimeBySessionId(input).pipe(
const deleteByThreadId: ProviderSessionRuntimeRepositoryShape["deleteByThreadId"] = (input) =>
deleteRuntimeByThreadId(input).pipe(
Effect.mapError(
toPersistenceSqlError("ProviderSessionRuntimeRepository.deleteBySessionId:query"),
toPersistenceSqlError("ProviderSessionRuntimeRepository.deleteByThreadId:query"),
),
);
return {
upsert,
getBySessionId,
getByThreadId,
list,
deleteBySessionId,
deleteByThreadId,
} satisfies ProviderSessionRuntimeRepositoryShape;
});
@@ -1,225 +0,0 @@
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,
);
+18 -1
View File
@@ -19,6 +19,13 @@ 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.
@@ -38,6 +45,12 @@ 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,
});
/**
@@ -56,7 +69,11 @@ const run = Migrator.make({});
*
* @returns Effect containing array of executed migrations
*/
export const runMigrations = run({ loader });
export const runMigrations = Effect.gen(function* () {
yield* Effect.log("Running migrations...");
yield* run({ loader });
yield* Effect.log("Migrations ran successfully");
});
/**
* Layer that runs migrations when the layer is built.
@@ -6,11 +6,10 @@ export default Effect.gen(function* () {
yield* sql`
CREATE TABLE IF NOT EXISTS provider_session_runtime (
provider_session_id TEXT PRIMARY KEY,
thread_id TEXT NOT NULL,
thread_id TEXT PRIMARY KEY,
provider_name TEXT NOT NULL,
adapter_key TEXT NOT NULL,
provider_thread_id TEXT,
runtime_mode TEXT NOT NULL DEFAULT 'full-access',
status TEXT NOT NULL,
last_seen_at TEXT NOT NULL,
resume_cursor_json TEXT,
@@ -18,11 +17,6 @@ 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)
@@ -1,30 +1,19 @@
import * as SqlClient from "effect/unstable/sql/SqlClient";
import * as Effect from "effect/Effect";
const DEFAULT_APPROVAL_POLICY = "never";
const DEFAULT_SANDBOX_MODE = "workspace-write";
const DEFAULT_RUNTIME_MODE = "full-access";
export default Effect.gen(function* () {
const sql = yield* SqlClient.SqlClient;
yield* sql`
ALTER TABLE projection_thread_sessions
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'
ADD COLUMN runtime_mode TEXT NOT NULL DEFAULT 'full-access'
`;
yield* sql`
UPDATE projection_thread_sessions
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
SET runtime_mode = ${DEFAULT_RUNTIME_MODE}
WHERE runtime_mode IS NULL
`;
});
@@ -0,0 +1,16 @@
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)
`;
});
@@ -0,0 +1,6 @@
import * as SqlClient from "effect/unstable/sql/SqlClient";
import * as Effect from "effect/Effect";
export default Effect.gen(function* () {
yield* SqlClient.SqlClient;
});
@@ -0,0 +1,17 @@
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
`;
});
@@ -0,0 +1,13 @@
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
`;
});
@@ -0,0 +1,11 @@
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'
`;
});
@@ -0,0 +1,22 @@
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,6 +9,7 @@
import {
EventId,
IsoDateTime,
NonNegativeInt,
OrchestrationThreadActivityTone,
ThreadId,
TurnId,
@@ -26,6 +27,7 @@ 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;
@@ -57,7 +59,8 @@ export interface ProjectionThreadActivityRepositoryShape {
/**
* List projected thread activity rows for a thread.
*
* Returned in ascending creation order.
* Returned in ascending runtime sequence order (or creation order when
* sequence is unavailable).
*/
readonly listByThreadId: (
input: ListProjectionThreadActivitiesInput,
@@ -0,0 +1,52 @@
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,12 +7,9 @@
* @module ProjectionThreadSessionRepository
*/
import {
RuntimeMode,
IsoDateTime,
OrchestrationSessionStatus,
ProviderApprovalPolicy,
ProviderSandboxMode,
ProviderSessionId,
ProviderThreadId,
ThreadId,
TurnId,
} from "@t3tools/contracts";
@@ -25,10 +22,7 @@ export const ProjectionThreadSession = Schema.Struct({
threadId: ThreadId,
status: OrchestrationSessionStatus,
providerName: Schema.NullOr(Schema.String),
providerSessionId: Schema.NullOr(ProviderSessionId),
providerThreadId: Schema.NullOr(ProviderThreadId),
approvalPolicy: ProviderApprovalPolicy,
sandboxMode: ProviderSandboxMode,
runtimeMode: RuntimeMode,
activeTurnId: Schema.NullOr(TurnId),
lastError: Schema.NullOr(Schema.String),
updatedAt: IsoDateTime,
@@ -6,7 +6,14 @@
*
* @module ProjectionThreadRepository
*/
import { IsoDateTime, ProjectId, ThreadId, TurnId } from "@t3tools/contracts";
import {
IsoDateTime,
ProjectId,
ProviderInteractionMode,
RuntimeMode,
ThreadId,
TurnId,
} from "@t3tools/contracts";
import { Option, Schema, ServiceMap } from "effect";
import type { Effect } from "effect";
@@ -17,6 +24,8 @@ 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,9 +7,8 @@
*/
import {
IsoDateTime,
ProviderSessionId,
ProviderSessionRuntimeStatus,
ProviderThreadId,
RuntimeMode,
ThreadId,
} from "@t3tools/contracts";
import { Option, Schema, ServiceMap } from "effect";
@@ -18,11 +17,10 @@ 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,
providerThreadId: Schema.NullOr(ProviderThreadId),
runtimeMode: RuntimeMode,
status: ProviderSessionRuntimeStatus,
lastSeenAt: IsoDateTime,
resumeCursor: Schema.NullOr(Schema.Unknown),
@@ -30,14 +28,10 @@ export const ProviderSessionRuntime = Schema.Struct({
});
export type ProviderSessionRuntime = typeof ProviderSessionRuntime.Type;
export const GetProviderSessionRuntimeInput = Schema.Struct({
providerSessionId: ProviderSessionId,
});
export const GetProviderSessionRuntimeInput = Schema.Struct({ threadId: ThreadId });
export type GetProviderSessionRuntimeInput = typeof GetProviderSessionRuntimeInput.Type;
export const DeleteProviderSessionRuntimeInput = Schema.Struct({
providerSessionId: ProviderSessionId,
});
export const DeleteProviderSessionRuntimeInput = Schema.Struct({ threadId: ThreadId });
export type DeleteProviderSessionRuntimeInput = typeof DeleteProviderSessionRuntimeInput.Type;
/**
@@ -47,16 +41,16 @@ export interface ProviderSessionRuntimeRepositoryShape {
/**
* Insert or replace a provider runtime row.
*
* Upserts by `providerSessionId`, including JSON payload/cursor fields.
* Upserts by canonical `threadId`, including JSON payload/cursor fields.
*/
readonly upsert: (
runtime: ProviderSessionRuntime,
) => Effect.Effect<void, ProviderSessionRuntimeRepositoryError>;
/**
* Read provider runtime state by provider session id.
* Read provider runtime state by canonical thread id.
*/
readonly getBySessionId: (
readonly getByThreadId: (
input: GetProviderSessionRuntimeInput,
) => Effect.Effect<Option.Option<ProviderSessionRuntime>, ProviderSessionRuntimeRepositoryError>;
@@ -71,9 +65,9 @@ export interface ProviderSessionRuntimeRepositoryShape {
>;
/**
* Delete provider runtime state by provider session id.
* Delete provider runtime state by canonical thread id.
*/
readonly deleteBySessionId: (
readonly deleteByThreadId: (
input: DeleteProviderSessionRuntimeInput,
) => Effect.Effect<void, ProviderSessionRuntimeRepositoryError>;
}
@@ -1,81 +0,0 @@
/**
* 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") {}
+8 -8
View File
@@ -26,12 +26,12 @@ export class ProviderAdapterSessionNotFoundError extends Schema.TaggedErrorClass
"ProviderAdapterSessionNotFoundError",
{
provider: Schema.String,
sessionId: Schema.String,
threadId: Schema.String,
cause: Schema.optional(Schema.Defect),
},
) {
override get message(): string {
return `Unknown ${this.provider} adapter session: ${this.sessionId}`;
return `Unknown ${this.provider} adapter thread: ${this.threadId}`;
}
}
@@ -42,12 +42,12 @@ export class ProviderAdapterSessionClosedError extends Schema.TaggedErrorClass<P
"ProviderAdapterSessionClosedError",
{
provider: Schema.String,
sessionId: Schema.String,
threadId: Schema.String,
cause: Schema.optional(Schema.Defect),
},
) {
override get message(): string {
return `${this.provider} adapter session is closed: ${this.sessionId}`;
return `${this.provider} adapter thread is closed: ${this.threadId}`;
}
}
@@ -75,13 +75,13 @@ export class ProviderAdapterProcessError extends Schema.TaggedErrorClass<Provide
"ProviderAdapterProcessError",
{
provider: Schema.String,
sessionId: Schema.String,
threadId: Schema.String,
detail: Schema.String,
cause: Schema.optional(Schema.Defect),
},
) {
override get message(): string {
return `Provider adapter process error (${this.provider}) for session ${this.sessionId}: ${this.detail}`;
return `Provider adapter process error (${this.provider}) for thread ${this.threadId}: ${this.detail}`;
}
}
@@ -122,12 +122,12 @@ export class ProviderUnsupportedError extends Schema.TaggedErrorClass<ProviderUn
export class ProviderSessionNotFoundError extends Schema.TaggedErrorClass<ProviderSessionNotFoundError>()(
"ProviderSessionNotFoundError",
{
sessionId: Schema.String,
threadId: Schema.String,
cause: Schema.optional(Schema.Defect),
},
) {
override get message(): string {
return `Unknown provider session: ${this.sessionId}`;
return `Unknown provider thread: ${this.threadId}`;
}
}
@@ -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, assert, it, vi } from "@effect/vitest";
import { assertFailure } from "@effect/vitest/utils";
import { afterAll, it, vi } from "@effect/vitest";
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 asSessionId = (value: string): ProviderSessionId => ProviderSessionId.makeUnsafe(value);
const asTurnId = (value: string): ProviderTurnId => ProviderTurnId.makeUnsafe(value);
const asThreadId = (value: string): ThreadId => ThreadId.makeUnsafe(value);
const asTurnId = (value: string): TurnId => TurnId.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: ProviderSessionStartInput): Promise<ProviderSession> => {
async (input: CodexAppServerStartSessionInput): Promise<ProviderSession> => {
const now = new Date().toISOString();
return {
sessionId: asSessionId("sess-1"),
provider: "codex",
status: "ready",
threadId: ProviderThreadId.makeUnsafe("thread-1"),
runtimeMode: input.runtimeMode,
threadId: input.threadId,
cwd: input.cwd,
createdAt: now,
updatedAt: now,
@@ -50,36 +50,44 @@ class FakeCodexManager extends CodexAppServerManager {
public sendTurnImpl = vi.fn(
async (_input: CodexAppServerSendTurnInput): Promise<ProviderTurnStartResult> => ({
threadId: ProviderThreadId.makeUnsafe("thread-1"),
threadId: asThreadId("thread-1"),
turnId: asTurnId("turn-1"),
}),
);
public interruptTurnImpl = vi.fn(
async (_sessionId: ProviderSessionId, _turnId?: ProviderTurnId): Promise<void> => undefined,
async (_threadId: ThreadId, _turnId?: TurnId): Promise<void> => undefined,
);
public readThreadImpl = vi.fn(async (_sessionId: ProviderSessionId) => ({
threadId: ProviderThreadId.makeUnsafe("thread-1"),
public readThreadImpl = vi.fn(async (_threadId: ThreadId) => ({
threadId: asThreadId("thread-1"),
turns: [],
}));
public rollbackThreadImpl = vi.fn(async (_sessionId: ProviderSessionId, _numTurns: number) => ({
threadId: ProviderThreadId.makeUnsafe("thread-1"),
public rollbackThreadImpl = vi.fn(async (_threadId: ThreadId, _numTurns: number) => ({
threadId: asThreadId("thread-1"),
turns: [],
}));
public respondToRequestImpl = vi.fn(
async (
_sessionId: ProviderSessionId,
_threadId: ThreadId,
_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: ProviderSessionStartInput): Promise<ProviderSession> {
override startSession(input: CodexAppServerStartSessionInput): Promise<ProviderSession> {
return this.startSessionImpl(input);
}
@@ -87,33 +95,41 @@ class FakeCodexManager extends CodexAppServerManager {
return this.sendTurnImpl(input);
}
override interruptTurn(sessionId: ProviderSessionId, turnId?: ProviderTurnId): Promise<void> {
return this.interruptTurnImpl(sessionId, turnId);
override interruptTurn(threadId: ThreadId, turnId?: TurnId): Promise<void> {
return this.interruptTurnImpl(threadId, turnId);
}
override readThread(sessionId: ProviderSessionId) {
return this.readThreadImpl(sessionId);
override readThread(threadId: ThreadId) {
return this.readThreadImpl(threadId);
}
override rollbackThread(sessionId: ProviderSessionId, numTurns: number) {
return this.rollbackThreadImpl(sessionId, numTurns);
override rollbackThread(threadId: ThreadId, numTurns: number) {
return this.rollbackThreadImpl(threadId, numTurns);
}
override respondToRequest(
sessionId: ProviderSessionId,
threadId: ThreadId,
requestId: ApprovalRequestId,
decision: ProviderApprovalDecision,
): Promise<void> {
return this.respondToRequestImpl(sessionId, requestId, decision);
return this.respondToRequestImpl(threadId, requestId, decision);
}
override stopSession(_sessionId: ProviderSessionId): void {}
override respondToUserInput(
threadId: ThreadId,
requestId: ApprovalRequestId,
answers: ProviderUserInputAnswers,
): Promise<void> {
return this.respondToUserInputImpl(threadId, requestId, answers);
}
override stopSession(_threadId: ThreadId): void {}
override listSessions(): ProviderSession[] {
return [];
}
override hasSession(_sessionId: ProviderSessionId): boolean {
override hasSession(_threadId: ThreadId): boolean {
return false;
}
@@ -127,9 +143,8 @@ 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,
listSessionIds: () => Effect.succeed([]),
listThreadIds: () => Effect.succeed([]),
});
const validationManager = new FakeCodexManager();
@@ -142,24 +157,30 @@ const validationLayer = it.layer(
);
validationLayer("CodexAdapterLive validation", (it) => {
it.effect("returns validation error for non-codex provider on startSession", () =>
it.effect("maps codex model options before starting a session", () =>
Effect.gen(function* () {
validationManager.startSessionImpl.mockClear();
const adapter = yield* CodexAdapter;
const result = yield* adapter
.startSession({
provider: "claudeCode",
})
.pipe(Effect.result);
assertFailure(
result,
new ProviderAdapterValidationError({
provider: "codex",
operation: "startSession",
issue: "Expected provider 'codex' but received 'claudeCode'.",
}),
);
assert.equal(validationManager.startSessionImpl.mock.calls.length, 0);
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",
});
}),
);
});
@@ -182,7 +203,7 @@ sessionErrorLayer("CodexAdapterLive session errors", (it) => {
const adapter = yield* CodexAdapter;
const result = yield* adapter
.sendTurn({
sessionId: asSessionId("sess-missing"),
threadId: asThreadId("sess-missing"),
input: "hello",
attachments: [],
})
@@ -198,8 +219,38 @@ sessionErrorLayer("CodexAdapterLive session errors", (it) => {
return;
}
assert.equal(result.failure.provider, "codex");
assert.equal(result.failure.sessionId, "sess-missing");
assert.instanceOf(result.failure.cause, Error);
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",
});
}),
);
});
@@ -214,7 +265,7 @@ const lifecycleLayer = it.layer(
);
lifecycleLayer("CodexAdapterLive lifecycle", (it) => {
it.effect("maps completed agent message items to canonical message.completed events", () =>
it.effect("maps completed agent message items to canonical item.completed events", () =>
Effect.gen(function* () {
const adapter = yield* CodexAdapter;
const firstEventFiber = yield* Stream.runHead(adapter.streamEvents).pipe(Effect.forkChild);
@@ -223,10 +274,9 @@ 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: ProviderThreadId.makeUnsafe("thread-1"),
threadId: asThreadId("thread-1"),
turnId: asTurnId("turn-1"),
itemId: asItemId("msg_1"),
payload: {
@@ -244,12 +294,86 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => {
if (firstEvent._tag !== "Some") {
return;
}
assert.equal(firstEvent.value.type, "message.completed");
if (firstEvent.value.type !== "message.completed") {
assert.equal(firstEvent.value.type, "item.completed");
if (firstEvent.value.type !== "item.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");
}),
);
@@ -262,7 +386,7 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => {
id: asEventId("evt-session-closed"),
kind: "session",
provider: "codex",
sessionId: asSessionId("sess-1"),
threadId: asThreadId("thread-1"),
createdAt: new Date().toISOString(),
method: "session/closed",
message: "Session stopped",
@@ -279,12 +403,349 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => {
if (firstEvent.value.type !== "session.exited") {
return;
}
assert.equal(firstEvent.value.sessionId, "sess-1");
assert.equal(firstEvent.value.message, "Session stopped");
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("preserves file-read 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-file-read-request-resolved"),
kind: "notification",
provider: "codex",
threadId: asThreadId("thread-1"),
createdAt: new Date().toISOString(),
method: "serverRequest/resolved",
requestId: ApprovalRequestId.makeUnsafe("req-file-read-1"),
payload: {
request: {
method: "item/fileRead/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, "file_read_approval");
}),
);
it.effect("preserves explicit empty multi-select user-input answers", () =>
Effect.gen(function* () {
const adapter = yield* CodexAdapter;
const firstEventFiber = yield* Stream.runHead(adapter.streamEvents).pipe(Effect.forkChild);
const event: ProviderEvent = {
id: asEventId("evt-user-input-empty"),
kind: "notification",
provider: "codex",
threadId: asThreadId("thread-1"),
createdAt: new Date().toISOString(),
method: "item/tool/requestUserInput/answered",
payload: {
answers: {
scope: [],
},
},
};
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, "user-input.resolved");
if (firstEvent.value.type !== "user-input.resolved") {
return;
}
assert.deepEqual(firstEvent.value.payload.answers, {
scope: [],
});
}),
);
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");
}
}),
);
});
afterAll(() => {
assert.equal(lifecycleManager.stopAllImpl.mock.calls.length, 1);
if (lifecycleManager.stopAllImpl.mock.calls.length === 0) {
lifecycleManager.stopAll();
}
assert.ok(lifecycleManager.stopAllImpl.mock.calls.length >= 1);
});
File diff suppressed because it is too large. Load diff
@@ -12,10 +12,12 @@ 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(),
@@ -27,7 +29,10 @@ const fakeCodexAdapter: CodexAdapterShape = {
const layer = it.layer(
Layer.mergeAll(
Layer.provide(ProviderAdapterRegistryLive, Layer.succeed(CodexAdapter, fakeCodexAdapter)),
Layer.provide(
ProviderAdapterRegistryLive,
Layer.succeed(CodexAdapter, fakeCodexAdapter),
),
NodeServices.layer,
),
);
@@ -36,8 +41,8 @@ layer("ProviderAdapterRegistryLive", (it) => {
it.effect("resolves a registered provider adapter", () =>
Effect.gen(function* () {
const registry = yield* ProviderAdapterRegistry;
const adapter = yield* registry.getByProvider("codex");
assert.equal(adapter, fakeCodexAdapter);
const codex = yield* registry.getByProvider("codex");
assert.equal(codex, fakeCodexAdapter);
const providers = yield* registry.listProviders();
assert.deepEqual(providers, ["codex"]);
@@ -1,7 +1,7 @@
/**
* ProviderAdapterRegistryLive - In-memory provider adapter lookup layer.
*
* Binds provider kinds (codex/claudeCode/...) to concrete adapter services.
* Binds provider kinds (codex/cursor/...) to concrete adapter services.
* This layer only performs adapter lookup; it does not route session-scoped
* calls or own provider lifecycle workflows.
*
@@ -23,7 +23,10 @@ export interface ProviderAdapterRegistryLiveOptions {
const makeProviderAdapterRegistry = (options?: ProviderAdapterRegistryLiveOptions) =>
Effect.gen(function* () {
const adapters = options?.adapters !== undefined ? options.adapters : [yield* CodexAdapter];
const adapters =
options?.adapters !== undefined
? options.adapters
: [yield* CodexAdapter];
const byProvider = new Map(adapters.map((adapter) => [adapter.provider, adapter]));
const getByProvider: ProviderAdapterRegistryShape["getByProvider"] = (provider) => {
@@ -12,11 +12,10 @@ 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";
@@ -26,9 +25,8 @@ import * as SqlClient from "effect/unstable/sql/SqlClient";
import {
ProviderAdapterSessionNotFoundError,
ProviderSessionNotFoundError,
ProviderValidationError,
ProviderUnsupportedError,
ProviderValidationError,
type ProviderAdapterError,
} from "../Errors.ts";
import type { ProviderAdapterShape } from "../Services/ProviderAdapter.ts";
@@ -44,34 +42,44 @@ import {
makeSqlitePersistenceLive,
SqlitePersistenceMemory,
} from "../../persistence/Layers/Sqlite.ts";
import { AnalyticsService } from "../../telemetry/Services/AnalyticsService.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);
function makeFakeCodexAdapter() {
const sessions = new Map<ProviderSessionId, ProviderSession>();
type LegacyProviderRuntimeEvent = {
readonly type: string;
readonly eventId: EventId;
readonly provider: "codex";
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>();
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 = {
sessionId: ProviderSessionId.makeUnsafe(`sess-${next}`),
provider: "codex",
provider,
status: "ready",
threadId: input.resumeThreadId ?? ProviderThreadId.makeUnsafe(`thread-${next}`),
runtimeMode: input.runtimeMode,
threadId: input.threadId,
resumeCursor: input.resumeCursor ?? { opaque: `cursor-${String(input.threadId)}` },
cwd: input.cwd ?? process.cwd(),
createdAt: now,
updatedAt: now,
};
nextSession += 1;
sessions.set(session.sessionId, session);
sessions.set(session.threadId, session);
return session;
}),
);
@@ -80,39 +88,47 @@ function makeFakeCodexAdapter() {
(
input: ProviderSendTurnInput,
): Effect.Effect<ProviderTurnStartResult, ProviderAdapterError> => {
if (!sessions.has(input.sessionId)) {
if (!sessions.has(input.threadId)) {
return Effect.fail(
new ProviderAdapterSessionNotFoundError({
provider: "codex",
sessionId: input.sessionId,
provider,
threadId: input.threadId,
}),
);
}
return Effect.succeed({
threadId: ProviderThreadId.makeUnsafe("thread-1"),
turnId: ProviderTurnId.makeUnsafe("turn-1"),
threadId: input.threadId,
turnId: TurnId.makeUnsafe(`turn-${String(input.threadId)}`),
});
},
);
const interruptTurn = vi.fn(
(_sessionId: string, _turnId?: string): Effect.Effect<void, ProviderAdapterError> =>
(_threadId: ThreadId, _turnId?: TurnId): Effect.Effect<void, ProviderAdapterError> =>
Effect.void,
);
const respondToRequest = vi.fn(
(
_sessionId: string,
_threadId: ThreadId,
_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(
(sessionId: string): Effect.Effect<void, ProviderAdapterError> =>
(threadId: ThreadId): Effect.Effect<void, ProviderAdapterError> =>
Effect.sync(() => {
sessions.delete(ProviderSessionId.makeUnsafe(sessionId));
sessions.delete(threadId);
}),
);
@@ -122,32 +138,31 @@ function makeFakeCodexAdapter() {
);
const hasSession = vi.fn(
(sessionId: string): Effect.Effect<boolean> =>
Effect.succeed(sessions.has(ProviderSessionId.makeUnsafe(sessionId))),
(threadId: ThreadId): Effect.Effect<boolean> => Effect.succeed(sessions.has(threadId)),
);
const readThread = vi.fn(
(
_sessionId: ProviderSessionId,
threadId: ThreadId,
): Effect.Effect<
{
threadId: ProviderThreadId;
turns: ReadonlyArray<{ id: ProviderTurnId; items: readonly [] }>;
threadId: ThreadId;
turns: ReadonlyArray<{ id: TurnId; items: readonly [] }>;
},
ProviderAdapterError
> =>
Effect.succeed({
threadId: ProviderThreadId.makeUnsafe("thread-1"),
threadId,
turns: [{ id: asTurnId("turn-1"), items: [] }],
}),
);
const rollbackThread = vi.fn(
(
_sessionId: ProviderSessionId,
threadId: ThreadId,
_numTurns: number,
): Effect.Effect<{ threadId: ProviderThreadId; turns: readonly [] }, ProviderAdapterError> =>
Effect.succeed({ threadId: ProviderThreadId.makeUnsafe("thread-1"), turns: [] }),
): Effect.Effect<{ threadId: ThreadId; turns: readonly [] }, ProviderAdapterError> =>
Effect.succeed({ threadId, turns: [] }),
);
const stopAll = vi.fn(
@@ -158,11 +173,15 @@ function makeFakeCodexAdapter() {
);
const adapter: ProviderAdapterShape<ProviderAdapterError> = {
provider: "codex",
provider,
capabilities: {
sessionModelSwitch: "in-session",
},
startSession,
sendTurn,
interruptTurn,
respondToRequest,
respondToUserInput,
stopSession,
listSessions,
hasSession,
@@ -172,8 +191,8 @@ function makeFakeCodexAdapter() {
streamEvents: Stream.fromPubSub(runtimeEventPubSub),
};
const emit = (event: ProviderRuntimeEvent): void => {
Effect.runSync(PubSub.publish(runtimeEventPubSub, event));
const emit = (event: LegacyProviderRuntimeEvent): void => {
Effect.runSync(PubSub.publish(runtimeEventPubSub, event as unknown as ProviderRuntimeEvent));
};
return {
@@ -183,6 +202,7 @@ function makeFakeCodexAdapter() {
sendTurn,
interruptTurn,
respondToRequest,
respondToUserInput,
stopSession,
listSessions,
hasSession,
@@ -216,8 +236,10 @@ function makeProviderServiceLayer() {
makeProviderServiceLive().pipe(
Layer.provide(providerAdapterLayer),
Layer.provide(directoryLayer),
Layer.provideMerge(AnalyticsService.layerTest),
),
directoryLayer,
runtimeRepositoryLayer,
NodeServices.layer,
),
@@ -253,7 +275,6 @@ 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"),
});
@@ -262,6 +283,7 @@ it.effect("ProviderServiceLive keeps persisted resumable sessions on startup", (
const providerLayer = makeProviderServiceLive().pipe(
Layer.provide(Layer.succeed(ProviderAdapterRegistry, registry)),
Layer.provide(directoryLayer),
Layer.provide(AnalyticsService.layerTest),
);
yield* Effect.gen(function* () {
@@ -270,13 +292,13 @@ it.effect("ProviderServiceLive keeps persisted resumable sessions on startup", (
const persistedProvider = yield* Effect.gen(function* () {
const directory = yield* ProviderSessionDirectory;
return yield* directory.getProvider(asSessionId("sess-stale"));
return yield* directory.getProvider(asThreadId("thread-stale"));
}).pipe(Effect.provide(directoryLayer));
assert.equal(persistedProvider, "codex");
const runtime = yield* Effect.gen(function* () {
const repository = yield* ProviderSessionRuntimeRepository;
return yield* repository.getBySessionId({ providerSessionId: asSessionId("sess-stale") });
return yield* repository.getByThreadId({ threadId: asThreadId("thread-stale") });
}).pipe(Effect.provide(runtimeRepositoryLayer));
assert.equal(Option.isSome(runtime), true);
@@ -320,31 +342,28 @@ it.effect(
const firstProviderLayer = makeProviderServiceLive().pipe(
Layer.provide(Layer.succeed(ProviderAdapterRegistry, firstRegistry)),
Layer.provide(firstDirectoryLayer),
Layer.provide(AnalyticsService.layerTest),
);
const startedSession = yield* Effect.gen(function* () {
const provider = yield* ProviderService;
return yield* provider.startSession(asThreadId("thread-1"), {
const threadId = asThreadId("thread-1");
return yield* provider.startSession(threadId, {
provider: "codex",
cwd: "/tmp/project",
runtimeMode: "full-access",
threadId,
});
}).pipe(Effect.provide(firstProviderLayer));
yield* Effect.gen(function* () {
const provider = yield* ProviderService;
yield* provider.stopAll();
}).pipe(Effect.provide(firstProviderLayer));
const persistedAfterStopAll = yield* Effect.gen(function* () {
const repository = yield* ProviderSessionRuntimeRepository;
return yield* repository.getBySessionId({
providerSessionId: startedSession.sessionId,
});
return yield* repository.getByThreadId({ threadId: startedSession.threadId });
}).pipe(Effect.provide(runtimeRepositoryLayer));
assert.equal(Option.isSome(persistedAfterStopAll), true);
if (Option.isSome(persistedAfterStopAll)) {
assert.equal(persistedAfterStopAll.value.status, "stopped");
assert.equal(persistedAfterStopAll.value.resumeCursor, null);
assert.deepEqual(persistedAfterStopAll.value.resumeCursor, startedSession.resumeCursor);
}
const secondCodex = makeFakeCodexAdapter();
@@ -361,6 +380,7 @@ it.effect(
const secondProviderLayer = makeProviderServiceLive().pipe(
Layer.provide(Layer.succeed(ProviderAdapterRegistry, secondRegistry)),
Layer.provide(secondDirectoryLayer),
Layer.provide(AnalyticsService.layerTest),
);
secondCodex.startSession.mockClear();
@@ -369,20 +389,26 @@ it.effect(
yield* Effect.gen(function* () {
const provider = yield* ProviderService;
yield* provider.rollbackConversation({
sessionId: startedSession.sessionId,
threadId: startedSession.threadId,
numTurns: 1,
});
}).pipe(Effect.provide(secondProviderLayer));
assert.deepEqual(secondCodex.startSession.mock.calls, [
[
{
provider: "codex",
cwd: "/tmp/project",
resumeThreadId: startedSession.threadId,
},
],
]);
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.equal(secondCodex.rollbackThread.mock.calls.length, 1);
const rollbackCall = secondCodex.rollbackThread.mock.calls[0];
assert.equal(typeof rollbackCall?.[0], "string");
@@ -399,7 +425,9 @@ 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");
@@ -407,40 +435,60 @@ routing.layer("ProviderServiceLive routing", (it) => {
assert.equal(sessions.length, 1);
yield* provider.sendTurn({
sessionId: session.sessionId,
threadId: session.threadId,
input: "hello",
attachments: [],
});
assert.equal(routing.codex.sendTurn.mock.calls.length, 1);
yield* provider.interruptTurn({ sessionId: session.sessionId });
assert.deepEqual(routing.codex.interruptTurn.mock.calls, [[session.sessionId, undefined]]);
yield* provider.interruptTurn({ threadId: session.threadId });
assert.deepEqual(routing.codex.interruptTurn.mock.calls, [[session.threadId, undefined]]);
yield* provider.respondToRequest({
sessionId: session.sessionId,
threadId: session.threadId,
requestId: asRequestId("req-1"),
decision: "accept",
});
assert.deepEqual(routing.codex.respondToRequest.mock.calls, [
[session.sessionId, asRequestId("req-1"), "accept"],
[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",
},
],
]);
yield* provider.rollbackConversation({
sessionId: session.sessionId,
threadId: session.threadId,
numTurns: 0,
});
yield* provider.stopSession({ sessionId: session.sessionId });
yield* provider.stopSession({ threadId: session.threadId });
const sendAfterStop = yield* Effect.result(
provider.sendTurn({
sessionId: session.sessionId,
threadId: session.threadId,
input: "after-stop",
attachments: [],
}),
);
assertFailure(
sendAfterStop,
new ProviderSessionNotFoundError({ sessionId: session.sessionId }),
new ProviderValidationError({
operation: "ProviderService.sendTurn",
issue: `Cannot route thread '${session.threadId}' because no persisted provider binding exists.`,
}),
);
}),
);
@@ -451,26 +499,34 @@ routing.layer("ProviderServiceLive routing", (it) => {
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.sessionId);
yield* routing.codex.stopSession(initial.threadId);
routing.codex.startSession.mockClear();
routing.codex.rollbackThread.mockClear();
yield* provider.rollbackConversation({
sessionId: initial.sessionId,
threadId: initial.threadId,
numTurns: 1,
});
assert.deepEqual(routing.codex.startSession.mock.calls, [
[
{
provider: "codex",
cwd: "/tmp/project",
resumeThreadId: initial.threadId,
},
],
]);
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.equal(routing.codex.rollbackThread.mock.calls.length, 1);
const rollbackCall = routing.codex.rollbackThread.mock.calls[0];
assert.equal(rollbackCall?.[1], 1);
@@ -483,44 +539,56 @@ 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();
yield* routing.codex.stopAll();
routing.codex.startSession.mockClear();
routing.codex.sendTurn.mockClear();
yield* provider.sendTurn({
sessionId: initial.sessionId,
threadId: initial.threadId,
input: "resume",
attachments: [],
});
assert.deepEqual(routing.codex.startSession.mock.calls, [
[
{
provider: "codex",
cwd: "/tmp/project-send-turn",
resumeThreadId: initial.threadId,
},
],
]);
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.equal(routing.codex.sendTurn.mock.calls.length, 1);
}),
);
it.effect("stops all sessions and clears adapter runtime", () =>
it.effect("lists no sessions after adapter runtime clears", () =>
Effect.gen(function* () {
const provider = yield* ProviderService;
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();
yield* routing.codex.stopAll();
const remaining = yield* provider.listSessions();
assert.equal(remaining.length, 0);
@@ -534,20 +602,22 @@ 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({
sessionId: session.sessionId,
threadId: session.threadId,
input: "hello",
attachments: [],
});
const runningRuntime = yield* runtimeRepository.getBySessionId({
providerSessionId: session.sessionId,
const runningRuntime = yield* runtimeRepository.getByThreadId({
threadId: session.threadId,
});
assert.equal(Option.isSome(runningRuntime), true);
if (Option.isSome(runningRuntime)) {
assert.equal(runningRuntime.value.status, "running");
assert.equal(runningRuntime.value.resumeCursor, null);
assert.deepEqual(runningRuntime.value.resumeCursor, session.resumeCursor);
const payload = runningRuntime.value.runtimePayload;
assert.equal(payload !== null && typeof payload === "object", true);
if (payload !== null && typeof payload === "object" && !Array.isArray(payload)) {
@@ -560,20 +630,12 @@ routing.layer("ProviderServiceLive routing", (it) => {
};
assert.equal(runtimePayload.cwd, process.cwd());
assert.equal(runtimePayload.model, null);
assert.equal(runtimePayload.activeTurnId, "turn-1");
assert.equal(runtimePayload.activeTurnId, `turn-${String(session.threadId)}`);
assert.equal(runtimePayload.lastError, null);
assert.equal(runtimePayload.lastRuntimeEvent, "provider.sendTurn");
}
}
yield* provider.stopAll();
const stoppedRuntime = yield* runtimeRepository.getBySessionId({
providerSessionId: session.sessionId,
});
assert.equal(Option.isSome(stoppedRuntime), true);
if (Option.isSome(stoppedRuntime)) {
assert.equal(stoppedRuntime.value.status, "stopped");
}
}),
);
});
@@ -585,6 +647,8 @@ 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>>([]);
@@ -593,13 +657,12 @@ fanout.layer("ProviderServiceLive fanout", (it) => {
).pipe(Effect.forkChild);
yield* sleep(20);
const completedEvent: ProviderRuntimeEvent = {
const completedEvent: LegacyProviderRuntimeEvent = {
type: "turn.completed",
eventId: asEventId("evt-1"),
provider: "codex",
sessionId: session.sessionId,
createdAt: new Date().toISOString(),
threadId: asProviderThreadId("thread-1"),
threadId: session.threadId,
turnId: asTurnId("turn-1"),
status: "completed",
};
@@ -617,11 +680,68 @@ 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[] = [];
@@ -640,14 +760,13 @@ fanout.layer("ProviderServiceLive fanout", (it) => {
);
yield* sleep(20);
const events: ReadonlyArray<ProviderRuntimeEvent> = [
const events: ReadonlyArray<LegacyProviderRuntimeEvent> = [
{
type: "tool.completed",
eventId: asEventId("evt-ordered-1"),
provider: "codex",
sessionId: session.sessionId,
createdAt: new Date().toISOString(),
threadId: asProviderThreadId("thread-1"),
threadId: session.threadId,
turnId: asTurnId("turn-1"),
toolKind: "command",
title: "Command run",
@@ -657,9 +776,8 @@ fanout.layer("ProviderServiceLive fanout", (it) => {
type: "message.delta",
eventId: asEventId("evt-ordered-2"),
provider: "codex",
sessionId: session.sessionId,
createdAt: new Date().toISOString(),
threadId: asProviderThreadId("thread-1"),
threadId: session.threadId,
turnId: asTurnId("turn-1"),
delta: "hello",
},
@@ -667,9 +785,8 @@ fanout.layer("ProviderServiceLive fanout", (it) => {
type: "turn.completed",
eventId: asEventId("evt-ordered-3"),
provider: "codex",
sessionId: session.sessionId,
createdAt: new Date().toISOString(),
threadId: asProviderThreadId("thread-1"),
threadId: session.threadId,
turnId: asTurnId("turn-1"),
status: "completed",
},
@@ -698,7 +815,9 @@ 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),
);
@@ -715,17 +834,19 @@ validation.layer("ProviderServiceLive validation", (it) => {
}),
);
it.effect("fails startSession when adapter returns no threadId", () =>
it.effect("accepts startSession when adapter has not emitted provider thread id yet", () =>
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,
@@ -733,20 +854,22 @@ validation.layer("ProviderServiceLive validation", (it) => {
}),
);
const failure = yield* Effect.result(
provider.startSession(asThreadId("thread-missing"), {
provider: "codex",
cwd: "/tmp/project",
}),
);
const session = yield* provider.startSession(asThreadId("thread-missing"), {
provider: "codex",
threadId: asThreadId("thread-missing"),
cwd: "/tmp/project",
runtimeMode: "full-access",
});
assertFailure(
failure,
new ProviderValidationError({
operation: "ProviderService.startSession",
issue: "Provider 'codex' returned a session without threadId.",
}),
);
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);
}
}),
);
});
+166 -248
View File
@@ -11,26 +11,27 @@
*/
import {
NonNegativeInt,
ProviderSessionId,
ThreadId,
ProviderInterruptTurnInput,
ProviderRespondToRequestInput,
ProviderRespondToUserInputInput,
ProviderSendTurnInput,
ProviderSessionStartInput,
ProviderStopSessionInput,
type ProviderRuntimeEvent,
type ProviderSession,
} from "@t3tools/contracts";
import { Effect, Layer, Option, PubSub, Queue, Ref, Schema, SchemaIssue, Stream } from "effect";
import { Effect, Layer, Option, PubSub, Queue, Schema, SchemaIssue, Stream } from "effect";
import { ProviderSessionNotFoundError, ProviderValidationError } from "../Errors.ts";
import { ProviderValidationError } from "../Errors.ts";
import { ProviderAdapterRegistry } from "../Services/ProviderAdapterRegistry.ts";
import { ProviderService, type ProviderServiceShape } from "../Services/ProviderService.ts";
import {
ProviderSessionDirectory,
type ProviderSessionBinding,
type ProviderRuntimeBinding,
} from "../Services/ProviderSessionDirectory.ts";
import { type EventNdjsonLogger, makeEventNdjsonLogger } from "./EventNdjsonLogger.ts";
import { AnalyticsService } from "../../telemetry/Services/AnalyticsService.ts";
export interface ProviderServiceLiveOptions {
readonly canonicalEventLogPath?: string;
@@ -38,7 +39,7 @@ export interface ProviderServiceLiveOptions {
}
const ProviderRollbackConversationInput = Schema.Struct({
sessionId: ProviderSessionId,
threadId: ThreadId,
numTurns: NonNegativeInt,
});
@@ -95,7 +96,7 @@ function toRuntimePayloadFromSession(session: ProviderSession): Record<string, u
}
function readPersistedCwd(
runtimePayload: ProviderSessionBinding["runtimePayload"],
runtimePayload: ProviderRuntimeBinding["runtimePayload"],
): string | undefined {
if (!runtimePayload || typeof runtimePayload !== "object" || Array.isArray(runtimePayload)) {
return undefined;
@@ -108,6 +109,7 @@ function readPersistedCwd(
const makeProviderService = (options?: ProviderServiceLiveOptions) =>
Effect.gen(function* () {
const analytics = yield* Effect.service(AnalyticsService);
const canonicalEventLogger =
options?.canonicalEventLogger ??
(options?.canonicalEventLogPath !== undefined
@@ -120,43 +122,12 @@ 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> =>
canonicalizeRuntimeEventSession(event).pipe(
Effect.succeed(event).pipe(
Effect.tap((canonicalEvent) =>
canonicalEventLogger
? 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),
)
? canonicalEventLogger.write(canonicalEvent, null)
: Effect.void,
),
Effect.flatMap((canonicalEvent) => PubSub.publish(runtimeEventPubSub, canonicalEvent)),
@@ -165,64 +136,15 @@ const makeProviderService = (options?: ProviderServiceLiveOptions) =>
const upsertSessionBinding = (
session: ProviderSession,
operation: string,
threadId: ThreadId,
) =>
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;
directory.upsert({
threadId,
provider: session.provider,
runtimeMode: session.runtimeMode,
status: toRuntimeStatus(session),
...(session.resumeCursor !== undefined ? { resumeCursor: session.resumeCursor } : {}),
runtimePayload: toRuntimePayloadFromSession(session),
});
const providers = yield* registry.listProviders();
@@ -245,163 +167,87 @@ const makeProviderService = (options?: ProviderServiceLiveOptions) =>
).pipe(Effect.asVoid);
const recoverSessionForThread = (input: {
readonly staleSessionId: ProviderSessionId;
readonly binding: ProviderSessionBinding & { readonly threadId: ThreadId };
readonly binding: ProviderRuntimeBinding;
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 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);
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);
yield* analytics.record("provider.session.recovered", {
provider: existing.provider,
strategy: "adopt-existing",
hasResumeCursor: existing.resumeCursor !== undefined,
});
return { adapter, session: existing } as const;
}
return {
adapter,
sessionId: existing.sessionId,
} as const;
}
if (!resumeThreadId && !hasResumeCursor) {
if (!hasResumeCursor) {
return yield* toValidationError(
input.operation,
`Cannot recover stale session '${input.staleSessionId}' because no provider resume state is persisted.`,
`Cannot recover thread '${input.binding.threadId}' 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 stale session '${input.staleSessionId}'. Expected '${adapter.provider}', received '${resumed.provider}'.`,
`Adapter/provider mismatch while recovering thread '${input.binding.threadId}'. Expected '${adapter.provider}', received '${resumed.provider}'.`,
);
}
const resumedProviderThreadId = yield* upsertSessionBinding(
resumed,
`${input.operation}:upsertRecoveredSession`,
input.binding.threadId,
);
yield* directory.upsert({
sessionId: input.staleSessionId,
yield* upsertSessionBinding(resumed, input.binding.threadId);
yield* analytics.record("provider.session.recovered", {
provider: resumed.provider,
threadId: input.binding.threadId,
providerThreadId: resumedProviderThreadId,
...(resumed.resumeCursor !== undefined ? { resumeCursor: resumed.resumeCursor } : {}),
strategy: "resume-thread",
hasResumeCursor: resumed.resumeCursor !== undefined,
});
if (resumed.sessionId !== input.staleSessionId) {
yield* setAlias(input.staleSessionId, resumed.sessionId);
} else {
yield* clearAliasKey(input.staleSessionId);
}
return {
adapter,
sessionId: resumed.sessionId,
} as const;
return { adapter, session: resumed } as const;
});
const resolveRoutableSession = (input: {
readonly sessionId: ProviderSessionId;
readonly threadId: ThreadId;
readonly operation: string;
readonly allowRecovery: boolean;
}) =>
Effect.gen(function* () {
const bindingOption = yield* directory.getBinding(input.sessionId);
const bindingOption = yield* directory.getBinding(input.threadId);
const binding = Option.getOrUndefined(bindingOption);
if (!binding) {
return yield* new ProviderSessionNotFoundError({
sessionId: input.sessionId,
});
}
if (!binding.threadId) {
return yield* toValidationError(
input.operation,
`Cannot route session '${input.sessionId}' because no orchestration thread id is persisted.`,
`Cannot route thread '${input.threadId}' because no persisted provider binding exists.`,
);
}
const bindingWithThreadId: ProviderSessionBinding & {
readonly threadId: ThreadId;
} = {
...binding,
threadId: binding.threadId,
};
const adapter = yield* registry.getByProvider(binding.provider);
const hasRequestedSession = yield* adapter.hasSession(input.sessionId);
const hasRequestedSession = yield* adapter.hasSession(input.threadId);
if (hasRequestedSession) {
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);
return { adapter, threadId: input.threadId, isActive: true } as const;
}
if (!input.allowRecovery) {
return {
adapter,
sessionId: input.sessionId,
isActive: false,
} as const;
return { adapter, threadId: input.threadId, isActive: false } 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 recovered = yield* recoverSessionForThread({ binding, operation: input.operation });
return { adapter: recovered.adapter, threadId: input.threadId, isActive: true } as const;
});
const startSession: ProviderServiceShape["startSession"] = (threadId, rawInput) =>
@@ -414,9 +260,8 @@ 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);
@@ -428,7 +273,14 @@ const makeProviderService = (options?: ProviderServiceLiveOptions) =>
);
}
yield* upsertSessionBinding(session, "ProviderService.startSession", threadId);
yield* upsertSessionBinding(session, threadId);
yield* analytics.record("provider.session.started", {
provider: session.provider,
runtimeMode: input.runtimeMode,
hasResumeCursor: session.resumeCursor !== undefined,
hasCwd: typeof input.cwd === "string" && input.cwd.trim().length > 0,
hasModel: typeof input.model === "string" && input.model.trim().length > 0,
});
return session;
});
@@ -452,28 +304,14 @@ const makeProviderService = (options?: ProviderServiceLiveOptions) =>
);
}
const routed = yield* resolveRoutableSession({
sessionId: input.sessionId,
threadId: input.threadId,
operation: "ProviderService.sendTurn",
allowRecovery: true,
});
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}'.`,
);
}
const turn = yield* routed.adapter.sendTurn(input);
yield* directory.upsert({
sessionId: input.sessionId,
threadId: input.threadId,
provider: routed.adapter.provider,
threadId,
providerThreadId: turn.threadId,
status: "running",
...(turn.resumeCursor !== undefined ? { resumeCursor: turn.resumeCursor } : {}),
runtimePayload: {
@@ -482,6 +320,13 @@ const makeProviderService = (options?: ProviderServiceLiveOptions) =>
lastRuntimeEventAt: new Date().toISOString(),
},
});
yield* analytics.record("provider.turn.sent", {
provider: routed.adapter.provider,
model: input.model,
interactionMode: input.interactionMode,
attachmentCount: input.attachments.length,
hasInput: typeof input.input === "string" && input.input.trim().length > 0,
});
return turn;
});
@@ -493,11 +338,14 @@ const makeProviderService = (options?: ProviderServiceLiveOptions) =>
payload: rawInput,
});
const routed = yield* resolveRoutableSession({
sessionId: input.sessionId,
threadId: input.threadId,
operation: "ProviderService.interruptTurn",
allowRecovery: true,
});
yield* routed.adapter.interruptTurn(routed.sessionId, input.turnId);
yield* routed.adapter.interruptTurn(routed.threadId, input.turnId);
yield* analytics.record("provider.turn.interrupted", {
provider: routed.adapter.provider,
});
});
const respondToRequest: ProviderServiceShape["respondToRequest"] = (rawInput) =>
@@ -508,11 +356,30 @@ const makeProviderService = (options?: ProviderServiceLiveOptions) =>
payload: rawInput,
});
const routed = yield* resolveRoutableSession({
sessionId: input.sessionId,
threadId: input.threadId,
operation: "ProviderService.respondToRequest",
allowRecovery: true,
});
yield* routed.adapter.respondToRequest(routed.sessionId, input.requestId, input.decision);
yield* routed.adapter.respondToRequest(routed.threadId, input.requestId, input.decision);
yield* analytics.record("provider.request.responded", {
provider: routed.adapter.provider,
decision: 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);
});
const stopSession: ProviderServiceShape["stopSession"] = (rawInput) =>
@@ -523,25 +390,64 @@ const makeProviderService = (options?: ProviderServiceLiveOptions) =>
payload: rawInput,
});
const routed = yield* resolveRoutableSession({
sessionId: input.sessionId,
threadId: input.threadId,
operation: "ProviderService.stopSession",
allowRecovery: false,
});
if (routed.isActive) {
yield* routed.adapter.stopSession(routed.sessionId);
yield* routed.adapter.stopSession(routed.threadId);
}
if (routed.sessionId !== input.sessionId) {
yield* directory.remove(routed.sessionId);
yield* clearAliasesReferencing(routed.sessionId);
}
yield* directory.remove(input.sessionId);
yield* clearAliasesReferencing(input.sessionId);
yield* directory.remove(input.threadId);
yield* analytics.record("provider.session.stopped", {
provider: routed.adapter.provider,
});
});
const listSessions: ProviderServiceShape["listSessions"] = () =>
Effect.forEach(adapters, (adapter) => adapter.listSessions()).pipe(
Effect.map((sessionsByProvider) => sessionsByProvider.flatMap((sessions) => sessions)),
);
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));
const rollbackConversation: ProviderServiceShape["rollbackConversation"] = (rawInput) =>
Effect.gen(function* () {
@@ -554,22 +460,26 @@ const makeProviderService = (options?: ProviderServiceLiveOptions) =>
return;
}
const routed = yield* resolveRoutableSession({
sessionId: input.sessionId,
threadId: input.threadId,
operation: "ProviderService.rollbackConversation",
allowRecovery: true,
});
yield* routed.adapter.rollbackThread(routed.sessionId, input.numTurns);
yield* routed.adapter.rollbackThread(routed.threadId, input.numTurns);
yield* analytics.record("provider.conversation.rolled_back", {
provider: routed.adapter.provider,
turns: input.numTurns,
});
});
const stopAll: ProviderServiceShape["stopAll"] = () =>
const runStopAll = () =>
Effect.gen(function* () {
const sessionIds = yield* directory.listSessionIds();
const threadIds = yield* directory.listThreadIds();
yield* Effect.forEach(adapters, (adapter) => adapter.stopAll()).pipe(Effect.asVoid);
yield* Effect.forEach(sessionIds, (sessionId) =>
directory.getProvider(sessionId).pipe(
yield* Effect.forEach(threadIds, (threadId) =>
directory.getProvider(threadId).pipe(
Effect.flatMap((provider) =>
directory.upsert({
sessionId,
threadId,
provider,
status: "stopped",
runtimePayload: {
@@ -581,20 +491,28 @@ 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());
yield* analytics.record("provider.sessions.stopped_all", {
sessionCount: threadIds.length,
});
yield* analytics.flush;
});
yield* Effect.addFinalizer(() =>
Effect.catch(runStopAll(), (cause) =>
Effect.logWarning("failed to stop provider service", { cause }),
),
);
return {
startSession,
sendTurn,
interruptTurn,
respondToRequest,
respondToUserInput,
stopSession,
listSessions,
getCapabilities,
rollbackConversation,
stopAll,
streamEvents: Stream.fromPubSub(runtimeEventPubSub),
} satisfies ProviderServiceShape;
});
@@ -3,7 +3,7 @@ import os from "node:os";
import path from "node:path";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { ProviderSessionId, ProviderThreadId, ThreadId } from "@t3tools/contracts";
import { 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 { ProviderSessionNotFoundError, ProviderValidationError } from "../Errors.ts";
import { ProviderSessionDirectoryPersistenceError } from "../Errors.ts";
import { ProviderSessionDirectory } from "../Services/ProviderSessionDirectory.ts";
import { ProviderSessionDirectoryLive } from "./ProviderSessionDirectory.ts";
@@ -31,74 +31,59 @@ function makeDirectoryLayer<E, R>(persistenceLayer: Layer.Layer<SqlClient.SqlCli
}
it.layer(makeDirectoryLayer(SqlitePersistenceMemory))("ProviderSessionDirectoryLive", (it) => {
it("upserts, reads, and removes session bindings", () =>
it("upserts, reads, and removes thread 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(sessionId);
const provider = yield* directory.getProvider(initialThreadId);
assert.equal(provider, "codex");
const resolvedThreadId = yield* directory.getThreadId(sessionId);
assertSome(resolvedThreadId, initialThreadId);
const resolvedBinding = yield* directory.getBinding(initialThreadId);
assertSome(resolvedBinding, {
threadId: initialThreadId,
provider: "codex",
});
if (Option.isSome(resolvedBinding)) {
assert.equal(resolvedBinding.value.threadId, initialThreadId);
}
const nextThreadId = ThreadId.makeUnsafe("thread-2");
yield* directory.upsert({
sessionId: sessionId,
provider: "codex",
threadId: nextThreadId,
});
const updatedThreadId = yield* directory.getThreadId(sessionId);
assertSome(updatedThreadId, nextThreadId);
const updatedBinding = yield* directory.getBinding(sessionId);
const updatedBinding = yield* directory.getBinding(nextThreadId);
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.getBySessionId({
providerSessionId: sessionId,
});
const runtime = yield* runtimeRepository.getByThreadId({ threadId: nextThreadId });
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.adapterKey, "codex");
assert.equal(runtime.value.providerName, "codex");
}
const sessionIds = yield* directory.listSessionIds();
assert.deepEqual(sessionIds, [sessionId]);
const threadIds = yield* directory.listThreadIds();
assert.deepEqual(threadIds, [nextThreadId]);
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",
}),
);
yield* directory.remove(nextThreadId);
const missingProvider = yield* directory.getProvider(nextThreadId).pipe(Effect.result);
assertFailure(
result,
new ProviderValidationError({
operation: "ProviderSessionDirectory.upsert",
issue: "threadId must be a non-empty string.",
missingProvider,
new ProviderSessionDirectoryPersistenceError({
operation: "ProviderSessionDirectory.getProvider",
detail: `No persisted provider binding found for thread '${nextThreadId}'.`,
}),
);
}));
@@ -108,18 +93,14 @@ 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: {
resumeThreadId: "provider-thread-runtime",
threadId: "provider-thread-runtime",
},
runtimePayload: {
cwd: "/tmp/project",
@@ -128,24 +109,21 @@ it.layer(makeDirectoryLayer(SqlitePersistenceMemory))("ProviderSessionDirectoryL
});
yield* directory.upsert({
sessionId,
provider: "codex",
threadId,
status: "running",
runtimePayload: {
activeTurnId: "turn-1",
},
});
const runtime = yield* runtimeRepository.getBySessionId({
providerSessionId: sessionId,
});
const runtime = yield* runtimeRepository.getByThreadId({ threadId });
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, {
resumeThreadId: providerThreadId,
threadId: "provider-thread-runtime",
});
assert.deepEqual(runtime.value.runtimePayload, {
cwd: "/tmp/project",
@@ -155,36 +133,33 @@ it.layer(makeDirectoryLayer(SqlitePersistenceMemory))("ProviderSessionDirectoryL
}
}));
it("clears providerThreadId when explicitly set to null", () =>
it("resets adapterKey to the new provider when provider changes without an explicit adapter key", () =>
Effect.gen(function* () {
const directory = yield* ProviderSessionDirectory;
const runtimeRepository = yield* ProviderSessionRuntimeRepository;
const threadId = ThreadId.makeUnsafe("thread-provider-change");
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* runtimeRepository.upsert({
threadId,
providerName: "cursor",
adapterKey: "cursor",
runtimeMode: "full-access",
status: "running",
lastSeenAt: new Date().toISOString(),
resumeCursor: null,
runtimePayload: null,
});
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,
});
const runtime = yield* runtimeRepository.getByThreadId({ threadId });
assert.equal(Option.isSome(runtime), true);
if (Option.isSome(runtime)) {
assert.equal(runtime.value.providerThreadId, null);
assert.equal(runtime.value.adapterKey, "custom-adapter");
assert.equal(runtime.value.providerName, "codex");
assert.equal(runtime.value.adapterKey, "codex");
}
}));
@@ -194,13 +169,11 @@ it.layer(makeDirectoryLayer(SqlitePersistenceMemory))("ProviderSessionDirectoryL
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,
});
@@ -209,11 +182,17 @@ it.layer(makeDirectoryLayer(SqlitePersistenceMemory))("ProviderSessionDirectoryL
yield* Effect.gen(function* () {
const directory = yield* ProviderSessionDirectory;
const sql = yield* SqlClient.SqlClient;
const provider = yield* directory.getProvider(sessionId);
const provider = yield* directory.getProvider(threadId);
assert.equal(provider, "codex");
const resolvedThreadId = yield* directory.getThreadId(sessionId);
assertSome(resolvedThreadId, threadId);
const resolvedBinding = yield* directory.getBinding(threadId);
assertSome(resolvedBinding, {
threadId,
provider: "codex",
});
if (Option.isSome(resolvedBinding)) {
assert.equal(resolvedBinding.value.threadId, threadId);
}
const legacyTableRows = yield* sql<{ readonly name: string }>`
SELECT name
@@ -1,15 +1,14 @@
import { ProviderSessionId, type ProviderKind } from "@t3tools/contracts";
import { type ProviderKind, type ThreadId } 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 ProviderSessionBinding,
type ProviderRuntimeBinding,
type ProviderSessionDirectoryShape,
} from "../Services/ProviderSessionDirectory.ts";
@@ -26,7 +25,7 @@ function decodeProviderKind(
providerName: string,
operation: string,
): Effect.Effect<ProviderKind, ProviderSessionDirectoryPersistenceError> {
if (providerName === "codex" || providerName === "claudeCode") {
if (providerName === "codex") {
return Effect.succeed(providerName);
}
return Effect.fail(
@@ -49,10 +48,7 @@ function mergeRuntimePayload(
return existing ?? null;
}
if (isRecord(existing) && isRecord(next)) {
return {
...existing,
...next,
};
return { ...existing, ...next };
}
return next;
}
@@ -60,21 +56,20 @@ function mergeRuntimePayload(
const makeProviderSessionDirectory = Effect.gen(function* () {
const repository = yield* ProviderSessionRuntimeRepository;
const getBinding = (sessionId: ProviderSessionId) =>
repository.getBySessionId({ providerSessionId: sessionId }).pipe(
Effect.mapError(toPersistenceError("ProviderSessionDirectory.getBinding:getBySessionId")),
const getBinding = (threadId: ThreadId) =>
repository.getByThreadId({ threadId }).pipe(
Effect.mapError(toPersistenceError("ProviderSessionDirectory.getBinding:getByThreadId")),
Effect.flatMap((runtime) =>
Option.match(runtime, {
onNone: () => Effect.succeed(Option.none<ProviderSessionBinding>()),
onNone: () => Effect.succeed(Option.none<ProviderRuntimeBinding>()),
onSome: (value) =>
decodeProviderKind(value.providerName, "ProviderSessionDirectory.getBinding").pipe(
Effect.map((provider) =>
Option.some({
sessionId: value.providerSessionId,
provider,
threadId: value.threadId,
provider,
adapterKey: value.adapterKey,
providerThreadId: value.providerThreadId,
runtimeMode: value.runtimeMode,
status: value.status,
resumeCursor: value.resumeCursor,
runtimePayload: value.runtimePayload,
@@ -87,10 +82,8 @@ const makeProviderSessionDirectory = Effect.gen(function* () {
const upsert: ProviderSessionDirectoryShape["upsert"] = Effect.fn(function* (binding) {
const existing = yield* repository
.getBySessionId({
providerSessionId: binding.sessionId,
})
.pipe(Effect.mapError(toPersistenceError("ProviderSessionDirectory.upsert:getBySessionId")));
.getByThreadId({ threadId: binding.threadId })
.pipe(Effect.mapError(toPersistenceError("ProviderSessionDirectory.upsert:getByThreadId")));
const existingRuntime = Option.getOrUndefined(existing);
const resolvedThreadId = binding.threadId ?? existingRuntime?.threadId;
@@ -102,16 +95,16 @@ const makeProviderSessionDirectory = Effect.gen(function* () {
}
const now = new Date().toISOString();
const providerChanged =
existingRuntime !== undefined && existingRuntime.providerName !== binding.provider;
yield* repository
.upsert({
providerSessionId: binding.sessionId,
threadId: resolvedThreadId,
providerName: binding.provider,
adapterKey: binding.adapterKey ?? existingRuntime?.adapterKey ?? binding.provider,
providerThreadId:
binding.providerThreadId !== undefined
? binding.providerThreadId
: (existingRuntime?.providerThreadId ?? null),
adapterKey:
binding.adapterKey ??
(providerChanged ? binding.provider : (existingRuntime?.adapterKey ?? binding.provider)),
runtimeMode: binding.runtimeMode ?? existingRuntime?.runtimeMode ?? "full-access",
status: binding.status ?? existingRuntime?.status ?? "running",
lastSeenAt: now,
resumeCursor:
@@ -126,63 +119,39 @@ const makeProviderSessionDirectory = Effect.gen(function* () {
.pipe(Effect.mapError(toPersistenceError("ProviderSessionDirectory.upsert:upsert")));
});
const getProvider: ProviderSessionDirectoryShape["getProvider"] = (sessionId) =>
getBinding(sessionId).pipe(
const getProvider: ProviderSessionDirectoryShape["getProvider"] = (threadId) =>
getBinding(threadId).pipe(
Effect.flatMap((binding) =>
Option.match(binding, {
onSome: (value) => Effect.succeed(value.provider),
onNone: () => Effect.fail(new ProviderSessionNotFoundError({ sessionId })),
}),
),
);
const getBindingBySessionId: ProviderSessionDirectoryShape["getBinding"] = (sessionId) =>
getBinding(sessionId);
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.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,
})),
onNone: () =>
Effect.fail(
new ProviderSessionDirectoryPersistenceError({
operation: "ProviderSessionDirectory.getProvider",
detail: `No persisted provider binding found for thread '${threadId}'.`,
}),
),
{ concurrency: "unbounded" },
),
}),
),
Effect.map((bindings) => bindings.map((binding) => binding.sessionId)),
);
const remove: ProviderSessionDirectoryShape["remove"] = (threadId) =>
repository
.deleteByThreadId({ threadId })
.pipe(Effect.mapError(toPersistenceError("ProviderSessionDirectory.remove:deleteByThreadId")));
const listThreadIds: ProviderSessionDirectoryShape["listThreadIds"] = () =>
repository.list().pipe(
Effect.mapError(toPersistenceError("ProviderSessionDirectory.listThreadIds:list")),
Effect.map((rows) => rows.map((row) => row.threadId)),
);
return {
upsert,
getProvider,
getBinding: getBindingBySessionId,
getThreadId,
getBinding,
remove,
listSessionIds,
listThreadIds,
} satisfies ProviderSessionDirectoryShape;
});
@@ -11,25 +11,34 @@ import type {
ApprovalRequestId,
ProviderApprovalDecision,
ProviderKind,
ProviderUserInputAnswers,
ProviderRuntimeEvent,
ProviderSendTurnInput,
ProviderSession,
ProviderSessionId,
ProviderSessionStartInput,
ProviderThreadId,
ProviderTurnId,
ThreadId,
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: ProviderTurnId;
readonly id: TurnId;
readonly items: ReadonlyArray<unknown>;
}
export interface ProviderThreadSnapshot {
readonly threadId: ProviderThreadId;
readonly threadId: ThreadId;
readonly turns: ReadonlyArray<ProviderThreadTurnSnapshot>;
}
@@ -38,6 +47,7 @@ export interface ProviderAdapterShape<TError> {
* Provider kind implemented by this adapter.
*/
readonly provider: ProviderKind;
readonly capabilities: ProviderAdapterCapabilities;
/**
* Start a provider-backed session.
@@ -57,23 +67,32 @@ export interface ProviderAdapterShape<TError> {
* Interrupt an active turn.
*/
readonly interruptTurn: (
sessionId: ProviderSessionId,
turnId?: ProviderTurnId,
threadId: ThreadId,
turnId?: TurnId,
) => Effect.Effect<void, TError>;
/**
* Respond to an interactive approval request.
*/
readonly respondToRequest: (
sessionId: ProviderSessionId,
threadId: ThreadId,
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: (sessionId: ProviderSessionId) => Effect.Effect<void, TError>;
readonly stopSession: (threadId: ThreadId) => Effect.Effect<void, TError>;
/**
* List currently active provider sessions for this adapter.
@@ -83,20 +102,20 @@ export interface ProviderAdapterShape<TError> {
/**
* Check whether this adapter owns an active session id.
*/
readonly hasSession: (sessionId: ProviderSessionId) => Effect.Effect<boolean>;
readonly hasSession: (threadId: ThreadId) => Effect.Effect<boolean>;
/**
* Read a provider thread snapshot.
*/
readonly readThread: (
sessionId: ProviderSessionId,
threadId: ThreadId,
) => Effect.Effect<ProviderThreadSnapshot, TError>;
/**
* Roll back a provider thread by N turns.
*/
readonly rollbackThread: (
sessionId: ProviderSessionId,
threadId: ThreadId,
numTurns: number,
) => Effect.Effect<ProviderThreadSnapshot, TError>;
@@ -13,11 +13,12 @@
*/
import type {
ProviderInterruptTurnInput,
ProviderKind,
ProviderRespondToRequestInput,
ProviderRespondToUserInputInput,
ProviderRuntimeEvent,
ProviderSendTurnInput,
ProviderSession,
ProviderSessionId,
ProviderSessionStartInput,
ProviderStopSessionInput,
ThreadId,
@@ -27,6 +28,7 @@ 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.
@@ -61,6 +63,13 @@ 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.
*/
@@ -75,24 +84,21 @@ 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 sessionId: ProviderSessionId;
readonly threadId: ThreadId;
readonly numTurns: number;
}) => Effect.Effect<void, ProviderServiceError>;
/**
* Stop all active provider sessions.
*
* Persisted session bindings remain so stale sessions can be resumed after
* process restart.
*
* Runtime alias mappings are cleared as part of shutdown.
*/
readonly stopAll: () => Effect.Effect<void, ProviderServiceError>;
/**
* Canonical provider runtime event stream.
*
@@ -1,17 +1,7 @@
/**
* 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,
ProviderThreadId,
RuntimeMode,
ThreadId,
} from "@t3tools/contracts";
import { Option, ServiceMap } from "effect";
@@ -19,83 +9,48 @@ import type { Effect } from "effect";
import type {
ProviderSessionDirectoryPersistenceError,
ProviderSessionNotFoundError,
ProviderValidationError,
} from "../Errors.ts";
export interface ProviderSessionBinding {
readonly sessionId: ProviderSessionId;
export interface ProviderRuntimeBinding {
readonly threadId: ThreadId;
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 =
| ProviderSessionNotFoundError
| ProviderSessionDirectoryPersistenceError;
export type ProviderSessionDirectoryReadError = 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: ProviderSessionBinding,
binding: ProviderRuntimeBinding,
) => Effect.Effect<void, ProviderSessionDirectoryWriteError>;
/**
* Resolve the provider owner for a session id.
*/
readonly getProvider: (
sessionId: ProviderSessionId,
threadId: ThreadId,
) => Effect.Effect<ProviderKind, ProviderSessionDirectoryReadError>;
/**
* Resolve the full tracked binding for a session id.
*/
readonly getBinding: (
sessionId: ProviderSessionId,
) => Effect.Effect<Option.Option<ProviderSessionBinding>, ProviderSessionDirectoryReadError>;
threadId: ThreadId,
) => Effect.Effect<Option.Option<ProviderRuntimeBinding>, 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: (
sessionId: ProviderSessionId,
threadId: ThreadId,
) => Effect.Effect<void, ProviderSessionDirectoryPersistenceError>;
/**
* List tracked session ids.
*/
readonly listSessionIds: () => Effect.Effect<
ReadonlyArray<ProviderSessionId>,
readonly listThreadIds: () => Effect.Effect<
ReadonlyArray<ThreadId>,
ProviderSessionDirectoryPersistenceError
>;
}
/**
* ProviderSessionDirectory - Service tag for session ownership lookup.
*/
export class ProviderSessionDirectory extends ServiceMap.Service<
ProviderSessionDirectory,
ProviderSessionDirectoryShape
+2 -1
View File
@@ -34,11 +34,12 @@ import { CodexTextGenerationLive } from "./git/Layers/CodexTextGeneration";
import { GitServiceLive } from "./git/Layers/GitService";
import { BunPtyAdapterLive } from "./terminal/Layers/BunPTY";
import { NodePtyAdapterLive } from "./terminal/Layers/NodePTY";
import { AnalyticsService } from "./telemetry/Services/AnalyticsService";
export function makeServerProviderLayer(): Layer.Layer<
ProviderService,
ProviderUnsupportedError,
SqlClient.SqlClient | ServerConfig | FileSystem.FileSystem
SqlClient.SqlClient | ServerConfig | FileSystem.FileSystem | AnalyticsService
> {
return Effect.gen(function* () {
const { stateDir } = yield* ServerConfig;
+24
View File
@@ -0,0 +1,24 @@
import fs from "node:fs";
import path from "node:path";
import { Effect, Logger } from "effect";
import * as Layer from "effect/Layer";
import { ServerConfig } from "./config";
export const ServerLoggerLive = Effect.gen(function* () {
const config = yield* ServerConfig;
const logDir = path.join(config.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);
+79
View File
@@ -0,0 +1,79 @@
import { Effect, FileSystem, Path, Random, Schema } from "effect";
import * as Crypto from "node:crypto";
import { homedir } from "node:os";
import { ServerConfig } from "../config";
const CodexAuthJsonSchema = Schema.Struct({
tokens: Schema.Struct({
account_id: Schema.String,
}),
});
class IdentifyUserError extends Schema.TaggedErrorClass<IdentifyUserError>()("IdentifyUserError", {
message: Schema.String,
cause: Schema.optional(Schema.Defect),
}) {}
const hash = (value: string) =>
Effect.try({
try: () => Crypto.createHash("sha256").update(value).digest("hex"),
catch: (error) =>
new IdentifyUserError({
message: "Failed to hash identifier",
cause: error,
}),
});
const getCodexAccountId = Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const authJsonPath = path.join(homedir(), ".codex", "auth.json");
const authJson = yield* Effect.flatMap(
fileSystem.readFileString(authJsonPath),
Schema.decodeEffect(Schema.fromJsonString(CodexAuthJsonSchema)),
);
return authJson.tokens.account_id;
});
const upsertAnonymousId = Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const serverConfig = yield* ServerConfig;
const anonymousIdPath = path.join(serverConfig.stateDir, "anonymous-id");
const anonymousId = yield* fileSystem.readFileString(anonymousIdPath).pipe(
Effect.catch(() =>
Effect.gen(function* () {
const randomId = yield* Random.nextUUIDv4;
yield* fileSystem.writeFileString(anonymousIdPath, randomId);
return randomId;
}),
),
);
return anonymousId;
});
/**
* getTelemetryIdentifier - Users are "identified" by finding the first match of the following, then hashing the value.
* 1. ~/.codex/auth.json tokens.account_id
* 2. ~/.t3/telemetry/anonymous-id
*/
export const getTelemetryIdentifier = Effect.gen(function* () {
const codexAccountId = yield* Effect.result(getCodexAccountId);
if (codexAccountId._tag === "Success") {
return yield* hash(codexAccountId.success);
}
const anonymousId = yield* Effect.result(upsertAnonymousId);
if (anonymousId._tag === "Success") {
return yield* hash(anonymousId.success);
}
return null;
}).pipe(
Effect.tapError((error) => Effect.logWarning("Failed to get identifier", { cause: error })),
Effect.orElseSucceed(() => null),
);
@@ -0,0 +1,122 @@
import * as NodeHttpServer from "@effect/platform-node/NodeHttpServer";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { assert, it } from "@effect/vitest";
import { ConfigProvider, Effect, FileSystem, Layer } from "effect";
import * as HttpServer from "effect/unstable/http/HttpServer";
import * as HttpServerRequest from "effect/unstable/http/HttpServerRequest";
import * as HttpServerResponse from "effect/unstable/http/HttpServerResponse";
import { ServerConfig } from "../../config.ts";
import { getTelemetryIdentifier } from "../Identify.ts";
import { AnalyticsService } from "../Services/AnalyticsService.ts";
import { AnalyticsServiceLayerLive } from "./AnalyticsService.ts";
interface RecordedBatchRequest {
readonly path: string;
readonly body: {
readonly batch?: ReadonlyArray<{
readonly event?: string;
readonly properties?: {
readonly index?: number;
readonly clientType?: string;
};
}>;
} | null;
}
interface RecordedBatchBody {
readonly batch: ReadonlyArray<{
readonly event?: string;
readonly properties?: {
readonly index?: number;
readonly clientType?: string;
};
}>;
}
it.layer(NodeServices.layer)("AnalyticsService test", (it) => {
it.effect("flush drains all buffered events across multiple batches", () =>
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const stateDir = yield* fileSystem.makeTempDirectoryScoped({
prefix: "t3-telemetry-flush-",
});
const capturedRequests: Array<RecordedBatchRequest> = [];
const serverConfigLayer = ServerConfig.layerTest(process.cwd(), stateDir);
const telemetryLayer = AnalyticsServiceLayerLive.pipe(Layer.provideMerge(serverConfigLayer));
const configLayer = ConfigProvider.layer(
ConfigProvider.fromUnknown({
T3CODE_TELEMETRY_ENABLED: true,
T3CODE_POSTHOG_KEY: "phc_test_key",
T3CODE_POSTHOG_HOST: "",
T3CODE_TELEMETRY_FLUSH_BATCH_SIZE: 20,
}),
);
const batchServerLayer = HttpServer.serve(
Effect.gen(function* () {
const request = yield* HttpServerRequest.HttpServerRequest;
if (request.method !== "POST") {
return HttpServerResponse.empty({ status: 404 });
}
const payload = yield* request.json.pipe(
Effect.map((body) => body as RecordedBatchRequest["body"]),
Effect.catch(() => Effect.succeed(null)),
);
capturedRequests.push({ path: request.url, body: payload });
return HttpServerResponse.jsonUnsafe({});
}),
);
const runtimeLayer = telemetryLayer.pipe(
Layer.provide(configLayer),
Layer.provideMerge(NodeHttpServer.layerTest),
);
yield* Effect.gen(function* () {
yield* Layer.launch(batchServerLayer).pipe(Effect.forkScoped);
const telemetryIdentifier = yield* getTelemetryIdentifier;
assert.equal(telemetryIdentifier !== null, true);
const analytics = yield* AnalyticsService;
for (let index = 0; index < 45; index += 1) {
yield* analytics.record("test.flush.drain", { index });
}
yield* analytics.flush;
}).pipe(Effect.provide(runtimeLayer));
const batchRequests = capturedRequests.filter(
(request): request is RecordedBatchRequest & { readonly body: RecordedBatchBody } =>
Array.isArray(request.body?.batch),
);
assert.equal(batchRequests.length, 3);
assert.equal(
batchRequests.every((request) => request.path === "/batch/" || request.path === "/batch"),
true,
);
const deliveredIndexes = batchRequests.flatMap((request) =>
request.body.batch
.filter((event) => event.event === "test.flush.drain")
.map((event) => event.properties?.index)
.filter((index): index is number => typeof index === "number"),
);
const sorted = deliveredIndexes.toSorted((a, b) => a - b);
assert.equal(sorted.length, 45);
assert.deepEqual(
sorted,
Array.from({ length: 45 }, (_, index) => index),
);
assert.equal(
batchRequests.every((request) =>
request.body.batch.every((event) => event.properties?.clientType === "cli-web-client"),
),
true,
);
}),
);
});
@@ -0,0 +1,151 @@
/**
* AnalyticsServiceLive - Anonymous PostHog telemetry layer.
*
* Persists a random installation-scoped anonymous id to state dir, buffers
* events in memory, and flushes batches to PostHog over Effect HttpClient.
*
* @module AnalyticsServiceLive
*/
import { Config, DateTime, Effect, Layer, Ref } from "effect";
import { HttpClient, HttpClientRequest, HttpClientResponse } from "effect/unstable/http";
import { ServerConfig } from "../../config.ts";
import { AnalyticsService, type AnalyticsServiceShape } from "../Services/AnalyticsService.ts";
import { getTelemetryIdentifier } from "../Identify.ts";
import { version } from "../../../package.json" with { type: "json" };
interface BufferedAnalyticsEvent {
readonly event: string;
readonly properties?: Readonly<Record<string, unknown>>;
readonly capturedAt: string;
}
const TelemetryEnvConfig = Config.all({
posthogKey: Config.string("T3CODE_POSTHOG_KEY").pipe(
Config.withDefault("phc_XOWci4oZP4VvLiEyrFqkFjP4CZn55mjYYBMREK5Wd6m"),
),
posthogHost: Config.string("T3CODE_POSTHOG_HOST").pipe(
Config.withDefault("https://us.i.posthog.com"),
),
enabled: Config.boolean("T3CODE_TELEMETRY_ENABLED").pipe(Config.withDefault(true)),
flushBatchSize: Config.number("T3CODE_TELEMETRY_FLUSH_BATCH_SIZE").pipe(Config.withDefault(20)),
maxBufferedEvents: Config.number("T3CODE_TELEMETRY_MAX_BUFFERED_EVENTS").pipe(
Config.withDefault(1_000),
),
});
const makeAnalyticsService = Effect.gen(function* () {
const telemetryConfig = yield* TelemetryEnvConfig.asEffect();
const httpClient = yield* HttpClient.HttpClient;
const serverConfig = yield* ServerConfig;
const identifier = yield* getTelemetryIdentifier;
const bufferRef = yield* Ref.make<ReadonlyArray<BufferedAnalyticsEvent>>([]);
const clientType = serverConfig.mode === "desktop" ? "desktop-app" : "cli-web-client";
const enqueueBufferedEvent = (event: string, properties?: Readonly<Record<string, unknown>>) =>
Effect.flatMap(DateTime.now, (now) =>
Ref.modify(bufferRef, (current) => {
const appended = [
...current,
{
event,
...(properties ? { properties } : {}),
capturedAt: DateTime.formatIso(now),
} satisfies BufferedAnalyticsEvent,
];
const next =
appended.length > telemetryConfig.maxBufferedEvents
? appended.slice(appended.length - telemetryConfig.maxBufferedEvents)
: appended;
return [
{
size: next.length,
dropped: next.length !== appended.length,
} as const,
next,
] as const;
}),
);
const sendBatch = (events: ReadonlyArray<BufferedAnalyticsEvent>) =>
Effect.gen(function* () {
if (!telemetryConfig.enabled || !identifier) return;
const payload = {
api_key: telemetryConfig.posthogKey,
batch: events.map((event) => ({
event: event.event,
distinct_id: identifier,
properties: {
...event.properties,
$process_person_profile: false,
platform: process.platform,
wsl: process.env.WSL_DISTRO_NAME,
arch: process.arch,
t3CodeVersion: version,
clientType,
},
timestamp: event.capturedAt,
})),
};
yield* HttpClientRequest.post(`${telemetryConfig.posthogHost}/batch/`).pipe(
HttpClientRequest.bodyJson(payload),
Effect.flatMap(httpClient.execute),
Effect.flatMap(HttpClientResponse.filterStatusOk),
);
});
const flush: AnalyticsServiceShape["flush"] = Effect.gen(function* () {
while (true) {
const batch = yield* Ref.modify(bufferRef, (current) => {
if (current.length === 0) {
return [[] as ReadonlyArray<BufferedAnalyticsEvent>, current] as const;
}
const nextBatch = current.slice(0, telemetryConfig.flushBatchSize);
const remaining = current.slice(nextBatch.length);
return [nextBatch, remaining] as const;
});
if (batch.length === 0) {
return;
}
yield* sendBatch(batch).pipe(
Effect.catch((error) =>
Ref.update(bufferRef, (current) => [...batch, ...current]).pipe(
Effect.flatMap(() => Effect.fail(error)),
),
),
);
}
}).pipe(Effect.catch((cause) => Effect.logError("Failed to flush telemetry", { cause })));
const record: AnalyticsServiceShape["record"] = Effect.fnUntraced(function* (event, properties) {
if (!telemetryConfig.enabled || !identifier) return;
const enqueueResult = yield* enqueueBufferedEvent(event, properties);
if (enqueueResult.dropped) {
yield* Effect.logDebug("analytics buffer full; dropping oldest event", {
size: enqueueResult.size,
event,
});
}
});
yield* Effect.forever(Effect.sleep(1000).pipe(Effect.flatMap(() => flush)), {
disableYield: true,
}).pipe(Effect.forkScoped);
yield* Effect.addFinalizer(() => flush);
return {
record,
flush,
} satisfies AnalyticsServiceShape;
});
export const AnalyticsServiceLayerLive = Layer.effect(AnalyticsService, makeAnalyticsService);
@@ -0,0 +1,33 @@
/**
* AnalyticsService - Anonymous telemetry capture contract.
*
* Provides a best-effort event API for runtime telemetry and a strict
* `captureImmediate` method for call sites that need explicit error handling.
*
* @module AnalyticsService
*/
import { Effect, Layer, ServiceMap } from "effect";
export interface AnalyticsServiceShape {
/**
* Capture an event immediately; returns typed failure when capture fails.
*/
readonly record: (
event: string,
properties?: Readonly<Record<string, unknown>>,
) => Effect.Effect<void, never>;
/**
* Flush queued telemetry.
*/
readonly flush: Effect.Effect<void, never>;
}
export class AnalyticsService extends ServiceMap.Service<AnalyticsService, AnalyticsServiceShape>()(
"t3/telemetry/Services/AnalyticsService",
) {
static readonly layerTest = Layer.succeed(AnalyticsService, {
record: () => Effect.void,
flush: Effect.void,
});
}
+85 -32
View File
@@ -18,9 +18,8 @@ import {
ORCHESTRATION_WS_CHANNELS,
ORCHESTRATION_WS_METHODS,
ProviderItemId,
ProviderSessionId,
ProviderThreadId,
ProviderTurnId,
ThreadId,
TurnId,
WS_CHANNELS,
WS_METHODS,
type WebSocketResponse,
@@ -51,6 +50,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 { AnalyticsService } from "./telemetry/Services/AnalyticsService.ts";
interface PendingMessages {
queue: unknown[];
@@ -60,11 +60,9 @@ 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,
@@ -396,10 +394,7 @@ describe("WebSocket Server", () => {
providerHealth?: ProviderHealthShape;
open?: OpenShape;
gitManager?: GitManagerShape;
gitCore?: Pick<
GitCoreShape,
"listBranches" | "initRepo" | "pullCurrentBranch"
>;
gitCore?: Pick<GitCoreShape, "listBranches" | "initRepo" | "pullCurrentBranch">;
terminalManager?: TerminalManagerShape;
} = {},
): Promise<Http.Server> {
@@ -440,6 +435,7 @@ describe("WebSocket Server", () => {
? Layer.succeed(TerminalManager, options.terminalManager)
: Layer.empty,
);
const runtimeLayer = Layer.merge(
Layer.merge(
makeServerRuntimeServicesLayer().pipe(Layer.provide(infrastructureLayer)),
@@ -452,6 +448,7 @@ describe("WebSocket Server", () => {
Layer.provideMerge(providerHealthLayer),
Layer.provideMerge(openLayer),
Layer.provideMerge(serverConfigLayer),
Layer.provideMerge(AnalyticsService.layerTest),
Layer.provideMerge(NodeServices.layer),
);
const runtimeServices = await Effect.runPromise(
@@ -1129,6 +1126,8 @@ describe("WebSocket Server", () => {
projectId: "project-diff",
title: "Diff Thread",
model: "gpt-5-codex",
runtimeMode: "full-access",
interactionMode: "default",
branch: null,
worktreePath: null,
createdAt,
@@ -1210,32 +1209,32 @@ 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: () =>
startSession: (threadId) =>
Effect.succeed({
sessionId,
provider: "codex",
status: "ready",
threadId: asProviderThreadId("provider-thread-1"),
runtimeMode: "full-access",
threadId,
createdAt: new Date().toISOString(),
updatedAt: new Date().toISOString(),
}),
sendTurn: () =>
sendTurn: ({ threadId }) =>
Effect.succeed({
threadId: asProviderThreadId("provider-thread-1"),
turnId: asProviderTurnId("provider-turn-1"),
threadId,
turnId: asTurnId("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),
};
const providerLayer = Layer.succeed(ProviderService, providerService);
@@ -1269,6 +1268,8 @@ describe("WebSocket Server", () => {
projectId: "project-1",
title: "Thread 1",
model: "gpt-5-codex",
runtimeMode: "full-access",
interactionMode: "default",
branch: null,
worktreePath: null,
createdAt,
@@ -1286,8 +1287,8 @@ describe("WebSocket Server", () => {
attachments: [],
},
assistantDeliveryMode: "streaming",
approvalPolicy: "on-request",
sandboxMode: "workspace-write",
runtimeMode: "approval-required",
interactionMode: "default",
createdAt,
});
expect(startTurnResponse.error).toBeUndefined();
@@ -1297,16 +1298,21 @@ describe("WebSocket Server", () => {
return event.type === "thread.session-set";
});
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",
});
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,
);
const domainPush = await waitForPush(ws, ORCHESTRATION_WS_CHANNELS.domainEvent, (push) => {
const event = push.data as { type?: string; payload?: { messageId?: string; text?: string } };
@@ -1582,6 +1588,54 @@ 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({
@@ -1629,7 +1683,6 @@ describe("WebSocket Server", () => {
expect(pullResponse.result).toBeUndefined();
expect(pullResponse.error?.message).toContain("No upstream configured");
expect(pullCurrentBranch).toHaveBeenCalledWith("/repo/path");
});
it("supports git.status over websocket", async () => {
+101 -32
View File
@@ -12,6 +12,7 @@ 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,
@@ -70,6 +71,7 @@ import {
resolveAttachmentPathById,
} from "./attachmentStore.ts";
import { parseBase64DataUrl } from "./imageMime.ts";
import { AnalyticsService } from "./telemetry/Services/AnalyticsService.ts";
/**
* ServerShape - Service API for server lifecycle control.
@@ -146,6 +148,48 @@ 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"]);
}
@@ -164,7 +208,8 @@ export type ServerRuntimeServices =
| GitCore
| TerminalManager
| Keybindings
| Open;
| Open
| AnalyticsService;
export class ServerLifecycleError extends Schema.TaggedErrorClass<ServerLifecycleError>()(
"ServerLifecycleError",
@@ -523,7 +568,6 @@ export const createServer = Effect.fn(function* (): Effect.fn.Return<
const orchestrationEngine = yield* OrchestrationEngineService;
const projectionReadModelQuery = yield* ProjectionSnapshotQuery;
const checkpointDiffQuery = yield* CheckpointDiffQuery;
const liveProviderService = yield* ProviderService;
const orchestrationReactor = yield* OrchestrationReactor;
const { openInEditor } = yield* Open;
@@ -595,6 +639,8 @@ 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,
@@ -612,6 +658,28 @@ export const createServer = Effect.fn(function* (): Effect.fn.Return<
);
}
const runPromise = yield* Effect.map(Effect.services<never>(), Effect.runPromiseWith);
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:
@@ -656,6 +724,32 @@ 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);
@@ -799,6 +893,7 @@ export const createServer = Effect.fn(function* (): Effect.fn.Return<
id: request.value.id,
result: result.value,
});
ws.send(response);
});
@@ -827,7 +922,7 @@ export const createServer = Effect.fn(function* (): Effect.fn.Return<
});
wss.on("connection", (ws) => {
void Effect.runPromise(Ref.update(clients, (clients) => clients.add(ws)));
void runPromise(Ref.update(clients, (clients) => clients.add(ws)));
const segments = cwd.split(/[/\\]/).filter(Boolean);
const projectName = segments[segments.length - 1] ?? "project";
@@ -846,7 +941,7 @@ export const createServer = Effect.fn(function* (): Effect.fn.Return<
ws.send(JSON.stringify(welcome));
ws.on("message", (raw) => {
void Effect.runPromise(
void runPromise(
handleMessage(ws, raw).pipe(
Effect.catch((error) => Effect.logError("Error handling message", error)),
),
@@ -854,7 +949,7 @@ export const createServer = Effect.fn(function* (): Effect.fn.Return<
});
ws.on("close", () => {
void Effect.runPromise(
void runPromise(
Ref.update(clients, (clients) => {
clients.delete(ws);
return clients;
@@ -863,7 +958,7 @@ export const createServer = Effect.fn(function* (): Effect.fn.Return<
});
ws.on("error", () => {
void Effect.runPromise(
void runPromise(
Ref.update(clients, (clients) => {
clients.delete(ws);
return clients;
@@ -872,32 +967,6 @@ 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 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@t3tools/web",
"version": "0.0.0-alpha.20",
"version": "0.0.0-alpha.22",
"private": true,
"type": "module",
"scripts": {
Binary file not shown.

Before

Width:  |  Height:  |  Size: 47 KiB

After

Width:  |  Height:  |  Size: 74 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.2 KiB

After

Width:  |  Height:  |  Size: 1003 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.3 KiB

After

Width:  |  Height:  |  Size: 3.0 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 279 KiB

After

Width:  |  Height:  |  Size: 204 KiB

Loaded 100 of 181 files, more files were not shown because too many files have changed in this diff. Show more