From c83bc5d48a2bf983acb1c8aaff3d34f86c14032e Mon Sep 17 00:00:00 2001 From: Efe Baran Durmaz <75971010+EfeDurmaz16@users.noreply.github.com> Date: Sun, 19 Apr 2026 20:58:04 +0300 Subject: [PATCH 01/82] fix(release): use v tag format for nightly releases (#2186) --- .github/workflows/release.yml | 3 ++- scripts/release-smoke.ts | 2 +- scripts/resolve-nightly-release.test.ts | 2 +- scripts/resolve-nightly-release.ts | 2 +- scripts/resolve-previous-release-tag.ts | 12 ++++++++++-- 5 files changed, 15 insertions(+), 6 deletions(-) diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 25b4ac213c..366a6b4de3 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -4,6 +4,7 @@ on: push: tags: - "v*.*.*" + - "!v*-nightly.*" schedule: - cron: "0 */3 * * *" workflow_dispatch: @@ -41,7 +42,7 @@ jobs: - id: check name: Compare HEAD to last nightly tag run: | - last_nightly_tag=$(git tag --list 'nightly-v*' --sort=-creatordate | head -n 1) + last_nightly_tag=$(git tag --list 'v*-nightly.*' 'nightly-v*' --sort=-creatordate | head -n 1) if [[ -z "$last_nightly_tag" ]]; then echo "No previous nightly tag found. Proceeding with release." echo "has_changes=true" >> "$GITHUB_OUTPUT" diff --git a/scripts/release-smoke.ts b/scripts/release-smoke.ts index 41f948c685..362771d12e 100644 --- a/scripts/release-smoke.ts +++ b/scripts/release-smoke.ts @@ -220,7 +220,7 @@ try { ); assertContains( nightlyReleaseMetadata, - "tag=nightly-v9.9.10-nightly.20260413.321", + "tag=v9.9.10-nightly.20260413.321", "Expected nightly metadata to contain the derived nightly tag.", ); assertContains( diff --git a/scripts/resolve-nightly-release.test.ts b/scripts/resolve-nightly-release.test.ts index 56358d6c14..82b25737a5 100644 --- a/scripts/resolve-nightly-release.test.ts +++ b/scripts/resolve-nightly-release.test.ts @@ -24,7 +24,7 @@ it("derives nightly metadata including the short commit sha in the release name" { baseVersion: "9.9.10", version: "9.9.10-nightly.20260413.321", - tag: "nightly-v9.9.10-nightly.20260413.321", + tag: "v9.9.10-nightly.20260413.321", name: "T3 Code Nightly 9.9.10-nightly.20260413.321 (abcdef123456)", shortSha: "abcdef123456", }, diff --git a/scripts/resolve-nightly-release.ts b/scripts/resolve-nightly-release.ts index 4a92ef63ae..5f9413db20 100644 --- a/scripts/resolve-nightly-release.ts +++ b/scripts/resolve-nightly-release.ts @@ -54,7 +54,7 @@ export const resolveNightlyReleaseMetadata = ( return { baseVersion, version, - tag: `nightly-v${version}`, + tag: `v${version}`, name: `T3 Code Nightly ${version} (${shortSha})`, shortSha, }; diff --git a/scripts/resolve-previous-release-tag.ts b/scripts/resolve-previous-release-tag.ts index 93f932821f..5f2ef1316b 100644 --- a/scripts/resolve-previous-release-tag.ts +++ b/scripts/resolve-previous-release-tag.ts @@ -75,11 +75,17 @@ const parseStableTag = (tag: string): StableVersion | undefined => { const [, major, minor, patch, prerelease] = match; if (!major || !minor || !patch) return undefined; + const prereleaseIdentifiers = prerelease ? prerelease.split(".") : []; + // Nightly tags also start with `v` and carry a `nightly.*` prerelease + // identifier. They must not be considered stable candidates when resolving + // the previous stable tag. + if (prereleaseIdentifiers[0] === "nightly") return undefined; + return { major: Number(major), minor: Number(minor), patch: Number(patch), - prerelease: prerelease ? prerelease.split(".") : [], + prerelease: prereleaseIdentifiers, }; }; @@ -92,7 +98,9 @@ const compareNightlyVersions = (left: NightlyVersion, right: NightlyVersion): nu }; const parseNightlyTag = (tag: string): NightlyVersion | undefined => { - const match = /^nightly-v(\d+)\.(\d+)\.(\d+)-nightly\.(\d{8})\.(\d+)$/.exec(tag); + // Accept both the current `v` format and the legacy `nightly-v` + // format so release note diffs keep working across the tag-format transition. + const match = /^(?:nightly-)?v(\d+)\.(\d+)\.(\d+)-nightly\.(\d{8})\.(\d+)$/.exec(tag); if (!match) return undefined; const [, major, minor, patch, date, runNumber] = match; From 20f346d8ef58b21c339bc956c1728f4f16d09a87 Mon Sep 17 00:00:00 2001 From: "Alton Johnson, OSCP, OSCE" <4023423+altjx@users.noreply.github.com> Date: Sun, 19 Apr 2026 20:06:19 -0400 Subject: [PATCH 02/82] Expand leading ~ in Codex home paths before exporting CODEX_HOME (#2210) Co-authored-by: Claude Opus 4.7 (1M context) Co-authored-by: = <=> --- apps/server/src/codexAppServerManager.ts | 5 +-- .../src/git/Layers/CodexTextGeneration.ts | 5 ++- apps/server/src/pathExpansion.test.ts | 33 +++++++++++++++++++ apps/server/src/pathExpansion.ts | 23 +++++++++++++ .../src/provider/Layers/CodexProvider.ts | 3 +- apps/server/src/provider/codexAppServer.ts | 3 +- 6 files changed, 67 insertions(+), 5 deletions(-) create mode 100644 apps/server/src/pathExpansion.test.ts create mode 100644 apps/server/src/pathExpansion.ts diff --git a/apps/server/src/codexAppServerManager.ts b/apps/server/src/codexAppServerManager.ts index 6d98264c91..ba776890ee 100644 --- a/apps/server/src/codexAppServerManager.ts +++ b/apps/server/src/codexAppServerManager.ts @@ -32,6 +32,7 @@ import { type CodexAccountSnapshot, } from "./provider/codexAccount.ts"; import { buildCodexInitializeParams, killCodexChildProcess } from "./provider/codexAppServer.ts"; +import { expandHomePath } from "./pathExpansion.ts"; export { buildCodexInitializeParams } from "./provider/codexAppServer.ts"; export { readCodexAccountSnapshot, resolveCodexModelForAccount } from "./provider/codexAccount.ts"; @@ -493,7 +494,7 @@ export class CodexAppServerManager extends EventEmitter { + it("returns an empty string unchanged", () => { + expect(expandHomePath("")).toBe(""); + }); + + it("returns paths without a leading tilde unchanged", () => { + expect(expandHomePath("/absolute/path")).toBe("/absolute/path"); + expect(expandHomePath("relative/path")).toBe("relative/path"); + expect(expandHomePath("some~weird~path")).toBe("some~weird~path"); + }); + + it("expands a lone tilde to the home directory", () => { + expect(expandHomePath("~")).toBe(homedir()); + }); + + it("expands ~/ to a subpath of the home directory", () => { + expect(expandHomePath("~/.codex-work")).toBe(join(homedir(), ".codex-work")); + }); + + it("expands a Windows-style ~\\ prefix", () => { + expect(expandHomePath("~\\.codex")).toBe(join(homedir(), ".codex")); + }); + + it("does not expand ~user paths", () => { + expect(expandHomePath("~alice/foo")).toBe("~alice/foo"); + }); +}); diff --git a/apps/server/src/pathExpansion.ts b/apps/server/src/pathExpansion.ts new file mode 100644 index 0000000000..18060c3e55 --- /dev/null +++ b/apps/server/src/pathExpansion.ts @@ -0,0 +1,23 @@ +import { homedir } from "node:os"; +import { join } from "node:path"; + +/** + * Expand a leading `~` (or `~/…`, `~\…`) in a user-supplied path to the + * current user's home directory. Spawned processes don't get shell + * expansion, so env vars like `CODEX_HOME=~/.codex-work` would be passed + * verbatim and treated as relative paths by the receiver. + * + * Matches the behavior of the other `expandHomePath` helpers in the + * workspace layers and CLI bootstrap: `~` alone and both `~/` and `~\` + * separators are handled. Returns the input unchanged if it doesn't + * start with `~` or is empty. Does not handle `~user` (other-user) + * expansion. + */ +export function expandHomePath(value: string): string { + if (!value) return value; + if (value === "~") return homedir(); + if (value.startsWith("~/") || value.startsWith("~\\")) { + return join(homedir(), value.slice(2)); + } + return value; +} diff --git a/apps/server/src/provider/Layers/CodexProvider.ts b/apps/server/src/provider/Layers/CodexProvider.ts index de4aceeac9..ab2f962eae 100644 --- a/apps/server/src/provider/Layers/CodexProvider.ts +++ b/apps/server/src/provider/Layers/CodexProvider.ts @@ -47,6 +47,7 @@ import { } from "../codexAccount.ts"; import { probeCodexDiscovery } from "../codexAppServer.ts"; import { CodexProvider } from "../Services/CodexProvider.ts"; +import { expandHomePath } from "../../pathExpansion.ts"; import { ServerSettingsService } from "../../serverSettings.ts"; import { ServerSettingsError } from "@t3tools/contracts"; @@ -325,7 +326,7 @@ const runCodexCommand = Effect.fn("runCodexCommand")(function* (args: ReadonlyAr shell: process.platform === "win32", env: { ...process.env, - ...(codexSettings.homePath ? { CODEX_HOME: codexSettings.homePath } : {}), + ...(codexSettings.homePath ? { CODEX_HOME: expandHomePath(codexSettings.homePath) } : {}), }, }); return yield* spawnAndCollect(codexSettings.binaryPath, command); diff --git a/apps/server/src/provider/codexAppServer.ts b/apps/server/src/provider/codexAppServer.ts index 24a9e29c59..7806e135fe 100644 --- a/apps/server/src/provider/codexAppServer.ts +++ b/apps/server/src/provider/codexAppServer.ts @@ -2,6 +2,7 @@ import { spawn, spawnSync, type ChildProcessWithoutNullStreams } from "node:chil import readline from "node:readline"; import type { ServerProviderSkill } from "@t3tools/contracts"; import { readCodexAccountSnapshot, type CodexAccountSnapshot } from "./codexAccount.ts"; +import { expandHomePath } from "../pathExpansion.ts"; interface JsonRpcProbeResponse { readonly id?: unknown; @@ -115,7 +116,7 @@ export async function probeCodexDiscovery(input: { const child = spawn(input.binaryPath, ["app-server"], { env: { ...process.env, - ...(input.homePath ? { CODEX_HOME: input.homePath } : {}), + ...(input.homePath ? { CODEX_HOME: expandHomePath(input.homePath) } : {}), }, stdio: ["pipe", "pipe", "pipe"], shell: process.platform === "win32", From 57b59b5bf209837db3ae911f2ca181f8f1dc2df7 Mon Sep 17 00:00:00 2001 From: Kyle Gottfried <6462596+Spitfire1900@users.noreply.github.com> Date: Sun, 19 Apr 2026 20:07:12 -0400 Subject: [PATCH 03/82] Devcontainer / IDE updates (#2208) --- .devcontainer/devcontainer.json | 15 +++++++++++---- .oxfmtrc.json | 10 +++++++++- .vscode/settings.json | 2 +- 3 files changed, 21 insertions(+), 6 deletions(-) diff --git a/.devcontainer/devcontainer.json b/.devcontainer/devcontainer.json index 0c4c30240c..cc1f11cd8b 100644 --- a/.devcontainer/devcontainer.json +++ b/.devcontainer/devcontainer.json @@ -2,15 +2,22 @@ "name": "T3 Code Dev", "image": "debian:bookworm", "features": { - "ghcr.io/devcontainers-extra/features/bun:1": {}, + "ghcr.io/devcontainers/features/git:1": {}, + "ghcr.io/devcontainers-extra/features/bun:1": { + "version": "1.3.11" + }, "ghcr.io/devcontainers/features/node:1": { - "version": "24", - "nodeGypDependencies": true + "version": "24.13.1" }, "ghcr.io/devcontainers/features/python:1": { - "version": "3.12" + "version": "3.10", + "installTools": false } }, + "overrideFeatureInstallOrder": [ + "ghcr.io/devcontainers/features/git", + "ghcr.io/devcontainers-extra/features/bun" + ], "postCreateCommand": { "bun-install": "bun install --backend=copyfile --frozen-lockfile" }, diff --git a/.oxfmtrc.json b/.oxfmtrc.json index dded6b0acd..3d65d9c93b 100644 --- a/.oxfmtrc.json +++ b/.oxfmtrc.json @@ -13,5 +13,13 @@ "apps/web/src/lib/vendor/qrcodegen.ts", "*.icon/**" ], - "sortPackageJson": {} + "sortPackageJson": {}, + "overrides": [ + { + "files": [".devcontainer/devcontainer.json"], + "options": { + "trailingComma": "none" + } + } + ] } diff --git a/.vscode/settings.json b/.vscode/settings.json index 752d9a9071..8a1b614ddd 100644 --- a/.vscode/settings.json +++ b/.vscode/settings.json @@ -5,5 +5,5 @@ "source.fixAll.oxc": "always" }, "oxc.unusedDisableDirectives": "warn", - "typescript.tsdk": "node_modules/typescript/lib" + "js/ts.tsdk.path": "node_modules/typescript/lib" } From 37965da01d34e50a67f92cd7fb978b74a6cf8fcf Mon Sep 17 00:00:00 2001 From: Abdul Azeez Date: Mon, 20 Apr 2026 05:42:35 +0530 Subject: [PATCH 04/82] =?UTF-8?q?fix(server):=20handle=20OpenCode=20text?= =?UTF-8?q?=20response=20format=20in=20commit=20message=20g=E2=80=A6=20(#2?= =?UTF-8?q?202)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../src/git/Layers/CursorTextGeneration.ts | 55 ++----------- .../git/Layers/OpenCodeTextGeneration.test.ts | 81 +++++++++++++++++-- .../src/git/Layers/OpenCodeTextGeneration.ts | 68 +++++++++++++--- apps/server/src/git/Utils.ts | 48 +++++++++++ 4 files changed, 184 insertions(+), 68 deletions(-) diff --git a/apps/server/src/git/Layers/CursorTextGeneration.ts b/apps/server/src/git/Layers/CursorTextGeneration.ts index 754f3737eb..24f066059c 100644 --- a/apps/server/src/git/Layers/CursorTextGeneration.ts +++ b/apps/server/src/git/Layers/CursorTextGeneration.ts @@ -16,7 +16,12 @@ import { buildPrContentPrompt, buildThreadTitlePrompt, } from "../Prompts.ts"; -import { sanitizeCommitSubject, sanitizePrTitle, sanitizeThreadTitle } from "../Utils.ts"; +import { + extractJsonObject, + sanitizeCommitSubject, + sanitizePrTitle, + sanitizeThreadTitle, +} from "../Utils.ts"; import { applyCursorAcpModelSelection, makeCursorAcpRuntime, @@ -25,54 +30,6 @@ import { ServerSettingsService } from "../../serverSettings.ts"; const CURSOR_TIMEOUT_MS = 180_000; -function extractJsonObject(raw: string): string { - const trimmed = raw.trim(); - if (trimmed.length === 0) { - return trimmed; - } - - const start = trimmed.indexOf("{"); - if (start < 0) { - return trimmed; - } - - let depth = 0; - let inString = false; - let escaping = false; - for (let index = start; index < trimmed.length; index += 1) { - const char = trimmed[index]; - if (inString) { - if (escaping) { - escaping = false; - } else if (char === "\\") { - escaping = true; - } else if (char === '"') { - inString = false; - } - continue; - } - - if (char === '"') { - inString = true; - continue; - } - - if (char === "{") { - depth += 1; - continue; - } - - if (char === "}") { - depth -= 1; - if (depth === 0) { - return trimmed.slice(start, index + 1); - } - } - } - - return trimmed.slice(start); -} - function mapCursorAcpError( operation: | "generateCommitMessage" diff --git a/apps/server/src/git/Layers/OpenCodeTextGeneration.test.ts b/apps/server/src/git/Layers/OpenCodeTextGeneration.test.ts index 4cf25c9468..ab98024567 100644 --- a/apps/server/src/git/Layers/OpenCodeTextGeneration.test.ts +++ b/apps/server/src/git/Layers/OpenCodeTextGeneration.test.ts @@ -17,7 +17,9 @@ const runtimeMock = vi.hoisted(() => { promptUrls: [] as string[], authHeaders: [] as Array, closeCalls: [] as string[], - promptResult: undefined as { data?: { info?: { structured?: unknown } } } | undefined, + promptResult: undefined as + | { data?: { info?: { error?: unknown }; parts?: Array<{ type: string; text?: string }> } } + | undefined, }; return { @@ -63,12 +65,15 @@ vi.mock("../../provider/opencodeRuntime.ts", async () => { return ( runtimeMock.state.promptResult ?? { data: { - info: { - structured: { - subject: "Improve OpenCode reuse", - body: "Reuse one server for the full action.", + parts: [ + { + type: "text", + text: JSON.stringify({ + subject: "Improve OpenCode reuse", + body: "Reuse one server for the full action.", + }), }, - }, + ], }, } ); @@ -198,7 +203,7 @@ it.layer(OpenCodeTextGenerationTestLayer)("OpenCodeTextGenerationLive", (it) => }).pipe(Effect.provide(TestClock.layer())), ); - it.effect("returns a typed missing-output error when OpenCode omits info.structured", () => + it.effect("returns a typed empty-output error when OpenCode returns no text parts", () => Effect.gen(function* () { runtimeMock.state.promptResult = { data: {} }; const textGeneration = yield* TextGeneration; @@ -213,7 +218,67 @@ it.layer(OpenCodeTextGenerationTestLayer)("OpenCodeTextGenerationLive", (it) => }) .pipe(Effect.flip); - expect(error.message).toContain("OpenCode returned no structured output."); + expect(error.message).toContain("OpenCode returned empty output."); + }), + ); + + it.effect("parses JSON returned as plain text output", () => + Effect.gen(function* () { + runtimeMock.state.promptResult = { + data: { + parts: [ + { + type: "text", + text: 'Here is the result:\n{"subject":"Tighten OpenCode parsing","body":"Handle JSON text output locally."}', + }, + ], + }, + }; + const textGeneration = yield* TextGeneration; + + const result = yield* textGeneration.generateCommitMessage({ + cwd: process.cwd(), + branch: "feature/opencode-reuse", + stagedSummary: "M README.md", + stagedPatch: "diff --git a/README.md b/README.md", + modelSelection: DEFAULT_TEST_MODEL_SELECTION, + }); + + expect(result).toEqual({ + subject: "Tighten OpenCode parsing", + body: "Handle JSON text output locally.", + }); + }), + ); + + it.effect("surfaces the upstream OpenCode structured-output error message", () => + Effect.gen(function* () { + runtimeMock.state.promptResult = { + data: { + info: { + error: { + name: "StructuredOutputError", + data: { + message: "Model did not produce structured output", + retries: 2, + }, + }, + }, + }, + }; + const textGeneration = yield* TextGeneration; + + const error = yield* textGeneration + .generateCommitMessage({ + cwd: process.cwd(), + branch: "feature/opencode-reuse", + stagedSummary: "M README.md", + stagedPatch: "diff --git a/README.md b/README.md", + modelSelection: DEFAULT_TEST_MODEL_SELECTION, + }) + .pipe(Effect.flip); + + expect(error.message).toContain("Model did not produce structured output"); }), ); }); diff --git a/apps/server/src/git/Layers/OpenCodeTextGeneration.ts b/apps/server/src/git/Layers/OpenCodeTextGeneration.ts index 7721354e4d..d206e59e8d 100644 --- a/apps/server/src/git/Layers/OpenCodeTextGeneration.ts +++ b/apps/server/src/git/Layers/OpenCodeTextGeneration.ts @@ -19,10 +19,10 @@ import { } from "../Prompts.ts"; import { type TextGenerationShape, TextGeneration } from "../Services/TextGeneration.ts"; import { + extractJsonObject, sanitizeCommitSubject, sanitizePrTitle, sanitizeThreadTitle, - toJsonSchemaObject, } from "../Utils.ts"; import { createOpenCodeSdkClient, @@ -35,6 +35,49 @@ import { const OPENCODE_TEXT_GENERATION_IDLE_TTL_MS = 30_000; +function getOpenCodePromptErrorMessage(error: unknown): string | null { + if (!error || typeof error !== "object") { + return null; + } + + const message = + "data" in error && + error.data && + typeof error.data === "object" && + "message" in error.data && + typeof error.data.message === "string" + ? error.data.message.trim() + : ""; + if (message.length > 0) { + return message; + } + + if ("name" in error && typeof error.name === "string") { + const name = error.name.trim(); + return name.length > 0 ? name : null; + } + + return null; +} + +function getOpenCodeTextResponse(parts: ReadonlyArray | undefined): string { + return (parts ?? []) + .flatMap((part) => { + if (!part || typeof part !== "object") { + return []; + } + if (!("type" in part) || part.type !== "text") { + return []; + } + if (!("text" in part) || typeof part.text !== "string") { + return []; + } + return [part.text]; + }) + .join("") + .trim(); +} + interface SharedOpenCodeTextGenerationServerState { server: OpenCodeServerProcess | null; binaryPath: string | null; @@ -245,17 +288,18 @@ const makeOpenCodeTextGeneration = Effect.gen(function* () { ...(input.modelSelection.options?.variant ? { variant: input.modelSelection.options.variant } : {}), - format: { - type: "json_schema", - schema: toJsonSchemaObject(input.outputSchemaJson) as Record, - }, parts: [{ type: "text", text: input.prompt }, ...fileParts], }); - const structured = result.data?.info?.structured; - if (structured === undefined) { - throw new Error("OpenCode returned no structured output."); + const info = result.data?.info; + const errorMessage = getOpenCodePromptErrorMessage(info?.error); + if (errorMessage) { + throw new Error(errorMessage); } - return structured; + const rawText = getOpenCodeTextResponse(result.data?.parts); + if (rawText.length === 0) { + throw new Error("OpenCode returned empty output."); + } + return rawText; }, catch: (cause) => new TextGenerationError({ @@ -266,7 +310,7 @@ const makeOpenCodeTextGeneration = Effect.gen(function* () { }), }); - const structuredOutput = + const rawOutput = settings.serverUrl.length > 0 ? yield* runAgainstServer({ url: settings.serverUrl }) : yield* Effect.acquireUseRelease( @@ -278,7 +322,9 @@ const makeOpenCodeTextGeneration = Effect.gen(function* () { releaseSharedServer, ); - return yield* Schema.decodeUnknownEffect(input.outputSchemaJson)(structuredOutput).pipe( + return yield* Schema.decodeEffect(Schema.fromJsonString(input.outputSchemaJson))( + extractJsonObject(rawOutput), + ).pipe( Effect.catchTag("SchemaError", (cause) => Effect.fail( new TextGenerationError({ diff --git a/apps/server/src/git/Utils.ts b/apps/server/src/git/Utils.ts index 4a7931c74b..15015e8cda 100644 --- a/apps/server/src/git/Utils.ts +++ b/apps/server/src/git/Utils.ts @@ -30,6 +30,54 @@ export function limitSection(value: string, maxChars: number): string { return `${truncated}\n\n[truncated]`; } +export function extractJsonObject(raw: string): string { + const trimmed = raw.trim(); + if (trimmed.length === 0) { + return trimmed; + } + + const start = trimmed.indexOf("{"); + if (start < 0) { + return trimmed; + } + + let depth = 0; + let inString = false; + let escaping = false; + for (let index = start; index < trimmed.length; index += 1) { + const char = trimmed[index]; + if (inString) { + if (escaping) { + escaping = false; + } else if (char === "\\") { + escaping = true; + } else if (char === '"') { + inString = false; + } + continue; + } + + if (char === '"') { + inString = true; + continue; + } + + if (char === "{") { + depth += 1; + continue; + } + + if (char === "}") { + depth -= 1; + if (depth === 0) { + return trimmed.slice(start, index + 1); + } + } + } + + return trimmed.slice(start); +} + /** Normalise a raw commit subject to imperative-mood, ≤72 chars, no trailing period. */ export function sanitizeCommitSubject(raw: string): string { const singleLine = raw.trim().split(/\r?\n/g)[0]?.trim() ?? ""; From 8dbcf92a0d125050988474f258df3e55c538efec Mon Sep 17 00:00:00 2001 From: reasv <7143787+reasv@users.noreply.github.com> Date: Mon, 20 Apr 2026 02:13:20 +0200 Subject: [PATCH 05/82] fix(server): prevent probeClaudeCapabilities from wasting API requests (#2192) Co-authored-by: Claude Opus 4.6 Co-authored-by: Julius Marminge --- .../src/provider/Layers/ClaudeProvider.ts | 26 +++++++++++++++---- 1 file changed, 21 insertions(+), 5 deletions(-) diff --git a/apps/server/src/provider/Layers/ClaudeProvider.ts b/apps/server/src/provider/Layers/ClaudeProvider.ts index 5274f84285..7c8a4c27a6 100644 --- a/apps/server/src/provider/Layers/ClaudeProvider.ts +++ b/apps/server/src/provider/Layers/ClaudeProvider.ts @@ -14,6 +14,7 @@ import { decodeJsonResult } from "@t3tools/shared/schemaJson"; import { query as claudeQuery, type SlashCommand as ClaudeSlashCommand, + type SDKUserMessage, } from "@anthropic-ai/claude-agent-sdk"; import { @@ -480,13 +481,24 @@ function dedupeSlashCommands( return [...commandsByName.values()]; } +function waitForAbortSignal(signal: AbortSignal): Promise { + if (signal.aborted) { + return Promise.resolve(); + } + return new Promise((resolve) => { + signal.addEventListener("abort", () => resolve(), { once: true }); + }); +} + /** * Probe account information by spawning a lightweight Claude Agent SDK * session and reading the initialization result. * - * The prompt is never sent to the Anthropic API — we abort immediately - * after the local initialization phase completes. This gives us the - * user's subscription type without incurring any token cost. + * We pass a never-yielding AsyncIterable as the prompt so that no user + * message is ever written to the subprocess stdin. This means the Claude + * Code subprocess completes its local initialization IPC (returning + * account info and slash commands) but never starts an API request to + * Anthropic. We read the init data and then abort the subprocess. * * This is used as a fallback when `claude auth status` does not include * subscription type information. @@ -495,12 +507,16 @@ const probeClaudeCapabilities = (binaryPath: string) => { const abort = new AbortController(); return Effect.tryPromise(async () => { const q = claudeQuery({ - prompt: ".", + // Never yield — we only need initialization data, not a conversation. + // This prevents any prompt from reaching the Anthropic API. + // oxlint-disable-next-line require-yield + prompt: (async function* (): AsyncGenerator { + await waitForAbortSignal(abort.signal); + })(), options: { persistSession: false, pathToClaudeCodeExecutable: binaryPath, abortController: abort, - maxTurns: 0, settingSources: ["user", "project", "local"], allowedTools: [], stderr: () => {}, From 66c326b8c424ca1e3702232a4fe5a06f6ba2a525 Mon Sep 17 00:00:00 2001 From: Ellie Gummere Date: Sun, 19 Apr 2026 20:43:40 -0400 Subject: [PATCH 06/82] Redesign model picker with favorites and search (#2153) Co-authored-by: Julius Marminge --- apps/desktop/src/clientPersistence.test.ts | 1 + apps/server/src/keybindings.test.ts | 3 + apps/server/src/keybindings.ts | 7 + .../src/provider/opencodeRuntime.test.ts | 59 +- apps/server/src/provider/opencodeRuntime.ts | 3 +- apps/web/src/components/AppSidebarLayout.tsx | 32 +- apps/web/src/components/ChatView.browser.tsx | 237 ++++++ apps/web/src/components/ChatView.tsx | 10 + .../src/components/CommandPalette.logic.ts | 34 +- apps/web/src/components/Icons.tsx | 43 +- apps/web/src/components/Sidebar.tsx | 145 +--- apps/web/src/components/chat/ChatComposer.tsx | 110 +-- .../components/chat/ComposerCommandMenu.tsx | 14 - apps/web/src/components/chat/ModelListRow.tsx | 104 +++ .../components/chat/ModelPickerContent.tsx | 519 ++++++++++++ .../components/chat/ModelPickerSidebar.tsx | 210 +++++ .../chat/ProviderModelPicker.browser.tsx | 763 ++++++++++++++++-- .../components/chat/ProviderModelPicker.tsx | 277 +++---- .../chat/modelPickerModelHighlights.ts | 13 + .../components/chat/modelPickerSearch.test.ts | 109 +++ .../src/components/chat/modelPickerSearch.ts | 83 ++ .../src/components/chat/providerIconUtils.ts | 52 ++ apps/web/src/components/ui/autocomplete.tsx | 2 +- apps/web/src/components/ui/combobox.tsx | 16 +- apps/web/src/components/ui/scroll-area.tsx | 7 +- apps/web/src/composer-logic.test.ts | 15 +- apps/web/src/composer-logic.ts | 20 +- apps/web/src/hooks/useSettings.ts | 7 +- apps/web/src/index.css | 22 + apps/web/src/keybindings.test.ts | 60 ++ apps/web/src/keybindings.ts | 60 +- apps/web/src/localApi.test.ts | 2 + apps/web/src/modelPickerOpenState.ts | 17 + apps/web/src/modelSelection.ts | 9 +- apps/web/src/session-logic.ts | 6 +- apps/web/src/shortcutModifierState.test.ts | 146 ++++ apps/web/src/shortcutModifierState.ts | 96 +++ packages/contracts/src/keybindings.test.ts | 12 + packages/contracts/src/keybindings.ts | 21 + packages/contracts/src/server.ts | 2 + packages/contracts/src/settings.ts | 31 +- 41 files changed, 2838 insertions(+), 541 deletions(-) create mode 100644 apps/web/src/components/chat/ModelListRow.tsx create mode 100644 apps/web/src/components/chat/ModelPickerContent.tsx create mode 100644 apps/web/src/components/chat/ModelPickerSidebar.tsx create mode 100644 apps/web/src/components/chat/modelPickerModelHighlights.ts create mode 100644 apps/web/src/components/chat/modelPickerSearch.test.ts create mode 100644 apps/web/src/components/chat/modelPickerSearch.ts create mode 100644 apps/web/src/components/chat/providerIconUtils.ts create mode 100644 apps/web/src/modelPickerOpenState.ts create mode 100644 apps/web/src/shortcutModifierState.test.ts create mode 100644 apps/web/src/shortcutModifierState.ts diff --git a/apps/desktop/src/clientPersistence.test.ts b/apps/desktop/src/clientPersistence.test.ts index 27f1e1d91a..19f9b09f9f 100644 --- a/apps/desktop/src/clientPersistence.test.ts +++ b/apps/desktop/src/clientPersistence.test.ts @@ -52,6 +52,7 @@ const clientSettings: ClientSettings = { confirmThreadArchive: true, confirmThreadDelete: false, diffWordWrap: true, + favorites: [], sidebarProjectGroupingMode: "repository_path", sidebarProjectGroupingOverrides: { "environment-1:/tmp/project-a": "separate", diff --git a/apps/server/src/keybindings.test.ts b/apps/server/src/keybindings.test.ts index 15edd4295d..bbb7e1b430 100644 --- a/apps/server/src/keybindings.test.ts +++ b/apps/server/src/keybindings.test.ts @@ -192,6 +192,9 @@ it.layer(NodeServices.layer)("keybindings", (it) => { assert.equal(defaultsByCommand.get("thread.next"), "mod+shift+]"); assert.equal(defaultsByCommand.get("thread.jump.1"), "mod+1"); assert.equal(defaultsByCommand.get("thread.jump.9"), "mod+9"); + assert.equal(defaultsByCommand.get("modelPicker.toggle"), "mod+shift+m"); + assert.equal(defaultsByCommand.get("modelPicker.jump.1"), "mod+1"); + assert.equal(defaultsByCommand.get("modelPicker.jump.9"), "mod+9"); }), ); diff --git a/apps/server/src/keybindings.ts b/apps/server/src/keybindings.ts index 07ae9156c1..9689254c17 100644 --- a/apps/server/src/keybindings.ts +++ b/apps/server/src/keybindings.ts @@ -13,6 +13,7 @@ import { KeybindingShortcut, KeybindingWhenNode, MAX_KEYBINDINGS_COUNT, + MODEL_PICKER_JUMP_KEYBINDING_COMMANDS, MAX_WHEN_EXPRESSION_DEPTH, ResolvedKeybindingRule, ResolvedKeybindingsConfig, @@ -65,6 +66,7 @@ export const DEFAULT_KEYBINDINGS: ReadonlyArray = [ { key: "mod+n", command: "chat.new", when: "!terminalFocus" }, { key: "mod+shift+o", command: "chat.new", when: "!terminalFocus" }, { key: "mod+shift+n", command: "chat.newLocal", when: "!terminalFocus" }, + { key: "mod+shift+m", command: "modelPicker.toggle", when: "!terminalFocus" }, { key: "mod+o", command: "editor.openFavorite" }, { key: "mod+shift+[", command: "thread.previous" }, { key: "mod+shift+]", command: "thread.next" }, @@ -72,6 +74,11 @@ export const DEFAULT_KEYBINDINGS: ReadonlyArray = [ key: `mod+${index + 1}`, command, })), + ...MODEL_PICKER_JUMP_KEYBINDING_COMMANDS.map((command, index) => ({ + key: `mod+${index + 1}`, + command, + when: "modelPickerOpen", + })), ]; function normalizeKeyToken(token: string): string { diff --git a/apps/server/src/provider/opencodeRuntime.test.ts b/apps/server/src/provider/opencodeRuntime.test.ts index 0ea63f8d53..0e7024efc9 100644 --- a/apps/server/src/provider/opencodeRuntime.test.ts +++ b/apps/server/src/provider/opencodeRuntime.test.ts @@ -1,37 +1,36 @@ -import assert from "node:assert/strict"; +import { describe, expect, it } from "vitest"; -import { describe, it, vi } from "vitest"; +import { DEFAULT_OPENCODE_MODEL_CAPABILITIES, flattenOpenCodeModels } from "./opencodeRuntime.ts"; -const childProcessMock = vi.hoisted(() => ({ - execFileSync: vi.fn((command: string, args: ReadonlyArray) => { - if (command === "which" && args[0] === "opencode") { - return "/opt/homebrew/bin/opencode\n"; - } - return ""; - }), - spawn: vi.fn(), -})); +describe("flattenOpenCodeModels", () => { + it("keeps the canonical model name separate from the subprovider label", () => { + const models = flattenOpenCodeModels({ + providerList: { + connected: ["github-copilot"], + all: [ + { + id: "github-copilot", + name: "GitHub Copilot", + models: { + "claude-opus-4.5": { + id: "claude-opus-4.5", + name: "Claude Opus 4.5", + variants: {}, + }, + }, + }, + ], + }, + agents: [], + } as unknown as Parameters[0]); -vi.mock("node:child_process", () => childProcessMock); - -describe("resolveOpenCodeBinaryPath", () => { - it("returns absolute binary paths without PATH lookup", async () => { - const { resolveOpenCodeBinaryPath } = await import("./opencodeRuntime.ts"); - - assert.equal(resolveOpenCodeBinaryPath("/usr/local/bin/opencode"), "/usr/local/bin/opencode"); - assert.equal(childProcessMock.execFileSync.mock.calls.length, 0); - }); - - it("resolves command names through PATH", async () => { - const { resolveOpenCodeBinaryPath } = await import("./opencodeRuntime.ts"); - - assert.equal(resolveOpenCodeBinaryPath("opencode"), "/opt/homebrew/bin/opencode"); - assert.deepEqual(childProcessMock.execFileSync.mock.calls[0], [ - "which", - ["opencode"], + expect(models).toEqual([ { - encoding: "utf8", - timeout: 3_000, + slug: "github-copilot/claude-opus-4.5", + name: "Claude Opus 4.5", + subProvider: "GitHub Copilot", + isCustom: false, + capabilities: DEFAULT_OPENCODE_MODEL_CAPABILITIES, }, ]); }); diff --git a/apps/server/src/provider/opencodeRuntime.ts b/apps/server/src/provider/opencodeRuntime.ts index 4778f6eac9..91a855bce6 100644 --- a/apps/server/src/provider/opencodeRuntime.ts +++ b/apps/server/src/provider/opencodeRuntime.ts @@ -558,7 +558,8 @@ export function flattenOpenCodeModels( for (const model of Object.values(provider.models)) { models.push({ slug: toOpenCodeModelSlug(provider.id, model.id), - name: `${provider.name} · ${model.name}`, + name: model.name, + subProvider: provider.name, isCustom: false, capabilities: openCodeCapabilitiesForModel({ providerID: provider.id, diff --git a/apps/web/src/components/AppSidebarLayout.tsx b/apps/web/src/components/AppSidebarLayout.tsx index a2b27bb1e9..b1ce57235a 100644 --- a/apps/web/src/components/AppSidebarLayout.tsx +++ b/apps/web/src/components/AppSidebarLayout.tsx @@ -3,14 +3,39 @@ import { useNavigate } from "@tanstack/react-router"; import ThreadSidebar from "./Sidebar"; import { Sidebar, SidebarProvider, SidebarRail } from "./ui/sidebar"; +import { + clearShortcutModifierState, + syncShortcutModifierStateFromKeyboardEvent, +} from "../shortcutModifierState"; const THREAD_SIDEBAR_WIDTH_STORAGE_KEY = "chat_thread_sidebar_width"; const THREAD_SIDEBAR_MIN_WIDTH = 13 * 16; const THREAD_MAIN_CONTENT_MIN_WIDTH = 40 * 16; - export function AppSidebarLayout({ children }: { children: ReactNode }) { const navigate = useNavigate(); + useEffect(() => { + const onWindowKeyDown = (event: KeyboardEvent) => { + syncShortcutModifierStateFromKeyboardEvent(event); + }; + const onWindowKeyUp = (event: KeyboardEvent) => { + syncShortcutModifierStateFromKeyboardEvent(event); + }; + const onWindowBlur = () => { + clearShortcutModifierState(); + }; + + window.addEventListener("keydown", onWindowKeyDown, true); + window.addEventListener("keyup", onWindowKeyUp, true); + window.addEventListener("blur", onWindowBlur); + + return () => { + window.removeEventListener("keydown", onWindowKeyDown, true); + window.removeEventListener("keyup", onWindowKeyUp, true); + window.removeEventListener("blur", onWindowBlur); + }; + }, []); + useEffect(() => { const onMenuAction = window.desktopBridge?.onMenuAction; if (typeof onMenuAction !== "function") { @@ -18,8 +43,9 @@ export function AppSidebarLayout({ children }: { children: ReactNode }) { } const unsubscribe = onMenuAction((action) => { - if (action !== "open-settings") return; - void navigate({ to: "/settings" }); + if (action === "open-settings") { + void navigate({ to: "/settings" }); + } }); return () => { diff --git a/apps/web/src/components/ChatView.browser.tsx b/apps/web/src/components/ChatView.browser.tsx index 41f627332e..6857a51b51 100644 --- a/apps/web/src/components/ChatView.browser.tsx +++ b/apps/web/src/components/ChatView.browser.tsx @@ -1384,6 +1384,18 @@ function dispatchChatNewShortcut(): void { ); } +function releaseModShortcut(key?: string): void { + window.dispatchEvent( + new KeyboardEvent("keyup", { + key: key ?? (isMacPlatform(navigator.platform) ? "Meta" : "Control"), + metaKey: false, + ctrlKey: false, + bubbles: true, + cancelable: true, + }), + ); +} + async function triggerChatNewShortcutUntilPath( router: ReturnType, predicate: (pathname: string) => boolean, @@ -4006,6 +4018,29 @@ describe("ChatView timeline estimator parity (full app)", () => { node: { type: "identifier", name: "terminalFocus" }, }, }, + { + command: "thread.jump.1", + shortcut: { + key: "1", + metaKey: true, + ctrlKey: false, + shiftKey: false, + altKey: false, + modKey: false, + }, + }, + { + command: "modelPicker.jump.1", + shortcut: { + key: "1", + metaKey: true, + ctrlKey: false, + shiftKey: false, + altKey: false, + modKey: false, + }, + whenAst: { type: "identifier", name: "modelPickerOpen" }, + }, ], }; }, @@ -5520,6 +5555,208 @@ describe("ChatView timeline estimator parity (full app)", () => { } }); + it("opens the model picker when selecting /model", async () => { + const mounted = await mountChatView({ + viewport: DEFAULT_VIEWPORT, + snapshot: createSnapshotForTargetUser({ + targetMessageId: "msg-user-model-command-target" as MessageId, + targetText: "model command thread", + }), + }); + + try { + await waitForComposerEditor(); + await page.getByTestId("composer-editor").fill("/mod"); + + const menuItem = await waitForComposerMenuItem("slash:model"); + await menuItem.click(); + + await vi.waitFor(() => { + expect(document.querySelector(".model-picker-list")).not.toBeNull(); + expect(findComposerProviderModelPicker()?.textContent).not.toContain("/model"); + }); + + await new Promise((resolve) => { + requestAnimationFrame(() => { + requestAnimationFrame(() => resolve()); + }); + }); + + await vi.waitFor(() => { + const searchInput = document.querySelector( + 'input[placeholder="Search models..."]', + ); + expect(searchInput).not.toBeNull(); + expect(document.activeElement).toBe(searchInput); + }); + } finally { + await mounted.cleanup(); + } + }); + + it("toggles the model picker and shows jump keys immediately from the shortcut", async () => { + const snapshot = createSnapshotForTargetUser({ + targetMessageId: "msg-user-model-picker-shortcut-target" as MessageId, + targetText: "model picker shortcut thread", + }); + const mounted = await mountChatView({ + viewport: DEFAULT_VIEWPORT, + snapshot: { + ...snapshot, + projects: snapshot.projects.map((project) => + project.id === PROJECT_ID + ? Object.assign({}, project, { + defaultModelSelection: { provider: "codex", model: "gpt-5.4" }, + }) + : project, + ), + threads: snapshot.threads.map((thread) => + thread.id === THREAD_ID + ? Object.assign({}, thread, { + modelSelection: { provider: "codex", model: "gpt-5.4" }, + }) + : thread, + ), + }, + configureFixture: (nextFixture) => { + nextFixture.serverConfig = { + ...nextFixture.serverConfig, + keybindings: [ + { + command: "modelPicker.toggle", + shortcut: { + key: "m", + metaKey: false, + ctrlKey: true, + shiftKey: true, + altKey: false, + modKey: false, + }, + whenAst: { + type: "not", + node: { type: "identifier", name: "terminalFocus" }, + }, + }, + { + command: "thread.jump.1", + shortcut: { + key: "1", + metaKey: false, + ctrlKey: true, + shiftKey: false, + altKey: false, + modKey: false, + }, + }, + { + command: "modelPicker.jump.1", + shortcut: { + key: "1", + metaKey: false, + ctrlKey: true, + shiftKey: false, + altKey: false, + modKey: false, + }, + whenAst: { type: "identifier", name: "modelPickerOpen" }, + }, + ], + providers: [ + { + ...nextFixture.serverConfig.providers[0]!, + provider: "codex", + models: [ + { + slug: "gpt-5.1-codex-max", + name: "GPT-5.1 Codex Max", + isCustom: false, + capabilities: { + supportsFastMode: true, + supportsThinkingToggle: false, + reasoningEffortLevels: [], + promptInjectedEffortLevels: [], + contextWindowOptions: [], + }, + }, + { + slug: "gpt-5.3-codex", + name: "GPT-5.3 Codex", + isCustom: false, + capabilities: { + supportsFastMode: true, + supportsThinkingToggle: false, + reasoningEffortLevels: [], + promptInjectedEffortLevels: [], + contextWindowOptions: [], + }, + }, + { + slug: "gpt-5.4", + name: "GPT-5.4", + isCustom: false, + capabilities: { + supportsFastMode: true, + supportsThinkingToggle: false, + reasoningEffortLevels: [], + promptInjectedEffortLevels: [], + contextWindowOptions: [], + }, + }, + ], + }, + ], + }; + }, + }); + + try { + await waitForServerConfigToApply(); + await waitForComposerEditor(); + + const initialPath = mounted.router.state.location.pathname; + window.dispatchEvent( + new KeyboardEvent("keydown", { + key: "m", + ctrlKey: true, + shiftKey: true, + bubbles: true, + cancelable: true, + }), + ); + + await vi.waitFor(() => { + expect(document.querySelector(".model-picker-list")).not.toBeNull(); + }); + + const jumpLabel = isMacPlatform(navigator.platform) ? "⌃1" : "Ctrl+1"; + await vi.waitFor(() => { + expect( + Array.from( + document.querySelectorAll('.model-picker-list [data-slot="kbd"]'), + ).some((element) => element.textContent?.trim() === jumpLabel), + ).toBe(true); + }); + expect(mounted.router.state.location.pathname).toBe(initialPath); + + window.dispatchEvent( + new KeyboardEvent("keydown", { + key: "m", + ctrlKey: true, + shiftKey: true, + bubbles: true, + cancelable: true, + }), + ); + + await vi.waitFor(() => { + expect(document.querySelector(".model-picker-list")).toBeNull(); + }); + } finally { + releaseModShortcut("Control"); + await mounted.cleanup(); + } + }); + it("shows a tooltip with the skill description when hovering a skill pill", async () => { const mounted = await mountChatView({ viewport: DEFAULT_VIEWPORT, diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsx index 47dad09ea2..535c0d9fca 100644 --- a/apps/web/src/components/ChatView.tsx +++ b/apps/web/src/components/ChatView.tsx @@ -2233,6 +2233,7 @@ export default function ChatView(props: ChatViewProps) { const shortcutContext = { terminalFocus: isTerminalFocused(), terminalOpen: Boolean(terminalState.terminalOpen), + modelPickerOpen: composerRef.current?.isModelPickerOpen() ?? false, }; const command = resolveShortcutCommand(event, keybindings, { @@ -2282,6 +2283,13 @@ export default function ChatView(props: ChatViewProps) { return; } + if (command === "modelPicker.toggle") { + event.preventDefault(); + event.stopPropagation(); + composerRef.current?.toggleModelPicker(); + return; + } + const scriptId = projectScriptIdFromCommand(command); if (!scriptId || !activeProject) return; const script = activeProject.scripts.find((entry) => entry.id === scriptId); @@ -3341,6 +3349,8 @@ export default function ChatView(props: ChatViewProps) { activeThreadActivities={activeThread?.activities} resolvedTheme={resolvedTheme} settings={settings} + keybindings={keybindings} + terminalOpen={Boolean(terminalState.terminalOpen)} gitCwd={gitCwd} promptRef={promptRef} composerImagesRef={composerImagesRef} diff --git a/apps/web/src/components/CommandPalette.logic.ts b/apps/web/src/components/CommandPalette.logic.ts index 866db58fb4..450f678dd5 100644 --- a/apps/web/src/components/CommandPalette.logic.ts +++ b/apps/web/src/components/CommandPalette.logic.ts @@ -151,22 +151,26 @@ export function buildThreadActionItems { - await input.runThread(thread); + return Object.assign( + { + kind: "action" as const, + value: `thread:${thread.id}`, + searchTerms: [thread.title, projectTitle ?? ``, thread.branch ?? ``], + title: thread.title, + description: descriptionParts.join(` · `), + timestamp: formatRelativeTimeLabel( + thread.latestUserMessageAt ?? thread.updatedAt ?? thread.createdAt, + ), + icon: input.icon, }, - }; + leadingContent ? { titleLeadingContent: leadingContent } : {}, + trailingContent ? { titleTrailingContent: trailingContent } : {}, + { + run: async () => { + await input.runThread(thread); + }, + }, + ); }); } diff --git a/apps/web/src/components/Icons.tsx b/apps/web/src/components/Icons.tsx index 9a7ac5fbb9..98bc509a6f 100644 --- a/apps/web/src/components/Icons.tsx +++ b/apps/web/src/components/Icons.tsx @@ -1,4 +1,5 @@ import { type SVGProps, useId } from "react"; +import { cn } from "~/lib/utils"; export type Icon = React.FC>; @@ -14,8 +15,12 @@ export const GitHubIcon: Icon = (props) => ( ); -export const CursorIcon: Icon = (props) => ( - +export const CursorIcon: Icon = ({ className, ...props }) => ( + ); @@ -290,18 +295,25 @@ export const Zed: Icon = (props) => { ); }; -export const OpenAI: Icon = (props) => ( - +export const OpenAI: Icon = ({ className, ...props }) => ( + ); -export const ClaudeAI: Icon = (props) => ( - - +export const ClaudeAI: Icon = ({ className, ...props }) => ( + + ); @@ -565,3 +577,14 @@ export const OpenCodeIcon: Icon = (props) => ( ); + +export const GithubCopilotIcon: Icon = ({ className, ...props }) => ( + + + +); diff --git a/apps/web/src/components/Sidebar.tsx b/apps/web/src/components/Sidebar.tsx index 8272779399..8335042c11 100644 --- a/apps/web/src/components/Sidebar.tsx +++ b/apps/web/src/components/Sidebar.tsx @@ -75,11 +75,13 @@ import { useUiStateStore } from "../uiStateStore"; import { resolveShortcutCommand, shortcutLabelForCommand, - shouldShowThreadJumpHints, + shouldShowThreadJumpHintsForModifiers, threadJumpCommandForIndex, threadJumpIndexFromCommand, threadTraversalDirectionFromCommand, } from "../keybindings"; +import { useModelPickerOpen } from "../modelPickerOpenState"; +import { useShortcutModifierState } from "../shortcutModifierState"; import { useGitStatus } from "../lib/gitStatusState"; import { readLocalApi } from "../localApi"; import { useComposerDraftStore } from "../composerDraftStore"; @@ -199,24 +201,6 @@ const PROJECT_GROUPING_MODE_LABELS: Record = separate: "Keep separate", }; -function threadJumpLabelMapsEqual( - left: ReadonlyMap, - right: ReadonlyMap, -): boolean { - if (left === right) { - return true; - } - if (left.size !== right.size) { - return false; - } - for (const [key, value] of left) { - if (right.get(key) !== value) { - return false; - } - } - return true; -} - function formatProjectMemberActionLabel( member: SidebarProjectGroupMember, groupedProjectCount: number, @@ -2715,6 +2699,8 @@ export default function Sidebar() { const clearSelection = useThreadSelectionStore((s) => s.clearSelection); const setSelectionAnchor = useThreadSelectionStore((s) => s.setAnchor); const platform = navigator.platform; + const shortcutModifiers = useShortcutModifierState(); + const modelPickerOpen = useModelPickerOpen(); const primaryEnvironmentId = usePrimaryEnvironmentId(); const savedEnvironmentRegistry = useSavedEnvironmentRegistryStore((s) => s.byId); const savedEnvironmentRuntimeById = useSavedEnvironmentRuntimeStore((s) => s.byId); @@ -2822,8 +2808,9 @@ export default function Sidebar() { routeThreadRef, ).terminalOpen : false, + modelPickerOpen, }), - [routeThreadRef], + [modelPickerOpen, routeThreadRef], ); const newThreadShortcutLabelOptions = useMemo( () => ({ @@ -3016,12 +3003,37 @@ export default function Sidebar() { () => [...threadJumpCommandByKey.keys()], [threadJumpCommandByKey], ); - const [threadJumpLabelByKey, setThreadJumpLabelByKey] = - useState>(EMPTY_THREAD_JUMP_LABELS); - const threadJumpLabelsRef = useRef>(EMPTY_THREAD_JUMP_LABELS); - threadJumpLabelsRef.current = threadJumpLabelByKey; - const showThreadJumpHintsRef = useRef(showThreadJumpHints); - showThreadJumpHintsRef.current = showThreadJumpHints; + const sidebarShortcutContext = useMemo( + () => ({ + terminalFocus: false, + terminalOpen: routeThreadRef + ? selectThreadTerminalState( + useTerminalStateStore.getState().terminalStateByThreadKey, + routeThreadRef, + ).terminalOpen + : false, + modelPickerOpen, + }), + [modelPickerOpen, routeThreadRef], + ); + const threadJumpLabelByKey = useMemo( + () => + buildThreadJumpLabelMap({ + keybindings, + platform, + terminalOpen: sidebarShortcutContext.terminalOpen, + threadJumpCommandByKey, + }), + [keybindings, platform, sidebarShortcutContext.terminalOpen, threadJumpCommandByKey], + ); + const shouldShowThreadJumpHintsNow = shouldShowThreadJumpHintsForModifiers( + shortcutModifiers, + keybindings, + { + platform, + context: sidebarShortcutContext, + }, + ); const visibleThreadJumpLabelByKey = showThreadJumpHints ? threadJumpLabelByKey : EMPTY_THREAD_JUMP_LABELS; @@ -3052,52 +3064,12 @@ export default function Sidebar() { }, [prewarmedSidebarThreadRefs]); useEffect(() => { - const clearThreadJumpHints = () => { - setThreadJumpLabelByKey((current) => - current === EMPTY_THREAD_JUMP_LABELS ? current : EMPTY_THREAD_JUMP_LABELS, - ); - updateThreadJumpHintsVisibility(false); - }; - const shouldIgnoreThreadJumpHintUpdate = (event: globalThis.KeyboardEvent) => - !event.metaKey && - !event.ctrlKey && - !event.altKey && - !event.shiftKey && - event.key !== "Meta" && - event.key !== "Control" && - event.key !== "Alt" && - event.key !== "Shift" && - !showThreadJumpHintsRef.current && - threadJumpLabelsRef.current === EMPTY_THREAD_JUMP_LABELS; + updateThreadJumpHintsVisibility(shouldShowThreadJumpHintsNow); + }, [shouldShowThreadJumpHintsNow, updateThreadJumpHintsVisibility]); + useEffect(() => { const onWindowKeyDown = (event: globalThis.KeyboardEvent) => { - if (shouldIgnoreThreadJumpHintUpdate(event)) { - return; - } const shortcutContext = getCurrentSidebarShortcutContext(); - const shouldShowHints = shouldShowThreadJumpHints(event, keybindings, { - platform, - context: shortcutContext, - }); - if (!shouldShowHints) { - if ( - showThreadJumpHintsRef.current || - threadJumpLabelsRef.current !== EMPTY_THREAD_JUMP_LABELS - ) { - clearThreadJumpHints(); - } - } else { - setThreadJumpLabelByKey((current) => { - const nextLabelMap = buildThreadJumpLabelMap({ - keybindings, - platform, - terminalOpen: shortcutContext.terminalOpen, - threadJumpCommandByKey, - }); - return threadJumpLabelMapsEqual(current, nextLabelMap) ? current : nextLabelMap; - }); - updateThreadJumpHintsVisibility(true); - } if (event.defaultPrevented || event.repeat) { return; @@ -3147,43 +3119,10 @@ export default function Sidebar() { navigateToThread(scopeThreadRef(targetThread.environmentId, targetThread.id)); }; - const onWindowKeyUp = (event: globalThis.KeyboardEvent) => { - if (shouldIgnoreThreadJumpHintUpdate(event)) { - return; - } - const shortcutContext = getCurrentSidebarShortcutContext(); - const shouldShowHints = shouldShowThreadJumpHints(event, keybindings, { - platform, - context: shortcutContext, - }); - if (!shouldShowHints) { - clearThreadJumpHints(); - return; - } - setThreadJumpLabelByKey((current) => { - const nextLabelMap = buildThreadJumpLabelMap({ - keybindings, - platform, - terminalOpen: shortcutContext.terminalOpen, - threadJumpCommandByKey, - }); - return threadJumpLabelMapsEqual(current, nextLabelMap) ? current : nextLabelMap; - }); - updateThreadJumpHintsVisibility(true); - }; - - const onWindowBlur = () => { - clearThreadJumpHints(); - }; - window.addEventListener("keydown", onWindowKeyDown); - window.addEventListener("keyup", onWindowKeyUp); - window.addEventListener("blur", onWindowBlur); return () => { window.removeEventListener("keydown", onWindowKeyDown); - window.removeEventListener("keyup", onWindowKeyUp); - window.removeEventListener("blur", onWindowBlur); }; }, [ getCurrentSidebarShortcutContext, @@ -3193,9 +3132,7 @@ export default function Sidebar() { platform, routeThreadKey, sidebarThreadByKey, - threadJumpCommandByKey, threadJumpThreadKeys, - updateThreadJumpHintsVisibility, ]); useEffect(() => { diff --git a/apps/web/src/components/chat/ChatComposer.tsx b/apps/web/src/components/chat/ChatComposer.tsx index 4cc2c85cae..3d3b081af9 100644 --- a/apps/web/src/components/chat/ChatComposer.tsx +++ b/apps/web/src/components/chat/ChatComposer.tsx @@ -6,6 +6,7 @@ import type { ProviderApprovalDecision, ProviderInteractionMode, ProviderKind, + ResolvedKeybindingsConfig, RuntimeMode, ScopedThreadRef, ServerProvider, @@ -59,7 +60,7 @@ import { shouldUseCompactComposerFooter, } from "../composerFooterLayout"; import { type ComposerPromptEditorHandle, ComposerPromptEditor } from "../ComposerPromptEditor"; -import { AVAILABLE_PROVIDER_OPTIONS, ProviderModelPicker } from "./ProviderModelPicker"; +import { ProviderModelPicker } from "./ProviderModelPicker"; import { type ComposerCommandItem, ComposerCommandMenu } from "./ComposerCommandMenu"; import { ComposerPendingApprovalActions } from "./ComposerPendingApprovalActions"; import { CompactComposerControlsMenu } from "./CompactComposerControlsMenu"; @@ -317,6 +318,9 @@ const ComposerFooterPrimaryActions = memo(function ComposerFooterPrimaryActions( export interface ChatComposerHandle { focusAtEnd: () => void; focusAt: (cursor: number) => void; + openModelPicker: () => void; + toggleModelPicker: () => void; + isModelPickerOpen: () => boolean; readSnapshot: () => { value: string; cursor: number; @@ -410,6 +414,8 @@ export interface ChatComposerProps { // Misc resolvedTheme: "light" | "dark"; settings: UnifiedSettings; + keybindings: ResolvedKeybindingsConfig; + terminalOpen: boolean; gitCwd: string | null; // Refs the parent needs kept in sync @@ -497,6 +503,8 @@ export const ChatComposer = memo( activeThreadActivities, resolvedTheme, settings, + keybindings, + terminalOpen, gitCwd, promptRef, composerImagesRef, @@ -622,23 +630,6 @@ export const ChatComposer = memo( ? selectedModelForPicker : (normalizeModelSlug(selectedModelForPicker, selectedProvider) ?? selectedModelForPicker); }, [modelOptionsByProvider, selectedModelForPicker, selectedProvider]); - const searchableModelOptions = useMemo( - () => - AVAILABLE_PROVIDER_OPTIONS.filter( - (option) => lockedProvider === null || option.value === lockedProvider, - ).flatMap((option) => - modelOptionsByProvider[option.value].map(({ slug, name }) => ({ - provider: option.value, - providerLabel: option.label, - slug, - name, - searchSlug: slug.toLowerCase(), - searchName: name.toLowerCase(), - searchProvider: option.label.toLowerCase(), - })), - ), - [lockedProvider, modelOptionsByProvider], - ); // ------------------------------------------------------------------ // Context window @@ -664,6 +655,7 @@ export const ChatComposer = memo( const [isDragOverComposer, setIsDragOverComposer] = useState(false); const [isComposerFooterCompact, setIsComposerFooterCompact] = useState(false); const [isComposerPrimaryActionsCompact, setIsComposerPrimaryActionsCompact] = useState(false); + const [isComposerModelPickerOpen, setIsComposerModelPickerOpen] = useState(false); // ------------------------------------------------------------------ // Refs @@ -782,31 +774,8 @@ export const ChatComposer = memo( (skill.scope ? `${skill.scope} skill` : "Run provider skill"), })); } - return searchableModelOptions - .filter(({ searchSlug, searchName, searchProvider }) => { - const query = composerTrigger.query.trim().toLowerCase(); - if (!query) return true; - return ( - searchSlug.includes(query) || - searchName.includes(query) || - searchProvider.includes(query) - ); - }) - .map(({ provider, providerLabel, slug, name }) => ({ - id: `model:${provider}:${slug}`, - type: "model", - provider, - model: slug, - label: name, - description: `${providerLabel} · ${slug}`, - })); - }, [ - composerTrigger, - searchableModelOptions, - selectedProvider, - selectedProviderStatus, - workspaceEntries, - ]); + return []; + }, [composerTrigger, selectedProvider, selectedProviderStatus, workspaceEntries]); const composerMenuOpen = Boolean(composerTrigger); const composerMenuSearchKey = composerTrigger @@ -1276,7 +1245,7 @@ export const ChatComposer = memo( rangeStart: number, rangeEnd: number, replacement: string, - options?: { expectedText?: string }, + options?: { expectedText?: string; focusEditorAfterReplace?: boolean }, ): boolean => { const currentText = promptRef.current; const safeStart = Math.max(0, Math.min(currentText.length, rangeStart)); @@ -1305,9 +1274,11 @@ export const ChatComposer = memo( } setComposerCursor(nextCursor); setComposerTrigger(detectComposerTrigger(next.text, nextExpandedCursor)); - window.requestAnimationFrame(() => { - composerEditorRef.current?.focusAt(nextCursor); - }); + if (options?.focusEditorAfterReplace !== false) { + window.requestAnimationFrame(() => { + composerEditorRef.current?.focusAt(nextCursor); + }); + } return true; }, [ @@ -1377,20 +1348,13 @@ export const ChatComposer = memo( } if (item.type === "slash-command") { if (item.command === "model") { - const replacement = "/model "; - const replacementRangeEnd = extendReplacementRangeForTrailingSpace( - snapshot.value, - trigger.rangeEnd, - replacement, - ); - const applied = applyPromptReplacement( - trigger.rangeStart, - replacementRangeEnd, - replacement, - { expectedText: snapshot.value.slice(trigger.rangeStart, replacementRangeEnd) }, - ); + const applied = applyPromptReplacement(trigger.rangeStart, trigger.rangeEnd, "", { + expectedText: snapshot.value.slice(trigger.rangeStart, trigger.rangeEnd), + focusEditorAfterReplace: false, + }); if (applied) { setComposerHighlightedItemId(null); + setIsComposerModelPickerOpen(true); } return; } @@ -1439,20 +1403,8 @@ export const ChatComposer = memo( } return; } - onProviderModelSelect(item.provider, item.model); - const applied = applyPromptReplacement(trigger.rangeStart, trigger.rangeEnd, "", { - expectedText: snapshot.value.slice(trigger.rangeStart, trigger.rangeEnd), - }); - if (applied) { - setComposerHighlightedItemId(null); - } }, - [ - applyPromptReplacement, - handleInteractionModeChange, - onProviderModelSelect, - resolveActiveComposerTrigger, - ], + [applyPromptReplacement, handleInteractionModeChange, resolveActiveComposerTrigger], ); const onComposerMenuItemHighlighted = useCallback( @@ -1633,6 +1585,13 @@ export const ChatComposer = memo( focusAt: (cursor: number) => { composerEditorRef.current?.focusAt(cursor); }, + openModelPicker: () => { + setIsComposerModelPickerOpen(true); + }, + toggleModelPicker: () => { + setIsComposerModelPickerOpen((open) => !open); + }, + isModelPickerOpen: () => isComposerModelPickerOpen, readSnapshot: () => { return readComposerSnapshot(); }, @@ -1710,6 +1669,7 @@ export const ChatComposer = memo( promptRef, composerImagesRef, composerTerminalContextsRef, + isComposerModelPickerOpen, readComposerSnapshot, selectedModel, selectedModelOptionsForDispatch, @@ -1925,13 +1885,19 @@ export const ChatComposer = memo( model={selectedModelForPickerWithCustomFallback} lockedProvider={lockedProvider} providers={providerStatuses} + keybindings={keybindings} modelOptionsByProvider={modelOptionsByProvider} + terminalOpen={terminalOpen} + open={isComposerModelPickerOpen} {...(composerProviderState.modelPickerIconClassName ? { activeProviderIconClassName: composerProviderState.modelPickerIconClassName, } : {})} + onOpenChange={(open) => { + setIsComposerModelPickerOpen(open); + }} onProviderModelChange={onProviderModelSelect} /> diff --git a/apps/web/src/components/chat/ComposerCommandMenu.tsx b/apps/web/src/components/chat/ComposerCommandMenu.tsx index de7cf2b2b8..5d13e6593b 100644 --- a/apps/web/src/components/chat/ComposerCommandMenu.tsx +++ b/apps/web/src/components/chat/ComposerCommandMenu.tsx @@ -10,7 +10,6 @@ import { memo, useLayoutEffect, useMemo, useRef } from "react"; import { type ComposerSlashCommand, type ComposerTriggerKind } from "../../composer-logic"; import { formatProviderSkillInstallSource } from "~/providerSkillPresentation"; import { cn } from "~/lib/utils"; -import { Badge } from "../ui/badge"; import { Command, CommandGroup, @@ -45,14 +44,6 @@ export type ComposerCommandItem = label: string; description: string; } - | { - id: string; - type: "model"; - provider: ProviderKind; - model: string; - label: string; - description: string; - } | { id: string; type: "skill"; @@ -255,11 +246,6 @@ const ComposerCommandMenuItem = memo(function ComposerCommandMenuItem(props: { ) : null} - {props.item.type === "model" ? ( - - model - - ) : null} {props.item.label} diff --git a/apps/web/src/components/chat/ModelListRow.tsx b/apps/web/src/components/chat/ModelListRow.tsx new file mode 100644 index 0000000000..6cd097ad1f --- /dev/null +++ b/apps/web/src/components/chat/ModelListRow.tsx @@ -0,0 +1,104 @@ +import { type ProviderKind } from "@t3tools/contracts"; +import { memo } from "react"; +import { StarIcon } from "lucide-react"; +import { + getDisplayModelName, + getProviderLabel, + getTriggerDisplayModelLabel, + type ModelEsque, + PROVIDER_ICON_BY_PROVIDER, +} from "./providerIconUtils"; +import { ComboboxItem } from "../ui/combobox"; +import { Kbd } from "../ui/kbd"; +import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip"; +import { cn } from "~/lib/utils"; + +export const ModelListRow = memo(function ModelListRow(props: { + index: number; + model: ModelEsque; + provider: ProviderKind; + isFavorite: boolean; + showProvider: boolean; + preferShortName?: boolean; + useTriggerLabel?: boolean; + showNewBadge?: boolean; + jumpLabel?: string | null; + onToggleFavorite: () => void; +}) { + const ProviderIcon = PROVIDER_ICON_BY_PROVIDER[props.provider]; + + return ( + + + { + event.stopPropagation(); + props.onToggleFavorite(); + }} + onKeyDown={(event) => { + event.stopPropagation(); + }} + type="button" + aria-label={props.isFavorite ? "Remove from favorites" : "Add to favorites"} + > + + + } + /> + + {props.isFavorite ? "Remove from favorites" : "Add to favorites"} + + + +
+
+
+ + {props.useTriggerLabel + ? getTriggerDisplayModelLabel(props.model) + : getDisplayModelName( + props.model, + props.preferShortName ? { preferShortName: true } : undefined, + )} + + {props.showNewBadge ? ( + + New + + ) : null} +
+ {props.jumpLabel ? ( + + {props.jumpLabel} + + ) : null} +
+ {props.showProvider && ( +
+ + + {getProviderLabel(props.provider, props.model)} + +
+ )} +
+
+ ); +}); diff --git a/apps/web/src/components/chat/ModelPickerContent.tsx b/apps/web/src/components/chat/ModelPickerContent.tsx new file mode 100644 index 0000000000..82720425ef --- /dev/null +++ b/apps/web/src/components/chat/ModelPickerContent.tsx @@ -0,0 +1,519 @@ +import { + type ProviderKind, + PROVIDER_DISPLAY_NAMES, + type ResolvedKeybindingsConfig, + type ServerProvider, +} from "@t3tools/contracts"; +import { resolveSelectableModel } from "@t3tools/shared/model"; +import { memo, useMemo, useState, useCallback, useEffect, useLayoutEffect, useRef } from "react"; +import { SearchIcon } from "lucide-react"; +import { ModelListRow } from "./ModelListRow"; +import { ModelPickerSidebar } from "./ModelPickerSidebar"; +import { isModelPickerNewModel } from "./modelPickerModelHighlights"; +import { buildModelPickerSearchText, scoreModelPickerSearch } from "./modelPickerSearch"; +import { Combobox, ComboboxEmpty, ComboboxInput, ComboboxList } from "../ui/combobox"; +import { ModelEsque, PROVIDER_ICON_BY_PROVIDER } from "./providerIconUtils"; +import { + modelPickerJumpCommandForIndex, + modelPickerJumpIndexFromCommand, + resolveShortcutCommand, + shortcutLabelForCommand, +} from "../../keybindings"; +import { useSettings, useUpdateSettings } from "~/hooks/useSettings"; +import { cn } from "~/lib/utils"; +import { TooltipProvider } from "../ui/tooltip"; + +type ModelPickerItem = { + slug: string; + name: string; + shortName?: string; + subProvider?: string; + provider: ProviderKind; +}; + +const EMPTY_MODEL_JUMP_LABELS = new Map(); + +export const ModelPickerContent = memo(function ModelPickerContent(props: { + provider: ProviderKind; + model: string; + lockedProvider: ProviderKind | null; + providers?: ReadonlyArray; + keybindings?: ResolvedKeybindingsConfig; + modelOptionsByProvider: Record>; + terminalOpen: boolean; + onRequestClose?: () => void; + onProviderModelChange: (provider: ProviderKind, model: string) => void; +}) { + const { keybindings: providedKeybindings, modelOptionsByProvider, onProviderModelChange } = props; + const [searchQuery, setSearchQuery] = useState(""); + const searchInputRef = useRef(null); + const listRegionRef = useRef(null); + const highlightedModelKeyRef = useRef(null); + const favorites = useSettings((s) => s.favorites ?? []); + const [selectedProvider, setSelectedProvider] = useState(() => { + if (props.lockedProvider !== null) { + return props.lockedProvider; + } + return favorites.length > 0 ? "favorites" : props.provider; + }); + const keybindings = useMemo( + () => providedKeybindings ?? [], + [providedKeybindings], + ); + const { updateSettings } = useUpdateSettings(); + + const focusSearchInput = useCallback(() => { + searchInputRef.current?.focus({ preventScroll: true }); + }, []); + + const handleSelectProvider = useCallback( + (provider: ProviderKind | "favorites") => { + setSelectedProvider(provider); + window.requestAnimationFrame(() => { + focusSearchInput(); + }); + }, + [focusSearchInput], + ); + + useLayoutEffect(() => { + focusSearchInput(); + const frame = window.requestAnimationFrame(() => { + focusSearchInput(); + }); + const timeout = window.setTimeout(() => { + focusSearchInput(); + }, 0); + return () => { + window.cancelAnimationFrame(frame); + window.clearTimeout(timeout); + }; + }, [focusSearchInput]); + + // Create a Set for efficient lookup + const favoritesSet = useMemo(() => { + return new Set(favorites.map((fav) => `${fav.provider}:${fav.model}`)); + }, [favorites]); + const favoriteOrder = useMemo(() => { + return new Map( + favorites.map((favorite, index) => [`${favorite.provider}:${favorite.model}`, index]), + ); + }, [favorites]); + + const readyProviderSet = useMemo(() => { + if (!props.providers || props.providers.length === 0) { + return null; + } + return new Set( + props.providers + .filter((provider) => provider.status === "ready") + .map((provider) => provider.provider), + ); + }, [props.providers]); + + // Flatten models into a searchable array + const flatModels = useMemo(() => { + return Object.entries(props.modelOptionsByProvider).flatMap(([providerKind, models]) => { + if (readyProviderSet && !readyProviderSet.has(providerKind as ProviderKind)) { + return []; + } + return models.map((m) => ({ + slug: m.slug, + name: m.name, + ...(m.shortName ? { shortName: m.shortName } : {}), + ...(m.subProvider ? { subProvider: m.subProvider } : {}), + provider: providerKind as ProviderKind, + })) satisfies Array; + }); + }, [props.modelOptionsByProvider, readyProviderSet]); + + // Filter models based on search query and selected provider + const filteredModels = useMemo(() => { + let result = flatModels; + + // Apply tokenized fuzzy search across the combined provider/model search fields. + if (searchQuery.trim()) { + const rankedMatches = result + .map((model) => ({ + model, + score: scoreModelPickerSearch( + { + ...model, + isFavorite: favoritesSet.has(`${model.provider}:${model.slug}`), + }, + searchQuery, + ), + isFavorite: favoritesSet.has(`${model.provider}:${model.slug}`), + tieBreaker: buildModelPickerSearchText(model), + })) + .filter( + ( + rankedModel, + ): rankedModel is { + model: ModelPickerItem; + score: number; + isFavorite: boolean; + tieBreaker: string; + } => rankedModel.score !== null, + ); + + // When searching, we only respect locked provider, ignoring sidebar selection + if (props.lockedProvider !== null) { + return rankedMatches + .filter((rankedModel) => rankedModel.model.provider === props.lockedProvider) + .toSorted((a, b) => { + const scoreDelta = a.score - b.score; + if (scoreDelta !== 0) { + return scoreDelta; + } + if (a.isFavorite !== b.isFavorite) { + return a.isFavorite ? -1 : 1; + } + return a.tieBreaker.localeCompare(b.tieBreaker); + }) + .map((rankedModel) => rankedModel.model); + } + + return rankedMatches + .toSorted((a, b) => { + const scoreDelta = a.score - b.score; + if (scoreDelta !== 0) { + return scoreDelta; + } + if (a.isFavorite !== b.isFavorite) { + return a.isFavorite ? -1 : 1; + } + return a.tieBreaker.localeCompare(b.tieBreaker); + }) + .map((rankedModel) => rankedModel.model); + } + + // Locked provider mode always shows that provider's models, with favorites first. + if (props.lockedProvider !== null) { + result = result.filter((m) => m.provider === props.lockedProvider); + } else if (selectedProvider === "favorites") { + result = result.filter((m) => favoritesSet.has(`${m.provider}:${m.slug}`)); + } else { + result = result.filter((m) => m.provider === selectedProvider); + } + + return result.toSorted((a, b) => { + const aOrder = favoriteOrder.get(`${a.provider}:${a.slug}`); + const bOrder = favoriteOrder.get(`${b.provider}:${b.slug}`); + + if (aOrder !== undefined && bOrder !== undefined) { + return aOrder - bOrder; + } + if (aOrder !== undefined) { + return -1; + } + if (bOrder !== undefined) { + return 1; + } + return 0; + }); + }, [ + favoriteOrder, + favoritesSet, + flatModels, + props.lockedProvider, + searchQuery, + selectedProvider, + ]); + + const handleModelSelect = useCallback( + (modelSlug: string, provider: ProviderKind) => { + const resolvedModel = resolveSelectableModel( + provider, + modelSlug, + modelOptionsByProvider[provider], + ); + if (resolvedModel) { + onProviderModelChange(provider, resolvedModel); + } + }, + [modelOptionsByProvider, onProviderModelChange], + ); + + const toggleFavorite = useCallback( + (provider: ProviderKind, model: string) => { + const newFavorites = [...favorites]; + const index = newFavorites.findIndex((f) => f.provider === provider && f.model === model); + if (index >= 0) { + newFavorites.splice(index, 1); + } else { + newFavorites.push({ provider, model }); + } + updateSettings({ favorites: newFavorites }); + }, + [favorites, updateSettings], + ); + + const isLocked = props.lockedProvider !== null; + const isSearching = searchQuery.trim().length > 0; + const showSidebar = !isLocked && !isSearching; + const LockedProviderIcon = + isLocked && props.lockedProvider ? PROVIDER_ICON_BY_PROVIDER[props.lockedProvider] : null; + const modelJumpCommandByKey = useMemo(() => { + const mapping = new Map< + string, + NonNullable> + >(); + for (const [visibleModelIndex, model] of filteredModels.entries()) { + const jumpCommand = modelPickerJumpCommandForIndex(visibleModelIndex); + if (!jumpCommand) { + return mapping; + } + mapping.set(`${model.provider}:${model.slug}`, jumpCommand); + } + return mapping; + }, [filteredModels]); + const modelJumpModelKeys = useMemo( + () => [...modelJumpCommandByKey.keys()], + [modelJumpCommandByKey], + ); + const allModelKeys = useMemo( + (): string[] => flatModels.map((model) => `${model.provider}:${model.slug}`), + [flatModels], + ); + const filteredModelKeys = useMemo( + (): string[] => filteredModels.map((model) => `${model.provider}:${model.slug}`), + [filteredModels], + ); + const filteredModelByKey = useMemo( + (): ReadonlyMap => + new Map(filteredModels.map((model) => [`${model.provider}:${model.slug}`, model] as const)), + [filteredModels], + ); + const modelJumpShortcutContext = useMemo( + () => + ({ + terminalFocus: false, + terminalOpen: props.terminalOpen, + modelPickerOpen: true, + }) as const, + [props.terminalOpen], + ); + const modelJumpLabelByKey = useMemo((): ReadonlyMap => { + if (modelJumpCommandByKey.size === 0) { + return EMPTY_MODEL_JUMP_LABELS; + } + const shortcutLabelOptions = { + platform: navigator.platform, + context: modelJumpShortcutContext, + }; + const mapping = new Map(); + for (const [modelKey, command] of modelJumpCommandByKey) { + const label = shortcutLabelForCommand(keybindings, command, shortcutLabelOptions); + if (label) { + mapping.set(modelKey, label); + } + } + return mapping.size > 0 ? mapping : EMPTY_MODEL_JUMP_LABELS; + }, [keybindings, modelJumpCommandByKey, modelJumpShortcutContext]); + + useEffect(() => { + const onWindowKeyDown = (event: globalThis.KeyboardEvent) => { + if (event.defaultPrevented || event.repeat) { + return; + } + + const command = resolveShortcutCommand(event, keybindings, { + platform: navigator.platform, + context: modelJumpShortcutContext, + }); + const jumpIndex = modelPickerJumpIndexFromCommand(command ?? ""); + if (jumpIndex === null) { + return; + } + + const targetModelKey = modelJumpModelKeys[jumpIndex]; + if (!targetModelKey) { + return; + } + const [provider, slug] = targetModelKey.split(":") as [ProviderKind, string]; + event.preventDefault(); + event.stopPropagation(); + handleModelSelect(slug, provider); + }; + + window.addEventListener("keydown", onWindowKeyDown, true); + + return () => { + window.removeEventListener("keydown", onWindowKeyDown, true); + }; + }, [handleModelSelect, keybindings, modelJumpModelKeys, modelJumpShortcutContext]); + + useLayoutEffect(() => { + const listRegion = listRegionRef.current; + if (!listRegion) { + return; + } + + let cancelled = false; + let frame = 0; + let nestedFrame = 0; + let timeout = 0; + + const measureScrollArea = () => { + if (cancelled) { + return; + } + const viewport = listRegion.querySelector('[data-slot="scroll-area-viewport"]'); + if (!viewport || viewport.scrollHeight <= viewport.clientHeight) { + return; + } + const originalScrollTop = viewport.scrollTop; + const maxScrollTop = viewport.scrollHeight - viewport.clientHeight; + if (maxScrollTop <= 0) { + return; + } + viewport.scrollTop = Math.min(originalScrollTop + 1, maxScrollTop); + viewport.scrollTop = originalScrollTop; + }; + + queueMicrotask(measureScrollArea); + frame = window.requestAnimationFrame(() => { + measureScrollArea(); + nestedFrame = window.requestAnimationFrame(measureScrollArea); + }); + timeout = window.setTimeout(measureScrollArea, 0); + + return () => { + cancelled = true; + window.cancelAnimationFrame(frame); + window.cancelAnimationFrame(nestedFrame); + window.clearTimeout(timeout); + }; + }, [filteredModelKeys]); + + return ( + +
+ {/* Locked provider header (only shown in locked mode) */} + {isLocked && LockedProviderIcon && props.lockedProvider && ( +
+ + + {PROVIDER_DISPLAY_NAMES[props.lockedProvider]} + +
+ )} + + {/* Sidebar (only in unlocked mode) */} + {showSidebar && ( + + )} + + {/* Main content area */} + { + highlightedModelKeyRef.current = typeof modelKey === "string" ? modelKey : null; + }} + onValueChange={(modelKey) => { + if (typeof modelKey !== "string") { + return; + } + const [provider, slug] = modelKey.split(":") as [ProviderKind, string]; + handleModelSelect(slug, provider); + }} + > +
+ {/* Search bar */} +
+ } + value={searchQuery} + onChange={(e) => setSearchQuery(e.target.value)} + onKeyDown={(e) => { + if (e.key === "Escape") { + e.preventDefault(); + e.stopPropagation(); + props.onRequestClose?.(); + return; + } + if (e.key === "Enter" && highlightedModelKeyRef.current) { + ( + e as typeof e & { preventBaseUIHandler?: () => void } + ).preventBaseUIHandler?.(); + e.preventDefault(); + e.stopPropagation(); + const [provider, slug] = highlightedModelKeyRef.current.split(":") as [ + ProviderKind, + string, + ]; + handleModelSelect(slug, provider); + return; + } + e.stopPropagation(); + }} + onMouseDown={(e) => e.stopPropagation()} + onTouchStart={(e) => e.stopPropagation()} + size="sm" + /> +
+ + {/* Model list */} +
+ + {filteredModelKeys.map((modelKey, index) => { + const model = filteredModelByKey.get(modelKey); + if (!model) { + return null; + } + return ( + toggleFavorite(model.provider, model.slug)} + /> + ); + })} + +
+ + No models found + +
+
+
+
+ ); +}); diff --git a/apps/web/src/components/chat/ModelPickerSidebar.tsx b/apps/web/src/components/chat/ModelPickerSidebar.tsx new file mode 100644 index 0000000000..b4f23cacdd --- /dev/null +++ b/apps/web/src/components/chat/ModelPickerSidebar.tsx @@ -0,0 +1,210 @@ +import { type ProviderKind, type ServerProvider } from "@t3tools/contracts"; +import { memo } from "react"; +import { Clock3Icon, SparklesIcon, StarIcon } from "lucide-react"; +import { Gemini, GithubCopilotIcon } from "../Icons"; +import { AVAILABLE_PROVIDER_OPTIONS, PROVIDER_ICON_BY_PROVIDER } from "./providerIconUtils"; +import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip"; +import { cn } from "~/lib/utils"; +import { getProviderSnapshot } from "../../providerModels"; + +function describeUnavailableProvider(label: string, live: ServerProvider | undefined): string { + if (!live) { + return `${label} — waiting for provider status…`; + } + if (live.status === "ready") { + return label; + } + const kind = + live.status === "error" + ? "Unavailable" + : live.status === "warning" + ? "Limited" + : live.status === "disabled" + ? "Disabled in settings" + : "Not ready"; + const msg = live.message?.trim(); + return msg ? `${label} — ${kind}. ${msg}` : `${label} — ${kind}.`; +} + +const SELECTED_BUTTON_CLASS = "bg-background text-foreground shadow-sm"; +const SELECTED_INDICATOR_CLASS = + "pointer-events-none absolute -right-1 top-1/2 z-10 h-5 w-0.5 -translate-y-1/2 rounded-l-full bg-primary"; +const BADGE_BASE_CLASS = + "pointer-events-none absolute -right-0.5 top-0.5 z-10 flex size-3.5 items-center justify-center rounded-full bg-transparent shadow-sm "; +const NEW_BADGE_CLASS = `${BADGE_BASE_CLASS} text-amber-600 dark:text-amber-300 `; +const SOON_BADGE_CLASS = `${BADGE_BASE_CLASS} text-muted-foreground `; + +/** Opens toward the rail so the list stays readable (not over the model names). */ +const PICKER_TOOLTIP_SIDE = "left" as const; +const PICKER_TOOLTIP_CLASS = "max-w-64 text-balance font-normal leading-snug"; + +export const ModelPickerSidebar = memo(function ModelPickerSidebar(props: { + selectedProvider: ProviderKind | "favorites"; + onSelectProvider: (provider: ProviderKind | "favorites") => void; + providers?: ReadonlyArray; +}) { + const handleProviderClick = (provider: ProviderKind | "favorites") => { + props.onSelectProvider(provider); + }; + + return ( +
+ {/* Favorites section */} +
+
+ {props.selectedProvider === "favorites" &&
} + + handleProviderClick("favorites")} + type="button" + data-model-picker-provider="favorites" + aria-label="Favorites" + > + + + } + /> + + Favorites + + +
+
+ + {/* Provider buttons */} + {AVAILABLE_PROVIDER_OPTIONS.map((option) => { + const OptionIcon = PROVIDER_ICON_BY_PROVIDER[option.value]; + const liveProvider = props.providers + ? getProviderSnapshot(props.providers, option.value) + : undefined; + + const isDisabled = !liveProvider || liveProvider.status !== "ready"; + const isSelected = props.selectedProvider === option.value; + const badge = option.pickerSidebarBadge; + + const providerTooltip = isDisabled + ? describeUnavailableProvider(option.label, liveProvider) + : badge === "new" + ? `${option.label} — New` + : option.label; + + const button = ( + + ); + + const trigger = isDisabled ? ( + {button} + ) : ( + button + ); + + return ( +
+ {isSelected &&
} + + + + {providerTooltip} + + +
+ ); + })} + + {/* Gemini button (coming soon) */} + + + + + } + /> + + Gemini — Coming soon + + + {/* Github Copilot button (coming soon) */} + + + + + } + /> + + Github Copilot — Coming soon + + +
+ ); +}); diff --git a/apps/web/src/components/chat/ProviderModelPicker.browser.tsx b/apps/web/src/components/chat/ProviderModelPicker.browser.tsx index abedcd6eeb..f4854dd9a6 100644 --- a/apps/web/src/components/chat/ProviderModelPicker.browser.tsx +++ b/apps/web/src/components/chat/ProviderModelPicker.browser.tsx @@ -1,11 +1,70 @@ import { type ProviderKind, type ServerProvider } from "@t3tools/contracts"; -import { page } from "vitest/browser"; -import { afterEach, describe, expect, it, vi } from "vitest"; +import { EnvironmentId } from "@t3tools/contracts"; +import { page, userEvent } from "vitest/browser"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import { render } from "vitest-browser-react"; import { ProviderModelPicker } from "./ProviderModelPicker"; import { getCustomModelOptionsByProvider } from "../../modelSelection"; -import { DEFAULT_UNIFIED_SETTINGS } from "@t3tools/contracts/settings"; +import { DEFAULT_CLIENT_SETTINGS, DEFAULT_UNIFIED_SETTINGS } from "@t3tools/contracts/settings"; +import { __resetLocalApiForTests } from "../../localApi"; + +// Mock the environments/runtime module to provide a mock primary environment connection +vi.mock("../../environments/runtime", () => { + const primaryConnection = { + kind: "primary" as const, + knownEnvironment: { + id: "environment-local", + label: "Local environment", + source: "manual" as const, + environmentId: EnvironmentId.make("environment-local"), + target: { + httpBaseUrl: "http://localhost:3000", + wsBaseUrl: "ws://localhost:3000", + }, + }, + environmentId: EnvironmentId.make("environment-local"), + client: { + server: { + getConfig: vi.fn(), + updateSettings: vi.fn(), + }, + }, + ensureBootstrapped: async () => undefined, + reconnect: async () => undefined, + dispose: async () => undefined, + }; + + return { + getEnvironmentHttpBaseUrl: () => "http://localhost:3000", + getSavedEnvironmentRecord: () => null, + getSavedEnvironmentRuntimeState: () => null, + hasSavedEnvironmentRegistryHydrated: () => true, + listSavedEnvironmentRecords: () => [], + resetSavedEnvironmentRegistryStoreForTests: vi.fn(), + resetSavedEnvironmentRuntimeStoreForTests: vi.fn(), + resolveEnvironmentHttpUrl: (_environmentId: unknown, path: string) => + new URL(path, "http://localhost:3000").toString(), + waitForSavedEnvironmentRegistryHydration: async () => undefined, + addSavedEnvironment: vi.fn(), + disconnectSavedEnvironment: vi.fn(), + ensureEnvironmentConnectionBootstrapped: async () => undefined, + getPrimaryEnvironmentConnection: () => primaryConnection, + readEnvironmentConnection: () => primaryConnection, + reconnectSavedEnvironment: vi.fn(), + removeSavedEnvironment: vi.fn(), + requireEnvironmentConnection: () => primaryConnection, + resetEnvironmentServiceForTests: vi.fn(), + startEnvironmentConnectionService: vi.fn(), + subscribeEnvironmentConnections: () => () => {}, + useSavedEnvironmentRegistryStore: ( + selector: (state: { byId: Record }) => unknown, + ) => selector({ byId: {} }), + useSavedEnvironmentRuntimeStore: ( + selector: (state: { byId: Record }) => unknown, + ) => selector({ byId: {} }), + }; +}); function effort(value: string, isDefault = false) { return { @@ -129,6 +188,21 @@ function buildCodexProvider(models: ServerProvider["models"]): ServerProvider { }; } +function buildOpenCodeProvider(models: ServerProvider["models"]): ServerProvider { + return { + provider: "opencode", + enabled: true, + installed: true, + version: "1.0.0", + status: "ready", + auth: { status: "authenticated" }, + checkedAt: new Date().toISOString(), + models, + slashCommands: [], + skills: [], + }; +} + async function mountPicker(props: { provider: ProviderKind; model: string; @@ -168,12 +242,40 @@ async function mountPicker(props: { }; } +function getModelPickerListElement() { + const modelPickerList = document.querySelector(".model-picker-list"); + expect(modelPickerList).not.toBeNull(); + return modelPickerList!; +} + +function getModelPickerListText() { + return getModelPickerListElement().textContent ?? ""; +} + +function getVisibleModelNames() { + return Array.from(getModelPickerListElement().querySelectorAll("div.font-medium")) + .map((element) => element.textContent?.replace(/New$/u, "").trim() ?? "") + .filter((text) => text.length > 0); +} + +function getSidebarProviderOrder() { + return Array.from(document.querySelectorAll("[data-model-picker-provider]")).map( + (element) => element.dataset.modelPickerProvider ?? "", + ); +} + describe("ProviderModelPicker", () => { - afterEach(() => { - document.body.innerHTML = ""; + beforeEach(async () => { + // Reset test environment before each test + await __resetLocalApiForTests(); }); - it("shows provider submenus when provider switching is allowed", async () => { + afterEach(async () => { + document.body.innerHTML = ""; + await __resetLocalApiForTests(); + }); + + it("shows provider sidebar in unlocked mode", async () => { const mounted = await mountPicker({ provider: "claudeAgent", model: "claude-opus-4-6", @@ -185,16 +287,16 @@ describe("ProviderModelPicker", () => { await vi.waitFor(() => { const text = document.body.textContent ?? ""; - expect(text).toContain("Codex"); + expect(text).not.toContain("Codex"); expect(text).toContain("Claude"); - expect(text).not.toContain("Claude Sonnet 4.6"); + expect(text).toContain("Claude Opus 4.6"); }); } finally { await mounted.cleanup(); } }); - it("opens provider submenus with a visible gap from the parent menu", async () => { + it("shows favorites first in the provider sidebar", async () => { const mounted = await mountPicker({ provider: "claudeAgent", model: "claude-opus-4-6", @@ -203,43 +305,575 @@ describe("ProviderModelPicker", () => { try { await page.getByRole("button").click(); - const providerTrigger = page.getByRole("menuitem", { name: "Codex" }); - await providerTrigger.hover(); await vi.waitFor(() => { - expect(document.body.textContent ?? "").toContain("GPT-5 Codex"); + expect(getSidebarProviderOrder().slice(0, 3)).toEqual([ + "favorites", + "codex", + "claudeAgent", + ]); }); - - const providerTriggerElement = Array.from( - document.querySelectorAll('[role="menuitem"]'), - ).find((element) => element.textContent?.includes("Codex")); - if (!providerTriggerElement) { - throw new Error("Expected the Codex provider trigger to be mounted."); - } - - const providerTriggerRect = providerTriggerElement.getBoundingClientRect(); - const modelElement = Array.from( - document.querySelectorAll('[role="menuitemradio"]'), - ).find((element) => element.textContent?.includes("GPT-5 Codex")); - if (!modelElement) { - throw new Error("Expected the submenu model option to be mounted."); - } - - const submenuPopup = modelElement.closest('[data-slot="menu-sub-content"]'); - if (!(submenuPopup instanceof HTMLElement)) { - throw new Error("Expected submenu popup to be mounted."); - } - - const submenuRect = submenuPopup.getBoundingClientRect(); - - expect(submenuRect.left).toBeGreaterThanOrEqual(providerTriggerRect.right); - expect(submenuRect.left - providerTriggerRect.right).toBeGreaterThanOrEqual(2); } finally { await mounted.cleanup(); } }); - it("shows models directly when the provider is locked mid-thread", async () => { + it("filters models by selected provider in sidebar", async () => { + const mounted = await mountPicker({ + provider: "claudeAgent", + model: "claude-opus-4-6", + lockedProvider: null, + }); + + try { + await page.getByRole("button").click(); + + // Start with Claude models visible + await vi.waitFor(() => { + const text = document.body.textContent ?? ""; + expect(text).not.toContain("GPT-5 Codex"); + expect(text).toContain("Claude Opus 4.6"); + }); + + // Click on Codex provider in sidebar + await vi.waitFor(() => { + expect(document.querySelector('[data-model-picker-provider="codex"]')).not.toBeNull(); + }); + await page.getByRole("button", { name: "Codex", exact: true }).click(); + + // Now should only show Codex models + await vi.waitFor(() => { + const listText = getModelPickerListText(); + expect(listText).toContain("GPT-5 Codex"); + expect(listText).not.toContain("Claude Opus 4.6"); + }); + } finally { + await mounted.cleanup(); + } + }); + + it("focuses the search input after selecting a sidebar provider", async () => { + const mounted = await mountPicker({ + provider: "claudeAgent", + model: "claude-opus-4-6", + lockedProvider: null, + }); + + try { + await page.getByRole("button").click(); + + await vi.waitFor(() => { + expect(document.querySelector('[data-model-picker-provider="codex"]')).not.toBeNull(); + }); + await page.getByRole("button", { name: "Codex", exact: true }).click(); + + await vi.waitFor(() => { + const searchInput = document.querySelector( + 'input[placeholder="Search models..."]', + ); + expect(searchInput).not.toBeNull(); + expect(document.activeElement).toBe(searchInput); + }); + } finally { + await mounted.cleanup(); + } + }); + + it("shows locked provider header and only its models in locked mode", async () => { + localStorage.setItem( + "t3code:client-settings:v1", + JSON.stringify({ + ...DEFAULT_CLIENT_SETTINGS, + favorites: [ + { provider: "codex", model: "gpt-5-codex" }, + { provider: "claudeAgent", model: "claude-sonnet-4-6" }, + ], + }), + ); + + const mounted = await mountPicker({ + provider: "claudeAgent", + model: "claude-opus-4-6", + lockedProvider: "claudeAgent", + }); + + try { + await page.getByRole("button").click(); + + await vi.waitFor(() => { + const text = document.body.textContent ?? ""; + // Should show locked provider label + expect(text).toContain("Claude"); + expect(getVisibleModelNames()).toEqual([ + "Claude Sonnet 4.6", + "Claude Opus 4.6", + "Claude Haiku 4.5", + ]); + }); + } finally { + localStorage.removeItem("t3code:client-settings:v1"); + await mounted.cleanup(); + } + }); + + it("falls back to the active provider's first model when props.model belongs to another provider (#1982)", async () => { + const host = document.createElement("div"); + document.body.append(host); + const onProviderModelChange = vi.fn(); + const modelOptionsByProvider = { + claudeAgent: [ + { slug: "claude-opus-4-6", name: "Claude Opus 4.6" }, + { slug: "claude-sonnet-4-6", name: "Claude Sonnet 4.6" }, + ], + codex: [{ slug: "gpt-5-codex", name: "GPT-5 Codex" }], + cursor: [], + opencode: [], + } as const; + const screen = await render( + , + { container: host }, + ); + + try { + const trigger = document.querySelector( + '[data-chat-provider-model-picker="true"]', + ); + expect(trigger).not.toBeNull(); + const label = trigger?.textContent ?? ""; + expect(label).not.toContain("gpt-5-codex"); + expect(label).toContain("Claude Opus 4.6"); + } finally { + await screen.unmount(); + host.remove(); + } + }); + + it("uses the trigger label for locked opencode rows", async () => { + const providers: ReadonlyArray = [ + buildOpenCodeProvider([ + { + slug: "github-copilot/claude-opus-4.5", + name: "Claude Opus 4.5", + subProvider: "GitHub Copilot", + shortName: "Opus 4.5", + isCustom: false, + capabilities: { + reasoningEffortLevels: [effort("low"), effort("medium", true), effort("high")], + supportsFastMode: false, + supportsThinkingToggle: false, + contextWindowOptions: [], + promptInjectedEffortLevels: [], + }, + }, + ]), + ]; + const mounted = await mountPicker({ + provider: "opencode", + model: "github-copilot/claude-opus-4.5", + lockedProvider: "opencode", + providers, + }); + + try { + await vi.waitFor(() => { + const trigger = document.querySelector( + '[data-chat-provider-model-picker="true"]', + ); + expect(trigger?.textContent).toContain("GitHub Copilot"); + expect(trigger?.textContent).toContain("Opus 4.5"); + }); + + await page.getByRole("button").click(); + + await vi.waitFor(() => { + expect(getVisibleModelNames()).toEqual(["GitHub Copilot · Opus 4.5"]); + }); + } finally { + await mounted.cleanup(); + } + }); + + it("searches models by name in flat list", async () => { + const mounted = await mountPicker({ + provider: "claudeAgent", + model: "claude-opus-4-6", + lockedProvider: null, + }); + + try { + await page.getByRole("button").click(); + + await vi.waitFor(() => { + const text = document.body.textContent ?? ""; + expect(text).toContain("Claude Opus 4.6"); + expect(text).not.toContain("GPT-5 Codex"); + }); + + // Find and type in search box + const searchInput = page.getByPlaceholder("Search models..."); + await searchInput.fill("claude"); + + await vi.waitFor(() => { + const text = document.body.textContent ?? ""; + expect(text).toContain("Claude Opus 4.6"); + expect(text).not.toContain("GPT-5 Codex"); + }); + } finally { + await mounted.cleanup(); + } + }); + + it("supports arrow-key navigation in the model picker", async () => { + const mounted = await mountPicker({ + provider: "claudeAgent", + model: "claude-opus-4-6", + lockedProvider: "claudeAgent", + }); + + try { + await page.getByRole("button").click(); + + const searchInput = page.getByPlaceholder("Search models..."); + await userEvent.click(searchInput); + await userEvent.keyboard("{ArrowDown}"); + await vi.waitFor(() => { + const highlightedItem = document.querySelector( + '[data-slot="combobox-item"][data-highlighted]', + ); + expect(highlightedItem).not.toBeNull(); + expect(highlightedItem?.textContent).toContain("Claude Opus 4.6"); + }); + await userEvent.keyboard("{ArrowDown}"); + await vi.waitFor(() => { + const highlightedItem = document.querySelector( + '[data-slot="combobox-item"][data-highlighted]', + ); + expect(highlightedItem).not.toBeNull(); + expect(highlightedItem?.textContent).toContain("Claude Sonnet 4.6"); + }); + await userEvent.keyboard("{Enter}"); + + expect(mounted.onProviderModelChange).toHaveBeenCalledWith( + "claudeAgent", + "claude-sonnet-4-6", + ); + } finally { + await mounted.cleanup(); + } + }); + + it("hides the provider sidebar while searching", async () => { + const mounted = await mountPicker({ + provider: "claudeAgent", + model: "claude-opus-4-6", + lockedProvider: null, + }); + + try { + await page.getByRole("button").click(); + + await vi.waitFor(() => { + expect(getSidebarProviderOrder().length).toBeGreaterThan(0); + }); + + await page.getByPlaceholder("Search models...").fill("cla"); + + await vi.waitFor(() => { + expect(getSidebarProviderOrder()).toEqual([]); + }); + } finally { + await mounted.cleanup(); + } + }); + + it("closes the picker when escape is pressed in search", async () => { + const mounted = await mountPicker({ + provider: "claudeAgent", + model: "claude-opus-4-6", + lockedProvider: null, + }); + + try { + await page.getByRole("button").click(); + + const searchInput = page.getByPlaceholder("Search models..."); + await searchInput.click(); + const searchInputElement = document.querySelector( + 'input[placeholder="Search models..."]', + ); + expect(searchInputElement).not.toBeNull(); + searchInputElement!.dispatchEvent( + new KeyboardEvent("keydown", { key: "Escape", bubbles: true }), + ); + + await vi.waitFor(() => { + expect(document.querySelector(".model-picker-list")).toBeNull(); + }); + } finally { + await mounted.cleanup(); + } + }); + + it("searches models by provider name", async () => { + const mounted = await mountPicker({ + provider: "claudeAgent", + model: "claude-opus-4-6", + lockedProvider: null, + }); + + try { + await page.getByRole("button").click(); + + await vi.waitFor(() => { + const text = document.body.textContent ?? ""; + expect(text).toContain("Claude Opus 4.6"); + expect(text).not.toContain("GPT-5 Codex"); + }); + + // Search by provider name + const searchInput = page.getByPlaceholder("Search models..."); + await searchInput.fill("codex"); + + await vi.waitFor(() => { + const listText = getModelPickerListText(); + expect(listText).toContain("GPT-5 Codex"); + expect(listText).not.toContain("Claude Opus 4.6"); + }); + } finally { + await mounted.cleanup(); + } + }); + + it("matches fuzzy multi-token queries across provider and model text", async () => { + const providers: ReadonlyArray = [ + buildCodexProvider([ + { + slug: "gpt-5-codex", + name: "GPT-5 Codex", + isCustom: false, + capabilities: { + reasoningEffortLevels: [effort("low"), effort("medium", true), effort("high")], + supportsFastMode: true, + supportsThinkingToggle: false, + contextWindowOptions: [], + promptInjectedEffortLevels: [], + }, + }, + ]), + buildOpenCodeProvider([ + { + slug: "github-copilot/claude-opus-4.7", + name: "Claude Opus 4.7", + subProvider: "GitHub Copilot", + isCustom: false, + capabilities: { + reasoningEffortLevels: [effort("low"), effort("medium", true), effort("high")], + supportsFastMode: false, + supportsThinkingToggle: false, + contextWindowOptions: [], + promptInjectedEffortLevels: [], + }, + }, + ]), + ]; + const mounted = await mountPicker({ + provider: "opencode", + model: "github-copilot/claude-opus-4.7", + lockedProvider: null, + providers, + }); + + try { + await page.getByRole("button").click(); + await page.getByPlaceholder("Search models...").fill("coplt op"); + + await vi.waitFor(() => { + const listText = getModelPickerListText(); + expect(listText).toContain("Claude Opus 4.7"); + expect(listText).not.toContain("GPT-5 Codex"); + }); + } finally { + await mounted.cleanup(); + } + }); + + it("renders each search result with its own provider branding", async () => { + const providers: ReadonlyArray = [ + buildOpenCodeProvider([ + { + slug: "github-copilot/claude-opus-4.7", + name: "Claude Opus 4.7", + subProvider: "GitHub Copilot", + isCustom: false, + capabilities: { + reasoningEffortLevels: [effort("low"), effort("medium", true), effort("high")], + supportsFastMode: false, + supportsThinkingToggle: false, + contextWindowOptions: [], + promptInjectedEffortLevels: [], + }, + }, + ]), + { + ...TEST_PROVIDERS[1]!, + models: [ + { + slug: "claude-opus-4-6", + name: "Claude Opus 4.6", + isCustom: false, + capabilities: { + reasoningEffortLevels: [ + effort("low"), + effort("medium", true), + effort("high"), + effort("max"), + ], + supportsFastMode: false, + supportsThinkingToggle: true, + contextWindowOptions: [], + promptInjectedEffortLevels: [], + }, + }, + ], + }, + ]; + const mounted = await mountPicker({ + provider: "opencode", + model: "github-copilot/claude-opus-4.7", + lockedProvider: null, + providers, + }); + + try { + await page.getByRole("button").click(); + await page.getByPlaceholder("Search models...").fill("opus"); + + await vi.waitFor(() => { + const listText = getModelPickerListText(); + expect(listText).toContain("OpenCode · GitHub Copilot"); + expect(listText).toContain("Claude"); + expect(listText).not.toContain("OpenCodeClaude Opus 4.6"); + }); + } finally { + await mounted.cleanup(); + } + }); + + it("toggles favorite stars when clicked", async () => { + localStorage.removeItem("t3code:client-settings:v1"); + + const mounted = await mountPicker({ + provider: "claudeAgent", + model: "claude-opus-4-6", + lockedProvider: null, + }); + + try { + await page.getByRole("button").click(); + + await vi.waitFor(() => { + const text = document.body.textContent ?? ""; + expect(text).toContain("Claude Opus 4.6"); + }); + + const getFirstStarButton = () => { + const starButton = document.querySelector( + 'button[aria-label*="favorites"]', + ); + expect(starButton).not.toBeNull(); + return starButton!; + }; + + const firstStar = getFirstStarButton(); + const initialAriaLabel = firstStar.getAttribute("aria-label"); + expect( + initialAriaLabel === "Add to favorites" || initialAriaLabel === "Remove from favorites", + ).toBe(true); + + await page.getByRole("button", { name: initialAriaLabel! }).first().click(); + + const expectedAriaLabel = + initialAriaLabel === "Add to favorites" ? "Remove from favorites" : "Add to favorites"; + + await vi.waitFor(() => { + expect(getFirstStarButton().getAttribute("aria-label")).toBe(expectedAriaLabel); + }); + } finally { + await mounted.cleanup(); + localStorage.removeItem("t3code:client-settings:v1"); + } + }); + + it("does not duplicate favorited models across favorites and all models sections", async () => { + localStorage.removeItem("t3code:client-settings:v1"); + + const mounted = await mountPicker({ + provider: "claudeAgent", + model: "claude-opus-4-6", + lockedProvider: null, + }); + + try { + await page.getByRole("button").click(); + + await vi.waitFor(() => { + const text = document.body.textContent ?? ""; + expect(text).toContain("Claude Opus 4.6"); + }); + + const favoriteButton = page.getByRole("button", { + name: "Add to favorites", + }); + await favoriteButton.first().click(); + + await vi.waitFor(async () => { + const favoritedModelRows = Array.from( + getModelPickerListElement().querySelectorAll("div.font-medium"), + ).filter((element) => element.textContent?.trim() === "Claude Opus 4.6"); + expect(favoritedModelRows.length).toBe(1); + }); + } finally { + await mounted.cleanup(); + localStorage.removeItem("t3code:client-settings:v1"); + } + }); + + it("shows favorited models first within the selected provider list", async () => { + localStorage.setItem( + "t3code:client-settings:v1", + JSON.stringify({ + ...DEFAULT_CLIENT_SETTINGS, + favorites: [{ provider: "codex", model: "gpt-5.3-codex" }], + }), + ); + + const mounted = await mountPicker({ + provider: "codex", + model: "gpt-5-codex", + lockedProvider: null, + }); + + try { + await page.getByRole("button").click(); + await page.getByRole("button", { name: "Codex", exact: true }).click(); + + await vi.waitFor(() => { + expect(getVisibleModelNames().slice(0, 2)).toEqual(["GPT-5.3 Codex", "GPT-5 Codex"]); + }); + } finally { + await mounted.cleanup(); + localStorage.removeItem("t3code:client-settings:v1"); + } + }); + + it("dispatches callback with correct provider and model when selected", async () => { const mounted = await mountPicker({ provider: "claudeAgent", model: "claude-opus-4-6", @@ -252,15 +886,23 @@ describe("ProviderModelPicker", () => { await vi.waitFor(() => { const text = document.body.textContent ?? ""; expect(text).toContain("Claude Sonnet 4.6"); - expect(text).toContain("Claude Haiku 4.5"); - expect(text).not.toContain("Codex"); }); + + // Click on a model + const modelRow = page.getByText("Claude Sonnet 4.6").first(); + await modelRow.click(); + + // Verify callback was called with correct values + expect(mounted.onProviderModelChange).toHaveBeenCalledWith( + "claudeAgent", + "claude-sonnet-4-6", + ); } finally { await mounted.cleanup(); } }); - it("only shows codex spark when the server reports it for the account", async () => { + it("only shows codex spark when the server reports it", async () => { const providersWithoutSpark: ReadonlyArray = [ buildCodexProvider([ { @@ -309,15 +951,14 @@ describe("ProviderModelPicker", () => { ]; const hidden = await mountPicker({ - provider: "claudeAgent", - model: "claude-opus-4-6", + provider: "codex", + model: "gpt-5.3-codex", lockedProvider: null, providers: providersWithoutSpark, }); try { await page.getByRole("button").click(); - await page.getByRole("menuitem", { name: "Codex" }).hover(); await vi.waitFor(() => { const text = document.body.textContent ?? ""; @@ -329,15 +970,14 @@ describe("ProviderModelPicker", () => { } const visible = await mountPicker({ - provider: "claudeAgent", - model: "claude-opus-4-6", + provider: "codex", + model: "gpt-5.3-codex", lockedProvider: null, providers: providersWithSpark, }); try { await page.getByRole("button").click(); - await page.getByRole("menuitem", { name: "Codex" }).hover(); await vi.waitFor(() => { expect(document.body.textContent ?? "").toContain("GPT-5.3 Codex Spark"); @@ -347,27 +987,7 @@ describe("ProviderModelPicker", () => { } }); - it("dispatches the canonical slug when a model is selected", async () => { - const mounted = await mountPicker({ - provider: "claudeAgent", - model: "claude-opus-4-6", - lockedProvider: "claudeAgent", - }); - - try { - await page.getByRole("button").click(); - await page.getByRole("menuitemradio", { name: "Claude Sonnet 4.6" }).click(); - - expect(mounted.onProviderModelChange).toHaveBeenCalledWith( - "claudeAgent", - "claude-sonnet-4-6", - ); - } finally { - await mounted.cleanup(); - } - }); - - it("shows disabled providers as non-selectable entries", async () => { + it("shows disabled providers grayed out in sidebar", async () => { const disabledProviders = TEST_PROVIDERS.slice(); const claudeIndex = disabledProviders.findIndex( (provider) => provider.provider === "claudeAgent", @@ -380,6 +1000,7 @@ describe("ProviderModelPicker", () => { status: "disabled", }; } + const mounted = await mountPicker({ provider: "codex", model: "gpt-5-codex", @@ -392,9 +1013,9 @@ describe("ProviderModelPicker", () => { await vi.waitFor(() => { const text = document.body.textContent ?? ""; - expect(text).toContain("Claude"); - expect(text).toContain("Disabled"); - expect(text).not.toContain("Claude Sonnet 4.6"); + expect(text).toContain("GPT-5 Codex"); + // Disabled provider should not have its models shown + expect(text).not.toContain("Claude Opus 4.6"); }); } finally { await mounted.cleanup(); diff --git a/apps/web/src/components/chat/ProviderModelPicker.tsx b/apps/web/src/components/chat/ProviderModelPicker.tsx index 8b20237a83..4f4140f834 100644 --- a/apps/web/src/components/chat/ProviderModelPicker.tsx +++ b/apps/web/src/components/chat/ProviderModelPicker.tsx @@ -1,87 +1,78 @@ -import { type ProviderKind, type ServerProvider } from "@t3tools/contracts"; -import { resolveSelectableModel } from "@t3tools/shared/model"; -import { memo, useState } from "react"; +import { + type ProviderKind, + type ResolvedKeybindingsConfig, + type ServerProvider, +} from "@t3tools/contracts"; +import { memo, useEffect, useState } from "react"; import type { VariantProps } from "class-variance-authority"; -import { type ProviderPickerKind, PROVIDER_OPTIONS } from "../../session-logic"; import { ChevronDownIcon } from "lucide-react"; import { Button, buttonVariants } from "../ui/button"; -import { - Menu, - MenuGroup, - MenuItem, - MenuPopup, - MenuRadioGroup, - MenuRadioItem, - MenuSeparator as MenuDivider, - MenuSub, - MenuSubPopup, - MenuSubTrigger, - MenuTrigger, -} from "../ui/menu"; -import { ClaudeAI, CursorIcon, Gemini, Icon, OpenAI, OpenCodeIcon } from "../Icons"; +import { Popover, PopoverPopup, PopoverTrigger } from "../ui/popover"; +import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip"; import { cn } from "~/lib/utils"; -import { getProviderSnapshot } from "../../providerModels"; - -function isAvailableProviderOption(option: (typeof PROVIDER_OPTIONS)[number]): option is { - value: ProviderKind; - label: string; - available: true; -} { - return option.available; -} - -const PROVIDER_ICON_BY_PROVIDER: Record = { - codex: OpenAI, - claudeAgent: ClaudeAI, - opencode: OpenCodeIcon, - cursor: CursorIcon, -}; - -export const AVAILABLE_PROVIDER_OPTIONS = PROVIDER_OPTIONS.filter(isAvailableProviderOption); -const UNAVAILABLE_PROVIDER_OPTIONS = PROVIDER_OPTIONS.filter((option) => !option.available); -const COMING_SOON_PROVIDER_OPTIONS = [{ id: "gemini", label: "Gemini", icon: Gemini }] as const; - -function providerIconClassName( - provider: ProviderKind | ProviderPickerKind, - fallbackClassName: string, -): string { - return provider === "claudeAgent" ? "text-[#d97757]" : fallbackClassName; -} +import { ModelPickerContent } from "./ModelPickerContent"; +import { + ModelEsque, + PROVIDER_ICON_BY_PROVIDER, + getTriggerDisplayModelLabel, + getTriggerDisplayModelName, +} from "./providerIconUtils"; +import { setModelPickerOpen } from "../../modelPickerOpenState"; export const ProviderModelPicker = memo(function ProviderModelPicker(props: { provider: ProviderKind; model: string; lockedProvider: ProviderKind | null; providers?: ReadonlyArray; - modelOptionsByProvider: Record>; + keybindings?: ResolvedKeybindingsConfig; + modelOptionsByProvider: Record>; activeProviderIconClassName?: string; compact?: boolean; disabled?: boolean; + terminalOpen?: boolean; + open?: boolean; triggerVariant?: VariantProps["variant"]; triggerClassName?: string; + onOpenChange?: (open: boolean) => void; onProviderModelChange: (provider: ProviderKind, model: string) => void; }) { - const [isMenuOpen, setIsMenuOpen] = useState(false); + const [uncontrolledIsMenuOpen, setUncontrolledIsMenuOpen] = useState(false); const activeProvider = props.lockedProvider ?? props.provider; + const isMenuOpen = props.open ?? uncontrolledIsMenuOpen; const selectedProviderOptions = props.modelOptionsByProvider[activeProvider]; - const selectedModelLabel = - selectedProviderOptions.find((option) => option.slug === props.model)?.name ?? props.model; + // If the current slug belongs to a different provider (for example after a provider + // switch or disable), prefer the active provider's first option so the trigger icon + // and label stay in sync instead of showing a stale foreign slug. + const selectedModel = + selectedProviderOptions.find((option) => option.slug === props.model) ?? + selectedProviderOptions[0]; const ProviderIcon = PROVIDER_ICON_BY_PROVIDER[activeProvider]; - const handleModelChange = (provider: ProviderKind, value: string) => { + const triggerTitle = selectedModel ? getTriggerDisplayModelName(selectedModel) : props.model; + const triggerSubtitle = selectedModel?.subProvider; + const triggerLabel = selectedModel ? getTriggerDisplayModelLabel(selectedModel) : props.model; + + const setIsMenuOpen = (open: boolean) => { + props.onOpenChange?.(open); + if (props.open === undefined) { + setUncontrolledIsMenuOpen(open); + } + }; + + useEffect(() => { + setModelPickerOpen(isMenuOpen); + return () => { + setModelPickerOpen(false); + }; + }, [isMenuOpen]); + + const handleProviderModelChange = (provider: ProviderKind, model: string) => { if (props.disabled) return; - if (!value) return; - const resolvedModel = resolveSelectableModel( - provider, - value, - props.modelOptionsByProvider[provider], - ); - if (!resolvedModel) return; - props.onProviderModelChange(provider, resolvedModel); + props.onProviderModelChange(provider, model); setIsMenuOpen(false); }; return ( - { if (props.disabled) { @@ -91,7 +82,7 @@ export const ProviderModelPicker = memo(function ProviderModelPicker(props: { setIsMenuOpen(open); }} > - - - {props.lockedProvider !== null ? ( - - handleModelChange(props.lockedProvider!, value)} - > - {props.modelOptionsByProvider[props.lockedProvider].map((modelOption) => ( - setIsMenuOpen(false)} - > - {modelOption.name} - - ))} - - - ) : ( - <> - {AVAILABLE_PROVIDER_OPTIONS.map((option) => { - const OptionIcon = PROVIDER_ICON_BY_PROVIDER[option.value]; - const liveProvider = props.providers - ? getProviderSnapshot(props.providers, option.value) - : undefined; - if (liveProvider && liveProvider.status !== "ready") { - const unavailableLabel = !liveProvider.enabled - ? "Disabled" - : !liveProvider.installed - ? "Not installed" - : "Unavailable"; - return ( - - - ); - } - return ( - - - - - - handleModelChange(option.value, value)} - > - {props.modelOptionsByProvider[option.value].map((modelOption) => ( - setIsMenuOpen(false)} - > - {modelOption.name} - - ))} - - - - - ); - })} - {UNAVAILABLE_PROVIDER_OPTIONS.length > 0 && } - {UNAVAILABLE_PROVIDER_OPTIONS.map((option) => { - const OptionIcon = PROVIDER_ICON_BY_PROVIDER[option.value]; - return ( - - - ); - })} - {UNAVAILABLE_PROVIDER_OPTIONS.length === 0 && } - {COMING_SOON_PROVIDER_OPTIONS.map((option) => { - const OptionIcon = option.icon; - return ( - - - ); - })} - - )} - - + + + setIsMenuOpen(false)} + onProviderModelChange={handleProviderModelChange} + /> + + ); }); diff --git a/apps/web/src/components/chat/modelPickerModelHighlights.ts b/apps/web/src/components/chat/modelPickerModelHighlights.ts new file mode 100644 index 0000000000..c3661fda2b --- /dev/null +++ b/apps/web/src/components/chat/modelPickerModelHighlights.ts @@ -0,0 +1,13 @@ +import type { ProviderKind } from "@t3tools/contracts"; + +/** + * Model slugs that show a gold "NEW" chip in the model picker list. + * Add entries as `provider:slug` when you want to highlight freshly shipped models. + */ +const NEW_MODEL_KEYS = new Set([ + // Example: "claudeAgent:claude-opus-4-7", +]); + +export function isModelPickerNewModel(provider: ProviderKind, slug: string): boolean { + return NEW_MODEL_KEYS.has(`${provider}:${slug}`); +} diff --git a/apps/web/src/components/chat/modelPickerSearch.test.ts b/apps/web/src/components/chat/modelPickerSearch.test.ts new file mode 100644 index 0000000000..1ce629d8a4 --- /dev/null +++ b/apps/web/src/components/chat/modelPickerSearch.test.ts @@ -0,0 +1,109 @@ +import { describe, expect, it } from "vitest"; + +import { buildModelPickerSearchText, scoreModelPickerSearch } from "./modelPickerSearch"; + +describe("buildModelPickerSearchText", () => { + it("builds provider-agnostic search text from generic fields", () => { + expect( + buildModelPickerSearchText({ + provider: "opencode", + name: "Claude Opus 4.7", + subProvider: "GitHub Copilot", + }), + ).toBe("claude opus 4.7 github copilot opencode opencode"); + }); +}); + +describe("scoreModelPickerSearch", () => { + it("matches typo-tolerant multi-token queries", () => { + expect( + scoreModelPickerSearch( + { + provider: "opencode", + name: "Claude Opus 4.7", + subProvider: "GitHub Copilot", + }, + "coplt op", + ), + ).not.toBeNull(); + }); + + it("rejects results when any query token does not match", () => { + expect( + scoreModelPickerSearch( + { + provider: "codex", + name: "GPT-5 Codex", + }, + "coplt op", + ), + ).toBeNull(); + }); + + it("ranks exact token matches ahead of fuzzier matches", () => { + const exactScore = scoreModelPickerSearch( + { + provider: "opencode", + name: "Claude Opus 4.7", + subProvider: "GitHub Copilot", + }, + "copilot opus", + ); + const fuzzyScore = scoreModelPickerSearch( + { + provider: "opencode", + name: "Claude Opus 4.7", + subProvider: "GitHub Copilot", + }, + "coplt op", + ); + + expect(exactScore).not.toBeNull(); + expect(fuzzyScore).not.toBeNull(); + expect(exactScore!).toBeLessThan(fuzzyScore!); + }); + + it("gives favorite models a strong enough ranking boost for partial queries", () => { + const favoriteScore = scoreModelPickerSearch( + { + provider: "claudeAgent", + name: "Claude Opus 4.7", + isFavorite: true, + }, + "opu", + ); + const nonFavoriteScore = scoreModelPickerSearch( + { + provider: "cursor", + name: "Opus 4.5", + }, + "opu", + ); + + expect(favoriteScore).not.toBeNull(); + expect(nonFavoriteScore).not.toBeNull(); + expect(favoriteScore!).toBeLessThan(nonFavoriteScore!); + }); + + it("does not let the favorite boost outrank clearly better textual matches", () => { + const favoriteScore = scoreModelPickerSearch( + { + provider: "claudeAgent", + name: "Claude Opus 4.7", + isFavorite: true, + }, + "opus 4.7", + ); + const nonFavoriteExactScore = scoreModelPickerSearch( + { + provider: "cursor", + name: "Opus 4.7", + }, + "opus 4.7", + ); + + expect(favoriteScore).not.toBeNull(); + expect(nonFavoriteExactScore).not.toBeNull(); + expect(nonFavoriteExactScore!).toBeLessThan(favoriteScore!); + }); +}); diff --git a/apps/web/src/components/chat/modelPickerSearch.ts b/apps/web/src/components/chat/modelPickerSearch.ts new file mode 100644 index 0000000000..a4871fa0f3 --- /dev/null +++ b/apps/web/src/components/chat/modelPickerSearch.ts @@ -0,0 +1,83 @@ +import { type ProviderKind, PROVIDER_DISPLAY_NAMES } from "@t3tools/contracts"; +import { normalizeSearchQuery, scoreQueryMatch } from "@t3tools/shared/searchRanking"; + +type ModelPickerSearchableModel = { + provider: ProviderKind; + name: string; + shortName?: string; + subProvider?: string; + isFavorite?: boolean; +}; + +const MODEL_PICKER_FAVORITE_SCORE_BOOST = 24; + +function getModelPickerSearchFields(model: ModelPickerSearchableModel): string[] { + return [ + normalizeSearchQuery(model.name), + ...(model.shortName ? [normalizeSearchQuery(model.shortName)] : []), + ...(model.subProvider ? [normalizeSearchQuery(model.subProvider)] : []), + normalizeSearchQuery(model.provider), + normalizeSearchQuery(PROVIDER_DISPLAY_NAMES[model.provider]), + buildModelPickerSearchText(model), + ]; +} + +function scoreModelPickerSearchToken( + field: string, + token: string, + fieldBase: number, +): number | null { + return scoreQueryMatch({ + value: field, + query: token, + exactBase: fieldBase, + prefixBase: fieldBase + 2, + boundaryBase: fieldBase + 4, + includesBase: fieldBase + 6, + ...(token.length >= 3 ? { fuzzyBase: fieldBase + 100 } : {}), + }); +} + +export function buildModelPickerSearchText(model: ModelPickerSearchableModel): string { + return normalizeSearchQuery( + [ + model.name, + model.shortName, + model.subProvider, + model.provider, + PROVIDER_DISPLAY_NAMES[model.provider], + ] + .filter((value): value is string => typeof value === "string" && value.length > 0) + .join(" "), + ); +} + +export function scoreModelPickerSearch( + model: ModelPickerSearchableModel, + query: string, +): number | null { + const tokens = normalizeSearchQuery(query) + .split(/\s+/u) + .filter((token) => token.length > 0); + + if (tokens.length === 0) { + return 0; + } + + const fields = getModelPickerSearchFields(model); + let score = 0; + + for (const token of tokens) { + const tokenScores = fields + .map((field, index) => scoreModelPickerSearchToken(field, token, index * 10)) + .filter((fieldScore): fieldScore is number => fieldScore !== null); + + if (tokenScores.length === 0) { + return null; + } + + score += Math.min(...tokenScores); + } + + return model.isFavorite ? score - MODEL_PICKER_FAVORITE_SCORE_BOOST : score; +} diff --git a/apps/web/src/components/chat/providerIconUtils.ts b/apps/web/src/components/chat/providerIconUtils.ts new file mode 100644 index 0000000000..66f5220771 --- /dev/null +++ b/apps/web/src/components/chat/providerIconUtils.ts @@ -0,0 +1,52 @@ +import { type ProviderKind, PROVIDER_DISPLAY_NAMES } from "@t3tools/contracts"; +import { ClaudeAI, CursorIcon, Icon, OpenAI, OpenCodeIcon } from "../Icons"; +import { PROVIDER_OPTIONS } from "../../session-logic"; + +export const PROVIDER_ICON_BY_PROVIDER: Record = { + codex: OpenAI, + claudeAgent: ClaudeAI, + opencode: OpenCodeIcon, + cursor: CursorIcon, +}; + +function isAvailableProviderOption(option: (typeof PROVIDER_OPTIONS)[number]): option is { + value: ProviderKind; + label: string; + available: true; + pickerSidebarBadge?: "new" | "soon"; +} { + return option.available; +} + +export const AVAILABLE_PROVIDER_OPTIONS = PROVIDER_OPTIONS.filter(isAvailableProviderOption); + +export type ModelEsque = { + slug: string; + name: string; + shortName?: string | undefined; + subProvider?: string | undefined; +}; + +export function getProviderLabel(provider: ProviderKind, model: ModelEsque): string { + const providerLabel = PROVIDER_DISPLAY_NAMES[provider]; + return model.subProvider ? `${providerLabel} · ${model.subProvider}` : providerLabel; +} + +export function getDisplayModelName( + model: ModelEsque, + options?: { preferShortName?: boolean }, +): string { + if (options?.preferShortName && model.shortName) { + return model.shortName; + } + return model.name; +} + +export function getTriggerDisplayModelName(model: ModelEsque): string { + return getDisplayModelName(model, { preferShortName: true }); +} + +export function getTriggerDisplayModelLabel(model: ModelEsque): string { + const title = getTriggerDisplayModelName(model); + return model.subProvider ? `${model.subProvider} · ${title}` : title; +} diff --git a/apps/web/src/components/ui/autocomplete.tsx b/apps/web/src/components/ui/autocomplete.tsx index 676db613ae..d6db87d48c 100644 --- a/apps/web/src/components/ui/autocomplete.tsx +++ b/apps/web/src/components/ui/autocomplete.tsx @@ -193,7 +193,7 @@ function AutocompleteList({ className, ...props }: AutocompletePrimitive.List.Pr return ( diff --git a/apps/web/src/components/ui/combobox.tsx b/apps/web/src/components/ui/combobox.tsx index 52dd996ec5..ff6056e9cf 100644 --- a/apps/web/src/components/ui/combobox.tsx +++ b/apps/web/src/components/ui/combobox.tsx @@ -186,10 +186,12 @@ function ComboboxPopup({ function ComboboxItem({ className, + contentClassName, children, hideIndicator = false, ...props }: ComboboxPrimitive.Item.Props & { + contentClassName?: string; hideIndicator?: boolean; }) { return ( @@ -204,7 +206,14 @@ function ComboboxItem({ -
{children}
+
+ {children} +
); } @@ -264,10 +273,7 @@ function ComboboxList({ className, ...props }: ComboboxPrimitive.List.Props) { return ( diff --git a/apps/web/src/components/ui/scroll-area.tsx b/apps/web/src/components/ui/scroll-area.tsx index 50deb1ba87..c8aa6dc96d 100644 --- a/apps/web/src/components/ui/scroll-area.tsx +++ b/apps/web/src/components/ui/scroll-area.tsx @@ -17,13 +17,16 @@ function ScrollArea({ hideScrollbars?: boolean; }) { return ( - + { }); }); - it("detects slash model query after /model", () => { - const text = "/model spark"; + it("keeps /model as a slash command item", () => { + const text = "/model"; const trigger = detectComposerTrigger(text, text.length); expect(trigger).toEqual({ - kind: "slash-model", - query: "spark", + kind: "slash-command", + query: "model", rangeStart: 0, rangeEnd: text.length, }); }); + it("does not keep a subcommand trigger active after /model arguments", () => { + const text = "/model spark"; + const trigger = detectComposerTrigger(text, text.length); + + expect(trigger).toBeNull(); + }); + it("detects non-model slash commands while typing", () => { const text = "/pl"; const trigger = detectComposerTrigger(text, text.length); diff --git a/apps/web/src/composer-logic.ts b/apps/web/src/composer-logic.ts index a5b26b0e2d..fb63d2581c 100644 --- a/apps/web/src/composer-logic.ts +++ b/apps/web/src/composer-logic.ts @@ -1,7 +1,7 @@ import { splitPromptIntoComposerSegments } from "./composer-editor-mentions"; import { INLINE_TERMINAL_CONTEXT_PLACEHOLDER } from "./lib/terminalContext"; -export type ComposerTriggerKind = "path" | "slash-command" | "slash-model" | "skill"; +export type ComposerTriggerKind = "path" | "slash-command" | "skill"; export type ComposerSlashCommand = "model" | "plan" | "default"; export interface ComposerTrigger { @@ -224,14 +224,6 @@ export function detectComposerTrigger(text: string, cursorInput: number): Compos const commandMatch = /^\/(\S*)$/.exec(linePrefix); if (commandMatch) { const commandQuery = commandMatch[1] ?? ""; - if (commandQuery.toLowerCase() === "model") { - return { - kind: "slash-model", - query: "", - rangeStart: lineStart, - rangeEnd: cursor, - }; - } return { kind: "slash-command", query: commandQuery, @@ -239,16 +231,6 @@ export function detectComposerTrigger(text: string, cursorInput: number): Compos rangeEnd: cursor, }; } - - const modelMatch = /^\/model(?:\s+(.*))?$/.exec(linePrefix); - if (modelMatch) { - return { - kind: "slash-model", - query: (modelMatch[1] ?? "").trim(), - rangeStart: lineStart, - rangeEnd: cursor, - }; - } } const tokenStart = tokenStartForCursor(text, cursor); diff --git a/apps/web/src/hooks/useSettings.ts b/apps/web/src/hooks/useSettings.ts index c2301b23a3..18b2668a60 100644 --- a/apps/web/src/hooks/useSettings.ts +++ b/apps/web/src/hooks/useSettings.ts @@ -10,8 +10,9 @@ * store. */ import { useCallback, useMemo, useSyncExternalStore } from "react"; -import { ServerSettings, ServerSettingsPatch } from "@t3tools/contracts"; +import { ServerSettings, type ServerSettingsPatch } from "@t3tools/contracts"; import { + type ClientSettingsPatch, type ClientSettings, DEFAULT_CLIENT_SETTINGS, DEFAULT_UNIFIED_SETTINGS, @@ -98,7 +99,7 @@ const SERVER_SETTINGS_KEYS = new Set(Struct.keys(ServerSettings.fields)) function splitPatch(patch: Partial): { serverPatch: ServerSettingsPatch; - clientPatch: Partial; + clientPatch: ClientSettingsPatch; } { const serverPatch: Record = {}; const clientPatch: Record = {}; @@ -111,7 +112,7 @@ function splitPatch(patch: Partial): { } return { serverPatch: serverPatch as ServerSettingsPatch, - clientPatch: clientPatch as Partial, + clientPatch: clientPatch as ClientSettingsPatch, }; } diff --git a/apps/web/src/index.css b/apps/web/src/index.css index 6a4db39855..5c568ad5d6 100644 --- a/apps/web/src/index.css +++ b/apps/web/src/index.css @@ -534,3 +534,25 @@ label:has(> select#reasoning-effort) select { -webkit-background-clip: text; animation: ultrathink-rainbow 10s linear infinite; } + +/* Thin scrollbar for model picker */ +.model-picker-list::-webkit-scrollbar { + width: 4px; +} + +.model-picker-list::-webkit-scrollbar-thumb { + background: rgba(0, 0, 0, 0.1); + border-radius: 2px; +} + +.model-picker-list::-webkit-scrollbar-thumb:hover { + background: rgba(0, 0, 0, 0.2); +} + +.dark .model-picker-list::-webkit-scrollbar-thumb { + background: rgba(255, 255, 255, 0.08); +} + +.dark .model-picker-list::-webkit-scrollbar-thumb:hover { + background: rgba(255, 255, 255, 0.15); +} diff --git a/apps/web/src/keybindings.test.ts b/apps/web/src/keybindings.test.ts index 683afbbfe4..85c14fa0ab 100644 --- a/apps/web/src/keybindings.test.ts +++ b/apps/web/src/keybindings.test.ts @@ -11,6 +11,8 @@ import { isChatNewShortcut, isChatNewLocalShortcut, isDiffToggleShortcut, + modelPickerJumpCommandForIndex, + modelPickerJumpIndexFromCommand, isOpenFavoriteEditorShortcut, isTerminalClearShortcut, isTerminalCloseShortcut, @@ -18,6 +20,7 @@ import { isTerminalSplitShortcut, isTerminalToggleShortcut, resolveShortcutCommand, + shouldShowModelPickerJumpHints, shouldShowThreadJumpHints, shortcutLabelForCommand, terminalDeleteShortcutData, @@ -107,6 +110,11 @@ const DEFAULT_BINDINGS = compile([ command: "commandPalette.toggle", whenAst: whenNot(whenIdentifier("terminalFocus")), }, + { + shortcut: modShortcut("m", { shiftKey: true }), + command: "modelPicker.toggle", + whenAst: whenNot(whenIdentifier("terminalFocus")), + }, { shortcut: modShortcut("o", { shiftKey: true }), command: "chat.new" }, { shortcut: modShortcut("n", { shiftKey: true }), command: "chat.newLocal" }, { shortcut: modShortcut("o"), command: "editor.openFavorite" }, @@ -115,6 +123,21 @@ const DEFAULT_BINDINGS = compile([ { shortcut: modShortcut("1"), command: "thread.jump.1" }, { shortcut: modShortcut("2"), command: "thread.jump.2" }, { shortcut: modShortcut("3"), command: "thread.jump.3" }, + { + shortcut: modShortcut("1"), + command: "modelPicker.jump.1", + whenAst: whenIdentifier("modelPickerOpen"), + }, + { + shortcut: modShortcut("2"), + command: "modelPicker.jump.2", + whenAst: whenIdentifier("modelPickerOpen"), + }, + { + shortcut: modShortcut("3"), + command: "modelPicker.jump.3", + whenAst: whenIdentifier("modelPickerOpen"), + }, ]); describe("isTerminalToggleShortcut", () => { @@ -268,6 +291,10 @@ describe("shortcutLabelForCommand", () => { shortcutLabelForCommand(DEFAULT_BINDINGS, "commandPalette.toggle", "MacIntel"), "⌘K", ); + assert.strictEqual( + shortcutLabelForCommand(DEFAULT_BINDINGS, "modelPicker.toggle", "Linux"), + "Ctrl+Shift+M", + ); assert.strictEqual( shortcutLabelForCommand(DEFAULT_BINDINGS, "editor.openFavorite", "Linux"), "Ctrl+O", @@ -280,6 +307,13 @@ describe("shortcutLabelForCommand", () => { shortcutLabelForCommand(DEFAULT_BINDINGS, "thread.previous", "Linux"), "Ctrl+Shift+[", ); + assert.strictEqual( + shortcutLabelForCommand(DEFAULT_BINDINGS, "modelPicker.jump.3", { + platform: "MacIntel", + context: { modelPickerOpen: true }, + }), + "⌘3", + ); }); it("returns null for commands shadowed by a later conflicting shortcut", () => { @@ -361,6 +395,32 @@ describe("thread navigation helpers", () => { }); }); +describe("model picker navigation helpers", () => { + it("maps jump commands to visible model indices", () => { + assert.strictEqual(modelPickerJumpCommandForIndex(0), "modelPicker.jump.1"); + assert.strictEqual(modelPickerJumpCommandForIndex(2), "modelPicker.jump.3"); + assert.isNull(modelPickerJumpCommandForIndex(9)); + assert.strictEqual(modelPickerJumpIndexFromCommand("modelPicker.jump.1"), 0); + assert.strictEqual(modelPickerJumpIndexFromCommand("modelPicker.jump.3"), 2); + assert.isNull(modelPickerJumpIndexFromCommand("thread.jump.1")); + }); + + it("shows jump hints only while the model picker context is active", () => { + assert.isFalse( + shouldShowModelPickerJumpHints(event({ metaKey: true }), DEFAULT_BINDINGS, { + platform: "MacIntel", + context: { modelPickerOpen: false }, + }), + ); + assert.isTrue( + shouldShowModelPickerJumpHints(event({ metaKey: true }), DEFAULT_BINDINGS, { + platform: "MacIntel", + context: { modelPickerOpen: true }, + }), + ); + }); +}); + describe("chat/editor shortcuts", () => { it("matches chat.new shortcut", () => { assert.isTrue( diff --git a/apps/web/src/keybindings.ts b/apps/web/src/keybindings.ts index 977c1319b9..dbf2450f79 100644 --- a/apps/web/src/keybindings.ts +++ b/apps/web/src/keybindings.ts @@ -2,8 +2,10 @@ import { type KeybindingCommand, type KeybindingShortcut, type KeybindingWhenNode, + MODEL_PICKER_JUMP_KEYBINDING_COMMANDS, type ResolvedKeybindingsConfig, THREAD_JUMP_KEYBINDING_COMMANDS, + type ModelPickerJumpKeybindingCommand, type ThreadJumpKeybindingCommand, } from "@t3tools/contracts"; import { isMacPlatform } from "./lib/utils"; @@ -18,6 +20,13 @@ export interface ShortcutEventLike { altKey: boolean; } +export interface ShortcutModifierStateLike { + metaKey: boolean; + ctrlKey: boolean; + shiftKey: boolean; + altKey: boolean; +} + export interface ShortcutMatchContext { terminalFocus: boolean; terminalOpen: boolean; @@ -71,7 +80,7 @@ function resolveEventKeys(event: ShortcutEventLike): Set { } function matchesShortcutModifiers( - event: ShortcutEventLike, + event: ShortcutModifierStateLike, shortcut: KeybindingShortcut, platform = navigator.platform, ): boolean { @@ -269,13 +278,60 @@ export function shouldShowThreadJumpHints( event: ShortcutEventLike, keybindings: ResolvedKeybindingsConfig, options?: ShortcutMatchOptions, +): boolean { + return shouldShowThreadJumpHintsForModifiers(event, keybindings, options); +} + +export function shouldShowThreadJumpHintsForModifiers( + modifiers: ShortcutModifierStateLike, + keybindings: ResolvedKeybindingsConfig, + options?: ShortcutMatchOptions, ): boolean { const platform = resolvePlatform(options); for (const command of THREAD_JUMP_KEYBINDING_COMMANDS) { const shortcut = findEffectiveShortcutForCommand(keybindings, command, options); if (!shortcut) continue; - if (matchesShortcutModifiers(event, shortcut, platform)) { + if (matchesShortcutModifiers(modifiers, shortcut, platform)) { + return true; + } + } + + return false; +} + +export function modelPickerJumpCommandForIndex( + index: number, +): ModelPickerJumpKeybindingCommand | null { + return MODEL_PICKER_JUMP_KEYBINDING_COMMANDS[index] ?? null; +} + +export function modelPickerJumpIndexFromCommand(command: string): number | null { + const index = MODEL_PICKER_JUMP_KEYBINDING_COMMANDS.indexOf( + command as ModelPickerJumpKeybindingCommand, + ); + return index === -1 ? null : index; +} + +export function shouldShowModelPickerJumpHints( + event: ShortcutEventLike, + keybindings: ResolvedKeybindingsConfig, + options?: ShortcutMatchOptions, +): boolean { + return shouldShowModelPickerJumpHintsForModifiers(event, keybindings, options); +} + +export function shouldShowModelPickerJumpHintsForModifiers( + modifiers: ShortcutModifierStateLike, + keybindings: ResolvedKeybindingsConfig, + options?: ShortcutMatchOptions, +): boolean { + const platform = resolvePlatform(options); + + for (const command of MODEL_PICKER_JUMP_KEYBINDING_COMMANDS) { + const shortcut = findEffectiveShortcutForCommand(keybindings, command, options); + if (!shortcut) continue; + if (matchesShortcutModifiers(modifiers, shortcut, platform)) { return true; } } diff --git a/apps/web/src/localApi.test.ts b/apps/web/src/localApi.test.ts index 4258ccb380..f531221753 100644 --- a/apps/web/src/localApi.test.ts +++ b/apps/web/src/localApi.test.ts @@ -532,6 +532,7 @@ describe("wsApi", () => { confirmThreadArchive: true, confirmThreadDelete: false, diffWordWrap: true, + favorites: [], sidebarProjectGroupingMode: "repository_path" as const, sidebarProjectGroupingOverrides: { "environment-local:/tmp/project": "separate" as const, @@ -589,6 +590,7 @@ describe("wsApi", () => { confirmThreadArchive: true, confirmThreadDelete: false, diffWordWrap: true, + favorites: [], sidebarProjectGroupingMode: "repository_path" as const, sidebarProjectGroupingOverrides: { "environment-local:/tmp/project": "separate" as const, diff --git a/apps/web/src/modelPickerOpenState.ts b/apps/web/src/modelPickerOpenState.ts new file mode 100644 index 0000000000..5a4993c16e --- /dev/null +++ b/apps/web/src/modelPickerOpenState.ts @@ -0,0 +1,17 @@ +import { create } from "zustand"; + +const useModelPickerOpenStore = create<{ + open: boolean; + setOpen: (open: boolean) => void; +}>((set) => ({ + open: false, + setOpen: (open) => set((current) => (current.open === open ? current : { open })), +})); + +export function useModelPickerOpen(): boolean { + return useModelPickerOpenStore((store) => store.open); +} + +export function setModelPickerOpen(open: boolean): void { + useModelPickerOpenStore.getState().setOpen(open); +} diff --git a/apps/web/src/modelSelection.ts b/apps/web/src/modelSelection.ts index 60ab386b83..2ffa8e2014 100644 --- a/apps/web/src/modelSelection.ts +++ b/apps/web/src/modelSelection.ts @@ -16,6 +16,7 @@ import { getProviderModels, resolveSelectableProvider, } from "./providerModels"; +import { ModelEsque } from "./components/chat/providerIconUtils"; const MAX_CUSTOM_MODEL_COUNT = 32; export const MAX_CUSTOM_MODEL_LENGTH = 256; @@ -31,6 +32,8 @@ export type ProviderCustomModelConfig = { export interface AppModelOption { slug: string; name: string; + shortName?: string; + subProvider?: string; isCustom: boolean; } @@ -103,9 +106,11 @@ export function getAppModelOptions( selectedModel?: string | null, ): AppModelOption[] { const options: AppModelOption[] = getProviderModels(providers, provider).map( - ({ slug, name, isCustom }) => ({ + ({ slug, name, shortName, subProvider, isCustom }) => ({ slug, name, + ...(shortName ? { shortName } : {}), + ...(subProvider ? { subProvider } : {}), isCustom, }), ); @@ -169,7 +174,7 @@ export function getCustomModelOptionsByProvider( providers: ReadonlyArray, selectedProvider?: ProviderKind | null, selectedModel?: string | null, -): Record> { +): Record> { return { codex: getAppModelOptions( settings, diff --git a/apps/web/src/session-logic.ts b/apps/web/src/session-logic.ts index 477bc57bea..44e0498d7b 100644 --- a/apps/web/src/session-logic.ts +++ b/apps/web/src/session-logic.ts @@ -28,11 +28,13 @@ export const PROVIDER_OPTIONS: Array<{ value: ProviderPickerKind; label: string; available: boolean; + /** Shown on the model picker sidebar when relevant */ + pickerSidebarBadge?: "new" | "soon"; }> = [ { value: "codex", label: "Codex", available: true }, { value: "claudeAgent", label: "Claude", available: true }, - { value: "opencode", label: "OpenCode", available: true }, - { value: "cursor", label: "Cursor", available: true }, + { value: "opencode", label: "OpenCode", available: true, pickerSidebarBadge: "new" }, + { value: "cursor", label: "Cursor", available: true, pickerSidebarBadge: "new" }, ]; export interface WorkLogEntry { diff --git a/apps/web/src/shortcutModifierState.test.ts b/apps/web/src/shortcutModifierState.test.ts new file mode 100644 index 0000000000..46a7fc4aac --- /dev/null +++ b/apps/web/src/shortcutModifierState.test.ts @@ -0,0 +1,146 @@ +import { describe, expect, it } from "vitest"; + +import { + areShortcutModifierStatesEqual, + clearShortcutModifierState, + readShortcutModifierState, + setShortcutModifierState, + syncShortcutModifierStateFromKeyboardEvent, +} from "./shortcutModifierState"; + +function keyboardEventLike(type: "keydown" | "keyup", init: Partial): KeyboardEvent { + return { + type, + key: "", + metaKey: false, + ctrlKey: false, + altKey: false, + shiftKey: false, + ...init, + } as KeyboardEvent; +} + +describe("shortcutModifierState", () => { + it("compares modifier states by value", () => { + expect( + areShortcutModifierStatesEqual( + { metaKey: false, ctrlKey: true, altKey: false, shiftKey: true }, + { metaKey: false, ctrlKey: true, altKey: false, shiftKey: true }, + ), + ).toBe(true); + expect( + areShortcutModifierStatesEqual( + { metaKey: false, ctrlKey: true, altKey: false, shiftKey: true }, + { metaKey: false, ctrlKey: false, altKey: false, shiftKey: true }, + ), + ).toBe(false); + }); + + it("preserves the current store object when modifier values do not change", () => { + clearShortcutModifierState(); + + const initialState = readShortcutModifierState(); + setShortcutModifierState({ + metaKey: false, + ctrlKey: false, + altKey: false, + shiftKey: false, + }); + + expect(readShortcutModifierState()).toBe(initialState); + + setShortcutModifierState({ + metaKey: false, + ctrlKey: true, + altKey: false, + shiftKey: false, + }); + const updatedState = readShortcutModifierState(); + expect(updatedState).not.toBe(initialState); + expect(updatedState).toEqual({ + metaKey: false, + ctrlKey: true, + altKey: false, + shiftKey: false, + }); + + setShortcutModifierState({ + metaKey: false, + ctrlKey: true, + altKey: false, + shiftKey: false, + }); + expect(readShortcutModifierState()).toBe(updatedState); + + clearShortcutModifierState(); + const clearedState = readShortcutModifierState(); + expect(clearedState).toEqual({ + metaKey: false, + ctrlKey: false, + altKey: false, + shiftKey: false, + }); + expect(clearedState).not.toBe(updatedState); + + clearShortcutModifierState(); + expect(readShortcutModifierState()).toBe(clearedState); + }); + + it("tracks bare modifier keydown and keyup events explicitly", () => { + clearShortcutModifierState(); + + syncShortcutModifierStateFromKeyboardEvent( + keyboardEventLike("keydown", { + key: "Meta", + metaKey: false, + }), + ); + expect(readShortcutModifierState()).toEqual({ + metaKey: true, + ctrlKey: false, + altKey: false, + shiftKey: false, + }); + + syncShortcutModifierStateFromKeyboardEvent( + keyboardEventLike("keydown", { + key: "Shift", + metaKey: true, + shiftKey: false, + }), + ); + expect(readShortcutModifierState()).toEqual({ + metaKey: true, + ctrlKey: false, + altKey: false, + shiftKey: true, + }); + + syncShortcutModifierStateFromKeyboardEvent( + keyboardEventLike("keyup", { + key: "Meta", + metaKey: true, + shiftKey: true, + }), + ); + expect(readShortcutModifierState()).toEqual({ + metaKey: false, + ctrlKey: false, + altKey: false, + shiftKey: true, + }); + + syncShortcutModifierStateFromKeyboardEvent( + keyboardEventLike("keyup", { + key: "Shift", + shiftKey: true, + }), + ); + expect(readShortcutModifierState()).toEqual({ + metaKey: false, + ctrlKey: false, + altKey: false, + shiftKey: false, + }); + }); +}); diff --git a/apps/web/src/shortcutModifierState.ts b/apps/web/src/shortcutModifierState.ts new file mode 100644 index 0000000000..370f3b0a70 --- /dev/null +++ b/apps/web/src/shortcutModifierState.ts @@ -0,0 +1,96 @@ +import { create } from "zustand"; + +export interface ShortcutModifierState { + metaKey: boolean; + ctrlKey: boolean; + altKey: boolean; + shiftKey: boolean; +} + +const EMPTY_SHORTCUT_MODIFIER_STATE: ShortcutModifierState = { + metaKey: false, + ctrlKey: false, + altKey: false, + shiftKey: false, +}; + +export function areShortcutModifierStatesEqual( + left: ShortcutModifierState, + right: ShortcutModifierState, +): boolean { + return ( + left.metaKey === right.metaKey && + left.ctrlKey === right.ctrlKey && + left.altKey === right.altKey && + left.shiftKey === right.shiftKey + ); +} + +const useShortcutModifierStateStore = create<{ + state: ShortcutModifierState; + setState: (state: ShortcutModifierState) => void; + clear: () => void; +}>((set) => ({ + state: EMPTY_SHORTCUT_MODIFIER_STATE, + setState: (state) => + set((current) => (areShortcutModifierStatesEqual(current.state, state) ? current : { state })), + clear: () => + set((current) => + areShortcutModifierStatesEqual(current.state, EMPTY_SHORTCUT_MODIFIER_STATE) + ? current + : { state: EMPTY_SHORTCUT_MODIFIER_STATE }, + ), +})); + +export function useShortcutModifierState(): ShortcutModifierState { + return useShortcutModifierStateStore((store) => store.state); +} + +function normalizeModifierKey(key: string): keyof ShortcutModifierState | null { + switch (key) { + case "Meta": + case "OS": + case "Command": + return "metaKey"; + case "Control": + return "ctrlKey"; + case "Alt": + case "Option": + return "altKey"; + case "Shift": + return "shiftKey"; + default: + return null; + } +} + +export function syncShortcutModifierStateFromKeyboardEvent(event: KeyboardEvent): void { + const normalizedModifierKey = normalizeModifierKey(event.key); + if (normalizedModifierKey) { + const currentState = useShortcutModifierStateStore.getState().state; + useShortcutModifierStateStore.getState().setState({ + ...currentState, + [normalizedModifierKey]: event.type === "keydown", + }); + return; + } + + useShortcutModifierStateStore.getState().setState({ + metaKey: event.metaKey, + ctrlKey: event.ctrlKey, + altKey: event.altKey, + shiftKey: event.shiftKey, + }); +} + +export function setShortcutModifierState(state: ShortcutModifierState): void { + useShortcutModifierStateStore.getState().setState(state); +} + +export function clearShortcutModifierState(): void { + useShortcutModifierStateStore.getState().clear(); +} + +export function readShortcutModifierState(): ShortcutModifierState { + return useShortcutModifierStateStore.getState().state; +} diff --git a/packages/contracts/src/keybindings.test.ts b/packages/contracts/src/keybindings.test.ts index 79c2feb8ba..f040697013 100644 --- a/packages/contracts/src/keybindings.test.ts +++ b/packages/contracts/src/keybindings.test.ts @@ -53,6 +53,18 @@ it.effect("parses keybinding rules", () => }); assert.strictEqual(parsedLocal.command, "chat.newLocal"); + const parsedModelPickerToggle = yield* decode(KeybindingRule, { + key: "mod+shift+m", + command: "modelPicker.toggle", + }); + assert.strictEqual(parsedModelPickerToggle.command, "modelPicker.toggle"); + + const parsedModelPickerJump = yield* decode(KeybindingRule, { + key: "mod+1", + command: "modelPicker.jump.1", + }); + assert.strictEqual(parsedModelPickerJump.command, "modelPicker.jump.1"); + const parsedThreadPrevious = yield* decode(KeybindingRule, { key: "mod+shift+[", command: "thread.previous", diff --git a/packages/contracts/src/keybindings.ts b/packages/contracts/src/keybindings.ts index 1296e74c1b..d3b85d1cda 100644 --- a/packages/contracts/src/keybindings.ts +++ b/packages/contracts/src/keybindings.ts @@ -20,6 +20,20 @@ export const THREAD_JUMP_KEYBINDING_COMMANDS = [ ] as const; export type ThreadJumpKeybindingCommand = (typeof THREAD_JUMP_KEYBINDING_COMMANDS)[number]; +export const MODEL_PICKER_JUMP_KEYBINDING_COMMANDS = [ + "modelPicker.jump.1", + "modelPicker.jump.2", + "modelPicker.jump.3", + "modelPicker.jump.4", + "modelPicker.jump.5", + "modelPicker.jump.6", + "modelPicker.jump.7", + "modelPicker.jump.8", + "modelPicker.jump.9", +] as const; +export type ModelPickerJumpKeybindingCommand = + (typeof MODEL_PICKER_JUMP_KEYBINDING_COMMANDS)[number]; + export const THREAD_KEYBINDING_COMMANDS = [ "thread.previous", "thread.next", @@ -27,6 +41,12 @@ export const THREAD_KEYBINDING_COMMANDS = [ ] as const; export type ThreadKeybindingCommand = (typeof THREAD_KEYBINDING_COMMANDS)[number]; +export const MODEL_PICKER_KEYBINDING_COMMANDS = [ + "modelPicker.toggle", + ...MODEL_PICKER_JUMP_KEYBINDING_COMMANDS, +] as const; +export type ModelPickerKeybindingCommand = (typeof MODEL_PICKER_KEYBINDING_COMMANDS)[number]; + const STATIC_KEYBINDING_COMMANDS = [ "terminal.toggle", "terminal.split", @@ -37,6 +57,7 @@ const STATIC_KEYBINDING_COMMANDS = [ "chat.new", "chat.newLocal", "editor.openFavorite", + ...MODEL_PICKER_KEYBINDING_COMMANDS, ...THREAD_KEYBINDING_COMMANDS, ] as const; diff --git a/packages/contracts/src/server.ts b/packages/contracts/src/server.ts index c08dfa6cd1..3cd25f2e8e 100644 --- a/packages/contracts/src/server.ts +++ b/packages/contracts/src/server.ts @@ -53,6 +53,8 @@ export type ServerProviderAuth = typeof ServerProviderAuth.Type; export const ServerProviderModel = Schema.Struct({ slug: TrimmedNonEmptyString, name: TrimmedNonEmptyString, + shortName: Schema.optional(TrimmedNonEmptyString), + subProvider: Schema.optional(TrimmedNonEmptyString), isCustom: Schema.Boolean, capabilities: Schema.NullOr(ModelCapabilities), }); diff --git a/packages/contracts/src/settings.ts b/packages/contracts/src/settings.ts index 6c45dde530..cad1d197c1 100644 --- a/packages/contracts/src/settings.ts +++ b/packages/contracts/src/settings.ts @@ -9,7 +9,7 @@ import { DEFAULT_GIT_TEXT_GENERATION_MODEL_BY_PROVIDER, OpenCodeModelOptions, } from "./model.ts"; -import { ModelSelection } from "./orchestration.ts"; +import { ModelSelection, ProviderKind } from "./orchestration.ts"; // ── Client Settings (local-only) ─────────────────────────────── @@ -37,6 +37,12 @@ export const ClientSettingsSchema = Schema.Struct({ confirmThreadArchive: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(false))), confirmThreadDelete: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(true))), diffWordWrap: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(false))), + favorites: Schema.Array( + Schema.Struct({ + provider: ProviderKind, + model: TrimmedNonEmptyString, + }), + ).pipe(Schema.withDecodingDefault(Effect.succeed([]))), sidebarProjectGroupingMode: SidebarProjectGroupingMode.pipe( Schema.withDecodingDefault(Effect.succeed(DEFAULT_SIDEBAR_PROJECT_GROUPING_MODE)), ), @@ -241,6 +247,7 @@ const OpenCodeSettingsPatch = Schema.Struct({ }); export const ServerSettingsPatch = Schema.Struct({ + // Server settings enableAssistantStreaming: Schema.optionalKey(Schema.Boolean), defaultThreadEnvMode: Schema.optionalKey(ThreadEnvMode), addProjectBaseDirectory: Schema.optionalKey(Schema.String), @@ -261,3 +268,25 @@ export const ServerSettingsPatch = Schema.Struct({ ), }); export type ServerSettingsPatch = typeof ServerSettingsPatch.Type; + +export const ClientSettingsPatch = Schema.Struct({ + confirmThreadArchive: Schema.optionalKey(Schema.Boolean), + confirmThreadDelete: Schema.optionalKey(Schema.Boolean), + diffWordWrap: Schema.optionalKey(Schema.Boolean), + favorites: Schema.optionalKey( + Schema.Array( + Schema.Struct({ + provider: ProviderKind, + model: TrimmedNonEmptyString, + }), + ), + ), + sidebarProjectGroupingMode: Schema.optionalKey(SidebarProjectGroupingMode), + sidebarProjectGroupingOverrides: Schema.optionalKey( + Schema.Record(TrimmedNonEmptyString, SidebarProjectGroupingMode), + ), + sidebarProjectSortOrder: Schema.optionalKey(SidebarProjectSortOrder), + sidebarThreadSortOrder: Schema.optionalKey(SidebarThreadSortOrder), + timestampFormat: Schema.optionalKey(TimestampFormat), +}); +export type ClientSettingsPatch = typeof ClientSettingsPatch.Type; From 3b98fe3548831c536cf8c22d4b8a63e03e0a7d58 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sun, 19 Apr 2026 21:46:40 -0700 Subject: [PATCH 07/82] `effect-codex-app-server` (#1942) Co-authored-by: codex --- apps/server/package.json | 1 + apps/server/src/codexAppServerManager.test.ts | 1218 - apps/server/src/codexAppServerManager.ts | 1633 - .../src/git/Layers/CodexTextGeneration.ts | 8 +- .../provider/CodexDeveloperInstructions.ts | 134 + .../src/provider/Layers/CodexAdapter.test.ts | 698 +- .../src/provider/Layers/CodexAdapter.ts | 1293 +- .../src/provider/Layers/CodexProvider.ts | 919 +- .../Layers/CodexSessionRuntime.test.ts | 275 + .../provider/Layers/CodexSessionRuntime.ts | 1325 + .../provider/Layers/ProviderRegistry.test.ts | 843 +- apps/server/src/provider/codexAccount.ts | 123 - apps/server/src/provider/codexAppServer.ts | 242 - apps/server/src/provider/codexCliVersion.ts | 25 - apps/web/src/session-logic.test.ts | 1 - bun.lock | 18 + packages/effect-acp/src/_internal/stdio.ts | 7 +- packages/effect-codex-app-server/package.json | 48 + .../scripts/generate.ts | 772 + .../src/_generated/meta.gen.ts | 585 + .../src/_generated/namespaces.gen.ts | 180 + .../src/_generated/schema.gen.ts | 31734 ++++++++++++++++ .../src/_internal/shared.ts | 101 + .../src/_internal/stdio.ts | 57 + .../src/client.test.ts | 154 + .../effect-codex-app-server/src/client.ts | 300 + .../effect-codex-app-server/src/errors.ts | 151 + .../src/protocol.test.ts | 197 + .../effect-codex-app-server/src/protocol.ts | 394 + packages/effect-codex-app-server/src/rpc.ts | 1 + .../effect-codex-app-server/src/schema.ts | 3 + .../test/examples/codex-app-server-probe.ts | 62 + .../fixtures/codex-app-server-mock-peer.ts | 144 + .../effect-codex-app-server/tsconfig.json | 18 + scripts/release-smoke.ts | 1 + 35 files changed, 38195 insertions(+), 5470 deletions(-) delete mode 100644 apps/server/src/codexAppServerManager.test.ts delete mode 100644 apps/server/src/codexAppServerManager.ts create mode 100644 apps/server/src/provider/CodexDeveloperInstructions.ts create mode 100644 apps/server/src/provider/Layers/CodexSessionRuntime.test.ts create mode 100644 apps/server/src/provider/Layers/CodexSessionRuntime.ts delete mode 100644 apps/server/src/provider/codexAccount.ts delete mode 100644 apps/server/src/provider/codexAppServer.ts delete mode 100644 apps/server/src/provider/codexCliVersion.ts create mode 100644 packages/effect-codex-app-server/package.json create mode 100644 packages/effect-codex-app-server/scripts/generate.ts create mode 100644 packages/effect-codex-app-server/src/_generated/meta.gen.ts create mode 100644 packages/effect-codex-app-server/src/_generated/namespaces.gen.ts create mode 100644 packages/effect-codex-app-server/src/_generated/schema.gen.ts create mode 100644 packages/effect-codex-app-server/src/_internal/shared.ts create mode 100644 packages/effect-codex-app-server/src/_internal/stdio.ts create mode 100644 packages/effect-codex-app-server/src/client.test.ts create mode 100644 packages/effect-codex-app-server/src/client.ts create mode 100644 packages/effect-codex-app-server/src/errors.ts create mode 100644 packages/effect-codex-app-server/src/protocol.test.ts create mode 100644 packages/effect-codex-app-server/src/protocol.ts create mode 100644 packages/effect-codex-app-server/src/rpc.ts create mode 100644 packages/effect-codex-app-server/src/schema.ts create mode 100644 packages/effect-codex-app-server/test/examples/codex-app-server-probe.ts create mode 100644 packages/effect-codex-app-server/test/fixtures/codex-app-server-mock-peer.ts create mode 100644 packages/effect-codex-app-server/tsconfig.json diff --git a/apps/server/package.json b/apps/server/package.json index 250a667a57..14dbe35bcb 100644 --- a/apps/server/package.json +++ b/apps/server/package.json @@ -44,6 +44,7 @@ "@types/bun": "catalog:", "@types/node": "catalog:", "effect-acp": "workspace:*", + "effect-codex-app-server": "workspace:*", "tsdown": "catalog:", "typescript": "catalog:", "vitest": "catalog:" diff --git a/apps/server/src/codexAppServerManager.test.ts b/apps/server/src/codexAppServerManager.test.ts deleted file mode 100644 index 84225ef1ea..0000000000 --- a/apps/server/src/codexAppServerManager.test.ts +++ /dev/null @@ -1,1218 +0,0 @@ -import { describe, expect, it, vi } from "vitest"; -import { randomUUID } from "node:crypto"; -import { mkdtempSync, rmSync, writeFileSync } from "node:fs"; -import os from "node:os"; -import path from "node:path"; -import { ApprovalRequestId, ThreadId } from "@t3tools/contracts"; - -import { - buildCodexInitializeParams, - CODEX_DEFAULT_MODE_DEVELOPER_INSTRUCTIONS, - CODEX_PLAN_MODE_DEVELOPER_INSTRUCTIONS, - CodexAppServerManager, - classifyCodexStderrLine, - isRecoverableThreadResumeError, - normalizeCodexModelSlug, - readCodexAccountSnapshot, - resolveCodexModelForAccount, -} from "./codexAppServerManager.ts"; - -const asThreadId = (value: string): ThreadId => ThreadId.make(value); - -function createSendTurnHarness() { - 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", - }, - account: { - type: "unknown", - planType: null, - sparkEnabled: true, - }, - collabReceiverTurns: new Map(), - }; - - const requireSession = vi - .spyOn( - manager as unknown as { requireSession: (sessionId: string) => unknown }, - "requireSession", - ) - .mockReturnValue(context); - const sendRequest = vi - .spyOn( - manager as unknown as { sendRequest: (...args: unknown[]) => Promise }, - "sendRequest", - ) - .mockResolvedValue({ - turn: { - id: "turn_1", - }, - }); - const updateSession = vi - .spyOn(manager as unknown as { updateSession: (...args: unknown[]) => void }, "updateSession") - .mockImplementation(() => {}); - - return { manager, context, requireSession, sendRequest, updateSession }; -} - -function createThreadControlHarness() { - 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", - }, - collabReceiverTurns: new Map(), - }; - - const requireSession = vi - .spyOn( - manager as unknown as { requireSession: (sessionId: string) => unknown }, - "requireSession", - ) - .mockReturnValue(context); - const sendRequest = vi.spyOn( - manager as unknown as { sendRequest: (...args: unknown[]) => Promise }, - "sendRequest", - ); - const updateSession = vi - .spyOn(manager as unknown as { updateSession: (...args: unknown[]) => void }, "updateSession") - .mockImplementation(() => {}); - - 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.make("req-user-input-1"), - { - requestId: ApprovalRequestId.make("req-user-input-1"), - jsonRpcId: 42, - threadId: asThreadId("thread_1"), - }, - ], - ]), - collabReceiverTurns: new Map(), - }; - - 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 }; -} - -function createCollabNotificationHarness() { - const manager = new CodexAppServerManager(); - const context = { - session: { - provider: "codex", - status: "running", - threadId: asThreadId("thread_1"), - runtimeMode: "full-access", - model: "gpt-5.3-codex", - activeTurnId: "turn_parent", - resumeCursor: { threadId: "provider_parent" }, - createdAt: "2026-02-10T00:00:00.000Z", - updatedAt: "2026-02-10T00:00:00.000Z", - }, - account: { - type: "unknown", - planType: null, - sparkEnabled: true, - }, - pending: new Map(), - pendingApprovals: new Map(), - pendingUserInputs: new Map(), - collabReceiverTurns: new Map(), - nextRequestId: 1, - stopping: false, - }; - - const emitEvent = vi - .spyOn(manager as unknown as { emitEvent: (...args: unknown[]) => void }, "emitEvent") - .mockImplementation(() => {}); - const updateSession = vi - .spyOn(manager as unknown as { updateSession: (...args: unknown[]) => void }, "updateSession") - .mockImplementation(() => {}); - - return { manager, context, emitEvent, updateSession }; -} - -describe("classifyCodexStderrLine", () => { - it("ignores empty lines", () => { - expect(classifyCodexStderrLine(" ")).toBeNull(); - }); - - it("ignores non-error structured codex logs", () => { - const line = - "2026-02-08T04:24:19.241256Z WARN codex_core::features: unknown feature key in config: skills"; - expect(classifyCodexStderrLine(line)).toBeNull(); - }); - - it("ignores known benign rollout path errors", () => { - const line = - "\u001b[2m2026-02-08T04:24:20.085687Z\u001b[0m \u001b[31mERROR\u001b[0m \u001b[2mcodex_core::rollout::list\u001b[0m: state db missing rollout path for thread 019c3b6c-46b8-7b70-ad23-82f824d161fb"; - expect(classifyCodexStderrLine(line)).toBeNull(); - }); - - it("keeps unknown structured errors", () => { - const line = "2026-02-08T04:24:20.085687Z ERROR codex_core::runtime: unrecoverable failure"; - expect(classifyCodexStderrLine(line)).toEqual({ - message: line, - }); - }); - - it("keeps plain stderr messages", () => { - const line = "fatal: permission denied"; - expect(classifyCodexStderrLine(line)).toEqual({ - message: line, - }); - }); -}); - -describe("process stderr events", () => { - it("emits classified stderr lines as notifications", () => { - const manager = new CodexAppServerManager(); - const emitEvent = vi - .spyOn(manager as unknown as { emitEvent: (...args: unknown[]) => void }, "emitEvent") - .mockImplementation(() => {}); - - ( - manager as unknown as { - emitNotificationEvent: ( - context: { session: { threadId: ThreadId } }, - method: string, - message: string, - ) => void; - } - ).emitNotificationEvent( - { - session: { - threadId: asThreadId("thread-1"), - }, - }, - "process/stderr", - "fatal: permission denied", - ); - - expect(emitEvent).toHaveBeenCalledWith( - expect.objectContaining({ - kind: "notification", - method: "process/stderr", - threadId: "thread-1", - message: "fatal: permission denied", - }), - ); - }); -}); - -describe("normalizeCodexModelSlug", () => { - it("maps 5.3 aliases to gpt-5.3-codex", () => { - expect(normalizeCodexModelSlug("5.3")).toBe("gpt-5.3-codex"); - expect(normalizeCodexModelSlug("gpt-5.3")).toBe("gpt-5.3-codex"); - }); - - it("prefers codex id when model differs", () => { - expect(normalizeCodexModelSlug("gpt-5.3", "gpt-5.3-codex")).toBe("gpt-5.3-codex"); - }); - - it("keeps non-aliased models as-is", () => { - expect(normalizeCodexModelSlug("gpt-5.2-codex")).toBe("gpt-5.2-codex"); - expect(normalizeCodexModelSlug("gpt-5.2")).toBe("gpt-5.2"); - }); -}); - -describe("isRecoverableThreadResumeError", () => { - it("matches not-found resume errors", () => { - expect( - isRecoverableThreadResumeError(new Error("thread/resume failed: thread not found")), - ).toBe(true); - }); - - it("ignores non-resume errors", () => { - expect( - isRecoverableThreadResumeError(new Error("thread/start failed: permission denied")), - ).toBe(false); - }); - - it("ignores non-recoverable resume errors", () => { - expect( - isRecoverableThreadResumeError( - new Error("thread/resume failed: timed out waiting for server"), - ), - ).toBe(false); - }); -}); - -describe("readCodexAccountSnapshot", () => { - it("disables spark for chatgpt plus accounts", () => { - expect( - readCodexAccountSnapshot({ - type: "chatgpt", - email: "plus@example.com", - planType: "plus", - }), - ).toEqual({ - type: "chatgpt", - planType: "plus", - sparkEnabled: false, - }); - }); - - it("keeps spark enabled for chatgpt pro accounts", () => { - expect( - readCodexAccountSnapshot({ - type: "chatgpt", - email: "pro@example.com", - planType: "pro", - }), - ).toEqual({ - type: "chatgpt", - planType: "pro", - sparkEnabled: true, - }); - }); - - it("disables spark for api key accounts", () => { - expect( - readCodexAccountSnapshot({ - type: "apiKey", - }), - ).toEqual({ - type: "apiKey", - planType: null, - sparkEnabled: false, - }); - }); - - it("disables spark for unknown chatgpt plans", () => { - expect( - readCodexAccountSnapshot({ - type: "chatgpt", - email: "unknown@example.com", - }), - ).toEqual({ - type: "chatgpt", - planType: "unknown", - sparkEnabled: false, - }); - }); -}); - -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"); - }); - - it("falls back from spark to default for api key auth", () => { - expect( - resolveCodexModelForAccount("gpt-5.3-codex-spark", { - type: "apiKey", - planType: null, - sparkEnabled: false, - }), - ).toBe("gpt-5.3-codex"); - }); -}); - -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 }> = []; - manager.on("event", (event) => { - events.push({ - method: event.method, - kind: event.kind, - ...(event.message ? { message: event.message } : {}), - }); - }); - - const processCwd = vi.spyOn(process, "cwd").mockImplementation(() => { - throw new Error("cwd missing"); - }); - try { - await expect( - manager.startSession({ - threadId: asThreadId("thread-1"), - provider: "codex", - binaryPath: "codex", - runtimeMode: "full-access", - }), - ).rejects.toThrow("cwd missing"); - expect(events).toHaveLength(1); - expect(events[0]).toEqual({ - method: "session/startFailed", - kind: "error", - message: "cwd missing", - }); - } finally { - processCwd.mockRestore(); - manager.stopAll(); - } - }); - - it("fails fast with an upgrade message when codex is below the minimum supported version", async () => { - const manager = new CodexAppServerManager(); - const events: Array<{ method: string; kind: string; message?: string }> = []; - manager.on("event", (event) => { - events.push({ - method: event.method, - kind: event.kind, - ...(event.message ? { message: event.message } : {}), - }); - }); - - const versionCheck = vi - .spyOn( - manager as unknown as { - assertSupportedCodexCliVersion: (input: { - binaryPath: string; - cwd: string; - homePath?: string; - }) => void; - }, - "assertSupportedCodexCliVersion", - ) - .mockImplementation(() => { - throw new Error( - "Codex CLI v0.36.0 is too old for T3 Code. Upgrade to v0.37.0 or newer and restart T3 Code.", - ); - }); - - try { - await expect( - manager.startSession({ - threadId: asThreadId("thread-1"), - provider: "codex", - binaryPath: "codex", - runtimeMode: "full-access", - }), - ).rejects.toThrow( - "Codex CLI v0.36.0 is too old for T3 Code. Upgrade to v0.37.0 or newer and restart T3 Code.", - ); - expect(versionCheck).toHaveBeenCalledTimes(1); - expect(events).toEqual([ - { - method: "session/startFailed", - kind: "error", - message: - "Codex CLI v0.36.0 is too old for T3 Code. Upgrade to v0.37.0 or newer and restart T3 Code.", - }, - ]); - } finally { - versionCheck.mockRestore(); - manager.stopAll(); - } - }); - - it("disposes an existing session before starting a replacement for the same thread", async () => { - const manager = new CodexAppServerManager(); - const existingContext = { - session: { - provider: "codex", - status: "ready", - threadId: asThreadId("thread-1"), - runtimeMode: "full-access", - createdAt: "2026-02-10T00:00:00.000Z", - updatedAt: "2026-02-10T00:00:00.000Z", - }, - }; - - ( - manager as unknown as { - sessions: Map; - } - ).sessions.set(asThreadId("thread-1"), existingContext); - - const disposeSession = vi - .spyOn( - manager as unknown as { - disposeSession: ( - context: typeof existingContext, - options?: { readonly emitLifecycleEvent?: boolean }, - ) => void; - }, - "disposeSession", - ) - .mockImplementation(() => {}); - const assertSupportedCodexCliVersion = vi - .spyOn( - manager as unknown as { - assertSupportedCodexCliVersion: (input: { - binaryPath: string; - cwd: string; - homePath?: string; - }) => void; - }, - "assertSupportedCodexCliVersion", - ) - .mockImplementation(() => {}); - const processCwd = vi.spyOn(process, "cwd").mockImplementation(() => { - throw new Error("cwd missing"); - }); - - try { - await expect( - manager.startSession({ - threadId: asThreadId("thread-1"), - provider: "codex", - binaryPath: "codex", - runtimeMode: "full-access", - }), - ).rejects.toThrow("cwd missing"); - - expect(disposeSession).toHaveBeenCalledWith(existingContext, { - emitLifecycleEvent: false, - }); - expect(assertSupportedCodexCliVersion).not.toHaveBeenCalled(); - } finally { - disposeSession.mockRestore(); - assertSupportedCodexCliVersion.mockRestore(); - processCwd.mockRestore(); - ( - manager as unknown as { - sessions: Map; - } - ).sessions.clear(); - manager.stopAll(); - } - }); - - it("continues replacement start when existing session disposal fails", async () => { - const manager = new CodexAppServerManager(); - const existingContext = { - session: { - provider: "codex", - status: "ready", - threadId: asThreadId("thread-1"), - runtimeMode: "full-access", - createdAt: "2026-02-10T00:00:00.000Z", - updatedAt: "2026-02-10T00:00:00.000Z", - }, - }; - - ( - manager as unknown as { - sessions: Map; - } - ).sessions.set(asThreadId("thread-1"), existingContext); - - const disposeSession = vi - .spyOn( - manager as unknown as { - disposeSession: ( - context: typeof existingContext, - options?: { readonly emitLifecycleEvent?: boolean }, - ) => void; - }, - "disposeSession", - ) - .mockImplementation(() => { - throw new Error("dispose failed"); - }); - const assertSupportedCodexCliVersion = vi - .spyOn( - manager as unknown as { - assertSupportedCodexCliVersion: (input: { - binaryPath: string; - cwd: string; - homePath?: string; - }) => void; - }, - "assertSupportedCodexCliVersion", - ) - .mockImplementation(() => {}); - const processCwd = vi.spyOn(process, "cwd").mockImplementation(() => { - throw new Error("cwd missing"); - }); - - try { - await expect( - manager.startSession({ - threadId: asThreadId("thread-1"), - provider: "codex", - binaryPath: "codex", - runtimeMode: "full-access", - }), - ).rejects.toThrow("cwd missing"); - - expect(disposeSession).toHaveBeenCalledWith(existingContext, { - emitLifecycleEvent: false, - }); - expect(assertSupportedCodexCliVersion).not.toHaveBeenCalled(); - } finally { - disposeSession.mockRestore(); - assertSupportedCodexCliVersion.mockRestore(); - processCwd.mockRestore(); - ( - manager as unknown as { - sessions: Map; - } - ).sessions.clear(); - manager.stopAll(); - } - }); -}); - -describe("sendTurn", () => { - it("sends text and image user input items to turn/start", async () => { - const { manager, context, requireSession, sendRequest, updateSession } = - createSendTurnHarness(); - - const result = await manager.sendTurn({ - threadId: asThreadId("thread_1"), - input: "Inspect this image", - attachments: [ - { - type: "image", - url: "data:image/png;base64,AAAA", - }, - ], - model: "gpt-5.3", - serviceTier: "fast", - effort: "high", - }); - - expect(result).toEqual({ - threadId: "thread_1", - turnId: "turn_1", - resumeCursor: { threadId: "thread_1" }, - }); - expect(requireSession).toHaveBeenCalledWith("thread_1"); - expect(sendRequest).toHaveBeenCalledWith(context, "turn/start", { - threadId: "thread_1", - input: [ - { - type: "text", - text: "Inspect this image", - text_elements: [], - }, - { - type: "image", - url: "data:image/png;base64,AAAA", - }, - ], - model: "gpt-5.3-codex", - serviceTier: "fast", - effort: "high", - }); - expect(updateSession).toHaveBeenCalledWith(context, { - status: "running", - activeTurnId: "turn_1", - resumeCursor: { threadId: "thread_1" }, - }); - }); - - it("supports image-only turns", async () => { - const { manager, context, sendRequest } = createSendTurnHarness(); - - await manager.sendTurn({ - threadId: asThreadId("thread_1"), - attachments: [ - { - type: "image", - url: "data:image/png;base64,BBBB", - }, - ], - }); - - expect(sendRequest).toHaveBeenCalledWith(context, "turn/start", { - threadId: "thread_1", - input: [ - { - type: "image", - 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, - }, - }, - }); - }); - - it("rejects empty turn input", async () => { - const { manager } = createSendTurnHarness(); - - await expect( - manager.sendTurn({ - threadId: asThreadId("thread_1"), - }), - ).rejects.toThrow("Turn input must include text or attachments."); - }); -}); - -describe("thread checkpoint control", () => { - it("reads thread turns from thread/read", async () => { - const { manager, context, requireSession, sendRequest } = createThreadControlHarness(); - sendRequest.mockResolvedValue({ - thread: { - id: "thread_1", - turns: [ - { - id: "turn_1", - items: [{ type: "userMessage", content: [{ type: "text", text: "hello" }] }], - }, - ], - }, - }); - - const result = await manager.readThread(asThreadId("thread_1")); - - expect(requireSession).toHaveBeenCalledWith("thread_1"); - expect(sendRequest).toHaveBeenCalledWith(context, "thread/read", { - threadId: "thread_1", - includeTurns: true, - }); - expect(result).toEqual({ - threadId: "thread_1", - turns: [ - { - id: "turn_1", - items: [{ type: "userMessage", content: [{ type: "text", text: "hello" }] }], - }, - ], - }); - }); - - it("reads thread turns from flat thread/read responses", async () => { - const { manager, context, sendRequest } = createThreadControlHarness(); - sendRequest.mockResolvedValue({ - threadId: "thread_1", - turns: [ - { - id: "turn_1", - items: [{ type: "userMessage", content: [{ type: "text", text: "hello" }] }], - }, - ], - }); - - const result = await manager.readThread(asThreadId("thread_1")); - - expect(sendRequest).toHaveBeenCalledWith(context, "thread/read", { - threadId: "thread_1", - includeTurns: true, - }); - expect(result).toEqual({ - threadId: "thread_1", - turns: [ - { - id: "turn_1", - items: [{ type: "userMessage", content: [{ type: "text", text: "hello" }] }], - }, - ], - }); - }); - - it("rolls back turns via thread/rollback and resets session running state", async () => { - const { manager, context, sendRequest, updateSession } = createThreadControlHarness(); - sendRequest.mockResolvedValue({ - thread: { - id: "thread_1", - turns: [], - }, - }); - - const result = await manager.rollbackThread(asThreadId("thread_1"), 2); - - expect(sendRequest).toHaveBeenCalledWith(context, "thread/rollback", { - threadId: "thread_1", - numTurns: 2, - }); - expect(updateSession).toHaveBeenCalledWith(context, { - status: "ready", - activeTurnId: undefined, - }); - expect(result).toEqual({ - threadId: "thread_1", - turns: [], - }); - }); -}); - -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.make("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.make("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(), - collabReceiverTurns: 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, - ) => 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("collab child conversation routing", () => { - it("rewrites child notification turn ids onto the parent turn", () => { - const { manager, context, emitEvent } = createCollabNotificationHarness(); - - ( - manager as unknown as { - handleServerNotification: (context: unknown, notification: Record) => void; - } - ).handleServerNotification(context, { - method: "item/completed", - params: { - item: { - type: "collabAgentToolCall", - id: "call_collab_1", - receiverThreadIds: ["child_provider_1"], - }, - threadId: "provider_parent", - turnId: "turn_parent", - }, - }); - - ( - manager as unknown as { - handleServerNotification: (context: unknown, notification: Record) => void; - } - ).handleServerNotification(context, { - method: "item/agentMessage/delta", - params: { - threadId: "child_provider_1", - turnId: "turn_child_1", - itemId: "msg_child_1", - delta: "working", - }, - }); - - expect(emitEvent).toHaveBeenLastCalledWith( - expect.objectContaining({ - method: "item/agentMessage/delta", - turnId: "turn_parent", - itemId: "msg_child_1", - }), - ); - }); - - it("suppresses child lifecycle notifications so they cannot replace the parent turn", () => { - const { manager, context, emitEvent, updateSession } = createCollabNotificationHarness(); - - ( - manager as unknown as { - handleServerNotification: (context: unknown, notification: Record) => void; - } - ).handleServerNotification(context, { - method: "item/completed", - params: { - item: { - type: "collabAgentToolCall", - id: "call_collab_1", - receiverThreadIds: ["child_provider_1"], - }, - threadId: "provider_parent", - turnId: "turn_parent", - }, - }); - emitEvent.mockClear(); - updateSession.mockClear(); - - ( - manager as unknown as { - handleServerNotification: (context: unknown, notification: Record) => void; - } - ).handleServerNotification(context, { - method: "turn/started", - params: { - threadId: "child_provider_1", - turn: { id: "turn_child_1" }, - }, - }); - - ( - manager as unknown as { - handleServerNotification: (context: unknown, notification: Record) => void; - } - ).handleServerNotification(context, { - method: "turn/completed", - params: { - threadId: "child_provider_1", - turn: { id: "turn_child_1", status: "completed" }, - }, - }); - - expect(emitEvent).not.toHaveBeenCalled(); - expect(updateSession).not.toHaveBeenCalled(); - }); - - it("rewrites child approval requests onto the parent turn", () => { - const { manager, context, emitEvent } = createCollabNotificationHarness(); - - ( - manager as unknown as { - handleServerNotification: (context: unknown, notification: Record) => void; - } - ).handleServerNotification(context, { - method: "item/completed", - params: { - item: { - type: "collabAgentToolCall", - id: "call_collab_1", - receiverThreadIds: ["child_provider_1"], - }, - threadId: "provider_parent", - turnId: "turn_parent", - }, - }); - emitEvent.mockClear(); - - ( - manager as unknown as { - handleServerRequest: (context: unknown, request: Record) => void; - } - ).handleServerRequest(context, { - id: 42, - method: "item/commandExecution/requestApproval", - params: { - threadId: "child_provider_1", - turnId: "turn_child_1", - itemId: "call_child_1", - command: "bun install", - }, - }); - - expect(Array.from(context.pendingApprovals.values())[0]).toEqual( - expect.objectContaining({ - turnId: "turn_parent", - itemId: "call_child_1", - }), - ); - expect(emitEvent).toHaveBeenCalledWith( - expect.objectContaining({ - method: "item/commandExecution/requestApproval", - turnId: "turn_parent", - itemId: "call_child_1", - }), - ); - }); -}); - -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", - 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, - 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); -}); diff --git a/apps/server/src/codexAppServerManager.ts b/apps/server/src/codexAppServerManager.ts deleted file mode 100644 index ba776890ee..0000000000 --- a/apps/server/src/codexAppServerManager.ts +++ /dev/null @@ -1,1633 +0,0 @@ -import { type ChildProcessWithoutNullStreams, spawn, spawnSync } from "node:child_process"; -import { randomUUID } from "node:crypto"; -import { EventEmitter } from "node:events"; -import readline from "node:readline"; - -import { - ApprovalRequestId, - EventId, - ProviderItemId, - ProviderRequestKind, - type ProviderUserInputAnswers, - ThreadId, - TurnId, - type ProviderApprovalDecision, - type ProviderEvent, - type ProviderSession, - type ProviderTurnStartResult, - RuntimeMode, - ProviderInteractionMode, -} from "@t3tools/contracts"; -import { normalizeModelSlug } from "@t3tools/shared/model"; -import { Effect, Context } from "effect"; - -import { - formatCodexCliUpgradeMessage, - isCodexCliVersionSupported, - parseCodexCliVersion, -} from "./provider/codexCliVersion.ts"; -import { - readCodexAccountSnapshot, - resolveCodexModelForAccount, - type CodexAccountSnapshot, -} from "./provider/codexAccount.ts"; -import { buildCodexInitializeParams, killCodexChildProcess } from "./provider/codexAppServer.ts"; -import { expandHomePath } from "./pathExpansion.ts"; - -export { buildCodexInitializeParams } from "./provider/codexAppServer.ts"; -export { readCodexAccountSnapshot, resolveCodexModelForAccount } from "./provider/codexAccount.ts"; - -type PendingRequestKey = string; - -interface PendingRequest { - method: string; - timeout: ReturnType; - resolve: (value: unknown) => void; - reject: (error: Error) => void; -} - -interface PendingApprovalRequest { - requestId: ApprovalRequestId; - jsonRpcId: string | number; - method: - | "item/commandExecution/requestApproval" - | "item/fileChange/requestApproval" - | "item/fileRead/requestApproval"; - requestKind: ProviderRequestKind; - threadId: ThreadId; - turnId?: TurnId; - itemId?: ProviderItemId; -} - -interface PendingUserInputRequest { - requestId: ApprovalRequestId; - jsonRpcId: string | number; - threadId: ThreadId; - turnId?: TurnId; - itemId?: ProviderItemId; -} - -interface CodexUserInputAnswer { - answers: string[]; -} - -interface CodexSessionContext { - session: ProviderSession; - account: CodexAccountSnapshot; - child: ChildProcessWithoutNullStreams; - output: readline.Interface; - pending: Map; - pendingApprovals: Map; - pendingUserInputs: Map; - collabReceiverTurns: Map; - nextRequestId: number; - stopping: boolean; -} - -interface JsonRpcError { - code?: number; - message?: string; -} - -interface JsonRpcRequest { - id: string | number; - method: string; - params?: unknown; -} - -interface JsonRpcResponse { - id: string | number; - result?: unknown; - error?: JsonRpcError; -} - -interface JsonRpcNotification { - method: string; - params?: unknown; -} - -export interface CodexAppServerSendTurnInput { - readonly threadId: ThreadId; - readonly input?: string; - readonly attachments?: ReadonlyArray<{ type: "image"; url: string }>; - readonly model?: string; - readonly serviceTier?: string | null; - readonly effort?: string; - readonly interactionMode?: ProviderInteractionMode; -} - -export interface CodexAppServerStartSessionInput { - readonly threadId: ThreadId; - readonly provider?: "codex"; - readonly cwd?: string; - readonly model?: string; - readonly serviceTier?: string; - readonly resumeCursor?: unknown; - readonly binaryPath: string; - readonly homePath?: string; - readonly runtimeMode: RuntimeMode; -} - -export interface CodexThreadTurnSnapshot { - id: TurnId; - items: unknown[]; -} - -export interface CodexThreadSnapshot { - threadId: string; - turns: CodexThreadTurnSnapshot[]; -} - -const CODEX_VERSION_CHECK_TIMEOUT_MS = 4_000; - -const ANSI_ESCAPE_CHAR = String.fromCharCode(27); -const ANSI_ESCAPE_REGEX = new RegExp(`${ANSI_ESCAPE_CHAR}\\[[0-9;]*m`, "g"); -const CODEX_STDERR_LOG_REGEX = - /^\d{4}-\d{2}-\d{2}T\S+\s+(TRACE|DEBUG|INFO|WARN|ERROR)\s+\S+:\s+(.*)$/; -const BENIGN_ERROR_LOG_SNIPPETS = [ - "state db missing rollout path for thread", - "state db record_discrepancy: find_thread_path_by_id_str_in_subdir, falling_back", -]; -const RECOVERABLE_THREAD_RESUME_ERROR_SNIPPETS = [ - "not found", - "missing thread", - "no such thread", - "unknown thread", - "does not exist", -]; -export const CODEX_PLAN_MODE_DEVELOPER_INSTRUCTIONS = `# Plan Mode (Conversational) - -You work in 3 phases, and you should *chat your way* to a great plan before finalizing it. A great plan is very detailed-intent- and implementation-wise-so that it can be handed to another engineer or agent to be implemented right away. It must be **decision complete**, where the implementer does not need to make any decisions. - -## Mode rules (strict) - -You are in **Plan Mode** until a developer message explicitly ends it. - -Plan Mode is not changed by user intent, tone, or imperative language. If a user asks for execution while still in Plan Mode, treat it as a request to **plan the execution**, not perform it. - -## Plan Mode vs update_plan tool - -Plan Mode is a collaboration mode that can involve requesting user input and eventually issuing a \`\` block. - -Separately, \`update_plan\` is a checklist/progress/TODOs tool; it does not enter or exit Plan Mode. Do not confuse it with Plan mode or try to use it while in Plan mode. If you try to use \`update_plan\` in Plan mode, it will return an error. - -## Execution vs. mutation in Plan Mode - -You may explore and execute **non-mutating** actions that improve the plan. You must not perform **mutating** actions. - -### Allowed (non-mutating, plan-improving) - -Actions that gather truth, reduce ambiguity, or validate feasibility without changing repo-tracked state. Examples: - -* Reading or searching files, configs, schemas, types, manifests, and docs -* Static analysis, inspection, and repo exploration -* Dry-run style commands when they do not edit repo-tracked files -* Tests, builds, or checks that may write to caches or build artifacts (for example, \`target/\`, \`.cache/\`, or snapshots) so long as they do not edit repo-tracked files - -### Not allowed (mutating, plan-executing) - -Actions that implement the plan or change repo-tracked state. Examples: - -* Editing or writing files -* Running formatters or linters that rewrite files -* Applying patches, migrations, or codegen that updates repo-tracked files -* Side-effectful commands whose purpose is to carry out the plan rather than refine it - -When in doubt: if the action would reasonably be described as "doing the work" rather than "planning the work," do not do it. - -## PHASE 1 - Ground in the environment (explore first, ask second) - -Begin by grounding yourself in the actual environment. Eliminate unknowns in the prompt by discovering facts, not by asking the user. Resolve all questions that can be answered through exploration or inspection. Identify missing or ambiguous details only if they cannot be derived from the environment. Silent exploration between turns is allowed and encouraged. - -Before asking the user any question, perform at least one targeted non-mutating exploration pass (for example: search relevant files, inspect likely entrypoints/configs, confirm current implementation shape), unless no local environment/repo is available. - -Exception: you may ask clarifying questions about the user's prompt before exploring, ONLY if there are obvious ambiguities or contradictions in the prompt itself. However, if ambiguity might be resolved by exploring, always prefer exploring first. - -Do not ask questions that can be answered from the repo or system (for example, "where is this struct?" or "which UI component should we use?" when exploration can make it clear). Only ask once you have exhausted reasonable non-mutating exploration. - -## PHASE 2 - Intent chat (what they actually want) - -* Keep asking until you can clearly state: goal + success criteria, audience, in/out of scope, constraints, current state, and the key preferences/tradeoffs. -* Bias toward questions over guessing: if any high-impact ambiguity remains, do NOT plan yet-ask. - -## PHASE 3 - Implementation chat (what/how we'll build) - -* Once intent is stable, keep asking until the spec is decision complete: approach, interfaces (APIs/schemas/I/O), data flow, edge cases/failure modes, testing + acceptance criteria, rollout/monitoring, and any migrations/compat constraints. - -## Asking questions - -Critical rules: - -* Strongly prefer using the \`request_user_input\` tool to ask any questions. -* Offer only meaningful multiple-choice options; don't include filler choices that are obviously wrong or irrelevant. -* In rare cases where an unavoidable, important question can't be expressed with reasonable multiple-choice options (due to extreme ambiguity), you may ask it directly without the tool. - -You SHOULD ask many questions, but each question must: - -* materially change the spec/plan, OR -* confirm/lock an assumption, OR -* choose between meaningful tradeoffs. -* not be answerable by non-mutating commands. - -Use the \`request_user_input\` tool only for decisions that materially change the plan, for confirming important assumptions, or for information that cannot be discovered via non-mutating exploration. - -## Two kinds of unknowns (treat differently) - -1. **Discoverable facts** (repo/system truth): explore first. - - * Before asking, run targeted searches and check likely sources of truth (configs/manifests/entrypoints/schemas/types/constants). - * Ask only if: multiple plausible candidates; nothing found but you need a missing identifier/context; or ambiguity is actually product intent. - * If asking, present concrete candidates (paths/service names) + recommend one. - * Never ask questions you can answer from your environment (e.g., "where is this struct"). - -2. **Preferences/tradeoffs** (not discoverable): ask early. - - * These are intent or implementation preferences that cannot be derived from exploration. - * Provide 2-4 mutually exclusive options + a recommended default. - * If unanswered, proceed with the recommended option and record it as an assumption in the final plan. - -## Finalization rule - -Only output the final plan when it is decision complete and leaves no decisions to the implementer. - -When you present the official plan, wrap it in a \`\` block so the client can render it specially: - -1) The opening tag must be on its own line. -2) Start the plan content on the next line (no text on the same line as the tag). -3) The closing tag must be on its own line. -4) Use Markdown inside the block. -5) Keep the tags exactly as \`\` and \`\` (do not translate or rename them), even if the plan content is in another language. - -Example: - - -plan content - - -plan content should be human and agent digestible. The final plan must be plan-only and include: - -* A clear title -* A brief summary section -* Important changes or additions to public APIs/interfaces/types -* Test cases and scenarios -* Explicit assumptions and defaults chosen where needed - -Do not ask "should I proceed?" in the final output. The user can easily switch out of Plan mode and request implementation if you have included a \`\` block in your response. Alternatively, they can decide to stay in Plan mode and continue refining the plan. - -Only produce at most one \`\` block per turn, and only when you are presenting a complete spec. -`; - -export const CODEX_DEFAULT_MODE_DEVELOPER_INSTRUCTIONS = `# Collaboration Mode: Default - -You are now in Default mode. Any previous instructions for other modes (e.g. Plan mode) are no longer active. - -Your active mode changes only when new developer instructions with a different \`...\` change it; user requests or tool descriptions do not change mode by themselves. Known mode names are Default and Plan. - -## request_user_input availability - -The \`request_user_input\` tool is unavailable in Default mode. If you call it while in Default mode, it will return an error. - -In Default mode, strongly prefer making reasonable assumptions and executing the user's request rather than stopping to ask questions. If you absolutely must ask a question because the answer cannot be discovered from local context and a reasonable assumption would be risky, ask the user directly with a concise plain-text question. Never write a multiple choice question as a textual assistant message. -`; - -function mapCodexRuntimeMode(runtimeMode: RuntimeMode): { - readonly approvalPolicy: "untrusted" | "on-request" | "never"; - readonly sandbox: "read-only" | "workspace-write" | "danger-full-access"; -} { - switch (runtimeMode) { - case "approval-required": - return { - approvalPolicy: "untrusted", - sandbox: "read-only", - }; - case "auto-accept-edits": - return { - approvalPolicy: "on-request", - sandbox: "workspace-write", - }; - case "full-access": - return { - approvalPolicy: "never", - sandbox: "danger-full-access", - }; - } -} - -/** - * On Windows with `shell: true`, `child.kill()` only terminates the `cmd.exe` - * wrapper, leaving the actual command running. Use `taskkill /T` to kill the - * entire process tree instead. - */ -function killChildTree(child: ChildProcessWithoutNullStreams): void { - killCodexChildProcess(child); -} - -export function normalizeCodexModelSlug( - model: string | undefined | null, - preferredId?: string, -): string | undefined { - const normalized = normalizeModelSlug(model); - if (!normalized) { - return undefined; - } - - if (preferredId?.endsWith("-codex") && preferredId !== normalized) { - return preferredId; - } - - return normalized; -} - -function buildCodexCollaborationMode(input: { - readonly interactionMode?: "default" | "plan"; - readonly model?: string; - readonly effort?: string; -}): - | { - mode: "default" | "plan"; - settings: { - model: string; - reasoning_effort: string; - developer_instructions: string; - }; - } - | undefined { - if (input.interactionMode === undefined) { - return undefined; - } - const model = normalizeCodexModelSlug(input.model) ?? "gpt-5.3-codex"; - return { - mode: input.interactionMode, - settings: { - model, - reasoning_effort: input.effort ?? "medium", - developer_instructions: - input.interactionMode === "plan" - ? CODEX_PLAN_MODE_DEVELOPER_INSTRUCTIONS - : CODEX_DEFAULT_MODE_DEVELOPER_INSTRUCTIONS, - }, - }; -} - -function toCodexUserInputAnswer(value: unknown): CodexUserInputAnswer { - if (typeof value === "string") { - return { answers: [value] }; - } - - if (Array.isArray(value)) { - const answers = value.filter((entry): entry is string => typeof entry === "string"); - return { answers }; - } - - if (value && typeof value === "object") { - const maybeAnswers = (value as { answers?: unknown }).answers; - if (Array.isArray(maybeAnswers)) { - const answers = maybeAnswers.filter((entry): entry is string => typeof entry === "string"); - return { answers }; - } - } - - throw new Error("User input answers must be strings or arrays of strings."); -} - -function toCodexUserInputAnswers( - answers: ProviderUserInputAnswers, -): Record { - return Object.fromEntries( - Object.entries(answers).map(([questionId, value]) => [ - questionId, - toCodexUserInputAnswer(value), - ]), - ); -} - -export function classifyCodexStderrLine(rawLine: string): { message: string } | null { - const line = rawLine.replaceAll(ANSI_ESCAPE_REGEX, "").trim(); - if (!line) { - return null; - } - - const match = line.match(CODEX_STDERR_LOG_REGEX); - if (match) { - const level = match[1]; - if (level && level !== "ERROR") { - return null; - } - - const isBenignError = BENIGN_ERROR_LOG_SNIPPETS.some((snippet) => line.includes(snippet)); - if (isBenignError) { - return null; - } - } - - return { message: line }; -} - -export function isRecoverableThreadResumeError(error: unknown): boolean { - const message = (error instanceof Error ? error.message : String(error)).toLowerCase(); - if (!message.includes("thread/resume")) { - return false; - } - - return RECOVERABLE_THREAD_RESUME_ERROR_SNIPPETS.some((snippet) => message.includes(snippet)); -} - -export interface CodexAppServerManagerEvents { - event: [event: ProviderEvent]; -} - -export class CodexAppServerManager extends EventEmitter { - private readonly sessions = new Map(); - - private runPromise: (effect: Effect.Effect) => Promise; - constructor(services?: Context.Context) { - super(); - this.runPromise = services ? Effect.runPromiseWith(services) : Effect.runPromise; - } - - async startSession(input: CodexAppServerStartSessionInput): Promise { - const threadId = input.threadId; - const now = new Date().toISOString(); - let context: CodexSessionContext | undefined; - - try { - const existingContext = this.sessions.get(threadId); - if (existingContext) { - await Effect.logWarning("codex app-server replacing existing session", { - threadId, - existingStatus: existingContext.session.status, - }).pipe(this.runPromise); - try { - this.disposeSession(existingContext, { - emitLifecycleEvent: false, - }); - } catch (error) { - await Effect.logWarning("codex app-server failed to dispose existing session", { - threadId, - existingStatus: existingContext.session.status, - cause: error instanceof Error ? error.message : String(error), - }).pipe(this.runPromise); - } - } - - const resolvedCwd = input.cwd ?? process.cwd(); - - const session: ProviderSession = { - provider: "codex", - status: "connecting", - runtimeMode: input.runtimeMode, - model: normalizeCodexModelSlug(input.model), - cwd: resolvedCwd, - threadId, - createdAt: now, - updatedAt: now, - }; - - const codexBinaryPath = input.binaryPath; - const codexHomePath = input.homePath; - this.assertSupportedCodexCliVersion({ - binaryPath: codexBinaryPath, - cwd: resolvedCwd, - ...(codexHomePath ? { homePath: codexHomePath } : {}), - }); - const child = spawn(codexBinaryPath, ["app-server"], { - cwd: resolvedCwd, - env: { - ...process.env, - ...(codexHomePath ? { CODEX_HOME: expandHomePath(codexHomePath) } : {}), - }, - stdio: ["pipe", "pipe", "pipe"], - shell: process.platform === "win32", - }); - const output = readline.createInterface({ input: child.stdout }); - - context = { - session, - account: { - type: "unknown", - planType: null, - sparkEnabled: true, - }, - child, - output, - pending: new Map(), - pendingApprovals: new Map(), - pendingUserInputs: new Map(), - collabReceiverTurns: new Map(), - nextRequestId: 1, - stopping: false, - }; - - this.sessions.set(threadId, context); - this.attachProcessListeners(context); - - this.emitLifecycleEvent(context, "session/connecting", "Starting codex app-server"); - - await this.sendRequest(context, "initialize", buildCodexInitializeParams()); - - this.writeMessage(context, { method: "initialized" }); - try { - const modelListResponse = await this.sendRequest(context, "model/list", {}); - console.log("codex model/list response", modelListResponse); - } catch (error) { - console.log("codex model/list failed", error); - } - try { - const accountReadResponse = await this.sendRequest(context, "account/read", {}); - console.log("codex account/read response", accountReadResponse); - context.account = readCodexAccountSnapshot(accountReadResponse); - console.log("codex subscription status", { - type: context.account.type, - planType: context.account.planType, - sparkEnabled: context.account.sparkEnabled, - }); - } catch (error) { - console.log("codex account/read failed", error); - } - - const normalizedModel = resolveCodexModelForAccount( - normalizeCodexModelSlug(input.model), - context.account, - ); - const sessionOverrides = { - model: normalizedModel ?? null, - ...(input.serviceTier !== undefined ? { serviceTier: input.serviceTier } : {}), - cwd: input.cwd ?? null, - ...mapCodexRuntimeMode(input.runtimeMode ?? "full-access"), - }; - - const threadStartParams = { - ...sessionOverrides, - experimentalRawEvents: false, - }; - const resumeThreadId = readResumeThreadId(input); - this.emitLifecycleEvent( - context, - "session/threadOpenRequested", - resumeThreadId - ? `Attempting to resume thread ${resumeThreadId}.` - : "Starting a new Codex thread.", - ); - await Effect.logInfo("codex app-server opening thread", { - threadId, - requestedRuntimeMode: input.runtimeMode, - requestedModel: normalizedModel ?? null, - requestedCwd: resolvedCwd, - resumeThreadId: resumeThreadId ?? null, - }).pipe(this.runPromise); - - let threadOpenMethod: "thread/start" | "thread/resume" = "thread/start"; - let threadOpenResponse: unknown; - if (resumeThreadId) { - try { - threadOpenMethod = "thread/resume"; - threadOpenResponse = await this.sendRequest(context, "thread/resume", { - ...sessionOverrides, - threadId: resumeThreadId, - }); - } catch (error) { - if (!isRecoverableThreadResumeError(error)) { - this.emitErrorEvent( - context, - "session/threadResumeFailed", - error instanceof Error ? error.message : "Codex thread resume failed.", - ); - await Effect.logWarning("codex app-server thread resume failed", { - threadId, - requestedRuntimeMode: input.runtimeMode, - resumeThreadId, - recoverable: false, - cause: error instanceof Error ? error.message : String(error), - }).pipe(this.runPromise); - throw error; - } - - threadOpenMethod = "thread/start"; - this.emitLifecycleEvent( - context, - "session/threadResumeFallback", - `Could not resume thread ${resumeThreadId}; started a new thread instead.`, - ); - await Effect.logWarning("codex app-server thread resume fell back to fresh start", { - threadId, - requestedRuntimeMode: input.runtimeMode, - resumeThreadId, - recoverable: true, - cause: error instanceof Error ? error.message : String(error), - }).pipe(this.runPromise); - threadOpenResponse = await this.sendRequest(context, "thread/start", threadStartParams); - } - } else { - threadOpenMethod = "thread/start"; - threadOpenResponse = await this.sendRequest(context, "thread/start", threadStartParams); - } - - const threadOpenRecord = this.readObject(threadOpenResponse); - const threadIdRaw = - this.readString(this.readObject(threadOpenRecord, "thread"), "id") ?? - this.readString(threadOpenRecord, "threadId"); - if (!threadIdRaw) { - throw new Error(`${threadOpenMethod} response did not include a thread id.`); - } - const providerThreadId = threadIdRaw; - - this.updateSession(context, { - status: "ready", - resumeCursor: { threadId: providerThreadId }, - }); - this.emitLifecycleEvent( - context, - "session/threadOpenResolved", - `Codex ${threadOpenMethod} resolved.`, - ); - await Effect.logInfo("codex app-server thread open resolved", { - threadId, - threadOpenMethod, - requestedResumeThreadId: resumeThreadId ?? null, - resolvedThreadId: providerThreadId, - requestedRuntimeMode: input.runtimeMode, - }).pipe(this.runPromise); - this.emitLifecycleEvent(context, "session/ready", `Connected to thread ${providerThreadId}`); - return { ...context.session }; - } catch (error) { - const message = error instanceof Error ? error.message : "Failed to start Codex session."; - if (context) { - this.updateSession(context, { - status: "error", - lastError: message, - }); - this.emitErrorEvent(context, "session/startFailed", message); - this.stopSession(threadId); - } else { - this.emitEvent({ - id: EventId.make(randomUUID()), - kind: "error", - provider: "codex", - threadId, - createdAt: new Date().toISOString(), - method: "session/startFailed", - message, - }); - } - throw new Error(message, { cause: error }); - } - } - - async sendTurn(input: CodexAppServerSendTurnInput): Promise { - const context = this.requireSession(input.threadId); - context.collabReceiverTurns.clear(); - - const turnInput: Array< - { type: "text"; text: string; text_elements: [] } | { type: "image"; url: string } - > = []; - if (input.input) { - turnInput.push({ - type: "text", - text: input.input, - text_elements: [], - }); - } - for (const attachment of input.attachments ?? []) { - if (attachment.type === "image") { - turnInput.push({ - type: "image", - url: attachment.url, - }); - } - } - if (turnInput.length === 0) { - throw new Error("Turn input must include text or attachments."); - } - - const providerThreadId = readResumeThreadId({ - threadId: context.session.threadId, - runtimeMode: context.session.runtimeMode, - resumeCursor: context.session.resumeCursor, - }); - if (!providerThreadId) { - throw new Error("Session is missing provider resume thread id."); - } - const turnStartParams: { - threadId: string; - input: Array< - { type: "text"; text: string; text_elements: [] } | { type: "image"; url: string } - >; - model?: string; - serviceTier?: string | null; - effort?: string; - collaborationMode?: { - mode: "default" | "plan"; - settings: { - model: string; - reasoning_effort: string; - developer_instructions: string; - }; - }; - } = { - threadId: providerThreadId, - input: turnInput, - }; - const normalizedModel = resolveCodexModelForAccount( - normalizeCodexModelSlug(input.model ?? context.session.model), - context.account, - ); - if (normalizedModel) { - turnStartParams.model = normalizedModel; - } - if (input.serviceTier !== undefined) { - turnStartParams.serviceTier = input.serviceTier; - } - if (input.effort) { - turnStartParams.effort = input.effort; - } - const collaborationMode = buildCodexCollaborationMode({ - ...(input.interactionMode !== undefined ? { interactionMode: input.interactionMode } : {}), - ...(normalizedModel !== undefined ? { model: normalizedModel } : {}), - ...(input.effort !== undefined ? { effort: input.effort } : {}), - }); - if (collaborationMode) { - if (!turnStartParams.model) { - turnStartParams.model = collaborationMode.settings.model; - } - turnStartParams.collaborationMode = collaborationMode; - } - - const response = await this.sendRequest(context, "turn/start", turnStartParams); - - const turn = this.readObject(this.readObject(response), "turn"); - const turnIdRaw = this.readString(turn, "id"); - if (!turnIdRaw) { - throw new Error("turn/start response did not include a turn id."); - } - const turnId = TurnId.make(turnIdRaw); - - this.updateSession(context, { - status: "running", - activeTurnId: turnId, - ...(context.session.resumeCursor !== undefined - ? { resumeCursor: context.session.resumeCursor } - : {}), - }); - - return { - threadId: context.session.threadId, - turnId, - ...(context.session.resumeCursor !== undefined - ? { resumeCursor: context.session.resumeCursor } - : {}), - }; - } - - async interruptTurn(threadId: ThreadId, turnId?: TurnId): Promise { - const context = this.requireSession(threadId); - const effectiveTurnId = turnId ?? context.session.activeTurnId; - - const providerThreadId = readResumeThreadId({ - threadId: context.session.threadId, - runtimeMode: context.session.runtimeMode, - resumeCursor: context.session.resumeCursor, - }); - if (!effectiveTurnId || !providerThreadId) { - return; - } - - await this.sendRequest(context, "turn/interrupt", { - threadId: providerThreadId, - turnId: effectiveTurnId, - }); - } - - async readThread(threadId: ThreadId): Promise { - const context = this.requireSession(threadId); - const providerThreadId = readResumeThreadId({ - threadId: context.session.threadId, - runtimeMode: context.session.runtimeMode, - resumeCursor: context.session.resumeCursor, - }); - if (!providerThreadId) { - throw new Error("Session is missing a provider resume thread id."); - } - - const response = await this.sendRequest(context, "thread/read", { - threadId: providerThreadId, - includeTurns: true, - }); - return this.parseThreadSnapshot("thread/read", response); - } - - async rollbackThread(threadId: ThreadId, numTurns: number): Promise { - const context = this.requireSession(threadId); - const providerThreadId = readResumeThreadId({ - threadId: context.session.threadId, - runtimeMode: context.session.runtimeMode, - resumeCursor: context.session.resumeCursor, - }); - if (!providerThreadId) { - throw new Error("Session is missing a provider resume thread id."); - } - if (!Number.isInteger(numTurns) || numTurns < 1) { - throw new Error("numTurns must be an integer >= 1."); - } - - const response = await this.sendRequest(context, "thread/rollback", { - threadId: providerThreadId, - numTurns, - }); - this.updateSession(context, { - status: "ready", - activeTurnId: undefined, - }); - return this.parseThreadSnapshot("thread/rollback", response); - } - - async respondToRequest( - threadId: ThreadId, - requestId: ApprovalRequestId, - decision: ProviderApprovalDecision, - ): Promise { - const context = this.requireSession(threadId); - const pendingRequest = context.pendingApprovals.get(requestId); - if (!pendingRequest) { - throw new Error(`Unknown pending approval request: ${requestId}`); - } - - context.pendingApprovals.delete(requestId); - this.writeMessage(context, { - id: pendingRequest.jsonRpcId, - result: { - decision, - }, - }); - - this.emitEvent({ - id: EventId.make(randomUUID()), - kind: "notification", - provider: "codex", - threadId: context.session.threadId, - createdAt: new Date().toISOString(), - method: "item/requestApproval/decision", - turnId: pendingRequest.turnId, - itemId: pendingRequest.itemId, - requestId: pendingRequest.requestId, - requestKind: pendingRequest.requestKind, - payload: { - requestId: pendingRequest.requestId, - requestKind: pendingRequest.requestKind, - decision, - }, - }); - } - - async respondToUserInput( - threadId: ThreadId, - requestId: ApprovalRequestId, - answers: ProviderUserInputAnswers, - ): Promise { - const context = this.requireSession(threadId); - const pendingRequest = context.pendingUserInputs.get(requestId); - if (!pendingRequest) { - throw new Error(`Unknown pending user input request: ${requestId}`); - } - - context.pendingUserInputs.delete(requestId); - const codexAnswers = toCodexUserInputAnswers(answers); - this.writeMessage(context, { - id: pendingRequest.jsonRpcId, - result: { - answers: codexAnswers, - }, - }); - - this.emitEvent({ - id: EventId.make(randomUUID()), - kind: "notification", - provider: "codex", - threadId: context.session.threadId, - createdAt: new Date().toISOString(), - method: "item/tool/requestUserInput/answered", - turnId: pendingRequest.turnId, - itemId: pendingRequest.itemId, - requestId: pendingRequest.requestId, - payload: { - requestId: pendingRequest.requestId, - answers: codexAnswers, - }, - }); - } - - stopSession(threadId: ThreadId): void { - const context = this.sessions.get(threadId); - if (!context) { - return; - } - - this.disposeSession(context, { - emitLifecycleEvent: true, - }); - } - - private disposeSession( - context: CodexSessionContext, - options?: { readonly emitLifecycleEvent?: boolean }, - ): void { - if (context.stopping) { - return; - } - - context.stopping = true; - - for (const pending of context.pending.values()) { - clearTimeout(pending.timeout); - pending.reject(new Error("Session stopped before request completed.")); - } - context.pending.clear(); - context.pendingApprovals.clear(); - context.pendingUserInputs.clear(); - - context.output.close(); - - if (!context.child.killed) { - killChildTree(context.child); - } - - this.updateSession(context, { - status: "closed", - activeTurnId: undefined, - }); - if (options?.emitLifecycleEvent !== false) { - this.emitLifecycleEvent(context, "session/closed", "Session stopped"); - } - this.sessions.delete(context.session.threadId); - } - - listSessions(): ProviderSession[] { - return Array.from(this.sessions.values(), ({ session }) => ({ - ...session, - })); - } - - hasSession(threadId: ThreadId): boolean { - return this.sessions.has(threadId); - } - - stopAll(): void { - for (const threadId of this.sessions.keys()) { - this.stopSession(threadId); - } - } - - private requireSession(threadId: ThreadId): CodexSessionContext { - const context = this.sessions.get(threadId); - if (!context) { - throw new Error(`Unknown session for thread: ${threadId}`); - } - - if (context.session.status === "closed") { - throw new Error(`Session is closed for thread: ${threadId}`); - } - - return context; - } - - private attachProcessListeners(context: CodexSessionContext): void { - context.output.on("line", (line) => { - this.handleStdoutLine(context, line); - }); - - context.child.stderr.on("data", (chunk: Buffer) => { - const raw = chunk.toString(); - const lines = raw.split(/\r?\n/g); - for (const rawLine of lines) { - const classified = classifyCodexStderrLine(rawLine); - if (!classified) { - continue; - } - - this.emitNotificationEvent(context, "process/stderr", classified.message); - } - }); - - context.child.on("error", (error) => { - const message = error.message || "codex app-server process errored."; - this.updateSession(context, { - status: "error", - lastError: message, - }); - this.emitErrorEvent(context, "process/error", message); - }); - - context.child.on("exit", (code, signal) => { - if (context.stopping) { - return; - } - - const message = `codex app-server exited (code=${code ?? "null"}, signal=${signal ?? "null"}).`; - this.updateSession(context, { - status: "closed", - activeTurnId: undefined, - lastError: code === 0 ? context.session.lastError : message, - }); - this.emitLifecycleEvent(context, "session/exited", message); - this.sessions.delete(context.session.threadId); - }); - } - - private handleStdoutLine(context: CodexSessionContext, line: string): void { - let parsed: unknown; - try { - parsed = JSON.parse(line); - } catch { - this.emitErrorEvent( - context, - "protocol/parseError", - "Received invalid JSON from codex app-server.", - ); - return; - } - - if (!parsed || typeof parsed !== "object") { - this.emitErrorEvent( - context, - "protocol/invalidMessage", - "Received non-object protocol message.", - ); - return; - } - - if (this.isServerRequest(parsed)) { - this.handleServerRequest(context, parsed); - return; - } - - if (this.isServerNotification(parsed)) { - this.handleServerNotification(context, parsed); - return; - } - - if (this.isResponse(parsed)) { - this.handleResponse(context, parsed); - return; - } - - this.emitErrorEvent( - context, - "protocol/unrecognizedMessage", - "Received protocol message in an unknown shape.", - ); - } - - private handleServerNotification( - context: CodexSessionContext, - notification: JsonRpcNotification, - ): void { - const rawRoute = this.readRouteFields(notification.params); - this.rememberCollabReceiverTurns(context, notification.params, rawRoute.turnId); - const childParentTurnId = this.readChildParentTurnId(context, notification.params); - const isChildConversation = childParentTurnId !== undefined; - if ( - isChildConversation && - this.shouldSuppressChildConversationNotification(notification.method) - ) { - return; - } - const textDelta = - notification.method === "item/agentMessage/delta" - ? this.readString(notification.params, "delta") - : undefined; - - this.emitEvent({ - id: EventId.make(randomUUID()), - kind: "notification", - provider: "codex", - threadId: context.session.threadId, - createdAt: new Date().toISOString(), - method: notification.method, - ...((childParentTurnId ?? rawRoute.turnId) - ? { turnId: childParentTurnId ?? rawRoute.turnId } - : {}), - ...(rawRoute.itemId ? { itemId: rawRoute.itemId } : {}), - textDelta, - payload: notification.params, - }); - - if (notification.method === "thread/started") { - const providerThreadId = normalizeProviderThreadId( - this.readString(this.readObject(notification.params)?.thread, "id"), - ); - if (providerThreadId) { - this.updateSession(context, { resumeCursor: { threadId: providerThreadId } }); - } - return; - } - - if (notification.method === "turn/started") { - if (isChildConversation) { - return; - } - const turnId = toTurnId(this.readString(this.readObject(notification.params)?.turn, "id")); - this.updateSession(context, { - status: "running", - activeTurnId: turnId, - }); - return; - } - - if (notification.method === "turn/completed") { - if (isChildConversation) { - return; - } - context.collabReceiverTurns.clear(); - const turn = this.readObject(notification.params, "turn"); - const status = this.readString(turn, "status"); - const errorMessage = this.readString(this.readObject(turn, "error"), "message"); - this.updateSession(context, { - status: status === "failed" ? "error" : "ready", - activeTurnId: undefined, - lastError: errorMessage ?? context.session.lastError, - }); - return; - } - - if (notification.method === "error") { - if (isChildConversation) { - return; - } - const message = this.readString(this.readObject(notification.params)?.error, "message"); - const willRetry = this.readBoolean(notification.params, "willRetry"); - - this.updateSession(context, { - status: willRetry ? "running" : "error", - lastError: message ?? context.session.lastError, - }); - } - } - - private handleServerRequest(context: CodexSessionContext, request: JsonRpcRequest): void { - const rawRoute = this.readRouteFields(request.params); - const childParentTurnId = this.readChildParentTurnId(context, request.params); - const effectiveTurnId = childParentTurnId ?? rawRoute.turnId; - const requestKind = this.requestKindForMethod(request.method); - let requestId: ApprovalRequestId | undefined; - if (requestKind) { - requestId = ApprovalRequestId.make(randomUUID()); - const pendingRequest: PendingApprovalRequest = { - requestId, - jsonRpcId: request.id, - method: - requestKind === "command" - ? "item/commandExecution/requestApproval" - : requestKind === "file-read" - ? "item/fileRead/requestApproval" - : "item/fileChange/requestApproval", - requestKind, - threadId: context.session.threadId, - ...(effectiveTurnId ? { turnId: effectiveTurnId } : {}), - ...(rawRoute.itemId ? { itemId: rawRoute.itemId } : {}), - }; - context.pendingApprovals.set(requestId, pendingRequest); - } - - if (request.method === "item/tool/requestUserInput") { - requestId = ApprovalRequestId.make(randomUUID()); - context.pendingUserInputs.set(requestId, { - requestId, - jsonRpcId: request.id, - threadId: context.session.threadId, - ...(effectiveTurnId ? { turnId: effectiveTurnId } : {}), - ...(rawRoute.itemId ? { itemId: rawRoute.itemId } : {}), - }); - } - - this.emitEvent({ - id: EventId.make(randomUUID()), - kind: "request", - provider: "codex", - threadId: context.session.threadId, - createdAt: new Date().toISOString(), - method: request.method, - ...(effectiveTurnId ? { turnId: effectiveTurnId } : {}), - ...(rawRoute.itemId ? { itemId: rawRoute.itemId } : {}), - requestId, - requestKind, - payload: request.params, - }); - - if (requestKind) { - return; - } - - if (request.method === "item/tool/requestUserInput") { - return; - } - - this.writeMessage(context, { - id: request.id, - error: { - code: -32601, - message: `Unsupported server request: ${request.method}`, - }, - }); - } - - private handleResponse(context: CodexSessionContext, response: JsonRpcResponse): void { - const key = String(response.id); - const pending = context.pending.get(key); - if (!pending) { - return; - } - - clearTimeout(pending.timeout); - context.pending.delete(key); - - if (response.error?.message) { - pending.reject(new Error(`${pending.method} failed: ${String(response.error.message)}`)); - return; - } - - pending.resolve(response.result); - } - - private async sendRequest( - context: CodexSessionContext, - method: string, - params: unknown, - timeoutMs = 20_000, - ): Promise { - const id = context.nextRequestId; - context.nextRequestId += 1; - - const result = await new Promise((resolve, reject) => { - const timeout = setTimeout(() => { - context.pending.delete(String(id)); - reject(new Error(`Timed out waiting for ${method}.`)); - }, timeoutMs); - - context.pending.set(String(id), { - method, - timeout, - resolve, - reject, - }); - this.writeMessage(context, { - method, - id, - params, - }); - }); - - return result as TResponse; - } - - private writeMessage(context: CodexSessionContext, message: unknown): void { - const encoded = JSON.stringify(message); - if (!context.child.stdin.writable) { - throw new Error("Cannot write to codex app-server stdin."); - } - - context.child.stdin.write(`${encoded}\n`); - } - - private emitLifecycleEvent(context: CodexSessionContext, method: string, message: string): void { - this.emitEvent({ - id: EventId.make(randomUUID()), - kind: "session", - provider: "codex", - threadId: context.session.threadId, - createdAt: new Date().toISOString(), - method, - message, - }); - } - - private emitErrorEvent(context: CodexSessionContext, method: string, message: string): void { - this.emitEvent({ - id: EventId.make(randomUUID()), - kind: "error", - provider: "codex", - threadId: context.session.threadId, - createdAt: new Date().toISOString(), - method, - message, - }); - } - - private emitNotificationEvent( - context: CodexSessionContext, - method: string, - message: string, - ): void { - this.emitEvent({ - id: EventId.make(randomUUID()), - kind: "notification", - provider: "codex", - threadId: context.session.threadId, - createdAt: new Date().toISOString(), - method, - message, - }); - } - - private emitEvent(event: ProviderEvent): void { - this.emit("event", event); - } - - private assertSupportedCodexCliVersion(input: { - readonly binaryPath: string; - readonly cwd: string; - readonly homePath?: string; - }): void { - assertSupportedCodexCliVersion(input); - } - - private updateSession(context: CodexSessionContext, updates: Partial): void { - context.session = { - ...context.session, - ...updates, - updatedAt: new Date().toISOString(), - }; - } - - private requestKindForMethod(method: string): ProviderRequestKind | undefined { - if (method === "item/commandExecution/requestApproval") { - return "command"; - } - - if (method === "item/fileRead/requestApproval") { - return "file-read"; - } - - if (method === "item/fileChange/requestApproval") { - return "file-change"; - } - - return undefined; - } - - private parseThreadSnapshot(method: string, response: unknown): CodexThreadSnapshot { - const responseRecord = this.readObject(response); - const thread = this.readObject(responseRecord, "thread"); - const threadIdRaw = - this.readString(thread, "id") ?? this.readString(responseRecord, "threadId"); - if (!threadIdRaw) { - throw new Error(`${method} response did not include a thread id.`); - } - const turnsRaw = - this.readArray(thread, "turns") ?? this.readArray(responseRecord, "turns") ?? []; - const turns = turnsRaw.map((turnValue, index) => { - const turn = this.readObject(turnValue); - const turnIdRaw = this.readString(turn, "id") ?? `${threadIdRaw}:turn:${index + 1}`; - const turnId = TurnId.make(turnIdRaw); - const items = this.readArray(turn, "items") ?? []; - return { - id: turnId, - items, - }; - }); - - return { - threadId: threadIdRaw, - turns, - }; - } - - private isServerRequest(value: unknown): value is JsonRpcRequest { - if (!value || typeof value !== "object") { - return false; - } - - const candidate = value as Record; - return ( - typeof candidate.method === "string" && - (typeof candidate.id === "string" || typeof candidate.id === "number") - ); - } - - private isServerNotification(value: unknown): value is JsonRpcNotification { - if (!value || typeof value !== "object") { - return false; - } - - const candidate = value as Record; - return typeof candidate.method === "string" && !("id" in candidate); - } - - private isResponse(value: unknown): value is JsonRpcResponse { - if (!value || typeof value !== "object") { - return false; - } - - const candidate = value as Record; - const hasId = typeof candidate.id === "string" || typeof candidate.id === "number"; - const hasMethod = typeof candidate.method === "string"; - return hasId && !hasMethod; - } - - private readRouteFields(params: unknown): { - turnId?: TurnId; - itemId?: ProviderItemId; - } { - const route: { - turnId?: TurnId; - itemId?: ProviderItemId; - } = {}; - - const turnId = toTurnId( - this.readString(params, "turnId") ?? this.readString(this.readObject(params, "turn"), "id"), - ); - const itemId = toProviderItemId( - this.readString(params, "itemId") ?? this.readString(this.readObject(params, "item"), "id"), - ); - - if (turnId) { - route.turnId = turnId; - } - - if (itemId) { - route.itemId = itemId; - } - - return route; - } - - private readProviderConversationId(params: unknown): string | undefined { - return ( - this.readString(params, "threadId") ?? - this.readString(this.readObject(params, "thread"), "id") ?? - this.readString(params, "conversationId") - ); - } - - private readChildParentTurnId(context: CodexSessionContext, params: unknown): TurnId | undefined { - const providerConversationId = this.readProviderConversationId(params); - if (!providerConversationId) { - return undefined; - } - return context.collabReceiverTurns.get(providerConversationId); - } - - private rememberCollabReceiverTurns( - context: CodexSessionContext, - params: unknown, - parentTurnId: TurnId | undefined, - ): void { - if (!parentTurnId) { - return; - } - const payload = this.readObject(params); - const item = this.readObject(payload, "item") ?? payload; - const itemType = this.readString(item, "type") ?? this.readString(item, "kind"); - if (itemType !== "collabAgentToolCall") { - return; - } - - const receiverThreadIds = - this.readArray(item, "receiverThreadIds") - ?.map((value) => (typeof value === "string" ? value : null)) - .filter((value): value is string => value !== null) ?? []; - for (const receiverThreadId of receiverThreadIds) { - context.collabReceiverTurns.set(receiverThreadId, parentTurnId); - } - } - - private shouldSuppressChildConversationNotification(method: string): boolean { - return ( - method === "thread/started" || - method === "thread/status/changed" || - method === "thread/archived" || - method === "thread/unarchived" || - method === "thread/closed" || - method === "thread/compacted" || - method === "thread/name/updated" || - method === "thread/tokenUsage/updated" || - method === "turn/started" || - method === "turn/completed" || - method === "turn/aborted" || - method === "turn/plan/updated" || - method === "item/plan/delta" - ); - } - - private readObject(value: unknown, key?: string): Record | undefined { - const target = - key === undefined - ? value - : value && typeof value === "object" - ? (value as Record)[key] - : undefined; - - if (!target || typeof target !== "object") { - return undefined; - } - - return target as Record; - } - - private readArray(value: unknown, key?: string): unknown[] | undefined { - const target = - key === undefined - ? value - : value && typeof value === "object" - ? (value as Record)[key] - : undefined; - return Array.isArray(target) ? target : undefined; - } - - private readString(value: unknown, key: string): string | undefined { - if (!value || typeof value !== "object") { - return undefined; - } - - const candidate = (value as Record)[key]; - return typeof candidate === "string" ? candidate : undefined; - } - - private readBoolean(value: unknown, key: string): boolean | undefined { - if (!value || typeof value !== "object") { - return undefined; - } - - const candidate = (value as Record)[key]; - return typeof candidate === "boolean" ? candidate : undefined; - } -} - -function brandIfNonEmpty( - value: string | undefined, - maker: (value: string) => T, -): T | undefined { - const normalized = value?.trim(); - return normalized?.length ? maker(normalized) : undefined; -} - -function normalizeProviderThreadId(value: string | undefined): string | undefined { - return brandIfNonEmpty(value, (normalized) => normalized); -} - -function assertSupportedCodexCliVersion(input: { - readonly binaryPath: string; - readonly cwd: string; - readonly homePath?: string; -}): void { - const result = spawnSync(input.binaryPath, ["--version"], { - cwd: input.cwd, - env: { - ...process.env, - ...(input.homePath ? { CODEX_HOME: expandHomePath(input.homePath) } : {}), - }, - encoding: "utf8", - shell: process.platform === "win32", - stdio: ["ignore", "pipe", "pipe"], - timeout: CODEX_VERSION_CHECK_TIMEOUT_MS, - maxBuffer: 1024 * 1024, - }); - - if (result.error) { - const lower = result.error.message.toLowerCase(); - if ( - lower.includes("enoent") || - lower.includes("command not found") || - lower.includes("not found") - ) { - throw new Error(`Codex CLI (${input.binaryPath}) is not installed or not executable.`); - } - throw new Error( - `Failed to execute Codex CLI version check: ${result.error.message || String(result.error)}`, - ); - } - - const stdout = result.stdout ?? ""; - const stderr = result.stderr ?? ""; - if (result.status !== 0) { - const detail = stderr.trim() || stdout.trim() || `Command exited with code ${result.status}.`; - throw new Error(`Codex CLI version check failed. ${detail}`); - } - - const parsedVersion = parseCodexCliVersion(`${stdout}\n${stderr}`); - if (parsedVersion && !isCodexCliVersionSupported(parsedVersion)) { - throw new Error(formatCodexCliUpgradeMessage(parsedVersion)); - } -} - -function readResumeCursorThreadId(resumeCursor: unknown): string | undefined { - if (!resumeCursor || typeof resumeCursor !== "object" || Array.isArray(resumeCursor)) { - return undefined; - } - const rawThreadId = (resumeCursor as Record).threadId; - return typeof rawThreadId === "string" ? normalizeProviderThreadId(rawThreadId) : undefined; -} - -function readResumeThreadId(input: { - readonly resumeCursor?: unknown; - readonly threadId?: ThreadId; - readonly runtimeMode?: RuntimeMode; -}): string | undefined { - return readResumeCursorThreadId(input.resumeCursor); -} - -function toTurnId(value: string | undefined): TurnId | undefined { - return brandIfNonEmpty(value, TurnId.make); -} - -function toProviderItemId(value: string | undefined): ProviderItemId | undefined { - return brandIfNonEmpty(value, ProviderItemId.make); -} diff --git a/apps/server/src/git/Layers/CodexTextGeneration.ts b/apps/server/src/git/Layers/CodexTextGeneration.ts index b629d91c18..8f15bfa186 100644 --- a/apps/server/src/git/Layers/CodexTextGeneration.ts +++ b/apps/server/src/git/Layers/CodexTextGeneration.ts @@ -29,9 +29,7 @@ import { sanitizeThreadTitle, toJsonSchemaObject, } from "../Utils.ts"; -import { getCodexModelCapabilities } from "../../provider/Layers/CodexProvider.ts"; import { ServerSettingsService } from "../../serverSettings.ts"; -import { normalizeCodexModelOptionsWithCapabilities } from "@t3tools/shared/model"; const CODEX_GIT_TEXT_GENERATION_REASONING_EFFORT = "low"; const CODEX_TIMEOUT_MS = 180_000; @@ -156,10 +154,6 @@ const makeCodexTextGeneration = Effect.gen(function* () { ).pipe(Effect.catch(() => Effect.undefined)); const runCodexCommand = Effect.fn("runCodexJson.runCodexCommand")(function* () { - const normalizedOptions = normalizeCodexModelOptionsWithCapabilities( - getCodexModelCapabilities(modelSelection.model), - modelSelection.options, - ); const reasoningEffort = modelSelection.options?.reasoningEffort ?? CODEX_GIT_TEXT_GENERATION_REASONING_EFFORT; const command = ChildProcess.make( @@ -174,7 +168,7 @@ const makeCodexTextGeneration = Effect.gen(function* () { modelSelection.model, "--config", `model_reasoning_effort="${reasoningEffort}"`, - ...(normalizedOptions?.fastMode ? ["--config", `service_tier="fast"`] : []), + ...(modelSelection.options?.fastMode ? ["--config", `service_tier="fast"`] : []), "--output-schema", schemaPath, "--output-last-message", diff --git a/apps/server/src/provider/CodexDeveloperInstructions.ts b/apps/server/src/provider/CodexDeveloperInstructions.ts new file mode 100644 index 0000000000..76055f8b8b --- /dev/null +++ b/apps/server/src/provider/CodexDeveloperInstructions.ts @@ -0,0 +1,134 @@ +export const CODEX_PLAN_MODE_DEVELOPER_INSTRUCTIONS = `# Plan Mode (Conversational) + +You work in 3 phases, and you should *chat your way* to a great plan before finalizing it. A great plan is very detailed-intent- and implementation-wise-so that it can be handed to another engineer or agent to be implemented right away. It must be **decision complete**, where the implementer does not need to make any decisions. + +## Mode rules (strict) + +You are in **Plan Mode** until a developer message explicitly ends it. + +Plan Mode is not changed by user intent, tone, or imperative language. If a user asks for execution while still in Plan Mode, treat it as a request to **plan the execution**, not perform it. + +## Plan Mode vs update_plan tool + +Plan Mode is a collaboration mode that can involve requesting user input and eventually issuing a \`\` block. + +Separately, \`update_plan\` is a checklist/progress/TODOs tool; it does not enter or exit Plan Mode. Do not confuse it with Plan mode or try to use it while in Plan mode. If you try to use \`update_plan\` in Plan mode, it will return an error. + +## Execution vs. mutation in Plan Mode + +You may explore and execute **non-mutating** actions that improve the plan. You must not perform **mutating** actions. + +### Allowed (non-mutating, plan-improving) + +Actions that gather truth, reduce ambiguity, or validate feasibility without changing repo-tracked state. Examples: + +* Reading or searching files, configs, schemas, types, manifests, and docs +* Static analysis, inspection, and repo exploration +* Dry-run style commands when they do not edit repo-tracked files +* Tests, builds, or checks that may write to caches or build artifacts (for example, \`target/\`, \`.cache/\`, or snapshots) so long as they do not edit repo-tracked files + +### Not allowed (mutating, plan-executing) + +Actions that implement the plan or change repo-tracked state. Examples: + +* Editing or writing files +* Running formatters or linters that rewrite files +* Applying patches, migrations, or codegen that updates repo-tracked files +* Side-effectful commands whose purpose is to carry out the plan rather than refine it + +When in doubt: if the action would reasonably be described as "doing the work" rather than "planning the work," do not do it. + +## PHASE 1 - Ground in the environment (explore first, ask second) + +Begin by grounding yourself in the actual environment. Eliminate unknowns in the prompt by discovering facts, not by asking the user. Resolve all questions that can be answered through exploration or inspection. Identify missing or ambiguous details only if they cannot be derived from the environment. Silent exploration between turns is allowed and encouraged. + +Before asking the user any question, perform at least one targeted non-mutating exploration pass (for example: search relevant files, inspect likely entrypoints/configs, confirm current implementation shape), unless no local environment/repo is available. + +Exception: you may ask clarifying questions about the user's prompt before exploring, ONLY if there are obvious ambiguities or contradictions in the prompt itself. However, if ambiguity might be resolved by exploring, always prefer exploring first. + +Do not ask questions that can be answered from the repo or system (for example, "where is this struct?" or "which UI component should we use?" when exploration can make it clear). Only ask once you have exhausted reasonable non-mutating exploration. + +## PHASE 2 - Intent chat (what they actually want) + +* Keep asking until you can clearly state: goal + success criteria, audience, in/out of scope, constraints, current state, and the key preferences/tradeoffs. +* Bias toward questions over guessing: if any high-impact ambiguity remains, do NOT plan yet-ask. + +## PHASE 3 - Implementation chat (what/how we'll build) + +* Once intent is stable, keep asking until the spec is decision complete: approach, interfaces (APIs/schemas/I/O), data flow, edge cases/failure modes, testing + acceptance criteria, rollout/monitoring, and any migrations/compat constraints. + +## Asking questions + +Critical rules: + +* Strongly prefer using the \`request_user_input\` tool to ask any questions. +* Offer only meaningful multiple-choice options; don't include filler choices that are obviously wrong or irrelevant. +* In rare cases where an unavoidable, important question can't be expressed with reasonable multiple-choice options (due to extreme ambiguity), you may ask it directly without the tool. + +You SHOULD ask many questions, but each question must: + +* materially change the spec/plan, OR +* confirm/lock an assumption, OR +* choose between meaningful tradeoffs. +* not be answerable by non-mutating commands. + +Use the \`request_user_input\` tool only for decisions that materially change the plan, for confirming important assumptions, or for information that cannot be discovered via non-mutating exploration. + +## Two kinds of unknowns (treat differently) + +1. **Discoverable facts** (repo/system truth): explore first. + + * Before asking, run targeted searches and check likely sources of truth (configs/manifests/entrypoints/schemas/types/constants). + * Ask only if: multiple plausible candidates; nothing found but you need a missing identifier/context; or ambiguity is actually product intent. + * If asking, present concrete candidates (paths/service names) + recommend one. + * Never ask questions you can answer from your environment (e.g., "where is this struct"). + +2. **Preferences/tradeoffs** (not discoverable): ask early. + + * These are intent or implementation preferences that cannot be derived from exploration. + * Provide 2-4 mutually exclusive options + a recommended default. + * If unanswered, proceed with the recommended option and record it as an assumption in the final plan. + +## Finalization rule + +Only output the final plan when it is decision complete and leaves no decisions to the implementer. + +When you present the official plan, wrap it in a \`\` block so the client can render it specially: + +1) The opening tag must be on its own line. +2) Start the plan content on the next line (no text on the same line as the tag). +3) The closing tag must be on its own line. +4) Use Markdown inside the block. +5) Keep the tags exactly as \`\` and \`\` (do not translate or rename them), even if the plan content is in another language. + +Example: + + +plan content + + +plan content should be human and agent digestible. The final plan must be plan-only and include: + +* A clear title +* A brief summary section +* Important changes or additions to public APIs/interfaces/types +* Test cases and scenarios +* Explicit assumptions and defaults chosen where needed + +Do not ask "should I proceed?" in the final output. The user can easily switch out of Plan mode and request implementation if you have included a \`\` block in your response. Alternatively, they can decide to stay in Plan mode and continue refining the plan. + +Only produce at most one \`\` block per turn, and only when you are presenting a complete spec. +`; + +export const CODEX_DEFAULT_MODE_DEVELOPER_INSTRUCTIONS = `# Collaboration Mode: Default + +You are now in Default mode. Any previous instructions for other modes (e.g. Plan mode) are no longer active. + +Your active mode changes only when new developer instructions with a different \`...\` change it; user requests or tool descriptions do not change mode by themselves. Known mode names are Default and Plan. + +## request_user_input availability + +The \`request_user_input\` tool is unavailable in Default mode. If you call it while in Default mode, it will return an error. + +In Default mode, strongly prefer making reasonable assumptions and executing the user's request rather than stopping to ask questions. If you absolutely must ask a question because the answer cannot be discovered from local context and a reasonable assumption would be risky, ask the user directly with a concise plain-text question. Never write a multiple choice question as a textual assistant message. +`; diff --git a/apps/server/src/provider/Layers/CodexAdapter.test.ts b/apps/server/src/provider/Layers/CodexAdapter.test.ts index ac272795ec..03d4155934 100644 --- a/apps/server/src/provider/Layers/CodexAdapter.test.ts +++ b/apps/server/src/provider/Layers/CodexAdapter.test.ts @@ -1,4 +1,7 @@ import assert from "node:assert/strict"; +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; import { ApprovalRequestId, EventId, @@ -12,20 +15,22 @@ import { TurnId, } from "@t3tools/contracts"; import * as NodeServices from "@effect/platform-node/NodeServices"; -import { afterAll, it, vi } from "@effect/vitest"; +import { it, vi } from "@effect/vitest"; -import { Effect, Fiber, Layer, Option, Stream } from "effect"; +import { Effect, Exit, Fiber, Layer, Option, Queue, Scope, Stream } from "effect"; +import * as CodexErrors from "effect-codex-app-server/errors"; -import { - CodexAppServerManager, - type CodexAppServerStartSessionInput, - type CodexAppServerSendTurnInput, -} from "../../codexAppServerManager.ts"; import { ServerConfig } from "../../config.ts"; import { ServerSettingsService } from "../../serverSettings.ts"; import { ProviderAdapterValidationError } from "../Errors.ts"; import { CodexAdapter } from "../Services/CodexAdapter.ts"; import { ProviderSessionDirectory } from "../Services/ProviderSessionDirectory.ts"; +import { + type CodexSessionRuntimeOptions, + type CodexSessionRuntimeSendTurnInput, + type CodexSessionRuntimeShape, + type CodexThreadSnapshot, +} from "./CodexSessionRuntime.ts"; import { makeCodexAdapterLive } from "./CodexAdapter.ts"; const asThreadId = (value: string): ThreadId => ThreadId.make(value); @@ -33,110 +38,157 @@ const asTurnId = (value: string): TurnId => TurnId.make(value); const asEventId = (value: string): EventId => EventId.make(value); const asItemId = (value: string): ProviderItemId => ProviderItemId.make(value); -class FakeCodexManager extends CodexAppServerManager { - public startSessionImpl = vi.fn( - async (input: CodexAppServerStartSessionInput): Promise => { - const now = new Date().toISOString(); - return { - provider: "codex", - status: "ready", - runtimeMode: input.runtimeMode, - threadId: input.threadId, - cwd: input.cwd, - createdAt: now, - updatedAt: now, - }; - }, +class FakeCodexRuntime implements CodexSessionRuntimeShape { + private readonly eventQueue = Effect.runSync(Queue.unbounded()); + private readonly now = new Date().toISOString(); + + public readonly startImpl = vi.fn(() => + Promise.resolve({ + provider: "codex" as const, + status: "ready" as const, + runtimeMode: this.options.runtimeMode, + threadId: this.options.threadId, + cwd: this.options.cwd, + ...(this.options.model ? { model: this.options.model } : {}), + createdAt: this.now, + updatedAt: this.now, + } satisfies ProviderSession), ); - public sendTurnImpl = vi.fn( - async (_input: CodexAppServerSendTurnInput): Promise => ({ - threadId: asThreadId("thread-1"), - turnId: asTurnId("turn-1"), + public readonly sendTurnImpl = vi.fn( + (_input: CodexSessionRuntimeSendTurnInput): Promise => + Promise.resolve({ + threadId: this.options.threadId, + turnId: asTurnId("turn-1"), + }), + ); + + public readonly interruptTurnImpl = vi.fn( + (_turnId?: TurnId): Promise => Promise.resolve(undefined), + ); + + public readonly readThreadImpl = vi.fn( + (): Promise => + Promise.resolve({ + threadId: "provider-thread-1", + turns: [], + }), + ); + + public readonly rollbackThreadImpl = vi.fn( + (_numTurns: number): Promise => + Promise.resolve({ + threadId: "provider-thread-1", + turns: [], + }), + ); + + public readonly respondToRequestImpl = vi.fn( + (_requestId: ApprovalRequestId, _decision: ProviderApprovalDecision): Promise => + Promise.resolve(undefined), + ); + + public readonly respondToUserInputImpl = vi.fn( + (_requestId: ApprovalRequestId, _answers: ProviderUserInputAnswers): Promise => + Promise.resolve(undefined), + ); + + public readonly closeImpl = vi.fn(() => Promise.resolve(undefined)); + + readonly options: CodexSessionRuntimeOptions; + + constructor(options: CodexSessionRuntimeOptions) { + this.options = options; + } + + start() { + return Effect.promise(() => this.startImpl()); + } + + getSession = Effect.promise(() => this.startImpl()); + + sendTurn(input: CodexSessionRuntimeSendTurnInput) { + return Effect.promise(() => this.sendTurnImpl(input)); + } + + interruptTurn(turnId?: TurnId) { + return Effect.promise(() => this.interruptTurnImpl(turnId)); + } + + readThread = Effect.promise(() => this.readThreadImpl()); + + rollbackThread(numTurns: number) { + return Effect.promise(() => this.rollbackThreadImpl(numTurns)); + } + + respondToRequest(requestId: ApprovalRequestId, decision: ProviderApprovalDecision) { + return Effect.promise(() => this.respondToRequestImpl(requestId, decision)); + } + + respondToUserInput(requestId: ApprovalRequestId, answers: ProviderUserInputAnswers) { + return Effect.promise(() => this.respondToUserInputImpl(requestId, answers)); + } + + get events() { + return Stream.fromQueue(this.eventQueue); + } + + close = Effect.promise(() => this.closeImpl()); + + emit(event: ProviderEvent) { + return Queue.offer(this.eventQueue, event).pipe(Effect.asVoid); + } +} + +function makeRuntimeFactory() { + const runtimes: Array = []; + const factory = vi.fn((options: CodexSessionRuntimeOptions) => { + const runtime = new FakeCodexRuntime(options); + runtimes.push(runtime); + return Effect.succeed(runtime); + }); + + return { + factory, + get lastRuntime(): FakeCodexRuntime | undefined { + return runtimes.at(-1); + }, + }; +} + +function makeScopedRuntimeFactory(options?: { readonly failConstruction?: boolean }) { + const runtimes: Array = []; + const releasedThreadIds: Array = []; + + const factory = vi.fn((runtimeOptions: CodexSessionRuntimeOptions) => + Effect.gen(function* () { + yield* Scope.Scope; + yield* Effect.addFinalizer(() => + Effect.sync(() => { + releasedThreadIds.push(runtimeOptions.threadId); + }), + ); + + if (options?.failConstruction) { + return yield* new CodexErrors.CodexAppServerSpawnError({ + command: `${runtimeOptions.binaryPath} app-server`, + cause: new Error("runtime construction failed"), + }); + } + + const runtime = new FakeCodexRuntime(runtimeOptions); + runtimes.push(runtime); + return runtime; }), ); - public interruptTurnImpl = vi.fn( - async (_threadId: ThreadId, _turnId?: TurnId): Promise => undefined, - ); - - public readThreadImpl = vi.fn(async (_threadId: ThreadId) => ({ - threadId: asThreadId("thread-1"), - turns: [], - })); - - public rollbackThreadImpl = vi.fn(async (_threadId: ThreadId, _numTurns: number) => ({ - threadId: asThreadId("thread-1"), - turns: [], - })); - - public respondToRequestImpl = vi.fn( - async ( - _threadId: ThreadId, - _requestId: ApprovalRequestId, - _decision: ProviderApprovalDecision, - ): Promise => undefined, - ); - - public respondToUserInputImpl = vi.fn( - async ( - _threadId: ThreadId, - _requestId: ApprovalRequestId, - _answers: ProviderUserInputAnswers, - ): Promise => undefined, - ); - - public stopAllImpl = vi.fn(() => undefined); - - override startSession(input: CodexAppServerStartSessionInput): Promise { - return this.startSessionImpl(input); - } - - override sendTurn(input: CodexAppServerSendTurnInput): Promise { - return this.sendTurnImpl(input); - } - - override interruptTurn(threadId: ThreadId, turnId?: TurnId): Promise { - return this.interruptTurnImpl(threadId, turnId); - } - - override readThread(threadId: ThreadId) { - return this.readThreadImpl(threadId); - } - - override rollbackThread(threadId: ThreadId, numTurns: number) { - return this.rollbackThreadImpl(threadId, numTurns); - } - - override respondToRequest( - threadId: ThreadId, - requestId: ApprovalRequestId, - decision: ProviderApprovalDecision, - ): Promise { - return this.respondToRequestImpl(threadId, requestId, decision); - } - - override respondToUserInput( - threadId: ThreadId, - requestId: ApprovalRequestId, - answers: ProviderUserInputAnswers, - ): Promise { - return this.respondToUserInputImpl(threadId, requestId, answers); - } - - override stopSession(_threadId: ThreadId): void {} - - override listSessions(): ProviderSession[] { - return []; - } - - override hasSession(_threadId: ThreadId): boolean { - return false; - } - - override stopAll(): void { - this.stopAllImpl(); - } + return { + factory, + releasedThreadIds, + get lastRuntime(): FakeCodexRuntime | undefined { + return runtimes.at(-1); + }, + }; } const providerSessionDirectoryTestLayer = Layer.succeed(ProviderSessionDirectory, { @@ -148,9 +200,9 @@ const providerSessionDirectoryTestLayer = Layer.succeed(ProviderSessionDirectory listBindings: () => Effect.succeed([]), }); -const validationManager = new FakeCodexManager(); +const validationRuntimeFactory = makeRuntimeFactory(); const validationLayer = it.layer( - makeCodexAdapterLive({ manager: validationManager }).pipe( + makeCodexAdapterLive({ makeRuntime: validationRuntimeFactory.factory }).pipe( Layer.provideMerge(ServerConfig.layerTest(process.cwd(), process.cwd())), Layer.provideMerge(ServerSettingsService.layerTest()), Layer.provideMerge(providerSessionDirectoryTestLayer), @@ -179,12 +231,12 @@ validationLayer("CodexAdapterLive validation", (it) => { issue: "Expected provider 'codex' but received 'claudeAgent'.", }), ); - assert.equal(validationManager.startSessionImpl.mock.calls.length, 0); + assert.equal(validationRuntimeFactory.factory.mock.calls.length, 0); }), ); it.effect("maps codex model options before starting a session", () => Effect.gen(function* () { - validationManager.startSessionImpl.mockClear(); + validationRuntimeFactory.factory.mockClear(); const adapter = yield* CodexAdapter; yield* adapter.startSession({ @@ -200,24 +252,21 @@ validationLayer("CodexAdapterLive validation", (it) => { runtimeMode: "full-access", }); - assert.deepStrictEqual(validationManager.startSessionImpl.mock.calls[0]?.[0], { - provider: "codex", - threadId: asThreadId("thread-1"), + assert.deepStrictEqual(validationRuntimeFactory.factory.mock.calls[0]?.[0], { binaryPath: "codex", + cwd: process.cwd(), model: "gpt-5.3-codex", serviceTier: "fast", + threadId: asThreadId("thread-1"), runtimeMode: "full-access", }); }), ); }); -const sessionErrorManager = new FakeCodexManager(); -sessionErrorManager.sendTurnImpl.mockImplementation(async () => { - throw new Error("Unknown session: sess-missing"); -}); +const sessionRuntimeFactory = makeRuntimeFactory(); const sessionErrorLayer = it.layer( - makeCodexAdapterLive({ manager: sessionErrorManager }).pipe( + makeCodexAdapterLive({ makeRuntime: sessionRuntimeFactory.factory }).pipe( Layer.provideMerge(ServerConfig.layerTest(process.cwd(), process.cwd())), Layer.provideMerge(ServerSettingsService.layerTest()), Layer.provideMerge(providerSessionDirectoryTestLayer), @@ -226,7 +275,7 @@ const sessionErrorLayer = it.layer( ); sessionErrorLayer("CodexAdapterLive session errors", (it) => { - it.effect("maps unknown-session sendTurn errors to ProviderAdapterSessionNotFoundError", () => + it.effect("maps missing adapter sessions to ProviderAdapterSessionNotFoundError", () => Effect.gen(function* () { const adapter = yield* CodexAdapter; const result = yield* adapter @@ -241,14 +290,20 @@ sessionErrorLayer("CodexAdapterLive session errors", (it) => { assert.equal(result.failure._tag, "ProviderAdapterSessionNotFoundError"); assert.equal(result.failure.provider, "codex"); assert.equal(result.failure.threadId, "sess-missing"); - assert.equal(result.failure.cause instanceof Error, true); }), ); it.effect("maps codex model options before sending a turn", () => Effect.gen(function* () { - sessionErrorManager.sendTurnImpl.mockClear(); const adapter = yield* CodexAdapter; + yield* adapter.startSession({ + provider: "codex", + threadId: asThreadId("sess-missing"), + runtimeMode: "full-access", + }); + const runtime = sessionRuntimeFactory.lastRuntime; + assert.ok(runtime); + runtime.sendTurnImpl.mockClear(); yield* Effect.ignore( adapter.sendTurn({ @@ -266,8 +321,7 @@ sessionErrorLayer("CodexAdapterLive session errors", (it) => { }), ); - assert.deepStrictEqual(sessionErrorManager.sendTurnImpl.mock.calls[0]?.[0], { - threadId: asThreadId("sess-missing"), + assert.deepStrictEqual(runtime.sendTurnImpl.mock.calls[0]?.[0], { input: "hello", model: "gpt-5.3-codex", effort: "high", @@ -277,9 +331,9 @@ sessionErrorLayer("CodexAdapterLive session errors", (it) => { ); }); -const lifecycleManager = new FakeCodexManager(); +const lifecycleRuntimeFactory = makeRuntimeFactory(); const lifecycleLayer = it.layer( - makeCodexAdapterLive({ manager: lifecycleManager }).pipe( + makeCodexAdapterLive({ makeRuntime: lifecycleRuntimeFactory.factory }).pipe( Layer.provideMerge(ServerConfig.layerTest(process.cwd(), process.cwd())), Layer.provideMerge(ServerSettingsService.layerTest()), Layer.provideMerge(providerSessionDirectoryTestLayer), @@ -287,10 +341,24 @@ const lifecycleLayer = it.layer( ), ); +function startLifecycleRuntime() { + return Effect.gen(function* () { + const adapter = yield* CodexAdapter; + yield* adapter.startSession({ + provider: "codex", + threadId: asThreadId("thread-1"), + runtimeMode: "full-access", + }); + const runtime = lifecycleRuntimeFactory.lastRuntime; + assert.ok(runtime); + return { adapter, runtime }; + }); +} + lifecycleLayer("CodexAdapterLive lifecycle", (it) => { it.effect("maps completed agent message items to canonical item.completed events", () => Effect.gen(function* () { - const adapter = yield* CodexAdapter; + const { adapter, runtime } = yield* startLifecycleRuntime(); const firstEventFiber = yield* Stream.runHead(adapter.streamEvents).pipe(Effect.forkChild); const event: ProviderEvent = { @@ -303,14 +371,17 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => { turnId: asTurnId("turn-1"), itemId: asItemId("msg_1"), payload: { + threadId: "thread-1", + turnId: "turn-1", item: { type: "agentMessage", id: "msg_1", + text: "done", }, }, }; - lifecycleManager.emit("event", event); + yield* runtime.emit(event); const firstEvent = yield* Fiber.join(firstEventFiber); assert.equal(firstEvent._tag, "Some"); @@ -329,7 +400,7 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => { it.effect("maps completed plan items to canonical proposed-plan completion events", () => Effect.gen(function* () { - const adapter = yield* CodexAdapter; + const { adapter, runtime } = yield* startLifecycleRuntime(); const firstEventFiber = yield* Stream.runHead(adapter.streamEvents).pipe(Effect.forkChild); const event: ProviderEvent = { @@ -342,15 +413,17 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => { turnId: asTurnId("turn-1"), itemId: asItemId("plan_1"), payload: { + threadId: "thread-1", + turnId: "turn-1", item: { - type: "Plan", + type: "plan", id: "plan_1", text: "## Final plan\n\n- one\n- two", }, }, }; - lifecycleManager.emit("event", event); + yield* runtime.emit(event); const firstEvent = yield* Fiber.join(firstEventFiber); assert.equal(firstEvent._tag, "Some"); @@ -368,10 +441,10 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => { it.effect("maps plan deltas to canonical proposed-plan delta events", () => Effect.gen(function* () { - const adapter = yield* CodexAdapter; + const { adapter, runtime } = yield* startLifecycleRuntime(); const firstEventFiber = yield* Stream.runHead(adapter.streamEvents).pipe(Effect.forkChild); - lifecycleManager.emit("event", { + yield* runtime.emit({ id: asEventId("evt-plan-delta"), kind: "notification", provider: "codex", @@ -381,6 +454,9 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => { turnId: asTurnId("turn-1"), itemId: asItemId("plan_1"), payload: { + threadId: "thread-1", + turnId: "turn-1", + itemId: "plan_1", delta: "## Final plan", }, } satisfies ProviderEvent); @@ -402,7 +478,7 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => { it.effect("maps session/closed lifecycle events to canonical session.exited runtime events", () => Effect.gen(function* () { - const adapter = yield* CodexAdapter; + const { adapter, runtime } = yield* startLifecycleRuntime(); const firstEventFiber = yield* Stream.runHead(adapter.streamEvents).pipe(Effect.forkChild); const event: ProviderEvent = { @@ -415,7 +491,7 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => { message: "Session stopped", }; - lifecycleManager.emit("event", event); + yield* runtime.emit(event); const firstEvent = yield* Fiber.join(firstEventFiber); assert.equal(firstEvent._tag, "Some"); @@ -433,10 +509,10 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => { it.effect("maps retryable Codex error notifications to runtime.warning", () => Effect.gen(function* () { - const adapter = yield* CodexAdapter; + const { adapter, runtime } = yield* startLifecycleRuntime(); const firstEventFiber = yield* Stream.runHead(adapter.streamEvents).pipe(Effect.forkChild); - lifecycleManager.emit("event", { + yield* runtime.emit({ id: asEventId("evt-retryable-error"), kind: "notification", provider: "codex", @@ -445,6 +521,8 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => { method: "error", turnId: asTurnId("turn-1"), payload: { + threadId: "thread-1", + turnId: "turn-1", error: { message: "Reconnecting... 2/5", }, @@ -469,10 +547,10 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => { it.effect("maps process stderr notifications to runtime.warning", () => Effect.gen(function* () { - const adapter = yield* CodexAdapter; + const { adapter, runtime } = yield* startLifecycleRuntime(); const firstEventFiber = yield* Stream.runHead(adapter.streamEvents).pipe(Effect.forkChild); - lifecycleManager.emit("event", { + yield* runtime.emit({ id: asEventId("evt-process-stderr"), kind: "notification", provider: "codex", @@ -503,10 +581,10 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => { it.effect("maps fatal websocket stderr notifications to runtime.error", () => Effect.gen(function* () { - const adapter = yield* CodexAdapter; + const { adapter, runtime } = yield* startLifecycleRuntime(); const firstEventFiber = yield* Stream.runHead(adapter.streamEvents).pipe(Effect.forkChild); - lifecycleManager.emit("event", { + yield* runtime.emit({ id: asEventId("evt-process-stderr-websocket"), kind: "notification", provider: "codex", @@ -539,7 +617,7 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => { it.effect("preserves request type when mapping serverRequest/resolved", () => Effect.gen(function* () { - const adapter = yield* CodexAdapter; + const { adapter, runtime } = yield* startLifecycleRuntime(); const firstEventFiber = yield* Stream.runHead(adapter.streamEvents).pipe(Effect.forkChild); const event: ProviderEvent = { @@ -549,16 +627,15 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => { threadId: asThreadId("thread-1"), createdAt: new Date().toISOString(), method: "serverRequest/resolved", + requestKind: "command", requestId: ApprovalRequestId.make("req-1"), payload: { - request: { - method: "item/commandExecution/requestApproval", - }, - decision: "accept", + threadId: "thread-1", + requestId: "req-1", }, }; - lifecycleManager.emit("event", event); + yield* runtime.emit(event); const firstEvent = yield* Fiber.join(firstEventFiber); assert.equal(firstEvent._tag, "Some"); @@ -575,7 +652,7 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => { it.effect("preserves file-read request type when mapping serverRequest/resolved", () => Effect.gen(function* () { - const adapter = yield* CodexAdapter; + const { adapter, runtime } = yield* startLifecycleRuntime(); const firstEventFiber = yield* Stream.runHead(adapter.streamEvents).pipe(Effect.forkChild); const event: ProviderEvent = { @@ -585,16 +662,15 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => { threadId: asThreadId("thread-1"), createdAt: new Date().toISOString(), method: "serverRequest/resolved", + requestKind: "file-read", requestId: ApprovalRequestId.make("req-file-read-1"), payload: { - request: { - method: "item/fileRead/requestApproval", - }, - decision: "accept", + threadId: "thread-1", + requestId: "req-file-read-1", }, }; - lifecycleManager.emit("event", event); + yield* runtime.emit(event); const firstEvent = yield* Fiber.join(firstEventFiber); assert.equal(firstEvent._tag, "Some"); @@ -611,7 +687,7 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => { it.effect("preserves explicit empty multi-select user-input answers", () => Effect.gen(function* () { - const adapter = yield* CodexAdapter; + const { adapter, runtime } = yield* startLifecycleRuntime(); const firstEventFiber = yield* Stream.runHead(adapter.streamEvents).pipe(Effect.forkChild); const event: ProviderEvent = { @@ -623,12 +699,14 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => { method: "item/tool/requestUserInput/answered", payload: { answers: { - scope: [], + scope: { + answers: [], + }, }, }, }; - lifecycleManager.emit("event", event); + yield* runtime.emit(event); const firstEvent = yield* Fiber.join(firstEventFiber); assert.equal(firstEvent._tag, "Some"); @@ -647,7 +725,7 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => { it.effect("maps windowsSandbox/setupCompleted to session state and warning on failure", () => Effect.gen(function* () { - const adapter = yield* CodexAdapter; + const { adapter, runtime } = yield* startLifecycleRuntime(); const eventsFiber = yield* Stream.runCollect(Stream.take(adapter.streamEvents, 2)).pipe( Effect.forkChild, ); @@ -661,12 +739,13 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => { method: "windowsSandbox/setupCompleted", message: "Sandbox setup failed", payload: { + mode: "unelevated", success: false, - detail: "unsupported environment", + error: "unsupported environment", }, }; - lifecycleManager.emit("event", event); + yield* runtime.emit(event); const events = Array.from(yield* Fiber.join(eventsFiber)); assert.equal(events.length, 2); @@ -691,12 +770,12 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => { "maps requestUserInput requests and answered notifications to canonical user-input events", () => Effect.gen(function* () { - const adapter = yield* CodexAdapter; + const { adapter, runtime } = yield* startLifecycleRuntime(); const eventsFiber = yield* Stream.runCollect(Stream.take(adapter.streamEvents, 2)).pipe( Effect.forkChild, ); - lifecycleManager.emit("event", { + yield* runtime.emit({ id: asEventId("evt-user-input-requested"), kind: "request", provider: "codex", @@ -705,6 +784,9 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => { method: "item/tool/requestUserInput", requestId: ApprovalRequestId.make("req-user-input-1"), payload: { + itemId: "item-user-input-1", + threadId: "thread-1", + turnId: "turn-1", questions: [ { id: "sandbox_mode", @@ -716,12 +798,11 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => { description: "Allow workspace writes only", }, ], - multiSelect: true, }, ], }, } satisfies ProviderEvent); - lifecycleManager.emit("event", { + yield* runtime.emit({ id: asEventId("evt-user-input-resolved"), kind: "notification", provider: "codex", @@ -743,7 +824,7 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => { 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[0].payload.questions[0]?.multiSelect, true); + assert.equal(events[0].payload.questions[0]?.multiSelect, false); } assert.equal(events[1]?.type, "user-input.resolved"); @@ -756,168 +837,12 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => { }), ); - 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: "\n# Ship it\n", - }, - }, - } 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, "\n# Ship it\n"); - } - - 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"); - } - }), - ); - - it.effect("prefers manager-assigned turn ids for Codex task events", () => - Effect.gen(function* () { - const adapter = yield* CodexAdapter; - const firstEventFiber = yield* Stream.runHead(adapter.streamEvents).pipe(Effect.forkChild); - - lifecycleManager.emit("event", { - id: asEventId("evt-codex-task-started-parent-turn"), - kind: "notification", - provider: "codex", - threadId: asThreadId("thread-1"), - turnId: asTurnId("turn-parent"), - createdAt: new Date().toISOString(), - method: "codex/event/task_started", - payload: { - id: "turn-child", - msg: { - type: "task_started", - turn_id: "turn-child", - collaboration_mode_kind: "default", - }, - conversationId: "child-provider-thread", - }, - } satisfies ProviderEvent); - - const firstEvent = yield* Fiber.join(firstEventFiber); - assert.equal(firstEvent._tag, "Some"); - if (firstEvent._tag !== "Some") { - return; - } - assert.equal(firstEvent.value.type, "task.started"); - if (firstEvent.value.type !== "task.started") { - return; - } - assert.equal(firstEvent.value.turnId, "turn-parent"); - assert.equal(firstEvent.value.providerRefs?.providerTurnId, "turn-parent"); - assert.equal(firstEvent.value.payload.taskId, "turn-child"); - }), - ); - it.effect("unwraps Codex token usage payloads for context window events", () => Effect.gen(function* () { - const adapter = yield* CodexAdapter; + const { adapter, runtime } = yield* startLifecycleRuntime(); const firstEventFiber = yield* Stream.runHead(adapter.streamEvents).pipe(Effect.forkChild); - lifecycleManager.emit("event", { + yield* runtime.emit({ id: asEventId("evt-codex-thread-token-usage-updated"), kind: "notification", provider: "codex", @@ -977,9 +902,130 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => { ); }); -afterAll(() => { - if (lifecycleManager.stopAllImpl.mock.calls.length === 0) { - lifecycleManager.stopAll(); - } - assert.ok(lifecycleManager.stopAllImpl.mock.calls.length >= 1); +const scopedLifecycleRuntimeFactory = makeScopedRuntimeFactory(); +const scopedLifecycleLayer = it.layer( + makeCodexAdapterLive({ makeRuntime: scopedLifecycleRuntimeFactory.factory }).pipe( + Layer.provideMerge(ServerConfig.layerTest(process.cwd(), process.cwd())), + Layer.provideMerge(ServerSettingsService.layerTest()), + Layer.provideMerge(providerSessionDirectoryTestLayer), + Layer.provideMerge(NodeServices.layer), + ), +); + +scopedLifecycleLayer("CodexAdapterLive scoped lifecycle", (it) => { + it.effect("closes the externally owned session scope on stopSession", () => + Effect.gen(function* () { + scopedLifecycleRuntimeFactory.releasedThreadIds.length = 0; + const adapter = yield* CodexAdapter; + + yield* adapter.startSession({ + provider: "codex", + threadId: asThreadId("thread-stop"), + runtimeMode: "full-access", + }); + + const runtime = scopedLifecycleRuntimeFactory.lastRuntime; + assert.ok(runtime); + + yield* adapter.stopSession(asThreadId("thread-stop")); + + assert.equal(runtime.closeImpl.mock.calls.length, 1); + assert.deepStrictEqual(scopedLifecycleRuntimeFactory.releasedThreadIds, [ + asThreadId("thread-stop"), + ]); + assert.equal(yield* adapter.hasSession(asThreadId("thread-stop")), false); + }), + ); }); + +const scopedFailureRuntimeFactory = makeScopedRuntimeFactory({ failConstruction: true }); +const scopedFailureLayer = it.layer( + makeCodexAdapterLive({ makeRuntime: scopedFailureRuntimeFactory.factory }).pipe( + Layer.provideMerge(ServerConfig.layerTest(process.cwd(), process.cwd())), + Layer.provideMerge(ServerSettingsService.layerTest()), + Layer.provideMerge(providerSessionDirectoryTestLayer), + Layer.provideMerge(NodeServices.layer), + ), +); + +scopedFailureLayer("CodexAdapterLive scoped startup failure", (it) => { + it.effect("closes the externally owned session scope when startSession fails", () => + Effect.gen(function* () { + scopedFailureRuntimeFactory.releasedThreadIds.length = 0; + const adapter = yield* CodexAdapter; + + const result = yield* adapter + .startSession({ + provider: "codex", + threadId: asThreadId("thread-fail"), + runtimeMode: "full-access", + }) + .pipe(Effect.result); + + assert.equal(result._tag, "Failure"); + assert.equal(result.failure._tag, "ProviderAdapterProcessError"); + assert.deepStrictEqual(scopedFailureRuntimeFactory.releasedThreadIds, [ + asThreadId("thread-fail"), + ]); + assert.equal(yield* adapter.hasSession(asThreadId("thread-fail")), false); + }), + ); +}); + +it.effect("flushes managed native logs when the adapter layer shuts down", () => + Effect.gen(function* () { + const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), "t3-codex-adapter-native-log-")); + const basePath = path.join(tempDir, "provider-native.ndjson"); + const runtimeFactory = makeRuntimeFactory(); + const scope = yield* Scope.make("sequential"); + let scopeClosed = false; + + try { + const layer = makeCodexAdapterLive({ + makeRuntime: runtimeFactory.factory, + nativeEventLogPath: basePath, + }).pipe( + Layer.provideMerge(ServerConfig.layerTest(process.cwd(), process.cwd())), + Layer.provideMerge(ServerSettingsService.layerTest()), + Layer.provideMerge(providerSessionDirectoryTestLayer), + Layer.provideMerge(NodeServices.layer), + ); + const context = yield* Layer.buildWithScope(layer, scope); + const adapter = yield* Effect.service(CodexAdapter).pipe(Effect.provide(context)); + + yield* adapter.startSession({ + provider: "codex", + threadId: asThreadId("thread-logger"), + runtimeMode: "full-access", + }); + + const runtime = runtimeFactory.lastRuntime; + assert.ok(runtime); + + const firstEventFiber = yield* Stream.runHead(adapter.streamEvents).pipe(Effect.forkChild); + yield* runtime.emit({ + id: asEventId("evt-native-log"), + kind: "notification", + provider: "codex", + threadId: asThreadId("thread-logger"), + createdAt: new Date().toISOString(), + method: "process/stderr", + message: "native flush test", + } satisfies ProviderEvent); + yield* Fiber.join(firstEventFiber); + + yield* Scope.close(scope, Exit.void); + scopeClosed = true; + + const threadLogPath = path.join(tempDir, "thread-logger.log"); + assert.equal(fs.existsSync(threadLogPath), true); + const contents = fs.readFileSync(threadLogPath, "utf8"); + assert.match(contents, /NTIVE: .*"message":"native flush test"/); + } finally { + if (!scopeClosed) { + yield* Scope.close(scope, Exit.void); + } + fs.rmSync(tempDir, { recursive: true, force: true }); + } + }), +); diff --git a/apps/server/src/provider/Layers/CodexAdapter.ts b/apps/server/src/provider/Layers/CodexAdapter.ts index 60de91b79a..0111cd013c 100644 --- a/apps/server/src/provider/Layers/CodexAdapter.ts +++ b/apps/server/src/provider/Layers/CodexAdapter.ts @@ -1,8 +1,9 @@ /** * CodexAdapterLive - Scoped live implementation for the Codex provider adapter. * - * Wraps `CodexAppServerManager` behind the `CodexAdapter` service contract and - * maps manager failures into the shared `ProviderAdapterError` algebra. + * Wraps the typed Codex session runtime behind the `CodexAdapter` service + * contract and maps runtime failures into the shared `ProviderAdapterError` + * algebra. * * @module CodexAdapterLive */ @@ -11,98 +12,118 @@ import { type CanonicalRequestType, type ProviderEvent, type ProviderRuntimeEvent, + type ProviderRequestKind, type ThreadTokenUsageSnapshot, type ProviderUserInputAnswers, RuntimeItemId, RuntimeRequestId, - RuntimeTaskId, ProviderApprovalDecision, - ProviderItemId, ThreadId, - TurnId, ProviderSendTurnInput, } from "@t3tools/contracts"; -import { Effect, FileSystem, Layer, Queue, Schema, Context, Stream } from "effect"; +import { Effect, Exit, Fiber, FileSystem, Layer, Queue, Schema, Scope, Stream } from "effect"; +import { ChildProcessSpawner } from "effect/unstable/process"; +import * as CodexErrors from "effect-codex-app-server/errors"; +import * as EffectCodexSchema from "effect-codex-app-server/schema"; import { - ProviderAdapterProcessError, ProviderAdapterRequestError, + ProviderAdapterProcessError, ProviderAdapterSessionClosedError, ProviderAdapterSessionNotFoundError, ProviderAdapterValidationError, type ProviderAdapterError, } from "../Errors.ts"; import { CodexAdapter, type CodexAdapterShape } from "../Services/CodexAdapter.ts"; -import { - CodexAppServerManager, - type CodexAppServerStartSessionInput, -} from "../../codexAppServerManager.ts"; import { resolveAttachmentPath } from "../../attachmentStore.ts"; import { ServerConfig } from "../../config.ts"; import { ServerSettingsService } from "../../serverSettings.ts"; +import { + CodexResumeCursorSchema, + CodexSessionRuntimeThreadIdMissingError, + makeCodexSessionRuntime, + type CodexSessionRuntimeError, + type CodexSessionRuntimeOptions, + type CodexSessionRuntimeShape, +} from "./CodexSessionRuntime.ts"; import { type EventNdjsonLogger, makeEventNdjsonLogger } from "./EventNdjsonLogger.ts"; const PROVIDER = "codex" as const; export interface CodexAdapterLiveOptions { - readonly manager?: CodexAppServerManager; - readonly makeManager?: (services?: Context.Context) => CodexAppServerManager; + readonly makeRuntime?: ( + options: CodexSessionRuntimeOptions, + ) => Effect.Effect< + CodexSessionRuntimeShape, + CodexSessionRuntimeError, + ChildProcessSpawner.ChildProcessSpawner | Scope.Scope + >; readonly nativeEventLogPath?: string; readonly nativeEventLogger?: EventNdjsonLogger; } -function toSessionError( +interface CodexAdapterSessionContext { + readonly threadId: ThreadId; + readonly scope: Scope.Closeable; + readonly runtime: CodexSessionRuntimeShape; + readonly eventFiber: Fiber.Fiber; + stopped: boolean; +} + +function mapCodexRuntimeError( threadId: ThreadId, - cause: unknown, -): ProviderAdapterSessionNotFoundError | ProviderAdapterSessionClosedError | undefined { - const normalized = cause instanceof Error ? cause.message.toLowerCase() : ""; - if (normalized.includes("unknown session") || normalized.includes("unknown provider session")) { - return new ProviderAdapterSessionNotFoundError({ - provider: PROVIDER, - threadId, - cause, - }); - } - if (normalized.includes("session is closed")) { + method: string, + error: CodexSessionRuntimeError, +): ProviderAdapterError { + if ( + Schema.is(CodexErrors.CodexAppServerProcessExitedError)(error) || + Schema.is(CodexErrors.CodexAppServerTransportError)(error) + ) { return new ProviderAdapterSessionClosedError({ provider: PROVIDER, threadId, - cause, + cause: error, }); } - return undefined; -} -function toRequestError(threadId: ThreadId, method: string, cause: unknown): ProviderAdapterError { - const sessionError = toSessionError(threadId, cause); - if (sessionError) { - return sessionError; + if (Schema.is(CodexSessionRuntimeThreadIdMissingError)(error)) { + return new ProviderAdapterSessionNotFoundError({ + provider: PROVIDER, + threadId, + cause: error, + }); } + return new ProviderAdapterRequestError({ provider: PROVIDER, method, - detail: cause instanceof Error ? `${method} failed: ${cause.message}` : `${method} failed`, - cause, + detail: error.message, + cause: error, }); } -function asObject(value: unknown): Record | undefined { - if (!value || typeof value !== "object") { - return undefined; - } - return value as Record; +type CodexLifecycleItem = + | EffectCodexSchema.V2ItemStartedNotification["item"] + | EffectCodexSchema.V2ItemCompletedNotification["item"]; + +type CodexToolUserInputQuestion = + | EffectCodexSchema.ServerRequest__ToolRequestUserInputQuestion + | EffectCodexSchema.ToolRequestUserInputParams__ToolRequestUserInputQuestion; + +const ApprovalDecisionPayload = Schema.Struct({ + decision: ProviderApprovalDecision, +}); + +function readPayload( + schema: Schema.Schema, + payload: ProviderEvent["payload"], +): A | undefined { + return Schema.is(schema)(payload) ? payload : undefined; } -function asString(value: unknown): string | undefined { - return typeof value === "string" ? value : undefined; -} - -function asArray(value: unknown): unknown[] | undefined { - return Array.isArray(value) ? value : undefined; -} - -function asNumber(value: unknown): number | undefined { - return typeof value === "number" && Number.isFinite(value) ? value : undefined; +function trimText(value: string | undefined | null): string | undefined { + const trimmed = value?.trim(); + return trimmed && trimmed.length > 0 ? trimmed : undefined; } const FATAL_CODEX_STDERR_SNIPPETS = ["failed to connect to websocket"]; @@ -112,26 +133,20 @@ function isFatalCodexProcessStderrMessage(message: string): boolean { return FATAL_CODEX_STDERR_SNIPPETS.some((snippet) => normalized.includes(snippet)); } -function normalizeCodexTokenUsage(value: unknown): ThreadTokenUsageSnapshot | undefined { - const usage = asObject(value); - const totalUsage = asObject(usage?.total_token_usage ?? usage?.total); - const lastUsage = asObject(usage?.last_token_usage ?? usage?.last); - - const totalProcessedTokens = - asNumber(totalUsage?.total_tokens) ?? asNumber(totalUsage?.totalTokens); - const usedTokens = - asNumber(lastUsage?.total_tokens) ?? asNumber(lastUsage?.totalTokens) ?? totalProcessedTokens; +function normalizeCodexTokenUsage( + usage: EffectCodexSchema.V2ThreadTokenUsageUpdatedNotification["tokenUsage"], +): ThreadTokenUsageSnapshot | undefined { + const totalProcessedTokens = usage.total.totalTokens; + const usedTokens = usage.last.totalTokens; if (usedTokens === undefined || usedTokens <= 0) { return undefined; } - const maxTokens = asNumber(usage?.model_context_window) ?? asNumber(usage?.modelContextWindow); - const inputTokens = asNumber(lastUsage?.input_tokens) ?? asNumber(lastUsage?.inputTokens); - const cachedInputTokens = - asNumber(lastUsage?.cached_input_tokens) ?? asNumber(lastUsage?.cachedInputTokens); - const outputTokens = asNumber(lastUsage?.output_tokens) ?? asNumber(lastUsage?.outputTokens); - const reasoningOutputTokens = - asNumber(lastUsage?.reasoning_output_tokens) ?? asNumber(lastUsage?.reasoningOutputTokens); + const maxTokens = usage.modelContextWindow ?? undefined; + const inputTokens = usage.last.inputTokens; + const cachedInputTokens = usage.last.cachedInputTokens; + const outputTokens = usage.last.outputTokens; + const reasoningOutputTokens = usage.last.reasoningOutputTokens; return { usedTokens, @@ -154,15 +169,9 @@ function normalizeCodexTokenUsage(value: unknown): ThreadTokenUsageSnapshot | un }; } -function toTurnId(value: string | undefined): TurnId | undefined { - return value?.trim() ? TurnId.make(value) : undefined; -} - -function toProviderItemId(value: string | undefined): ProviderItemId | undefined { - return value?.trim() ? ProviderItemId.make(value) : undefined; -} - -function toTurnStatus(value: unknown): "completed" | "failed" | "cancelled" | "interrupted" { +function toTurnStatus( + value: EffectCodexSchema.V2TurnCompletedNotification["turn"]["status"] | "cancelled", +): "completed" | "failed" | "cancelled" | "interrupted" { switch (value) { case "completed": case "failed": @@ -174,8 +183,8 @@ function toTurnStatus(value: unknown): "completed" | "failed" | "cancelled" | "i } } -function normalizeItemType(raw: unknown): string { - const type = asString(raw); +function normalizeItemType(raw: string | undefined | null): string { + const type = trimText(raw); if (!type) return "item"; return type .replace(/([a-z0-9])([A-Z])/g, "$1 $2") @@ -185,7 +194,7 @@ function normalizeItemType(raw: unknown): string { .toLowerCase(); } -function toCanonicalItemType(raw: unknown): CanonicalItemType { +function toCanonicalItemType(raw: string | undefined | null): CanonicalItemType { const type = normalizeItemType(raw); if (type.includes("user")) return "user_message"; if (type.includes("agent message") || type.includes("assistant")) return "assistant_message"; @@ -235,27 +244,18 @@ function itemTitle(itemType: CanonicalItemType): string | undefined { } } -function itemDetail( - item: Record, - payload: Record, -): string | undefined { - const nestedResult = asObject(item.result); +function itemDetail(item: CodexLifecycleItem): string | undefined { const candidates = [ - asString(item.command), - asString(item.title), - asString(item.summary), - asString(item.text), - asString(item.path), - asString(item.prompt), - asString(nestedResult?.command), - asString(payload.command), - asString(payload.message), - asString(payload.prompt), + "command" in item ? item.command : undefined, + "title" in item ? item.title : undefined, + "summary" in item ? item.summary : undefined, + "text" in item ? item.text : undefined, + "path" in item ? item.path : undefined, + "prompt" in item ? item.prompt : undefined, ]; for (const candidate of candidates) { - if (!candidate) continue; - const trimmed = candidate.trim(); - if (trimmed.length === 0) continue; + const trimmed = typeof candidate === "string" ? trimText(candidate) : undefined; + if (!trimmed) continue; return trimmed; } return undefined; @@ -284,7 +284,7 @@ function toRequestTypeFromMethod(method: string): CanonicalRequestType { } } -function toRequestTypeFromKind(kind: unknown): CanonicalRequestType { +function toRequestTypeFromKind(kind: ProviderRequestKind | undefined): CanonicalRequestType { switch (kind) { case "command": return "command_execution_approval"; @@ -297,77 +297,36 @@ function toRequestTypeFromKind(kind: unknown): CanonicalRequestType { } } -function toRequestTypeFromResolvedPayload( - payload: Record | undefined, -): CanonicalRequestType { - const request = asObject(payload?.request); - const method = asString(request?.method) ?? asString(payload?.method); - if (method) { - return toRequestTypeFromMethod(method); - } - const requestKind = asString(request?.kind) ?? asString(payload?.requestKind); - if (requestKind) { - return toRequestTypeFromKind(requestKind); - } - return "unknown"; -} - function toCanonicalUserInputAnswers( - answers: ProviderUserInputAnswers | undefined, + answers: EffectCodexSchema.ToolRequestUserInputResponse["answers"], ): ProviderUserInputAnswers { - if (!answers) { - return {}; - } - return Object.fromEntries( - Object.entries(answers).flatMap(([questionId, value]) => { - if (typeof value === "string") { - return [[questionId, value] as const]; - } - - if (Array.isArray(value)) { - const normalized = value.filter((entry): entry is string => typeof entry === "string"); - return [[questionId, normalized.length === 1 ? normalized[0] : normalized] as const]; - } - - const answerObject = asObject(value); - const answerList = asArray(answerObject?.answers)?.filter( - (entry): entry is string => typeof entry === "string", - ); - if (!answerList) { - return []; - } - return [[questionId, answerList.length === 1 ? answerList[0] : answerList] as const]; + Object.entries(answers).map(([questionId, value]) => { + const normalizedAnswers = value.answers.length === 1 ? value.answers[0]! : [...value.answers]; + return [questionId, normalizedAnswers] as const; }), ); } -function toUserInputQuestions(payload: Record | undefined) { - const questions = asArray(payload?.questions); - if (!questions) { - return undefined; - } - +function toUserInputQuestions(questions: ReadonlyArray) { const parsedQuestions = questions - .map((entry) => { - const question = asObject(entry); - if (!question) return undefined; - const options = asArray(question.options) - ?.map((option) => { - const optionRecord = asObject(option); - if (!optionRecord) return undefined; - const label = asString(optionRecord.label)?.trim(); - const description = asString(optionRecord.description)?.trim(); - if (!label || !description) { - return undefined; - } - return { label, description }; - }) - .filter((option): option is { label: string; description: string } => option !== undefined); - const id = asString(question.id)?.trim(); - const header = asString(question.header)?.trim(); - const prompt = asString(question.question)?.trim(); - if (!id || !header || !prompt || !options || options.length === 0) { + .map((question) => { + const options = + question.options + ?.map((option) => { + const label = trimText(option.label); + const description = trimText(option.description); + if (!label || !description) { + return undefined; + } + return { label, description }; + }) + .filter((option) => option !== undefined) ?? []; + + const id = trimText(question.id); + const header = trimText(question.header); + const prompt = trimText(question.question); + if (!id || !header || !prompt || options.length === 0) { return undefined; } return { @@ -375,38 +334,21 @@ function toUserInputQuestions(payload: Record | undefined) { header, question: prompt, options, - multiSelect: question.multiSelect === true, + multiSelect: false, }; }) - .filter( - ( - question, - ): question is { - id: string; - header: string; - question: string; - options: Array<{ label: string; description: string }>; - multiSelect: boolean; - } => question !== undefined, - ); + .filter((question) => question !== undefined); return parsedQuestions.length > 0 ? parsedQuestions : undefined; } function toThreadState( - value: unknown, + status: EffectCodexSchema.V2ThreadStatusChangedNotification["status"], ): "active" | "idle" | "archived" | "closed" | "compacted" | "error" { - switch (value) { + switch (status.type) { case "idle": return "idle"; - case "archived": - return "archived"; - case "closed": - return "closed"; - case "compacted": - return "compacted"; - case "error": - case "failed": + case "systemError": return "error"; default: return "active"; @@ -438,15 +380,7 @@ function contentStreamKindFromMethod( } } -const PROPOSED_PLAN_BLOCK_REGEX = /\s*([\s\S]*?)\s*<\/proposed_plan>/i; - -function extractProposedPlanMarkdown(text: string | undefined): string | undefined { - const match = text ? PROPOSED_PLAN_BLOCK_REGEX.exec(text) : null; - const planMarkdown = match?.[1]?.trim(); - return planMarkdown && planMarkdown.length > 0 ? planMarkdown : undefined; -} - -function asRuntimeItemId(itemId: ProviderItemId): RuntimeItemId { +function asRuntimeItemId(itemId: ProviderEvent["itemId"] & string): RuntimeItemId { return RuntimeItemId.make(itemId); } @@ -454,48 +388,6 @@ function asRuntimeRequestId(requestId: string): RuntimeRequestId { return RuntimeRequestId.make(requestId); } -function asRuntimeTaskId(taskId: string): RuntimeTaskId { - return RuntimeTaskId.make(taskId); -} - -function codexEventMessage( - payload: Record | undefined, -): Record | undefined { - return asObject(payload?.msg); -} - -function codexEventBase( - event: ProviderEvent, - canonicalThreadId: ThreadId, -): Omit { - const payload = asObject(event.payload); - const msg = codexEventMessage(payload); - const turnId = event.turnId ?? toTurnId(asString(msg?.turn_id) ?? asString(msg?.turnId)); - const itemId = event.itemId ?? toProviderItemId(asString(msg?.item_id) ?? asString(msg?.itemId)); - const requestId = asString(msg?.request_id) ?? asString(msg?.requestId); - const base = runtimeEventBase(event, canonicalThreadId); - const providerRefs = base.providerRefs - ? { - ...base.providerRefs, - ...(turnId ? { providerTurnId: turnId } : {}), - ...(itemId ? { providerItemId: itemId } : {}), - ...(requestId ? { providerRequestId: requestId } : {}), - } - : { - ...(turnId ? { providerTurnId: turnId } : {}), - ...(itemId ? { providerItemId: itemId } : {}), - ...(requestId ? { providerRequestId: requestId } : {}), - }; - - return { - ...base, - ...(turnId ? { turnId } : {}), - ...(itemId ? { itemId: asRuntimeItemId(itemId) } : {}), - ...(requestId ? { requestId: asRuntimeRequestId(requestId) } : {}), - ...(Object.keys(providerRefs).length > 0 ? { providerRefs } : {}), - }; -} - function eventRawSource(event: ProviderEvent): NonNullable["source"] { return event.kind === "request" ? "codex.app-server.request" : "codex.app-server.notification"; } @@ -538,19 +430,19 @@ function mapItemLifecycle( canonicalThreadId: ThreadId, lifecycle: "item.started" | "item.updated" | "item.completed", ): ProviderRuntimeEvent | undefined { - const payload = asObject(event.payload); - const item = asObject(payload?.item); - const source = item ?? payload; - if (!source) { + const payload = + readPayload(EffectCodexSchema.V2ItemStartedNotification, event.payload) ?? + readPayload(EffectCodexSchema.V2ItemCompletedNotification, event.payload); + const item = payload?.item; + if (!item) { return undefined; } - - const itemType = toCanonicalItemType(source.type ?? source.kind); + const itemType = toCanonicalItemType(item.type); if (itemType === "unknown" && lifecycle !== "item.updated") { return undefined; } - const detail = itemDetail(source, payload ?? {}); + const detail = itemDetail(item); const status = lifecycle === "item.started" ? "inProgress" @@ -575,9 +467,6 @@ function mapToRuntimeEvents( event: ProviderEvent, canonicalThreadId: ThreadId, ): ReadonlyArray { - const payload = asObject(event.payload); - const turn = asObject(payload?.turn); - if (event.kind === "error") { if (!event.message) { return []; @@ -597,7 +486,10 @@ function mapToRuntimeEvents( if (event.kind === "request") { if (event.method === "item/tool/requestUserInput") { - const questions = toUserInputQuestions(payload); + const payload = + readPayload(EffectCodexSchema.ServerRequest__ToolRequestUserInputParams, event.payload) ?? + readPayload(EffectCodexSchema.ToolRequestUserInputParams, event.payload); + const questions = payload ? toUserInputQuestions(payload.questions) : undefined; if (!questions) { return []; } @@ -612,8 +504,48 @@ function mapToRuntimeEvents( ]; } - const detail = - asString(payload?.command) ?? asString(payload?.reason) ?? asString(payload?.prompt); + const detail = (() => { + switch (event.method) { + case "item/commandExecution/requestApproval": { + const payload = readPayload( + EffectCodexSchema.ServerRequest__CommandExecutionRequestApprovalParams, + event.payload, + ); + return payload?.command ?? payload?.reason ?? undefined; + } + case "item/fileChange/requestApproval": { + const payload = readPayload( + EffectCodexSchema.ServerRequest__FileChangeRequestApprovalParams, + event.payload, + ); + return payload?.reason ?? undefined; + } + case "applyPatchApproval": { + const payload = readPayload( + EffectCodexSchema.ServerRequest__ApplyPatchApprovalParams, + event.payload, + ); + return payload?.reason ?? undefined; + } + case "execCommandApproval": { + const payload = readPayload( + EffectCodexSchema.ServerRequest__ExecCommandApprovalParams, + event.payload, + ); + return payload?.reason ?? payload?.command.join(" "); + } + case "item/tool/call": { + const payload = readPayload( + EffectCodexSchema.ServerRequest__DynamicToolCallParams, + event.payload, + ); + return payload?.tool ?? undefined; + } + default: + return undefined; + } + })(); + return [ { ...runtimeEventBase(event, canonicalThreadId), @@ -628,7 +560,7 @@ function mapToRuntimeEvents( } if (event.method === "item/requestApproval/decision" && event.requestId) { - const decision = Schema.decodeUnknownSync(ProviderApprovalDecision)(payload?.decision); + const payload = readPayload(ApprovalDecisionPayload, event.payload); const requestType = event.requestKind !== undefined ? toRequestTypeFromKind(event.requestKind) @@ -639,7 +571,7 @@ function mapToRuntimeEvents( type: "request.resolved", payload: { requestType, - ...(decision ? { decision } : {}), + ...(payload ? { decision: payload.decision } : {}), ...(event.payload !== undefined ? { resolution: event.payload } : {}), }, }, @@ -699,9 +631,8 @@ function mapToRuntimeEvents( } if (event.method === "thread/started") { - const payloadThreadId = asString(asObject(payload?.thread)?.id); - const providerThreadId = payloadThreadId ?? asString(payload?.threadId); - if (!providerThreadId) { + const payload = readPayload(EffectCodexSchema.V2ThreadStartedNotification, event.payload); + if (!payload) { return []; } return [ @@ -709,7 +640,7 @@ function mapToRuntimeEvents( ...runtimeEventBase(event, canonicalThreadId), type: "thread.started", payload: { - providerThreadId, + providerThreadId: payload.thread.id, }, }, ]; @@ -722,6 +653,10 @@ function mapToRuntimeEvents( event.method === "thread/closed" || event.method === "thread/compacted" ) { + const payload = + event.method === "thread/status/changed" + ? readPayload(EffectCodexSchema.V2ThreadStatusChangedNotification, event.payload) + : undefined; return [ { type: "thread.state.changed", @@ -734,7 +669,9 @@ function mapToRuntimeEvents( ? "closed" : event.method === "thread/compacted" ? "compacted" - : toThreadState(asObject(payload?.thread)?.state ?? payload?.state), + : payload + ? toThreadState(payload.status) + : "active", ...(event.payload !== undefined ? { detail: event.payload } : {}), }, }, @@ -742,21 +679,34 @@ function mapToRuntimeEvents( } if (event.method === "thread/name/updated") { + const payload = readPayload(EffectCodexSchema.V2ThreadNameUpdatedNotification, event.payload); return [ { type: "thread.metadata.updated", ...runtimeEventBase(event, canonicalThreadId), payload: { - ...(asString(payload?.threadName) ? { name: asString(payload?.threadName) } : {}), - ...(event.payload !== undefined ? { metadata: asObject(event.payload) } : {}), + ...(trimText(payload?.threadName) ? { name: trimText(payload?.threadName) } : {}), + ...(payload + ? { + metadata: { + threadId: payload.threadId, + ...(payload.threadName !== undefined && payload.threadName !== null + ? { threadName: payload.threadName } + : {}), + }, + } + : {}), }, }, ]; } if (event.method === "thread/tokenUsage/updated") { - const tokenUsage = asObject(payload?.tokenUsage); - const normalizedUsage = normalizeCodexTokenUsage(tokenUsage ?? event.payload); + const payload = readPayload( + EffectCodexSchema.V2ThreadTokenUsageUpdatedNotification, + event.payload, + ); + const normalizedUsage = payload ? normalizeCodexTokenUsage(payload.tokenUsage) : undefined; if (!normalizedUsage) { return []; } @@ -781,28 +731,23 @@ function mapToRuntimeEvents( ...runtimeEventBase(event, canonicalThreadId), turnId, type: "turn.started", - payload: { - ...(asString(turn?.model) ? { model: asString(turn?.model) } : {}), - ...(asString(turn?.effort) ? { effort: asString(turn?.effort) } : {}), - }, + payload: {}, }, ]; } if (event.method === "turn/completed") { - const errorMessage = asString(asObject(turn?.error)?.message); + const payload = readPayload(EffectCodexSchema.V2TurnCompletedNotification, event.payload); + if (!payload) { + return []; + } + const errorMessage = trimText(payload.turn.error?.message); return [ { ...runtimeEventBase(event, canonicalThreadId), type: "turn.completed", payload: { - state: toTurnStatus(turn?.status), - ...(asString(turn?.stopReason) ? { stopReason: asString(turn?.stopReason) } : {}), - ...(turn?.usage !== undefined ? { usage: turn.usage } : {}), - ...(asObject(turn?.modelUsage) ? { modelUsage: asObject(turn?.modelUsage) } : {}), - ...(asNumber(turn?.totalCostUsd) !== undefined - ? { totalCostUsd: asNumber(turn?.totalCostUsd) } - : {}), + state: toTurnStatus(payload.turn.status), ...(errorMessage ? { errorMessage } : {}), }, }, @@ -822,41 +767,37 @@ function mapToRuntimeEvents( } if (event.method === "turn/plan/updated") { - const steps = Array.isArray(payload?.plan) ? payload.plan : []; + const payload = readPayload(EffectCodexSchema.V2TurnPlanUpdatedNotification, event.payload); + if (!payload) { + return []; + } return [ { ...runtimeEventBase(event, canonicalThreadId), type: "turn.plan.updated", payload: { - ...(asString(payload?.explanation) - ? { explanation: asString(payload?.explanation) } - : {}), - plan: steps - .map((entry) => asObject(entry)) - .filter((entry): entry is Record => entry !== undefined) - .map((entry) => ({ - step: asString(entry.step) ?? "step", - status: - entry.status === "completed" || entry.status === "inProgress" - ? entry.status - : "pending", - })), + ...(trimText(payload.explanation) ? { explanation: trimText(payload.explanation) } : {}), + plan: payload.plan.map((step) => ({ + step: trimText(step.step) ?? "step", + status: + step.status === "completed" || step.status === "inProgress" ? step.status : "pending", + })), }, }, ]; } if (event.method === "turn/diff/updated") { + const payload = readPayload(EffectCodexSchema.V2TurnDiffUpdatedNotification, event.payload); + if (!payload) { + return []; + } return [ { ...runtimeEventBase(event, canonicalThreadId), type: "turn.diff.updated", payload: { - unifiedDiff: - asString(payload?.unifiedDiff) ?? - asString(payload?.diff) ?? - asString(payload?.patch) ?? - "", + unifiedDiff: payload.diff, }, }, ]; @@ -868,15 +809,14 @@ function mapToRuntimeEvents( } if (event.method === "item/completed") { - const payload = asObject(event.payload); - const item = asObject(payload?.item); - const source = item ?? payload; - if (!source) { + const payload = readPayload(EffectCodexSchema.V2ItemCompletedNotification, event.payload); + const item = payload?.item; + if (!item) { return []; } - const itemType = source ? toCanonicalItemType(source.type ?? source.kind) : "unknown"; + const itemType = toCanonicalItemType(item.type); if (itemType === "plan") { - const detail = itemDetail(source, payload ?? {}); + const detail = itemDetail(item); if (!detail) { return []; } @@ -898,16 +838,22 @@ function mapToRuntimeEvents( event.method === "item/reasoning/summaryPartAdded" || event.method === "item/commandExecution/terminalInteraction" ) { - const updated = mapItemLifecycle(event, canonicalThreadId, "item.updated"); - return updated ? [updated] : []; + return [ + { + ...runtimeEventBase(event, canonicalThreadId), + type: "item.updated", + payload: { + itemType: + event.method === "item/reasoning/summaryPartAdded" ? "reasoning" : "command_execution", + ...(event.payload !== undefined ? { data: event.payload } : {}), + }, + }, + ]; } if (event.method === "item/plan/delta") { - const delta = - event.textDelta ?? - asString(payload?.delta) ?? - asString(payload?.text) ?? - asString(asObject(payload?.content)?.text); + const payload = readPayload(EffectCodexSchema.V2PlanDeltaNotification, event.payload); + const delta = event.textDelta ?? payload?.delta; if (!delta || delta.length === 0) { return []; } @@ -922,18 +868,9 @@ function mapToRuntimeEvents( ]; } - if ( - event.method === "item/agentMessage/delta" || - event.method === "item/commandExecution/outputDelta" || - event.method === "item/fileChange/outputDelta" || - event.method === "item/reasoning/summaryTextDelta" || - event.method === "item/reasoning/textDelta" - ) { - const delta = - event.textDelta ?? - asString(payload?.delta) ?? - asString(payload?.text) ?? - asString(asObject(payload?.content)?.text); + if (event.method === "item/agentMessage/delta") { + const payload = readPayload(EffectCodexSchema.V2AgentMessageDeltaNotification, event.payload); + const delta = event.textDelta ?? payload?.delta; if (!delta || delta.length === 0) { return []; } @@ -944,41 +881,119 @@ function mapToRuntimeEvents( payload: { streamKind: contentStreamKindFromMethod(event.method), delta, - ...(typeof payload?.contentIndex === "number" - ? { contentIndex: payload.contentIndex } - : {}), - ...(typeof payload?.summaryIndex === "number" - ? { summaryIndex: payload.summaryIndex } - : {}), + }, + }, + ]; + } + + if (event.method === "item/commandExecution/outputDelta") { + const payload = readPayload( + EffectCodexSchema.V2CommandExecutionOutputDeltaNotification, + event.payload, + ); + const delta = event.textDelta ?? payload?.delta; + if (!delta || delta.length === 0) { + return []; + } + return [ + { + ...runtimeEventBase(event, canonicalThreadId), + type: "content.delta", + payload: { + streamKind: "command_output", + delta, + }, + }, + ]; + } + + if (event.method === "item/fileChange/outputDelta") { + const payload = readPayload( + EffectCodexSchema.V2FileChangeOutputDeltaNotification, + event.payload, + ); + const delta = event.textDelta ?? payload?.delta; + if (!delta || delta.length === 0) { + return []; + } + return [ + { + ...runtimeEventBase(event, canonicalThreadId), + type: "content.delta", + payload: { + streamKind: "file_change_output", + delta, + }, + }, + ]; + } + + if (event.method === "item/reasoning/summaryTextDelta") { + const payload = readPayload( + EffectCodexSchema.V2ReasoningSummaryTextDeltaNotification, + event.payload, + ); + const delta = event.textDelta ?? payload?.delta; + if (!delta || delta.length === 0) { + return []; + } + return [ + { + ...runtimeEventBase(event, canonicalThreadId), + type: "content.delta", + payload: { + streamKind: "reasoning_summary_text", + delta, + ...(payload ? { summaryIndex: payload.summaryIndex } : {}), + }, + }, + ]; + } + + if (event.method === "item/reasoning/textDelta") { + const payload = readPayload(EffectCodexSchema.V2ReasoningTextDeltaNotification, event.payload); + const delta = event.textDelta ?? payload?.delta; + if (!delta || delta.length === 0) { + return []; + } + return [ + { + ...runtimeEventBase(event, canonicalThreadId), + type: "content.delta", + payload: { + streamKind: "reasoning_text", + delta, + ...(payload ? { contentIndex: payload.contentIndex } : {}), }, }, ]; } if (event.method === "item/mcpToolCall/progress") { + const payload = readPayload(EffectCodexSchema.V2McpToolCallProgressNotification, event.payload); + if (!payload) { + return []; + } return [ { ...runtimeEventBase(event, canonicalThreadId), type: "tool.progress", payload: { - ...(asString(payload?.toolUseId) ? { toolUseId: asString(payload?.toolUseId) } : {}), - ...(asString(payload?.toolName) ? { toolName: asString(payload?.toolName) } : {}), - ...(asString(payload?.summary) ? { summary: asString(payload?.summary) } : {}), - ...(asNumber(payload?.elapsedSeconds) !== undefined - ? { elapsedSeconds: asNumber(payload?.elapsedSeconds) } - : {}), + summary: payload.message, }, }, ]; } if (event.method === "serverRequest/resolved") { - const requestType = - toRequestTypeFromResolvedPayload(payload) !== "unknown" - ? toRequestTypeFromResolvedPayload(payload) - : event.requestId && event.requestKind !== undefined - ? toRequestTypeFromKind(event.requestKind) - : "unknown"; + const payload = readPayload( + EffectCodexSchema.V2ServerRequestResolvedNotification, + event.payload, + ); + if (!payload) { + return []; + } + const requestType = toRequestTypeFromKind(event.requestKind); return [ { ...runtimeEventBase(event, canonicalThreadId), @@ -992,168 +1007,81 @@ function mapToRuntimeEvents( } if (event.method === "item/tool/requestUserInput/answered") { + const payload = readPayload(EffectCodexSchema.ToolRequestUserInputResponse, event.payload); + if (!payload) { + return []; + } return [ { ...runtimeEventBase(event, canonicalThreadId), type: "user-input.resolved", payload: { - answers: toCanonicalUserInputAnswers( - asObject(event.payload)?.answers as ProviderUserInputAnswers | undefined, - ), - }, - }, - ]; - } - - if (event.method === "codex/event/task_started") { - const msg = codexEventMessage(payload); - const taskId = asString(payload?.id) ?? asString(msg?.turn_id); - if (!taskId) { - return []; - } - return [ - { - ...codexEventBase(event, canonicalThreadId), - type: "task.started", - payload: { - taskId: asRuntimeTaskId(taskId), - ...(asString(msg?.collaboration_mode_kind) - ? { taskType: asString(msg?.collaboration_mode_kind) } - : {}), - }, - }, - ]; - } - - if (event.method === "codex/event/task_complete") { - const msg = codexEventMessage(payload); - const taskId = asString(payload?.id) ?? asString(msg?.turn_id); - const proposedPlanMarkdown = extractProposedPlanMarkdown(asString(msg?.last_agent_message)); - if (!taskId) { - if (!proposedPlanMarkdown) { - return []; - } - return [ - { - ...codexEventBase(event, canonicalThreadId), - type: "turn.proposed.completed", - payload: { - planMarkdown: proposedPlanMarkdown, - }, - }, - ]; - } - const events: ProviderRuntimeEvent[] = [ - { - ...codexEventBase(event, canonicalThreadId), - type: "task.completed", - payload: { - taskId: asRuntimeTaskId(taskId), - status: "completed", - ...(asString(msg?.last_agent_message) - ? { summary: asString(msg?.last_agent_message) } - : {}), - }, - }, - ]; - if (proposedPlanMarkdown) { - events.push({ - ...codexEventBase(event, canonicalThreadId), - type: "turn.proposed.completed", - payload: { - planMarkdown: proposedPlanMarkdown, - }, - }); - } - return events; - } - - if (event.method === "codex/event/agent_reasoning") { - const msg = codexEventMessage(payload); - const taskId = asString(payload?.id); - const description = asString(msg?.text); - if (!taskId || !description) { - return []; - } - return [ - { - ...codexEventBase(event, canonicalThreadId), - type: "task.progress", - payload: { - taskId: asRuntimeTaskId(taskId), - description, - }, - }, - ]; - } - - if (event.method === "codex/event/reasoning_content_delta") { - const msg = codexEventMessage(payload); - const delta = asString(msg?.delta); - if (!delta) { - return []; - } - return [ - { - ...codexEventBase(event, canonicalThreadId), - type: "content.delta", - payload: { - streamKind: - asNumber(msg?.summary_index) !== undefined - ? "reasoning_summary_text" - : "reasoning_text", - delta, - ...(asNumber(msg?.summary_index) !== undefined - ? { summaryIndex: asNumber(msg?.summary_index) } - : {}), + answers: toCanonicalUserInputAnswers(payload.answers), }, }, ]; } if (event.method === "model/rerouted") { + const payload = readPayload(EffectCodexSchema.V2ModelReroutedNotification, event.payload); + if (!payload) { + return []; + } return [ { type: "model.rerouted", ...runtimeEventBase(event, canonicalThreadId), payload: { - fromModel: asString(payload?.fromModel) ?? "unknown", - toModel: asString(payload?.toModel) ?? "unknown", - reason: asString(payload?.reason) ?? "unknown", + fromModel: payload.fromModel, + toModel: payload.toModel, + reason: payload.reason, }, }, ]; } if (event.method === "deprecationNotice") { + const payload = readPayload(EffectCodexSchema.V2DeprecationNoticeNotification, event.payload); + if (!payload) { + return []; + } return [ { type: "deprecation.notice", ...runtimeEventBase(event, canonicalThreadId), payload: { - summary: asString(payload?.summary) ?? "Deprecation notice", - ...(asString(payload?.details) ? { details: asString(payload?.details) } : {}), + summary: payload.summary, + ...(trimText(payload.details) ? { details: trimText(payload.details) } : {}), }, }, ]; } if (event.method === "configWarning") { + const payload = readPayload(EffectCodexSchema.V2ConfigWarningNotification, event.payload); + if (!payload) { + return []; + } return [ { type: "config.warning", ...runtimeEventBase(event, canonicalThreadId), payload: { - summary: asString(payload?.summary) ?? "Configuration warning", - ...(asString(payload?.details) ? { details: asString(payload?.details) } : {}), - ...(asString(payload?.path) ? { path: asString(payload?.path) } : {}), - ...(payload?.range !== undefined ? { range: payload.range } : {}), + summary: payload.summary, + ...(trimText(payload.details) ? { details: trimText(payload.details) } : {}), + ...(trimText(payload.path) ? { path: trimText(payload.path) } : {}), + ...(payload.range !== undefined && payload.range !== null + ? { range: payload.range } + : {}), }, }, ]; } if (event.method === "account/updated") { + if (!readPayload(EffectCodexSchema.V2AccountUpdatedNotification, event.payload)) { + return []; + } return [ { type: "account.updated", @@ -1166,6 +1094,9 @@ function mapToRuntimeEvents( } if (event.method === "account/rateLimits/updated") { + if (!readPayload(EffectCodexSchema.V2AccountRateLimitsUpdatedNotification, event.payload)) { + return []; + } return [ { type: "account.rate-limits.updated", @@ -1178,58 +1109,86 @@ function mapToRuntimeEvents( } if (event.method === "mcpServer/oauthLogin/completed") { + const payload = readPayload( + EffectCodexSchema.V2McpServerOauthLoginCompletedNotification, + event.payload, + ); + if (!payload) { + return []; + } return [ { type: "mcp.oauth.completed", ...runtimeEventBase(event, canonicalThreadId), payload: { - success: payload?.success === true, - ...(asString(payload?.name) ? { name: asString(payload?.name) } : {}), - ...(asString(payload?.error) ? { error: asString(payload?.error) } : {}), + success: payload.success, + name: payload.name, + ...(trimText(payload.error) ? { error: trimText(payload.error) } : {}), }, }, ]; } if (event.method === "thread/realtime/started") { - const realtimeSessionId = asString(payload?.realtimeSessionId); + const payload = readPayload( + EffectCodexSchema.V2ThreadRealtimeStartedNotification, + event.payload, + ); + if (!payload) { + return []; + } return [ { type: "thread.realtime.started", ...runtimeEventBase(event, canonicalThreadId), payload: { - realtimeSessionId, + realtimeSessionId: payload.sessionId ?? undefined, }, }, ]; } if (event.method === "thread/realtime/itemAdded") { + const payload = readPayload( + EffectCodexSchema.V2ThreadRealtimeItemAddedNotification, + event.payload, + ); + if (!payload) { + return []; + } return [ { type: "thread.realtime.item-added", ...runtimeEventBase(event, canonicalThreadId), payload: { - item: event.payload ?? {}, + item: payload.item, }, }, ]; } if (event.method === "thread/realtime/outputAudio/delta") { + const payload = readPayload( + EffectCodexSchema.V2ThreadRealtimeOutputAudioDeltaNotification, + event.payload, + ); + if (!payload) { + return []; + } return [ { type: "thread.realtime.audio.delta", ...runtimeEventBase(event, canonicalThreadId), payload: { - audio: event.payload ?? {}, + audio: payload.audio, }, }, ]; } if (event.method === "thread/realtime/error") { - const message = asString(payload?.message) ?? event.message ?? "Realtime error"; + const payload = readPayload(EffectCodexSchema.V2ThreadRealtimeErrorNotification, event.payload); + const message = payload?.message ?? event.message ?? "Realtime error"; return [ { type: "thread.realtime.error", @@ -1242,20 +1201,24 @@ function mapToRuntimeEvents( } if (event.method === "thread/realtime/closed") { + const payload = readPayload( + EffectCodexSchema.V2ThreadRealtimeClosedNotification, + event.payload, + ); return [ { type: "thread.realtime.closed", ...runtimeEventBase(event, canonicalThreadId), payload: { - reason: event.message, + reason: payload?.reason ?? event.message, }, }, ]; } if (event.method === "error") { - const message = - asString(asObject(payload?.error)?.message) ?? event.message ?? "Provider runtime error"; + const payload = readPayload(EffectCodexSchema.V2ErrorNotification, event.payload); + const message = payload?.error.message ?? event.message ?? "Provider runtime error"; const willRetry = payload?.willRetry === true; return [ { @@ -1296,6 +1259,9 @@ function mapToRuntimeEvents( } if (event.method === "windows/worldWritableWarning") { + if (!readPayload(EffectCodexSchema.V2WindowsWorldWritableWarningNotification, event.payload)) { + return []; + } return [ { type: "runtime.warning", @@ -1309,8 +1275,13 @@ function mapToRuntimeEvents( } if (event.method === "windowsSandbox/setupCompleted") { - const payloadRecord = asObject(event.payload); - const success = payloadRecord?.success; + const payload = readPayload( + EffectCodexSchema.V2WindowsSandboxSetupCompletedNotification, + event.payload, + ); + if (!payload) { + return []; + } const successMessage = event.message ?? "Windows sandbox setup completed"; const failureMessage = event.message ?? "Windows sandbox setup failed"; @@ -1319,12 +1290,12 @@ function mapToRuntimeEvents( type: "session.state.changed", ...runtimeEventBase(event, canonicalThreadId), payload: { - state: success === false ? "error" : "ready", - reason: success === false ? failureMessage : successMessage, + state: payload.success === false ? "error" : "ready", + reason: payload.success === false ? failureMessage : successMessage, ...(event.payload !== undefined ? { detail: event.payload } : {}), }, }, - ...(success === false + ...(payload.success === false ? [ { type: "runtime.warning" as const, @@ -1346,6 +1317,7 @@ const makeCodexAdapter = Effect.fn("makeCodexAdapter")(function* ( options?: CodexAdapterLiveOptions, ) { const fileSystem = yield* FileSystem.FileSystem; + const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; const serverConfig = yield* Effect.service(ServerConfig); const nativeEventLogger = options?.nativeEventLogger ?? @@ -1354,78 +1326,124 @@ const makeCodexAdapter = Effect.fn("makeCodexAdapter")(function* ( stream: "native", }) : undefined); - - const acquireManager = Effect.fn("acquireManager")(function* () { - if (options?.manager) { - return options.manager; - } - const services = yield* Effect.context(); - return options?.makeManager?.(services) ?? new CodexAppServerManager(services); - }); - - const manager = yield* Effect.acquireRelease(acquireManager(), (manager) => - Effect.sync(() => { - try { - manager.stopAll(); - } catch { - // Finalizers should never fail and block shutdown. - } - }), - ); + const managedNativeEventLogger = + options?.nativeEventLogger === undefined ? nativeEventLogger : undefined; const serverSettingsService = yield* ServerSettingsService; + const runtimeEventQueue = yield* Queue.unbounded(); + const sessions = new Map(); - const startSession: CodexAdapterShape["startSession"] = Effect.fn("startSession")( - function* (input) { - if (input.provider !== undefined && input.provider !== PROVIDER) { - return yield* new ProviderAdapterValidationError({ - provider: PROVIDER, - operation: "startSession", - issue: `Expected provider '${PROVIDER}' but received '${input.provider}'.`, - }); - } - - const codexSettings = yield* serverSettingsService.getSettings.pipe( - Effect.map((settings) => settings.providers.codex), - Effect.mapError( - (error) => - new ProviderAdapterProcessError({ - provider: PROVIDER, - threadId: input.threadId, - detail: error.message, - cause: error, - }), - ), - ); - const binaryPath = codexSettings.binaryPath; - const homePath = codexSettings.homePath; - const managerInput: CodexAppServerStartSessionInput = { - threadId: input.threadId, - provider: "codex", - ...(input.cwd !== undefined ? { cwd: input.cwd } : {}), - ...(input.resumeCursor !== undefined ? { resumeCursor: input.resumeCursor } : {}), - runtimeMode: input.runtimeMode, - binaryPath, - ...(homePath ? { homePath } : {}), - ...(input.modelSelection?.provider === "codex" - ? { model: input.modelSelection.model } - : {}), - ...(input.modelSelection?.provider === "codex" && input.modelSelection.options?.fastMode - ? { serviceTier: "fast" } - : {}), - }; - - return yield* Effect.tryPromise({ - try: () => manager.startSession(managerInput), - catch: (cause) => - new ProviderAdapterProcessError({ + const startSession: CodexAdapterShape["startSession"] = (input) => + Effect.scoped( + Effect.gen(function* () { + if (input.provider !== undefined && input.provider !== PROVIDER) { + return yield* new ProviderAdapterValidationError({ provider: PROVIDER, - threadId: input.threadId, - detail: `Failed to start Codex adapter session: ${cause instanceof Error ? cause.message : String(cause)}.`, - cause, + operation: "startSession", + issue: `Expected provider '${PROVIDER}' but received '${input.provider}'.`, + }); + } + + const existing = sessions.get(input.threadId); + if (existing && !existing.stopped) { + yield* Effect.suspend(() => stopSessionInternal(existing)); + } + + const codexSettings = yield* serverSettingsService.getSettings.pipe( + Effect.map((settings) => settings.providers.codex), + Effect.mapError( + (error) => + new ProviderAdapterProcessError({ + provider: PROVIDER, + threadId: input.threadId, + detail: error.message, + cause: error, + }), + ), + ); + const runtimeInput: CodexSessionRuntimeOptions = { + threadId: input.threadId, + cwd: input.cwd ?? process.cwd(), + binaryPath: codexSettings.binaryPath, + ...(codexSettings.homePath ? { homePath: codexSettings.homePath } : {}), + ...(Schema.is(CodexResumeCursorSchema)(input.resumeCursor) + ? { resumeCursor: input.resumeCursor } + : {}), + runtimeMode: input.runtimeMode, + ...(input.modelSelection?.provider === "codex" + ? { model: input.modelSelection.model } + : {}), + ...(input.modelSelection?.provider === "codex" && input.modelSelection.options?.fastMode + ? { serviceTier: "fast" } + : {}), + }; + const sessionScope = yield* Scope.make("sequential"); + let sessionScopeTransferred = false; + yield* Effect.addFinalizer(() => + sessionScopeTransferred ? Effect.void : Scope.close(sessionScope, Exit.void), + ); + const createRuntime = options?.makeRuntime ?? makeCodexSessionRuntime; + const runtime = yield* createRuntime(runtimeInput).pipe( + Effect.provideService(Scope.Scope, sessionScope), + Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, childProcessSpawner), + Effect.mapError( + (cause) => + new ProviderAdapterProcessError({ + provider: PROVIDER, + threadId: input.threadId, + detail: cause.message, + cause, + }), + ), + ); + + const eventFiber = yield* Stream.runForEach(runtime.events, (event) => + Effect.gen(function* () { + yield* writeNativeEvent(event); + const runtimeEvents = mapToRuntimeEvents(event, event.threadId); + if (runtimeEvents.length === 0) { + yield* Effect.logDebug("ignoring unhandled Codex provider event", { + method: event.method, + threadId: event.threadId, + turnId: event.turnId, + itemId: event.itemId, + }); + return; + } + yield* Queue.offerAll(runtimeEventQueue, runtimeEvents); }), - }); - }, - ); + ).pipe(Effect.forkChild); + + const started = yield* runtime.start().pipe( + Effect.mapError( + (cause) => + new ProviderAdapterProcessError({ + provider: PROVIDER, + threadId: input.threadId, + detail: cause.message, + cause, + }), + ), + Effect.onError(() => + runtime.close.pipe( + Effect.andThen(Effect.ignore(Scope.close(sessionScope, Exit.void))), + Effect.andThen(Fiber.interrupt(eventFiber)), + Effect.ignore, + ), + ), + ); + + sessions.set(input.threadId, { + threadId: input.threadId, + scope: sessionScope, + runtime, + eventFiber, + stopped: false, + }); + sessionScopeTransferred = true; + + return started; + }), + ); const resolveAttachment = Effect.fn("resolveAttachment")(function* ( input: ProviderSendTurnInput, @@ -1436,11 +1454,11 @@ const makeCodexAdapter = Effect.fn("makeCodexAdapter")(function* ( attachment, }); if (!attachmentPath) { - return yield* toRequestError( - input.threadId, - "turn/start", - new Error(`Invalid attachment id '${attachment.id}'.`), - ); + return yield* new ProviderAdapterRequestError({ + provider: PROVIDER, + method: "turn/start", + detail: `Invalid attachment id '${attachment.id}'.`, + }); } const bytes = yield* fileSystem.readFile(attachmentPath).pipe( Effect.mapError( @@ -1466,48 +1484,55 @@ const makeCodexAdapter = Effect.fn("makeCodexAdapter")(function* ( { concurrency: 1 }, ); - return yield* Effect.tryPromise({ - try: () => { - const managerInput = { - threadId: input.threadId, - ...(input.input !== undefined ? { input: input.input } : {}), - ...(input.modelSelection?.provider === "codex" - ? { model: input.modelSelection.model } - : {}), - ...(input.modelSelection?.provider === "codex" && - input.modelSelection.options?.reasoningEffort !== undefined - ? { effort: input.modelSelection.options.reasoningEffort } - : {}), - ...(input.modelSelection?.provider === "codex" && input.modelSelection.options?.fastMode - ? { serviceTier: "fast" } - : {}), - ...(input.interactionMode !== undefined - ? { interactionMode: input.interactionMode } - : {}), - ...(codexAttachments.length > 0 ? { attachments: codexAttachments } : {}), - }; - return manager.sendTurn(managerInput); - }, - catch: (cause) => toRequestError(input.threadId, "turn/start", cause), - }).pipe( - Effect.map((result) => ({ - ...result, - threadId: input.threadId, - })), - ); + const session = yield* requireSession(input.threadId); + return yield* session.runtime + .sendTurn({ + ...(input.input !== undefined ? { input: input.input } : {}), + ...(input.modelSelection?.provider === "codex" + ? { model: input.modelSelection.model } + : {}), + ...(input.modelSelection?.provider === "codex" && + input.modelSelection.options?.reasoningEffort !== undefined + ? { effort: input.modelSelection.options.reasoningEffort } + : {}), + ...(input.modelSelection?.provider === "codex" && input.modelSelection.options?.fastMode + ? { serviceTier: "fast" } + : {}), + ...(input.interactionMode !== undefined ? { interactionMode: input.interactionMode } : {}), + ...(codexAttachments.length > 0 ? { attachments: codexAttachments } : {}), + }) + .pipe(Effect.mapError((cause) => mapCodexRuntimeError(input.threadId, "turn/start", cause))); + }); + + const requireSession = Effect.fn("requireSession")(function* (threadId: ThreadId) { + const session = sessions.get(threadId); + if (!session || session.stopped) { + return yield* new ProviderAdapterSessionNotFoundError({ + provider: PROVIDER, + threadId, + }); + } + return session; }); const interruptTurn: CodexAdapterShape["interruptTurn"] = (threadId, turnId) => - Effect.tryPromise({ - try: () => manager.interruptTurn(threadId, turnId), - catch: (cause) => toRequestError(threadId, "turn/interrupt", cause), - }); + requireSession(threadId).pipe( + Effect.flatMap((session) => session.runtime.interruptTurn(turnId)), + Effect.mapError((cause) => + cause._tag === "ProviderAdapterSessionNotFoundError" + ? cause + : mapCodexRuntimeError(threadId, "turn/interrupt", cause), + ), + ); const readThread: CodexAdapterShape["readThread"] = (threadId) => - Effect.tryPromise({ - try: () => manager.readThread(threadId), - catch: (cause) => toRequestError(threadId, "thread/read", cause), - }).pipe( + requireSession(threadId).pipe( + Effect.flatMap((session) => session.runtime.readThread), + Effect.mapError((cause) => + cause._tag === "ProviderAdapterSessionNotFoundError" + ? cause + : mapCodexRuntimeError(threadId, "thread/read", cause), + ), Effect.map((snapshot) => ({ threadId, turns: snapshot.turns, @@ -1525,10 +1550,13 @@ const makeCodexAdapter = Effect.fn("makeCodexAdapter")(function* ( ); } - return Effect.tryPromise({ - try: () => manager.rollbackThread(threadId, numTurns), - catch: (cause) => toRequestError(threadId, "thread/rollback", cause), - }).pipe( + return requireSession(threadId).pipe( + Effect.flatMap((session) => session.runtime.rollbackThread(numTurns)), + Effect.mapError((cause) => + cause._tag === "ProviderAdapterSessionNotFoundError" + ? cause + : mapCodexRuntimeError(threadId, "thread/rollback", cause), + ), Effect.map((snapshot) => ({ threadId, turns: snapshot.turns, @@ -1537,38 +1565,28 @@ const makeCodexAdapter = Effect.fn("makeCodexAdapter")(function* ( }; const respondToRequest: CodexAdapterShape["respondToRequest"] = (threadId, requestId, decision) => - Effect.tryPromise({ - try: () => manager.respondToRequest(threadId, requestId, decision), - catch: (cause) => toRequestError(threadId, "item/requestApproval/decision", cause), - }); + requireSession(threadId).pipe( + Effect.flatMap((session) => session.runtime.respondToRequest(requestId, decision)), + Effect.mapError((cause) => + cause._tag === "ProviderAdapterSessionNotFoundError" + ? cause + : mapCodexRuntimeError(threadId, "item/requestApproval/decision", cause), + ), + ); const respondToUserInput: CodexAdapterShape["respondToUserInput"] = ( threadId, requestId, answers, ) => - Effect.tryPromise({ - try: () => manager.respondToUserInput(threadId, requestId, answers), - catch: (cause) => toRequestError(threadId, "item/tool/requestUserInput", cause), - }); - - const stopSession: CodexAdapterShape["stopSession"] = (threadId) => - Effect.sync(() => { - manager.stopSession(threadId); - }); - - const listSessions: CodexAdapterShape["listSessions"] = () => - Effect.sync(() => manager.listSessions()); - - const hasSession: CodexAdapterShape["hasSession"] = (threadId) => - Effect.sync(() => manager.hasSession(threadId)); - - const stopAll: CodexAdapterShape["stopAll"] = () => - Effect.sync(() => { - manager.stopAll(); - }); - - const runtimeEventQueue = yield* Queue.unbounded(); + requireSession(threadId).pipe( + Effect.flatMap((session) => session.runtime.respondToUserInput(requestId, answers)), + Effect.mapError((cause) => + cause._tag === "ProviderAdapterSessionNotFoundError" + ? cause + : mapCodexRuntimeError(threadId, "item/tool/requestUserInput", cause), + ), + ); const writeNativeEvent = Effect.fn("writeNativeEvent")(function* (event: ProviderEvent) { if (!nativeEventLogger) { @@ -1577,38 +1595,51 @@ const makeCodexAdapter = Effect.fn("makeCodexAdapter")(function* ( yield* nativeEventLogger.write(event, event.threadId); }); - const registerListener = Effect.fn("registerListener")(function* () { - const services = yield* Effect.context(); - const listenerEffect = Effect.fn("listener")(function* (event: ProviderEvent) { - yield* writeNativeEvent(event); - const runtimeEvents = mapToRuntimeEvents(event, event.threadId); - if (runtimeEvents.length === 0) { - yield* Effect.logDebug("ignoring unhandled Codex provider event", { - method: event.method, - threadId: event.threadId, - turnId: event.turnId, - itemId: event.itemId, - }); + const stopSessionInternal = Effect.fn("stopSessionInternal")(function* ( + session: CodexAdapterSessionContext, + ) { + if (session.stopped) { + return; + } + session.stopped = true; + sessions.delete(session.threadId); + yield* session.runtime.close.pipe(Effect.ignore); + yield* Effect.ignore(Scope.close(session.scope, Exit.void)); + yield* Fiber.interrupt(session.eventFiber).pipe(Effect.ignore); + }); + + const stopSession: CodexAdapterShape["stopSession"] = (threadId) => + Effect.gen(function* () { + const session = sessions.get(threadId); + if (!session) { return; } - yield* Queue.offerAll(runtimeEventQueue, runtimeEvents); + yield* stopSessionInternal(session); }); - const listener = (event: ProviderEvent) => - listenerEffect(event).pipe(Effect.runPromiseWith(services)); - manager.on("event", listener); - return listener; - }); - const unregisterListener = Effect.fn("unregisterListener")(function* ( - listener: (event: ProviderEvent) => Promise, - ) { - yield* Effect.sync(() => { - manager.off("event", listener); - }); - yield* Queue.shutdown(runtimeEventQueue); - }); + const listSessions: CodexAdapterShape["listSessions"] = () => + Effect.forEach( + Array.from(sessions.values()).filter((session) => !session.stopped), + (session) => session.runtime.getSession, + { concurrency: 1 }, + ); - yield* Effect.acquireRelease(registerListener(), unregisterListener); + const hasSession: CodexAdapterShape["hasSession"] = (threadId) => + Effect.succeed(Boolean(sessions.get(threadId) && !sessions.get(threadId)?.stopped)); + + const stopAll: CodexAdapterShape["stopAll"] = () => + Effect.forEach(Array.from(sessions.values()), stopSessionInternal, { + concurrency: 1, + discard: true, + }).pipe(Effect.asVoid); + + yield* Effect.acquireRelease(Effect.void, () => + stopAll().pipe( + Effect.andThen(Queue.shutdown(runtimeEventQueue)), + Effect.andThen(managedNativeEventLogger?.close() ?? Effect.void), + Effect.ignore, + ), + ); return { provider: PROVIDER, diff --git a/apps/server/src/provider/Layers/CodexProvider.ts b/apps/server/src/provider/Layers/CodexProvider.ts index ab2f962eae..cea768266d 100644 --- a/apps/server/src/provider/Layers/CodexProvider.ts +++ b/apps/server/src/provider/Layers/CodexProvider.ts @@ -1,566 +1,290 @@ -import * as OS from "node:os"; -import type { - ModelCapabilities, - CodexSettings, - ServerProvider, - ServerProviderModel, - ServerProviderAuth, - ServerProviderSkill, - ServerProviderState, -} from "@t3tools/contracts"; import { - Cache, + DateTime, Duration, Effect, Equal, - FileSystem, Layer, Option, - Path, Result, + Schema, Stream, + Types, } from "effect"; -import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process"; +import { ChildProcessSpawner } from "effect/unstable/process"; +import * as CodexClient from "effect-codex-app-server/client"; +import * as CodexSchema from "effect-codex-app-server/schema"; +import * as CodexErrors from "effect-codex-app-server/errors"; -import { - buildServerProvider, - DEFAULT_TIMEOUT_MS, - detailFromResult, - extractAuthBoolean, - isCommandMissingCause, - parseGenericCliVersion, - providerModelsFromSettings, - spawnAndCollect, - type CommandResult, -} from "../providerSnapshot.ts"; -import { makeManagedServerProvider } from "../makeManagedServerProvider.ts"; -import { - formatCodexCliUpgradeMessage, - isCodexCliVersionSupported, - parseCodexCliVersion, -} from "../codexCliVersion.ts"; -import { - adjustCodexModelsForAccount, - codexAuthSubLabel, - codexAuthSubType, - type CodexAccountSnapshot, -} from "../codexAccount.ts"; -import { probeCodexDiscovery } from "../codexAppServer.ts"; -import { CodexProvider } from "../Services/CodexProvider.ts"; -import { expandHomePath } from "../../pathExpansion.ts"; -import { ServerSettingsService } from "../../serverSettings.ts"; +import type { + CodexSettings, + ServerProvider, + ServerProviderState, + ModelCapabilities, + ServerProviderModel, + ServerProviderSkill, +} from "@t3tools/contracts"; import { ServerSettingsError } from "@t3tools/contracts"; -const DEFAULT_CODEX_MODEL_CAPABILITIES: ModelCapabilities = { - reasoningEffortLevels: [ - { value: "xhigh", label: "Extra High" }, - { value: "high", label: "High", isDefault: true }, - { value: "medium", label: "Medium" }, - { value: "low", label: "Low" }, - ], - supportsFastMode: true, - supportsThinkingToggle: false, - contextWindowOptions: [], - promptInjectedEffortLevels: [], -}; +import { makeManagedServerProvider } from "../makeManagedServerProvider.ts"; +import { buildServerProvider } from "../providerSnapshot.ts"; +import { CodexProvider } from "../Services/CodexProvider.ts"; +import { ServerSettingsService } from "../../serverSettings.ts"; +import packageJson from "../../../package.json" with { type: "json" }; const PROVIDER = "codex" as const; -const OPENAI_AUTH_PROVIDERS = new Set(["openai"]); -const BUILT_IN_MODELS: ReadonlyArray = [ - { - slug: "gpt-5.4", - name: "GPT-5.4", - isCustom: false, - capabilities: { - reasoningEffortLevels: [ - { value: "xhigh", label: "Extra High" }, - { value: "high", label: "High", isDefault: true }, - { value: "medium", label: "Medium" }, - { value: "low", label: "Low" }, - ], - supportsFastMode: true, - supportsThinkingToggle: false, - contextWindowOptions: [], - promptInjectedEffortLevels: [], - }, - }, - { - slug: "gpt-5.4-mini", - name: "GPT-5.4 Mini", - isCustom: false, - capabilities: { - reasoningEffortLevels: [ - { value: "xhigh", label: "Extra High" }, - { value: "high", label: "High", isDefault: true }, - { value: "medium", label: "Medium" }, - { value: "low", label: "Low" }, - ], - supportsFastMode: true, - supportsThinkingToggle: false, - contextWindowOptions: [], - promptInjectedEffortLevels: [], - }, - }, - { - slug: "gpt-5.3-codex", - name: "GPT-5.3 Codex", - isCustom: false, - capabilities: { - reasoningEffortLevels: [ - { value: "xhigh", label: "Extra High" }, - { value: "high", label: "High", isDefault: true }, - { value: "medium", label: "Medium" }, - { value: "low", label: "Low" }, - ], - supportsFastMode: true, - supportsThinkingToggle: false, - contextWindowOptions: [], - promptInjectedEffortLevels: [], - }, - }, - { - slug: "gpt-5.3-codex-spark", - name: "GPT-5.3 Codex Spark", - isCustom: false, - capabilities: { - reasoningEffortLevels: [ - { value: "xhigh", label: "Extra High" }, - { value: "high", label: "High", isDefault: true }, - { value: "medium", label: "Medium" }, - { value: "low", label: "Low" }, - ], - supportsFastMode: true, - supportsThinkingToggle: false, - contextWindowOptions: [], - promptInjectedEffortLevels: [], - }, - }, - { - slug: "gpt-5.2-codex", - name: "GPT-5.2 Codex", - isCustom: false, - capabilities: { - reasoningEffortLevels: [ - { value: "xhigh", label: "Extra High" }, - { value: "high", label: "High", isDefault: true }, - { value: "medium", label: "Medium" }, - { value: "low", label: "Low" }, - ], - supportsFastMode: true, - supportsThinkingToggle: false, - contextWindowOptions: [], - promptInjectedEffortLevels: [], - }, - }, - { - slug: "gpt-5.2", - name: "GPT-5.2", - isCustom: false, - capabilities: { - reasoningEffortLevels: [ - { value: "xhigh", label: "Extra High" }, - { value: "high", label: "High", isDefault: true }, - { value: "medium", label: "Medium" }, - { value: "low", label: "Low" }, - ], - supportsFastMode: true, - supportsThinkingToggle: false, - contextWindowOptions: [], - promptInjectedEffortLevels: [], - }, - }, -]; +const PROVIDER_PROBE_TIMEOUT_MS = 8_000; -export function getCodexModelCapabilities(model: string | null | undefined): ModelCapabilities { - const slug = model?.trim(); - return ( - BUILT_IN_MODELS.find((candidate) => candidate.slug === slug)?.capabilities ?? - DEFAULT_CODEX_MODEL_CAPABILITIES - ); +export interface CodexAppServerProviderSnapshot { + readonly account: CodexSchema.V2GetAccountResponse; + readonly version: string | undefined; + readonly models: ReadonlyArray; + readonly skills: ReadonlyArray; } -export function parseAuthStatusFromOutput(result: CommandResult): { - readonly status: Exclude; - readonly auth: Pick; - readonly message?: string; -} { - const lowerOutput = `${result.stdout}\n${result.stderr}`.toLowerCase(); +const REASONING_EFFORT_LABELS: Record = { + none: "None", + minimal: "Minimal", + low: "Low", + medium: "Medium", + high: "High", + xhigh: "Extra High", +}; - if ( - lowerOutput.includes("unknown command") || - lowerOutput.includes("unrecognized command") || - lowerOutput.includes("unexpected argument") - ) { - return { - status: "warning", - auth: { status: "unknown" }, - message: "Codex CLI authentication status command is unavailable in this Codex version.", - }; - } +function codexAccountAuthLabel(account: CodexSchema.V2GetAccountResponse["account"]) { + if (!account) return undefined; + if (account.type === "apiKey") return "OpenAI API Key"; - if ( - lowerOutput.includes("not logged in") || - lowerOutput.includes("login required") || - lowerOutput.includes("authentication required") || - lowerOutput.includes("run `codex login`") || - lowerOutput.includes("run codex login") - ) { - return { - status: "error", - auth: { status: "unauthenticated" }, - message: "Codex CLI is not authenticated. Run `codex login` and try again.", - }; + switch (account.planType) { + case "free": + return "ChatGPT Free Subscription"; + case "go": + return "ChatGPT Go Subscription"; + case "plus": + return "ChatGPT Plus Subscription"; + case "pro": + return "ChatGPT Pro Subscription"; + case "team": + return "ChatGPT Team Subscription"; + case "self_serve_business_usage_based": + case "business": + return "ChatGPT Business Subscription"; + case "enterprise_cbp_usage_based": + case "enterprise": + return "ChatGPT Enterprise Subscription"; + case "edu": + return "ChatGPT Edu Subscription"; + case "unknown": + return "ChatGPT Subscription"; + default: + account.planType satisfies never; + return undefined; } +} - const parsedAuth = (() => { - const trimmed = result.stdout.trim(); - if (!trimmed || (!trimmed.startsWith("{") && !trimmed.startsWith("["))) { - return { attemptedJsonParse: false as const, auth: undefined as boolean | undefined }; - } - try { - return { - attemptedJsonParse: true as const, - auth: extractAuthBoolean(JSON.parse(trimmed)), - }; - } catch { - return { attemptedJsonParse: false as const, auth: undefined as boolean | undefined }; - } - })(); - - if (parsedAuth.auth === true) { - return { status: "ready", auth: { status: "authenticated" } }; - } - if (parsedAuth.auth === false) { - return { - status: "error", - auth: { status: "unauthenticated" }, - message: "Codex CLI is not authenticated. Run `codex login` and try again.", - }; - } - if (parsedAuth.attemptedJsonParse) { - return { - status: "warning", - auth: { status: "unknown" }, - message: - "Could not verify Codex authentication status from JSON output (missing auth marker).", - }; - } - if (result.code === 0) { - return { status: "ready", auth: { status: "authenticated" } }; - } - - const detail = detailFromResult(result); +function mapCodexModelCapabilities( + model: CodexSchema.V2ModelListResponse__Model, +): ModelCapabilities { return { - status: "warning", - auth: { status: "unknown" }, - message: detail - ? `Could not verify Codex authentication status. ${detail}` - : "Could not verify Codex authentication status.", + reasoningEffortLevels: model.supportedReasoningEfforts.map(({ reasoningEffort }) => ({ + value: reasoningEffort, + label: REASONING_EFFORT_LABELS[reasoningEffort], + ...(reasoningEffort === model.defaultReasoningEffort ? { isDefault: true } : {}), + })), + supportsFastMode: (model.additionalSpeedTiers ?? []).includes("fast"), + supportsThinkingToggle: false, + contextWindowOptions: [], + promptInjectedEffortLevels: [], }; } -export const readCodexConfigModelProvider = Effect.fn("readCodexConfigModelProvider")(function* () { - const fileSystem = yield* FileSystem.FileSystem; - const path = yield* Path.Path; - const settingsService = yield* ServerSettingsService; - const codexHome = yield* settingsService.getSettings.pipe( - Effect.map( - (settings) => - settings.providers.codex.homePath || - process.env.CODEX_HOME || - path.join(OS.homedir(), ".codex"), - ), - ); - const configPath = path.join(codexHome, "config.toml"); +const toDisplayName = (model: CodexSchema.V2ModelListResponse__Model): string => { + // Capitalize 'gpt' to 'GPT-' and capitalize any letter following a dash + return model.displayName + .replace(/^gpt/i, "GPT") // Handle start with 'gpt' or 'GPT' + .replace(/-([a-z])/g, (_, c) => "-" + c.toUpperCase()); +}; - const content = yield* fileSystem - .readFileString(configPath) - .pipe(Effect.orElseSucceed(() => undefined)); - if (content === undefined) { - return undefined; +function parseCodexModelListResponse( + response: CodexSchema.V2ModelListResponse, +): ReadonlyArray { + return response.data.map((model) => ({ + slug: model.model, + name: toDisplayName(model), + isCustom: false, + capabilities: mapCodexModelCapabilities(model), + })); +} + +function appendCustomCodexModels( + models: ReadonlyArray, + customModels: ReadonlyArray, +): ReadonlyArray { + if (customModels.length === 0) { + return models; } - let inTopLevel = true; - for (const line of content.split("\n")) { - const trimmed = line.trim(); - if (!trimmed || trimmed.startsWith("#")) continue; - if (trimmed.startsWith("[")) { - inTopLevel = false; + const seen = new Set(models.map((model) => model.slug)); + const fallbackCapabilities = models.find((model) => model.capabilities)?.capabilities ?? null; + const customEntries: ServerProviderModel[] = []; + for (const rawModel of customModels) { + const slug = rawModel.trim(); + if (!slug || seen.has(slug)) { continue; } - if (!inTopLevel) continue; - - const match = trimmed.match(/^model_provider\s*=\s*["']([^"']+)["']/); - if (match) return match[1]; + seen.add(slug); + customEntries.push({ + slug, + name: slug, + isCustom: true, + capabilities: fallbackCapabilities, + }); } - return undefined; + return customEntries.length === 0 ? models : [...models, ...customEntries]; +} + +function parseCodexSkillsListResponse( + response: CodexSchema.V2SkillsListResponse, + cwd: string, +): ReadonlyArray { + const matchingEntry = response.data.find((entry) => entry.cwd === cwd); + const skills = matchingEntry + ? matchingEntry.skills + : response.data.flatMap((entry) => entry.skills); + + return skills.map((skill) => { + const shortDescription = + skill.shortDescription ?? skill.interface?.shortDescription ?? undefined; + + const parsedSkill: Types.Mutable = { + name: skill.name, + path: skill.path, + enabled: skill.enabled, + }; + + if (skill.description) { + parsedSkill.description = skill.description; + } + if (skill.scope) { + parsedSkill.scope = skill.scope; + } + if (skill.interface?.displayName) { + parsedSkill.displayName = skill.interface.displayName; + } + if (shortDescription) { + parsedSkill.shortDescription = shortDescription; + } + + return parsedSkill; + }); +} + +const requestAllCodexModels = Effect.fn("requestAllCodexModels")(function* ( + client: CodexClient.CodexAppServerClientShape, +) { + const models: ServerProviderModel[] = []; + let cursor: string | null | undefined = undefined; + + do { + const response: CodexSchema.V2ModelListResponse = yield* client.request( + "model/list", + cursor ? { cursor } : {}, + ); + models.push(...parseCodexModelListResponse(response)); + cursor = response.nextCursor; + } while (cursor); + + return models; }); -export const hasCustomModelProvider = readCodexConfigModelProvider().pipe( - Effect.map((provider) => provider !== undefined && !OPENAI_AUTH_PROVIDERS.has(provider)), - Effect.orElseSucceed(() => false), -); +export function buildCodexInitializeParams(): CodexSchema.V1InitializeParams { + return { + clientInfo: { + name: "t3code_desktop", + title: "T3 Code Desktop", + version: packageJson.version, + }, + capabilities: { + experimentalApi: true, + }, + }; +} -const CAPABILITIES_PROBE_TIMEOUT_MS = 8_000; - -const probeCodexCapabilities = (input: { +const probeCodexAppServerProvider = Effect.fn("probeCodexAppServerProvider")(function* (input: { readonly binaryPath: string; readonly homePath?: string; readonly cwd: string; -}) => - Effect.tryPromise((signal) => probeCodexDiscovery({ ...input, signal })).pipe( - Effect.timeoutOption(CAPABILITIES_PROBE_TIMEOUT_MS), - Effect.result, - Effect.map((result) => { - if (Result.isFailure(result)) return undefined; - return Option.isSome(result.success) ? result.success.value : undefined; + readonly customModels?: ReadonlyArray; +}) { + const clientContext = yield* Layer.build( + CodexClient.layerCommand({ + command: input.binaryPath, + args: ["app-server"], + cwd: input.cwd, + ...(input.homePath ? { env: { CODEX_HOME: input.homePath } } : {}), }), ); - -const runCodexCommand = Effect.fn("runCodexCommand")(function* (args: ReadonlyArray) { - const settingsService = yield* ServerSettingsService; - const codexSettings = yield* settingsService.getSettings.pipe( - Effect.map((settings) => settings.providers.codex), + const client = yield* Effect.service(CodexClient.CodexAppServerClient).pipe( + Effect.provide(clientContext), ); - const command = ChildProcess.make(codexSettings.binaryPath, [...args], { - shell: process.platform === "win32", - env: { - ...process.env, - ...(codexSettings.homePath ? { CODEX_HOME: expandHomePath(codexSettings.homePath) } : {}), + + const initialize = yield* client.request("initialize", { + clientInfo: { + name: "t3code_desktop", + title: "T3 Code Desktop", + version: "0.1.0", + }, + capabilities: { + experimentalApi: true, }, }); - return yield* spawnAndCollect(codexSettings.binaryPath, command); -}); + yield* client.notify("initialized", undefined); -export const checkCodexProviderStatus = Effect.fn("checkCodexProviderStatus")(function* ( - resolveAccount?: (input: { - readonly binaryPath: string; - readonly homePath?: string; - }) => Effect.Effect, - resolveSkills?: (input: { - readonly binaryPath: string; - readonly homePath?: string; - readonly cwd: string; - }) => Effect.Effect | undefined>, -): Effect.fn.Return< - ServerProvider, - ServerSettingsError, - | ChildProcessSpawner.ChildProcessSpawner - | FileSystem.FileSystem - | Path.Path - | ServerSettingsService -> { - const codexSettings = yield* Effect.service(ServerSettingsService).pipe( - Effect.flatMap((service) => service.getSettings), - Effect.map((settings) => settings.providers.codex), - ); - const checkedAt = new Date().toISOString(); - const models = providerModelsFromSettings( - BUILT_IN_MODELS, - PROVIDER, - codexSettings.customModels, - DEFAULT_CODEX_MODEL_CAPABILITIES, + // Extract the version string after the first '/' in userAgent, up to the next space or the end + const versionMatch = initialize.userAgent.match(/\/([^\s]+)/); + const version = versionMatch ? versionMatch[1] : undefined; + + const accountResponse = yield* client.request("account/read", {}); + if (!accountResponse.account && accountResponse.requiresOpenaiAuth) { + return { + account: accountResponse, + version, + models: appendCustomCodexModels([], input.customModels ?? []), + skills: [], + } satisfies CodexAppServerProviderSnapshot; + } + + const [skillsResponse, models] = yield* Effect.all( + [ + client.request("skills/list", { + cwds: [input.cwd], + }), + requestAllCodexModels(client), + ], + { concurrency: "unbounded" }, ); - if (!codexSettings.enabled) { - return buildServerProvider({ - provider: PROVIDER, - enabled: false, - checkedAt, - models, - probe: { - installed: false, - version: null, - status: "warning", - auth: { status: "unknown" }, - message: "Codex is disabled in T3 Code settings.", - }, - }); - } + return { + account: accountResponse, + version, + models: appendCustomCodexModels(models, input.customModels ?? []), + skills: parseCodexSkillsListResponse(skillsResponse, input.cwd), + } satisfies CodexAppServerProviderSnapshot; +}, Effect.scoped); - const versionProbe = yield* runCodexCommand(["--version"]).pipe( - Effect.timeoutOption(DEFAULT_TIMEOUT_MS), - Effect.result, - ); - - if (Result.isFailure(versionProbe)) { - const error = versionProbe.failure; - return buildServerProvider({ - provider: PROVIDER, - enabled: codexSettings.enabled, - checkedAt, - models, - probe: { - installed: !isCommandMissingCause(error), - version: null, - status: "error", - auth: { status: "unknown" }, - message: isCommandMissingCause(error) - ? "Codex CLI (`codex`) is not installed or not on PATH." - : `Failed to execute Codex CLI health check: ${error.message}.`, - }, - }); - } - - if (Option.isNone(versionProbe.success)) { - return buildServerProvider({ - provider: PROVIDER, - enabled: codexSettings.enabled, - checkedAt, - models, - probe: { - installed: true, - version: null, - status: "error", - auth: { status: "unknown" }, - message: "Codex CLI is installed but failed to run. Timed out while running command.", - }, - }); - } - - const version = versionProbe.success.value; - const parsedVersion = - parseCodexCliVersion(`${version.stdout}\n${version.stderr}`) ?? - parseGenericCliVersion(`${version.stdout}\n${version.stderr}`); - if (version.code !== 0) { - const detail = detailFromResult(version); - return buildServerProvider({ - provider: PROVIDER, - enabled: codexSettings.enabled, - checkedAt, - models, - probe: { - installed: true, - version: parsedVersion, - status: "error", - auth: { status: "unknown" }, - message: detail - ? `Codex CLI is installed but failed to run. ${detail}` - : "Codex CLI is installed but failed to run.", - }, - }); - } - - if (parsedVersion && !isCodexCliVersionSupported(parsedVersion)) { - return buildServerProvider({ - provider: PROVIDER, - enabled: codexSettings.enabled, - checkedAt, - models, - probe: { - installed: true, - version: parsedVersion, - status: "error", - auth: { status: "unknown" }, - message: formatCodexCliUpgradeMessage(parsedVersion), - }, - }); - } - - const skills = - (resolveSkills - ? yield* resolveSkills({ - binaryPath: codexSettings.binaryPath, - homePath: codexSettings.homePath, - cwd: process.cwd(), - }).pipe(Effect.orElseSucceed(() => undefined)) - : undefined) ?? []; - - if (yield* hasCustomModelProvider) { - return buildServerProvider({ - provider: PROVIDER, - enabled: codexSettings.enabled, - checkedAt, - models, - skills, - probe: { - installed: true, - version: parsedVersion, - status: "ready", - auth: { status: "unknown" }, - message: "Using a custom Codex model provider; OpenAI login check skipped.", - }, - }); - } - - const authProbe = yield* runCodexCommand(["login", "status"]).pipe( - Effect.timeoutOption(DEFAULT_TIMEOUT_MS), - Effect.result, - ); - const account = resolveAccount - ? yield* resolveAccount({ - binaryPath: codexSettings.binaryPath, - homePath: codexSettings.homePath, - }) - : undefined; - const resolvedModels = adjustCodexModelsForAccount(models, account); - - if (Result.isFailure(authProbe)) { - const error = authProbe.failure; - return buildServerProvider({ - provider: PROVIDER, - enabled: codexSettings.enabled, - checkedAt, - models: resolvedModels, - skills, - probe: { - installed: true, - version: parsedVersion, - status: "warning", - auth: { status: "unknown" }, - message: `Could not verify Codex authentication status: ${error.message}.`, - }, - }); - } - - if (Option.isNone(authProbe.success)) { - return buildServerProvider({ - provider: PROVIDER, - enabled: codexSettings.enabled, - checkedAt, - models: resolvedModels, - skills, - probe: { - installed: true, - version: parsedVersion, - status: "warning", - auth: { status: "unknown" }, - message: "Could not verify Codex authentication status. Timed out while running command.", - }, - }); - } - - const parsed = parseAuthStatusFromOutput(authProbe.success.value); - const authType = codexAuthSubType(account); - const authLabel = codexAuthSubLabel(account); - return buildServerProvider({ - provider: PROVIDER, - enabled: codexSettings.enabled, - checkedAt, - models: resolvedModels, - skills, - probe: { - installed: true, - version: parsedVersion, - status: parsed.status, - auth: { - ...parsed.auth, - ...(authType ? { type: authType } : {}), - ...(authLabel ? { label: authLabel } : {}), - }, - ...(parsed.message ? { message: parsed.message } : {}), - }, - }); -}); +const emptyCodexModelsFromSettings = (codexSettings: CodexSettings): ServerProvider["models"] => + codexSettings.customModels + .map((model) => model.trim()) + .filter((model, index, models) => model.length > 0 && models.indexOf(model) === index) + .map((model) => ({ + slug: model, + name: model, + isCustom: true, + capabilities: null, + })); const makePendingCodexProvider = (codexSettings: CodexSettings): ServerProvider => { const checkedAt = new Date().toISOString(); - const models = providerModelsFromSettings( - BUILT_IN_MODELS, - PROVIDER, - codexSettings.customModels, - DEFAULT_CODEX_MODEL_CAPABILITIES, - ); + const models = emptyCodexModelsFromSettings(codexSettings); if (!codexSettings.enabled) { return buildServerProvider({ @@ -568,6 +292,7 @@ const makePendingCodexProvider = (codexSettings: CodexSettings): ServerProvider enabled: false, checkedAt, models, + skills: [], probe: { installed: false, version: null, @@ -583,6 +308,7 @@ const makePendingCodexProvider = (codexSettings: CodexSettings): ServerProvider enabled: true, checkedAt, models, + skills: [], probe: { installed: false, version: null, @@ -593,44 +319,144 @@ const makePendingCodexProvider = (codexSettings: CodexSettings): ServerProvider }); }; +function accountProbeStatus(account: CodexAppServerProviderSnapshot["account"]): { + readonly status: Exclude; + readonly auth: ServerProvider["auth"]; + readonly message?: string; +} { + const authLabel = codexAccountAuthLabel(account.account); + const auth = { + status: account.account ? ("authenticated" as const) : ("unknown" as const), + ...(account.account?.type ? { type: account.account?.type } : {}), + ...(authLabel ? { label: authLabel } : {}), + } satisfies ServerProvider["auth"]; + + if (account.account) { + return { status: "ready", auth }; + } + + if (account.requiresOpenaiAuth) { + return { + status: "error", + auth: { status: "unauthenticated" }, + message: "Codex CLI is not authenticated. Run `codex login` and try again.", + }; + } + + return { status: "ready", auth }; +} + +export const checkCodexProviderStatus = Effect.fn("checkCodexProviderStatus")(function* ( + probe: (input: { + readonly binaryPath: string; + readonly homePath?: string; + readonly cwd: string; + readonly customModels: ReadonlyArray; + }) => Effect.Effect< + CodexAppServerProviderSnapshot, + CodexErrors.CodexAppServerError, + ChildProcessSpawner.ChildProcessSpawner + > = probeCodexAppServerProvider, +): Effect.fn.Return< + ServerProvider, + ServerSettingsError, + ServerSettingsService | ChildProcessSpawner.ChildProcessSpawner +> { + const codexSettings = yield* Effect.service(ServerSettingsService).pipe( + Effect.flatMap((service) => service.getSettings), + Effect.map((settings) => settings.providers.codex), + ); + const checkedAt = DateTime.formatIso(yield* DateTime.now); + const emptyModels = emptyCodexModelsFromSettings(codexSettings); + + if (!codexSettings.enabled) { + return buildServerProvider({ + provider: PROVIDER, + enabled: false, + checkedAt, + models: emptyModels, + skills: [], + probe: { + installed: false, + version: null, + status: "warning", + auth: { status: "unknown" }, + message: "Codex is disabled in T3 Code settings.", + }, + }); + } + + const probeResult = yield* probe({ + binaryPath: codexSettings.binaryPath, + homePath: codexSettings.homePath, + cwd: process.cwd(), + customModels: codexSettings.customModels, + }).pipe(Effect.timeoutOption(Duration.millis(PROVIDER_PROBE_TIMEOUT_MS)), Effect.result); + + if (Result.isFailure(probeResult)) { + const error = probeResult.failure; + const installed = !Schema.is(CodexErrors.CodexAppServerSpawnError)(error); + return buildServerProvider({ + provider: PROVIDER, + enabled: codexSettings.enabled, + checkedAt, + models: emptyModels, + skills: [], + probe: { + installed, + version: null, + status: "error", + auth: { status: "unknown" }, + message: installed + ? `Codex app-server provider probe failed: ${error.message}.` + : "Codex CLI (`codex`) is not installed or not on PATH.", + }, + }); + } + + if (Option.isNone(probeResult.success)) { + return buildServerProvider({ + provider: PROVIDER, + enabled: codexSettings.enabled, + checkedAt, + models: emptyModels, + skills: [], + probe: { + installed: true, + version: null, + status: "error", + auth: { status: "unknown" }, + message: "Timed out while checking Codex app-server provider status.", + }, + }); + } + + const snapshot = probeResult.success.value; + const accountStatus = accountProbeStatus(snapshot.account); + + return buildServerProvider({ + provider: PROVIDER, + enabled: codexSettings.enabled, + checkedAt, + models: snapshot.models, + skills: snapshot.skills, + probe: { + installed: true, + version: snapshot.version ?? null, + status: accountStatus.status, + auth: accountStatus.auth, + ...(accountStatus.message ? { message: accountStatus.message } : {}), + }, + }); +}); + export const CodexProviderLive = Layer.effect( CodexProvider, Effect.gen(function* () { const serverSettings = yield* ServerSettingsService; - const fileSystem = yield* FileSystem.FileSystem; - const path = yield* Path.Path; const spawner = yield* ChildProcessSpawner.ChildProcessSpawner; - const accountProbeCache = yield* Cache.make({ - capacity: 4, - timeToLive: Duration.minutes(5), - lookup: (key: string) => { - const [binaryPath, homePath, cwd] = JSON.parse(key) as [string, string | undefined, string]; - return probeCodexCapabilities({ - binaryPath, - cwd, - ...(homePath ? { homePath } : {}), - }); - }, - }); - - const getDiscovery = (input: { - readonly binaryPath: string; - readonly homePath?: string; - readonly cwd: string; - }) => - Cache.get(accountProbeCache, JSON.stringify([input.binaryPath, input.homePath, input.cwd])); - - const checkProvider = checkCodexProviderStatus( - (input) => - getDiscovery({ - ...input, - cwd: process.cwd(), - }).pipe(Effect.map((discovery) => discovery?.account)), - (input) => getDiscovery(input).pipe(Effect.map((discovery) => discovery?.skills)), - ).pipe( + const checkProvider = checkCodexProviderStatus().pipe( Effect.provideService(ServerSettingsService, serverSettings), - Effect.provideService(FileSystem.FileSystem, fileSystem), - Effect.provideService(Path.Path, path), Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner), ); @@ -645,6 +471,7 @@ export const CodexProviderLive = Layer.effect( haveSettingsChanged: (previous, next) => !Equal.equals(previous, next), initialSnapshot: makePendingCodexProvider, checkProvider, + refreshInterval: Duration.minutes(5), }); }), ); diff --git a/apps/server/src/provider/Layers/CodexSessionRuntime.test.ts b/apps/server/src/provider/Layers/CodexSessionRuntime.test.ts new file mode 100644 index 0000000000..780f9731fd --- /dev/null +++ b/apps/server/src/provider/Layers/CodexSessionRuntime.test.ts @@ -0,0 +1,275 @@ +import assert from "node:assert/strict"; + +import { Effect, Schema } from "effect"; +import { describe, it } from "vitest"; +import { ThreadId } from "@t3tools/contracts"; +import * as CodexErrors from "effect-codex-app-server/errors"; +import * as CodexRpc from "effect-codex-app-server/rpc"; + +import { + CODEX_DEFAULT_MODE_DEVELOPER_INSTRUCTIONS, + CODEX_PLAN_MODE_DEVELOPER_INSTRUCTIONS, +} from "../CodexDeveloperInstructions.ts"; +import { + buildTurnStartParams, + isRecoverableThreadResumeError, + openCodexThread, +} from "./CodexSessionRuntime.ts"; + +function makeThreadOpenResponse( + threadId: string, +): CodexRpc.ClientRequestResponsesByMethod["thread/start"] { + return { + cwd: "/tmp/project", + model: "gpt-5.3-codex", + modelProvider: "openai", + approvalPolicy: "never", + approvalsReviewer: "user", + sandbox: { type: "danger-full-access" }, + thread: { + id: threadId, + createdAt: "2026-04-18T00:00:00.000Z", + source: { session: "cli" }, + turns: [], + status: { + state: "idle", + activeFlags: [], + }, + }, + } as unknown as CodexRpc.ClientRequestResponsesByMethod["thread/start"]; +} + +describe("buildTurnStartParams", () => { + it("includes plan collaboration mode when requested", () => { + const params = Effect.runSync( + buildTurnStartParams({ + threadId: "provider-thread-1", + runtimeMode: "full-access", + prompt: "Make a plan", + model: "gpt-5.3-codex", + effort: "medium", + interactionMode: "plan", + }), + ); + + assert.deepStrictEqual(params, { + threadId: "provider-thread-1", + approvalPolicy: "never", + sandboxPolicy: { + type: "dangerFullAccess", + }, + input: [ + { + type: "text", + text: "Make a plan", + }, + ], + model: "gpt-5.3-codex", + effort: "medium", + collaborationMode: { + mode: "plan", + settings: { + model: "gpt-5.3-codex", + reasoning_effort: "medium", + developer_instructions: CODEX_PLAN_MODE_DEVELOPER_INSTRUCTIONS, + }, + }, + }); + }); + + it("includes default collaboration mode and image attachments", () => { + const params = Effect.runSync( + buildTurnStartParams({ + threadId: "provider-thread-1", + runtimeMode: "auto-accept-edits", + prompt: "Implement it", + model: "gpt-5.3-codex", + interactionMode: "default", + attachments: [ + { + type: "image", + url: "data:image/png;base64,abc", + }, + ], + }), + ); + + assert.deepStrictEqual(params, { + threadId: "provider-thread-1", + approvalPolicy: "on-request", + sandboxPolicy: { + type: "workspaceWrite", + }, + input: [ + { + type: "text", + text: "Implement it", + }, + { + type: "image", + url: "data:image/png;base64,abc", + }, + ], + 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("omits collaboration mode when interaction mode is absent", () => { + const params = Effect.runSync( + buildTurnStartParams({ + threadId: "provider-thread-1", + runtimeMode: "approval-required", + prompt: "Review", + }), + ); + + assert.deepStrictEqual(params, { + threadId: "provider-thread-1", + approvalPolicy: "untrusted", + sandboxPolicy: { + type: "readOnly", + }, + input: [ + { + type: "text", + text: "Review", + }, + ], + }); + }); +}); + +describe("isRecoverableThreadResumeError", () => { + it("matches missing thread errors", () => { + assert.equal( + isRecoverableThreadResumeError( + new CodexErrors.CodexAppServerRequestError({ + code: -32603, + errorMessage: "Thread does not exist", + }), + ), + true, + ); + }); + + it("ignores non-recoverable resume errors", () => { + assert.equal( + isRecoverableThreadResumeError( + new CodexErrors.CodexAppServerRequestError({ + code: -32603, + errorMessage: "Permission denied", + }), + ), + false, + ); + }); + + it("ignores unrelated missing-resource errors that do not mention threads", () => { + assert.equal( + isRecoverableThreadResumeError( + new CodexErrors.CodexAppServerRequestError({ + code: -32603, + errorMessage: "Config file not found", + }), + ), + false, + ); + assert.equal( + isRecoverableThreadResumeError( + new CodexErrors.CodexAppServerRequestError({ + code: -32603, + errorMessage: "Model does not exist", + }), + ), + false, + ); + }); +}); + +describe("openCodexThread", () => { + it("falls back to thread/start when resume fails recoverably", async () => { + const calls: Array<{ method: "thread/start" | "thread/resume"; payload: unknown }> = []; + const started = makeThreadOpenResponse("fresh-thread"); + const client = { + request: ( + method: M, + payload: CodexRpc.ClientRequestParamsByMethod[M], + ) => { + calls.push({ method, payload }); + if (method === "thread/resume") { + return Effect.fail( + new CodexErrors.CodexAppServerRequestError({ + code: -32603, + errorMessage: "thread not found", + }), + ); + } + return Effect.succeed(started as CodexRpc.ClientRequestResponsesByMethod[M]); + }, + }; + + const opened = await Effect.runPromise( + openCodexThread({ + client, + threadId: ThreadId.make("thread-1"), + runtimeMode: "full-access", + cwd: "/tmp/project", + requestedModel: "gpt-5.3-codex", + serviceTier: undefined, + resumeThreadId: "stale-thread", + }), + ); + + assert.equal(opened.thread.id, "fresh-thread"); + assert.deepStrictEqual( + calls.map((call) => call.method), + ["thread/resume", "thread/start"], + ); + }); + + it("propagates non-recoverable resume failures", async () => { + const client = { + request: ( + method: M, + _payload: CodexRpc.ClientRequestParamsByMethod[M], + ) => { + if (method === "thread/resume") { + return Effect.fail( + new CodexErrors.CodexAppServerRequestError({ + code: -32603, + errorMessage: "timed out waiting for server", + }), + ); + } + return Effect.succeed( + makeThreadOpenResponse("fresh-thread") as CodexRpc.ClientRequestResponsesByMethod[M], + ); + }, + }; + + await assert.rejects( + Effect.runPromise( + openCodexThread({ + client, + threadId: ThreadId.make("thread-1"), + runtimeMode: "full-access", + cwd: "/tmp/project", + requestedModel: "gpt-5.3-codex", + serviceTier: undefined, + resumeThreadId: "stale-thread", + }), + ), + (error: unknown) => + Schema.is(CodexErrors.CodexAppServerRequestError)(error) && + error.errorMessage === "timed out waiting for server", + ); + }); +}); diff --git a/apps/server/src/provider/Layers/CodexSessionRuntime.ts b/apps/server/src/provider/Layers/CodexSessionRuntime.ts new file mode 100644 index 0000000000..29b22e16f8 --- /dev/null +++ b/apps/server/src/provider/Layers/CodexSessionRuntime.ts @@ -0,0 +1,1325 @@ +import { randomUUID } from "node:crypto"; + +import { + ApprovalRequestId, + DEFAULT_MODEL_BY_PROVIDER, + EventId, + ProviderItemId, + type ProviderApprovalDecision, + type ProviderEvent, + type ProviderInteractionMode, + type ProviderRequestKind, + type ProviderSession, + type ProviderTurnStartResult, + type ProviderUserInputAnswers, + RuntimeMode, + ThreadId, + TurnId, +} from "@t3tools/contracts"; +import { normalizeModelSlug } from "@t3tools/shared/model"; +import { Deferred, Effect, Exit, Layer, Queue, Ref, Scope, Schema, Stream } from "effect"; +import * as SchemaIssue from "effect/SchemaIssue"; +import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process"; +import * as CodexClient from "effect-codex-app-server/client"; +import * as CodexErrors from "effect-codex-app-server/errors"; +import * as CodexRpc from "effect-codex-app-server/rpc"; +import * as EffectCodexSchema from "effect-codex-app-server/schema"; + +import { buildCodexInitializeParams } from "./CodexProvider.ts"; +import { + CODEX_DEFAULT_MODE_DEVELOPER_INSTRUCTIONS, + CODEX_PLAN_MODE_DEVELOPER_INSTRUCTIONS, +} from "../CodexDeveloperInstructions.ts"; + +const PROVIDER = "codex" as const; + +const ANSI_ESCAPE_CHAR = String.fromCharCode(27); +const ANSI_ESCAPE_REGEX = new RegExp(`${ANSI_ESCAPE_CHAR}\\[[0-9;]*m`, "g"); +const CODEX_STDERR_LOG_REGEX = + /^\d{4}-\d{2}-\d{2}T\S+\s+(TRACE|DEBUG|INFO|WARN|ERROR)\s+\S+:\s+(.*)$/; +const BENIGN_ERROR_LOG_SNIPPETS = [ + "state db missing rollout path for thread", + "state db record_discrepancy: find_thread_path_by_id_str_in_subdir, falling_back", +]; +const RECOVERABLE_THREAD_RESUME_ERROR_SNIPPETS = [ + "not found", + "missing thread", + "no such thread", + "unknown thread", + "does not exist", +]; + +export const CodexResumeCursorSchema = Schema.Struct({ + threadId: Schema.String, +}); +const CodexUserInputAnswerObject = Schema.Struct({ + answers: Schema.Array(Schema.String), +}); + +// TODO: Verify `packages/effect-codex-app-server/scripts/generate.ts` so the generated +// `V2TurnStartParams` schema includes `collaborationMode` directly. +const CodexTurnStartParamsWithCollaborationMode = EffectCodexSchema.V2TurnStartParams.pipe( + Schema.fieldsAssign({ + collaborationMode: Schema.optionalKey(EffectCodexSchema.V2TurnStartParams__CollaborationMode), + }), +); + +export type CodexTurnStartParamsWithCollaborationMode = + typeof CodexTurnStartParamsWithCollaborationMode.Type; +const formatSchemaIssue = SchemaIssue.makeFormatterDefault(); + +export type CodexResumeCursor = typeof CodexResumeCursorSchema.Type; +type CodexThreadItem = + | EffectCodexSchema.V2ThreadReadResponse["thread"]["turns"][number]["items"][number] + | EffectCodexSchema.V2ThreadRollbackResponse["thread"]["turns"][number]["items"][number]; + +export interface CodexSessionRuntimeOptions { + readonly threadId: ThreadId; + readonly binaryPath: string; + readonly homePath?: string; + readonly cwd: string; + readonly runtimeMode: RuntimeMode; + readonly model?: string; + readonly serviceTier?: EffectCodexSchema.V2ThreadStartParams__ServiceTier | undefined; + readonly resumeCursor?: CodexResumeCursor; +} + +export interface CodexSessionRuntimeSendTurnInput { + readonly input?: string; + readonly attachments?: ReadonlyArray<{ readonly type: "image"; readonly url: string }>; + readonly model?: string; + readonly serviceTier?: EffectCodexSchema.V2TurnStartParams__ServiceTier | undefined; + readonly effort?: EffectCodexSchema.V2TurnStartParams__ReasoningEffort | undefined; + readonly interactionMode?: ProviderInteractionMode; +} + +export interface CodexThreadTurnSnapshot { + readonly id: TurnId; + readonly items: ReadonlyArray; +} + +export interface CodexThreadSnapshot { + readonly threadId: string; + readonly turns: ReadonlyArray; +} + +export interface CodexSessionRuntimeShape { + readonly start: () => Effect.Effect; + readonly getSession: Effect.Effect; + readonly sendTurn: ( + input: CodexSessionRuntimeSendTurnInput, + ) => Effect.Effect; + readonly interruptTurn: (turnId?: TurnId) => Effect.Effect; + readonly readThread: Effect.Effect; + readonly rollbackThread: ( + numTurns: number, + ) => Effect.Effect; + readonly respondToRequest: ( + requestId: ApprovalRequestId, + decision: ProviderApprovalDecision, + ) => Effect.Effect; + readonly respondToUserInput: ( + requestId: ApprovalRequestId, + answers: ProviderUserInputAnswers, + ) => Effect.Effect; + readonly events: Stream.Stream; + readonly close: Effect.Effect; +} + +export type CodexSessionRuntimeError = + | CodexErrors.CodexAppServerError + | CodexSessionRuntimePendingApprovalNotFoundError + | CodexSessionRuntimePendingUserInputNotFoundError + | CodexSessionRuntimeInvalidUserInputAnswersError + | CodexSessionRuntimeThreadIdMissingError; + +export class CodexSessionRuntimePendingApprovalNotFoundError extends Schema.TaggedErrorClass()( + "CodexSessionRuntimePendingApprovalNotFoundError", + { + requestId: Schema.String, + }, +) { + override get message(): string { + return `Unknown pending Codex approval request: ${this.requestId}`; + } +} + +export class CodexSessionRuntimePendingUserInputNotFoundError extends Schema.TaggedErrorClass()( + "CodexSessionRuntimePendingUserInputNotFoundError", + { + requestId: Schema.String, + }, +) { + override get message(): string { + return `Unknown pending Codex user input request: ${this.requestId}`; + } +} + +export class CodexSessionRuntimeInvalidUserInputAnswersError extends Schema.TaggedErrorClass()( + "CodexSessionRuntimeInvalidUserInputAnswersError", + { + questionId: Schema.String, + }, +) { + override get message(): string { + return `Invalid Codex user input answers for question '${this.questionId}'`; + } +} + +export class CodexSessionRuntimeThreadIdMissingError extends Schema.TaggedErrorClass()( + "CodexSessionRuntimeThreadIdMissingError", + { + threadId: Schema.String, + }, +) { + override get message(): string { + return `Codex session is missing a provider thread id for ${this.threadId}`; + } +} + +interface PendingApproval { + readonly requestId: ApprovalRequestId; + readonly jsonRpcId: string; + readonly requestKind: ProviderRequestKind; + readonly turnId: TurnId | undefined; + readonly itemId: ProviderItemId | undefined; + readonly decision: Deferred.Deferred; +} + +interface ApprovalCorrelation { + readonly requestId: ApprovalRequestId; + readonly requestKind: ProviderRequestKind; + readonly turnId: TurnId | undefined; + readonly itemId: ProviderItemId | undefined; +} + +interface PendingUserInput { + readonly requestId: ApprovalRequestId; + readonly turnId: TurnId | undefined; + readonly itemId: ProviderItemId | undefined; + readonly answers: Deferred.Deferred; +} + +type CodexServerNotification = { + readonly [M in CodexRpc.ServerNotificationMethod]: { + readonly method: M; + readonly params: CodexRpc.ServerNotificationParamsByMethod[M]; + }; +}[CodexRpc.ServerNotificationMethod]; + +function makeCodexServerNotification( + method: M, + params: CodexRpc.ServerNotificationParamsByMethod[M], +): CodexServerNotification { + return { method, params } as CodexServerNotification; +} + +function normalizeCodexModelSlug( + model: string | undefined | null, + preferredId?: string, +): string | undefined { + const normalized = normalizeModelSlug(model); + if (!normalized) { + return undefined; + } + if (preferredId?.endsWith("-codex") && preferredId !== normalized) { + return preferredId; + } + return normalized; +} + +function readResumeCursorThreadId( + resumeCursor: ProviderSession["resumeCursor"], +): string | undefined { + return Schema.is(CodexResumeCursorSchema)(resumeCursor) ? resumeCursor.threadId : undefined; +} + +function runtimeModeToThreadConfig(input: RuntimeMode): { + readonly approvalPolicy: EffectCodexSchema.V2ThreadStartParams__AskForApproval; + readonly sandbox: EffectCodexSchema.V2ThreadStartParams__SandboxMode; +} { + switch (input) { + case "approval-required": + return { + approvalPolicy: "untrusted", + sandbox: "read-only", + }; + case "auto-accept-edits": + return { + approvalPolicy: "on-request", + sandbox: "workspace-write", + }; + case "full-access": + default: + return { + approvalPolicy: "never", + sandbox: "danger-full-access", + }; + } +} + +function buildThreadStartParams(input: { + readonly cwd: string; + readonly runtimeMode: RuntimeMode; + readonly model: string | undefined; + readonly serviceTier: EffectCodexSchema.V2ThreadStartParams__ServiceTier | undefined; +}): EffectCodexSchema.V2ThreadStartParams { + const config = runtimeModeToThreadConfig(input.runtimeMode); + return { + cwd: input.cwd, + approvalPolicy: config.approvalPolicy, + sandbox: config.sandbox, + ...(input.model ? { model: input.model } : {}), + ...(input.serviceTier ? { serviceTier: input.serviceTier } : {}), + }; +} + +function runtimeModeToTurnSandboxPolicy( + input: RuntimeMode, +): EffectCodexSchema.V2TurnStartParams__SandboxPolicy { + switch (input) { + case "approval-required": + return { + type: "readOnly", + }; + case "auto-accept-edits": + return { + type: "workspaceWrite", + }; + case "full-access": + default: + return { + type: "dangerFullAccess", + }; + } +} + +function buildCodexCollaborationMode(input: { + readonly interactionMode?: ProviderInteractionMode; + readonly model?: string; + readonly effort?: EffectCodexSchema.V2TurnStartParams__ReasoningEffort; +}): EffectCodexSchema.V2TurnStartParams__CollaborationMode | undefined { + if (input.interactionMode === undefined) { + return undefined; + } + const model = normalizeCodexModelSlug(input.model) ?? DEFAULT_MODEL_BY_PROVIDER.codex; + return { + mode: input.interactionMode, + settings: { + model, + reasoning_effort: input.effort ?? "medium", + developer_instructions: + input.interactionMode === "plan" + ? CODEX_PLAN_MODE_DEVELOPER_INSTRUCTIONS + : CODEX_DEFAULT_MODE_DEVELOPER_INSTRUCTIONS, + }, + }; +} + +export function buildTurnStartParams(input: { + readonly threadId: string; + readonly runtimeMode: RuntimeMode; + readonly prompt?: string; + readonly attachments?: ReadonlyArray<{ readonly type: "image"; readonly url: string }>; + readonly model?: string; + readonly serviceTier?: EffectCodexSchema.V2TurnStartParams__ServiceTier; + readonly effort?: EffectCodexSchema.V2TurnStartParams__ReasoningEffort; + readonly interactionMode?: ProviderInteractionMode; +}): Effect.Effect< + CodexTurnStartParamsWithCollaborationMode, + CodexErrors.CodexAppServerProtocolParseError +> { + const turnInput: Array = []; + if (input.prompt) { + turnInput.push({ + type: "text", + text: input.prompt, + }); + } + for (const attachment of input.attachments ?? []) { + turnInput.push(attachment); + } + + const config = runtimeModeToThreadConfig(input.runtimeMode); + const collaborationMode = buildCodexCollaborationMode({ + ...(input.interactionMode ? { interactionMode: input.interactionMode } : {}), + ...(input.model ? { model: input.model } : {}), + ...(input.effort ? { effort: input.effort } : {}), + }); + + return Schema.decodeUnknownEffect(CodexTurnStartParamsWithCollaborationMode)({ + threadId: input.threadId, + input: turnInput, + approvalPolicy: config.approvalPolicy, + sandboxPolicy: runtimeModeToTurnSandboxPolicy(input.runtimeMode), + ...(input.model ? { model: input.model } : {}), + ...(input.serviceTier ? { serviceTier: input.serviceTier } : {}), + ...(input.effort ? { effort: input.effort } : {}), + ...(collaborationMode ? { collaborationMode } : {}), + }).pipe( + Effect.mapError((error) => toProtocolParseError("Invalid turn/start request payload", error)), + ); +} + +function classifyCodexStderrLine(rawLine: string): { readonly message: string } | null { + const line = rawLine.replaceAll(ANSI_ESCAPE_REGEX, "").trim(); + if (!line) { + return null; + } + + const match = line.match(CODEX_STDERR_LOG_REGEX); + if (match) { + const level = match[1]; + if (level && level !== "ERROR") { + return null; + } + if (BENIGN_ERROR_LOG_SNIPPETS.some((snippet) => line.includes(snippet))) { + return null; + } + } + + return { message: line }; +} + +export function isRecoverableThreadResumeError(error: unknown): boolean { + const message = (error instanceof Error ? error.message : String(error)).toLowerCase(); + if (!message.includes("thread")) { + return false; + } + return RECOVERABLE_THREAD_RESUME_ERROR_SNIPPETS.some((snippet) => message.includes(snippet)); +} + +type CodexThreadOpenResponse = + | CodexRpc.ClientRequestResponsesByMethod["thread/start"] + | CodexRpc.ClientRequestResponsesByMethod["thread/resume"]; + +type CodexThreadOpenMethod = "thread/start" | "thread/resume"; + +interface CodexThreadOpenClient { + readonly request: ( + method: M, + payload: CodexRpc.ClientRequestParamsByMethod[M], + ) => Effect.Effect; +} + +export const openCodexThread = (input: { + readonly client: CodexThreadOpenClient; + readonly threadId: ThreadId; + readonly runtimeMode: RuntimeMode; + readonly cwd: string; + readonly requestedModel: string | undefined; + readonly serviceTier: EffectCodexSchema.V2ThreadStartParams__ServiceTier | undefined; + readonly resumeThreadId: string | undefined; +}): Effect.Effect => { + const resumeThreadId = input.resumeThreadId; + const startParams = buildThreadStartParams({ + cwd: input.cwd, + runtimeMode: input.runtimeMode, + model: input.requestedModel, + serviceTier: input.serviceTier, + }); + + if (resumeThreadId === undefined) { + return input.client.request("thread/start", startParams); + } + + return input.client + .request("thread/resume", { + threadId: resumeThreadId, + ...startParams, + }) + .pipe( + Effect.catchIf(isRecoverableThreadResumeError, (error) => + Effect.logWarning("codex app-server thread resume fell back to fresh start", { + threadId: input.threadId, + requestedRuntimeMode: input.runtimeMode, + resumeThreadId, + recoverable: true, + cause: error.message, + }).pipe(Effect.andThen(input.client.request("thread/start", startParams))), + ), + ); +}; + +function readNotificationThreadId(notification: CodexServerNotification): string | undefined { + switch (notification.method) { + case "thread/started": + return notification.params.thread.id; + case "error": + case "thread/status/changed": + case "thread/archived": + case "thread/unarchived": + case "thread/closed": + case "thread/name/updated": + case "thread/tokenUsage/updated": + case "turn/started": + case "hook/started": + case "turn/completed": + case "hook/completed": + case "turn/diff/updated": + case "turn/plan/updated": + case "item/started": + case "item/autoApprovalReview/started": + case "item/autoApprovalReview/completed": + case "item/completed": + case "rawResponseItem/completed": + case "item/agentMessage/delta": + case "item/plan/delta": + case "item/commandExecution/outputDelta": + case "item/commandExecution/terminalInteraction": + case "item/fileChange/outputDelta": + case "serverRequest/resolved": + case "item/mcpToolCall/progress": + case "item/reasoning/summaryTextDelta": + case "item/reasoning/summaryPartAdded": + case "item/reasoning/textDelta": + case "thread/compacted": + case "thread/realtime/started": + case "thread/realtime/itemAdded": + case "thread/realtime/transcriptUpdated": + case "thread/realtime/outputAudio/delta": + case "thread/realtime/sdp": + case "thread/realtime/error": + case "thread/realtime/closed": + return notification.params.threadId; + default: + return undefined; + } +} + +function readRouteFields(notification: CodexServerNotification): { + readonly turnId: TurnId | undefined; + readonly itemId: ProviderItemId | undefined; +} { + switch (notification.method) { + case "thread/started": + return { + turnId: undefined, + itemId: undefined, + }; + case "turn/started": + case "turn/completed": + return { + turnId: TurnId.make(notification.params.turn.id), + itemId: undefined, + }; + case "error": + return { + turnId: TurnId.make(notification.params.turnId), + itemId: undefined, + }; + case "turn/diff/updated": + case "turn/plan/updated": + return { + turnId: TurnId.make(notification.params.turnId), + itemId: undefined, + }; + case "serverRequest/resolved": + return { + turnId: undefined, + itemId: undefined, + }; + case "item/started": + case "item/completed": + return { + turnId: TurnId.make(notification.params.turnId), + itemId: ProviderItemId.make(notification.params.item.id), + }; + case "item/agentMessage/delta": + case "item/plan/delta": + case "item/commandExecution/outputDelta": + case "item/commandExecution/terminalInteraction": + case "item/fileChange/outputDelta": + case "item/reasoning/summaryTextDelta": + case "item/reasoning/summaryPartAdded": + case "item/reasoning/textDelta": + return { + turnId: TurnId.make(notification.params.turnId), + itemId: ProviderItemId.make(notification.params.itemId), + }; + default: + return { + turnId: undefined, + itemId: undefined, + }; + } +} + +function rememberCollabReceiverTurns( + collabReceiverTurns: Map, + notification: CodexServerNotification, + parentTurnId: TurnId | undefined, +): void { + if (!parentTurnId) { + return; + } + + if (notification.method !== "item/started" && notification.method !== "item/completed") { + return; + } + + if (notification.params.item.type !== "collabAgentToolCall") { + return; + } + + for (const receiverThreadId of notification.params.item.receiverThreadIds) { + collabReceiverTurns.set(receiverThreadId, parentTurnId); + } +} + +function shouldSuppressChildConversationNotification( + method: CodexRpc.ServerNotificationMethod, +): boolean { + return ( + method === "thread/started" || + method === "thread/status/changed" || + method === "thread/archived" || + method === "thread/unarchived" || + method === "thread/closed" || + method === "thread/compacted" || + method === "thread/name/updated" || + method === "thread/tokenUsage/updated" || + method === "turn/started" || + method === "turn/completed" || + method === "turn/plan/updated" || + method === "item/plan/delta" + ); +} + +function toCodexUserInputAnswer( + questionId: string, + value: ProviderUserInputAnswers[string], +): Effect.Effect< + EffectCodexSchema.ToolRequestUserInputResponse__ToolRequestUserInputAnswer, + CodexSessionRuntimeInvalidUserInputAnswersError +> { + if (typeof value === "string") { + return Effect.succeed({ answers: [value] }); + } + if (Array.isArray(value)) { + const answers = value.filter((entry): entry is string => typeof entry === "string"); + return Effect.succeed({ answers }); + } + if (Schema.is(CodexUserInputAnswerObject)(value)) { + return Effect.succeed({ answers: value.answers }); + } + return Effect.fail(new CodexSessionRuntimeInvalidUserInputAnswersError({ questionId })); +} + +function toCodexUserInputAnswers( + answers: ProviderUserInputAnswers, +): Effect.Effect< + EffectCodexSchema.ToolRequestUserInputResponse["answers"], + CodexSessionRuntimeInvalidUserInputAnswersError +> { + return Effect.forEach( + Object.entries(answers), + ([questionId, value]) => + toCodexUserInputAnswer(questionId, value).pipe( + Effect.map((answer) => [questionId, answer] as const), + ), + { concurrency: 1 }, + ).pipe(Effect.map((entries) => Object.fromEntries(entries))); +} + +function toProtocolParseError( + detail: string, + cause: Schema.SchemaError, +): CodexErrors.CodexAppServerProtocolParseError { + return new CodexErrors.CodexAppServerProtocolParseError({ + detail: `${detail}: ${formatSchemaIssue(cause.issue)}`, + cause, + }); +} + +function currentProviderThreadId(session: ProviderSession): string | undefined { + return readResumeCursorThreadId(session.resumeCursor); +} + +function updateSession( + sessionRef: Ref.Ref, + updates: Partial, +): Effect.Effect { + return Ref.update(sessionRef, (session) => ({ + ...session, + ...updates, + updatedAt: new Date().toISOString(), + })); +} + +function parseThreadSnapshot( + response: EffectCodexSchema.V2ThreadReadResponse | EffectCodexSchema.V2ThreadRollbackResponse, +): CodexThreadSnapshot { + return { + threadId: response.thread.id, + turns: response.thread.turns.map((turn) => ({ + id: TurnId.make(turn.id), + items: turn.items, + })), + }; +} + +export const makeCodexSessionRuntime = ( + options: CodexSessionRuntimeOptions, +): Effect.Effect< + CodexSessionRuntimeShape, + CodexErrors.CodexAppServerError, + ChildProcessSpawner.ChildProcessSpawner | Scope.Scope +> => + Effect.gen(function* () { + const spawner = yield* ChildProcessSpawner.ChildProcessSpawner; + const runtimeScope = yield* Scope.Scope; + const events = yield* Queue.unbounded(); + const pendingApprovalsRef = yield* Ref.make(new Map()); + const approvalCorrelationsRef = yield* Ref.make(new Map()); + const pendingUserInputsRef = yield* Ref.make(new Map()); + const collabReceiverTurnsRef = yield* Ref.make(new Map()); + const closedRef = yield* Ref.make(false); + + const child = yield* spawner + .spawn( + ChildProcess.make(options.binaryPath, ["app-server"], { + cwd: options.cwd, + ...(options.homePath ? { env: { ...process.env, CODEX_HOME: options.homePath } } : {}), + shell: process.platform === "win32", + }), + ) + .pipe( + Effect.provideService(Scope.Scope, runtimeScope), + Effect.mapError( + (cause) => + new CodexErrors.CodexAppServerSpawnError({ + command: `${options.binaryPath} app-server`, + cause, + }), + ), + ); + + const clientContext = yield* CodexClient.layerChildProcess(child).pipe( + Layer.build, + Effect.provideService(Scope.Scope, runtimeScope), + ); + const client = yield* Effect.service(CodexClient.CodexAppServerClient).pipe( + Effect.provide(clientContext), + ); + const serverNotifications = yield* Queue.unbounded(); + + const initialSession = { + provider: PROVIDER, + status: "connecting", + runtimeMode: options.runtimeMode, + cwd: options.cwd, + ...(options.model ? { model: options.model } : {}), + threadId: options.threadId, + ...(options.resumeCursor !== undefined ? { resumeCursor: options.resumeCursor } : {}), + createdAt: new Date().toISOString(), + updatedAt: new Date().toISOString(), + } satisfies ProviderSession; + const sessionRef = yield* Ref.make(initialSession); + const offerEvent = (event: ProviderEvent) => Queue.offer(events, event).pipe(Effect.asVoid); + + const emitEvent = (event: Omit) => + offerEvent({ + id: EventId.make(randomUUID()), + provider: PROVIDER, + createdAt: new Date().toISOString(), + ...event, + }); + + const emitSessionEvent = (method: string, message: string) => + emitEvent({ + kind: "session", + threadId: options.threadId, + method, + message, + }); + + const settlePendingApprovals = (decision: ProviderApprovalDecision) => + Ref.get(pendingApprovalsRef).pipe( + Effect.flatMap((pendingApprovals) => + Effect.forEach( + Array.from(pendingApprovals.values()), + (pendingApproval) => + Deferred.succeed(pendingApproval.decision, decision).pipe(Effect.ignore), + { discard: true }, + ), + ), + ); + + const settlePendingUserInputs = (answers: ProviderUserInputAnswers) => + Ref.get(pendingUserInputsRef).pipe( + Effect.flatMap((pendingUserInputs) => + Effect.forEach( + Array.from(pendingUserInputs.values()), + (pendingUserInput) => + Deferred.succeed(pendingUserInput.answers, answers).pipe(Effect.ignore), + { discard: true }, + ), + ), + ); + + const handleRawNotification = (notification: CodexServerNotification) => + Effect.gen(function* () { + const payload = notification.params; + const route = readRouteFields(notification); + const collabReceiverTurns = yield* Ref.get(collabReceiverTurnsRef); + const childParentTurnId = (() => { + const providerConversationId = readNotificationThreadId(notification); + return providerConversationId + ? collabReceiverTurns.get(providerConversationId) + : undefined; + })(); + + rememberCollabReceiverTurns(collabReceiverTurns, notification, route.turnId); + if (childParentTurnId && shouldSuppressChildConversationNotification(notification.method)) { + yield* Ref.set(collabReceiverTurnsRef, collabReceiverTurns); + return; + } + + let requestId: ApprovalRequestId | undefined; + let requestKind: ProviderRequestKind | undefined; + let turnId = childParentTurnId ?? route.turnId; + let itemId = route.itemId; + + if (notification.method === "serverRequest/resolved") { + const rawRequestId = + typeof notification.params.requestId === "string" + ? notification.params.requestId + : String(notification.params.requestId); + const correlation = rawRequestId + ? (yield* Ref.get(approvalCorrelationsRef)).get(rawRequestId) + : undefined; + if (correlation) { + requestId = correlation.requestId; + requestKind = correlation.requestKind; + turnId = correlation.turnId ?? turnId; + itemId = correlation.itemId ?? itemId; + yield* Ref.update(approvalCorrelationsRef, (current) => { + const next = new Map(current); + next.delete(rawRequestId); + return next; + }); + } + } + + yield* Ref.set(collabReceiverTurnsRef, collabReceiverTurns); + yield* emitEvent({ + kind: "notification", + threadId: options.threadId, + method: notification.method, + ...(turnId ? { turnId } : {}), + ...(itemId ? { itemId } : {}), + ...(requestId ? { requestId } : {}), + ...(requestKind ? { requestKind } : {}), + ...(notification.method === "item/agentMessage/delta" + ? { textDelta: notification.params.delta } + : {}), + ...(payload !== undefined ? { payload } : {}), + }); + }); + + const currentSessionProviderThreadId = Effect.map(Ref.get(sessionRef), currentProviderThreadId); + + yield* client.handleServerNotification("thread/started", (payload) => + currentSessionProviderThreadId.pipe( + Effect.flatMap((providerThreadId) => { + if (providerThreadId && payload.thread.id !== providerThreadId) { + return Effect.void; + } + return updateSession(sessionRef, { + resumeCursor: { threadId: payload.thread.id }, + }); + }), + ), + ); + + yield* client.handleServerNotification("turn/started", (payload) => + currentSessionProviderThreadId.pipe( + Effect.flatMap((providerThreadId) => { + if (providerThreadId && payload.threadId !== providerThreadId) { + return Effect.void; + } + return updateSession(sessionRef, { + status: "running", + activeTurnId: TurnId.make(payload.turn.id), + }); + }), + ), + ); + + yield* client.handleServerNotification("turn/completed", (payload) => + currentSessionProviderThreadId.pipe( + Effect.flatMap((providerThreadId) => { + if (providerThreadId && payload.threadId !== providerThreadId) { + return Effect.void; + } + const lastError = + payload.turn.status === "failed" && "error" in payload.turn && payload.turn.error + ? payload.turn.error.message + : undefined; + return updateSession(sessionRef, { + status: payload.turn.status === "failed" ? "error" : "ready", + activeTurnId: undefined, + ...(lastError ? { lastError } : {}), + }); + }), + ), + ); + + yield* client.handleServerNotification("error", (payload) => + currentSessionProviderThreadId.pipe( + Effect.flatMap((providerThreadId) => { + const payloadThreadId = payload.threadId; + if (providerThreadId && payloadThreadId && payloadThreadId !== providerThreadId) { + return Effect.void; + } + const errorMessage = payload.error.message; + const willRetry = payload.willRetry; + return updateSession(sessionRef, { + status: willRetry ? "running" : "error", + ...(errorMessage ? { lastError: errorMessage } : {}), + }); + }), + ), + ); + + yield* client.handleServerRequest("item/commandExecution/requestApproval", (payload) => + Effect.gen(function* () { + const requestId = ApprovalRequestId.make(randomUUID()); + const turnId = TurnId.make(payload.turnId); + const itemId = ProviderItemId.make(payload.itemId); + const decision = yield* Deferred.make(); + + yield* Ref.update(pendingApprovalsRef, (current) => { + const next = new Map(current); + next.set(requestId, { + requestId, + jsonRpcId: payload.approvalId ?? payload.itemId, + requestKind: "command", + turnId, + itemId, + decision, + }); + return next; + }); + yield* Ref.update(approvalCorrelationsRef, (current) => { + const next = new Map(current); + next.set(payload.approvalId ?? payload.itemId, { + requestId, + requestKind: "command", + turnId, + itemId, + }); + return next; + }); + + yield* emitEvent({ + kind: "request", + threadId: options.threadId, + method: "item/commandExecution/requestApproval", + requestId, + requestKind: "command", + ...(turnId ? { turnId } : {}), + ...(itemId ? { itemId } : {}), + payload, + }); + + const resolved = yield* Deferred.await(decision).pipe( + Effect.ensuring( + Ref.update(pendingApprovalsRef, (current) => { + const next = new Map(current); + next.delete(requestId); + return next; + }), + ), + ); + return { + decision: resolved, + } satisfies EffectCodexSchema.CommandExecutionRequestApprovalResponse; + }), + ); + + yield* client.handleServerRequest("item/fileChange/requestApproval", (payload) => + Effect.gen(function* () { + const requestId = ApprovalRequestId.make(randomUUID()); + const turnId = TurnId.make(payload.turnId); + const itemId = ProviderItemId.make(payload.itemId); + const decision = yield* Deferred.make(); + + yield* Ref.update(pendingApprovalsRef, (current) => { + const next = new Map(current); + next.set(requestId, { + requestId, + jsonRpcId: payload.itemId, + requestKind: "file-change", + turnId, + itemId, + decision, + }); + return next; + }); + yield* Ref.update(approvalCorrelationsRef, (current) => { + const next = new Map(current); + next.set(payload.itemId, { + requestId, + requestKind: "file-change", + turnId, + itemId, + }); + return next; + }); + + yield* emitEvent({ + kind: "request", + threadId: options.threadId, + method: "item/fileChange/requestApproval", + requestId, + requestKind: "file-change", + ...(turnId ? { turnId } : {}), + ...(itemId ? { itemId } : {}), + payload, + }); + + const resolved = yield* Deferred.await(decision).pipe( + Effect.ensuring( + Ref.update(pendingApprovalsRef, (current) => { + const next = new Map(current); + next.delete(requestId); + return next; + }), + ), + ); + return { + decision: resolved, + } satisfies EffectCodexSchema.FileChangeRequestApprovalResponse; + }), + ); + + yield* client.handleServerRequest("item/tool/requestUserInput", (payload) => + Effect.gen(function* () { + const requestId = ApprovalRequestId.make(randomUUID()); + const turnId = TurnId.make(payload.turnId); + const itemId = ProviderItemId.make(payload.itemId); + const answers = yield* Deferred.make(); + + yield* Ref.update(pendingUserInputsRef, (current) => { + const next = new Map(current); + next.set(requestId, { + requestId, + turnId, + itemId, + answers, + }); + return next; + }); + + yield* emitEvent({ + kind: "request", + threadId: options.threadId, + method: "item/tool/requestUserInput", + requestId, + ...(turnId ? { turnId } : {}), + ...(itemId ? { itemId } : {}), + payload, + }); + + const resolvedAnswers = yield* Deferred.await(answers).pipe( + Effect.ensuring( + Ref.update(pendingUserInputsRef, (current) => { + const next = new Map(current); + next.delete(requestId); + return next; + }), + ), + ); + + return { + answers: yield* toCodexUserInputAnswers(resolvedAnswers).pipe( + Effect.mapError((error) => + CodexErrors.CodexAppServerRequestError.invalidParams(error.message, { + questionId: error.questionId, + }), + ), + ), + } satisfies EffectCodexSchema.ToolRequestUserInputResponse; + }), + ); + + yield* client.handleUnknownServerRequest((method) => + Effect.fail(CodexErrors.CodexAppServerRequestError.methodNotFound(method)), + ); + + const registerServerNotification = (method: M) => + client.handleServerNotification(method, (params) => + Queue.offer(serverNotifications, makeCodexServerNotification(method, params)).pipe( + Effect.asVoid, + ), + ); + + yield* Effect.forEach( + Object.values( + CodexRpc.SERVER_NOTIFICATION_METHODS, + ) as ReadonlyArray, + registerServerNotification, + { concurrency: 1, discard: true }, + ); + + yield* Stream.fromQueue(serverNotifications).pipe( + Stream.runForEach(handleRawNotification), + Effect.forkIn(runtimeScope), + ); + + const stderrRemainderRef = yield* Ref.make(""); + yield* child.stderr.pipe( + Stream.decodeText(), + Stream.runForEach((chunk) => + Ref.modify(stderrRemainderRef, (current) => { + const combined = current + chunk; + const lines = combined.split("\n"); + const remainder = lines.pop() ?? ""; + return [lines.map((line) => line.replace(/\r$/, "")), remainder] as const; + }).pipe( + Effect.flatMap((lines) => + Effect.forEach( + lines, + (line) => { + const classified = classifyCodexStderrLine(line); + if (!classified) { + return Effect.void; + } + return emitEvent({ + kind: "notification", + threadId: options.threadId, + method: "process/stderr", + message: classified.message, + }); + }, + { discard: true }, + ), + ), + ), + ), + Effect.forkIn(runtimeScope), + ); + + yield* child.exitCode.pipe( + Effect.flatMap((exitCode) => + Ref.get(closedRef).pipe( + Effect.flatMap((closed) => { + if (closed) { + return Effect.void; + } + const nextStatus = exitCode === 0 ? "closed" : "error"; + return updateSession(sessionRef, { + status: nextStatus, + activeTurnId: undefined, + }).pipe( + Effect.andThen( + emitSessionEvent( + "session/exited", + exitCode === 0 + ? "Codex App Server exited." + : `Codex App Server exited with code ${exitCode}.`, + ), + ), + ); + }), + ), + ), + Effect.forkIn(runtimeScope), + ); + + const start = Effect.fn("CodexSessionRuntime.start")(function* () { + yield* emitSessionEvent("session/connecting", "Starting Codex App Server session."); + yield* client.request("initialize", buildCodexInitializeParams()); + yield* client.notify("initialized", undefined); + + const requestedModel = normalizeCodexModelSlug(options.model); + + const opened = yield* openCodexThread({ + client, + threadId: options.threadId, + runtimeMode: options.runtimeMode, + cwd: options.cwd, + requestedModel, + serviceTier: options.serviceTier, + resumeThreadId: readResumeCursorThreadId(options.resumeCursor), + }); + + const providerThreadId = opened.thread.id; + const session = { + ...(yield* Ref.get(sessionRef)), + status: "ready", + cwd: opened.cwd, + model: opened.model, + resumeCursor: { threadId: providerThreadId }, + updatedAt: new Date().toISOString(), + } satisfies ProviderSession; + yield* Ref.set(sessionRef, session); + yield* emitSessionEvent("session/ready", "Codex App Server session ready."); + return session; + }); + + const readProviderThreadId = Effect.gen(function* () { + const providerThreadId = currentProviderThreadId(yield* Ref.get(sessionRef)); + if (!providerThreadId) { + return yield* new CodexSessionRuntimeThreadIdMissingError({ + threadId: options.threadId, + }); + } + return providerThreadId; + }); + + const close = Effect.gen(function* () { + const alreadyClosed = yield* Ref.getAndSet(closedRef, true); + if (alreadyClosed) { + return; + } + yield* settlePendingApprovals("cancel"); + yield* settlePendingUserInputs({}); + yield* updateSession(sessionRef, { + status: "closed", + activeTurnId: undefined, + }); + yield* emitSessionEvent("session/closed", "Session stopped"); + yield* Scope.close(runtimeScope, Exit.void); + yield* Queue.shutdown(serverNotifications); + yield* Queue.shutdown(events); + }); + + return { + start, + getSession: Ref.get(sessionRef), + sendTurn: (input) => + Effect.gen(function* () { + const providerThreadId = yield* readProviderThreadId; + const normalizedModel = normalizeCodexModelSlug( + input.model ?? (yield* Ref.get(sessionRef)).model, + ); + const params = yield* buildTurnStartParams({ + threadId: providerThreadId, + runtimeMode: options.runtimeMode, + ...(input.input ? { prompt: input.input } : {}), + ...(input.attachments ? { attachments: input.attachments } : {}), + ...(normalizedModel ? { model: normalizedModel } : {}), + ...(input.serviceTier ? { serviceTier: input.serviceTier } : {}), + ...(input.effort ? { effort: input.effort } : {}), + ...(input.interactionMode ? { interactionMode: input.interactionMode } : {}), + }); + const rawResponse = yield* client.raw.request("turn/start", params); + const response = yield* Schema.decodeUnknownEffect(EffectCodexSchema.V2TurnStartResponse)( + rawResponse, + ).pipe( + Effect.mapError((error) => + toProtocolParseError("Invalid turn/start response payload", error), + ), + ); + const turnId = TurnId.make(response.turn.id); + yield* updateSession(sessionRef, { + status: "running", + activeTurnId: turnId, + ...(normalizedModel ? { model: normalizedModel } : {}), + }); + const resumedProviderThreadId = currentProviderThreadId(yield* Ref.get(sessionRef)); + return { + threadId: options.threadId, + turnId, + ...(resumedProviderThreadId + ? { resumeCursor: { threadId: resumedProviderThreadId } } + : {}), + } satisfies ProviderTurnStartResult; + }), + interruptTurn: (turnId) => + Effect.gen(function* () { + const providerThreadId = yield* readProviderThreadId; + const session = yield* Ref.get(sessionRef); + const effectiveTurnId = turnId ?? session.activeTurnId; + if (!effectiveTurnId) { + return; + } + yield* client.request("turn/interrupt", { + threadId: providerThreadId, + turnId: effectiveTurnId, + }); + }), + readThread: Effect.gen(function* () { + const providerThreadId = yield* readProviderThreadId; + const response = yield* client.request("thread/read", { + threadId: providerThreadId, + includeTurns: true, + }); + return parseThreadSnapshot(response); + }), + rollbackThread: (numTurns) => + Effect.gen(function* () { + const providerThreadId = yield* readProviderThreadId; + const response = yield* client.request("thread/rollback", { + threadId: providerThreadId, + numTurns, + }); + yield* updateSession(sessionRef, { + status: "ready", + activeTurnId: undefined, + }); + return parseThreadSnapshot(response); + }), + respondToRequest: (requestId, decision) => + Effect.gen(function* () { + const pending = (yield* Ref.get(pendingApprovalsRef)).get(requestId); + if (!pending) { + return yield* new CodexSessionRuntimePendingApprovalNotFoundError({ + requestId, + }); + } + yield* Ref.update(pendingApprovalsRef, (current) => { + const next = new Map(current); + next.delete(requestId); + return next; + }); + yield* Deferred.succeed(pending.decision, decision); + yield* emitEvent({ + kind: "notification", + threadId: options.threadId, + method: "item/requestApproval/decision", + requestId: pending.requestId, + requestKind: pending.requestKind, + ...(pending.turnId ? { turnId: pending.turnId } : {}), + ...(pending.itemId ? { itemId: pending.itemId } : {}), + payload: { + requestId: pending.requestId, + requestKind: pending.requestKind, + decision, + }, + }); + }), + respondToUserInput: (requestId, answers) => + Effect.gen(function* () { + const pending = (yield* Ref.get(pendingUserInputsRef)).get(requestId); + if (!pending) { + return yield* new CodexSessionRuntimePendingUserInputNotFoundError({ + requestId, + }); + } + const codexAnswers = yield* toCodexUserInputAnswers(answers); + yield* Ref.update(pendingUserInputsRef, (current) => { + const next = new Map(current); + next.delete(requestId); + return next; + }); + yield* Deferred.succeed(pending.answers, answers); + yield* emitEvent({ + kind: "notification", + threadId: options.threadId, + method: "item/tool/requestUserInput/answered", + requestId: pending.requestId, + ...(pending.turnId ? { turnId: pending.turnId } : {}), + ...(pending.itemId ? { itemId: pending.itemId } : {}), + payload: { + answers: codexAnswers, + }, + }); + }), + events: Stream.fromQueue(events), + close, + } satisfies CodexSessionRuntimeShape; + }); diff --git a/apps/server/src/provider/Layers/ProviderRegistry.test.ts b/apps/server/src/provider/Layers/ProviderRegistry.test.ts index 14583e6842..2d6855f914 100644 --- a/apps/server/src/provider/Layers/ProviderRegistry.test.ts +++ b/apps/server/src/provider/Layers/ProviderRegistry.test.ts @@ -1,18 +1,7 @@ import * as NodeServices from "@effect/platform-node/NodeServices"; import { describe, it, assert } from "@effect/vitest"; -import { - Effect, - Exit, - FileSystem, - Layer, - Path, - PubSub, - Ref, - Schema, - Scope, - Sink, - Stream, -} from "effect"; +import { Effect, Exit, Layer, PubSub, Ref, Schema, Scope, Sink, Stream } from "effect"; +import * as CodexErrors from "effect-codex-app-server/errors"; import { DEFAULT_SERVER_SETTINGS, ServerSettings, @@ -23,19 +12,13 @@ import * as PlatformError from "effect/PlatformError"; import { ChildProcessSpawner } from "effect/unstable/process"; import { deepMerge } from "@t3tools/shared/Struct"; -import { - checkCodexProviderStatus, - hasCustomModelProvider, - parseAuthStatusFromOutput, - readCodexConfigModelProvider, -} from "./CodexProvider.ts"; +import { checkCodexProviderStatus, type CodexAppServerProviderSnapshot } from "./CodexProvider.ts"; import { checkClaudeProviderStatus, parseClaudeAuthStatusFromOutput } from "./ClaudeProvider.ts"; import { haveProvidersChanged, mergeProviderSnapshot, ProviderRegistryLive, } from "./ProviderRegistry.ts"; -import { OpenCodeProvider } from "../Services/OpenCodeProvider.ts"; import { ServerConfig } from "../../config.ts"; import { ServerSettingsService, type ServerSettingsShape } from "../../serverSettings.ts"; import { ProviderRegistry } from "../Services/ProviderRegistry.ts"; @@ -45,19 +28,6 @@ process.env.T3CODE_CURSOR_ENABLED = "1"; // ── Test helpers ──────────────────────────────────────────────────── const encoder = new TextEncoder(); -const fakeOpenCodeSnapshot: ServerProvider = { - provider: "opencode", - status: "warning", - enabled: true, - installed: false, - auth: { status: "unknown" }, - checkedAt: "2026-03-25T00:00:00.000Z", - version: null, - models: [], - slashCommands: [], - skills: [], - message: "OpenCode test stub", -}; function mockHandle(result: { stdout: string; stderr: string; code: number }) { return ChildProcessSpawner.makeHandle({ @@ -118,6 +88,43 @@ function failingSpawnerLayer(description: string) { ); } +const codexModelCapabilities = { + reasoningEffortLevels: [ + { value: "high", label: "High", isDefault: true }, + { value: "low", label: "Low" }, + ], + supportsFastMode: true, + supportsThinkingToggle: false, + contextWindowOptions: [], + promptInjectedEffortLevels: [], +} satisfies NonNullable; + +function makeCodexProbeSnapshot( + input: Partial = {}, +): CodexAppServerProviderSnapshot { + return { + version: "1.0.0", + account: { + account: { + type: "chatgpt", + email: "test@example.com", + planType: "pro", + }, + requiresOpenaiAuth: false, + }, + models: [ + { + slug: "gpt-live-codex", + name: "GPT Live Codex", + isCustom: false, + capabilities: codexModelCapabilities, + }, + ], + skills: [], + ...input, + }; +} + function makeMutableServerSettingsService( initial: ContractServerSettings = DEFAULT_SERVER_SETTINGS, ) { @@ -144,126 +151,43 @@ function makeMutableServerSettingsService( }); } -/** - * Create a temporary CODEX_HOME scoped to the current Effect test. - * Cleanup is registered in the test scope rather than via Vitest hooks. - */ -function withTempCodexHome(configContent?: string) { - return Effect.gen(function* () { - const fileSystem = yield* FileSystem.FileSystem; - const path = yield* Path.Path; - const tmpDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-test-codex-" }); - - yield* Effect.acquireRelease( - Effect.sync(() => { - const originalCodexHome = process.env.CODEX_HOME; - process.env.CODEX_HOME = tmpDir; - return originalCodexHome; - }), - (originalCodexHome) => - Effect.sync(() => { - if (originalCodexHome !== undefined) { - process.env.CODEX_HOME = originalCodexHome; - } else { - delete process.env.CODEX_HOME; - } - }), - ); - - if (configContent !== undefined) { - yield* fileSystem.writeFileString(path.join(tmpDir, "config.toml"), configContent); - } - - return { tmpDir } as const; - }); -} - it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))( "ProviderRegistry", (it) => { - // ── checkCodexProviderStatus tests ──────────────────────────────── - // - // These tests control CODEX_HOME to ensure the custom-provider detection - // in hasCustomModelProvider() does not interfere with the auth-probe - // path being tested. - describe("checkCodexProviderStatus", () => { - it.effect("returns ready when codex is installed and authenticated", () => + it.effect("uses the app-server account and model list for provider status", () => Effect.gen(function* () { - // Point CODEX_HOME at an empty tmp dir (no config.toml) so the - // default code path (OpenAI provider, auth probe runs) is exercised. - yield* withTempCodexHome(); - const status = yield* checkCodexProviderStatus(); + const status = yield* checkCodexProviderStatus(() => + Effect.succeed( + makeCodexProbeSnapshot({ + skills: [ + { + name: "github:gh-fix-ci", + path: "/Users/test/.codex/skills/gh-fix-ci/SKILL.md", + enabled: true, + displayName: "CI Debug", + shortDescription: "Debug failing GitHub Actions checks", + }, + ], + }), + ), + ); + assert.strictEqual(status.provider, "codex"); assert.strictEqual(status.status, "ready"); assert.strictEqual(status.installed, true); + assert.strictEqual(status.version, "1.0.0"); assert.strictEqual(status.auth.status, "authenticated"); - }).pipe( - Effect.provide( - mockSpawnerLayer((args) => { - const joined = args.join(" "); - if (joined === "--version") return { stdout: "codex 1.0.0\n", stderr: "", code: 0 }; - if (joined === "login status") return { stdout: "Logged in\n", stderr: "", code: 0 }; - throw new Error(`Unexpected args: ${joined}`); - }), - ), - ), - ); - - it.effect("returns the codex plan type in auth and keeps spark for supported plans", () => - Effect.gen(function* () { - yield* withTempCodexHome(); - const status = yield* checkCodexProviderStatus(() => - Effect.succeed({ - type: "chatgpt" as const, - planType: "pro" as const, - sparkEnabled: true, - }), - ); - - assert.strictEqual(status.provider, "codex"); - assert.strictEqual(status.status, "ready"); - assert.strictEqual(status.auth.status, "authenticated"); - assert.strictEqual(status.auth.type, "pro"); + assert.strictEqual(status.auth.type, "chatgpt"); assert.strictEqual(status.auth.label, "ChatGPT Pro Subscription"); - assert.deepStrictEqual( - status.models.some((model) => model.slug === "gpt-5.3-codex-spark"), - true, - ); - }).pipe( - Effect.provide( - mockSpawnerLayer((args) => { - const joined = args.join(" "); - if (joined === "--version") return { stdout: "codex 1.0.0\n", stderr: "", code: 0 }; - if (joined === "login status") return { stdout: "Logged in\n", stderr: "", code: 0 }; - throw new Error(`Unexpected args: ${joined}`); - }), - ), - ), - ); - - it.effect("includes probed codex skills in the provider snapshot", () => - Effect.gen(function* () { - yield* withTempCodexHome(); - const status = yield* checkCodexProviderStatus( - () => - Effect.succeed({ - type: "chatgpt" as const, - planType: "pro" as const, - sparkEnabled: true, - }), - () => - Effect.succeed([ - { - name: "github:gh-fix-ci", - path: "/Users/test/.codex/skills/gh-fix-ci/SKILL.md", - enabled: true, - displayName: "CI Debug", - shortDescription: "Debug failing GitHub Actions checks", - }, - ]), - ); - + assert.deepStrictEqual(status.models, [ + { + slug: "gpt-live-codex", + name: "GPT Live Codex", + isCustom: false, + capabilities: codexModelCapabilities, + }, + ]); assert.deepStrictEqual(status.skills, [ { name: "github:gh-fix-ci", @@ -273,172 +197,81 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))( shortDescription: "Debug failing GitHub Actions checks", }, ]); - }).pipe( - Effect.provide( - mockSpawnerLayer((args) => { - const joined = args.join(" "); - if (joined === "--version") return { stdout: "codex 1.0.0\n", stderr: "", code: 0 }; - if (joined === "login status") return { stdout: "Logged in\n", stderr: "", code: 0 }; - throw new Error(`Unexpected args: ${joined}`); - }), - ), - ), + }), ); - it.effect("hides spark from codex models for unsupported chatgpt plans", () => + it.effect("returns unauthenticated when app-server requires OpenAI auth", () => Effect.gen(function* () { - yield* withTempCodexHome(); const status = yield* checkCodexProviderStatus(() => - Effect.succeed({ - type: "chatgpt" as const, - planType: "plus" as const, - sparkEnabled: false, - }), + Effect.succeed( + makeCodexProbeSnapshot({ + account: { + account: null, + requiresOpenaiAuth: true, + }, + }), + ), ); - assert.strictEqual(status.provider, "codex"); - assert.strictEqual(status.status, "ready"); - assert.strictEqual(status.auth.status, "authenticated"); - assert.strictEqual(status.auth.type, "plus"); - assert.strictEqual(status.auth.label, "ChatGPT Plus Subscription"); - assert.deepStrictEqual( - status.models.some((model) => model.slug === "gpt-5.3-codex-spark"), - false, + assert.strictEqual(status.status, "error"); + assert.strictEqual(status.auth.status, "unauthenticated"); + assert.strictEqual( + status.message, + "Codex CLI is not authenticated. Run `codex login` and try again.", ); - }).pipe( - Effect.provide( - mockSpawnerLayer((args) => { - const joined = args.join(" "); - if (joined === "--version") return { stdout: "codex 1.0.0\n", stderr: "", code: 0 }; - if (joined === "login status") return { stdout: "Logged in\n", stderr: "", code: 0 }; - throw new Error(`Unexpected args: ${joined}`); - }), - ), - ), + }), ); - it.effect("hides spark from codex models for non-pro chatgpt subscriptions", () => - Effect.gen(function* () { - yield* withTempCodexHome(); - const status = yield* checkCodexProviderStatus(() => - Effect.succeed({ - type: "chatgpt" as const, - planType: "team" as const, - sparkEnabled: false, - }), - ); + it.effect( + "returns ready with unknown auth when app-server does not require OpenAI auth", + () => + Effect.gen(function* () { + const status = yield* checkCodexProviderStatus(() => + Effect.succeed( + makeCodexProbeSnapshot({ + account: { + account: null, + requiresOpenaiAuth: false, + }, + }), + ), + ); - assert.strictEqual(status.provider, "codex"); - assert.strictEqual(status.auth.type, "team"); - assert.strictEqual(status.auth.label, "ChatGPT Team Subscription"); - assert.deepStrictEqual( - status.models.some((model) => model.slug === "gpt-5.3-codex-spark"), - false, - ); - }).pipe( - Effect.provide( - mockSpawnerLayer((args) => { - const joined = args.join(" "); - if (joined === "--version") return { stdout: "codex 1.0.0\n", stderr: "", code: 0 }; - if (joined === "login status") return { stdout: "Logged in\n", stderr: "", code: 0 }; - throw new Error(`Unexpected args: ${joined}`); - }), - ), - ), + assert.strictEqual(status.status, "ready"); + assert.strictEqual(status.auth.status, "unknown"); + }), ); it.effect("returns an api key label for codex api key auth", () => Effect.gen(function* () { - yield* withTempCodexHome(); const status = yield* checkCodexProviderStatus(() => - Effect.succeed({ - type: "apiKey" as const, - planType: null, - sparkEnabled: false, - }), + Effect.succeed( + makeCodexProbeSnapshot({ + account: { + account: { type: "apiKey" }, + requiresOpenaiAuth: false, + }, + }), + ), ); - assert.strictEqual(status.provider, "codex"); assert.strictEqual(status.status, "ready"); assert.strictEqual(status.auth.status, "authenticated"); assert.strictEqual(status.auth.type, "apiKey"); assert.strictEqual(status.auth.label, "OpenAI API Key"); - assert.deepStrictEqual( - status.models.some((model) => model.slug === "gpt-5.3-codex-spark"), - false, - ); - }).pipe( - Effect.provide( - mockSpawnerLayer((args) => { - const joined = args.join(" "); - if (joined === "--version") return { stdout: "codex 1.0.0\n", stderr: "", code: 0 }; - if (joined === "login status") return { stdout: "Logged in\n", stderr: "", code: 0 }; - throw new Error(`Unexpected args: ${joined}`); - }), - ), - ), - ); - - it.effect.skipIf(process.platform === "win32")( - "inherits PATH when launching the codex probe with a CODEX_HOME override", - () => - Effect.gen(function* () { - const fileSystem = yield* FileSystem.FileSystem; - const path = yield* Path.Path; - const binDir = yield* fileSystem.makeTempDirectoryScoped({ - prefix: "t3-test-codex-bin-", - }); - const codexPath = path.join(binDir, "codex"); - yield* fileSystem.writeFileString( - codexPath, - [ - "#!/bin/sh", - 'if [ "$1" = "--version" ]; then', - ' echo "codex-cli 1.0.0"', - " exit 0", - "fi", - 'if [ "$1" = "login" ] && [ "$2" = "status" ]; then', - ' echo "Logged in using ChatGPT"', - " exit 0", - "fi", - 'echo "unexpected args: $*" >&2', - "exit 1", - "", - ].join("\n"), - ); - yield* fileSystem.chmod(codexPath, 0o755); - const customCodexHome = yield* fileSystem.makeTempDirectoryScoped({ - prefix: "t3-test-codex-home-", - }); - const previousPath = process.env.PATH; - process.env.PATH = binDir; - - try { - const serverSettingsLayer = ServerSettingsService.layerTest({ - providers: { - codex: { - homePath: customCodexHome, - }, - }, - }); - - const status = yield* checkCodexProviderStatus().pipe( - Effect.provide(serverSettingsLayer), - ); - assert.strictEqual(status.provider, "codex"); - assert.strictEqual(status.installed, true); - assert.strictEqual(status.status, "ready"); - assert.strictEqual(status.auth.status, "authenticated"); - } finally { - process.env.PATH = previousPath; - } - }), + }), ); it.effect("returns unavailable when codex is missing", () => Effect.gen(function* () { - yield* withTempCodexHome(); - const status = yield* checkCodexProviderStatus(); + const status = yield* checkCodexProviderStatus(() => + Effect.fail( + new CodexErrors.CodexAppServerSpawnError({ + command: "codex app-server", + cause: new Error("spawn codex ENOENT"), + }), + ), + ); assert.strictEqual(status.provider, "codex"); assert.strictEqual(status.status, "error"); assert.strictEqual(status.installed, false); @@ -447,107 +280,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))( status.message, "Codex CLI (`codex`) is not installed or not on PATH.", ); - }).pipe(Effect.provide(failingSpawnerLayer("spawn codex ENOENT"))), - ); - - it.effect("returns unavailable when codex is below the minimum supported version", () => - Effect.gen(function* () { - yield* withTempCodexHome(); - const status = yield* checkCodexProviderStatus(); - assert.strictEqual(status.provider, "codex"); - assert.strictEqual(status.status, "error"); - assert.strictEqual(status.installed, true); - assert.strictEqual(status.auth.status, "unknown"); - assert.strictEqual( - status.message, - "Codex CLI v0.36.0 is too old for T3 Code. Upgrade to v0.37.0 or newer and restart T3 Code.", - ); - }).pipe( - Effect.provide( - mockSpawnerLayer((args) => { - const joined = args.join(" "); - if (joined === "--version") return { stdout: "codex 0.36.0\n", stderr: "", code: 0 }; - throw new Error(`Unexpected args: ${joined}`); - }), - ), - ), - ); - - it.effect("returns unauthenticated when auth probe reports login required", () => - Effect.gen(function* () { - yield* withTempCodexHome(); - const status = yield* checkCodexProviderStatus(); - assert.strictEqual(status.provider, "codex"); - assert.strictEqual(status.status, "error"); - assert.strictEqual(status.installed, true); - assert.strictEqual(status.auth.status, "unauthenticated"); - assert.strictEqual( - status.message, - "Codex CLI is not authenticated. Run `codex login` and try again.", - ); - }).pipe( - Effect.provide( - mockSpawnerLayer((args) => { - const joined = args.join(" "); - if (joined === "--version") return { stdout: "codex 1.0.0\n", stderr: "", code: 0 }; - if (joined === "login status") { - return { stdout: "", stderr: "Not logged in. Run codex login.", code: 1 }; - } - throw new Error(`Unexpected args: ${joined}`); - }), - ), - ), - ); - - it.effect("returns unauthenticated when login status output includes 'not logged in'", () => - Effect.gen(function* () { - yield* withTempCodexHome(); - const status = yield* checkCodexProviderStatus(); - assert.strictEqual(status.provider, "codex"); - assert.strictEqual(status.status, "error"); - assert.strictEqual(status.installed, true); - assert.strictEqual(status.auth.status, "unauthenticated"); - assert.strictEqual( - status.message, - "Codex CLI is not authenticated. Run `codex login` and try again.", - ); - }).pipe( - Effect.provide( - mockSpawnerLayer((args) => { - const joined = args.join(" "); - if (joined === "--version") return { stdout: "codex 1.0.0\n", stderr: "", code: 0 }; - if (joined === "login status") - return { stdout: "Not logged in\n", stderr: "", code: 1 }; - throw new Error(`Unexpected args: ${joined}`); - }), - ), - ), - ); - - it.effect("returns warning when login status command is unsupported", () => - Effect.gen(function* () { - yield* withTempCodexHome(); - const status = yield* checkCodexProviderStatus(); - assert.strictEqual(status.provider, "codex"); - assert.strictEqual(status.status, "warning"); - assert.strictEqual(status.installed, true); - assert.strictEqual(status.auth.status, "unknown"); - assert.strictEqual( - status.message, - "Codex CLI authentication status command is unavailable in this Codex version.", - ); - }).pipe( - Effect.provide( - mockSpawnerLayer((args) => { - const joined = args.join(" "); - if (joined === "--version") return { stdout: "codex 1.0.0\n", stderr: "", code: 0 }; - if (joined === "login status") { - return { stdout: "", stderr: "error: unknown command 'login'", code: 2 }; - } - throw new Error(`Unexpected args: ${joined}`); - }), - ), - ), + }), ); }); @@ -677,7 +410,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))( Schema.decodeSync(ServerSettings)( deepMerge(DEFAULT_SERVER_SETTINGS, { providers: { - claudeAgent: { enabled: false }, + codex: { enabled: false }, cursor: { enabled: false }, }, }), @@ -697,14 +430,8 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))( spawnCount += 1; const joined = args.join(" "); if (joined === "--version") { - if (command === "codex") { - return { stdout: "codex 1.0.0\n", stderr: "", code: 0 }; - } return { stdout: "claude 1.0.0\n", stderr: "", code: 0 }; } - if (joined === "login status") { - return { stdout: "Logged in\n", stderr: "", code: 0 }; - } if (joined === "auth status") { return { stdout: '{"authenticated":true}\n', stderr: "", code: 0 }; } @@ -722,8 +449,10 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))( const refreshed = yield* Effect.gen(function* () { for (let remainingAttempts = 50; remainingAttempts > 0; remainingAttempts -= 1) { const providers = yield* registry.getProviders; - const codexProvider = providers.find((provider) => provider.provider === "codex"); - if (codexProvider?.status === "ready") { + const claudeProvider = providers.find( + (provider) => provider.provider === "claudeAgent", + ); + if (claudeProvider?.status === "ready") { return providers; } yield* Effect.sleep("10 millis"); @@ -731,99 +460,13 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))( return yield* registry.getProviders; }); assert.strictEqual( - refreshed.find((provider) => provider.provider === "codex")?.status, + refreshed.find((provider) => provider.provider === "claudeAgent")?.status, "ready", ); }).pipe(Effect.provide(runtimeServices)); }), ); - it.effect("reruns codex health when codex provider settings change", () => - Effect.gen(function* () { - const serverSettings = yield* makeMutableServerSettingsService(); - const scope = yield* Scope.make(); - yield* Effect.addFinalizer(() => Scope.close(scope, Exit.void)); - const providerRegistryLayer = ProviderRegistryLive.pipe( - Layer.provideMerge(Layer.succeed(ServerSettingsService, serverSettings)), - Layer.provideMerge( - ServerConfig.layerTest(process.cwd(), { - prefix: "t3-provider-registry-", - }), - ), - Layer.provideMerge( - Layer.succeed(OpenCodeProvider, { - getSnapshot: Effect.succeed(fakeOpenCodeSnapshot), - refresh: Effect.succeed(fakeOpenCodeSnapshot), - streamChanges: Stream.empty, - }), - ), - Layer.provideMerge( - mockCommandSpawnerLayer((command, args) => { - const joined = args.join(" "); - if (joined === "--version") { - if (command === "codex") { - return { stdout: "codex 1.0.0\n", stderr: "", code: 0 }; - } - return { stdout: "", stderr: "spawn ENOENT", code: 1 }; - } - if (joined === "about --format json") { - return { - stdout: JSON.stringify({ - cliVersion: "2026.04.09-f2b0fcd", - userEmail: null, - }), - stderr: "", - code: 0, - }; - } - if (joined === "about") { - return { stdout: "", stderr: "spawn ENOENT", code: 1 }; - } - if (joined === "login status") { - return { stdout: "Logged in\n", stderr: "", code: 0 }; - } - throw new Error(`Unexpected args: ${joined}`); - }), - ), - ); - const runtimeServices = yield* Layer.build(providerRegistryLayer).pipe( - Scope.provide(scope), - ); - - yield* Effect.gen(function* () { - const registry = yield* ProviderRegistry; - - const refreshed = yield* registry.refresh("codex"); - assert.strictEqual( - refreshed.find((status) => status.provider === "codex")?.status, - "ready", - ); - - yield* serverSettings.updateSettings({ - providers: { - codex: { - binaryPath: "/custom/codex", - }, - }, - }); - - for (let attempt = 0; attempt < 20; attempt += 1) { - const updated = yield* registry.getProviders; - if (updated.find((status) => status.provider === "codex")?.status === "error") { - return; - } - yield* Effect.promise(() => new Promise((resolve) => setTimeout(resolve, 0))); - } - - const updated = yield* registry.getProviders; - assert.strictEqual( - updated.find((status) => status.provider === "codex")?.status, - "error", - ); - }).pipe(Effect.provide(runtimeServices)); - }), - ); - it.effect( "keeps cursor disabled and skips probing when the provider setting is disabled", () => @@ -832,6 +475,9 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))( Schema.decodeSync(ServerSettings)( deepMerge(DEFAULT_SERVER_SETTINGS, { providers: { + codex: { + enabled: false, + }, cursor: { enabled: false, }, @@ -858,9 +504,6 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))( if (joined === "--version") { return { stdout: `${command} 1.0.0\n`, stderr: "", code: 0 }; } - if (joined === "login status") { - return { stdout: "Logged in\n", stderr: "", code: 0 }; - } if (joined === "auth status") { return { stdout: '{"authenticated":true}\n', stderr: "", code: 0 }; } @@ -919,238 +562,6 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))( ); }); - // ── Custom model provider: checkCodexProviderStatus integration ─── - - describe("checkCodexProviderStatus with custom model provider", () => { - it.effect( - "skips auth probe and returns ready when a custom model provider is configured", - () => - Effect.gen(function* () { - yield* withTempCodexHome( - [ - 'model_provider = "portkey"', - "", - "[model_providers.portkey]", - 'base_url = "https://api.portkey.ai/v1"', - 'env_key = "PORTKEY_API_KEY"', - ].join("\n"), - ); - const status = yield* checkCodexProviderStatus(); - assert.strictEqual(status.provider, "codex"); - assert.strictEqual(status.status, "ready"); - assert.strictEqual(status.installed, true); - assert.strictEqual(status.auth.status, "unknown"); - assert.strictEqual( - status.message, - "Using a custom Codex model provider; OpenAI login check skipped.", - ); - }).pipe( - Effect.provide( - // The spawner only handles --version; if the test attempts - // "login status" the throw proves the auth probe was NOT skipped. - mockSpawnerLayer((args) => { - const joined = args.join(" "); - if (joined === "--version") return { stdout: "codex 1.0.0\n", stderr: "", code: 0 }; - throw new Error(`Auth probe should have been skipped but got args: ${joined}`); - }), - ), - ), - ); - - it.effect("still reports error when codex CLI is missing even with custom provider", () => - Effect.gen(function* () { - yield* withTempCodexHome( - [ - 'model_provider = "portkey"', - "", - "[model_providers.portkey]", - 'base_url = "https://api.portkey.ai/v1"', - 'env_key = "PORTKEY_API_KEY"', - ].join("\n"), - ); - const status = yield* checkCodexProviderStatus(); - assert.strictEqual(status.status, "error"); - assert.strictEqual(status.installed, false); - }).pipe(Effect.provide(failingSpawnerLayer("spawn codex ENOENT"))), - ); - }); - - describe("checkCodexProviderStatus with openai model provider", () => { - it.effect("still runs auth probe when model_provider is openai", () => - Effect.gen(function* () { - yield* withTempCodexHome('model_provider = "openai"\n'); - const status = yield* checkCodexProviderStatus(); - // The auth probe runs and sees "not logged in" → error - assert.strictEqual(status.status, "error"); - assert.strictEqual(status.auth.status, "unauthenticated"); - }).pipe( - Effect.provide( - mockSpawnerLayer((args) => { - const joined = args.join(" "); - if (joined === "--version") return { stdout: "codex 1.0.0\n", stderr: "", code: 0 }; - if (joined === "login status") - return { stdout: "Not logged in\n", stderr: "", code: 1 }; - throw new Error(`Unexpected args: ${joined}`); - }), - ), - ), - ); - }); - - // ── parseAuthStatusFromOutput pure tests ────────────────────────── - - describe("parseAuthStatusFromOutput", () => { - it("exit code 0 with no auth markers is ready", () => { - const parsed = parseAuthStatusFromOutput({ stdout: "OK\n", stderr: "", code: 0 }); - assert.strictEqual(parsed.status, "ready"); - assert.strictEqual(parsed.auth.status, "authenticated"); - }); - - it("JSON with authenticated=false is unauthenticated", () => { - const parsed = parseAuthStatusFromOutput({ - stdout: '[{"authenticated":false}]\n', - stderr: "", - code: 0, - }); - assert.strictEqual(parsed.status, "error"); - assert.strictEqual(parsed.auth.status, "unauthenticated"); - }); - - it("JSON without auth marker is warning", () => { - const parsed = parseAuthStatusFromOutput({ - stdout: '[{"ok":true}]\n', - stderr: "", - code: 0, - }); - assert.strictEqual(parsed.status, "warning"); - assert.strictEqual(parsed.auth.status, "unknown"); - }); - }); - - // ── readCodexConfigModelProvider tests ───────────────────────────── - - describe("readCodexConfigModelProvider", () => { - it.effect("returns undefined when config file does not exist", () => - Effect.gen(function* () { - yield* withTempCodexHome(); - assert.strictEqual(yield* readCodexConfigModelProvider(), undefined); - }), - ); - - it.effect("returns undefined when config has no model_provider key", () => - Effect.gen(function* () { - yield* withTempCodexHome('model = "gpt-5-codex"\n'); - assert.strictEqual(yield* readCodexConfigModelProvider(), undefined); - }), - ); - - it.effect("returns the provider when model_provider is set at top level", () => - Effect.gen(function* () { - yield* withTempCodexHome('model = "gpt-5-codex"\nmodel_provider = "portkey"\n'); - assert.strictEqual(yield* readCodexConfigModelProvider(), "portkey"); - }), - ); - - it.effect("returns openai when model_provider is openai", () => - Effect.gen(function* () { - yield* withTempCodexHome('model_provider = "openai"\n'); - assert.strictEqual(yield* readCodexConfigModelProvider(), "openai"); - }), - ); - - it.effect("ignores model_provider inside section headers", () => - Effect.gen(function* () { - yield* withTempCodexHome( - [ - 'model = "gpt-5-codex"', - "", - "[model_providers.portkey]", - 'base_url = "https://api.portkey.ai/v1"', - 'model_provider = "should-be-ignored"', - "", - ].join("\n"), - ); - assert.strictEqual(yield* readCodexConfigModelProvider(), undefined); - }), - ); - - it.effect("handles comments and whitespace", () => - Effect.gen(function* () { - yield* withTempCodexHome( - [ - "# This is a comment", - "", - ' model_provider = "azure" ', - "", - "[profiles.deep-review]", - 'model = "gpt-5-pro"', - ].join("\n"), - ); - assert.strictEqual(yield* readCodexConfigModelProvider(), "azure"); - }), - ); - - it.effect("handles single-quoted values in TOML", () => - Effect.gen(function* () { - yield* withTempCodexHome("model_provider = 'mistral'\n"); - assert.strictEqual(yield* readCodexConfigModelProvider(), "mistral"); - }), - ); - }); - - // ── hasCustomModelProvider tests ─────────────────────────────────── - - describe("hasCustomModelProvider", () => { - it.effect("returns false when no config file exists", () => - Effect.gen(function* () { - yield* withTempCodexHome(); - assert.strictEqual(yield* hasCustomModelProvider, false); - }), - ); - - it.effect("returns false when model_provider is not set", () => - Effect.gen(function* () { - yield* withTempCodexHome('model = "gpt-5-codex"\n'); - assert.strictEqual(yield* hasCustomModelProvider, false); - }), - ); - - it.effect("returns false when model_provider is openai", () => - Effect.gen(function* () { - yield* withTempCodexHome('model_provider = "openai"\n'); - assert.strictEqual(yield* hasCustomModelProvider, false); - }), - ); - - it.effect("returns true when model_provider is portkey", () => - Effect.gen(function* () { - yield* withTempCodexHome('model_provider = "portkey"\n'); - assert.strictEqual(yield* hasCustomModelProvider, true); - }), - ); - - it.effect("returns true when model_provider is azure", () => - Effect.gen(function* () { - yield* withTempCodexHome('model_provider = "azure"\n'); - assert.strictEqual(yield* hasCustomModelProvider, true); - }), - ); - - it.effect("returns true when model_provider is ollama", () => - Effect.gen(function* () { - yield* withTempCodexHome('model_provider = "ollama"\n'); - assert.strictEqual(yield* hasCustomModelProvider, true); - }), - ); - - it.effect("returns true when model_provider is a custom proxy", () => - Effect.gen(function* () { - yield* withTempCodexHome('model_provider = "my-company-proxy"\n'); - assert.strictEqual(yield* hasCustomModelProvider, true); - }), - ); - }); - // ── checkClaudeProviderStatus tests ────────────────────────── describe("checkClaudeProviderStatus", () => { diff --git a/apps/server/src/provider/codexAccount.ts b/apps/server/src/provider/codexAccount.ts deleted file mode 100644 index 1db00250f6..0000000000 --- a/apps/server/src/provider/codexAccount.ts +++ /dev/null @@ -1,123 +0,0 @@ -import type { ServerProviderModel } from "@t3tools/contracts"; - -export type CodexPlanType = - | "free" - | "go" - | "plus" - | "pro" - | "team" - | "business" - | "enterprise" - | "edu" - | "unknown"; - -export interface CodexAccountSnapshot { - readonly type: "apiKey" | "chatgpt" | "unknown"; - readonly planType: CodexPlanType | null; - readonly sparkEnabled: boolean; -} - -export const CODEX_DEFAULT_MODEL = "gpt-5.3-codex"; -export const CODEX_SPARK_MODEL = "gpt-5.3-codex-spark"; -const CODEX_SPARK_ENABLED_PLAN_TYPES = new Set(["pro"]); - -function asObject(value: unknown): Record | undefined { - if (!value || typeof value !== "object") { - return undefined; - } - return value as Record; -} - -function asString(value: unknown): string | undefined { - return typeof value === "string" ? value : undefined; -} - -export function readCodexAccountSnapshot(response: unknown): CodexAccountSnapshot { - const record = asObject(response); - const account = asObject(record?.account) ?? record; - const accountType = asString(account?.type); - - if (accountType === "apiKey") { - return { - type: "apiKey", - planType: null, - sparkEnabled: false, - }; - } - - if (accountType === "chatgpt") { - const planType = (account?.planType as CodexPlanType | null) ?? "unknown"; - return { - type: "chatgpt", - planType, - sparkEnabled: CODEX_SPARK_ENABLED_PLAN_TYPES.has(planType), - }; - } - - return { - type: "unknown", - planType: null, - sparkEnabled: false, - }; -} - -export function codexAuthSubType(account: CodexAccountSnapshot | undefined): string | undefined { - if (account?.type === "apiKey") { - return "apiKey"; - } - - if (account?.type !== "chatgpt") { - return undefined; - } - - return account.planType && account.planType !== "unknown" ? account.planType : "chatgpt"; -} - -export function codexAuthSubLabel(account: CodexAccountSnapshot | undefined): string | undefined { - switch (codexAuthSubType(account)) { - case "apiKey": - return "OpenAI API Key"; - case "chatgpt": - return "ChatGPT Subscription"; - case "free": - return "ChatGPT Free Subscription"; - case "go": - return "ChatGPT Go Subscription"; - case "plus": - return "ChatGPT Plus Subscription"; - case "pro": - return "ChatGPT Pro Subscription"; - case "team": - return "ChatGPT Team Subscription"; - case "business": - return "ChatGPT Business Subscription"; - case "enterprise": - return "ChatGPT Enterprise Subscription"; - case "edu": - return "ChatGPT Edu Subscription"; - default: - return undefined; - } -} - -export function adjustCodexModelsForAccount( - baseModels: ReadonlyArray, - account: CodexAccountSnapshot | undefined, -): ReadonlyArray { - if (account?.sparkEnabled !== false) { - return baseModels; - } - - return baseModels.filter((model) => model.isCustom || model.slug !== CODEX_SPARK_MODEL); -} - -export function resolveCodexModelForAccount( - model: string | undefined, - account: CodexAccountSnapshot, -): string | undefined { - if (model !== CODEX_SPARK_MODEL || account.sparkEnabled) { - return model; - } - - return CODEX_DEFAULT_MODEL; -} diff --git a/apps/server/src/provider/codexAppServer.ts b/apps/server/src/provider/codexAppServer.ts deleted file mode 100644 index 7806e135fe..0000000000 --- a/apps/server/src/provider/codexAppServer.ts +++ /dev/null @@ -1,242 +0,0 @@ -import { spawn, spawnSync, type ChildProcessWithoutNullStreams } from "node:child_process"; -import readline from "node:readline"; -import type { ServerProviderSkill } from "@t3tools/contracts"; -import { readCodexAccountSnapshot, type CodexAccountSnapshot } from "./codexAccount.ts"; -import { expandHomePath } from "../pathExpansion.ts"; - -interface JsonRpcProbeResponse { - readonly id?: unknown; - readonly result?: unknown; - readonly error?: { - readonly message?: unknown; - }; -} - -export interface CodexDiscoverySnapshot { - readonly account: CodexAccountSnapshot; - readonly skills: ReadonlyArray; -} - -function readErrorMessage(response: JsonRpcProbeResponse): string | undefined { - return typeof response.error?.message === "string" ? response.error.message : undefined; -} - -function readObject(value: unknown): Record | undefined { - return value && typeof value === "object" ? (value as Record) : undefined; -} - -function readArray(value: unknown): ReadonlyArray | undefined { - return Array.isArray(value) ? value : undefined; -} - -function readString(value: unknown): string | undefined { - return typeof value === "string" ? value : undefined; -} - -function nonEmptyTrimmed(value: unknown): string | undefined { - const candidate = readString(value)?.trim(); - return candidate ? candidate : undefined; -} - -function parseCodexSkillsResult(result: unknown, cwd: string): ReadonlyArray { - const resultRecord = readObject(result); - const dataBuckets = readArray(resultRecord?.data) ?? []; - const matchingBucket = dataBuckets.find( - (value) => nonEmptyTrimmed(readObject(value)?.cwd) === cwd, - ); - const rawSkills = - readArray(readObject(matchingBucket)?.skills) ?? readArray(resultRecord?.skills) ?? []; - - return rawSkills.flatMap((value) => { - const skill = readObject(value); - const display = readObject(skill?.interface); - const name = nonEmptyTrimmed(skill?.name); - const path = nonEmptyTrimmed(skill?.path); - if (!name || !path) { - return []; - } - - return [ - { - name, - path, - enabled: skill?.enabled !== false, - ...(nonEmptyTrimmed(skill?.description) - ? { description: nonEmptyTrimmed(skill?.description) } - : {}), - ...(nonEmptyTrimmed(skill?.scope) ? { scope: nonEmptyTrimmed(skill?.scope) } : {}), - ...(nonEmptyTrimmed(display?.displayName) - ? { displayName: nonEmptyTrimmed(display?.displayName) } - : {}), - ...(nonEmptyTrimmed(skill?.shortDescription) || nonEmptyTrimmed(display?.shortDescription) - ? { - shortDescription: - nonEmptyTrimmed(skill?.shortDescription) ?? - nonEmptyTrimmed(display?.shortDescription), - } - : {}), - } satisfies ServerProviderSkill, - ]; - }); -} - -export function buildCodexInitializeParams() { - return { - clientInfo: { - name: "t3code_desktop", - title: "T3 Code Desktop", - version: "0.1.0", - }, - capabilities: { - experimentalApi: true, - }, - } as const; -} - -export function killCodexChildProcess(child: ChildProcessWithoutNullStreams): void { - if (process.platform === "win32" && child.pid !== undefined) { - try { - spawnSync("taskkill", ["/pid", String(child.pid), "/T", "/F"], { stdio: "ignore" }); - return; - } catch { - // Fall through to direct kill when taskkill is unavailable. - } - } - - child.kill(); -} - -export async function probeCodexDiscovery(input: { - readonly binaryPath: string; - readonly homePath?: string; - readonly cwd: string; - readonly signal?: AbortSignal; -}): Promise { - return await new Promise((resolve, reject) => { - const child = spawn(input.binaryPath, ["app-server"], { - env: { - ...process.env, - ...(input.homePath ? { CODEX_HOME: expandHomePath(input.homePath) } : {}), - }, - stdio: ["pipe", "pipe", "pipe"], - shell: process.platform === "win32", - }); - const output = readline.createInterface({ input: child.stdout }); - - let completed = false; - let account: CodexAccountSnapshot | undefined; - let skills: ReadonlyArray | undefined; - - const cleanup = () => { - output.removeAllListeners(); - output.close(); - child.removeAllListeners(); - if (!child.killed) { - killCodexChildProcess(child); - } - }; - - const finish = (callback: () => void) => { - if (completed) return; - completed = true; - cleanup(); - callback(); - }; - - const fail = (error: unknown) => - finish(() => - reject( - error instanceof Error - ? error - : new Error(`Codex discovery probe failed: ${String(error)}.`), - ), - ); - - const maybeResolve = () => { - if (account && skills !== undefined) { - const resolvedAccount = account; - const resolvedSkills = skills; - finish(() => resolve({ account: resolvedAccount, skills: resolvedSkills })); - } - }; - - if (input.signal?.aborted) { - fail(new Error("Codex discovery probe aborted.")); - return; - } - input.signal?.addEventListener("abort", () => - fail(new Error("Codex discovery probe aborted.")), - ); - - const writeMessage = (message: unknown) => { - if (!child.stdin.writable) { - fail(new Error("Cannot write to codex app-server stdin.")); - return; - } - - child.stdin.write(`${JSON.stringify(message)}\n`); - }; - - output.on("line", (line) => { - let parsed: unknown; - try { - parsed = JSON.parse(line); - } catch { - fail(new Error("Received invalid JSON from codex app-server during discovery probe.")); - return; - } - - if (!parsed || typeof parsed !== "object") { - return; - } - - const response = parsed as JsonRpcProbeResponse; - if (response.id === 1) { - const errorMessage = readErrorMessage(response); - if (errorMessage) { - fail(new Error(`initialize failed: ${errorMessage}`)); - return; - } - - writeMessage({ method: "initialized" }); - writeMessage({ id: 2, method: "skills/list", params: { cwds: [input.cwd] } }); - writeMessage({ id: 3, method: "account/read", params: {} }); - return; - } - - if (response.id === 2) { - const errorMessage = readErrorMessage(response); - skills = errorMessage ? [] : parseCodexSkillsResult(response.result, input.cwd); - maybeResolve(); - return; - } - - if (response.id === 3) { - const errorMessage = readErrorMessage(response); - if (errorMessage) { - fail(new Error(`account/read failed: ${errorMessage}`)); - return; - } - - account = readCodexAccountSnapshot(response.result); - maybeResolve(); - } - }); - - child.once("error", fail); - child.once("exit", (code, signal) => { - if (completed) return; - fail( - new Error( - `codex app-server exited before probe completed (code=${code ?? "null"}, signal=${signal ?? "null"}).`, - ), - ); - }); - - writeMessage({ - id: 1, - method: "initialize", - params: buildCodexInitializeParams(), - }); - }); -} diff --git a/apps/server/src/provider/codexCliVersion.ts b/apps/server/src/provider/codexCliVersion.ts deleted file mode 100644 index 33f7cf85d2..0000000000 --- a/apps/server/src/provider/codexCliVersion.ts +++ /dev/null @@ -1,25 +0,0 @@ -import { compareCliVersions, normalizeCliVersion } from "./cliVersion.ts"; - -const CODEX_VERSION_PATTERN = /\bv?(\d+\.\d+(?:\.\d+)?(?:-[0-9A-Za-z.-]+)?)\b/; - -export const MINIMUM_CODEX_CLI_VERSION = "0.37.0"; - -export const compareCodexCliVersions = compareCliVersions; - -export function parseCodexCliVersion(output: string): string | null { - const match = CODEX_VERSION_PATTERN.exec(output); - if (!match?.[1]) { - return null; - } - - return normalizeCliVersion(match[1]); -} - -export function isCodexCliVersionSupported(version: string): boolean { - return compareCodexCliVersions(version, MINIMUM_CODEX_CLI_VERSION) >= 0; -} - -export function formatCodexCliUpgradeMessage(version: string | null): string { - const versionLabel = version ? `v${version}` : "the installed version"; - return `Codex CLI ${versionLabel} is too old for T3 Code. Upgrade to v${MINIMUM_CODEX_CLI_VERSION} or newer and restart T3 Code.`; -} diff --git a/apps/web/src/session-logic.test.ts b/apps/web/src/session-logic.test.ts index bee0fd0029..baf384d6af 100644 --- a/apps/web/src/session-logic.test.ts +++ b/apps/web/src/session-logic.test.ts @@ -11,7 +11,6 @@ import { deriveCompletionDividerBeforeEntryId, deriveActiveWorkStartedAt, deriveActivePlanState, - PROVIDER_OPTIONS, derivePendingApprovals, derivePendingUserInputs, deriveTimelineEntries, diff --git a/bun.lock b/bun.lock index 35d9915b41..e9b7511e34 100644 --- a/bun.lock +++ b/bun.lock @@ -67,6 +67,7 @@ "@types/bun": "catalog:", "@types/node": "catalog:", "effect-acp": "workspace:*", + "effect-codex-app-server": "workspace:*", "tsdown": "catalog:", "typescript": "catalog:", "vitest": "catalog:", @@ -166,6 +167,21 @@ "vitest": "catalog:", }, }, + "packages/effect-codex-app-server": { + "name": "effect-codex-app-server", + "dependencies": { + "effect": "catalog:", + }, + "devDependencies": { + "@effect/language-service": "catalog:", + "@effect/openapi-generator": "catalog:", + "@effect/platform-node": "catalog:", + "@effect/vitest": "catalog:", + "tsdown": "catalog:", + "typescript": "catalog:", + "vitest": "catalog:", + }, + }, "packages/shared": { "name": "@t3tools/shared", "version": "0.0.0-alpha.1", @@ -1083,6 +1099,8 @@ "effect-acp": ["effect-acp@workspace:packages/effect-acp"], + "effect-codex-app-server": ["effect-codex-app-server@workspace:packages/effect-codex-app-server"], + "electron": ["electron@40.6.0", "", { "dependencies": { "@electron/get": "^2.0.0", "@types/node": "^24.9.0", "extract-zip": "^2.0.1" }, "bin": { "electron": "cli.js" } }, "sha512-ett8W+yOFGDuM0vhJMamYSkrbV3LoaffzJd9GfjI96zRAxyrNqUSKqBpf/WGbQCweDxX2pkUCUfrv4wwKpsFZA=="], "electron-to-chromium": ["electron-to-chromium@1.5.313", "", {}, "sha512-QBMrTWEf00GXZmJyx2lbYD45jpI3TUFnNIzJ5BBc8piGUDwMPa1GV6HJWTZVvY/eiN3fSopl7NRbgGp9sZ9LTA=="], diff --git a/packages/effect-acp/src/_internal/stdio.ts b/packages/effect-acp/src/_internal/stdio.ts index b175756892..8ddb4d37d0 100644 --- a/packages/effect-acp/src/_internal/stdio.ts +++ b/packages/effect-acp/src/_internal/stdio.ts @@ -9,7 +9,6 @@ import { ChildProcessSpawner } from "effect/unstable/process"; import * as AcpError from "../errors.ts"; const encoder = new TextEncoder(); -const decoder = new TextDecoder(); export const makeChildStdio = (handle: ChildProcessSpawner.ChildProcessHandle) => Stdio.make({ @@ -25,6 +24,7 @@ export const makeChildStdio = (handle: ChildProcessSpawner.ChildProcessHandle) = export const makeInMemoryStdio = Effect.fn("makeInMemoryStdio")(function* () { const input = yield* Queue.unbounded>(); const output = yield* Queue.unbounded(); + const decoder = new TextDecoder(); return { stdio: Stdio.make({ @@ -32,7 +32,10 @@ export const makeInMemoryStdio = Effect.fn("makeInMemoryStdio")(function* () { stdin: Stream.fromQueue(input), stdout: () => Sink.forEach((chunk: string | Uint8Array) => - Queue.offer(output, typeof chunk === "string" ? chunk : decoder.decode(chunk)), + Queue.offer( + output, + typeof chunk === "string" ? chunk : decoder.decode(chunk, { stream: true }), + ), ), stderr: () => Sink.drain, }), diff --git a/packages/effect-codex-app-server/package.json b/packages/effect-codex-app-server/package.json new file mode 100644 index 0000000000..01249f5608 --- /dev/null +++ b/packages/effect-codex-app-server/package.json @@ -0,0 +1,48 @@ +{ + "name": "effect-codex-app-server", + "private": true, + "type": "module", + "exports": { + "./client": { + "types": "./src/client.ts", + "import": "./src/client.ts" + }, + "./schema": { + "types": "./src/schema.ts", + "import": "./src/schema.ts" + }, + "./rpc": { + "types": "./src/rpc.ts", + "import": "./src/rpc.ts" + }, + "./protocol": { + "types": "./src/protocol.ts", + "import": "./src/protocol.ts" + }, + "./errors": { + "types": "./src/errors.ts", + "import": "./src/errors.ts" + } + }, + "scripts": { + "dev": "tsdown src/client.ts src/rpc.ts src/protocol.ts src/schema.ts --format esm,cjs --dts --watch --clean", + "build": "tsdown src/client.ts src/rpc.ts src/protocol.ts src/schema.ts --format esm,cjs --dts --clean", + "prepare": "effect-language-service patch", + "typecheck": "tsc --noEmit", + "test": "vitest run", + "generate": "bun run scripts/generate.ts", + "probe": "bun run test/examples/codex-app-server-probe.ts" + }, + "dependencies": { + "effect": "catalog:" + }, + "devDependencies": { + "@effect/language-service": "catalog:", + "@effect/openapi-generator": "catalog:", + "@effect/platform-node": "catalog:", + "@effect/vitest": "catalog:", + "tsdown": "catalog:", + "typescript": "catalog:", + "vitest": "catalog:" + } +} diff --git a/packages/effect-codex-app-server/scripts/generate.ts b/packages/effect-codex-app-server/scripts/generate.ts new file mode 100644 index 0000000000..5f0991c39f --- /dev/null +++ b/packages/effect-codex-app-server/scripts/generate.ts @@ -0,0 +1,772 @@ +#!/usr/bin/env node + +import * as NodeRuntime from "@effect/platform-node/NodeRuntime"; +import * as NodeServices from "@effect/platform-node/NodeServices"; +import { make as makeJsonSchemaGenerator } from "@effect/openapi-generator/JsonSchemaGenerator"; +import { Effect, FileSystem, Layer, Logger, Path, Schema } from "effect"; +import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process"; + +const UPSTREAM_REF = "dbfe855f4fd0f5dcdf079882652a8efe622b0595"; +const USER_AGENT = "effect-codex-app-server-generator"; +const GITHUB_API_BASE = + "https://api.github.com/repos/openai/codex/contents/codex-rs/app-server-protocol"; + +const GithubContentEntries = Schema.Array( + Schema.Struct({ + name: Schema.String, + path: Schema.String, + download_url: Schema.NullOr(Schema.String), + type: Schema.String, + }), +); +type GithubContentEntry = (typeof GithubContentEntries.Type)[number]; + +interface GeneratedPaths { + readonly generatedDir: string; + readonly schemaOutputPath: string; + readonly metaOutputPath: string; + readonly namespacesOutputPath: string; +} + +interface MethodEntry { + readonly method: string; + readonly paramsType?: string; +} + +interface JsonSchemaFile { + readonly namespace?: string; + readonly exportName: string; + readonly fileName: string; + readonly downloadUrl: string; + readonly qualifiedName: string; +} + +class GeneratorError extends Schema.TaggedErrorClass()("GeneratorError", { + detail: Schema.String, + cause: Schema.optional(Schema.Defect), +}) { + override get message() { + return this.detail; + } +} + +const ManualSchemas: Record = { + GetAuthStatusParams: { + type: "object", + title: "GetAuthStatusParams", + properties: { + includeToken: { + anyOf: [{ type: "boolean" }, { type: "null" }], + }, + refreshToken: { + anyOf: [{ type: "boolean" }, { type: "null" }], + }, + }, + }, + GetConversationSummaryParams: { + title: "GetConversationSummaryParams", + oneOf: [ + { + type: "object", + properties: { + rolloutPath: { type: "string" }, + }, + required: ["rolloutPath"], + }, + { + type: "object", + properties: { + conversationId: { type: "string" }, + }, + required: ["conversationId"], + }, + ], + }, + GetConversationSummaryResponse: { + type: "object", + title: "GetConversationSummaryResponse", + properties: { + summary: {}, + }, + required: ["summary"], + }, + GitDiffToRemoteParams: { + type: "object", + title: "GitDiffToRemoteParams", + properties: { + cwd: { type: "string" }, + }, + required: ["cwd"], + }, + GitDiffToRemoteResponse: { + type: "object", + title: "GitDiffToRemoteResponse", + properties: { + sha: { type: "string" }, + diff: { type: "string" }, + }, + required: ["sha", "diff"], + }, + GetAuthStatusResponse: { + type: "object", + title: "GetAuthStatusResponse", + properties: { + authMethod: { + anyOf: [{}, { type: "null" }], + }, + authToken: { + anyOf: [{ type: "string" }, { type: "null" }], + }, + requiresOpenaiAuth: { + anyOf: [{ type: "boolean" }, { type: "null" }], + }, + }, + required: ["authMethod", "authToken", "requiresOpenaiAuth"], + }, +}; + +const getGeneratedPaths = Effect.fn("getGeneratedPaths")(function* () { + const path = yield* Path.Path; + const generatedDir = path.join(import.meta.dirname, "..", "src", "_generated"); + return { + generatedDir, + schemaOutputPath: path.join(generatedDir, "schema.gen.ts"), + metaOutputPath: path.join(generatedDir, "meta.gen.ts"), + namespacesOutputPath: path.join(generatedDir, "namespaces.gen.ts"), + } satisfies GeneratedPaths; +}); + +const ensureGeneratedDir = Effect.fn("ensureGeneratedDir")(function* () { + const fs = yield* FileSystem.FileSystem; + const { generatedDir } = yield* getGeneratedPaths(); + yield* fs.makeDirectory(generatedDir, { recursive: true }); +}); + +const fetchText = Effect.fn("fetchText")(function* (url: string) { + const response = yield* Effect.tryPromise({ + try: () => + fetch(url, { + headers: { + "user-agent": USER_AGENT, + }, + }), + catch: (cause) => + new GeneratorError({ + detail: `Failed to fetch ${url}`, + cause, + }), + }); + + if (!response.ok) { + const detail = yield* Effect.tryPromise({ + try: () => response.text(), + catch: () => "", + }); + return yield* Effect.fail( + new GeneratorError({ + detail: `Failed to download ${url}: ${response.status} ${detail}`, + }), + ); + } + + return yield* Effect.tryPromise({ + try: () => response.text(), + catch: (cause) => + new GeneratorError({ + detail: `Failed to read response body for ${url}`, + cause, + }), + }); +}); + +const fetchDirectoryEntries = Effect.fn("fetchDirectoryEntries")(function* (path: string) { + const raw = yield* fetchText(`${GITHUB_API_BASE}/${path}?ref=${UPSTREAM_REF}`); + return yield* Schema.decodeEffect(Schema.fromJsonString(GithubContentEntries))(raw); +}); + +function collectSchemaEntries( + chunk: string, +): ReadonlyArray<{ readonly name: string; readonly code: string }> { + const lines = chunk + .split("\n") + .map((line) => line.trim()) + .filter((line) => line.length > 0 && !line.startsWith("//")); + const entries: Array<{ name: string; code: string }> = []; + + for (let index = 0; index < lines.length; index += 1) { + const typeLine = lines[index]; + if (!typeLine?.startsWith("export type ")) { + continue; + } + + const constLine = lines[index + 1]; + if (!constLine?.startsWith("export const ")) { + throw new Error(`Malformed generator output near: ${typeLine}`); + } + + const match = /^export type ([A-Za-z0-9_]+)/.exec(typeLine); + if (!match?.[1]) { + throw new Error(`Could not extract schema name from: ${typeLine}`); + } + + entries.push({ + name: match[1], + code: `${typeLine}\n${constLine}`, + }); + index += 1; + } + + return entries; +} + +function normalizeNullableTypes(value: typeof Schema.Json.Type): typeof Schema.Json.Type { + if (Array.isArray(value)) { + return value.map(normalizeNullableTypes); + } + if (value === null || typeof value !== "object") { + return value; + } + + const normalizedEntries = Object.entries(value).map(([key, child]) => [ + key, + normalizeNullableTypes(child), + ]); + const normalizedObject = Object.fromEntries(normalizedEntries) as Record< + string, + typeof Schema.Json.Type + >; + const typeValue = normalizedObject.type; + + if (!Array.isArray(typeValue)) { + return normalizedObject; + } + + const normalizedTypes = typeValue.filter((entry): entry is string => typeof entry === "string"); + if (normalizedTypes.length !== typeValue.length || !normalizedTypes.includes("null")) { + return normalizedObject; + } + + const nonNullTypes = normalizedTypes.filter((entry) => entry !== "null"); + if (nonNullTypes.length !== 1) { + return normalizedObject; + } + const nonNullType = nonNullTypes[0]!; + + const nextObject: Record = {}; + for (const [key, child] of Object.entries(normalizedObject)) { + if (key !== "type") { + nextObject[key] = child; + } + } + + return { + anyOf: [ + { + ...nextObject, + type: nonNullType, + }, + { type: "null" }, + ], + }; +} + +function stripNullDefaults(value: typeof Schema.Json.Type): typeof Schema.Json.Type { + if (Array.isArray(value)) { + return value.map(stripNullDefaults); + } + if (value === null || typeof value !== "object") { + return value; + } + + return Object.fromEntries( + Object.entries(value) + .filter(([key, child]) => !(key === "default" && child === null)) + .map(([key, child]) => [key, stripNullDefaults(child)]), + ) as typeof Schema.Json.Type; +} + +function toPascalCaseMethod(method: string) { + return method + .split("/") + .flatMap((segment) => segment.split(/(?=[A-Z])/)) + .flatMap((segment) => segment.split(/[-_]/)) + .filter(Boolean) + .map((segment) => segment[0]!.toUpperCase() + segment.slice(1)) + .join(""); +} + +function parseRequestEntries(fileContents: string): ReadonlyArray { + const entryPattern = /\{\s*"method":\s*"([^"]+)",\s*id:\s*RequestId,\s*params:\s*([^,}]+)/g; + const entries: Array = []; + let match: RegExpExecArray | null; + while ((match = entryPattern.exec(fileContents)) !== null) { + entries.push({ + method: match[1]!, + paramsType: match[2]!.trim(), + }); + } + return entries; +} + +function parseNotificationEntries(fileContents: string): ReadonlyArray { + const entryPattern = /\{\s*"method":\s*"([^"]+)"(?:,\s*"params":\s*([^ }]+))?\s*\}/g; + const entries: Array = []; + let match: RegExpExecArray | null; + while ((match = entryPattern.exec(fileContents)) !== null) { + entries.push({ + method: match[1]!, + ...(match[2] ? { paramsType: match[2].trim() } : {}), + }); + } + return entries; +} + +function resolveSchemaTypeName( + rawTypeName: string, + generatedSchemaNames: ReadonlySet, +): string { + if (rawTypeName === "undefined") { + return "undefined"; + } + + const candidates = [ + rawTypeName, + `V2${rawTypeName}`, + `V1${rawTypeName}`, + `SerdeJson${rawTypeName}`, + ]; + for (const candidate of candidates) { + if (generatedSchemaNames.has(candidate)) { + return candidate; + } + } + + throw new Error(`Unable to resolve schema type name: ${rawTypeName}`); +} + +function resolveResponseTypeName( + method: string, + paramsType: string | undefined, + generatedSchemaNames: ReadonlySet, +): string { + const overrides: Record = { + "account/logout": "LogoutAccountResponse", + "account/rateLimits/read": "GetAccountRateLimitsResponse", + "config/batchWrite": "ConfigWriteResponse", + "config/mcpServer/reload": "McpServerRefreshResponse", + "config/value/write": "ConfigWriteResponse", + "configRequirements/read": "ConfigRequirementsReadResponse", + }; + + const override = overrides[method]; + if (override) { + return resolveSchemaTypeName(override, generatedSchemaNames); + } + + if (paramsType && paramsType !== "undefined") { + const fromParams = paramsType.replace(/Params$/, "Response"); + try { + return resolveSchemaTypeName(fromParams, generatedSchemaNames); + } catch { + // Fall through to method-based lookup. + } + } + + return resolveSchemaTypeName(`${toPascalCaseMethod(method)}Response`, generatedSchemaNames); +} + +function renderMethodConstants(constantName: string, entries: ReadonlyArray) { + return [ + `export const ${constantName} = {`, + ...entries.map( + (entry) => ` ${JSON.stringify(entry.method)}: ${JSON.stringify(entry.method)},`, + ), + "} as const;", + "", + ].join("\n"); +} + +function renderTypeInterface( + interfaceName: string, + entries: ReadonlyArray, + typeName: (entry: MethodEntry) => string, +) { + return [ + `export interface ${interfaceName} {`, + ...entries.map((entry) => ` readonly ${JSON.stringify(entry.method)}: ${typeName(entry)};`), + "}", + "", + ].join("\n"); +} + +function renderSchemaMap( + constantName: string, + entries: ReadonlyArray, + typeName: (entry: MethodEntry) => string, +) { + return [ + `export const ${constantName} = {`, + ...entries.map((entry) => { + const schemaName = typeName(entry); + return ` ${JSON.stringify(entry.method)}: ${ + schemaName === "undefined" ? "undefined" : `CodexSchema.${schemaName}` + },`; + }), + "} as const;", + "", + ].join("\n"); +} + +function renderSchemaTypeReference(schemaName: string) { + return schemaName === "undefined" ? "undefined" : `typeof CodexSchema.${schemaName}.Type`; +} + +function exportNameForPath(filePath: string): string { + const relative = filePath.replace(/^schema\/json\//, "").replace(/\.json$/, ""); + if (!relative.includes("/")) { + return relative; + } + + const [namespace, name] = relative.split("/", 2) as [string, string]; + const namespacePrefix = namespace + .split(/[^A-Za-z0-9]+/) + .filter(Boolean) + .map((segment) => segment[0]!.toUpperCase() + segment.slice(1)) + .join(""); + return `${namespacePrefix}${name}`; +} + +function buildJsonSchemaFiles( + entries: ReadonlyArray, +): ReadonlyArray { + return entries + .filter( + (entry) => + entry.type === "file" && + entry.name.endsWith(".json") && + entry.download_url !== null && + !entry.name.startsWith("codex_app_server_protocol."), + ) + .map((entry) => { + const relative = entry.path.replace(/^codex-rs\/app-server-protocol\/schema\/json\//, ""); + const parts = relative.split("/"); + if (parts.length > 1) { + return { + namespace: parts[0]!, + exportName: exportNameForPath(relative), + fileName: entry.name, + downloadUrl: entry.download_url!, + qualifiedName: relative.replace(/\.json$/, ""), + } satisfies JsonSchemaFile; + } + return { + exportName: exportNameForPath(relative), + fileName: entry.name, + downloadUrl: entry.download_url!, + qualifiedName: relative.replace(/\.json$/, ""), + } satisfies JsonSchemaFile; + }); +} + +function rewriteExternalRefs( + value: typeof Schema.Json.Type, + localDefinitionNames: ReadonlyMap, + currentNamespace: string | undefined, + exportNameByQualifiedName: ReadonlyMap, +): typeof Schema.Json.Type { + if (Array.isArray(value)) { + return value.map((entry) => + rewriteExternalRefs(entry, localDefinitionNames, currentNamespace, exportNameByQualifiedName), + ); + } + if (value === null || typeof value !== "object") { + return value; + } + + return Object.fromEntries( + Object.entries(value).map(([key, child]) => { + if (key === "$ref" && typeof child === "string" && child.startsWith("#/definitions/")) { + const definitionName = child.slice("#/definitions/".length); + const localRewrite = localDefinitionNames.get(definitionName); + if (localRewrite) { + return [key, `#/definitions/${localRewrite}`]; + } + + const candidates = [ + ...(currentNamespace ? [`${currentNamespace}/${definitionName}`] : []), + definitionName, + definitionName.replace(/^v[12]\//, ""), + definitionName.replace(/^serde_json\//, ""), + `v2/${definitionName}`, + `v1/${definitionName}`, + `serde_json/${definitionName}`, + ]; + + const rewritten = candidates + .map((candidate) => exportNameByQualifiedName.get(candidate)) + .find((candidate) => candidate !== undefined); + + if (!rewritten) { + throw new Error(`Missing rewritten definition for ref: ${child}`); + } + + return [key, `#/definitions/${rewritten}`]; + } + + return [ + key, + rewriteExternalRefs( + child, + localDefinitionNames, + currentNamespace, + exportNameByQualifiedName, + ), + ]; + }), + ) as typeof Schema.Json.Type; +} + +const generateFiles = Effect.fn("generateFiles")(function* () { + yield* ensureGeneratedDir(); + + const [rootJsonEntries, v1JsonEntries, v2JsonEntries] = yield* Effect.all([ + fetchDirectoryEntries("schema/json"), + fetchDirectoryEntries("schema/json/v1"), + fetchDirectoryEntries("schema/json/v2"), + ]); + + const jsonSchemaFiles = [ + ...buildJsonSchemaFiles(rootJsonEntries), + ...buildJsonSchemaFiles(v1JsonEntries), + ...buildJsonSchemaFiles(v2JsonEntries), + ].toSorted((left, right) => left.exportName.localeCompare(right.exportName)); + + const exportNameByQualifiedName = new Map( + jsonSchemaFiles.map((file) => [file.qualifiedName, file.exportName]), + ); + const aggregateSchemas: Record = {}; + + for (const file of jsonSchemaFiles) { + const raw = yield* fetchText(file.downloadUrl); + const parsed = JSON.parse(raw) as { + readonly definitions?: Record; + } & Record; + const localDefinitionNames = new Map( + Object.keys(parsed.definitions ?? {}).map((definitionName) => [ + definitionName, + `${file.exportName}__${definitionName.replace(/[^A-Za-z0-9]/g, "")}`, + ]), + ); + + for (const [definitionName, definitionSchema] of Object.entries(parsed.definitions ?? {})) { + aggregateSchemas[localDefinitionNames.get(definitionName)!] = stripNullDefaults( + normalizeNullableTypes( + rewriteExternalRefs( + definitionSchema, + localDefinitionNames, + file.namespace, + exportNameByQualifiedName, + ), + ), + ); + } + + const topLevelSchema: Record = {}; + for (const [key, value] of Object.entries(parsed)) { + if (key !== "definitions") { + topLevelSchema[key] = value; + } + } + + aggregateSchemas[file.exportName] = stripNullDefaults( + normalizeNullableTypes( + rewriteExternalRefs( + topLevelSchema, + localDefinitionNames, + file.namespace, + exportNameByQualifiedName, + ), + ), + ); + } + + for (const [name, schema] of Object.entries(ManualSchemas)) { + if (!(name in aggregateSchemas)) { + aggregateSchemas[name] = stripNullDefaults(normalizeNullableTypes(schema)); + } + } + + const generator = makeJsonSchemaGenerator(); + for (const [name, schema] of Object.entries(aggregateSchemas).toSorted(([left], [right]) => + left.localeCompare(right), + )) { + generator.addSchema(name, schema as never); + } + + const generatedEntries = new Map(); + const output = generator.generate("openapi-3.1", aggregateSchemas as never, false).trim(); + if (output.length > 0) { + for (const entry of collectSchemaEntries(output)) { + if (!generatedEntries.has(entry.name)) { + generatedEntries.set(entry.name, entry.code); + } + } + } + + const generatedSchemaNames = new Set(generatedEntries.keys()); + const clientRequestRaw = yield* fetchText( + `https://raw.githubusercontent.com/openai/codex/${UPSTREAM_REF}/codex-rs/app-server-protocol/schema/typescript/ClientRequest.ts`, + ); + const clientNotificationRaw = yield* fetchText( + `https://raw.githubusercontent.com/openai/codex/${UPSTREAM_REF}/codex-rs/app-server-protocol/schema/typescript/ClientNotification.ts`, + ); + const serverRequestRaw = yield* fetchText( + `https://raw.githubusercontent.com/openai/codex/${UPSTREAM_REF}/codex-rs/app-server-protocol/schema/typescript/ServerRequest.ts`, + ); + const serverNotificationRaw = yield* fetchText( + `https://raw.githubusercontent.com/openai/codex/${UPSTREAM_REF}/codex-rs/app-server-protocol/schema/typescript/ServerNotification.ts`, + ); + + const clientRequestEntries = parseRequestEntries(clientRequestRaw); + const clientNotificationEntries = parseNotificationEntries(clientNotificationRaw); + const serverRequestEntries = parseRequestEntries(serverRequestRaw); + const serverNotificationEntries = parseNotificationEntries(serverNotificationRaw); + + const prelude = [ + "// This file is generated by the effect-codex-app-server package. Do not edit manually.", + `// Upstream protocol ref: ${UPSTREAM_REF}`, + "", + ]; + + const schemaOutput = [ + ...prelude, + 'import * as Schema from "effect/Schema";', + "", + [...generatedEntries.values()].join("\n\n"), + "", + ].join("\n"); + + const metaOutput = [ + ...prelude, + 'import * as CodexSchema from "./schema.gen.ts";', + "", + renderMethodConstants("CLIENT_REQUEST_METHODS", clientRequestEntries), + renderMethodConstants("CLIENT_NOTIFICATION_METHODS", clientNotificationEntries), + renderMethodConstants("SERVER_REQUEST_METHODS", serverRequestEntries), + renderMethodConstants("SERVER_NOTIFICATION_METHODS", serverNotificationEntries), + "export type ClientRequestMethod = keyof typeof CLIENT_REQUEST_METHODS;", + "export type ClientNotificationMethod = keyof typeof CLIENT_NOTIFICATION_METHODS;", + "export type ServerRequestMethod = keyof typeof SERVER_REQUEST_METHODS;", + "export type ServerNotificationMethod = keyof typeof SERVER_NOTIFICATION_METHODS;", + "", + renderTypeInterface("ClientRequestParamsByMethod", clientRequestEntries, (entry) => + renderSchemaTypeReference( + resolveSchemaTypeName(entry.paramsType ?? "undefined", generatedSchemaNames), + ), + ), + renderTypeInterface("ClientRequestResponsesByMethod", clientRequestEntries, (entry) => + renderSchemaTypeReference( + resolveResponseTypeName(entry.method, entry.paramsType, generatedSchemaNames), + ), + ), + renderTypeInterface("ClientNotificationParamsByMethod", clientNotificationEntries, (entry) => + renderSchemaTypeReference( + resolveSchemaTypeName(entry.paramsType ?? "undefined", generatedSchemaNames), + ), + ), + renderTypeInterface("ServerRequestParamsByMethod", serverRequestEntries, (entry) => + renderSchemaTypeReference( + resolveSchemaTypeName(entry.paramsType ?? "undefined", generatedSchemaNames), + ), + ), + renderTypeInterface("ServerRequestResponsesByMethod", serverRequestEntries, (entry) => + renderSchemaTypeReference( + resolveResponseTypeName(entry.method, entry.paramsType, generatedSchemaNames), + ), + ), + renderTypeInterface("ServerNotificationParamsByMethod", serverNotificationEntries, (entry) => + renderSchemaTypeReference( + resolveSchemaTypeName(entry.paramsType ?? "undefined", generatedSchemaNames), + ), + ), + renderSchemaMap("CLIENT_REQUEST_PARAMS", clientRequestEntries, (entry) => + resolveSchemaTypeName(entry.paramsType ?? "undefined", generatedSchemaNames), + ), + renderSchemaMap("CLIENT_REQUEST_RESPONSES", clientRequestEntries, (entry) => + resolveResponseTypeName(entry.method, entry.paramsType, generatedSchemaNames), + ), + renderSchemaMap("CLIENT_NOTIFICATION_PARAMS", clientNotificationEntries, (entry) => + resolveSchemaTypeName(entry.paramsType ?? "undefined", generatedSchemaNames), + ), + renderSchemaMap("SERVER_REQUEST_PARAMS", serverRequestEntries, (entry) => + resolveSchemaTypeName(entry.paramsType ?? "undefined", generatedSchemaNames), + ), + renderSchemaMap("SERVER_REQUEST_RESPONSES", serverRequestEntries, (entry) => + resolveResponseTypeName(entry.method, entry.paramsType, generatedSchemaNames), + ), + renderSchemaMap("SERVER_NOTIFICATION_PARAMS", serverNotificationEntries, (entry) => + resolveSchemaTypeName(entry.paramsType ?? "undefined", generatedSchemaNames), + ), + ].join("\n"); + + const namespaceGroups = new Map>(); + for (const file of jsonSchemaFiles) { + if (!file.namespace) { + continue; + } + const current = namespaceGroups.get(file.namespace) ?? []; + current.push(file); + namespaceGroups.set(file.namespace, current); + } + + const namespacesOutput = [ + ...prelude, + 'import * as CodexSchema from "./schema.gen.ts";', + "", + ...[...namespaceGroups.entries()] + .toSorted(([left], [right]) => left.localeCompare(right)) + .map(([namespace, files]) => { + const constantName = namespace.replace(/[^A-Za-z0-9]/g, ""); + return [ + `export const ${constantName} = {`, + ...files + .toSorted((left, right) => left.fileName.localeCompare(right.fileName)) + .map( + (file) => + ` ${JSON.stringify(file.fileName.replace(/\.json$/, ""))}: CodexSchema.${file.exportName},`, + ), + "} as const;", + "", + ].join("\n"); + }), + ].join("\n"); + + const fs = yield* FileSystem.FileSystem; + const { generatedDir, metaOutputPath, namespacesOutputPath, schemaOutputPath } = + yield* getGeneratedPaths(); + yield* fs.writeFileString(schemaOutputPath, schemaOutput); + yield* fs.writeFileString(metaOutputPath, metaOutput); + yield* fs.writeFileString(namespacesOutputPath, namespacesOutput); + + yield* Effect.log(`Generated Codex App Server schemas from ${UPSTREAM_REF}`); + + yield* Effect.service(ChildProcessSpawner.ChildProcessSpawner).pipe( + Effect.flatMap((spawner) => spawner.spawn(ChildProcess.make("bun", ["oxfmt", generatedDir]))), + Effect.flatMap((child) => child.exitCode), + Effect.tap((code) => + code === 0 + ? Effect.void + : Effect.fail( + new GeneratorError({ + detail: `oxfmt failed with exit code ${code}`, + }), + ), + ), + ); +}); + +generateFiles().pipe( + Effect.scoped, + Effect.provide(Layer.mergeAll(Logger.layer([Logger.consolePretty()]), NodeServices.layer)), + NodeRuntime.runMain, +); diff --git a/packages/effect-codex-app-server/src/_generated/meta.gen.ts b/packages/effect-codex-app-server/src/_generated/meta.gen.ts new file mode 100644 index 0000000000..d0b7376495 --- /dev/null +++ b/packages/effect-codex-app-server/src/_generated/meta.gen.ts @@ -0,0 +1,585 @@ +// This file is generated by the effect-codex-app-server package. Do not edit manually. +// Upstream protocol ref: dbfe855f4fd0f5dcdf079882652a8efe622b0595 + +import * as CodexSchema from "./schema.gen.ts"; + +export const CLIENT_REQUEST_METHODS = { + initialize: "initialize", + "thread/start": "thread/start", + "thread/resume": "thread/resume", + "thread/fork": "thread/fork", + "thread/archive": "thread/archive", + "thread/unsubscribe": "thread/unsubscribe", + "thread/name/set": "thread/name/set", + "thread/metadata/update": "thread/metadata/update", + "thread/unarchive": "thread/unarchive", + "thread/compact/start": "thread/compact/start", + "thread/shellCommand": "thread/shellCommand", + "thread/rollback": "thread/rollback", + "thread/list": "thread/list", + "thread/loaded/list": "thread/loaded/list", + "thread/read": "thread/read", + "skills/list": "skills/list", + "plugin/list": "plugin/list", + "plugin/read": "plugin/read", + "app/list": "app/list", + "fs/readFile": "fs/readFile", + "fs/writeFile": "fs/writeFile", + "fs/createDirectory": "fs/createDirectory", + "fs/getMetadata": "fs/getMetadata", + "fs/readDirectory": "fs/readDirectory", + "fs/remove": "fs/remove", + "fs/copy": "fs/copy", + "fs/watch": "fs/watch", + "fs/unwatch": "fs/unwatch", + "skills/config/write": "skills/config/write", + "plugin/install": "plugin/install", + "plugin/uninstall": "plugin/uninstall", + "turn/start": "turn/start", + "turn/steer": "turn/steer", + "turn/interrupt": "turn/interrupt", + "review/start": "review/start", + "model/list": "model/list", + "experimentalFeature/list": "experimentalFeature/list", + "experimentalFeature/enablement/set": "experimentalFeature/enablement/set", + "mcpServer/oauth/login": "mcpServer/oauth/login", + "config/mcpServer/reload": "config/mcpServer/reload", + "mcpServerStatus/list": "mcpServerStatus/list", + "mcpServer/resource/read": "mcpServer/resource/read", + "mcpServer/tool/call": "mcpServer/tool/call", + "windowsSandbox/setupStart": "windowsSandbox/setupStart", + "account/login/start": "account/login/start", + "account/login/cancel": "account/login/cancel", + "account/logout": "account/logout", + "account/rateLimits/read": "account/rateLimits/read", + "feedback/upload": "feedback/upload", + "command/exec": "command/exec", + "command/exec/write": "command/exec/write", + "command/exec/terminate": "command/exec/terminate", + "command/exec/resize": "command/exec/resize", + "config/read": "config/read", + "externalAgentConfig/detect": "externalAgentConfig/detect", + "externalAgentConfig/import": "externalAgentConfig/import", + "config/value/write": "config/value/write", + "config/batchWrite": "config/batchWrite", + "configRequirements/read": "configRequirements/read", + "account/read": "account/read", + getConversationSummary: "getConversationSummary", + gitDiffToRemote: "gitDiffToRemote", + getAuthStatus: "getAuthStatus", + fuzzyFileSearch: "fuzzyFileSearch", +} as const; + +export const CLIENT_NOTIFICATION_METHODS = { + initialized: "initialized", +} as const; + +export const SERVER_REQUEST_METHODS = { + "item/commandExecution/requestApproval": "item/commandExecution/requestApproval", + "item/fileChange/requestApproval": "item/fileChange/requestApproval", + "item/tool/requestUserInput": "item/tool/requestUserInput", + "mcpServer/elicitation/request": "mcpServer/elicitation/request", + "item/permissions/requestApproval": "item/permissions/requestApproval", + "item/tool/call": "item/tool/call", + "account/chatgptAuthTokens/refresh": "account/chatgptAuthTokens/refresh", + applyPatchApproval: "applyPatchApproval", + execCommandApproval: "execCommandApproval", +} as const; + +export const SERVER_NOTIFICATION_METHODS = { + error: "error", + "thread/started": "thread/started", + "thread/status/changed": "thread/status/changed", + "thread/archived": "thread/archived", + "thread/unarchived": "thread/unarchived", + "thread/closed": "thread/closed", + "skills/changed": "skills/changed", + "thread/name/updated": "thread/name/updated", + "thread/tokenUsage/updated": "thread/tokenUsage/updated", + "turn/started": "turn/started", + "hook/started": "hook/started", + "turn/completed": "turn/completed", + "hook/completed": "hook/completed", + "turn/diff/updated": "turn/diff/updated", + "turn/plan/updated": "turn/plan/updated", + "item/started": "item/started", + "item/autoApprovalReview/started": "item/autoApprovalReview/started", + "item/autoApprovalReview/completed": "item/autoApprovalReview/completed", + "item/completed": "item/completed", + "rawResponseItem/completed": "rawResponseItem/completed", + "item/agentMessage/delta": "item/agentMessage/delta", + "item/plan/delta": "item/plan/delta", + "command/exec/outputDelta": "command/exec/outputDelta", + "item/commandExecution/outputDelta": "item/commandExecution/outputDelta", + "item/commandExecution/terminalInteraction": "item/commandExecution/terminalInteraction", + "item/fileChange/outputDelta": "item/fileChange/outputDelta", + "serverRequest/resolved": "serverRequest/resolved", + "item/mcpToolCall/progress": "item/mcpToolCall/progress", + "mcpServer/oauthLogin/completed": "mcpServer/oauthLogin/completed", + "mcpServer/startupStatus/updated": "mcpServer/startupStatus/updated", + "account/updated": "account/updated", + "account/rateLimits/updated": "account/rateLimits/updated", + "app/list/updated": "app/list/updated", + "fs/changed": "fs/changed", + "item/reasoning/summaryTextDelta": "item/reasoning/summaryTextDelta", + "item/reasoning/summaryPartAdded": "item/reasoning/summaryPartAdded", + "item/reasoning/textDelta": "item/reasoning/textDelta", + "thread/compacted": "thread/compacted", + "model/rerouted": "model/rerouted", + deprecationNotice: "deprecationNotice", + configWarning: "configWarning", + "fuzzyFileSearch/sessionUpdated": "fuzzyFileSearch/sessionUpdated", + "fuzzyFileSearch/sessionCompleted": "fuzzyFileSearch/sessionCompleted", + "thread/realtime/started": "thread/realtime/started", + "thread/realtime/itemAdded": "thread/realtime/itemAdded", + "thread/realtime/transcriptUpdated": "thread/realtime/transcriptUpdated", + "thread/realtime/outputAudio/delta": "thread/realtime/outputAudio/delta", + "thread/realtime/sdp": "thread/realtime/sdp", + "thread/realtime/error": "thread/realtime/error", + "thread/realtime/closed": "thread/realtime/closed", + "windows/worldWritableWarning": "windows/worldWritableWarning", + "windowsSandbox/setupCompleted": "windowsSandbox/setupCompleted", + "account/login/completed": "account/login/completed", +} as const; + +export type ClientRequestMethod = keyof typeof CLIENT_REQUEST_METHODS; +export type ClientNotificationMethod = keyof typeof CLIENT_NOTIFICATION_METHODS; +export type ServerRequestMethod = keyof typeof SERVER_REQUEST_METHODS; +export type ServerNotificationMethod = keyof typeof SERVER_NOTIFICATION_METHODS; + +export interface ClientRequestParamsByMethod { + readonly initialize: typeof CodexSchema.V1InitializeParams.Type; + readonly "thread/start": typeof CodexSchema.V2ThreadStartParams.Type; + readonly "thread/resume": typeof CodexSchema.V2ThreadResumeParams.Type; + readonly "thread/fork": typeof CodexSchema.V2ThreadForkParams.Type; + readonly "thread/archive": typeof CodexSchema.V2ThreadArchiveParams.Type; + readonly "thread/unsubscribe": typeof CodexSchema.V2ThreadUnsubscribeParams.Type; + readonly "thread/name/set": typeof CodexSchema.V2ThreadSetNameParams.Type; + readonly "thread/metadata/update": typeof CodexSchema.V2ThreadMetadataUpdateParams.Type; + readonly "thread/unarchive": typeof CodexSchema.V2ThreadUnarchiveParams.Type; + readonly "thread/compact/start": typeof CodexSchema.V2ThreadCompactStartParams.Type; + readonly "thread/shellCommand": typeof CodexSchema.V2ThreadShellCommandParams.Type; + readonly "thread/rollback": typeof CodexSchema.V2ThreadRollbackParams.Type; + readonly "thread/list": typeof CodexSchema.V2ThreadListParams.Type; + readonly "thread/loaded/list": typeof CodexSchema.V2ThreadLoadedListParams.Type; + readonly "thread/read": typeof CodexSchema.V2ThreadReadParams.Type; + readonly "skills/list": typeof CodexSchema.V2SkillsListParams.Type; + readonly "plugin/list": typeof CodexSchema.V2PluginListParams.Type; + readonly "plugin/read": typeof CodexSchema.V2PluginReadParams.Type; + readonly "app/list": typeof CodexSchema.V2AppsListParams.Type; + readonly "fs/readFile": typeof CodexSchema.V2FsReadFileParams.Type; + readonly "fs/writeFile": typeof CodexSchema.V2FsWriteFileParams.Type; + readonly "fs/createDirectory": typeof CodexSchema.V2FsCreateDirectoryParams.Type; + readonly "fs/getMetadata": typeof CodexSchema.V2FsGetMetadataParams.Type; + readonly "fs/readDirectory": typeof CodexSchema.V2FsReadDirectoryParams.Type; + readonly "fs/remove": typeof CodexSchema.V2FsRemoveParams.Type; + readonly "fs/copy": typeof CodexSchema.V2FsCopyParams.Type; + readonly "fs/watch": typeof CodexSchema.V2FsWatchParams.Type; + readonly "fs/unwatch": typeof CodexSchema.V2FsUnwatchParams.Type; + readonly "skills/config/write": typeof CodexSchema.V2SkillsConfigWriteParams.Type; + readonly "plugin/install": typeof CodexSchema.V2PluginInstallParams.Type; + readonly "plugin/uninstall": typeof CodexSchema.V2PluginUninstallParams.Type; + readonly "turn/start": typeof CodexSchema.V2TurnStartParams.Type; + readonly "turn/steer": typeof CodexSchema.V2TurnSteerParams.Type; + readonly "turn/interrupt": typeof CodexSchema.V2TurnInterruptParams.Type; + readonly "review/start": typeof CodexSchema.V2ReviewStartParams.Type; + readonly "model/list": typeof CodexSchema.V2ModelListParams.Type; + readonly "experimentalFeature/list": typeof CodexSchema.V2ExperimentalFeatureListParams.Type; + readonly "experimentalFeature/enablement/set": typeof CodexSchema.V2ExperimentalFeatureEnablementSetParams.Type; + readonly "mcpServer/oauth/login": typeof CodexSchema.V2McpServerOauthLoginParams.Type; + readonly "config/mcpServer/reload": undefined; + readonly "mcpServerStatus/list": typeof CodexSchema.V2ListMcpServerStatusParams.Type; + readonly "mcpServer/resource/read": typeof CodexSchema.V2McpResourceReadParams.Type; + readonly "mcpServer/tool/call": typeof CodexSchema.V2McpServerToolCallParams.Type; + readonly "windowsSandbox/setupStart": typeof CodexSchema.V2WindowsSandboxSetupStartParams.Type; + readonly "account/login/start": typeof CodexSchema.V2LoginAccountParams.Type; + readonly "account/login/cancel": typeof CodexSchema.V2CancelLoginAccountParams.Type; + readonly "account/logout": undefined; + readonly "account/rateLimits/read": undefined; + readonly "feedback/upload": typeof CodexSchema.V2FeedbackUploadParams.Type; + readonly "command/exec": typeof CodexSchema.V2CommandExecParams.Type; + readonly "command/exec/write": typeof CodexSchema.V2CommandExecWriteParams.Type; + readonly "command/exec/terminate": typeof CodexSchema.V2CommandExecTerminateParams.Type; + readonly "command/exec/resize": typeof CodexSchema.V2CommandExecResizeParams.Type; + readonly "config/read": typeof CodexSchema.V2ConfigReadParams.Type; + readonly "externalAgentConfig/detect": typeof CodexSchema.V2ExternalAgentConfigDetectParams.Type; + readonly "externalAgentConfig/import": typeof CodexSchema.V2ExternalAgentConfigImportParams.Type; + readonly "config/value/write": typeof CodexSchema.V2ConfigValueWriteParams.Type; + readonly "config/batchWrite": typeof CodexSchema.V2ConfigBatchWriteParams.Type; + readonly "configRequirements/read": undefined; + readonly "account/read": typeof CodexSchema.V2GetAccountParams.Type; + readonly getConversationSummary: typeof CodexSchema.GetConversationSummaryParams.Type; + readonly gitDiffToRemote: typeof CodexSchema.GitDiffToRemoteParams.Type; + readonly getAuthStatus: typeof CodexSchema.GetAuthStatusParams.Type; + readonly fuzzyFileSearch: typeof CodexSchema.FuzzyFileSearchParams.Type; +} + +export interface ClientRequestResponsesByMethod { + readonly initialize: typeof CodexSchema.V1InitializeResponse.Type; + readonly "thread/start": typeof CodexSchema.V2ThreadStartResponse.Type; + readonly "thread/resume": typeof CodexSchema.V2ThreadResumeResponse.Type; + readonly "thread/fork": typeof CodexSchema.V2ThreadForkResponse.Type; + readonly "thread/archive": typeof CodexSchema.V2ThreadArchiveResponse.Type; + readonly "thread/unsubscribe": typeof CodexSchema.V2ThreadUnsubscribeResponse.Type; + readonly "thread/name/set": typeof CodexSchema.V2ThreadSetNameResponse.Type; + readonly "thread/metadata/update": typeof CodexSchema.V2ThreadMetadataUpdateResponse.Type; + readonly "thread/unarchive": typeof CodexSchema.V2ThreadUnarchiveResponse.Type; + readonly "thread/compact/start": typeof CodexSchema.V2ThreadCompactStartResponse.Type; + readonly "thread/shellCommand": typeof CodexSchema.V2ThreadShellCommandResponse.Type; + readonly "thread/rollback": typeof CodexSchema.V2ThreadRollbackResponse.Type; + readonly "thread/list": typeof CodexSchema.V2ThreadListResponse.Type; + readonly "thread/loaded/list": typeof CodexSchema.V2ThreadLoadedListResponse.Type; + readonly "thread/read": typeof CodexSchema.V2ThreadReadResponse.Type; + readonly "skills/list": typeof CodexSchema.V2SkillsListResponse.Type; + readonly "plugin/list": typeof CodexSchema.V2PluginListResponse.Type; + readonly "plugin/read": typeof CodexSchema.V2PluginReadResponse.Type; + readonly "app/list": typeof CodexSchema.V2AppsListResponse.Type; + readonly "fs/readFile": typeof CodexSchema.V2FsReadFileResponse.Type; + readonly "fs/writeFile": typeof CodexSchema.V2FsWriteFileResponse.Type; + readonly "fs/createDirectory": typeof CodexSchema.V2FsCreateDirectoryResponse.Type; + readonly "fs/getMetadata": typeof CodexSchema.V2FsGetMetadataResponse.Type; + readonly "fs/readDirectory": typeof CodexSchema.V2FsReadDirectoryResponse.Type; + readonly "fs/remove": typeof CodexSchema.V2FsRemoveResponse.Type; + readonly "fs/copy": typeof CodexSchema.V2FsCopyResponse.Type; + readonly "fs/watch": typeof CodexSchema.V2FsWatchResponse.Type; + readonly "fs/unwatch": typeof CodexSchema.V2FsUnwatchResponse.Type; + readonly "skills/config/write": typeof CodexSchema.V2SkillsConfigWriteResponse.Type; + readonly "plugin/install": typeof CodexSchema.V2PluginInstallResponse.Type; + readonly "plugin/uninstall": typeof CodexSchema.V2PluginUninstallResponse.Type; + readonly "turn/start": typeof CodexSchema.V2TurnStartResponse.Type; + readonly "turn/steer": typeof CodexSchema.V2TurnSteerResponse.Type; + readonly "turn/interrupt": typeof CodexSchema.V2TurnInterruptResponse.Type; + readonly "review/start": typeof CodexSchema.V2ReviewStartResponse.Type; + readonly "model/list": typeof CodexSchema.V2ModelListResponse.Type; + readonly "experimentalFeature/list": typeof CodexSchema.V2ExperimentalFeatureListResponse.Type; + readonly "experimentalFeature/enablement/set": typeof CodexSchema.V2ExperimentalFeatureEnablementSetResponse.Type; + readonly "mcpServer/oauth/login": typeof CodexSchema.V2McpServerOauthLoginResponse.Type; + readonly "config/mcpServer/reload": typeof CodexSchema.V2McpServerRefreshResponse.Type; + readonly "mcpServerStatus/list": typeof CodexSchema.V2ListMcpServerStatusResponse.Type; + readonly "mcpServer/resource/read": typeof CodexSchema.V2McpResourceReadResponse.Type; + readonly "mcpServer/tool/call": typeof CodexSchema.V2McpServerToolCallResponse.Type; + readonly "windowsSandbox/setupStart": typeof CodexSchema.V2WindowsSandboxSetupStartResponse.Type; + readonly "account/login/start": typeof CodexSchema.V2LoginAccountResponse.Type; + readonly "account/login/cancel": typeof CodexSchema.V2CancelLoginAccountResponse.Type; + readonly "account/logout": typeof CodexSchema.V2LogoutAccountResponse.Type; + readonly "account/rateLimits/read": typeof CodexSchema.V2GetAccountRateLimitsResponse.Type; + readonly "feedback/upload": typeof CodexSchema.V2FeedbackUploadResponse.Type; + readonly "command/exec": typeof CodexSchema.V2CommandExecResponse.Type; + readonly "command/exec/write": typeof CodexSchema.V2CommandExecWriteResponse.Type; + readonly "command/exec/terminate": typeof CodexSchema.V2CommandExecTerminateResponse.Type; + readonly "command/exec/resize": typeof CodexSchema.V2CommandExecResizeResponse.Type; + readonly "config/read": typeof CodexSchema.V2ConfigReadResponse.Type; + readonly "externalAgentConfig/detect": typeof CodexSchema.V2ExternalAgentConfigDetectResponse.Type; + readonly "externalAgentConfig/import": typeof CodexSchema.V2ExternalAgentConfigImportResponse.Type; + readonly "config/value/write": typeof CodexSchema.V2ConfigWriteResponse.Type; + readonly "config/batchWrite": typeof CodexSchema.V2ConfigWriteResponse.Type; + readonly "configRequirements/read": typeof CodexSchema.V2ConfigRequirementsReadResponse.Type; + readonly "account/read": typeof CodexSchema.V2GetAccountResponse.Type; + readonly getConversationSummary: typeof CodexSchema.GetConversationSummaryResponse.Type; + readonly gitDiffToRemote: typeof CodexSchema.GitDiffToRemoteResponse.Type; + readonly getAuthStatus: typeof CodexSchema.GetAuthStatusResponse.Type; + readonly fuzzyFileSearch: typeof CodexSchema.FuzzyFileSearchResponse.Type; +} + +export interface ClientNotificationParamsByMethod { + readonly initialized: undefined; +} + +export interface ServerRequestParamsByMethod { + readonly "item/commandExecution/requestApproval": typeof CodexSchema.CommandExecutionRequestApprovalParams.Type; + readonly "item/fileChange/requestApproval": typeof CodexSchema.FileChangeRequestApprovalParams.Type; + readonly "item/tool/requestUserInput": typeof CodexSchema.ToolRequestUserInputParams.Type; + readonly "mcpServer/elicitation/request": typeof CodexSchema.McpServerElicitationRequestParams.Type; + readonly "item/permissions/requestApproval": typeof CodexSchema.PermissionsRequestApprovalParams.Type; + readonly "item/tool/call": typeof CodexSchema.DynamicToolCallParams.Type; + readonly "account/chatgptAuthTokens/refresh": typeof CodexSchema.ChatgptAuthTokensRefreshParams.Type; + readonly applyPatchApproval: typeof CodexSchema.ApplyPatchApprovalParams.Type; + readonly execCommandApproval: typeof CodexSchema.ExecCommandApprovalParams.Type; +} + +export interface ServerRequestResponsesByMethod { + readonly "item/commandExecution/requestApproval": typeof CodexSchema.CommandExecutionRequestApprovalResponse.Type; + readonly "item/fileChange/requestApproval": typeof CodexSchema.FileChangeRequestApprovalResponse.Type; + readonly "item/tool/requestUserInput": typeof CodexSchema.ToolRequestUserInputResponse.Type; + readonly "mcpServer/elicitation/request": typeof CodexSchema.McpServerElicitationRequestResponse.Type; + readonly "item/permissions/requestApproval": typeof CodexSchema.PermissionsRequestApprovalResponse.Type; + readonly "item/tool/call": typeof CodexSchema.DynamicToolCallResponse.Type; + readonly "account/chatgptAuthTokens/refresh": typeof CodexSchema.ChatgptAuthTokensRefreshResponse.Type; + readonly applyPatchApproval: typeof CodexSchema.ApplyPatchApprovalResponse.Type; + readonly execCommandApproval: typeof CodexSchema.ExecCommandApprovalResponse.Type; +} + +export interface ServerNotificationParamsByMethod { + readonly error: typeof CodexSchema.V2ErrorNotification.Type; + readonly "thread/started": typeof CodexSchema.V2ThreadStartedNotification.Type; + readonly "thread/status/changed": typeof CodexSchema.V2ThreadStatusChangedNotification.Type; + readonly "thread/archived": typeof CodexSchema.V2ThreadArchivedNotification.Type; + readonly "thread/unarchived": typeof CodexSchema.V2ThreadUnarchivedNotification.Type; + readonly "thread/closed": typeof CodexSchema.V2ThreadClosedNotification.Type; + readonly "skills/changed": typeof CodexSchema.V2SkillsChangedNotification.Type; + readonly "thread/name/updated": typeof CodexSchema.V2ThreadNameUpdatedNotification.Type; + readonly "thread/tokenUsage/updated": typeof CodexSchema.V2ThreadTokenUsageUpdatedNotification.Type; + readonly "turn/started": typeof CodexSchema.V2TurnStartedNotification.Type; + readonly "hook/started": typeof CodexSchema.V2HookStartedNotification.Type; + readonly "turn/completed": typeof CodexSchema.V2TurnCompletedNotification.Type; + readonly "hook/completed": typeof CodexSchema.V2HookCompletedNotification.Type; + readonly "turn/diff/updated": typeof CodexSchema.V2TurnDiffUpdatedNotification.Type; + readonly "turn/plan/updated": typeof CodexSchema.V2TurnPlanUpdatedNotification.Type; + readonly "item/started": typeof CodexSchema.V2ItemStartedNotification.Type; + readonly "item/autoApprovalReview/started": typeof CodexSchema.V2ItemGuardianApprovalReviewStartedNotification.Type; + readonly "item/autoApprovalReview/completed": typeof CodexSchema.V2ItemGuardianApprovalReviewCompletedNotification.Type; + readonly "item/completed": typeof CodexSchema.V2ItemCompletedNotification.Type; + readonly "rawResponseItem/completed": typeof CodexSchema.V2RawResponseItemCompletedNotification.Type; + readonly "item/agentMessage/delta": typeof CodexSchema.V2AgentMessageDeltaNotification.Type; + readonly "item/plan/delta": typeof CodexSchema.V2PlanDeltaNotification.Type; + readonly "command/exec/outputDelta": typeof CodexSchema.V2CommandExecOutputDeltaNotification.Type; + readonly "item/commandExecution/outputDelta": typeof CodexSchema.V2CommandExecutionOutputDeltaNotification.Type; + readonly "item/commandExecution/terminalInteraction": typeof CodexSchema.V2TerminalInteractionNotification.Type; + readonly "item/fileChange/outputDelta": typeof CodexSchema.V2FileChangeOutputDeltaNotification.Type; + readonly "serverRequest/resolved": typeof CodexSchema.V2ServerRequestResolvedNotification.Type; + readonly "item/mcpToolCall/progress": typeof CodexSchema.V2McpToolCallProgressNotification.Type; + readonly "mcpServer/oauthLogin/completed": typeof CodexSchema.V2McpServerOauthLoginCompletedNotification.Type; + readonly "mcpServer/startupStatus/updated": typeof CodexSchema.V2McpServerStatusUpdatedNotification.Type; + readonly "account/updated": typeof CodexSchema.V2AccountUpdatedNotification.Type; + readonly "account/rateLimits/updated": typeof CodexSchema.V2AccountRateLimitsUpdatedNotification.Type; + readonly "app/list/updated": typeof CodexSchema.V2AppListUpdatedNotification.Type; + readonly "fs/changed": typeof CodexSchema.V2FsChangedNotification.Type; + readonly "item/reasoning/summaryTextDelta": typeof CodexSchema.V2ReasoningSummaryTextDeltaNotification.Type; + readonly "item/reasoning/summaryPartAdded": typeof CodexSchema.V2ReasoningSummaryPartAddedNotification.Type; + readonly "item/reasoning/textDelta": typeof CodexSchema.V2ReasoningTextDeltaNotification.Type; + readonly "thread/compacted": typeof CodexSchema.V2ContextCompactedNotification.Type; + readonly "model/rerouted": typeof CodexSchema.V2ModelReroutedNotification.Type; + readonly deprecationNotice: typeof CodexSchema.V2DeprecationNoticeNotification.Type; + readonly configWarning: typeof CodexSchema.V2ConfigWarningNotification.Type; + readonly "fuzzyFileSearch/sessionUpdated": typeof CodexSchema.FuzzyFileSearchSessionUpdatedNotification.Type; + readonly "fuzzyFileSearch/sessionCompleted": typeof CodexSchema.FuzzyFileSearchSessionCompletedNotification.Type; + readonly "thread/realtime/started": typeof CodexSchema.V2ThreadRealtimeStartedNotification.Type; + readonly "thread/realtime/itemAdded": typeof CodexSchema.V2ThreadRealtimeItemAddedNotification.Type; + readonly "thread/realtime/transcriptUpdated": typeof CodexSchema.V2ThreadRealtimeTranscriptUpdatedNotification.Type; + readonly "thread/realtime/outputAudio/delta": typeof CodexSchema.V2ThreadRealtimeOutputAudioDeltaNotification.Type; + readonly "thread/realtime/sdp": typeof CodexSchema.V2ThreadRealtimeSdpNotification.Type; + readonly "thread/realtime/error": typeof CodexSchema.V2ThreadRealtimeErrorNotification.Type; + readonly "thread/realtime/closed": typeof CodexSchema.V2ThreadRealtimeClosedNotification.Type; + readonly "windows/worldWritableWarning": typeof CodexSchema.V2WindowsWorldWritableWarningNotification.Type; + readonly "windowsSandbox/setupCompleted": typeof CodexSchema.V2WindowsSandboxSetupCompletedNotification.Type; + readonly "account/login/completed": typeof CodexSchema.V2AccountLoginCompletedNotification.Type; +} + +export const CLIENT_REQUEST_PARAMS = { + initialize: CodexSchema.V1InitializeParams, + "thread/start": CodexSchema.V2ThreadStartParams, + "thread/resume": CodexSchema.V2ThreadResumeParams, + "thread/fork": CodexSchema.V2ThreadForkParams, + "thread/archive": CodexSchema.V2ThreadArchiveParams, + "thread/unsubscribe": CodexSchema.V2ThreadUnsubscribeParams, + "thread/name/set": CodexSchema.V2ThreadSetNameParams, + "thread/metadata/update": CodexSchema.V2ThreadMetadataUpdateParams, + "thread/unarchive": CodexSchema.V2ThreadUnarchiveParams, + "thread/compact/start": CodexSchema.V2ThreadCompactStartParams, + "thread/shellCommand": CodexSchema.V2ThreadShellCommandParams, + "thread/rollback": CodexSchema.V2ThreadRollbackParams, + "thread/list": CodexSchema.V2ThreadListParams, + "thread/loaded/list": CodexSchema.V2ThreadLoadedListParams, + "thread/read": CodexSchema.V2ThreadReadParams, + "skills/list": CodexSchema.V2SkillsListParams, + "plugin/list": CodexSchema.V2PluginListParams, + "plugin/read": CodexSchema.V2PluginReadParams, + "app/list": CodexSchema.V2AppsListParams, + "fs/readFile": CodexSchema.V2FsReadFileParams, + "fs/writeFile": CodexSchema.V2FsWriteFileParams, + "fs/createDirectory": CodexSchema.V2FsCreateDirectoryParams, + "fs/getMetadata": CodexSchema.V2FsGetMetadataParams, + "fs/readDirectory": CodexSchema.V2FsReadDirectoryParams, + "fs/remove": CodexSchema.V2FsRemoveParams, + "fs/copy": CodexSchema.V2FsCopyParams, + "fs/watch": CodexSchema.V2FsWatchParams, + "fs/unwatch": CodexSchema.V2FsUnwatchParams, + "skills/config/write": CodexSchema.V2SkillsConfigWriteParams, + "plugin/install": CodexSchema.V2PluginInstallParams, + "plugin/uninstall": CodexSchema.V2PluginUninstallParams, + "turn/start": CodexSchema.V2TurnStartParams, + "turn/steer": CodexSchema.V2TurnSteerParams, + "turn/interrupt": CodexSchema.V2TurnInterruptParams, + "review/start": CodexSchema.V2ReviewStartParams, + "model/list": CodexSchema.V2ModelListParams, + "experimentalFeature/list": CodexSchema.V2ExperimentalFeatureListParams, + "experimentalFeature/enablement/set": CodexSchema.V2ExperimentalFeatureEnablementSetParams, + "mcpServer/oauth/login": CodexSchema.V2McpServerOauthLoginParams, + "config/mcpServer/reload": undefined, + "mcpServerStatus/list": CodexSchema.V2ListMcpServerStatusParams, + "mcpServer/resource/read": CodexSchema.V2McpResourceReadParams, + "mcpServer/tool/call": CodexSchema.V2McpServerToolCallParams, + "windowsSandbox/setupStart": CodexSchema.V2WindowsSandboxSetupStartParams, + "account/login/start": CodexSchema.V2LoginAccountParams, + "account/login/cancel": CodexSchema.V2CancelLoginAccountParams, + "account/logout": undefined, + "account/rateLimits/read": undefined, + "feedback/upload": CodexSchema.V2FeedbackUploadParams, + "command/exec": CodexSchema.V2CommandExecParams, + "command/exec/write": CodexSchema.V2CommandExecWriteParams, + "command/exec/terminate": CodexSchema.V2CommandExecTerminateParams, + "command/exec/resize": CodexSchema.V2CommandExecResizeParams, + "config/read": CodexSchema.V2ConfigReadParams, + "externalAgentConfig/detect": CodexSchema.V2ExternalAgentConfigDetectParams, + "externalAgentConfig/import": CodexSchema.V2ExternalAgentConfigImportParams, + "config/value/write": CodexSchema.V2ConfigValueWriteParams, + "config/batchWrite": CodexSchema.V2ConfigBatchWriteParams, + "configRequirements/read": undefined, + "account/read": CodexSchema.V2GetAccountParams, + getConversationSummary: CodexSchema.GetConversationSummaryParams, + gitDiffToRemote: CodexSchema.GitDiffToRemoteParams, + getAuthStatus: CodexSchema.GetAuthStatusParams, + fuzzyFileSearch: CodexSchema.FuzzyFileSearchParams, +} as const; + +export const CLIENT_REQUEST_RESPONSES = { + initialize: CodexSchema.V1InitializeResponse, + "thread/start": CodexSchema.V2ThreadStartResponse, + "thread/resume": CodexSchema.V2ThreadResumeResponse, + "thread/fork": CodexSchema.V2ThreadForkResponse, + "thread/archive": CodexSchema.V2ThreadArchiveResponse, + "thread/unsubscribe": CodexSchema.V2ThreadUnsubscribeResponse, + "thread/name/set": CodexSchema.V2ThreadSetNameResponse, + "thread/metadata/update": CodexSchema.V2ThreadMetadataUpdateResponse, + "thread/unarchive": CodexSchema.V2ThreadUnarchiveResponse, + "thread/compact/start": CodexSchema.V2ThreadCompactStartResponse, + "thread/shellCommand": CodexSchema.V2ThreadShellCommandResponse, + "thread/rollback": CodexSchema.V2ThreadRollbackResponse, + "thread/list": CodexSchema.V2ThreadListResponse, + "thread/loaded/list": CodexSchema.V2ThreadLoadedListResponse, + "thread/read": CodexSchema.V2ThreadReadResponse, + "skills/list": CodexSchema.V2SkillsListResponse, + "plugin/list": CodexSchema.V2PluginListResponse, + "plugin/read": CodexSchema.V2PluginReadResponse, + "app/list": CodexSchema.V2AppsListResponse, + "fs/readFile": CodexSchema.V2FsReadFileResponse, + "fs/writeFile": CodexSchema.V2FsWriteFileResponse, + "fs/createDirectory": CodexSchema.V2FsCreateDirectoryResponse, + "fs/getMetadata": CodexSchema.V2FsGetMetadataResponse, + "fs/readDirectory": CodexSchema.V2FsReadDirectoryResponse, + "fs/remove": CodexSchema.V2FsRemoveResponse, + "fs/copy": CodexSchema.V2FsCopyResponse, + "fs/watch": CodexSchema.V2FsWatchResponse, + "fs/unwatch": CodexSchema.V2FsUnwatchResponse, + "skills/config/write": CodexSchema.V2SkillsConfigWriteResponse, + "plugin/install": CodexSchema.V2PluginInstallResponse, + "plugin/uninstall": CodexSchema.V2PluginUninstallResponse, + "turn/start": CodexSchema.V2TurnStartResponse, + "turn/steer": CodexSchema.V2TurnSteerResponse, + "turn/interrupt": CodexSchema.V2TurnInterruptResponse, + "review/start": CodexSchema.V2ReviewStartResponse, + "model/list": CodexSchema.V2ModelListResponse, + "experimentalFeature/list": CodexSchema.V2ExperimentalFeatureListResponse, + "experimentalFeature/enablement/set": CodexSchema.V2ExperimentalFeatureEnablementSetResponse, + "mcpServer/oauth/login": CodexSchema.V2McpServerOauthLoginResponse, + "config/mcpServer/reload": CodexSchema.V2McpServerRefreshResponse, + "mcpServerStatus/list": CodexSchema.V2ListMcpServerStatusResponse, + "mcpServer/resource/read": CodexSchema.V2McpResourceReadResponse, + "mcpServer/tool/call": CodexSchema.V2McpServerToolCallResponse, + "windowsSandbox/setupStart": CodexSchema.V2WindowsSandboxSetupStartResponse, + "account/login/start": CodexSchema.V2LoginAccountResponse, + "account/login/cancel": CodexSchema.V2CancelLoginAccountResponse, + "account/logout": CodexSchema.V2LogoutAccountResponse, + "account/rateLimits/read": CodexSchema.V2GetAccountRateLimitsResponse, + "feedback/upload": CodexSchema.V2FeedbackUploadResponse, + "command/exec": CodexSchema.V2CommandExecResponse, + "command/exec/write": CodexSchema.V2CommandExecWriteResponse, + "command/exec/terminate": CodexSchema.V2CommandExecTerminateResponse, + "command/exec/resize": CodexSchema.V2CommandExecResizeResponse, + "config/read": CodexSchema.V2ConfigReadResponse, + "externalAgentConfig/detect": CodexSchema.V2ExternalAgentConfigDetectResponse, + "externalAgentConfig/import": CodexSchema.V2ExternalAgentConfigImportResponse, + "config/value/write": CodexSchema.V2ConfigWriteResponse, + "config/batchWrite": CodexSchema.V2ConfigWriteResponse, + "configRequirements/read": CodexSchema.V2ConfigRequirementsReadResponse, + "account/read": CodexSchema.V2GetAccountResponse, + getConversationSummary: CodexSchema.GetConversationSummaryResponse, + gitDiffToRemote: CodexSchema.GitDiffToRemoteResponse, + getAuthStatus: CodexSchema.GetAuthStatusResponse, + fuzzyFileSearch: CodexSchema.FuzzyFileSearchResponse, +} as const; + +export const CLIENT_NOTIFICATION_PARAMS = { + initialized: undefined, +} as const; + +export const SERVER_REQUEST_PARAMS = { + "item/commandExecution/requestApproval": CodexSchema.CommandExecutionRequestApprovalParams, + "item/fileChange/requestApproval": CodexSchema.FileChangeRequestApprovalParams, + "item/tool/requestUserInput": CodexSchema.ToolRequestUserInputParams, + "mcpServer/elicitation/request": CodexSchema.McpServerElicitationRequestParams, + "item/permissions/requestApproval": CodexSchema.PermissionsRequestApprovalParams, + "item/tool/call": CodexSchema.DynamicToolCallParams, + "account/chatgptAuthTokens/refresh": CodexSchema.ChatgptAuthTokensRefreshParams, + applyPatchApproval: CodexSchema.ApplyPatchApprovalParams, + execCommandApproval: CodexSchema.ExecCommandApprovalParams, +} as const; + +export const SERVER_REQUEST_RESPONSES = { + "item/commandExecution/requestApproval": CodexSchema.CommandExecutionRequestApprovalResponse, + "item/fileChange/requestApproval": CodexSchema.FileChangeRequestApprovalResponse, + "item/tool/requestUserInput": CodexSchema.ToolRequestUserInputResponse, + "mcpServer/elicitation/request": CodexSchema.McpServerElicitationRequestResponse, + "item/permissions/requestApproval": CodexSchema.PermissionsRequestApprovalResponse, + "item/tool/call": CodexSchema.DynamicToolCallResponse, + "account/chatgptAuthTokens/refresh": CodexSchema.ChatgptAuthTokensRefreshResponse, + applyPatchApproval: CodexSchema.ApplyPatchApprovalResponse, + execCommandApproval: CodexSchema.ExecCommandApprovalResponse, +} as const; + +export const SERVER_NOTIFICATION_PARAMS = { + error: CodexSchema.V2ErrorNotification, + "thread/started": CodexSchema.V2ThreadStartedNotification, + "thread/status/changed": CodexSchema.V2ThreadStatusChangedNotification, + "thread/archived": CodexSchema.V2ThreadArchivedNotification, + "thread/unarchived": CodexSchema.V2ThreadUnarchivedNotification, + "thread/closed": CodexSchema.V2ThreadClosedNotification, + "skills/changed": CodexSchema.V2SkillsChangedNotification, + "thread/name/updated": CodexSchema.V2ThreadNameUpdatedNotification, + "thread/tokenUsage/updated": CodexSchema.V2ThreadTokenUsageUpdatedNotification, + "turn/started": CodexSchema.V2TurnStartedNotification, + "hook/started": CodexSchema.V2HookStartedNotification, + "turn/completed": CodexSchema.V2TurnCompletedNotification, + "hook/completed": CodexSchema.V2HookCompletedNotification, + "turn/diff/updated": CodexSchema.V2TurnDiffUpdatedNotification, + "turn/plan/updated": CodexSchema.V2TurnPlanUpdatedNotification, + "item/started": CodexSchema.V2ItemStartedNotification, + "item/autoApprovalReview/started": CodexSchema.V2ItemGuardianApprovalReviewStartedNotification, + "item/autoApprovalReview/completed": + CodexSchema.V2ItemGuardianApprovalReviewCompletedNotification, + "item/completed": CodexSchema.V2ItemCompletedNotification, + "rawResponseItem/completed": CodexSchema.V2RawResponseItemCompletedNotification, + "item/agentMessage/delta": CodexSchema.V2AgentMessageDeltaNotification, + "item/plan/delta": CodexSchema.V2PlanDeltaNotification, + "command/exec/outputDelta": CodexSchema.V2CommandExecOutputDeltaNotification, + "item/commandExecution/outputDelta": CodexSchema.V2CommandExecutionOutputDeltaNotification, + "item/commandExecution/terminalInteraction": CodexSchema.V2TerminalInteractionNotification, + "item/fileChange/outputDelta": CodexSchema.V2FileChangeOutputDeltaNotification, + "serverRequest/resolved": CodexSchema.V2ServerRequestResolvedNotification, + "item/mcpToolCall/progress": CodexSchema.V2McpToolCallProgressNotification, + "mcpServer/oauthLogin/completed": CodexSchema.V2McpServerOauthLoginCompletedNotification, + "mcpServer/startupStatus/updated": CodexSchema.V2McpServerStatusUpdatedNotification, + "account/updated": CodexSchema.V2AccountUpdatedNotification, + "account/rateLimits/updated": CodexSchema.V2AccountRateLimitsUpdatedNotification, + "app/list/updated": CodexSchema.V2AppListUpdatedNotification, + "fs/changed": CodexSchema.V2FsChangedNotification, + "item/reasoning/summaryTextDelta": CodexSchema.V2ReasoningSummaryTextDeltaNotification, + "item/reasoning/summaryPartAdded": CodexSchema.V2ReasoningSummaryPartAddedNotification, + "item/reasoning/textDelta": CodexSchema.V2ReasoningTextDeltaNotification, + "thread/compacted": CodexSchema.V2ContextCompactedNotification, + "model/rerouted": CodexSchema.V2ModelReroutedNotification, + deprecationNotice: CodexSchema.V2DeprecationNoticeNotification, + configWarning: CodexSchema.V2ConfigWarningNotification, + "fuzzyFileSearch/sessionUpdated": CodexSchema.FuzzyFileSearchSessionUpdatedNotification, + "fuzzyFileSearch/sessionCompleted": CodexSchema.FuzzyFileSearchSessionCompletedNotification, + "thread/realtime/started": CodexSchema.V2ThreadRealtimeStartedNotification, + "thread/realtime/itemAdded": CodexSchema.V2ThreadRealtimeItemAddedNotification, + "thread/realtime/transcriptUpdated": CodexSchema.V2ThreadRealtimeTranscriptUpdatedNotification, + "thread/realtime/outputAudio/delta": CodexSchema.V2ThreadRealtimeOutputAudioDeltaNotification, + "thread/realtime/sdp": CodexSchema.V2ThreadRealtimeSdpNotification, + "thread/realtime/error": CodexSchema.V2ThreadRealtimeErrorNotification, + "thread/realtime/closed": CodexSchema.V2ThreadRealtimeClosedNotification, + "windows/worldWritableWarning": CodexSchema.V2WindowsWorldWritableWarningNotification, + "windowsSandbox/setupCompleted": CodexSchema.V2WindowsSandboxSetupCompletedNotification, + "account/login/completed": CodexSchema.V2AccountLoginCompletedNotification, +} as const; diff --git a/packages/effect-codex-app-server/src/_generated/namespaces.gen.ts b/packages/effect-codex-app-server/src/_generated/namespaces.gen.ts new file mode 100644 index 0000000000..baa94c8797 --- /dev/null +++ b/packages/effect-codex-app-server/src/_generated/namespaces.gen.ts @@ -0,0 +1,180 @@ +// This file is generated by the effect-codex-app-server package. Do not edit manually. +// Upstream protocol ref: dbfe855f4fd0f5dcdf079882652a8efe622b0595 + +import * as CodexSchema from "./schema.gen.ts"; + +export const v1 = { + InitializeParams: CodexSchema.V1InitializeParams, + InitializeResponse: CodexSchema.V1InitializeResponse, +} as const; + +export const v2 = { + AccountLoginCompletedNotification: CodexSchema.V2AccountLoginCompletedNotification, + AccountRateLimitsUpdatedNotification: CodexSchema.V2AccountRateLimitsUpdatedNotification, + AccountUpdatedNotification: CodexSchema.V2AccountUpdatedNotification, + AgentMessageDeltaNotification: CodexSchema.V2AgentMessageDeltaNotification, + AppListUpdatedNotification: CodexSchema.V2AppListUpdatedNotification, + AppsListParams: CodexSchema.V2AppsListParams, + AppsListResponse: CodexSchema.V2AppsListResponse, + CancelLoginAccountParams: CodexSchema.V2CancelLoginAccountParams, + CancelLoginAccountResponse: CodexSchema.V2CancelLoginAccountResponse, + CommandExecOutputDeltaNotification: CodexSchema.V2CommandExecOutputDeltaNotification, + CommandExecParams: CodexSchema.V2CommandExecParams, + CommandExecResizeParams: CodexSchema.V2CommandExecResizeParams, + CommandExecResizeResponse: CodexSchema.V2CommandExecResizeResponse, + CommandExecResponse: CodexSchema.V2CommandExecResponse, + CommandExecTerminateParams: CodexSchema.V2CommandExecTerminateParams, + CommandExecTerminateResponse: CodexSchema.V2CommandExecTerminateResponse, + CommandExecutionOutputDeltaNotification: CodexSchema.V2CommandExecutionOutputDeltaNotification, + CommandExecWriteParams: CodexSchema.V2CommandExecWriteParams, + CommandExecWriteResponse: CodexSchema.V2CommandExecWriteResponse, + ConfigBatchWriteParams: CodexSchema.V2ConfigBatchWriteParams, + ConfigReadParams: CodexSchema.V2ConfigReadParams, + ConfigReadResponse: CodexSchema.V2ConfigReadResponse, + ConfigRequirementsReadResponse: CodexSchema.V2ConfigRequirementsReadResponse, + ConfigValueWriteParams: CodexSchema.V2ConfigValueWriteParams, + ConfigWarningNotification: CodexSchema.V2ConfigWarningNotification, + ConfigWriteResponse: CodexSchema.V2ConfigWriteResponse, + ContextCompactedNotification: CodexSchema.V2ContextCompactedNotification, + DeprecationNoticeNotification: CodexSchema.V2DeprecationNoticeNotification, + ErrorNotification: CodexSchema.V2ErrorNotification, + ExperimentalFeatureEnablementSetParams: CodexSchema.V2ExperimentalFeatureEnablementSetParams, + ExperimentalFeatureEnablementSetResponse: CodexSchema.V2ExperimentalFeatureEnablementSetResponse, + ExperimentalFeatureListParams: CodexSchema.V2ExperimentalFeatureListParams, + ExperimentalFeatureListResponse: CodexSchema.V2ExperimentalFeatureListResponse, + ExternalAgentConfigDetectParams: CodexSchema.V2ExternalAgentConfigDetectParams, + ExternalAgentConfigDetectResponse: CodexSchema.V2ExternalAgentConfigDetectResponse, + ExternalAgentConfigImportParams: CodexSchema.V2ExternalAgentConfigImportParams, + ExternalAgentConfigImportResponse: CodexSchema.V2ExternalAgentConfigImportResponse, + FeedbackUploadParams: CodexSchema.V2FeedbackUploadParams, + FeedbackUploadResponse: CodexSchema.V2FeedbackUploadResponse, + FileChangeOutputDeltaNotification: CodexSchema.V2FileChangeOutputDeltaNotification, + FsChangedNotification: CodexSchema.V2FsChangedNotification, + FsCopyParams: CodexSchema.V2FsCopyParams, + FsCopyResponse: CodexSchema.V2FsCopyResponse, + FsCreateDirectoryParams: CodexSchema.V2FsCreateDirectoryParams, + FsCreateDirectoryResponse: CodexSchema.V2FsCreateDirectoryResponse, + FsGetMetadataParams: CodexSchema.V2FsGetMetadataParams, + FsGetMetadataResponse: CodexSchema.V2FsGetMetadataResponse, + FsReadDirectoryParams: CodexSchema.V2FsReadDirectoryParams, + FsReadDirectoryResponse: CodexSchema.V2FsReadDirectoryResponse, + FsReadFileParams: CodexSchema.V2FsReadFileParams, + FsReadFileResponse: CodexSchema.V2FsReadFileResponse, + FsRemoveParams: CodexSchema.V2FsRemoveParams, + FsRemoveResponse: CodexSchema.V2FsRemoveResponse, + FsUnwatchParams: CodexSchema.V2FsUnwatchParams, + FsUnwatchResponse: CodexSchema.V2FsUnwatchResponse, + FsWatchParams: CodexSchema.V2FsWatchParams, + FsWatchResponse: CodexSchema.V2FsWatchResponse, + FsWriteFileParams: CodexSchema.V2FsWriteFileParams, + FsWriteFileResponse: CodexSchema.V2FsWriteFileResponse, + GetAccountParams: CodexSchema.V2GetAccountParams, + GetAccountRateLimitsResponse: CodexSchema.V2GetAccountRateLimitsResponse, + GetAccountResponse: CodexSchema.V2GetAccountResponse, + HookCompletedNotification: CodexSchema.V2HookCompletedNotification, + HookStartedNotification: CodexSchema.V2HookStartedNotification, + ItemCompletedNotification: CodexSchema.V2ItemCompletedNotification, + ItemGuardianApprovalReviewCompletedNotification: + CodexSchema.V2ItemGuardianApprovalReviewCompletedNotification, + ItemGuardianApprovalReviewStartedNotification: + CodexSchema.V2ItemGuardianApprovalReviewStartedNotification, + ItemStartedNotification: CodexSchema.V2ItemStartedNotification, + ListMcpServerStatusParams: CodexSchema.V2ListMcpServerStatusParams, + ListMcpServerStatusResponse: CodexSchema.V2ListMcpServerStatusResponse, + LoginAccountParams: CodexSchema.V2LoginAccountParams, + LoginAccountResponse: CodexSchema.V2LoginAccountResponse, + LogoutAccountResponse: CodexSchema.V2LogoutAccountResponse, + McpResourceReadParams: CodexSchema.V2McpResourceReadParams, + McpResourceReadResponse: CodexSchema.V2McpResourceReadResponse, + McpServerOauthLoginCompletedNotification: CodexSchema.V2McpServerOauthLoginCompletedNotification, + McpServerOauthLoginParams: CodexSchema.V2McpServerOauthLoginParams, + McpServerOauthLoginResponse: CodexSchema.V2McpServerOauthLoginResponse, + McpServerRefreshResponse: CodexSchema.V2McpServerRefreshResponse, + McpServerStatusUpdatedNotification: CodexSchema.V2McpServerStatusUpdatedNotification, + McpServerToolCallParams: CodexSchema.V2McpServerToolCallParams, + McpServerToolCallResponse: CodexSchema.V2McpServerToolCallResponse, + McpToolCallProgressNotification: CodexSchema.V2McpToolCallProgressNotification, + ModelListParams: CodexSchema.V2ModelListParams, + ModelListResponse: CodexSchema.V2ModelListResponse, + ModelReroutedNotification: CodexSchema.V2ModelReroutedNotification, + PlanDeltaNotification: CodexSchema.V2PlanDeltaNotification, + PluginInstallParams: CodexSchema.V2PluginInstallParams, + PluginInstallResponse: CodexSchema.V2PluginInstallResponse, + PluginListParams: CodexSchema.V2PluginListParams, + PluginListResponse: CodexSchema.V2PluginListResponse, + PluginReadParams: CodexSchema.V2PluginReadParams, + PluginReadResponse: CodexSchema.V2PluginReadResponse, + PluginUninstallParams: CodexSchema.V2PluginUninstallParams, + PluginUninstallResponse: CodexSchema.V2PluginUninstallResponse, + RawResponseItemCompletedNotification: CodexSchema.V2RawResponseItemCompletedNotification, + ReasoningSummaryPartAddedNotification: CodexSchema.V2ReasoningSummaryPartAddedNotification, + ReasoningSummaryTextDeltaNotification: CodexSchema.V2ReasoningSummaryTextDeltaNotification, + ReasoningTextDeltaNotification: CodexSchema.V2ReasoningTextDeltaNotification, + ReviewStartParams: CodexSchema.V2ReviewStartParams, + ReviewStartResponse: CodexSchema.V2ReviewStartResponse, + ServerRequestResolvedNotification: CodexSchema.V2ServerRequestResolvedNotification, + SkillsChangedNotification: CodexSchema.V2SkillsChangedNotification, + SkillsConfigWriteParams: CodexSchema.V2SkillsConfigWriteParams, + SkillsConfigWriteResponse: CodexSchema.V2SkillsConfigWriteResponse, + SkillsListParams: CodexSchema.V2SkillsListParams, + SkillsListResponse: CodexSchema.V2SkillsListResponse, + TerminalInteractionNotification: CodexSchema.V2TerminalInteractionNotification, + ThreadArchivedNotification: CodexSchema.V2ThreadArchivedNotification, + ThreadArchiveParams: CodexSchema.V2ThreadArchiveParams, + ThreadArchiveResponse: CodexSchema.V2ThreadArchiveResponse, + ThreadClosedNotification: CodexSchema.V2ThreadClosedNotification, + ThreadCompactStartParams: CodexSchema.V2ThreadCompactStartParams, + ThreadCompactStartResponse: CodexSchema.V2ThreadCompactStartResponse, + ThreadForkParams: CodexSchema.V2ThreadForkParams, + ThreadForkResponse: CodexSchema.V2ThreadForkResponse, + ThreadListParams: CodexSchema.V2ThreadListParams, + ThreadListResponse: CodexSchema.V2ThreadListResponse, + ThreadLoadedListParams: CodexSchema.V2ThreadLoadedListParams, + ThreadLoadedListResponse: CodexSchema.V2ThreadLoadedListResponse, + ThreadMetadataUpdateParams: CodexSchema.V2ThreadMetadataUpdateParams, + ThreadMetadataUpdateResponse: CodexSchema.V2ThreadMetadataUpdateResponse, + ThreadNameUpdatedNotification: CodexSchema.V2ThreadNameUpdatedNotification, + ThreadReadParams: CodexSchema.V2ThreadReadParams, + ThreadReadResponse: CodexSchema.V2ThreadReadResponse, + ThreadRealtimeClosedNotification: CodexSchema.V2ThreadRealtimeClosedNotification, + ThreadRealtimeErrorNotification: CodexSchema.V2ThreadRealtimeErrorNotification, + ThreadRealtimeItemAddedNotification: CodexSchema.V2ThreadRealtimeItemAddedNotification, + ThreadRealtimeOutputAudioDeltaNotification: + CodexSchema.V2ThreadRealtimeOutputAudioDeltaNotification, + ThreadRealtimeSdpNotification: CodexSchema.V2ThreadRealtimeSdpNotification, + ThreadRealtimeStartedNotification: CodexSchema.V2ThreadRealtimeStartedNotification, + ThreadRealtimeTranscriptUpdatedNotification: + CodexSchema.V2ThreadRealtimeTranscriptUpdatedNotification, + ThreadResumeParams: CodexSchema.V2ThreadResumeParams, + ThreadResumeResponse: CodexSchema.V2ThreadResumeResponse, + ThreadRollbackParams: CodexSchema.V2ThreadRollbackParams, + ThreadRollbackResponse: CodexSchema.V2ThreadRollbackResponse, + ThreadSetNameParams: CodexSchema.V2ThreadSetNameParams, + ThreadSetNameResponse: CodexSchema.V2ThreadSetNameResponse, + ThreadShellCommandParams: CodexSchema.V2ThreadShellCommandParams, + ThreadShellCommandResponse: CodexSchema.V2ThreadShellCommandResponse, + ThreadStartedNotification: CodexSchema.V2ThreadStartedNotification, + ThreadStartParams: CodexSchema.V2ThreadStartParams, + ThreadStartResponse: CodexSchema.V2ThreadStartResponse, + ThreadStatusChangedNotification: CodexSchema.V2ThreadStatusChangedNotification, + ThreadTokenUsageUpdatedNotification: CodexSchema.V2ThreadTokenUsageUpdatedNotification, + ThreadUnarchivedNotification: CodexSchema.V2ThreadUnarchivedNotification, + ThreadUnarchiveParams: CodexSchema.V2ThreadUnarchiveParams, + ThreadUnarchiveResponse: CodexSchema.V2ThreadUnarchiveResponse, + ThreadUnsubscribeParams: CodexSchema.V2ThreadUnsubscribeParams, + ThreadUnsubscribeResponse: CodexSchema.V2ThreadUnsubscribeResponse, + TurnCompletedNotification: CodexSchema.V2TurnCompletedNotification, + TurnDiffUpdatedNotification: CodexSchema.V2TurnDiffUpdatedNotification, + TurnInterruptParams: CodexSchema.V2TurnInterruptParams, + TurnInterruptResponse: CodexSchema.V2TurnInterruptResponse, + TurnPlanUpdatedNotification: CodexSchema.V2TurnPlanUpdatedNotification, + TurnStartedNotification: CodexSchema.V2TurnStartedNotification, + TurnStartParams: CodexSchema.V2TurnStartParams, + TurnStartResponse: CodexSchema.V2TurnStartResponse, + TurnSteerParams: CodexSchema.V2TurnSteerParams, + TurnSteerResponse: CodexSchema.V2TurnSteerResponse, + WindowsSandboxSetupCompletedNotification: CodexSchema.V2WindowsSandboxSetupCompletedNotification, + WindowsSandboxSetupStartParams: CodexSchema.V2WindowsSandboxSetupStartParams, + WindowsSandboxSetupStartResponse: CodexSchema.V2WindowsSandboxSetupStartResponse, + WindowsWorldWritableWarningNotification: CodexSchema.V2WindowsWorldWritableWarningNotification, +} as const; diff --git a/packages/effect-codex-app-server/src/_generated/schema.gen.ts b/packages/effect-codex-app-server/src/_generated/schema.gen.ts new file mode 100644 index 0000000000..5f2119a19b --- /dev/null +++ b/packages/effect-codex-app-server/src/_generated/schema.gen.ts @@ -0,0 +1,31734 @@ +// This file is generated by the effect-codex-app-server package. Do not edit manually. +// Upstream protocol ref: dbfe855f4fd0f5dcdf079882652a8efe622b0595 + +import * as Schema from "effect/Schema"; + +export type ApplyPatchApprovalParams__FileChange = + | { readonly content: string; readonly type: "add" } + | { readonly content: string; readonly type: "delete" } + | { readonly move_path?: string | null; readonly type: "update"; readonly unified_diff: string }; +export const ApplyPatchApprovalParams__FileChange = Schema.Union( + [ + Schema.Struct({ + content: Schema.String, + type: Schema.Literal("add").annotate({ title: "AddFileChangeType" }), + }).annotate({ title: "AddFileChange" }), + Schema.Struct({ + content: Schema.String, + type: Schema.Literal("delete").annotate({ title: "DeleteFileChangeType" }), + }).annotate({ title: "DeleteFileChange" }), + Schema.Struct({ + move_path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + type: Schema.Literal("update").annotate({ title: "UpdateFileChangeType" }), + unified_diff: Schema.String, + }).annotate({ title: "UpdateFileChange" }), + ], + { mode: "oneOf" }, +); + +export type ApplyPatchApprovalParams__ThreadId = string; +export const ApplyPatchApprovalParams__ThreadId = Schema.String; + +export type ApplyPatchApprovalResponse__NetworkPolicyRuleAction = "allow" | "deny"; +export const ApplyPatchApprovalResponse__NetworkPolicyRuleAction = Schema.Literals([ + "allow", + "deny", +]); + +export type ChatgptAuthTokensRefreshParams__ChatgptAuthTokensRefreshReason = "unauthorized"; +export const ChatgptAuthTokensRefreshParams__ChatgptAuthTokensRefreshReason = + Schema.Literal("unauthorized"); + +export type ClientRequest__AbsolutePathBuf = string; +export const ClientRequest__AbsolutePathBuf = Schema.String.annotate({ + description: + "A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\n\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.", +}); + +export type ClientRequest__ApprovalsReviewer = "user" | "guardian_subagent"; +export const ClientRequest__ApprovalsReviewer = Schema.Literals([ + "user", + "guardian_subagent", +]).annotate({ + description: + "Configures who approval requests are routed to for review. Examples include sandbox escapes, blocked network access, MCP approval prompts, and ARC escalations. Defaults to `user`. `guardian_subagent` uses a carefully prompted subagent to gather relevant context and apply a risk-based decision framework before approving or denying the request.", +}); + +export type ClientRequest__AppsListParams = { + readonly cursor?: string | null; + readonly forceRefetch?: boolean; + readonly limit?: number | null; + readonly threadId?: string | null; +}; +export const ClientRequest__AppsListParams = Schema.Struct({ + cursor: Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + description: "Opaque pagination cursor returned by a previous call.", + }), + Schema.Null, + ]), + ), + forceRefetch: Schema.optionalKey( + Schema.Boolean.annotate({ + description: "When true, bypass app caches and fetch the latest data from sources.", + }), + ), + limit: Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ + description: "Optional page size; defaults to a reasonable server-side value.", + format: "uint32", + }) + .check(Schema.isInt()) + .check(Schema.isGreaterThanOrEqualTo(0)), + Schema.Null, + ]), + ), + threadId: Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + description: + "Optional thread id used to evaluate app feature gating from that thread's config.", + }), + Schema.Null, + ]), + ), +}).annotate({ description: "EXPERIMENTAL - list available apps/connectors." }); + +export type ClientRequest__AskForApproval = + | "untrusted" + | "on-failure" + | "on-request" + | "never" + | { + readonly granular: { + readonly mcp_elicitations: boolean; + readonly request_permissions?: boolean; + readonly rules: boolean; + readonly sandbox_approval: boolean; + readonly skill_approval?: boolean; + }; + }; +export const ClientRequest__AskForApproval = Schema.Union( + [ + Schema.Literals(["untrusted", "on-failure", "on-request", "never"]), + Schema.Struct({ + granular: Schema.Struct({ + mcp_elicitations: Schema.Boolean, + request_permissions: Schema.optionalKey(Schema.Boolean.annotate({ default: false })), + rules: Schema.Boolean, + sandbox_approval: Schema.Boolean, + skill_approval: Schema.optionalKey(Schema.Boolean.annotate({ default: false })), + }), + }).annotate({ title: "GranularAskForApproval" }), + ], + { mode: "oneOf" }, +); + +export type ClientRequest__CancelLoginAccountParams = { readonly loginId: string }; +export const ClientRequest__CancelLoginAccountParams = Schema.Struct({ loginId: Schema.String }); + +export type ClientRequest__ClientInfo = { + readonly name: string; + readonly title?: string | null; + readonly version: string; +}; +export const ClientRequest__ClientInfo = Schema.Struct({ + name: Schema.String, + title: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + version: Schema.String, +}); + +export type ClientRequest__CommandExecResizeParams = { + readonly processId: string; + readonly size: { readonly cols: number; readonly rows: number }; +}; +export const ClientRequest__CommandExecResizeParams = Schema.Struct({ + processId: Schema.String.annotate({ + description: + "Client-supplied, connection-scoped `processId` from the original `command/exec` request.", + }), + size: Schema.Struct({ + cols: Schema.Number.annotate({ + description: "Terminal width in character cells.", + format: "uint16", + }) + .check(Schema.isInt()) + .check(Schema.isGreaterThanOrEqualTo(0)), + rows: Schema.Number.annotate({ + description: "Terminal height in character cells.", + format: "uint16", + }) + .check(Schema.isInt()) + .check(Schema.isGreaterThanOrEqualTo(0)), + }).annotate({ description: "PTY size in character cells for `command/exec` PTY sessions." }), +}).annotate({ description: "Resize a running PTY-backed `command/exec` session." }); + +export type ClientRequest__CommandExecTerminalSize = { + readonly cols: number; + readonly rows: number; +}; +export const ClientRequest__CommandExecTerminalSize = Schema.Struct({ + cols: Schema.Number.annotate({ + description: "Terminal width in character cells.", + format: "uint16", + }) + .check(Schema.isInt()) + .check(Schema.isGreaterThanOrEqualTo(0)), + rows: Schema.Number.annotate({ + description: "Terminal height in character cells.", + format: "uint16", + }) + .check(Schema.isInt()) + .check(Schema.isGreaterThanOrEqualTo(0)), +}).annotate({ description: "PTY size in character cells for `command/exec` PTY sessions." }); + +export type ClientRequest__CommandExecTerminateParams = { readonly processId: string }; +export const ClientRequest__CommandExecTerminateParams = Schema.Struct({ + processId: Schema.String.annotate({ + description: + "Client-supplied, connection-scoped `processId` from the original `command/exec` request.", + }), +}).annotate({ description: "Terminate a running `command/exec` session." }); + +export type ClientRequest__CommandExecWriteParams = { + readonly closeStdin?: boolean; + readonly deltaBase64?: string | null; + readonly processId: string; +}; +export const ClientRequest__CommandExecWriteParams = Schema.Struct({ + closeStdin: Schema.optionalKey( + Schema.Boolean.annotate({ + description: "Close stdin after writing `deltaBase64`, if present.", + }), + ), + deltaBase64: Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ description: "Optional base64-encoded stdin bytes to write." }), + Schema.Null, + ]), + ), + processId: Schema.String.annotate({ + description: + "Client-supplied, connection-scoped `processId` from the original `command/exec` request.", + }), +}).annotate({ + description: "Write stdin bytes to a running `command/exec` session, close stdin, or both.", +}); + +export type ClientRequest__ConfigReadParams = { + readonly cwd?: string | null; + readonly includeLayers?: boolean; +}; +export const ClientRequest__ConfigReadParams = Schema.Struct({ + cwd: Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + description: + "Optional working directory to resolve project config layers. If specified, return the effective config as seen from that directory (i.e., including any project layers between `cwd` and the project/repo root).", + }), + Schema.Null, + ]), + ), + includeLayers: Schema.optionalKey(Schema.Boolean.annotate({ default: false })), +}); + +export type ClientRequest__ContentItem = + | { readonly text: string; readonly type: "input_text" } + | { readonly image_url: string; readonly type: "input_image" } + | { readonly text: string; readonly type: "output_text" }; +export const ClientRequest__ContentItem = Schema.Union( + [ + Schema.Struct({ + text: Schema.String, + type: Schema.Literal("input_text").annotate({ title: "InputTextContentItemType" }), + }).annotate({ title: "InputTextContentItem" }), + Schema.Struct({ + image_url: Schema.String, + type: Schema.Literal("input_image").annotate({ title: "InputImageContentItemType" }), + }).annotate({ title: "InputImageContentItem" }), + Schema.Struct({ + text: Schema.String, + type: Schema.Literal("output_text").annotate({ title: "OutputTextContentItemType" }), + }).annotate({ title: "OutputTextContentItem" }), + ], + { mode: "oneOf" }, +); + +export type ClientRequest__ExperimentalFeatureEnablementSetParams = { + readonly enablement: { readonly [x: string]: boolean }; +}; +export const ClientRequest__ExperimentalFeatureEnablementSetParams = Schema.Struct({ + enablement: Schema.Record(Schema.String, Schema.Boolean).annotate({ + description: + "Process-wide runtime feature enablement keyed by canonical feature name.\n\nOnly named features are updated. Omitted features are left unchanged. Send an empty map for a no-op.", + }), +}); + +export type ClientRequest__ExperimentalFeatureListParams = { + readonly cursor?: string | null; + readonly limit?: number | null; +}; +export const ClientRequest__ExperimentalFeatureListParams = Schema.Struct({ + cursor: Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + description: "Opaque pagination cursor returned by a previous call.", + }), + Schema.Null, + ]), + ), + limit: Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ + description: "Optional page size; defaults to a reasonable server-side value.", + format: "uint32", + }) + .check(Schema.isInt()) + .check(Schema.isGreaterThanOrEqualTo(0)), + Schema.Null, + ]), + ), +}); + +export type ClientRequest__ExternalAgentConfigDetectParams = { + readonly cwds?: ReadonlyArray | null; + readonly includeHome?: boolean; +}; +export const ClientRequest__ExternalAgentConfigDetectParams = Schema.Struct({ + cwds: Schema.optionalKey( + Schema.Union([ + Schema.Array(Schema.String).annotate({ + description: "Zero or more working directories to include for repo-scoped detection.", + }), + Schema.Null, + ]), + ), + includeHome: Schema.optionalKey( + Schema.Boolean.annotate({ + description: "If true, include detection under the user's home (~/.claude, ~/.codex, etc.).", + }), + ), +}); + +export type ClientRequest__ExternalAgentConfigMigrationItemType = + | "AGENTS_MD" + | "CONFIG" + | "SKILLS" + | "MCP_SERVER_CONFIG"; +export const ClientRequest__ExternalAgentConfigMigrationItemType = Schema.Literals([ + "AGENTS_MD", + "CONFIG", + "SKILLS", + "MCP_SERVER_CONFIG", +]); + +export type ClientRequest__FeedbackUploadParams = { + readonly classification: string; + readonly extraLogFiles?: ReadonlyArray | null; + readonly includeLogs: boolean; + readonly reason?: string | null; + readonly threadId?: string | null; +}; +export const ClientRequest__FeedbackUploadParams = Schema.Struct({ + classification: Schema.String, + extraLogFiles: Schema.optionalKey(Schema.Union([Schema.Array(Schema.String), Schema.Null])), + includeLogs: Schema.Boolean, + reason: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + threadId: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), +}); + +export type ClientRequest__FsCopyParams = { + readonly destinationPath: string; + readonly recursive?: boolean; + readonly sourcePath: string; +}; +export const ClientRequest__FsCopyParams = Schema.Struct({ + destinationPath: Schema.String.annotate({ + description: + "A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\n\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.", + }), + recursive: Schema.optionalKey( + Schema.Boolean.annotate({ + description: "Required for directory copies; ignored for file copies.", + }), + ), + sourcePath: Schema.String.annotate({ + description: + "A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\n\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.", + }), +}).annotate({ description: "Copy a file or directory tree on the host filesystem." }); + +export type ClientRequest__FsCreateDirectoryParams = { + readonly path: string; + readonly recursive?: boolean | null; +}; +export const ClientRequest__FsCreateDirectoryParams = Schema.Struct({ + path: Schema.String.annotate({ + description: + "A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\n\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.", + }), + recursive: Schema.optionalKey( + Schema.Union([ + Schema.Boolean.annotate({ + description: "Whether parent directories should also be created. Defaults to `true`.", + }), + Schema.Null, + ]), + ), +}).annotate({ description: "Create a directory on the host filesystem." }); + +export type ClientRequest__FsGetMetadataParams = { readonly path: string }; +export const ClientRequest__FsGetMetadataParams = Schema.Struct({ + path: Schema.String.annotate({ + description: + "A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\n\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.", + }), +}).annotate({ description: "Request metadata for an absolute path." }); + +export type ClientRequest__FsReadDirectoryParams = { readonly path: string }; +export const ClientRequest__FsReadDirectoryParams = Schema.Struct({ + path: Schema.String.annotate({ + description: + "A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\n\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.", + }), +}).annotate({ description: "List direct child names for a directory." }); + +export type ClientRequest__FsReadFileParams = { readonly path: string }; +export const ClientRequest__FsReadFileParams = Schema.Struct({ + path: Schema.String.annotate({ + description: + "A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\n\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.", + }), +}).annotate({ description: "Read a file from the host filesystem." }); + +export type ClientRequest__FsRemoveParams = { + readonly force?: boolean | null; + readonly path: string; + readonly recursive?: boolean | null; +}; +export const ClientRequest__FsRemoveParams = Schema.Struct({ + force: Schema.optionalKey( + Schema.Union([ + Schema.Boolean.annotate({ + description: "Whether missing paths should be ignored. Defaults to `true`.", + }), + Schema.Null, + ]), + ), + path: Schema.String.annotate({ + description: + "A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\n\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.", + }), + recursive: Schema.optionalKey( + Schema.Union([ + Schema.Boolean.annotate({ + description: "Whether directory removal should recurse. Defaults to `true`.", + }), + Schema.Null, + ]), + ), +}).annotate({ description: "Remove a file or directory tree from the host filesystem." }); + +export type ClientRequest__FsUnwatchParams = { readonly watchId: string }; +export const ClientRequest__FsUnwatchParams = Schema.Struct({ + watchId: Schema.String.annotate({ + description: "Watch identifier previously provided to `fs/watch`.", + }), +}).annotate({ description: "Stop filesystem watch notifications for a prior `fs/watch`." }); + +export type ClientRequest__FsWatchParams = { readonly path: string; readonly watchId: string }; +export const ClientRequest__FsWatchParams = Schema.Struct({ + path: Schema.String.annotate({ + description: + "A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\n\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.", + }), + watchId: Schema.String.annotate({ + description: "Connection-scoped watch identifier used for `fs/unwatch` and `fs/changed`.", + }), +}).annotate({ description: "Start filesystem watch notifications for an absolute path." }); + +export type ClientRequest__FsWriteFileParams = { + readonly dataBase64: string; + readonly path: string; +}; +export const ClientRequest__FsWriteFileParams = Schema.Struct({ + dataBase64: Schema.String.annotate({ description: "File contents encoded as base64." }), + path: Schema.String.annotate({ + description: + "A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\n\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.", + }), +}).annotate({ description: "Write a file on the host filesystem." }); + +export type ClientRequest__FuzzyFileSearchParams = { + readonly cancellationToken?: string | null; + readonly query: string; + readonly roots: ReadonlyArray; +}; +export const ClientRequest__FuzzyFileSearchParams = Schema.Struct({ + cancellationToken: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + query: Schema.String, + roots: Schema.Array(Schema.String), +}); + +export type ClientRequest__GetAccountParams = { readonly refreshToken?: boolean }; +export const ClientRequest__GetAccountParams = Schema.Struct({ + refreshToken: Schema.optionalKey( + Schema.Boolean.annotate({ + description: + "When `true`, requests a proactive token refresh before returning.\n\nIn managed auth mode this triggers the normal refresh-token flow. In external auth mode this flag is ignored. Clients should refresh tokens themselves and call `account/login/start` with `chatgptAuthTokens`.", + default: false, + }), + ), +}); + +export type ClientRequest__GhostCommit = { + readonly id: string; + readonly parent?: string | null; + readonly preexisting_untracked_dirs: ReadonlyArray; + readonly preexisting_untracked_files: ReadonlyArray; +}; +export const ClientRequest__GhostCommit = Schema.Struct({ + id: Schema.String, + parent: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + preexisting_untracked_dirs: Schema.Array(Schema.String), + preexisting_untracked_files: Schema.Array(Schema.String), +}).annotate({ description: "Details of a ghost commit created from a repository state." }); + +export type ClientRequest__ImageDetail = "auto" | "low" | "high" | "original"; +export const ClientRequest__ImageDetail = Schema.Literals(["auto", "low", "high", "original"]); + +export type ClientRequest__InitializeCapabilities = { + readonly experimentalApi?: boolean; + readonly optOutNotificationMethods?: ReadonlyArray | null; +}; +export const ClientRequest__InitializeCapabilities = Schema.Struct({ + experimentalApi: Schema.optionalKey( + Schema.Boolean.annotate({ + description: "Opt into receiving experimental API methods and fields.", + default: false, + }), + ), + optOutNotificationMethods: Schema.optionalKey( + Schema.Union([ + Schema.Array(Schema.String).annotate({ + description: + "Exact notification method names that should be suppressed for this connection (for example `thread/started`).", + }), + Schema.Null, + ]), + ), +}).annotate({ description: "Client-declared capabilities negotiated during initialize." }); + +export type ClientRequest__LocalShellAction = { + readonly command: ReadonlyArray; + readonly env?: { readonly [x: string]: string } | null; + readonly timeout_ms?: number | null; + readonly type: "exec"; + readonly user?: string | null; + readonly working_directory?: string | null; +}; +export const ClientRequest__LocalShellAction = Schema.Union( + [ + Schema.Struct({ + command: Schema.Array(Schema.String), + env: Schema.optionalKey( + Schema.Union([Schema.Record(Schema.String, Schema.String), Schema.Null]), + ), + timeout_ms: Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ format: "uint64" }) + .check(Schema.isInt()) + .check(Schema.isGreaterThanOrEqualTo(0)), + Schema.Null, + ]), + ), + type: Schema.Literal("exec").annotate({ title: "ExecLocalShellActionType" }), + user: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + working_directory: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + }).annotate({ title: "ExecLocalShellAction" }), + ], + { mode: "oneOf" }, +); + +export type ClientRequest__LocalShellStatus = "completed" | "in_progress" | "incomplete"; +export const ClientRequest__LocalShellStatus = Schema.Literals([ + "completed", + "in_progress", + "incomplete", +]); + +export type ClientRequest__LoginAccountParams = + | { readonly apiKey: string; readonly type: "apiKey" } + | { readonly type: "chatgpt" } + | { readonly type: "chatgptDeviceCode" } + | { + readonly accessToken: string; + readonly chatgptAccountId: string; + readonly chatgptPlanType?: string | null; + readonly type: "chatgptAuthTokens"; + }; +export const ClientRequest__LoginAccountParams = Schema.Union( + [ + Schema.Struct({ + apiKey: Schema.String, + type: Schema.Literal("apiKey").annotate({ title: "ApiKeyLoginAccountParamsType" }), + }).annotate({ title: "ApiKeyLoginAccountParams" }), + Schema.Struct({ + type: Schema.Literal("chatgpt").annotate({ title: "ChatgptLoginAccountParamsType" }), + }).annotate({ title: "ChatgptLoginAccountParams" }), + Schema.Struct({ + type: Schema.Literal("chatgptDeviceCode").annotate({ + title: "ChatgptDeviceCodeLoginAccountParamsType", + }), + }).annotate({ title: "ChatgptDeviceCodeLoginAccountParams" }), + Schema.Struct({ + accessToken: Schema.String.annotate({ + description: + "Access token (JWT) supplied by the client. This token is used for backend API requests and email extraction.", + }), + chatgptAccountId: Schema.String.annotate({ + description: "Workspace/account identifier supplied by the client.", + }), + chatgptPlanType: Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + description: + "Optional plan type supplied by the client.\n\nWhen `null`, Codex attempts to derive the plan type from access-token claims. If unavailable, the plan defaults to `unknown`.", + }), + Schema.Null, + ]), + ), + type: Schema.Literal("chatgptAuthTokens").annotate({ + title: "ChatgptAuthTokensLoginAccountParamsType", + }), + }).annotate({ + title: "ChatgptAuthTokensLoginAccountParams", + description: + "[UNSTABLE] FOR OPENAI INTERNAL USE ONLY - DO NOT USE. The access token must contain the same scopes that Codex-managed ChatGPT auth tokens have.", + }), + ], + { mode: "oneOf" }, +); + +export type ClientRequest__McpResourceReadParams = { + readonly server: string; + readonly threadId: string; + readonly uri: string; +}; +export const ClientRequest__McpResourceReadParams = Schema.Struct({ + server: Schema.String, + threadId: Schema.String, + uri: Schema.String, +}); + +export type ClientRequest__McpServerOauthLoginParams = { + readonly name: string; + readonly scopes?: ReadonlyArray | null; + readonly timeoutSecs?: number | null; +}; +export const ClientRequest__McpServerOauthLoginParams = Schema.Struct({ + name: Schema.String, + scopes: Schema.optionalKey(Schema.Union([Schema.Array(Schema.String), Schema.Null])), + timeoutSecs: Schema.optionalKey( + Schema.Union([Schema.Number.annotate({ format: "int64" }).check(Schema.isInt()), Schema.Null]), + ), +}); + +export type ClientRequest__McpServerStatusDetail = "full" | "toolsAndAuthOnly"; +export const ClientRequest__McpServerStatusDetail = Schema.Literals(["full", "toolsAndAuthOnly"]); + +export type ClientRequest__McpServerToolCallParams = { + readonly _meta?: unknown; + readonly arguments?: unknown; + readonly server: string; + readonly threadId: string; + readonly tool: string; +}; +export const ClientRequest__McpServerToolCallParams = Schema.Struct({ + _meta: Schema.optionalKey(Schema.Unknown), + arguments: Schema.optionalKey(Schema.Unknown), + server: Schema.String, + threadId: Schema.String, + tool: Schema.String, +}); + +export type ClientRequest__MergeStrategy = "replace" | "upsert"; +export const ClientRequest__MergeStrategy = Schema.Literals(["replace", "upsert"]); + +export type ClientRequest__MessagePhase = "commentary" | "final_answer"; +export const ClientRequest__MessagePhase = Schema.Literals(["commentary", "final_answer"]).annotate( + { + description: + 'Classifies an assistant message as interim commentary or final answer text.\n\nProviders do not emit this consistently, so callers must treat `None` as "phase unknown" and keep compatibility behavior for legacy models.', + }, +); + +export type ClientRequest__ModeKind = "plan" | "default"; +export const ClientRequest__ModeKind = Schema.Literals(["plan", "default"]).annotate({ + description: "Initial collaboration mode to use when the TUI starts.", +}); + +export type ClientRequest__ModelListParams = { + readonly cursor?: string | null; + readonly includeHidden?: boolean | null; + readonly limit?: number | null; +}; +export const ClientRequest__ModelListParams = Schema.Struct({ + cursor: Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + description: "Opaque pagination cursor returned by a previous call.", + }), + Schema.Null, + ]), + ), + includeHidden: Schema.optionalKey( + Schema.Union([ + Schema.Boolean.annotate({ + description: "When true, include models that are hidden from the default picker list.", + }), + Schema.Null, + ]), + ), + limit: Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ + description: "Optional page size; defaults to a reasonable server-side value.", + format: "uint32", + }) + .check(Schema.isInt()) + .check(Schema.isGreaterThanOrEqualTo(0)), + Schema.Null, + ]), + ), +}); + +export type ClientRequest__Personality = "none" | "friendly" | "pragmatic"; +export const ClientRequest__Personality = Schema.Literals(["none", "friendly", "pragmatic"]); + +export type ClientRequest__PluginUninstallParams = { + readonly forceRemoteSync?: boolean; + readonly pluginId: string; +}; +export const ClientRequest__PluginUninstallParams = Schema.Struct({ + forceRemoteSync: Schema.optionalKey( + Schema.Boolean.annotate({ + description: "When true, apply the remote plugin change before the local uninstall flow.", + }), + ), + pluginId: Schema.String, +}); + +export type ClientRequest__ReasoningEffort = + | "none" + | "minimal" + | "low" + | "medium" + | "high" + | "xhigh"; +export const ClientRequest__ReasoningEffort = Schema.Literals([ + "none", + "minimal", + "low", + "medium", + "high", + "xhigh", +]).annotate({ + description: + "See https://platform.openai.com/docs/guides/reasoning?api-mode=responses#get-started-with-reasoning", +}); + +export type ClientRequest__ReasoningItemContent = + | { readonly text: string; readonly type: "reasoning_text" } + | { readonly text: string; readonly type: "text" }; +export const ClientRequest__ReasoningItemContent = Schema.Union( + [ + Schema.Struct({ + text: Schema.String, + type: Schema.Literal("reasoning_text").annotate({ + title: "ReasoningTextReasoningItemContentType", + }), + }).annotate({ title: "ReasoningTextReasoningItemContent" }), + Schema.Struct({ + text: Schema.String, + type: Schema.Literal("text").annotate({ title: "TextReasoningItemContentType" }), + }).annotate({ title: "TextReasoningItemContent" }), + ], + { mode: "oneOf" }, +); + +export type ClientRequest__ReasoningItemReasoningSummary = { + readonly text: string; + readonly type: "summary_text"; +}; +export const ClientRequest__ReasoningItemReasoningSummary = Schema.Union( + [ + Schema.Struct({ + text: Schema.String, + type: Schema.Literal("summary_text").annotate({ + title: "SummaryTextReasoningItemReasoningSummaryType", + }), + }).annotate({ title: "SummaryTextReasoningItemReasoningSummary" }), + ], + { mode: "oneOf" }, +); + +export type ClientRequest__ReasoningSummary = "auto" | "concise" | "detailed" | "none"; +export const ClientRequest__ReasoningSummary = Schema.Union( + [ + Schema.Literals(["auto", "concise", "detailed"]), + Schema.Literal("none").annotate({ description: "Option to disable reasoning summaries." }), + ], + { mode: "oneOf" }, +).annotate({ + description: + "A summary of the reasoning performed by the model. This can be useful for debugging and understanding the model's reasoning process. See https://platform.openai.com/docs/guides/reasoning?api-mode=responses#reasoning-summaries", +}); + +export type ClientRequest__RequestId = string | number; +export const ClientRequest__RequestId = Schema.Union([ + Schema.String, + Schema.Number.annotate({ format: "int64" }).check(Schema.isInt()), +]); + +export type ClientRequest__ResponsesApiWebSearchAction = + | { + readonly queries?: ReadonlyArray | null; + readonly query?: string | null; + readonly type: "search"; + } + | { readonly type: "open_page"; readonly url?: string | null } + | { + readonly pattern?: string | null; + readonly type: "find_in_page"; + readonly url?: string | null; + } + | { readonly type: "other" }; +export const ClientRequest__ResponsesApiWebSearchAction = Schema.Union( + [ + Schema.Struct({ + queries: Schema.optionalKey(Schema.Union([Schema.Array(Schema.String), Schema.Null])), + query: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + type: Schema.Literal("search").annotate({ title: "SearchResponsesApiWebSearchActionType" }), + }).annotate({ title: "SearchResponsesApiWebSearchAction" }), + Schema.Struct({ + type: Schema.Literal("open_page").annotate({ + title: "OpenPageResponsesApiWebSearchActionType", + }), + url: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + }).annotate({ title: "OpenPageResponsesApiWebSearchAction" }), + Schema.Struct({ + pattern: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + type: Schema.Literal("find_in_page").annotate({ + title: "FindInPageResponsesApiWebSearchActionType", + }), + url: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + }).annotate({ title: "FindInPageResponsesApiWebSearchAction" }), + Schema.Struct({ + type: Schema.Literal("other").annotate({ title: "OtherResponsesApiWebSearchActionType" }), + }).annotate({ title: "OtherResponsesApiWebSearchAction" }), + ], + { mode: "oneOf" }, +); + +export type ClientRequest__ReviewDelivery = "inline" | "detached"; +export const ClientRequest__ReviewDelivery = Schema.Literals(["inline", "detached"]); + +export type ClientRequest__ReviewTarget = + | { readonly type: "uncommittedChanges" } + | { readonly branch: string; readonly type: "baseBranch" } + | { readonly sha: string; readonly title?: string | null; readonly type: "commit" } + | { readonly instructions: string; readonly type: "custom" }; +export const ClientRequest__ReviewTarget = Schema.Union( + [ + Schema.Struct({ + type: Schema.Literal("uncommittedChanges").annotate({ + title: "UncommittedChangesReviewTargetType", + }), + }).annotate({ + title: "UncommittedChangesReviewTarget", + description: "Review the working tree: staged, unstaged, and untracked files.", + }), + Schema.Struct({ + branch: Schema.String, + type: Schema.Literal("baseBranch").annotate({ title: "BaseBranchReviewTargetType" }), + }).annotate({ + title: "BaseBranchReviewTarget", + description: "Review changes between the current branch and the given base branch.", + }), + Schema.Struct({ + sha: Schema.String, + title: Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + description: "Optional human-readable label (e.g., commit subject) for UIs.", + }), + Schema.Null, + ]), + ), + type: Schema.Literal("commit").annotate({ title: "CommitReviewTargetType" }), + }).annotate({ + title: "CommitReviewTarget", + description: "Review the changes introduced by a specific commit.", + }), + Schema.Struct({ + instructions: Schema.String, + type: Schema.Literal("custom").annotate({ title: "CustomReviewTargetType" }), + }).annotate({ + title: "CustomReviewTarget", + description: "Arbitrary instructions, equivalent to the old free-form prompt.", + }), + ], + { mode: "oneOf" }, +); + +export type ClientRequest__SandboxMode = "read-only" | "workspace-write" | "danger-full-access"; +export const ClientRequest__SandboxMode = Schema.Literals([ + "read-only", + "workspace-write", + "danger-full-access", +]); + +export type ClientRequest__ServiceTier = "fast" | "flex"; +export const ClientRequest__ServiceTier = Schema.Literals(["fast", "flex"]); + +export type ClientRequest__SkillsListExtraRootsForCwd = { + readonly cwd: string; + readonly extraUserRoots: ReadonlyArray; +}; +export const ClientRequest__SkillsListExtraRootsForCwd = Schema.Struct({ + cwd: Schema.String, + extraUserRoots: Schema.Array(Schema.String), +}); + +export type ClientRequest__TextElement = { + readonly byteRange: { readonly end: number; readonly start: number }; + readonly placeholder?: string | null; +}; +export const ClientRequest__TextElement = Schema.Struct({ + byteRange: Schema.Struct({ + end: Schema.Number.annotate({ format: "uint" }) + .check(Schema.isInt()) + .check(Schema.isGreaterThanOrEqualTo(0)), + start: Schema.Number.annotate({ format: "uint" }) + .check(Schema.isInt()) + .check(Schema.isGreaterThanOrEqualTo(0)), + }).annotate({ + description: "Byte range in the parent `text` buffer that this element occupies.", + }), + placeholder: Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + description: "Optional human-readable placeholder for the element, displayed in the UI.", + }), + Schema.Null, + ]), + ), +}); + +export type ClientRequest__ThreadArchiveParams = { readonly threadId: string }; +export const ClientRequest__ThreadArchiveParams = Schema.Struct({ threadId: Schema.String }); + +export type ClientRequest__ThreadCompactStartParams = { readonly threadId: string }; +export const ClientRequest__ThreadCompactStartParams = Schema.Struct({ threadId: Schema.String }); + +export type ClientRequest__ThreadLoadedListParams = { + readonly cursor?: string | null; + readonly limit?: number | null; +}; +export const ClientRequest__ThreadLoadedListParams = Schema.Struct({ + cursor: Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + description: "Opaque pagination cursor returned by a previous call.", + }), + Schema.Null, + ]), + ), + limit: Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ + description: "Optional page size; defaults to no limit.", + format: "uint32", + }) + .check(Schema.isInt()) + .check(Schema.isGreaterThanOrEqualTo(0)), + Schema.Null, + ]), + ), +}); + +export type ClientRequest__ThreadMetadataGitInfoUpdateParams = { + readonly branch?: string | null; + readonly originUrl?: string | null; + readonly sha?: string | null; +}; +export const ClientRequest__ThreadMetadataGitInfoUpdateParams = Schema.Struct({ + branch: Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + description: + "Omit to leave the stored branch unchanged, set to `null` to clear it, or provide a non-empty string to replace it.", + }), + Schema.Null, + ]), + ), + originUrl: Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + description: + "Omit to leave the stored origin URL unchanged, set to `null` to clear it, or provide a non-empty string to replace it.", + }), + Schema.Null, + ]), + ), + sha: Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + description: + "Omit to leave the stored commit unchanged, set to `null` to clear it, or provide a non-empty string to replace it.", + }), + Schema.Null, + ]), + ), +}); + +export type ClientRequest__ThreadReadParams = { + readonly includeTurns?: boolean; + readonly threadId: string; +}; +export const ClientRequest__ThreadReadParams = Schema.Struct({ + includeTurns: Schema.optionalKey( + Schema.Boolean.annotate({ + description: "When true, include turns and their items from rollout history.", + default: false, + }), + ), + threadId: Schema.String, +}); + +export type ClientRequest__ThreadRollbackParams = { + readonly numTurns: number; + readonly threadId: string; +}; +export const ClientRequest__ThreadRollbackParams = Schema.Struct({ + numTurns: Schema.Number.annotate({ + description: + "The number of turns to drop from the end of the thread. Must be >= 1.\n\nThis only modifies the thread's history and does not revert local file changes that have been made by the agent. Clients are responsible for reverting these changes.", + format: "uint32", + }) + .check(Schema.isInt()) + .check(Schema.isGreaterThanOrEqualTo(0)), + threadId: Schema.String, +}); + +export type ClientRequest__ThreadSetNameParams = { + readonly name: string; + readonly threadId: string; +}; +export const ClientRequest__ThreadSetNameParams = Schema.Struct({ + name: Schema.String, + threadId: Schema.String, +}); + +export type ClientRequest__ThreadShellCommandParams = { + readonly command: string; + readonly threadId: string; +}; +export const ClientRequest__ThreadShellCommandParams = Schema.Struct({ + command: Schema.String.annotate({ + description: + "Shell command string evaluated by the thread's configured shell. Unlike `command/exec`, this intentionally preserves shell syntax such as pipes, redirects, and quoting. This runs unsandboxed with full access rather than inheriting the thread sandbox policy.", + }), + threadId: Schema.String, +}); + +export type ClientRequest__ThreadSortKey = "created_at" | "updated_at"; +export const ClientRequest__ThreadSortKey = Schema.Literals(["created_at", "updated_at"]); + +export type ClientRequest__ThreadSourceKind = + | "cli" + | "vscode" + | "exec" + | "appServer" + | "subAgent" + | "subAgentReview" + | "subAgentCompact" + | "subAgentThreadSpawn" + | "subAgentOther" + | "unknown"; +export const ClientRequest__ThreadSourceKind = Schema.Literals([ + "cli", + "vscode", + "exec", + "appServer", + "subAgent", + "subAgentReview", + "subAgentCompact", + "subAgentThreadSpawn", + "subAgentOther", + "unknown", +]); + +export type ClientRequest__ThreadStartSource = "startup" | "clear"; +export const ClientRequest__ThreadStartSource = Schema.Literals(["startup", "clear"]); + +export type ClientRequest__ThreadUnarchiveParams = { readonly threadId: string }; +export const ClientRequest__ThreadUnarchiveParams = Schema.Struct({ threadId: Schema.String }); + +export type ClientRequest__ThreadUnsubscribeParams = { readonly threadId: string }; +export const ClientRequest__ThreadUnsubscribeParams = Schema.Struct({ threadId: Schema.String }); + +export type ClientRequest__TurnInterruptParams = { + readonly threadId: string; + readonly turnId: string; +}; +export const ClientRequest__TurnInterruptParams = Schema.Struct({ + threadId: Schema.String, + turnId: Schema.String, +}); + +export type ClientRequest__WindowsSandboxSetupMode = "elevated" | "unelevated"; +export const ClientRequest__WindowsSandboxSetupMode = Schema.Literals(["elevated", "unelevated"]); + +export type CommandExecutionRequestApprovalParams__AbsolutePathBuf = string; +export const CommandExecutionRequestApprovalParams__AbsolutePathBuf = Schema.String.annotate({ + description: + "A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\n\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.", +}); + +export type CommandExecutionRequestApprovalParams__AdditionalNetworkPermissions = { + readonly enabled?: boolean | null; +}; +export const CommandExecutionRequestApprovalParams__AdditionalNetworkPermissions = Schema.Struct({ + enabled: Schema.optionalKey(Schema.Union([Schema.Boolean, Schema.Null])), +}); + +export type CommandExecutionRequestApprovalParams__CommandAction = + | { + readonly command: string; + readonly name: string; + readonly path: string; + readonly type: "read"; + } + | { readonly command: string; readonly path?: string | null; readonly type: "listFiles" } + | { + readonly command: string; + readonly path?: string | null; + readonly query?: string | null; + readonly type: "search"; + } + | { readonly command: string; readonly type: "unknown" }; +export const CommandExecutionRequestApprovalParams__CommandAction = Schema.Union( + [ + Schema.Struct({ + command: Schema.String, + name: Schema.String, + path: Schema.String, + type: Schema.Literal("read").annotate({ title: "ReadCommandActionType" }), + }).annotate({ title: "ReadCommandAction" }), + Schema.Struct({ + command: Schema.String, + path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + type: Schema.Literal("listFiles").annotate({ title: "ListFilesCommandActionType" }), + }).annotate({ title: "ListFilesCommandAction" }), + Schema.Struct({ + command: Schema.String, + path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + query: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + type: Schema.Literal("search").annotate({ title: "SearchCommandActionType" }), + }).annotate({ title: "SearchCommandAction" }), + Schema.Struct({ + command: Schema.String, + type: Schema.Literal("unknown").annotate({ title: "UnknownCommandActionType" }), + }).annotate({ title: "UnknownCommandAction" }), + ], + { mode: "oneOf" }, +); + +export type CommandExecutionRequestApprovalParams__NetworkApprovalProtocol = + | "http" + | "https" + | "socks5Tcp" + | "socks5Udp"; +export const CommandExecutionRequestApprovalParams__NetworkApprovalProtocol = Schema.Literals([ + "http", + "https", + "socks5Tcp", + "socks5Udp", +]); + +export type CommandExecutionRequestApprovalParams__NetworkPolicyRuleAction = "allow" | "deny"; +export const CommandExecutionRequestApprovalParams__NetworkPolicyRuleAction = Schema.Literals([ + "allow", + "deny", +]); + +export type CommandExecutionRequestApprovalResponse__NetworkPolicyRuleAction = "allow" | "deny"; +export const CommandExecutionRequestApprovalResponse__NetworkPolicyRuleAction = Schema.Literals([ + "allow", + "deny", +]); + +export type DynamicToolCallResponse__DynamicToolCallOutputContentItem = + | { readonly text: string; readonly type: "inputText" } + | { readonly imageUrl: string; readonly type: "inputImage" }; +export const DynamicToolCallResponse__DynamicToolCallOutputContentItem = Schema.Union( + [ + Schema.Struct({ + text: Schema.String, + type: Schema.Literal("inputText").annotate({ + title: "InputTextDynamicToolCallOutputContentItemType", + }), + }).annotate({ title: "InputTextDynamicToolCallOutputContentItem" }), + Schema.Struct({ + imageUrl: Schema.String, + type: Schema.Literal("inputImage").annotate({ + title: "InputImageDynamicToolCallOutputContentItemType", + }), + }).annotate({ title: "InputImageDynamicToolCallOutputContentItem" }), + ], + { mode: "oneOf" }, +); + +export type ExecCommandApprovalParams__ParsedCommand = + | { readonly cmd: string; readonly name: string; readonly path: string; readonly type: "read" } + | { readonly cmd: string; readonly path?: string | null; readonly type: "list_files" } + | { + readonly cmd: string; + readonly path?: string | null; + readonly query?: string | null; + readonly type: "search"; + } + | { readonly cmd: string; readonly type: "unknown" }; +export const ExecCommandApprovalParams__ParsedCommand = Schema.Union( + [ + Schema.Struct({ + cmd: Schema.String, + name: Schema.String, + path: Schema.String.annotate({ + description: + "(Best effort) Path to the file being read by the command. When possible, this is an absolute path, though when relative, it should be resolved against the `cwd`` that will be used to run the command to derive the absolute path.", + }), + type: Schema.Literal("read").annotate({ title: "ReadParsedCommandType" }), + }).annotate({ title: "ReadParsedCommand" }), + Schema.Struct({ + cmd: Schema.String, + path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + type: Schema.Literal("list_files").annotate({ title: "ListFilesParsedCommandType" }), + }).annotate({ title: "ListFilesParsedCommand" }), + Schema.Struct({ + cmd: Schema.String, + path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + query: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + type: Schema.Literal("search").annotate({ title: "SearchParsedCommandType" }), + }).annotate({ title: "SearchParsedCommand" }), + Schema.Struct({ + cmd: Schema.String, + type: Schema.Literal("unknown").annotate({ title: "UnknownParsedCommandType" }), + }).annotate({ title: "UnknownParsedCommand" }), + ], + { mode: "oneOf" }, +); + +export type ExecCommandApprovalParams__ThreadId = string; +export const ExecCommandApprovalParams__ThreadId = Schema.String; + +export type ExecCommandApprovalResponse__NetworkPolicyRuleAction = "allow" | "deny"; +export const ExecCommandApprovalResponse__NetworkPolicyRuleAction = Schema.Literals([ + "allow", + "deny", +]); + +export type FileChangeRequestApprovalResponse__FileChangeApprovalDecision = + | "accept" + | "acceptForSession" + | "decline" + | "cancel"; +export const FileChangeRequestApprovalResponse__FileChangeApprovalDecision = Schema.Literals([ + "accept", + "acceptForSession", + "decline", + "cancel", +]); + +export type FuzzyFileSearchResponse__FuzzyFileSearchMatchType = "file" | "directory"; +export const FuzzyFileSearchResponse__FuzzyFileSearchMatchType = Schema.Literals([ + "file", + "directory", +]); + +export type FuzzyFileSearchSessionUpdatedNotification__FuzzyFileSearchMatchType = + | "file" + | "directory"; +export const FuzzyFileSearchSessionUpdatedNotification__FuzzyFileSearchMatchType = Schema.Literals([ + "file", + "directory", +]); + +export type JSONRPCError__JSONRPCErrorError = { + readonly code: number; + readonly data?: unknown; + readonly message: string; +}; +export const JSONRPCError__JSONRPCErrorError = Schema.Struct({ + code: Schema.Number.annotate({ format: "int64" }).check(Schema.isInt()), + data: Schema.optionalKey(Schema.Unknown), + message: Schema.String, +}); + +export type JSONRPCError__RequestId = string | number; +export const JSONRPCError__RequestId = Schema.Union([ + Schema.String, + Schema.Number.annotate({ format: "int64" }).check(Schema.isInt()), +]); + +export type JSONRPCMessage__JSONRPCErrorError = { + readonly code: number; + readonly data?: unknown; + readonly message: string; +}; +export const JSONRPCMessage__JSONRPCErrorError = Schema.Struct({ + code: Schema.Number.annotate({ format: "int64" }).check(Schema.isInt()), + data: Schema.optionalKey(Schema.Unknown), + message: Schema.String, +}); + +export type JSONRPCMessage__JSONRPCNotification = { + readonly method: string; + readonly params?: unknown; +}; +export const JSONRPCMessage__JSONRPCNotification = Schema.Struct({ + method: Schema.String, + params: Schema.optionalKey(Schema.Unknown), +}).annotate({ description: "A notification which does not expect a response." }); + +export type JSONRPCMessage__RequestId = string | number; +export const JSONRPCMessage__RequestId = Schema.Union([ + Schema.String, + Schema.Number.annotate({ format: "int64" }).check(Schema.isInt()), +]); + +export type JSONRPCMessage__W3cTraceContext = { + readonly traceparent?: string | null; + readonly tracestate?: string | null; +}; +export const JSONRPCMessage__W3cTraceContext = Schema.Struct({ + traceparent: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + tracestate: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), +}); + +export type JSONRPCRequest__RequestId = string | number; +export const JSONRPCRequest__RequestId = Schema.Union([ + Schema.String, + Schema.Number.annotate({ format: "int64" }).check(Schema.isInt()), +]); + +export type JSONRPCRequest__W3cTraceContext = { + readonly traceparent?: string | null; + readonly tracestate?: string | null; +}; +export const JSONRPCRequest__W3cTraceContext = Schema.Struct({ + traceparent: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + tracestate: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), +}); + +export type JSONRPCResponse__RequestId = string | number; +export const JSONRPCResponse__RequestId = Schema.Union([ + Schema.String, + Schema.Number.annotate({ format: "int64" }).check(Schema.isInt()), +]); + +export type McpServerElicitationRequestParams__McpElicitationArrayType = "array"; +export const McpServerElicitationRequestParams__McpElicitationArrayType = Schema.Literal("array"); + +export type McpServerElicitationRequestParams__McpElicitationBooleanType = "boolean"; +export const McpServerElicitationRequestParams__McpElicitationBooleanType = + Schema.Literal("boolean"); + +export type McpServerElicitationRequestParams__McpElicitationConstOption = { + readonly const: string; + readonly title: string; +}; +export const McpServerElicitationRequestParams__McpElicitationConstOption = Schema.Struct({ + const: Schema.String, + title: Schema.String, +}); + +export type McpServerElicitationRequestParams__McpElicitationNumberType = "number" | "integer"; +export const McpServerElicitationRequestParams__McpElicitationNumberType = Schema.Literals([ + "number", + "integer", +]); + +export type McpServerElicitationRequestParams__McpElicitationObjectType = "object"; +export const McpServerElicitationRequestParams__McpElicitationObjectType = Schema.Literal("object"); + +export type McpServerElicitationRequestParams__McpElicitationStringFormat = + | "email" + | "uri" + | "date" + | "date-time"; +export const McpServerElicitationRequestParams__McpElicitationStringFormat = Schema.Literals([ + "email", + "uri", + "date", + "date-time", +]); + +export type McpServerElicitationRequestParams__McpElicitationStringType = "string"; +export const McpServerElicitationRequestParams__McpElicitationStringType = Schema.Literal("string"); + +export type McpServerElicitationRequestResponse__McpServerElicitationAction = + | "accept" + | "decline" + | "cancel"; +export const McpServerElicitationRequestResponse__McpServerElicitationAction = Schema.Literals([ + "accept", + "decline", + "cancel", +]); + +export type PermissionsRequestApprovalParams__AbsolutePathBuf = string; +export const PermissionsRequestApprovalParams__AbsolutePathBuf = Schema.String.annotate({ + description: + "A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\n\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.", +}); + +export type PermissionsRequestApprovalParams__AdditionalNetworkPermissions = { + readonly enabled?: boolean | null; +}; +export const PermissionsRequestApprovalParams__AdditionalNetworkPermissions = Schema.Struct({ + enabled: Schema.optionalKey(Schema.Union([Schema.Boolean, Schema.Null])), +}); + +export type PermissionsRequestApprovalResponse__AbsolutePathBuf = string; +export const PermissionsRequestApprovalResponse__AbsolutePathBuf = Schema.String.annotate({ + description: + "A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\n\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.", +}); + +export type PermissionsRequestApprovalResponse__AdditionalNetworkPermissions = { + readonly enabled?: boolean | null; +}; +export const PermissionsRequestApprovalResponse__AdditionalNetworkPermissions = Schema.Struct({ + enabled: Schema.optionalKey(Schema.Union([Schema.Boolean, Schema.Null])), +}); + +export type ServerNotification__AbsolutePathBuf = string; +export const ServerNotification__AbsolutePathBuf = Schema.String.annotate({ + description: + "A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\n\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.", +}); + +export type ServerNotification__AccountLoginCompletedNotification = { + readonly error?: string | null; + readonly loginId?: string | null; + readonly success: boolean; +}; +export const ServerNotification__AccountLoginCompletedNotification = Schema.Struct({ + error: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + loginId: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + success: Schema.Boolean, +}); + +export type ServerNotification__AgentMessageDeltaNotification = { + readonly delta: string; + readonly itemId: string; + readonly threadId: string; + readonly turnId: string; +}; +export const ServerNotification__AgentMessageDeltaNotification = Schema.Struct({ + delta: Schema.String, + itemId: Schema.String, + threadId: Schema.String, + turnId: Schema.String, +}); + +export type ServerNotification__AgentPath = string; +export const ServerNotification__AgentPath = Schema.String; + +export type ServerNotification__AppBranding = { + readonly category?: string | null; + readonly developer?: string | null; + readonly isDiscoverableApp: boolean; + readonly privacyPolicy?: string | null; + readonly termsOfService?: string | null; + readonly website?: string | null; +}; +export const ServerNotification__AppBranding = Schema.Struct({ + category: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + developer: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + isDiscoverableApp: Schema.Boolean, + privacyPolicy: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + termsOfService: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + website: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), +}).annotate({ description: "EXPERIMENTAL - app metadata returned by app-list APIs." }); + +export type ServerNotification__AppReview = { readonly status: string }; +export const ServerNotification__AppReview = Schema.Struct({ status: Schema.String }); + +export type ServerNotification__AppScreenshot = { + readonly fileId?: string | null; + readonly url?: string | null; + readonly userPrompt: string; +}; +export const ServerNotification__AppScreenshot = Schema.Struct({ + fileId: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + url: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + userPrompt: Schema.String, +}); + +export type ServerNotification__AuthMode = "apikey" | "chatgpt" | "chatgptAuthTokens"; +export const ServerNotification__AuthMode = Schema.Literals([ + "apikey", + "chatgpt", + "chatgptAuthTokens", +]).annotate({ description: "Authentication mode for OpenAI-backed providers." }); + +export type ServerNotification__AutoReviewDecisionSource = "agent"; +export const ServerNotification__AutoReviewDecisionSource = Schema.Literal("agent").annotate({ + description: "[UNSTABLE] Source that produced a terminal guardian approval review decision.", +}); + +export type ServerNotification__CollabAgentStatus = + | "pendingInit" + | "running" + | "interrupted" + | "completed" + | "errored" + | "shutdown" + | "notFound"; +export const ServerNotification__CollabAgentStatus = Schema.Literals([ + "pendingInit", + "running", + "interrupted", + "completed", + "errored", + "shutdown", + "notFound", +]); + +export type ServerNotification__CommandAction = + | { + readonly command: string; + readonly name: string; + readonly path: string; + readonly type: "read"; + } + | { readonly command: string; readonly path?: string | null; readonly type: "listFiles" } + | { + readonly command: string; + readonly path?: string | null; + readonly query?: string | null; + readonly type: "search"; + } + | { readonly command: string; readonly type: "unknown" }; +export const ServerNotification__CommandAction = Schema.Union( + [ + Schema.Struct({ + command: Schema.String, + name: Schema.String, + path: Schema.String, + type: Schema.Literal("read").annotate({ title: "ReadCommandActionType" }), + }).annotate({ title: "ReadCommandAction" }), + Schema.Struct({ + command: Schema.String, + path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + type: Schema.Literal("listFiles").annotate({ title: "ListFilesCommandActionType" }), + }).annotate({ title: "ListFilesCommandAction" }), + Schema.Struct({ + command: Schema.String, + path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + query: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + type: Schema.Literal("search").annotate({ title: "SearchCommandActionType" }), + }).annotate({ title: "SearchCommandAction" }), + Schema.Struct({ + command: Schema.String, + type: Schema.Literal("unknown").annotate({ title: "UnknownCommandActionType" }), + }).annotate({ title: "UnknownCommandAction" }), + ], + { mode: "oneOf" }, +); + +export type ServerNotification__CommandExecOutputDeltaNotification = { + readonly capReached: boolean; + readonly deltaBase64: string; + readonly processId: string; + readonly stream: "stdout" | "stderr"; +}; +export const ServerNotification__CommandExecOutputDeltaNotification = Schema.Struct({ + capReached: Schema.Boolean.annotate({ + description: + "`true` on the final streamed chunk for a stream when `outputBytesCap` truncated later output on that stream.", + }), + deltaBase64: Schema.String.annotate({ description: "Base64-encoded output bytes." }), + processId: Schema.String.annotate({ + description: + "Client-supplied, connection-scoped `processId` from the original `command/exec` request.", + }), + stream: Schema.Literals(["stdout", "stderr"]).annotate({ + description: "Stream label for `command/exec/outputDelta` notifications.", + }), +}).annotate({ + description: + "Base64-encoded output chunk emitted for a streaming `command/exec` request.\n\nThese notifications are connection-scoped. If the originating connection closes, the server terminates the process.", +}); + +export type ServerNotification__CommandExecutionOutputDeltaNotification = { + readonly delta: string; + readonly itemId: string; + readonly threadId: string; + readonly turnId: string; +}; +export const ServerNotification__CommandExecutionOutputDeltaNotification = Schema.Struct({ + delta: Schema.String, + itemId: Schema.String, + threadId: Schema.String, + turnId: Schema.String, +}); + +export type ServerNotification__CommandExecutionStatus = + | "inProgress" + | "completed" + | "failed" + | "declined"; +export const ServerNotification__CommandExecutionStatus = Schema.Literals([ + "inProgress", + "completed", + "failed", + "declined", +]); + +export type ServerNotification__ContextCompactedNotification = { + readonly threadId: string; + readonly turnId: string; +}; +export const ServerNotification__ContextCompactedNotification = Schema.Struct({ + threadId: Schema.String, + turnId: Schema.String, +}).annotate({ description: "Deprecated: Use `ContextCompaction` item type instead." }); + +export type ServerNotification__CreditsSnapshot = { + readonly balance?: string | null; + readonly hasCredits: boolean; + readonly unlimited: boolean; +}; +export const ServerNotification__CreditsSnapshot = Schema.Struct({ + balance: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + hasCredits: Schema.Boolean, + unlimited: Schema.Boolean, +}); + +export type ServerNotification__DeprecationNoticeNotification = { + readonly details?: string | null; + readonly summary: string; +}; +export const ServerNotification__DeprecationNoticeNotification = Schema.Struct({ + details: Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + description: "Optional extra guidance, such as migration steps or rationale.", + }), + Schema.Null, + ]), + ), + summary: Schema.String.annotate({ description: "Concise summary of what is deprecated." }), +}); + +export type ServerNotification__DynamicToolCallOutputContentItem = + | { readonly text: string; readonly type: "inputText" } + | { readonly imageUrl: string; readonly type: "inputImage" }; +export const ServerNotification__DynamicToolCallOutputContentItem = Schema.Union( + [ + Schema.Struct({ + text: Schema.String, + type: Schema.Literal("inputText").annotate({ + title: "InputTextDynamicToolCallOutputContentItemType", + }), + }).annotate({ title: "InputTextDynamicToolCallOutputContentItem" }), + Schema.Struct({ + imageUrl: Schema.String, + type: Schema.Literal("inputImage").annotate({ + title: "InputImageDynamicToolCallOutputContentItemType", + }), + }).annotate({ title: "InputImageDynamicToolCallOutputContentItem" }), + ], + { mode: "oneOf" }, +); + +export type ServerNotification__DynamicToolCallStatus = "inProgress" | "completed" | "failed"; +export const ServerNotification__DynamicToolCallStatus = Schema.Literals([ + "inProgress", + "completed", + "failed", +]); + +export type ServerNotification__FileChangeOutputDeltaNotification = { + readonly delta: string; + readonly itemId: string; + readonly threadId: string; + readonly turnId: string; +}; +export const ServerNotification__FileChangeOutputDeltaNotification = Schema.Struct({ + delta: Schema.String, + itemId: Schema.String, + threadId: Schema.String, + turnId: Schema.String, +}); + +export type ServerNotification__FuzzyFileSearchMatchType = "file" | "directory"; +export const ServerNotification__FuzzyFileSearchMatchType = Schema.Literals(["file", "directory"]); + +export type ServerNotification__FuzzyFileSearchSessionCompletedNotification = { + readonly sessionId: string; +}; +export const ServerNotification__FuzzyFileSearchSessionCompletedNotification = Schema.Struct({ + sessionId: Schema.String, +}); + +export type ServerNotification__GitInfo = { + readonly branch?: string | null; + readonly originUrl?: string | null; + readonly sha?: string | null; +}; +export const ServerNotification__GitInfo = Schema.Struct({ + branch: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + originUrl: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + sha: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), +}); + +export type ServerNotification__GuardianApprovalReviewStatus = + | "inProgress" + | "approved" + | "denied" + | "timedOut" + | "aborted"; +export const ServerNotification__GuardianApprovalReviewStatus = Schema.Literals([ + "inProgress", + "approved", + "denied", + "timedOut", + "aborted", +]).annotate({ description: "[UNSTABLE] Lifecycle state for a guardian approval review." }); + +export type ServerNotification__GuardianCommandSource = "shell" | "unifiedExec"; +export const ServerNotification__GuardianCommandSource = Schema.Literals(["shell", "unifiedExec"]); + +export type ServerNotification__GuardianRiskLevel = "low" | "medium" | "high" | "critical"; +export const ServerNotification__GuardianRiskLevel = Schema.Literals([ + "low", + "medium", + "high", + "critical", +]).annotate({ description: "[UNSTABLE] Risk level assigned by guardian approval review." }); + +export type ServerNotification__GuardianUserAuthorization = "unknown" | "low" | "medium" | "high"; +export const ServerNotification__GuardianUserAuthorization = Schema.Literals([ + "unknown", + "low", + "medium", + "high", +]).annotate({ + description: "[UNSTABLE] Authorization level assigned by guardian approval review.", +}); + +export type ServerNotification__HookEventName = + | "preToolUse" + | "postToolUse" + | "sessionStart" + | "userPromptSubmit" + | "stop"; +export const ServerNotification__HookEventName = Schema.Literals([ + "preToolUse", + "postToolUse", + "sessionStart", + "userPromptSubmit", + "stop", +]); + +export type ServerNotification__HookExecutionMode = "sync" | "async"; +export const ServerNotification__HookExecutionMode = Schema.Literals(["sync", "async"]); + +export type ServerNotification__HookHandlerType = "command" | "prompt" | "agent"; +export const ServerNotification__HookHandlerType = Schema.Literals(["command", "prompt", "agent"]); + +export type ServerNotification__HookOutputEntryKind = + | "warning" + | "stop" + | "feedback" + | "context" + | "error"; +export const ServerNotification__HookOutputEntryKind = Schema.Literals([ + "warning", + "stop", + "feedback", + "context", + "error", +]); + +export type ServerNotification__HookPromptFragment = { + readonly hookRunId: string; + readonly text: string; +}; +export const ServerNotification__HookPromptFragment = Schema.Struct({ + hookRunId: Schema.String, + text: Schema.String, +}); + +export type ServerNotification__HookRunStatus = + | "running" + | "completed" + | "failed" + | "blocked" + | "stopped"; +export const ServerNotification__HookRunStatus = Schema.Literals([ + "running", + "completed", + "failed", + "blocked", + "stopped", +]); + +export type ServerNotification__HookScope = "thread" | "turn"; +export const ServerNotification__HookScope = Schema.Literals(["thread", "turn"]); + +export type ServerNotification__McpServerOauthLoginCompletedNotification = { + readonly error?: string | null; + readonly name: string; + readonly success: boolean; +}; +export const ServerNotification__McpServerOauthLoginCompletedNotification = Schema.Struct({ + error: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + name: Schema.String, + success: Schema.Boolean, +}); + +export type ServerNotification__McpServerStartupState = + | "starting" + | "ready" + | "failed" + | "cancelled"; +export const ServerNotification__McpServerStartupState = Schema.Literals([ + "starting", + "ready", + "failed", + "cancelled", +]); + +export type ServerNotification__McpToolCallError = { readonly message: string }; +export const ServerNotification__McpToolCallError = Schema.Struct({ message: Schema.String }); + +export type ServerNotification__McpToolCallProgressNotification = { + readonly itemId: string; + readonly message: string; + readonly threadId: string; + readonly turnId: string; +}; +export const ServerNotification__McpToolCallProgressNotification = Schema.Struct({ + itemId: Schema.String, + message: Schema.String, + threadId: Schema.String, + turnId: Schema.String, +}); + +export type ServerNotification__McpToolCallResult = { + readonly _meta?: unknown; + readonly content: ReadonlyArray; + readonly structuredContent?: unknown; +}; +export const ServerNotification__McpToolCallResult = Schema.Struct({ + _meta: Schema.optionalKey(Schema.Unknown), + content: Schema.Array(Schema.Unknown), + structuredContent: Schema.optionalKey(Schema.Unknown), +}); + +export type ServerNotification__McpToolCallStatus = "inProgress" | "completed" | "failed"; +export const ServerNotification__McpToolCallStatus = Schema.Literals([ + "inProgress", + "completed", + "failed", +]); + +export type ServerNotification__MemoryCitationEntry = { + readonly lineEnd: number; + readonly lineStart: number; + readonly note: string; + readonly path: string; +}; +export const ServerNotification__MemoryCitationEntry = Schema.Struct({ + lineEnd: Schema.Number.annotate({ format: "uint32" }) + .check(Schema.isInt()) + .check(Schema.isGreaterThanOrEqualTo(0)), + lineStart: Schema.Number.annotate({ format: "uint32" }) + .check(Schema.isInt()) + .check(Schema.isGreaterThanOrEqualTo(0)), + note: Schema.String, + path: Schema.String, +}); + +export type ServerNotification__MessagePhase = "commentary" | "final_answer"; +export const ServerNotification__MessagePhase = Schema.Literals([ + "commentary", + "final_answer", +]).annotate({ + description: + 'Classifies an assistant message as interim commentary or final answer text.\n\nProviders do not emit this consistently, so callers must treat `None` as "phase unknown" and keep compatibility behavior for legacy models.', +}); + +export type ServerNotification__ModelRerouteReason = "highRiskCyberActivity"; +export const ServerNotification__ModelRerouteReason = Schema.Literal("highRiskCyberActivity"); + +export type ServerNotification__NetworkApprovalProtocol = + | "http" + | "https" + | "socks5Tcp" + | "socks5Udp"; +export const ServerNotification__NetworkApprovalProtocol = Schema.Literals([ + "http", + "https", + "socks5Tcp", + "socks5Udp", +]); + +export type ServerNotification__NonSteerableTurnKind = "review" | "compact"; +export const ServerNotification__NonSteerableTurnKind = Schema.Literals(["review", "compact"]); + +export type ServerNotification__PatchApplyStatus = + | "inProgress" + | "completed" + | "failed" + | "declined"; +export const ServerNotification__PatchApplyStatus = Schema.Literals([ + "inProgress", + "completed", + "failed", + "declined", +]); + +export type ServerNotification__PatchChangeKind = + | { readonly type: "add" } + | { readonly type: "delete" } + | { readonly move_path?: string | null; readonly type: "update" }; +export const ServerNotification__PatchChangeKind = Schema.Union( + [ + Schema.Struct({ + type: Schema.Literal("add").annotate({ title: "AddPatchChangeKindType" }), + }).annotate({ title: "AddPatchChangeKind" }), + Schema.Struct({ + type: Schema.Literal("delete").annotate({ title: "DeletePatchChangeKindType" }), + }).annotate({ title: "DeletePatchChangeKind" }), + Schema.Struct({ + move_path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + type: Schema.Literal("update").annotate({ title: "UpdatePatchChangeKindType" }), + }).annotate({ title: "UpdatePatchChangeKind" }), + ], + { mode: "oneOf" }, +); + +export type ServerNotification__PlanDeltaNotification = { + readonly delta: string; + readonly itemId: string; + readonly threadId: string; + readonly turnId: string; +}; +export const ServerNotification__PlanDeltaNotification = Schema.Struct({ + delta: Schema.String, + itemId: Schema.String, + threadId: Schema.String, + turnId: Schema.String, +}).annotate({ + description: + "EXPERIMENTAL - proposed plan streaming deltas for plan items. Clients should not assume concatenated deltas match the completed plan item content.", +}); + +export type ServerNotification__PlanType = + | "free" + | "go" + | "plus" + | "pro" + | "team" + | "self_serve_business_usage_based" + | "business" + | "enterprise_cbp_usage_based" + | "enterprise" + | "edu" + | "unknown"; +export const ServerNotification__PlanType = Schema.Literals([ + "free", + "go", + "plus", + "pro", + "team", + "self_serve_business_usage_based", + "business", + "enterprise_cbp_usage_based", + "enterprise", + "edu", + "unknown", +]); + +export type ServerNotification__RateLimitWindow = { + readonly resetsAt?: number | null; + readonly usedPercent: number; + readonly windowDurationMins?: number | null; +}; +export const ServerNotification__RateLimitWindow = Schema.Struct({ + resetsAt: Schema.optionalKey( + Schema.Union([Schema.Number.annotate({ format: "int64" }).check(Schema.isInt()), Schema.Null]), + ), + usedPercent: Schema.Number.annotate({ format: "int32" }).check(Schema.isInt()), + windowDurationMins: Schema.optionalKey( + Schema.Union([Schema.Number.annotate({ format: "int64" }).check(Schema.isInt()), Schema.Null]), + ), +}); + +export type ServerNotification__RealtimeConversationVersion = "v1" | "v2"; +export const ServerNotification__RealtimeConversationVersion = Schema.Literals(["v1", "v2"]); + +export type ServerNotification__ReasoningEffort = + | "none" + | "minimal" + | "low" + | "medium" + | "high" + | "xhigh"; +export const ServerNotification__ReasoningEffort = Schema.Literals([ + "none", + "minimal", + "low", + "medium", + "high", + "xhigh", +]).annotate({ + description: + "See https://platform.openai.com/docs/guides/reasoning?api-mode=responses#get-started-with-reasoning", +}); + +export type ServerNotification__ReasoningSummaryPartAddedNotification = { + readonly itemId: string; + readonly summaryIndex: number; + readonly threadId: string; + readonly turnId: string; +}; +export const ServerNotification__ReasoningSummaryPartAddedNotification = Schema.Struct({ + itemId: Schema.String, + summaryIndex: Schema.Number.annotate({ format: "int64" }).check(Schema.isInt()), + threadId: Schema.String, + turnId: Schema.String, +}); + +export type ServerNotification__ReasoningSummaryTextDeltaNotification = { + readonly delta: string; + readonly itemId: string; + readonly summaryIndex: number; + readonly threadId: string; + readonly turnId: string; +}; +export const ServerNotification__ReasoningSummaryTextDeltaNotification = Schema.Struct({ + delta: Schema.String, + itemId: Schema.String, + summaryIndex: Schema.Number.annotate({ format: "int64" }).check(Schema.isInt()), + threadId: Schema.String, + turnId: Schema.String, +}); + +export type ServerNotification__ReasoningTextDeltaNotification = { + readonly contentIndex: number; + readonly delta: string; + readonly itemId: string; + readonly threadId: string; + readonly turnId: string; +}; +export const ServerNotification__ReasoningTextDeltaNotification = Schema.Struct({ + contentIndex: Schema.Number.annotate({ format: "int64" }).check(Schema.isInt()), + delta: Schema.String, + itemId: Schema.String, + threadId: Schema.String, + turnId: Schema.String, +}); + +export type ServerNotification__RequestId = string | number; +export const ServerNotification__RequestId = Schema.Union([ + Schema.String, + Schema.Number.annotate({ format: "int64" }).check(Schema.isInt()), +]); + +export type ServerNotification__SkillsChangedNotification = {}; +export const ServerNotification__SkillsChangedNotification = Schema.Struct({}).annotate({ + description: + "Notification emitted when watched local skill files change.\n\nTreat this as an invalidation signal and re-run `skills/list` with the client's current parameters when refreshed skill metadata is needed.", +}); + +export type ServerNotification__TerminalInteractionNotification = { + readonly itemId: string; + readonly processId: string; + readonly stdin: string; + readonly threadId: string; + readonly turnId: string; +}; +export const ServerNotification__TerminalInteractionNotification = Schema.Struct({ + itemId: Schema.String, + processId: Schema.String, + stdin: Schema.String, + threadId: Schema.String, + turnId: Schema.String, +}); + +export type ServerNotification__TextElement = { + readonly byteRange: { readonly end: number; readonly start: number }; + readonly placeholder?: string | null; +}; +export const ServerNotification__TextElement = Schema.Struct({ + byteRange: Schema.Struct({ + end: Schema.Number.annotate({ format: "uint" }) + .check(Schema.isInt()) + .check(Schema.isGreaterThanOrEqualTo(0)), + start: Schema.Number.annotate({ format: "uint" }) + .check(Schema.isInt()) + .check(Schema.isGreaterThanOrEqualTo(0)), + }).annotate({ + description: "Byte range in the parent `text` buffer that this element occupies.", + }), + placeholder: Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + description: "Optional human-readable placeholder for the element, displayed in the UI.", + }), + Schema.Null, + ]), + ), +}); + +export type ServerNotification__TextPosition = { readonly column: number; readonly line: number }; +export const ServerNotification__TextPosition = Schema.Struct({ + column: Schema.Number.annotate({ + description: "1-based column number (in Unicode scalar values).", + format: "uint", + }) + .check(Schema.isInt()) + .check(Schema.isGreaterThanOrEqualTo(0)), + line: Schema.Number.annotate({ description: "1-based line number.", format: "uint" }) + .check(Schema.isInt()) + .check(Schema.isGreaterThanOrEqualTo(0)), +}); + +export type ServerNotification__ThreadActiveFlag = "waitingOnApproval" | "waitingOnUserInput"; +export const ServerNotification__ThreadActiveFlag = Schema.Literals([ + "waitingOnApproval", + "waitingOnUserInput", +]); + +export type ServerNotification__ThreadArchivedNotification = { readonly threadId: string }; +export const ServerNotification__ThreadArchivedNotification = Schema.Struct({ + threadId: Schema.String, +}); + +export type ServerNotification__ThreadClosedNotification = { readonly threadId: string }; +export const ServerNotification__ThreadClosedNotification = Schema.Struct({ + threadId: Schema.String, +}); + +export type ServerNotification__ThreadId = string; +export const ServerNotification__ThreadId = Schema.String; + +export type ServerNotification__ThreadNameUpdatedNotification = { + readonly threadId: string; + readonly threadName?: string | null; +}; +export const ServerNotification__ThreadNameUpdatedNotification = Schema.Struct({ + threadId: Schema.String, + threadName: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), +}); + +export type ServerNotification__ThreadRealtimeAudioChunk = { + readonly data: string; + readonly itemId?: string | null; + readonly numChannels: number; + readonly sampleRate: number; + readonly samplesPerChannel?: number | null; +}; +export const ServerNotification__ThreadRealtimeAudioChunk = Schema.Struct({ + data: Schema.String, + itemId: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + numChannels: Schema.Number.annotate({ format: "uint16" }) + .check(Schema.isInt()) + .check(Schema.isGreaterThanOrEqualTo(0)), + sampleRate: Schema.Number.annotate({ format: "uint32" }) + .check(Schema.isInt()) + .check(Schema.isGreaterThanOrEqualTo(0)), + samplesPerChannel: Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ format: "uint32" }) + .check(Schema.isInt()) + .check(Schema.isGreaterThanOrEqualTo(0)), + Schema.Null, + ]), + ), +}).annotate({ description: "EXPERIMENTAL - thread realtime audio chunk." }); + +export type ServerNotification__ThreadRealtimeClosedNotification = { + readonly reason?: string | null; + readonly threadId: string; +}; +export const ServerNotification__ThreadRealtimeClosedNotification = Schema.Struct({ + reason: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + threadId: Schema.String, +}).annotate({ description: "EXPERIMENTAL - emitted when thread realtime transport closes." }); + +export type ServerNotification__ThreadRealtimeErrorNotification = { + readonly message: string; + readonly threadId: string; +}; +export const ServerNotification__ThreadRealtimeErrorNotification = Schema.Struct({ + message: Schema.String, + threadId: Schema.String, +}).annotate({ description: "EXPERIMENTAL - emitted when thread realtime encounters an error." }); + +export type ServerNotification__ThreadRealtimeItemAddedNotification = { + readonly item: unknown; + readonly threadId: string; +}; +export const ServerNotification__ThreadRealtimeItemAddedNotification = Schema.Struct({ + item: Schema.Unknown, + threadId: Schema.String, +}).annotate({ + description: "EXPERIMENTAL - raw non-audio thread realtime item emitted by the backend.", +}); + +export type ServerNotification__ThreadRealtimeSdpNotification = { + readonly sdp: string; + readonly threadId: string; +}; +export const ServerNotification__ThreadRealtimeSdpNotification = Schema.Struct({ + sdp: Schema.String, + threadId: Schema.String, +}).annotate({ + description: "EXPERIMENTAL - emitted with the remote SDP for a WebRTC realtime session.", +}); + +export type ServerNotification__ThreadRealtimeTranscriptUpdatedNotification = { + readonly role: string; + readonly text: string; + readonly threadId: string; +}; +export const ServerNotification__ThreadRealtimeTranscriptUpdatedNotification = Schema.Struct({ + role: Schema.String, + text: Schema.String, + threadId: Schema.String, +}).annotate({ + description: + "EXPERIMENTAL - flat transcript delta emitted whenever realtime transcript text changes.", +}); + +export type ServerNotification__ThreadUnarchivedNotification = { readonly threadId: string }; +export const ServerNotification__ThreadUnarchivedNotification = Schema.Struct({ + threadId: Schema.String, +}); + +export type ServerNotification__TokenUsageBreakdown = { + readonly cachedInputTokens: number; + readonly inputTokens: number; + readonly outputTokens: number; + readonly reasoningOutputTokens: number; + readonly totalTokens: number; +}; +export const ServerNotification__TokenUsageBreakdown = Schema.Struct({ + cachedInputTokens: Schema.Number.annotate({ format: "int64" }).check(Schema.isInt()), + inputTokens: Schema.Number.annotate({ format: "int64" }).check(Schema.isInt()), + outputTokens: Schema.Number.annotate({ format: "int64" }).check(Schema.isInt()), + reasoningOutputTokens: Schema.Number.annotate({ format: "int64" }).check(Schema.isInt()), + totalTokens: Schema.Number.annotate({ format: "int64" }).check(Schema.isInt()), +}); + +export type ServerNotification__TurnDiffUpdatedNotification = { + readonly diff: string; + readonly threadId: string; + readonly turnId: string; +}; +export const ServerNotification__TurnDiffUpdatedNotification = Schema.Struct({ + diff: Schema.String, + threadId: Schema.String, + turnId: Schema.String, +}).annotate({ + description: + "Notification that the turn-level unified diff has changed. Contains the latest aggregated diff across all file changes in the turn.", +}); + +export type ServerNotification__TurnPlanStepStatus = "pending" | "inProgress" | "completed"; +export const ServerNotification__TurnPlanStepStatus = Schema.Literals([ + "pending", + "inProgress", + "completed", +]); + +export type ServerNotification__TurnStatus = "completed" | "interrupted" | "failed" | "inProgress"; +export const ServerNotification__TurnStatus = Schema.Literals([ + "completed", + "interrupted", + "failed", + "inProgress", +]); + +export type ServerNotification__WebSearchAction = + | { + readonly queries?: ReadonlyArray | null; + readonly query?: string | null; + readonly type: "search"; + } + | { readonly type: "openPage"; readonly url?: string | null } + | { readonly pattern?: string | null; readonly type: "findInPage"; readonly url?: string | null } + | { readonly type: "other" }; +export const ServerNotification__WebSearchAction = Schema.Union( + [ + Schema.Struct({ + queries: Schema.optionalKey(Schema.Union([Schema.Array(Schema.String), Schema.Null])), + query: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + type: Schema.Literal("search").annotate({ title: "SearchWebSearchActionType" }), + }).annotate({ title: "SearchWebSearchAction" }), + Schema.Struct({ + type: Schema.Literal("openPage").annotate({ title: "OpenPageWebSearchActionType" }), + url: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + }).annotate({ title: "OpenPageWebSearchAction" }), + Schema.Struct({ + pattern: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + type: Schema.Literal("findInPage").annotate({ title: "FindInPageWebSearchActionType" }), + url: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + }).annotate({ title: "FindInPageWebSearchAction" }), + Schema.Struct({ + type: Schema.Literal("other").annotate({ title: "OtherWebSearchActionType" }), + }).annotate({ title: "OtherWebSearchAction" }), + ], + { mode: "oneOf" }, +); + +export type ServerNotification__WindowsSandboxSetupMode = "elevated" | "unelevated"; +export const ServerNotification__WindowsSandboxSetupMode = Schema.Literals([ + "elevated", + "unelevated", +]); + +export type ServerNotification__WindowsWorldWritableWarningNotification = { + readonly extraCount: number; + readonly failedScan: boolean; + readonly samplePaths: ReadonlyArray; +}; +export const ServerNotification__WindowsWorldWritableWarningNotification = Schema.Struct({ + extraCount: Schema.Number.annotate({ format: "uint" }) + .check(Schema.isInt()) + .check(Schema.isGreaterThanOrEqualTo(0)), + failedScan: Schema.Boolean, + samplePaths: Schema.Array(Schema.String), +}); + +export type ServerRequest__AbsolutePathBuf = string; +export const ServerRequest__AbsolutePathBuf = Schema.String.annotate({ + description: + "A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\n\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.", +}); + +export type ServerRequest__AdditionalNetworkPermissions = { readonly enabled?: boolean | null }; +export const ServerRequest__AdditionalNetworkPermissions = Schema.Struct({ + enabled: Schema.optionalKey(Schema.Union([Schema.Boolean, Schema.Null])), +}); + +export type ServerRequest__ChatgptAuthTokensRefreshReason = "unauthorized"; +export const ServerRequest__ChatgptAuthTokensRefreshReason = Schema.Literal("unauthorized"); + +export type ServerRequest__CommandAction = + | { + readonly command: string; + readonly name: string; + readonly path: string; + readonly type: "read"; + } + | { readonly command: string; readonly path?: string | null; readonly type: "listFiles" } + | { + readonly command: string; + readonly path?: string | null; + readonly query?: string | null; + readonly type: "search"; + } + | { readonly command: string; readonly type: "unknown" }; +export const ServerRequest__CommandAction = Schema.Union( + [ + Schema.Struct({ + command: Schema.String, + name: Schema.String, + path: Schema.String, + type: Schema.Literal("read").annotate({ title: "ReadCommandActionType" }), + }).annotate({ title: "ReadCommandAction" }), + Schema.Struct({ + command: Schema.String, + path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + type: Schema.Literal("listFiles").annotate({ title: "ListFilesCommandActionType" }), + }).annotate({ title: "ListFilesCommandAction" }), + Schema.Struct({ + command: Schema.String, + path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + query: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + type: Schema.Literal("search").annotate({ title: "SearchCommandActionType" }), + }).annotate({ title: "SearchCommandAction" }), + Schema.Struct({ + command: Schema.String, + type: Schema.Literal("unknown").annotate({ title: "UnknownCommandActionType" }), + }).annotate({ title: "UnknownCommandAction" }), + ], + { mode: "oneOf" }, +); + +export type ServerRequest__DynamicToolCallParams = { + readonly arguments: unknown; + readonly callId: string; + readonly threadId: string; + readonly tool: string; + readonly turnId: string; +}; +export const ServerRequest__DynamicToolCallParams = Schema.Struct({ + arguments: Schema.Unknown, + callId: Schema.String, + threadId: Schema.String, + tool: Schema.String, + turnId: Schema.String, +}); + +export type ServerRequest__FileChange = + | { readonly content: string; readonly type: "add" } + | { readonly content: string; readonly type: "delete" } + | { readonly move_path?: string | null; readonly type: "update"; readonly unified_diff: string }; +export const ServerRequest__FileChange = Schema.Union( + [ + Schema.Struct({ + content: Schema.String, + type: Schema.Literal("add").annotate({ title: "AddFileChangeType" }), + }).annotate({ title: "AddFileChange" }), + Schema.Struct({ + content: Schema.String, + type: Schema.Literal("delete").annotate({ title: "DeleteFileChangeType" }), + }).annotate({ title: "DeleteFileChange" }), + Schema.Struct({ + move_path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + type: Schema.Literal("update").annotate({ title: "UpdateFileChangeType" }), + unified_diff: Schema.String, + }).annotate({ title: "UpdateFileChange" }), + ], + { mode: "oneOf" }, +); + +export type ServerRequest__FileChangeRequestApprovalParams = { + readonly grantRoot?: string | null; + readonly itemId: string; + readonly reason?: string | null; + readonly threadId: string; + readonly turnId: string; +}; +export const ServerRequest__FileChangeRequestApprovalParams = Schema.Struct({ + grantRoot: Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + description: + "[UNSTABLE] When set, the agent is asking the user to allow writes under this root for the remainder of the session (unclear if this is honored today).", + }), + Schema.Null, + ]), + ), + itemId: Schema.String, + reason: Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + description: "Optional explanatory reason (e.g. request for extra write access).", + }), + Schema.Null, + ]), + ), + threadId: Schema.String, + turnId: Schema.String, +}); + +export type ServerRequest__McpElicitationArrayType = "array"; +export const ServerRequest__McpElicitationArrayType = Schema.Literal("array"); + +export type ServerRequest__McpElicitationBooleanType = "boolean"; +export const ServerRequest__McpElicitationBooleanType = Schema.Literal("boolean"); + +export type ServerRequest__McpElicitationConstOption = { + readonly const: string; + readonly title: string; +}; +export const ServerRequest__McpElicitationConstOption = Schema.Struct({ + const: Schema.String, + title: Schema.String, +}); + +export type ServerRequest__McpElicitationNumberType = "number" | "integer"; +export const ServerRequest__McpElicitationNumberType = Schema.Literals(["number", "integer"]); + +export type ServerRequest__McpElicitationObjectType = "object"; +export const ServerRequest__McpElicitationObjectType = Schema.Literal("object"); + +export type ServerRequest__McpElicitationStringFormat = "email" | "uri" | "date" | "date-time"; +export const ServerRequest__McpElicitationStringFormat = Schema.Literals([ + "email", + "uri", + "date", + "date-time", +]); + +export type ServerRequest__McpElicitationStringType = "string"; +export const ServerRequest__McpElicitationStringType = Schema.Literal("string"); + +export type ServerRequest__NetworkApprovalProtocol = "http" | "https" | "socks5Tcp" | "socks5Udp"; +export const ServerRequest__NetworkApprovalProtocol = Schema.Literals([ + "http", + "https", + "socks5Tcp", + "socks5Udp", +]); + +export type ServerRequest__NetworkPolicyRuleAction = "allow" | "deny"; +export const ServerRequest__NetworkPolicyRuleAction = Schema.Literals(["allow", "deny"]); + +export type ServerRequest__ParsedCommand = + | { readonly cmd: string; readonly name: string; readonly path: string; readonly type: "read" } + | { readonly cmd: string; readonly path?: string | null; readonly type: "list_files" } + | { + readonly cmd: string; + readonly path?: string | null; + readonly query?: string | null; + readonly type: "search"; + } + | { readonly cmd: string; readonly type: "unknown" }; +export const ServerRequest__ParsedCommand = Schema.Union( + [ + Schema.Struct({ + cmd: Schema.String, + name: Schema.String, + path: Schema.String.annotate({ + description: + "(Best effort) Path to the file being read by the command. When possible, this is an absolute path, though when relative, it should be resolved against the `cwd`` that will be used to run the command to derive the absolute path.", + }), + type: Schema.Literal("read").annotate({ title: "ReadParsedCommandType" }), + }).annotate({ title: "ReadParsedCommand" }), + Schema.Struct({ + cmd: Schema.String, + path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + type: Schema.Literal("list_files").annotate({ title: "ListFilesParsedCommandType" }), + }).annotate({ title: "ListFilesParsedCommand" }), + Schema.Struct({ + cmd: Schema.String, + path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + query: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + type: Schema.Literal("search").annotate({ title: "SearchParsedCommandType" }), + }).annotate({ title: "SearchParsedCommand" }), + Schema.Struct({ + cmd: Schema.String, + type: Schema.Literal("unknown").annotate({ title: "UnknownParsedCommandType" }), + }).annotate({ title: "UnknownParsedCommand" }), + ], + { mode: "oneOf" }, +); + +export type ServerRequest__RequestId = string | number; +export const ServerRequest__RequestId = Schema.Union([ + Schema.String, + Schema.Number.annotate({ format: "int64" }).check(Schema.isInt()), +]); + +export type ServerRequest__ThreadId = string; +export const ServerRequest__ThreadId = Schema.String; + +export type ServerRequest__ToolRequestUserInputOption = { + readonly description: string; + readonly label: string; +}; +export const ServerRequest__ToolRequestUserInputOption = Schema.Struct({ + description: Schema.String, + label: Schema.String, +}).annotate({ + description: "EXPERIMENTAL. Defines a single selectable option for request_user_input.", +}); + +export type ToolRequestUserInputParams__ToolRequestUserInputOption = { + readonly description: string; + readonly label: string; +}; +export const ToolRequestUserInputParams__ToolRequestUserInputOption = Schema.Struct({ + description: Schema.String, + label: Schema.String, +}).annotate({ + description: "EXPERIMENTAL. Defines a single selectable option for request_user_input.", +}); + +export type ToolRequestUserInputResponse__ToolRequestUserInputAnswer = { + readonly answers: ReadonlyArray; +}; +export const ToolRequestUserInputResponse__ToolRequestUserInputAnswer = Schema.Struct({ + answers: Schema.Array(Schema.String), +}).annotate({ + description: "EXPERIMENTAL. Captures a user's answer to a request_user_input question.", +}); + +export type V1InitializeParams__ClientInfo = { + readonly name: string; + readonly title?: string | null; + readonly version: string; +}; +export const V1InitializeParams__ClientInfo = Schema.Struct({ + name: Schema.String, + title: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + version: Schema.String, +}); + +export type V1InitializeParams__InitializeCapabilities = { + readonly experimentalApi?: boolean; + readonly optOutNotificationMethods?: ReadonlyArray | null; +}; +export const V1InitializeParams__InitializeCapabilities = Schema.Struct({ + experimentalApi: Schema.optionalKey( + Schema.Boolean.annotate({ + description: "Opt into receiving experimental API methods and fields.", + default: false, + }), + ), + optOutNotificationMethods: Schema.optionalKey( + Schema.Union([ + Schema.Array(Schema.String).annotate({ + description: + "Exact notification method names that should be suppressed for this connection (for example `thread/started`).", + }), + Schema.Null, + ]), + ), +}).annotate({ description: "Client-declared capabilities negotiated during initialize." }); + +export type V2AccountRateLimitsUpdatedNotification__CreditsSnapshot = { + readonly balance?: string | null; + readonly hasCredits: boolean; + readonly unlimited: boolean; +}; +export const V2AccountRateLimitsUpdatedNotification__CreditsSnapshot = Schema.Struct({ + balance: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + hasCredits: Schema.Boolean, + unlimited: Schema.Boolean, +}); + +export type V2AccountRateLimitsUpdatedNotification__PlanType = + | "free" + | "go" + | "plus" + | "pro" + | "team" + | "self_serve_business_usage_based" + | "business" + | "enterprise_cbp_usage_based" + | "enterprise" + | "edu" + | "unknown"; +export const V2AccountRateLimitsUpdatedNotification__PlanType = Schema.Literals([ + "free", + "go", + "plus", + "pro", + "team", + "self_serve_business_usage_based", + "business", + "enterprise_cbp_usage_based", + "enterprise", + "edu", + "unknown", +]); + +export type V2AccountRateLimitsUpdatedNotification__RateLimitWindow = { + readonly resetsAt?: number | null; + readonly usedPercent: number; + readonly windowDurationMins?: number | null; +}; +export const V2AccountRateLimitsUpdatedNotification__RateLimitWindow = Schema.Struct({ + resetsAt: Schema.optionalKey( + Schema.Union([Schema.Number.annotate({ format: "int64" }).check(Schema.isInt()), Schema.Null]), + ), + usedPercent: Schema.Number.annotate({ format: "int32" }).check(Schema.isInt()), + windowDurationMins: Schema.optionalKey( + Schema.Union([Schema.Number.annotate({ format: "int64" }).check(Schema.isInt()), Schema.Null]), + ), +}); + +export type V2AccountUpdatedNotification__AuthMode = "apikey" | "chatgpt" | "chatgptAuthTokens"; +export const V2AccountUpdatedNotification__AuthMode = Schema.Literals([ + "apikey", + "chatgpt", + "chatgptAuthTokens", +]).annotate({ description: "Authentication mode for OpenAI-backed providers." }); + +export type V2AccountUpdatedNotification__PlanType = + | "free" + | "go" + | "plus" + | "pro" + | "team" + | "self_serve_business_usage_based" + | "business" + | "enterprise_cbp_usage_based" + | "enterprise" + | "edu" + | "unknown"; +export const V2AccountUpdatedNotification__PlanType = Schema.Literals([ + "free", + "go", + "plus", + "pro", + "team", + "self_serve_business_usage_based", + "business", + "enterprise_cbp_usage_based", + "enterprise", + "edu", + "unknown", +]); + +export type V2AppListUpdatedNotification__AppBranding = { + readonly category?: string | null; + readonly developer?: string | null; + readonly isDiscoverableApp: boolean; + readonly privacyPolicy?: string | null; + readonly termsOfService?: string | null; + readonly website?: string | null; +}; +export const V2AppListUpdatedNotification__AppBranding = Schema.Struct({ + category: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + developer: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + isDiscoverableApp: Schema.Boolean, + privacyPolicy: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + termsOfService: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + website: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), +}).annotate({ description: "EXPERIMENTAL - app metadata returned by app-list APIs." }); + +export type V2AppListUpdatedNotification__AppReview = { readonly status: string }; +export const V2AppListUpdatedNotification__AppReview = Schema.Struct({ status: Schema.String }); + +export type V2AppListUpdatedNotification__AppScreenshot = { + readonly fileId?: string | null; + readonly url?: string | null; + readonly userPrompt: string; +}; +export const V2AppListUpdatedNotification__AppScreenshot = Schema.Struct({ + fileId: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + url: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + userPrompt: Schema.String, +}); + +export type V2AppsListResponse__AppBranding = { + readonly category?: string | null; + readonly developer?: string | null; + readonly isDiscoverableApp: boolean; + readonly privacyPolicy?: string | null; + readonly termsOfService?: string | null; + readonly website?: string | null; +}; +export const V2AppsListResponse__AppBranding = Schema.Struct({ + category: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + developer: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + isDiscoverableApp: Schema.Boolean, + privacyPolicy: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + termsOfService: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + website: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), +}).annotate({ description: "EXPERIMENTAL - app metadata returned by app-list APIs." }); + +export type V2AppsListResponse__AppReview = { readonly status: string }; +export const V2AppsListResponse__AppReview = Schema.Struct({ status: Schema.String }); + +export type V2AppsListResponse__AppScreenshot = { + readonly fileId?: string | null; + readonly url?: string | null; + readonly userPrompt: string; +}; +export const V2AppsListResponse__AppScreenshot = Schema.Struct({ + fileId: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + url: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + userPrompt: Schema.String, +}); + +export type V2CancelLoginAccountResponse__CancelLoginAccountStatus = "canceled" | "notFound"; +export const V2CancelLoginAccountResponse__CancelLoginAccountStatus = Schema.Literals([ + "canceled", + "notFound", +]); + +export type V2CommandExecParams__AbsolutePathBuf = string; +export const V2CommandExecParams__AbsolutePathBuf = Schema.String.annotate({ + description: + "A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\n\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.", +}); + +export type V2CommandExecParams__CommandExecTerminalSize = { + readonly cols: number; + readonly rows: number; +}; +export const V2CommandExecParams__CommandExecTerminalSize = Schema.Struct({ + cols: Schema.Number.annotate({ + description: "Terminal width in character cells.", + format: "uint16", + }) + .check(Schema.isInt()) + .check(Schema.isGreaterThanOrEqualTo(0)), + rows: Schema.Number.annotate({ + description: "Terminal height in character cells.", + format: "uint16", + }) + .check(Schema.isInt()) + .check(Schema.isGreaterThanOrEqualTo(0)), +}).annotate({ description: "PTY size in character cells for `command/exec` PTY sessions." }); + +export type V2ConfigBatchWriteParams__MergeStrategy = "replace" | "upsert"; +export const V2ConfigBatchWriteParams__MergeStrategy = Schema.Literals(["replace", "upsert"]); + +export type V2ConfigReadResponse__AbsolutePathBuf = string; +export const V2ConfigReadResponse__AbsolutePathBuf = Schema.String.annotate({ + description: + "A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\n\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.", +}); + +export type V2ConfigReadResponse__AnalyticsConfig = { + readonly enabled?: boolean | null; + readonly [x: string]: unknown; +}; +export const V2ConfigReadResponse__AnalyticsConfig = Schema.StructWithRest( + Schema.Struct({ enabled: Schema.optionalKey(Schema.Union([Schema.Boolean, Schema.Null])) }), + [Schema.Record(Schema.String, Schema.Unknown)], +); + +export type V2ConfigReadResponse__AppToolApproval = "auto" | "prompt" | "approve"; +export const V2ConfigReadResponse__AppToolApproval = Schema.Literals(["auto", "prompt", "approve"]); + +export type V2ConfigReadResponse__AppToolsConfig = {}; +export const V2ConfigReadResponse__AppToolsConfig = Schema.Struct({}); + +export type V2ConfigReadResponse__ApprovalsReviewer = "user" | "guardian_subagent"; +export const V2ConfigReadResponse__ApprovalsReviewer = Schema.Literals([ + "user", + "guardian_subagent", +]).annotate({ + description: + "Configures who approval requests are routed to for review. Examples include sandbox escapes, blocked network access, MCP approval prompts, and ARC escalations. Defaults to `user`. `guardian_subagent` uses a carefully prompted subagent to gather relevant context and apply a risk-based decision framework before approving or denying the request.", +}); + +export type V2ConfigReadResponse__AppsDefaultConfig = { + readonly destructive_enabled?: boolean; + readonly enabled?: boolean; + readonly open_world_enabled?: boolean; +}; +export const V2ConfigReadResponse__AppsDefaultConfig = Schema.Struct({ + destructive_enabled: Schema.optionalKey(Schema.Boolean.annotate({ default: true })), + enabled: Schema.optionalKey(Schema.Boolean.annotate({ default: true })), + open_world_enabled: Schema.optionalKey(Schema.Boolean.annotate({ default: true })), +}); + +export type V2ConfigReadResponse__AskForApproval = + | "untrusted" + | "on-failure" + | "on-request" + | "never" + | { + readonly granular: { + readonly mcp_elicitations: boolean; + readonly request_permissions?: boolean; + readonly rules: boolean; + readonly sandbox_approval: boolean; + readonly skill_approval?: boolean; + }; + }; +export const V2ConfigReadResponse__AskForApproval = Schema.Union( + [ + Schema.Literals(["untrusted", "on-failure", "on-request", "never"]), + Schema.Struct({ + granular: Schema.Struct({ + mcp_elicitations: Schema.Boolean, + request_permissions: Schema.optionalKey(Schema.Boolean.annotate({ default: false })), + rules: Schema.Boolean, + sandbox_approval: Schema.Boolean, + skill_approval: Schema.optionalKey(Schema.Boolean.annotate({ default: false })), + }), + }).annotate({ title: "GranularAskForApproval" }), + ], + { mode: "oneOf" }, +); + +export type V2ConfigReadResponse__ForcedLoginMethod = "chatgpt" | "api"; +export const V2ConfigReadResponse__ForcedLoginMethod = Schema.Literals(["chatgpt", "api"]); + +export type V2ConfigReadResponse__ReasoningEffort = + | "none" + | "minimal" + | "low" + | "medium" + | "high" + | "xhigh"; +export const V2ConfigReadResponse__ReasoningEffort = Schema.Literals([ + "none", + "minimal", + "low", + "medium", + "high", + "xhigh", +]).annotate({ + description: + "See https://platform.openai.com/docs/guides/reasoning?api-mode=responses#get-started-with-reasoning", +}); + +export type V2ConfigReadResponse__ReasoningSummary = "auto" | "concise" | "detailed" | "none"; +export const V2ConfigReadResponse__ReasoningSummary = Schema.Union( + [ + Schema.Literals(["auto", "concise", "detailed"]), + Schema.Literal("none").annotate({ description: "Option to disable reasoning summaries." }), + ], + { mode: "oneOf" }, +).annotate({ + description: + "A summary of the reasoning performed by the model. This can be useful for debugging and understanding the model's reasoning process. See https://platform.openai.com/docs/guides/reasoning?api-mode=responses#reasoning-summaries", +}); + +export type V2ConfigReadResponse__SandboxMode = + | "read-only" + | "workspace-write" + | "danger-full-access"; +export const V2ConfigReadResponse__SandboxMode = Schema.Literals([ + "read-only", + "workspace-write", + "danger-full-access", +]); + +export type V2ConfigReadResponse__SandboxWorkspaceWrite = { + readonly exclude_slash_tmp?: boolean; + readonly exclude_tmpdir_env_var?: boolean; + readonly network_access?: boolean; + readonly writable_roots?: ReadonlyArray; +}; +export const V2ConfigReadResponse__SandboxWorkspaceWrite = Schema.Struct({ + exclude_slash_tmp: Schema.optionalKey(Schema.Boolean.annotate({ default: false })), + exclude_tmpdir_env_var: Schema.optionalKey(Schema.Boolean.annotate({ default: false })), + network_access: Schema.optionalKey(Schema.Boolean.annotate({ default: false })), + writable_roots: Schema.optionalKey(Schema.Array(Schema.String).annotate({ default: [] })), +}); + +export type V2ConfigReadResponse__ServiceTier = "fast" | "flex"; +export const V2ConfigReadResponse__ServiceTier = Schema.Literals(["fast", "flex"]); + +export type V2ConfigReadResponse__Verbosity = "low" | "medium" | "high"; +export const V2ConfigReadResponse__Verbosity = Schema.Literals(["low", "medium", "high"]).annotate({ + description: + "Controls output length/detail on GPT-5 models via the Responses API. Serialized with lowercase values to match the OpenAI API.", +}); + +export type V2ConfigReadResponse__WebSearchContextSize = "low" | "medium" | "high"; +export const V2ConfigReadResponse__WebSearchContextSize = Schema.Literals([ + "low", + "medium", + "high", +]); + +export type V2ConfigReadResponse__WebSearchLocation = { + readonly city?: string | null; + readonly country?: string | null; + readonly region?: string | null; + readonly timezone?: string | null; +}; +export const V2ConfigReadResponse__WebSearchLocation = Schema.Struct({ + city: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + country: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + region: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + timezone: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), +}); + +export type V2ConfigReadResponse__WebSearchMode = "disabled" | "cached" | "live"; +export const V2ConfigReadResponse__WebSearchMode = Schema.Literals(["disabled", "cached", "live"]); + +export type V2ConfigRequirementsReadResponse__AskForApproval = + | "untrusted" + | "on-failure" + | "on-request" + | "never" + | { + readonly granular: { + readonly mcp_elicitations: boolean; + readonly request_permissions?: boolean; + readonly rules: boolean; + readonly sandbox_approval: boolean; + readonly skill_approval?: boolean; + }; + }; +export const V2ConfigRequirementsReadResponse__AskForApproval = Schema.Union( + [ + Schema.Literals(["untrusted", "on-failure", "on-request", "never"]), + Schema.Struct({ + granular: Schema.Struct({ + mcp_elicitations: Schema.Boolean, + request_permissions: Schema.optionalKey(Schema.Boolean.annotate({ default: false })), + rules: Schema.Boolean, + sandbox_approval: Schema.Boolean, + skill_approval: Schema.optionalKey(Schema.Boolean.annotate({ default: false })), + }), + }).annotate({ title: "GranularAskForApproval" }), + ], + { mode: "oneOf" }, +); + +export type V2ConfigRequirementsReadResponse__NetworkDomainPermission = "allow" | "deny"; +export const V2ConfigRequirementsReadResponse__NetworkDomainPermission = Schema.Literals([ + "allow", + "deny", +]); + +export type V2ConfigRequirementsReadResponse__NetworkUnixSocketPermission = "allow" | "none"; +export const V2ConfigRequirementsReadResponse__NetworkUnixSocketPermission = Schema.Literals([ + "allow", + "none", +]); + +export type V2ConfigRequirementsReadResponse__ResidencyRequirement = "us"; +export const V2ConfigRequirementsReadResponse__ResidencyRequirement = Schema.Literal("us"); + +export type V2ConfigRequirementsReadResponse__SandboxMode = + | "read-only" + | "workspace-write" + | "danger-full-access"; +export const V2ConfigRequirementsReadResponse__SandboxMode = Schema.Literals([ + "read-only", + "workspace-write", + "danger-full-access", +]); + +export type V2ConfigRequirementsReadResponse__WebSearchMode = "disabled" | "cached" | "live"; +export const V2ConfigRequirementsReadResponse__WebSearchMode = Schema.Literals([ + "disabled", + "cached", + "live", +]); + +export type V2ConfigValueWriteParams__MergeStrategy = "replace" | "upsert"; +export const V2ConfigValueWriteParams__MergeStrategy = Schema.Literals(["replace", "upsert"]); + +export type V2ConfigWarningNotification__TextPosition = { + readonly column: number; + readonly line: number; +}; +export const V2ConfigWarningNotification__TextPosition = Schema.Struct({ + column: Schema.Number.annotate({ + description: "1-based column number (in Unicode scalar values).", + format: "uint", + }) + .check(Schema.isInt()) + .check(Schema.isGreaterThanOrEqualTo(0)), + line: Schema.Number.annotate({ description: "1-based line number.", format: "uint" }) + .check(Schema.isInt()) + .check(Schema.isGreaterThanOrEqualTo(0)), +}); + +export type V2ConfigWriteResponse__AbsolutePathBuf = string; +export const V2ConfigWriteResponse__AbsolutePathBuf = Schema.String.annotate({ + description: + "A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\n\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.", +}); + +export type V2ConfigWriteResponse__WriteStatus = "ok" | "okOverridden"; +export const V2ConfigWriteResponse__WriteStatus = Schema.Literals(["ok", "okOverridden"]); + +export type V2ErrorNotification__NonSteerableTurnKind = "review" | "compact"; +export const V2ErrorNotification__NonSteerableTurnKind = Schema.Literals(["review", "compact"]); + +export type V2ExperimentalFeatureListResponse__ExperimentalFeature = { + readonly announcement?: string | null; + readonly defaultEnabled: boolean; + readonly description?: string | null; + readonly displayName?: string | null; + readonly enabled: boolean; + readonly name: string; + readonly stage: "beta" | "underDevelopment" | "stable" | "deprecated" | "removed"; +}; +export const V2ExperimentalFeatureListResponse__ExperimentalFeature = Schema.Struct({ + announcement: Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + description: + "Announcement copy shown to users when the feature is introduced. Null when this feature is not in beta.", + }), + Schema.Null, + ]), + ), + defaultEnabled: Schema.Boolean.annotate({ + description: "Whether this feature is enabled by default.", + }), + description: Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + description: + "Short summary describing what the feature does. Null when this feature is not in beta.", + }), + Schema.Null, + ]), + ), + displayName: Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + description: + "User-facing display name shown in the experimental features UI. Null when this feature is not in beta.", + }), + Schema.Null, + ]), + ), + enabled: Schema.Boolean.annotate({ + description: "Whether this feature is currently enabled in the loaded config.", + }), + name: Schema.String.annotate({ + description: "Stable key used in config.toml and CLI flag toggles.", + }), + stage: Schema.Literals(["beta", "underDevelopment", "stable", "deprecated", "removed"]).annotate({ + description: "Lifecycle stage of this feature flag.", + }), +}); + +export type V2ExternalAgentConfigDetectResponse__ExternalAgentConfigMigrationItemType = + | "AGENTS_MD" + | "CONFIG" + | "SKILLS" + | "MCP_SERVER_CONFIG"; +export const V2ExternalAgentConfigDetectResponse__ExternalAgentConfigMigrationItemType = + Schema.Literals(["AGENTS_MD", "CONFIG", "SKILLS", "MCP_SERVER_CONFIG"]); + +export type V2ExternalAgentConfigImportParams__ExternalAgentConfigMigrationItemType = + | "AGENTS_MD" + | "CONFIG" + | "SKILLS" + | "MCP_SERVER_CONFIG"; +export const V2ExternalAgentConfigImportParams__ExternalAgentConfigMigrationItemType = + Schema.Literals(["AGENTS_MD", "CONFIG", "SKILLS", "MCP_SERVER_CONFIG"]); + +export type V2FsChangedNotification__AbsolutePathBuf = string; +export const V2FsChangedNotification__AbsolutePathBuf = Schema.String.annotate({ + description: + "A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\n\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.", +}); + +export type V2FsReadDirectoryResponse__FsReadDirectoryEntry = { + readonly fileName: string; + readonly isDirectory: boolean; + readonly isFile: boolean; +}; +export const V2FsReadDirectoryResponse__FsReadDirectoryEntry = Schema.Struct({ + fileName: Schema.String.annotate({ + description: "Direct child entry name only, not an absolute or relative path.", + }), + isDirectory: Schema.Boolean.annotate({ + description: "Whether this entry resolves to a directory.", + }), + isFile: Schema.Boolean.annotate({ + description: "Whether this entry resolves to a regular file.", + }), +}).annotate({ description: "A directory entry returned by `fs/readDirectory`." }); + +export type V2GetAccountRateLimitsResponse__CreditsSnapshot = { + readonly balance?: string | null; + readonly hasCredits: boolean; + readonly unlimited: boolean; +}; +export const V2GetAccountRateLimitsResponse__CreditsSnapshot = Schema.Struct({ + balance: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + hasCredits: Schema.Boolean, + unlimited: Schema.Boolean, +}); + +export type V2GetAccountRateLimitsResponse__PlanType = + | "free" + | "go" + | "plus" + | "pro" + | "team" + | "self_serve_business_usage_based" + | "business" + | "enterprise_cbp_usage_based" + | "enterprise" + | "edu" + | "unknown"; +export const V2GetAccountRateLimitsResponse__PlanType = Schema.Literals([ + "free", + "go", + "plus", + "pro", + "team", + "self_serve_business_usage_based", + "business", + "enterprise_cbp_usage_based", + "enterprise", + "edu", + "unknown", +]); + +export type V2GetAccountRateLimitsResponse__RateLimitWindow = { + readonly resetsAt?: number | null; + readonly usedPercent: number; + readonly windowDurationMins?: number | null; +}; +export const V2GetAccountRateLimitsResponse__RateLimitWindow = Schema.Struct({ + resetsAt: Schema.optionalKey( + Schema.Union([Schema.Number.annotate({ format: "int64" }).check(Schema.isInt()), Schema.Null]), + ), + usedPercent: Schema.Number.annotate({ format: "int32" }).check(Schema.isInt()), + windowDurationMins: Schema.optionalKey( + Schema.Union([Schema.Number.annotate({ format: "int64" }).check(Schema.isInt()), Schema.Null]), + ), +}); + +export type V2GetAccountResponse__PlanType = + | "free" + | "go" + | "plus" + | "pro" + | "team" + | "self_serve_business_usage_based" + | "business" + | "enterprise_cbp_usage_based" + | "enterprise" + | "edu" + | "unknown"; +export const V2GetAccountResponse__PlanType = Schema.Literals([ + "free", + "go", + "plus", + "pro", + "team", + "self_serve_business_usage_based", + "business", + "enterprise_cbp_usage_based", + "enterprise", + "edu", + "unknown", +]); + +export type V2HookCompletedNotification__HookEventName = + | "preToolUse" + | "postToolUse" + | "sessionStart" + | "userPromptSubmit" + | "stop"; +export const V2HookCompletedNotification__HookEventName = Schema.Literals([ + "preToolUse", + "postToolUse", + "sessionStart", + "userPromptSubmit", + "stop", +]); + +export type V2HookCompletedNotification__HookExecutionMode = "sync" | "async"; +export const V2HookCompletedNotification__HookExecutionMode = Schema.Literals(["sync", "async"]); + +export type V2HookCompletedNotification__HookHandlerType = "command" | "prompt" | "agent"; +export const V2HookCompletedNotification__HookHandlerType = Schema.Literals([ + "command", + "prompt", + "agent", +]); + +export type V2HookCompletedNotification__HookOutputEntryKind = + | "warning" + | "stop" + | "feedback" + | "context" + | "error"; +export const V2HookCompletedNotification__HookOutputEntryKind = Schema.Literals([ + "warning", + "stop", + "feedback", + "context", + "error", +]); + +export type V2HookCompletedNotification__HookRunStatus = + | "running" + | "completed" + | "failed" + | "blocked" + | "stopped"; +export const V2HookCompletedNotification__HookRunStatus = Schema.Literals([ + "running", + "completed", + "failed", + "blocked", + "stopped", +]); + +export type V2HookCompletedNotification__HookScope = "thread" | "turn"; +export const V2HookCompletedNotification__HookScope = Schema.Literals(["thread", "turn"]); + +export type V2HookStartedNotification__HookEventName = + | "preToolUse" + | "postToolUse" + | "sessionStart" + | "userPromptSubmit" + | "stop"; +export const V2HookStartedNotification__HookEventName = Schema.Literals([ + "preToolUse", + "postToolUse", + "sessionStart", + "userPromptSubmit", + "stop", +]); + +export type V2HookStartedNotification__HookExecutionMode = "sync" | "async"; +export const V2HookStartedNotification__HookExecutionMode = Schema.Literals(["sync", "async"]); + +export type V2HookStartedNotification__HookHandlerType = "command" | "prompt" | "agent"; +export const V2HookStartedNotification__HookHandlerType = Schema.Literals([ + "command", + "prompt", + "agent", +]); + +export type V2HookStartedNotification__HookOutputEntryKind = + | "warning" + | "stop" + | "feedback" + | "context" + | "error"; +export const V2HookStartedNotification__HookOutputEntryKind = Schema.Literals([ + "warning", + "stop", + "feedback", + "context", + "error", +]); + +export type V2HookStartedNotification__HookRunStatus = + | "running" + | "completed" + | "failed" + | "blocked" + | "stopped"; +export const V2HookStartedNotification__HookRunStatus = Schema.Literals([ + "running", + "completed", + "failed", + "blocked", + "stopped", +]); + +export type V2HookStartedNotification__HookScope = "thread" | "turn"; +export const V2HookStartedNotification__HookScope = Schema.Literals(["thread", "turn"]); + +export type V2ItemCompletedNotification__CollabAgentStatus = + | "pendingInit" + | "running" + | "interrupted" + | "completed" + | "errored" + | "shutdown" + | "notFound"; +export const V2ItemCompletedNotification__CollabAgentStatus = Schema.Literals([ + "pendingInit", + "running", + "interrupted", + "completed", + "errored", + "shutdown", + "notFound", +]); + +export type V2ItemCompletedNotification__CommandAction = + | { + readonly command: string; + readonly name: string; + readonly path: string; + readonly type: "read"; + } + | { readonly command: string; readonly path?: string | null; readonly type: "listFiles" } + | { + readonly command: string; + readonly path?: string | null; + readonly query?: string | null; + readonly type: "search"; + } + | { readonly command: string; readonly type: "unknown" }; +export const V2ItemCompletedNotification__CommandAction = Schema.Union( + [ + Schema.Struct({ + command: Schema.String, + name: Schema.String, + path: Schema.String, + type: Schema.Literal("read").annotate({ title: "ReadCommandActionType" }), + }).annotate({ title: "ReadCommandAction" }), + Schema.Struct({ + command: Schema.String, + path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + type: Schema.Literal("listFiles").annotate({ title: "ListFilesCommandActionType" }), + }).annotate({ title: "ListFilesCommandAction" }), + Schema.Struct({ + command: Schema.String, + path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + query: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + type: Schema.Literal("search").annotate({ title: "SearchCommandActionType" }), + }).annotate({ title: "SearchCommandAction" }), + Schema.Struct({ + command: Schema.String, + type: Schema.Literal("unknown").annotate({ title: "UnknownCommandActionType" }), + }).annotate({ title: "UnknownCommandAction" }), + ], + { mode: "oneOf" }, +); + +export type V2ItemCompletedNotification__CommandExecutionStatus = + | "inProgress" + | "completed" + | "failed" + | "declined"; +export const V2ItemCompletedNotification__CommandExecutionStatus = Schema.Literals([ + "inProgress", + "completed", + "failed", + "declined", +]); + +export type V2ItemCompletedNotification__DynamicToolCallOutputContentItem = + | { readonly text: string; readonly type: "inputText" } + | { readonly imageUrl: string; readonly type: "inputImage" }; +export const V2ItemCompletedNotification__DynamicToolCallOutputContentItem = Schema.Union( + [ + Schema.Struct({ + text: Schema.String, + type: Schema.Literal("inputText").annotate({ + title: "InputTextDynamicToolCallOutputContentItemType", + }), + }).annotate({ title: "InputTextDynamicToolCallOutputContentItem" }), + Schema.Struct({ + imageUrl: Schema.String, + type: Schema.Literal("inputImage").annotate({ + title: "InputImageDynamicToolCallOutputContentItemType", + }), + }).annotate({ title: "InputImageDynamicToolCallOutputContentItem" }), + ], + { mode: "oneOf" }, +); + +export type V2ItemCompletedNotification__DynamicToolCallStatus = + | "inProgress" + | "completed" + | "failed"; +export const V2ItemCompletedNotification__DynamicToolCallStatus = Schema.Literals([ + "inProgress", + "completed", + "failed", +]); + +export type V2ItemCompletedNotification__HookPromptFragment = { + readonly hookRunId: string; + readonly text: string; +}; +export const V2ItemCompletedNotification__HookPromptFragment = Schema.Struct({ + hookRunId: Schema.String, + text: Schema.String, +}); + +export type V2ItemCompletedNotification__McpToolCallError = { readonly message: string }; +export const V2ItemCompletedNotification__McpToolCallError = Schema.Struct({ + message: Schema.String, +}); + +export type V2ItemCompletedNotification__McpToolCallResult = { + readonly _meta?: unknown; + readonly content: ReadonlyArray; + readonly structuredContent?: unknown; +}; +export const V2ItemCompletedNotification__McpToolCallResult = Schema.Struct({ + _meta: Schema.optionalKey(Schema.Unknown), + content: Schema.Array(Schema.Unknown), + structuredContent: Schema.optionalKey(Schema.Unknown), +}); + +export type V2ItemCompletedNotification__McpToolCallStatus = "inProgress" | "completed" | "failed"; +export const V2ItemCompletedNotification__McpToolCallStatus = Schema.Literals([ + "inProgress", + "completed", + "failed", +]); + +export type V2ItemCompletedNotification__MemoryCitationEntry = { + readonly lineEnd: number; + readonly lineStart: number; + readonly note: string; + readonly path: string; +}; +export const V2ItemCompletedNotification__MemoryCitationEntry = Schema.Struct({ + lineEnd: Schema.Number.annotate({ format: "uint32" }) + .check(Schema.isInt()) + .check(Schema.isGreaterThanOrEqualTo(0)), + lineStart: Schema.Number.annotate({ format: "uint32" }) + .check(Schema.isInt()) + .check(Schema.isGreaterThanOrEqualTo(0)), + note: Schema.String, + path: Schema.String, +}); + +export type V2ItemCompletedNotification__MessagePhase = "commentary" | "final_answer"; +export const V2ItemCompletedNotification__MessagePhase = Schema.Literals([ + "commentary", + "final_answer", +]).annotate({ + description: + 'Classifies an assistant message as interim commentary or final answer text.\n\nProviders do not emit this consistently, so callers must treat `None` as "phase unknown" and keep compatibility behavior for legacy models.', +}); + +export type V2ItemCompletedNotification__PatchApplyStatus = + | "inProgress" + | "completed" + | "failed" + | "declined"; +export const V2ItemCompletedNotification__PatchApplyStatus = Schema.Literals([ + "inProgress", + "completed", + "failed", + "declined", +]); + +export type V2ItemCompletedNotification__PatchChangeKind = + | { readonly type: "add" } + | { readonly type: "delete" } + | { readonly move_path?: string | null; readonly type: "update" }; +export const V2ItemCompletedNotification__PatchChangeKind = Schema.Union( + [ + Schema.Struct({ + type: Schema.Literal("add").annotate({ title: "AddPatchChangeKindType" }), + }).annotate({ title: "AddPatchChangeKind" }), + Schema.Struct({ + type: Schema.Literal("delete").annotate({ title: "DeletePatchChangeKindType" }), + }).annotate({ title: "DeletePatchChangeKind" }), + Schema.Struct({ + move_path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + type: Schema.Literal("update").annotate({ title: "UpdatePatchChangeKindType" }), + }).annotate({ title: "UpdatePatchChangeKind" }), + ], + { mode: "oneOf" }, +); + +export type V2ItemCompletedNotification__ReasoningEffort = + | "none" + | "minimal" + | "low" + | "medium" + | "high" + | "xhigh"; +export const V2ItemCompletedNotification__ReasoningEffort = Schema.Literals([ + "none", + "minimal", + "low", + "medium", + "high", + "xhigh", +]).annotate({ + description: + "See https://platform.openai.com/docs/guides/reasoning?api-mode=responses#get-started-with-reasoning", +}); + +export type V2ItemCompletedNotification__TextElement = { + readonly byteRange: { readonly end: number; readonly start: number }; + readonly placeholder?: string | null; +}; +export const V2ItemCompletedNotification__TextElement = Schema.Struct({ + byteRange: Schema.Struct({ + end: Schema.Number.annotate({ format: "uint" }) + .check(Schema.isInt()) + .check(Schema.isGreaterThanOrEqualTo(0)), + start: Schema.Number.annotate({ format: "uint" }) + .check(Schema.isInt()) + .check(Schema.isGreaterThanOrEqualTo(0)), + }).annotate({ + description: "Byte range in the parent `text` buffer that this element occupies.", + }), + placeholder: Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + description: "Optional human-readable placeholder for the element, displayed in the UI.", + }), + Schema.Null, + ]), + ), +}); + +export type V2ItemCompletedNotification__WebSearchAction = + | { + readonly queries?: ReadonlyArray | null; + readonly query?: string | null; + readonly type: "search"; + } + | { readonly type: "openPage"; readonly url?: string | null } + | { readonly pattern?: string | null; readonly type: "findInPage"; readonly url?: string | null } + | { readonly type: "other" }; +export const V2ItemCompletedNotification__WebSearchAction = Schema.Union( + [ + Schema.Struct({ + queries: Schema.optionalKey(Schema.Union([Schema.Array(Schema.String), Schema.Null])), + query: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + type: Schema.Literal("search").annotate({ title: "SearchWebSearchActionType" }), + }).annotate({ title: "SearchWebSearchAction" }), + Schema.Struct({ + type: Schema.Literal("openPage").annotate({ title: "OpenPageWebSearchActionType" }), + url: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + }).annotate({ title: "OpenPageWebSearchAction" }), + Schema.Struct({ + pattern: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + type: Schema.Literal("findInPage").annotate({ title: "FindInPageWebSearchActionType" }), + url: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + }).annotate({ title: "FindInPageWebSearchAction" }), + Schema.Struct({ + type: Schema.Literal("other").annotate({ title: "OtherWebSearchActionType" }), + }).annotate({ title: "OtherWebSearchAction" }), + ], + { mode: "oneOf" }, +); + +export type V2ItemGuardianApprovalReviewCompletedNotification__AutoReviewDecisionSource = "agent"; +export const V2ItemGuardianApprovalReviewCompletedNotification__AutoReviewDecisionSource = + Schema.Literal("agent").annotate({ + description: "[UNSTABLE] Source that produced a terminal guardian approval review decision.", + }); + +export type V2ItemGuardianApprovalReviewCompletedNotification__GuardianApprovalReviewStatus = + | "inProgress" + | "approved" + | "denied" + | "timedOut" + | "aborted"; +export const V2ItemGuardianApprovalReviewCompletedNotification__GuardianApprovalReviewStatus = + Schema.Literals(["inProgress", "approved", "denied", "timedOut", "aborted"]).annotate({ + description: "[UNSTABLE] Lifecycle state for a guardian approval review.", + }); + +export type V2ItemGuardianApprovalReviewCompletedNotification__GuardianCommandSource = + | "shell" + | "unifiedExec"; +export const V2ItemGuardianApprovalReviewCompletedNotification__GuardianCommandSource = + Schema.Literals(["shell", "unifiedExec"]); + +export type V2ItemGuardianApprovalReviewCompletedNotification__GuardianRiskLevel = + | "low" + | "medium" + | "high" + | "critical"; +export const V2ItemGuardianApprovalReviewCompletedNotification__GuardianRiskLevel = Schema.Literals( + ["low", "medium", "high", "critical"], +).annotate({ description: "[UNSTABLE] Risk level assigned by guardian approval review." }); + +export type V2ItemGuardianApprovalReviewCompletedNotification__GuardianUserAuthorization = + | "unknown" + | "low" + | "medium" + | "high"; +export const V2ItemGuardianApprovalReviewCompletedNotification__GuardianUserAuthorization = + Schema.Literals(["unknown", "low", "medium", "high"]).annotate({ + description: "[UNSTABLE] Authorization level assigned by guardian approval review.", + }); + +export type V2ItemGuardianApprovalReviewCompletedNotification__NetworkApprovalProtocol = + | "http" + | "https" + | "socks5Tcp" + | "socks5Udp"; +export const V2ItemGuardianApprovalReviewCompletedNotification__NetworkApprovalProtocol = + Schema.Literals(["http", "https", "socks5Tcp", "socks5Udp"]); + +export type V2ItemGuardianApprovalReviewStartedNotification__GuardianApprovalReviewStatus = + | "inProgress" + | "approved" + | "denied" + | "timedOut" + | "aborted"; +export const V2ItemGuardianApprovalReviewStartedNotification__GuardianApprovalReviewStatus = + Schema.Literals(["inProgress", "approved", "denied", "timedOut", "aborted"]).annotate({ + description: "[UNSTABLE] Lifecycle state for a guardian approval review.", + }); + +export type V2ItemGuardianApprovalReviewStartedNotification__GuardianCommandSource = + | "shell" + | "unifiedExec"; +export const V2ItemGuardianApprovalReviewStartedNotification__GuardianCommandSource = + Schema.Literals(["shell", "unifiedExec"]); + +export type V2ItemGuardianApprovalReviewStartedNotification__GuardianRiskLevel = + | "low" + | "medium" + | "high" + | "critical"; +export const V2ItemGuardianApprovalReviewStartedNotification__GuardianRiskLevel = Schema.Literals([ + "low", + "medium", + "high", + "critical", +]).annotate({ description: "[UNSTABLE] Risk level assigned by guardian approval review." }); + +export type V2ItemGuardianApprovalReviewStartedNotification__GuardianUserAuthorization = + | "unknown" + | "low" + | "medium" + | "high"; +export const V2ItemGuardianApprovalReviewStartedNotification__GuardianUserAuthorization = + Schema.Literals(["unknown", "low", "medium", "high"]).annotate({ + description: "[UNSTABLE] Authorization level assigned by guardian approval review.", + }); + +export type V2ItemGuardianApprovalReviewStartedNotification__NetworkApprovalProtocol = + | "http" + | "https" + | "socks5Tcp" + | "socks5Udp"; +export const V2ItemGuardianApprovalReviewStartedNotification__NetworkApprovalProtocol = + Schema.Literals(["http", "https", "socks5Tcp", "socks5Udp"]); + +export type V2ItemStartedNotification__CollabAgentStatus = + | "pendingInit" + | "running" + | "interrupted" + | "completed" + | "errored" + | "shutdown" + | "notFound"; +export const V2ItemStartedNotification__CollabAgentStatus = Schema.Literals([ + "pendingInit", + "running", + "interrupted", + "completed", + "errored", + "shutdown", + "notFound", +]); + +export type V2ItemStartedNotification__CommandAction = + | { + readonly command: string; + readonly name: string; + readonly path: string; + readonly type: "read"; + } + | { readonly command: string; readonly path?: string | null; readonly type: "listFiles" } + | { + readonly command: string; + readonly path?: string | null; + readonly query?: string | null; + readonly type: "search"; + } + | { readonly command: string; readonly type: "unknown" }; +export const V2ItemStartedNotification__CommandAction = Schema.Union( + [ + Schema.Struct({ + command: Schema.String, + name: Schema.String, + path: Schema.String, + type: Schema.Literal("read").annotate({ title: "ReadCommandActionType" }), + }).annotate({ title: "ReadCommandAction" }), + Schema.Struct({ + command: Schema.String, + path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + type: Schema.Literal("listFiles").annotate({ title: "ListFilesCommandActionType" }), + }).annotate({ title: "ListFilesCommandAction" }), + Schema.Struct({ + command: Schema.String, + path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + query: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + type: Schema.Literal("search").annotate({ title: "SearchCommandActionType" }), + }).annotate({ title: "SearchCommandAction" }), + Schema.Struct({ + command: Schema.String, + type: Schema.Literal("unknown").annotate({ title: "UnknownCommandActionType" }), + }).annotate({ title: "UnknownCommandAction" }), + ], + { mode: "oneOf" }, +); + +export type V2ItemStartedNotification__CommandExecutionStatus = + | "inProgress" + | "completed" + | "failed" + | "declined"; +export const V2ItemStartedNotification__CommandExecutionStatus = Schema.Literals([ + "inProgress", + "completed", + "failed", + "declined", +]); + +export type V2ItemStartedNotification__DynamicToolCallOutputContentItem = + | { readonly text: string; readonly type: "inputText" } + | { readonly imageUrl: string; readonly type: "inputImage" }; +export const V2ItemStartedNotification__DynamicToolCallOutputContentItem = Schema.Union( + [ + Schema.Struct({ + text: Schema.String, + type: Schema.Literal("inputText").annotate({ + title: "InputTextDynamicToolCallOutputContentItemType", + }), + }).annotate({ title: "InputTextDynamicToolCallOutputContentItem" }), + Schema.Struct({ + imageUrl: Schema.String, + type: Schema.Literal("inputImage").annotate({ + title: "InputImageDynamicToolCallOutputContentItemType", + }), + }).annotate({ title: "InputImageDynamicToolCallOutputContentItem" }), + ], + { mode: "oneOf" }, +); + +export type V2ItemStartedNotification__DynamicToolCallStatus = + | "inProgress" + | "completed" + | "failed"; +export const V2ItemStartedNotification__DynamicToolCallStatus = Schema.Literals([ + "inProgress", + "completed", + "failed", +]); + +export type V2ItemStartedNotification__HookPromptFragment = { + readonly hookRunId: string; + readonly text: string; +}; +export const V2ItemStartedNotification__HookPromptFragment = Schema.Struct({ + hookRunId: Schema.String, + text: Schema.String, +}); + +export type V2ItemStartedNotification__McpToolCallError = { readonly message: string }; +export const V2ItemStartedNotification__McpToolCallError = Schema.Struct({ + message: Schema.String, +}); + +export type V2ItemStartedNotification__McpToolCallResult = { + readonly _meta?: unknown; + readonly content: ReadonlyArray; + readonly structuredContent?: unknown; +}; +export const V2ItemStartedNotification__McpToolCallResult = Schema.Struct({ + _meta: Schema.optionalKey(Schema.Unknown), + content: Schema.Array(Schema.Unknown), + structuredContent: Schema.optionalKey(Schema.Unknown), +}); + +export type V2ItemStartedNotification__McpToolCallStatus = "inProgress" | "completed" | "failed"; +export const V2ItemStartedNotification__McpToolCallStatus = Schema.Literals([ + "inProgress", + "completed", + "failed", +]); + +export type V2ItemStartedNotification__MemoryCitationEntry = { + readonly lineEnd: number; + readonly lineStart: number; + readonly note: string; + readonly path: string; +}; +export const V2ItemStartedNotification__MemoryCitationEntry = Schema.Struct({ + lineEnd: Schema.Number.annotate({ format: "uint32" }) + .check(Schema.isInt()) + .check(Schema.isGreaterThanOrEqualTo(0)), + lineStart: Schema.Number.annotate({ format: "uint32" }) + .check(Schema.isInt()) + .check(Schema.isGreaterThanOrEqualTo(0)), + note: Schema.String, + path: Schema.String, +}); + +export type V2ItemStartedNotification__MessagePhase = "commentary" | "final_answer"; +export const V2ItemStartedNotification__MessagePhase = Schema.Literals([ + "commentary", + "final_answer", +]).annotate({ + description: + 'Classifies an assistant message as interim commentary or final answer text.\n\nProviders do not emit this consistently, so callers must treat `None` as "phase unknown" and keep compatibility behavior for legacy models.', +}); + +export type V2ItemStartedNotification__PatchApplyStatus = + | "inProgress" + | "completed" + | "failed" + | "declined"; +export const V2ItemStartedNotification__PatchApplyStatus = Schema.Literals([ + "inProgress", + "completed", + "failed", + "declined", +]); + +export type V2ItemStartedNotification__PatchChangeKind = + | { readonly type: "add" } + | { readonly type: "delete" } + | { readonly move_path?: string | null; readonly type: "update" }; +export const V2ItemStartedNotification__PatchChangeKind = Schema.Union( + [ + Schema.Struct({ + type: Schema.Literal("add").annotate({ title: "AddPatchChangeKindType" }), + }).annotate({ title: "AddPatchChangeKind" }), + Schema.Struct({ + type: Schema.Literal("delete").annotate({ title: "DeletePatchChangeKindType" }), + }).annotate({ title: "DeletePatchChangeKind" }), + Schema.Struct({ + move_path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + type: Schema.Literal("update").annotate({ title: "UpdatePatchChangeKindType" }), + }).annotate({ title: "UpdatePatchChangeKind" }), + ], + { mode: "oneOf" }, +); + +export type V2ItemStartedNotification__ReasoningEffort = + | "none" + | "minimal" + | "low" + | "medium" + | "high" + | "xhigh"; +export const V2ItemStartedNotification__ReasoningEffort = Schema.Literals([ + "none", + "minimal", + "low", + "medium", + "high", + "xhigh", +]).annotate({ + description: + "See https://platform.openai.com/docs/guides/reasoning?api-mode=responses#get-started-with-reasoning", +}); + +export type V2ItemStartedNotification__TextElement = { + readonly byteRange: { readonly end: number; readonly start: number }; + readonly placeholder?: string | null; +}; +export const V2ItemStartedNotification__TextElement = Schema.Struct({ + byteRange: Schema.Struct({ + end: Schema.Number.annotate({ format: "uint" }) + .check(Schema.isInt()) + .check(Schema.isGreaterThanOrEqualTo(0)), + start: Schema.Number.annotate({ format: "uint" }) + .check(Schema.isInt()) + .check(Schema.isGreaterThanOrEqualTo(0)), + }).annotate({ + description: "Byte range in the parent `text` buffer that this element occupies.", + }), + placeholder: Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + description: "Optional human-readable placeholder for the element, displayed in the UI.", + }), + Schema.Null, + ]), + ), +}); + +export type V2ItemStartedNotification__WebSearchAction = + | { + readonly queries?: ReadonlyArray | null; + readonly query?: string | null; + readonly type: "search"; + } + | { readonly type: "openPage"; readonly url?: string | null } + | { readonly pattern?: string | null; readonly type: "findInPage"; readonly url?: string | null } + | { readonly type: "other" }; +export const V2ItemStartedNotification__WebSearchAction = Schema.Union( + [ + Schema.Struct({ + queries: Schema.optionalKey(Schema.Union([Schema.Array(Schema.String), Schema.Null])), + query: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + type: Schema.Literal("search").annotate({ title: "SearchWebSearchActionType" }), + }).annotate({ title: "SearchWebSearchAction" }), + Schema.Struct({ + type: Schema.Literal("openPage").annotate({ title: "OpenPageWebSearchActionType" }), + url: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + }).annotate({ title: "OpenPageWebSearchAction" }), + Schema.Struct({ + pattern: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + type: Schema.Literal("findInPage").annotate({ title: "FindInPageWebSearchActionType" }), + url: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + }).annotate({ title: "FindInPageWebSearchAction" }), + Schema.Struct({ + type: Schema.Literal("other").annotate({ title: "OtherWebSearchActionType" }), + }).annotate({ title: "OtherWebSearchAction" }), + ], + { mode: "oneOf" }, +); + +export type V2ListMcpServerStatusParams__McpServerStatusDetail = "full" | "toolsAndAuthOnly"; +export const V2ListMcpServerStatusParams__McpServerStatusDetail = Schema.Literals([ + "full", + "toolsAndAuthOnly", +]); + +export type V2ListMcpServerStatusResponse__McpAuthStatus = + | "unsupported" + | "notLoggedIn" + | "bearerToken" + | "oAuth"; +export const V2ListMcpServerStatusResponse__McpAuthStatus = Schema.Literals([ + "unsupported", + "notLoggedIn", + "bearerToken", + "oAuth", +]); + +export type V2ListMcpServerStatusResponse__Resource = { + readonly _meta?: unknown; + readonly annotations?: unknown; + readonly description?: string | null; + readonly icons?: ReadonlyArray | null; + readonly mimeType?: string | null; + readonly name: string; + readonly size?: number | null; + readonly title?: string | null; + readonly uri: string; +}; +export const V2ListMcpServerStatusResponse__Resource = Schema.Struct({ + _meta: Schema.optionalKey(Schema.Unknown), + annotations: Schema.optionalKey(Schema.Unknown), + description: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + icons: Schema.optionalKey(Schema.Union([Schema.Array(Schema.Unknown), Schema.Null])), + mimeType: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + name: Schema.String, + size: Schema.optionalKey( + Schema.Union([Schema.Number.annotate({ format: "int64" }).check(Schema.isInt()), Schema.Null]), + ), + title: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + uri: Schema.String, +}).annotate({ description: "A known resource that the server is capable of reading." }); + +export type V2ListMcpServerStatusResponse__ResourceTemplate = { + readonly annotations?: unknown; + readonly description?: string | null; + readonly mimeType?: string | null; + readonly name: string; + readonly title?: string | null; + readonly uriTemplate: string; +}; +export const V2ListMcpServerStatusResponse__ResourceTemplate = Schema.Struct({ + annotations: Schema.optionalKey(Schema.Unknown), + description: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + mimeType: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + name: Schema.String, + title: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + uriTemplate: Schema.String, +}).annotate({ description: "A template description for resources available on the server." }); + +export type V2ListMcpServerStatusResponse__Tool = { + readonly _meta?: unknown; + readonly annotations?: unknown; + readonly description?: string | null; + readonly icons?: ReadonlyArray | null; + readonly inputSchema: unknown; + readonly name: string; + readonly outputSchema?: unknown; + readonly title?: string | null; +}; +export const V2ListMcpServerStatusResponse__Tool = Schema.Struct({ + _meta: Schema.optionalKey(Schema.Unknown), + annotations: Schema.optionalKey(Schema.Unknown), + description: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + icons: Schema.optionalKey(Schema.Union([Schema.Array(Schema.Unknown), Schema.Null])), + inputSchema: Schema.Unknown, + name: Schema.String, + outputSchema: Schema.optionalKey(Schema.Unknown), + title: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), +}).annotate({ description: "Definition for a tool the client can call." }); + +export type V2McpResourceReadResponse__ResourceContent = + | { + readonly _meta?: unknown; + readonly mimeType?: string | null; + readonly text: string; + readonly uri: string; + } + | { + readonly _meta?: unknown; + readonly blob: string; + readonly mimeType?: string | null; + readonly uri: string; + }; +export const V2McpResourceReadResponse__ResourceContent = Schema.Union([ + Schema.Struct({ + _meta: Schema.optionalKey(Schema.Unknown), + mimeType: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + text: Schema.String, + uri: Schema.String.annotate({ description: "The URI of this resource." }), + }), + Schema.Struct({ + _meta: Schema.optionalKey(Schema.Unknown), + blob: Schema.String, + mimeType: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + uri: Schema.String.annotate({ description: "The URI of this resource." }), + }), +]).annotate({ description: "Contents returned when reading a resource from an MCP server." }); + +export type V2McpServerStatusUpdatedNotification__McpServerStartupState = + | "starting" + | "ready" + | "failed" + | "cancelled"; +export const V2McpServerStatusUpdatedNotification__McpServerStartupState = Schema.Literals([ + "starting", + "ready", + "failed", + "cancelled", +]); + +export type V2ModelListResponse__InputModality = "text" | "image"; +export const V2ModelListResponse__InputModality = Schema.Literals(["text", "image"]).annotate({ + description: "Canonical user-input modality tags advertised by a model.", +}); + +export type V2ModelListResponse__ModelAvailabilityNux = { readonly message: string }; +export const V2ModelListResponse__ModelAvailabilityNux = Schema.Struct({ message: Schema.String }); + +export type V2ModelListResponse__ModelUpgradeInfo = { + readonly migrationMarkdown?: string | null; + readonly model: string; + readonly modelLink?: string | null; + readonly upgradeCopy?: string | null; +}; +export const V2ModelListResponse__ModelUpgradeInfo = Schema.Struct({ + migrationMarkdown: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + model: Schema.String, + modelLink: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + upgradeCopy: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), +}); + +export type V2ModelListResponse__ReasoningEffort = + | "none" + | "minimal" + | "low" + | "medium" + | "high" + | "xhigh"; +export const V2ModelListResponse__ReasoningEffort = Schema.Literals([ + "none", + "minimal", + "low", + "medium", + "high", + "xhigh", +]).annotate({ + description: + "See https://platform.openai.com/docs/guides/reasoning?api-mode=responses#get-started-with-reasoning", +}); + +export type V2ModelReroutedNotification__ModelRerouteReason = "highRiskCyberActivity"; +export const V2ModelReroutedNotification__ModelRerouteReason = + Schema.Literal("highRiskCyberActivity"); + +export type V2PluginInstallParams__AbsolutePathBuf = string; +export const V2PluginInstallParams__AbsolutePathBuf = Schema.String.annotate({ + description: + "A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\n\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.", +}); + +export type V2PluginInstallResponse__AppSummary = { + readonly description?: string | null; + readonly id: string; + readonly installUrl?: string | null; + readonly name: string; + readonly needsAuth: boolean; +}; +export const V2PluginInstallResponse__AppSummary = Schema.Struct({ + description: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + id: Schema.String, + installUrl: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + name: Schema.String, + needsAuth: Schema.Boolean, +}).annotate({ description: "EXPERIMENTAL - app metadata summary for plugin responses." }); + +export type V2PluginInstallResponse__PluginAuthPolicy = "ON_INSTALL" | "ON_USE"; +export const V2PluginInstallResponse__PluginAuthPolicy = Schema.Literals(["ON_INSTALL", "ON_USE"]); + +export type V2PluginListParams__AbsolutePathBuf = string; +export const V2PluginListParams__AbsolutePathBuf = Schema.String.annotate({ + description: + "A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\n\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.", +}); + +export type V2PluginListResponse__AbsolutePathBuf = string; +export const V2PluginListResponse__AbsolutePathBuf = Schema.String.annotate({ + description: + "A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\n\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.", +}); + +export type V2PluginListResponse__MarketplaceInterface = { readonly displayName?: string | null }; +export const V2PluginListResponse__MarketplaceInterface = Schema.Struct({ + displayName: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), +}); + +export type V2PluginListResponse__PluginAuthPolicy = "ON_INSTALL" | "ON_USE"; +export const V2PluginListResponse__PluginAuthPolicy = Schema.Literals(["ON_INSTALL", "ON_USE"]); + +export type V2PluginListResponse__PluginInstallPolicy = + | "NOT_AVAILABLE" + | "AVAILABLE" + | "INSTALLED_BY_DEFAULT"; +export const V2PluginListResponse__PluginInstallPolicy = Schema.Literals([ + "NOT_AVAILABLE", + "AVAILABLE", + "INSTALLED_BY_DEFAULT", +]); + +export type V2PluginReadParams__AbsolutePathBuf = string; +export const V2PluginReadParams__AbsolutePathBuf = Schema.String.annotate({ + description: + "A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\n\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.", +}); + +export type V2PluginReadResponse__AbsolutePathBuf = string; +export const V2PluginReadResponse__AbsolutePathBuf = Schema.String.annotate({ + description: + "A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\n\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.", +}); + +export type V2PluginReadResponse__AppSummary = { + readonly description?: string | null; + readonly id: string; + readonly installUrl?: string | null; + readonly name: string; + readonly needsAuth: boolean; +}; +export const V2PluginReadResponse__AppSummary = Schema.Struct({ + description: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + id: Schema.String, + installUrl: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + name: Schema.String, + needsAuth: Schema.Boolean, +}).annotate({ description: "EXPERIMENTAL - app metadata summary for plugin responses." }); + +export type V2PluginReadResponse__PluginAuthPolicy = "ON_INSTALL" | "ON_USE"; +export const V2PluginReadResponse__PluginAuthPolicy = Schema.Literals(["ON_INSTALL", "ON_USE"]); + +export type V2PluginReadResponse__PluginInstallPolicy = + | "NOT_AVAILABLE" + | "AVAILABLE" + | "INSTALLED_BY_DEFAULT"; +export const V2PluginReadResponse__PluginInstallPolicy = Schema.Literals([ + "NOT_AVAILABLE", + "AVAILABLE", + "INSTALLED_BY_DEFAULT", +]); + +export type V2PluginReadResponse__SkillInterface = { + readonly brandColor?: string | null; + readonly defaultPrompt?: string | null; + readonly displayName?: string | null; + readonly iconLarge?: string | null; + readonly iconSmall?: string | null; + readonly shortDescription?: string | null; +}; +export const V2PluginReadResponse__SkillInterface = Schema.Struct({ + brandColor: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + defaultPrompt: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + displayName: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + iconLarge: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + iconSmall: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + shortDescription: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), +}); + +export type V2RawResponseItemCompletedNotification__ContentItem = + | { readonly text: string; readonly type: "input_text" } + | { readonly image_url: string; readonly type: "input_image" } + | { readonly text: string; readonly type: "output_text" }; +export const V2RawResponseItemCompletedNotification__ContentItem = Schema.Union( + [ + Schema.Struct({ + text: Schema.String, + type: Schema.Literal("input_text").annotate({ title: "InputTextContentItemType" }), + }).annotate({ title: "InputTextContentItem" }), + Schema.Struct({ + image_url: Schema.String, + type: Schema.Literal("input_image").annotate({ title: "InputImageContentItemType" }), + }).annotate({ title: "InputImageContentItem" }), + Schema.Struct({ + text: Schema.String, + type: Schema.Literal("output_text").annotate({ title: "OutputTextContentItemType" }), + }).annotate({ title: "OutputTextContentItem" }), + ], + { mode: "oneOf" }, +); + +export type V2RawResponseItemCompletedNotification__GhostCommit = { + readonly id: string; + readonly parent?: string | null; + readonly preexisting_untracked_dirs: ReadonlyArray; + readonly preexisting_untracked_files: ReadonlyArray; +}; +export const V2RawResponseItemCompletedNotification__GhostCommit = Schema.Struct({ + id: Schema.String, + parent: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + preexisting_untracked_dirs: Schema.Array(Schema.String), + preexisting_untracked_files: Schema.Array(Schema.String), +}).annotate({ description: "Details of a ghost commit created from a repository state." }); + +export type V2RawResponseItemCompletedNotification__ImageDetail = + | "auto" + | "low" + | "high" + | "original"; +export const V2RawResponseItemCompletedNotification__ImageDetail = Schema.Literals([ + "auto", + "low", + "high", + "original", +]); + +export type V2RawResponseItemCompletedNotification__LocalShellAction = { + readonly command: ReadonlyArray; + readonly env?: { readonly [x: string]: string } | null; + readonly timeout_ms?: number | null; + readonly type: "exec"; + readonly user?: string | null; + readonly working_directory?: string | null; +}; +export const V2RawResponseItemCompletedNotification__LocalShellAction = Schema.Union( + [ + Schema.Struct({ + command: Schema.Array(Schema.String), + env: Schema.optionalKey( + Schema.Union([Schema.Record(Schema.String, Schema.String), Schema.Null]), + ), + timeout_ms: Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ format: "uint64" }) + .check(Schema.isInt()) + .check(Schema.isGreaterThanOrEqualTo(0)), + Schema.Null, + ]), + ), + type: Schema.Literal("exec").annotate({ title: "ExecLocalShellActionType" }), + user: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + working_directory: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + }).annotate({ title: "ExecLocalShellAction" }), + ], + { mode: "oneOf" }, +); + +export type V2RawResponseItemCompletedNotification__LocalShellStatus = + | "completed" + | "in_progress" + | "incomplete"; +export const V2RawResponseItemCompletedNotification__LocalShellStatus = Schema.Literals([ + "completed", + "in_progress", + "incomplete", +]); + +export type V2RawResponseItemCompletedNotification__MessagePhase = "commentary" | "final_answer"; +export const V2RawResponseItemCompletedNotification__MessagePhase = Schema.Literals([ + "commentary", + "final_answer", +]).annotate({ + description: + 'Classifies an assistant message as interim commentary or final answer text.\n\nProviders do not emit this consistently, so callers must treat `None` as "phase unknown" and keep compatibility behavior for legacy models.', +}); + +export type V2RawResponseItemCompletedNotification__ReasoningItemContent = + | { readonly text: string; readonly type: "reasoning_text" } + | { readonly text: string; readonly type: "text" }; +export const V2RawResponseItemCompletedNotification__ReasoningItemContent = Schema.Union( + [ + Schema.Struct({ + text: Schema.String, + type: Schema.Literal("reasoning_text").annotate({ + title: "ReasoningTextReasoningItemContentType", + }), + }).annotate({ title: "ReasoningTextReasoningItemContent" }), + Schema.Struct({ + text: Schema.String, + type: Schema.Literal("text").annotate({ title: "TextReasoningItemContentType" }), + }).annotate({ title: "TextReasoningItemContent" }), + ], + { mode: "oneOf" }, +); + +export type V2RawResponseItemCompletedNotification__ReasoningItemReasoningSummary = { + readonly text: string; + readonly type: "summary_text"; +}; +export const V2RawResponseItemCompletedNotification__ReasoningItemReasoningSummary = Schema.Union( + [ + Schema.Struct({ + text: Schema.String, + type: Schema.Literal("summary_text").annotate({ + title: "SummaryTextReasoningItemReasoningSummaryType", + }), + }).annotate({ title: "SummaryTextReasoningItemReasoningSummary" }), + ], + { mode: "oneOf" }, +); + +export type V2RawResponseItemCompletedNotification__ResponsesApiWebSearchAction = + | { + readonly queries?: ReadonlyArray | null; + readonly query?: string | null; + readonly type: "search"; + } + | { readonly type: "open_page"; readonly url?: string | null } + | { + readonly pattern?: string | null; + readonly type: "find_in_page"; + readonly url?: string | null; + } + | { readonly type: "other" }; +export const V2RawResponseItemCompletedNotification__ResponsesApiWebSearchAction = Schema.Union( + [ + Schema.Struct({ + queries: Schema.optionalKey(Schema.Union([Schema.Array(Schema.String), Schema.Null])), + query: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + type: Schema.Literal("search").annotate({ title: "SearchResponsesApiWebSearchActionType" }), + }).annotate({ title: "SearchResponsesApiWebSearchAction" }), + Schema.Struct({ + type: Schema.Literal("open_page").annotate({ + title: "OpenPageResponsesApiWebSearchActionType", + }), + url: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + }).annotate({ title: "OpenPageResponsesApiWebSearchAction" }), + Schema.Struct({ + pattern: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + type: Schema.Literal("find_in_page").annotate({ + title: "FindInPageResponsesApiWebSearchActionType", + }), + url: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + }).annotate({ title: "FindInPageResponsesApiWebSearchAction" }), + Schema.Struct({ + type: Schema.Literal("other").annotate({ title: "OtherResponsesApiWebSearchActionType" }), + }).annotate({ title: "OtherResponsesApiWebSearchAction" }), + ], + { mode: "oneOf" }, +); + +export type V2ReviewStartParams__ReviewDelivery = "inline" | "detached"; +export const V2ReviewStartParams__ReviewDelivery = Schema.Literals(["inline", "detached"]); + +export type V2ReviewStartParams__ReviewTarget = + | { readonly type: "uncommittedChanges" } + | { readonly branch: string; readonly type: "baseBranch" } + | { readonly sha: string; readonly title?: string | null; readonly type: "commit" } + | { readonly instructions: string; readonly type: "custom" }; +export const V2ReviewStartParams__ReviewTarget = Schema.Union( + [ + Schema.Struct({ + type: Schema.Literal("uncommittedChanges").annotate({ + title: "UncommittedChangesReviewTargetType", + }), + }).annotate({ + title: "UncommittedChangesReviewTarget", + description: "Review the working tree: staged, unstaged, and untracked files.", + }), + Schema.Struct({ + branch: Schema.String, + type: Schema.Literal("baseBranch").annotate({ title: "BaseBranchReviewTargetType" }), + }).annotate({ + title: "BaseBranchReviewTarget", + description: "Review changes between the current branch and the given base branch.", + }), + Schema.Struct({ + sha: Schema.String, + title: Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + description: "Optional human-readable label (e.g., commit subject) for UIs.", + }), + Schema.Null, + ]), + ), + type: Schema.Literal("commit").annotate({ title: "CommitReviewTargetType" }), + }).annotate({ + title: "CommitReviewTarget", + description: "Review the changes introduced by a specific commit.", + }), + Schema.Struct({ + instructions: Schema.String, + type: Schema.Literal("custom").annotate({ title: "CustomReviewTargetType" }), + }).annotate({ + title: "CustomReviewTarget", + description: "Arbitrary instructions, equivalent to the old free-form prompt.", + }), + ], + { mode: "oneOf" }, +); + +export type V2ReviewStartResponse__CollabAgentStatus = + | "pendingInit" + | "running" + | "interrupted" + | "completed" + | "errored" + | "shutdown" + | "notFound"; +export const V2ReviewStartResponse__CollabAgentStatus = Schema.Literals([ + "pendingInit", + "running", + "interrupted", + "completed", + "errored", + "shutdown", + "notFound", +]); + +export type V2ReviewStartResponse__CommandAction = + | { + readonly command: string; + readonly name: string; + readonly path: string; + readonly type: "read"; + } + | { readonly command: string; readonly path?: string | null; readonly type: "listFiles" } + | { + readonly command: string; + readonly path?: string | null; + readonly query?: string | null; + readonly type: "search"; + } + | { readonly command: string; readonly type: "unknown" }; +export const V2ReviewStartResponse__CommandAction = Schema.Union( + [ + Schema.Struct({ + command: Schema.String, + name: Schema.String, + path: Schema.String, + type: Schema.Literal("read").annotate({ title: "ReadCommandActionType" }), + }).annotate({ title: "ReadCommandAction" }), + Schema.Struct({ + command: Schema.String, + path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + type: Schema.Literal("listFiles").annotate({ title: "ListFilesCommandActionType" }), + }).annotate({ title: "ListFilesCommandAction" }), + Schema.Struct({ + command: Schema.String, + path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + query: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + type: Schema.Literal("search").annotate({ title: "SearchCommandActionType" }), + }).annotate({ title: "SearchCommandAction" }), + Schema.Struct({ + command: Schema.String, + type: Schema.Literal("unknown").annotate({ title: "UnknownCommandActionType" }), + }).annotate({ title: "UnknownCommandAction" }), + ], + { mode: "oneOf" }, +); + +export type V2ReviewStartResponse__CommandExecutionStatus = + | "inProgress" + | "completed" + | "failed" + | "declined"; +export const V2ReviewStartResponse__CommandExecutionStatus = Schema.Literals([ + "inProgress", + "completed", + "failed", + "declined", +]); + +export type V2ReviewStartResponse__DynamicToolCallOutputContentItem = + | { readonly text: string; readonly type: "inputText" } + | { readonly imageUrl: string; readonly type: "inputImage" }; +export const V2ReviewStartResponse__DynamicToolCallOutputContentItem = Schema.Union( + [ + Schema.Struct({ + text: Schema.String, + type: Schema.Literal("inputText").annotate({ + title: "InputTextDynamicToolCallOutputContentItemType", + }), + }).annotate({ title: "InputTextDynamicToolCallOutputContentItem" }), + Schema.Struct({ + imageUrl: Schema.String, + type: Schema.Literal("inputImage").annotate({ + title: "InputImageDynamicToolCallOutputContentItemType", + }), + }).annotate({ title: "InputImageDynamicToolCallOutputContentItem" }), + ], + { mode: "oneOf" }, +); + +export type V2ReviewStartResponse__DynamicToolCallStatus = "inProgress" | "completed" | "failed"; +export const V2ReviewStartResponse__DynamicToolCallStatus = Schema.Literals([ + "inProgress", + "completed", + "failed", +]); + +export type V2ReviewStartResponse__HookPromptFragment = { + readonly hookRunId: string; + readonly text: string; +}; +export const V2ReviewStartResponse__HookPromptFragment = Schema.Struct({ + hookRunId: Schema.String, + text: Schema.String, +}); + +export type V2ReviewStartResponse__McpToolCallError = { readonly message: string }; +export const V2ReviewStartResponse__McpToolCallError = Schema.Struct({ message: Schema.String }); + +export type V2ReviewStartResponse__McpToolCallResult = { + readonly _meta?: unknown; + readonly content: ReadonlyArray; + readonly structuredContent?: unknown; +}; +export const V2ReviewStartResponse__McpToolCallResult = Schema.Struct({ + _meta: Schema.optionalKey(Schema.Unknown), + content: Schema.Array(Schema.Unknown), + structuredContent: Schema.optionalKey(Schema.Unknown), +}); + +export type V2ReviewStartResponse__McpToolCallStatus = "inProgress" | "completed" | "failed"; +export const V2ReviewStartResponse__McpToolCallStatus = Schema.Literals([ + "inProgress", + "completed", + "failed", +]); + +export type V2ReviewStartResponse__MemoryCitationEntry = { + readonly lineEnd: number; + readonly lineStart: number; + readonly note: string; + readonly path: string; +}; +export const V2ReviewStartResponse__MemoryCitationEntry = Schema.Struct({ + lineEnd: Schema.Number.annotate({ format: "uint32" }) + .check(Schema.isInt()) + .check(Schema.isGreaterThanOrEqualTo(0)), + lineStart: Schema.Number.annotate({ format: "uint32" }) + .check(Schema.isInt()) + .check(Schema.isGreaterThanOrEqualTo(0)), + note: Schema.String, + path: Schema.String, +}); + +export type V2ReviewStartResponse__MessagePhase = "commentary" | "final_answer"; +export const V2ReviewStartResponse__MessagePhase = Schema.Literals([ + "commentary", + "final_answer", +]).annotate({ + description: + 'Classifies an assistant message as interim commentary or final answer text.\n\nProviders do not emit this consistently, so callers must treat `None` as "phase unknown" and keep compatibility behavior for legacy models.', +}); + +export type V2ReviewStartResponse__NonSteerableTurnKind = "review" | "compact"; +export const V2ReviewStartResponse__NonSteerableTurnKind = Schema.Literals(["review", "compact"]); + +export type V2ReviewStartResponse__PatchApplyStatus = + | "inProgress" + | "completed" + | "failed" + | "declined"; +export const V2ReviewStartResponse__PatchApplyStatus = Schema.Literals([ + "inProgress", + "completed", + "failed", + "declined", +]); + +export type V2ReviewStartResponse__PatchChangeKind = + | { readonly type: "add" } + | { readonly type: "delete" } + | { readonly move_path?: string | null; readonly type: "update" }; +export const V2ReviewStartResponse__PatchChangeKind = Schema.Union( + [ + Schema.Struct({ + type: Schema.Literal("add").annotate({ title: "AddPatchChangeKindType" }), + }).annotate({ title: "AddPatchChangeKind" }), + Schema.Struct({ + type: Schema.Literal("delete").annotate({ title: "DeletePatchChangeKindType" }), + }).annotate({ title: "DeletePatchChangeKind" }), + Schema.Struct({ + move_path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + type: Schema.Literal("update").annotate({ title: "UpdatePatchChangeKindType" }), + }).annotate({ title: "UpdatePatchChangeKind" }), + ], + { mode: "oneOf" }, +); + +export type V2ReviewStartResponse__ReasoningEffort = + | "none" + | "minimal" + | "low" + | "medium" + | "high" + | "xhigh"; +export const V2ReviewStartResponse__ReasoningEffort = Schema.Literals([ + "none", + "minimal", + "low", + "medium", + "high", + "xhigh", +]).annotate({ + description: + "See https://platform.openai.com/docs/guides/reasoning?api-mode=responses#get-started-with-reasoning", +}); + +export type V2ReviewStartResponse__TextElement = { + readonly byteRange: { readonly end: number; readonly start: number }; + readonly placeholder?: string | null; +}; +export const V2ReviewStartResponse__TextElement = Schema.Struct({ + byteRange: Schema.Struct({ + end: Schema.Number.annotate({ format: "uint" }) + .check(Schema.isInt()) + .check(Schema.isGreaterThanOrEqualTo(0)), + start: Schema.Number.annotate({ format: "uint" }) + .check(Schema.isInt()) + .check(Schema.isGreaterThanOrEqualTo(0)), + }).annotate({ + description: "Byte range in the parent `text` buffer that this element occupies.", + }), + placeholder: Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + description: "Optional human-readable placeholder for the element, displayed in the UI.", + }), + Schema.Null, + ]), + ), +}); + +export type V2ReviewStartResponse__TurnStatus = + | "completed" + | "interrupted" + | "failed" + | "inProgress"; +export const V2ReviewStartResponse__TurnStatus = Schema.Literals([ + "completed", + "interrupted", + "failed", + "inProgress", +]); + +export type V2ReviewStartResponse__WebSearchAction = + | { + readonly queries?: ReadonlyArray | null; + readonly query?: string | null; + readonly type: "search"; + } + | { readonly type: "openPage"; readonly url?: string | null } + | { readonly pattern?: string | null; readonly type: "findInPage"; readonly url?: string | null } + | { readonly type: "other" }; +export const V2ReviewStartResponse__WebSearchAction = Schema.Union( + [ + Schema.Struct({ + queries: Schema.optionalKey(Schema.Union([Schema.Array(Schema.String), Schema.Null])), + query: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + type: Schema.Literal("search").annotate({ title: "SearchWebSearchActionType" }), + }).annotate({ title: "SearchWebSearchAction" }), + Schema.Struct({ + type: Schema.Literal("openPage").annotate({ title: "OpenPageWebSearchActionType" }), + url: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + }).annotate({ title: "OpenPageWebSearchAction" }), + Schema.Struct({ + pattern: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + type: Schema.Literal("findInPage").annotate({ title: "FindInPageWebSearchActionType" }), + url: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + }).annotate({ title: "FindInPageWebSearchAction" }), + Schema.Struct({ + type: Schema.Literal("other").annotate({ title: "OtherWebSearchActionType" }), + }).annotate({ title: "OtherWebSearchAction" }), + ], + { mode: "oneOf" }, +); + +export type V2ServerRequestResolvedNotification__RequestId = string | number; +export const V2ServerRequestResolvedNotification__RequestId = Schema.Union([ + Schema.String, + Schema.Number.annotate({ format: "int64" }).check(Schema.isInt()), +]); + +export type V2SkillsConfigWriteParams__AbsolutePathBuf = string; +export const V2SkillsConfigWriteParams__AbsolutePathBuf = Schema.String.annotate({ + description: + "A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\n\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.", +}); + +export type V2SkillsListParams__SkillsListExtraRootsForCwd = { + readonly cwd: string; + readonly extraUserRoots: ReadonlyArray; +}; +export const V2SkillsListParams__SkillsListExtraRootsForCwd = Schema.Struct({ + cwd: Schema.String, + extraUserRoots: Schema.Array(Schema.String), +}); + +export type V2SkillsListResponse__SkillErrorInfo = { + readonly message: string; + readonly path: string; +}; +export const V2SkillsListResponse__SkillErrorInfo = Schema.Struct({ + message: Schema.String, + path: Schema.String, +}); + +export type V2SkillsListResponse__SkillInterface = { + readonly brandColor?: string | null; + readonly defaultPrompt?: string | null; + readonly displayName?: string | null; + readonly iconLarge?: string | null; + readonly iconSmall?: string | null; + readonly shortDescription?: string | null; +}; +export const V2SkillsListResponse__SkillInterface = Schema.Struct({ + brandColor: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + defaultPrompt: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + displayName: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + iconLarge: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + iconSmall: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + shortDescription: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), +}); + +export type V2SkillsListResponse__SkillScope = "user" | "repo" | "system" | "admin"; +export const V2SkillsListResponse__SkillScope = Schema.Literals([ + "user", + "repo", + "system", + "admin", +]); + +export type V2SkillsListResponse__SkillToolDependency = { + readonly command?: string | null; + readonly description?: string | null; + readonly transport?: string | null; + readonly type: string; + readonly url?: string | null; + readonly value: string; +}; +export const V2SkillsListResponse__SkillToolDependency = Schema.Struct({ + command: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + description: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + transport: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + type: Schema.String, + url: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + value: Schema.String, +}); + +export type V2ThreadForkParams__ApprovalsReviewer = "user" | "guardian_subagent"; +export const V2ThreadForkParams__ApprovalsReviewer = Schema.Literals([ + "user", + "guardian_subagent", +]).annotate({ + description: + "Configures who approval requests are routed to for review. Examples include sandbox escapes, blocked network access, MCP approval prompts, and ARC escalations. Defaults to `user`. `guardian_subagent` uses a carefully prompted subagent to gather relevant context and apply a risk-based decision framework before approving or denying the request.", +}); + +export type V2ThreadForkParams__AskForApproval = + | "untrusted" + | "on-failure" + | "on-request" + | "never" + | { + readonly granular: { + readonly mcp_elicitations: boolean; + readonly request_permissions?: boolean; + readonly rules: boolean; + readonly sandbox_approval: boolean; + readonly skill_approval?: boolean; + }; + }; +export const V2ThreadForkParams__AskForApproval = Schema.Union( + [ + Schema.Literals(["untrusted", "on-failure", "on-request", "never"]), + Schema.Struct({ + granular: Schema.Struct({ + mcp_elicitations: Schema.Boolean, + request_permissions: Schema.optionalKey(Schema.Boolean.annotate({ default: false })), + rules: Schema.Boolean, + sandbox_approval: Schema.Boolean, + skill_approval: Schema.optionalKey(Schema.Boolean.annotate({ default: false })), + }), + }).annotate({ title: "GranularAskForApproval" }), + ], + { mode: "oneOf" }, +); + +export type V2ThreadForkParams__SandboxMode = + | "read-only" + | "workspace-write" + | "danger-full-access"; +export const V2ThreadForkParams__SandboxMode = Schema.Literals([ + "read-only", + "workspace-write", + "danger-full-access", +]); + +export type V2ThreadForkParams__ServiceTier = "fast" | "flex"; +export const V2ThreadForkParams__ServiceTier = Schema.Literals(["fast", "flex"]); + +export type V2ThreadForkResponse__AbsolutePathBuf = string; +export const V2ThreadForkResponse__AbsolutePathBuf = Schema.String.annotate({ + description: + "A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\n\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.", +}); + +export type V2ThreadForkResponse__AgentPath = string; +export const V2ThreadForkResponse__AgentPath = Schema.String; + +export type V2ThreadForkResponse__AskForApproval = + | "untrusted" + | "on-failure" + | "on-request" + | "never" + | { + readonly granular: { + readonly mcp_elicitations: boolean; + readonly request_permissions?: boolean; + readonly rules: boolean; + readonly sandbox_approval: boolean; + readonly skill_approval?: boolean; + }; + }; +export const V2ThreadForkResponse__AskForApproval = Schema.Union( + [ + Schema.Literals(["untrusted", "on-failure", "on-request", "never"]), + Schema.Struct({ + granular: Schema.Struct({ + mcp_elicitations: Schema.Boolean, + request_permissions: Schema.optionalKey(Schema.Boolean.annotate({ default: false })), + rules: Schema.Boolean, + sandbox_approval: Schema.Boolean, + skill_approval: Schema.optionalKey(Schema.Boolean.annotate({ default: false })), + }), + }).annotate({ title: "GranularAskForApproval" }), + ], + { mode: "oneOf" }, +); + +export type V2ThreadForkResponse__CollabAgentStatus = + | "pendingInit" + | "running" + | "interrupted" + | "completed" + | "errored" + | "shutdown" + | "notFound"; +export const V2ThreadForkResponse__CollabAgentStatus = Schema.Literals([ + "pendingInit", + "running", + "interrupted", + "completed", + "errored", + "shutdown", + "notFound", +]); + +export type V2ThreadForkResponse__CommandAction = + | { + readonly command: string; + readonly name: string; + readonly path: string; + readonly type: "read"; + } + | { readonly command: string; readonly path?: string | null; readonly type: "listFiles" } + | { + readonly command: string; + readonly path?: string | null; + readonly query?: string | null; + readonly type: "search"; + } + | { readonly command: string; readonly type: "unknown" }; +export const V2ThreadForkResponse__CommandAction = Schema.Union( + [ + Schema.Struct({ + command: Schema.String, + name: Schema.String, + path: Schema.String, + type: Schema.Literal("read").annotate({ title: "ReadCommandActionType" }), + }).annotate({ title: "ReadCommandAction" }), + Schema.Struct({ + command: Schema.String, + path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + type: Schema.Literal("listFiles").annotate({ title: "ListFilesCommandActionType" }), + }).annotate({ title: "ListFilesCommandAction" }), + Schema.Struct({ + command: Schema.String, + path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + query: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + type: Schema.Literal("search").annotate({ title: "SearchCommandActionType" }), + }).annotate({ title: "SearchCommandAction" }), + Schema.Struct({ + command: Schema.String, + type: Schema.Literal("unknown").annotate({ title: "UnknownCommandActionType" }), + }).annotate({ title: "UnknownCommandAction" }), + ], + { mode: "oneOf" }, +); + +export type V2ThreadForkResponse__CommandExecutionStatus = + | "inProgress" + | "completed" + | "failed" + | "declined"; +export const V2ThreadForkResponse__CommandExecutionStatus = Schema.Literals([ + "inProgress", + "completed", + "failed", + "declined", +]); + +export type V2ThreadForkResponse__DynamicToolCallOutputContentItem = + | { readonly text: string; readonly type: "inputText" } + | { readonly imageUrl: string; readonly type: "inputImage" }; +export const V2ThreadForkResponse__DynamicToolCallOutputContentItem = Schema.Union( + [ + Schema.Struct({ + text: Schema.String, + type: Schema.Literal("inputText").annotate({ + title: "InputTextDynamicToolCallOutputContentItemType", + }), + }).annotate({ title: "InputTextDynamicToolCallOutputContentItem" }), + Schema.Struct({ + imageUrl: Schema.String, + type: Schema.Literal("inputImage").annotate({ + title: "InputImageDynamicToolCallOutputContentItemType", + }), + }).annotate({ title: "InputImageDynamicToolCallOutputContentItem" }), + ], + { mode: "oneOf" }, +); + +export type V2ThreadForkResponse__DynamicToolCallStatus = "inProgress" | "completed" | "failed"; +export const V2ThreadForkResponse__DynamicToolCallStatus = Schema.Literals([ + "inProgress", + "completed", + "failed", +]); + +export type V2ThreadForkResponse__GitInfo = { + readonly branch?: string | null; + readonly originUrl?: string | null; + readonly sha?: string | null; +}; +export const V2ThreadForkResponse__GitInfo = Schema.Struct({ + branch: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + originUrl: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + sha: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), +}); + +export type V2ThreadForkResponse__HookPromptFragment = { + readonly hookRunId: string; + readonly text: string; +}; +export const V2ThreadForkResponse__HookPromptFragment = Schema.Struct({ + hookRunId: Schema.String, + text: Schema.String, +}); + +export type V2ThreadForkResponse__McpToolCallError = { readonly message: string }; +export const V2ThreadForkResponse__McpToolCallError = Schema.Struct({ message: Schema.String }); + +export type V2ThreadForkResponse__McpToolCallResult = { + readonly _meta?: unknown; + readonly content: ReadonlyArray; + readonly structuredContent?: unknown; +}; +export const V2ThreadForkResponse__McpToolCallResult = Schema.Struct({ + _meta: Schema.optionalKey(Schema.Unknown), + content: Schema.Array(Schema.Unknown), + structuredContent: Schema.optionalKey(Schema.Unknown), +}); + +export type V2ThreadForkResponse__McpToolCallStatus = "inProgress" | "completed" | "failed"; +export const V2ThreadForkResponse__McpToolCallStatus = Schema.Literals([ + "inProgress", + "completed", + "failed", +]); + +export type V2ThreadForkResponse__MemoryCitationEntry = { + readonly lineEnd: number; + readonly lineStart: number; + readonly note: string; + readonly path: string; +}; +export const V2ThreadForkResponse__MemoryCitationEntry = Schema.Struct({ + lineEnd: Schema.Number.annotate({ format: "uint32" }) + .check(Schema.isInt()) + .check(Schema.isGreaterThanOrEqualTo(0)), + lineStart: Schema.Number.annotate({ format: "uint32" }) + .check(Schema.isInt()) + .check(Schema.isGreaterThanOrEqualTo(0)), + note: Schema.String, + path: Schema.String, +}); + +export type V2ThreadForkResponse__MessagePhase = "commentary" | "final_answer"; +export const V2ThreadForkResponse__MessagePhase = Schema.Literals([ + "commentary", + "final_answer", +]).annotate({ + description: + 'Classifies an assistant message as interim commentary or final answer text.\n\nProviders do not emit this consistently, so callers must treat `None` as "phase unknown" and keep compatibility behavior for legacy models.', +}); + +export type V2ThreadForkResponse__NonSteerableTurnKind = "review" | "compact"; +export const V2ThreadForkResponse__NonSteerableTurnKind = Schema.Literals(["review", "compact"]); + +export type V2ThreadForkResponse__PatchApplyStatus = + | "inProgress" + | "completed" + | "failed" + | "declined"; +export const V2ThreadForkResponse__PatchApplyStatus = Schema.Literals([ + "inProgress", + "completed", + "failed", + "declined", +]); + +export type V2ThreadForkResponse__PatchChangeKind = + | { readonly type: "add" } + | { readonly type: "delete" } + | { readonly move_path?: string | null; readonly type: "update" }; +export const V2ThreadForkResponse__PatchChangeKind = Schema.Union( + [ + Schema.Struct({ + type: Schema.Literal("add").annotate({ title: "AddPatchChangeKindType" }), + }).annotate({ title: "AddPatchChangeKind" }), + Schema.Struct({ + type: Schema.Literal("delete").annotate({ title: "DeletePatchChangeKindType" }), + }).annotate({ title: "DeletePatchChangeKind" }), + Schema.Struct({ + move_path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + type: Schema.Literal("update").annotate({ title: "UpdatePatchChangeKindType" }), + }).annotate({ title: "UpdatePatchChangeKind" }), + ], + { mode: "oneOf" }, +); + +export type V2ThreadForkResponse__ReasoningEffort = + | "none" + | "minimal" + | "low" + | "medium" + | "high" + | "xhigh"; +export const V2ThreadForkResponse__ReasoningEffort = Schema.Literals([ + "none", + "minimal", + "low", + "medium", + "high", + "xhigh", +]).annotate({ + description: + "See https://platform.openai.com/docs/guides/reasoning?api-mode=responses#get-started-with-reasoning", +}); + +export type V2ThreadForkResponse__ServiceTier = "fast" | "flex"; +export const V2ThreadForkResponse__ServiceTier = Schema.Literals(["fast", "flex"]); + +export type V2ThreadForkResponse__TextElement = { + readonly byteRange: { readonly end: number; readonly start: number }; + readonly placeholder?: string | null; +}; +export const V2ThreadForkResponse__TextElement = Schema.Struct({ + byteRange: Schema.Struct({ + end: Schema.Number.annotate({ format: "uint" }) + .check(Schema.isInt()) + .check(Schema.isGreaterThanOrEqualTo(0)), + start: Schema.Number.annotate({ format: "uint" }) + .check(Schema.isInt()) + .check(Schema.isGreaterThanOrEqualTo(0)), + }).annotate({ + description: "Byte range in the parent `text` buffer that this element occupies.", + }), + placeholder: Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + description: "Optional human-readable placeholder for the element, displayed in the UI.", + }), + Schema.Null, + ]), + ), +}); + +export type V2ThreadForkResponse__ThreadActiveFlag = "waitingOnApproval" | "waitingOnUserInput"; +export const V2ThreadForkResponse__ThreadActiveFlag = Schema.Literals([ + "waitingOnApproval", + "waitingOnUserInput", +]); + +export type V2ThreadForkResponse__ThreadId = string; +export const V2ThreadForkResponse__ThreadId = Schema.String; + +export type V2ThreadForkResponse__TurnStatus = + | "completed" + | "interrupted" + | "failed" + | "inProgress"; +export const V2ThreadForkResponse__TurnStatus = Schema.Literals([ + "completed", + "interrupted", + "failed", + "inProgress", +]); + +export type V2ThreadForkResponse__WebSearchAction = + | { + readonly queries?: ReadonlyArray | null; + readonly query?: string | null; + readonly type: "search"; + } + | { readonly type: "openPage"; readonly url?: string | null } + | { readonly pattern?: string | null; readonly type: "findInPage"; readonly url?: string | null } + | { readonly type: "other" }; +export const V2ThreadForkResponse__WebSearchAction = Schema.Union( + [ + Schema.Struct({ + queries: Schema.optionalKey(Schema.Union([Schema.Array(Schema.String), Schema.Null])), + query: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + type: Schema.Literal("search").annotate({ title: "SearchWebSearchActionType" }), + }).annotate({ title: "SearchWebSearchAction" }), + Schema.Struct({ + type: Schema.Literal("openPage").annotate({ title: "OpenPageWebSearchActionType" }), + url: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + }).annotate({ title: "OpenPageWebSearchAction" }), + Schema.Struct({ + pattern: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + type: Schema.Literal("findInPage").annotate({ title: "FindInPageWebSearchActionType" }), + url: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + }).annotate({ title: "FindInPageWebSearchAction" }), + Schema.Struct({ + type: Schema.Literal("other").annotate({ title: "OtherWebSearchActionType" }), + }).annotate({ title: "OtherWebSearchAction" }), + ], + { mode: "oneOf" }, +); + +export type V2ThreadListParams__ThreadSortKey = "created_at" | "updated_at"; +export const V2ThreadListParams__ThreadSortKey = Schema.Literals(["created_at", "updated_at"]); + +export type V2ThreadListParams__ThreadSourceKind = + | "cli" + | "vscode" + | "exec" + | "appServer" + | "subAgent" + | "subAgentReview" + | "subAgentCompact" + | "subAgentThreadSpawn" + | "subAgentOther" + | "unknown"; +export const V2ThreadListParams__ThreadSourceKind = Schema.Literals([ + "cli", + "vscode", + "exec", + "appServer", + "subAgent", + "subAgentReview", + "subAgentCompact", + "subAgentThreadSpawn", + "subAgentOther", + "unknown", +]); + +export type V2ThreadListResponse__AgentPath = string; +export const V2ThreadListResponse__AgentPath = Schema.String; + +export type V2ThreadListResponse__CollabAgentStatus = + | "pendingInit" + | "running" + | "interrupted" + | "completed" + | "errored" + | "shutdown" + | "notFound"; +export const V2ThreadListResponse__CollabAgentStatus = Schema.Literals([ + "pendingInit", + "running", + "interrupted", + "completed", + "errored", + "shutdown", + "notFound", +]); + +export type V2ThreadListResponse__CommandAction = + | { + readonly command: string; + readonly name: string; + readonly path: string; + readonly type: "read"; + } + | { readonly command: string; readonly path?: string | null; readonly type: "listFiles" } + | { + readonly command: string; + readonly path?: string | null; + readonly query?: string | null; + readonly type: "search"; + } + | { readonly command: string; readonly type: "unknown" }; +export const V2ThreadListResponse__CommandAction = Schema.Union( + [ + Schema.Struct({ + command: Schema.String, + name: Schema.String, + path: Schema.String, + type: Schema.Literal("read").annotate({ title: "ReadCommandActionType" }), + }).annotate({ title: "ReadCommandAction" }), + Schema.Struct({ + command: Schema.String, + path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + type: Schema.Literal("listFiles").annotate({ title: "ListFilesCommandActionType" }), + }).annotate({ title: "ListFilesCommandAction" }), + Schema.Struct({ + command: Schema.String, + path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + query: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + type: Schema.Literal("search").annotate({ title: "SearchCommandActionType" }), + }).annotate({ title: "SearchCommandAction" }), + Schema.Struct({ + command: Schema.String, + type: Schema.Literal("unknown").annotate({ title: "UnknownCommandActionType" }), + }).annotate({ title: "UnknownCommandAction" }), + ], + { mode: "oneOf" }, +); + +export type V2ThreadListResponse__CommandExecutionStatus = + | "inProgress" + | "completed" + | "failed" + | "declined"; +export const V2ThreadListResponse__CommandExecutionStatus = Schema.Literals([ + "inProgress", + "completed", + "failed", + "declined", +]); + +export type V2ThreadListResponse__DynamicToolCallOutputContentItem = + | { readonly text: string; readonly type: "inputText" } + | { readonly imageUrl: string; readonly type: "inputImage" }; +export const V2ThreadListResponse__DynamicToolCallOutputContentItem = Schema.Union( + [ + Schema.Struct({ + text: Schema.String, + type: Schema.Literal("inputText").annotate({ + title: "InputTextDynamicToolCallOutputContentItemType", + }), + }).annotate({ title: "InputTextDynamicToolCallOutputContentItem" }), + Schema.Struct({ + imageUrl: Schema.String, + type: Schema.Literal("inputImage").annotate({ + title: "InputImageDynamicToolCallOutputContentItemType", + }), + }).annotate({ title: "InputImageDynamicToolCallOutputContentItem" }), + ], + { mode: "oneOf" }, +); + +export type V2ThreadListResponse__DynamicToolCallStatus = "inProgress" | "completed" | "failed"; +export const V2ThreadListResponse__DynamicToolCallStatus = Schema.Literals([ + "inProgress", + "completed", + "failed", +]); + +export type V2ThreadListResponse__GitInfo = { + readonly branch?: string | null; + readonly originUrl?: string | null; + readonly sha?: string | null; +}; +export const V2ThreadListResponse__GitInfo = Schema.Struct({ + branch: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + originUrl: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + sha: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), +}); + +export type V2ThreadListResponse__HookPromptFragment = { + readonly hookRunId: string; + readonly text: string; +}; +export const V2ThreadListResponse__HookPromptFragment = Schema.Struct({ + hookRunId: Schema.String, + text: Schema.String, +}); + +export type V2ThreadListResponse__McpToolCallError = { readonly message: string }; +export const V2ThreadListResponse__McpToolCallError = Schema.Struct({ message: Schema.String }); + +export type V2ThreadListResponse__McpToolCallResult = { + readonly _meta?: unknown; + readonly content: ReadonlyArray; + readonly structuredContent?: unknown; +}; +export const V2ThreadListResponse__McpToolCallResult = Schema.Struct({ + _meta: Schema.optionalKey(Schema.Unknown), + content: Schema.Array(Schema.Unknown), + structuredContent: Schema.optionalKey(Schema.Unknown), +}); + +export type V2ThreadListResponse__McpToolCallStatus = "inProgress" | "completed" | "failed"; +export const V2ThreadListResponse__McpToolCallStatus = Schema.Literals([ + "inProgress", + "completed", + "failed", +]); + +export type V2ThreadListResponse__MemoryCitationEntry = { + readonly lineEnd: number; + readonly lineStart: number; + readonly note: string; + readonly path: string; +}; +export const V2ThreadListResponse__MemoryCitationEntry = Schema.Struct({ + lineEnd: Schema.Number.annotate({ format: "uint32" }) + .check(Schema.isInt()) + .check(Schema.isGreaterThanOrEqualTo(0)), + lineStart: Schema.Number.annotate({ format: "uint32" }) + .check(Schema.isInt()) + .check(Schema.isGreaterThanOrEqualTo(0)), + note: Schema.String, + path: Schema.String, +}); + +export type V2ThreadListResponse__MessagePhase = "commentary" | "final_answer"; +export const V2ThreadListResponse__MessagePhase = Schema.Literals([ + "commentary", + "final_answer", +]).annotate({ + description: + 'Classifies an assistant message as interim commentary or final answer text.\n\nProviders do not emit this consistently, so callers must treat `None` as "phase unknown" and keep compatibility behavior for legacy models.', +}); + +export type V2ThreadListResponse__NonSteerableTurnKind = "review" | "compact"; +export const V2ThreadListResponse__NonSteerableTurnKind = Schema.Literals(["review", "compact"]); + +export type V2ThreadListResponse__PatchApplyStatus = + | "inProgress" + | "completed" + | "failed" + | "declined"; +export const V2ThreadListResponse__PatchApplyStatus = Schema.Literals([ + "inProgress", + "completed", + "failed", + "declined", +]); + +export type V2ThreadListResponse__PatchChangeKind = + | { readonly type: "add" } + | { readonly type: "delete" } + | { readonly move_path?: string | null; readonly type: "update" }; +export const V2ThreadListResponse__PatchChangeKind = Schema.Union( + [ + Schema.Struct({ + type: Schema.Literal("add").annotate({ title: "AddPatchChangeKindType" }), + }).annotate({ title: "AddPatchChangeKind" }), + Schema.Struct({ + type: Schema.Literal("delete").annotate({ title: "DeletePatchChangeKindType" }), + }).annotate({ title: "DeletePatchChangeKind" }), + Schema.Struct({ + move_path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + type: Schema.Literal("update").annotate({ title: "UpdatePatchChangeKindType" }), + }).annotate({ title: "UpdatePatchChangeKind" }), + ], + { mode: "oneOf" }, +); + +export type V2ThreadListResponse__ReasoningEffort = + | "none" + | "minimal" + | "low" + | "medium" + | "high" + | "xhigh"; +export const V2ThreadListResponse__ReasoningEffort = Schema.Literals([ + "none", + "minimal", + "low", + "medium", + "high", + "xhigh", +]).annotate({ + description: + "See https://platform.openai.com/docs/guides/reasoning?api-mode=responses#get-started-with-reasoning", +}); + +export type V2ThreadListResponse__TextElement = { + readonly byteRange: { readonly end: number; readonly start: number }; + readonly placeholder?: string | null; +}; +export const V2ThreadListResponse__TextElement = Schema.Struct({ + byteRange: Schema.Struct({ + end: Schema.Number.annotate({ format: "uint" }) + .check(Schema.isInt()) + .check(Schema.isGreaterThanOrEqualTo(0)), + start: Schema.Number.annotate({ format: "uint" }) + .check(Schema.isInt()) + .check(Schema.isGreaterThanOrEqualTo(0)), + }).annotate({ + description: "Byte range in the parent `text` buffer that this element occupies.", + }), + placeholder: Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + description: "Optional human-readable placeholder for the element, displayed in the UI.", + }), + Schema.Null, + ]), + ), +}); + +export type V2ThreadListResponse__ThreadActiveFlag = "waitingOnApproval" | "waitingOnUserInput"; +export const V2ThreadListResponse__ThreadActiveFlag = Schema.Literals([ + "waitingOnApproval", + "waitingOnUserInput", +]); + +export type V2ThreadListResponse__ThreadId = string; +export const V2ThreadListResponse__ThreadId = Schema.String; + +export type V2ThreadListResponse__TurnStatus = + | "completed" + | "interrupted" + | "failed" + | "inProgress"; +export const V2ThreadListResponse__TurnStatus = Schema.Literals([ + "completed", + "interrupted", + "failed", + "inProgress", +]); + +export type V2ThreadListResponse__WebSearchAction = + | { + readonly queries?: ReadonlyArray | null; + readonly query?: string | null; + readonly type: "search"; + } + | { readonly type: "openPage"; readonly url?: string | null } + | { readonly pattern?: string | null; readonly type: "findInPage"; readonly url?: string | null } + | { readonly type: "other" }; +export const V2ThreadListResponse__WebSearchAction = Schema.Union( + [ + Schema.Struct({ + queries: Schema.optionalKey(Schema.Union([Schema.Array(Schema.String), Schema.Null])), + query: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + type: Schema.Literal("search").annotate({ title: "SearchWebSearchActionType" }), + }).annotate({ title: "SearchWebSearchAction" }), + Schema.Struct({ + type: Schema.Literal("openPage").annotate({ title: "OpenPageWebSearchActionType" }), + url: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + }).annotate({ title: "OpenPageWebSearchAction" }), + Schema.Struct({ + pattern: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + type: Schema.Literal("findInPage").annotate({ title: "FindInPageWebSearchActionType" }), + url: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + }).annotate({ title: "FindInPageWebSearchAction" }), + Schema.Struct({ + type: Schema.Literal("other").annotate({ title: "OtherWebSearchActionType" }), + }).annotate({ title: "OtherWebSearchAction" }), + ], + { mode: "oneOf" }, +); + +export type V2ThreadMetadataUpdateParams__ThreadMetadataGitInfoUpdateParams = { + readonly branch?: string | null; + readonly originUrl?: string | null; + readonly sha?: string | null; +}; +export const V2ThreadMetadataUpdateParams__ThreadMetadataGitInfoUpdateParams = Schema.Struct({ + branch: Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + description: + "Omit to leave the stored branch unchanged, set to `null` to clear it, or provide a non-empty string to replace it.", + }), + Schema.Null, + ]), + ), + originUrl: Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + description: + "Omit to leave the stored origin URL unchanged, set to `null` to clear it, or provide a non-empty string to replace it.", + }), + Schema.Null, + ]), + ), + sha: Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + description: + "Omit to leave the stored commit unchanged, set to `null` to clear it, or provide a non-empty string to replace it.", + }), + Schema.Null, + ]), + ), +}); + +export type V2ThreadMetadataUpdateResponse__AgentPath = string; +export const V2ThreadMetadataUpdateResponse__AgentPath = Schema.String; + +export type V2ThreadMetadataUpdateResponse__CollabAgentStatus = + | "pendingInit" + | "running" + | "interrupted" + | "completed" + | "errored" + | "shutdown" + | "notFound"; +export const V2ThreadMetadataUpdateResponse__CollabAgentStatus = Schema.Literals([ + "pendingInit", + "running", + "interrupted", + "completed", + "errored", + "shutdown", + "notFound", +]); + +export type V2ThreadMetadataUpdateResponse__CommandAction = + | { + readonly command: string; + readonly name: string; + readonly path: string; + readonly type: "read"; + } + | { readonly command: string; readonly path?: string | null; readonly type: "listFiles" } + | { + readonly command: string; + readonly path?: string | null; + readonly query?: string | null; + readonly type: "search"; + } + | { readonly command: string; readonly type: "unknown" }; +export const V2ThreadMetadataUpdateResponse__CommandAction = Schema.Union( + [ + Schema.Struct({ + command: Schema.String, + name: Schema.String, + path: Schema.String, + type: Schema.Literal("read").annotate({ title: "ReadCommandActionType" }), + }).annotate({ title: "ReadCommandAction" }), + Schema.Struct({ + command: Schema.String, + path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + type: Schema.Literal("listFiles").annotate({ title: "ListFilesCommandActionType" }), + }).annotate({ title: "ListFilesCommandAction" }), + Schema.Struct({ + command: Schema.String, + path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + query: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + type: Schema.Literal("search").annotate({ title: "SearchCommandActionType" }), + }).annotate({ title: "SearchCommandAction" }), + Schema.Struct({ + command: Schema.String, + type: Schema.Literal("unknown").annotate({ title: "UnknownCommandActionType" }), + }).annotate({ title: "UnknownCommandAction" }), + ], + { mode: "oneOf" }, +); + +export type V2ThreadMetadataUpdateResponse__CommandExecutionStatus = + | "inProgress" + | "completed" + | "failed" + | "declined"; +export const V2ThreadMetadataUpdateResponse__CommandExecutionStatus = Schema.Literals([ + "inProgress", + "completed", + "failed", + "declined", +]); + +export type V2ThreadMetadataUpdateResponse__DynamicToolCallOutputContentItem = + | { readonly text: string; readonly type: "inputText" } + | { readonly imageUrl: string; readonly type: "inputImage" }; +export const V2ThreadMetadataUpdateResponse__DynamicToolCallOutputContentItem = Schema.Union( + [ + Schema.Struct({ + text: Schema.String, + type: Schema.Literal("inputText").annotate({ + title: "InputTextDynamicToolCallOutputContentItemType", + }), + }).annotate({ title: "InputTextDynamicToolCallOutputContentItem" }), + Schema.Struct({ + imageUrl: Schema.String, + type: Schema.Literal("inputImage").annotate({ + title: "InputImageDynamicToolCallOutputContentItemType", + }), + }).annotate({ title: "InputImageDynamicToolCallOutputContentItem" }), + ], + { mode: "oneOf" }, +); + +export type V2ThreadMetadataUpdateResponse__DynamicToolCallStatus = + | "inProgress" + | "completed" + | "failed"; +export const V2ThreadMetadataUpdateResponse__DynamicToolCallStatus = Schema.Literals([ + "inProgress", + "completed", + "failed", +]); + +export type V2ThreadMetadataUpdateResponse__GitInfo = { + readonly branch?: string | null; + readonly originUrl?: string | null; + readonly sha?: string | null; +}; +export const V2ThreadMetadataUpdateResponse__GitInfo = Schema.Struct({ + branch: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + originUrl: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + sha: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), +}); + +export type V2ThreadMetadataUpdateResponse__HookPromptFragment = { + readonly hookRunId: string; + readonly text: string; +}; +export const V2ThreadMetadataUpdateResponse__HookPromptFragment = Schema.Struct({ + hookRunId: Schema.String, + text: Schema.String, +}); + +export type V2ThreadMetadataUpdateResponse__McpToolCallError = { readonly message: string }; +export const V2ThreadMetadataUpdateResponse__McpToolCallError = Schema.Struct({ + message: Schema.String, +}); + +export type V2ThreadMetadataUpdateResponse__McpToolCallResult = { + readonly _meta?: unknown; + readonly content: ReadonlyArray; + readonly structuredContent?: unknown; +}; +export const V2ThreadMetadataUpdateResponse__McpToolCallResult = Schema.Struct({ + _meta: Schema.optionalKey(Schema.Unknown), + content: Schema.Array(Schema.Unknown), + structuredContent: Schema.optionalKey(Schema.Unknown), +}); + +export type V2ThreadMetadataUpdateResponse__McpToolCallStatus = + | "inProgress" + | "completed" + | "failed"; +export const V2ThreadMetadataUpdateResponse__McpToolCallStatus = Schema.Literals([ + "inProgress", + "completed", + "failed", +]); + +export type V2ThreadMetadataUpdateResponse__MemoryCitationEntry = { + readonly lineEnd: number; + readonly lineStart: number; + readonly note: string; + readonly path: string; +}; +export const V2ThreadMetadataUpdateResponse__MemoryCitationEntry = Schema.Struct({ + lineEnd: Schema.Number.annotate({ format: "uint32" }) + .check(Schema.isInt()) + .check(Schema.isGreaterThanOrEqualTo(0)), + lineStart: Schema.Number.annotate({ format: "uint32" }) + .check(Schema.isInt()) + .check(Schema.isGreaterThanOrEqualTo(0)), + note: Schema.String, + path: Schema.String, +}); + +export type V2ThreadMetadataUpdateResponse__MessagePhase = "commentary" | "final_answer"; +export const V2ThreadMetadataUpdateResponse__MessagePhase = Schema.Literals([ + "commentary", + "final_answer", +]).annotate({ + description: + 'Classifies an assistant message as interim commentary or final answer text.\n\nProviders do not emit this consistently, so callers must treat `None` as "phase unknown" and keep compatibility behavior for legacy models.', +}); + +export type V2ThreadMetadataUpdateResponse__NonSteerableTurnKind = "review" | "compact"; +export const V2ThreadMetadataUpdateResponse__NonSteerableTurnKind = Schema.Literals([ + "review", + "compact", +]); + +export type V2ThreadMetadataUpdateResponse__PatchApplyStatus = + | "inProgress" + | "completed" + | "failed" + | "declined"; +export const V2ThreadMetadataUpdateResponse__PatchApplyStatus = Schema.Literals([ + "inProgress", + "completed", + "failed", + "declined", +]); + +export type V2ThreadMetadataUpdateResponse__PatchChangeKind = + | { readonly type: "add" } + | { readonly type: "delete" } + | { readonly move_path?: string | null; readonly type: "update" }; +export const V2ThreadMetadataUpdateResponse__PatchChangeKind = Schema.Union( + [ + Schema.Struct({ + type: Schema.Literal("add").annotate({ title: "AddPatchChangeKindType" }), + }).annotate({ title: "AddPatchChangeKind" }), + Schema.Struct({ + type: Schema.Literal("delete").annotate({ title: "DeletePatchChangeKindType" }), + }).annotate({ title: "DeletePatchChangeKind" }), + Schema.Struct({ + move_path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + type: Schema.Literal("update").annotate({ title: "UpdatePatchChangeKindType" }), + }).annotate({ title: "UpdatePatchChangeKind" }), + ], + { mode: "oneOf" }, +); + +export type V2ThreadMetadataUpdateResponse__ReasoningEffort = + | "none" + | "minimal" + | "low" + | "medium" + | "high" + | "xhigh"; +export const V2ThreadMetadataUpdateResponse__ReasoningEffort = Schema.Literals([ + "none", + "minimal", + "low", + "medium", + "high", + "xhigh", +]).annotate({ + description: + "See https://platform.openai.com/docs/guides/reasoning?api-mode=responses#get-started-with-reasoning", +}); + +export type V2ThreadMetadataUpdateResponse__TextElement = { + readonly byteRange: { readonly end: number; readonly start: number }; + readonly placeholder?: string | null; +}; +export const V2ThreadMetadataUpdateResponse__TextElement = Schema.Struct({ + byteRange: Schema.Struct({ + end: Schema.Number.annotate({ format: "uint" }) + .check(Schema.isInt()) + .check(Schema.isGreaterThanOrEqualTo(0)), + start: Schema.Number.annotate({ format: "uint" }) + .check(Schema.isInt()) + .check(Schema.isGreaterThanOrEqualTo(0)), + }).annotate({ + description: "Byte range in the parent `text` buffer that this element occupies.", + }), + placeholder: Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + description: "Optional human-readable placeholder for the element, displayed in the UI.", + }), + Schema.Null, + ]), + ), +}); + +export type V2ThreadMetadataUpdateResponse__ThreadActiveFlag = + | "waitingOnApproval" + | "waitingOnUserInput"; +export const V2ThreadMetadataUpdateResponse__ThreadActiveFlag = Schema.Literals([ + "waitingOnApproval", + "waitingOnUserInput", +]); + +export type V2ThreadMetadataUpdateResponse__ThreadId = string; +export const V2ThreadMetadataUpdateResponse__ThreadId = Schema.String; + +export type V2ThreadMetadataUpdateResponse__TurnStatus = + | "completed" + | "interrupted" + | "failed" + | "inProgress"; +export const V2ThreadMetadataUpdateResponse__TurnStatus = Schema.Literals([ + "completed", + "interrupted", + "failed", + "inProgress", +]); + +export type V2ThreadMetadataUpdateResponse__WebSearchAction = + | { + readonly queries?: ReadonlyArray | null; + readonly query?: string | null; + readonly type: "search"; + } + | { readonly type: "openPage"; readonly url?: string | null } + | { readonly pattern?: string | null; readonly type: "findInPage"; readonly url?: string | null } + | { readonly type: "other" }; +export const V2ThreadMetadataUpdateResponse__WebSearchAction = Schema.Union( + [ + Schema.Struct({ + queries: Schema.optionalKey(Schema.Union([Schema.Array(Schema.String), Schema.Null])), + query: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + type: Schema.Literal("search").annotate({ title: "SearchWebSearchActionType" }), + }).annotate({ title: "SearchWebSearchAction" }), + Schema.Struct({ + type: Schema.Literal("openPage").annotate({ title: "OpenPageWebSearchActionType" }), + url: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + }).annotate({ title: "OpenPageWebSearchAction" }), + Schema.Struct({ + pattern: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + type: Schema.Literal("findInPage").annotate({ title: "FindInPageWebSearchActionType" }), + url: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + }).annotate({ title: "FindInPageWebSearchAction" }), + Schema.Struct({ + type: Schema.Literal("other").annotate({ title: "OtherWebSearchActionType" }), + }).annotate({ title: "OtherWebSearchAction" }), + ], + { mode: "oneOf" }, +); + +export type V2ThreadReadResponse__AgentPath = string; +export const V2ThreadReadResponse__AgentPath = Schema.String; + +export type V2ThreadReadResponse__CollabAgentStatus = + | "pendingInit" + | "running" + | "interrupted" + | "completed" + | "errored" + | "shutdown" + | "notFound"; +export const V2ThreadReadResponse__CollabAgentStatus = Schema.Literals([ + "pendingInit", + "running", + "interrupted", + "completed", + "errored", + "shutdown", + "notFound", +]); + +export type V2ThreadReadResponse__CommandAction = + | { + readonly command: string; + readonly name: string; + readonly path: string; + readonly type: "read"; + } + | { readonly command: string; readonly path?: string | null; readonly type: "listFiles" } + | { + readonly command: string; + readonly path?: string | null; + readonly query?: string | null; + readonly type: "search"; + } + | { readonly command: string; readonly type: "unknown" }; +export const V2ThreadReadResponse__CommandAction = Schema.Union( + [ + Schema.Struct({ + command: Schema.String, + name: Schema.String, + path: Schema.String, + type: Schema.Literal("read").annotate({ title: "ReadCommandActionType" }), + }).annotate({ title: "ReadCommandAction" }), + Schema.Struct({ + command: Schema.String, + path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + type: Schema.Literal("listFiles").annotate({ title: "ListFilesCommandActionType" }), + }).annotate({ title: "ListFilesCommandAction" }), + Schema.Struct({ + command: Schema.String, + path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + query: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + type: Schema.Literal("search").annotate({ title: "SearchCommandActionType" }), + }).annotate({ title: "SearchCommandAction" }), + Schema.Struct({ + command: Schema.String, + type: Schema.Literal("unknown").annotate({ title: "UnknownCommandActionType" }), + }).annotate({ title: "UnknownCommandAction" }), + ], + { mode: "oneOf" }, +); + +export type V2ThreadReadResponse__CommandExecutionStatus = + | "inProgress" + | "completed" + | "failed" + | "declined"; +export const V2ThreadReadResponse__CommandExecutionStatus = Schema.Literals([ + "inProgress", + "completed", + "failed", + "declined", +]); + +export type V2ThreadReadResponse__DynamicToolCallOutputContentItem = + | { readonly text: string; readonly type: "inputText" } + | { readonly imageUrl: string; readonly type: "inputImage" }; +export const V2ThreadReadResponse__DynamicToolCallOutputContentItem = Schema.Union( + [ + Schema.Struct({ + text: Schema.String, + type: Schema.Literal("inputText").annotate({ + title: "InputTextDynamicToolCallOutputContentItemType", + }), + }).annotate({ title: "InputTextDynamicToolCallOutputContentItem" }), + Schema.Struct({ + imageUrl: Schema.String, + type: Schema.Literal("inputImage").annotate({ + title: "InputImageDynamicToolCallOutputContentItemType", + }), + }).annotate({ title: "InputImageDynamicToolCallOutputContentItem" }), + ], + { mode: "oneOf" }, +); + +export type V2ThreadReadResponse__DynamicToolCallStatus = "inProgress" | "completed" | "failed"; +export const V2ThreadReadResponse__DynamicToolCallStatus = Schema.Literals([ + "inProgress", + "completed", + "failed", +]); + +export type V2ThreadReadResponse__GitInfo = { + readonly branch?: string | null; + readonly originUrl?: string | null; + readonly sha?: string | null; +}; +export const V2ThreadReadResponse__GitInfo = Schema.Struct({ + branch: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + originUrl: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + sha: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), +}); + +export type V2ThreadReadResponse__HookPromptFragment = { + readonly hookRunId: string; + readonly text: string; +}; +export const V2ThreadReadResponse__HookPromptFragment = Schema.Struct({ + hookRunId: Schema.String, + text: Schema.String, +}); + +export type V2ThreadReadResponse__McpToolCallError = { readonly message: string }; +export const V2ThreadReadResponse__McpToolCallError = Schema.Struct({ message: Schema.String }); + +export type V2ThreadReadResponse__McpToolCallResult = { + readonly _meta?: unknown; + readonly content: ReadonlyArray; + readonly structuredContent?: unknown; +}; +export const V2ThreadReadResponse__McpToolCallResult = Schema.Struct({ + _meta: Schema.optionalKey(Schema.Unknown), + content: Schema.Array(Schema.Unknown), + structuredContent: Schema.optionalKey(Schema.Unknown), +}); + +export type V2ThreadReadResponse__McpToolCallStatus = "inProgress" | "completed" | "failed"; +export const V2ThreadReadResponse__McpToolCallStatus = Schema.Literals([ + "inProgress", + "completed", + "failed", +]); + +export type V2ThreadReadResponse__MemoryCitationEntry = { + readonly lineEnd: number; + readonly lineStart: number; + readonly note: string; + readonly path: string; +}; +export const V2ThreadReadResponse__MemoryCitationEntry = Schema.Struct({ + lineEnd: Schema.Number.annotate({ format: "uint32" }) + .check(Schema.isInt()) + .check(Schema.isGreaterThanOrEqualTo(0)), + lineStart: Schema.Number.annotate({ format: "uint32" }) + .check(Schema.isInt()) + .check(Schema.isGreaterThanOrEqualTo(0)), + note: Schema.String, + path: Schema.String, +}); + +export type V2ThreadReadResponse__MessagePhase = "commentary" | "final_answer"; +export const V2ThreadReadResponse__MessagePhase = Schema.Literals([ + "commentary", + "final_answer", +]).annotate({ + description: + 'Classifies an assistant message as interim commentary or final answer text.\n\nProviders do not emit this consistently, so callers must treat `None` as "phase unknown" and keep compatibility behavior for legacy models.', +}); + +export type V2ThreadReadResponse__NonSteerableTurnKind = "review" | "compact"; +export const V2ThreadReadResponse__NonSteerableTurnKind = Schema.Literals(["review", "compact"]); + +export type V2ThreadReadResponse__PatchApplyStatus = + | "inProgress" + | "completed" + | "failed" + | "declined"; +export const V2ThreadReadResponse__PatchApplyStatus = Schema.Literals([ + "inProgress", + "completed", + "failed", + "declined", +]); + +export type V2ThreadReadResponse__PatchChangeKind = + | { readonly type: "add" } + | { readonly type: "delete" } + | { readonly move_path?: string | null; readonly type: "update" }; +export const V2ThreadReadResponse__PatchChangeKind = Schema.Union( + [ + Schema.Struct({ + type: Schema.Literal("add").annotate({ title: "AddPatchChangeKindType" }), + }).annotate({ title: "AddPatchChangeKind" }), + Schema.Struct({ + type: Schema.Literal("delete").annotate({ title: "DeletePatchChangeKindType" }), + }).annotate({ title: "DeletePatchChangeKind" }), + Schema.Struct({ + move_path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + type: Schema.Literal("update").annotate({ title: "UpdatePatchChangeKindType" }), + }).annotate({ title: "UpdatePatchChangeKind" }), + ], + { mode: "oneOf" }, +); + +export type V2ThreadReadResponse__ReasoningEffort = + | "none" + | "minimal" + | "low" + | "medium" + | "high" + | "xhigh"; +export const V2ThreadReadResponse__ReasoningEffort = Schema.Literals([ + "none", + "minimal", + "low", + "medium", + "high", + "xhigh", +]).annotate({ + description: + "See https://platform.openai.com/docs/guides/reasoning?api-mode=responses#get-started-with-reasoning", +}); + +export type V2ThreadReadResponse__TextElement = { + readonly byteRange: { readonly end: number; readonly start: number }; + readonly placeholder?: string | null; +}; +export const V2ThreadReadResponse__TextElement = Schema.Struct({ + byteRange: Schema.Struct({ + end: Schema.Number.annotate({ format: "uint" }) + .check(Schema.isInt()) + .check(Schema.isGreaterThanOrEqualTo(0)), + start: Schema.Number.annotate({ format: "uint" }) + .check(Schema.isInt()) + .check(Schema.isGreaterThanOrEqualTo(0)), + }).annotate({ + description: "Byte range in the parent `text` buffer that this element occupies.", + }), + placeholder: Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + description: "Optional human-readable placeholder for the element, displayed in the UI.", + }), + Schema.Null, + ]), + ), +}); + +export type V2ThreadReadResponse__ThreadActiveFlag = "waitingOnApproval" | "waitingOnUserInput"; +export const V2ThreadReadResponse__ThreadActiveFlag = Schema.Literals([ + "waitingOnApproval", + "waitingOnUserInput", +]); + +export type V2ThreadReadResponse__ThreadId = string; +export const V2ThreadReadResponse__ThreadId = Schema.String; + +export type V2ThreadReadResponse__TurnStatus = + | "completed" + | "interrupted" + | "failed" + | "inProgress"; +export const V2ThreadReadResponse__TurnStatus = Schema.Literals([ + "completed", + "interrupted", + "failed", + "inProgress", +]); + +export type V2ThreadReadResponse__WebSearchAction = + | { + readonly queries?: ReadonlyArray | null; + readonly query?: string | null; + readonly type: "search"; + } + | { readonly type: "openPage"; readonly url?: string | null } + | { readonly pattern?: string | null; readonly type: "findInPage"; readonly url?: string | null } + | { readonly type: "other" }; +export const V2ThreadReadResponse__WebSearchAction = Schema.Union( + [ + Schema.Struct({ + queries: Schema.optionalKey(Schema.Union([Schema.Array(Schema.String), Schema.Null])), + query: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + type: Schema.Literal("search").annotate({ title: "SearchWebSearchActionType" }), + }).annotate({ title: "SearchWebSearchAction" }), + Schema.Struct({ + type: Schema.Literal("openPage").annotate({ title: "OpenPageWebSearchActionType" }), + url: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + }).annotate({ title: "OpenPageWebSearchAction" }), + Schema.Struct({ + pattern: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + type: Schema.Literal("findInPage").annotate({ title: "FindInPageWebSearchActionType" }), + url: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + }).annotate({ title: "FindInPageWebSearchAction" }), + Schema.Struct({ + type: Schema.Literal("other").annotate({ title: "OtherWebSearchActionType" }), + }).annotate({ title: "OtherWebSearchAction" }), + ], + { mode: "oneOf" }, +); + +export type V2ThreadRealtimeOutputAudioDeltaNotification__ThreadRealtimeAudioChunk = { + readonly data: string; + readonly itemId?: string | null; + readonly numChannels: number; + readonly sampleRate: number; + readonly samplesPerChannel?: number | null; +}; +export const V2ThreadRealtimeOutputAudioDeltaNotification__ThreadRealtimeAudioChunk = Schema.Struct( + { + data: Schema.String, + itemId: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + numChannels: Schema.Number.annotate({ format: "uint16" }) + .check(Schema.isInt()) + .check(Schema.isGreaterThanOrEqualTo(0)), + sampleRate: Schema.Number.annotate({ format: "uint32" }) + .check(Schema.isInt()) + .check(Schema.isGreaterThanOrEqualTo(0)), + samplesPerChannel: Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ format: "uint32" }) + .check(Schema.isInt()) + .check(Schema.isGreaterThanOrEqualTo(0)), + Schema.Null, + ]), + ), + }, +).annotate({ description: "EXPERIMENTAL - thread realtime audio chunk." }); + +export type V2ThreadRealtimeStartedNotification__RealtimeConversationVersion = "v1" | "v2"; +export const V2ThreadRealtimeStartedNotification__RealtimeConversationVersion = Schema.Literals([ + "v1", + "v2", +]); + +export type V2ThreadResumeParams__ApprovalsReviewer = "user" | "guardian_subagent"; +export const V2ThreadResumeParams__ApprovalsReviewer = Schema.Literals([ + "user", + "guardian_subagent", +]).annotate({ + description: + "Configures who approval requests are routed to for review. Examples include sandbox escapes, blocked network access, MCP approval prompts, and ARC escalations. Defaults to `user`. `guardian_subagent` uses a carefully prompted subagent to gather relevant context and apply a risk-based decision framework before approving or denying the request.", +}); + +export type V2ThreadResumeParams__AskForApproval = + | "untrusted" + | "on-failure" + | "on-request" + | "never" + | { + readonly granular: { + readonly mcp_elicitations: boolean; + readonly request_permissions?: boolean; + readonly rules: boolean; + readonly sandbox_approval: boolean; + readonly skill_approval?: boolean; + }; + }; +export const V2ThreadResumeParams__AskForApproval = Schema.Union( + [ + Schema.Literals(["untrusted", "on-failure", "on-request", "never"]), + Schema.Struct({ + granular: Schema.Struct({ + mcp_elicitations: Schema.Boolean, + request_permissions: Schema.optionalKey(Schema.Boolean.annotate({ default: false })), + rules: Schema.Boolean, + sandbox_approval: Schema.Boolean, + skill_approval: Schema.optionalKey(Schema.Boolean.annotate({ default: false })), + }), + }).annotate({ title: "GranularAskForApproval" }), + ], + { mode: "oneOf" }, +); + +export type V2ThreadResumeParams__ContentItem = + | { readonly text: string; readonly type: "input_text" } + | { readonly image_url: string; readonly type: "input_image" } + | { readonly text: string; readonly type: "output_text" }; +export const V2ThreadResumeParams__ContentItem = Schema.Union( + [ + Schema.Struct({ + text: Schema.String, + type: Schema.Literal("input_text").annotate({ title: "InputTextContentItemType" }), + }).annotate({ title: "InputTextContentItem" }), + Schema.Struct({ + image_url: Schema.String, + type: Schema.Literal("input_image").annotate({ title: "InputImageContentItemType" }), + }).annotate({ title: "InputImageContentItem" }), + Schema.Struct({ + text: Schema.String, + type: Schema.Literal("output_text").annotate({ title: "OutputTextContentItemType" }), + }).annotate({ title: "OutputTextContentItem" }), + ], + { mode: "oneOf" }, +); + +export type V2ThreadResumeParams__GhostCommit = { + readonly id: string; + readonly parent?: string | null; + readonly preexisting_untracked_dirs: ReadonlyArray; + readonly preexisting_untracked_files: ReadonlyArray; +}; +export const V2ThreadResumeParams__GhostCommit = Schema.Struct({ + id: Schema.String, + parent: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + preexisting_untracked_dirs: Schema.Array(Schema.String), + preexisting_untracked_files: Schema.Array(Schema.String), +}).annotate({ description: "Details of a ghost commit created from a repository state." }); + +export type V2ThreadResumeParams__ImageDetail = "auto" | "low" | "high" | "original"; +export const V2ThreadResumeParams__ImageDetail = Schema.Literals([ + "auto", + "low", + "high", + "original", +]); + +export type V2ThreadResumeParams__LocalShellAction = { + readonly command: ReadonlyArray; + readonly env?: { readonly [x: string]: string } | null; + readonly timeout_ms?: number | null; + readonly type: "exec"; + readonly user?: string | null; + readonly working_directory?: string | null; +}; +export const V2ThreadResumeParams__LocalShellAction = Schema.Union( + [ + Schema.Struct({ + command: Schema.Array(Schema.String), + env: Schema.optionalKey( + Schema.Union([Schema.Record(Schema.String, Schema.String), Schema.Null]), + ), + timeout_ms: Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ format: "uint64" }) + .check(Schema.isInt()) + .check(Schema.isGreaterThanOrEqualTo(0)), + Schema.Null, + ]), + ), + type: Schema.Literal("exec").annotate({ title: "ExecLocalShellActionType" }), + user: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + working_directory: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + }).annotate({ title: "ExecLocalShellAction" }), + ], + { mode: "oneOf" }, +); + +export type V2ThreadResumeParams__LocalShellStatus = "completed" | "in_progress" | "incomplete"; +export const V2ThreadResumeParams__LocalShellStatus = Schema.Literals([ + "completed", + "in_progress", + "incomplete", +]); + +export type V2ThreadResumeParams__MessagePhase = "commentary" | "final_answer"; +export const V2ThreadResumeParams__MessagePhase = Schema.Literals([ + "commentary", + "final_answer", +]).annotate({ + description: + 'Classifies an assistant message as interim commentary or final answer text.\n\nProviders do not emit this consistently, so callers must treat `None` as "phase unknown" and keep compatibility behavior for legacy models.', +}); + +export type V2ThreadResumeParams__Personality = "none" | "friendly" | "pragmatic"; +export const V2ThreadResumeParams__Personality = Schema.Literals(["none", "friendly", "pragmatic"]); + +export type V2ThreadResumeParams__ReasoningItemContent = + | { readonly text: string; readonly type: "reasoning_text" } + | { readonly text: string; readonly type: "text" }; +export const V2ThreadResumeParams__ReasoningItemContent = Schema.Union( + [ + Schema.Struct({ + text: Schema.String, + type: Schema.Literal("reasoning_text").annotate({ + title: "ReasoningTextReasoningItemContentType", + }), + }).annotate({ title: "ReasoningTextReasoningItemContent" }), + Schema.Struct({ + text: Schema.String, + type: Schema.Literal("text").annotate({ title: "TextReasoningItemContentType" }), + }).annotate({ title: "TextReasoningItemContent" }), + ], + { mode: "oneOf" }, +); + +export type V2ThreadResumeParams__ReasoningItemReasoningSummary = { + readonly text: string; + readonly type: "summary_text"; +}; +export const V2ThreadResumeParams__ReasoningItemReasoningSummary = Schema.Union( + [ + Schema.Struct({ + text: Schema.String, + type: Schema.Literal("summary_text").annotate({ + title: "SummaryTextReasoningItemReasoningSummaryType", + }), + }).annotate({ title: "SummaryTextReasoningItemReasoningSummary" }), + ], + { mode: "oneOf" }, +); + +export type V2ThreadResumeParams__ResponsesApiWebSearchAction = + | { + readonly queries?: ReadonlyArray | null; + readonly query?: string | null; + readonly type: "search"; + } + | { readonly type: "open_page"; readonly url?: string | null } + | { + readonly pattern?: string | null; + readonly type: "find_in_page"; + readonly url?: string | null; + } + | { readonly type: "other" }; +export const V2ThreadResumeParams__ResponsesApiWebSearchAction = Schema.Union( + [ + Schema.Struct({ + queries: Schema.optionalKey(Schema.Union([Schema.Array(Schema.String), Schema.Null])), + query: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + type: Schema.Literal("search").annotate({ title: "SearchResponsesApiWebSearchActionType" }), + }).annotate({ title: "SearchResponsesApiWebSearchAction" }), + Schema.Struct({ + type: Schema.Literal("open_page").annotate({ + title: "OpenPageResponsesApiWebSearchActionType", + }), + url: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + }).annotate({ title: "OpenPageResponsesApiWebSearchAction" }), + Schema.Struct({ + pattern: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + type: Schema.Literal("find_in_page").annotate({ + title: "FindInPageResponsesApiWebSearchActionType", + }), + url: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + }).annotate({ title: "FindInPageResponsesApiWebSearchAction" }), + Schema.Struct({ + type: Schema.Literal("other").annotate({ title: "OtherResponsesApiWebSearchActionType" }), + }).annotate({ title: "OtherResponsesApiWebSearchAction" }), + ], + { mode: "oneOf" }, +); + +export type V2ThreadResumeParams__SandboxMode = + | "read-only" + | "workspace-write" + | "danger-full-access"; +export const V2ThreadResumeParams__SandboxMode = Schema.Literals([ + "read-only", + "workspace-write", + "danger-full-access", +]); + +export type V2ThreadResumeParams__ServiceTier = "fast" | "flex"; +export const V2ThreadResumeParams__ServiceTier = Schema.Literals(["fast", "flex"]); + +export type V2ThreadResumeResponse__AbsolutePathBuf = string; +export const V2ThreadResumeResponse__AbsolutePathBuf = Schema.String.annotate({ + description: + "A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\n\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.", +}); + +export type V2ThreadResumeResponse__AgentPath = string; +export const V2ThreadResumeResponse__AgentPath = Schema.String; + +export type V2ThreadResumeResponse__AskForApproval = + | "untrusted" + | "on-failure" + | "on-request" + | "never" + | { + readonly granular: { + readonly mcp_elicitations: boolean; + readonly request_permissions?: boolean; + readonly rules: boolean; + readonly sandbox_approval: boolean; + readonly skill_approval?: boolean; + }; + }; +export const V2ThreadResumeResponse__AskForApproval = Schema.Union( + [ + Schema.Literals(["untrusted", "on-failure", "on-request", "never"]), + Schema.Struct({ + granular: Schema.Struct({ + mcp_elicitations: Schema.Boolean, + request_permissions: Schema.optionalKey(Schema.Boolean.annotate({ default: false })), + rules: Schema.Boolean, + sandbox_approval: Schema.Boolean, + skill_approval: Schema.optionalKey(Schema.Boolean.annotate({ default: false })), + }), + }).annotate({ title: "GranularAskForApproval" }), + ], + { mode: "oneOf" }, +); + +export type V2ThreadResumeResponse__CollabAgentStatus = + | "pendingInit" + | "running" + | "interrupted" + | "completed" + | "errored" + | "shutdown" + | "notFound"; +export const V2ThreadResumeResponse__CollabAgentStatus = Schema.Literals([ + "pendingInit", + "running", + "interrupted", + "completed", + "errored", + "shutdown", + "notFound", +]); + +export type V2ThreadResumeResponse__CommandAction = + | { + readonly command: string; + readonly name: string; + readonly path: string; + readonly type: "read"; + } + | { readonly command: string; readonly path?: string | null; readonly type: "listFiles" } + | { + readonly command: string; + readonly path?: string | null; + readonly query?: string | null; + readonly type: "search"; + } + | { readonly command: string; readonly type: "unknown" }; +export const V2ThreadResumeResponse__CommandAction = Schema.Union( + [ + Schema.Struct({ + command: Schema.String, + name: Schema.String, + path: Schema.String, + type: Schema.Literal("read").annotate({ title: "ReadCommandActionType" }), + }).annotate({ title: "ReadCommandAction" }), + Schema.Struct({ + command: Schema.String, + path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + type: Schema.Literal("listFiles").annotate({ title: "ListFilesCommandActionType" }), + }).annotate({ title: "ListFilesCommandAction" }), + Schema.Struct({ + command: Schema.String, + path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + query: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + type: Schema.Literal("search").annotate({ title: "SearchCommandActionType" }), + }).annotate({ title: "SearchCommandAction" }), + Schema.Struct({ + command: Schema.String, + type: Schema.Literal("unknown").annotate({ title: "UnknownCommandActionType" }), + }).annotate({ title: "UnknownCommandAction" }), + ], + { mode: "oneOf" }, +); + +export type V2ThreadResumeResponse__CommandExecutionStatus = + | "inProgress" + | "completed" + | "failed" + | "declined"; +export const V2ThreadResumeResponse__CommandExecutionStatus = Schema.Literals([ + "inProgress", + "completed", + "failed", + "declined", +]); + +export type V2ThreadResumeResponse__DynamicToolCallOutputContentItem = + | { readonly text: string; readonly type: "inputText" } + | { readonly imageUrl: string; readonly type: "inputImage" }; +export const V2ThreadResumeResponse__DynamicToolCallOutputContentItem = Schema.Union( + [ + Schema.Struct({ + text: Schema.String, + type: Schema.Literal("inputText").annotate({ + title: "InputTextDynamicToolCallOutputContentItemType", + }), + }).annotate({ title: "InputTextDynamicToolCallOutputContentItem" }), + Schema.Struct({ + imageUrl: Schema.String, + type: Schema.Literal("inputImage").annotate({ + title: "InputImageDynamicToolCallOutputContentItemType", + }), + }).annotate({ title: "InputImageDynamicToolCallOutputContentItem" }), + ], + { mode: "oneOf" }, +); + +export type V2ThreadResumeResponse__DynamicToolCallStatus = "inProgress" | "completed" | "failed"; +export const V2ThreadResumeResponse__DynamicToolCallStatus = Schema.Literals([ + "inProgress", + "completed", + "failed", +]); + +export type V2ThreadResumeResponse__GitInfo = { + readonly branch?: string | null; + readonly originUrl?: string | null; + readonly sha?: string | null; +}; +export const V2ThreadResumeResponse__GitInfo = Schema.Struct({ + branch: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + originUrl: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + sha: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), +}); + +export type V2ThreadResumeResponse__HookPromptFragment = { + readonly hookRunId: string; + readonly text: string; +}; +export const V2ThreadResumeResponse__HookPromptFragment = Schema.Struct({ + hookRunId: Schema.String, + text: Schema.String, +}); + +export type V2ThreadResumeResponse__McpToolCallError = { readonly message: string }; +export const V2ThreadResumeResponse__McpToolCallError = Schema.Struct({ message: Schema.String }); + +export type V2ThreadResumeResponse__McpToolCallResult = { + readonly _meta?: unknown; + readonly content: ReadonlyArray; + readonly structuredContent?: unknown; +}; +export const V2ThreadResumeResponse__McpToolCallResult = Schema.Struct({ + _meta: Schema.optionalKey(Schema.Unknown), + content: Schema.Array(Schema.Unknown), + structuredContent: Schema.optionalKey(Schema.Unknown), +}); + +export type V2ThreadResumeResponse__McpToolCallStatus = "inProgress" | "completed" | "failed"; +export const V2ThreadResumeResponse__McpToolCallStatus = Schema.Literals([ + "inProgress", + "completed", + "failed", +]); + +export type V2ThreadResumeResponse__MemoryCitationEntry = { + readonly lineEnd: number; + readonly lineStart: number; + readonly note: string; + readonly path: string; +}; +export const V2ThreadResumeResponse__MemoryCitationEntry = Schema.Struct({ + lineEnd: Schema.Number.annotate({ format: "uint32" }) + .check(Schema.isInt()) + .check(Schema.isGreaterThanOrEqualTo(0)), + lineStart: Schema.Number.annotate({ format: "uint32" }) + .check(Schema.isInt()) + .check(Schema.isGreaterThanOrEqualTo(0)), + note: Schema.String, + path: Schema.String, +}); + +export type V2ThreadResumeResponse__MessagePhase = "commentary" | "final_answer"; +export const V2ThreadResumeResponse__MessagePhase = Schema.Literals([ + "commentary", + "final_answer", +]).annotate({ + description: + 'Classifies an assistant message as interim commentary or final answer text.\n\nProviders do not emit this consistently, so callers must treat `None` as "phase unknown" and keep compatibility behavior for legacy models.', +}); + +export type V2ThreadResumeResponse__NonSteerableTurnKind = "review" | "compact"; +export const V2ThreadResumeResponse__NonSteerableTurnKind = Schema.Literals(["review", "compact"]); + +export type V2ThreadResumeResponse__PatchApplyStatus = + | "inProgress" + | "completed" + | "failed" + | "declined"; +export const V2ThreadResumeResponse__PatchApplyStatus = Schema.Literals([ + "inProgress", + "completed", + "failed", + "declined", +]); + +export type V2ThreadResumeResponse__PatchChangeKind = + | { readonly type: "add" } + | { readonly type: "delete" } + | { readonly move_path?: string | null; readonly type: "update" }; +export const V2ThreadResumeResponse__PatchChangeKind = Schema.Union( + [ + Schema.Struct({ + type: Schema.Literal("add").annotate({ title: "AddPatchChangeKindType" }), + }).annotate({ title: "AddPatchChangeKind" }), + Schema.Struct({ + type: Schema.Literal("delete").annotate({ title: "DeletePatchChangeKindType" }), + }).annotate({ title: "DeletePatchChangeKind" }), + Schema.Struct({ + move_path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + type: Schema.Literal("update").annotate({ title: "UpdatePatchChangeKindType" }), + }).annotate({ title: "UpdatePatchChangeKind" }), + ], + { mode: "oneOf" }, +); + +export type V2ThreadResumeResponse__ReasoningEffort = + | "none" + | "minimal" + | "low" + | "medium" + | "high" + | "xhigh"; +export const V2ThreadResumeResponse__ReasoningEffort = Schema.Literals([ + "none", + "minimal", + "low", + "medium", + "high", + "xhigh", +]).annotate({ + description: + "See https://platform.openai.com/docs/guides/reasoning?api-mode=responses#get-started-with-reasoning", +}); + +export type V2ThreadResumeResponse__ServiceTier = "fast" | "flex"; +export const V2ThreadResumeResponse__ServiceTier = Schema.Literals(["fast", "flex"]); + +export type V2ThreadResumeResponse__TextElement = { + readonly byteRange: { readonly end: number; readonly start: number }; + readonly placeholder?: string | null; +}; +export const V2ThreadResumeResponse__TextElement = Schema.Struct({ + byteRange: Schema.Struct({ + end: Schema.Number.annotate({ format: "uint" }) + .check(Schema.isInt()) + .check(Schema.isGreaterThanOrEqualTo(0)), + start: Schema.Number.annotate({ format: "uint" }) + .check(Schema.isInt()) + .check(Schema.isGreaterThanOrEqualTo(0)), + }).annotate({ + description: "Byte range in the parent `text` buffer that this element occupies.", + }), + placeholder: Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + description: "Optional human-readable placeholder for the element, displayed in the UI.", + }), + Schema.Null, + ]), + ), +}); + +export type V2ThreadResumeResponse__ThreadActiveFlag = "waitingOnApproval" | "waitingOnUserInput"; +export const V2ThreadResumeResponse__ThreadActiveFlag = Schema.Literals([ + "waitingOnApproval", + "waitingOnUserInput", +]); + +export type V2ThreadResumeResponse__ThreadId = string; +export const V2ThreadResumeResponse__ThreadId = Schema.String; + +export type V2ThreadResumeResponse__TurnStatus = + | "completed" + | "interrupted" + | "failed" + | "inProgress"; +export const V2ThreadResumeResponse__TurnStatus = Schema.Literals([ + "completed", + "interrupted", + "failed", + "inProgress", +]); + +export type V2ThreadResumeResponse__WebSearchAction = + | { + readonly queries?: ReadonlyArray | null; + readonly query?: string | null; + readonly type: "search"; + } + | { readonly type: "openPage"; readonly url?: string | null } + | { readonly pattern?: string | null; readonly type: "findInPage"; readonly url?: string | null } + | { readonly type: "other" }; +export const V2ThreadResumeResponse__WebSearchAction = Schema.Union( + [ + Schema.Struct({ + queries: Schema.optionalKey(Schema.Union([Schema.Array(Schema.String), Schema.Null])), + query: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + type: Schema.Literal("search").annotate({ title: "SearchWebSearchActionType" }), + }).annotate({ title: "SearchWebSearchAction" }), + Schema.Struct({ + type: Schema.Literal("openPage").annotate({ title: "OpenPageWebSearchActionType" }), + url: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + }).annotate({ title: "OpenPageWebSearchAction" }), + Schema.Struct({ + pattern: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + type: Schema.Literal("findInPage").annotate({ title: "FindInPageWebSearchActionType" }), + url: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + }).annotate({ title: "FindInPageWebSearchAction" }), + Schema.Struct({ + type: Schema.Literal("other").annotate({ title: "OtherWebSearchActionType" }), + }).annotate({ title: "OtherWebSearchAction" }), + ], + { mode: "oneOf" }, +); + +export type V2ThreadRollbackResponse__AgentPath = string; +export const V2ThreadRollbackResponse__AgentPath = Schema.String; + +export type V2ThreadRollbackResponse__CollabAgentStatus = + | "pendingInit" + | "running" + | "interrupted" + | "completed" + | "errored" + | "shutdown" + | "notFound"; +export const V2ThreadRollbackResponse__CollabAgentStatus = Schema.Literals([ + "pendingInit", + "running", + "interrupted", + "completed", + "errored", + "shutdown", + "notFound", +]); + +export type V2ThreadRollbackResponse__CommandAction = + | { + readonly command: string; + readonly name: string; + readonly path: string; + readonly type: "read"; + } + | { readonly command: string; readonly path?: string | null; readonly type: "listFiles" } + | { + readonly command: string; + readonly path?: string | null; + readonly query?: string | null; + readonly type: "search"; + } + | { readonly command: string; readonly type: "unknown" }; +export const V2ThreadRollbackResponse__CommandAction = Schema.Union( + [ + Schema.Struct({ + command: Schema.String, + name: Schema.String, + path: Schema.String, + type: Schema.Literal("read").annotate({ title: "ReadCommandActionType" }), + }).annotate({ title: "ReadCommandAction" }), + Schema.Struct({ + command: Schema.String, + path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + type: Schema.Literal("listFiles").annotate({ title: "ListFilesCommandActionType" }), + }).annotate({ title: "ListFilesCommandAction" }), + Schema.Struct({ + command: Schema.String, + path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + query: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + type: Schema.Literal("search").annotate({ title: "SearchCommandActionType" }), + }).annotate({ title: "SearchCommandAction" }), + Schema.Struct({ + command: Schema.String, + type: Schema.Literal("unknown").annotate({ title: "UnknownCommandActionType" }), + }).annotate({ title: "UnknownCommandAction" }), + ], + { mode: "oneOf" }, +); + +export type V2ThreadRollbackResponse__CommandExecutionStatus = + | "inProgress" + | "completed" + | "failed" + | "declined"; +export const V2ThreadRollbackResponse__CommandExecutionStatus = Schema.Literals([ + "inProgress", + "completed", + "failed", + "declined", +]); + +export type V2ThreadRollbackResponse__DynamicToolCallOutputContentItem = + | { readonly text: string; readonly type: "inputText" } + | { readonly imageUrl: string; readonly type: "inputImage" }; +export const V2ThreadRollbackResponse__DynamicToolCallOutputContentItem = Schema.Union( + [ + Schema.Struct({ + text: Schema.String, + type: Schema.Literal("inputText").annotate({ + title: "InputTextDynamicToolCallOutputContentItemType", + }), + }).annotate({ title: "InputTextDynamicToolCallOutputContentItem" }), + Schema.Struct({ + imageUrl: Schema.String, + type: Schema.Literal("inputImage").annotate({ + title: "InputImageDynamicToolCallOutputContentItemType", + }), + }).annotate({ title: "InputImageDynamicToolCallOutputContentItem" }), + ], + { mode: "oneOf" }, +); + +export type V2ThreadRollbackResponse__DynamicToolCallStatus = "inProgress" | "completed" | "failed"; +export const V2ThreadRollbackResponse__DynamicToolCallStatus = Schema.Literals([ + "inProgress", + "completed", + "failed", +]); + +export type V2ThreadRollbackResponse__GitInfo = { + readonly branch?: string | null; + readonly originUrl?: string | null; + readonly sha?: string | null; +}; +export const V2ThreadRollbackResponse__GitInfo = Schema.Struct({ + branch: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + originUrl: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + sha: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), +}); + +export type V2ThreadRollbackResponse__HookPromptFragment = { + readonly hookRunId: string; + readonly text: string; +}; +export const V2ThreadRollbackResponse__HookPromptFragment = Schema.Struct({ + hookRunId: Schema.String, + text: Schema.String, +}); + +export type V2ThreadRollbackResponse__McpToolCallError = { readonly message: string }; +export const V2ThreadRollbackResponse__McpToolCallError = Schema.Struct({ message: Schema.String }); + +export type V2ThreadRollbackResponse__McpToolCallResult = { + readonly _meta?: unknown; + readonly content: ReadonlyArray; + readonly structuredContent?: unknown; +}; +export const V2ThreadRollbackResponse__McpToolCallResult = Schema.Struct({ + _meta: Schema.optionalKey(Schema.Unknown), + content: Schema.Array(Schema.Unknown), + structuredContent: Schema.optionalKey(Schema.Unknown), +}); + +export type V2ThreadRollbackResponse__McpToolCallStatus = "inProgress" | "completed" | "failed"; +export const V2ThreadRollbackResponse__McpToolCallStatus = Schema.Literals([ + "inProgress", + "completed", + "failed", +]); + +export type V2ThreadRollbackResponse__MemoryCitationEntry = { + readonly lineEnd: number; + readonly lineStart: number; + readonly note: string; + readonly path: string; +}; +export const V2ThreadRollbackResponse__MemoryCitationEntry = Schema.Struct({ + lineEnd: Schema.Number.annotate({ format: "uint32" }) + .check(Schema.isInt()) + .check(Schema.isGreaterThanOrEqualTo(0)), + lineStart: Schema.Number.annotate({ format: "uint32" }) + .check(Schema.isInt()) + .check(Schema.isGreaterThanOrEqualTo(0)), + note: Schema.String, + path: Schema.String, +}); + +export type V2ThreadRollbackResponse__MessagePhase = "commentary" | "final_answer"; +export const V2ThreadRollbackResponse__MessagePhase = Schema.Literals([ + "commentary", + "final_answer", +]).annotate({ + description: + 'Classifies an assistant message as interim commentary or final answer text.\n\nProviders do not emit this consistently, so callers must treat `None` as "phase unknown" and keep compatibility behavior for legacy models.', +}); + +export type V2ThreadRollbackResponse__NonSteerableTurnKind = "review" | "compact"; +export const V2ThreadRollbackResponse__NonSteerableTurnKind = Schema.Literals([ + "review", + "compact", +]); + +export type V2ThreadRollbackResponse__PatchApplyStatus = + | "inProgress" + | "completed" + | "failed" + | "declined"; +export const V2ThreadRollbackResponse__PatchApplyStatus = Schema.Literals([ + "inProgress", + "completed", + "failed", + "declined", +]); + +export type V2ThreadRollbackResponse__PatchChangeKind = + | { readonly type: "add" } + | { readonly type: "delete" } + | { readonly move_path?: string | null; readonly type: "update" }; +export const V2ThreadRollbackResponse__PatchChangeKind = Schema.Union( + [ + Schema.Struct({ + type: Schema.Literal("add").annotate({ title: "AddPatchChangeKindType" }), + }).annotate({ title: "AddPatchChangeKind" }), + Schema.Struct({ + type: Schema.Literal("delete").annotate({ title: "DeletePatchChangeKindType" }), + }).annotate({ title: "DeletePatchChangeKind" }), + Schema.Struct({ + move_path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + type: Schema.Literal("update").annotate({ title: "UpdatePatchChangeKindType" }), + }).annotate({ title: "UpdatePatchChangeKind" }), + ], + { mode: "oneOf" }, +); + +export type V2ThreadRollbackResponse__ReasoningEffort = + | "none" + | "minimal" + | "low" + | "medium" + | "high" + | "xhigh"; +export const V2ThreadRollbackResponse__ReasoningEffort = Schema.Literals([ + "none", + "minimal", + "low", + "medium", + "high", + "xhigh", +]).annotate({ + description: + "See https://platform.openai.com/docs/guides/reasoning?api-mode=responses#get-started-with-reasoning", +}); + +export type V2ThreadRollbackResponse__TextElement = { + readonly byteRange: { readonly end: number; readonly start: number }; + readonly placeholder?: string | null; +}; +export const V2ThreadRollbackResponse__TextElement = Schema.Struct({ + byteRange: Schema.Struct({ + end: Schema.Number.annotate({ format: "uint" }) + .check(Schema.isInt()) + .check(Schema.isGreaterThanOrEqualTo(0)), + start: Schema.Number.annotate({ format: "uint" }) + .check(Schema.isInt()) + .check(Schema.isGreaterThanOrEqualTo(0)), + }).annotate({ + description: "Byte range in the parent `text` buffer that this element occupies.", + }), + placeholder: Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + description: "Optional human-readable placeholder for the element, displayed in the UI.", + }), + Schema.Null, + ]), + ), +}); + +export type V2ThreadRollbackResponse__ThreadActiveFlag = "waitingOnApproval" | "waitingOnUserInput"; +export const V2ThreadRollbackResponse__ThreadActiveFlag = Schema.Literals([ + "waitingOnApproval", + "waitingOnUserInput", +]); + +export type V2ThreadRollbackResponse__ThreadId = string; +export const V2ThreadRollbackResponse__ThreadId = Schema.String; + +export type V2ThreadRollbackResponse__TurnStatus = + | "completed" + | "interrupted" + | "failed" + | "inProgress"; +export const V2ThreadRollbackResponse__TurnStatus = Schema.Literals([ + "completed", + "interrupted", + "failed", + "inProgress", +]); + +export type V2ThreadRollbackResponse__WebSearchAction = + | { + readonly queries?: ReadonlyArray | null; + readonly query?: string | null; + readonly type: "search"; + } + | { readonly type: "openPage"; readonly url?: string | null } + | { readonly pattern?: string | null; readonly type: "findInPage"; readonly url?: string | null } + | { readonly type: "other" }; +export const V2ThreadRollbackResponse__WebSearchAction = Schema.Union( + [ + Schema.Struct({ + queries: Schema.optionalKey(Schema.Union([Schema.Array(Schema.String), Schema.Null])), + query: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + type: Schema.Literal("search").annotate({ title: "SearchWebSearchActionType" }), + }).annotate({ title: "SearchWebSearchAction" }), + Schema.Struct({ + type: Schema.Literal("openPage").annotate({ title: "OpenPageWebSearchActionType" }), + url: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + }).annotate({ title: "OpenPageWebSearchAction" }), + Schema.Struct({ + pattern: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + type: Schema.Literal("findInPage").annotate({ title: "FindInPageWebSearchActionType" }), + url: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + }).annotate({ title: "FindInPageWebSearchAction" }), + Schema.Struct({ + type: Schema.Literal("other").annotate({ title: "OtherWebSearchActionType" }), + }).annotate({ title: "OtherWebSearchAction" }), + ], + { mode: "oneOf" }, +); + +export type V2ThreadStartedNotification__AgentPath = string; +export const V2ThreadStartedNotification__AgentPath = Schema.String; + +export type V2ThreadStartedNotification__CollabAgentStatus = + | "pendingInit" + | "running" + | "interrupted" + | "completed" + | "errored" + | "shutdown" + | "notFound"; +export const V2ThreadStartedNotification__CollabAgentStatus = Schema.Literals([ + "pendingInit", + "running", + "interrupted", + "completed", + "errored", + "shutdown", + "notFound", +]); + +export type V2ThreadStartedNotification__CommandAction = + | { + readonly command: string; + readonly name: string; + readonly path: string; + readonly type: "read"; + } + | { readonly command: string; readonly path?: string | null; readonly type: "listFiles" } + | { + readonly command: string; + readonly path?: string | null; + readonly query?: string | null; + readonly type: "search"; + } + | { readonly command: string; readonly type: "unknown" }; +export const V2ThreadStartedNotification__CommandAction = Schema.Union( + [ + Schema.Struct({ + command: Schema.String, + name: Schema.String, + path: Schema.String, + type: Schema.Literal("read").annotate({ title: "ReadCommandActionType" }), + }).annotate({ title: "ReadCommandAction" }), + Schema.Struct({ + command: Schema.String, + path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + type: Schema.Literal("listFiles").annotate({ title: "ListFilesCommandActionType" }), + }).annotate({ title: "ListFilesCommandAction" }), + Schema.Struct({ + command: Schema.String, + path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + query: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + type: Schema.Literal("search").annotate({ title: "SearchCommandActionType" }), + }).annotate({ title: "SearchCommandAction" }), + Schema.Struct({ + command: Schema.String, + type: Schema.Literal("unknown").annotate({ title: "UnknownCommandActionType" }), + }).annotate({ title: "UnknownCommandAction" }), + ], + { mode: "oneOf" }, +); + +export type V2ThreadStartedNotification__CommandExecutionStatus = + | "inProgress" + | "completed" + | "failed" + | "declined"; +export const V2ThreadStartedNotification__CommandExecutionStatus = Schema.Literals([ + "inProgress", + "completed", + "failed", + "declined", +]); + +export type V2ThreadStartedNotification__DynamicToolCallOutputContentItem = + | { readonly text: string; readonly type: "inputText" } + | { readonly imageUrl: string; readonly type: "inputImage" }; +export const V2ThreadStartedNotification__DynamicToolCallOutputContentItem = Schema.Union( + [ + Schema.Struct({ + text: Schema.String, + type: Schema.Literal("inputText").annotate({ + title: "InputTextDynamicToolCallOutputContentItemType", + }), + }).annotate({ title: "InputTextDynamicToolCallOutputContentItem" }), + Schema.Struct({ + imageUrl: Schema.String, + type: Schema.Literal("inputImage").annotate({ + title: "InputImageDynamicToolCallOutputContentItemType", + }), + }).annotate({ title: "InputImageDynamicToolCallOutputContentItem" }), + ], + { mode: "oneOf" }, +); + +export type V2ThreadStartedNotification__DynamicToolCallStatus = + | "inProgress" + | "completed" + | "failed"; +export const V2ThreadStartedNotification__DynamicToolCallStatus = Schema.Literals([ + "inProgress", + "completed", + "failed", +]); + +export type V2ThreadStartedNotification__GitInfo = { + readonly branch?: string | null; + readonly originUrl?: string | null; + readonly sha?: string | null; +}; +export const V2ThreadStartedNotification__GitInfo = Schema.Struct({ + branch: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + originUrl: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + sha: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), +}); + +export type V2ThreadStartedNotification__HookPromptFragment = { + readonly hookRunId: string; + readonly text: string; +}; +export const V2ThreadStartedNotification__HookPromptFragment = Schema.Struct({ + hookRunId: Schema.String, + text: Schema.String, +}); + +export type V2ThreadStartedNotification__McpToolCallError = { readonly message: string }; +export const V2ThreadStartedNotification__McpToolCallError = Schema.Struct({ + message: Schema.String, +}); + +export type V2ThreadStartedNotification__McpToolCallResult = { + readonly _meta?: unknown; + readonly content: ReadonlyArray; + readonly structuredContent?: unknown; +}; +export const V2ThreadStartedNotification__McpToolCallResult = Schema.Struct({ + _meta: Schema.optionalKey(Schema.Unknown), + content: Schema.Array(Schema.Unknown), + structuredContent: Schema.optionalKey(Schema.Unknown), +}); + +export type V2ThreadStartedNotification__McpToolCallStatus = "inProgress" | "completed" | "failed"; +export const V2ThreadStartedNotification__McpToolCallStatus = Schema.Literals([ + "inProgress", + "completed", + "failed", +]); + +export type V2ThreadStartedNotification__MemoryCitationEntry = { + readonly lineEnd: number; + readonly lineStart: number; + readonly note: string; + readonly path: string; +}; +export const V2ThreadStartedNotification__MemoryCitationEntry = Schema.Struct({ + lineEnd: Schema.Number.annotate({ format: "uint32" }) + .check(Schema.isInt()) + .check(Schema.isGreaterThanOrEqualTo(0)), + lineStart: Schema.Number.annotate({ format: "uint32" }) + .check(Schema.isInt()) + .check(Schema.isGreaterThanOrEqualTo(0)), + note: Schema.String, + path: Schema.String, +}); + +export type V2ThreadStartedNotification__MessagePhase = "commentary" | "final_answer"; +export const V2ThreadStartedNotification__MessagePhase = Schema.Literals([ + "commentary", + "final_answer", +]).annotate({ + description: + 'Classifies an assistant message as interim commentary or final answer text.\n\nProviders do not emit this consistently, so callers must treat `None` as "phase unknown" and keep compatibility behavior for legacy models.', +}); + +export type V2ThreadStartedNotification__NonSteerableTurnKind = "review" | "compact"; +export const V2ThreadStartedNotification__NonSteerableTurnKind = Schema.Literals([ + "review", + "compact", +]); + +export type V2ThreadStartedNotification__PatchApplyStatus = + | "inProgress" + | "completed" + | "failed" + | "declined"; +export const V2ThreadStartedNotification__PatchApplyStatus = Schema.Literals([ + "inProgress", + "completed", + "failed", + "declined", +]); + +export type V2ThreadStartedNotification__PatchChangeKind = + | { readonly type: "add" } + | { readonly type: "delete" } + | { readonly move_path?: string | null; readonly type: "update" }; +export const V2ThreadStartedNotification__PatchChangeKind = Schema.Union( + [ + Schema.Struct({ + type: Schema.Literal("add").annotate({ title: "AddPatchChangeKindType" }), + }).annotate({ title: "AddPatchChangeKind" }), + Schema.Struct({ + type: Schema.Literal("delete").annotate({ title: "DeletePatchChangeKindType" }), + }).annotate({ title: "DeletePatchChangeKind" }), + Schema.Struct({ + move_path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + type: Schema.Literal("update").annotate({ title: "UpdatePatchChangeKindType" }), + }).annotate({ title: "UpdatePatchChangeKind" }), + ], + { mode: "oneOf" }, +); + +export type V2ThreadStartedNotification__ReasoningEffort = + | "none" + | "minimal" + | "low" + | "medium" + | "high" + | "xhigh"; +export const V2ThreadStartedNotification__ReasoningEffort = Schema.Literals([ + "none", + "minimal", + "low", + "medium", + "high", + "xhigh", +]).annotate({ + description: + "See https://platform.openai.com/docs/guides/reasoning?api-mode=responses#get-started-with-reasoning", +}); + +export type V2ThreadStartedNotification__TextElement = { + readonly byteRange: { readonly end: number; readonly start: number }; + readonly placeholder?: string | null; +}; +export const V2ThreadStartedNotification__TextElement = Schema.Struct({ + byteRange: Schema.Struct({ + end: Schema.Number.annotate({ format: "uint" }) + .check(Schema.isInt()) + .check(Schema.isGreaterThanOrEqualTo(0)), + start: Schema.Number.annotate({ format: "uint" }) + .check(Schema.isInt()) + .check(Schema.isGreaterThanOrEqualTo(0)), + }).annotate({ + description: "Byte range in the parent `text` buffer that this element occupies.", + }), + placeholder: Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + description: "Optional human-readable placeholder for the element, displayed in the UI.", + }), + Schema.Null, + ]), + ), +}); + +export type V2ThreadStartedNotification__ThreadActiveFlag = + | "waitingOnApproval" + | "waitingOnUserInput"; +export const V2ThreadStartedNotification__ThreadActiveFlag = Schema.Literals([ + "waitingOnApproval", + "waitingOnUserInput", +]); + +export type V2ThreadStartedNotification__ThreadId = string; +export const V2ThreadStartedNotification__ThreadId = Schema.String; + +export type V2ThreadStartedNotification__TurnStatus = + | "completed" + | "interrupted" + | "failed" + | "inProgress"; +export const V2ThreadStartedNotification__TurnStatus = Schema.Literals([ + "completed", + "interrupted", + "failed", + "inProgress", +]); + +export type V2ThreadStartedNotification__WebSearchAction = + | { + readonly queries?: ReadonlyArray | null; + readonly query?: string | null; + readonly type: "search"; + } + | { readonly type: "openPage"; readonly url?: string | null } + | { readonly pattern?: string | null; readonly type: "findInPage"; readonly url?: string | null } + | { readonly type: "other" }; +export const V2ThreadStartedNotification__WebSearchAction = Schema.Union( + [ + Schema.Struct({ + queries: Schema.optionalKey(Schema.Union([Schema.Array(Schema.String), Schema.Null])), + query: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + type: Schema.Literal("search").annotate({ title: "SearchWebSearchActionType" }), + }).annotate({ title: "SearchWebSearchAction" }), + Schema.Struct({ + type: Schema.Literal("openPage").annotate({ title: "OpenPageWebSearchActionType" }), + url: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + }).annotate({ title: "OpenPageWebSearchAction" }), + Schema.Struct({ + pattern: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + type: Schema.Literal("findInPage").annotate({ title: "FindInPageWebSearchActionType" }), + url: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + }).annotate({ title: "FindInPageWebSearchAction" }), + Schema.Struct({ + type: Schema.Literal("other").annotate({ title: "OtherWebSearchActionType" }), + }).annotate({ title: "OtherWebSearchAction" }), + ], + { mode: "oneOf" }, +); + +export type V2ThreadStartParams__ApprovalsReviewer = "user" | "guardian_subagent"; +export const V2ThreadStartParams__ApprovalsReviewer = Schema.Literals([ + "user", + "guardian_subagent", +]).annotate({ + description: + "Configures who approval requests are routed to for review. Examples include sandbox escapes, blocked network access, MCP approval prompts, and ARC escalations. Defaults to `user`. `guardian_subagent` uses a carefully prompted subagent to gather relevant context and apply a risk-based decision framework before approving or denying the request.", +}); + +export type V2ThreadStartParams__AskForApproval = + | "untrusted" + | "on-failure" + | "on-request" + | "never" + | { + readonly granular: { + readonly mcp_elicitations: boolean; + readonly request_permissions?: boolean; + readonly rules: boolean; + readonly sandbox_approval: boolean; + readonly skill_approval?: boolean; + }; + }; +export const V2ThreadStartParams__AskForApproval = Schema.Union( + [ + Schema.Literals(["untrusted", "on-failure", "on-request", "never"]), + Schema.Struct({ + granular: Schema.Struct({ + mcp_elicitations: Schema.Boolean, + request_permissions: Schema.optionalKey(Schema.Boolean.annotate({ default: false })), + rules: Schema.Boolean, + sandbox_approval: Schema.Boolean, + skill_approval: Schema.optionalKey(Schema.Boolean.annotate({ default: false })), + }), + }).annotate({ title: "GranularAskForApproval" }), + ], + { mode: "oneOf" }, +); + +export type V2ThreadStartParams__Personality = "none" | "friendly" | "pragmatic"; +export const V2ThreadStartParams__Personality = Schema.Literals(["none", "friendly", "pragmatic"]); + +export type V2ThreadStartParams__SandboxMode = + | "read-only" + | "workspace-write" + | "danger-full-access"; +export const V2ThreadStartParams__SandboxMode = Schema.Literals([ + "read-only", + "workspace-write", + "danger-full-access", +]); + +export type V2ThreadStartParams__ServiceTier = "fast" | "flex"; +export const V2ThreadStartParams__ServiceTier = Schema.Literals(["fast", "flex"]); + +export type V2ThreadStartParams__ThreadStartSource = "startup" | "clear"; +export const V2ThreadStartParams__ThreadStartSource = Schema.Literals(["startup", "clear"]); + +export type V2ThreadStartResponse__AbsolutePathBuf = string; +export const V2ThreadStartResponse__AbsolutePathBuf = Schema.String.annotate({ + description: + "A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\n\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.", +}); + +export type V2ThreadStartResponse__AgentPath = string; +export const V2ThreadStartResponse__AgentPath = Schema.String; + +export type V2ThreadStartResponse__AskForApproval = + | "untrusted" + | "on-failure" + | "on-request" + | "never" + | { + readonly granular: { + readonly mcp_elicitations: boolean; + readonly request_permissions?: boolean; + readonly rules: boolean; + readonly sandbox_approval: boolean; + readonly skill_approval?: boolean; + }; + }; +export const V2ThreadStartResponse__AskForApproval = Schema.Union( + [ + Schema.Literals(["untrusted", "on-failure", "on-request", "never"]), + Schema.Struct({ + granular: Schema.Struct({ + mcp_elicitations: Schema.Boolean, + request_permissions: Schema.optionalKey(Schema.Boolean.annotate({ default: false })), + rules: Schema.Boolean, + sandbox_approval: Schema.Boolean, + skill_approval: Schema.optionalKey(Schema.Boolean.annotate({ default: false })), + }), + }).annotate({ title: "GranularAskForApproval" }), + ], + { mode: "oneOf" }, +); + +export type V2ThreadStartResponse__CollabAgentStatus = + | "pendingInit" + | "running" + | "interrupted" + | "completed" + | "errored" + | "shutdown" + | "notFound"; +export const V2ThreadStartResponse__CollabAgentStatus = Schema.Literals([ + "pendingInit", + "running", + "interrupted", + "completed", + "errored", + "shutdown", + "notFound", +]); + +export type V2ThreadStartResponse__CommandAction = + | { + readonly command: string; + readonly name: string; + readonly path: string; + readonly type: "read"; + } + | { readonly command: string; readonly path?: string | null; readonly type: "listFiles" } + | { + readonly command: string; + readonly path?: string | null; + readonly query?: string | null; + readonly type: "search"; + } + | { readonly command: string; readonly type: "unknown" }; +export const V2ThreadStartResponse__CommandAction = Schema.Union( + [ + Schema.Struct({ + command: Schema.String, + name: Schema.String, + path: Schema.String, + type: Schema.Literal("read").annotate({ title: "ReadCommandActionType" }), + }).annotate({ title: "ReadCommandAction" }), + Schema.Struct({ + command: Schema.String, + path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + type: Schema.Literal("listFiles").annotate({ title: "ListFilesCommandActionType" }), + }).annotate({ title: "ListFilesCommandAction" }), + Schema.Struct({ + command: Schema.String, + path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + query: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + type: Schema.Literal("search").annotate({ title: "SearchCommandActionType" }), + }).annotate({ title: "SearchCommandAction" }), + Schema.Struct({ + command: Schema.String, + type: Schema.Literal("unknown").annotate({ title: "UnknownCommandActionType" }), + }).annotate({ title: "UnknownCommandAction" }), + ], + { mode: "oneOf" }, +); + +export type V2ThreadStartResponse__CommandExecutionStatus = + | "inProgress" + | "completed" + | "failed" + | "declined"; +export const V2ThreadStartResponse__CommandExecutionStatus = Schema.Literals([ + "inProgress", + "completed", + "failed", + "declined", +]); + +export type V2ThreadStartResponse__DynamicToolCallOutputContentItem = + | { readonly text: string; readonly type: "inputText" } + | { readonly imageUrl: string; readonly type: "inputImage" }; +export const V2ThreadStartResponse__DynamicToolCallOutputContentItem = Schema.Union( + [ + Schema.Struct({ + text: Schema.String, + type: Schema.Literal("inputText").annotate({ + title: "InputTextDynamicToolCallOutputContentItemType", + }), + }).annotate({ title: "InputTextDynamicToolCallOutputContentItem" }), + Schema.Struct({ + imageUrl: Schema.String, + type: Schema.Literal("inputImage").annotate({ + title: "InputImageDynamicToolCallOutputContentItemType", + }), + }).annotate({ title: "InputImageDynamicToolCallOutputContentItem" }), + ], + { mode: "oneOf" }, +); + +export type V2ThreadStartResponse__DynamicToolCallStatus = "inProgress" | "completed" | "failed"; +export const V2ThreadStartResponse__DynamicToolCallStatus = Schema.Literals([ + "inProgress", + "completed", + "failed", +]); + +export type V2ThreadStartResponse__GitInfo = { + readonly branch?: string | null; + readonly originUrl?: string | null; + readonly sha?: string | null; +}; +export const V2ThreadStartResponse__GitInfo = Schema.Struct({ + branch: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + originUrl: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + sha: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), +}); + +export type V2ThreadStartResponse__HookPromptFragment = { + readonly hookRunId: string; + readonly text: string; +}; +export const V2ThreadStartResponse__HookPromptFragment = Schema.Struct({ + hookRunId: Schema.String, + text: Schema.String, +}); + +export type V2ThreadStartResponse__McpToolCallError = { readonly message: string }; +export const V2ThreadStartResponse__McpToolCallError = Schema.Struct({ message: Schema.String }); + +export type V2ThreadStartResponse__McpToolCallResult = { + readonly _meta?: unknown; + readonly content: ReadonlyArray; + readonly structuredContent?: unknown; +}; +export const V2ThreadStartResponse__McpToolCallResult = Schema.Struct({ + _meta: Schema.optionalKey(Schema.Unknown), + content: Schema.Array(Schema.Unknown), + structuredContent: Schema.optionalKey(Schema.Unknown), +}); + +export type V2ThreadStartResponse__McpToolCallStatus = "inProgress" | "completed" | "failed"; +export const V2ThreadStartResponse__McpToolCallStatus = Schema.Literals([ + "inProgress", + "completed", + "failed", +]); + +export type V2ThreadStartResponse__MemoryCitationEntry = { + readonly lineEnd: number; + readonly lineStart: number; + readonly note: string; + readonly path: string; +}; +export const V2ThreadStartResponse__MemoryCitationEntry = Schema.Struct({ + lineEnd: Schema.Number.annotate({ format: "uint32" }) + .check(Schema.isInt()) + .check(Schema.isGreaterThanOrEqualTo(0)), + lineStart: Schema.Number.annotate({ format: "uint32" }) + .check(Schema.isInt()) + .check(Schema.isGreaterThanOrEqualTo(0)), + note: Schema.String, + path: Schema.String, +}); + +export type V2ThreadStartResponse__MessagePhase = "commentary" | "final_answer"; +export const V2ThreadStartResponse__MessagePhase = Schema.Literals([ + "commentary", + "final_answer", +]).annotate({ + description: + 'Classifies an assistant message as interim commentary or final answer text.\n\nProviders do not emit this consistently, so callers must treat `None` as "phase unknown" and keep compatibility behavior for legacy models.', +}); + +export type V2ThreadStartResponse__NonSteerableTurnKind = "review" | "compact"; +export const V2ThreadStartResponse__NonSteerableTurnKind = Schema.Literals(["review", "compact"]); + +export type V2ThreadStartResponse__PatchApplyStatus = + | "inProgress" + | "completed" + | "failed" + | "declined"; +export const V2ThreadStartResponse__PatchApplyStatus = Schema.Literals([ + "inProgress", + "completed", + "failed", + "declined", +]); + +export type V2ThreadStartResponse__PatchChangeKind = + | { readonly type: "add" } + | { readonly type: "delete" } + | { readonly move_path?: string | null; readonly type: "update" }; +export const V2ThreadStartResponse__PatchChangeKind = Schema.Union( + [ + Schema.Struct({ + type: Schema.Literal("add").annotate({ title: "AddPatchChangeKindType" }), + }).annotate({ title: "AddPatchChangeKind" }), + Schema.Struct({ + type: Schema.Literal("delete").annotate({ title: "DeletePatchChangeKindType" }), + }).annotate({ title: "DeletePatchChangeKind" }), + Schema.Struct({ + move_path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + type: Schema.Literal("update").annotate({ title: "UpdatePatchChangeKindType" }), + }).annotate({ title: "UpdatePatchChangeKind" }), + ], + { mode: "oneOf" }, +); + +export type V2ThreadStartResponse__ReasoningEffort = + | "none" + | "minimal" + | "low" + | "medium" + | "high" + | "xhigh"; +export const V2ThreadStartResponse__ReasoningEffort = Schema.Literals([ + "none", + "minimal", + "low", + "medium", + "high", + "xhigh", +]).annotate({ + description: + "See https://platform.openai.com/docs/guides/reasoning?api-mode=responses#get-started-with-reasoning", +}); + +export type V2ThreadStartResponse__ServiceTier = "fast" | "flex"; +export const V2ThreadStartResponse__ServiceTier = Schema.Literals(["fast", "flex"]); + +export type V2ThreadStartResponse__TextElement = { + readonly byteRange: { readonly end: number; readonly start: number }; + readonly placeholder?: string | null; +}; +export const V2ThreadStartResponse__TextElement = Schema.Struct({ + byteRange: Schema.Struct({ + end: Schema.Number.annotate({ format: "uint" }) + .check(Schema.isInt()) + .check(Schema.isGreaterThanOrEqualTo(0)), + start: Schema.Number.annotate({ format: "uint" }) + .check(Schema.isInt()) + .check(Schema.isGreaterThanOrEqualTo(0)), + }).annotate({ + description: "Byte range in the parent `text` buffer that this element occupies.", + }), + placeholder: Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + description: "Optional human-readable placeholder for the element, displayed in the UI.", + }), + Schema.Null, + ]), + ), +}); + +export type V2ThreadStartResponse__ThreadActiveFlag = "waitingOnApproval" | "waitingOnUserInput"; +export const V2ThreadStartResponse__ThreadActiveFlag = Schema.Literals([ + "waitingOnApproval", + "waitingOnUserInput", +]); + +export type V2ThreadStartResponse__ThreadId = string; +export const V2ThreadStartResponse__ThreadId = Schema.String; + +export type V2ThreadStartResponse__TurnStatus = + | "completed" + | "interrupted" + | "failed" + | "inProgress"; +export const V2ThreadStartResponse__TurnStatus = Schema.Literals([ + "completed", + "interrupted", + "failed", + "inProgress", +]); + +export type V2ThreadStartResponse__WebSearchAction = + | { + readonly queries?: ReadonlyArray | null; + readonly query?: string | null; + readonly type: "search"; + } + | { readonly type: "openPage"; readonly url?: string | null } + | { readonly pattern?: string | null; readonly type: "findInPage"; readonly url?: string | null } + | { readonly type: "other" }; +export const V2ThreadStartResponse__WebSearchAction = Schema.Union( + [ + Schema.Struct({ + queries: Schema.optionalKey(Schema.Union([Schema.Array(Schema.String), Schema.Null])), + query: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + type: Schema.Literal("search").annotate({ title: "SearchWebSearchActionType" }), + }).annotate({ title: "SearchWebSearchAction" }), + Schema.Struct({ + type: Schema.Literal("openPage").annotate({ title: "OpenPageWebSearchActionType" }), + url: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + }).annotate({ title: "OpenPageWebSearchAction" }), + Schema.Struct({ + pattern: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + type: Schema.Literal("findInPage").annotate({ title: "FindInPageWebSearchActionType" }), + url: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + }).annotate({ title: "FindInPageWebSearchAction" }), + Schema.Struct({ + type: Schema.Literal("other").annotate({ title: "OtherWebSearchActionType" }), + }).annotate({ title: "OtherWebSearchAction" }), + ], + { mode: "oneOf" }, +); + +export type V2ThreadStatusChangedNotification__ThreadActiveFlag = + | "waitingOnApproval" + | "waitingOnUserInput"; +export const V2ThreadStatusChangedNotification__ThreadActiveFlag = Schema.Literals([ + "waitingOnApproval", + "waitingOnUserInput", +]); + +export type V2ThreadTokenUsageUpdatedNotification__TokenUsageBreakdown = { + readonly cachedInputTokens: number; + readonly inputTokens: number; + readonly outputTokens: number; + readonly reasoningOutputTokens: number; + readonly totalTokens: number; +}; +export const V2ThreadTokenUsageUpdatedNotification__TokenUsageBreakdown = Schema.Struct({ + cachedInputTokens: Schema.Number.annotate({ format: "int64" }).check(Schema.isInt()), + inputTokens: Schema.Number.annotate({ format: "int64" }).check(Schema.isInt()), + outputTokens: Schema.Number.annotate({ format: "int64" }).check(Schema.isInt()), + reasoningOutputTokens: Schema.Number.annotate({ format: "int64" }).check(Schema.isInt()), + totalTokens: Schema.Number.annotate({ format: "int64" }).check(Schema.isInt()), +}); + +export type V2ThreadUnarchiveResponse__AgentPath = string; +export const V2ThreadUnarchiveResponse__AgentPath = Schema.String; + +export type V2ThreadUnarchiveResponse__CollabAgentStatus = + | "pendingInit" + | "running" + | "interrupted" + | "completed" + | "errored" + | "shutdown" + | "notFound"; +export const V2ThreadUnarchiveResponse__CollabAgentStatus = Schema.Literals([ + "pendingInit", + "running", + "interrupted", + "completed", + "errored", + "shutdown", + "notFound", +]); + +export type V2ThreadUnarchiveResponse__CommandAction = + | { + readonly command: string; + readonly name: string; + readonly path: string; + readonly type: "read"; + } + | { readonly command: string; readonly path?: string | null; readonly type: "listFiles" } + | { + readonly command: string; + readonly path?: string | null; + readonly query?: string | null; + readonly type: "search"; + } + | { readonly command: string; readonly type: "unknown" }; +export const V2ThreadUnarchiveResponse__CommandAction = Schema.Union( + [ + Schema.Struct({ + command: Schema.String, + name: Schema.String, + path: Schema.String, + type: Schema.Literal("read").annotate({ title: "ReadCommandActionType" }), + }).annotate({ title: "ReadCommandAction" }), + Schema.Struct({ + command: Schema.String, + path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + type: Schema.Literal("listFiles").annotate({ title: "ListFilesCommandActionType" }), + }).annotate({ title: "ListFilesCommandAction" }), + Schema.Struct({ + command: Schema.String, + path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + query: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + type: Schema.Literal("search").annotate({ title: "SearchCommandActionType" }), + }).annotate({ title: "SearchCommandAction" }), + Schema.Struct({ + command: Schema.String, + type: Schema.Literal("unknown").annotate({ title: "UnknownCommandActionType" }), + }).annotate({ title: "UnknownCommandAction" }), + ], + { mode: "oneOf" }, +); + +export type V2ThreadUnarchiveResponse__CommandExecutionStatus = + | "inProgress" + | "completed" + | "failed" + | "declined"; +export const V2ThreadUnarchiveResponse__CommandExecutionStatus = Schema.Literals([ + "inProgress", + "completed", + "failed", + "declined", +]); + +export type V2ThreadUnarchiveResponse__DynamicToolCallOutputContentItem = + | { readonly text: string; readonly type: "inputText" } + | { readonly imageUrl: string; readonly type: "inputImage" }; +export const V2ThreadUnarchiveResponse__DynamicToolCallOutputContentItem = Schema.Union( + [ + Schema.Struct({ + text: Schema.String, + type: Schema.Literal("inputText").annotate({ + title: "InputTextDynamicToolCallOutputContentItemType", + }), + }).annotate({ title: "InputTextDynamicToolCallOutputContentItem" }), + Schema.Struct({ + imageUrl: Schema.String, + type: Schema.Literal("inputImage").annotate({ + title: "InputImageDynamicToolCallOutputContentItemType", + }), + }).annotate({ title: "InputImageDynamicToolCallOutputContentItem" }), + ], + { mode: "oneOf" }, +); + +export type V2ThreadUnarchiveResponse__DynamicToolCallStatus = + | "inProgress" + | "completed" + | "failed"; +export const V2ThreadUnarchiveResponse__DynamicToolCallStatus = Schema.Literals([ + "inProgress", + "completed", + "failed", +]); + +export type V2ThreadUnarchiveResponse__GitInfo = { + readonly branch?: string | null; + readonly originUrl?: string | null; + readonly sha?: string | null; +}; +export const V2ThreadUnarchiveResponse__GitInfo = Schema.Struct({ + branch: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + originUrl: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + sha: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), +}); + +export type V2ThreadUnarchiveResponse__HookPromptFragment = { + readonly hookRunId: string; + readonly text: string; +}; +export const V2ThreadUnarchiveResponse__HookPromptFragment = Schema.Struct({ + hookRunId: Schema.String, + text: Schema.String, +}); + +export type V2ThreadUnarchiveResponse__McpToolCallError = { readonly message: string }; +export const V2ThreadUnarchiveResponse__McpToolCallError = Schema.Struct({ + message: Schema.String, +}); + +export type V2ThreadUnarchiveResponse__McpToolCallResult = { + readonly _meta?: unknown; + readonly content: ReadonlyArray; + readonly structuredContent?: unknown; +}; +export const V2ThreadUnarchiveResponse__McpToolCallResult = Schema.Struct({ + _meta: Schema.optionalKey(Schema.Unknown), + content: Schema.Array(Schema.Unknown), + structuredContent: Schema.optionalKey(Schema.Unknown), +}); + +export type V2ThreadUnarchiveResponse__McpToolCallStatus = "inProgress" | "completed" | "failed"; +export const V2ThreadUnarchiveResponse__McpToolCallStatus = Schema.Literals([ + "inProgress", + "completed", + "failed", +]); + +export type V2ThreadUnarchiveResponse__MemoryCitationEntry = { + readonly lineEnd: number; + readonly lineStart: number; + readonly note: string; + readonly path: string; +}; +export const V2ThreadUnarchiveResponse__MemoryCitationEntry = Schema.Struct({ + lineEnd: Schema.Number.annotate({ format: "uint32" }) + .check(Schema.isInt()) + .check(Schema.isGreaterThanOrEqualTo(0)), + lineStart: Schema.Number.annotate({ format: "uint32" }) + .check(Schema.isInt()) + .check(Schema.isGreaterThanOrEqualTo(0)), + note: Schema.String, + path: Schema.String, +}); + +export type V2ThreadUnarchiveResponse__MessagePhase = "commentary" | "final_answer"; +export const V2ThreadUnarchiveResponse__MessagePhase = Schema.Literals([ + "commentary", + "final_answer", +]).annotate({ + description: + 'Classifies an assistant message as interim commentary or final answer text.\n\nProviders do not emit this consistently, so callers must treat `None` as "phase unknown" and keep compatibility behavior for legacy models.', +}); + +export type V2ThreadUnarchiveResponse__NonSteerableTurnKind = "review" | "compact"; +export const V2ThreadUnarchiveResponse__NonSteerableTurnKind = Schema.Literals([ + "review", + "compact", +]); + +export type V2ThreadUnarchiveResponse__PatchApplyStatus = + | "inProgress" + | "completed" + | "failed" + | "declined"; +export const V2ThreadUnarchiveResponse__PatchApplyStatus = Schema.Literals([ + "inProgress", + "completed", + "failed", + "declined", +]); + +export type V2ThreadUnarchiveResponse__PatchChangeKind = + | { readonly type: "add" } + | { readonly type: "delete" } + | { readonly move_path?: string | null; readonly type: "update" }; +export const V2ThreadUnarchiveResponse__PatchChangeKind = Schema.Union( + [ + Schema.Struct({ + type: Schema.Literal("add").annotate({ title: "AddPatchChangeKindType" }), + }).annotate({ title: "AddPatchChangeKind" }), + Schema.Struct({ + type: Schema.Literal("delete").annotate({ title: "DeletePatchChangeKindType" }), + }).annotate({ title: "DeletePatchChangeKind" }), + Schema.Struct({ + move_path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + type: Schema.Literal("update").annotate({ title: "UpdatePatchChangeKindType" }), + }).annotate({ title: "UpdatePatchChangeKind" }), + ], + { mode: "oneOf" }, +); + +export type V2ThreadUnarchiveResponse__ReasoningEffort = + | "none" + | "minimal" + | "low" + | "medium" + | "high" + | "xhigh"; +export const V2ThreadUnarchiveResponse__ReasoningEffort = Schema.Literals([ + "none", + "minimal", + "low", + "medium", + "high", + "xhigh", +]).annotate({ + description: + "See https://platform.openai.com/docs/guides/reasoning?api-mode=responses#get-started-with-reasoning", +}); + +export type V2ThreadUnarchiveResponse__TextElement = { + readonly byteRange: { readonly end: number; readonly start: number }; + readonly placeholder?: string | null; +}; +export const V2ThreadUnarchiveResponse__TextElement = Schema.Struct({ + byteRange: Schema.Struct({ + end: Schema.Number.annotate({ format: "uint" }) + .check(Schema.isInt()) + .check(Schema.isGreaterThanOrEqualTo(0)), + start: Schema.Number.annotate({ format: "uint" }) + .check(Schema.isInt()) + .check(Schema.isGreaterThanOrEqualTo(0)), + }).annotate({ + description: "Byte range in the parent `text` buffer that this element occupies.", + }), + placeholder: Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + description: "Optional human-readable placeholder for the element, displayed in the UI.", + }), + Schema.Null, + ]), + ), +}); + +export type V2ThreadUnarchiveResponse__ThreadActiveFlag = + | "waitingOnApproval" + | "waitingOnUserInput"; +export const V2ThreadUnarchiveResponse__ThreadActiveFlag = Schema.Literals([ + "waitingOnApproval", + "waitingOnUserInput", +]); + +export type V2ThreadUnarchiveResponse__ThreadId = string; +export const V2ThreadUnarchiveResponse__ThreadId = Schema.String; + +export type V2ThreadUnarchiveResponse__TurnStatus = + | "completed" + | "interrupted" + | "failed" + | "inProgress"; +export const V2ThreadUnarchiveResponse__TurnStatus = Schema.Literals([ + "completed", + "interrupted", + "failed", + "inProgress", +]); + +export type V2ThreadUnarchiveResponse__WebSearchAction = + | { + readonly queries?: ReadonlyArray | null; + readonly query?: string | null; + readonly type: "search"; + } + | { readonly type: "openPage"; readonly url?: string | null } + | { readonly pattern?: string | null; readonly type: "findInPage"; readonly url?: string | null } + | { readonly type: "other" }; +export const V2ThreadUnarchiveResponse__WebSearchAction = Schema.Union( + [ + Schema.Struct({ + queries: Schema.optionalKey(Schema.Union([Schema.Array(Schema.String), Schema.Null])), + query: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + type: Schema.Literal("search").annotate({ title: "SearchWebSearchActionType" }), + }).annotate({ title: "SearchWebSearchAction" }), + Schema.Struct({ + type: Schema.Literal("openPage").annotate({ title: "OpenPageWebSearchActionType" }), + url: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + }).annotate({ title: "OpenPageWebSearchAction" }), + Schema.Struct({ + pattern: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + type: Schema.Literal("findInPage").annotate({ title: "FindInPageWebSearchActionType" }), + url: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + }).annotate({ title: "FindInPageWebSearchAction" }), + Schema.Struct({ + type: Schema.Literal("other").annotate({ title: "OtherWebSearchActionType" }), + }).annotate({ title: "OtherWebSearchAction" }), + ], + { mode: "oneOf" }, +); + +export type V2ThreadUnsubscribeResponse__ThreadUnsubscribeStatus = + | "notLoaded" + | "notSubscribed" + | "unsubscribed"; +export const V2ThreadUnsubscribeResponse__ThreadUnsubscribeStatus = Schema.Literals([ + "notLoaded", + "notSubscribed", + "unsubscribed", +]); + +export type V2TurnCompletedNotification__CollabAgentStatus = + | "pendingInit" + | "running" + | "interrupted" + | "completed" + | "errored" + | "shutdown" + | "notFound"; +export const V2TurnCompletedNotification__CollabAgentStatus = Schema.Literals([ + "pendingInit", + "running", + "interrupted", + "completed", + "errored", + "shutdown", + "notFound", +]); + +export type V2TurnCompletedNotification__CommandAction = + | { + readonly command: string; + readonly name: string; + readonly path: string; + readonly type: "read"; + } + | { readonly command: string; readonly path?: string | null; readonly type: "listFiles" } + | { + readonly command: string; + readonly path?: string | null; + readonly query?: string | null; + readonly type: "search"; + } + | { readonly command: string; readonly type: "unknown" }; +export const V2TurnCompletedNotification__CommandAction = Schema.Union( + [ + Schema.Struct({ + command: Schema.String, + name: Schema.String, + path: Schema.String, + type: Schema.Literal("read").annotate({ title: "ReadCommandActionType" }), + }).annotate({ title: "ReadCommandAction" }), + Schema.Struct({ + command: Schema.String, + path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + type: Schema.Literal("listFiles").annotate({ title: "ListFilesCommandActionType" }), + }).annotate({ title: "ListFilesCommandAction" }), + Schema.Struct({ + command: Schema.String, + path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + query: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + type: Schema.Literal("search").annotate({ title: "SearchCommandActionType" }), + }).annotate({ title: "SearchCommandAction" }), + Schema.Struct({ + command: Schema.String, + type: Schema.Literal("unknown").annotate({ title: "UnknownCommandActionType" }), + }).annotate({ title: "UnknownCommandAction" }), + ], + { mode: "oneOf" }, +); + +export type V2TurnCompletedNotification__CommandExecutionStatus = + | "inProgress" + | "completed" + | "failed" + | "declined"; +export const V2TurnCompletedNotification__CommandExecutionStatus = Schema.Literals([ + "inProgress", + "completed", + "failed", + "declined", +]); + +export type V2TurnCompletedNotification__DynamicToolCallOutputContentItem = + | { readonly text: string; readonly type: "inputText" } + | { readonly imageUrl: string; readonly type: "inputImage" }; +export const V2TurnCompletedNotification__DynamicToolCallOutputContentItem = Schema.Union( + [ + Schema.Struct({ + text: Schema.String, + type: Schema.Literal("inputText").annotate({ + title: "InputTextDynamicToolCallOutputContentItemType", + }), + }).annotate({ title: "InputTextDynamicToolCallOutputContentItem" }), + Schema.Struct({ + imageUrl: Schema.String, + type: Schema.Literal("inputImage").annotate({ + title: "InputImageDynamicToolCallOutputContentItemType", + }), + }).annotate({ title: "InputImageDynamicToolCallOutputContentItem" }), + ], + { mode: "oneOf" }, +); + +export type V2TurnCompletedNotification__DynamicToolCallStatus = + | "inProgress" + | "completed" + | "failed"; +export const V2TurnCompletedNotification__DynamicToolCallStatus = Schema.Literals([ + "inProgress", + "completed", + "failed", +]); + +export type V2TurnCompletedNotification__HookPromptFragment = { + readonly hookRunId: string; + readonly text: string; +}; +export const V2TurnCompletedNotification__HookPromptFragment = Schema.Struct({ + hookRunId: Schema.String, + text: Schema.String, +}); + +export type V2TurnCompletedNotification__McpToolCallError = { readonly message: string }; +export const V2TurnCompletedNotification__McpToolCallError = Schema.Struct({ + message: Schema.String, +}); + +export type V2TurnCompletedNotification__McpToolCallResult = { + readonly _meta?: unknown; + readonly content: ReadonlyArray; + readonly structuredContent?: unknown; +}; +export const V2TurnCompletedNotification__McpToolCallResult = Schema.Struct({ + _meta: Schema.optionalKey(Schema.Unknown), + content: Schema.Array(Schema.Unknown), + structuredContent: Schema.optionalKey(Schema.Unknown), +}); + +export type V2TurnCompletedNotification__McpToolCallStatus = "inProgress" | "completed" | "failed"; +export const V2TurnCompletedNotification__McpToolCallStatus = Schema.Literals([ + "inProgress", + "completed", + "failed", +]); + +export type V2TurnCompletedNotification__MemoryCitationEntry = { + readonly lineEnd: number; + readonly lineStart: number; + readonly note: string; + readonly path: string; +}; +export const V2TurnCompletedNotification__MemoryCitationEntry = Schema.Struct({ + lineEnd: Schema.Number.annotate({ format: "uint32" }) + .check(Schema.isInt()) + .check(Schema.isGreaterThanOrEqualTo(0)), + lineStart: Schema.Number.annotate({ format: "uint32" }) + .check(Schema.isInt()) + .check(Schema.isGreaterThanOrEqualTo(0)), + note: Schema.String, + path: Schema.String, +}); + +export type V2TurnCompletedNotification__MessagePhase = "commentary" | "final_answer"; +export const V2TurnCompletedNotification__MessagePhase = Schema.Literals([ + "commentary", + "final_answer", +]).annotate({ + description: + 'Classifies an assistant message as interim commentary or final answer text.\n\nProviders do not emit this consistently, so callers must treat `None` as "phase unknown" and keep compatibility behavior for legacy models.', +}); + +export type V2TurnCompletedNotification__NonSteerableTurnKind = "review" | "compact"; +export const V2TurnCompletedNotification__NonSteerableTurnKind = Schema.Literals([ + "review", + "compact", +]); + +export type V2TurnCompletedNotification__PatchApplyStatus = + | "inProgress" + | "completed" + | "failed" + | "declined"; +export const V2TurnCompletedNotification__PatchApplyStatus = Schema.Literals([ + "inProgress", + "completed", + "failed", + "declined", +]); + +export type V2TurnCompletedNotification__PatchChangeKind = + | { readonly type: "add" } + | { readonly type: "delete" } + | { readonly move_path?: string | null; readonly type: "update" }; +export const V2TurnCompletedNotification__PatchChangeKind = Schema.Union( + [ + Schema.Struct({ + type: Schema.Literal("add").annotate({ title: "AddPatchChangeKindType" }), + }).annotate({ title: "AddPatchChangeKind" }), + Schema.Struct({ + type: Schema.Literal("delete").annotate({ title: "DeletePatchChangeKindType" }), + }).annotate({ title: "DeletePatchChangeKind" }), + Schema.Struct({ + move_path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + type: Schema.Literal("update").annotate({ title: "UpdatePatchChangeKindType" }), + }).annotate({ title: "UpdatePatchChangeKind" }), + ], + { mode: "oneOf" }, +); + +export type V2TurnCompletedNotification__ReasoningEffort = + | "none" + | "minimal" + | "low" + | "medium" + | "high" + | "xhigh"; +export const V2TurnCompletedNotification__ReasoningEffort = Schema.Literals([ + "none", + "minimal", + "low", + "medium", + "high", + "xhigh", +]).annotate({ + description: + "See https://platform.openai.com/docs/guides/reasoning?api-mode=responses#get-started-with-reasoning", +}); + +export type V2TurnCompletedNotification__TextElement = { + readonly byteRange: { readonly end: number; readonly start: number }; + readonly placeholder?: string | null; +}; +export const V2TurnCompletedNotification__TextElement = Schema.Struct({ + byteRange: Schema.Struct({ + end: Schema.Number.annotate({ format: "uint" }) + .check(Schema.isInt()) + .check(Schema.isGreaterThanOrEqualTo(0)), + start: Schema.Number.annotate({ format: "uint" }) + .check(Schema.isInt()) + .check(Schema.isGreaterThanOrEqualTo(0)), + }).annotate({ + description: "Byte range in the parent `text` buffer that this element occupies.", + }), + placeholder: Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + description: "Optional human-readable placeholder for the element, displayed in the UI.", + }), + Schema.Null, + ]), + ), +}); + +export type V2TurnCompletedNotification__TurnStatus = + | "completed" + | "interrupted" + | "failed" + | "inProgress"; +export const V2TurnCompletedNotification__TurnStatus = Schema.Literals([ + "completed", + "interrupted", + "failed", + "inProgress", +]); + +export type V2TurnCompletedNotification__WebSearchAction = + | { + readonly queries?: ReadonlyArray | null; + readonly query?: string | null; + readonly type: "search"; + } + | { readonly type: "openPage"; readonly url?: string | null } + | { readonly pattern?: string | null; readonly type: "findInPage"; readonly url?: string | null } + | { readonly type: "other" }; +export const V2TurnCompletedNotification__WebSearchAction = Schema.Union( + [ + Schema.Struct({ + queries: Schema.optionalKey(Schema.Union([Schema.Array(Schema.String), Schema.Null])), + query: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + type: Schema.Literal("search").annotate({ title: "SearchWebSearchActionType" }), + }).annotate({ title: "SearchWebSearchAction" }), + Schema.Struct({ + type: Schema.Literal("openPage").annotate({ title: "OpenPageWebSearchActionType" }), + url: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + }).annotate({ title: "OpenPageWebSearchAction" }), + Schema.Struct({ + pattern: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + type: Schema.Literal("findInPage").annotate({ title: "FindInPageWebSearchActionType" }), + url: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + }).annotate({ title: "FindInPageWebSearchAction" }), + Schema.Struct({ + type: Schema.Literal("other").annotate({ title: "OtherWebSearchActionType" }), + }).annotate({ title: "OtherWebSearchAction" }), + ], + { mode: "oneOf" }, +); + +export type V2TurnPlanUpdatedNotification__TurnPlanStepStatus = + | "pending" + | "inProgress" + | "completed"; +export const V2TurnPlanUpdatedNotification__TurnPlanStepStatus = Schema.Literals([ + "pending", + "inProgress", + "completed", +]); + +export type V2TurnStartedNotification__CollabAgentStatus = + | "pendingInit" + | "running" + | "interrupted" + | "completed" + | "errored" + | "shutdown" + | "notFound"; +export const V2TurnStartedNotification__CollabAgentStatus = Schema.Literals([ + "pendingInit", + "running", + "interrupted", + "completed", + "errored", + "shutdown", + "notFound", +]); + +export type V2TurnStartedNotification__CommandAction = + | { + readonly command: string; + readonly name: string; + readonly path: string; + readonly type: "read"; + } + | { readonly command: string; readonly path?: string | null; readonly type: "listFiles" } + | { + readonly command: string; + readonly path?: string | null; + readonly query?: string | null; + readonly type: "search"; + } + | { readonly command: string; readonly type: "unknown" }; +export const V2TurnStartedNotification__CommandAction = Schema.Union( + [ + Schema.Struct({ + command: Schema.String, + name: Schema.String, + path: Schema.String, + type: Schema.Literal("read").annotate({ title: "ReadCommandActionType" }), + }).annotate({ title: "ReadCommandAction" }), + Schema.Struct({ + command: Schema.String, + path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + type: Schema.Literal("listFiles").annotate({ title: "ListFilesCommandActionType" }), + }).annotate({ title: "ListFilesCommandAction" }), + Schema.Struct({ + command: Schema.String, + path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + query: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + type: Schema.Literal("search").annotate({ title: "SearchCommandActionType" }), + }).annotate({ title: "SearchCommandAction" }), + Schema.Struct({ + command: Schema.String, + type: Schema.Literal("unknown").annotate({ title: "UnknownCommandActionType" }), + }).annotate({ title: "UnknownCommandAction" }), + ], + { mode: "oneOf" }, +); + +export type V2TurnStartedNotification__CommandExecutionStatus = + | "inProgress" + | "completed" + | "failed" + | "declined"; +export const V2TurnStartedNotification__CommandExecutionStatus = Schema.Literals([ + "inProgress", + "completed", + "failed", + "declined", +]); + +export type V2TurnStartedNotification__DynamicToolCallOutputContentItem = + | { readonly text: string; readonly type: "inputText" } + | { readonly imageUrl: string; readonly type: "inputImage" }; +export const V2TurnStartedNotification__DynamicToolCallOutputContentItem = Schema.Union( + [ + Schema.Struct({ + text: Schema.String, + type: Schema.Literal("inputText").annotate({ + title: "InputTextDynamicToolCallOutputContentItemType", + }), + }).annotate({ title: "InputTextDynamicToolCallOutputContentItem" }), + Schema.Struct({ + imageUrl: Schema.String, + type: Schema.Literal("inputImage").annotate({ + title: "InputImageDynamicToolCallOutputContentItemType", + }), + }).annotate({ title: "InputImageDynamicToolCallOutputContentItem" }), + ], + { mode: "oneOf" }, +); + +export type V2TurnStartedNotification__DynamicToolCallStatus = + | "inProgress" + | "completed" + | "failed"; +export const V2TurnStartedNotification__DynamicToolCallStatus = Schema.Literals([ + "inProgress", + "completed", + "failed", +]); + +export type V2TurnStartedNotification__HookPromptFragment = { + readonly hookRunId: string; + readonly text: string; +}; +export const V2TurnStartedNotification__HookPromptFragment = Schema.Struct({ + hookRunId: Schema.String, + text: Schema.String, +}); + +export type V2TurnStartedNotification__McpToolCallError = { readonly message: string }; +export const V2TurnStartedNotification__McpToolCallError = Schema.Struct({ + message: Schema.String, +}); + +export type V2TurnStartedNotification__McpToolCallResult = { + readonly _meta?: unknown; + readonly content: ReadonlyArray; + readonly structuredContent?: unknown; +}; +export const V2TurnStartedNotification__McpToolCallResult = Schema.Struct({ + _meta: Schema.optionalKey(Schema.Unknown), + content: Schema.Array(Schema.Unknown), + structuredContent: Schema.optionalKey(Schema.Unknown), +}); + +export type V2TurnStartedNotification__McpToolCallStatus = "inProgress" | "completed" | "failed"; +export const V2TurnStartedNotification__McpToolCallStatus = Schema.Literals([ + "inProgress", + "completed", + "failed", +]); + +export type V2TurnStartedNotification__MemoryCitationEntry = { + readonly lineEnd: number; + readonly lineStart: number; + readonly note: string; + readonly path: string; +}; +export const V2TurnStartedNotification__MemoryCitationEntry = Schema.Struct({ + lineEnd: Schema.Number.annotate({ format: "uint32" }) + .check(Schema.isInt()) + .check(Schema.isGreaterThanOrEqualTo(0)), + lineStart: Schema.Number.annotate({ format: "uint32" }) + .check(Schema.isInt()) + .check(Schema.isGreaterThanOrEqualTo(0)), + note: Schema.String, + path: Schema.String, +}); + +export type V2TurnStartedNotification__MessagePhase = "commentary" | "final_answer"; +export const V2TurnStartedNotification__MessagePhase = Schema.Literals([ + "commentary", + "final_answer", +]).annotate({ + description: + 'Classifies an assistant message as interim commentary or final answer text.\n\nProviders do not emit this consistently, so callers must treat `None` as "phase unknown" and keep compatibility behavior for legacy models.', +}); + +export type V2TurnStartedNotification__NonSteerableTurnKind = "review" | "compact"; +export const V2TurnStartedNotification__NonSteerableTurnKind = Schema.Literals([ + "review", + "compact", +]); + +export type V2TurnStartedNotification__PatchApplyStatus = + | "inProgress" + | "completed" + | "failed" + | "declined"; +export const V2TurnStartedNotification__PatchApplyStatus = Schema.Literals([ + "inProgress", + "completed", + "failed", + "declined", +]); + +export type V2TurnStartedNotification__PatchChangeKind = + | { readonly type: "add" } + | { readonly type: "delete" } + | { readonly move_path?: string | null; readonly type: "update" }; +export const V2TurnStartedNotification__PatchChangeKind = Schema.Union( + [ + Schema.Struct({ + type: Schema.Literal("add").annotate({ title: "AddPatchChangeKindType" }), + }).annotate({ title: "AddPatchChangeKind" }), + Schema.Struct({ + type: Schema.Literal("delete").annotate({ title: "DeletePatchChangeKindType" }), + }).annotate({ title: "DeletePatchChangeKind" }), + Schema.Struct({ + move_path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + type: Schema.Literal("update").annotate({ title: "UpdatePatchChangeKindType" }), + }).annotate({ title: "UpdatePatchChangeKind" }), + ], + { mode: "oneOf" }, +); + +export type V2TurnStartedNotification__ReasoningEffort = + | "none" + | "minimal" + | "low" + | "medium" + | "high" + | "xhigh"; +export const V2TurnStartedNotification__ReasoningEffort = Schema.Literals([ + "none", + "minimal", + "low", + "medium", + "high", + "xhigh", +]).annotate({ + description: + "See https://platform.openai.com/docs/guides/reasoning?api-mode=responses#get-started-with-reasoning", +}); + +export type V2TurnStartedNotification__TextElement = { + readonly byteRange: { readonly end: number; readonly start: number }; + readonly placeholder?: string | null; +}; +export const V2TurnStartedNotification__TextElement = Schema.Struct({ + byteRange: Schema.Struct({ + end: Schema.Number.annotate({ format: "uint" }) + .check(Schema.isInt()) + .check(Schema.isGreaterThanOrEqualTo(0)), + start: Schema.Number.annotate({ format: "uint" }) + .check(Schema.isInt()) + .check(Schema.isGreaterThanOrEqualTo(0)), + }).annotate({ + description: "Byte range in the parent `text` buffer that this element occupies.", + }), + placeholder: Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + description: "Optional human-readable placeholder for the element, displayed in the UI.", + }), + Schema.Null, + ]), + ), +}); + +export type V2TurnStartedNotification__TurnStatus = + | "completed" + | "interrupted" + | "failed" + | "inProgress"; +export const V2TurnStartedNotification__TurnStatus = Schema.Literals([ + "completed", + "interrupted", + "failed", + "inProgress", +]); + +export type V2TurnStartedNotification__WebSearchAction = + | { + readonly queries?: ReadonlyArray | null; + readonly query?: string | null; + readonly type: "search"; + } + | { readonly type: "openPage"; readonly url?: string | null } + | { readonly pattern?: string | null; readonly type: "findInPage"; readonly url?: string | null } + | { readonly type: "other" }; +export const V2TurnStartedNotification__WebSearchAction = Schema.Union( + [ + Schema.Struct({ + queries: Schema.optionalKey(Schema.Union([Schema.Array(Schema.String), Schema.Null])), + query: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + type: Schema.Literal("search").annotate({ title: "SearchWebSearchActionType" }), + }).annotate({ title: "SearchWebSearchAction" }), + Schema.Struct({ + type: Schema.Literal("openPage").annotate({ title: "OpenPageWebSearchActionType" }), + url: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + }).annotate({ title: "OpenPageWebSearchAction" }), + Schema.Struct({ + pattern: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + type: Schema.Literal("findInPage").annotate({ title: "FindInPageWebSearchActionType" }), + url: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + }).annotate({ title: "FindInPageWebSearchAction" }), + Schema.Struct({ + type: Schema.Literal("other").annotate({ title: "OtherWebSearchActionType" }), + }).annotate({ title: "OtherWebSearchAction" }), + ], + { mode: "oneOf" }, +); + +export type V2TurnStartParams__AbsolutePathBuf = string; +export const V2TurnStartParams__AbsolutePathBuf = Schema.String.annotate({ + description: + "A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\n\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.", +}); + +export type V2TurnStartParams__ApprovalsReviewer = "user" | "guardian_subagent"; +export const V2TurnStartParams__ApprovalsReviewer = Schema.Literals([ + "user", + "guardian_subagent", +]).annotate({ + description: + "Configures who approval requests are routed to for review. Examples include sandbox escapes, blocked network access, MCP approval prompts, and ARC escalations. Defaults to `user`. `guardian_subagent` uses a carefully prompted subagent to gather relevant context and apply a risk-based decision framework before approving or denying the request.", +}); + +export type V2TurnStartParams__AskForApproval = + | "untrusted" + | "on-failure" + | "on-request" + | "never" + | { + readonly granular: { + readonly mcp_elicitations: boolean; + readonly request_permissions?: boolean; + readonly rules: boolean; + readonly sandbox_approval: boolean; + readonly skill_approval?: boolean; + }; + }; +export const V2TurnStartParams__AskForApproval = Schema.Union( + [ + Schema.Literals(["untrusted", "on-failure", "on-request", "never"]), + Schema.Struct({ + granular: Schema.Struct({ + mcp_elicitations: Schema.Boolean, + request_permissions: Schema.optionalKey(Schema.Boolean.annotate({ default: false })), + rules: Schema.Boolean, + sandbox_approval: Schema.Boolean, + skill_approval: Schema.optionalKey(Schema.Boolean.annotate({ default: false })), + }), + }).annotate({ title: "GranularAskForApproval" }), + ], + { mode: "oneOf" }, +); + +export type V2TurnStartParams__ModeKind = "plan" | "default"; +export const V2TurnStartParams__ModeKind = Schema.Literals(["plan", "default"]).annotate({ + description: "Initial collaboration mode to use when the TUI starts.", +}); + +export type V2TurnStartParams__Personality = "none" | "friendly" | "pragmatic"; +export const V2TurnStartParams__Personality = Schema.Literals(["none", "friendly", "pragmatic"]); + +export type V2TurnStartParams__ReasoningEffort = + | "none" + | "minimal" + | "low" + | "medium" + | "high" + | "xhigh"; +export const V2TurnStartParams__ReasoningEffort = Schema.Literals([ + "none", + "minimal", + "low", + "medium", + "high", + "xhigh", +]).annotate({ + description: + "See https://platform.openai.com/docs/guides/reasoning?api-mode=responses#get-started-with-reasoning", +}); + +export type V2TurnStartParams__ReasoningSummary = "auto" | "concise" | "detailed" | "none"; +export const V2TurnStartParams__ReasoningSummary = Schema.Union( + [ + Schema.Literals(["auto", "concise", "detailed"]), + Schema.Literal("none").annotate({ description: "Option to disable reasoning summaries." }), + ], + { mode: "oneOf" }, +).annotate({ + description: + "A summary of the reasoning performed by the model. This can be useful for debugging and understanding the model's reasoning process. See https://platform.openai.com/docs/guides/reasoning?api-mode=responses#reasoning-summaries", +}); + +export type V2TurnStartParams__ServiceTier = "fast" | "flex"; +export const V2TurnStartParams__ServiceTier = Schema.Literals(["fast", "flex"]); + +export type V2TurnStartParams__TextElement = { + readonly byteRange: { readonly end: number; readonly start: number }; + readonly placeholder?: string | null; +}; +export const V2TurnStartParams__TextElement = Schema.Struct({ + byteRange: Schema.Struct({ + end: Schema.Number.annotate({ format: "uint" }) + .check(Schema.isInt()) + .check(Schema.isGreaterThanOrEqualTo(0)), + start: Schema.Number.annotate({ format: "uint" }) + .check(Schema.isInt()) + .check(Schema.isGreaterThanOrEqualTo(0)), + }).annotate({ + description: "Byte range in the parent `text` buffer that this element occupies.", + }), + placeholder: Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + description: "Optional human-readable placeholder for the element, displayed in the UI.", + }), + Schema.Null, + ]), + ), +}); + +export type V2TurnStartResponse__CollabAgentStatus = + | "pendingInit" + | "running" + | "interrupted" + | "completed" + | "errored" + | "shutdown" + | "notFound"; +export const V2TurnStartResponse__CollabAgentStatus = Schema.Literals([ + "pendingInit", + "running", + "interrupted", + "completed", + "errored", + "shutdown", + "notFound", +]); + +export type V2TurnStartResponse__CommandAction = + | { + readonly command: string; + readonly name: string; + readonly path: string; + readonly type: "read"; + } + | { readonly command: string; readonly path?: string | null; readonly type: "listFiles" } + | { + readonly command: string; + readonly path?: string | null; + readonly query?: string | null; + readonly type: "search"; + } + | { readonly command: string; readonly type: "unknown" }; +export const V2TurnStartResponse__CommandAction = Schema.Union( + [ + Schema.Struct({ + command: Schema.String, + name: Schema.String, + path: Schema.String, + type: Schema.Literal("read").annotate({ title: "ReadCommandActionType" }), + }).annotate({ title: "ReadCommandAction" }), + Schema.Struct({ + command: Schema.String, + path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + type: Schema.Literal("listFiles").annotate({ title: "ListFilesCommandActionType" }), + }).annotate({ title: "ListFilesCommandAction" }), + Schema.Struct({ + command: Schema.String, + path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + query: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + type: Schema.Literal("search").annotate({ title: "SearchCommandActionType" }), + }).annotate({ title: "SearchCommandAction" }), + Schema.Struct({ + command: Schema.String, + type: Schema.Literal("unknown").annotate({ title: "UnknownCommandActionType" }), + }).annotate({ title: "UnknownCommandAction" }), + ], + { mode: "oneOf" }, +); + +export type V2TurnStartResponse__CommandExecutionStatus = + | "inProgress" + | "completed" + | "failed" + | "declined"; +export const V2TurnStartResponse__CommandExecutionStatus = Schema.Literals([ + "inProgress", + "completed", + "failed", + "declined", +]); + +export type V2TurnStartResponse__DynamicToolCallOutputContentItem = + | { readonly text: string; readonly type: "inputText" } + | { readonly imageUrl: string; readonly type: "inputImage" }; +export const V2TurnStartResponse__DynamicToolCallOutputContentItem = Schema.Union( + [ + Schema.Struct({ + text: Schema.String, + type: Schema.Literal("inputText").annotate({ + title: "InputTextDynamicToolCallOutputContentItemType", + }), + }).annotate({ title: "InputTextDynamicToolCallOutputContentItem" }), + Schema.Struct({ + imageUrl: Schema.String, + type: Schema.Literal("inputImage").annotate({ + title: "InputImageDynamicToolCallOutputContentItemType", + }), + }).annotate({ title: "InputImageDynamicToolCallOutputContentItem" }), + ], + { mode: "oneOf" }, +); + +export type V2TurnStartResponse__DynamicToolCallStatus = "inProgress" | "completed" | "failed"; +export const V2TurnStartResponse__DynamicToolCallStatus = Schema.Literals([ + "inProgress", + "completed", + "failed", +]); + +export type V2TurnStartResponse__HookPromptFragment = { + readonly hookRunId: string; + readonly text: string; +}; +export const V2TurnStartResponse__HookPromptFragment = Schema.Struct({ + hookRunId: Schema.String, + text: Schema.String, +}); + +export type V2TurnStartResponse__McpToolCallError = { readonly message: string }; +export const V2TurnStartResponse__McpToolCallError = Schema.Struct({ message: Schema.String }); + +export type V2TurnStartResponse__McpToolCallResult = { + readonly _meta?: unknown; + readonly content: ReadonlyArray; + readonly structuredContent?: unknown; +}; +export const V2TurnStartResponse__McpToolCallResult = Schema.Struct({ + _meta: Schema.optionalKey(Schema.Unknown), + content: Schema.Array(Schema.Unknown), + structuredContent: Schema.optionalKey(Schema.Unknown), +}); + +export type V2TurnStartResponse__McpToolCallStatus = "inProgress" | "completed" | "failed"; +export const V2TurnStartResponse__McpToolCallStatus = Schema.Literals([ + "inProgress", + "completed", + "failed", +]); + +export type V2TurnStartResponse__MemoryCitationEntry = { + readonly lineEnd: number; + readonly lineStart: number; + readonly note: string; + readonly path: string; +}; +export const V2TurnStartResponse__MemoryCitationEntry = Schema.Struct({ + lineEnd: Schema.Number.annotate({ format: "uint32" }) + .check(Schema.isInt()) + .check(Schema.isGreaterThanOrEqualTo(0)), + lineStart: Schema.Number.annotate({ format: "uint32" }) + .check(Schema.isInt()) + .check(Schema.isGreaterThanOrEqualTo(0)), + note: Schema.String, + path: Schema.String, +}); + +export type V2TurnStartResponse__MessagePhase = "commentary" | "final_answer"; +export const V2TurnStartResponse__MessagePhase = Schema.Literals([ + "commentary", + "final_answer", +]).annotate({ + description: + 'Classifies an assistant message as interim commentary or final answer text.\n\nProviders do not emit this consistently, so callers must treat `None` as "phase unknown" and keep compatibility behavior for legacy models.', +}); + +export type V2TurnStartResponse__NonSteerableTurnKind = "review" | "compact"; +export const V2TurnStartResponse__NonSteerableTurnKind = Schema.Literals(["review", "compact"]); + +export type V2TurnStartResponse__PatchApplyStatus = + | "inProgress" + | "completed" + | "failed" + | "declined"; +export const V2TurnStartResponse__PatchApplyStatus = Schema.Literals([ + "inProgress", + "completed", + "failed", + "declined", +]); + +export type V2TurnStartResponse__PatchChangeKind = + | { readonly type: "add" } + | { readonly type: "delete" } + | { readonly move_path?: string | null; readonly type: "update" }; +export const V2TurnStartResponse__PatchChangeKind = Schema.Union( + [ + Schema.Struct({ + type: Schema.Literal("add").annotate({ title: "AddPatchChangeKindType" }), + }).annotate({ title: "AddPatchChangeKind" }), + Schema.Struct({ + type: Schema.Literal("delete").annotate({ title: "DeletePatchChangeKindType" }), + }).annotate({ title: "DeletePatchChangeKind" }), + Schema.Struct({ + move_path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + type: Schema.Literal("update").annotate({ title: "UpdatePatchChangeKindType" }), + }).annotate({ title: "UpdatePatchChangeKind" }), + ], + { mode: "oneOf" }, +); + +export type V2TurnStartResponse__ReasoningEffort = + | "none" + | "minimal" + | "low" + | "medium" + | "high" + | "xhigh"; +export const V2TurnStartResponse__ReasoningEffort = Schema.Literals([ + "none", + "minimal", + "low", + "medium", + "high", + "xhigh", +]).annotate({ + description: + "See https://platform.openai.com/docs/guides/reasoning?api-mode=responses#get-started-with-reasoning", +}); + +export type V2TurnStartResponse__TextElement = { + readonly byteRange: { readonly end: number; readonly start: number }; + readonly placeholder?: string | null; +}; +export const V2TurnStartResponse__TextElement = Schema.Struct({ + byteRange: Schema.Struct({ + end: Schema.Number.annotate({ format: "uint" }) + .check(Schema.isInt()) + .check(Schema.isGreaterThanOrEqualTo(0)), + start: Schema.Number.annotate({ format: "uint" }) + .check(Schema.isInt()) + .check(Schema.isGreaterThanOrEqualTo(0)), + }).annotate({ + description: "Byte range in the parent `text` buffer that this element occupies.", + }), + placeholder: Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + description: "Optional human-readable placeholder for the element, displayed in the UI.", + }), + Schema.Null, + ]), + ), +}); + +export type V2TurnStartResponse__TurnStatus = "completed" | "interrupted" | "failed" | "inProgress"; +export const V2TurnStartResponse__TurnStatus = Schema.Literals([ + "completed", + "interrupted", + "failed", + "inProgress", +]); + +export type V2TurnStartResponse__WebSearchAction = + | { + readonly queries?: ReadonlyArray | null; + readonly query?: string | null; + readonly type: "search"; + } + | { readonly type: "openPage"; readonly url?: string | null } + | { readonly pattern?: string | null; readonly type: "findInPage"; readonly url?: string | null } + | { readonly type: "other" }; +export const V2TurnStartResponse__WebSearchAction = Schema.Union( + [ + Schema.Struct({ + queries: Schema.optionalKey(Schema.Union([Schema.Array(Schema.String), Schema.Null])), + query: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + type: Schema.Literal("search").annotate({ title: "SearchWebSearchActionType" }), + }).annotate({ title: "SearchWebSearchAction" }), + Schema.Struct({ + type: Schema.Literal("openPage").annotate({ title: "OpenPageWebSearchActionType" }), + url: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + }).annotate({ title: "OpenPageWebSearchAction" }), + Schema.Struct({ + pattern: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + type: Schema.Literal("findInPage").annotate({ title: "FindInPageWebSearchActionType" }), + url: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + }).annotate({ title: "FindInPageWebSearchAction" }), + Schema.Struct({ + type: Schema.Literal("other").annotate({ title: "OtherWebSearchActionType" }), + }).annotate({ title: "OtherWebSearchAction" }), + ], + { mode: "oneOf" }, +); + +export type V2TurnSteerParams__TextElement = { + readonly byteRange: { readonly end: number; readonly start: number }; + readonly placeholder?: string | null; +}; +export const V2TurnSteerParams__TextElement = Schema.Struct({ + byteRange: Schema.Struct({ + end: Schema.Number.annotate({ format: "uint" }) + .check(Schema.isInt()) + .check(Schema.isGreaterThanOrEqualTo(0)), + start: Schema.Number.annotate({ format: "uint" }) + .check(Schema.isInt()) + .check(Schema.isGreaterThanOrEqualTo(0)), + }).annotate({ + description: "Byte range in the parent `text` buffer that this element occupies.", + }), + placeholder: Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + description: "Optional human-readable placeholder for the element, displayed in the UI.", + }), + Schema.Null, + ]), + ), +}); + +export type V2WindowsSandboxSetupCompletedNotification__WindowsSandboxSetupMode = + | "elevated" + | "unelevated"; +export const V2WindowsSandboxSetupCompletedNotification__WindowsSandboxSetupMode = Schema.Literals([ + "elevated", + "unelevated", +]); + +export type V2WindowsSandboxSetupStartParams__AbsolutePathBuf = string; +export const V2WindowsSandboxSetupStartParams__AbsolutePathBuf = Schema.String.annotate({ + description: + "A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\n\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.", +}); + +export type V2WindowsSandboxSetupStartParams__WindowsSandboxSetupMode = "elevated" | "unelevated"; +export const V2WindowsSandboxSetupStartParams__WindowsSandboxSetupMode = Schema.Literals([ + "elevated", + "unelevated", +]); + +export type ApplyPatchApprovalResponse__NetworkPolicyAmendment = { + readonly action: ApplyPatchApprovalResponse__NetworkPolicyRuleAction; + readonly host: string; +}; +export const ApplyPatchApprovalResponse__NetworkPolicyAmendment = Schema.Struct({ + action: ApplyPatchApprovalResponse__NetworkPolicyRuleAction, + host: Schema.String, +}); + +export type ClientRequest__PluginInstallParams = { + readonly forceRemoteSync?: boolean; + readonly marketplacePath: ClientRequest__AbsolutePathBuf; + readonly pluginName: string; +}; +export const ClientRequest__PluginInstallParams = Schema.Struct({ + forceRemoteSync: Schema.optionalKey( + Schema.Boolean.annotate({ + description: "When true, apply the remote plugin change before the local install flow.", + }), + ), + marketplacePath: ClientRequest__AbsolutePathBuf, + pluginName: Schema.String, +}); + +export type ClientRequest__PluginListParams = { + readonly cwds?: ReadonlyArray | null; + readonly forceRemoteSync?: boolean; +}; +export const ClientRequest__PluginListParams = Schema.Struct({ + cwds: Schema.optionalKey( + Schema.Union([ + Schema.Array(ClientRequest__AbsolutePathBuf).annotate({ + description: + "Optional working directories used to discover repo marketplaces. When omitted, only home-scoped marketplaces and the official curated marketplace are considered.", + }), + Schema.Null, + ]), + ), + forceRemoteSync: Schema.optionalKey( + Schema.Boolean.annotate({ + description: + "When true, reconcile the official curated marketplace against the remote plugin state before listing marketplaces.", + }), + ), +}); + +export type ClientRequest__PluginReadParams = { + readonly marketplacePath: ClientRequest__AbsolutePathBuf; + readonly pluginName: string; +}; +export const ClientRequest__PluginReadParams = Schema.Struct({ + marketplacePath: ClientRequest__AbsolutePathBuf, + pluginName: Schema.String, +}); + +export type ClientRequest__SandboxPolicy = + | { readonly type: "dangerFullAccess" } + | { + readonly access?: + | { + readonly includePlatformDefaults?: boolean; + readonly readableRoots?: ReadonlyArray; + readonly type: "restricted"; + } + | { readonly type: "fullAccess" }; + readonly networkAccess?: boolean; + readonly type: "readOnly"; + } + | { readonly networkAccess?: "restricted" | "enabled"; readonly type: "externalSandbox" } + | { + readonly excludeSlashTmp?: boolean; + readonly excludeTmpdirEnvVar?: boolean; + readonly networkAccess?: boolean; + readonly readOnlyAccess?: + | { + readonly includePlatformDefaults?: boolean; + readonly readableRoots?: ReadonlyArray; + readonly type: "restricted"; + } + | { readonly type: "fullAccess" }; + readonly type: "workspaceWrite"; + readonly writableRoots?: ReadonlyArray; + }; +export const ClientRequest__SandboxPolicy = Schema.Union( + [ + Schema.Struct({ + type: Schema.Literal("dangerFullAccess").annotate({ + title: "DangerFullAccessSandboxPolicyType", + }), + }).annotate({ title: "DangerFullAccessSandboxPolicy" }), + Schema.Struct({ + access: Schema.optionalKey( + Schema.Union( + [ + Schema.Struct({ + includePlatformDefaults: Schema.optionalKey( + Schema.Boolean.annotate({ default: true }), + ), + readableRoots: Schema.optionalKey( + Schema.Array(ClientRequest__AbsolutePathBuf).annotate({ default: [] }), + ), + type: Schema.Literal("restricted").annotate({ + title: "RestrictedReadOnlyAccessType", + }), + }).annotate({ title: "RestrictedReadOnlyAccess" }), + Schema.Struct({ + type: Schema.Literal("fullAccess").annotate({ + title: "FullAccessReadOnlyAccessType", + }), + }).annotate({ title: "FullAccessReadOnlyAccess" }), + ], + { mode: "oneOf" }, + ).annotate({ default: { type: "fullAccess" } }), + ), + networkAccess: Schema.optionalKey(Schema.Boolean.annotate({ default: false })), + type: Schema.Literal("readOnly").annotate({ title: "ReadOnlySandboxPolicyType" }), + }).annotate({ title: "ReadOnlySandboxPolicy" }), + Schema.Struct({ + networkAccess: Schema.optionalKey( + Schema.Literals(["restricted", "enabled"]).annotate({ default: "restricted" }), + ), + type: Schema.Literal("externalSandbox").annotate({ + title: "ExternalSandboxSandboxPolicyType", + }), + }).annotate({ title: "ExternalSandboxSandboxPolicy" }), + Schema.Struct({ + excludeSlashTmp: Schema.optionalKey(Schema.Boolean.annotate({ default: false })), + excludeTmpdirEnvVar: Schema.optionalKey(Schema.Boolean.annotate({ default: false })), + networkAccess: Schema.optionalKey(Schema.Boolean.annotate({ default: false })), + readOnlyAccess: Schema.optionalKey( + Schema.Union( + [ + Schema.Struct({ + includePlatformDefaults: Schema.optionalKey( + Schema.Boolean.annotate({ default: true }), + ), + readableRoots: Schema.optionalKey( + Schema.Array(ClientRequest__AbsolutePathBuf).annotate({ default: [] }), + ), + type: Schema.Literal("restricted").annotate({ + title: "RestrictedReadOnlyAccessType", + }), + }).annotate({ title: "RestrictedReadOnlyAccess" }), + Schema.Struct({ + type: Schema.Literal("fullAccess").annotate({ + title: "FullAccessReadOnlyAccessType", + }), + }).annotate({ title: "FullAccessReadOnlyAccess" }), + ], + { mode: "oneOf" }, + ).annotate({ default: { type: "fullAccess" } }), + ), + type: Schema.Literal("workspaceWrite").annotate({ title: "WorkspaceWriteSandboxPolicyType" }), + writableRoots: Schema.optionalKey( + Schema.Array(ClientRequest__AbsolutePathBuf).annotate({ default: [] }), + ), + }).annotate({ title: "WorkspaceWriteSandboxPolicy" }), + ], + { mode: "oneOf" }, +); + +export type ClientRequest__SkillsConfigWriteParams = { + readonly enabled: boolean; + readonly name?: string | null; + readonly path?: ClientRequest__AbsolutePathBuf | null; +}; +export const ClientRequest__SkillsConfigWriteParams = Schema.Struct({ + enabled: Schema.Boolean, + name: Schema.optionalKey( + Schema.Union([Schema.String.annotate({ description: "Name-based selector." }), Schema.Null]), + ), + path: Schema.optionalKey( + Schema.Union([ClientRequest__AbsolutePathBuf, Schema.Null]).annotate({ + description: "Path-based selector.", + }), + ), +}); + +export type ClientRequest__ExternalAgentConfigMigrationItem = { + readonly cwd?: string | null; + readonly description: string; + readonly itemType: ClientRequest__ExternalAgentConfigMigrationItemType; +}; +export const ClientRequest__ExternalAgentConfigMigrationItem = Schema.Struct({ + cwd: Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + description: + "Null or empty means home-scoped migration; non-empty means repo-scoped migration.", + }), + Schema.Null, + ]), + ), + description: Schema.String, + itemType: ClientRequest__ExternalAgentConfigMigrationItemType, +}); + +export type ClientRequest__FunctionCallOutputContentItem = + | { readonly text: string; readonly type: "input_text" } + | { + readonly detail?: ClientRequest__ImageDetail | null; + readonly image_url: string; + readonly type: "input_image"; + }; +export const ClientRequest__FunctionCallOutputContentItem = Schema.Union( + [ + Schema.Struct({ + text: Schema.String, + type: Schema.Literal("input_text").annotate({ + title: "InputTextFunctionCallOutputContentItemType", + }), + }).annotate({ title: "InputTextFunctionCallOutputContentItem" }), + Schema.Struct({ + detail: Schema.optionalKey(Schema.Union([ClientRequest__ImageDetail, Schema.Null])), + image_url: Schema.String, + type: Schema.Literal("input_image").annotate({ + title: "InputImageFunctionCallOutputContentItemType", + }), + }).annotate({ title: "InputImageFunctionCallOutputContentItem" }), + ], + { mode: "oneOf" }, +).annotate({ + description: + "Responses API compatible content items that can be returned by a tool call. This is a subset of ContentItem with the types we support as function call outputs.", +}); + +export type ClientRequest__InitializeParams = { + readonly capabilities?: ClientRequest__InitializeCapabilities | null; + readonly clientInfo: ClientRequest__ClientInfo; +}; +export const ClientRequest__InitializeParams = Schema.Struct({ + capabilities: Schema.optionalKey( + Schema.Union([ClientRequest__InitializeCapabilities, Schema.Null]), + ), + clientInfo: ClientRequest__ClientInfo, +}); + +export type ClientRequest__ListMcpServerStatusParams = { + readonly cursor?: string | null; + readonly detail?: ClientRequest__McpServerStatusDetail | null; + readonly limit?: number | null; +}; +export const ClientRequest__ListMcpServerStatusParams = Schema.Struct({ + cursor: Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + description: "Opaque pagination cursor returned by a previous call.", + }), + Schema.Null, + ]), + ), + detail: Schema.optionalKey( + Schema.Union([ClientRequest__McpServerStatusDetail, Schema.Null]).annotate({ + description: + "Controls how much MCP inventory data to fetch for each server. Defaults to `Full` when omitted.", + }), + ), + limit: Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ + description: "Optional page size; defaults to a server-defined value.", + format: "uint32", + }) + .check(Schema.isInt()) + .check(Schema.isGreaterThanOrEqualTo(0)), + Schema.Null, + ]), + ), +}); + +export type ClientRequest__ConfigEdit = { + readonly keyPath: string; + readonly mergeStrategy: ClientRequest__MergeStrategy; + readonly value: unknown; +}; +export const ClientRequest__ConfigEdit = Schema.Struct({ + keyPath: Schema.String, + mergeStrategy: ClientRequest__MergeStrategy, + value: Schema.Unknown, +}); + +export type ClientRequest__ConfigValueWriteParams = { + readonly expectedVersion?: string | null; + readonly filePath?: string | null; + readonly keyPath: string; + readonly mergeStrategy: ClientRequest__MergeStrategy; + readonly value: unknown; +}; +export const ClientRequest__ConfigValueWriteParams = Schema.Struct({ + expectedVersion: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + filePath: Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + description: + "Path to the config file to write; defaults to the user's `config.toml` when omitted.", + }), + Schema.Null, + ]), + ), + keyPath: Schema.String, + mergeStrategy: ClientRequest__MergeStrategy, + value: Schema.Unknown, +}); + +export type ClientRequest__Settings = { + readonly developer_instructions?: string | null; + readonly model: string; + readonly reasoning_effort?: ClientRequest__ReasoningEffort | null; +}; +export const ClientRequest__Settings = Schema.Struct({ + developer_instructions: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + model: Schema.String, + reasoning_effort: Schema.optionalKey(Schema.Union([ClientRequest__ReasoningEffort, Schema.Null])), +}).annotate({ description: "Settings for a collaboration mode." }); + +export type ClientRequest__ReviewStartParams = { + readonly delivery?: ClientRequest__ReviewDelivery | null; + readonly target: ClientRequest__ReviewTarget; + readonly threadId: string; +}; +export const ClientRequest__ReviewStartParams = Schema.Struct({ + delivery: Schema.optionalKey( + Schema.Union([ClientRequest__ReviewDelivery, Schema.Null]).annotate({ + description: + "Where to run the review: inline (default) on the current thread or detached on a new thread (returned in `reviewThreadId`).", + }), + ), + target: ClientRequest__ReviewTarget, + threadId: Schema.String, +}); + +export type ClientRequest__ThreadForkParams = { + readonly approvalPolicy?: ClientRequest__AskForApproval | null; + readonly approvalsReviewer?: ClientRequest__ApprovalsReviewer | null; + readonly baseInstructions?: string | null; + readonly config?: { readonly [x: string]: unknown } | null; + readonly cwd?: string | null; + readonly developerInstructions?: string | null; + readonly ephemeral?: boolean; + readonly model?: string | null; + readonly modelProvider?: string | null; + readonly sandbox?: ClientRequest__SandboxMode | null; + readonly serviceTier?: ClientRequest__ServiceTier | null | null; + readonly threadId: string; +}; +export const ClientRequest__ThreadForkParams = Schema.Struct({ + approvalPolicy: Schema.optionalKey(Schema.Union([ClientRequest__AskForApproval, Schema.Null])), + approvalsReviewer: Schema.optionalKey( + Schema.Union([ClientRequest__ApprovalsReviewer, Schema.Null]).annotate({ + description: + "Override where approval requests are routed for review on this thread and subsequent turns.", + }), + ), + baseInstructions: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + config: Schema.optionalKey( + Schema.Union([Schema.Record(Schema.String, Schema.Unknown), Schema.Null]), + ), + cwd: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + developerInstructions: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + ephemeral: Schema.optionalKey(Schema.Boolean), + model: Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + description: "Configuration overrides for the forked thread, if any.", + }), + Schema.Null, + ]), + ), + modelProvider: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + sandbox: Schema.optionalKey(Schema.Union([ClientRequest__SandboxMode, Schema.Null])), + serviceTier: Schema.optionalKey( + Schema.Union([Schema.Union([ClientRequest__ServiceTier, Schema.Null]), Schema.Null]), + ), + threadId: Schema.String, +}).annotate({ + description: + "There are two ways to fork a thread: 1. By thread_id: load the thread from disk by thread_id and fork it into a new thread. 2. By path: load the thread from disk by path and fork it into a new thread.\n\nIf using path, the thread_id param will be ignored.\n\nPrefer using thread_id whenever possible.", +}); + +export type ClientRequest__ThreadResumeParams = { + readonly approvalPolicy?: ClientRequest__AskForApproval | null; + readonly approvalsReviewer?: ClientRequest__ApprovalsReviewer | null; + readonly baseInstructions?: string | null; + readonly config?: { readonly [x: string]: unknown } | null; + readonly cwd?: string | null; + readonly developerInstructions?: string | null; + readonly model?: string | null; + readonly modelProvider?: string | null; + readonly personality?: ClientRequest__Personality | null; + readonly sandbox?: ClientRequest__SandboxMode | null; + readonly serviceTier?: ClientRequest__ServiceTier | null | null; + readonly threadId: string; +}; +export const ClientRequest__ThreadResumeParams = Schema.Struct({ + approvalPolicy: Schema.optionalKey(Schema.Union([ClientRequest__AskForApproval, Schema.Null])), + approvalsReviewer: Schema.optionalKey( + Schema.Union([ClientRequest__ApprovalsReviewer, Schema.Null]).annotate({ + description: + "Override where approval requests are routed for review on this thread and subsequent turns.", + }), + ), + baseInstructions: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + config: Schema.optionalKey( + Schema.Union([Schema.Record(Schema.String, Schema.Unknown), Schema.Null]), + ), + cwd: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + developerInstructions: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + model: Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + description: "Configuration overrides for the resumed thread, if any.", + }), + Schema.Null, + ]), + ), + modelProvider: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + personality: Schema.optionalKey(Schema.Union([ClientRequest__Personality, Schema.Null])), + sandbox: Schema.optionalKey(Schema.Union([ClientRequest__SandboxMode, Schema.Null])), + serviceTier: Schema.optionalKey( + Schema.Union([Schema.Union([ClientRequest__ServiceTier, Schema.Null]), Schema.Null]), + ), + threadId: Schema.String, +}).annotate({ + description: + "There are three ways to resume a thread: 1. By thread_id: load the thread from disk by thread_id and resume it. 2. By history: instantiate the thread from memory and resume it. 3. By path: load the thread from disk by path and resume it.\n\nThe precedence is: history > path > thread_id. If using history or path, the thread_id param will be ignored.\n\nPrefer using thread_id whenever possible.", +}); + +export type ClientRequest__SkillsListParams = { + readonly cwds?: ReadonlyArray; + readonly forceReload?: boolean; + readonly perCwdExtraUserRoots?: ReadonlyArray | null; +}; +export const ClientRequest__SkillsListParams = Schema.Struct({ + cwds: Schema.optionalKey( + Schema.Array(Schema.String).annotate({ + description: "When empty, defaults to the current session working directory.", + }), + ), + forceReload: Schema.optionalKey( + Schema.Boolean.annotate({ + description: "When true, bypass the skills cache and re-scan skills from disk.", + }), + ), + perCwdExtraUserRoots: Schema.optionalKey( + Schema.Union([ + Schema.Array(ClientRequest__SkillsListExtraRootsForCwd).annotate({ + description: "Optional per-cwd extra roots to scan as user-scoped skills.", + }), + Schema.Null, + ]), + ), +}); + +export type ClientRequest__UserInput = + | { + readonly text: string; + readonly text_elements?: ReadonlyArray; + readonly type: "text"; + } + | { readonly type: "image"; readonly url: string } + | { readonly path: string; readonly type: "localImage" } + | { readonly name: string; readonly path: string; readonly type: "skill" } + | { readonly name: string; readonly path: string; readonly type: "mention" }; +export const ClientRequest__UserInput = Schema.Union( + [ + Schema.Struct({ + text: Schema.String, + text_elements: Schema.optionalKey( + Schema.Array(ClientRequest__TextElement).annotate({ + description: "UI-defined spans within `text` used to render or persist special elements.", + default: [], + }), + ), + type: Schema.Literal("text").annotate({ title: "TextUserInputType" }), + }).annotate({ title: "TextUserInput" }), + Schema.Struct({ + type: Schema.Literal("image").annotate({ title: "ImageUserInputType" }), + url: Schema.String, + }).annotate({ title: "ImageUserInput" }), + Schema.Struct({ + path: Schema.String, + type: Schema.Literal("localImage").annotate({ title: "LocalImageUserInputType" }), + }).annotate({ title: "LocalImageUserInput" }), + Schema.Struct({ + name: Schema.String, + path: Schema.String, + type: Schema.Literal("skill").annotate({ title: "SkillUserInputType" }), + }).annotate({ title: "SkillUserInput" }), + Schema.Struct({ + name: Schema.String, + path: Schema.String, + type: Schema.Literal("mention").annotate({ title: "MentionUserInputType" }), + }).annotate({ title: "MentionUserInput" }), + ], + { mode: "oneOf" }, +); + +export type ClientRequest__ThreadMetadataUpdateParams = { + readonly gitInfo?: ClientRequest__ThreadMetadataGitInfoUpdateParams | null; + readonly threadId: string; +}; +export const ClientRequest__ThreadMetadataUpdateParams = Schema.Struct({ + gitInfo: Schema.optionalKey( + Schema.Union([ClientRequest__ThreadMetadataGitInfoUpdateParams, Schema.Null]).annotate({ + description: + "Patch the stored Git metadata for this thread. Omit a field to leave it unchanged, set it to `null` to clear it, or provide a string to replace the stored value.", + }), + ), + threadId: Schema.String, +}); + +export type ClientRequest__ThreadListParams = { + readonly archived?: boolean | null; + readonly cursor?: string | null; + readonly cwd?: string | null; + readonly limit?: number | null; + readonly modelProviders?: ReadonlyArray | null; + readonly searchTerm?: string | null; + readonly sortKey?: ClientRequest__ThreadSortKey | null; + readonly sourceKinds?: ReadonlyArray | null; +}; +export const ClientRequest__ThreadListParams = Schema.Struct({ + archived: Schema.optionalKey( + Schema.Union([ + Schema.Boolean.annotate({ + description: + "Optional archived filter; when set to true, only archived threads are returned. If false or null, only non-archived threads are returned.", + }), + Schema.Null, + ]), + ), + cursor: Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + description: "Opaque pagination cursor returned by a previous call.", + }), + Schema.Null, + ]), + ), + cwd: Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + description: + "Optional cwd filter; when set, only threads whose session cwd exactly matches this path are returned.", + }), + Schema.Null, + ]), + ), + limit: Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ + description: "Optional page size; defaults to a reasonable server-side value.", + format: "uint32", + }) + .check(Schema.isInt()) + .check(Schema.isGreaterThanOrEqualTo(0)), + Schema.Null, + ]), + ), + modelProviders: Schema.optionalKey( + Schema.Union([ + Schema.Array(Schema.String).annotate({ + description: + "Optional provider filter; when set, only sessions recorded under these providers are returned. When present but empty, includes all providers.", + }), + Schema.Null, + ]), + ), + searchTerm: Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + description: "Optional substring filter for the extracted thread title.", + }), + Schema.Null, + ]), + ), + sortKey: Schema.optionalKey( + Schema.Union([ClientRequest__ThreadSortKey, Schema.Null]).annotate({ + description: "Optional sort key; defaults to created_at.", + }), + ), + sourceKinds: Schema.optionalKey( + Schema.Union([ + Schema.Array(ClientRequest__ThreadSourceKind).annotate({ + description: + "Optional source filter; when set, only sessions from these source kinds are returned. When omitted or empty, defaults to interactive sources.", + }), + Schema.Null, + ]), + ), +}); + +export type ClientRequest__ThreadStartParams = { + readonly approvalPolicy?: ClientRequest__AskForApproval | null; + readonly approvalsReviewer?: ClientRequest__ApprovalsReviewer | null; + readonly baseInstructions?: string | null; + readonly config?: { readonly [x: string]: unknown } | null; + readonly cwd?: string | null; + readonly developerInstructions?: string | null; + readonly ephemeral?: boolean | null; + readonly model?: string | null; + readonly modelProvider?: string | null; + readonly personality?: ClientRequest__Personality | null; + readonly sandbox?: ClientRequest__SandboxMode | null; + readonly serviceName?: string | null; + readonly serviceTier?: ClientRequest__ServiceTier | null | null; + readonly sessionStartSource?: ClientRequest__ThreadStartSource | null; +}; +export const ClientRequest__ThreadStartParams = Schema.Struct({ + approvalPolicy: Schema.optionalKey(Schema.Union([ClientRequest__AskForApproval, Schema.Null])), + approvalsReviewer: Schema.optionalKey( + Schema.Union([ClientRequest__ApprovalsReviewer, Schema.Null]).annotate({ + description: + "Override where approval requests are routed for review on this thread and subsequent turns.", + }), + ), + baseInstructions: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + config: Schema.optionalKey( + Schema.Union([Schema.Record(Schema.String, Schema.Unknown), Schema.Null]), + ), + cwd: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + developerInstructions: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + ephemeral: Schema.optionalKey(Schema.Union([Schema.Boolean, Schema.Null])), + model: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + modelProvider: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + personality: Schema.optionalKey(Schema.Union([ClientRequest__Personality, Schema.Null])), + sandbox: Schema.optionalKey(Schema.Union([ClientRequest__SandboxMode, Schema.Null])), + serviceName: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + serviceTier: Schema.optionalKey( + Schema.Union([Schema.Union([ClientRequest__ServiceTier, Schema.Null]), Schema.Null]), + ), + sessionStartSource: Schema.optionalKey( + Schema.Union([ClientRequest__ThreadStartSource, Schema.Null]), + ), +}); + +export type ClientRequest__WindowsSandboxSetupStartParams = { + readonly cwd?: ClientRequest__AbsolutePathBuf | null; + readonly mode: ClientRequest__WindowsSandboxSetupMode; +}; +export const ClientRequest__WindowsSandboxSetupStartParams = Schema.Struct({ + cwd: Schema.optionalKey(Schema.Union([ClientRequest__AbsolutePathBuf, Schema.Null])), + mode: ClientRequest__WindowsSandboxSetupMode, +}); + +export type CommandExecutionRequestApprovalParams__AdditionalFileSystemPermissions = { + readonly read?: ReadonlyArray | null; + readonly write?: ReadonlyArray | null; +}; +export const CommandExecutionRequestApprovalParams__AdditionalFileSystemPermissions = Schema.Struct( + { + read: Schema.optionalKey( + Schema.Union([ + Schema.Array(CommandExecutionRequestApprovalParams__AbsolutePathBuf), + Schema.Null, + ]), + ), + write: Schema.optionalKey( + Schema.Union([ + Schema.Array(CommandExecutionRequestApprovalParams__AbsolutePathBuf), + Schema.Null, + ]), + ), + }, +); + +export type CommandExecutionRequestApprovalParams__NetworkApprovalContext = { + readonly host: string; + readonly protocol: CommandExecutionRequestApprovalParams__NetworkApprovalProtocol; +}; +export const CommandExecutionRequestApprovalParams__NetworkApprovalContext = Schema.Struct({ + host: Schema.String, + protocol: CommandExecutionRequestApprovalParams__NetworkApprovalProtocol, +}); + +export type CommandExecutionRequestApprovalParams__NetworkPolicyAmendment = { + readonly action: CommandExecutionRequestApprovalParams__NetworkPolicyRuleAction; + readonly host: string; +}; +export const CommandExecutionRequestApprovalParams__NetworkPolicyAmendment = Schema.Struct({ + action: CommandExecutionRequestApprovalParams__NetworkPolicyRuleAction, + host: Schema.String, +}); + +export type CommandExecutionRequestApprovalResponse__NetworkPolicyAmendment = { + readonly action: CommandExecutionRequestApprovalResponse__NetworkPolicyRuleAction; + readonly host: string; +}; +export const CommandExecutionRequestApprovalResponse__NetworkPolicyAmendment = Schema.Struct({ + action: CommandExecutionRequestApprovalResponse__NetworkPolicyRuleAction, + host: Schema.String, +}); + +export type ExecCommandApprovalResponse__NetworkPolicyAmendment = { + readonly action: ExecCommandApprovalResponse__NetworkPolicyRuleAction; + readonly host: string; +}; +export const ExecCommandApprovalResponse__NetworkPolicyAmendment = Schema.Struct({ + action: ExecCommandApprovalResponse__NetworkPolicyRuleAction, + host: Schema.String, +}); + +export type FuzzyFileSearchResponse__FuzzyFileSearchResult = { + readonly file_name: string; + readonly indices?: ReadonlyArray | null; + readonly match_type: FuzzyFileSearchResponse__FuzzyFileSearchMatchType; + readonly path: string; + readonly root: string; + readonly score: number; +}; +export const FuzzyFileSearchResponse__FuzzyFileSearchResult = Schema.Struct({ + file_name: Schema.String, + indices: Schema.optionalKey( + Schema.Union([ + Schema.Array( + Schema.Number.annotate({ format: "uint32" }) + .check(Schema.isInt()) + .check(Schema.isGreaterThanOrEqualTo(0)), + ), + Schema.Null, + ]), + ), + match_type: FuzzyFileSearchResponse__FuzzyFileSearchMatchType, + path: Schema.String, + root: Schema.String, + score: Schema.Number.annotate({ format: "uint32" }) + .check(Schema.isInt()) + .check(Schema.isGreaterThanOrEqualTo(0)), +}).annotate({ description: "Superset of [`codex_file_search::FileMatch`]" }); + +export type FuzzyFileSearchSessionUpdatedNotification__FuzzyFileSearchResult = { + readonly file_name: string; + readonly indices?: ReadonlyArray | null; + readonly match_type: FuzzyFileSearchSessionUpdatedNotification__FuzzyFileSearchMatchType; + readonly path: string; + readonly root: string; + readonly score: number; +}; +export const FuzzyFileSearchSessionUpdatedNotification__FuzzyFileSearchResult = Schema.Struct({ + file_name: Schema.String, + indices: Schema.optionalKey( + Schema.Union([ + Schema.Array( + Schema.Number.annotate({ format: "uint32" }) + .check(Schema.isInt()) + .check(Schema.isGreaterThanOrEqualTo(0)), + ), + Schema.Null, + ]), + ), + match_type: FuzzyFileSearchSessionUpdatedNotification__FuzzyFileSearchMatchType, + path: Schema.String, + root: Schema.String, + score: Schema.Number.annotate({ format: "uint32" }) + .check(Schema.isInt()) + .check(Schema.isGreaterThanOrEqualTo(0)), +}).annotate({ description: "Superset of [`codex_file_search::FileMatch`]" }); + +export type JSONRPCMessage__JSONRPCError = { + readonly error: JSONRPCMessage__JSONRPCErrorError; + readonly id: JSONRPCMessage__RequestId; +}; +export const JSONRPCMessage__JSONRPCError = Schema.Struct({ + error: JSONRPCMessage__JSONRPCErrorError, + id: JSONRPCMessage__RequestId, +}).annotate({ description: "A response to a request that indicates an error occurred." }); + +export type JSONRPCMessage__JSONRPCResponse = { + readonly id: JSONRPCMessage__RequestId; + readonly result: unknown; +}; +export const JSONRPCMessage__JSONRPCResponse = Schema.Struct({ + id: JSONRPCMessage__RequestId, + result: Schema.Unknown, +}).annotate({ description: "A successful (non-error) response to a request." }); + +export type JSONRPCMessage__JSONRPCRequest = { + readonly id: JSONRPCMessage__RequestId; + readonly method: string; + readonly params?: unknown; + readonly trace?: JSONRPCMessage__W3cTraceContext | null; +}; +export const JSONRPCMessage__JSONRPCRequest = Schema.Struct({ + id: JSONRPCMessage__RequestId, + method: Schema.String, + params: Schema.optionalKey(Schema.Unknown), + trace: Schema.optionalKey( + Schema.Union([JSONRPCMessage__W3cTraceContext, Schema.Null]).annotate({ + description: "Optional W3C Trace Context for distributed tracing.", + }), + ), +}).annotate({ description: "A request that expects a response." }); + +export type McpServerElicitationRequestParams__McpElicitationBooleanSchema = { + readonly default?: boolean | null; + readonly description?: string | null; + readonly title?: string | null; + readonly type: McpServerElicitationRequestParams__McpElicitationBooleanType; +}; +export const McpServerElicitationRequestParams__McpElicitationBooleanSchema = Schema.Struct({ + default: Schema.optionalKey(Schema.Union([Schema.Boolean, Schema.Null])), + description: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + title: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + type: McpServerElicitationRequestParams__McpElicitationBooleanType, +}); + +export type McpServerElicitationRequestParams__McpElicitationTitledEnumItems = { + readonly anyOf: ReadonlyArray; +}; +export const McpServerElicitationRequestParams__McpElicitationTitledEnumItems = Schema.Struct({ + anyOf: Schema.Array(McpServerElicitationRequestParams__McpElicitationConstOption), +}); + +export type McpServerElicitationRequestParams__McpElicitationNumberSchema = { + readonly default?: number | null; + readonly description?: string | null; + readonly maximum?: number | null; + readonly minimum?: number | null; + readonly title?: string | null; + readonly type: McpServerElicitationRequestParams__McpElicitationNumberType; +}; +export const McpServerElicitationRequestParams__McpElicitationNumberSchema = Schema.Struct({ + default: Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ format: "double" }).check(Schema.isFinite()), + Schema.Null, + ]), + ), + description: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + maximum: Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ format: "double" }).check(Schema.isFinite()), + Schema.Null, + ]), + ), + minimum: Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ format: "double" }).check(Schema.isFinite()), + Schema.Null, + ]), + ), + title: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + type: McpServerElicitationRequestParams__McpElicitationNumberType, +}); + +export type McpServerElicitationRequestParams__McpElicitationLegacyTitledEnumSchema = { + readonly default?: string | null; + readonly description?: string | null; + readonly enum: ReadonlyArray; + readonly enumNames?: ReadonlyArray | null; + readonly title?: string | null; + readonly type: McpServerElicitationRequestParams__McpElicitationStringType; +}; +export const McpServerElicitationRequestParams__McpElicitationLegacyTitledEnumSchema = + Schema.Struct({ + default: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + description: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + enum: Schema.Array(Schema.String), + enumNames: Schema.optionalKey(Schema.Union([Schema.Array(Schema.String), Schema.Null])), + title: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + type: McpServerElicitationRequestParams__McpElicitationStringType, + }); + +export type McpServerElicitationRequestParams__McpElicitationStringSchema = { + readonly default?: string | null; + readonly description?: string | null; + readonly format?: McpServerElicitationRequestParams__McpElicitationStringFormat | null; + readonly maxLength?: number | null; + readonly minLength?: number | null; + readonly title?: string | null; + readonly type: McpServerElicitationRequestParams__McpElicitationStringType; +}; +export const McpServerElicitationRequestParams__McpElicitationStringSchema = Schema.Struct({ + default: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + description: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + format: Schema.optionalKey( + Schema.Union([McpServerElicitationRequestParams__McpElicitationStringFormat, Schema.Null]), + ), + maxLength: Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ format: "uint32" }) + .check(Schema.isInt()) + .check(Schema.isGreaterThanOrEqualTo(0)), + Schema.Null, + ]), + ), + minLength: Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ format: "uint32" }) + .check(Schema.isInt()) + .check(Schema.isGreaterThanOrEqualTo(0)), + Schema.Null, + ]), + ), + title: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + type: McpServerElicitationRequestParams__McpElicitationStringType, +}); + +export type McpServerElicitationRequestParams__McpElicitationTitledSingleSelectEnumSchema = { + readonly default?: string | null; + readonly description?: string | null; + readonly oneOf: ReadonlyArray; + readonly title?: string | null; + readonly type: McpServerElicitationRequestParams__McpElicitationStringType; +}; +export const McpServerElicitationRequestParams__McpElicitationTitledSingleSelectEnumSchema = + Schema.Struct({ + default: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + description: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + oneOf: Schema.Array(McpServerElicitationRequestParams__McpElicitationConstOption), + title: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + type: McpServerElicitationRequestParams__McpElicitationStringType, + }); + +export type McpServerElicitationRequestParams__McpElicitationUntitledEnumItems = { + readonly enum: ReadonlyArray; + readonly type: McpServerElicitationRequestParams__McpElicitationStringType; +}; +export const McpServerElicitationRequestParams__McpElicitationUntitledEnumItems = Schema.Struct({ + enum: Schema.Array(Schema.String), + type: McpServerElicitationRequestParams__McpElicitationStringType, +}); + +export type McpServerElicitationRequestParams__McpElicitationUntitledSingleSelectEnumSchema = { + readonly default?: string | null; + readonly description?: string | null; + readonly enum: ReadonlyArray; + readonly title?: string | null; + readonly type: McpServerElicitationRequestParams__McpElicitationStringType; +}; +export const McpServerElicitationRequestParams__McpElicitationUntitledSingleSelectEnumSchema = + Schema.Struct({ + default: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + description: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + enum: Schema.Array(Schema.String), + title: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + type: McpServerElicitationRequestParams__McpElicitationStringType, + }); + +export type PermissionsRequestApprovalParams__AdditionalFileSystemPermissions = { + readonly read?: ReadonlyArray | null; + readonly write?: ReadonlyArray | null; +}; +export const PermissionsRequestApprovalParams__AdditionalFileSystemPermissions = Schema.Struct({ + read: Schema.optionalKey( + Schema.Union([Schema.Array(PermissionsRequestApprovalParams__AbsolutePathBuf), Schema.Null]), + ), + write: Schema.optionalKey( + Schema.Union([Schema.Array(PermissionsRequestApprovalParams__AbsolutePathBuf), Schema.Null]), + ), +}); + +export type PermissionsRequestApprovalResponse__AdditionalFileSystemPermissions = { + readonly read?: ReadonlyArray | null; + readonly write?: ReadonlyArray | null; +}; +export const PermissionsRequestApprovalResponse__AdditionalFileSystemPermissions = Schema.Struct({ + read: Schema.optionalKey( + Schema.Union([Schema.Array(PermissionsRequestApprovalResponse__AbsolutePathBuf), Schema.Null]), + ), + write: Schema.optionalKey( + Schema.Union([Schema.Array(PermissionsRequestApprovalResponse__AbsolutePathBuf), Schema.Null]), + ), +}); + +export type ServerNotification__FsChangedNotification = { + readonly changedPaths: ReadonlyArray; + readonly watchId: string; +}; +export const ServerNotification__FsChangedNotification = Schema.Struct({ + changedPaths: Schema.Array(ServerNotification__AbsolutePathBuf).annotate({ + description: "File or directory paths associated with this event.", + }), + watchId: Schema.String.annotate({ + description: "Watch identifier previously provided to `fs/watch`.", + }), +}).annotate({ description: "Filesystem watch notification emitted for `fs/watch` subscribers." }); + +export type ServerNotification__AppMetadata = { + readonly categories?: ReadonlyArray | null; + readonly developer?: string | null; + readonly firstPartyRequiresInstall?: boolean | null; + readonly firstPartyType?: string | null; + readonly review?: ServerNotification__AppReview | null; + readonly screenshots?: ReadonlyArray | null; + readonly seoDescription?: string | null; + readonly showInComposerWhenUnlinked?: boolean | null; + readonly subCategories?: ReadonlyArray | null; + readonly version?: string | null; + readonly versionId?: string | null; + readonly versionNotes?: string | null; +}; +export const ServerNotification__AppMetadata = Schema.Struct({ + categories: Schema.optionalKey(Schema.Union([Schema.Array(Schema.String), Schema.Null])), + developer: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + firstPartyRequiresInstall: Schema.optionalKey(Schema.Union([Schema.Boolean, Schema.Null])), + firstPartyType: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + review: Schema.optionalKey(Schema.Union([ServerNotification__AppReview, Schema.Null])), + screenshots: Schema.optionalKey( + Schema.Union([Schema.Array(ServerNotification__AppScreenshot), Schema.Null]), + ), + seoDescription: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + showInComposerWhenUnlinked: Schema.optionalKey(Schema.Union([Schema.Boolean, Schema.Null])), + subCategories: Schema.optionalKey(Schema.Union([Schema.Array(Schema.String), Schema.Null])), + version: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + versionId: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + versionNotes: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), +}); + +export type ServerNotification__CollabAgentState = { + readonly message?: string | null; + readonly status: ServerNotification__CollabAgentStatus; +}; +export const ServerNotification__CollabAgentState = Schema.Struct({ + message: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + status: ServerNotification__CollabAgentStatus, +}); + +export type ServerNotification__FuzzyFileSearchResult = { + readonly file_name: string; + readonly indices?: ReadonlyArray | null; + readonly match_type: ServerNotification__FuzzyFileSearchMatchType; + readonly path: string; + readonly root: string; + readonly score: number; +}; +export const ServerNotification__FuzzyFileSearchResult = Schema.Struct({ + file_name: Schema.String, + indices: Schema.optionalKey( + Schema.Union([ + Schema.Array( + Schema.Number.annotate({ format: "uint32" }) + .check(Schema.isInt()) + .check(Schema.isGreaterThanOrEqualTo(0)), + ), + Schema.Null, + ]), + ), + match_type: ServerNotification__FuzzyFileSearchMatchType, + path: Schema.String, + root: Schema.String, + score: Schema.Number.annotate({ format: "uint32" }) + .check(Schema.isInt()) + .check(Schema.isGreaterThanOrEqualTo(0)), +}).annotate({ description: "Superset of [`codex_file_search::FileMatch`]" }); + +export type ServerNotification__GuardianApprovalReview = { + readonly rationale?: string | null; + readonly riskLevel?: ServerNotification__GuardianRiskLevel | null; + readonly status: ServerNotification__GuardianApprovalReviewStatus; + readonly userAuthorization?: ServerNotification__GuardianUserAuthorization | null; +}; +export const ServerNotification__GuardianApprovalReview = Schema.Struct({ + rationale: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + riskLevel: Schema.optionalKey(Schema.Union([ServerNotification__GuardianRiskLevel, Schema.Null])), + status: ServerNotification__GuardianApprovalReviewStatus, + userAuthorization: Schema.optionalKey( + Schema.Union([ServerNotification__GuardianUserAuthorization, Schema.Null]), + ), +}).annotate({ + description: + "[UNSTABLE] Temporary guardian approval review payload used by `item/autoApprovalReview/*` notifications. This shape is expected to change soon.", +}); + +export type ServerNotification__HookOutputEntry = { + readonly kind: ServerNotification__HookOutputEntryKind; + readonly text: string; +}; +export const ServerNotification__HookOutputEntry = Schema.Struct({ + kind: ServerNotification__HookOutputEntryKind, + text: Schema.String, +}); + +export type ServerNotification__McpServerStatusUpdatedNotification = { + readonly error?: string | null; + readonly name: string; + readonly status: ServerNotification__McpServerStartupState; +}; +export const ServerNotification__McpServerStatusUpdatedNotification = Schema.Struct({ + error: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + name: Schema.String, + status: ServerNotification__McpServerStartupState, +}); + +export type ServerNotification__MemoryCitation = { + readonly entries: ReadonlyArray; + readonly threadIds: ReadonlyArray; +}; +export const ServerNotification__MemoryCitation = Schema.Struct({ + entries: Schema.Array(ServerNotification__MemoryCitationEntry), + threadIds: Schema.Array(Schema.String), +}); + +export type ServerNotification__ModelReroutedNotification = { + readonly fromModel: string; + readonly reason: ServerNotification__ModelRerouteReason; + readonly threadId: string; + readonly toModel: string; + readonly turnId: string; +}; +export const ServerNotification__ModelReroutedNotification = Schema.Struct({ + fromModel: Schema.String, + reason: ServerNotification__ModelRerouteReason, + threadId: Schema.String, + toModel: Schema.String, + turnId: Schema.String, +}); + +export type ServerNotification__GuardianApprovalReviewAction = + | { + readonly command: string; + readonly cwd: string; + readonly source: ServerNotification__GuardianCommandSource; + readonly type: "command"; + } + | { + readonly argv: ReadonlyArray; + readonly cwd: string; + readonly program: string; + readonly source: ServerNotification__GuardianCommandSource; + readonly type: "execve"; + } + | { readonly cwd: string; readonly files: ReadonlyArray; readonly type: "applyPatch" } + | { + readonly host: string; + readonly port: number; + readonly protocol: ServerNotification__NetworkApprovalProtocol; + readonly target: string; + readonly type: "networkAccess"; + } + | { + readonly connectorId?: string | null; + readonly connectorName?: string | null; + readonly server: string; + readonly toolName: string; + readonly toolTitle?: string | null; + readonly type: "mcpToolCall"; + }; +export const ServerNotification__GuardianApprovalReviewAction = Schema.Union( + [ + Schema.Struct({ + command: Schema.String, + cwd: Schema.String, + source: ServerNotification__GuardianCommandSource, + type: Schema.Literal("command").annotate({ + title: "CommandGuardianApprovalReviewActionType", + }), + }).annotate({ title: "CommandGuardianApprovalReviewAction" }), + Schema.Struct({ + argv: Schema.Array(Schema.String), + cwd: Schema.String, + program: Schema.String, + source: ServerNotification__GuardianCommandSource, + type: Schema.Literal("execve").annotate({ title: "ExecveGuardianApprovalReviewActionType" }), + }).annotate({ title: "ExecveGuardianApprovalReviewAction" }), + Schema.Struct({ + cwd: Schema.String, + files: Schema.Array(Schema.String), + type: Schema.Literal("applyPatch").annotate({ + title: "ApplyPatchGuardianApprovalReviewActionType", + }), + }).annotate({ title: "ApplyPatchGuardianApprovalReviewAction" }), + Schema.Struct({ + host: Schema.String, + port: Schema.Number.annotate({ format: "uint16" }) + .check(Schema.isInt()) + .check(Schema.isGreaterThanOrEqualTo(0)), + protocol: ServerNotification__NetworkApprovalProtocol, + target: Schema.String, + type: Schema.Literal("networkAccess").annotate({ + title: "NetworkAccessGuardianApprovalReviewActionType", + }), + }).annotate({ title: "NetworkAccessGuardianApprovalReviewAction" }), + Schema.Struct({ + connectorId: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + connectorName: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + server: Schema.String, + toolName: Schema.String, + toolTitle: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + type: Schema.Literal("mcpToolCall").annotate({ + title: "McpToolCallGuardianApprovalReviewActionType", + }), + }).annotate({ title: "McpToolCallGuardianApprovalReviewAction" }), + ], + { mode: "oneOf" }, +); + +export type ServerNotification__CodexErrorInfo = + | "contextWindowExceeded" + | "usageLimitExceeded" + | "serverOverloaded" + | "internalServerError" + | "unauthorized" + | "badRequest" + | "threadRollbackFailed" + | "sandboxError" + | "other" + | { readonly httpConnectionFailed: { readonly httpStatusCode?: number | null } } + | { readonly responseStreamConnectionFailed: { readonly httpStatusCode?: number | null } } + | { readonly responseStreamDisconnected: { readonly httpStatusCode?: number | null } } + | { readonly responseTooManyFailedAttempts: { readonly httpStatusCode?: number | null } } + | { + readonly activeTurnNotSteerable: { + readonly turnKind: ServerNotification__NonSteerableTurnKind; + }; + }; +export const ServerNotification__CodexErrorInfo = Schema.Union( + [ + Schema.Literals([ + "contextWindowExceeded", + "usageLimitExceeded", + "serverOverloaded", + "internalServerError", + "unauthorized", + "badRequest", + "threadRollbackFailed", + "sandboxError", + "other", + ]), + Schema.Struct({ + httpConnectionFailed: Schema.Struct({ + httpStatusCode: Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ format: "uint16" }) + .check(Schema.isInt()) + .check(Schema.isGreaterThanOrEqualTo(0)), + Schema.Null, + ]), + ), + }), + }).annotate({ title: "HttpConnectionFailedCodexErrorInfo" }), + Schema.Struct({ + responseStreamConnectionFailed: Schema.Struct({ + httpStatusCode: Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ format: "uint16" }) + .check(Schema.isInt()) + .check(Schema.isGreaterThanOrEqualTo(0)), + Schema.Null, + ]), + ), + }), + }).annotate({ + title: "ResponseStreamConnectionFailedCodexErrorInfo", + description: "Failed to connect to the response SSE stream.", + }), + Schema.Struct({ + responseStreamDisconnected: Schema.Struct({ + httpStatusCode: Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ format: "uint16" }) + .check(Schema.isInt()) + .check(Schema.isGreaterThanOrEqualTo(0)), + Schema.Null, + ]), + ), + }), + }).annotate({ + title: "ResponseStreamDisconnectedCodexErrorInfo", + description: + "The response SSE stream disconnected in the middle of a turn before completion.", + }), + Schema.Struct({ + responseTooManyFailedAttempts: Schema.Struct({ + httpStatusCode: Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ format: "uint16" }) + .check(Schema.isInt()) + .check(Schema.isGreaterThanOrEqualTo(0)), + Schema.Null, + ]), + ), + }), + }).annotate({ + title: "ResponseTooManyFailedAttemptsCodexErrorInfo", + description: "Reached the retry limit for responses.", + }), + Schema.Struct({ + activeTurnNotSteerable: Schema.Struct({ turnKind: ServerNotification__NonSteerableTurnKind }), + }).annotate({ + title: "ActiveTurnNotSteerableCodexErrorInfo", + description: + "Returned when `turn/start` or `turn/steer` is submitted while the current active turn cannot accept same-turn steering, for example `/review` or manual `/compact`.", + }), + ], + { mode: "oneOf" }, +).annotate({ + description: + "This translation layer make sure that we expose codex error code in camel case.\n\nWhen an upstream HTTP status is available (for example, from the Responses API or a provider), it is forwarded in `httpStatusCode` on the relevant `codexErrorInfo` variant.", +}); + +export type ServerNotification__FileUpdateChange = { + readonly diff: string; + readonly kind: ServerNotification__PatchChangeKind; + readonly path: string; +}; +export const ServerNotification__FileUpdateChange = Schema.Struct({ + diff: Schema.String, + kind: ServerNotification__PatchChangeKind, + path: Schema.String, +}); + +export type ServerNotification__AccountUpdatedNotification = { + readonly authMode?: ServerNotification__AuthMode | null; + readonly planType?: ServerNotification__PlanType | null; +}; +export const ServerNotification__AccountUpdatedNotification = Schema.Struct({ + authMode: Schema.optionalKey(Schema.Union([ServerNotification__AuthMode, Schema.Null])), + planType: Schema.optionalKey(Schema.Union([ServerNotification__PlanType, Schema.Null])), +}); + +export type ServerNotification__RateLimitSnapshot = { + readonly credits?: ServerNotification__CreditsSnapshot | null; + readonly limitId?: string | null; + readonly limitName?: string | null; + readonly planType?: ServerNotification__PlanType | null; + readonly primary?: ServerNotification__RateLimitWindow | null; + readonly secondary?: ServerNotification__RateLimitWindow | null; +}; +export const ServerNotification__RateLimitSnapshot = Schema.Struct({ + credits: Schema.optionalKey(Schema.Union([ServerNotification__CreditsSnapshot, Schema.Null])), + limitId: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + limitName: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + planType: Schema.optionalKey(Schema.Union([ServerNotification__PlanType, Schema.Null])), + primary: Schema.optionalKey(Schema.Union([ServerNotification__RateLimitWindow, Schema.Null])), + secondary: Schema.optionalKey(Schema.Union([ServerNotification__RateLimitWindow, Schema.Null])), +}); + +export type ServerNotification__ThreadRealtimeStartedNotification = { + readonly sessionId?: string | null; + readonly threadId: string; + readonly version: ServerNotification__RealtimeConversationVersion; +}; +export const ServerNotification__ThreadRealtimeStartedNotification = Schema.Struct({ + sessionId: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + threadId: Schema.String, + version: ServerNotification__RealtimeConversationVersion, +}).annotate({ description: "EXPERIMENTAL - emitted when thread realtime startup is accepted." }); + +export type ServerNotification__ServerRequestResolvedNotification = { + readonly requestId: ServerNotification__RequestId; + readonly threadId: string; +}; +export const ServerNotification__ServerRequestResolvedNotification = Schema.Struct({ + requestId: ServerNotification__RequestId, + threadId: Schema.String, +}); + +export type ServerNotification__UserInput = + | { + readonly text: string; + readonly text_elements?: ReadonlyArray; + readonly type: "text"; + } + | { readonly type: "image"; readonly url: string } + | { readonly path: string; readonly type: "localImage" } + | { readonly name: string; readonly path: string; readonly type: "skill" } + | { readonly name: string; readonly path: string; readonly type: "mention" }; +export const ServerNotification__UserInput = Schema.Union( + [ + Schema.Struct({ + text: Schema.String, + text_elements: Schema.optionalKey( + Schema.Array(ServerNotification__TextElement).annotate({ + description: "UI-defined spans within `text` used to render or persist special elements.", + default: [], + }), + ), + type: Schema.Literal("text").annotate({ title: "TextUserInputType" }), + }).annotate({ title: "TextUserInput" }), + Schema.Struct({ + type: Schema.Literal("image").annotate({ title: "ImageUserInputType" }), + url: Schema.String, + }).annotate({ title: "ImageUserInput" }), + Schema.Struct({ + path: Schema.String, + type: Schema.Literal("localImage").annotate({ title: "LocalImageUserInputType" }), + }).annotate({ title: "LocalImageUserInput" }), + Schema.Struct({ + name: Schema.String, + path: Schema.String, + type: Schema.Literal("skill").annotate({ title: "SkillUserInputType" }), + }).annotate({ title: "SkillUserInput" }), + Schema.Struct({ + name: Schema.String, + path: Schema.String, + type: Schema.Literal("mention").annotate({ title: "MentionUserInputType" }), + }).annotate({ title: "MentionUserInput" }), + ], + { mode: "oneOf" }, +); + +export type ServerNotification__TextRange = { + readonly end: ServerNotification__TextPosition; + readonly start: ServerNotification__TextPosition; +}; +export const ServerNotification__TextRange = Schema.Struct({ + end: ServerNotification__TextPosition, + start: ServerNotification__TextPosition, +}); + +export type ServerNotification__ThreadStatus = + | { readonly type: "notLoaded" } + | { readonly type: "idle" } + | { readonly type: "systemError" } + | { + readonly activeFlags: ReadonlyArray; + readonly type: "active"; + }; +export const ServerNotification__ThreadStatus = Schema.Union( + [ + Schema.Struct({ + type: Schema.Literal("notLoaded").annotate({ title: "NotLoadedThreadStatusType" }), + }).annotate({ title: "NotLoadedThreadStatus" }), + Schema.Struct({ + type: Schema.Literal("idle").annotate({ title: "IdleThreadStatusType" }), + }).annotate({ title: "IdleThreadStatus" }), + Schema.Struct({ + type: Schema.Literal("systemError").annotate({ title: "SystemErrorThreadStatusType" }), + }).annotate({ title: "SystemErrorThreadStatus" }), + Schema.Struct({ + activeFlags: Schema.Array(ServerNotification__ThreadActiveFlag), + type: Schema.Literal("active").annotate({ title: "ActiveThreadStatusType" }), + }).annotate({ title: "ActiveThreadStatus" }), + ], + { mode: "oneOf" }, +); + +export type ServerNotification__SubAgentSource = + | "review" + | "compact" + | "memory_consolidation" + | { + readonly thread_spawn: { + readonly agent_nickname?: string | null; + readonly agent_path?: ServerNotification__AgentPath | null; + readonly agent_role?: string | null; + readonly depth: number; + readonly parent_thread_id: ServerNotification__ThreadId; + }; + } + | { readonly other: string }; +export const ServerNotification__SubAgentSource = Schema.Union( + [ + Schema.Literals(["review", "compact", "memory_consolidation"]), + Schema.Struct({ + thread_spawn: Schema.Struct({ + agent_nickname: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + agent_path: Schema.optionalKey(Schema.Union([ServerNotification__AgentPath, Schema.Null])), + agent_role: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + depth: Schema.Number.annotate({ format: "int32" }).check(Schema.isInt()), + parent_thread_id: ServerNotification__ThreadId, + }), + }).annotate({ title: "ThreadSpawnSubAgentSource" }), + Schema.Struct({ other: Schema.String }).annotate({ title: "OtherSubAgentSource" }), + ], + { mode: "oneOf" }, +); + +export type ServerNotification__ThreadRealtimeOutputAudioDeltaNotification = { + readonly audio: ServerNotification__ThreadRealtimeAudioChunk; + readonly threadId: string; +}; +export const ServerNotification__ThreadRealtimeOutputAudioDeltaNotification = Schema.Struct({ + audio: ServerNotification__ThreadRealtimeAudioChunk, + threadId: Schema.String, +}).annotate({ description: "EXPERIMENTAL - streamed output audio emitted by thread realtime." }); + +export type ServerNotification__ThreadTokenUsage = { + readonly last: ServerNotification__TokenUsageBreakdown; + readonly modelContextWindow?: number | null; + readonly total: ServerNotification__TokenUsageBreakdown; +}; +export const ServerNotification__ThreadTokenUsage = Schema.Struct({ + last: ServerNotification__TokenUsageBreakdown, + modelContextWindow: Schema.optionalKey( + Schema.Union([Schema.Number.annotate({ format: "int64" }).check(Schema.isInt()), Schema.Null]), + ), + total: ServerNotification__TokenUsageBreakdown, +}); + +export type ServerNotification__TurnPlanStep = { + readonly status: ServerNotification__TurnPlanStepStatus; + readonly step: string; +}; +export const ServerNotification__TurnPlanStep = Schema.Struct({ + status: ServerNotification__TurnPlanStepStatus, + step: Schema.String, +}); + +export type ServerNotification__WindowsSandboxSetupCompletedNotification = { + readonly error?: string | null; + readonly mode: ServerNotification__WindowsSandboxSetupMode; + readonly success: boolean; +}; +export const ServerNotification__WindowsSandboxSetupCompletedNotification = Schema.Struct({ + error: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + mode: ServerNotification__WindowsSandboxSetupMode, + success: Schema.Boolean, +}); + +export type ServerRequest__AdditionalFileSystemPermissions = { + readonly read?: ReadonlyArray | null; + readonly write?: ReadonlyArray | null; +}; +export const ServerRequest__AdditionalFileSystemPermissions = Schema.Struct({ + read: Schema.optionalKey( + Schema.Union([Schema.Array(ServerRequest__AbsolutePathBuf), Schema.Null]), + ), + write: Schema.optionalKey( + Schema.Union([Schema.Array(ServerRequest__AbsolutePathBuf), Schema.Null]), + ), +}); + +export type ServerRequest__ChatgptAuthTokensRefreshParams = { + readonly previousAccountId?: string | null; + readonly reason: ServerRequest__ChatgptAuthTokensRefreshReason; +}; +export const ServerRequest__ChatgptAuthTokensRefreshParams = Schema.Struct({ + previousAccountId: Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + description: + "Workspace/account identifier that Codex was previously using.\n\nClients that manage multiple accounts/workspaces can use this as a hint to refresh the token for the correct workspace.\n\nThis may be `null` when the prior auth state did not include a workspace identifier (`chatgpt_account_id`).", + }), + Schema.Null, + ]), + ), + reason: ServerRequest__ChatgptAuthTokensRefreshReason, +}); + +export type ServerRequest__McpElicitationBooleanSchema = { + readonly default?: boolean | null; + readonly description?: string | null; + readonly title?: string | null; + readonly type: ServerRequest__McpElicitationBooleanType; +}; +export const ServerRequest__McpElicitationBooleanSchema = Schema.Struct({ + default: Schema.optionalKey(Schema.Union([Schema.Boolean, Schema.Null])), + description: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + title: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + type: ServerRequest__McpElicitationBooleanType, +}); + +export type ServerRequest__McpElicitationTitledEnumItems = { + readonly anyOf: ReadonlyArray; +}; +export const ServerRequest__McpElicitationTitledEnumItems = Schema.Struct({ + anyOf: Schema.Array(ServerRequest__McpElicitationConstOption), +}); + +export type ServerRequest__McpElicitationNumberSchema = { + readonly default?: number | null; + readonly description?: string | null; + readonly maximum?: number | null; + readonly minimum?: number | null; + readonly title?: string | null; + readonly type: ServerRequest__McpElicitationNumberType; +}; +export const ServerRequest__McpElicitationNumberSchema = Schema.Struct({ + default: Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ format: "double" }).check(Schema.isFinite()), + Schema.Null, + ]), + ), + description: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + maximum: Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ format: "double" }).check(Schema.isFinite()), + Schema.Null, + ]), + ), + minimum: Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ format: "double" }).check(Schema.isFinite()), + Schema.Null, + ]), + ), + title: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + type: ServerRequest__McpElicitationNumberType, +}); + +export type ServerRequest__McpElicitationLegacyTitledEnumSchema = { + readonly default?: string | null; + readonly description?: string | null; + readonly enum: ReadonlyArray; + readonly enumNames?: ReadonlyArray | null; + readonly title?: string | null; + readonly type: ServerRequest__McpElicitationStringType; +}; +export const ServerRequest__McpElicitationLegacyTitledEnumSchema = Schema.Struct({ + default: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + description: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + enum: Schema.Array(Schema.String), + enumNames: Schema.optionalKey(Schema.Union([Schema.Array(Schema.String), Schema.Null])), + title: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + type: ServerRequest__McpElicitationStringType, +}); + +export type ServerRequest__McpElicitationStringSchema = { + readonly default?: string | null; + readonly description?: string | null; + readonly format?: ServerRequest__McpElicitationStringFormat | null; + readonly maxLength?: number | null; + readonly minLength?: number | null; + readonly title?: string | null; + readonly type: ServerRequest__McpElicitationStringType; +}; +export const ServerRequest__McpElicitationStringSchema = Schema.Struct({ + default: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + description: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + format: Schema.optionalKey( + Schema.Union([ServerRequest__McpElicitationStringFormat, Schema.Null]), + ), + maxLength: Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ format: "uint32" }) + .check(Schema.isInt()) + .check(Schema.isGreaterThanOrEqualTo(0)), + Schema.Null, + ]), + ), + minLength: Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ format: "uint32" }) + .check(Schema.isInt()) + .check(Schema.isGreaterThanOrEqualTo(0)), + Schema.Null, + ]), + ), + title: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + type: ServerRequest__McpElicitationStringType, +}); + +export type ServerRequest__McpElicitationTitledSingleSelectEnumSchema = { + readonly default?: string | null; + readonly description?: string | null; + readonly oneOf: ReadonlyArray; + readonly title?: string | null; + readonly type: ServerRequest__McpElicitationStringType; +}; +export const ServerRequest__McpElicitationTitledSingleSelectEnumSchema = Schema.Struct({ + default: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + description: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + oneOf: Schema.Array(ServerRequest__McpElicitationConstOption), + title: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + type: ServerRequest__McpElicitationStringType, +}); + +export type ServerRequest__McpElicitationUntitledEnumItems = { + readonly enum: ReadonlyArray; + readonly type: ServerRequest__McpElicitationStringType; +}; +export const ServerRequest__McpElicitationUntitledEnumItems = Schema.Struct({ + enum: Schema.Array(Schema.String), + type: ServerRequest__McpElicitationStringType, +}); + +export type ServerRequest__McpElicitationUntitledSingleSelectEnumSchema = { + readonly default?: string | null; + readonly description?: string | null; + readonly enum: ReadonlyArray; + readonly title?: string | null; + readonly type: ServerRequest__McpElicitationStringType; +}; +export const ServerRequest__McpElicitationUntitledSingleSelectEnumSchema = Schema.Struct({ + default: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + description: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + enum: Schema.Array(Schema.String), + title: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + type: ServerRequest__McpElicitationStringType, +}); + +export type ServerRequest__NetworkApprovalContext = { + readonly host: string; + readonly protocol: ServerRequest__NetworkApprovalProtocol; +}; +export const ServerRequest__NetworkApprovalContext = Schema.Struct({ + host: Schema.String, + protocol: ServerRequest__NetworkApprovalProtocol, +}); + +export type ServerRequest__NetworkPolicyAmendment = { + readonly action: ServerRequest__NetworkPolicyRuleAction; + readonly host: string; +}; +export const ServerRequest__NetworkPolicyAmendment = Schema.Struct({ + action: ServerRequest__NetworkPolicyRuleAction, + host: Schema.String, +}); + +export type ServerRequest__ApplyPatchApprovalParams = { + readonly callId: string; + readonly conversationId: ServerRequest__ThreadId; + readonly fileChanges: { readonly [x: string]: ServerRequest__FileChange }; + readonly grantRoot?: string | null; + readonly reason?: string | null; +}; +export const ServerRequest__ApplyPatchApprovalParams = Schema.Struct({ + callId: Schema.String.annotate({ + description: + "Use to correlate this with [codex_protocol::protocol::PatchApplyBeginEvent] and [codex_protocol::protocol::PatchApplyEndEvent].", + }), + conversationId: ServerRequest__ThreadId, + fileChanges: Schema.Record(Schema.String, ServerRequest__FileChange), + grantRoot: Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + description: + "When set, the agent is asking the user to allow writes under this root for the remainder of the session (unclear if this is honored today).", + }), + Schema.Null, + ]), + ), + reason: Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + description: "Optional explanatory reason (e.g. request for extra write access).", + }), + Schema.Null, + ]), + ), +}); + +export type ServerRequest__ExecCommandApprovalParams = { + readonly approvalId?: string | null; + readonly callId: string; + readonly command: ReadonlyArray; + readonly conversationId: ServerRequest__ThreadId; + readonly cwd: string; + readonly parsedCmd: ReadonlyArray; + readonly reason?: string | null; +}; +export const ServerRequest__ExecCommandApprovalParams = Schema.Struct({ + approvalId: Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ description: "Identifier for this specific approval callback." }), + Schema.Null, + ]), + ), + callId: Schema.String.annotate({ + description: + "Use to correlate this with [codex_protocol::protocol::ExecCommandBeginEvent] and [codex_protocol::protocol::ExecCommandEndEvent].", + }), + command: Schema.Array(Schema.String), + conversationId: ServerRequest__ThreadId, + cwd: Schema.String, + parsedCmd: Schema.Array(ServerRequest__ParsedCommand), + reason: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), +}); + +export type ServerRequest__ToolRequestUserInputQuestion = { + readonly header: string; + readonly id: string; + readonly isOther?: boolean; + readonly isSecret?: boolean; + readonly options?: ReadonlyArray | null; + readonly question: string; +}; +export const ServerRequest__ToolRequestUserInputQuestion = Schema.Struct({ + header: Schema.String, + id: Schema.String, + isOther: Schema.optionalKey(Schema.Boolean.annotate({ default: false })), + isSecret: Schema.optionalKey(Schema.Boolean.annotate({ default: false })), + options: Schema.optionalKey( + Schema.Union([Schema.Array(ServerRequest__ToolRequestUserInputOption), Schema.Null]), + ), + question: Schema.String, +}).annotate({ + description: "EXPERIMENTAL. Represents one request_user_input question and its required options.", +}); + +export type ToolRequestUserInputParams__ToolRequestUserInputQuestion = { + readonly header: string; + readonly id: string; + readonly isOther?: boolean; + readonly isSecret?: boolean; + readonly options?: ReadonlyArray | null; + readonly question: string; +}; +export const ToolRequestUserInputParams__ToolRequestUserInputQuestion = Schema.Struct({ + header: Schema.String, + id: Schema.String, + isOther: Schema.optionalKey(Schema.Boolean.annotate({ default: false })), + isSecret: Schema.optionalKey(Schema.Boolean.annotate({ default: false })), + options: Schema.optionalKey( + Schema.Union([ + Schema.Array(ToolRequestUserInputParams__ToolRequestUserInputOption), + Schema.Null, + ]), + ), + question: Schema.String, +}).annotate({ + description: "EXPERIMENTAL. Represents one request_user_input question and its required options.", +}); + +export type V2AccountRateLimitsUpdatedNotification__RateLimitSnapshot = { + readonly credits?: V2AccountRateLimitsUpdatedNotification__CreditsSnapshot | null; + readonly limitId?: string | null; + readonly limitName?: string | null; + readonly planType?: V2AccountRateLimitsUpdatedNotification__PlanType | null; + readonly primary?: V2AccountRateLimitsUpdatedNotification__RateLimitWindow | null; + readonly secondary?: V2AccountRateLimitsUpdatedNotification__RateLimitWindow | null; +}; +export const V2AccountRateLimitsUpdatedNotification__RateLimitSnapshot = Schema.Struct({ + credits: Schema.optionalKey( + Schema.Union([V2AccountRateLimitsUpdatedNotification__CreditsSnapshot, Schema.Null]), + ), + limitId: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + limitName: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + planType: Schema.optionalKey( + Schema.Union([V2AccountRateLimitsUpdatedNotification__PlanType, Schema.Null]), + ), + primary: Schema.optionalKey( + Schema.Union([V2AccountRateLimitsUpdatedNotification__RateLimitWindow, Schema.Null]), + ), + secondary: Schema.optionalKey( + Schema.Union([V2AccountRateLimitsUpdatedNotification__RateLimitWindow, Schema.Null]), + ), +}); + +export type V2AppListUpdatedNotification__AppMetadata = { + readonly categories?: ReadonlyArray | null; + readonly developer?: string | null; + readonly firstPartyRequiresInstall?: boolean | null; + readonly firstPartyType?: string | null; + readonly review?: V2AppListUpdatedNotification__AppReview | null; + readonly screenshots?: ReadonlyArray | null; + readonly seoDescription?: string | null; + readonly showInComposerWhenUnlinked?: boolean | null; + readonly subCategories?: ReadonlyArray | null; + readonly version?: string | null; + readonly versionId?: string | null; + readonly versionNotes?: string | null; +}; +export const V2AppListUpdatedNotification__AppMetadata = Schema.Struct({ + categories: Schema.optionalKey(Schema.Union([Schema.Array(Schema.String), Schema.Null])), + developer: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + firstPartyRequiresInstall: Schema.optionalKey(Schema.Union([Schema.Boolean, Schema.Null])), + firstPartyType: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + review: Schema.optionalKey(Schema.Union([V2AppListUpdatedNotification__AppReview, Schema.Null])), + screenshots: Schema.optionalKey( + Schema.Union([Schema.Array(V2AppListUpdatedNotification__AppScreenshot), Schema.Null]), + ), + seoDescription: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + showInComposerWhenUnlinked: Schema.optionalKey(Schema.Union([Schema.Boolean, Schema.Null])), + subCategories: Schema.optionalKey(Schema.Union([Schema.Array(Schema.String), Schema.Null])), + version: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + versionId: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + versionNotes: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), +}); + +export type V2AppsListResponse__AppMetadata = { + readonly categories?: ReadonlyArray | null; + readonly developer?: string | null; + readonly firstPartyRequiresInstall?: boolean | null; + readonly firstPartyType?: string | null; + readonly review?: V2AppsListResponse__AppReview | null; + readonly screenshots?: ReadonlyArray | null; + readonly seoDescription?: string | null; + readonly showInComposerWhenUnlinked?: boolean | null; + readonly subCategories?: ReadonlyArray | null; + readonly version?: string | null; + readonly versionId?: string | null; + readonly versionNotes?: string | null; +}; +export const V2AppsListResponse__AppMetadata = Schema.Struct({ + categories: Schema.optionalKey(Schema.Union([Schema.Array(Schema.String), Schema.Null])), + developer: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + firstPartyRequiresInstall: Schema.optionalKey(Schema.Union([Schema.Boolean, Schema.Null])), + firstPartyType: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + review: Schema.optionalKey(Schema.Union([V2AppsListResponse__AppReview, Schema.Null])), + screenshots: Schema.optionalKey( + Schema.Union([Schema.Array(V2AppsListResponse__AppScreenshot), Schema.Null]), + ), + seoDescription: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + showInComposerWhenUnlinked: Schema.optionalKey(Schema.Union([Schema.Boolean, Schema.Null])), + subCategories: Schema.optionalKey(Schema.Union([Schema.Array(Schema.String), Schema.Null])), + version: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + versionId: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + versionNotes: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), +}); + +export type V2CommandExecParams__SandboxPolicy = + | { readonly type: "dangerFullAccess" } + | { + readonly access?: + | { + readonly includePlatformDefaults?: boolean; + readonly readableRoots?: ReadonlyArray; + readonly type: "restricted"; + } + | { readonly type: "fullAccess" }; + readonly networkAccess?: boolean; + readonly type: "readOnly"; + } + | { readonly networkAccess?: "restricted" | "enabled"; readonly type: "externalSandbox" } + | { + readonly excludeSlashTmp?: boolean; + readonly excludeTmpdirEnvVar?: boolean; + readonly networkAccess?: boolean; + readonly readOnlyAccess?: + | { + readonly includePlatformDefaults?: boolean; + readonly readableRoots?: ReadonlyArray; + readonly type: "restricted"; + } + | { readonly type: "fullAccess" }; + readonly type: "workspaceWrite"; + readonly writableRoots?: ReadonlyArray; + }; +export const V2CommandExecParams__SandboxPolicy = Schema.Union( + [ + Schema.Struct({ + type: Schema.Literal("dangerFullAccess").annotate({ + title: "DangerFullAccessSandboxPolicyType", + }), + }).annotate({ title: "DangerFullAccessSandboxPolicy" }), + Schema.Struct({ + access: Schema.optionalKey( + Schema.Union( + [ + Schema.Struct({ + includePlatformDefaults: Schema.optionalKey( + Schema.Boolean.annotate({ default: true }), + ), + readableRoots: Schema.optionalKey( + Schema.Array(V2CommandExecParams__AbsolutePathBuf).annotate({ default: [] }), + ), + type: Schema.Literal("restricted").annotate({ + title: "RestrictedReadOnlyAccessType", + }), + }).annotate({ title: "RestrictedReadOnlyAccess" }), + Schema.Struct({ + type: Schema.Literal("fullAccess").annotate({ + title: "FullAccessReadOnlyAccessType", + }), + }).annotate({ title: "FullAccessReadOnlyAccess" }), + ], + { mode: "oneOf" }, + ).annotate({ default: { type: "fullAccess" } }), + ), + networkAccess: Schema.optionalKey(Schema.Boolean.annotate({ default: false })), + type: Schema.Literal("readOnly").annotate({ title: "ReadOnlySandboxPolicyType" }), + }).annotate({ title: "ReadOnlySandboxPolicy" }), + Schema.Struct({ + networkAccess: Schema.optionalKey( + Schema.Literals(["restricted", "enabled"]).annotate({ default: "restricted" }), + ), + type: Schema.Literal("externalSandbox").annotate({ + title: "ExternalSandboxSandboxPolicyType", + }), + }).annotate({ title: "ExternalSandboxSandboxPolicy" }), + Schema.Struct({ + excludeSlashTmp: Schema.optionalKey(Schema.Boolean.annotate({ default: false })), + excludeTmpdirEnvVar: Schema.optionalKey(Schema.Boolean.annotate({ default: false })), + networkAccess: Schema.optionalKey(Schema.Boolean.annotate({ default: false })), + readOnlyAccess: Schema.optionalKey( + Schema.Union( + [ + Schema.Struct({ + includePlatformDefaults: Schema.optionalKey( + Schema.Boolean.annotate({ default: true }), + ), + readableRoots: Schema.optionalKey( + Schema.Array(V2CommandExecParams__AbsolutePathBuf).annotate({ default: [] }), + ), + type: Schema.Literal("restricted").annotate({ + title: "RestrictedReadOnlyAccessType", + }), + }).annotate({ title: "RestrictedReadOnlyAccess" }), + Schema.Struct({ + type: Schema.Literal("fullAccess").annotate({ + title: "FullAccessReadOnlyAccessType", + }), + }).annotate({ title: "FullAccessReadOnlyAccess" }), + ], + { mode: "oneOf" }, + ).annotate({ default: { type: "fullAccess" } }), + ), + type: Schema.Literal("workspaceWrite").annotate({ title: "WorkspaceWriteSandboxPolicyType" }), + writableRoots: Schema.optionalKey( + Schema.Array(V2CommandExecParams__AbsolutePathBuf).annotate({ default: [] }), + ), + }).annotate({ title: "WorkspaceWriteSandboxPolicy" }), + ], + { mode: "oneOf" }, +); + +export type V2ConfigBatchWriteParams__ConfigEdit = { + readonly keyPath: string; + readonly mergeStrategy: V2ConfigBatchWriteParams__MergeStrategy; + readonly value: unknown; +}; +export const V2ConfigBatchWriteParams__ConfigEdit = Schema.Struct({ + keyPath: Schema.String, + mergeStrategy: V2ConfigBatchWriteParams__MergeStrategy, + value: Schema.Unknown, +}); + +export type V2ConfigReadResponse__ConfigLayerSource = + | { readonly domain: string; readonly key: string; readonly type: "mdm" } + | { readonly file: string; readonly type: "system" } + | { readonly file: string; readonly type: "user" } + | { readonly dotCodexFolder: V2ConfigReadResponse__AbsolutePathBuf; readonly type: "project" } + | { readonly type: "sessionFlags" } + | { + readonly file: V2ConfigReadResponse__AbsolutePathBuf; + readonly type: "legacyManagedConfigTomlFromFile"; + } + | { readonly type: "legacyManagedConfigTomlFromMdm" }; +export const V2ConfigReadResponse__ConfigLayerSource = Schema.Union( + [ + Schema.Struct({ + domain: Schema.String, + key: Schema.String, + type: Schema.Literal("mdm").annotate({ title: "MdmConfigLayerSourceType" }), + }).annotate({ + title: "MdmConfigLayerSource", + description: "Managed preferences layer delivered by MDM (macOS only).", + }), + Schema.Struct({ + file: Schema.String.annotate({ + description: + "A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\n\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.", + }), + type: Schema.Literal("system").annotate({ title: "SystemConfigLayerSourceType" }), + }).annotate({ + title: "SystemConfigLayerSource", + description: "Managed config layer from a file (usually `managed_config.toml`).", + }), + Schema.Struct({ + file: Schema.String.annotate({ + description: + "A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\n\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.", + }), + type: Schema.Literal("user").annotate({ title: "UserConfigLayerSourceType" }), + }).annotate({ + title: "UserConfigLayerSource", + description: + "User config layer from $CODEX_HOME/config.toml. This layer is special in that it is expected to be: - writable by the user - generally outside the workspace directory", + }), + Schema.Struct({ + dotCodexFolder: V2ConfigReadResponse__AbsolutePathBuf, + type: Schema.Literal("project").annotate({ title: "ProjectConfigLayerSourceType" }), + }).annotate({ + title: "ProjectConfigLayerSource", + description: + "Path to a .codex/ folder within a project. There could be multiple of these between `cwd` and the project/repo root.", + }), + Schema.Struct({ + type: Schema.Literal("sessionFlags").annotate({ title: "SessionFlagsConfigLayerSourceType" }), + }).annotate({ + title: "SessionFlagsConfigLayerSource", + description: "Session-layer overrides supplied via `-c`/`--config`.", + }), + Schema.Struct({ + file: V2ConfigReadResponse__AbsolutePathBuf, + type: Schema.Literal("legacyManagedConfigTomlFromFile").annotate({ + title: "LegacyManagedConfigTomlFromFileConfigLayerSourceType", + }), + }).annotate({ + title: "LegacyManagedConfigTomlFromFileConfigLayerSource", + description: + '`managed_config.toml` was designed to be a config that was loaded as the last layer on top of everything else. This scheme did not quite work out as intended, but we keep this variant as a "best effort" while we phase out `managed_config.toml` in favor of `requirements.toml`.', + }), + Schema.Struct({ + type: Schema.Literal("legacyManagedConfigTomlFromMdm").annotate({ + title: "LegacyManagedConfigTomlFromMdmConfigLayerSourceType", + }), + }).annotate({ title: "LegacyManagedConfigTomlFromMdmConfigLayerSource" }), + ], + { mode: "oneOf" }, +); + +export type V2ConfigReadResponse__WebSearchToolConfig = { + readonly allowed_domains?: ReadonlyArray | null; + readonly context_size?: V2ConfigReadResponse__WebSearchContextSize | null; + readonly location?: V2ConfigReadResponse__WebSearchLocation | null; +}; +export const V2ConfigReadResponse__WebSearchToolConfig = Schema.Struct({ + allowed_domains: Schema.optionalKey(Schema.Union([Schema.Array(Schema.String), Schema.Null])), + context_size: Schema.optionalKey( + Schema.Union([V2ConfigReadResponse__WebSearchContextSize, Schema.Null]), + ), + location: Schema.optionalKey( + Schema.Union([V2ConfigReadResponse__WebSearchLocation, Schema.Null]), + ), +}); + +export type V2ConfigRequirementsReadResponse__ConfigRequirements = { + readonly allowedApprovalPolicies?: ReadonlyArray | null; + readonly allowedSandboxModes?: ReadonlyArray | null; + readonly allowedWebSearchModes?: ReadonlyArray | null; + readonly enforceResidency?: V2ConfigRequirementsReadResponse__ResidencyRequirement | null; + readonly featureRequirements?: { readonly [x: string]: boolean } | null; +}; +export const V2ConfigRequirementsReadResponse__ConfigRequirements = Schema.Struct({ + allowedApprovalPolicies: Schema.optionalKey( + Schema.Union([Schema.Array(V2ConfigRequirementsReadResponse__AskForApproval), Schema.Null]), + ), + allowedSandboxModes: Schema.optionalKey( + Schema.Union([Schema.Array(V2ConfigRequirementsReadResponse__SandboxMode), Schema.Null]), + ), + allowedWebSearchModes: Schema.optionalKey( + Schema.Union([Schema.Array(V2ConfigRequirementsReadResponse__WebSearchMode), Schema.Null]), + ), + enforceResidency: Schema.optionalKey( + Schema.Union([V2ConfigRequirementsReadResponse__ResidencyRequirement, Schema.Null]), + ), + featureRequirements: Schema.optionalKey( + Schema.Union([Schema.Record(Schema.String, Schema.Boolean), Schema.Null]), + ), +}); + +export type V2ConfigWarningNotification__TextRange = { + readonly end: V2ConfigWarningNotification__TextPosition; + readonly start: V2ConfigWarningNotification__TextPosition; +}; +export const V2ConfigWarningNotification__TextRange = Schema.Struct({ + end: V2ConfigWarningNotification__TextPosition, + start: V2ConfigWarningNotification__TextPosition, +}); + +export type V2ConfigWriteResponse__ConfigLayerSource = + | { readonly domain: string; readonly key: string; readonly type: "mdm" } + | { readonly file: string; readonly type: "system" } + | { readonly file: string; readonly type: "user" } + | { readonly dotCodexFolder: V2ConfigWriteResponse__AbsolutePathBuf; readonly type: "project" } + | { readonly type: "sessionFlags" } + | { + readonly file: V2ConfigWriteResponse__AbsolutePathBuf; + readonly type: "legacyManagedConfigTomlFromFile"; + } + | { readonly type: "legacyManagedConfigTomlFromMdm" }; +export const V2ConfigWriteResponse__ConfigLayerSource = Schema.Union( + [ + Schema.Struct({ + domain: Schema.String, + key: Schema.String, + type: Schema.Literal("mdm").annotate({ title: "MdmConfigLayerSourceType" }), + }).annotate({ + title: "MdmConfigLayerSource", + description: "Managed preferences layer delivered by MDM (macOS only).", + }), + Schema.Struct({ + file: Schema.String.annotate({ + description: + "A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\n\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.", + }), + type: Schema.Literal("system").annotate({ title: "SystemConfigLayerSourceType" }), + }).annotate({ + title: "SystemConfigLayerSource", + description: "Managed config layer from a file (usually `managed_config.toml`).", + }), + Schema.Struct({ + file: Schema.String.annotate({ + description: + "A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\n\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.", + }), + type: Schema.Literal("user").annotate({ title: "UserConfigLayerSourceType" }), + }).annotate({ + title: "UserConfigLayerSource", + description: + "User config layer from $CODEX_HOME/config.toml. This layer is special in that it is expected to be: - writable by the user - generally outside the workspace directory", + }), + Schema.Struct({ + dotCodexFolder: V2ConfigWriteResponse__AbsolutePathBuf, + type: Schema.Literal("project").annotate({ title: "ProjectConfigLayerSourceType" }), + }).annotate({ + title: "ProjectConfigLayerSource", + description: + "Path to a .codex/ folder within a project. There could be multiple of these between `cwd` and the project/repo root.", + }), + Schema.Struct({ + type: Schema.Literal("sessionFlags").annotate({ title: "SessionFlagsConfigLayerSourceType" }), + }).annotate({ + title: "SessionFlagsConfigLayerSource", + description: "Session-layer overrides supplied via `-c`/`--config`.", + }), + Schema.Struct({ + file: V2ConfigWriteResponse__AbsolutePathBuf, + type: Schema.Literal("legacyManagedConfigTomlFromFile").annotate({ + title: "LegacyManagedConfigTomlFromFileConfigLayerSourceType", + }), + }).annotate({ + title: "LegacyManagedConfigTomlFromFileConfigLayerSource", + description: + '`managed_config.toml` was designed to be a config that was loaded as the last layer on top of everything else. This scheme did not quite work out as intended, but we keep this variant as a "best effort" while we phase out `managed_config.toml` in favor of `requirements.toml`.', + }), + Schema.Struct({ + type: Schema.Literal("legacyManagedConfigTomlFromMdm").annotate({ + title: "LegacyManagedConfigTomlFromMdmConfigLayerSourceType", + }), + }).annotate({ title: "LegacyManagedConfigTomlFromMdmConfigLayerSource" }), + ], + { mode: "oneOf" }, +); + +export type V2ErrorNotification__CodexErrorInfo = + | "contextWindowExceeded" + | "usageLimitExceeded" + | "serverOverloaded" + | "internalServerError" + | "unauthorized" + | "badRequest" + | "threadRollbackFailed" + | "sandboxError" + | "other" + | { readonly httpConnectionFailed: { readonly httpStatusCode?: number | null } } + | { readonly responseStreamConnectionFailed: { readonly httpStatusCode?: number | null } } + | { readonly responseStreamDisconnected: { readonly httpStatusCode?: number | null } } + | { readonly responseTooManyFailedAttempts: { readonly httpStatusCode?: number | null } } + | { + readonly activeTurnNotSteerable: { + readonly turnKind: V2ErrorNotification__NonSteerableTurnKind; + }; + }; +export const V2ErrorNotification__CodexErrorInfo = Schema.Union( + [ + Schema.Literals([ + "contextWindowExceeded", + "usageLimitExceeded", + "serverOverloaded", + "internalServerError", + "unauthorized", + "badRequest", + "threadRollbackFailed", + "sandboxError", + "other", + ]), + Schema.Struct({ + httpConnectionFailed: Schema.Struct({ + httpStatusCode: Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ format: "uint16" }) + .check(Schema.isInt()) + .check(Schema.isGreaterThanOrEqualTo(0)), + Schema.Null, + ]), + ), + }), + }).annotate({ title: "HttpConnectionFailedCodexErrorInfo" }), + Schema.Struct({ + responseStreamConnectionFailed: Schema.Struct({ + httpStatusCode: Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ format: "uint16" }) + .check(Schema.isInt()) + .check(Schema.isGreaterThanOrEqualTo(0)), + Schema.Null, + ]), + ), + }), + }).annotate({ + title: "ResponseStreamConnectionFailedCodexErrorInfo", + description: "Failed to connect to the response SSE stream.", + }), + Schema.Struct({ + responseStreamDisconnected: Schema.Struct({ + httpStatusCode: Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ format: "uint16" }) + .check(Schema.isInt()) + .check(Schema.isGreaterThanOrEqualTo(0)), + Schema.Null, + ]), + ), + }), + }).annotate({ + title: "ResponseStreamDisconnectedCodexErrorInfo", + description: + "The response SSE stream disconnected in the middle of a turn before completion.", + }), + Schema.Struct({ + responseTooManyFailedAttempts: Schema.Struct({ + httpStatusCode: Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ format: "uint16" }) + .check(Schema.isInt()) + .check(Schema.isGreaterThanOrEqualTo(0)), + Schema.Null, + ]), + ), + }), + }).annotate({ + title: "ResponseTooManyFailedAttemptsCodexErrorInfo", + description: "Reached the retry limit for responses.", + }), + Schema.Struct({ + activeTurnNotSteerable: Schema.Struct({ + turnKind: V2ErrorNotification__NonSteerableTurnKind, + }), + }).annotate({ + title: "ActiveTurnNotSteerableCodexErrorInfo", + description: + "Returned when `turn/start` or `turn/steer` is submitted while the current active turn cannot accept same-turn steering, for example `/review` or manual `/compact`.", + }), + ], + { mode: "oneOf" }, +).annotate({ + description: + "This translation layer make sure that we expose codex error code in camel case.\n\nWhen an upstream HTTP status is available (for example, from the Responses API or a provider), it is forwarded in `httpStatusCode` on the relevant `codexErrorInfo` variant.", +}); + +export type V2ExternalAgentConfigDetectResponse__ExternalAgentConfigMigrationItem = { + readonly cwd?: string | null; + readonly description: string; + readonly itemType: V2ExternalAgentConfigDetectResponse__ExternalAgentConfigMigrationItemType; +}; +export const V2ExternalAgentConfigDetectResponse__ExternalAgentConfigMigrationItem = Schema.Struct({ + cwd: Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + description: + "Null or empty means home-scoped migration; non-empty means repo-scoped migration.", + }), + Schema.Null, + ]), + ), + description: Schema.String, + itemType: V2ExternalAgentConfigDetectResponse__ExternalAgentConfigMigrationItemType, +}); + +export type V2ExternalAgentConfigImportParams__ExternalAgentConfigMigrationItem = { + readonly cwd?: string | null; + readonly description: string; + readonly itemType: V2ExternalAgentConfigImportParams__ExternalAgentConfigMigrationItemType; +}; +export const V2ExternalAgentConfigImportParams__ExternalAgentConfigMigrationItem = Schema.Struct({ + cwd: Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + description: + "Null or empty means home-scoped migration; non-empty means repo-scoped migration.", + }), + Schema.Null, + ]), + ), + description: Schema.String, + itemType: V2ExternalAgentConfigImportParams__ExternalAgentConfigMigrationItemType, +}); + +export type V2GetAccountRateLimitsResponse__RateLimitSnapshot = { + readonly credits?: V2GetAccountRateLimitsResponse__CreditsSnapshot | null; + readonly limitId?: string | null; + readonly limitName?: string | null; + readonly planType?: V2GetAccountRateLimitsResponse__PlanType | null; + readonly primary?: V2GetAccountRateLimitsResponse__RateLimitWindow | null; + readonly secondary?: V2GetAccountRateLimitsResponse__RateLimitWindow | null; +}; +export const V2GetAccountRateLimitsResponse__RateLimitSnapshot = Schema.Struct({ + credits: Schema.optionalKey( + Schema.Union([V2GetAccountRateLimitsResponse__CreditsSnapshot, Schema.Null]), + ), + limitId: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + limitName: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + planType: Schema.optionalKey( + Schema.Union([V2GetAccountRateLimitsResponse__PlanType, Schema.Null]), + ), + primary: Schema.optionalKey( + Schema.Union([V2GetAccountRateLimitsResponse__RateLimitWindow, Schema.Null]), + ), + secondary: Schema.optionalKey( + Schema.Union([V2GetAccountRateLimitsResponse__RateLimitWindow, Schema.Null]), + ), +}); + +export type V2GetAccountResponse__Account = + | { readonly type: "apiKey" } + | { + readonly email: string; + readonly planType: V2GetAccountResponse__PlanType; + readonly type: "chatgpt"; + }; +export const V2GetAccountResponse__Account = Schema.Union( + [ + Schema.Struct({ + type: Schema.Literal("apiKey").annotate({ title: "ApiKeyAccountType" }), + }).annotate({ title: "ApiKeyAccount" }), + Schema.Struct({ + email: Schema.String, + planType: V2GetAccountResponse__PlanType, + type: Schema.Literal("chatgpt").annotate({ title: "ChatgptAccountType" }), + }).annotate({ title: "ChatgptAccount" }), + ], + { mode: "oneOf" }, +); + +export type V2HookCompletedNotification__HookOutputEntry = { + readonly kind: V2HookCompletedNotification__HookOutputEntryKind; + readonly text: string; +}; +export const V2HookCompletedNotification__HookOutputEntry = Schema.Struct({ + kind: V2HookCompletedNotification__HookOutputEntryKind, + text: Schema.String, +}); + +export type V2HookStartedNotification__HookOutputEntry = { + readonly kind: V2HookStartedNotification__HookOutputEntryKind; + readonly text: string; +}; +export const V2HookStartedNotification__HookOutputEntry = Schema.Struct({ + kind: V2HookStartedNotification__HookOutputEntryKind, + text: Schema.String, +}); + +export type V2ItemCompletedNotification__CollabAgentState = { + readonly message?: string | null; + readonly status: V2ItemCompletedNotification__CollabAgentStatus; +}; +export const V2ItemCompletedNotification__CollabAgentState = Schema.Struct({ + message: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + status: V2ItemCompletedNotification__CollabAgentStatus, +}); + +export type V2ItemCompletedNotification__MemoryCitation = { + readonly entries: ReadonlyArray; + readonly threadIds: ReadonlyArray; +}; +export const V2ItemCompletedNotification__MemoryCitation = Schema.Struct({ + entries: Schema.Array(V2ItemCompletedNotification__MemoryCitationEntry), + threadIds: Schema.Array(Schema.String), +}); + +export type V2ItemCompletedNotification__FileUpdateChange = { + readonly diff: string; + readonly kind: V2ItemCompletedNotification__PatchChangeKind; + readonly path: string; +}; +export const V2ItemCompletedNotification__FileUpdateChange = Schema.Struct({ + diff: Schema.String, + kind: V2ItemCompletedNotification__PatchChangeKind, + path: Schema.String, +}); + +export type V2ItemCompletedNotification__UserInput = + | { + readonly text: string; + readonly text_elements?: ReadonlyArray; + readonly type: "text"; + } + | { readonly type: "image"; readonly url: string } + | { readonly path: string; readonly type: "localImage" } + | { readonly name: string; readonly path: string; readonly type: "skill" } + | { readonly name: string; readonly path: string; readonly type: "mention" }; +export const V2ItemCompletedNotification__UserInput = Schema.Union( + [ + Schema.Struct({ + text: Schema.String, + text_elements: Schema.optionalKey( + Schema.Array(V2ItemCompletedNotification__TextElement).annotate({ + description: "UI-defined spans within `text` used to render or persist special elements.", + default: [], + }), + ), + type: Schema.Literal("text").annotate({ title: "TextUserInputType" }), + }).annotate({ title: "TextUserInput" }), + Schema.Struct({ + type: Schema.Literal("image").annotate({ title: "ImageUserInputType" }), + url: Schema.String, + }).annotate({ title: "ImageUserInput" }), + Schema.Struct({ + path: Schema.String, + type: Schema.Literal("localImage").annotate({ title: "LocalImageUserInputType" }), + }).annotate({ title: "LocalImageUserInput" }), + Schema.Struct({ + name: Schema.String, + path: Schema.String, + type: Schema.Literal("skill").annotate({ title: "SkillUserInputType" }), + }).annotate({ title: "SkillUserInput" }), + Schema.Struct({ + name: Schema.String, + path: Schema.String, + type: Schema.Literal("mention").annotate({ title: "MentionUserInputType" }), + }).annotate({ title: "MentionUserInput" }), + ], + { mode: "oneOf" }, +); + +export type V2ItemGuardianApprovalReviewCompletedNotification__GuardianApprovalReview = { + readonly rationale?: string | null; + readonly riskLevel?: V2ItemGuardianApprovalReviewCompletedNotification__GuardianRiskLevel | null; + readonly status: V2ItemGuardianApprovalReviewCompletedNotification__GuardianApprovalReviewStatus; + readonly userAuthorization?: V2ItemGuardianApprovalReviewCompletedNotification__GuardianUserAuthorization | null; +}; +export const V2ItemGuardianApprovalReviewCompletedNotification__GuardianApprovalReview = + Schema.Struct({ + rationale: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + riskLevel: Schema.optionalKey( + Schema.Union([ + V2ItemGuardianApprovalReviewCompletedNotification__GuardianRiskLevel, + Schema.Null, + ]), + ), + status: V2ItemGuardianApprovalReviewCompletedNotification__GuardianApprovalReviewStatus, + userAuthorization: Schema.optionalKey( + Schema.Union([ + V2ItemGuardianApprovalReviewCompletedNotification__GuardianUserAuthorization, + Schema.Null, + ]), + ), + }).annotate({ + description: + "[UNSTABLE] Temporary guardian approval review payload used by `item/autoApprovalReview/*` notifications. This shape is expected to change soon.", + }); + +export type V2ItemGuardianApprovalReviewCompletedNotification__GuardianApprovalReviewAction = + | { + readonly command: string; + readonly cwd: string; + readonly source: V2ItemGuardianApprovalReviewCompletedNotification__GuardianCommandSource; + readonly type: "command"; + } + | { + readonly argv: ReadonlyArray; + readonly cwd: string; + readonly program: string; + readonly source: V2ItemGuardianApprovalReviewCompletedNotification__GuardianCommandSource; + readonly type: "execve"; + } + | { readonly cwd: string; readonly files: ReadonlyArray; readonly type: "applyPatch" } + | { + readonly host: string; + readonly port: number; + readonly protocol: V2ItemGuardianApprovalReviewCompletedNotification__NetworkApprovalProtocol; + readonly target: string; + readonly type: "networkAccess"; + } + | { + readonly connectorId?: string | null; + readonly connectorName?: string | null; + readonly server: string; + readonly toolName: string; + readonly toolTitle?: string | null; + readonly type: "mcpToolCall"; + }; +export const V2ItemGuardianApprovalReviewCompletedNotification__GuardianApprovalReviewAction = + Schema.Union( + [ + Schema.Struct({ + command: Schema.String, + cwd: Schema.String, + source: V2ItemGuardianApprovalReviewCompletedNotification__GuardianCommandSource, + type: Schema.Literal("command").annotate({ + title: "CommandGuardianApprovalReviewActionType", + }), + }).annotate({ title: "CommandGuardianApprovalReviewAction" }), + Schema.Struct({ + argv: Schema.Array(Schema.String), + cwd: Schema.String, + program: Schema.String, + source: V2ItemGuardianApprovalReviewCompletedNotification__GuardianCommandSource, + type: Schema.Literal("execve").annotate({ + title: "ExecveGuardianApprovalReviewActionType", + }), + }).annotate({ title: "ExecveGuardianApprovalReviewAction" }), + Schema.Struct({ + cwd: Schema.String, + files: Schema.Array(Schema.String), + type: Schema.Literal("applyPatch").annotate({ + title: "ApplyPatchGuardianApprovalReviewActionType", + }), + }).annotate({ title: "ApplyPatchGuardianApprovalReviewAction" }), + Schema.Struct({ + host: Schema.String, + port: Schema.Number.annotate({ format: "uint16" }) + .check(Schema.isInt()) + .check(Schema.isGreaterThanOrEqualTo(0)), + protocol: V2ItemGuardianApprovalReviewCompletedNotification__NetworkApprovalProtocol, + target: Schema.String, + type: Schema.Literal("networkAccess").annotate({ + title: "NetworkAccessGuardianApprovalReviewActionType", + }), + }).annotate({ title: "NetworkAccessGuardianApprovalReviewAction" }), + Schema.Struct({ + connectorId: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + connectorName: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + server: Schema.String, + toolName: Schema.String, + toolTitle: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + type: Schema.Literal("mcpToolCall").annotate({ + title: "McpToolCallGuardianApprovalReviewActionType", + }), + }).annotate({ title: "McpToolCallGuardianApprovalReviewAction" }), + ], + { mode: "oneOf" }, + ); + +export type V2ItemGuardianApprovalReviewStartedNotification__GuardianApprovalReview = { + readonly rationale?: string | null; + readonly riskLevel?: V2ItemGuardianApprovalReviewStartedNotification__GuardianRiskLevel | null; + readonly status: V2ItemGuardianApprovalReviewStartedNotification__GuardianApprovalReviewStatus; + readonly userAuthorization?: V2ItemGuardianApprovalReviewStartedNotification__GuardianUserAuthorization | null; +}; +export const V2ItemGuardianApprovalReviewStartedNotification__GuardianApprovalReview = + Schema.Struct({ + rationale: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + riskLevel: Schema.optionalKey( + Schema.Union([ + V2ItemGuardianApprovalReviewStartedNotification__GuardianRiskLevel, + Schema.Null, + ]), + ), + status: V2ItemGuardianApprovalReviewStartedNotification__GuardianApprovalReviewStatus, + userAuthorization: Schema.optionalKey( + Schema.Union([ + V2ItemGuardianApprovalReviewStartedNotification__GuardianUserAuthorization, + Schema.Null, + ]), + ), + }).annotate({ + description: + "[UNSTABLE] Temporary guardian approval review payload used by `item/autoApprovalReview/*` notifications. This shape is expected to change soon.", + }); + +export type V2ItemGuardianApprovalReviewStartedNotification__GuardianApprovalReviewAction = + | { + readonly command: string; + readonly cwd: string; + readonly source: V2ItemGuardianApprovalReviewStartedNotification__GuardianCommandSource; + readonly type: "command"; + } + | { + readonly argv: ReadonlyArray; + readonly cwd: string; + readonly program: string; + readonly source: V2ItemGuardianApprovalReviewStartedNotification__GuardianCommandSource; + readonly type: "execve"; + } + | { readonly cwd: string; readonly files: ReadonlyArray; readonly type: "applyPatch" } + | { + readonly host: string; + readonly port: number; + readonly protocol: V2ItemGuardianApprovalReviewStartedNotification__NetworkApprovalProtocol; + readonly target: string; + readonly type: "networkAccess"; + } + | { + readonly connectorId?: string | null; + readonly connectorName?: string | null; + readonly server: string; + readonly toolName: string; + readonly toolTitle?: string | null; + readonly type: "mcpToolCall"; + }; +export const V2ItemGuardianApprovalReviewStartedNotification__GuardianApprovalReviewAction = + Schema.Union( + [ + Schema.Struct({ + command: Schema.String, + cwd: Schema.String, + source: V2ItemGuardianApprovalReviewStartedNotification__GuardianCommandSource, + type: Schema.Literal("command").annotate({ + title: "CommandGuardianApprovalReviewActionType", + }), + }).annotate({ title: "CommandGuardianApprovalReviewAction" }), + Schema.Struct({ + argv: Schema.Array(Schema.String), + cwd: Schema.String, + program: Schema.String, + source: V2ItemGuardianApprovalReviewStartedNotification__GuardianCommandSource, + type: Schema.Literal("execve").annotate({ + title: "ExecveGuardianApprovalReviewActionType", + }), + }).annotate({ title: "ExecveGuardianApprovalReviewAction" }), + Schema.Struct({ + cwd: Schema.String, + files: Schema.Array(Schema.String), + type: Schema.Literal("applyPatch").annotate({ + title: "ApplyPatchGuardianApprovalReviewActionType", + }), + }).annotate({ title: "ApplyPatchGuardianApprovalReviewAction" }), + Schema.Struct({ + host: Schema.String, + port: Schema.Number.annotate({ format: "uint16" }) + .check(Schema.isInt()) + .check(Schema.isGreaterThanOrEqualTo(0)), + protocol: V2ItemGuardianApprovalReviewStartedNotification__NetworkApprovalProtocol, + target: Schema.String, + type: Schema.Literal("networkAccess").annotate({ + title: "NetworkAccessGuardianApprovalReviewActionType", + }), + }).annotate({ title: "NetworkAccessGuardianApprovalReviewAction" }), + Schema.Struct({ + connectorId: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + connectorName: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + server: Schema.String, + toolName: Schema.String, + toolTitle: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + type: Schema.Literal("mcpToolCall").annotate({ + title: "McpToolCallGuardianApprovalReviewActionType", + }), + }).annotate({ title: "McpToolCallGuardianApprovalReviewAction" }), + ], + { mode: "oneOf" }, + ); + +export type V2ItemStartedNotification__CollabAgentState = { + readonly message?: string | null; + readonly status: V2ItemStartedNotification__CollabAgentStatus; +}; +export const V2ItemStartedNotification__CollabAgentState = Schema.Struct({ + message: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + status: V2ItemStartedNotification__CollabAgentStatus, +}); + +export type V2ItemStartedNotification__MemoryCitation = { + readonly entries: ReadonlyArray; + readonly threadIds: ReadonlyArray; +}; +export const V2ItemStartedNotification__MemoryCitation = Schema.Struct({ + entries: Schema.Array(V2ItemStartedNotification__MemoryCitationEntry), + threadIds: Schema.Array(Schema.String), +}); + +export type V2ItemStartedNotification__FileUpdateChange = { + readonly diff: string; + readonly kind: V2ItemStartedNotification__PatchChangeKind; + readonly path: string; +}; +export const V2ItemStartedNotification__FileUpdateChange = Schema.Struct({ + diff: Schema.String, + kind: V2ItemStartedNotification__PatchChangeKind, + path: Schema.String, +}); + +export type V2ItemStartedNotification__UserInput = + | { + readonly text: string; + readonly text_elements?: ReadonlyArray; + readonly type: "text"; + } + | { readonly type: "image"; readonly url: string } + | { readonly path: string; readonly type: "localImage" } + | { readonly name: string; readonly path: string; readonly type: "skill" } + | { readonly name: string; readonly path: string; readonly type: "mention" }; +export const V2ItemStartedNotification__UserInput = Schema.Union( + [ + Schema.Struct({ + text: Schema.String, + text_elements: Schema.optionalKey( + Schema.Array(V2ItemStartedNotification__TextElement).annotate({ + description: "UI-defined spans within `text` used to render or persist special elements.", + default: [], + }), + ), + type: Schema.Literal("text").annotate({ title: "TextUserInputType" }), + }).annotate({ title: "TextUserInput" }), + Schema.Struct({ + type: Schema.Literal("image").annotate({ title: "ImageUserInputType" }), + url: Schema.String, + }).annotate({ title: "ImageUserInput" }), + Schema.Struct({ + path: Schema.String, + type: Schema.Literal("localImage").annotate({ title: "LocalImageUserInputType" }), + }).annotate({ title: "LocalImageUserInput" }), + Schema.Struct({ + name: Schema.String, + path: Schema.String, + type: Schema.Literal("skill").annotate({ title: "SkillUserInputType" }), + }).annotate({ title: "SkillUserInput" }), + Schema.Struct({ + name: Schema.String, + path: Schema.String, + type: Schema.Literal("mention").annotate({ title: "MentionUserInputType" }), + }).annotate({ title: "MentionUserInput" }), + ], + { mode: "oneOf" }, +); + +export type V2ListMcpServerStatusResponse__McpServerStatus = { + readonly authStatus: V2ListMcpServerStatusResponse__McpAuthStatus; + readonly name: string; + readonly resourceTemplates: ReadonlyArray; + readonly resources: ReadonlyArray; + readonly tools: { readonly [x: string]: V2ListMcpServerStatusResponse__Tool }; +}; +export const V2ListMcpServerStatusResponse__McpServerStatus = Schema.Struct({ + authStatus: V2ListMcpServerStatusResponse__McpAuthStatus, + name: Schema.String, + resourceTemplates: Schema.Array(V2ListMcpServerStatusResponse__ResourceTemplate), + resources: Schema.Array(V2ListMcpServerStatusResponse__Resource), + tools: Schema.Record(Schema.String, V2ListMcpServerStatusResponse__Tool), +}); + +export type V2ModelListResponse__ReasoningEffortOption = { + readonly description: string; + readonly reasoningEffort: V2ModelListResponse__ReasoningEffort; +}; +export const V2ModelListResponse__ReasoningEffortOption = Schema.Struct({ + description: Schema.String, + reasoningEffort: V2ModelListResponse__ReasoningEffort, +}); + +export type V2PluginListResponse__MarketplaceLoadErrorInfo = { + readonly marketplacePath: V2PluginListResponse__AbsolutePathBuf; + readonly message: string; +}; +export const V2PluginListResponse__MarketplaceLoadErrorInfo = Schema.Struct({ + marketplacePath: V2PluginListResponse__AbsolutePathBuf, + message: Schema.String, +}); + +export type V2PluginListResponse__PluginInterface = { + readonly brandColor?: string | null; + readonly capabilities: ReadonlyArray; + readonly category?: string | null; + readonly composerIcon?: V2PluginListResponse__AbsolutePathBuf | null; + readonly defaultPrompt?: ReadonlyArray | null; + readonly developerName?: string | null; + readonly displayName?: string | null; + readonly logo?: V2PluginListResponse__AbsolutePathBuf | null; + readonly longDescription?: string | null; + readonly privacyPolicyUrl?: string | null; + readonly screenshots: ReadonlyArray; + readonly shortDescription?: string | null; + readonly termsOfServiceUrl?: string | null; + readonly websiteUrl?: string | null; +}; +export const V2PluginListResponse__PluginInterface = Schema.Struct({ + brandColor: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + capabilities: Schema.Array(Schema.String), + category: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + composerIcon: Schema.optionalKey( + Schema.Union([V2PluginListResponse__AbsolutePathBuf, Schema.Null]), + ), + defaultPrompt: Schema.optionalKey( + Schema.Union([ + Schema.Array(Schema.String).annotate({ + description: + "Starter prompts for the plugin. Capped at 3 entries with a maximum of 128 characters per entry.", + }), + Schema.Null, + ]), + ), + developerName: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + displayName: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + logo: Schema.optionalKey(Schema.Union([V2PluginListResponse__AbsolutePathBuf, Schema.Null])), + longDescription: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + privacyPolicyUrl: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + screenshots: Schema.Array(V2PluginListResponse__AbsolutePathBuf), + shortDescription: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + termsOfServiceUrl: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + websiteUrl: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), +}); + +export type V2PluginListResponse__PluginSource = { + readonly path: V2PluginListResponse__AbsolutePathBuf; + readonly type: "local"; +}; +export const V2PluginListResponse__PluginSource = Schema.Union( + [ + Schema.Struct({ + path: V2PluginListResponse__AbsolutePathBuf, + type: Schema.Literal("local").annotate({ title: "LocalPluginSourceType" }), + }).annotate({ title: "LocalPluginSource" }), + ], + { mode: "oneOf" }, +); + +export type V2PluginReadResponse__PluginInterface = { + readonly brandColor?: string | null; + readonly capabilities: ReadonlyArray; + readonly category?: string | null; + readonly composerIcon?: V2PluginReadResponse__AbsolutePathBuf | null; + readonly defaultPrompt?: ReadonlyArray | null; + readonly developerName?: string | null; + readonly displayName?: string | null; + readonly logo?: V2PluginReadResponse__AbsolutePathBuf | null; + readonly longDescription?: string | null; + readonly privacyPolicyUrl?: string | null; + readonly screenshots: ReadonlyArray; + readonly shortDescription?: string | null; + readonly termsOfServiceUrl?: string | null; + readonly websiteUrl?: string | null; +}; +export const V2PluginReadResponse__PluginInterface = Schema.Struct({ + brandColor: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + capabilities: Schema.Array(Schema.String), + category: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + composerIcon: Schema.optionalKey( + Schema.Union([V2PluginReadResponse__AbsolutePathBuf, Schema.Null]), + ), + defaultPrompt: Schema.optionalKey( + Schema.Union([ + Schema.Array(Schema.String).annotate({ + description: + "Starter prompts for the plugin. Capped at 3 entries with a maximum of 128 characters per entry.", + }), + Schema.Null, + ]), + ), + developerName: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + displayName: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + logo: Schema.optionalKey(Schema.Union([V2PluginReadResponse__AbsolutePathBuf, Schema.Null])), + longDescription: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + privacyPolicyUrl: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + screenshots: Schema.Array(V2PluginReadResponse__AbsolutePathBuf), + shortDescription: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + termsOfServiceUrl: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + websiteUrl: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), +}); + +export type V2PluginReadResponse__PluginSource = { + readonly path: V2PluginReadResponse__AbsolutePathBuf; + readonly type: "local"; +}; +export const V2PluginReadResponse__PluginSource = Schema.Union( + [ + Schema.Struct({ + path: V2PluginReadResponse__AbsolutePathBuf, + type: Schema.Literal("local").annotate({ title: "LocalPluginSourceType" }), + }).annotate({ title: "LocalPluginSource" }), + ], + { mode: "oneOf" }, +); + +export type V2PluginReadResponse__SkillSummary = { + readonly description: string; + readonly enabled: boolean; + readonly interface?: V2PluginReadResponse__SkillInterface | null; + readonly name: string; + readonly path: string; + readonly shortDescription?: string | null; +}; +export const V2PluginReadResponse__SkillSummary = Schema.Struct({ + description: Schema.String, + enabled: Schema.Boolean, + interface: Schema.optionalKey(Schema.Union([V2PluginReadResponse__SkillInterface, Schema.Null])), + name: Schema.String, + path: Schema.String, + shortDescription: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), +}); + +export type V2RawResponseItemCompletedNotification__FunctionCallOutputContentItem = + | { readonly text: string; readonly type: "input_text" } + | { + readonly detail?: V2RawResponseItemCompletedNotification__ImageDetail | null; + readonly image_url: string; + readonly type: "input_image"; + }; +export const V2RawResponseItemCompletedNotification__FunctionCallOutputContentItem = Schema.Union( + [ + Schema.Struct({ + text: Schema.String, + type: Schema.Literal("input_text").annotate({ + title: "InputTextFunctionCallOutputContentItemType", + }), + }).annotate({ title: "InputTextFunctionCallOutputContentItem" }), + Schema.Struct({ + detail: Schema.optionalKey( + Schema.Union([V2RawResponseItemCompletedNotification__ImageDetail, Schema.Null]), + ), + image_url: Schema.String, + type: Schema.Literal("input_image").annotate({ + title: "InputImageFunctionCallOutputContentItemType", + }), + }).annotate({ title: "InputImageFunctionCallOutputContentItem" }), + ], + { mode: "oneOf" }, +).annotate({ + description: + "Responses API compatible content items that can be returned by a tool call. This is a subset of ContentItem with the types we support as function call outputs.", +}); + +export type V2ReviewStartResponse__CollabAgentState = { + readonly message?: string | null; + readonly status: V2ReviewStartResponse__CollabAgentStatus; +}; +export const V2ReviewStartResponse__CollabAgentState = Schema.Struct({ + message: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + status: V2ReviewStartResponse__CollabAgentStatus, +}); + +export type V2ReviewStartResponse__MemoryCitation = { + readonly entries: ReadonlyArray; + readonly threadIds: ReadonlyArray; +}; +export const V2ReviewStartResponse__MemoryCitation = Schema.Struct({ + entries: Schema.Array(V2ReviewStartResponse__MemoryCitationEntry), + threadIds: Schema.Array(Schema.String), +}); + +export type V2ReviewStartResponse__CodexErrorInfo = + | "contextWindowExceeded" + | "usageLimitExceeded" + | "serverOverloaded" + | "internalServerError" + | "unauthorized" + | "badRequest" + | "threadRollbackFailed" + | "sandboxError" + | "other" + | { readonly httpConnectionFailed: { readonly httpStatusCode?: number | null } } + | { readonly responseStreamConnectionFailed: { readonly httpStatusCode?: number | null } } + | { readonly responseStreamDisconnected: { readonly httpStatusCode?: number | null } } + | { readonly responseTooManyFailedAttempts: { readonly httpStatusCode?: number | null } } + | { + readonly activeTurnNotSteerable: { + readonly turnKind: V2ReviewStartResponse__NonSteerableTurnKind; + }; + }; +export const V2ReviewStartResponse__CodexErrorInfo = Schema.Union( + [ + Schema.Literals([ + "contextWindowExceeded", + "usageLimitExceeded", + "serverOverloaded", + "internalServerError", + "unauthorized", + "badRequest", + "threadRollbackFailed", + "sandboxError", + "other", + ]), + Schema.Struct({ + httpConnectionFailed: Schema.Struct({ + httpStatusCode: Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ format: "uint16" }) + .check(Schema.isInt()) + .check(Schema.isGreaterThanOrEqualTo(0)), + Schema.Null, + ]), + ), + }), + }).annotate({ title: "HttpConnectionFailedCodexErrorInfo" }), + Schema.Struct({ + responseStreamConnectionFailed: Schema.Struct({ + httpStatusCode: Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ format: "uint16" }) + .check(Schema.isInt()) + .check(Schema.isGreaterThanOrEqualTo(0)), + Schema.Null, + ]), + ), + }), + }).annotate({ + title: "ResponseStreamConnectionFailedCodexErrorInfo", + description: "Failed to connect to the response SSE stream.", + }), + Schema.Struct({ + responseStreamDisconnected: Schema.Struct({ + httpStatusCode: Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ format: "uint16" }) + .check(Schema.isInt()) + .check(Schema.isGreaterThanOrEqualTo(0)), + Schema.Null, + ]), + ), + }), + }).annotate({ + title: "ResponseStreamDisconnectedCodexErrorInfo", + description: + "The response SSE stream disconnected in the middle of a turn before completion.", + }), + Schema.Struct({ + responseTooManyFailedAttempts: Schema.Struct({ + httpStatusCode: Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ format: "uint16" }) + .check(Schema.isInt()) + .check(Schema.isGreaterThanOrEqualTo(0)), + Schema.Null, + ]), + ), + }), + }).annotate({ + title: "ResponseTooManyFailedAttemptsCodexErrorInfo", + description: "Reached the retry limit for responses.", + }), + Schema.Struct({ + activeTurnNotSteerable: Schema.Struct({ + turnKind: V2ReviewStartResponse__NonSteerableTurnKind, + }), + }).annotate({ + title: "ActiveTurnNotSteerableCodexErrorInfo", + description: + "Returned when `turn/start` or `turn/steer` is submitted while the current active turn cannot accept same-turn steering, for example `/review` or manual `/compact`.", + }), + ], + { mode: "oneOf" }, +).annotate({ + description: + "This translation layer make sure that we expose codex error code in camel case.\n\nWhen an upstream HTTP status is available (for example, from the Responses API or a provider), it is forwarded in `httpStatusCode` on the relevant `codexErrorInfo` variant.", +}); + +export type V2ReviewStartResponse__FileUpdateChange = { + readonly diff: string; + readonly kind: V2ReviewStartResponse__PatchChangeKind; + readonly path: string; +}; +export const V2ReviewStartResponse__FileUpdateChange = Schema.Struct({ + diff: Schema.String, + kind: V2ReviewStartResponse__PatchChangeKind, + path: Schema.String, +}); + +export type V2ReviewStartResponse__UserInput = + | { + readonly text: string; + readonly text_elements?: ReadonlyArray; + readonly type: "text"; + } + | { readonly type: "image"; readonly url: string } + | { readonly path: string; readonly type: "localImage" } + | { readonly name: string; readonly path: string; readonly type: "skill" } + | { readonly name: string; readonly path: string; readonly type: "mention" }; +export const V2ReviewStartResponse__UserInput = Schema.Union( + [ + Schema.Struct({ + text: Schema.String, + text_elements: Schema.optionalKey( + Schema.Array(V2ReviewStartResponse__TextElement).annotate({ + description: "UI-defined spans within `text` used to render or persist special elements.", + default: [], + }), + ), + type: Schema.Literal("text").annotate({ title: "TextUserInputType" }), + }).annotate({ title: "TextUserInput" }), + Schema.Struct({ + type: Schema.Literal("image").annotate({ title: "ImageUserInputType" }), + url: Schema.String, + }).annotate({ title: "ImageUserInput" }), + Schema.Struct({ + path: Schema.String, + type: Schema.Literal("localImage").annotate({ title: "LocalImageUserInputType" }), + }).annotate({ title: "LocalImageUserInput" }), + Schema.Struct({ + name: Schema.String, + path: Schema.String, + type: Schema.Literal("skill").annotate({ title: "SkillUserInputType" }), + }).annotate({ title: "SkillUserInput" }), + Schema.Struct({ + name: Schema.String, + path: Schema.String, + type: Schema.Literal("mention").annotate({ title: "MentionUserInputType" }), + }).annotate({ title: "MentionUserInput" }), + ], + { mode: "oneOf" }, +); + +export type V2SkillsListResponse__SkillDependencies = { + readonly tools: ReadonlyArray; +}; +export const V2SkillsListResponse__SkillDependencies = Schema.Struct({ + tools: Schema.Array(V2SkillsListResponse__SkillToolDependency), +}); + +export type V2ThreadForkResponse__SandboxPolicy = + | { readonly type: "dangerFullAccess" } + | { + readonly access?: + | { + readonly includePlatformDefaults?: boolean; + readonly readableRoots?: ReadonlyArray; + readonly type: "restricted"; + } + | { readonly type: "fullAccess" }; + readonly networkAccess?: boolean; + readonly type: "readOnly"; + } + | { readonly networkAccess?: "restricted" | "enabled"; readonly type: "externalSandbox" } + | { + readonly excludeSlashTmp?: boolean; + readonly excludeTmpdirEnvVar?: boolean; + readonly networkAccess?: boolean; + readonly readOnlyAccess?: + | { + readonly includePlatformDefaults?: boolean; + readonly readableRoots?: ReadonlyArray; + readonly type: "restricted"; + } + | { readonly type: "fullAccess" }; + readonly type: "workspaceWrite"; + readonly writableRoots?: ReadonlyArray; + }; +export const V2ThreadForkResponse__SandboxPolicy = Schema.Union( + [ + Schema.Struct({ + type: Schema.Literal("dangerFullAccess").annotate({ + title: "DangerFullAccessSandboxPolicyType", + }), + }).annotate({ title: "DangerFullAccessSandboxPolicy" }), + Schema.Struct({ + access: Schema.optionalKey( + Schema.Union( + [ + Schema.Struct({ + includePlatformDefaults: Schema.optionalKey( + Schema.Boolean.annotate({ default: true }), + ), + readableRoots: Schema.optionalKey( + Schema.Array(V2ThreadForkResponse__AbsolutePathBuf).annotate({ default: [] }), + ), + type: Schema.Literal("restricted").annotate({ + title: "RestrictedReadOnlyAccessType", + }), + }).annotate({ title: "RestrictedReadOnlyAccess" }), + Schema.Struct({ + type: Schema.Literal("fullAccess").annotate({ + title: "FullAccessReadOnlyAccessType", + }), + }).annotate({ title: "FullAccessReadOnlyAccess" }), + ], + { mode: "oneOf" }, + ).annotate({ default: { type: "fullAccess" } }), + ), + networkAccess: Schema.optionalKey(Schema.Boolean.annotate({ default: false })), + type: Schema.Literal("readOnly").annotate({ title: "ReadOnlySandboxPolicyType" }), + }).annotate({ title: "ReadOnlySandboxPolicy" }), + Schema.Struct({ + networkAccess: Schema.optionalKey( + Schema.Literals(["restricted", "enabled"]).annotate({ default: "restricted" }), + ), + type: Schema.Literal("externalSandbox").annotate({ + title: "ExternalSandboxSandboxPolicyType", + }), + }).annotate({ title: "ExternalSandboxSandboxPolicy" }), + Schema.Struct({ + excludeSlashTmp: Schema.optionalKey(Schema.Boolean.annotate({ default: false })), + excludeTmpdirEnvVar: Schema.optionalKey(Schema.Boolean.annotate({ default: false })), + networkAccess: Schema.optionalKey(Schema.Boolean.annotate({ default: false })), + readOnlyAccess: Schema.optionalKey( + Schema.Union( + [ + Schema.Struct({ + includePlatformDefaults: Schema.optionalKey( + Schema.Boolean.annotate({ default: true }), + ), + readableRoots: Schema.optionalKey( + Schema.Array(V2ThreadForkResponse__AbsolutePathBuf).annotate({ default: [] }), + ), + type: Schema.Literal("restricted").annotate({ + title: "RestrictedReadOnlyAccessType", + }), + }).annotate({ title: "RestrictedReadOnlyAccess" }), + Schema.Struct({ + type: Schema.Literal("fullAccess").annotate({ + title: "FullAccessReadOnlyAccessType", + }), + }).annotate({ title: "FullAccessReadOnlyAccess" }), + ], + { mode: "oneOf" }, + ).annotate({ default: { type: "fullAccess" } }), + ), + type: Schema.Literal("workspaceWrite").annotate({ title: "WorkspaceWriteSandboxPolicyType" }), + writableRoots: Schema.optionalKey( + Schema.Array(V2ThreadForkResponse__AbsolutePathBuf).annotate({ default: [] }), + ), + }).annotate({ title: "WorkspaceWriteSandboxPolicy" }), + ], + { mode: "oneOf" }, +); + +export type V2ThreadForkResponse__CollabAgentState = { + readonly message?: string | null; + readonly status: V2ThreadForkResponse__CollabAgentStatus; +}; +export const V2ThreadForkResponse__CollabAgentState = Schema.Struct({ + message: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + status: V2ThreadForkResponse__CollabAgentStatus, +}); + +export type V2ThreadForkResponse__MemoryCitation = { + readonly entries: ReadonlyArray; + readonly threadIds: ReadonlyArray; +}; +export const V2ThreadForkResponse__MemoryCitation = Schema.Struct({ + entries: Schema.Array(V2ThreadForkResponse__MemoryCitationEntry), + threadIds: Schema.Array(Schema.String), +}); + +export type V2ThreadForkResponse__CodexErrorInfo = + | "contextWindowExceeded" + | "usageLimitExceeded" + | "serverOverloaded" + | "internalServerError" + | "unauthorized" + | "badRequest" + | "threadRollbackFailed" + | "sandboxError" + | "other" + | { readonly httpConnectionFailed: { readonly httpStatusCode?: number | null } } + | { readonly responseStreamConnectionFailed: { readonly httpStatusCode?: number | null } } + | { readonly responseStreamDisconnected: { readonly httpStatusCode?: number | null } } + | { readonly responseTooManyFailedAttempts: { readonly httpStatusCode?: number | null } } + | { + readonly activeTurnNotSteerable: { + readonly turnKind: V2ThreadForkResponse__NonSteerableTurnKind; + }; + }; +export const V2ThreadForkResponse__CodexErrorInfo = Schema.Union( + [ + Schema.Literals([ + "contextWindowExceeded", + "usageLimitExceeded", + "serverOverloaded", + "internalServerError", + "unauthorized", + "badRequest", + "threadRollbackFailed", + "sandboxError", + "other", + ]), + Schema.Struct({ + httpConnectionFailed: Schema.Struct({ + httpStatusCode: Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ format: "uint16" }) + .check(Schema.isInt()) + .check(Schema.isGreaterThanOrEqualTo(0)), + Schema.Null, + ]), + ), + }), + }).annotate({ title: "HttpConnectionFailedCodexErrorInfo" }), + Schema.Struct({ + responseStreamConnectionFailed: Schema.Struct({ + httpStatusCode: Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ format: "uint16" }) + .check(Schema.isInt()) + .check(Schema.isGreaterThanOrEqualTo(0)), + Schema.Null, + ]), + ), + }), + }).annotate({ + title: "ResponseStreamConnectionFailedCodexErrorInfo", + description: "Failed to connect to the response SSE stream.", + }), + Schema.Struct({ + responseStreamDisconnected: Schema.Struct({ + httpStatusCode: Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ format: "uint16" }) + .check(Schema.isInt()) + .check(Schema.isGreaterThanOrEqualTo(0)), + Schema.Null, + ]), + ), + }), + }).annotate({ + title: "ResponseStreamDisconnectedCodexErrorInfo", + description: + "The response SSE stream disconnected in the middle of a turn before completion.", + }), + Schema.Struct({ + responseTooManyFailedAttempts: Schema.Struct({ + httpStatusCode: Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ format: "uint16" }) + .check(Schema.isInt()) + .check(Schema.isGreaterThanOrEqualTo(0)), + Schema.Null, + ]), + ), + }), + }).annotate({ + title: "ResponseTooManyFailedAttemptsCodexErrorInfo", + description: "Reached the retry limit for responses.", + }), + Schema.Struct({ + activeTurnNotSteerable: Schema.Struct({ + turnKind: V2ThreadForkResponse__NonSteerableTurnKind, + }), + }).annotate({ + title: "ActiveTurnNotSteerableCodexErrorInfo", + description: + "Returned when `turn/start` or `turn/steer` is submitted while the current active turn cannot accept same-turn steering, for example `/review` or manual `/compact`.", + }), + ], + { mode: "oneOf" }, +).annotate({ + description: + "This translation layer make sure that we expose codex error code in camel case.\n\nWhen an upstream HTTP status is available (for example, from the Responses API or a provider), it is forwarded in `httpStatusCode` on the relevant `codexErrorInfo` variant.", +}); + +export type V2ThreadForkResponse__FileUpdateChange = { + readonly diff: string; + readonly kind: V2ThreadForkResponse__PatchChangeKind; + readonly path: string; +}; +export const V2ThreadForkResponse__FileUpdateChange = Schema.Struct({ + diff: Schema.String, + kind: V2ThreadForkResponse__PatchChangeKind, + path: Schema.String, +}); + +export type V2ThreadForkResponse__UserInput = + | { + readonly text: string; + readonly text_elements?: ReadonlyArray; + readonly type: "text"; + } + | { readonly type: "image"; readonly url: string } + | { readonly path: string; readonly type: "localImage" } + | { readonly name: string; readonly path: string; readonly type: "skill" } + | { readonly name: string; readonly path: string; readonly type: "mention" }; +export const V2ThreadForkResponse__UserInput = Schema.Union( + [ + Schema.Struct({ + text: Schema.String, + text_elements: Schema.optionalKey( + Schema.Array(V2ThreadForkResponse__TextElement).annotate({ + description: "UI-defined spans within `text` used to render or persist special elements.", + default: [], + }), + ), + type: Schema.Literal("text").annotate({ title: "TextUserInputType" }), + }).annotate({ title: "TextUserInput" }), + Schema.Struct({ + type: Schema.Literal("image").annotate({ title: "ImageUserInputType" }), + url: Schema.String, + }).annotate({ title: "ImageUserInput" }), + Schema.Struct({ + path: Schema.String, + type: Schema.Literal("localImage").annotate({ title: "LocalImageUserInputType" }), + }).annotate({ title: "LocalImageUserInput" }), + Schema.Struct({ + name: Schema.String, + path: Schema.String, + type: Schema.Literal("skill").annotate({ title: "SkillUserInputType" }), + }).annotate({ title: "SkillUserInput" }), + Schema.Struct({ + name: Schema.String, + path: Schema.String, + type: Schema.Literal("mention").annotate({ title: "MentionUserInputType" }), + }).annotate({ title: "MentionUserInput" }), + ], + { mode: "oneOf" }, +); + +export type V2ThreadForkResponse__SubAgentSource = + | "review" + | "compact" + | "memory_consolidation" + | { + readonly thread_spawn: { + readonly agent_nickname?: string | null; + readonly agent_path?: V2ThreadForkResponse__AgentPath | null; + readonly agent_role?: string | null; + readonly depth: number; + readonly parent_thread_id: V2ThreadForkResponse__ThreadId; + }; + } + | { readonly other: string }; +export const V2ThreadForkResponse__SubAgentSource = Schema.Union( + [ + Schema.Literals(["review", "compact", "memory_consolidation"]), + Schema.Struct({ + thread_spawn: Schema.Struct({ + agent_nickname: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + agent_path: Schema.optionalKey( + Schema.Union([V2ThreadForkResponse__AgentPath, Schema.Null]), + ), + agent_role: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + depth: Schema.Number.annotate({ format: "int32" }).check(Schema.isInt()), + parent_thread_id: V2ThreadForkResponse__ThreadId, + }), + }).annotate({ title: "ThreadSpawnSubAgentSource" }), + Schema.Struct({ other: Schema.String }).annotate({ title: "OtherSubAgentSource" }), + ], + { mode: "oneOf" }, +); + +export type V2ThreadListResponse__CollabAgentState = { + readonly message?: string | null; + readonly status: V2ThreadListResponse__CollabAgentStatus; +}; +export const V2ThreadListResponse__CollabAgentState = Schema.Struct({ + message: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + status: V2ThreadListResponse__CollabAgentStatus, +}); + +export type V2ThreadListResponse__MemoryCitation = { + readonly entries: ReadonlyArray; + readonly threadIds: ReadonlyArray; +}; +export const V2ThreadListResponse__MemoryCitation = Schema.Struct({ + entries: Schema.Array(V2ThreadListResponse__MemoryCitationEntry), + threadIds: Schema.Array(Schema.String), +}); + +export type V2ThreadListResponse__CodexErrorInfo = + | "contextWindowExceeded" + | "usageLimitExceeded" + | "serverOverloaded" + | "internalServerError" + | "unauthorized" + | "badRequest" + | "threadRollbackFailed" + | "sandboxError" + | "other" + | { readonly httpConnectionFailed: { readonly httpStatusCode?: number | null } } + | { readonly responseStreamConnectionFailed: { readonly httpStatusCode?: number | null } } + | { readonly responseStreamDisconnected: { readonly httpStatusCode?: number | null } } + | { readonly responseTooManyFailedAttempts: { readonly httpStatusCode?: number | null } } + | { + readonly activeTurnNotSteerable: { + readonly turnKind: V2ThreadListResponse__NonSteerableTurnKind; + }; + }; +export const V2ThreadListResponse__CodexErrorInfo = Schema.Union( + [ + Schema.Literals([ + "contextWindowExceeded", + "usageLimitExceeded", + "serverOverloaded", + "internalServerError", + "unauthorized", + "badRequest", + "threadRollbackFailed", + "sandboxError", + "other", + ]), + Schema.Struct({ + httpConnectionFailed: Schema.Struct({ + httpStatusCode: Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ format: "uint16" }) + .check(Schema.isInt()) + .check(Schema.isGreaterThanOrEqualTo(0)), + Schema.Null, + ]), + ), + }), + }).annotate({ title: "HttpConnectionFailedCodexErrorInfo" }), + Schema.Struct({ + responseStreamConnectionFailed: Schema.Struct({ + httpStatusCode: Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ format: "uint16" }) + .check(Schema.isInt()) + .check(Schema.isGreaterThanOrEqualTo(0)), + Schema.Null, + ]), + ), + }), + }).annotate({ + title: "ResponseStreamConnectionFailedCodexErrorInfo", + description: "Failed to connect to the response SSE stream.", + }), + Schema.Struct({ + responseStreamDisconnected: Schema.Struct({ + httpStatusCode: Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ format: "uint16" }) + .check(Schema.isInt()) + .check(Schema.isGreaterThanOrEqualTo(0)), + Schema.Null, + ]), + ), + }), + }).annotate({ + title: "ResponseStreamDisconnectedCodexErrorInfo", + description: + "The response SSE stream disconnected in the middle of a turn before completion.", + }), + Schema.Struct({ + responseTooManyFailedAttempts: Schema.Struct({ + httpStatusCode: Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ format: "uint16" }) + .check(Schema.isInt()) + .check(Schema.isGreaterThanOrEqualTo(0)), + Schema.Null, + ]), + ), + }), + }).annotate({ + title: "ResponseTooManyFailedAttemptsCodexErrorInfo", + description: "Reached the retry limit for responses.", + }), + Schema.Struct({ + activeTurnNotSteerable: Schema.Struct({ + turnKind: V2ThreadListResponse__NonSteerableTurnKind, + }), + }).annotate({ + title: "ActiveTurnNotSteerableCodexErrorInfo", + description: + "Returned when `turn/start` or `turn/steer` is submitted while the current active turn cannot accept same-turn steering, for example `/review` or manual `/compact`.", + }), + ], + { mode: "oneOf" }, +).annotate({ + description: + "This translation layer make sure that we expose codex error code in camel case.\n\nWhen an upstream HTTP status is available (for example, from the Responses API or a provider), it is forwarded in `httpStatusCode` on the relevant `codexErrorInfo` variant.", +}); + +export type V2ThreadListResponse__FileUpdateChange = { + readonly diff: string; + readonly kind: V2ThreadListResponse__PatchChangeKind; + readonly path: string; +}; +export const V2ThreadListResponse__FileUpdateChange = Schema.Struct({ + diff: Schema.String, + kind: V2ThreadListResponse__PatchChangeKind, + path: Schema.String, +}); + +export type V2ThreadListResponse__UserInput = + | { + readonly text: string; + readonly text_elements?: ReadonlyArray; + readonly type: "text"; + } + | { readonly type: "image"; readonly url: string } + | { readonly path: string; readonly type: "localImage" } + | { readonly name: string; readonly path: string; readonly type: "skill" } + | { readonly name: string; readonly path: string; readonly type: "mention" }; +export const V2ThreadListResponse__UserInput = Schema.Union( + [ + Schema.Struct({ + text: Schema.String, + text_elements: Schema.optionalKey( + Schema.Array(V2ThreadListResponse__TextElement).annotate({ + description: "UI-defined spans within `text` used to render or persist special elements.", + default: [], + }), + ), + type: Schema.Literal("text").annotate({ title: "TextUserInputType" }), + }).annotate({ title: "TextUserInput" }), + Schema.Struct({ + type: Schema.Literal("image").annotate({ title: "ImageUserInputType" }), + url: Schema.String, + }).annotate({ title: "ImageUserInput" }), + Schema.Struct({ + path: Schema.String, + type: Schema.Literal("localImage").annotate({ title: "LocalImageUserInputType" }), + }).annotate({ title: "LocalImageUserInput" }), + Schema.Struct({ + name: Schema.String, + path: Schema.String, + type: Schema.Literal("skill").annotate({ title: "SkillUserInputType" }), + }).annotate({ title: "SkillUserInput" }), + Schema.Struct({ + name: Schema.String, + path: Schema.String, + type: Schema.Literal("mention").annotate({ title: "MentionUserInputType" }), + }).annotate({ title: "MentionUserInput" }), + ], + { mode: "oneOf" }, +); + +export type V2ThreadListResponse__SubAgentSource = + | "review" + | "compact" + | "memory_consolidation" + | { + readonly thread_spawn: { + readonly agent_nickname?: string | null; + readonly agent_path?: V2ThreadListResponse__AgentPath | null; + readonly agent_role?: string | null; + readonly depth: number; + readonly parent_thread_id: V2ThreadListResponse__ThreadId; + }; + } + | { readonly other: string }; +export const V2ThreadListResponse__SubAgentSource = Schema.Union( + [ + Schema.Literals(["review", "compact", "memory_consolidation"]), + Schema.Struct({ + thread_spawn: Schema.Struct({ + agent_nickname: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + agent_path: Schema.optionalKey( + Schema.Union([V2ThreadListResponse__AgentPath, Schema.Null]), + ), + agent_role: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + depth: Schema.Number.annotate({ format: "int32" }).check(Schema.isInt()), + parent_thread_id: V2ThreadListResponse__ThreadId, + }), + }).annotate({ title: "ThreadSpawnSubAgentSource" }), + Schema.Struct({ other: Schema.String }).annotate({ title: "OtherSubAgentSource" }), + ], + { mode: "oneOf" }, +); + +export type V2ThreadMetadataUpdateResponse__CollabAgentState = { + readonly message?: string | null; + readonly status: V2ThreadMetadataUpdateResponse__CollabAgentStatus; +}; +export const V2ThreadMetadataUpdateResponse__CollabAgentState = Schema.Struct({ + message: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + status: V2ThreadMetadataUpdateResponse__CollabAgentStatus, +}); + +export type V2ThreadMetadataUpdateResponse__MemoryCitation = { + readonly entries: ReadonlyArray; + readonly threadIds: ReadonlyArray; +}; +export const V2ThreadMetadataUpdateResponse__MemoryCitation = Schema.Struct({ + entries: Schema.Array(V2ThreadMetadataUpdateResponse__MemoryCitationEntry), + threadIds: Schema.Array(Schema.String), +}); + +export type V2ThreadMetadataUpdateResponse__CodexErrorInfo = + | "contextWindowExceeded" + | "usageLimitExceeded" + | "serverOverloaded" + | "internalServerError" + | "unauthorized" + | "badRequest" + | "threadRollbackFailed" + | "sandboxError" + | "other" + | { readonly httpConnectionFailed: { readonly httpStatusCode?: number | null } } + | { readonly responseStreamConnectionFailed: { readonly httpStatusCode?: number | null } } + | { readonly responseStreamDisconnected: { readonly httpStatusCode?: number | null } } + | { readonly responseTooManyFailedAttempts: { readonly httpStatusCode?: number | null } } + | { + readonly activeTurnNotSteerable: { + readonly turnKind: V2ThreadMetadataUpdateResponse__NonSteerableTurnKind; + }; + }; +export const V2ThreadMetadataUpdateResponse__CodexErrorInfo = Schema.Union( + [ + Schema.Literals([ + "contextWindowExceeded", + "usageLimitExceeded", + "serverOverloaded", + "internalServerError", + "unauthorized", + "badRequest", + "threadRollbackFailed", + "sandboxError", + "other", + ]), + Schema.Struct({ + httpConnectionFailed: Schema.Struct({ + httpStatusCode: Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ format: "uint16" }) + .check(Schema.isInt()) + .check(Schema.isGreaterThanOrEqualTo(0)), + Schema.Null, + ]), + ), + }), + }).annotate({ title: "HttpConnectionFailedCodexErrorInfo" }), + Schema.Struct({ + responseStreamConnectionFailed: Schema.Struct({ + httpStatusCode: Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ format: "uint16" }) + .check(Schema.isInt()) + .check(Schema.isGreaterThanOrEqualTo(0)), + Schema.Null, + ]), + ), + }), + }).annotate({ + title: "ResponseStreamConnectionFailedCodexErrorInfo", + description: "Failed to connect to the response SSE stream.", + }), + Schema.Struct({ + responseStreamDisconnected: Schema.Struct({ + httpStatusCode: Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ format: "uint16" }) + .check(Schema.isInt()) + .check(Schema.isGreaterThanOrEqualTo(0)), + Schema.Null, + ]), + ), + }), + }).annotate({ + title: "ResponseStreamDisconnectedCodexErrorInfo", + description: + "The response SSE stream disconnected in the middle of a turn before completion.", + }), + Schema.Struct({ + responseTooManyFailedAttempts: Schema.Struct({ + httpStatusCode: Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ format: "uint16" }) + .check(Schema.isInt()) + .check(Schema.isGreaterThanOrEqualTo(0)), + Schema.Null, + ]), + ), + }), + }).annotate({ + title: "ResponseTooManyFailedAttemptsCodexErrorInfo", + description: "Reached the retry limit for responses.", + }), + Schema.Struct({ + activeTurnNotSteerable: Schema.Struct({ + turnKind: V2ThreadMetadataUpdateResponse__NonSteerableTurnKind, + }), + }).annotate({ + title: "ActiveTurnNotSteerableCodexErrorInfo", + description: + "Returned when `turn/start` or `turn/steer` is submitted while the current active turn cannot accept same-turn steering, for example `/review` or manual `/compact`.", + }), + ], + { mode: "oneOf" }, +).annotate({ + description: + "This translation layer make sure that we expose codex error code in camel case.\n\nWhen an upstream HTTP status is available (for example, from the Responses API or a provider), it is forwarded in `httpStatusCode` on the relevant `codexErrorInfo` variant.", +}); + +export type V2ThreadMetadataUpdateResponse__FileUpdateChange = { + readonly diff: string; + readonly kind: V2ThreadMetadataUpdateResponse__PatchChangeKind; + readonly path: string; +}; +export const V2ThreadMetadataUpdateResponse__FileUpdateChange = Schema.Struct({ + diff: Schema.String, + kind: V2ThreadMetadataUpdateResponse__PatchChangeKind, + path: Schema.String, +}); + +export type V2ThreadMetadataUpdateResponse__UserInput = + | { + readonly text: string; + readonly text_elements?: ReadonlyArray; + readonly type: "text"; + } + | { readonly type: "image"; readonly url: string } + | { readonly path: string; readonly type: "localImage" } + | { readonly name: string; readonly path: string; readonly type: "skill" } + | { readonly name: string; readonly path: string; readonly type: "mention" }; +export const V2ThreadMetadataUpdateResponse__UserInput = Schema.Union( + [ + Schema.Struct({ + text: Schema.String, + text_elements: Schema.optionalKey( + Schema.Array(V2ThreadMetadataUpdateResponse__TextElement).annotate({ + description: "UI-defined spans within `text` used to render or persist special elements.", + default: [], + }), + ), + type: Schema.Literal("text").annotate({ title: "TextUserInputType" }), + }).annotate({ title: "TextUserInput" }), + Schema.Struct({ + type: Schema.Literal("image").annotate({ title: "ImageUserInputType" }), + url: Schema.String, + }).annotate({ title: "ImageUserInput" }), + Schema.Struct({ + path: Schema.String, + type: Schema.Literal("localImage").annotate({ title: "LocalImageUserInputType" }), + }).annotate({ title: "LocalImageUserInput" }), + Schema.Struct({ + name: Schema.String, + path: Schema.String, + type: Schema.Literal("skill").annotate({ title: "SkillUserInputType" }), + }).annotate({ title: "SkillUserInput" }), + Schema.Struct({ + name: Schema.String, + path: Schema.String, + type: Schema.Literal("mention").annotate({ title: "MentionUserInputType" }), + }).annotate({ title: "MentionUserInput" }), + ], + { mode: "oneOf" }, +); + +export type V2ThreadMetadataUpdateResponse__SubAgentSource = + | "review" + | "compact" + | "memory_consolidation" + | { + readonly thread_spawn: { + readonly agent_nickname?: string | null; + readonly agent_path?: V2ThreadMetadataUpdateResponse__AgentPath | null; + readonly agent_role?: string | null; + readonly depth: number; + readonly parent_thread_id: V2ThreadMetadataUpdateResponse__ThreadId; + }; + } + | { readonly other: string }; +export const V2ThreadMetadataUpdateResponse__SubAgentSource = Schema.Union( + [ + Schema.Literals(["review", "compact", "memory_consolidation"]), + Schema.Struct({ + thread_spawn: Schema.Struct({ + agent_nickname: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + agent_path: Schema.optionalKey( + Schema.Union([V2ThreadMetadataUpdateResponse__AgentPath, Schema.Null]), + ), + agent_role: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + depth: Schema.Number.annotate({ format: "int32" }).check(Schema.isInt()), + parent_thread_id: V2ThreadMetadataUpdateResponse__ThreadId, + }), + }).annotate({ title: "ThreadSpawnSubAgentSource" }), + Schema.Struct({ other: Schema.String }).annotate({ title: "OtherSubAgentSource" }), + ], + { mode: "oneOf" }, +); + +export type V2ThreadReadResponse__CollabAgentState = { + readonly message?: string | null; + readonly status: V2ThreadReadResponse__CollabAgentStatus; +}; +export const V2ThreadReadResponse__CollabAgentState = Schema.Struct({ + message: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + status: V2ThreadReadResponse__CollabAgentStatus, +}); + +export type V2ThreadReadResponse__MemoryCitation = { + readonly entries: ReadonlyArray; + readonly threadIds: ReadonlyArray; +}; +export const V2ThreadReadResponse__MemoryCitation = Schema.Struct({ + entries: Schema.Array(V2ThreadReadResponse__MemoryCitationEntry), + threadIds: Schema.Array(Schema.String), +}); + +export type V2ThreadReadResponse__CodexErrorInfo = + | "contextWindowExceeded" + | "usageLimitExceeded" + | "serverOverloaded" + | "internalServerError" + | "unauthorized" + | "badRequest" + | "threadRollbackFailed" + | "sandboxError" + | "other" + | { readonly httpConnectionFailed: { readonly httpStatusCode?: number | null } } + | { readonly responseStreamConnectionFailed: { readonly httpStatusCode?: number | null } } + | { readonly responseStreamDisconnected: { readonly httpStatusCode?: number | null } } + | { readonly responseTooManyFailedAttempts: { readonly httpStatusCode?: number | null } } + | { + readonly activeTurnNotSteerable: { + readonly turnKind: V2ThreadReadResponse__NonSteerableTurnKind; + }; + }; +export const V2ThreadReadResponse__CodexErrorInfo = Schema.Union( + [ + Schema.Literals([ + "contextWindowExceeded", + "usageLimitExceeded", + "serverOverloaded", + "internalServerError", + "unauthorized", + "badRequest", + "threadRollbackFailed", + "sandboxError", + "other", + ]), + Schema.Struct({ + httpConnectionFailed: Schema.Struct({ + httpStatusCode: Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ format: "uint16" }) + .check(Schema.isInt()) + .check(Schema.isGreaterThanOrEqualTo(0)), + Schema.Null, + ]), + ), + }), + }).annotate({ title: "HttpConnectionFailedCodexErrorInfo" }), + Schema.Struct({ + responseStreamConnectionFailed: Schema.Struct({ + httpStatusCode: Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ format: "uint16" }) + .check(Schema.isInt()) + .check(Schema.isGreaterThanOrEqualTo(0)), + Schema.Null, + ]), + ), + }), + }).annotate({ + title: "ResponseStreamConnectionFailedCodexErrorInfo", + description: "Failed to connect to the response SSE stream.", + }), + Schema.Struct({ + responseStreamDisconnected: Schema.Struct({ + httpStatusCode: Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ format: "uint16" }) + .check(Schema.isInt()) + .check(Schema.isGreaterThanOrEqualTo(0)), + Schema.Null, + ]), + ), + }), + }).annotate({ + title: "ResponseStreamDisconnectedCodexErrorInfo", + description: + "The response SSE stream disconnected in the middle of a turn before completion.", + }), + Schema.Struct({ + responseTooManyFailedAttempts: Schema.Struct({ + httpStatusCode: Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ format: "uint16" }) + .check(Schema.isInt()) + .check(Schema.isGreaterThanOrEqualTo(0)), + Schema.Null, + ]), + ), + }), + }).annotate({ + title: "ResponseTooManyFailedAttemptsCodexErrorInfo", + description: "Reached the retry limit for responses.", + }), + Schema.Struct({ + activeTurnNotSteerable: Schema.Struct({ + turnKind: V2ThreadReadResponse__NonSteerableTurnKind, + }), + }).annotate({ + title: "ActiveTurnNotSteerableCodexErrorInfo", + description: + "Returned when `turn/start` or `turn/steer` is submitted while the current active turn cannot accept same-turn steering, for example `/review` or manual `/compact`.", + }), + ], + { mode: "oneOf" }, +).annotate({ + description: + "This translation layer make sure that we expose codex error code in camel case.\n\nWhen an upstream HTTP status is available (for example, from the Responses API or a provider), it is forwarded in `httpStatusCode` on the relevant `codexErrorInfo` variant.", +}); + +export type V2ThreadReadResponse__FileUpdateChange = { + readonly diff: string; + readonly kind: V2ThreadReadResponse__PatchChangeKind; + readonly path: string; +}; +export const V2ThreadReadResponse__FileUpdateChange = Schema.Struct({ + diff: Schema.String, + kind: V2ThreadReadResponse__PatchChangeKind, + path: Schema.String, +}); + +export type V2ThreadReadResponse__UserInput = + | { + readonly text: string; + readonly text_elements?: ReadonlyArray; + readonly type: "text"; + } + | { readonly type: "image"; readonly url: string } + | { readonly path: string; readonly type: "localImage" } + | { readonly name: string; readonly path: string; readonly type: "skill" } + | { readonly name: string; readonly path: string; readonly type: "mention" }; +export const V2ThreadReadResponse__UserInput = Schema.Union( + [ + Schema.Struct({ + text: Schema.String, + text_elements: Schema.optionalKey( + Schema.Array(V2ThreadReadResponse__TextElement).annotate({ + description: "UI-defined spans within `text` used to render or persist special elements.", + default: [], + }), + ), + type: Schema.Literal("text").annotate({ title: "TextUserInputType" }), + }).annotate({ title: "TextUserInput" }), + Schema.Struct({ + type: Schema.Literal("image").annotate({ title: "ImageUserInputType" }), + url: Schema.String, + }).annotate({ title: "ImageUserInput" }), + Schema.Struct({ + path: Schema.String, + type: Schema.Literal("localImage").annotate({ title: "LocalImageUserInputType" }), + }).annotate({ title: "LocalImageUserInput" }), + Schema.Struct({ + name: Schema.String, + path: Schema.String, + type: Schema.Literal("skill").annotate({ title: "SkillUserInputType" }), + }).annotate({ title: "SkillUserInput" }), + Schema.Struct({ + name: Schema.String, + path: Schema.String, + type: Schema.Literal("mention").annotate({ title: "MentionUserInputType" }), + }).annotate({ title: "MentionUserInput" }), + ], + { mode: "oneOf" }, +); + +export type V2ThreadReadResponse__SubAgentSource = + | "review" + | "compact" + | "memory_consolidation" + | { + readonly thread_spawn: { + readonly agent_nickname?: string | null; + readonly agent_path?: V2ThreadReadResponse__AgentPath | null; + readonly agent_role?: string | null; + readonly depth: number; + readonly parent_thread_id: V2ThreadReadResponse__ThreadId; + }; + } + | { readonly other: string }; +export const V2ThreadReadResponse__SubAgentSource = Schema.Union( + [ + Schema.Literals(["review", "compact", "memory_consolidation"]), + Schema.Struct({ + thread_spawn: Schema.Struct({ + agent_nickname: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + agent_path: Schema.optionalKey( + Schema.Union([V2ThreadReadResponse__AgentPath, Schema.Null]), + ), + agent_role: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + depth: Schema.Number.annotate({ format: "int32" }).check(Schema.isInt()), + parent_thread_id: V2ThreadReadResponse__ThreadId, + }), + }).annotate({ title: "ThreadSpawnSubAgentSource" }), + Schema.Struct({ other: Schema.String }).annotate({ title: "OtherSubAgentSource" }), + ], + { mode: "oneOf" }, +); + +export type V2ThreadResumeParams__FunctionCallOutputContentItem = + | { readonly text: string; readonly type: "input_text" } + | { + readonly detail?: V2ThreadResumeParams__ImageDetail | null; + readonly image_url: string; + readonly type: "input_image"; + }; +export const V2ThreadResumeParams__FunctionCallOutputContentItem = Schema.Union( + [ + Schema.Struct({ + text: Schema.String, + type: Schema.Literal("input_text").annotate({ + title: "InputTextFunctionCallOutputContentItemType", + }), + }).annotate({ title: "InputTextFunctionCallOutputContentItem" }), + Schema.Struct({ + detail: Schema.optionalKey(Schema.Union([V2ThreadResumeParams__ImageDetail, Schema.Null])), + image_url: Schema.String, + type: Schema.Literal("input_image").annotate({ + title: "InputImageFunctionCallOutputContentItemType", + }), + }).annotate({ title: "InputImageFunctionCallOutputContentItem" }), + ], + { mode: "oneOf" }, +).annotate({ + description: + "Responses API compatible content items that can be returned by a tool call. This is a subset of ContentItem with the types we support as function call outputs.", +}); + +export type V2ThreadResumeResponse__SandboxPolicy = + | { readonly type: "dangerFullAccess" } + | { + readonly access?: + | { + readonly includePlatformDefaults?: boolean; + readonly readableRoots?: ReadonlyArray; + readonly type: "restricted"; + } + | { readonly type: "fullAccess" }; + readonly networkAccess?: boolean; + readonly type: "readOnly"; + } + | { readonly networkAccess?: "restricted" | "enabled"; readonly type: "externalSandbox" } + | { + readonly excludeSlashTmp?: boolean; + readonly excludeTmpdirEnvVar?: boolean; + readonly networkAccess?: boolean; + readonly readOnlyAccess?: + | { + readonly includePlatformDefaults?: boolean; + readonly readableRoots?: ReadonlyArray; + readonly type: "restricted"; + } + | { readonly type: "fullAccess" }; + readonly type: "workspaceWrite"; + readonly writableRoots?: ReadonlyArray; + }; +export const V2ThreadResumeResponse__SandboxPolicy = Schema.Union( + [ + Schema.Struct({ + type: Schema.Literal("dangerFullAccess").annotate({ + title: "DangerFullAccessSandboxPolicyType", + }), + }).annotate({ title: "DangerFullAccessSandboxPolicy" }), + Schema.Struct({ + access: Schema.optionalKey( + Schema.Union( + [ + Schema.Struct({ + includePlatformDefaults: Schema.optionalKey( + Schema.Boolean.annotate({ default: true }), + ), + readableRoots: Schema.optionalKey( + Schema.Array(V2ThreadResumeResponse__AbsolutePathBuf).annotate({ default: [] }), + ), + type: Schema.Literal("restricted").annotate({ + title: "RestrictedReadOnlyAccessType", + }), + }).annotate({ title: "RestrictedReadOnlyAccess" }), + Schema.Struct({ + type: Schema.Literal("fullAccess").annotate({ + title: "FullAccessReadOnlyAccessType", + }), + }).annotate({ title: "FullAccessReadOnlyAccess" }), + ], + { mode: "oneOf" }, + ).annotate({ default: { type: "fullAccess" } }), + ), + networkAccess: Schema.optionalKey(Schema.Boolean.annotate({ default: false })), + type: Schema.Literal("readOnly").annotate({ title: "ReadOnlySandboxPolicyType" }), + }).annotate({ title: "ReadOnlySandboxPolicy" }), + Schema.Struct({ + networkAccess: Schema.optionalKey( + Schema.Literals(["restricted", "enabled"]).annotate({ default: "restricted" }), + ), + type: Schema.Literal("externalSandbox").annotate({ + title: "ExternalSandboxSandboxPolicyType", + }), + }).annotate({ title: "ExternalSandboxSandboxPolicy" }), + Schema.Struct({ + excludeSlashTmp: Schema.optionalKey(Schema.Boolean.annotate({ default: false })), + excludeTmpdirEnvVar: Schema.optionalKey(Schema.Boolean.annotate({ default: false })), + networkAccess: Schema.optionalKey(Schema.Boolean.annotate({ default: false })), + readOnlyAccess: Schema.optionalKey( + Schema.Union( + [ + Schema.Struct({ + includePlatformDefaults: Schema.optionalKey( + Schema.Boolean.annotate({ default: true }), + ), + readableRoots: Schema.optionalKey( + Schema.Array(V2ThreadResumeResponse__AbsolutePathBuf).annotate({ default: [] }), + ), + type: Schema.Literal("restricted").annotate({ + title: "RestrictedReadOnlyAccessType", + }), + }).annotate({ title: "RestrictedReadOnlyAccess" }), + Schema.Struct({ + type: Schema.Literal("fullAccess").annotate({ + title: "FullAccessReadOnlyAccessType", + }), + }).annotate({ title: "FullAccessReadOnlyAccess" }), + ], + { mode: "oneOf" }, + ).annotate({ default: { type: "fullAccess" } }), + ), + type: Schema.Literal("workspaceWrite").annotate({ title: "WorkspaceWriteSandboxPolicyType" }), + writableRoots: Schema.optionalKey( + Schema.Array(V2ThreadResumeResponse__AbsolutePathBuf).annotate({ default: [] }), + ), + }).annotate({ title: "WorkspaceWriteSandboxPolicy" }), + ], + { mode: "oneOf" }, +); + +export type V2ThreadResumeResponse__CollabAgentState = { + readonly message?: string | null; + readonly status: V2ThreadResumeResponse__CollabAgentStatus; +}; +export const V2ThreadResumeResponse__CollabAgentState = Schema.Struct({ + message: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + status: V2ThreadResumeResponse__CollabAgentStatus, +}); + +export type V2ThreadResumeResponse__MemoryCitation = { + readonly entries: ReadonlyArray; + readonly threadIds: ReadonlyArray; +}; +export const V2ThreadResumeResponse__MemoryCitation = Schema.Struct({ + entries: Schema.Array(V2ThreadResumeResponse__MemoryCitationEntry), + threadIds: Schema.Array(Schema.String), +}); + +export type V2ThreadResumeResponse__CodexErrorInfo = + | "contextWindowExceeded" + | "usageLimitExceeded" + | "serverOverloaded" + | "internalServerError" + | "unauthorized" + | "badRequest" + | "threadRollbackFailed" + | "sandboxError" + | "other" + | { readonly httpConnectionFailed: { readonly httpStatusCode?: number | null } } + | { readonly responseStreamConnectionFailed: { readonly httpStatusCode?: number | null } } + | { readonly responseStreamDisconnected: { readonly httpStatusCode?: number | null } } + | { readonly responseTooManyFailedAttempts: { readonly httpStatusCode?: number | null } } + | { + readonly activeTurnNotSteerable: { + readonly turnKind: V2ThreadResumeResponse__NonSteerableTurnKind; + }; + }; +export const V2ThreadResumeResponse__CodexErrorInfo = Schema.Union( + [ + Schema.Literals([ + "contextWindowExceeded", + "usageLimitExceeded", + "serverOverloaded", + "internalServerError", + "unauthorized", + "badRequest", + "threadRollbackFailed", + "sandboxError", + "other", + ]), + Schema.Struct({ + httpConnectionFailed: Schema.Struct({ + httpStatusCode: Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ format: "uint16" }) + .check(Schema.isInt()) + .check(Schema.isGreaterThanOrEqualTo(0)), + Schema.Null, + ]), + ), + }), + }).annotate({ title: "HttpConnectionFailedCodexErrorInfo" }), + Schema.Struct({ + responseStreamConnectionFailed: Schema.Struct({ + httpStatusCode: Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ format: "uint16" }) + .check(Schema.isInt()) + .check(Schema.isGreaterThanOrEqualTo(0)), + Schema.Null, + ]), + ), + }), + }).annotate({ + title: "ResponseStreamConnectionFailedCodexErrorInfo", + description: "Failed to connect to the response SSE stream.", + }), + Schema.Struct({ + responseStreamDisconnected: Schema.Struct({ + httpStatusCode: Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ format: "uint16" }) + .check(Schema.isInt()) + .check(Schema.isGreaterThanOrEqualTo(0)), + Schema.Null, + ]), + ), + }), + }).annotate({ + title: "ResponseStreamDisconnectedCodexErrorInfo", + description: + "The response SSE stream disconnected in the middle of a turn before completion.", + }), + Schema.Struct({ + responseTooManyFailedAttempts: Schema.Struct({ + httpStatusCode: Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ format: "uint16" }) + .check(Schema.isInt()) + .check(Schema.isGreaterThanOrEqualTo(0)), + Schema.Null, + ]), + ), + }), + }).annotate({ + title: "ResponseTooManyFailedAttemptsCodexErrorInfo", + description: "Reached the retry limit for responses.", + }), + Schema.Struct({ + activeTurnNotSteerable: Schema.Struct({ + turnKind: V2ThreadResumeResponse__NonSteerableTurnKind, + }), + }).annotate({ + title: "ActiveTurnNotSteerableCodexErrorInfo", + description: + "Returned when `turn/start` or `turn/steer` is submitted while the current active turn cannot accept same-turn steering, for example `/review` or manual `/compact`.", + }), + ], + { mode: "oneOf" }, +).annotate({ + description: + "This translation layer make sure that we expose codex error code in camel case.\n\nWhen an upstream HTTP status is available (for example, from the Responses API or a provider), it is forwarded in `httpStatusCode` on the relevant `codexErrorInfo` variant.", +}); + +export type V2ThreadResumeResponse__FileUpdateChange = { + readonly diff: string; + readonly kind: V2ThreadResumeResponse__PatchChangeKind; + readonly path: string; +}; +export const V2ThreadResumeResponse__FileUpdateChange = Schema.Struct({ + diff: Schema.String, + kind: V2ThreadResumeResponse__PatchChangeKind, + path: Schema.String, +}); + +export type V2ThreadResumeResponse__UserInput = + | { + readonly text: string; + readonly text_elements?: ReadonlyArray; + readonly type: "text"; + } + | { readonly type: "image"; readonly url: string } + | { readonly path: string; readonly type: "localImage" } + | { readonly name: string; readonly path: string; readonly type: "skill" } + | { readonly name: string; readonly path: string; readonly type: "mention" }; +export const V2ThreadResumeResponse__UserInput = Schema.Union( + [ + Schema.Struct({ + text: Schema.String, + text_elements: Schema.optionalKey( + Schema.Array(V2ThreadResumeResponse__TextElement).annotate({ + description: "UI-defined spans within `text` used to render or persist special elements.", + default: [], + }), + ), + type: Schema.Literal("text").annotate({ title: "TextUserInputType" }), + }).annotate({ title: "TextUserInput" }), + Schema.Struct({ + type: Schema.Literal("image").annotate({ title: "ImageUserInputType" }), + url: Schema.String, + }).annotate({ title: "ImageUserInput" }), + Schema.Struct({ + path: Schema.String, + type: Schema.Literal("localImage").annotate({ title: "LocalImageUserInputType" }), + }).annotate({ title: "LocalImageUserInput" }), + Schema.Struct({ + name: Schema.String, + path: Schema.String, + type: Schema.Literal("skill").annotate({ title: "SkillUserInputType" }), + }).annotate({ title: "SkillUserInput" }), + Schema.Struct({ + name: Schema.String, + path: Schema.String, + type: Schema.Literal("mention").annotate({ title: "MentionUserInputType" }), + }).annotate({ title: "MentionUserInput" }), + ], + { mode: "oneOf" }, +); + +export type V2ThreadResumeResponse__SubAgentSource = + | "review" + | "compact" + | "memory_consolidation" + | { + readonly thread_spawn: { + readonly agent_nickname?: string | null; + readonly agent_path?: V2ThreadResumeResponse__AgentPath | null; + readonly agent_role?: string | null; + readonly depth: number; + readonly parent_thread_id: V2ThreadResumeResponse__ThreadId; + }; + } + | { readonly other: string }; +export const V2ThreadResumeResponse__SubAgentSource = Schema.Union( + [ + Schema.Literals(["review", "compact", "memory_consolidation"]), + Schema.Struct({ + thread_spawn: Schema.Struct({ + agent_nickname: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + agent_path: Schema.optionalKey( + Schema.Union([V2ThreadResumeResponse__AgentPath, Schema.Null]), + ), + agent_role: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + depth: Schema.Number.annotate({ format: "int32" }).check(Schema.isInt()), + parent_thread_id: V2ThreadResumeResponse__ThreadId, + }), + }).annotate({ title: "ThreadSpawnSubAgentSource" }), + Schema.Struct({ other: Schema.String }).annotate({ title: "OtherSubAgentSource" }), + ], + { mode: "oneOf" }, +); + +export type V2ThreadRollbackResponse__CollabAgentState = { + readonly message?: string | null; + readonly status: V2ThreadRollbackResponse__CollabAgentStatus; +}; +export const V2ThreadRollbackResponse__CollabAgentState = Schema.Struct({ + message: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + status: V2ThreadRollbackResponse__CollabAgentStatus, +}); + +export type V2ThreadRollbackResponse__MemoryCitation = { + readonly entries: ReadonlyArray; + readonly threadIds: ReadonlyArray; +}; +export const V2ThreadRollbackResponse__MemoryCitation = Schema.Struct({ + entries: Schema.Array(V2ThreadRollbackResponse__MemoryCitationEntry), + threadIds: Schema.Array(Schema.String), +}); + +export type V2ThreadRollbackResponse__CodexErrorInfo = + | "contextWindowExceeded" + | "usageLimitExceeded" + | "serverOverloaded" + | "internalServerError" + | "unauthorized" + | "badRequest" + | "threadRollbackFailed" + | "sandboxError" + | "other" + | { readonly httpConnectionFailed: { readonly httpStatusCode?: number | null } } + | { readonly responseStreamConnectionFailed: { readonly httpStatusCode?: number | null } } + | { readonly responseStreamDisconnected: { readonly httpStatusCode?: number | null } } + | { readonly responseTooManyFailedAttempts: { readonly httpStatusCode?: number | null } } + | { + readonly activeTurnNotSteerable: { + readonly turnKind: V2ThreadRollbackResponse__NonSteerableTurnKind; + }; + }; +export const V2ThreadRollbackResponse__CodexErrorInfo = Schema.Union( + [ + Schema.Literals([ + "contextWindowExceeded", + "usageLimitExceeded", + "serverOverloaded", + "internalServerError", + "unauthorized", + "badRequest", + "threadRollbackFailed", + "sandboxError", + "other", + ]), + Schema.Struct({ + httpConnectionFailed: Schema.Struct({ + httpStatusCode: Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ format: "uint16" }) + .check(Schema.isInt()) + .check(Schema.isGreaterThanOrEqualTo(0)), + Schema.Null, + ]), + ), + }), + }).annotate({ title: "HttpConnectionFailedCodexErrorInfo" }), + Schema.Struct({ + responseStreamConnectionFailed: Schema.Struct({ + httpStatusCode: Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ format: "uint16" }) + .check(Schema.isInt()) + .check(Schema.isGreaterThanOrEqualTo(0)), + Schema.Null, + ]), + ), + }), + }).annotate({ + title: "ResponseStreamConnectionFailedCodexErrorInfo", + description: "Failed to connect to the response SSE stream.", + }), + Schema.Struct({ + responseStreamDisconnected: Schema.Struct({ + httpStatusCode: Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ format: "uint16" }) + .check(Schema.isInt()) + .check(Schema.isGreaterThanOrEqualTo(0)), + Schema.Null, + ]), + ), + }), + }).annotate({ + title: "ResponseStreamDisconnectedCodexErrorInfo", + description: + "The response SSE stream disconnected in the middle of a turn before completion.", + }), + Schema.Struct({ + responseTooManyFailedAttempts: Schema.Struct({ + httpStatusCode: Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ format: "uint16" }) + .check(Schema.isInt()) + .check(Schema.isGreaterThanOrEqualTo(0)), + Schema.Null, + ]), + ), + }), + }).annotate({ + title: "ResponseTooManyFailedAttemptsCodexErrorInfo", + description: "Reached the retry limit for responses.", + }), + Schema.Struct({ + activeTurnNotSteerable: Schema.Struct({ + turnKind: V2ThreadRollbackResponse__NonSteerableTurnKind, + }), + }).annotate({ + title: "ActiveTurnNotSteerableCodexErrorInfo", + description: + "Returned when `turn/start` or `turn/steer` is submitted while the current active turn cannot accept same-turn steering, for example `/review` or manual `/compact`.", + }), + ], + { mode: "oneOf" }, +).annotate({ + description: + "This translation layer make sure that we expose codex error code in camel case.\n\nWhen an upstream HTTP status is available (for example, from the Responses API or a provider), it is forwarded in `httpStatusCode` on the relevant `codexErrorInfo` variant.", +}); + +export type V2ThreadRollbackResponse__FileUpdateChange = { + readonly diff: string; + readonly kind: V2ThreadRollbackResponse__PatchChangeKind; + readonly path: string; +}; +export const V2ThreadRollbackResponse__FileUpdateChange = Schema.Struct({ + diff: Schema.String, + kind: V2ThreadRollbackResponse__PatchChangeKind, + path: Schema.String, +}); + +export type V2ThreadRollbackResponse__UserInput = + | { + readonly text: string; + readonly text_elements?: ReadonlyArray; + readonly type: "text"; + } + | { readonly type: "image"; readonly url: string } + | { readonly path: string; readonly type: "localImage" } + | { readonly name: string; readonly path: string; readonly type: "skill" } + | { readonly name: string; readonly path: string; readonly type: "mention" }; +export const V2ThreadRollbackResponse__UserInput = Schema.Union( + [ + Schema.Struct({ + text: Schema.String, + text_elements: Schema.optionalKey( + Schema.Array(V2ThreadRollbackResponse__TextElement).annotate({ + description: "UI-defined spans within `text` used to render or persist special elements.", + default: [], + }), + ), + type: Schema.Literal("text").annotate({ title: "TextUserInputType" }), + }).annotate({ title: "TextUserInput" }), + Schema.Struct({ + type: Schema.Literal("image").annotate({ title: "ImageUserInputType" }), + url: Schema.String, + }).annotate({ title: "ImageUserInput" }), + Schema.Struct({ + path: Schema.String, + type: Schema.Literal("localImage").annotate({ title: "LocalImageUserInputType" }), + }).annotate({ title: "LocalImageUserInput" }), + Schema.Struct({ + name: Schema.String, + path: Schema.String, + type: Schema.Literal("skill").annotate({ title: "SkillUserInputType" }), + }).annotate({ title: "SkillUserInput" }), + Schema.Struct({ + name: Schema.String, + path: Schema.String, + type: Schema.Literal("mention").annotate({ title: "MentionUserInputType" }), + }).annotate({ title: "MentionUserInput" }), + ], + { mode: "oneOf" }, +); + +export type V2ThreadRollbackResponse__SubAgentSource = + | "review" + | "compact" + | "memory_consolidation" + | { + readonly thread_spawn: { + readonly agent_nickname?: string | null; + readonly agent_path?: V2ThreadRollbackResponse__AgentPath | null; + readonly agent_role?: string | null; + readonly depth: number; + readonly parent_thread_id: V2ThreadRollbackResponse__ThreadId; + }; + } + | { readonly other: string }; +export const V2ThreadRollbackResponse__SubAgentSource = Schema.Union( + [ + Schema.Literals(["review", "compact", "memory_consolidation"]), + Schema.Struct({ + thread_spawn: Schema.Struct({ + agent_nickname: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + agent_path: Schema.optionalKey( + Schema.Union([V2ThreadRollbackResponse__AgentPath, Schema.Null]), + ), + agent_role: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + depth: Schema.Number.annotate({ format: "int32" }).check(Schema.isInt()), + parent_thread_id: V2ThreadRollbackResponse__ThreadId, + }), + }).annotate({ title: "ThreadSpawnSubAgentSource" }), + Schema.Struct({ other: Schema.String }).annotate({ title: "OtherSubAgentSource" }), + ], + { mode: "oneOf" }, +); + +export type V2ThreadStartedNotification__CollabAgentState = { + readonly message?: string | null; + readonly status: V2ThreadStartedNotification__CollabAgentStatus; +}; +export const V2ThreadStartedNotification__CollabAgentState = Schema.Struct({ + message: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + status: V2ThreadStartedNotification__CollabAgentStatus, +}); + +export type V2ThreadStartedNotification__MemoryCitation = { + readonly entries: ReadonlyArray; + readonly threadIds: ReadonlyArray; +}; +export const V2ThreadStartedNotification__MemoryCitation = Schema.Struct({ + entries: Schema.Array(V2ThreadStartedNotification__MemoryCitationEntry), + threadIds: Schema.Array(Schema.String), +}); + +export type V2ThreadStartedNotification__CodexErrorInfo = + | "contextWindowExceeded" + | "usageLimitExceeded" + | "serverOverloaded" + | "internalServerError" + | "unauthorized" + | "badRequest" + | "threadRollbackFailed" + | "sandboxError" + | "other" + | { readonly httpConnectionFailed: { readonly httpStatusCode?: number | null } } + | { readonly responseStreamConnectionFailed: { readonly httpStatusCode?: number | null } } + | { readonly responseStreamDisconnected: { readonly httpStatusCode?: number | null } } + | { readonly responseTooManyFailedAttempts: { readonly httpStatusCode?: number | null } } + | { + readonly activeTurnNotSteerable: { + readonly turnKind: V2ThreadStartedNotification__NonSteerableTurnKind; + }; + }; +export const V2ThreadStartedNotification__CodexErrorInfo = Schema.Union( + [ + Schema.Literals([ + "contextWindowExceeded", + "usageLimitExceeded", + "serverOverloaded", + "internalServerError", + "unauthorized", + "badRequest", + "threadRollbackFailed", + "sandboxError", + "other", + ]), + Schema.Struct({ + httpConnectionFailed: Schema.Struct({ + httpStatusCode: Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ format: "uint16" }) + .check(Schema.isInt()) + .check(Schema.isGreaterThanOrEqualTo(0)), + Schema.Null, + ]), + ), + }), + }).annotate({ title: "HttpConnectionFailedCodexErrorInfo" }), + Schema.Struct({ + responseStreamConnectionFailed: Schema.Struct({ + httpStatusCode: Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ format: "uint16" }) + .check(Schema.isInt()) + .check(Schema.isGreaterThanOrEqualTo(0)), + Schema.Null, + ]), + ), + }), + }).annotate({ + title: "ResponseStreamConnectionFailedCodexErrorInfo", + description: "Failed to connect to the response SSE stream.", + }), + Schema.Struct({ + responseStreamDisconnected: Schema.Struct({ + httpStatusCode: Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ format: "uint16" }) + .check(Schema.isInt()) + .check(Schema.isGreaterThanOrEqualTo(0)), + Schema.Null, + ]), + ), + }), + }).annotate({ + title: "ResponseStreamDisconnectedCodexErrorInfo", + description: + "The response SSE stream disconnected in the middle of a turn before completion.", + }), + Schema.Struct({ + responseTooManyFailedAttempts: Schema.Struct({ + httpStatusCode: Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ format: "uint16" }) + .check(Schema.isInt()) + .check(Schema.isGreaterThanOrEqualTo(0)), + Schema.Null, + ]), + ), + }), + }).annotate({ + title: "ResponseTooManyFailedAttemptsCodexErrorInfo", + description: "Reached the retry limit for responses.", + }), + Schema.Struct({ + activeTurnNotSteerable: Schema.Struct({ + turnKind: V2ThreadStartedNotification__NonSteerableTurnKind, + }), + }).annotate({ + title: "ActiveTurnNotSteerableCodexErrorInfo", + description: + "Returned when `turn/start` or `turn/steer` is submitted while the current active turn cannot accept same-turn steering, for example `/review` or manual `/compact`.", + }), + ], + { mode: "oneOf" }, +).annotate({ + description: + "This translation layer make sure that we expose codex error code in camel case.\n\nWhen an upstream HTTP status is available (for example, from the Responses API or a provider), it is forwarded in `httpStatusCode` on the relevant `codexErrorInfo` variant.", +}); + +export type V2ThreadStartedNotification__FileUpdateChange = { + readonly diff: string; + readonly kind: V2ThreadStartedNotification__PatchChangeKind; + readonly path: string; +}; +export const V2ThreadStartedNotification__FileUpdateChange = Schema.Struct({ + diff: Schema.String, + kind: V2ThreadStartedNotification__PatchChangeKind, + path: Schema.String, +}); + +export type V2ThreadStartedNotification__UserInput = + | { + readonly text: string; + readonly text_elements?: ReadonlyArray; + readonly type: "text"; + } + | { readonly type: "image"; readonly url: string } + | { readonly path: string; readonly type: "localImage" } + | { readonly name: string; readonly path: string; readonly type: "skill" } + | { readonly name: string; readonly path: string; readonly type: "mention" }; +export const V2ThreadStartedNotification__UserInput = Schema.Union( + [ + Schema.Struct({ + text: Schema.String, + text_elements: Schema.optionalKey( + Schema.Array(V2ThreadStartedNotification__TextElement).annotate({ + description: "UI-defined spans within `text` used to render or persist special elements.", + default: [], + }), + ), + type: Schema.Literal("text").annotate({ title: "TextUserInputType" }), + }).annotate({ title: "TextUserInput" }), + Schema.Struct({ + type: Schema.Literal("image").annotate({ title: "ImageUserInputType" }), + url: Schema.String, + }).annotate({ title: "ImageUserInput" }), + Schema.Struct({ + path: Schema.String, + type: Schema.Literal("localImage").annotate({ title: "LocalImageUserInputType" }), + }).annotate({ title: "LocalImageUserInput" }), + Schema.Struct({ + name: Schema.String, + path: Schema.String, + type: Schema.Literal("skill").annotate({ title: "SkillUserInputType" }), + }).annotate({ title: "SkillUserInput" }), + Schema.Struct({ + name: Schema.String, + path: Schema.String, + type: Schema.Literal("mention").annotate({ title: "MentionUserInputType" }), + }).annotate({ title: "MentionUserInput" }), + ], + { mode: "oneOf" }, +); + +export type V2ThreadStartedNotification__SubAgentSource = + | "review" + | "compact" + | "memory_consolidation" + | { + readonly thread_spawn: { + readonly agent_nickname?: string | null; + readonly agent_path?: V2ThreadStartedNotification__AgentPath | null; + readonly agent_role?: string | null; + readonly depth: number; + readonly parent_thread_id: V2ThreadStartedNotification__ThreadId; + }; + } + | { readonly other: string }; +export const V2ThreadStartedNotification__SubAgentSource = Schema.Union( + [ + Schema.Literals(["review", "compact", "memory_consolidation"]), + Schema.Struct({ + thread_spawn: Schema.Struct({ + agent_nickname: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + agent_path: Schema.optionalKey( + Schema.Union([V2ThreadStartedNotification__AgentPath, Schema.Null]), + ), + agent_role: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + depth: Schema.Number.annotate({ format: "int32" }).check(Schema.isInt()), + parent_thread_id: V2ThreadStartedNotification__ThreadId, + }), + }).annotate({ title: "ThreadSpawnSubAgentSource" }), + Schema.Struct({ other: Schema.String }).annotate({ title: "OtherSubAgentSource" }), + ], + { mode: "oneOf" }, +); + +export type V2ThreadStartResponse__SandboxPolicy = + | { readonly type: "dangerFullAccess" } + | { + readonly access?: + | { + readonly includePlatformDefaults?: boolean; + readonly readableRoots?: ReadonlyArray; + readonly type: "restricted"; + } + | { readonly type: "fullAccess" }; + readonly networkAccess?: boolean; + readonly type: "readOnly"; + } + | { readonly networkAccess?: "restricted" | "enabled"; readonly type: "externalSandbox" } + | { + readonly excludeSlashTmp?: boolean; + readonly excludeTmpdirEnvVar?: boolean; + readonly networkAccess?: boolean; + readonly readOnlyAccess?: + | { + readonly includePlatformDefaults?: boolean; + readonly readableRoots?: ReadonlyArray; + readonly type: "restricted"; + } + | { readonly type: "fullAccess" }; + readonly type: "workspaceWrite"; + readonly writableRoots?: ReadonlyArray; + }; +export const V2ThreadStartResponse__SandboxPolicy = Schema.Union( + [ + Schema.Struct({ + type: Schema.Literal("dangerFullAccess").annotate({ + title: "DangerFullAccessSandboxPolicyType", + }), + }).annotate({ title: "DangerFullAccessSandboxPolicy" }), + Schema.Struct({ + access: Schema.optionalKey( + Schema.Union( + [ + Schema.Struct({ + includePlatformDefaults: Schema.optionalKey( + Schema.Boolean.annotate({ default: true }), + ), + readableRoots: Schema.optionalKey( + Schema.Array(V2ThreadStartResponse__AbsolutePathBuf).annotate({ default: [] }), + ), + type: Schema.Literal("restricted").annotate({ + title: "RestrictedReadOnlyAccessType", + }), + }).annotate({ title: "RestrictedReadOnlyAccess" }), + Schema.Struct({ + type: Schema.Literal("fullAccess").annotate({ + title: "FullAccessReadOnlyAccessType", + }), + }).annotate({ title: "FullAccessReadOnlyAccess" }), + ], + { mode: "oneOf" }, + ).annotate({ default: { type: "fullAccess" } }), + ), + networkAccess: Schema.optionalKey(Schema.Boolean.annotate({ default: false })), + type: Schema.Literal("readOnly").annotate({ title: "ReadOnlySandboxPolicyType" }), + }).annotate({ title: "ReadOnlySandboxPolicy" }), + Schema.Struct({ + networkAccess: Schema.optionalKey( + Schema.Literals(["restricted", "enabled"]).annotate({ default: "restricted" }), + ), + type: Schema.Literal("externalSandbox").annotate({ + title: "ExternalSandboxSandboxPolicyType", + }), + }).annotate({ title: "ExternalSandboxSandboxPolicy" }), + Schema.Struct({ + excludeSlashTmp: Schema.optionalKey(Schema.Boolean.annotate({ default: false })), + excludeTmpdirEnvVar: Schema.optionalKey(Schema.Boolean.annotate({ default: false })), + networkAccess: Schema.optionalKey(Schema.Boolean.annotate({ default: false })), + readOnlyAccess: Schema.optionalKey( + Schema.Union( + [ + Schema.Struct({ + includePlatformDefaults: Schema.optionalKey( + Schema.Boolean.annotate({ default: true }), + ), + readableRoots: Schema.optionalKey( + Schema.Array(V2ThreadStartResponse__AbsolutePathBuf).annotate({ default: [] }), + ), + type: Schema.Literal("restricted").annotate({ + title: "RestrictedReadOnlyAccessType", + }), + }).annotate({ title: "RestrictedReadOnlyAccess" }), + Schema.Struct({ + type: Schema.Literal("fullAccess").annotate({ + title: "FullAccessReadOnlyAccessType", + }), + }).annotate({ title: "FullAccessReadOnlyAccess" }), + ], + { mode: "oneOf" }, + ).annotate({ default: { type: "fullAccess" } }), + ), + type: Schema.Literal("workspaceWrite").annotate({ title: "WorkspaceWriteSandboxPolicyType" }), + writableRoots: Schema.optionalKey( + Schema.Array(V2ThreadStartResponse__AbsolutePathBuf).annotate({ default: [] }), + ), + }).annotate({ title: "WorkspaceWriteSandboxPolicy" }), + ], + { mode: "oneOf" }, +); + +export type V2ThreadStartResponse__CollabAgentState = { + readonly message?: string | null; + readonly status: V2ThreadStartResponse__CollabAgentStatus; +}; +export const V2ThreadStartResponse__CollabAgentState = Schema.Struct({ + message: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + status: V2ThreadStartResponse__CollabAgentStatus, +}); + +export type V2ThreadStartResponse__MemoryCitation = { + readonly entries: ReadonlyArray; + readonly threadIds: ReadonlyArray; +}; +export const V2ThreadStartResponse__MemoryCitation = Schema.Struct({ + entries: Schema.Array(V2ThreadStartResponse__MemoryCitationEntry), + threadIds: Schema.Array(Schema.String), +}); + +export type V2ThreadStartResponse__CodexErrorInfo = + | "contextWindowExceeded" + | "usageLimitExceeded" + | "serverOverloaded" + | "internalServerError" + | "unauthorized" + | "badRequest" + | "threadRollbackFailed" + | "sandboxError" + | "other" + | { readonly httpConnectionFailed: { readonly httpStatusCode?: number | null } } + | { readonly responseStreamConnectionFailed: { readonly httpStatusCode?: number | null } } + | { readonly responseStreamDisconnected: { readonly httpStatusCode?: number | null } } + | { readonly responseTooManyFailedAttempts: { readonly httpStatusCode?: number | null } } + | { + readonly activeTurnNotSteerable: { + readonly turnKind: V2ThreadStartResponse__NonSteerableTurnKind; + }; + }; +export const V2ThreadStartResponse__CodexErrorInfo = Schema.Union( + [ + Schema.Literals([ + "contextWindowExceeded", + "usageLimitExceeded", + "serverOverloaded", + "internalServerError", + "unauthorized", + "badRequest", + "threadRollbackFailed", + "sandboxError", + "other", + ]), + Schema.Struct({ + httpConnectionFailed: Schema.Struct({ + httpStatusCode: Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ format: "uint16" }) + .check(Schema.isInt()) + .check(Schema.isGreaterThanOrEqualTo(0)), + Schema.Null, + ]), + ), + }), + }).annotate({ title: "HttpConnectionFailedCodexErrorInfo" }), + Schema.Struct({ + responseStreamConnectionFailed: Schema.Struct({ + httpStatusCode: Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ format: "uint16" }) + .check(Schema.isInt()) + .check(Schema.isGreaterThanOrEqualTo(0)), + Schema.Null, + ]), + ), + }), + }).annotate({ + title: "ResponseStreamConnectionFailedCodexErrorInfo", + description: "Failed to connect to the response SSE stream.", + }), + Schema.Struct({ + responseStreamDisconnected: Schema.Struct({ + httpStatusCode: Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ format: "uint16" }) + .check(Schema.isInt()) + .check(Schema.isGreaterThanOrEqualTo(0)), + Schema.Null, + ]), + ), + }), + }).annotate({ + title: "ResponseStreamDisconnectedCodexErrorInfo", + description: + "The response SSE stream disconnected in the middle of a turn before completion.", + }), + Schema.Struct({ + responseTooManyFailedAttempts: Schema.Struct({ + httpStatusCode: Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ format: "uint16" }) + .check(Schema.isInt()) + .check(Schema.isGreaterThanOrEqualTo(0)), + Schema.Null, + ]), + ), + }), + }).annotate({ + title: "ResponseTooManyFailedAttemptsCodexErrorInfo", + description: "Reached the retry limit for responses.", + }), + Schema.Struct({ + activeTurnNotSteerable: Schema.Struct({ + turnKind: V2ThreadStartResponse__NonSteerableTurnKind, + }), + }).annotate({ + title: "ActiveTurnNotSteerableCodexErrorInfo", + description: + "Returned when `turn/start` or `turn/steer` is submitted while the current active turn cannot accept same-turn steering, for example `/review` or manual `/compact`.", + }), + ], + { mode: "oneOf" }, +).annotate({ + description: + "This translation layer make sure that we expose codex error code in camel case.\n\nWhen an upstream HTTP status is available (for example, from the Responses API or a provider), it is forwarded in `httpStatusCode` on the relevant `codexErrorInfo` variant.", +}); + +export type V2ThreadStartResponse__FileUpdateChange = { + readonly diff: string; + readonly kind: V2ThreadStartResponse__PatchChangeKind; + readonly path: string; +}; +export const V2ThreadStartResponse__FileUpdateChange = Schema.Struct({ + diff: Schema.String, + kind: V2ThreadStartResponse__PatchChangeKind, + path: Schema.String, +}); + +export type V2ThreadStartResponse__UserInput = + | { + readonly text: string; + readonly text_elements?: ReadonlyArray; + readonly type: "text"; + } + | { readonly type: "image"; readonly url: string } + | { readonly path: string; readonly type: "localImage" } + | { readonly name: string; readonly path: string; readonly type: "skill" } + | { readonly name: string; readonly path: string; readonly type: "mention" }; +export const V2ThreadStartResponse__UserInput = Schema.Union( + [ + Schema.Struct({ + text: Schema.String, + text_elements: Schema.optionalKey( + Schema.Array(V2ThreadStartResponse__TextElement).annotate({ + description: "UI-defined spans within `text` used to render or persist special elements.", + default: [], + }), + ), + type: Schema.Literal("text").annotate({ title: "TextUserInputType" }), + }).annotate({ title: "TextUserInput" }), + Schema.Struct({ + type: Schema.Literal("image").annotate({ title: "ImageUserInputType" }), + url: Schema.String, + }).annotate({ title: "ImageUserInput" }), + Schema.Struct({ + path: Schema.String, + type: Schema.Literal("localImage").annotate({ title: "LocalImageUserInputType" }), + }).annotate({ title: "LocalImageUserInput" }), + Schema.Struct({ + name: Schema.String, + path: Schema.String, + type: Schema.Literal("skill").annotate({ title: "SkillUserInputType" }), + }).annotate({ title: "SkillUserInput" }), + Schema.Struct({ + name: Schema.String, + path: Schema.String, + type: Schema.Literal("mention").annotate({ title: "MentionUserInputType" }), + }).annotate({ title: "MentionUserInput" }), + ], + { mode: "oneOf" }, +); + +export type V2ThreadStartResponse__SubAgentSource = + | "review" + | "compact" + | "memory_consolidation" + | { + readonly thread_spawn: { + readonly agent_nickname?: string | null; + readonly agent_path?: V2ThreadStartResponse__AgentPath | null; + readonly agent_role?: string | null; + readonly depth: number; + readonly parent_thread_id: V2ThreadStartResponse__ThreadId; + }; + } + | { readonly other: string }; +export const V2ThreadStartResponse__SubAgentSource = Schema.Union( + [ + Schema.Literals(["review", "compact", "memory_consolidation"]), + Schema.Struct({ + thread_spawn: Schema.Struct({ + agent_nickname: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + agent_path: Schema.optionalKey( + Schema.Union([V2ThreadStartResponse__AgentPath, Schema.Null]), + ), + agent_role: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + depth: Schema.Number.annotate({ format: "int32" }).check(Schema.isInt()), + parent_thread_id: V2ThreadStartResponse__ThreadId, + }), + }).annotate({ title: "ThreadSpawnSubAgentSource" }), + Schema.Struct({ other: Schema.String }).annotate({ title: "OtherSubAgentSource" }), + ], + { mode: "oneOf" }, +); + +export type V2ThreadStatusChangedNotification__ThreadStatus = + | { readonly type: "notLoaded" } + | { readonly type: "idle" } + | { readonly type: "systemError" } + | { + readonly activeFlags: ReadonlyArray; + readonly type: "active"; + }; +export const V2ThreadStatusChangedNotification__ThreadStatus = Schema.Union( + [ + Schema.Struct({ + type: Schema.Literal("notLoaded").annotate({ title: "NotLoadedThreadStatusType" }), + }).annotate({ title: "NotLoadedThreadStatus" }), + Schema.Struct({ + type: Schema.Literal("idle").annotate({ title: "IdleThreadStatusType" }), + }).annotate({ title: "IdleThreadStatus" }), + Schema.Struct({ + type: Schema.Literal("systemError").annotate({ title: "SystemErrorThreadStatusType" }), + }).annotate({ title: "SystemErrorThreadStatus" }), + Schema.Struct({ + activeFlags: Schema.Array(V2ThreadStatusChangedNotification__ThreadActiveFlag), + type: Schema.Literal("active").annotate({ title: "ActiveThreadStatusType" }), + }).annotate({ title: "ActiveThreadStatus" }), + ], + { mode: "oneOf" }, +); + +export type V2ThreadTokenUsageUpdatedNotification__ThreadTokenUsage = { + readonly last: V2ThreadTokenUsageUpdatedNotification__TokenUsageBreakdown; + readonly modelContextWindow?: number | null; + readonly total: V2ThreadTokenUsageUpdatedNotification__TokenUsageBreakdown; +}; +export const V2ThreadTokenUsageUpdatedNotification__ThreadTokenUsage = Schema.Struct({ + last: V2ThreadTokenUsageUpdatedNotification__TokenUsageBreakdown, + modelContextWindow: Schema.optionalKey( + Schema.Union([Schema.Number.annotate({ format: "int64" }).check(Schema.isInt()), Schema.Null]), + ), + total: V2ThreadTokenUsageUpdatedNotification__TokenUsageBreakdown, +}); + +export type V2ThreadUnarchiveResponse__CollabAgentState = { + readonly message?: string | null; + readonly status: V2ThreadUnarchiveResponse__CollabAgentStatus; +}; +export const V2ThreadUnarchiveResponse__CollabAgentState = Schema.Struct({ + message: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + status: V2ThreadUnarchiveResponse__CollabAgentStatus, +}); + +export type V2ThreadUnarchiveResponse__MemoryCitation = { + readonly entries: ReadonlyArray; + readonly threadIds: ReadonlyArray; +}; +export const V2ThreadUnarchiveResponse__MemoryCitation = Schema.Struct({ + entries: Schema.Array(V2ThreadUnarchiveResponse__MemoryCitationEntry), + threadIds: Schema.Array(Schema.String), +}); + +export type V2ThreadUnarchiveResponse__CodexErrorInfo = + | "contextWindowExceeded" + | "usageLimitExceeded" + | "serverOverloaded" + | "internalServerError" + | "unauthorized" + | "badRequest" + | "threadRollbackFailed" + | "sandboxError" + | "other" + | { readonly httpConnectionFailed: { readonly httpStatusCode?: number | null } } + | { readonly responseStreamConnectionFailed: { readonly httpStatusCode?: number | null } } + | { readonly responseStreamDisconnected: { readonly httpStatusCode?: number | null } } + | { readonly responseTooManyFailedAttempts: { readonly httpStatusCode?: number | null } } + | { + readonly activeTurnNotSteerable: { + readonly turnKind: V2ThreadUnarchiveResponse__NonSteerableTurnKind; + }; + }; +export const V2ThreadUnarchiveResponse__CodexErrorInfo = Schema.Union( + [ + Schema.Literals([ + "contextWindowExceeded", + "usageLimitExceeded", + "serverOverloaded", + "internalServerError", + "unauthorized", + "badRequest", + "threadRollbackFailed", + "sandboxError", + "other", + ]), + Schema.Struct({ + httpConnectionFailed: Schema.Struct({ + httpStatusCode: Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ format: "uint16" }) + .check(Schema.isInt()) + .check(Schema.isGreaterThanOrEqualTo(0)), + Schema.Null, + ]), + ), + }), + }).annotate({ title: "HttpConnectionFailedCodexErrorInfo" }), + Schema.Struct({ + responseStreamConnectionFailed: Schema.Struct({ + httpStatusCode: Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ format: "uint16" }) + .check(Schema.isInt()) + .check(Schema.isGreaterThanOrEqualTo(0)), + Schema.Null, + ]), + ), + }), + }).annotate({ + title: "ResponseStreamConnectionFailedCodexErrorInfo", + description: "Failed to connect to the response SSE stream.", + }), + Schema.Struct({ + responseStreamDisconnected: Schema.Struct({ + httpStatusCode: Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ format: "uint16" }) + .check(Schema.isInt()) + .check(Schema.isGreaterThanOrEqualTo(0)), + Schema.Null, + ]), + ), + }), + }).annotate({ + title: "ResponseStreamDisconnectedCodexErrorInfo", + description: + "The response SSE stream disconnected in the middle of a turn before completion.", + }), + Schema.Struct({ + responseTooManyFailedAttempts: Schema.Struct({ + httpStatusCode: Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ format: "uint16" }) + .check(Schema.isInt()) + .check(Schema.isGreaterThanOrEqualTo(0)), + Schema.Null, + ]), + ), + }), + }).annotate({ + title: "ResponseTooManyFailedAttemptsCodexErrorInfo", + description: "Reached the retry limit for responses.", + }), + Schema.Struct({ + activeTurnNotSteerable: Schema.Struct({ + turnKind: V2ThreadUnarchiveResponse__NonSteerableTurnKind, + }), + }).annotate({ + title: "ActiveTurnNotSteerableCodexErrorInfo", + description: + "Returned when `turn/start` or `turn/steer` is submitted while the current active turn cannot accept same-turn steering, for example `/review` or manual `/compact`.", + }), + ], + { mode: "oneOf" }, +).annotate({ + description: + "This translation layer make sure that we expose codex error code in camel case.\n\nWhen an upstream HTTP status is available (for example, from the Responses API or a provider), it is forwarded in `httpStatusCode` on the relevant `codexErrorInfo` variant.", +}); + +export type V2ThreadUnarchiveResponse__FileUpdateChange = { + readonly diff: string; + readonly kind: V2ThreadUnarchiveResponse__PatchChangeKind; + readonly path: string; +}; +export const V2ThreadUnarchiveResponse__FileUpdateChange = Schema.Struct({ + diff: Schema.String, + kind: V2ThreadUnarchiveResponse__PatchChangeKind, + path: Schema.String, +}); + +export type V2ThreadUnarchiveResponse__UserInput = + | { + readonly text: string; + readonly text_elements?: ReadonlyArray; + readonly type: "text"; + } + | { readonly type: "image"; readonly url: string } + | { readonly path: string; readonly type: "localImage" } + | { readonly name: string; readonly path: string; readonly type: "skill" } + | { readonly name: string; readonly path: string; readonly type: "mention" }; +export const V2ThreadUnarchiveResponse__UserInput = Schema.Union( + [ + Schema.Struct({ + text: Schema.String, + text_elements: Schema.optionalKey( + Schema.Array(V2ThreadUnarchiveResponse__TextElement).annotate({ + description: "UI-defined spans within `text` used to render or persist special elements.", + default: [], + }), + ), + type: Schema.Literal("text").annotate({ title: "TextUserInputType" }), + }).annotate({ title: "TextUserInput" }), + Schema.Struct({ + type: Schema.Literal("image").annotate({ title: "ImageUserInputType" }), + url: Schema.String, + }).annotate({ title: "ImageUserInput" }), + Schema.Struct({ + path: Schema.String, + type: Schema.Literal("localImage").annotate({ title: "LocalImageUserInputType" }), + }).annotate({ title: "LocalImageUserInput" }), + Schema.Struct({ + name: Schema.String, + path: Schema.String, + type: Schema.Literal("skill").annotate({ title: "SkillUserInputType" }), + }).annotate({ title: "SkillUserInput" }), + Schema.Struct({ + name: Schema.String, + path: Schema.String, + type: Schema.Literal("mention").annotate({ title: "MentionUserInputType" }), + }).annotate({ title: "MentionUserInput" }), + ], + { mode: "oneOf" }, +); + +export type V2ThreadUnarchiveResponse__SubAgentSource = + | "review" + | "compact" + | "memory_consolidation" + | { + readonly thread_spawn: { + readonly agent_nickname?: string | null; + readonly agent_path?: V2ThreadUnarchiveResponse__AgentPath | null; + readonly agent_role?: string | null; + readonly depth: number; + readonly parent_thread_id: V2ThreadUnarchiveResponse__ThreadId; + }; + } + | { readonly other: string }; +export const V2ThreadUnarchiveResponse__SubAgentSource = Schema.Union( + [ + Schema.Literals(["review", "compact", "memory_consolidation"]), + Schema.Struct({ + thread_spawn: Schema.Struct({ + agent_nickname: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + agent_path: Schema.optionalKey( + Schema.Union([V2ThreadUnarchiveResponse__AgentPath, Schema.Null]), + ), + agent_role: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + depth: Schema.Number.annotate({ format: "int32" }).check(Schema.isInt()), + parent_thread_id: V2ThreadUnarchiveResponse__ThreadId, + }), + }).annotate({ title: "ThreadSpawnSubAgentSource" }), + Schema.Struct({ other: Schema.String }).annotate({ title: "OtherSubAgentSource" }), + ], + { mode: "oneOf" }, +); + +export type V2TurnCompletedNotification__CollabAgentState = { + readonly message?: string | null; + readonly status: V2TurnCompletedNotification__CollabAgentStatus; +}; +export const V2TurnCompletedNotification__CollabAgentState = Schema.Struct({ + message: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + status: V2TurnCompletedNotification__CollabAgentStatus, +}); + +export type V2TurnCompletedNotification__MemoryCitation = { + readonly entries: ReadonlyArray; + readonly threadIds: ReadonlyArray; +}; +export const V2TurnCompletedNotification__MemoryCitation = Schema.Struct({ + entries: Schema.Array(V2TurnCompletedNotification__MemoryCitationEntry), + threadIds: Schema.Array(Schema.String), +}); + +export type V2TurnCompletedNotification__CodexErrorInfo = + | "contextWindowExceeded" + | "usageLimitExceeded" + | "serverOverloaded" + | "internalServerError" + | "unauthorized" + | "badRequest" + | "threadRollbackFailed" + | "sandboxError" + | "other" + | { readonly httpConnectionFailed: { readonly httpStatusCode?: number | null } } + | { readonly responseStreamConnectionFailed: { readonly httpStatusCode?: number | null } } + | { readonly responseStreamDisconnected: { readonly httpStatusCode?: number | null } } + | { readonly responseTooManyFailedAttempts: { readonly httpStatusCode?: number | null } } + | { + readonly activeTurnNotSteerable: { + readonly turnKind: V2TurnCompletedNotification__NonSteerableTurnKind; + }; + }; +export const V2TurnCompletedNotification__CodexErrorInfo = Schema.Union( + [ + Schema.Literals([ + "contextWindowExceeded", + "usageLimitExceeded", + "serverOverloaded", + "internalServerError", + "unauthorized", + "badRequest", + "threadRollbackFailed", + "sandboxError", + "other", + ]), + Schema.Struct({ + httpConnectionFailed: Schema.Struct({ + httpStatusCode: Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ format: "uint16" }) + .check(Schema.isInt()) + .check(Schema.isGreaterThanOrEqualTo(0)), + Schema.Null, + ]), + ), + }), + }).annotate({ title: "HttpConnectionFailedCodexErrorInfo" }), + Schema.Struct({ + responseStreamConnectionFailed: Schema.Struct({ + httpStatusCode: Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ format: "uint16" }) + .check(Schema.isInt()) + .check(Schema.isGreaterThanOrEqualTo(0)), + Schema.Null, + ]), + ), + }), + }).annotate({ + title: "ResponseStreamConnectionFailedCodexErrorInfo", + description: "Failed to connect to the response SSE stream.", + }), + Schema.Struct({ + responseStreamDisconnected: Schema.Struct({ + httpStatusCode: Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ format: "uint16" }) + .check(Schema.isInt()) + .check(Schema.isGreaterThanOrEqualTo(0)), + Schema.Null, + ]), + ), + }), + }).annotate({ + title: "ResponseStreamDisconnectedCodexErrorInfo", + description: + "The response SSE stream disconnected in the middle of a turn before completion.", + }), + Schema.Struct({ + responseTooManyFailedAttempts: Schema.Struct({ + httpStatusCode: Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ format: "uint16" }) + .check(Schema.isInt()) + .check(Schema.isGreaterThanOrEqualTo(0)), + Schema.Null, + ]), + ), + }), + }).annotate({ + title: "ResponseTooManyFailedAttemptsCodexErrorInfo", + description: "Reached the retry limit for responses.", + }), + Schema.Struct({ + activeTurnNotSteerable: Schema.Struct({ + turnKind: V2TurnCompletedNotification__NonSteerableTurnKind, + }), + }).annotate({ + title: "ActiveTurnNotSteerableCodexErrorInfo", + description: + "Returned when `turn/start` or `turn/steer` is submitted while the current active turn cannot accept same-turn steering, for example `/review` or manual `/compact`.", + }), + ], + { mode: "oneOf" }, +).annotate({ + description: + "This translation layer make sure that we expose codex error code in camel case.\n\nWhen an upstream HTTP status is available (for example, from the Responses API or a provider), it is forwarded in `httpStatusCode` on the relevant `codexErrorInfo` variant.", +}); + +export type V2TurnCompletedNotification__FileUpdateChange = { + readonly diff: string; + readonly kind: V2TurnCompletedNotification__PatchChangeKind; + readonly path: string; +}; +export const V2TurnCompletedNotification__FileUpdateChange = Schema.Struct({ + diff: Schema.String, + kind: V2TurnCompletedNotification__PatchChangeKind, + path: Schema.String, +}); + +export type V2TurnCompletedNotification__UserInput = + | { + readonly text: string; + readonly text_elements?: ReadonlyArray; + readonly type: "text"; + } + | { readonly type: "image"; readonly url: string } + | { readonly path: string; readonly type: "localImage" } + | { readonly name: string; readonly path: string; readonly type: "skill" } + | { readonly name: string; readonly path: string; readonly type: "mention" }; +export const V2TurnCompletedNotification__UserInput = Schema.Union( + [ + Schema.Struct({ + text: Schema.String, + text_elements: Schema.optionalKey( + Schema.Array(V2TurnCompletedNotification__TextElement).annotate({ + description: "UI-defined spans within `text` used to render or persist special elements.", + default: [], + }), + ), + type: Schema.Literal("text").annotate({ title: "TextUserInputType" }), + }).annotate({ title: "TextUserInput" }), + Schema.Struct({ + type: Schema.Literal("image").annotate({ title: "ImageUserInputType" }), + url: Schema.String, + }).annotate({ title: "ImageUserInput" }), + Schema.Struct({ + path: Schema.String, + type: Schema.Literal("localImage").annotate({ title: "LocalImageUserInputType" }), + }).annotate({ title: "LocalImageUserInput" }), + Schema.Struct({ + name: Schema.String, + path: Schema.String, + type: Schema.Literal("skill").annotate({ title: "SkillUserInputType" }), + }).annotate({ title: "SkillUserInput" }), + Schema.Struct({ + name: Schema.String, + path: Schema.String, + type: Schema.Literal("mention").annotate({ title: "MentionUserInputType" }), + }).annotate({ title: "MentionUserInput" }), + ], + { mode: "oneOf" }, +); + +export type V2TurnPlanUpdatedNotification__TurnPlanStep = { + readonly status: V2TurnPlanUpdatedNotification__TurnPlanStepStatus; + readonly step: string; +}; +export const V2TurnPlanUpdatedNotification__TurnPlanStep = Schema.Struct({ + status: V2TurnPlanUpdatedNotification__TurnPlanStepStatus, + step: Schema.String, +}); + +export type V2TurnStartedNotification__CollabAgentState = { + readonly message?: string | null; + readonly status: V2TurnStartedNotification__CollabAgentStatus; +}; +export const V2TurnStartedNotification__CollabAgentState = Schema.Struct({ + message: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + status: V2TurnStartedNotification__CollabAgentStatus, +}); + +export type V2TurnStartedNotification__MemoryCitation = { + readonly entries: ReadonlyArray; + readonly threadIds: ReadonlyArray; +}; +export const V2TurnStartedNotification__MemoryCitation = Schema.Struct({ + entries: Schema.Array(V2TurnStartedNotification__MemoryCitationEntry), + threadIds: Schema.Array(Schema.String), +}); + +export type V2TurnStartedNotification__CodexErrorInfo = + | "contextWindowExceeded" + | "usageLimitExceeded" + | "serverOverloaded" + | "internalServerError" + | "unauthorized" + | "badRequest" + | "threadRollbackFailed" + | "sandboxError" + | "other" + | { readonly httpConnectionFailed: { readonly httpStatusCode?: number | null } } + | { readonly responseStreamConnectionFailed: { readonly httpStatusCode?: number | null } } + | { readonly responseStreamDisconnected: { readonly httpStatusCode?: number | null } } + | { readonly responseTooManyFailedAttempts: { readonly httpStatusCode?: number | null } } + | { + readonly activeTurnNotSteerable: { + readonly turnKind: V2TurnStartedNotification__NonSteerableTurnKind; + }; + }; +export const V2TurnStartedNotification__CodexErrorInfo = Schema.Union( + [ + Schema.Literals([ + "contextWindowExceeded", + "usageLimitExceeded", + "serverOverloaded", + "internalServerError", + "unauthorized", + "badRequest", + "threadRollbackFailed", + "sandboxError", + "other", + ]), + Schema.Struct({ + httpConnectionFailed: Schema.Struct({ + httpStatusCode: Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ format: "uint16" }) + .check(Schema.isInt()) + .check(Schema.isGreaterThanOrEqualTo(0)), + Schema.Null, + ]), + ), + }), + }).annotate({ title: "HttpConnectionFailedCodexErrorInfo" }), + Schema.Struct({ + responseStreamConnectionFailed: Schema.Struct({ + httpStatusCode: Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ format: "uint16" }) + .check(Schema.isInt()) + .check(Schema.isGreaterThanOrEqualTo(0)), + Schema.Null, + ]), + ), + }), + }).annotate({ + title: "ResponseStreamConnectionFailedCodexErrorInfo", + description: "Failed to connect to the response SSE stream.", + }), + Schema.Struct({ + responseStreamDisconnected: Schema.Struct({ + httpStatusCode: Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ format: "uint16" }) + .check(Schema.isInt()) + .check(Schema.isGreaterThanOrEqualTo(0)), + Schema.Null, + ]), + ), + }), + }).annotate({ + title: "ResponseStreamDisconnectedCodexErrorInfo", + description: + "The response SSE stream disconnected in the middle of a turn before completion.", + }), + Schema.Struct({ + responseTooManyFailedAttempts: Schema.Struct({ + httpStatusCode: Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ format: "uint16" }) + .check(Schema.isInt()) + .check(Schema.isGreaterThanOrEqualTo(0)), + Schema.Null, + ]), + ), + }), + }).annotate({ + title: "ResponseTooManyFailedAttemptsCodexErrorInfo", + description: "Reached the retry limit for responses.", + }), + Schema.Struct({ + activeTurnNotSteerable: Schema.Struct({ + turnKind: V2TurnStartedNotification__NonSteerableTurnKind, + }), + }).annotate({ + title: "ActiveTurnNotSteerableCodexErrorInfo", + description: + "Returned when `turn/start` or `turn/steer` is submitted while the current active turn cannot accept same-turn steering, for example `/review` or manual `/compact`.", + }), + ], + { mode: "oneOf" }, +).annotate({ + description: + "This translation layer make sure that we expose codex error code in camel case.\n\nWhen an upstream HTTP status is available (for example, from the Responses API or a provider), it is forwarded in `httpStatusCode` on the relevant `codexErrorInfo` variant.", +}); + +export type V2TurnStartedNotification__FileUpdateChange = { + readonly diff: string; + readonly kind: V2TurnStartedNotification__PatchChangeKind; + readonly path: string; +}; +export const V2TurnStartedNotification__FileUpdateChange = Schema.Struct({ + diff: Schema.String, + kind: V2TurnStartedNotification__PatchChangeKind, + path: Schema.String, +}); + +export type V2TurnStartedNotification__UserInput = + | { + readonly text: string; + readonly text_elements?: ReadonlyArray; + readonly type: "text"; + } + | { readonly type: "image"; readonly url: string } + | { readonly path: string; readonly type: "localImage" } + | { readonly name: string; readonly path: string; readonly type: "skill" } + | { readonly name: string; readonly path: string; readonly type: "mention" }; +export const V2TurnStartedNotification__UserInput = Schema.Union( + [ + Schema.Struct({ + text: Schema.String, + text_elements: Schema.optionalKey( + Schema.Array(V2TurnStartedNotification__TextElement).annotate({ + description: "UI-defined spans within `text` used to render or persist special elements.", + default: [], + }), + ), + type: Schema.Literal("text").annotate({ title: "TextUserInputType" }), + }).annotate({ title: "TextUserInput" }), + Schema.Struct({ + type: Schema.Literal("image").annotate({ title: "ImageUserInputType" }), + url: Schema.String, + }).annotate({ title: "ImageUserInput" }), + Schema.Struct({ + path: Schema.String, + type: Schema.Literal("localImage").annotate({ title: "LocalImageUserInputType" }), + }).annotate({ title: "LocalImageUserInput" }), + Schema.Struct({ + name: Schema.String, + path: Schema.String, + type: Schema.Literal("skill").annotate({ title: "SkillUserInputType" }), + }).annotate({ title: "SkillUserInput" }), + Schema.Struct({ + name: Schema.String, + path: Schema.String, + type: Schema.Literal("mention").annotate({ title: "MentionUserInputType" }), + }).annotate({ title: "MentionUserInput" }), + ], + { mode: "oneOf" }, +); + +export type V2TurnStartParams__SandboxPolicy = + | { readonly type: "dangerFullAccess" } + | { + readonly access?: + | { + readonly includePlatformDefaults?: boolean; + readonly readableRoots?: ReadonlyArray; + readonly type: "restricted"; + } + | { readonly type: "fullAccess" }; + readonly networkAccess?: boolean; + readonly type: "readOnly"; + } + | { readonly networkAccess?: "restricted" | "enabled"; readonly type: "externalSandbox" } + | { + readonly excludeSlashTmp?: boolean; + readonly excludeTmpdirEnvVar?: boolean; + readonly networkAccess?: boolean; + readonly readOnlyAccess?: + | { + readonly includePlatformDefaults?: boolean; + readonly readableRoots?: ReadonlyArray; + readonly type: "restricted"; + } + | { readonly type: "fullAccess" }; + readonly type: "workspaceWrite"; + readonly writableRoots?: ReadonlyArray; + }; +export const V2TurnStartParams__SandboxPolicy = Schema.Union( + [ + Schema.Struct({ + type: Schema.Literal("dangerFullAccess").annotate({ + title: "DangerFullAccessSandboxPolicyType", + }), + }).annotate({ title: "DangerFullAccessSandboxPolicy" }), + Schema.Struct({ + access: Schema.optionalKey( + Schema.Union( + [ + Schema.Struct({ + includePlatformDefaults: Schema.optionalKey( + Schema.Boolean.annotate({ default: true }), + ), + readableRoots: Schema.optionalKey( + Schema.Array(V2TurnStartParams__AbsolutePathBuf).annotate({ default: [] }), + ), + type: Schema.Literal("restricted").annotate({ + title: "RestrictedReadOnlyAccessType", + }), + }).annotate({ title: "RestrictedReadOnlyAccess" }), + Schema.Struct({ + type: Schema.Literal("fullAccess").annotate({ + title: "FullAccessReadOnlyAccessType", + }), + }).annotate({ title: "FullAccessReadOnlyAccess" }), + ], + { mode: "oneOf" }, + ).annotate({ default: { type: "fullAccess" } }), + ), + networkAccess: Schema.optionalKey(Schema.Boolean.annotate({ default: false })), + type: Schema.Literal("readOnly").annotate({ title: "ReadOnlySandboxPolicyType" }), + }).annotate({ title: "ReadOnlySandboxPolicy" }), + Schema.Struct({ + networkAccess: Schema.optionalKey( + Schema.Literals(["restricted", "enabled"]).annotate({ default: "restricted" }), + ), + type: Schema.Literal("externalSandbox").annotate({ + title: "ExternalSandboxSandboxPolicyType", + }), + }).annotate({ title: "ExternalSandboxSandboxPolicy" }), + Schema.Struct({ + excludeSlashTmp: Schema.optionalKey(Schema.Boolean.annotate({ default: false })), + excludeTmpdirEnvVar: Schema.optionalKey(Schema.Boolean.annotate({ default: false })), + networkAccess: Schema.optionalKey(Schema.Boolean.annotate({ default: false })), + readOnlyAccess: Schema.optionalKey( + Schema.Union( + [ + Schema.Struct({ + includePlatformDefaults: Schema.optionalKey( + Schema.Boolean.annotate({ default: true }), + ), + readableRoots: Schema.optionalKey( + Schema.Array(V2TurnStartParams__AbsolutePathBuf).annotate({ default: [] }), + ), + type: Schema.Literal("restricted").annotate({ + title: "RestrictedReadOnlyAccessType", + }), + }).annotate({ title: "RestrictedReadOnlyAccess" }), + Schema.Struct({ + type: Schema.Literal("fullAccess").annotate({ + title: "FullAccessReadOnlyAccessType", + }), + }).annotate({ title: "FullAccessReadOnlyAccess" }), + ], + { mode: "oneOf" }, + ).annotate({ default: { type: "fullAccess" } }), + ), + type: Schema.Literal("workspaceWrite").annotate({ title: "WorkspaceWriteSandboxPolicyType" }), + writableRoots: Schema.optionalKey( + Schema.Array(V2TurnStartParams__AbsolutePathBuf).annotate({ default: [] }), + ), + }).annotate({ title: "WorkspaceWriteSandboxPolicy" }), + ], + { mode: "oneOf" }, +); + +export type V2TurnStartParams__Settings = { + readonly developer_instructions?: string | null; + readonly model: string; + readonly reasoning_effort?: V2TurnStartParams__ReasoningEffort | null; +}; +export const V2TurnStartParams__Settings = Schema.Struct({ + developer_instructions: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + model: Schema.String, + reasoning_effort: Schema.optionalKey( + Schema.Union([V2TurnStartParams__ReasoningEffort, Schema.Null]), + ), +}).annotate({ description: "Settings for a collaboration mode." }); + +export type V2TurnStartParams__UserInput = + | { + readonly text: string; + readonly text_elements?: ReadonlyArray; + readonly type: "text"; + } + | { readonly type: "image"; readonly url: string } + | { readonly path: string; readonly type: "localImage" } + | { readonly name: string; readonly path: string; readonly type: "skill" } + | { readonly name: string; readonly path: string; readonly type: "mention" }; +export const V2TurnStartParams__UserInput = Schema.Union( + [ + Schema.Struct({ + text: Schema.String, + text_elements: Schema.optionalKey( + Schema.Array(V2TurnStartParams__TextElement).annotate({ + description: "UI-defined spans within `text` used to render or persist special elements.", + default: [], + }), + ), + type: Schema.Literal("text").annotate({ title: "TextUserInputType" }), + }).annotate({ title: "TextUserInput" }), + Schema.Struct({ + type: Schema.Literal("image").annotate({ title: "ImageUserInputType" }), + url: Schema.String, + }).annotate({ title: "ImageUserInput" }), + Schema.Struct({ + path: Schema.String, + type: Schema.Literal("localImage").annotate({ title: "LocalImageUserInputType" }), + }).annotate({ title: "LocalImageUserInput" }), + Schema.Struct({ + name: Schema.String, + path: Schema.String, + type: Schema.Literal("skill").annotate({ title: "SkillUserInputType" }), + }).annotate({ title: "SkillUserInput" }), + Schema.Struct({ + name: Schema.String, + path: Schema.String, + type: Schema.Literal("mention").annotate({ title: "MentionUserInputType" }), + }).annotate({ title: "MentionUserInput" }), + ], + { mode: "oneOf" }, +); + +export type V2TurnStartResponse__CollabAgentState = { + readonly message?: string | null; + readonly status: V2TurnStartResponse__CollabAgentStatus; +}; +export const V2TurnStartResponse__CollabAgentState = Schema.Struct({ + message: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + status: V2TurnStartResponse__CollabAgentStatus, +}); + +export type V2TurnStartResponse__MemoryCitation = { + readonly entries: ReadonlyArray; + readonly threadIds: ReadonlyArray; +}; +export const V2TurnStartResponse__MemoryCitation = Schema.Struct({ + entries: Schema.Array(V2TurnStartResponse__MemoryCitationEntry), + threadIds: Schema.Array(Schema.String), +}); + +export type V2TurnStartResponse__CodexErrorInfo = + | "contextWindowExceeded" + | "usageLimitExceeded" + | "serverOverloaded" + | "internalServerError" + | "unauthorized" + | "badRequest" + | "threadRollbackFailed" + | "sandboxError" + | "other" + | { readonly httpConnectionFailed: { readonly httpStatusCode?: number | null } } + | { readonly responseStreamConnectionFailed: { readonly httpStatusCode?: number | null } } + | { readonly responseStreamDisconnected: { readonly httpStatusCode?: number | null } } + | { readonly responseTooManyFailedAttempts: { readonly httpStatusCode?: number | null } } + | { + readonly activeTurnNotSteerable: { + readonly turnKind: V2TurnStartResponse__NonSteerableTurnKind; + }; + }; +export const V2TurnStartResponse__CodexErrorInfo = Schema.Union( + [ + Schema.Literals([ + "contextWindowExceeded", + "usageLimitExceeded", + "serverOverloaded", + "internalServerError", + "unauthorized", + "badRequest", + "threadRollbackFailed", + "sandboxError", + "other", + ]), + Schema.Struct({ + httpConnectionFailed: Schema.Struct({ + httpStatusCode: Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ format: "uint16" }) + .check(Schema.isInt()) + .check(Schema.isGreaterThanOrEqualTo(0)), + Schema.Null, + ]), + ), + }), + }).annotate({ title: "HttpConnectionFailedCodexErrorInfo" }), + Schema.Struct({ + responseStreamConnectionFailed: Schema.Struct({ + httpStatusCode: Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ format: "uint16" }) + .check(Schema.isInt()) + .check(Schema.isGreaterThanOrEqualTo(0)), + Schema.Null, + ]), + ), + }), + }).annotate({ + title: "ResponseStreamConnectionFailedCodexErrorInfo", + description: "Failed to connect to the response SSE stream.", + }), + Schema.Struct({ + responseStreamDisconnected: Schema.Struct({ + httpStatusCode: Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ format: "uint16" }) + .check(Schema.isInt()) + .check(Schema.isGreaterThanOrEqualTo(0)), + Schema.Null, + ]), + ), + }), + }).annotate({ + title: "ResponseStreamDisconnectedCodexErrorInfo", + description: + "The response SSE stream disconnected in the middle of a turn before completion.", + }), + Schema.Struct({ + responseTooManyFailedAttempts: Schema.Struct({ + httpStatusCode: Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ format: "uint16" }) + .check(Schema.isInt()) + .check(Schema.isGreaterThanOrEqualTo(0)), + Schema.Null, + ]), + ), + }), + }).annotate({ + title: "ResponseTooManyFailedAttemptsCodexErrorInfo", + description: "Reached the retry limit for responses.", + }), + Schema.Struct({ + activeTurnNotSteerable: Schema.Struct({ + turnKind: V2TurnStartResponse__NonSteerableTurnKind, + }), + }).annotate({ + title: "ActiveTurnNotSteerableCodexErrorInfo", + description: + "Returned when `turn/start` or `turn/steer` is submitted while the current active turn cannot accept same-turn steering, for example `/review` or manual `/compact`.", + }), + ], + { mode: "oneOf" }, +).annotate({ + description: + "This translation layer make sure that we expose codex error code in camel case.\n\nWhen an upstream HTTP status is available (for example, from the Responses API or a provider), it is forwarded in `httpStatusCode` on the relevant `codexErrorInfo` variant.", +}); + +export type V2TurnStartResponse__FileUpdateChange = { + readonly diff: string; + readonly kind: V2TurnStartResponse__PatchChangeKind; + readonly path: string; +}; +export const V2TurnStartResponse__FileUpdateChange = Schema.Struct({ + diff: Schema.String, + kind: V2TurnStartResponse__PatchChangeKind, + path: Schema.String, +}); + +export type V2TurnStartResponse__UserInput = + | { + readonly text: string; + readonly text_elements?: ReadonlyArray; + readonly type: "text"; + } + | { readonly type: "image"; readonly url: string } + | { readonly path: string; readonly type: "localImage" } + | { readonly name: string; readonly path: string; readonly type: "skill" } + | { readonly name: string; readonly path: string; readonly type: "mention" }; +export const V2TurnStartResponse__UserInput = Schema.Union( + [ + Schema.Struct({ + text: Schema.String, + text_elements: Schema.optionalKey( + Schema.Array(V2TurnStartResponse__TextElement).annotate({ + description: "UI-defined spans within `text` used to render or persist special elements.", + default: [], + }), + ), + type: Schema.Literal("text").annotate({ title: "TextUserInputType" }), + }).annotate({ title: "TextUserInput" }), + Schema.Struct({ + type: Schema.Literal("image").annotate({ title: "ImageUserInputType" }), + url: Schema.String, + }).annotate({ title: "ImageUserInput" }), + Schema.Struct({ + path: Schema.String, + type: Schema.Literal("localImage").annotate({ title: "LocalImageUserInputType" }), + }).annotate({ title: "LocalImageUserInput" }), + Schema.Struct({ + name: Schema.String, + path: Schema.String, + type: Schema.Literal("skill").annotate({ title: "SkillUserInputType" }), + }).annotate({ title: "SkillUserInput" }), + Schema.Struct({ + name: Schema.String, + path: Schema.String, + type: Schema.Literal("mention").annotate({ title: "MentionUserInputType" }), + }).annotate({ title: "MentionUserInput" }), + ], + { mode: "oneOf" }, +); + +export type V2TurnSteerParams__UserInput = + | { + readonly text: string; + readonly text_elements?: ReadonlyArray; + readonly type: "text"; + } + | { readonly type: "image"; readonly url: string } + | { readonly path: string; readonly type: "localImage" } + | { readonly name: string; readonly path: string; readonly type: "skill" } + | { readonly name: string; readonly path: string; readonly type: "mention" }; +export const V2TurnSteerParams__UserInput = Schema.Union( + [ + Schema.Struct({ + text: Schema.String, + text_elements: Schema.optionalKey( + Schema.Array(V2TurnSteerParams__TextElement).annotate({ + description: "UI-defined spans within `text` used to render or persist special elements.", + default: [], + }), + ), + type: Schema.Literal("text").annotate({ title: "TextUserInputType" }), + }).annotate({ title: "TextUserInput" }), + Schema.Struct({ + type: Schema.Literal("image").annotate({ title: "ImageUserInputType" }), + url: Schema.String, + }).annotate({ title: "ImageUserInput" }), + Schema.Struct({ + path: Schema.String, + type: Schema.Literal("localImage").annotate({ title: "LocalImageUserInputType" }), + }).annotate({ title: "LocalImageUserInput" }), + Schema.Struct({ + name: Schema.String, + path: Schema.String, + type: Schema.Literal("skill").annotate({ title: "SkillUserInputType" }), + }).annotate({ title: "SkillUserInput" }), + Schema.Struct({ + name: Schema.String, + path: Schema.String, + type: Schema.Literal("mention").annotate({ title: "MentionUserInputType" }), + }).annotate({ title: "MentionUserInput" }), + ], + { mode: "oneOf" }, +); + +export type ApplyPatchApprovalResponse__ReviewDecision = + | "approved" + | { + readonly approved_execpolicy_amendment: { + readonly proposed_execpolicy_amendment: ReadonlyArray; + }; + } + | "approved_for_session" + | { + readonly network_policy_amendment: { + readonly network_policy_amendment: ApplyPatchApprovalResponse__NetworkPolicyAmendment; + }; + } + | "denied" + | "timed_out" + | "abort"; +export const ApplyPatchApprovalResponse__ReviewDecision = Schema.Union( + [ + Schema.Literal("approved").annotate({ + description: "User has approved this command and the agent should execute it.", + }), + Schema.Struct({ + approved_execpolicy_amendment: Schema.Struct({ + proposed_execpolicy_amendment: Schema.Array(Schema.String), + }), + }).annotate({ + title: "ApprovedExecpolicyAmendmentReviewDecision", + description: + "User has approved this command and wants to apply the proposed execpolicy amendment so future matching commands are permitted.", + }), + Schema.Literal("approved_for_session").annotate({ + description: + "User has approved this request and wants future prompts in the same session-scoped approval cache to be automatically approved for the remainder of the session.", + }), + Schema.Struct({ + network_policy_amendment: Schema.Struct({ + network_policy_amendment: ApplyPatchApprovalResponse__NetworkPolicyAmendment, + }), + }).annotate({ + title: "NetworkPolicyAmendmentReviewDecision", + description: + "User chose to persist a network policy rule (allow/deny) for future requests to the same host.", + }), + Schema.Literal("denied").annotate({ + description: + "User has denied this command and the agent should not execute it, but it should continue the session and try something else.", + }), + Schema.Literal("timed_out").annotate({ + description: "Automatic approval review timed out before reaching a decision.", + }), + Schema.Literal("abort").annotate({ + description: + "User has denied this command and the agent should not do anything until the user's next command.", + }), + ], + { mode: "oneOf" }, +).annotate({ description: "User's decision in response to an ExecApprovalRequest." }); + +export type ClientRequest__CommandExecParams = { + readonly command: ReadonlyArray; + readonly cwd?: string | null; + readonly disableOutputCap?: boolean; + readonly disableTimeout?: boolean; + readonly env?: { readonly [x: string]: string | null } | null; + readonly outputBytesCap?: number | null; + readonly processId?: string | null; + readonly sandboxPolicy?: ClientRequest__SandboxPolicy | null; + readonly size?: ClientRequest__CommandExecTerminalSize | null; + readonly streamStdin?: boolean; + readonly streamStdoutStderr?: boolean; + readonly timeoutMs?: number | null; + readonly tty?: boolean; +}; +export const ClientRequest__CommandExecParams = Schema.Struct({ + command: Schema.Array(Schema.String).annotate({ + description: "Command argv vector. Empty arrays are rejected.", + }), + cwd: Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + description: "Optional working directory. Defaults to the server cwd.", + }), + Schema.Null, + ]), + ), + disableOutputCap: Schema.optionalKey( + Schema.Boolean.annotate({ + description: + "Disable stdout/stderr capture truncation for this request.\n\nCannot be combined with `outputBytesCap`.", + }), + ), + disableTimeout: Schema.optionalKey( + Schema.Boolean.annotate({ + description: + "Disable the timeout entirely for this request.\n\nCannot be combined with `timeoutMs`.", + }), + ), + env: Schema.optionalKey( + Schema.Union([ + Schema.Record(Schema.String, Schema.Union([Schema.String, Schema.Null])).annotate({ + description: + "Optional environment overrides merged into the server-computed environment.\n\nMatching names override inherited values. Set a key to `null` to unset an inherited variable.", + }), + Schema.Null, + ]), + ), + outputBytesCap: Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ + description: + "Optional per-stream stdout/stderr capture cap in bytes.\n\nWhen omitted, the server default applies. Cannot be combined with `disableOutputCap`.", + format: "uint", + }) + .check(Schema.isInt()) + .check(Schema.isGreaterThanOrEqualTo(0)), + Schema.Null, + ]), + ), + processId: Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + description: + "Optional client-supplied, connection-scoped process id.\n\nRequired for `tty`, `streamStdin`, `streamStdoutStderr`, and follow-up `command/exec/write`, `command/exec/resize`, and `command/exec/terminate` calls. When omitted, buffered execution gets an internal id that is not exposed to the client.", + }), + Schema.Null, + ]), + ), + sandboxPolicy: Schema.optionalKey( + Schema.Union([ClientRequest__SandboxPolicy, Schema.Null]).annotate({ + description: + "Optional sandbox policy for this command.\n\nUses the same shape as thread/turn execution sandbox configuration and defaults to the user's configured policy when omitted.", + }), + ), + size: Schema.optionalKey( + Schema.Union([ClientRequest__CommandExecTerminalSize, Schema.Null]).annotate({ + description: "Optional initial PTY size in character cells. Only valid when `tty` is true.", + }), + ), + streamStdin: Schema.optionalKey( + Schema.Boolean.annotate({ + description: + "Allow follow-up `command/exec/write` requests to write stdin bytes.\n\nRequires a client-supplied `processId`.", + }), + ), + streamStdoutStderr: Schema.optionalKey( + Schema.Boolean.annotate({ + description: + "Stream stdout/stderr via `command/exec/outputDelta` notifications.\n\nStreamed bytes are not duplicated into the final response and require a client-supplied `processId`.", + }), + ), + timeoutMs: Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ + description: + "Optional timeout in milliseconds.\n\nWhen omitted, the server default applies. Cannot be combined with `disableTimeout`.", + format: "int64", + }).check(Schema.isInt()), + Schema.Null, + ]), + ), + tty: Schema.optionalKey( + Schema.Boolean.annotate({ + description: "Enable PTY mode.\n\nThis implies `streamStdin` and `streamStdoutStderr`.", + }), + ), +}).annotate({ + description: + "Run a standalone command (argv vector) in the server sandbox without creating a thread or turn.\n\nThe final `command/exec` response is deferred until the process exits and is sent only after all `command/exec/outputDelta` notifications for that connection have been emitted.", +}); + +export type ClientRequest__ExternalAgentConfigImportParams = { + readonly migrationItems: ReadonlyArray; +}; +export const ClientRequest__ExternalAgentConfigImportParams = Schema.Struct({ + migrationItems: Schema.Array(ClientRequest__ExternalAgentConfigMigrationItem), +}); + +export type ClientRequest__FunctionCallOutputBody = + | string + | ReadonlyArray; +export const ClientRequest__FunctionCallOutputBody = Schema.Union([ + Schema.String, + Schema.Array(ClientRequest__FunctionCallOutputContentItem), +]); + +export type ClientRequest__ConfigBatchWriteParams = { + readonly edits: ReadonlyArray; + readonly expectedVersion?: string | null; + readonly filePath?: string | null; + readonly reloadUserConfig?: boolean; +}; +export const ClientRequest__ConfigBatchWriteParams = Schema.Struct({ + edits: Schema.Array(ClientRequest__ConfigEdit), + expectedVersion: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + filePath: Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + description: + "Path to the config file to write; defaults to the user's `config.toml` when omitted.", + }), + Schema.Null, + ]), + ), + reloadUserConfig: Schema.optionalKey( + Schema.Boolean.annotate({ + description: + "When true, hot-reload the updated user config into all loaded threads after writing.", + }), + ), +}); + +export type ClientRequest__TurnStartParams = { + readonly approvalPolicy?: ClientRequest__AskForApproval | null; + readonly approvalsReviewer?: ClientRequest__ApprovalsReviewer | null; + readonly cwd?: string | null; + readonly effort?: ClientRequest__ReasoningEffort | null; + readonly input: ReadonlyArray; + readonly model?: string | null; + readonly outputSchema?: unknown; + readonly personality?: ClientRequest__Personality | null; + readonly sandboxPolicy?: ClientRequest__SandboxPolicy | null; + readonly serviceTier?: ClientRequest__ServiceTier | null | null; + readonly summary?: ClientRequest__ReasoningSummary | null; + readonly threadId: string; +}; +export const ClientRequest__TurnStartParams = Schema.Struct({ + approvalPolicy: Schema.optionalKey( + Schema.Union([ClientRequest__AskForApproval, Schema.Null]).annotate({ + description: "Override the approval policy for this turn and subsequent turns.", + }), + ), + approvalsReviewer: Schema.optionalKey( + Schema.Union([ClientRequest__ApprovalsReviewer, Schema.Null]).annotate({ + description: + "Override where approval requests are routed for review on this turn and subsequent turns.", + }), + ), + cwd: Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + description: "Override the working directory for this turn and subsequent turns.", + }), + Schema.Null, + ]), + ), + effort: Schema.optionalKey( + Schema.Union([ClientRequest__ReasoningEffort, Schema.Null]).annotate({ + description: "Override the reasoning effort for this turn and subsequent turns.", + }), + ), + input: Schema.Array(ClientRequest__UserInput), + model: Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + description: "Override the model for this turn and subsequent turns.", + }), + Schema.Null, + ]), + ), + outputSchema: Schema.optionalKey( + Schema.Unknown.annotate({ + description: + "Optional JSON Schema used to constrain the final assistant message for this turn.", + }), + ), + personality: Schema.optionalKey( + Schema.Union([ClientRequest__Personality, Schema.Null]).annotate({ + description: "Override the personality for this turn and subsequent turns.", + }), + ), + sandboxPolicy: Schema.optionalKey( + Schema.Union([ClientRequest__SandboxPolicy, Schema.Null]).annotate({ + description: "Override the sandbox policy for this turn and subsequent turns.", + }), + ), + serviceTier: Schema.optionalKey( + Schema.Union([Schema.Union([ClientRequest__ServiceTier, Schema.Null]), Schema.Null]).annotate({ + description: "Override the service tier for this turn and subsequent turns.", + }), + ), + summary: Schema.optionalKey( + Schema.Union([ClientRequest__ReasoningSummary, Schema.Null]).annotate({ + description: "Override the reasoning summary for this turn and subsequent turns.", + }), + ), + threadId: Schema.String, +}); + +export type ClientRequest__TurnSteerParams = { + readonly expectedTurnId: string; + readonly input: ReadonlyArray; + readonly threadId: string; +}; +export const ClientRequest__TurnSteerParams = Schema.Struct({ + expectedTurnId: Schema.String.annotate({ + description: + "Required active turn id precondition. The request fails when it does not match the currently active turn.", + }), + input: Schema.Array(ClientRequest__UserInput), + threadId: Schema.String, +}); + +export type CommandExecutionRequestApprovalResponse__CommandExecutionApprovalDecision = + | "accept" + | "acceptForSession" + | { + readonly acceptWithExecpolicyAmendment: { + readonly execpolicy_amendment: ReadonlyArray; + }; + } + | { + readonly applyNetworkPolicyAmendment: { + readonly network_policy_amendment: CommandExecutionRequestApprovalResponse__NetworkPolicyAmendment; + }; + } + | "decline" + | "cancel"; +export const CommandExecutionRequestApprovalResponse__CommandExecutionApprovalDecision = + Schema.Union( + [ + Schema.Literal("accept").annotate({ description: "User approved the command." }), + Schema.Literal("acceptForSession").annotate({ + description: + "User approved the command and future prompts in the same session-scoped approval cache should run without prompting.", + }), + Schema.Struct({ + acceptWithExecpolicyAmendment: Schema.Struct({ + execpolicy_amendment: Schema.Array(Schema.String), + }), + }).annotate({ + title: "AcceptWithExecpolicyAmendmentCommandExecutionApprovalDecision", + description: + "User approved the command, and wants to apply the proposed execpolicy amendment so future matching commands can run without prompting.", + }), + Schema.Struct({ + applyNetworkPolicyAmendment: Schema.Struct({ + network_policy_amendment: CommandExecutionRequestApprovalResponse__NetworkPolicyAmendment, + }), + }).annotate({ + title: "ApplyNetworkPolicyAmendmentCommandExecutionApprovalDecision", + description: "User chose a persistent network policy rule (allow/deny) for this host.", + }), + Schema.Literal("decline").annotate({ + description: "User denied the command. The agent will continue the turn.", + }), + Schema.Literal("cancel").annotate({ + description: "User denied the command. The turn will also be immediately interrupted.", + }), + ], + { mode: "oneOf" }, + ); + +export type ExecCommandApprovalResponse__ReviewDecision = + | "approved" + | { + readonly approved_execpolicy_amendment: { + readonly proposed_execpolicy_amendment: ReadonlyArray; + }; + } + | "approved_for_session" + | { + readonly network_policy_amendment: { + readonly network_policy_amendment: ExecCommandApprovalResponse__NetworkPolicyAmendment; + }; + } + | "denied" + | "timed_out" + | "abort"; +export const ExecCommandApprovalResponse__ReviewDecision = Schema.Union( + [ + Schema.Literal("approved").annotate({ + description: "User has approved this command and the agent should execute it.", + }), + Schema.Struct({ + approved_execpolicy_amendment: Schema.Struct({ + proposed_execpolicy_amendment: Schema.Array(Schema.String), + }), + }).annotate({ + title: "ApprovedExecpolicyAmendmentReviewDecision", + description: + "User has approved this command and wants to apply the proposed execpolicy amendment so future matching commands are permitted.", + }), + Schema.Literal("approved_for_session").annotate({ + description: + "User has approved this request and wants future prompts in the same session-scoped approval cache to be automatically approved for the remainder of the session.", + }), + Schema.Struct({ + network_policy_amendment: Schema.Struct({ + network_policy_amendment: ExecCommandApprovalResponse__NetworkPolicyAmendment, + }), + }).annotate({ + title: "NetworkPolicyAmendmentReviewDecision", + description: + "User chose to persist a network policy rule (allow/deny) for future requests to the same host.", + }), + Schema.Literal("denied").annotate({ + description: + "User has denied this command and the agent should not execute it, but it should continue the session and try something else.", + }), + Schema.Literal("timed_out").annotate({ + description: "Automatic approval review timed out before reaching a decision.", + }), + Schema.Literal("abort").annotate({ + description: + "User has denied this command and the agent should not do anything until the user's next command.", + }), + ], + { mode: "oneOf" }, +).annotate({ description: "User's decision in response to an ExecApprovalRequest." }); + +export type McpServerElicitationRequestParams__McpElicitationTitledMultiSelectEnumSchema = { + readonly default?: ReadonlyArray | null; + readonly description?: string | null; + readonly items: McpServerElicitationRequestParams__McpElicitationTitledEnumItems; + readonly maxItems?: number | null; + readonly minItems?: number | null; + readonly title?: string | null; + readonly type: McpServerElicitationRequestParams__McpElicitationArrayType; +}; +export const McpServerElicitationRequestParams__McpElicitationTitledMultiSelectEnumSchema = + Schema.Struct({ + default: Schema.optionalKey(Schema.Union([Schema.Array(Schema.String), Schema.Null])), + description: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + items: McpServerElicitationRequestParams__McpElicitationTitledEnumItems, + maxItems: Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ format: "uint64" }) + .check(Schema.isInt()) + .check(Schema.isGreaterThanOrEqualTo(0)), + Schema.Null, + ]), + ), + minItems: Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ format: "uint64" }) + .check(Schema.isInt()) + .check(Schema.isGreaterThanOrEqualTo(0)), + Schema.Null, + ]), + ), + title: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + type: McpServerElicitationRequestParams__McpElicitationArrayType, + }); + +export type McpServerElicitationRequestParams__McpElicitationUntitledMultiSelectEnumSchema = { + readonly default?: ReadonlyArray | null; + readonly description?: string | null; + readonly items: McpServerElicitationRequestParams__McpElicitationUntitledEnumItems; + readonly maxItems?: number | null; + readonly minItems?: number | null; + readonly title?: string | null; + readonly type: McpServerElicitationRequestParams__McpElicitationArrayType; +}; +export const McpServerElicitationRequestParams__McpElicitationUntitledMultiSelectEnumSchema = + Schema.Struct({ + default: Schema.optionalKey(Schema.Union([Schema.Array(Schema.String), Schema.Null])), + description: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + items: McpServerElicitationRequestParams__McpElicitationUntitledEnumItems, + maxItems: Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ format: "uint64" }) + .check(Schema.isInt()) + .check(Schema.isGreaterThanOrEqualTo(0)), + Schema.Null, + ]), + ), + minItems: Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ format: "uint64" }) + .check(Schema.isInt()) + .check(Schema.isGreaterThanOrEqualTo(0)), + Schema.Null, + ]), + ), + title: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + type: McpServerElicitationRequestParams__McpElicitationArrayType, + }); + +export type McpServerElicitationRequestParams__McpElicitationSingleSelectEnumSchema = + | McpServerElicitationRequestParams__McpElicitationUntitledSingleSelectEnumSchema + | McpServerElicitationRequestParams__McpElicitationTitledSingleSelectEnumSchema; +export const McpServerElicitationRequestParams__McpElicitationSingleSelectEnumSchema = Schema.Union( + [ + McpServerElicitationRequestParams__McpElicitationUntitledSingleSelectEnumSchema, + McpServerElicitationRequestParams__McpElicitationTitledSingleSelectEnumSchema, + ], +); + +export type PermissionsRequestApprovalParams__RequestPermissionProfile = { + readonly fileSystem?: PermissionsRequestApprovalParams__AdditionalFileSystemPermissions | null; + readonly network?: PermissionsRequestApprovalParams__AdditionalNetworkPermissions | null; +}; +export const PermissionsRequestApprovalParams__RequestPermissionProfile = Schema.Struct({ + fileSystem: Schema.optionalKey( + Schema.Union([PermissionsRequestApprovalParams__AdditionalFileSystemPermissions, Schema.Null]), + ), + network: Schema.optionalKey( + Schema.Union([PermissionsRequestApprovalParams__AdditionalNetworkPermissions, Schema.Null]), + ), +}); + +export type PermissionsRequestApprovalResponse__GrantedPermissionProfile = { + readonly fileSystem?: PermissionsRequestApprovalResponse__AdditionalFileSystemPermissions | null; + readonly network?: PermissionsRequestApprovalResponse__AdditionalNetworkPermissions | null; +}; +export const PermissionsRequestApprovalResponse__GrantedPermissionProfile = Schema.Struct({ + fileSystem: Schema.optionalKey( + Schema.Union([ + PermissionsRequestApprovalResponse__AdditionalFileSystemPermissions, + Schema.Null, + ]), + ), + network: Schema.optionalKey( + Schema.Union([PermissionsRequestApprovalResponse__AdditionalNetworkPermissions, Schema.Null]), + ), +}); + +export type ServerNotification__AppInfo = { + readonly appMetadata?: ServerNotification__AppMetadata | null; + readonly branding?: ServerNotification__AppBranding | null; + readonly description?: string | null; + readonly distributionChannel?: string | null; + readonly id: string; + readonly installUrl?: string | null; + readonly isAccessible?: boolean; + readonly isEnabled?: boolean; + readonly labels?: { readonly [x: string]: string } | null; + readonly logoUrl?: string | null; + readonly logoUrlDark?: string | null; + readonly name: string; + readonly pluginDisplayNames?: ReadonlyArray; +}; +export const ServerNotification__AppInfo = Schema.Struct({ + appMetadata: Schema.optionalKey(Schema.Union([ServerNotification__AppMetadata, Schema.Null])), + branding: Schema.optionalKey(Schema.Union([ServerNotification__AppBranding, Schema.Null])), + description: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + distributionChannel: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + id: Schema.String, + installUrl: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + isAccessible: Schema.optionalKey(Schema.Boolean.annotate({ default: false })), + isEnabled: Schema.optionalKey( + Schema.Boolean.annotate({ + description: + "Whether this app is enabled in config.toml. Example: ```toml [apps.bad_app] enabled = false ```", + default: true, + }), + ), + labels: Schema.optionalKey( + Schema.Union([Schema.Record(Schema.String, Schema.String), Schema.Null]), + ), + logoUrl: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + logoUrlDark: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + name: Schema.String, + pluginDisplayNames: Schema.optionalKey(Schema.Array(Schema.String).annotate({ default: [] })), +}).annotate({ description: "EXPERIMENTAL - app metadata returned by app-list APIs." }); + +export type ServerNotification__FuzzyFileSearchSessionUpdatedNotification = { + readonly files: ReadonlyArray; + readonly query: string; + readonly sessionId: string; +}; +export const ServerNotification__FuzzyFileSearchSessionUpdatedNotification = Schema.Struct({ + files: Schema.Array(ServerNotification__FuzzyFileSearchResult), + query: Schema.String, + sessionId: Schema.String, +}); + +export type ServerNotification__HookRunSummary = { + readonly completedAt?: number | null; + readonly displayOrder: number; + readonly durationMs?: number | null; + readonly entries: ReadonlyArray; + readonly eventName: ServerNotification__HookEventName; + readonly executionMode: ServerNotification__HookExecutionMode; + readonly handlerType: ServerNotification__HookHandlerType; + readonly id: string; + readonly scope: ServerNotification__HookScope; + readonly sourcePath: string; + readonly startedAt: number; + readonly status: ServerNotification__HookRunStatus; + readonly statusMessage?: string | null; +}; +export const ServerNotification__HookRunSummary = Schema.Struct({ + completedAt: Schema.optionalKey( + Schema.Union([Schema.Number.annotate({ format: "int64" }).check(Schema.isInt()), Schema.Null]), + ), + displayOrder: Schema.Number.annotate({ format: "int64" }).check(Schema.isInt()), + durationMs: Schema.optionalKey( + Schema.Union([Schema.Number.annotate({ format: "int64" }).check(Schema.isInt()), Schema.Null]), + ), + entries: Schema.Array(ServerNotification__HookOutputEntry), + eventName: ServerNotification__HookEventName, + executionMode: ServerNotification__HookExecutionMode, + handlerType: ServerNotification__HookHandlerType, + id: Schema.String, + scope: ServerNotification__HookScope, + sourcePath: Schema.String, + startedAt: Schema.Number.annotate({ format: "int64" }).check(Schema.isInt()), + status: ServerNotification__HookRunStatus, + statusMessage: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), +}); + +export type ServerNotification__ItemGuardianApprovalReviewCompletedNotification = { + readonly action: ServerNotification__GuardianApprovalReviewAction; + readonly decisionSource: ServerNotification__AutoReviewDecisionSource; + readonly review: ServerNotification__GuardianApprovalReview; + readonly reviewId: string; + readonly targetItemId?: string | null; + readonly threadId: string; + readonly turnId: string; +}; +export const ServerNotification__ItemGuardianApprovalReviewCompletedNotification = Schema.Struct({ + action: ServerNotification__GuardianApprovalReviewAction, + decisionSource: ServerNotification__AutoReviewDecisionSource, + review: ServerNotification__GuardianApprovalReview, + reviewId: Schema.String.annotate({ description: "Stable identifier for this review." }), + targetItemId: Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + description: + "Identifier for the reviewed item or tool call when one exists.\n\nIn most cases, one review maps to one target item. The exceptions are - execve reviews, where a single command may contain multiple execve calls to review (only possible when using the shell_zsh_fork feature) - network policy reviews, where there is no target item\n\nA network call is triggered by a CommandExecution item, so having a target_item_id set to the CommandExecution item would be misleading because the review is about the network call, not the command execution. Therefore, target_item_id is set to None for network policy reviews.", + }), + Schema.Null, + ]), + ), + threadId: Schema.String, + turnId: Schema.String, +}).annotate({ + description: + "[UNSTABLE] Temporary notification payload for guardian automatic approval review. This shape is expected to change soon.", +}); + +export type ServerNotification__ItemGuardianApprovalReviewStartedNotification = { + readonly action: ServerNotification__GuardianApprovalReviewAction; + readonly review: ServerNotification__GuardianApprovalReview; + readonly reviewId: string; + readonly targetItemId?: string | null; + readonly threadId: string; + readonly turnId: string; +}; +export const ServerNotification__ItemGuardianApprovalReviewStartedNotification = Schema.Struct({ + action: ServerNotification__GuardianApprovalReviewAction, + review: ServerNotification__GuardianApprovalReview, + reviewId: Schema.String.annotate({ description: "Stable identifier for this review." }), + targetItemId: Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + description: + "Identifier for the reviewed item or tool call when one exists.\n\nIn most cases, one review maps to one target item. The exceptions are - execve reviews, where a single command may contain multiple execve calls to review (only possible when using the shell_zsh_fork feature) - network policy reviews, where there is no target item\n\nA network call is triggered by a CommandExecution item, so having a target_item_id set to the CommandExecution item would be misleading because the review is about the network call, not the command execution. Therefore, target_item_id is set to None for network policy reviews.", + }), + Schema.Null, + ]), + ), + threadId: Schema.String, + turnId: Schema.String, +}).annotate({ + description: + "[UNSTABLE] Temporary notification payload for guardian automatic approval review. This shape is expected to change soon.", +}); + +export type ServerNotification__TurnError = { + readonly additionalDetails?: string | null; + readonly codexErrorInfo?: ServerNotification__CodexErrorInfo | null; + readonly message: string; +}; +export const ServerNotification__TurnError = Schema.Struct({ + additionalDetails: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + codexErrorInfo: Schema.optionalKey( + Schema.Union([ServerNotification__CodexErrorInfo, Schema.Null]), + ), + message: Schema.String, +}); + +export type ServerNotification__AccountRateLimitsUpdatedNotification = { + readonly rateLimits: ServerNotification__RateLimitSnapshot; +}; +export const ServerNotification__AccountRateLimitsUpdatedNotification = Schema.Struct({ + rateLimits: ServerNotification__RateLimitSnapshot, +}); + +export type ServerNotification__ThreadItem = + | { + readonly content: ReadonlyArray; + readonly id: string; + readonly type: "userMessage"; + } + | { + readonly fragments: ReadonlyArray; + readonly id: string; + readonly type: "hookPrompt"; + } + | { + readonly id: string; + readonly memoryCitation?: ServerNotification__MemoryCitation | null; + readonly phase?: ServerNotification__MessagePhase | null; + readonly text: string; + readonly type: "agentMessage"; + } + | { readonly id: string; readonly text: string; readonly type: "plan" } + | { + readonly content?: ReadonlyArray; + readonly id: string; + readonly summary?: ReadonlyArray; + readonly type: "reasoning"; + } + | { + readonly aggregatedOutput?: string | null; + readonly command: string; + readonly commandActions: ReadonlyArray; + readonly cwd: string; + readonly durationMs?: number | null; + readonly exitCode?: number | null; + readonly id: string; + readonly processId?: string | null; + readonly source?: "agent" | "userShell" | "unifiedExecStartup" | "unifiedExecInteraction"; + readonly status: ServerNotification__CommandExecutionStatus; + readonly type: "commandExecution"; + } + | { + readonly changes: ReadonlyArray; + readonly id: string; + readonly status: ServerNotification__PatchApplyStatus; + readonly type: "fileChange"; + } + | { + readonly arguments: unknown; + readonly durationMs?: number | null; + readonly error?: ServerNotification__McpToolCallError | null; + readonly id: string; + readonly result?: ServerNotification__McpToolCallResult | null; + readonly server: string; + readonly status: ServerNotification__McpToolCallStatus; + readonly tool: string; + readonly type: "mcpToolCall"; + } + | { + readonly arguments: unknown; + readonly contentItems?: ReadonlyArray | null; + readonly durationMs?: number | null; + readonly id: string; + readonly status: ServerNotification__DynamicToolCallStatus; + readonly success?: boolean | null; + readonly tool: string; + readonly type: "dynamicToolCall"; + } + | { + readonly agentsStates: { readonly [x: string]: ServerNotification__CollabAgentState }; + readonly id: string; + readonly model?: string | null; + readonly prompt?: string | null; + readonly reasoningEffort?: ServerNotification__ReasoningEffort | null; + readonly receiverThreadIds: ReadonlyArray; + readonly senderThreadId: string; + readonly status: "inProgress" | "completed" | "failed"; + readonly tool: "spawnAgent" | "sendInput" | "resumeAgent" | "wait" | "closeAgent"; + readonly type: "collabAgentToolCall"; + } + | { + readonly action?: ServerNotification__WebSearchAction | null; + readonly id: string; + readonly query: string; + readonly type: "webSearch"; + } + | { readonly id: string; readonly path: string; readonly type: "imageView" } + | { + readonly id: string; + readonly result: string; + readonly revisedPrompt?: string | null; + readonly savedPath?: string | null; + readonly status: string; + readonly type: "imageGeneration"; + } + | { readonly id: string; readonly review: string; readonly type: "enteredReviewMode" } + | { readonly id: string; readonly review: string; readonly type: "exitedReviewMode" } + | { readonly id: string; readonly type: "contextCompaction" }; +export const ServerNotification__ThreadItem = Schema.Union( + [ + Schema.Struct({ + content: Schema.Array(ServerNotification__UserInput), + id: Schema.String, + type: Schema.Literal("userMessage").annotate({ title: "UserMessageThreadItemType" }), + }).annotate({ title: "UserMessageThreadItem" }), + Schema.Struct({ + fragments: Schema.Array(ServerNotification__HookPromptFragment), + id: Schema.String, + type: Schema.Literal("hookPrompt").annotate({ title: "HookPromptThreadItemType" }), + }).annotate({ title: "HookPromptThreadItem" }), + Schema.Struct({ + id: Schema.String, + memoryCitation: Schema.optionalKey( + Schema.Union([ServerNotification__MemoryCitation, Schema.Null]), + ), + phase: Schema.optionalKey(Schema.Union([ServerNotification__MessagePhase, Schema.Null])), + text: Schema.String, + type: Schema.Literal("agentMessage").annotate({ title: "AgentMessageThreadItemType" }), + }).annotate({ title: "AgentMessageThreadItem" }), + Schema.Struct({ + id: Schema.String, + text: Schema.String, + type: Schema.Literal("plan").annotate({ title: "PlanThreadItemType" }), + }).annotate({ + title: "PlanThreadItem", + description: + "EXPERIMENTAL - proposed plan item content. The completed plan item is authoritative and may not match the concatenation of `PlanDelta` text.", + }), + Schema.Struct({ + content: Schema.optionalKey(Schema.Array(Schema.String).annotate({ default: [] })), + id: Schema.String, + summary: Schema.optionalKey(Schema.Array(Schema.String).annotate({ default: [] })), + type: Schema.Literal("reasoning").annotate({ title: "ReasoningThreadItemType" }), + }).annotate({ title: "ReasoningThreadItem" }), + Schema.Struct({ + aggregatedOutput: Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + description: "The command's output, aggregated from stdout and stderr.", + }), + Schema.Null, + ]), + ), + command: Schema.String.annotate({ description: "The command to be executed." }), + commandActions: Schema.Array(ServerNotification__CommandAction).annotate({ + description: + "A best-effort parsing of the command to understand the action(s) it will perform. This returns a list of CommandAction objects because a single shell command may be composed of many commands piped together.", + }), + cwd: Schema.String.annotate({ description: "The command's working directory." }), + durationMs: Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ + description: "The duration of the command execution in milliseconds.", + format: "int64", + }).check(Schema.isInt()), + Schema.Null, + ]), + ), + exitCode: Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ + description: "The command's exit code.", + format: "int32", + }).check(Schema.isInt()), + Schema.Null, + ]), + ), + id: Schema.String, + processId: Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + description: "Identifier for the underlying PTY process (when available).", + }), + Schema.Null, + ]), + ), + source: Schema.optionalKey( + Schema.Literals([ + "agent", + "userShell", + "unifiedExecStartup", + "unifiedExecInteraction", + ]).annotate({ default: "agent" }), + ), + status: ServerNotification__CommandExecutionStatus, + type: Schema.Literal("commandExecution").annotate({ + title: "CommandExecutionThreadItemType", + }), + }).annotate({ title: "CommandExecutionThreadItem" }), + Schema.Struct({ + changes: Schema.Array(ServerNotification__FileUpdateChange), + id: Schema.String, + status: ServerNotification__PatchApplyStatus, + type: Schema.Literal("fileChange").annotate({ title: "FileChangeThreadItemType" }), + }).annotate({ title: "FileChangeThreadItem" }), + Schema.Struct({ + arguments: Schema.Unknown, + durationMs: Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ + description: "The duration of the MCP tool call in milliseconds.", + format: "int64", + }).check(Schema.isInt()), + Schema.Null, + ]), + ), + error: Schema.optionalKey(Schema.Union([ServerNotification__McpToolCallError, Schema.Null])), + id: Schema.String, + result: Schema.optionalKey( + Schema.Union([ServerNotification__McpToolCallResult, Schema.Null]), + ), + server: Schema.String, + status: ServerNotification__McpToolCallStatus, + tool: Schema.String, + type: Schema.Literal("mcpToolCall").annotate({ title: "McpToolCallThreadItemType" }), + }).annotate({ title: "McpToolCallThreadItem" }), + Schema.Struct({ + arguments: Schema.Unknown, + contentItems: Schema.optionalKey( + Schema.Union([ + Schema.Array(ServerNotification__DynamicToolCallOutputContentItem), + Schema.Null, + ]), + ), + durationMs: Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ + description: "The duration of the dynamic tool call in milliseconds.", + format: "int64", + }).check(Schema.isInt()), + Schema.Null, + ]), + ), + id: Schema.String, + status: ServerNotification__DynamicToolCallStatus, + success: Schema.optionalKey(Schema.Union([Schema.Boolean, Schema.Null])), + tool: Schema.String, + type: Schema.Literal("dynamicToolCall").annotate({ title: "DynamicToolCallThreadItemType" }), + }).annotate({ title: "DynamicToolCallThreadItem" }), + Schema.Struct({ + agentsStates: Schema.Record(Schema.String, ServerNotification__CollabAgentState).annotate({ + description: "Last known status of the target agents, when available.", + }), + id: Schema.String.annotate({ description: "Unique identifier for this collab tool call." }), + model: Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + description: "Model requested for the spawned agent, when applicable.", + }), + Schema.Null, + ]), + ), + prompt: Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + description: "Prompt text sent as part of the collab tool call, when available.", + }), + Schema.Null, + ]), + ), + reasoningEffort: Schema.optionalKey( + Schema.Union([ServerNotification__ReasoningEffort, Schema.Null]).annotate({ + description: "Reasoning effort requested for the spawned agent, when applicable.", + }), + ), + receiverThreadIds: Schema.Array(Schema.String).annotate({ + description: + "Thread ID of the receiving agent, when applicable. In case of spawn operation, this corresponds to the newly spawned agent.", + }), + senderThreadId: Schema.String.annotate({ + description: "Thread ID of the agent issuing the collab request.", + }), + status: Schema.Literals(["inProgress", "completed", "failed"]).annotate({ + description: "Current status of the collab tool call.", + }), + tool: Schema.Literals([ + "spawnAgent", + "sendInput", + "resumeAgent", + "wait", + "closeAgent", + ]).annotate({ description: "Name of the collab tool that was invoked." }), + type: Schema.Literal("collabAgentToolCall").annotate({ + title: "CollabAgentToolCallThreadItemType", + }), + }).annotate({ title: "CollabAgentToolCallThreadItem" }), + Schema.Struct({ + action: Schema.optionalKey(Schema.Union([ServerNotification__WebSearchAction, Schema.Null])), + id: Schema.String, + query: Schema.String, + type: Schema.Literal("webSearch").annotate({ title: "WebSearchThreadItemType" }), + }).annotate({ title: "WebSearchThreadItem" }), + Schema.Struct({ + id: Schema.String, + path: Schema.String, + type: Schema.Literal("imageView").annotate({ title: "ImageViewThreadItemType" }), + }).annotate({ title: "ImageViewThreadItem" }), + Schema.Struct({ + id: Schema.String, + result: Schema.String, + revisedPrompt: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + savedPath: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + status: Schema.String, + type: Schema.Literal("imageGeneration").annotate({ title: "ImageGenerationThreadItemType" }), + }).annotate({ title: "ImageGenerationThreadItem" }), + Schema.Struct({ + id: Schema.String, + review: Schema.String, + type: Schema.Literal("enteredReviewMode").annotate({ + title: "EnteredReviewModeThreadItemType", + }), + }).annotate({ title: "EnteredReviewModeThreadItem" }), + Schema.Struct({ + id: Schema.String, + review: Schema.String, + type: Schema.Literal("exitedReviewMode").annotate({ + title: "ExitedReviewModeThreadItemType", + }), + }).annotate({ title: "ExitedReviewModeThreadItem" }), + Schema.Struct({ + id: Schema.String, + type: Schema.Literal("contextCompaction").annotate({ + title: "ContextCompactionThreadItemType", + }), + }).annotate({ title: "ContextCompactionThreadItem" }), + ], + { mode: "oneOf" }, +); + +export type ServerNotification__ConfigWarningNotification = { + readonly details?: string | null; + readonly path?: string | null; + readonly range?: ServerNotification__TextRange | null; + readonly summary: string; +}; +export const ServerNotification__ConfigWarningNotification = Schema.Struct({ + details: Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ description: "Optional extra guidance or error details." }), + Schema.Null, + ]), + ), + path: Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + description: "Optional path to the config file that triggered the warning.", + }), + Schema.Null, + ]), + ), + range: Schema.optionalKey( + Schema.Union([ServerNotification__TextRange, Schema.Null]).annotate({ + description: "Optional range for the error location inside the config file.", + }), + ), + summary: Schema.String.annotate({ description: "Concise summary of the warning." }), +}); + +export type ServerNotification__ThreadStatusChangedNotification = { + readonly status: ServerNotification__ThreadStatus; + readonly threadId: string; +}; +export const ServerNotification__ThreadStatusChangedNotification = Schema.Struct({ + status: ServerNotification__ThreadStatus, + threadId: Schema.String, +}); + +export type ServerNotification__ThreadTokenUsageUpdatedNotification = { + readonly threadId: string; + readonly tokenUsage: ServerNotification__ThreadTokenUsage; + readonly turnId: string; +}; +export const ServerNotification__ThreadTokenUsageUpdatedNotification = Schema.Struct({ + threadId: Schema.String, + tokenUsage: ServerNotification__ThreadTokenUsage, + turnId: Schema.String, +}); + +export type ServerNotification__TurnPlanUpdatedNotification = { + readonly explanation?: string | null; + readonly plan: ReadonlyArray; + readonly threadId: string; + readonly turnId: string; +}; +export const ServerNotification__TurnPlanUpdatedNotification = Schema.Struct({ + explanation: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + plan: Schema.Array(ServerNotification__TurnPlanStep), + threadId: Schema.String, + turnId: Schema.String, +}); + +export type ServerRequest__RequestPermissionProfile = { + readonly fileSystem?: ServerRequest__AdditionalFileSystemPermissions | null; + readonly network?: ServerRequest__AdditionalNetworkPermissions | null; +}; +export const ServerRequest__RequestPermissionProfile = Schema.Struct({ + fileSystem: Schema.optionalKey( + Schema.Union([ServerRequest__AdditionalFileSystemPermissions, Schema.Null]), + ), + network: Schema.optionalKey( + Schema.Union([ServerRequest__AdditionalNetworkPermissions, Schema.Null]), + ), +}); + +export type ServerRequest__McpElicitationTitledMultiSelectEnumSchema = { + readonly default?: ReadonlyArray | null; + readonly description?: string | null; + readonly items: ServerRequest__McpElicitationTitledEnumItems; + readonly maxItems?: number | null; + readonly minItems?: number | null; + readonly title?: string | null; + readonly type: ServerRequest__McpElicitationArrayType; +}; +export const ServerRequest__McpElicitationTitledMultiSelectEnumSchema = Schema.Struct({ + default: Schema.optionalKey(Schema.Union([Schema.Array(Schema.String), Schema.Null])), + description: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + items: ServerRequest__McpElicitationTitledEnumItems, + maxItems: Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ format: "uint64" }) + .check(Schema.isInt()) + .check(Schema.isGreaterThanOrEqualTo(0)), + Schema.Null, + ]), + ), + minItems: Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ format: "uint64" }) + .check(Schema.isInt()) + .check(Schema.isGreaterThanOrEqualTo(0)), + Schema.Null, + ]), + ), + title: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + type: ServerRequest__McpElicitationArrayType, +}); + +export type ServerRequest__McpElicitationUntitledMultiSelectEnumSchema = { + readonly default?: ReadonlyArray | null; + readonly description?: string | null; + readonly items: ServerRequest__McpElicitationUntitledEnumItems; + readonly maxItems?: number | null; + readonly minItems?: number | null; + readonly title?: string | null; + readonly type: ServerRequest__McpElicitationArrayType; +}; +export const ServerRequest__McpElicitationUntitledMultiSelectEnumSchema = Schema.Struct({ + default: Schema.optionalKey(Schema.Union([Schema.Array(Schema.String), Schema.Null])), + description: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + items: ServerRequest__McpElicitationUntitledEnumItems, + maxItems: Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ format: "uint64" }) + .check(Schema.isInt()) + .check(Schema.isGreaterThanOrEqualTo(0)), + Schema.Null, + ]), + ), + minItems: Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ format: "uint64" }) + .check(Schema.isInt()) + .check(Schema.isGreaterThanOrEqualTo(0)), + Schema.Null, + ]), + ), + title: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + type: ServerRequest__McpElicitationArrayType, +}); + +export type ServerRequest__McpElicitationSingleSelectEnumSchema = + | ServerRequest__McpElicitationUntitledSingleSelectEnumSchema + | ServerRequest__McpElicitationTitledSingleSelectEnumSchema; +export const ServerRequest__McpElicitationSingleSelectEnumSchema = Schema.Union([ + ServerRequest__McpElicitationUntitledSingleSelectEnumSchema, + ServerRequest__McpElicitationTitledSingleSelectEnumSchema, +]); + +export type ServerRequest__CommandExecutionRequestApprovalParams = { + readonly approvalId?: string | null; + readonly command?: string | null; + readonly commandActions?: ReadonlyArray | null; + readonly cwd?: string | null; + readonly itemId: string; + readonly networkApprovalContext?: ServerRequest__NetworkApprovalContext | null; + readonly proposedExecpolicyAmendment?: ReadonlyArray | null; + readonly proposedNetworkPolicyAmendments?: ReadonlyArray | null; + readonly reason?: string | null; + readonly threadId: string; + readonly turnId: string; +}; +export const ServerRequest__CommandExecutionRequestApprovalParams = Schema.Struct({ + approvalId: Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + description: + "Unique identifier for this specific approval callback.\n\nFor regular shell/unified_exec approvals, this is null.\n\nFor zsh-exec-bridge subcommand approvals, multiple callbacks can belong to one parent `itemId`, so `approvalId` is a distinct opaque callback id (a UUID) used to disambiguate routing.", + }), + Schema.Null, + ]), + ), + command: Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ description: "The command to be executed." }), + Schema.Null, + ]), + ), + commandActions: Schema.optionalKey( + Schema.Union([ + Schema.Array(ServerRequest__CommandAction).annotate({ + description: "Best-effort parsed command actions for friendly display.", + }), + Schema.Null, + ]), + ), + cwd: Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ description: "The command's working directory." }), + Schema.Null, + ]), + ), + itemId: Schema.String, + networkApprovalContext: Schema.optionalKey( + Schema.Union([ServerRequest__NetworkApprovalContext, Schema.Null]).annotate({ + description: "Optional context for a managed-network approval prompt.", + }), + ), + proposedExecpolicyAmendment: Schema.optionalKey( + Schema.Union([ + Schema.Array(Schema.String).annotate({ + description: + "Optional proposed execpolicy amendment to allow similar commands without prompting.", + }), + Schema.Null, + ]), + ), + proposedNetworkPolicyAmendments: Schema.optionalKey( + Schema.Union([ + Schema.Array(ServerRequest__NetworkPolicyAmendment).annotate({ + description: + "Optional proposed network policy amendments (allow/deny host) for future requests.", + }), + Schema.Null, + ]), + ), + reason: Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + description: "Optional explanatory reason (e.g. request for network access).", + }), + Schema.Null, + ]), + ), + threadId: Schema.String, + turnId: Schema.String, +}); + +export type ServerRequest__ToolRequestUserInputParams = { + readonly itemId: string; + readonly questions: ReadonlyArray; + readonly threadId: string; + readonly turnId: string; +}; +export const ServerRequest__ToolRequestUserInputParams = Schema.Struct({ + itemId: Schema.String, + questions: Schema.Array(ServerRequest__ToolRequestUserInputQuestion), + threadId: Schema.String, + turnId: Schema.String, +}).annotate({ description: "EXPERIMENTAL. Params sent with a request_user_input event." }); + +export type V2AppListUpdatedNotification__AppInfo = { + readonly appMetadata?: V2AppListUpdatedNotification__AppMetadata | null; + readonly branding?: V2AppListUpdatedNotification__AppBranding | null; + readonly description?: string | null; + readonly distributionChannel?: string | null; + readonly id: string; + readonly installUrl?: string | null; + readonly isAccessible?: boolean; + readonly isEnabled?: boolean; + readonly labels?: { readonly [x: string]: string } | null; + readonly logoUrl?: string | null; + readonly logoUrlDark?: string | null; + readonly name: string; + readonly pluginDisplayNames?: ReadonlyArray; +}; +export const V2AppListUpdatedNotification__AppInfo = Schema.Struct({ + appMetadata: Schema.optionalKey( + Schema.Union([V2AppListUpdatedNotification__AppMetadata, Schema.Null]), + ), + branding: Schema.optionalKey( + Schema.Union([V2AppListUpdatedNotification__AppBranding, Schema.Null]), + ), + description: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + distributionChannel: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + id: Schema.String, + installUrl: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + isAccessible: Schema.optionalKey(Schema.Boolean.annotate({ default: false })), + isEnabled: Schema.optionalKey( + Schema.Boolean.annotate({ + description: + "Whether this app is enabled in config.toml. Example: ```toml [apps.bad_app] enabled = false ```", + default: true, + }), + ), + labels: Schema.optionalKey( + Schema.Union([Schema.Record(Schema.String, Schema.String), Schema.Null]), + ), + logoUrl: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + logoUrlDark: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + name: Schema.String, + pluginDisplayNames: Schema.optionalKey(Schema.Array(Schema.String).annotate({ default: [] })), +}).annotate({ description: "EXPERIMENTAL - app metadata returned by app-list APIs." }); + +export type V2AppsListResponse__AppInfo = { + readonly appMetadata?: V2AppsListResponse__AppMetadata | null; + readonly branding?: V2AppsListResponse__AppBranding | null; + readonly description?: string | null; + readonly distributionChannel?: string | null; + readonly id: string; + readonly installUrl?: string | null; + readonly isAccessible?: boolean; + readonly isEnabled?: boolean; + readonly labels?: { readonly [x: string]: string } | null; + readonly logoUrl?: string | null; + readonly logoUrlDark?: string | null; + readonly name: string; + readonly pluginDisplayNames?: ReadonlyArray; +}; +export const V2AppsListResponse__AppInfo = Schema.Struct({ + appMetadata: Schema.optionalKey(Schema.Union([V2AppsListResponse__AppMetadata, Schema.Null])), + branding: Schema.optionalKey(Schema.Union([V2AppsListResponse__AppBranding, Schema.Null])), + description: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + distributionChannel: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + id: Schema.String, + installUrl: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + isAccessible: Schema.optionalKey(Schema.Boolean.annotate({ default: false })), + isEnabled: Schema.optionalKey( + Schema.Boolean.annotate({ + description: + "Whether this app is enabled in config.toml. Example: ```toml [apps.bad_app] enabled = false ```", + default: true, + }), + ), + labels: Schema.optionalKey( + Schema.Union([Schema.Record(Schema.String, Schema.String), Schema.Null]), + ), + logoUrl: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + logoUrlDark: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + name: Schema.String, + pluginDisplayNames: Schema.optionalKey(Schema.Array(Schema.String).annotate({ default: [] })), +}).annotate({ description: "EXPERIMENTAL - app metadata returned by app-list APIs." }); + +export type V2ConfigReadResponse__ConfigLayer = { + readonly config: unknown; + readonly disabledReason?: string | null; + readonly name: V2ConfigReadResponse__ConfigLayerSource; + readonly version: string; +}; +export const V2ConfigReadResponse__ConfigLayer = Schema.Struct({ + config: Schema.Unknown, + disabledReason: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + name: V2ConfigReadResponse__ConfigLayerSource, + version: Schema.String, +}); + +export type V2ConfigReadResponse__ConfigLayerMetadata = { + readonly name: V2ConfigReadResponse__ConfigLayerSource; + readonly version: string; +}; +export const V2ConfigReadResponse__ConfigLayerMetadata = Schema.Struct({ + name: V2ConfigReadResponse__ConfigLayerSource, + version: Schema.String, +}); + +export type V2ConfigReadResponse__ToolsV2 = { + readonly view_image?: boolean | null; + readonly web_search?: V2ConfigReadResponse__WebSearchToolConfig | null; +}; +export const V2ConfigReadResponse__ToolsV2 = Schema.Struct({ + view_image: Schema.optionalKey(Schema.Union([Schema.Boolean, Schema.Null])), + web_search: Schema.optionalKey( + Schema.Union([V2ConfigReadResponse__WebSearchToolConfig, Schema.Null]), + ), +}); + +export type V2ConfigWriteResponse__ConfigLayerMetadata = { + readonly name: V2ConfigWriteResponse__ConfigLayerSource; + readonly version: string; +}; +export const V2ConfigWriteResponse__ConfigLayerMetadata = Schema.Struct({ + name: V2ConfigWriteResponse__ConfigLayerSource, + version: Schema.String, +}); + +export type V2ErrorNotification__TurnError = { + readonly additionalDetails?: string | null; + readonly codexErrorInfo?: V2ErrorNotification__CodexErrorInfo | null; + readonly message: string; +}; +export const V2ErrorNotification__TurnError = Schema.Struct({ + additionalDetails: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + codexErrorInfo: Schema.optionalKey( + Schema.Union([V2ErrorNotification__CodexErrorInfo, Schema.Null]), + ), + message: Schema.String, +}); + +export type V2HookCompletedNotification__HookRunSummary = { + readonly completedAt?: number | null; + readonly displayOrder: number; + readonly durationMs?: number | null; + readonly entries: ReadonlyArray; + readonly eventName: V2HookCompletedNotification__HookEventName; + readonly executionMode: V2HookCompletedNotification__HookExecutionMode; + readonly handlerType: V2HookCompletedNotification__HookHandlerType; + readonly id: string; + readonly scope: V2HookCompletedNotification__HookScope; + readonly sourcePath: string; + readonly startedAt: number; + readonly status: V2HookCompletedNotification__HookRunStatus; + readonly statusMessage?: string | null; +}; +export const V2HookCompletedNotification__HookRunSummary = Schema.Struct({ + completedAt: Schema.optionalKey( + Schema.Union([Schema.Number.annotate({ format: "int64" }).check(Schema.isInt()), Schema.Null]), + ), + displayOrder: Schema.Number.annotate({ format: "int64" }).check(Schema.isInt()), + durationMs: Schema.optionalKey( + Schema.Union([Schema.Number.annotate({ format: "int64" }).check(Schema.isInt()), Schema.Null]), + ), + entries: Schema.Array(V2HookCompletedNotification__HookOutputEntry), + eventName: V2HookCompletedNotification__HookEventName, + executionMode: V2HookCompletedNotification__HookExecutionMode, + handlerType: V2HookCompletedNotification__HookHandlerType, + id: Schema.String, + scope: V2HookCompletedNotification__HookScope, + sourcePath: Schema.String, + startedAt: Schema.Number.annotate({ format: "int64" }).check(Schema.isInt()), + status: V2HookCompletedNotification__HookRunStatus, + statusMessage: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), +}); + +export type V2HookStartedNotification__HookRunSummary = { + readonly completedAt?: number | null; + readonly displayOrder: number; + readonly durationMs?: number | null; + readonly entries: ReadonlyArray; + readonly eventName: V2HookStartedNotification__HookEventName; + readonly executionMode: V2HookStartedNotification__HookExecutionMode; + readonly handlerType: V2HookStartedNotification__HookHandlerType; + readonly id: string; + readonly scope: V2HookStartedNotification__HookScope; + readonly sourcePath: string; + readonly startedAt: number; + readonly status: V2HookStartedNotification__HookRunStatus; + readonly statusMessage?: string | null; +}; +export const V2HookStartedNotification__HookRunSummary = Schema.Struct({ + completedAt: Schema.optionalKey( + Schema.Union([Schema.Number.annotate({ format: "int64" }).check(Schema.isInt()), Schema.Null]), + ), + displayOrder: Schema.Number.annotate({ format: "int64" }).check(Schema.isInt()), + durationMs: Schema.optionalKey( + Schema.Union([Schema.Number.annotate({ format: "int64" }).check(Schema.isInt()), Schema.Null]), + ), + entries: Schema.Array(V2HookStartedNotification__HookOutputEntry), + eventName: V2HookStartedNotification__HookEventName, + executionMode: V2HookStartedNotification__HookExecutionMode, + handlerType: V2HookStartedNotification__HookHandlerType, + id: Schema.String, + scope: V2HookStartedNotification__HookScope, + sourcePath: Schema.String, + startedAt: Schema.Number.annotate({ format: "int64" }).check(Schema.isInt()), + status: V2HookStartedNotification__HookRunStatus, + statusMessage: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), +}); + +export type V2ItemCompletedNotification__ThreadItem = + | { + readonly content: ReadonlyArray; + readonly id: string; + readonly type: "userMessage"; + } + | { + readonly fragments: ReadonlyArray; + readonly id: string; + readonly type: "hookPrompt"; + } + | { + readonly id: string; + readonly memoryCitation?: V2ItemCompletedNotification__MemoryCitation | null; + readonly phase?: V2ItemCompletedNotification__MessagePhase | null; + readonly text: string; + readonly type: "agentMessage"; + } + | { readonly id: string; readonly text: string; readonly type: "plan" } + | { + readonly content?: ReadonlyArray; + readonly id: string; + readonly summary?: ReadonlyArray; + readonly type: "reasoning"; + } + | { + readonly aggregatedOutput?: string | null; + readonly command: string; + readonly commandActions: ReadonlyArray; + readonly cwd: string; + readonly durationMs?: number | null; + readonly exitCode?: number | null; + readonly id: string; + readonly processId?: string | null; + readonly source?: "agent" | "userShell" | "unifiedExecStartup" | "unifiedExecInteraction"; + readonly status: V2ItemCompletedNotification__CommandExecutionStatus; + readonly type: "commandExecution"; + } + | { + readonly changes: ReadonlyArray; + readonly id: string; + readonly status: V2ItemCompletedNotification__PatchApplyStatus; + readonly type: "fileChange"; + } + | { + readonly arguments: unknown; + readonly durationMs?: number | null; + readonly error?: V2ItemCompletedNotification__McpToolCallError | null; + readonly id: string; + readonly result?: V2ItemCompletedNotification__McpToolCallResult | null; + readonly server: string; + readonly status: V2ItemCompletedNotification__McpToolCallStatus; + readonly tool: string; + readonly type: "mcpToolCall"; + } + | { + readonly arguments: unknown; + readonly contentItems?: ReadonlyArray | null; + readonly durationMs?: number | null; + readonly id: string; + readonly status: V2ItemCompletedNotification__DynamicToolCallStatus; + readonly success?: boolean | null; + readonly tool: string; + readonly type: "dynamicToolCall"; + } + | { + readonly agentsStates: { + readonly [x: string]: V2ItemCompletedNotification__CollabAgentState; + }; + readonly id: string; + readonly model?: string | null; + readonly prompt?: string | null; + readonly reasoningEffort?: V2ItemCompletedNotification__ReasoningEffort | null; + readonly receiverThreadIds: ReadonlyArray; + readonly senderThreadId: string; + readonly status: "inProgress" | "completed" | "failed"; + readonly tool: "spawnAgent" | "sendInput" | "resumeAgent" | "wait" | "closeAgent"; + readonly type: "collabAgentToolCall"; + } + | { + readonly action?: V2ItemCompletedNotification__WebSearchAction | null; + readonly id: string; + readonly query: string; + readonly type: "webSearch"; + } + | { readonly id: string; readonly path: string; readonly type: "imageView" } + | { + readonly id: string; + readonly result: string; + readonly revisedPrompt?: string | null; + readonly savedPath?: string | null; + readonly status: string; + readonly type: "imageGeneration"; + } + | { readonly id: string; readonly review: string; readonly type: "enteredReviewMode" } + | { readonly id: string; readonly review: string; readonly type: "exitedReviewMode" } + | { readonly id: string; readonly type: "contextCompaction" }; +export const V2ItemCompletedNotification__ThreadItem = Schema.Union( + [ + Schema.Struct({ + content: Schema.Array(V2ItemCompletedNotification__UserInput), + id: Schema.String, + type: Schema.Literal("userMessage").annotate({ title: "UserMessageThreadItemType" }), + }).annotate({ title: "UserMessageThreadItem" }), + Schema.Struct({ + fragments: Schema.Array(V2ItemCompletedNotification__HookPromptFragment), + id: Schema.String, + type: Schema.Literal("hookPrompt").annotate({ title: "HookPromptThreadItemType" }), + }).annotate({ title: "HookPromptThreadItem" }), + Schema.Struct({ + id: Schema.String, + memoryCitation: Schema.optionalKey( + Schema.Union([V2ItemCompletedNotification__MemoryCitation, Schema.Null]), + ), + phase: Schema.optionalKey( + Schema.Union([V2ItemCompletedNotification__MessagePhase, Schema.Null]), + ), + text: Schema.String, + type: Schema.Literal("agentMessage").annotate({ title: "AgentMessageThreadItemType" }), + }).annotate({ title: "AgentMessageThreadItem" }), + Schema.Struct({ + id: Schema.String, + text: Schema.String, + type: Schema.Literal("plan").annotate({ title: "PlanThreadItemType" }), + }).annotate({ + title: "PlanThreadItem", + description: + "EXPERIMENTAL - proposed plan item content. The completed plan item is authoritative and may not match the concatenation of `PlanDelta` text.", + }), + Schema.Struct({ + content: Schema.optionalKey(Schema.Array(Schema.String).annotate({ default: [] })), + id: Schema.String, + summary: Schema.optionalKey(Schema.Array(Schema.String).annotate({ default: [] })), + type: Schema.Literal("reasoning").annotate({ title: "ReasoningThreadItemType" }), + }).annotate({ title: "ReasoningThreadItem" }), + Schema.Struct({ + aggregatedOutput: Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + description: "The command's output, aggregated from stdout and stderr.", + }), + Schema.Null, + ]), + ), + command: Schema.String.annotate({ description: "The command to be executed." }), + commandActions: Schema.Array(V2ItemCompletedNotification__CommandAction).annotate({ + description: + "A best-effort parsing of the command to understand the action(s) it will perform. This returns a list of CommandAction objects because a single shell command may be composed of many commands piped together.", + }), + cwd: Schema.String.annotate({ description: "The command's working directory." }), + durationMs: Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ + description: "The duration of the command execution in milliseconds.", + format: "int64", + }).check(Schema.isInt()), + Schema.Null, + ]), + ), + exitCode: Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ + description: "The command's exit code.", + format: "int32", + }).check(Schema.isInt()), + Schema.Null, + ]), + ), + id: Schema.String, + processId: Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + description: "Identifier for the underlying PTY process (when available).", + }), + Schema.Null, + ]), + ), + source: Schema.optionalKey( + Schema.Literals([ + "agent", + "userShell", + "unifiedExecStartup", + "unifiedExecInteraction", + ]).annotate({ default: "agent" }), + ), + status: V2ItemCompletedNotification__CommandExecutionStatus, + type: Schema.Literal("commandExecution").annotate({ + title: "CommandExecutionThreadItemType", + }), + }).annotate({ title: "CommandExecutionThreadItem" }), + Schema.Struct({ + changes: Schema.Array(V2ItemCompletedNotification__FileUpdateChange), + id: Schema.String, + status: V2ItemCompletedNotification__PatchApplyStatus, + type: Schema.Literal("fileChange").annotate({ title: "FileChangeThreadItemType" }), + }).annotate({ title: "FileChangeThreadItem" }), + Schema.Struct({ + arguments: Schema.Unknown, + durationMs: Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ + description: "The duration of the MCP tool call in milliseconds.", + format: "int64", + }).check(Schema.isInt()), + Schema.Null, + ]), + ), + error: Schema.optionalKey( + Schema.Union([V2ItemCompletedNotification__McpToolCallError, Schema.Null]), + ), + id: Schema.String, + result: Schema.optionalKey( + Schema.Union([V2ItemCompletedNotification__McpToolCallResult, Schema.Null]), + ), + server: Schema.String, + status: V2ItemCompletedNotification__McpToolCallStatus, + tool: Schema.String, + type: Schema.Literal("mcpToolCall").annotate({ title: "McpToolCallThreadItemType" }), + }).annotate({ title: "McpToolCallThreadItem" }), + Schema.Struct({ + arguments: Schema.Unknown, + contentItems: Schema.optionalKey( + Schema.Union([ + Schema.Array(V2ItemCompletedNotification__DynamicToolCallOutputContentItem), + Schema.Null, + ]), + ), + durationMs: Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ + description: "The duration of the dynamic tool call in milliseconds.", + format: "int64", + }).check(Schema.isInt()), + Schema.Null, + ]), + ), + id: Schema.String, + status: V2ItemCompletedNotification__DynamicToolCallStatus, + success: Schema.optionalKey(Schema.Union([Schema.Boolean, Schema.Null])), + tool: Schema.String, + type: Schema.Literal("dynamicToolCall").annotate({ title: "DynamicToolCallThreadItemType" }), + }).annotate({ title: "DynamicToolCallThreadItem" }), + Schema.Struct({ + agentsStates: Schema.Record( + Schema.String, + V2ItemCompletedNotification__CollabAgentState, + ).annotate({ description: "Last known status of the target agents, when available." }), + id: Schema.String.annotate({ description: "Unique identifier for this collab tool call." }), + model: Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + description: "Model requested for the spawned agent, when applicable.", + }), + Schema.Null, + ]), + ), + prompt: Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + description: "Prompt text sent as part of the collab tool call, when available.", + }), + Schema.Null, + ]), + ), + reasoningEffort: Schema.optionalKey( + Schema.Union([V2ItemCompletedNotification__ReasoningEffort, Schema.Null]).annotate({ + description: "Reasoning effort requested for the spawned agent, when applicable.", + }), + ), + receiverThreadIds: Schema.Array(Schema.String).annotate({ + description: + "Thread ID of the receiving agent, when applicable. In case of spawn operation, this corresponds to the newly spawned agent.", + }), + senderThreadId: Schema.String.annotate({ + description: "Thread ID of the agent issuing the collab request.", + }), + status: Schema.Literals(["inProgress", "completed", "failed"]).annotate({ + description: "Current status of the collab tool call.", + }), + tool: Schema.Literals([ + "spawnAgent", + "sendInput", + "resumeAgent", + "wait", + "closeAgent", + ]).annotate({ description: "Name of the collab tool that was invoked." }), + type: Schema.Literal("collabAgentToolCall").annotate({ + title: "CollabAgentToolCallThreadItemType", + }), + }).annotate({ title: "CollabAgentToolCallThreadItem" }), + Schema.Struct({ + action: Schema.optionalKey( + Schema.Union([V2ItemCompletedNotification__WebSearchAction, Schema.Null]), + ), + id: Schema.String, + query: Schema.String, + type: Schema.Literal("webSearch").annotate({ title: "WebSearchThreadItemType" }), + }).annotate({ title: "WebSearchThreadItem" }), + Schema.Struct({ + id: Schema.String, + path: Schema.String, + type: Schema.Literal("imageView").annotate({ title: "ImageViewThreadItemType" }), + }).annotate({ title: "ImageViewThreadItem" }), + Schema.Struct({ + id: Schema.String, + result: Schema.String, + revisedPrompt: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + savedPath: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + status: Schema.String, + type: Schema.Literal("imageGeneration").annotate({ title: "ImageGenerationThreadItemType" }), + }).annotate({ title: "ImageGenerationThreadItem" }), + Schema.Struct({ + id: Schema.String, + review: Schema.String, + type: Schema.Literal("enteredReviewMode").annotate({ + title: "EnteredReviewModeThreadItemType", + }), + }).annotate({ title: "EnteredReviewModeThreadItem" }), + Schema.Struct({ + id: Schema.String, + review: Schema.String, + type: Schema.Literal("exitedReviewMode").annotate({ + title: "ExitedReviewModeThreadItemType", + }), + }).annotate({ title: "ExitedReviewModeThreadItem" }), + Schema.Struct({ + id: Schema.String, + type: Schema.Literal("contextCompaction").annotate({ + title: "ContextCompactionThreadItemType", + }), + }).annotate({ title: "ContextCompactionThreadItem" }), + ], + { mode: "oneOf" }, +); + +export type V2ItemStartedNotification__ThreadItem = + | { + readonly content: ReadonlyArray; + readonly id: string; + readonly type: "userMessage"; + } + | { + readonly fragments: ReadonlyArray; + readonly id: string; + readonly type: "hookPrompt"; + } + | { + readonly id: string; + readonly memoryCitation?: V2ItemStartedNotification__MemoryCitation | null; + readonly phase?: V2ItemStartedNotification__MessagePhase | null; + readonly text: string; + readonly type: "agentMessage"; + } + | { readonly id: string; readonly text: string; readonly type: "plan" } + | { + readonly content?: ReadonlyArray; + readonly id: string; + readonly summary?: ReadonlyArray; + readonly type: "reasoning"; + } + | { + readonly aggregatedOutput?: string | null; + readonly command: string; + readonly commandActions: ReadonlyArray; + readonly cwd: string; + readonly durationMs?: number | null; + readonly exitCode?: number | null; + readonly id: string; + readonly processId?: string | null; + readonly source?: "agent" | "userShell" | "unifiedExecStartup" | "unifiedExecInteraction"; + readonly status: V2ItemStartedNotification__CommandExecutionStatus; + readonly type: "commandExecution"; + } + | { + readonly changes: ReadonlyArray; + readonly id: string; + readonly status: V2ItemStartedNotification__PatchApplyStatus; + readonly type: "fileChange"; + } + | { + readonly arguments: unknown; + readonly durationMs?: number | null; + readonly error?: V2ItemStartedNotification__McpToolCallError | null; + readonly id: string; + readonly result?: V2ItemStartedNotification__McpToolCallResult | null; + readonly server: string; + readonly status: V2ItemStartedNotification__McpToolCallStatus; + readonly tool: string; + readonly type: "mcpToolCall"; + } + | { + readonly arguments: unknown; + readonly contentItems?: ReadonlyArray | null; + readonly durationMs?: number | null; + readonly id: string; + readonly status: V2ItemStartedNotification__DynamicToolCallStatus; + readonly success?: boolean | null; + readonly tool: string; + readonly type: "dynamicToolCall"; + } + | { + readonly agentsStates: { readonly [x: string]: V2ItemStartedNotification__CollabAgentState }; + readonly id: string; + readonly model?: string | null; + readonly prompt?: string | null; + readonly reasoningEffort?: V2ItemStartedNotification__ReasoningEffort | null; + readonly receiverThreadIds: ReadonlyArray; + readonly senderThreadId: string; + readonly status: "inProgress" | "completed" | "failed"; + readonly tool: "spawnAgent" | "sendInput" | "resumeAgent" | "wait" | "closeAgent"; + readonly type: "collabAgentToolCall"; + } + | { + readonly action?: V2ItemStartedNotification__WebSearchAction | null; + readonly id: string; + readonly query: string; + readonly type: "webSearch"; + } + | { readonly id: string; readonly path: string; readonly type: "imageView" } + | { + readonly id: string; + readonly result: string; + readonly revisedPrompt?: string | null; + readonly savedPath?: string | null; + readonly status: string; + readonly type: "imageGeneration"; + } + | { readonly id: string; readonly review: string; readonly type: "enteredReviewMode" } + | { readonly id: string; readonly review: string; readonly type: "exitedReviewMode" } + | { readonly id: string; readonly type: "contextCompaction" }; +export const V2ItemStartedNotification__ThreadItem = Schema.Union( + [ + Schema.Struct({ + content: Schema.Array(V2ItemStartedNotification__UserInput), + id: Schema.String, + type: Schema.Literal("userMessage").annotate({ title: "UserMessageThreadItemType" }), + }).annotate({ title: "UserMessageThreadItem" }), + Schema.Struct({ + fragments: Schema.Array(V2ItemStartedNotification__HookPromptFragment), + id: Schema.String, + type: Schema.Literal("hookPrompt").annotate({ title: "HookPromptThreadItemType" }), + }).annotate({ title: "HookPromptThreadItem" }), + Schema.Struct({ + id: Schema.String, + memoryCitation: Schema.optionalKey( + Schema.Union([V2ItemStartedNotification__MemoryCitation, Schema.Null]), + ), + phase: Schema.optionalKey( + Schema.Union([V2ItemStartedNotification__MessagePhase, Schema.Null]), + ), + text: Schema.String, + type: Schema.Literal("agentMessage").annotate({ title: "AgentMessageThreadItemType" }), + }).annotate({ title: "AgentMessageThreadItem" }), + Schema.Struct({ + id: Schema.String, + text: Schema.String, + type: Schema.Literal("plan").annotate({ title: "PlanThreadItemType" }), + }).annotate({ + title: "PlanThreadItem", + description: + "EXPERIMENTAL - proposed plan item content. The completed plan item is authoritative and may not match the concatenation of `PlanDelta` text.", + }), + Schema.Struct({ + content: Schema.optionalKey(Schema.Array(Schema.String).annotate({ default: [] })), + id: Schema.String, + summary: Schema.optionalKey(Schema.Array(Schema.String).annotate({ default: [] })), + type: Schema.Literal("reasoning").annotate({ title: "ReasoningThreadItemType" }), + }).annotate({ title: "ReasoningThreadItem" }), + Schema.Struct({ + aggregatedOutput: Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + description: "The command's output, aggregated from stdout and stderr.", + }), + Schema.Null, + ]), + ), + command: Schema.String.annotate({ description: "The command to be executed." }), + commandActions: Schema.Array(V2ItemStartedNotification__CommandAction).annotate({ + description: + "A best-effort parsing of the command to understand the action(s) it will perform. This returns a list of CommandAction objects because a single shell command may be composed of many commands piped together.", + }), + cwd: Schema.String.annotate({ description: "The command's working directory." }), + durationMs: Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ + description: "The duration of the command execution in milliseconds.", + format: "int64", + }).check(Schema.isInt()), + Schema.Null, + ]), + ), + exitCode: Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ + description: "The command's exit code.", + format: "int32", + }).check(Schema.isInt()), + Schema.Null, + ]), + ), + id: Schema.String, + processId: Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + description: "Identifier for the underlying PTY process (when available).", + }), + Schema.Null, + ]), + ), + source: Schema.optionalKey( + Schema.Literals([ + "agent", + "userShell", + "unifiedExecStartup", + "unifiedExecInteraction", + ]).annotate({ default: "agent" }), + ), + status: V2ItemStartedNotification__CommandExecutionStatus, + type: Schema.Literal("commandExecution").annotate({ + title: "CommandExecutionThreadItemType", + }), + }).annotate({ title: "CommandExecutionThreadItem" }), + Schema.Struct({ + changes: Schema.Array(V2ItemStartedNotification__FileUpdateChange), + id: Schema.String, + status: V2ItemStartedNotification__PatchApplyStatus, + type: Schema.Literal("fileChange").annotate({ title: "FileChangeThreadItemType" }), + }).annotate({ title: "FileChangeThreadItem" }), + Schema.Struct({ + arguments: Schema.Unknown, + durationMs: Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ + description: "The duration of the MCP tool call in milliseconds.", + format: "int64", + }).check(Schema.isInt()), + Schema.Null, + ]), + ), + error: Schema.optionalKey( + Schema.Union([V2ItemStartedNotification__McpToolCallError, Schema.Null]), + ), + id: Schema.String, + result: Schema.optionalKey( + Schema.Union([V2ItemStartedNotification__McpToolCallResult, Schema.Null]), + ), + server: Schema.String, + status: V2ItemStartedNotification__McpToolCallStatus, + tool: Schema.String, + type: Schema.Literal("mcpToolCall").annotate({ title: "McpToolCallThreadItemType" }), + }).annotate({ title: "McpToolCallThreadItem" }), + Schema.Struct({ + arguments: Schema.Unknown, + contentItems: Schema.optionalKey( + Schema.Union([ + Schema.Array(V2ItemStartedNotification__DynamicToolCallOutputContentItem), + Schema.Null, + ]), + ), + durationMs: Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ + description: "The duration of the dynamic tool call in milliseconds.", + format: "int64", + }).check(Schema.isInt()), + Schema.Null, + ]), + ), + id: Schema.String, + status: V2ItemStartedNotification__DynamicToolCallStatus, + success: Schema.optionalKey(Schema.Union([Schema.Boolean, Schema.Null])), + tool: Schema.String, + type: Schema.Literal("dynamicToolCall").annotate({ title: "DynamicToolCallThreadItemType" }), + }).annotate({ title: "DynamicToolCallThreadItem" }), + Schema.Struct({ + agentsStates: Schema.Record( + Schema.String, + V2ItemStartedNotification__CollabAgentState, + ).annotate({ description: "Last known status of the target agents, when available." }), + id: Schema.String.annotate({ description: "Unique identifier for this collab tool call." }), + model: Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + description: "Model requested for the spawned agent, when applicable.", + }), + Schema.Null, + ]), + ), + prompt: Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + description: "Prompt text sent as part of the collab tool call, when available.", + }), + Schema.Null, + ]), + ), + reasoningEffort: Schema.optionalKey( + Schema.Union([V2ItemStartedNotification__ReasoningEffort, Schema.Null]).annotate({ + description: "Reasoning effort requested for the spawned agent, when applicable.", + }), + ), + receiverThreadIds: Schema.Array(Schema.String).annotate({ + description: + "Thread ID of the receiving agent, when applicable. In case of spawn operation, this corresponds to the newly spawned agent.", + }), + senderThreadId: Schema.String.annotate({ + description: "Thread ID of the agent issuing the collab request.", + }), + status: Schema.Literals(["inProgress", "completed", "failed"]).annotate({ + description: "Current status of the collab tool call.", + }), + tool: Schema.Literals([ + "spawnAgent", + "sendInput", + "resumeAgent", + "wait", + "closeAgent", + ]).annotate({ description: "Name of the collab tool that was invoked." }), + type: Schema.Literal("collabAgentToolCall").annotate({ + title: "CollabAgentToolCallThreadItemType", + }), + }).annotate({ title: "CollabAgentToolCallThreadItem" }), + Schema.Struct({ + action: Schema.optionalKey( + Schema.Union([V2ItemStartedNotification__WebSearchAction, Schema.Null]), + ), + id: Schema.String, + query: Schema.String, + type: Schema.Literal("webSearch").annotate({ title: "WebSearchThreadItemType" }), + }).annotate({ title: "WebSearchThreadItem" }), + Schema.Struct({ + id: Schema.String, + path: Schema.String, + type: Schema.Literal("imageView").annotate({ title: "ImageViewThreadItemType" }), + }).annotate({ title: "ImageViewThreadItem" }), + Schema.Struct({ + id: Schema.String, + result: Schema.String, + revisedPrompt: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + savedPath: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + status: Schema.String, + type: Schema.Literal("imageGeneration").annotate({ title: "ImageGenerationThreadItemType" }), + }).annotate({ title: "ImageGenerationThreadItem" }), + Schema.Struct({ + id: Schema.String, + review: Schema.String, + type: Schema.Literal("enteredReviewMode").annotate({ + title: "EnteredReviewModeThreadItemType", + }), + }).annotate({ title: "EnteredReviewModeThreadItem" }), + Schema.Struct({ + id: Schema.String, + review: Schema.String, + type: Schema.Literal("exitedReviewMode").annotate({ + title: "ExitedReviewModeThreadItemType", + }), + }).annotate({ title: "ExitedReviewModeThreadItem" }), + Schema.Struct({ + id: Schema.String, + type: Schema.Literal("contextCompaction").annotate({ + title: "ContextCompactionThreadItemType", + }), + }).annotate({ title: "ContextCompactionThreadItem" }), + ], + { mode: "oneOf" }, +); + +export type V2ModelListResponse__Model = { + readonly additionalSpeedTiers?: ReadonlyArray; + readonly availabilityNux?: V2ModelListResponse__ModelAvailabilityNux | null; + readonly defaultReasoningEffort: V2ModelListResponse__ReasoningEffort; + readonly description: string; + readonly displayName: string; + readonly hidden: boolean; + readonly id: string; + readonly inputModalities?: ReadonlyArray; + readonly isDefault: boolean; + readonly model: string; + readonly supportedReasoningEfforts: ReadonlyArray; + readonly supportsPersonality?: boolean; + readonly upgrade?: string | null; + readonly upgradeInfo?: V2ModelListResponse__ModelUpgradeInfo | null; +}; +export const V2ModelListResponse__Model = Schema.Struct({ + additionalSpeedTiers: Schema.optionalKey(Schema.Array(Schema.String).annotate({ default: [] })), + availabilityNux: Schema.optionalKey( + Schema.Union([V2ModelListResponse__ModelAvailabilityNux, Schema.Null]), + ), + defaultReasoningEffort: V2ModelListResponse__ReasoningEffort, + description: Schema.String, + displayName: Schema.String, + hidden: Schema.Boolean, + id: Schema.String, + inputModalities: Schema.optionalKey( + Schema.Array(V2ModelListResponse__InputModality).annotate({ default: ["text", "image"] }), + ), + isDefault: Schema.Boolean, + model: Schema.String, + supportedReasoningEfforts: Schema.Array(V2ModelListResponse__ReasoningEffortOption), + supportsPersonality: Schema.optionalKey(Schema.Boolean.annotate({ default: false })), + upgrade: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + upgradeInfo: Schema.optionalKey( + Schema.Union([V2ModelListResponse__ModelUpgradeInfo, Schema.Null]), + ), +}); + +export type V2PluginListResponse__PluginSummary = { + readonly authPolicy: V2PluginListResponse__PluginAuthPolicy; + readonly enabled: boolean; + readonly id: string; + readonly installPolicy: V2PluginListResponse__PluginInstallPolicy; + readonly installed: boolean; + readonly interface?: V2PluginListResponse__PluginInterface | null; + readonly name: string; + readonly source: V2PluginListResponse__PluginSource; +}; +export const V2PluginListResponse__PluginSummary = Schema.Struct({ + authPolicy: V2PluginListResponse__PluginAuthPolicy, + enabled: Schema.Boolean, + id: Schema.String, + installPolicy: V2PluginListResponse__PluginInstallPolicy, + installed: Schema.Boolean, + interface: Schema.optionalKey(Schema.Union([V2PluginListResponse__PluginInterface, Schema.Null])), + name: Schema.String, + source: V2PluginListResponse__PluginSource, +}); + +export type V2PluginReadResponse__PluginSummary = { + readonly authPolicy: V2PluginReadResponse__PluginAuthPolicy; + readonly enabled: boolean; + readonly id: string; + readonly installPolicy: V2PluginReadResponse__PluginInstallPolicy; + readonly installed: boolean; + readonly interface?: V2PluginReadResponse__PluginInterface | null; + readonly name: string; + readonly source: V2PluginReadResponse__PluginSource; +}; +export const V2PluginReadResponse__PluginSummary = Schema.Struct({ + authPolicy: V2PluginReadResponse__PluginAuthPolicy, + enabled: Schema.Boolean, + id: Schema.String, + installPolicy: V2PluginReadResponse__PluginInstallPolicy, + installed: Schema.Boolean, + interface: Schema.optionalKey(Schema.Union([V2PluginReadResponse__PluginInterface, Schema.Null])), + name: Schema.String, + source: V2PluginReadResponse__PluginSource, +}); + +export type V2RawResponseItemCompletedNotification__FunctionCallOutputBody = + | string + | ReadonlyArray; +export const V2RawResponseItemCompletedNotification__FunctionCallOutputBody = Schema.Union([ + Schema.String, + Schema.Array(V2RawResponseItemCompletedNotification__FunctionCallOutputContentItem), +]); + +export type V2ReviewStartResponse__TurnError = { + readonly additionalDetails?: string | null; + readonly codexErrorInfo?: V2ReviewStartResponse__CodexErrorInfo | null; + readonly message: string; +}; +export const V2ReviewStartResponse__TurnError = Schema.Struct({ + additionalDetails: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + codexErrorInfo: Schema.optionalKey( + Schema.Union([V2ReviewStartResponse__CodexErrorInfo, Schema.Null]), + ), + message: Schema.String, +}); + +export type V2ReviewStartResponse__ThreadItem = + | { + readonly content: ReadonlyArray; + readonly id: string; + readonly type: "userMessage"; + } + | { + readonly fragments: ReadonlyArray; + readonly id: string; + readonly type: "hookPrompt"; + } + | { + readonly id: string; + readonly memoryCitation?: V2ReviewStartResponse__MemoryCitation | null; + readonly phase?: V2ReviewStartResponse__MessagePhase | null; + readonly text: string; + readonly type: "agentMessage"; + } + | { readonly id: string; readonly text: string; readonly type: "plan" } + | { + readonly content?: ReadonlyArray; + readonly id: string; + readonly summary?: ReadonlyArray; + readonly type: "reasoning"; + } + | { + readonly aggregatedOutput?: string | null; + readonly command: string; + readonly commandActions: ReadonlyArray; + readonly cwd: string; + readonly durationMs?: number | null; + readonly exitCode?: number | null; + readonly id: string; + readonly processId?: string | null; + readonly source?: "agent" | "userShell" | "unifiedExecStartup" | "unifiedExecInteraction"; + readonly status: V2ReviewStartResponse__CommandExecutionStatus; + readonly type: "commandExecution"; + } + | { + readonly changes: ReadonlyArray; + readonly id: string; + readonly status: V2ReviewStartResponse__PatchApplyStatus; + readonly type: "fileChange"; + } + | { + readonly arguments: unknown; + readonly durationMs?: number | null; + readonly error?: V2ReviewStartResponse__McpToolCallError | null; + readonly id: string; + readonly result?: V2ReviewStartResponse__McpToolCallResult | null; + readonly server: string; + readonly status: V2ReviewStartResponse__McpToolCallStatus; + readonly tool: string; + readonly type: "mcpToolCall"; + } + | { + readonly arguments: unknown; + readonly contentItems?: ReadonlyArray | null; + readonly durationMs?: number | null; + readonly id: string; + readonly status: V2ReviewStartResponse__DynamicToolCallStatus; + readonly success?: boolean | null; + readonly tool: string; + readonly type: "dynamicToolCall"; + } + | { + readonly agentsStates: { readonly [x: string]: V2ReviewStartResponse__CollabAgentState }; + readonly id: string; + readonly model?: string | null; + readonly prompt?: string | null; + readonly reasoningEffort?: V2ReviewStartResponse__ReasoningEffort | null; + readonly receiverThreadIds: ReadonlyArray; + readonly senderThreadId: string; + readonly status: "inProgress" | "completed" | "failed"; + readonly tool: "spawnAgent" | "sendInput" | "resumeAgent" | "wait" | "closeAgent"; + readonly type: "collabAgentToolCall"; + } + | { + readonly action?: V2ReviewStartResponse__WebSearchAction | null; + readonly id: string; + readonly query: string; + readonly type: "webSearch"; + } + | { readonly id: string; readonly path: string; readonly type: "imageView" } + | { + readonly id: string; + readonly result: string; + readonly revisedPrompt?: string | null; + readonly savedPath?: string | null; + readonly status: string; + readonly type: "imageGeneration"; + } + | { readonly id: string; readonly review: string; readonly type: "enteredReviewMode" } + | { readonly id: string; readonly review: string; readonly type: "exitedReviewMode" } + | { readonly id: string; readonly type: "contextCompaction" }; +export const V2ReviewStartResponse__ThreadItem = Schema.Union( + [ + Schema.Struct({ + content: Schema.Array(V2ReviewStartResponse__UserInput), + id: Schema.String, + type: Schema.Literal("userMessage").annotate({ title: "UserMessageThreadItemType" }), + }).annotate({ title: "UserMessageThreadItem" }), + Schema.Struct({ + fragments: Schema.Array(V2ReviewStartResponse__HookPromptFragment), + id: Schema.String, + type: Schema.Literal("hookPrompt").annotate({ title: "HookPromptThreadItemType" }), + }).annotate({ title: "HookPromptThreadItem" }), + Schema.Struct({ + id: Schema.String, + memoryCitation: Schema.optionalKey( + Schema.Union([V2ReviewStartResponse__MemoryCitation, Schema.Null]), + ), + phase: Schema.optionalKey(Schema.Union([V2ReviewStartResponse__MessagePhase, Schema.Null])), + text: Schema.String, + type: Schema.Literal("agentMessage").annotate({ title: "AgentMessageThreadItemType" }), + }).annotate({ title: "AgentMessageThreadItem" }), + Schema.Struct({ + id: Schema.String, + text: Schema.String, + type: Schema.Literal("plan").annotate({ title: "PlanThreadItemType" }), + }).annotate({ + title: "PlanThreadItem", + description: + "EXPERIMENTAL - proposed plan item content. The completed plan item is authoritative and may not match the concatenation of `PlanDelta` text.", + }), + Schema.Struct({ + content: Schema.optionalKey(Schema.Array(Schema.String).annotate({ default: [] })), + id: Schema.String, + summary: Schema.optionalKey(Schema.Array(Schema.String).annotate({ default: [] })), + type: Schema.Literal("reasoning").annotate({ title: "ReasoningThreadItemType" }), + }).annotate({ title: "ReasoningThreadItem" }), + Schema.Struct({ + aggregatedOutput: Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + description: "The command's output, aggregated from stdout and stderr.", + }), + Schema.Null, + ]), + ), + command: Schema.String.annotate({ description: "The command to be executed." }), + commandActions: Schema.Array(V2ReviewStartResponse__CommandAction).annotate({ + description: + "A best-effort parsing of the command to understand the action(s) it will perform. This returns a list of CommandAction objects because a single shell command may be composed of many commands piped together.", + }), + cwd: Schema.String.annotate({ description: "The command's working directory." }), + durationMs: Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ + description: "The duration of the command execution in milliseconds.", + format: "int64", + }).check(Schema.isInt()), + Schema.Null, + ]), + ), + exitCode: Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ + description: "The command's exit code.", + format: "int32", + }).check(Schema.isInt()), + Schema.Null, + ]), + ), + id: Schema.String, + processId: Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + description: "Identifier for the underlying PTY process (when available).", + }), + Schema.Null, + ]), + ), + source: Schema.optionalKey( + Schema.Literals([ + "agent", + "userShell", + "unifiedExecStartup", + "unifiedExecInteraction", + ]).annotate({ default: "agent" }), + ), + status: V2ReviewStartResponse__CommandExecutionStatus, + type: Schema.Literal("commandExecution").annotate({ + title: "CommandExecutionThreadItemType", + }), + }).annotate({ title: "CommandExecutionThreadItem" }), + Schema.Struct({ + changes: Schema.Array(V2ReviewStartResponse__FileUpdateChange), + id: Schema.String, + status: V2ReviewStartResponse__PatchApplyStatus, + type: Schema.Literal("fileChange").annotate({ title: "FileChangeThreadItemType" }), + }).annotate({ title: "FileChangeThreadItem" }), + Schema.Struct({ + arguments: Schema.Unknown, + durationMs: Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ + description: "The duration of the MCP tool call in milliseconds.", + format: "int64", + }).check(Schema.isInt()), + Schema.Null, + ]), + ), + error: Schema.optionalKey( + Schema.Union([V2ReviewStartResponse__McpToolCallError, Schema.Null]), + ), + id: Schema.String, + result: Schema.optionalKey( + Schema.Union([V2ReviewStartResponse__McpToolCallResult, Schema.Null]), + ), + server: Schema.String, + status: V2ReviewStartResponse__McpToolCallStatus, + tool: Schema.String, + type: Schema.Literal("mcpToolCall").annotate({ title: "McpToolCallThreadItemType" }), + }).annotate({ title: "McpToolCallThreadItem" }), + Schema.Struct({ + arguments: Schema.Unknown, + contentItems: Schema.optionalKey( + Schema.Union([ + Schema.Array(V2ReviewStartResponse__DynamicToolCallOutputContentItem), + Schema.Null, + ]), + ), + durationMs: Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ + description: "The duration of the dynamic tool call in milliseconds.", + format: "int64", + }).check(Schema.isInt()), + Schema.Null, + ]), + ), + id: Schema.String, + status: V2ReviewStartResponse__DynamicToolCallStatus, + success: Schema.optionalKey(Schema.Union([Schema.Boolean, Schema.Null])), + tool: Schema.String, + type: Schema.Literal("dynamicToolCall").annotate({ title: "DynamicToolCallThreadItemType" }), + }).annotate({ title: "DynamicToolCallThreadItem" }), + Schema.Struct({ + agentsStates: Schema.Record(Schema.String, V2ReviewStartResponse__CollabAgentState).annotate({ + description: "Last known status of the target agents, when available.", + }), + id: Schema.String.annotate({ description: "Unique identifier for this collab tool call." }), + model: Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + description: "Model requested for the spawned agent, when applicable.", + }), + Schema.Null, + ]), + ), + prompt: Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + description: "Prompt text sent as part of the collab tool call, when available.", + }), + Schema.Null, + ]), + ), + reasoningEffort: Schema.optionalKey( + Schema.Union([V2ReviewStartResponse__ReasoningEffort, Schema.Null]).annotate({ + description: "Reasoning effort requested for the spawned agent, when applicable.", + }), + ), + receiverThreadIds: Schema.Array(Schema.String).annotate({ + description: + "Thread ID of the receiving agent, when applicable. In case of spawn operation, this corresponds to the newly spawned agent.", + }), + senderThreadId: Schema.String.annotate({ + description: "Thread ID of the agent issuing the collab request.", + }), + status: Schema.Literals(["inProgress", "completed", "failed"]).annotate({ + description: "Current status of the collab tool call.", + }), + tool: Schema.Literals([ + "spawnAgent", + "sendInput", + "resumeAgent", + "wait", + "closeAgent", + ]).annotate({ description: "Name of the collab tool that was invoked." }), + type: Schema.Literal("collabAgentToolCall").annotate({ + title: "CollabAgentToolCallThreadItemType", + }), + }).annotate({ title: "CollabAgentToolCallThreadItem" }), + Schema.Struct({ + action: Schema.optionalKey( + Schema.Union([V2ReviewStartResponse__WebSearchAction, Schema.Null]), + ), + id: Schema.String, + query: Schema.String, + type: Schema.Literal("webSearch").annotate({ title: "WebSearchThreadItemType" }), + }).annotate({ title: "WebSearchThreadItem" }), + Schema.Struct({ + id: Schema.String, + path: Schema.String, + type: Schema.Literal("imageView").annotate({ title: "ImageViewThreadItemType" }), + }).annotate({ title: "ImageViewThreadItem" }), + Schema.Struct({ + id: Schema.String, + result: Schema.String, + revisedPrompt: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + savedPath: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + status: Schema.String, + type: Schema.Literal("imageGeneration").annotate({ title: "ImageGenerationThreadItemType" }), + }).annotate({ title: "ImageGenerationThreadItem" }), + Schema.Struct({ + id: Schema.String, + review: Schema.String, + type: Schema.Literal("enteredReviewMode").annotate({ + title: "EnteredReviewModeThreadItemType", + }), + }).annotate({ title: "EnteredReviewModeThreadItem" }), + Schema.Struct({ + id: Schema.String, + review: Schema.String, + type: Schema.Literal("exitedReviewMode").annotate({ + title: "ExitedReviewModeThreadItemType", + }), + }).annotate({ title: "ExitedReviewModeThreadItem" }), + Schema.Struct({ + id: Schema.String, + type: Schema.Literal("contextCompaction").annotate({ + title: "ContextCompactionThreadItemType", + }), + }).annotate({ title: "ContextCompactionThreadItem" }), + ], + { mode: "oneOf" }, +); + +export type V2SkillsListResponse__SkillMetadata = { + readonly dependencies?: V2SkillsListResponse__SkillDependencies | null; + readonly description: string; + readonly enabled: boolean; + readonly interface?: V2SkillsListResponse__SkillInterface | null; + readonly name: string; + readonly path: string; + readonly scope: V2SkillsListResponse__SkillScope; + readonly shortDescription?: string | null; +}; +export const V2SkillsListResponse__SkillMetadata = Schema.Struct({ + dependencies: Schema.optionalKey( + Schema.Union([V2SkillsListResponse__SkillDependencies, Schema.Null]), + ), + description: Schema.String, + enabled: Schema.Boolean, + interface: Schema.optionalKey(Schema.Union([V2SkillsListResponse__SkillInterface, Schema.Null])), + name: Schema.String, + path: Schema.String, + scope: V2SkillsListResponse__SkillScope, + shortDescription: Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + description: + "Legacy short_description from SKILL.md. Prefer SKILL.json interface.short_description.", + }), + Schema.Null, + ]), + ), +}); + +export type V2ThreadForkResponse__TurnError = { + readonly additionalDetails?: string | null; + readonly codexErrorInfo?: V2ThreadForkResponse__CodexErrorInfo | null; + readonly message: string; +}; +export const V2ThreadForkResponse__TurnError = Schema.Struct({ + additionalDetails: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + codexErrorInfo: Schema.optionalKey( + Schema.Union([V2ThreadForkResponse__CodexErrorInfo, Schema.Null]), + ), + message: Schema.String, +}); + +export type V2ThreadForkResponse__ThreadItem = + | { + readonly content: ReadonlyArray; + readonly id: string; + readonly type: "userMessage"; + } + | { + readonly fragments: ReadonlyArray; + readonly id: string; + readonly type: "hookPrompt"; + } + | { + readonly id: string; + readonly memoryCitation?: V2ThreadForkResponse__MemoryCitation | null; + readonly phase?: V2ThreadForkResponse__MessagePhase | null; + readonly text: string; + readonly type: "agentMessage"; + } + | { readonly id: string; readonly text: string; readonly type: "plan" } + | { + readonly content?: ReadonlyArray; + readonly id: string; + readonly summary?: ReadonlyArray; + readonly type: "reasoning"; + } + | { + readonly aggregatedOutput?: string | null; + readonly command: string; + readonly commandActions: ReadonlyArray; + readonly cwd: string; + readonly durationMs?: number | null; + readonly exitCode?: number | null; + readonly id: string; + readonly processId?: string | null; + readonly source?: "agent" | "userShell" | "unifiedExecStartup" | "unifiedExecInteraction"; + readonly status: V2ThreadForkResponse__CommandExecutionStatus; + readonly type: "commandExecution"; + } + | { + readonly changes: ReadonlyArray; + readonly id: string; + readonly status: V2ThreadForkResponse__PatchApplyStatus; + readonly type: "fileChange"; + } + | { + readonly arguments: unknown; + readonly durationMs?: number | null; + readonly error?: V2ThreadForkResponse__McpToolCallError | null; + readonly id: string; + readonly result?: V2ThreadForkResponse__McpToolCallResult | null; + readonly server: string; + readonly status: V2ThreadForkResponse__McpToolCallStatus; + readonly tool: string; + readonly type: "mcpToolCall"; + } + | { + readonly arguments: unknown; + readonly contentItems?: ReadonlyArray | null; + readonly durationMs?: number | null; + readonly id: string; + readonly status: V2ThreadForkResponse__DynamicToolCallStatus; + readonly success?: boolean | null; + readonly tool: string; + readonly type: "dynamicToolCall"; + } + | { + readonly agentsStates: { readonly [x: string]: V2ThreadForkResponse__CollabAgentState }; + readonly id: string; + readonly model?: string | null; + readonly prompt?: string | null; + readonly reasoningEffort?: V2ThreadForkResponse__ReasoningEffort | null; + readonly receiverThreadIds: ReadonlyArray; + readonly senderThreadId: string; + readonly status: "inProgress" | "completed" | "failed"; + readonly tool: "spawnAgent" | "sendInput" | "resumeAgent" | "wait" | "closeAgent"; + readonly type: "collabAgentToolCall"; + } + | { + readonly action?: V2ThreadForkResponse__WebSearchAction | null; + readonly id: string; + readonly query: string; + readonly type: "webSearch"; + } + | { readonly id: string; readonly path: string; readonly type: "imageView" } + | { + readonly id: string; + readonly result: string; + readonly revisedPrompt?: string | null; + readonly savedPath?: string | null; + readonly status: string; + readonly type: "imageGeneration"; + } + | { readonly id: string; readonly review: string; readonly type: "enteredReviewMode" } + | { readonly id: string; readonly review: string; readonly type: "exitedReviewMode" } + | { readonly id: string; readonly type: "contextCompaction" }; +export const V2ThreadForkResponse__ThreadItem = Schema.Union( + [ + Schema.Struct({ + content: Schema.Array(V2ThreadForkResponse__UserInput), + id: Schema.String, + type: Schema.Literal("userMessage").annotate({ title: "UserMessageThreadItemType" }), + }).annotate({ title: "UserMessageThreadItem" }), + Schema.Struct({ + fragments: Schema.Array(V2ThreadForkResponse__HookPromptFragment), + id: Schema.String, + type: Schema.Literal("hookPrompt").annotate({ title: "HookPromptThreadItemType" }), + }).annotate({ title: "HookPromptThreadItem" }), + Schema.Struct({ + id: Schema.String, + memoryCitation: Schema.optionalKey( + Schema.Union([V2ThreadForkResponse__MemoryCitation, Schema.Null]), + ), + phase: Schema.optionalKey(Schema.Union([V2ThreadForkResponse__MessagePhase, Schema.Null])), + text: Schema.String, + type: Schema.Literal("agentMessage").annotate({ title: "AgentMessageThreadItemType" }), + }).annotate({ title: "AgentMessageThreadItem" }), + Schema.Struct({ + id: Schema.String, + text: Schema.String, + type: Schema.Literal("plan").annotate({ title: "PlanThreadItemType" }), + }).annotate({ + title: "PlanThreadItem", + description: + "EXPERIMENTAL - proposed plan item content. The completed plan item is authoritative and may not match the concatenation of `PlanDelta` text.", + }), + Schema.Struct({ + content: Schema.optionalKey(Schema.Array(Schema.String).annotate({ default: [] })), + id: Schema.String, + summary: Schema.optionalKey(Schema.Array(Schema.String).annotate({ default: [] })), + type: Schema.Literal("reasoning").annotate({ title: "ReasoningThreadItemType" }), + }).annotate({ title: "ReasoningThreadItem" }), + Schema.Struct({ + aggregatedOutput: Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + description: "The command's output, aggregated from stdout and stderr.", + }), + Schema.Null, + ]), + ), + command: Schema.String.annotate({ description: "The command to be executed." }), + commandActions: Schema.Array(V2ThreadForkResponse__CommandAction).annotate({ + description: + "A best-effort parsing of the command to understand the action(s) it will perform. This returns a list of CommandAction objects because a single shell command may be composed of many commands piped together.", + }), + cwd: Schema.String.annotate({ description: "The command's working directory." }), + durationMs: Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ + description: "The duration of the command execution in milliseconds.", + format: "int64", + }).check(Schema.isInt()), + Schema.Null, + ]), + ), + exitCode: Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ + description: "The command's exit code.", + format: "int32", + }).check(Schema.isInt()), + Schema.Null, + ]), + ), + id: Schema.String, + processId: Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + description: "Identifier for the underlying PTY process (when available).", + }), + Schema.Null, + ]), + ), + source: Schema.optionalKey( + Schema.Literals([ + "agent", + "userShell", + "unifiedExecStartup", + "unifiedExecInteraction", + ]).annotate({ default: "agent" }), + ), + status: V2ThreadForkResponse__CommandExecutionStatus, + type: Schema.Literal("commandExecution").annotate({ + title: "CommandExecutionThreadItemType", + }), + }).annotate({ title: "CommandExecutionThreadItem" }), + Schema.Struct({ + changes: Schema.Array(V2ThreadForkResponse__FileUpdateChange), + id: Schema.String, + status: V2ThreadForkResponse__PatchApplyStatus, + type: Schema.Literal("fileChange").annotate({ title: "FileChangeThreadItemType" }), + }).annotate({ title: "FileChangeThreadItem" }), + Schema.Struct({ + arguments: Schema.Unknown, + durationMs: Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ + description: "The duration of the MCP tool call in milliseconds.", + format: "int64", + }).check(Schema.isInt()), + Schema.Null, + ]), + ), + error: Schema.optionalKey( + Schema.Union([V2ThreadForkResponse__McpToolCallError, Schema.Null]), + ), + id: Schema.String, + result: Schema.optionalKey( + Schema.Union([V2ThreadForkResponse__McpToolCallResult, Schema.Null]), + ), + server: Schema.String, + status: V2ThreadForkResponse__McpToolCallStatus, + tool: Schema.String, + type: Schema.Literal("mcpToolCall").annotate({ title: "McpToolCallThreadItemType" }), + }).annotate({ title: "McpToolCallThreadItem" }), + Schema.Struct({ + arguments: Schema.Unknown, + contentItems: Schema.optionalKey( + Schema.Union([ + Schema.Array(V2ThreadForkResponse__DynamicToolCallOutputContentItem), + Schema.Null, + ]), + ), + durationMs: Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ + description: "The duration of the dynamic tool call in milliseconds.", + format: "int64", + }).check(Schema.isInt()), + Schema.Null, + ]), + ), + id: Schema.String, + status: V2ThreadForkResponse__DynamicToolCallStatus, + success: Schema.optionalKey(Schema.Union([Schema.Boolean, Schema.Null])), + tool: Schema.String, + type: Schema.Literal("dynamicToolCall").annotate({ title: "DynamicToolCallThreadItemType" }), + }).annotate({ title: "DynamicToolCallThreadItem" }), + Schema.Struct({ + agentsStates: Schema.Record(Schema.String, V2ThreadForkResponse__CollabAgentState).annotate({ + description: "Last known status of the target agents, when available.", + }), + id: Schema.String.annotate({ description: "Unique identifier for this collab tool call." }), + model: Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + description: "Model requested for the spawned agent, when applicable.", + }), + Schema.Null, + ]), + ), + prompt: Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + description: "Prompt text sent as part of the collab tool call, when available.", + }), + Schema.Null, + ]), + ), + reasoningEffort: Schema.optionalKey( + Schema.Union([V2ThreadForkResponse__ReasoningEffort, Schema.Null]).annotate({ + description: "Reasoning effort requested for the spawned agent, when applicable.", + }), + ), + receiverThreadIds: Schema.Array(Schema.String).annotate({ + description: + "Thread ID of the receiving agent, when applicable. In case of spawn operation, this corresponds to the newly spawned agent.", + }), + senderThreadId: Schema.String.annotate({ + description: "Thread ID of the agent issuing the collab request.", + }), + status: Schema.Literals(["inProgress", "completed", "failed"]).annotate({ + description: "Current status of the collab tool call.", + }), + tool: Schema.Literals([ + "spawnAgent", + "sendInput", + "resumeAgent", + "wait", + "closeAgent", + ]).annotate({ description: "Name of the collab tool that was invoked." }), + type: Schema.Literal("collabAgentToolCall").annotate({ + title: "CollabAgentToolCallThreadItemType", + }), + }).annotate({ title: "CollabAgentToolCallThreadItem" }), + Schema.Struct({ + action: Schema.optionalKey( + Schema.Union([V2ThreadForkResponse__WebSearchAction, Schema.Null]), + ), + id: Schema.String, + query: Schema.String, + type: Schema.Literal("webSearch").annotate({ title: "WebSearchThreadItemType" }), + }).annotate({ title: "WebSearchThreadItem" }), + Schema.Struct({ + id: Schema.String, + path: Schema.String, + type: Schema.Literal("imageView").annotate({ title: "ImageViewThreadItemType" }), + }).annotate({ title: "ImageViewThreadItem" }), + Schema.Struct({ + id: Schema.String, + result: Schema.String, + revisedPrompt: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + savedPath: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + status: Schema.String, + type: Schema.Literal("imageGeneration").annotate({ title: "ImageGenerationThreadItemType" }), + }).annotate({ title: "ImageGenerationThreadItem" }), + Schema.Struct({ + id: Schema.String, + review: Schema.String, + type: Schema.Literal("enteredReviewMode").annotate({ + title: "EnteredReviewModeThreadItemType", + }), + }).annotate({ title: "EnteredReviewModeThreadItem" }), + Schema.Struct({ + id: Schema.String, + review: Schema.String, + type: Schema.Literal("exitedReviewMode").annotate({ + title: "ExitedReviewModeThreadItemType", + }), + }).annotate({ title: "ExitedReviewModeThreadItem" }), + Schema.Struct({ + id: Schema.String, + type: Schema.Literal("contextCompaction").annotate({ + title: "ContextCompactionThreadItemType", + }), + }).annotate({ title: "ContextCompactionThreadItem" }), + ], + { mode: "oneOf" }, +); + +export type V2ThreadListResponse__TurnError = { + readonly additionalDetails?: string | null; + readonly codexErrorInfo?: V2ThreadListResponse__CodexErrorInfo | null; + readonly message: string; +}; +export const V2ThreadListResponse__TurnError = Schema.Struct({ + additionalDetails: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + codexErrorInfo: Schema.optionalKey( + Schema.Union([V2ThreadListResponse__CodexErrorInfo, Schema.Null]), + ), + message: Schema.String, +}); + +export type V2ThreadListResponse__ThreadItem = + | { + readonly content: ReadonlyArray; + readonly id: string; + readonly type: "userMessage"; + } + | { + readonly fragments: ReadonlyArray; + readonly id: string; + readonly type: "hookPrompt"; + } + | { + readonly id: string; + readonly memoryCitation?: V2ThreadListResponse__MemoryCitation | null; + readonly phase?: V2ThreadListResponse__MessagePhase | null; + readonly text: string; + readonly type: "agentMessage"; + } + | { readonly id: string; readonly text: string; readonly type: "plan" } + | { + readonly content?: ReadonlyArray; + readonly id: string; + readonly summary?: ReadonlyArray; + readonly type: "reasoning"; + } + | { + readonly aggregatedOutput?: string | null; + readonly command: string; + readonly commandActions: ReadonlyArray; + readonly cwd: string; + readonly durationMs?: number | null; + readonly exitCode?: number | null; + readonly id: string; + readonly processId?: string | null; + readonly source?: "agent" | "userShell" | "unifiedExecStartup" | "unifiedExecInteraction"; + readonly status: V2ThreadListResponse__CommandExecutionStatus; + readonly type: "commandExecution"; + } + | { + readonly changes: ReadonlyArray; + readonly id: string; + readonly status: V2ThreadListResponse__PatchApplyStatus; + readonly type: "fileChange"; + } + | { + readonly arguments: unknown; + readonly durationMs?: number | null; + readonly error?: V2ThreadListResponse__McpToolCallError | null; + readonly id: string; + readonly result?: V2ThreadListResponse__McpToolCallResult | null; + readonly server: string; + readonly status: V2ThreadListResponse__McpToolCallStatus; + readonly tool: string; + readonly type: "mcpToolCall"; + } + | { + readonly arguments: unknown; + readonly contentItems?: ReadonlyArray | null; + readonly durationMs?: number | null; + readonly id: string; + readonly status: V2ThreadListResponse__DynamicToolCallStatus; + readonly success?: boolean | null; + readonly tool: string; + readonly type: "dynamicToolCall"; + } + | { + readonly agentsStates: { readonly [x: string]: V2ThreadListResponse__CollabAgentState }; + readonly id: string; + readonly model?: string | null; + readonly prompt?: string | null; + readonly reasoningEffort?: V2ThreadListResponse__ReasoningEffort | null; + readonly receiverThreadIds: ReadonlyArray; + readonly senderThreadId: string; + readonly status: "inProgress" | "completed" | "failed"; + readonly tool: "spawnAgent" | "sendInput" | "resumeAgent" | "wait" | "closeAgent"; + readonly type: "collabAgentToolCall"; + } + | { + readonly action?: V2ThreadListResponse__WebSearchAction | null; + readonly id: string; + readonly query: string; + readonly type: "webSearch"; + } + | { readonly id: string; readonly path: string; readonly type: "imageView" } + | { + readonly id: string; + readonly result: string; + readonly revisedPrompt?: string | null; + readonly savedPath?: string | null; + readonly status: string; + readonly type: "imageGeneration"; + } + | { readonly id: string; readonly review: string; readonly type: "enteredReviewMode" } + | { readonly id: string; readonly review: string; readonly type: "exitedReviewMode" } + | { readonly id: string; readonly type: "contextCompaction" }; +export const V2ThreadListResponse__ThreadItem = Schema.Union( + [ + Schema.Struct({ + content: Schema.Array(V2ThreadListResponse__UserInput), + id: Schema.String, + type: Schema.Literal("userMessage").annotate({ title: "UserMessageThreadItemType" }), + }).annotate({ title: "UserMessageThreadItem" }), + Schema.Struct({ + fragments: Schema.Array(V2ThreadListResponse__HookPromptFragment), + id: Schema.String, + type: Schema.Literal("hookPrompt").annotate({ title: "HookPromptThreadItemType" }), + }).annotate({ title: "HookPromptThreadItem" }), + Schema.Struct({ + id: Schema.String, + memoryCitation: Schema.optionalKey( + Schema.Union([V2ThreadListResponse__MemoryCitation, Schema.Null]), + ), + phase: Schema.optionalKey(Schema.Union([V2ThreadListResponse__MessagePhase, Schema.Null])), + text: Schema.String, + type: Schema.Literal("agentMessage").annotate({ title: "AgentMessageThreadItemType" }), + }).annotate({ title: "AgentMessageThreadItem" }), + Schema.Struct({ + id: Schema.String, + text: Schema.String, + type: Schema.Literal("plan").annotate({ title: "PlanThreadItemType" }), + }).annotate({ + title: "PlanThreadItem", + description: + "EXPERIMENTAL - proposed plan item content. The completed plan item is authoritative and may not match the concatenation of `PlanDelta` text.", + }), + Schema.Struct({ + content: Schema.optionalKey(Schema.Array(Schema.String).annotate({ default: [] })), + id: Schema.String, + summary: Schema.optionalKey(Schema.Array(Schema.String).annotate({ default: [] })), + type: Schema.Literal("reasoning").annotate({ title: "ReasoningThreadItemType" }), + }).annotate({ title: "ReasoningThreadItem" }), + Schema.Struct({ + aggregatedOutput: Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + description: "The command's output, aggregated from stdout and stderr.", + }), + Schema.Null, + ]), + ), + command: Schema.String.annotate({ description: "The command to be executed." }), + commandActions: Schema.Array(V2ThreadListResponse__CommandAction).annotate({ + description: + "A best-effort parsing of the command to understand the action(s) it will perform. This returns a list of CommandAction objects because a single shell command may be composed of many commands piped together.", + }), + cwd: Schema.String.annotate({ description: "The command's working directory." }), + durationMs: Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ + description: "The duration of the command execution in milliseconds.", + format: "int64", + }).check(Schema.isInt()), + Schema.Null, + ]), + ), + exitCode: Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ + description: "The command's exit code.", + format: "int32", + }).check(Schema.isInt()), + Schema.Null, + ]), + ), + id: Schema.String, + processId: Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + description: "Identifier for the underlying PTY process (when available).", + }), + Schema.Null, + ]), + ), + source: Schema.optionalKey( + Schema.Literals([ + "agent", + "userShell", + "unifiedExecStartup", + "unifiedExecInteraction", + ]).annotate({ default: "agent" }), + ), + status: V2ThreadListResponse__CommandExecutionStatus, + type: Schema.Literal("commandExecution").annotate({ + title: "CommandExecutionThreadItemType", + }), + }).annotate({ title: "CommandExecutionThreadItem" }), + Schema.Struct({ + changes: Schema.Array(V2ThreadListResponse__FileUpdateChange), + id: Schema.String, + status: V2ThreadListResponse__PatchApplyStatus, + type: Schema.Literal("fileChange").annotate({ title: "FileChangeThreadItemType" }), + }).annotate({ title: "FileChangeThreadItem" }), + Schema.Struct({ + arguments: Schema.Unknown, + durationMs: Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ + description: "The duration of the MCP tool call in milliseconds.", + format: "int64", + }).check(Schema.isInt()), + Schema.Null, + ]), + ), + error: Schema.optionalKey( + Schema.Union([V2ThreadListResponse__McpToolCallError, Schema.Null]), + ), + id: Schema.String, + result: Schema.optionalKey( + Schema.Union([V2ThreadListResponse__McpToolCallResult, Schema.Null]), + ), + server: Schema.String, + status: V2ThreadListResponse__McpToolCallStatus, + tool: Schema.String, + type: Schema.Literal("mcpToolCall").annotate({ title: "McpToolCallThreadItemType" }), + }).annotate({ title: "McpToolCallThreadItem" }), + Schema.Struct({ + arguments: Schema.Unknown, + contentItems: Schema.optionalKey( + Schema.Union([ + Schema.Array(V2ThreadListResponse__DynamicToolCallOutputContentItem), + Schema.Null, + ]), + ), + durationMs: Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ + description: "The duration of the dynamic tool call in milliseconds.", + format: "int64", + }).check(Schema.isInt()), + Schema.Null, + ]), + ), + id: Schema.String, + status: V2ThreadListResponse__DynamicToolCallStatus, + success: Schema.optionalKey(Schema.Union([Schema.Boolean, Schema.Null])), + tool: Schema.String, + type: Schema.Literal("dynamicToolCall").annotate({ title: "DynamicToolCallThreadItemType" }), + }).annotate({ title: "DynamicToolCallThreadItem" }), + Schema.Struct({ + agentsStates: Schema.Record(Schema.String, V2ThreadListResponse__CollabAgentState).annotate({ + description: "Last known status of the target agents, when available.", + }), + id: Schema.String.annotate({ description: "Unique identifier for this collab tool call." }), + model: Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + description: "Model requested for the spawned agent, when applicable.", + }), + Schema.Null, + ]), + ), + prompt: Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + description: "Prompt text sent as part of the collab tool call, when available.", + }), + Schema.Null, + ]), + ), + reasoningEffort: Schema.optionalKey( + Schema.Union([V2ThreadListResponse__ReasoningEffort, Schema.Null]).annotate({ + description: "Reasoning effort requested for the spawned agent, when applicable.", + }), + ), + receiverThreadIds: Schema.Array(Schema.String).annotate({ + description: + "Thread ID of the receiving agent, when applicable. In case of spawn operation, this corresponds to the newly spawned agent.", + }), + senderThreadId: Schema.String.annotate({ + description: "Thread ID of the agent issuing the collab request.", + }), + status: Schema.Literals(["inProgress", "completed", "failed"]).annotate({ + description: "Current status of the collab tool call.", + }), + tool: Schema.Literals([ + "spawnAgent", + "sendInput", + "resumeAgent", + "wait", + "closeAgent", + ]).annotate({ description: "Name of the collab tool that was invoked." }), + type: Schema.Literal("collabAgentToolCall").annotate({ + title: "CollabAgentToolCallThreadItemType", + }), + }).annotate({ title: "CollabAgentToolCallThreadItem" }), + Schema.Struct({ + action: Schema.optionalKey( + Schema.Union([V2ThreadListResponse__WebSearchAction, Schema.Null]), + ), + id: Schema.String, + query: Schema.String, + type: Schema.Literal("webSearch").annotate({ title: "WebSearchThreadItemType" }), + }).annotate({ title: "WebSearchThreadItem" }), + Schema.Struct({ + id: Schema.String, + path: Schema.String, + type: Schema.Literal("imageView").annotate({ title: "ImageViewThreadItemType" }), + }).annotate({ title: "ImageViewThreadItem" }), + Schema.Struct({ + id: Schema.String, + result: Schema.String, + revisedPrompt: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + savedPath: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + status: Schema.String, + type: Schema.Literal("imageGeneration").annotate({ title: "ImageGenerationThreadItemType" }), + }).annotate({ title: "ImageGenerationThreadItem" }), + Schema.Struct({ + id: Schema.String, + review: Schema.String, + type: Schema.Literal("enteredReviewMode").annotate({ + title: "EnteredReviewModeThreadItemType", + }), + }).annotate({ title: "EnteredReviewModeThreadItem" }), + Schema.Struct({ + id: Schema.String, + review: Schema.String, + type: Schema.Literal("exitedReviewMode").annotate({ + title: "ExitedReviewModeThreadItemType", + }), + }).annotate({ title: "ExitedReviewModeThreadItem" }), + Schema.Struct({ + id: Schema.String, + type: Schema.Literal("contextCompaction").annotate({ + title: "ContextCompactionThreadItemType", + }), + }).annotate({ title: "ContextCompactionThreadItem" }), + ], + { mode: "oneOf" }, +); + +export type V2ThreadMetadataUpdateResponse__TurnError = { + readonly additionalDetails?: string | null; + readonly codexErrorInfo?: V2ThreadMetadataUpdateResponse__CodexErrorInfo | null; + readonly message: string; +}; +export const V2ThreadMetadataUpdateResponse__TurnError = Schema.Struct({ + additionalDetails: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + codexErrorInfo: Schema.optionalKey( + Schema.Union([V2ThreadMetadataUpdateResponse__CodexErrorInfo, Schema.Null]), + ), + message: Schema.String, +}); + +export type V2ThreadMetadataUpdateResponse__ThreadItem = + | { + readonly content: ReadonlyArray; + readonly id: string; + readonly type: "userMessage"; + } + | { + readonly fragments: ReadonlyArray; + readonly id: string; + readonly type: "hookPrompt"; + } + | { + readonly id: string; + readonly memoryCitation?: V2ThreadMetadataUpdateResponse__MemoryCitation | null; + readonly phase?: V2ThreadMetadataUpdateResponse__MessagePhase | null; + readonly text: string; + readonly type: "agentMessage"; + } + | { readonly id: string; readonly text: string; readonly type: "plan" } + | { + readonly content?: ReadonlyArray; + readonly id: string; + readonly summary?: ReadonlyArray; + readonly type: "reasoning"; + } + | { + readonly aggregatedOutput?: string | null; + readonly command: string; + readonly commandActions: ReadonlyArray; + readonly cwd: string; + readonly durationMs?: number | null; + readonly exitCode?: number | null; + readonly id: string; + readonly processId?: string | null; + readonly source?: "agent" | "userShell" | "unifiedExecStartup" | "unifiedExecInteraction"; + readonly status: V2ThreadMetadataUpdateResponse__CommandExecutionStatus; + readonly type: "commandExecution"; + } + | { + readonly changes: ReadonlyArray; + readonly id: string; + readonly status: V2ThreadMetadataUpdateResponse__PatchApplyStatus; + readonly type: "fileChange"; + } + | { + readonly arguments: unknown; + readonly durationMs?: number | null; + readonly error?: V2ThreadMetadataUpdateResponse__McpToolCallError | null; + readonly id: string; + readonly result?: V2ThreadMetadataUpdateResponse__McpToolCallResult | null; + readonly server: string; + readonly status: V2ThreadMetadataUpdateResponse__McpToolCallStatus; + readonly tool: string; + readonly type: "mcpToolCall"; + } + | { + readonly arguments: unknown; + readonly contentItems?: ReadonlyArray | null; + readonly durationMs?: number | null; + readonly id: string; + readonly status: V2ThreadMetadataUpdateResponse__DynamicToolCallStatus; + readonly success?: boolean | null; + readonly tool: string; + readonly type: "dynamicToolCall"; + } + | { + readonly agentsStates: { + readonly [x: string]: V2ThreadMetadataUpdateResponse__CollabAgentState; + }; + readonly id: string; + readonly model?: string | null; + readonly prompt?: string | null; + readonly reasoningEffort?: V2ThreadMetadataUpdateResponse__ReasoningEffort | null; + readonly receiverThreadIds: ReadonlyArray; + readonly senderThreadId: string; + readonly status: "inProgress" | "completed" | "failed"; + readonly tool: "spawnAgent" | "sendInput" | "resumeAgent" | "wait" | "closeAgent"; + readonly type: "collabAgentToolCall"; + } + | { + readonly action?: V2ThreadMetadataUpdateResponse__WebSearchAction | null; + readonly id: string; + readonly query: string; + readonly type: "webSearch"; + } + | { readonly id: string; readonly path: string; readonly type: "imageView" } + | { + readonly id: string; + readonly result: string; + readonly revisedPrompt?: string | null; + readonly savedPath?: string | null; + readonly status: string; + readonly type: "imageGeneration"; + } + | { readonly id: string; readonly review: string; readonly type: "enteredReviewMode" } + | { readonly id: string; readonly review: string; readonly type: "exitedReviewMode" } + | { readonly id: string; readonly type: "contextCompaction" }; +export const V2ThreadMetadataUpdateResponse__ThreadItem = Schema.Union( + [ + Schema.Struct({ + content: Schema.Array(V2ThreadMetadataUpdateResponse__UserInput), + id: Schema.String, + type: Schema.Literal("userMessage").annotate({ title: "UserMessageThreadItemType" }), + }).annotate({ title: "UserMessageThreadItem" }), + Schema.Struct({ + fragments: Schema.Array(V2ThreadMetadataUpdateResponse__HookPromptFragment), + id: Schema.String, + type: Schema.Literal("hookPrompt").annotate({ title: "HookPromptThreadItemType" }), + }).annotate({ title: "HookPromptThreadItem" }), + Schema.Struct({ + id: Schema.String, + memoryCitation: Schema.optionalKey( + Schema.Union([V2ThreadMetadataUpdateResponse__MemoryCitation, Schema.Null]), + ), + phase: Schema.optionalKey( + Schema.Union([V2ThreadMetadataUpdateResponse__MessagePhase, Schema.Null]), + ), + text: Schema.String, + type: Schema.Literal("agentMessage").annotate({ title: "AgentMessageThreadItemType" }), + }).annotate({ title: "AgentMessageThreadItem" }), + Schema.Struct({ + id: Schema.String, + text: Schema.String, + type: Schema.Literal("plan").annotate({ title: "PlanThreadItemType" }), + }).annotate({ + title: "PlanThreadItem", + description: + "EXPERIMENTAL - proposed plan item content. The completed plan item is authoritative and may not match the concatenation of `PlanDelta` text.", + }), + Schema.Struct({ + content: Schema.optionalKey(Schema.Array(Schema.String).annotate({ default: [] })), + id: Schema.String, + summary: Schema.optionalKey(Schema.Array(Schema.String).annotate({ default: [] })), + type: Schema.Literal("reasoning").annotate({ title: "ReasoningThreadItemType" }), + }).annotate({ title: "ReasoningThreadItem" }), + Schema.Struct({ + aggregatedOutput: Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + description: "The command's output, aggregated from stdout and stderr.", + }), + Schema.Null, + ]), + ), + command: Schema.String.annotate({ description: "The command to be executed." }), + commandActions: Schema.Array(V2ThreadMetadataUpdateResponse__CommandAction).annotate({ + description: + "A best-effort parsing of the command to understand the action(s) it will perform. This returns a list of CommandAction objects because a single shell command may be composed of many commands piped together.", + }), + cwd: Schema.String.annotate({ description: "The command's working directory." }), + durationMs: Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ + description: "The duration of the command execution in milliseconds.", + format: "int64", + }).check(Schema.isInt()), + Schema.Null, + ]), + ), + exitCode: Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ + description: "The command's exit code.", + format: "int32", + }).check(Schema.isInt()), + Schema.Null, + ]), + ), + id: Schema.String, + processId: Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + description: "Identifier for the underlying PTY process (when available).", + }), + Schema.Null, + ]), + ), + source: Schema.optionalKey( + Schema.Literals([ + "agent", + "userShell", + "unifiedExecStartup", + "unifiedExecInteraction", + ]).annotate({ default: "agent" }), + ), + status: V2ThreadMetadataUpdateResponse__CommandExecutionStatus, + type: Schema.Literal("commandExecution").annotate({ + title: "CommandExecutionThreadItemType", + }), + }).annotate({ title: "CommandExecutionThreadItem" }), + Schema.Struct({ + changes: Schema.Array(V2ThreadMetadataUpdateResponse__FileUpdateChange), + id: Schema.String, + status: V2ThreadMetadataUpdateResponse__PatchApplyStatus, + type: Schema.Literal("fileChange").annotate({ title: "FileChangeThreadItemType" }), + }).annotate({ title: "FileChangeThreadItem" }), + Schema.Struct({ + arguments: Schema.Unknown, + durationMs: Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ + description: "The duration of the MCP tool call in milliseconds.", + format: "int64", + }).check(Schema.isInt()), + Schema.Null, + ]), + ), + error: Schema.optionalKey( + Schema.Union([V2ThreadMetadataUpdateResponse__McpToolCallError, Schema.Null]), + ), + id: Schema.String, + result: Schema.optionalKey( + Schema.Union([V2ThreadMetadataUpdateResponse__McpToolCallResult, Schema.Null]), + ), + server: Schema.String, + status: V2ThreadMetadataUpdateResponse__McpToolCallStatus, + tool: Schema.String, + type: Schema.Literal("mcpToolCall").annotate({ title: "McpToolCallThreadItemType" }), + }).annotate({ title: "McpToolCallThreadItem" }), + Schema.Struct({ + arguments: Schema.Unknown, + contentItems: Schema.optionalKey( + Schema.Union([ + Schema.Array(V2ThreadMetadataUpdateResponse__DynamicToolCallOutputContentItem), + Schema.Null, + ]), + ), + durationMs: Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ + description: "The duration of the dynamic tool call in milliseconds.", + format: "int64", + }).check(Schema.isInt()), + Schema.Null, + ]), + ), + id: Schema.String, + status: V2ThreadMetadataUpdateResponse__DynamicToolCallStatus, + success: Schema.optionalKey(Schema.Union([Schema.Boolean, Schema.Null])), + tool: Schema.String, + type: Schema.Literal("dynamicToolCall").annotate({ title: "DynamicToolCallThreadItemType" }), + }).annotate({ title: "DynamicToolCallThreadItem" }), + Schema.Struct({ + agentsStates: Schema.Record( + Schema.String, + V2ThreadMetadataUpdateResponse__CollabAgentState, + ).annotate({ description: "Last known status of the target agents, when available." }), + id: Schema.String.annotate({ description: "Unique identifier for this collab tool call." }), + model: Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + description: "Model requested for the spawned agent, when applicable.", + }), + Schema.Null, + ]), + ), + prompt: Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + description: "Prompt text sent as part of the collab tool call, when available.", + }), + Schema.Null, + ]), + ), + reasoningEffort: Schema.optionalKey( + Schema.Union([V2ThreadMetadataUpdateResponse__ReasoningEffort, Schema.Null]).annotate({ + description: "Reasoning effort requested for the spawned agent, when applicable.", + }), + ), + receiverThreadIds: Schema.Array(Schema.String).annotate({ + description: + "Thread ID of the receiving agent, when applicable. In case of spawn operation, this corresponds to the newly spawned agent.", + }), + senderThreadId: Schema.String.annotate({ + description: "Thread ID of the agent issuing the collab request.", + }), + status: Schema.Literals(["inProgress", "completed", "failed"]).annotate({ + description: "Current status of the collab tool call.", + }), + tool: Schema.Literals([ + "spawnAgent", + "sendInput", + "resumeAgent", + "wait", + "closeAgent", + ]).annotate({ description: "Name of the collab tool that was invoked." }), + type: Schema.Literal("collabAgentToolCall").annotate({ + title: "CollabAgentToolCallThreadItemType", + }), + }).annotate({ title: "CollabAgentToolCallThreadItem" }), + Schema.Struct({ + action: Schema.optionalKey( + Schema.Union([V2ThreadMetadataUpdateResponse__WebSearchAction, Schema.Null]), + ), + id: Schema.String, + query: Schema.String, + type: Schema.Literal("webSearch").annotate({ title: "WebSearchThreadItemType" }), + }).annotate({ title: "WebSearchThreadItem" }), + Schema.Struct({ + id: Schema.String, + path: Schema.String, + type: Schema.Literal("imageView").annotate({ title: "ImageViewThreadItemType" }), + }).annotate({ title: "ImageViewThreadItem" }), + Schema.Struct({ + id: Schema.String, + result: Schema.String, + revisedPrompt: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + savedPath: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + status: Schema.String, + type: Schema.Literal("imageGeneration").annotate({ title: "ImageGenerationThreadItemType" }), + }).annotate({ title: "ImageGenerationThreadItem" }), + Schema.Struct({ + id: Schema.String, + review: Schema.String, + type: Schema.Literal("enteredReviewMode").annotate({ + title: "EnteredReviewModeThreadItemType", + }), + }).annotate({ title: "EnteredReviewModeThreadItem" }), + Schema.Struct({ + id: Schema.String, + review: Schema.String, + type: Schema.Literal("exitedReviewMode").annotate({ + title: "ExitedReviewModeThreadItemType", + }), + }).annotate({ title: "ExitedReviewModeThreadItem" }), + Schema.Struct({ + id: Schema.String, + type: Schema.Literal("contextCompaction").annotate({ + title: "ContextCompactionThreadItemType", + }), + }).annotate({ title: "ContextCompactionThreadItem" }), + ], + { mode: "oneOf" }, +); + +export type V2ThreadReadResponse__TurnError = { + readonly additionalDetails?: string | null; + readonly codexErrorInfo?: V2ThreadReadResponse__CodexErrorInfo | null; + readonly message: string; +}; +export const V2ThreadReadResponse__TurnError = Schema.Struct({ + additionalDetails: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + codexErrorInfo: Schema.optionalKey( + Schema.Union([V2ThreadReadResponse__CodexErrorInfo, Schema.Null]), + ), + message: Schema.String, +}); + +export type V2ThreadReadResponse__ThreadItem = + | { + readonly content: ReadonlyArray; + readonly id: string; + readonly type: "userMessage"; + } + | { + readonly fragments: ReadonlyArray; + readonly id: string; + readonly type: "hookPrompt"; + } + | { + readonly id: string; + readonly memoryCitation?: V2ThreadReadResponse__MemoryCitation | null; + readonly phase?: V2ThreadReadResponse__MessagePhase | null; + readonly text: string; + readonly type: "agentMessage"; + } + | { readonly id: string; readonly text: string; readonly type: "plan" } + | { + readonly content?: ReadonlyArray; + readonly id: string; + readonly summary?: ReadonlyArray; + readonly type: "reasoning"; + } + | { + readonly aggregatedOutput?: string | null; + readonly command: string; + readonly commandActions: ReadonlyArray; + readonly cwd: string; + readonly durationMs?: number | null; + readonly exitCode?: number | null; + readonly id: string; + readonly processId?: string | null; + readonly source?: "agent" | "userShell" | "unifiedExecStartup" | "unifiedExecInteraction"; + readonly status: V2ThreadReadResponse__CommandExecutionStatus; + readonly type: "commandExecution"; + } + | { + readonly changes: ReadonlyArray; + readonly id: string; + readonly status: V2ThreadReadResponse__PatchApplyStatus; + readonly type: "fileChange"; + } + | { + readonly arguments: unknown; + readonly durationMs?: number | null; + readonly error?: V2ThreadReadResponse__McpToolCallError | null; + readonly id: string; + readonly result?: V2ThreadReadResponse__McpToolCallResult | null; + readonly server: string; + readonly status: V2ThreadReadResponse__McpToolCallStatus; + readonly tool: string; + readonly type: "mcpToolCall"; + } + | { + readonly arguments: unknown; + readonly contentItems?: ReadonlyArray | null; + readonly durationMs?: number | null; + readonly id: string; + readonly status: V2ThreadReadResponse__DynamicToolCallStatus; + readonly success?: boolean | null; + readonly tool: string; + readonly type: "dynamicToolCall"; + } + | { + readonly agentsStates: { readonly [x: string]: V2ThreadReadResponse__CollabAgentState }; + readonly id: string; + readonly model?: string | null; + readonly prompt?: string | null; + readonly reasoningEffort?: V2ThreadReadResponse__ReasoningEffort | null; + readonly receiverThreadIds: ReadonlyArray; + readonly senderThreadId: string; + readonly status: "inProgress" | "completed" | "failed"; + readonly tool: "spawnAgent" | "sendInput" | "resumeAgent" | "wait" | "closeAgent"; + readonly type: "collabAgentToolCall"; + } + | { + readonly action?: V2ThreadReadResponse__WebSearchAction | null; + readonly id: string; + readonly query: string; + readonly type: "webSearch"; + } + | { readonly id: string; readonly path: string; readonly type: "imageView" } + | { + readonly id: string; + readonly result: string; + readonly revisedPrompt?: string | null; + readonly savedPath?: string | null; + readonly status: string; + readonly type: "imageGeneration"; + } + | { readonly id: string; readonly review: string; readonly type: "enteredReviewMode" } + | { readonly id: string; readonly review: string; readonly type: "exitedReviewMode" } + | { readonly id: string; readonly type: "contextCompaction" }; +export const V2ThreadReadResponse__ThreadItem = Schema.Union( + [ + Schema.Struct({ + content: Schema.Array(V2ThreadReadResponse__UserInput), + id: Schema.String, + type: Schema.Literal("userMessage").annotate({ title: "UserMessageThreadItemType" }), + }).annotate({ title: "UserMessageThreadItem" }), + Schema.Struct({ + fragments: Schema.Array(V2ThreadReadResponse__HookPromptFragment), + id: Schema.String, + type: Schema.Literal("hookPrompt").annotate({ title: "HookPromptThreadItemType" }), + }).annotate({ title: "HookPromptThreadItem" }), + Schema.Struct({ + id: Schema.String, + memoryCitation: Schema.optionalKey( + Schema.Union([V2ThreadReadResponse__MemoryCitation, Schema.Null]), + ), + phase: Schema.optionalKey(Schema.Union([V2ThreadReadResponse__MessagePhase, Schema.Null])), + text: Schema.String, + type: Schema.Literal("agentMessage").annotate({ title: "AgentMessageThreadItemType" }), + }).annotate({ title: "AgentMessageThreadItem" }), + Schema.Struct({ + id: Schema.String, + text: Schema.String, + type: Schema.Literal("plan").annotate({ title: "PlanThreadItemType" }), + }).annotate({ + title: "PlanThreadItem", + description: + "EXPERIMENTAL - proposed plan item content. The completed plan item is authoritative and may not match the concatenation of `PlanDelta` text.", + }), + Schema.Struct({ + content: Schema.optionalKey(Schema.Array(Schema.String).annotate({ default: [] })), + id: Schema.String, + summary: Schema.optionalKey(Schema.Array(Schema.String).annotate({ default: [] })), + type: Schema.Literal("reasoning").annotate({ title: "ReasoningThreadItemType" }), + }).annotate({ title: "ReasoningThreadItem" }), + Schema.Struct({ + aggregatedOutput: Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + description: "The command's output, aggregated from stdout and stderr.", + }), + Schema.Null, + ]), + ), + command: Schema.String.annotate({ description: "The command to be executed." }), + commandActions: Schema.Array(V2ThreadReadResponse__CommandAction).annotate({ + description: + "A best-effort parsing of the command to understand the action(s) it will perform. This returns a list of CommandAction objects because a single shell command may be composed of many commands piped together.", + }), + cwd: Schema.String.annotate({ description: "The command's working directory." }), + durationMs: Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ + description: "The duration of the command execution in milliseconds.", + format: "int64", + }).check(Schema.isInt()), + Schema.Null, + ]), + ), + exitCode: Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ + description: "The command's exit code.", + format: "int32", + }).check(Schema.isInt()), + Schema.Null, + ]), + ), + id: Schema.String, + processId: Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + description: "Identifier for the underlying PTY process (when available).", + }), + Schema.Null, + ]), + ), + source: Schema.optionalKey( + Schema.Literals([ + "agent", + "userShell", + "unifiedExecStartup", + "unifiedExecInteraction", + ]).annotate({ default: "agent" }), + ), + status: V2ThreadReadResponse__CommandExecutionStatus, + type: Schema.Literal("commandExecution").annotate({ + title: "CommandExecutionThreadItemType", + }), + }).annotate({ title: "CommandExecutionThreadItem" }), + Schema.Struct({ + changes: Schema.Array(V2ThreadReadResponse__FileUpdateChange), + id: Schema.String, + status: V2ThreadReadResponse__PatchApplyStatus, + type: Schema.Literal("fileChange").annotate({ title: "FileChangeThreadItemType" }), + }).annotate({ title: "FileChangeThreadItem" }), + Schema.Struct({ + arguments: Schema.Unknown, + durationMs: Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ + description: "The duration of the MCP tool call in milliseconds.", + format: "int64", + }).check(Schema.isInt()), + Schema.Null, + ]), + ), + error: Schema.optionalKey( + Schema.Union([V2ThreadReadResponse__McpToolCallError, Schema.Null]), + ), + id: Schema.String, + result: Schema.optionalKey( + Schema.Union([V2ThreadReadResponse__McpToolCallResult, Schema.Null]), + ), + server: Schema.String, + status: V2ThreadReadResponse__McpToolCallStatus, + tool: Schema.String, + type: Schema.Literal("mcpToolCall").annotate({ title: "McpToolCallThreadItemType" }), + }).annotate({ title: "McpToolCallThreadItem" }), + Schema.Struct({ + arguments: Schema.Unknown, + contentItems: Schema.optionalKey( + Schema.Union([ + Schema.Array(V2ThreadReadResponse__DynamicToolCallOutputContentItem), + Schema.Null, + ]), + ), + durationMs: Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ + description: "The duration of the dynamic tool call in milliseconds.", + format: "int64", + }).check(Schema.isInt()), + Schema.Null, + ]), + ), + id: Schema.String, + status: V2ThreadReadResponse__DynamicToolCallStatus, + success: Schema.optionalKey(Schema.Union([Schema.Boolean, Schema.Null])), + tool: Schema.String, + type: Schema.Literal("dynamicToolCall").annotate({ title: "DynamicToolCallThreadItemType" }), + }).annotate({ title: "DynamicToolCallThreadItem" }), + Schema.Struct({ + agentsStates: Schema.Record(Schema.String, V2ThreadReadResponse__CollabAgentState).annotate({ + description: "Last known status of the target agents, when available.", + }), + id: Schema.String.annotate({ description: "Unique identifier for this collab tool call." }), + model: Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + description: "Model requested for the spawned agent, when applicable.", + }), + Schema.Null, + ]), + ), + prompt: Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + description: "Prompt text sent as part of the collab tool call, when available.", + }), + Schema.Null, + ]), + ), + reasoningEffort: Schema.optionalKey( + Schema.Union([V2ThreadReadResponse__ReasoningEffort, Schema.Null]).annotate({ + description: "Reasoning effort requested for the spawned agent, when applicable.", + }), + ), + receiverThreadIds: Schema.Array(Schema.String).annotate({ + description: + "Thread ID of the receiving agent, when applicable. In case of spawn operation, this corresponds to the newly spawned agent.", + }), + senderThreadId: Schema.String.annotate({ + description: "Thread ID of the agent issuing the collab request.", + }), + status: Schema.Literals(["inProgress", "completed", "failed"]).annotate({ + description: "Current status of the collab tool call.", + }), + tool: Schema.Literals([ + "spawnAgent", + "sendInput", + "resumeAgent", + "wait", + "closeAgent", + ]).annotate({ description: "Name of the collab tool that was invoked." }), + type: Schema.Literal("collabAgentToolCall").annotate({ + title: "CollabAgentToolCallThreadItemType", + }), + }).annotate({ title: "CollabAgentToolCallThreadItem" }), + Schema.Struct({ + action: Schema.optionalKey( + Schema.Union([V2ThreadReadResponse__WebSearchAction, Schema.Null]), + ), + id: Schema.String, + query: Schema.String, + type: Schema.Literal("webSearch").annotate({ title: "WebSearchThreadItemType" }), + }).annotate({ title: "WebSearchThreadItem" }), + Schema.Struct({ + id: Schema.String, + path: Schema.String, + type: Schema.Literal("imageView").annotate({ title: "ImageViewThreadItemType" }), + }).annotate({ title: "ImageViewThreadItem" }), + Schema.Struct({ + id: Schema.String, + result: Schema.String, + revisedPrompt: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + savedPath: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + status: Schema.String, + type: Schema.Literal("imageGeneration").annotate({ title: "ImageGenerationThreadItemType" }), + }).annotate({ title: "ImageGenerationThreadItem" }), + Schema.Struct({ + id: Schema.String, + review: Schema.String, + type: Schema.Literal("enteredReviewMode").annotate({ + title: "EnteredReviewModeThreadItemType", + }), + }).annotate({ title: "EnteredReviewModeThreadItem" }), + Schema.Struct({ + id: Schema.String, + review: Schema.String, + type: Schema.Literal("exitedReviewMode").annotate({ + title: "ExitedReviewModeThreadItemType", + }), + }).annotate({ title: "ExitedReviewModeThreadItem" }), + Schema.Struct({ + id: Schema.String, + type: Schema.Literal("contextCompaction").annotate({ + title: "ContextCompactionThreadItemType", + }), + }).annotate({ title: "ContextCompactionThreadItem" }), + ], + { mode: "oneOf" }, +); + +export type V2ThreadResumeParams__FunctionCallOutputBody = + | string + | ReadonlyArray; +export const V2ThreadResumeParams__FunctionCallOutputBody = Schema.Union([ + Schema.String, + Schema.Array(V2ThreadResumeParams__FunctionCallOutputContentItem), +]); + +export type V2ThreadResumeResponse__TurnError = { + readonly additionalDetails?: string | null; + readonly codexErrorInfo?: V2ThreadResumeResponse__CodexErrorInfo | null; + readonly message: string; +}; +export const V2ThreadResumeResponse__TurnError = Schema.Struct({ + additionalDetails: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + codexErrorInfo: Schema.optionalKey( + Schema.Union([V2ThreadResumeResponse__CodexErrorInfo, Schema.Null]), + ), + message: Schema.String, +}); + +export type V2ThreadResumeResponse__ThreadItem = + | { + readonly content: ReadonlyArray; + readonly id: string; + readonly type: "userMessage"; + } + | { + readonly fragments: ReadonlyArray; + readonly id: string; + readonly type: "hookPrompt"; + } + | { + readonly id: string; + readonly memoryCitation?: V2ThreadResumeResponse__MemoryCitation | null; + readonly phase?: V2ThreadResumeResponse__MessagePhase | null; + readonly text: string; + readonly type: "agentMessage"; + } + | { readonly id: string; readonly text: string; readonly type: "plan" } + | { + readonly content?: ReadonlyArray; + readonly id: string; + readonly summary?: ReadonlyArray; + readonly type: "reasoning"; + } + | { + readonly aggregatedOutput?: string | null; + readonly command: string; + readonly commandActions: ReadonlyArray; + readonly cwd: string; + readonly durationMs?: number | null; + readonly exitCode?: number | null; + readonly id: string; + readonly processId?: string | null; + readonly source?: "agent" | "userShell" | "unifiedExecStartup" | "unifiedExecInteraction"; + readonly status: V2ThreadResumeResponse__CommandExecutionStatus; + readonly type: "commandExecution"; + } + | { + readonly changes: ReadonlyArray; + readonly id: string; + readonly status: V2ThreadResumeResponse__PatchApplyStatus; + readonly type: "fileChange"; + } + | { + readonly arguments: unknown; + readonly durationMs?: number | null; + readonly error?: V2ThreadResumeResponse__McpToolCallError | null; + readonly id: string; + readonly result?: V2ThreadResumeResponse__McpToolCallResult | null; + readonly server: string; + readonly status: V2ThreadResumeResponse__McpToolCallStatus; + readonly tool: string; + readonly type: "mcpToolCall"; + } + | { + readonly arguments: unknown; + readonly contentItems?: ReadonlyArray | null; + readonly durationMs?: number | null; + readonly id: string; + readonly status: V2ThreadResumeResponse__DynamicToolCallStatus; + readonly success?: boolean | null; + readonly tool: string; + readonly type: "dynamicToolCall"; + } + | { + readonly agentsStates: { readonly [x: string]: V2ThreadResumeResponse__CollabAgentState }; + readonly id: string; + readonly model?: string | null; + readonly prompt?: string | null; + readonly reasoningEffort?: V2ThreadResumeResponse__ReasoningEffort | null; + readonly receiverThreadIds: ReadonlyArray; + readonly senderThreadId: string; + readonly status: "inProgress" | "completed" | "failed"; + readonly tool: "spawnAgent" | "sendInput" | "resumeAgent" | "wait" | "closeAgent"; + readonly type: "collabAgentToolCall"; + } + | { + readonly action?: V2ThreadResumeResponse__WebSearchAction | null; + readonly id: string; + readonly query: string; + readonly type: "webSearch"; + } + | { readonly id: string; readonly path: string; readonly type: "imageView" } + | { + readonly id: string; + readonly result: string; + readonly revisedPrompt?: string | null; + readonly savedPath?: string | null; + readonly status: string; + readonly type: "imageGeneration"; + } + | { readonly id: string; readonly review: string; readonly type: "enteredReviewMode" } + | { readonly id: string; readonly review: string; readonly type: "exitedReviewMode" } + | { readonly id: string; readonly type: "contextCompaction" }; +export const V2ThreadResumeResponse__ThreadItem = Schema.Union( + [ + Schema.Struct({ + content: Schema.Array(V2ThreadResumeResponse__UserInput), + id: Schema.String, + type: Schema.Literal("userMessage").annotate({ title: "UserMessageThreadItemType" }), + }).annotate({ title: "UserMessageThreadItem" }), + Schema.Struct({ + fragments: Schema.Array(V2ThreadResumeResponse__HookPromptFragment), + id: Schema.String, + type: Schema.Literal("hookPrompt").annotate({ title: "HookPromptThreadItemType" }), + }).annotate({ title: "HookPromptThreadItem" }), + Schema.Struct({ + id: Schema.String, + memoryCitation: Schema.optionalKey( + Schema.Union([V2ThreadResumeResponse__MemoryCitation, Schema.Null]), + ), + phase: Schema.optionalKey(Schema.Union([V2ThreadResumeResponse__MessagePhase, Schema.Null])), + text: Schema.String, + type: Schema.Literal("agentMessage").annotate({ title: "AgentMessageThreadItemType" }), + }).annotate({ title: "AgentMessageThreadItem" }), + Schema.Struct({ + id: Schema.String, + text: Schema.String, + type: Schema.Literal("plan").annotate({ title: "PlanThreadItemType" }), + }).annotate({ + title: "PlanThreadItem", + description: + "EXPERIMENTAL - proposed plan item content. The completed plan item is authoritative and may not match the concatenation of `PlanDelta` text.", + }), + Schema.Struct({ + content: Schema.optionalKey(Schema.Array(Schema.String).annotate({ default: [] })), + id: Schema.String, + summary: Schema.optionalKey(Schema.Array(Schema.String).annotate({ default: [] })), + type: Schema.Literal("reasoning").annotate({ title: "ReasoningThreadItemType" }), + }).annotate({ title: "ReasoningThreadItem" }), + Schema.Struct({ + aggregatedOutput: Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + description: "The command's output, aggregated from stdout and stderr.", + }), + Schema.Null, + ]), + ), + command: Schema.String.annotate({ description: "The command to be executed." }), + commandActions: Schema.Array(V2ThreadResumeResponse__CommandAction).annotate({ + description: + "A best-effort parsing of the command to understand the action(s) it will perform. This returns a list of CommandAction objects because a single shell command may be composed of many commands piped together.", + }), + cwd: Schema.String.annotate({ description: "The command's working directory." }), + durationMs: Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ + description: "The duration of the command execution in milliseconds.", + format: "int64", + }).check(Schema.isInt()), + Schema.Null, + ]), + ), + exitCode: Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ + description: "The command's exit code.", + format: "int32", + }).check(Schema.isInt()), + Schema.Null, + ]), + ), + id: Schema.String, + processId: Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + description: "Identifier for the underlying PTY process (when available).", + }), + Schema.Null, + ]), + ), + source: Schema.optionalKey( + Schema.Literals([ + "agent", + "userShell", + "unifiedExecStartup", + "unifiedExecInteraction", + ]).annotate({ default: "agent" }), + ), + status: V2ThreadResumeResponse__CommandExecutionStatus, + type: Schema.Literal("commandExecution").annotate({ + title: "CommandExecutionThreadItemType", + }), + }).annotate({ title: "CommandExecutionThreadItem" }), + Schema.Struct({ + changes: Schema.Array(V2ThreadResumeResponse__FileUpdateChange), + id: Schema.String, + status: V2ThreadResumeResponse__PatchApplyStatus, + type: Schema.Literal("fileChange").annotate({ title: "FileChangeThreadItemType" }), + }).annotate({ title: "FileChangeThreadItem" }), + Schema.Struct({ + arguments: Schema.Unknown, + durationMs: Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ + description: "The duration of the MCP tool call in milliseconds.", + format: "int64", + }).check(Schema.isInt()), + Schema.Null, + ]), + ), + error: Schema.optionalKey( + Schema.Union([V2ThreadResumeResponse__McpToolCallError, Schema.Null]), + ), + id: Schema.String, + result: Schema.optionalKey( + Schema.Union([V2ThreadResumeResponse__McpToolCallResult, Schema.Null]), + ), + server: Schema.String, + status: V2ThreadResumeResponse__McpToolCallStatus, + tool: Schema.String, + type: Schema.Literal("mcpToolCall").annotate({ title: "McpToolCallThreadItemType" }), + }).annotate({ title: "McpToolCallThreadItem" }), + Schema.Struct({ + arguments: Schema.Unknown, + contentItems: Schema.optionalKey( + Schema.Union([ + Schema.Array(V2ThreadResumeResponse__DynamicToolCallOutputContentItem), + Schema.Null, + ]), + ), + durationMs: Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ + description: "The duration of the dynamic tool call in milliseconds.", + format: "int64", + }).check(Schema.isInt()), + Schema.Null, + ]), + ), + id: Schema.String, + status: V2ThreadResumeResponse__DynamicToolCallStatus, + success: Schema.optionalKey(Schema.Union([Schema.Boolean, Schema.Null])), + tool: Schema.String, + type: Schema.Literal("dynamicToolCall").annotate({ title: "DynamicToolCallThreadItemType" }), + }).annotate({ title: "DynamicToolCallThreadItem" }), + Schema.Struct({ + agentsStates: Schema.Record(Schema.String, V2ThreadResumeResponse__CollabAgentState).annotate( + { description: "Last known status of the target agents, when available." }, + ), + id: Schema.String.annotate({ description: "Unique identifier for this collab tool call." }), + model: Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + description: "Model requested for the spawned agent, when applicable.", + }), + Schema.Null, + ]), + ), + prompt: Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + description: "Prompt text sent as part of the collab tool call, when available.", + }), + Schema.Null, + ]), + ), + reasoningEffort: Schema.optionalKey( + Schema.Union([V2ThreadResumeResponse__ReasoningEffort, Schema.Null]).annotate({ + description: "Reasoning effort requested for the spawned agent, when applicable.", + }), + ), + receiverThreadIds: Schema.Array(Schema.String).annotate({ + description: + "Thread ID of the receiving agent, when applicable. In case of spawn operation, this corresponds to the newly spawned agent.", + }), + senderThreadId: Schema.String.annotate({ + description: "Thread ID of the agent issuing the collab request.", + }), + status: Schema.Literals(["inProgress", "completed", "failed"]).annotate({ + description: "Current status of the collab tool call.", + }), + tool: Schema.Literals([ + "spawnAgent", + "sendInput", + "resumeAgent", + "wait", + "closeAgent", + ]).annotate({ description: "Name of the collab tool that was invoked." }), + type: Schema.Literal("collabAgentToolCall").annotate({ + title: "CollabAgentToolCallThreadItemType", + }), + }).annotate({ title: "CollabAgentToolCallThreadItem" }), + Schema.Struct({ + action: Schema.optionalKey( + Schema.Union([V2ThreadResumeResponse__WebSearchAction, Schema.Null]), + ), + id: Schema.String, + query: Schema.String, + type: Schema.Literal("webSearch").annotate({ title: "WebSearchThreadItemType" }), + }).annotate({ title: "WebSearchThreadItem" }), + Schema.Struct({ + id: Schema.String, + path: Schema.String, + type: Schema.Literal("imageView").annotate({ title: "ImageViewThreadItemType" }), + }).annotate({ title: "ImageViewThreadItem" }), + Schema.Struct({ + id: Schema.String, + result: Schema.String, + revisedPrompt: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + savedPath: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + status: Schema.String, + type: Schema.Literal("imageGeneration").annotate({ title: "ImageGenerationThreadItemType" }), + }).annotate({ title: "ImageGenerationThreadItem" }), + Schema.Struct({ + id: Schema.String, + review: Schema.String, + type: Schema.Literal("enteredReviewMode").annotate({ + title: "EnteredReviewModeThreadItemType", + }), + }).annotate({ title: "EnteredReviewModeThreadItem" }), + Schema.Struct({ + id: Schema.String, + review: Schema.String, + type: Schema.Literal("exitedReviewMode").annotate({ + title: "ExitedReviewModeThreadItemType", + }), + }).annotate({ title: "ExitedReviewModeThreadItem" }), + Schema.Struct({ + id: Schema.String, + type: Schema.Literal("contextCompaction").annotate({ + title: "ContextCompactionThreadItemType", + }), + }).annotate({ title: "ContextCompactionThreadItem" }), + ], + { mode: "oneOf" }, +); + +export type V2ThreadRollbackResponse__TurnError = { + readonly additionalDetails?: string | null; + readonly codexErrorInfo?: V2ThreadRollbackResponse__CodexErrorInfo | null; + readonly message: string; +}; +export const V2ThreadRollbackResponse__TurnError = Schema.Struct({ + additionalDetails: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + codexErrorInfo: Schema.optionalKey( + Schema.Union([V2ThreadRollbackResponse__CodexErrorInfo, Schema.Null]), + ), + message: Schema.String, +}); + +export type V2ThreadRollbackResponse__ThreadItem = + | { + readonly content: ReadonlyArray; + readonly id: string; + readonly type: "userMessage"; + } + | { + readonly fragments: ReadonlyArray; + readonly id: string; + readonly type: "hookPrompt"; + } + | { + readonly id: string; + readonly memoryCitation?: V2ThreadRollbackResponse__MemoryCitation | null; + readonly phase?: V2ThreadRollbackResponse__MessagePhase | null; + readonly text: string; + readonly type: "agentMessage"; + } + | { readonly id: string; readonly text: string; readonly type: "plan" } + | { + readonly content?: ReadonlyArray; + readonly id: string; + readonly summary?: ReadonlyArray; + readonly type: "reasoning"; + } + | { + readonly aggregatedOutput?: string | null; + readonly command: string; + readonly commandActions: ReadonlyArray; + readonly cwd: string; + readonly durationMs?: number | null; + readonly exitCode?: number | null; + readonly id: string; + readonly processId?: string | null; + readonly source?: "agent" | "userShell" | "unifiedExecStartup" | "unifiedExecInteraction"; + readonly status: V2ThreadRollbackResponse__CommandExecutionStatus; + readonly type: "commandExecution"; + } + | { + readonly changes: ReadonlyArray; + readonly id: string; + readonly status: V2ThreadRollbackResponse__PatchApplyStatus; + readonly type: "fileChange"; + } + | { + readonly arguments: unknown; + readonly durationMs?: number | null; + readonly error?: V2ThreadRollbackResponse__McpToolCallError | null; + readonly id: string; + readonly result?: V2ThreadRollbackResponse__McpToolCallResult | null; + readonly server: string; + readonly status: V2ThreadRollbackResponse__McpToolCallStatus; + readonly tool: string; + readonly type: "mcpToolCall"; + } + | { + readonly arguments: unknown; + readonly contentItems?: ReadonlyArray | null; + readonly durationMs?: number | null; + readonly id: string; + readonly status: V2ThreadRollbackResponse__DynamicToolCallStatus; + readonly success?: boolean | null; + readonly tool: string; + readonly type: "dynamicToolCall"; + } + | { + readonly agentsStates: { readonly [x: string]: V2ThreadRollbackResponse__CollabAgentState }; + readonly id: string; + readonly model?: string | null; + readonly prompt?: string | null; + readonly reasoningEffort?: V2ThreadRollbackResponse__ReasoningEffort | null; + readonly receiverThreadIds: ReadonlyArray; + readonly senderThreadId: string; + readonly status: "inProgress" | "completed" | "failed"; + readonly tool: "spawnAgent" | "sendInput" | "resumeAgent" | "wait" | "closeAgent"; + readonly type: "collabAgentToolCall"; + } + | { + readonly action?: V2ThreadRollbackResponse__WebSearchAction | null; + readonly id: string; + readonly query: string; + readonly type: "webSearch"; + } + | { readonly id: string; readonly path: string; readonly type: "imageView" } + | { + readonly id: string; + readonly result: string; + readonly revisedPrompt?: string | null; + readonly savedPath?: string | null; + readonly status: string; + readonly type: "imageGeneration"; + } + | { readonly id: string; readonly review: string; readonly type: "enteredReviewMode" } + | { readonly id: string; readonly review: string; readonly type: "exitedReviewMode" } + | { readonly id: string; readonly type: "contextCompaction" }; +export const V2ThreadRollbackResponse__ThreadItem = Schema.Union( + [ + Schema.Struct({ + content: Schema.Array(V2ThreadRollbackResponse__UserInput), + id: Schema.String, + type: Schema.Literal("userMessage").annotate({ title: "UserMessageThreadItemType" }), + }).annotate({ title: "UserMessageThreadItem" }), + Schema.Struct({ + fragments: Schema.Array(V2ThreadRollbackResponse__HookPromptFragment), + id: Schema.String, + type: Schema.Literal("hookPrompt").annotate({ title: "HookPromptThreadItemType" }), + }).annotate({ title: "HookPromptThreadItem" }), + Schema.Struct({ + id: Schema.String, + memoryCitation: Schema.optionalKey( + Schema.Union([V2ThreadRollbackResponse__MemoryCitation, Schema.Null]), + ), + phase: Schema.optionalKey( + Schema.Union([V2ThreadRollbackResponse__MessagePhase, Schema.Null]), + ), + text: Schema.String, + type: Schema.Literal("agentMessage").annotate({ title: "AgentMessageThreadItemType" }), + }).annotate({ title: "AgentMessageThreadItem" }), + Schema.Struct({ + id: Schema.String, + text: Schema.String, + type: Schema.Literal("plan").annotate({ title: "PlanThreadItemType" }), + }).annotate({ + title: "PlanThreadItem", + description: + "EXPERIMENTAL - proposed plan item content. The completed plan item is authoritative and may not match the concatenation of `PlanDelta` text.", + }), + Schema.Struct({ + content: Schema.optionalKey(Schema.Array(Schema.String).annotate({ default: [] })), + id: Schema.String, + summary: Schema.optionalKey(Schema.Array(Schema.String).annotate({ default: [] })), + type: Schema.Literal("reasoning").annotate({ title: "ReasoningThreadItemType" }), + }).annotate({ title: "ReasoningThreadItem" }), + Schema.Struct({ + aggregatedOutput: Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + description: "The command's output, aggregated from stdout and stderr.", + }), + Schema.Null, + ]), + ), + command: Schema.String.annotate({ description: "The command to be executed." }), + commandActions: Schema.Array(V2ThreadRollbackResponse__CommandAction).annotate({ + description: + "A best-effort parsing of the command to understand the action(s) it will perform. This returns a list of CommandAction objects because a single shell command may be composed of many commands piped together.", + }), + cwd: Schema.String.annotate({ description: "The command's working directory." }), + durationMs: Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ + description: "The duration of the command execution in milliseconds.", + format: "int64", + }).check(Schema.isInt()), + Schema.Null, + ]), + ), + exitCode: Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ + description: "The command's exit code.", + format: "int32", + }).check(Schema.isInt()), + Schema.Null, + ]), + ), + id: Schema.String, + processId: Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + description: "Identifier for the underlying PTY process (when available).", + }), + Schema.Null, + ]), + ), + source: Schema.optionalKey( + Schema.Literals([ + "agent", + "userShell", + "unifiedExecStartup", + "unifiedExecInteraction", + ]).annotate({ default: "agent" }), + ), + status: V2ThreadRollbackResponse__CommandExecutionStatus, + type: Schema.Literal("commandExecution").annotate({ + title: "CommandExecutionThreadItemType", + }), + }).annotate({ title: "CommandExecutionThreadItem" }), + Schema.Struct({ + changes: Schema.Array(V2ThreadRollbackResponse__FileUpdateChange), + id: Schema.String, + status: V2ThreadRollbackResponse__PatchApplyStatus, + type: Schema.Literal("fileChange").annotate({ title: "FileChangeThreadItemType" }), + }).annotate({ title: "FileChangeThreadItem" }), + Schema.Struct({ + arguments: Schema.Unknown, + durationMs: Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ + description: "The duration of the MCP tool call in milliseconds.", + format: "int64", + }).check(Schema.isInt()), + Schema.Null, + ]), + ), + error: Schema.optionalKey( + Schema.Union([V2ThreadRollbackResponse__McpToolCallError, Schema.Null]), + ), + id: Schema.String, + result: Schema.optionalKey( + Schema.Union([V2ThreadRollbackResponse__McpToolCallResult, Schema.Null]), + ), + server: Schema.String, + status: V2ThreadRollbackResponse__McpToolCallStatus, + tool: Schema.String, + type: Schema.Literal("mcpToolCall").annotate({ title: "McpToolCallThreadItemType" }), + }).annotate({ title: "McpToolCallThreadItem" }), + Schema.Struct({ + arguments: Schema.Unknown, + contentItems: Schema.optionalKey( + Schema.Union([ + Schema.Array(V2ThreadRollbackResponse__DynamicToolCallOutputContentItem), + Schema.Null, + ]), + ), + durationMs: Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ + description: "The duration of the dynamic tool call in milliseconds.", + format: "int64", + }).check(Schema.isInt()), + Schema.Null, + ]), + ), + id: Schema.String, + status: V2ThreadRollbackResponse__DynamicToolCallStatus, + success: Schema.optionalKey(Schema.Union([Schema.Boolean, Schema.Null])), + tool: Schema.String, + type: Schema.Literal("dynamicToolCall").annotate({ title: "DynamicToolCallThreadItemType" }), + }).annotate({ title: "DynamicToolCallThreadItem" }), + Schema.Struct({ + agentsStates: Schema.Record( + Schema.String, + V2ThreadRollbackResponse__CollabAgentState, + ).annotate({ description: "Last known status of the target agents, when available." }), + id: Schema.String.annotate({ description: "Unique identifier for this collab tool call." }), + model: Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + description: "Model requested for the spawned agent, when applicable.", + }), + Schema.Null, + ]), + ), + prompt: Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + description: "Prompt text sent as part of the collab tool call, when available.", + }), + Schema.Null, + ]), + ), + reasoningEffort: Schema.optionalKey( + Schema.Union([V2ThreadRollbackResponse__ReasoningEffort, Schema.Null]).annotate({ + description: "Reasoning effort requested for the spawned agent, when applicable.", + }), + ), + receiverThreadIds: Schema.Array(Schema.String).annotate({ + description: + "Thread ID of the receiving agent, when applicable. In case of spawn operation, this corresponds to the newly spawned agent.", + }), + senderThreadId: Schema.String.annotate({ + description: "Thread ID of the agent issuing the collab request.", + }), + status: Schema.Literals(["inProgress", "completed", "failed"]).annotate({ + description: "Current status of the collab tool call.", + }), + tool: Schema.Literals([ + "spawnAgent", + "sendInput", + "resumeAgent", + "wait", + "closeAgent", + ]).annotate({ description: "Name of the collab tool that was invoked." }), + type: Schema.Literal("collabAgentToolCall").annotate({ + title: "CollabAgentToolCallThreadItemType", + }), + }).annotate({ title: "CollabAgentToolCallThreadItem" }), + Schema.Struct({ + action: Schema.optionalKey( + Schema.Union([V2ThreadRollbackResponse__WebSearchAction, Schema.Null]), + ), + id: Schema.String, + query: Schema.String, + type: Schema.Literal("webSearch").annotate({ title: "WebSearchThreadItemType" }), + }).annotate({ title: "WebSearchThreadItem" }), + Schema.Struct({ + id: Schema.String, + path: Schema.String, + type: Schema.Literal("imageView").annotate({ title: "ImageViewThreadItemType" }), + }).annotate({ title: "ImageViewThreadItem" }), + Schema.Struct({ + id: Schema.String, + result: Schema.String, + revisedPrompt: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + savedPath: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + status: Schema.String, + type: Schema.Literal("imageGeneration").annotate({ title: "ImageGenerationThreadItemType" }), + }).annotate({ title: "ImageGenerationThreadItem" }), + Schema.Struct({ + id: Schema.String, + review: Schema.String, + type: Schema.Literal("enteredReviewMode").annotate({ + title: "EnteredReviewModeThreadItemType", + }), + }).annotate({ title: "EnteredReviewModeThreadItem" }), + Schema.Struct({ + id: Schema.String, + review: Schema.String, + type: Schema.Literal("exitedReviewMode").annotate({ + title: "ExitedReviewModeThreadItemType", + }), + }).annotate({ title: "ExitedReviewModeThreadItem" }), + Schema.Struct({ + id: Schema.String, + type: Schema.Literal("contextCompaction").annotate({ + title: "ContextCompactionThreadItemType", + }), + }).annotate({ title: "ContextCompactionThreadItem" }), + ], + { mode: "oneOf" }, +); + +export type V2ThreadStartedNotification__TurnError = { + readonly additionalDetails?: string | null; + readonly codexErrorInfo?: V2ThreadStartedNotification__CodexErrorInfo | null; + readonly message: string; +}; +export const V2ThreadStartedNotification__TurnError = Schema.Struct({ + additionalDetails: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + codexErrorInfo: Schema.optionalKey( + Schema.Union([V2ThreadStartedNotification__CodexErrorInfo, Schema.Null]), + ), + message: Schema.String, +}); + +export type V2ThreadStartedNotification__ThreadItem = + | { + readonly content: ReadonlyArray; + readonly id: string; + readonly type: "userMessage"; + } + | { + readonly fragments: ReadonlyArray; + readonly id: string; + readonly type: "hookPrompt"; + } + | { + readonly id: string; + readonly memoryCitation?: V2ThreadStartedNotification__MemoryCitation | null; + readonly phase?: V2ThreadStartedNotification__MessagePhase | null; + readonly text: string; + readonly type: "agentMessage"; + } + | { readonly id: string; readonly text: string; readonly type: "plan" } + | { + readonly content?: ReadonlyArray; + readonly id: string; + readonly summary?: ReadonlyArray; + readonly type: "reasoning"; + } + | { + readonly aggregatedOutput?: string | null; + readonly command: string; + readonly commandActions: ReadonlyArray; + readonly cwd: string; + readonly durationMs?: number | null; + readonly exitCode?: number | null; + readonly id: string; + readonly processId?: string | null; + readonly source?: "agent" | "userShell" | "unifiedExecStartup" | "unifiedExecInteraction"; + readonly status: V2ThreadStartedNotification__CommandExecutionStatus; + readonly type: "commandExecution"; + } + | { + readonly changes: ReadonlyArray; + readonly id: string; + readonly status: V2ThreadStartedNotification__PatchApplyStatus; + readonly type: "fileChange"; + } + | { + readonly arguments: unknown; + readonly durationMs?: number | null; + readonly error?: V2ThreadStartedNotification__McpToolCallError | null; + readonly id: string; + readonly result?: V2ThreadStartedNotification__McpToolCallResult | null; + readonly server: string; + readonly status: V2ThreadStartedNotification__McpToolCallStatus; + readonly tool: string; + readonly type: "mcpToolCall"; + } + | { + readonly arguments: unknown; + readonly contentItems?: ReadonlyArray | null; + readonly durationMs?: number | null; + readonly id: string; + readonly status: V2ThreadStartedNotification__DynamicToolCallStatus; + readonly success?: boolean | null; + readonly tool: string; + readonly type: "dynamicToolCall"; + } + | { + readonly agentsStates: { + readonly [x: string]: V2ThreadStartedNotification__CollabAgentState; + }; + readonly id: string; + readonly model?: string | null; + readonly prompt?: string | null; + readonly reasoningEffort?: V2ThreadStartedNotification__ReasoningEffort | null; + readonly receiverThreadIds: ReadonlyArray; + readonly senderThreadId: string; + readonly status: "inProgress" | "completed" | "failed"; + readonly tool: "spawnAgent" | "sendInput" | "resumeAgent" | "wait" | "closeAgent"; + readonly type: "collabAgentToolCall"; + } + | { + readonly action?: V2ThreadStartedNotification__WebSearchAction | null; + readonly id: string; + readonly query: string; + readonly type: "webSearch"; + } + | { readonly id: string; readonly path: string; readonly type: "imageView" } + | { + readonly id: string; + readonly result: string; + readonly revisedPrompt?: string | null; + readonly savedPath?: string | null; + readonly status: string; + readonly type: "imageGeneration"; + } + | { readonly id: string; readonly review: string; readonly type: "enteredReviewMode" } + | { readonly id: string; readonly review: string; readonly type: "exitedReviewMode" } + | { readonly id: string; readonly type: "contextCompaction" }; +export const V2ThreadStartedNotification__ThreadItem = Schema.Union( + [ + Schema.Struct({ + content: Schema.Array(V2ThreadStartedNotification__UserInput), + id: Schema.String, + type: Schema.Literal("userMessage").annotate({ title: "UserMessageThreadItemType" }), + }).annotate({ title: "UserMessageThreadItem" }), + Schema.Struct({ + fragments: Schema.Array(V2ThreadStartedNotification__HookPromptFragment), + id: Schema.String, + type: Schema.Literal("hookPrompt").annotate({ title: "HookPromptThreadItemType" }), + }).annotate({ title: "HookPromptThreadItem" }), + Schema.Struct({ + id: Schema.String, + memoryCitation: Schema.optionalKey( + Schema.Union([V2ThreadStartedNotification__MemoryCitation, Schema.Null]), + ), + phase: Schema.optionalKey( + Schema.Union([V2ThreadStartedNotification__MessagePhase, Schema.Null]), + ), + text: Schema.String, + type: Schema.Literal("agentMessage").annotate({ title: "AgentMessageThreadItemType" }), + }).annotate({ title: "AgentMessageThreadItem" }), + Schema.Struct({ + id: Schema.String, + text: Schema.String, + type: Schema.Literal("plan").annotate({ title: "PlanThreadItemType" }), + }).annotate({ + title: "PlanThreadItem", + description: + "EXPERIMENTAL - proposed plan item content. The completed plan item is authoritative and may not match the concatenation of `PlanDelta` text.", + }), + Schema.Struct({ + content: Schema.optionalKey(Schema.Array(Schema.String).annotate({ default: [] })), + id: Schema.String, + summary: Schema.optionalKey(Schema.Array(Schema.String).annotate({ default: [] })), + type: Schema.Literal("reasoning").annotate({ title: "ReasoningThreadItemType" }), + }).annotate({ title: "ReasoningThreadItem" }), + Schema.Struct({ + aggregatedOutput: Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + description: "The command's output, aggregated from stdout and stderr.", + }), + Schema.Null, + ]), + ), + command: Schema.String.annotate({ description: "The command to be executed." }), + commandActions: Schema.Array(V2ThreadStartedNotification__CommandAction).annotate({ + description: + "A best-effort parsing of the command to understand the action(s) it will perform. This returns a list of CommandAction objects because a single shell command may be composed of many commands piped together.", + }), + cwd: Schema.String.annotate({ description: "The command's working directory." }), + durationMs: Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ + description: "The duration of the command execution in milliseconds.", + format: "int64", + }).check(Schema.isInt()), + Schema.Null, + ]), + ), + exitCode: Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ + description: "The command's exit code.", + format: "int32", + }).check(Schema.isInt()), + Schema.Null, + ]), + ), + id: Schema.String, + processId: Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + description: "Identifier for the underlying PTY process (when available).", + }), + Schema.Null, + ]), + ), + source: Schema.optionalKey( + Schema.Literals([ + "agent", + "userShell", + "unifiedExecStartup", + "unifiedExecInteraction", + ]).annotate({ default: "agent" }), + ), + status: V2ThreadStartedNotification__CommandExecutionStatus, + type: Schema.Literal("commandExecution").annotate({ + title: "CommandExecutionThreadItemType", + }), + }).annotate({ title: "CommandExecutionThreadItem" }), + Schema.Struct({ + changes: Schema.Array(V2ThreadStartedNotification__FileUpdateChange), + id: Schema.String, + status: V2ThreadStartedNotification__PatchApplyStatus, + type: Schema.Literal("fileChange").annotate({ title: "FileChangeThreadItemType" }), + }).annotate({ title: "FileChangeThreadItem" }), + Schema.Struct({ + arguments: Schema.Unknown, + durationMs: Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ + description: "The duration of the MCP tool call in milliseconds.", + format: "int64", + }).check(Schema.isInt()), + Schema.Null, + ]), + ), + error: Schema.optionalKey( + Schema.Union([V2ThreadStartedNotification__McpToolCallError, Schema.Null]), + ), + id: Schema.String, + result: Schema.optionalKey( + Schema.Union([V2ThreadStartedNotification__McpToolCallResult, Schema.Null]), + ), + server: Schema.String, + status: V2ThreadStartedNotification__McpToolCallStatus, + tool: Schema.String, + type: Schema.Literal("mcpToolCall").annotate({ title: "McpToolCallThreadItemType" }), + }).annotate({ title: "McpToolCallThreadItem" }), + Schema.Struct({ + arguments: Schema.Unknown, + contentItems: Schema.optionalKey( + Schema.Union([ + Schema.Array(V2ThreadStartedNotification__DynamicToolCallOutputContentItem), + Schema.Null, + ]), + ), + durationMs: Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ + description: "The duration of the dynamic tool call in milliseconds.", + format: "int64", + }).check(Schema.isInt()), + Schema.Null, + ]), + ), + id: Schema.String, + status: V2ThreadStartedNotification__DynamicToolCallStatus, + success: Schema.optionalKey(Schema.Union([Schema.Boolean, Schema.Null])), + tool: Schema.String, + type: Schema.Literal("dynamicToolCall").annotate({ title: "DynamicToolCallThreadItemType" }), + }).annotate({ title: "DynamicToolCallThreadItem" }), + Schema.Struct({ + agentsStates: Schema.Record( + Schema.String, + V2ThreadStartedNotification__CollabAgentState, + ).annotate({ description: "Last known status of the target agents, when available." }), + id: Schema.String.annotate({ description: "Unique identifier for this collab tool call." }), + model: Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + description: "Model requested for the spawned agent, when applicable.", + }), + Schema.Null, + ]), + ), + prompt: Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + description: "Prompt text sent as part of the collab tool call, when available.", + }), + Schema.Null, + ]), + ), + reasoningEffort: Schema.optionalKey( + Schema.Union([V2ThreadStartedNotification__ReasoningEffort, Schema.Null]).annotate({ + description: "Reasoning effort requested for the spawned agent, when applicable.", + }), + ), + receiverThreadIds: Schema.Array(Schema.String).annotate({ + description: + "Thread ID of the receiving agent, when applicable. In case of spawn operation, this corresponds to the newly spawned agent.", + }), + senderThreadId: Schema.String.annotate({ + description: "Thread ID of the agent issuing the collab request.", + }), + status: Schema.Literals(["inProgress", "completed", "failed"]).annotate({ + description: "Current status of the collab tool call.", + }), + tool: Schema.Literals([ + "spawnAgent", + "sendInput", + "resumeAgent", + "wait", + "closeAgent", + ]).annotate({ description: "Name of the collab tool that was invoked." }), + type: Schema.Literal("collabAgentToolCall").annotate({ + title: "CollabAgentToolCallThreadItemType", + }), + }).annotate({ title: "CollabAgentToolCallThreadItem" }), + Schema.Struct({ + action: Schema.optionalKey( + Schema.Union([V2ThreadStartedNotification__WebSearchAction, Schema.Null]), + ), + id: Schema.String, + query: Schema.String, + type: Schema.Literal("webSearch").annotate({ title: "WebSearchThreadItemType" }), + }).annotate({ title: "WebSearchThreadItem" }), + Schema.Struct({ + id: Schema.String, + path: Schema.String, + type: Schema.Literal("imageView").annotate({ title: "ImageViewThreadItemType" }), + }).annotate({ title: "ImageViewThreadItem" }), + Schema.Struct({ + id: Schema.String, + result: Schema.String, + revisedPrompt: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + savedPath: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + status: Schema.String, + type: Schema.Literal("imageGeneration").annotate({ title: "ImageGenerationThreadItemType" }), + }).annotate({ title: "ImageGenerationThreadItem" }), + Schema.Struct({ + id: Schema.String, + review: Schema.String, + type: Schema.Literal("enteredReviewMode").annotate({ + title: "EnteredReviewModeThreadItemType", + }), + }).annotate({ title: "EnteredReviewModeThreadItem" }), + Schema.Struct({ + id: Schema.String, + review: Schema.String, + type: Schema.Literal("exitedReviewMode").annotate({ + title: "ExitedReviewModeThreadItemType", + }), + }).annotate({ title: "ExitedReviewModeThreadItem" }), + Schema.Struct({ + id: Schema.String, + type: Schema.Literal("contextCompaction").annotate({ + title: "ContextCompactionThreadItemType", + }), + }).annotate({ title: "ContextCompactionThreadItem" }), + ], + { mode: "oneOf" }, +); + +export type V2ThreadStartResponse__TurnError = { + readonly additionalDetails?: string | null; + readonly codexErrorInfo?: V2ThreadStartResponse__CodexErrorInfo | null; + readonly message: string; +}; +export const V2ThreadStartResponse__TurnError = Schema.Struct({ + additionalDetails: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + codexErrorInfo: Schema.optionalKey( + Schema.Union([V2ThreadStartResponse__CodexErrorInfo, Schema.Null]), + ), + message: Schema.String, +}); + +export type V2ThreadStartResponse__ThreadItem = + | { + readonly content: ReadonlyArray; + readonly id: string; + readonly type: "userMessage"; + } + | { + readonly fragments: ReadonlyArray; + readonly id: string; + readonly type: "hookPrompt"; + } + | { + readonly id: string; + readonly memoryCitation?: V2ThreadStartResponse__MemoryCitation | null; + readonly phase?: V2ThreadStartResponse__MessagePhase | null; + readonly text: string; + readonly type: "agentMessage"; + } + | { readonly id: string; readonly text: string; readonly type: "plan" } + | { + readonly content?: ReadonlyArray; + readonly id: string; + readonly summary?: ReadonlyArray; + readonly type: "reasoning"; + } + | { + readonly aggregatedOutput?: string | null; + readonly command: string; + readonly commandActions: ReadonlyArray; + readonly cwd: string; + readonly durationMs?: number | null; + readonly exitCode?: number | null; + readonly id: string; + readonly processId?: string | null; + readonly source?: "agent" | "userShell" | "unifiedExecStartup" | "unifiedExecInteraction"; + readonly status: V2ThreadStartResponse__CommandExecutionStatus; + readonly type: "commandExecution"; + } + | { + readonly changes: ReadonlyArray; + readonly id: string; + readonly status: V2ThreadStartResponse__PatchApplyStatus; + readonly type: "fileChange"; + } + | { + readonly arguments: unknown; + readonly durationMs?: number | null; + readonly error?: V2ThreadStartResponse__McpToolCallError | null; + readonly id: string; + readonly result?: V2ThreadStartResponse__McpToolCallResult | null; + readonly server: string; + readonly status: V2ThreadStartResponse__McpToolCallStatus; + readonly tool: string; + readonly type: "mcpToolCall"; + } + | { + readonly arguments: unknown; + readonly contentItems?: ReadonlyArray | null; + readonly durationMs?: number | null; + readonly id: string; + readonly status: V2ThreadStartResponse__DynamicToolCallStatus; + readonly success?: boolean | null; + readonly tool: string; + readonly type: "dynamicToolCall"; + } + | { + readonly agentsStates: { readonly [x: string]: V2ThreadStartResponse__CollabAgentState }; + readonly id: string; + readonly model?: string | null; + readonly prompt?: string | null; + readonly reasoningEffort?: V2ThreadStartResponse__ReasoningEffort | null; + readonly receiverThreadIds: ReadonlyArray; + readonly senderThreadId: string; + readonly status: "inProgress" | "completed" | "failed"; + readonly tool: "spawnAgent" | "sendInput" | "resumeAgent" | "wait" | "closeAgent"; + readonly type: "collabAgentToolCall"; + } + | { + readonly action?: V2ThreadStartResponse__WebSearchAction | null; + readonly id: string; + readonly query: string; + readonly type: "webSearch"; + } + | { readonly id: string; readonly path: string; readonly type: "imageView" } + | { + readonly id: string; + readonly result: string; + readonly revisedPrompt?: string | null; + readonly savedPath?: string | null; + readonly status: string; + readonly type: "imageGeneration"; + } + | { readonly id: string; readonly review: string; readonly type: "enteredReviewMode" } + | { readonly id: string; readonly review: string; readonly type: "exitedReviewMode" } + | { readonly id: string; readonly type: "contextCompaction" }; +export const V2ThreadStartResponse__ThreadItem = Schema.Union( + [ + Schema.Struct({ + content: Schema.Array(V2ThreadStartResponse__UserInput), + id: Schema.String, + type: Schema.Literal("userMessage").annotate({ title: "UserMessageThreadItemType" }), + }).annotate({ title: "UserMessageThreadItem" }), + Schema.Struct({ + fragments: Schema.Array(V2ThreadStartResponse__HookPromptFragment), + id: Schema.String, + type: Schema.Literal("hookPrompt").annotate({ title: "HookPromptThreadItemType" }), + }).annotate({ title: "HookPromptThreadItem" }), + Schema.Struct({ + id: Schema.String, + memoryCitation: Schema.optionalKey( + Schema.Union([V2ThreadStartResponse__MemoryCitation, Schema.Null]), + ), + phase: Schema.optionalKey(Schema.Union([V2ThreadStartResponse__MessagePhase, Schema.Null])), + text: Schema.String, + type: Schema.Literal("agentMessage").annotate({ title: "AgentMessageThreadItemType" }), + }).annotate({ title: "AgentMessageThreadItem" }), + Schema.Struct({ + id: Schema.String, + text: Schema.String, + type: Schema.Literal("plan").annotate({ title: "PlanThreadItemType" }), + }).annotate({ + title: "PlanThreadItem", + description: + "EXPERIMENTAL - proposed plan item content. The completed plan item is authoritative and may not match the concatenation of `PlanDelta` text.", + }), + Schema.Struct({ + content: Schema.optionalKey(Schema.Array(Schema.String).annotate({ default: [] })), + id: Schema.String, + summary: Schema.optionalKey(Schema.Array(Schema.String).annotate({ default: [] })), + type: Schema.Literal("reasoning").annotate({ title: "ReasoningThreadItemType" }), + }).annotate({ title: "ReasoningThreadItem" }), + Schema.Struct({ + aggregatedOutput: Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + description: "The command's output, aggregated from stdout and stderr.", + }), + Schema.Null, + ]), + ), + command: Schema.String.annotate({ description: "The command to be executed." }), + commandActions: Schema.Array(V2ThreadStartResponse__CommandAction).annotate({ + description: + "A best-effort parsing of the command to understand the action(s) it will perform. This returns a list of CommandAction objects because a single shell command may be composed of many commands piped together.", + }), + cwd: Schema.String.annotate({ description: "The command's working directory." }), + durationMs: Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ + description: "The duration of the command execution in milliseconds.", + format: "int64", + }).check(Schema.isInt()), + Schema.Null, + ]), + ), + exitCode: Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ + description: "The command's exit code.", + format: "int32", + }).check(Schema.isInt()), + Schema.Null, + ]), + ), + id: Schema.String, + processId: Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + description: "Identifier for the underlying PTY process (when available).", + }), + Schema.Null, + ]), + ), + source: Schema.optionalKey( + Schema.Literals([ + "agent", + "userShell", + "unifiedExecStartup", + "unifiedExecInteraction", + ]).annotate({ default: "agent" }), + ), + status: V2ThreadStartResponse__CommandExecutionStatus, + type: Schema.Literal("commandExecution").annotate({ + title: "CommandExecutionThreadItemType", + }), + }).annotate({ title: "CommandExecutionThreadItem" }), + Schema.Struct({ + changes: Schema.Array(V2ThreadStartResponse__FileUpdateChange), + id: Schema.String, + status: V2ThreadStartResponse__PatchApplyStatus, + type: Schema.Literal("fileChange").annotate({ title: "FileChangeThreadItemType" }), + }).annotate({ title: "FileChangeThreadItem" }), + Schema.Struct({ + arguments: Schema.Unknown, + durationMs: Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ + description: "The duration of the MCP tool call in milliseconds.", + format: "int64", + }).check(Schema.isInt()), + Schema.Null, + ]), + ), + error: Schema.optionalKey( + Schema.Union([V2ThreadStartResponse__McpToolCallError, Schema.Null]), + ), + id: Schema.String, + result: Schema.optionalKey( + Schema.Union([V2ThreadStartResponse__McpToolCallResult, Schema.Null]), + ), + server: Schema.String, + status: V2ThreadStartResponse__McpToolCallStatus, + tool: Schema.String, + type: Schema.Literal("mcpToolCall").annotate({ title: "McpToolCallThreadItemType" }), + }).annotate({ title: "McpToolCallThreadItem" }), + Schema.Struct({ + arguments: Schema.Unknown, + contentItems: Schema.optionalKey( + Schema.Union([ + Schema.Array(V2ThreadStartResponse__DynamicToolCallOutputContentItem), + Schema.Null, + ]), + ), + durationMs: Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ + description: "The duration of the dynamic tool call in milliseconds.", + format: "int64", + }).check(Schema.isInt()), + Schema.Null, + ]), + ), + id: Schema.String, + status: V2ThreadStartResponse__DynamicToolCallStatus, + success: Schema.optionalKey(Schema.Union([Schema.Boolean, Schema.Null])), + tool: Schema.String, + type: Schema.Literal("dynamicToolCall").annotate({ title: "DynamicToolCallThreadItemType" }), + }).annotate({ title: "DynamicToolCallThreadItem" }), + Schema.Struct({ + agentsStates: Schema.Record(Schema.String, V2ThreadStartResponse__CollabAgentState).annotate({ + description: "Last known status of the target agents, when available.", + }), + id: Schema.String.annotate({ description: "Unique identifier for this collab tool call." }), + model: Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + description: "Model requested for the spawned agent, when applicable.", + }), + Schema.Null, + ]), + ), + prompt: Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + description: "Prompt text sent as part of the collab tool call, when available.", + }), + Schema.Null, + ]), + ), + reasoningEffort: Schema.optionalKey( + Schema.Union([V2ThreadStartResponse__ReasoningEffort, Schema.Null]).annotate({ + description: "Reasoning effort requested for the spawned agent, when applicable.", + }), + ), + receiverThreadIds: Schema.Array(Schema.String).annotate({ + description: + "Thread ID of the receiving agent, when applicable. In case of spawn operation, this corresponds to the newly spawned agent.", + }), + senderThreadId: Schema.String.annotate({ + description: "Thread ID of the agent issuing the collab request.", + }), + status: Schema.Literals(["inProgress", "completed", "failed"]).annotate({ + description: "Current status of the collab tool call.", + }), + tool: Schema.Literals([ + "spawnAgent", + "sendInput", + "resumeAgent", + "wait", + "closeAgent", + ]).annotate({ description: "Name of the collab tool that was invoked." }), + type: Schema.Literal("collabAgentToolCall").annotate({ + title: "CollabAgentToolCallThreadItemType", + }), + }).annotate({ title: "CollabAgentToolCallThreadItem" }), + Schema.Struct({ + action: Schema.optionalKey( + Schema.Union([V2ThreadStartResponse__WebSearchAction, Schema.Null]), + ), + id: Schema.String, + query: Schema.String, + type: Schema.Literal("webSearch").annotate({ title: "WebSearchThreadItemType" }), + }).annotate({ title: "WebSearchThreadItem" }), + Schema.Struct({ + id: Schema.String, + path: Schema.String, + type: Schema.Literal("imageView").annotate({ title: "ImageViewThreadItemType" }), + }).annotate({ title: "ImageViewThreadItem" }), + Schema.Struct({ + id: Schema.String, + result: Schema.String, + revisedPrompt: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + savedPath: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + status: Schema.String, + type: Schema.Literal("imageGeneration").annotate({ title: "ImageGenerationThreadItemType" }), + }).annotate({ title: "ImageGenerationThreadItem" }), + Schema.Struct({ + id: Schema.String, + review: Schema.String, + type: Schema.Literal("enteredReviewMode").annotate({ + title: "EnteredReviewModeThreadItemType", + }), + }).annotate({ title: "EnteredReviewModeThreadItem" }), + Schema.Struct({ + id: Schema.String, + review: Schema.String, + type: Schema.Literal("exitedReviewMode").annotate({ + title: "ExitedReviewModeThreadItemType", + }), + }).annotate({ title: "ExitedReviewModeThreadItem" }), + Schema.Struct({ + id: Schema.String, + type: Schema.Literal("contextCompaction").annotate({ + title: "ContextCompactionThreadItemType", + }), + }).annotate({ title: "ContextCompactionThreadItem" }), + ], + { mode: "oneOf" }, +); + +export type V2ThreadUnarchiveResponse__TurnError = { + readonly additionalDetails?: string | null; + readonly codexErrorInfo?: V2ThreadUnarchiveResponse__CodexErrorInfo | null; + readonly message: string; +}; +export const V2ThreadUnarchiveResponse__TurnError = Schema.Struct({ + additionalDetails: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + codexErrorInfo: Schema.optionalKey( + Schema.Union([V2ThreadUnarchiveResponse__CodexErrorInfo, Schema.Null]), + ), + message: Schema.String, +}); + +export type V2ThreadUnarchiveResponse__ThreadItem = + | { + readonly content: ReadonlyArray; + readonly id: string; + readonly type: "userMessage"; + } + | { + readonly fragments: ReadonlyArray; + readonly id: string; + readonly type: "hookPrompt"; + } + | { + readonly id: string; + readonly memoryCitation?: V2ThreadUnarchiveResponse__MemoryCitation | null; + readonly phase?: V2ThreadUnarchiveResponse__MessagePhase | null; + readonly text: string; + readonly type: "agentMessage"; + } + | { readonly id: string; readonly text: string; readonly type: "plan" } + | { + readonly content?: ReadonlyArray; + readonly id: string; + readonly summary?: ReadonlyArray; + readonly type: "reasoning"; + } + | { + readonly aggregatedOutput?: string | null; + readonly command: string; + readonly commandActions: ReadonlyArray; + readonly cwd: string; + readonly durationMs?: number | null; + readonly exitCode?: number | null; + readonly id: string; + readonly processId?: string | null; + readonly source?: "agent" | "userShell" | "unifiedExecStartup" | "unifiedExecInteraction"; + readonly status: V2ThreadUnarchiveResponse__CommandExecutionStatus; + readonly type: "commandExecution"; + } + | { + readonly changes: ReadonlyArray; + readonly id: string; + readonly status: V2ThreadUnarchiveResponse__PatchApplyStatus; + readonly type: "fileChange"; + } + | { + readonly arguments: unknown; + readonly durationMs?: number | null; + readonly error?: V2ThreadUnarchiveResponse__McpToolCallError | null; + readonly id: string; + readonly result?: V2ThreadUnarchiveResponse__McpToolCallResult | null; + readonly server: string; + readonly status: V2ThreadUnarchiveResponse__McpToolCallStatus; + readonly tool: string; + readonly type: "mcpToolCall"; + } + | { + readonly arguments: unknown; + readonly contentItems?: ReadonlyArray | null; + readonly durationMs?: number | null; + readonly id: string; + readonly status: V2ThreadUnarchiveResponse__DynamicToolCallStatus; + readonly success?: boolean | null; + readonly tool: string; + readonly type: "dynamicToolCall"; + } + | { + readonly agentsStates: { readonly [x: string]: V2ThreadUnarchiveResponse__CollabAgentState }; + readonly id: string; + readonly model?: string | null; + readonly prompt?: string | null; + readonly reasoningEffort?: V2ThreadUnarchiveResponse__ReasoningEffort | null; + readonly receiverThreadIds: ReadonlyArray; + readonly senderThreadId: string; + readonly status: "inProgress" | "completed" | "failed"; + readonly tool: "spawnAgent" | "sendInput" | "resumeAgent" | "wait" | "closeAgent"; + readonly type: "collabAgentToolCall"; + } + | { + readonly action?: V2ThreadUnarchiveResponse__WebSearchAction | null; + readonly id: string; + readonly query: string; + readonly type: "webSearch"; + } + | { readonly id: string; readonly path: string; readonly type: "imageView" } + | { + readonly id: string; + readonly result: string; + readonly revisedPrompt?: string | null; + readonly savedPath?: string | null; + readonly status: string; + readonly type: "imageGeneration"; + } + | { readonly id: string; readonly review: string; readonly type: "enteredReviewMode" } + | { readonly id: string; readonly review: string; readonly type: "exitedReviewMode" } + | { readonly id: string; readonly type: "contextCompaction" }; +export const V2ThreadUnarchiveResponse__ThreadItem = Schema.Union( + [ + Schema.Struct({ + content: Schema.Array(V2ThreadUnarchiveResponse__UserInput), + id: Schema.String, + type: Schema.Literal("userMessage").annotate({ title: "UserMessageThreadItemType" }), + }).annotate({ title: "UserMessageThreadItem" }), + Schema.Struct({ + fragments: Schema.Array(V2ThreadUnarchiveResponse__HookPromptFragment), + id: Schema.String, + type: Schema.Literal("hookPrompt").annotate({ title: "HookPromptThreadItemType" }), + }).annotate({ title: "HookPromptThreadItem" }), + Schema.Struct({ + id: Schema.String, + memoryCitation: Schema.optionalKey( + Schema.Union([V2ThreadUnarchiveResponse__MemoryCitation, Schema.Null]), + ), + phase: Schema.optionalKey( + Schema.Union([V2ThreadUnarchiveResponse__MessagePhase, Schema.Null]), + ), + text: Schema.String, + type: Schema.Literal("agentMessage").annotate({ title: "AgentMessageThreadItemType" }), + }).annotate({ title: "AgentMessageThreadItem" }), + Schema.Struct({ + id: Schema.String, + text: Schema.String, + type: Schema.Literal("plan").annotate({ title: "PlanThreadItemType" }), + }).annotate({ + title: "PlanThreadItem", + description: + "EXPERIMENTAL - proposed plan item content. The completed plan item is authoritative and may not match the concatenation of `PlanDelta` text.", + }), + Schema.Struct({ + content: Schema.optionalKey(Schema.Array(Schema.String).annotate({ default: [] })), + id: Schema.String, + summary: Schema.optionalKey(Schema.Array(Schema.String).annotate({ default: [] })), + type: Schema.Literal("reasoning").annotate({ title: "ReasoningThreadItemType" }), + }).annotate({ title: "ReasoningThreadItem" }), + Schema.Struct({ + aggregatedOutput: Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + description: "The command's output, aggregated from stdout and stderr.", + }), + Schema.Null, + ]), + ), + command: Schema.String.annotate({ description: "The command to be executed." }), + commandActions: Schema.Array(V2ThreadUnarchiveResponse__CommandAction).annotate({ + description: + "A best-effort parsing of the command to understand the action(s) it will perform. This returns a list of CommandAction objects because a single shell command may be composed of many commands piped together.", + }), + cwd: Schema.String.annotate({ description: "The command's working directory." }), + durationMs: Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ + description: "The duration of the command execution in milliseconds.", + format: "int64", + }).check(Schema.isInt()), + Schema.Null, + ]), + ), + exitCode: Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ + description: "The command's exit code.", + format: "int32", + }).check(Schema.isInt()), + Schema.Null, + ]), + ), + id: Schema.String, + processId: Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + description: "Identifier for the underlying PTY process (when available).", + }), + Schema.Null, + ]), + ), + source: Schema.optionalKey( + Schema.Literals([ + "agent", + "userShell", + "unifiedExecStartup", + "unifiedExecInteraction", + ]).annotate({ default: "agent" }), + ), + status: V2ThreadUnarchiveResponse__CommandExecutionStatus, + type: Schema.Literal("commandExecution").annotate({ + title: "CommandExecutionThreadItemType", + }), + }).annotate({ title: "CommandExecutionThreadItem" }), + Schema.Struct({ + changes: Schema.Array(V2ThreadUnarchiveResponse__FileUpdateChange), + id: Schema.String, + status: V2ThreadUnarchiveResponse__PatchApplyStatus, + type: Schema.Literal("fileChange").annotate({ title: "FileChangeThreadItemType" }), + }).annotate({ title: "FileChangeThreadItem" }), + Schema.Struct({ + arguments: Schema.Unknown, + durationMs: Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ + description: "The duration of the MCP tool call in milliseconds.", + format: "int64", + }).check(Schema.isInt()), + Schema.Null, + ]), + ), + error: Schema.optionalKey( + Schema.Union([V2ThreadUnarchiveResponse__McpToolCallError, Schema.Null]), + ), + id: Schema.String, + result: Schema.optionalKey( + Schema.Union([V2ThreadUnarchiveResponse__McpToolCallResult, Schema.Null]), + ), + server: Schema.String, + status: V2ThreadUnarchiveResponse__McpToolCallStatus, + tool: Schema.String, + type: Schema.Literal("mcpToolCall").annotate({ title: "McpToolCallThreadItemType" }), + }).annotate({ title: "McpToolCallThreadItem" }), + Schema.Struct({ + arguments: Schema.Unknown, + contentItems: Schema.optionalKey( + Schema.Union([ + Schema.Array(V2ThreadUnarchiveResponse__DynamicToolCallOutputContentItem), + Schema.Null, + ]), + ), + durationMs: Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ + description: "The duration of the dynamic tool call in milliseconds.", + format: "int64", + }).check(Schema.isInt()), + Schema.Null, + ]), + ), + id: Schema.String, + status: V2ThreadUnarchiveResponse__DynamicToolCallStatus, + success: Schema.optionalKey(Schema.Union([Schema.Boolean, Schema.Null])), + tool: Schema.String, + type: Schema.Literal("dynamicToolCall").annotate({ title: "DynamicToolCallThreadItemType" }), + }).annotate({ title: "DynamicToolCallThreadItem" }), + Schema.Struct({ + agentsStates: Schema.Record( + Schema.String, + V2ThreadUnarchiveResponse__CollabAgentState, + ).annotate({ description: "Last known status of the target agents, when available." }), + id: Schema.String.annotate({ description: "Unique identifier for this collab tool call." }), + model: Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + description: "Model requested for the spawned agent, when applicable.", + }), + Schema.Null, + ]), + ), + prompt: Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + description: "Prompt text sent as part of the collab tool call, when available.", + }), + Schema.Null, + ]), + ), + reasoningEffort: Schema.optionalKey( + Schema.Union([V2ThreadUnarchiveResponse__ReasoningEffort, Schema.Null]).annotate({ + description: "Reasoning effort requested for the spawned agent, when applicable.", + }), + ), + receiverThreadIds: Schema.Array(Schema.String).annotate({ + description: + "Thread ID of the receiving agent, when applicable. In case of spawn operation, this corresponds to the newly spawned agent.", + }), + senderThreadId: Schema.String.annotate({ + description: "Thread ID of the agent issuing the collab request.", + }), + status: Schema.Literals(["inProgress", "completed", "failed"]).annotate({ + description: "Current status of the collab tool call.", + }), + tool: Schema.Literals([ + "spawnAgent", + "sendInput", + "resumeAgent", + "wait", + "closeAgent", + ]).annotate({ description: "Name of the collab tool that was invoked." }), + type: Schema.Literal("collabAgentToolCall").annotate({ + title: "CollabAgentToolCallThreadItemType", + }), + }).annotate({ title: "CollabAgentToolCallThreadItem" }), + Schema.Struct({ + action: Schema.optionalKey( + Schema.Union([V2ThreadUnarchiveResponse__WebSearchAction, Schema.Null]), + ), + id: Schema.String, + query: Schema.String, + type: Schema.Literal("webSearch").annotate({ title: "WebSearchThreadItemType" }), + }).annotate({ title: "WebSearchThreadItem" }), + Schema.Struct({ + id: Schema.String, + path: Schema.String, + type: Schema.Literal("imageView").annotate({ title: "ImageViewThreadItemType" }), + }).annotate({ title: "ImageViewThreadItem" }), + Schema.Struct({ + id: Schema.String, + result: Schema.String, + revisedPrompt: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + savedPath: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + status: Schema.String, + type: Schema.Literal("imageGeneration").annotate({ title: "ImageGenerationThreadItemType" }), + }).annotate({ title: "ImageGenerationThreadItem" }), + Schema.Struct({ + id: Schema.String, + review: Schema.String, + type: Schema.Literal("enteredReviewMode").annotate({ + title: "EnteredReviewModeThreadItemType", + }), + }).annotate({ title: "EnteredReviewModeThreadItem" }), + Schema.Struct({ + id: Schema.String, + review: Schema.String, + type: Schema.Literal("exitedReviewMode").annotate({ + title: "ExitedReviewModeThreadItemType", + }), + }).annotate({ title: "ExitedReviewModeThreadItem" }), + Schema.Struct({ + id: Schema.String, + type: Schema.Literal("contextCompaction").annotate({ + title: "ContextCompactionThreadItemType", + }), + }).annotate({ title: "ContextCompactionThreadItem" }), + ], + { mode: "oneOf" }, +); + +export type V2TurnCompletedNotification__TurnError = { + readonly additionalDetails?: string | null; + readonly codexErrorInfo?: V2TurnCompletedNotification__CodexErrorInfo | null; + readonly message: string; +}; +export const V2TurnCompletedNotification__TurnError = Schema.Struct({ + additionalDetails: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + codexErrorInfo: Schema.optionalKey( + Schema.Union([V2TurnCompletedNotification__CodexErrorInfo, Schema.Null]), + ), + message: Schema.String, +}); + +export type V2TurnCompletedNotification__ThreadItem = + | { + readonly content: ReadonlyArray; + readonly id: string; + readonly type: "userMessage"; + } + | { + readonly fragments: ReadonlyArray; + readonly id: string; + readonly type: "hookPrompt"; + } + | { + readonly id: string; + readonly memoryCitation?: V2TurnCompletedNotification__MemoryCitation | null; + readonly phase?: V2TurnCompletedNotification__MessagePhase | null; + readonly text: string; + readonly type: "agentMessage"; + } + | { readonly id: string; readonly text: string; readonly type: "plan" } + | { + readonly content?: ReadonlyArray; + readonly id: string; + readonly summary?: ReadonlyArray; + readonly type: "reasoning"; + } + | { + readonly aggregatedOutput?: string | null; + readonly command: string; + readonly commandActions: ReadonlyArray; + readonly cwd: string; + readonly durationMs?: number | null; + readonly exitCode?: number | null; + readonly id: string; + readonly processId?: string | null; + readonly source?: "agent" | "userShell" | "unifiedExecStartup" | "unifiedExecInteraction"; + readonly status: V2TurnCompletedNotification__CommandExecutionStatus; + readonly type: "commandExecution"; + } + | { + readonly changes: ReadonlyArray; + readonly id: string; + readonly status: V2TurnCompletedNotification__PatchApplyStatus; + readonly type: "fileChange"; + } + | { + readonly arguments: unknown; + readonly durationMs?: number | null; + readonly error?: V2TurnCompletedNotification__McpToolCallError | null; + readonly id: string; + readonly result?: V2TurnCompletedNotification__McpToolCallResult | null; + readonly server: string; + readonly status: V2TurnCompletedNotification__McpToolCallStatus; + readonly tool: string; + readonly type: "mcpToolCall"; + } + | { + readonly arguments: unknown; + readonly contentItems?: ReadonlyArray | null; + readonly durationMs?: number | null; + readonly id: string; + readonly status: V2TurnCompletedNotification__DynamicToolCallStatus; + readonly success?: boolean | null; + readonly tool: string; + readonly type: "dynamicToolCall"; + } + | { + readonly agentsStates: { + readonly [x: string]: V2TurnCompletedNotification__CollabAgentState; + }; + readonly id: string; + readonly model?: string | null; + readonly prompt?: string | null; + readonly reasoningEffort?: V2TurnCompletedNotification__ReasoningEffort | null; + readonly receiverThreadIds: ReadonlyArray; + readonly senderThreadId: string; + readonly status: "inProgress" | "completed" | "failed"; + readonly tool: "spawnAgent" | "sendInput" | "resumeAgent" | "wait" | "closeAgent"; + readonly type: "collabAgentToolCall"; + } + | { + readonly action?: V2TurnCompletedNotification__WebSearchAction | null; + readonly id: string; + readonly query: string; + readonly type: "webSearch"; + } + | { readonly id: string; readonly path: string; readonly type: "imageView" } + | { + readonly id: string; + readonly result: string; + readonly revisedPrompt?: string | null; + readonly savedPath?: string | null; + readonly status: string; + readonly type: "imageGeneration"; + } + | { readonly id: string; readonly review: string; readonly type: "enteredReviewMode" } + | { readonly id: string; readonly review: string; readonly type: "exitedReviewMode" } + | { readonly id: string; readonly type: "contextCompaction" }; +export const V2TurnCompletedNotification__ThreadItem = Schema.Union( + [ + Schema.Struct({ + content: Schema.Array(V2TurnCompletedNotification__UserInput), + id: Schema.String, + type: Schema.Literal("userMessage").annotate({ title: "UserMessageThreadItemType" }), + }).annotate({ title: "UserMessageThreadItem" }), + Schema.Struct({ + fragments: Schema.Array(V2TurnCompletedNotification__HookPromptFragment), + id: Schema.String, + type: Schema.Literal("hookPrompt").annotate({ title: "HookPromptThreadItemType" }), + }).annotate({ title: "HookPromptThreadItem" }), + Schema.Struct({ + id: Schema.String, + memoryCitation: Schema.optionalKey( + Schema.Union([V2TurnCompletedNotification__MemoryCitation, Schema.Null]), + ), + phase: Schema.optionalKey( + Schema.Union([V2TurnCompletedNotification__MessagePhase, Schema.Null]), + ), + text: Schema.String, + type: Schema.Literal("agentMessage").annotate({ title: "AgentMessageThreadItemType" }), + }).annotate({ title: "AgentMessageThreadItem" }), + Schema.Struct({ + id: Schema.String, + text: Schema.String, + type: Schema.Literal("plan").annotate({ title: "PlanThreadItemType" }), + }).annotate({ + title: "PlanThreadItem", + description: + "EXPERIMENTAL - proposed plan item content. The completed plan item is authoritative and may not match the concatenation of `PlanDelta` text.", + }), + Schema.Struct({ + content: Schema.optionalKey(Schema.Array(Schema.String).annotate({ default: [] })), + id: Schema.String, + summary: Schema.optionalKey(Schema.Array(Schema.String).annotate({ default: [] })), + type: Schema.Literal("reasoning").annotate({ title: "ReasoningThreadItemType" }), + }).annotate({ title: "ReasoningThreadItem" }), + Schema.Struct({ + aggregatedOutput: Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + description: "The command's output, aggregated from stdout and stderr.", + }), + Schema.Null, + ]), + ), + command: Schema.String.annotate({ description: "The command to be executed." }), + commandActions: Schema.Array(V2TurnCompletedNotification__CommandAction).annotate({ + description: + "A best-effort parsing of the command to understand the action(s) it will perform. This returns a list of CommandAction objects because a single shell command may be composed of many commands piped together.", + }), + cwd: Schema.String.annotate({ description: "The command's working directory." }), + durationMs: Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ + description: "The duration of the command execution in milliseconds.", + format: "int64", + }).check(Schema.isInt()), + Schema.Null, + ]), + ), + exitCode: Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ + description: "The command's exit code.", + format: "int32", + }).check(Schema.isInt()), + Schema.Null, + ]), + ), + id: Schema.String, + processId: Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + description: "Identifier for the underlying PTY process (when available).", + }), + Schema.Null, + ]), + ), + source: Schema.optionalKey( + Schema.Literals([ + "agent", + "userShell", + "unifiedExecStartup", + "unifiedExecInteraction", + ]).annotate({ default: "agent" }), + ), + status: V2TurnCompletedNotification__CommandExecutionStatus, + type: Schema.Literal("commandExecution").annotate({ + title: "CommandExecutionThreadItemType", + }), + }).annotate({ title: "CommandExecutionThreadItem" }), + Schema.Struct({ + changes: Schema.Array(V2TurnCompletedNotification__FileUpdateChange), + id: Schema.String, + status: V2TurnCompletedNotification__PatchApplyStatus, + type: Schema.Literal("fileChange").annotate({ title: "FileChangeThreadItemType" }), + }).annotate({ title: "FileChangeThreadItem" }), + Schema.Struct({ + arguments: Schema.Unknown, + durationMs: Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ + description: "The duration of the MCP tool call in milliseconds.", + format: "int64", + }).check(Schema.isInt()), + Schema.Null, + ]), + ), + error: Schema.optionalKey( + Schema.Union([V2TurnCompletedNotification__McpToolCallError, Schema.Null]), + ), + id: Schema.String, + result: Schema.optionalKey( + Schema.Union([V2TurnCompletedNotification__McpToolCallResult, Schema.Null]), + ), + server: Schema.String, + status: V2TurnCompletedNotification__McpToolCallStatus, + tool: Schema.String, + type: Schema.Literal("mcpToolCall").annotate({ title: "McpToolCallThreadItemType" }), + }).annotate({ title: "McpToolCallThreadItem" }), + Schema.Struct({ + arguments: Schema.Unknown, + contentItems: Schema.optionalKey( + Schema.Union([ + Schema.Array(V2TurnCompletedNotification__DynamicToolCallOutputContentItem), + Schema.Null, + ]), + ), + durationMs: Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ + description: "The duration of the dynamic tool call in milliseconds.", + format: "int64", + }).check(Schema.isInt()), + Schema.Null, + ]), + ), + id: Schema.String, + status: V2TurnCompletedNotification__DynamicToolCallStatus, + success: Schema.optionalKey(Schema.Union([Schema.Boolean, Schema.Null])), + tool: Schema.String, + type: Schema.Literal("dynamicToolCall").annotate({ title: "DynamicToolCallThreadItemType" }), + }).annotate({ title: "DynamicToolCallThreadItem" }), + Schema.Struct({ + agentsStates: Schema.Record( + Schema.String, + V2TurnCompletedNotification__CollabAgentState, + ).annotate({ description: "Last known status of the target agents, when available." }), + id: Schema.String.annotate({ description: "Unique identifier for this collab tool call." }), + model: Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + description: "Model requested for the spawned agent, when applicable.", + }), + Schema.Null, + ]), + ), + prompt: Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + description: "Prompt text sent as part of the collab tool call, when available.", + }), + Schema.Null, + ]), + ), + reasoningEffort: Schema.optionalKey( + Schema.Union([V2TurnCompletedNotification__ReasoningEffort, Schema.Null]).annotate({ + description: "Reasoning effort requested for the spawned agent, when applicable.", + }), + ), + receiverThreadIds: Schema.Array(Schema.String).annotate({ + description: + "Thread ID of the receiving agent, when applicable. In case of spawn operation, this corresponds to the newly spawned agent.", + }), + senderThreadId: Schema.String.annotate({ + description: "Thread ID of the agent issuing the collab request.", + }), + status: Schema.Literals(["inProgress", "completed", "failed"]).annotate({ + description: "Current status of the collab tool call.", + }), + tool: Schema.Literals([ + "spawnAgent", + "sendInput", + "resumeAgent", + "wait", + "closeAgent", + ]).annotate({ description: "Name of the collab tool that was invoked." }), + type: Schema.Literal("collabAgentToolCall").annotate({ + title: "CollabAgentToolCallThreadItemType", + }), + }).annotate({ title: "CollabAgentToolCallThreadItem" }), + Schema.Struct({ + action: Schema.optionalKey( + Schema.Union([V2TurnCompletedNotification__WebSearchAction, Schema.Null]), + ), + id: Schema.String, + query: Schema.String, + type: Schema.Literal("webSearch").annotate({ title: "WebSearchThreadItemType" }), + }).annotate({ title: "WebSearchThreadItem" }), + Schema.Struct({ + id: Schema.String, + path: Schema.String, + type: Schema.Literal("imageView").annotate({ title: "ImageViewThreadItemType" }), + }).annotate({ title: "ImageViewThreadItem" }), + Schema.Struct({ + id: Schema.String, + result: Schema.String, + revisedPrompt: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + savedPath: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + status: Schema.String, + type: Schema.Literal("imageGeneration").annotate({ title: "ImageGenerationThreadItemType" }), + }).annotate({ title: "ImageGenerationThreadItem" }), + Schema.Struct({ + id: Schema.String, + review: Schema.String, + type: Schema.Literal("enteredReviewMode").annotate({ + title: "EnteredReviewModeThreadItemType", + }), + }).annotate({ title: "EnteredReviewModeThreadItem" }), + Schema.Struct({ + id: Schema.String, + review: Schema.String, + type: Schema.Literal("exitedReviewMode").annotate({ + title: "ExitedReviewModeThreadItemType", + }), + }).annotate({ title: "ExitedReviewModeThreadItem" }), + Schema.Struct({ + id: Schema.String, + type: Schema.Literal("contextCompaction").annotate({ + title: "ContextCompactionThreadItemType", + }), + }).annotate({ title: "ContextCompactionThreadItem" }), + ], + { mode: "oneOf" }, +); + +export type V2TurnStartedNotification__TurnError = { + readonly additionalDetails?: string | null; + readonly codexErrorInfo?: V2TurnStartedNotification__CodexErrorInfo | null; + readonly message: string; +}; +export const V2TurnStartedNotification__TurnError = Schema.Struct({ + additionalDetails: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + codexErrorInfo: Schema.optionalKey( + Schema.Union([V2TurnStartedNotification__CodexErrorInfo, Schema.Null]), + ), + message: Schema.String, +}); + +export type V2TurnStartedNotification__ThreadItem = + | { + readonly content: ReadonlyArray; + readonly id: string; + readonly type: "userMessage"; + } + | { + readonly fragments: ReadonlyArray; + readonly id: string; + readonly type: "hookPrompt"; + } + | { + readonly id: string; + readonly memoryCitation?: V2TurnStartedNotification__MemoryCitation | null; + readonly phase?: V2TurnStartedNotification__MessagePhase | null; + readonly text: string; + readonly type: "agentMessage"; + } + | { readonly id: string; readonly text: string; readonly type: "plan" } + | { + readonly content?: ReadonlyArray; + readonly id: string; + readonly summary?: ReadonlyArray; + readonly type: "reasoning"; + } + | { + readonly aggregatedOutput?: string | null; + readonly command: string; + readonly commandActions: ReadonlyArray; + readonly cwd: string; + readonly durationMs?: number | null; + readonly exitCode?: number | null; + readonly id: string; + readonly processId?: string | null; + readonly source?: "agent" | "userShell" | "unifiedExecStartup" | "unifiedExecInteraction"; + readonly status: V2TurnStartedNotification__CommandExecutionStatus; + readonly type: "commandExecution"; + } + | { + readonly changes: ReadonlyArray; + readonly id: string; + readonly status: V2TurnStartedNotification__PatchApplyStatus; + readonly type: "fileChange"; + } + | { + readonly arguments: unknown; + readonly durationMs?: number | null; + readonly error?: V2TurnStartedNotification__McpToolCallError | null; + readonly id: string; + readonly result?: V2TurnStartedNotification__McpToolCallResult | null; + readonly server: string; + readonly status: V2TurnStartedNotification__McpToolCallStatus; + readonly tool: string; + readonly type: "mcpToolCall"; + } + | { + readonly arguments: unknown; + readonly contentItems?: ReadonlyArray | null; + readonly durationMs?: number | null; + readonly id: string; + readonly status: V2TurnStartedNotification__DynamicToolCallStatus; + readonly success?: boolean | null; + readonly tool: string; + readonly type: "dynamicToolCall"; + } + | { + readonly agentsStates: { readonly [x: string]: V2TurnStartedNotification__CollabAgentState }; + readonly id: string; + readonly model?: string | null; + readonly prompt?: string | null; + readonly reasoningEffort?: V2TurnStartedNotification__ReasoningEffort | null; + readonly receiverThreadIds: ReadonlyArray; + readonly senderThreadId: string; + readonly status: "inProgress" | "completed" | "failed"; + readonly tool: "spawnAgent" | "sendInput" | "resumeAgent" | "wait" | "closeAgent"; + readonly type: "collabAgentToolCall"; + } + | { + readonly action?: V2TurnStartedNotification__WebSearchAction | null; + readonly id: string; + readonly query: string; + readonly type: "webSearch"; + } + | { readonly id: string; readonly path: string; readonly type: "imageView" } + | { + readonly id: string; + readonly result: string; + readonly revisedPrompt?: string | null; + readonly savedPath?: string | null; + readonly status: string; + readonly type: "imageGeneration"; + } + | { readonly id: string; readonly review: string; readonly type: "enteredReviewMode" } + | { readonly id: string; readonly review: string; readonly type: "exitedReviewMode" } + | { readonly id: string; readonly type: "contextCompaction" }; +export const V2TurnStartedNotification__ThreadItem = Schema.Union( + [ + Schema.Struct({ + content: Schema.Array(V2TurnStartedNotification__UserInput), + id: Schema.String, + type: Schema.Literal("userMessage").annotate({ title: "UserMessageThreadItemType" }), + }).annotate({ title: "UserMessageThreadItem" }), + Schema.Struct({ + fragments: Schema.Array(V2TurnStartedNotification__HookPromptFragment), + id: Schema.String, + type: Schema.Literal("hookPrompt").annotate({ title: "HookPromptThreadItemType" }), + }).annotate({ title: "HookPromptThreadItem" }), + Schema.Struct({ + id: Schema.String, + memoryCitation: Schema.optionalKey( + Schema.Union([V2TurnStartedNotification__MemoryCitation, Schema.Null]), + ), + phase: Schema.optionalKey( + Schema.Union([V2TurnStartedNotification__MessagePhase, Schema.Null]), + ), + text: Schema.String, + type: Schema.Literal("agentMessage").annotate({ title: "AgentMessageThreadItemType" }), + }).annotate({ title: "AgentMessageThreadItem" }), + Schema.Struct({ + id: Schema.String, + text: Schema.String, + type: Schema.Literal("plan").annotate({ title: "PlanThreadItemType" }), + }).annotate({ + title: "PlanThreadItem", + description: + "EXPERIMENTAL - proposed plan item content. The completed plan item is authoritative and may not match the concatenation of `PlanDelta` text.", + }), + Schema.Struct({ + content: Schema.optionalKey(Schema.Array(Schema.String).annotate({ default: [] })), + id: Schema.String, + summary: Schema.optionalKey(Schema.Array(Schema.String).annotate({ default: [] })), + type: Schema.Literal("reasoning").annotate({ title: "ReasoningThreadItemType" }), + }).annotate({ title: "ReasoningThreadItem" }), + Schema.Struct({ + aggregatedOutput: Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + description: "The command's output, aggregated from stdout and stderr.", + }), + Schema.Null, + ]), + ), + command: Schema.String.annotate({ description: "The command to be executed." }), + commandActions: Schema.Array(V2TurnStartedNotification__CommandAction).annotate({ + description: + "A best-effort parsing of the command to understand the action(s) it will perform. This returns a list of CommandAction objects because a single shell command may be composed of many commands piped together.", + }), + cwd: Schema.String.annotate({ description: "The command's working directory." }), + durationMs: Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ + description: "The duration of the command execution in milliseconds.", + format: "int64", + }).check(Schema.isInt()), + Schema.Null, + ]), + ), + exitCode: Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ + description: "The command's exit code.", + format: "int32", + }).check(Schema.isInt()), + Schema.Null, + ]), + ), + id: Schema.String, + processId: Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + description: "Identifier for the underlying PTY process (when available).", + }), + Schema.Null, + ]), + ), + source: Schema.optionalKey( + Schema.Literals([ + "agent", + "userShell", + "unifiedExecStartup", + "unifiedExecInteraction", + ]).annotate({ default: "agent" }), + ), + status: V2TurnStartedNotification__CommandExecutionStatus, + type: Schema.Literal("commandExecution").annotate({ + title: "CommandExecutionThreadItemType", + }), + }).annotate({ title: "CommandExecutionThreadItem" }), + Schema.Struct({ + changes: Schema.Array(V2TurnStartedNotification__FileUpdateChange), + id: Schema.String, + status: V2TurnStartedNotification__PatchApplyStatus, + type: Schema.Literal("fileChange").annotate({ title: "FileChangeThreadItemType" }), + }).annotate({ title: "FileChangeThreadItem" }), + Schema.Struct({ + arguments: Schema.Unknown, + durationMs: Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ + description: "The duration of the MCP tool call in milliseconds.", + format: "int64", + }).check(Schema.isInt()), + Schema.Null, + ]), + ), + error: Schema.optionalKey( + Schema.Union([V2TurnStartedNotification__McpToolCallError, Schema.Null]), + ), + id: Schema.String, + result: Schema.optionalKey( + Schema.Union([V2TurnStartedNotification__McpToolCallResult, Schema.Null]), + ), + server: Schema.String, + status: V2TurnStartedNotification__McpToolCallStatus, + tool: Schema.String, + type: Schema.Literal("mcpToolCall").annotate({ title: "McpToolCallThreadItemType" }), + }).annotate({ title: "McpToolCallThreadItem" }), + Schema.Struct({ + arguments: Schema.Unknown, + contentItems: Schema.optionalKey( + Schema.Union([ + Schema.Array(V2TurnStartedNotification__DynamicToolCallOutputContentItem), + Schema.Null, + ]), + ), + durationMs: Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ + description: "The duration of the dynamic tool call in milliseconds.", + format: "int64", + }).check(Schema.isInt()), + Schema.Null, + ]), + ), + id: Schema.String, + status: V2TurnStartedNotification__DynamicToolCallStatus, + success: Schema.optionalKey(Schema.Union([Schema.Boolean, Schema.Null])), + tool: Schema.String, + type: Schema.Literal("dynamicToolCall").annotate({ title: "DynamicToolCallThreadItemType" }), + }).annotate({ title: "DynamicToolCallThreadItem" }), + Schema.Struct({ + agentsStates: Schema.Record( + Schema.String, + V2TurnStartedNotification__CollabAgentState, + ).annotate({ description: "Last known status of the target agents, when available." }), + id: Schema.String.annotate({ description: "Unique identifier for this collab tool call." }), + model: Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + description: "Model requested for the spawned agent, when applicable.", + }), + Schema.Null, + ]), + ), + prompt: Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + description: "Prompt text sent as part of the collab tool call, when available.", + }), + Schema.Null, + ]), + ), + reasoningEffort: Schema.optionalKey( + Schema.Union([V2TurnStartedNotification__ReasoningEffort, Schema.Null]).annotate({ + description: "Reasoning effort requested for the spawned agent, when applicable.", + }), + ), + receiverThreadIds: Schema.Array(Schema.String).annotate({ + description: + "Thread ID of the receiving agent, when applicable. In case of spawn operation, this corresponds to the newly spawned agent.", + }), + senderThreadId: Schema.String.annotate({ + description: "Thread ID of the agent issuing the collab request.", + }), + status: Schema.Literals(["inProgress", "completed", "failed"]).annotate({ + description: "Current status of the collab tool call.", + }), + tool: Schema.Literals([ + "spawnAgent", + "sendInput", + "resumeAgent", + "wait", + "closeAgent", + ]).annotate({ description: "Name of the collab tool that was invoked." }), + type: Schema.Literal("collabAgentToolCall").annotate({ + title: "CollabAgentToolCallThreadItemType", + }), + }).annotate({ title: "CollabAgentToolCallThreadItem" }), + Schema.Struct({ + action: Schema.optionalKey( + Schema.Union([V2TurnStartedNotification__WebSearchAction, Schema.Null]), + ), + id: Schema.String, + query: Schema.String, + type: Schema.Literal("webSearch").annotate({ title: "WebSearchThreadItemType" }), + }).annotate({ title: "WebSearchThreadItem" }), + Schema.Struct({ + id: Schema.String, + path: Schema.String, + type: Schema.Literal("imageView").annotate({ title: "ImageViewThreadItemType" }), + }).annotate({ title: "ImageViewThreadItem" }), + Schema.Struct({ + id: Schema.String, + result: Schema.String, + revisedPrompt: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + savedPath: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + status: Schema.String, + type: Schema.Literal("imageGeneration").annotate({ title: "ImageGenerationThreadItemType" }), + }).annotate({ title: "ImageGenerationThreadItem" }), + Schema.Struct({ + id: Schema.String, + review: Schema.String, + type: Schema.Literal("enteredReviewMode").annotate({ + title: "EnteredReviewModeThreadItemType", + }), + }).annotate({ title: "EnteredReviewModeThreadItem" }), + Schema.Struct({ + id: Schema.String, + review: Schema.String, + type: Schema.Literal("exitedReviewMode").annotate({ + title: "ExitedReviewModeThreadItemType", + }), + }).annotate({ title: "ExitedReviewModeThreadItem" }), + Schema.Struct({ + id: Schema.String, + type: Schema.Literal("contextCompaction").annotate({ + title: "ContextCompactionThreadItemType", + }), + }).annotate({ title: "ContextCompactionThreadItem" }), + ], + { mode: "oneOf" }, +); + +export type V2TurnStartResponse__TurnError = { + readonly additionalDetails?: string | null; + readonly codexErrorInfo?: V2TurnStartResponse__CodexErrorInfo | null; + readonly message: string; +}; +export const V2TurnStartResponse__TurnError = Schema.Struct({ + additionalDetails: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + codexErrorInfo: Schema.optionalKey( + Schema.Union([V2TurnStartResponse__CodexErrorInfo, Schema.Null]), + ), + message: Schema.String, +}); + +export type V2TurnStartResponse__ThreadItem = + | { + readonly content: ReadonlyArray; + readonly id: string; + readonly type: "userMessage"; + } + | { + readonly fragments: ReadonlyArray; + readonly id: string; + readonly type: "hookPrompt"; + } + | { + readonly id: string; + readonly memoryCitation?: V2TurnStartResponse__MemoryCitation | null; + readonly phase?: V2TurnStartResponse__MessagePhase | null; + readonly text: string; + readonly type: "agentMessage"; + } + | { readonly id: string; readonly text: string; readonly type: "plan" } + | { + readonly content?: ReadonlyArray; + readonly id: string; + readonly summary?: ReadonlyArray; + readonly type: "reasoning"; + } + | { + readonly aggregatedOutput?: string | null; + readonly command: string; + readonly commandActions: ReadonlyArray; + readonly cwd: string; + readonly durationMs?: number | null; + readonly exitCode?: number | null; + readonly id: string; + readonly processId?: string | null; + readonly source?: "agent" | "userShell" | "unifiedExecStartup" | "unifiedExecInteraction"; + readonly status: V2TurnStartResponse__CommandExecutionStatus; + readonly type: "commandExecution"; + } + | { + readonly changes: ReadonlyArray; + readonly id: string; + readonly status: V2TurnStartResponse__PatchApplyStatus; + readonly type: "fileChange"; + } + | { + readonly arguments: unknown; + readonly durationMs?: number | null; + readonly error?: V2TurnStartResponse__McpToolCallError | null; + readonly id: string; + readonly result?: V2TurnStartResponse__McpToolCallResult | null; + readonly server: string; + readonly status: V2TurnStartResponse__McpToolCallStatus; + readonly tool: string; + readonly type: "mcpToolCall"; + } + | { + readonly arguments: unknown; + readonly contentItems?: ReadonlyArray | null; + readonly durationMs?: number | null; + readonly id: string; + readonly status: V2TurnStartResponse__DynamicToolCallStatus; + readonly success?: boolean | null; + readonly tool: string; + readonly type: "dynamicToolCall"; + } + | { + readonly agentsStates: { readonly [x: string]: V2TurnStartResponse__CollabAgentState }; + readonly id: string; + readonly model?: string | null; + readonly prompt?: string | null; + readonly reasoningEffort?: V2TurnStartResponse__ReasoningEffort | null; + readonly receiverThreadIds: ReadonlyArray; + readonly senderThreadId: string; + readonly status: "inProgress" | "completed" | "failed"; + readonly tool: "spawnAgent" | "sendInput" | "resumeAgent" | "wait" | "closeAgent"; + readonly type: "collabAgentToolCall"; + } + | { + readonly action?: V2TurnStartResponse__WebSearchAction | null; + readonly id: string; + readonly query: string; + readonly type: "webSearch"; + } + | { readonly id: string; readonly path: string; readonly type: "imageView" } + | { + readonly id: string; + readonly result: string; + readonly revisedPrompt?: string | null; + readonly savedPath?: string | null; + readonly status: string; + readonly type: "imageGeneration"; + } + | { readonly id: string; readonly review: string; readonly type: "enteredReviewMode" } + | { readonly id: string; readonly review: string; readonly type: "exitedReviewMode" } + | { readonly id: string; readonly type: "contextCompaction" }; +export const V2TurnStartResponse__ThreadItem = Schema.Union( + [ + Schema.Struct({ + content: Schema.Array(V2TurnStartResponse__UserInput), + id: Schema.String, + type: Schema.Literal("userMessage").annotate({ title: "UserMessageThreadItemType" }), + }).annotate({ title: "UserMessageThreadItem" }), + Schema.Struct({ + fragments: Schema.Array(V2TurnStartResponse__HookPromptFragment), + id: Schema.String, + type: Schema.Literal("hookPrompt").annotate({ title: "HookPromptThreadItemType" }), + }).annotate({ title: "HookPromptThreadItem" }), + Schema.Struct({ + id: Schema.String, + memoryCitation: Schema.optionalKey( + Schema.Union([V2TurnStartResponse__MemoryCitation, Schema.Null]), + ), + phase: Schema.optionalKey(Schema.Union([V2TurnStartResponse__MessagePhase, Schema.Null])), + text: Schema.String, + type: Schema.Literal("agentMessage").annotate({ title: "AgentMessageThreadItemType" }), + }).annotate({ title: "AgentMessageThreadItem" }), + Schema.Struct({ + id: Schema.String, + text: Schema.String, + type: Schema.Literal("plan").annotate({ title: "PlanThreadItemType" }), + }).annotate({ + title: "PlanThreadItem", + description: + "EXPERIMENTAL - proposed plan item content. The completed plan item is authoritative and may not match the concatenation of `PlanDelta` text.", + }), + Schema.Struct({ + content: Schema.optionalKey(Schema.Array(Schema.String).annotate({ default: [] })), + id: Schema.String, + summary: Schema.optionalKey(Schema.Array(Schema.String).annotate({ default: [] })), + type: Schema.Literal("reasoning").annotate({ title: "ReasoningThreadItemType" }), + }).annotate({ title: "ReasoningThreadItem" }), + Schema.Struct({ + aggregatedOutput: Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + description: "The command's output, aggregated from stdout and stderr.", + }), + Schema.Null, + ]), + ), + command: Schema.String.annotate({ description: "The command to be executed." }), + commandActions: Schema.Array(V2TurnStartResponse__CommandAction).annotate({ + description: + "A best-effort parsing of the command to understand the action(s) it will perform. This returns a list of CommandAction objects because a single shell command may be composed of many commands piped together.", + }), + cwd: Schema.String.annotate({ description: "The command's working directory." }), + durationMs: Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ + description: "The duration of the command execution in milliseconds.", + format: "int64", + }).check(Schema.isInt()), + Schema.Null, + ]), + ), + exitCode: Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ + description: "The command's exit code.", + format: "int32", + }).check(Schema.isInt()), + Schema.Null, + ]), + ), + id: Schema.String, + processId: Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + description: "Identifier for the underlying PTY process (when available).", + }), + Schema.Null, + ]), + ), + source: Schema.optionalKey( + Schema.Literals([ + "agent", + "userShell", + "unifiedExecStartup", + "unifiedExecInteraction", + ]).annotate({ default: "agent" }), + ), + status: V2TurnStartResponse__CommandExecutionStatus, + type: Schema.Literal("commandExecution").annotate({ + title: "CommandExecutionThreadItemType", + }), + }).annotate({ title: "CommandExecutionThreadItem" }), + Schema.Struct({ + changes: Schema.Array(V2TurnStartResponse__FileUpdateChange), + id: Schema.String, + status: V2TurnStartResponse__PatchApplyStatus, + type: Schema.Literal("fileChange").annotate({ title: "FileChangeThreadItemType" }), + }).annotate({ title: "FileChangeThreadItem" }), + Schema.Struct({ + arguments: Schema.Unknown, + durationMs: Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ + description: "The duration of the MCP tool call in milliseconds.", + format: "int64", + }).check(Schema.isInt()), + Schema.Null, + ]), + ), + error: Schema.optionalKey(Schema.Union([V2TurnStartResponse__McpToolCallError, Schema.Null])), + id: Schema.String, + result: Schema.optionalKey( + Schema.Union([V2TurnStartResponse__McpToolCallResult, Schema.Null]), + ), + server: Schema.String, + status: V2TurnStartResponse__McpToolCallStatus, + tool: Schema.String, + type: Schema.Literal("mcpToolCall").annotate({ title: "McpToolCallThreadItemType" }), + }).annotate({ title: "McpToolCallThreadItem" }), + Schema.Struct({ + arguments: Schema.Unknown, + contentItems: Schema.optionalKey( + Schema.Union([ + Schema.Array(V2TurnStartResponse__DynamicToolCallOutputContentItem), + Schema.Null, + ]), + ), + durationMs: Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ + description: "The duration of the dynamic tool call in milliseconds.", + format: "int64", + }).check(Schema.isInt()), + Schema.Null, + ]), + ), + id: Schema.String, + status: V2TurnStartResponse__DynamicToolCallStatus, + success: Schema.optionalKey(Schema.Union([Schema.Boolean, Schema.Null])), + tool: Schema.String, + type: Schema.Literal("dynamicToolCall").annotate({ title: "DynamicToolCallThreadItemType" }), + }).annotate({ title: "DynamicToolCallThreadItem" }), + Schema.Struct({ + agentsStates: Schema.Record(Schema.String, V2TurnStartResponse__CollabAgentState).annotate({ + description: "Last known status of the target agents, when available.", + }), + id: Schema.String.annotate({ description: "Unique identifier for this collab tool call." }), + model: Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + description: "Model requested for the spawned agent, when applicable.", + }), + Schema.Null, + ]), + ), + prompt: Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + description: "Prompt text sent as part of the collab tool call, when available.", + }), + Schema.Null, + ]), + ), + reasoningEffort: Schema.optionalKey( + Schema.Union([V2TurnStartResponse__ReasoningEffort, Schema.Null]).annotate({ + description: "Reasoning effort requested for the spawned agent, when applicable.", + }), + ), + receiverThreadIds: Schema.Array(Schema.String).annotate({ + description: + "Thread ID of the receiving agent, when applicable. In case of spawn operation, this corresponds to the newly spawned agent.", + }), + senderThreadId: Schema.String.annotate({ + description: "Thread ID of the agent issuing the collab request.", + }), + status: Schema.Literals(["inProgress", "completed", "failed"]).annotate({ + description: "Current status of the collab tool call.", + }), + tool: Schema.Literals([ + "spawnAgent", + "sendInput", + "resumeAgent", + "wait", + "closeAgent", + ]).annotate({ description: "Name of the collab tool that was invoked." }), + type: Schema.Literal("collabAgentToolCall").annotate({ + title: "CollabAgentToolCallThreadItemType", + }), + }).annotate({ title: "CollabAgentToolCallThreadItem" }), + Schema.Struct({ + action: Schema.optionalKey(Schema.Union([V2TurnStartResponse__WebSearchAction, Schema.Null])), + id: Schema.String, + query: Schema.String, + type: Schema.Literal("webSearch").annotate({ title: "WebSearchThreadItemType" }), + }).annotate({ title: "WebSearchThreadItem" }), + Schema.Struct({ + id: Schema.String, + path: Schema.String, + type: Schema.Literal("imageView").annotate({ title: "ImageViewThreadItemType" }), + }).annotate({ title: "ImageViewThreadItem" }), + Schema.Struct({ + id: Schema.String, + result: Schema.String, + revisedPrompt: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + savedPath: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + status: Schema.String, + type: Schema.Literal("imageGeneration").annotate({ title: "ImageGenerationThreadItemType" }), + }).annotate({ title: "ImageGenerationThreadItem" }), + Schema.Struct({ + id: Schema.String, + review: Schema.String, + type: Schema.Literal("enteredReviewMode").annotate({ + title: "EnteredReviewModeThreadItemType", + }), + }).annotate({ title: "EnteredReviewModeThreadItem" }), + Schema.Struct({ + id: Schema.String, + review: Schema.String, + type: Schema.Literal("exitedReviewMode").annotate({ + title: "ExitedReviewModeThreadItemType", + }), + }).annotate({ title: "ExitedReviewModeThreadItem" }), + Schema.Struct({ + id: Schema.String, + type: Schema.Literal("contextCompaction").annotate({ + title: "ContextCompactionThreadItemType", + }), + }).annotate({ title: "ContextCompactionThreadItem" }), + ], + { mode: "oneOf" }, +); + +export type McpServerElicitationRequestParams__McpElicitationMultiSelectEnumSchema = + | McpServerElicitationRequestParams__McpElicitationUntitledMultiSelectEnumSchema + | McpServerElicitationRequestParams__McpElicitationTitledMultiSelectEnumSchema; +export const McpServerElicitationRequestParams__McpElicitationMultiSelectEnumSchema = Schema.Union([ + McpServerElicitationRequestParams__McpElicitationUntitledMultiSelectEnumSchema, + McpServerElicitationRequestParams__McpElicitationTitledMultiSelectEnumSchema, +]); + +export type ServerNotification__AppListUpdatedNotification = { + readonly data: ReadonlyArray; +}; +export const ServerNotification__AppListUpdatedNotification = Schema.Struct({ + data: Schema.Array(ServerNotification__AppInfo), +}).annotate({ description: "EXPERIMENTAL - notification emitted when the app list changes." }); + +export type ServerNotification__HookCompletedNotification = { + readonly run: ServerNotification__HookRunSummary; + readonly threadId: string; + readonly turnId?: string | null; +}; +export const ServerNotification__HookCompletedNotification = Schema.Struct({ + run: ServerNotification__HookRunSummary, + threadId: Schema.String, + turnId: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), +}); + +export type ServerNotification__HookStartedNotification = { + readonly run: ServerNotification__HookRunSummary; + readonly threadId: string; + readonly turnId?: string | null; +}; +export const ServerNotification__HookStartedNotification = Schema.Struct({ + run: ServerNotification__HookRunSummary, + threadId: Schema.String, + turnId: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), +}); + +export type ServerNotification__ErrorNotification = { + readonly error: ServerNotification__TurnError; + readonly threadId: string; + readonly turnId: string; + readonly willRetry: boolean; +}; +export const ServerNotification__ErrorNotification = Schema.Struct({ + error: ServerNotification__TurnError, + threadId: Schema.String, + turnId: Schema.String, + willRetry: Schema.Boolean, +}); + +export type ServerNotification__ItemCompletedNotification = { + readonly item: ServerNotification__ThreadItem; + readonly threadId: string; + readonly turnId: string; +}; +export const ServerNotification__ItemCompletedNotification = Schema.Struct({ + item: ServerNotification__ThreadItem, + threadId: Schema.String, + turnId: Schema.String, +}); + +export type ServerNotification__ItemStartedNotification = { + readonly item: ServerNotification__ThreadItem; + readonly threadId: string; + readonly turnId: string; +}; +export const ServerNotification__ItemStartedNotification = Schema.Struct({ + item: ServerNotification__ThreadItem, + threadId: Schema.String, + turnId: Schema.String, +}); + +export type ServerNotification__Turn = { + readonly completedAt?: number | null; + readonly durationMs?: number | null; + readonly error?: ServerNotification__TurnError | null; + readonly id: string; + readonly items: ReadonlyArray; + readonly startedAt?: number | null; + readonly status: ServerNotification__TurnStatus; +}; +export const ServerNotification__Turn = Schema.Struct({ + completedAt: Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ + description: "Unix timestamp (in seconds) when the turn completed.", + format: "int64", + }).check(Schema.isInt()), + Schema.Null, + ]), + ), + durationMs: Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ + description: "Duration between turn start and completion in milliseconds, if known.", + format: "int64", + }).check(Schema.isInt()), + Schema.Null, + ]), + ), + error: Schema.optionalKey( + Schema.Union([ServerNotification__TurnError, Schema.Null]).annotate({ + description: "Only populated when the Turn's status is failed.", + }), + ), + id: Schema.String, + items: Schema.Array(ServerNotification__ThreadItem).annotate({ + description: + "Only populated on a `thread/resume` or `thread/fork` response. For all other responses and notifications returning a Turn, the items field will be an empty list.", + }), + startedAt: Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ + description: "Unix timestamp (in seconds) when the turn started.", + format: "int64", + }).check(Schema.isInt()), + Schema.Null, + ]), + ), + status: ServerNotification__TurnStatus, +}); + +export type ServerRequest__PermissionsRequestApprovalParams = { + readonly itemId: string; + readonly permissions: ServerRequest__RequestPermissionProfile; + readonly reason?: string | null; + readonly threadId: string; + readonly turnId: string; +}; +export const ServerRequest__PermissionsRequestApprovalParams = Schema.Struct({ + itemId: Schema.String, + permissions: ServerRequest__RequestPermissionProfile, + reason: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + threadId: Schema.String, + turnId: Schema.String, +}); + +export type ServerRequest__McpElicitationMultiSelectEnumSchema = + | ServerRequest__McpElicitationUntitledMultiSelectEnumSchema + | ServerRequest__McpElicitationTitledMultiSelectEnumSchema; +export const ServerRequest__McpElicitationMultiSelectEnumSchema = Schema.Union([ + ServerRequest__McpElicitationUntitledMultiSelectEnumSchema, + ServerRequest__McpElicitationTitledMultiSelectEnumSchema, +]); + +export type V2ConfigReadResponse__ProfileV2 = { + readonly approval_policy?: V2ConfigReadResponse__AskForApproval | null; + readonly approvals_reviewer?: V2ConfigReadResponse__ApprovalsReviewer | null; + readonly chatgpt_base_url?: string | null; + readonly model?: string | null; + readonly model_provider?: string | null; + readonly model_reasoning_effort?: V2ConfigReadResponse__ReasoningEffort | null; + readonly model_reasoning_summary?: V2ConfigReadResponse__ReasoningSummary | null; + readonly model_verbosity?: V2ConfigReadResponse__Verbosity | null; + readonly service_tier?: V2ConfigReadResponse__ServiceTier | null; + readonly tools?: V2ConfigReadResponse__ToolsV2 | null; + readonly web_search?: V2ConfigReadResponse__WebSearchMode | null; + readonly [x: string]: unknown; +}; +export const V2ConfigReadResponse__ProfileV2 = Schema.StructWithRest( + Schema.Struct({ + approval_policy: Schema.optionalKey( + Schema.Union([V2ConfigReadResponse__AskForApproval, Schema.Null]), + ), + approvals_reviewer: Schema.optionalKey( + Schema.Union([V2ConfigReadResponse__ApprovalsReviewer, Schema.Null]).annotate({ + description: + "[UNSTABLE] Optional profile-level override for where approval requests are routed for review. If omitted, the enclosing config default is used.", + }), + ), + chatgpt_base_url: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + model: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + model_provider: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + model_reasoning_effort: Schema.optionalKey( + Schema.Union([V2ConfigReadResponse__ReasoningEffort, Schema.Null]), + ), + model_reasoning_summary: Schema.optionalKey( + Schema.Union([V2ConfigReadResponse__ReasoningSummary, Schema.Null]), + ), + model_verbosity: Schema.optionalKey( + Schema.Union([V2ConfigReadResponse__Verbosity, Schema.Null]), + ), + service_tier: Schema.optionalKey( + Schema.Union([V2ConfigReadResponse__ServiceTier, Schema.Null]), + ), + tools: Schema.optionalKey(Schema.Union([V2ConfigReadResponse__ToolsV2, Schema.Null])), + web_search: Schema.optionalKey( + Schema.Union([V2ConfigReadResponse__WebSearchMode, Schema.Null]), + ), + }), + [Schema.Record(Schema.String, Schema.Unknown)], +); + +export type V2ConfigWriteResponse__OverriddenMetadata = { + readonly effectiveValue: unknown; + readonly message: string; + readonly overridingLayer: V2ConfigWriteResponse__ConfigLayerMetadata; +}; +export const V2ConfigWriteResponse__OverriddenMetadata = Schema.Struct({ + effectiveValue: Schema.Unknown, + message: Schema.String, + overridingLayer: V2ConfigWriteResponse__ConfigLayerMetadata, +}); + +export type V2PluginListResponse__PluginMarketplaceEntry = { + readonly interface?: V2PluginListResponse__MarketplaceInterface | null; + readonly name: string; + readonly path: V2PluginListResponse__AbsolutePathBuf; + readonly plugins: ReadonlyArray; +}; +export const V2PluginListResponse__PluginMarketplaceEntry = Schema.Struct({ + interface: Schema.optionalKey( + Schema.Union([V2PluginListResponse__MarketplaceInterface, Schema.Null]), + ), + name: Schema.String, + path: V2PluginListResponse__AbsolutePathBuf, + plugins: Schema.Array(V2PluginListResponse__PluginSummary), +}); + +export type V2PluginReadResponse__PluginDetail = { + readonly apps: ReadonlyArray; + readonly description?: string | null; + readonly marketplaceName: string; + readonly marketplacePath: V2PluginReadResponse__AbsolutePathBuf; + readonly mcpServers: ReadonlyArray; + readonly skills: ReadonlyArray; + readonly summary: V2PluginReadResponse__PluginSummary; +}; +export const V2PluginReadResponse__PluginDetail = Schema.Struct({ + apps: Schema.Array(V2PluginReadResponse__AppSummary), + description: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + marketplaceName: Schema.String, + marketplacePath: V2PluginReadResponse__AbsolutePathBuf, + mcpServers: Schema.Array(Schema.String), + skills: Schema.Array(V2PluginReadResponse__SkillSummary), + summary: V2PluginReadResponse__PluginSummary, +}); + +export type V2RawResponseItemCompletedNotification__ResponseItem = + | { + readonly content: ReadonlyArray; + readonly end_turn?: boolean | null; + readonly id?: string | null; + readonly phase?: V2RawResponseItemCompletedNotification__MessagePhase | null; + readonly role: string; + readonly type: "message"; + } + | { + readonly content?: ReadonlyArray | null; + readonly encrypted_content?: string | null; + readonly summary: ReadonlyArray; + readonly type: "reasoning"; + } + | { + readonly action: V2RawResponseItemCompletedNotification__LocalShellAction; + readonly call_id?: string | null; + readonly id?: string | null; + readonly status: V2RawResponseItemCompletedNotification__LocalShellStatus; + readonly type: "local_shell_call"; + } + | { + readonly arguments: string; + readonly call_id: string; + readonly id?: string | null; + readonly name: string; + readonly namespace?: string | null; + readonly type: "function_call"; + } + | { + readonly arguments: unknown; + readonly call_id?: string | null; + readonly execution: string; + readonly id?: string | null; + readonly status?: string | null; + readonly type: "tool_search_call"; + } + | { + readonly call_id: string; + readonly output: V2RawResponseItemCompletedNotification__FunctionCallOutputBody; + readonly type: "function_call_output"; + } + | { + readonly call_id: string; + readonly id?: string | null; + readonly input: string; + readonly name: string; + readonly status?: string | null; + readonly type: "custom_tool_call"; + } + | { + readonly call_id: string; + readonly name?: string | null; + readonly output: V2RawResponseItemCompletedNotification__FunctionCallOutputBody; + readonly type: "custom_tool_call_output"; + } + | { + readonly call_id?: string | null; + readonly execution: string; + readonly status: string; + readonly tools: ReadonlyArray; + readonly type: "tool_search_output"; + } + | { + readonly action?: V2RawResponseItemCompletedNotification__ResponsesApiWebSearchAction | null; + readonly id?: string | null; + readonly status?: string | null; + readonly type: "web_search_call"; + } + | { + readonly id: string; + readonly result: string; + readonly revised_prompt?: string | null; + readonly status: string; + readonly type: "image_generation_call"; + } + | { + readonly ghost_commit: V2RawResponseItemCompletedNotification__GhostCommit; + readonly type: "ghost_snapshot"; + } + | { readonly encrypted_content: string; readonly type: "compaction" } + | { readonly type: "other" }; +export const V2RawResponseItemCompletedNotification__ResponseItem = Schema.Union( + [ + Schema.Struct({ + content: Schema.Array(V2RawResponseItemCompletedNotification__ContentItem), + end_turn: Schema.optionalKey(Schema.Union([Schema.Boolean, Schema.Null])), + id: Schema.optionalKey( + Schema.Union([Schema.String.annotate({ writeOnly: true }), Schema.Null]), + ), + phase: Schema.optionalKey( + Schema.Union([V2RawResponseItemCompletedNotification__MessagePhase, Schema.Null]), + ), + role: Schema.String, + type: Schema.Literal("message").annotate({ title: "MessageResponseItemType" }), + }).annotate({ title: "MessageResponseItem" }), + Schema.Struct({ + content: Schema.optionalKey( + Schema.Union([ + Schema.Array(V2RawResponseItemCompletedNotification__ReasoningItemContent), + Schema.Null, + ]), + ), + encrypted_content: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + summary: Schema.Array(V2RawResponseItemCompletedNotification__ReasoningItemReasoningSummary), + type: Schema.Literal("reasoning").annotate({ title: "ReasoningResponseItemType" }), + }).annotate({ title: "ReasoningResponseItem" }), + Schema.Struct({ + action: V2RawResponseItemCompletedNotification__LocalShellAction, + call_id: Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ description: "Set when using the Responses API." }), + Schema.Null, + ]), + ), + id: Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + description: "Legacy id field retained for compatibility with older payloads.", + writeOnly: true, + }), + Schema.Null, + ]), + ), + status: V2RawResponseItemCompletedNotification__LocalShellStatus, + type: Schema.Literal("local_shell_call").annotate({ + title: "LocalShellCallResponseItemType", + }), + }).annotate({ title: "LocalShellCallResponseItem" }), + Schema.Struct({ + arguments: Schema.String, + call_id: Schema.String, + id: Schema.optionalKey( + Schema.Union([Schema.String.annotate({ writeOnly: true }), Schema.Null]), + ), + name: Schema.String, + namespace: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + type: Schema.Literal("function_call").annotate({ title: "FunctionCallResponseItemType" }), + }).annotate({ title: "FunctionCallResponseItem" }), + Schema.Struct({ + arguments: Schema.Unknown, + call_id: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + execution: Schema.String, + id: Schema.optionalKey( + Schema.Union([Schema.String.annotate({ writeOnly: true }), Schema.Null]), + ), + status: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + type: Schema.Literal("tool_search_call").annotate({ + title: "ToolSearchCallResponseItemType", + }), + }).annotate({ title: "ToolSearchCallResponseItem" }), + Schema.Struct({ + call_id: Schema.String, + output: V2RawResponseItemCompletedNotification__FunctionCallOutputBody, + type: Schema.Literal("function_call_output").annotate({ + title: "FunctionCallOutputResponseItemType", + }), + }).annotate({ title: "FunctionCallOutputResponseItem" }), + Schema.Struct({ + call_id: Schema.String, + id: Schema.optionalKey( + Schema.Union([Schema.String.annotate({ writeOnly: true }), Schema.Null]), + ), + input: Schema.String, + name: Schema.String, + status: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + type: Schema.Literal("custom_tool_call").annotate({ + title: "CustomToolCallResponseItemType", + }), + }).annotate({ title: "CustomToolCallResponseItem" }), + Schema.Struct({ + call_id: Schema.String, + name: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + output: V2RawResponseItemCompletedNotification__FunctionCallOutputBody, + type: Schema.Literal("custom_tool_call_output").annotate({ + title: "CustomToolCallOutputResponseItemType", + }), + }).annotate({ title: "CustomToolCallOutputResponseItem" }), + Schema.Struct({ + call_id: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + execution: Schema.String, + status: Schema.String, + tools: Schema.Array(Schema.Unknown), + type: Schema.Literal("tool_search_output").annotate({ + title: "ToolSearchOutputResponseItemType", + }), + }).annotate({ title: "ToolSearchOutputResponseItem" }), + Schema.Struct({ + action: Schema.optionalKey( + Schema.Union([ + V2RawResponseItemCompletedNotification__ResponsesApiWebSearchAction, + Schema.Null, + ]), + ), + id: Schema.optionalKey( + Schema.Union([Schema.String.annotate({ writeOnly: true }), Schema.Null]), + ), + status: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + type: Schema.Literal("web_search_call").annotate({ title: "WebSearchCallResponseItemType" }), + }).annotate({ title: "WebSearchCallResponseItem" }), + Schema.Struct({ + id: Schema.String, + result: Schema.String, + revised_prompt: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + status: Schema.String, + type: Schema.Literal("image_generation_call").annotate({ + title: "ImageGenerationCallResponseItemType", + }), + }).annotate({ title: "ImageGenerationCallResponseItem" }), + Schema.Struct({ + ghost_commit: V2RawResponseItemCompletedNotification__GhostCommit, + type: Schema.Literal("ghost_snapshot").annotate({ title: "GhostSnapshotResponseItemType" }), + }).annotate({ title: "GhostSnapshotResponseItem" }), + Schema.Struct({ + encrypted_content: Schema.String, + type: Schema.Literal("compaction").annotate({ title: "CompactionResponseItemType" }), + }).annotate({ title: "CompactionResponseItem" }), + Schema.Struct({ + type: Schema.Literal("other").annotate({ title: "OtherResponseItemType" }), + }).annotate({ title: "OtherResponseItem" }), + ], + { mode: "oneOf" }, +); + +export type V2ReviewStartResponse__Turn = { + readonly completedAt?: number | null; + readonly durationMs?: number | null; + readonly error?: V2ReviewStartResponse__TurnError | null; + readonly id: string; + readonly items: ReadonlyArray; + readonly startedAt?: number | null; + readonly status: V2ReviewStartResponse__TurnStatus; +}; +export const V2ReviewStartResponse__Turn = Schema.Struct({ + completedAt: Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ + description: "Unix timestamp (in seconds) when the turn completed.", + format: "int64", + }).check(Schema.isInt()), + Schema.Null, + ]), + ), + durationMs: Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ + description: "Duration between turn start and completion in milliseconds, if known.", + format: "int64", + }).check(Schema.isInt()), + Schema.Null, + ]), + ), + error: Schema.optionalKey( + Schema.Union([V2ReviewStartResponse__TurnError, Schema.Null]).annotate({ + description: "Only populated when the Turn's status is failed.", + }), + ), + id: Schema.String, + items: Schema.Array(V2ReviewStartResponse__ThreadItem).annotate({ + description: + "Only populated on a `thread/resume` or `thread/fork` response. For all other responses and notifications returning a Turn, the items field will be an empty list.", + }), + startedAt: Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ + description: "Unix timestamp (in seconds) when the turn started.", + format: "int64", + }).check(Schema.isInt()), + Schema.Null, + ]), + ), + status: V2ReviewStartResponse__TurnStatus, +}); + +export type V2SkillsListResponse__SkillsListEntry = { + readonly cwd: string; + readonly errors: ReadonlyArray; + readonly skills: ReadonlyArray; +}; +export const V2SkillsListResponse__SkillsListEntry = Schema.Struct({ + cwd: Schema.String, + errors: Schema.Array(V2SkillsListResponse__SkillErrorInfo), + skills: Schema.Array(V2SkillsListResponse__SkillMetadata), +}); + +export type V2ThreadForkResponse__Turn = { + readonly completedAt?: number | null; + readonly durationMs?: number | null; + readonly error?: V2ThreadForkResponse__TurnError | null; + readonly id: string; + readonly items: ReadonlyArray; + readonly startedAt?: number | null; + readonly status: V2ThreadForkResponse__TurnStatus; +}; +export const V2ThreadForkResponse__Turn = Schema.Struct({ + completedAt: Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ + description: "Unix timestamp (in seconds) when the turn completed.", + format: "int64", + }).check(Schema.isInt()), + Schema.Null, + ]), + ), + durationMs: Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ + description: "Duration between turn start and completion in milliseconds, if known.", + format: "int64", + }).check(Schema.isInt()), + Schema.Null, + ]), + ), + error: Schema.optionalKey( + Schema.Union([V2ThreadForkResponse__TurnError, Schema.Null]).annotate({ + description: "Only populated when the Turn's status is failed.", + }), + ), + id: Schema.String, + items: Schema.Array(V2ThreadForkResponse__ThreadItem).annotate({ + description: + "Only populated on a `thread/resume` or `thread/fork` response. For all other responses and notifications returning a Turn, the items field will be an empty list.", + }), + startedAt: Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ + description: "Unix timestamp (in seconds) when the turn started.", + format: "int64", + }).check(Schema.isInt()), + Schema.Null, + ]), + ), + status: V2ThreadForkResponse__TurnStatus, +}); + +export type V2ThreadListResponse__Turn = { + readonly completedAt?: number | null; + readonly durationMs?: number | null; + readonly error?: V2ThreadListResponse__TurnError | null; + readonly id: string; + readonly items: ReadonlyArray; + readonly startedAt?: number | null; + readonly status: V2ThreadListResponse__TurnStatus; +}; +export const V2ThreadListResponse__Turn = Schema.Struct({ + completedAt: Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ + description: "Unix timestamp (in seconds) when the turn completed.", + format: "int64", + }).check(Schema.isInt()), + Schema.Null, + ]), + ), + durationMs: Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ + description: "Duration between turn start and completion in milliseconds, if known.", + format: "int64", + }).check(Schema.isInt()), + Schema.Null, + ]), + ), + error: Schema.optionalKey( + Schema.Union([V2ThreadListResponse__TurnError, Schema.Null]).annotate({ + description: "Only populated when the Turn's status is failed.", + }), + ), + id: Schema.String, + items: Schema.Array(V2ThreadListResponse__ThreadItem).annotate({ + description: + "Only populated on a `thread/resume` or `thread/fork` response. For all other responses and notifications returning a Turn, the items field will be an empty list.", + }), + startedAt: Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ + description: "Unix timestamp (in seconds) when the turn started.", + format: "int64", + }).check(Schema.isInt()), + Schema.Null, + ]), + ), + status: V2ThreadListResponse__TurnStatus, +}); + +export type V2ThreadMetadataUpdateResponse__Turn = { + readonly completedAt?: number | null; + readonly durationMs?: number | null; + readonly error?: V2ThreadMetadataUpdateResponse__TurnError | null; + readonly id: string; + readonly items: ReadonlyArray; + readonly startedAt?: number | null; + readonly status: V2ThreadMetadataUpdateResponse__TurnStatus; +}; +export const V2ThreadMetadataUpdateResponse__Turn = Schema.Struct({ + completedAt: Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ + description: "Unix timestamp (in seconds) when the turn completed.", + format: "int64", + }).check(Schema.isInt()), + Schema.Null, + ]), + ), + durationMs: Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ + description: "Duration between turn start and completion in milliseconds, if known.", + format: "int64", + }).check(Schema.isInt()), + Schema.Null, + ]), + ), + error: Schema.optionalKey( + Schema.Union([V2ThreadMetadataUpdateResponse__TurnError, Schema.Null]).annotate({ + description: "Only populated when the Turn's status is failed.", + }), + ), + id: Schema.String, + items: Schema.Array(V2ThreadMetadataUpdateResponse__ThreadItem).annotate({ + description: + "Only populated on a `thread/resume` or `thread/fork` response. For all other responses and notifications returning a Turn, the items field will be an empty list.", + }), + startedAt: Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ + description: "Unix timestamp (in seconds) when the turn started.", + format: "int64", + }).check(Schema.isInt()), + Schema.Null, + ]), + ), + status: V2ThreadMetadataUpdateResponse__TurnStatus, +}); + +export type V2ThreadReadResponse__Turn = { + readonly completedAt?: number | null; + readonly durationMs?: number | null; + readonly error?: V2ThreadReadResponse__TurnError | null; + readonly id: string; + readonly items: ReadonlyArray; + readonly startedAt?: number | null; + readonly status: V2ThreadReadResponse__TurnStatus; +}; +export const V2ThreadReadResponse__Turn = Schema.Struct({ + completedAt: Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ + description: "Unix timestamp (in seconds) when the turn completed.", + format: "int64", + }).check(Schema.isInt()), + Schema.Null, + ]), + ), + durationMs: Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ + description: "Duration between turn start and completion in milliseconds, if known.", + format: "int64", + }).check(Schema.isInt()), + Schema.Null, + ]), + ), + error: Schema.optionalKey( + Schema.Union([V2ThreadReadResponse__TurnError, Schema.Null]).annotate({ + description: "Only populated when the Turn's status is failed.", + }), + ), + id: Schema.String, + items: Schema.Array(V2ThreadReadResponse__ThreadItem).annotate({ + description: + "Only populated on a `thread/resume` or `thread/fork` response. For all other responses and notifications returning a Turn, the items field will be an empty list.", + }), + startedAt: Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ + description: "Unix timestamp (in seconds) when the turn started.", + format: "int64", + }).check(Schema.isInt()), + Schema.Null, + ]), + ), + status: V2ThreadReadResponse__TurnStatus, +}); + +export type V2ThreadResumeResponse__Turn = { + readonly completedAt?: number | null; + readonly durationMs?: number | null; + readonly error?: V2ThreadResumeResponse__TurnError | null; + readonly id: string; + readonly items: ReadonlyArray; + readonly startedAt?: number | null; + readonly status: V2ThreadResumeResponse__TurnStatus; +}; +export const V2ThreadResumeResponse__Turn = Schema.Struct({ + completedAt: Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ + description: "Unix timestamp (in seconds) when the turn completed.", + format: "int64", + }).check(Schema.isInt()), + Schema.Null, + ]), + ), + durationMs: Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ + description: "Duration between turn start and completion in milliseconds, if known.", + format: "int64", + }).check(Schema.isInt()), + Schema.Null, + ]), + ), + error: Schema.optionalKey( + Schema.Union([V2ThreadResumeResponse__TurnError, Schema.Null]).annotate({ + description: "Only populated when the Turn's status is failed.", + }), + ), + id: Schema.String, + items: Schema.Array(V2ThreadResumeResponse__ThreadItem).annotate({ + description: + "Only populated on a `thread/resume` or `thread/fork` response. For all other responses and notifications returning a Turn, the items field will be an empty list.", + }), + startedAt: Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ + description: "Unix timestamp (in seconds) when the turn started.", + format: "int64", + }).check(Schema.isInt()), + Schema.Null, + ]), + ), + status: V2ThreadResumeResponse__TurnStatus, +}); + +export type V2ThreadRollbackResponse__Turn = { + readonly completedAt?: number | null; + readonly durationMs?: number | null; + readonly error?: V2ThreadRollbackResponse__TurnError | null; + readonly id: string; + readonly items: ReadonlyArray; + readonly startedAt?: number | null; + readonly status: V2ThreadRollbackResponse__TurnStatus; +}; +export const V2ThreadRollbackResponse__Turn = Schema.Struct({ + completedAt: Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ + description: "Unix timestamp (in seconds) when the turn completed.", + format: "int64", + }).check(Schema.isInt()), + Schema.Null, + ]), + ), + durationMs: Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ + description: "Duration between turn start and completion in milliseconds, if known.", + format: "int64", + }).check(Schema.isInt()), + Schema.Null, + ]), + ), + error: Schema.optionalKey( + Schema.Union([V2ThreadRollbackResponse__TurnError, Schema.Null]).annotate({ + description: "Only populated when the Turn's status is failed.", + }), + ), + id: Schema.String, + items: Schema.Array(V2ThreadRollbackResponse__ThreadItem).annotate({ + description: + "Only populated on a `thread/resume` or `thread/fork` response. For all other responses and notifications returning a Turn, the items field will be an empty list.", + }), + startedAt: Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ + description: "Unix timestamp (in seconds) when the turn started.", + format: "int64", + }).check(Schema.isInt()), + Schema.Null, + ]), + ), + status: V2ThreadRollbackResponse__TurnStatus, +}); + +export type V2ThreadStartedNotification__Turn = { + readonly completedAt?: number | null; + readonly durationMs?: number | null; + readonly error?: V2ThreadStartedNotification__TurnError | null; + readonly id: string; + readonly items: ReadonlyArray; + readonly startedAt?: number | null; + readonly status: V2ThreadStartedNotification__TurnStatus; +}; +export const V2ThreadStartedNotification__Turn = Schema.Struct({ + completedAt: Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ + description: "Unix timestamp (in seconds) when the turn completed.", + format: "int64", + }).check(Schema.isInt()), + Schema.Null, + ]), + ), + durationMs: Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ + description: "Duration between turn start and completion in milliseconds, if known.", + format: "int64", + }).check(Schema.isInt()), + Schema.Null, + ]), + ), + error: Schema.optionalKey( + Schema.Union([V2ThreadStartedNotification__TurnError, Schema.Null]).annotate({ + description: "Only populated when the Turn's status is failed.", + }), + ), + id: Schema.String, + items: Schema.Array(V2ThreadStartedNotification__ThreadItem).annotate({ + description: + "Only populated on a `thread/resume` or `thread/fork` response. For all other responses and notifications returning a Turn, the items field will be an empty list.", + }), + startedAt: Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ + description: "Unix timestamp (in seconds) when the turn started.", + format: "int64", + }).check(Schema.isInt()), + Schema.Null, + ]), + ), + status: V2ThreadStartedNotification__TurnStatus, +}); + +export type V2ThreadStartResponse__Turn = { + readonly completedAt?: number | null; + readonly durationMs?: number | null; + readonly error?: V2ThreadStartResponse__TurnError | null; + readonly id: string; + readonly items: ReadonlyArray; + readonly startedAt?: number | null; + readonly status: V2ThreadStartResponse__TurnStatus; +}; +export const V2ThreadStartResponse__Turn = Schema.Struct({ + completedAt: Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ + description: "Unix timestamp (in seconds) when the turn completed.", + format: "int64", + }).check(Schema.isInt()), + Schema.Null, + ]), + ), + durationMs: Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ + description: "Duration between turn start and completion in milliseconds, if known.", + format: "int64", + }).check(Schema.isInt()), + Schema.Null, + ]), + ), + error: Schema.optionalKey( + Schema.Union([V2ThreadStartResponse__TurnError, Schema.Null]).annotate({ + description: "Only populated when the Turn's status is failed.", + }), + ), + id: Schema.String, + items: Schema.Array(V2ThreadStartResponse__ThreadItem).annotate({ + description: + "Only populated on a `thread/resume` or `thread/fork` response. For all other responses and notifications returning a Turn, the items field will be an empty list.", + }), + startedAt: Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ + description: "Unix timestamp (in seconds) when the turn started.", + format: "int64", + }).check(Schema.isInt()), + Schema.Null, + ]), + ), + status: V2ThreadStartResponse__TurnStatus, +}); + +export type V2ThreadUnarchiveResponse__Turn = { + readonly completedAt?: number | null; + readonly durationMs?: number | null; + readonly error?: V2ThreadUnarchiveResponse__TurnError | null; + readonly id: string; + readonly items: ReadonlyArray; + readonly startedAt?: number | null; + readonly status: V2ThreadUnarchiveResponse__TurnStatus; +}; +export const V2ThreadUnarchiveResponse__Turn = Schema.Struct({ + completedAt: Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ + description: "Unix timestamp (in seconds) when the turn completed.", + format: "int64", + }).check(Schema.isInt()), + Schema.Null, + ]), + ), + durationMs: Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ + description: "Duration between turn start and completion in milliseconds, if known.", + format: "int64", + }).check(Schema.isInt()), + Schema.Null, + ]), + ), + error: Schema.optionalKey( + Schema.Union([V2ThreadUnarchiveResponse__TurnError, Schema.Null]).annotate({ + description: "Only populated when the Turn's status is failed.", + }), + ), + id: Schema.String, + items: Schema.Array(V2ThreadUnarchiveResponse__ThreadItem).annotate({ + description: + "Only populated on a `thread/resume` or `thread/fork` response. For all other responses and notifications returning a Turn, the items field will be an empty list.", + }), + startedAt: Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ + description: "Unix timestamp (in seconds) when the turn started.", + format: "int64", + }).check(Schema.isInt()), + Schema.Null, + ]), + ), + status: V2ThreadUnarchiveResponse__TurnStatus, +}); + +export type V2TurnCompletedNotification__Turn = { + readonly completedAt?: number | null; + readonly durationMs?: number | null; + readonly error?: V2TurnCompletedNotification__TurnError | null; + readonly id: string; + readonly items: ReadonlyArray; + readonly startedAt?: number | null; + readonly status: V2TurnCompletedNotification__TurnStatus; +}; +export const V2TurnCompletedNotification__Turn = Schema.Struct({ + completedAt: Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ + description: "Unix timestamp (in seconds) when the turn completed.", + format: "int64", + }).check(Schema.isInt()), + Schema.Null, + ]), + ), + durationMs: Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ + description: "Duration between turn start and completion in milliseconds, if known.", + format: "int64", + }).check(Schema.isInt()), + Schema.Null, + ]), + ), + error: Schema.optionalKey( + Schema.Union([V2TurnCompletedNotification__TurnError, Schema.Null]).annotate({ + description: "Only populated when the Turn's status is failed.", + }), + ), + id: Schema.String, + items: Schema.Array(V2TurnCompletedNotification__ThreadItem).annotate({ + description: + "Only populated on a `thread/resume` or `thread/fork` response. For all other responses and notifications returning a Turn, the items field will be an empty list.", + }), + startedAt: Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ + description: "Unix timestamp (in seconds) when the turn started.", + format: "int64", + }).check(Schema.isInt()), + Schema.Null, + ]), + ), + status: V2TurnCompletedNotification__TurnStatus, +}); + +export type V2TurnStartedNotification__Turn = { + readonly completedAt?: number | null; + readonly durationMs?: number | null; + readonly error?: V2TurnStartedNotification__TurnError | null; + readonly id: string; + readonly items: ReadonlyArray; + readonly startedAt?: number | null; + readonly status: V2TurnStartedNotification__TurnStatus; +}; +export const V2TurnStartedNotification__Turn = Schema.Struct({ + completedAt: Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ + description: "Unix timestamp (in seconds) when the turn completed.", + format: "int64", + }).check(Schema.isInt()), + Schema.Null, + ]), + ), + durationMs: Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ + description: "Duration between turn start and completion in milliseconds, if known.", + format: "int64", + }).check(Schema.isInt()), + Schema.Null, + ]), + ), + error: Schema.optionalKey( + Schema.Union([V2TurnStartedNotification__TurnError, Schema.Null]).annotate({ + description: "Only populated when the Turn's status is failed.", + }), + ), + id: Schema.String, + items: Schema.Array(V2TurnStartedNotification__ThreadItem).annotate({ + description: + "Only populated on a `thread/resume` or `thread/fork` response. For all other responses and notifications returning a Turn, the items field will be an empty list.", + }), + startedAt: Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ + description: "Unix timestamp (in seconds) when the turn started.", + format: "int64", + }).check(Schema.isInt()), + Schema.Null, + ]), + ), + status: V2TurnStartedNotification__TurnStatus, +}); + +export type V2TurnStartResponse__Turn = { + readonly completedAt?: number | null; + readonly durationMs?: number | null; + readonly error?: V2TurnStartResponse__TurnError | null; + readonly id: string; + readonly items: ReadonlyArray; + readonly startedAt?: number | null; + readonly status: V2TurnStartResponse__TurnStatus; +}; +export const V2TurnStartResponse__Turn = Schema.Struct({ + completedAt: Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ + description: "Unix timestamp (in seconds) when the turn completed.", + format: "int64", + }).check(Schema.isInt()), + Schema.Null, + ]), + ), + durationMs: Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ + description: "Duration between turn start and completion in milliseconds, if known.", + format: "int64", + }).check(Schema.isInt()), + Schema.Null, + ]), + ), + error: Schema.optionalKey( + Schema.Union([V2TurnStartResponse__TurnError, Schema.Null]).annotate({ + description: "Only populated when the Turn's status is failed.", + }), + ), + id: Schema.String, + items: Schema.Array(V2TurnStartResponse__ThreadItem).annotate({ + description: + "Only populated on a `thread/resume` or `thread/fork` response. For all other responses and notifications returning a Turn, the items field will be an empty list.", + }), + startedAt: Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ + description: "Unix timestamp (in seconds) when the turn started.", + format: "int64", + }).check(Schema.isInt()), + Schema.Null, + ]), + ), + status: V2TurnStartResponse__TurnStatus, +}); + +export type McpServerElicitationRequestParams__McpElicitationEnumSchema = + | McpServerElicitationRequestParams__McpElicitationSingleSelectEnumSchema + | McpServerElicitationRequestParams__McpElicitationMultiSelectEnumSchema + | McpServerElicitationRequestParams__McpElicitationLegacyTitledEnumSchema; +export const McpServerElicitationRequestParams__McpElicitationEnumSchema = Schema.Union([ + McpServerElicitationRequestParams__McpElicitationSingleSelectEnumSchema, + McpServerElicitationRequestParams__McpElicitationMultiSelectEnumSchema, + McpServerElicitationRequestParams__McpElicitationLegacyTitledEnumSchema, +]); + +export type ServerNotification__Thread = { + readonly agentNickname?: string | null; + readonly agentRole?: string | null; + readonly cliVersion: string; + readonly createdAt: number; + readonly cwd: string; + readonly ephemeral: boolean; + readonly forkedFromId?: string | null; + readonly gitInfo?: ServerNotification__GitInfo | null; + readonly id: string; + readonly modelProvider: string; + readonly name?: string | null; + readonly path?: string | null; + readonly preview: string; + readonly source: + | "cli" + | "vscode" + | "exec" + | "appServer" + | "unknown" + | { readonly custom: string } + | { readonly subAgent: ServerNotification__SubAgentSource }; + readonly status: + | { readonly type: "notLoaded" } + | { readonly type: "idle" } + | { readonly type: "systemError" } + | { + readonly activeFlags: ReadonlyArray; + readonly type: "active"; + }; + readonly turns: ReadonlyArray; + readonly updatedAt: number; +}; +export const ServerNotification__Thread = Schema.Struct({ + agentNickname: Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + description: + "Optional random unique nickname assigned to an AgentControl-spawned sub-agent.", + }), + Schema.Null, + ]), + ), + agentRole: Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + description: "Optional role (agent_role) assigned to an AgentControl-spawned sub-agent.", + }), + Schema.Null, + ]), + ), + cliVersion: Schema.String.annotate({ + description: "Version of the CLI that created the thread.", + }), + createdAt: Schema.Number.annotate({ + description: "Unix timestamp (in seconds) when the thread was created.", + format: "int64", + }).check(Schema.isInt()), + cwd: Schema.String.annotate({ description: "Working directory captured for the thread." }), + ephemeral: Schema.Boolean.annotate({ + description: "Whether the thread is ephemeral and should not be materialized on disk.", + }), + forkedFromId: Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + description: "Source thread id when this thread was created by forking another thread.", + }), + Schema.Null, + ]), + ), + gitInfo: Schema.optionalKey( + Schema.Union([ServerNotification__GitInfo, Schema.Null]).annotate({ + description: "Optional Git metadata captured when the thread was created.", + }), + ), + id: Schema.String, + modelProvider: Schema.String.annotate({ + description: "Model provider used for this thread (for example, 'openai').", + }), + name: Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ description: "Optional user-facing thread title." }), + Schema.Null, + ]), + ), + path: Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ description: "[UNSTABLE] Path to the thread on disk." }), + Schema.Null, + ]), + ), + preview: Schema.String.annotate({ + description: "Usually the first user message in the thread, if available.", + }), + source: Schema.Union( + [ + Schema.Literals(["cli", "vscode", "exec", "appServer", "unknown"]), + Schema.Struct({ custom: Schema.String }).annotate({ title: "CustomSessionSource" }), + Schema.Struct({ subAgent: ServerNotification__SubAgentSource }).annotate({ + title: "SubAgentSessionSource", + }), + ], + { mode: "oneOf" }, + ).annotate({ + description: "Origin of the thread (CLI, VSCode, codex exec, codex app-server, etc.).", + }), + status: Schema.Union( + [ + Schema.Struct({ + type: Schema.Literal("notLoaded").annotate({ title: "NotLoadedThreadStatusType" }), + }).annotate({ title: "NotLoadedThreadStatus" }), + Schema.Struct({ + type: Schema.Literal("idle").annotate({ title: "IdleThreadStatusType" }), + }).annotate({ title: "IdleThreadStatus" }), + Schema.Struct({ + type: Schema.Literal("systemError").annotate({ title: "SystemErrorThreadStatusType" }), + }).annotate({ title: "SystemErrorThreadStatus" }), + Schema.Struct({ + activeFlags: Schema.Array(ServerNotification__ThreadActiveFlag), + type: Schema.Literal("active").annotate({ title: "ActiveThreadStatusType" }), + }).annotate({ title: "ActiveThreadStatus" }), + ], + { mode: "oneOf" }, + ).annotate({ description: "Current runtime status for the thread." }), + turns: Schema.Array(ServerNotification__Turn).annotate({ + description: + "Only populated on `thread/resume`, `thread/rollback`, `thread/fork`, and `thread/read` (when `includeTurns` is true) responses. For all other responses and notifications returning a Thread, the turns field will be an empty list.", + }), + updatedAt: Schema.Number.annotate({ + description: "Unix timestamp (in seconds) when the thread was last updated.", + format: "int64", + }).check(Schema.isInt()), +}); + +export type ServerNotification__TurnCompletedNotification = { + readonly threadId: string; + readonly turn: ServerNotification__Turn; +}; +export const ServerNotification__TurnCompletedNotification = Schema.Struct({ + threadId: Schema.String, + turn: ServerNotification__Turn, +}); + +export type ServerNotification__TurnStartedNotification = { + readonly threadId: string; + readonly turn: ServerNotification__Turn; +}; +export const ServerNotification__TurnStartedNotification = Schema.Struct({ + threadId: Schema.String, + turn: ServerNotification__Turn, +}); + +export type ServerRequest__McpElicitationEnumSchema = + | ServerRequest__McpElicitationSingleSelectEnumSchema + | ServerRequest__McpElicitationMultiSelectEnumSchema + | ServerRequest__McpElicitationLegacyTitledEnumSchema; +export const ServerRequest__McpElicitationEnumSchema = Schema.Union([ + ServerRequest__McpElicitationSingleSelectEnumSchema, + ServerRequest__McpElicitationMultiSelectEnumSchema, + ServerRequest__McpElicitationLegacyTitledEnumSchema, +]); + +export type V2ConfigReadResponse__Config = { + readonly analytics?: V2ConfigReadResponse__AnalyticsConfig | null; + readonly approval_policy?: V2ConfigReadResponse__AskForApproval | null; + readonly approvals_reviewer?: V2ConfigReadResponse__ApprovalsReviewer | null; + readonly compact_prompt?: string | null; + readonly developer_instructions?: string | null; + readonly forced_chatgpt_workspace_id?: string | null; + readonly forced_login_method?: V2ConfigReadResponse__ForcedLoginMethod | null; + readonly instructions?: string | null; + readonly model?: string | null; + readonly model_auto_compact_token_limit?: number | null; + readonly model_context_window?: number | null; + readonly model_provider?: string | null; + readonly model_reasoning_effort?: V2ConfigReadResponse__ReasoningEffort | null; + readonly model_reasoning_summary?: V2ConfigReadResponse__ReasoningSummary | null; + readonly model_verbosity?: V2ConfigReadResponse__Verbosity | null; + readonly profile?: string | null; + readonly profiles?: { readonly [x: string]: V2ConfigReadResponse__ProfileV2 }; + readonly review_model?: string | null; + readonly sandbox_mode?: V2ConfigReadResponse__SandboxMode | null; + readonly sandbox_workspace_write?: V2ConfigReadResponse__SandboxWorkspaceWrite | null; + readonly service_tier?: V2ConfigReadResponse__ServiceTier | null; + readonly tools?: V2ConfigReadResponse__ToolsV2 | null; + readonly web_search?: V2ConfigReadResponse__WebSearchMode | null; + readonly [x: string]: unknown; +}; +export const V2ConfigReadResponse__Config = Schema.StructWithRest( + Schema.Struct({ + analytics: Schema.optionalKey( + Schema.Union([V2ConfigReadResponse__AnalyticsConfig, Schema.Null]), + ), + approval_policy: Schema.optionalKey( + Schema.Union([V2ConfigReadResponse__AskForApproval, Schema.Null]), + ), + approvals_reviewer: Schema.optionalKey( + Schema.Union([V2ConfigReadResponse__ApprovalsReviewer, Schema.Null]).annotate({ + description: + "[UNSTABLE] Optional default for where approval requests are routed for review.", + }), + ), + compact_prompt: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + developer_instructions: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + forced_chatgpt_workspace_id: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + forced_login_method: Schema.optionalKey( + Schema.Union([V2ConfigReadResponse__ForcedLoginMethod, Schema.Null]), + ), + instructions: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + model: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + model_auto_compact_token_limit: Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ format: "int64" }).check(Schema.isInt()), + Schema.Null, + ]), + ), + model_context_window: Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ format: "int64" }).check(Schema.isInt()), + Schema.Null, + ]), + ), + model_provider: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + model_reasoning_effort: Schema.optionalKey( + Schema.Union([V2ConfigReadResponse__ReasoningEffort, Schema.Null]), + ), + model_reasoning_summary: Schema.optionalKey( + Schema.Union([V2ConfigReadResponse__ReasoningSummary, Schema.Null]), + ), + model_verbosity: Schema.optionalKey( + Schema.Union([V2ConfigReadResponse__Verbosity, Schema.Null]), + ), + profile: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + profiles: Schema.optionalKey( + Schema.Record(Schema.String, V2ConfigReadResponse__ProfileV2).annotate({ default: {} }), + ), + review_model: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + sandbox_mode: Schema.optionalKey( + Schema.Union([V2ConfigReadResponse__SandboxMode, Schema.Null]), + ), + sandbox_workspace_write: Schema.optionalKey( + Schema.Union([V2ConfigReadResponse__SandboxWorkspaceWrite, Schema.Null]), + ), + service_tier: Schema.optionalKey( + Schema.Union([V2ConfigReadResponse__ServiceTier, Schema.Null]), + ), + tools: Schema.optionalKey(Schema.Union([V2ConfigReadResponse__ToolsV2, Schema.Null])), + web_search: Schema.optionalKey( + Schema.Union([V2ConfigReadResponse__WebSearchMode, Schema.Null]), + ), + }), + [Schema.Record(Schema.String, Schema.Unknown)], +); + +export type V2ThreadForkResponse__Thread = { + readonly agentNickname?: string | null; + readonly agentRole?: string | null; + readonly cliVersion: string; + readonly createdAt: number; + readonly cwd: string; + readonly ephemeral: boolean; + readonly forkedFromId?: string | null; + readonly gitInfo?: V2ThreadForkResponse__GitInfo | null; + readonly id: string; + readonly modelProvider: string; + readonly name?: string | null; + readonly path?: string | null; + readonly preview: string; + readonly source: + | "cli" + | "vscode" + | "exec" + | "appServer" + | "unknown" + | { readonly custom: string } + | { readonly subAgent: V2ThreadForkResponse__SubAgentSource }; + readonly status: + | { readonly type: "notLoaded" } + | { readonly type: "idle" } + | { readonly type: "systemError" } + | { + readonly activeFlags: ReadonlyArray; + readonly type: "active"; + }; + readonly turns: ReadonlyArray; + readonly updatedAt: number; +}; +export const V2ThreadForkResponse__Thread = Schema.Struct({ + agentNickname: Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + description: + "Optional random unique nickname assigned to an AgentControl-spawned sub-agent.", + }), + Schema.Null, + ]), + ), + agentRole: Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + description: "Optional role (agent_role) assigned to an AgentControl-spawned sub-agent.", + }), + Schema.Null, + ]), + ), + cliVersion: Schema.String.annotate({ + description: "Version of the CLI that created the thread.", + }), + createdAt: Schema.Number.annotate({ + description: "Unix timestamp (in seconds) when the thread was created.", + format: "int64", + }).check(Schema.isInt()), + cwd: Schema.String.annotate({ description: "Working directory captured for the thread." }), + ephemeral: Schema.Boolean.annotate({ + description: "Whether the thread is ephemeral and should not be materialized on disk.", + }), + forkedFromId: Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + description: "Source thread id when this thread was created by forking another thread.", + }), + Schema.Null, + ]), + ), + gitInfo: Schema.optionalKey( + Schema.Union([V2ThreadForkResponse__GitInfo, Schema.Null]).annotate({ + description: "Optional Git metadata captured when the thread was created.", + }), + ), + id: Schema.String, + modelProvider: Schema.String.annotate({ + description: "Model provider used for this thread (for example, 'openai').", + }), + name: Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ description: "Optional user-facing thread title." }), + Schema.Null, + ]), + ), + path: Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ description: "[UNSTABLE] Path to the thread on disk." }), + Schema.Null, + ]), + ), + preview: Schema.String.annotate({ + description: "Usually the first user message in the thread, if available.", + }), + source: Schema.Union( + [ + Schema.Literals(["cli", "vscode", "exec", "appServer", "unknown"]), + Schema.Struct({ custom: Schema.String }).annotate({ title: "CustomSessionSource" }), + Schema.Struct({ subAgent: V2ThreadForkResponse__SubAgentSource }).annotate({ + title: "SubAgentSessionSource", + }), + ], + { mode: "oneOf" }, + ).annotate({ + description: "Origin of the thread (CLI, VSCode, codex exec, codex app-server, etc.).", + }), + status: Schema.Union( + [ + Schema.Struct({ + type: Schema.Literal("notLoaded").annotate({ title: "NotLoadedThreadStatusType" }), + }).annotate({ title: "NotLoadedThreadStatus" }), + Schema.Struct({ + type: Schema.Literal("idle").annotate({ title: "IdleThreadStatusType" }), + }).annotate({ title: "IdleThreadStatus" }), + Schema.Struct({ + type: Schema.Literal("systemError").annotate({ title: "SystemErrorThreadStatusType" }), + }).annotate({ title: "SystemErrorThreadStatus" }), + Schema.Struct({ + activeFlags: Schema.Array(V2ThreadForkResponse__ThreadActiveFlag), + type: Schema.Literal("active").annotate({ title: "ActiveThreadStatusType" }), + }).annotate({ title: "ActiveThreadStatus" }), + ], + { mode: "oneOf" }, + ).annotate({ description: "Current runtime status for the thread." }), + turns: Schema.Array(V2ThreadForkResponse__Turn).annotate({ + description: + "Only populated on `thread/resume`, `thread/rollback`, `thread/fork`, and `thread/read` (when `includeTurns` is true) responses. For all other responses and notifications returning a Thread, the turns field will be an empty list.", + }), + updatedAt: Schema.Number.annotate({ + description: "Unix timestamp (in seconds) when the thread was last updated.", + format: "int64", + }).check(Schema.isInt()), +}); + +export type V2ThreadListResponse__Thread = { + readonly agentNickname?: string | null; + readonly agentRole?: string | null; + readonly cliVersion: string; + readonly createdAt: number; + readonly cwd: string; + readonly ephemeral: boolean; + readonly forkedFromId?: string | null; + readonly gitInfo?: V2ThreadListResponse__GitInfo | null; + readonly id: string; + readonly modelProvider: string; + readonly name?: string | null; + readonly path?: string | null; + readonly preview: string; + readonly source: + | "cli" + | "vscode" + | "exec" + | "appServer" + | "unknown" + | { readonly custom: string } + | { readonly subAgent: V2ThreadListResponse__SubAgentSource }; + readonly status: + | { readonly type: "notLoaded" } + | { readonly type: "idle" } + | { readonly type: "systemError" } + | { + readonly activeFlags: ReadonlyArray; + readonly type: "active"; + }; + readonly turns: ReadonlyArray; + readonly updatedAt: number; +}; +export const V2ThreadListResponse__Thread = Schema.Struct({ + agentNickname: Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + description: + "Optional random unique nickname assigned to an AgentControl-spawned sub-agent.", + }), + Schema.Null, + ]), + ), + agentRole: Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + description: "Optional role (agent_role) assigned to an AgentControl-spawned sub-agent.", + }), + Schema.Null, + ]), + ), + cliVersion: Schema.String.annotate({ + description: "Version of the CLI that created the thread.", + }), + createdAt: Schema.Number.annotate({ + description: "Unix timestamp (in seconds) when the thread was created.", + format: "int64", + }).check(Schema.isInt()), + cwd: Schema.String.annotate({ description: "Working directory captured for the thread." }), + ephemeral: Schema.Boolean.annotate({ + description: "Whether the thread is ephemeral and should not be materialized on disk.", + }), + forkedFromId: Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + description: "Source thread id when this thread was created by forking another thread.", + }), + Schema.Null, + ]), + ), + gitInfo: Schema.optionalKey( + Schema.Union([V2ThreadListResponse__GitInfo, Schema.Null]).annotate({ + description: "Optional Git metadata captured when the thread was created.", + }), + ), + id: Schema.String, + modelProvider: Schema.String.annotate({ + description: "Model provider used for this thread (for example, 'openai').", + }), + name: Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ description: "Optional user-facing thread title." }), + Schema.Null, + ]), + ), + path: Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ description: "[UNSTABLE] Path to the thread on disk." }), + Schema.Null, + ]), + ), + preview: Schema.String.annotate({ + description: "Usually the first user message in the thread, if available.", + }), + source: Schema.Union( + [ + Schema.Literals(["cli", "vscode", "exec", "appServer", "unknown"]), + Schema.Struct({ custom: Schema.String }).annotate({ title: "CustomSessionSource" }), + Schema.Struct({ subAgent: V2ThreadListResponse__SubAgentSource }).annotate({ + title: "SubAgentSessionSource", + }), + ], + { mode: "oneOf" }, + ).annotate({ + description: "Origin of the thread (CLI, VSCode, codex exec, codex app-server, etc.).", + }), + status: Schema.Union( + [ + Schema.Struct({ + type: Schema.Literal("notLoaded").annotate({ title: "NotLoadedThreadStatusType" }), + }).annotate({ title: "NotLoadedThreadStatus" }), + Schema.Struct({ + type: Schema.Literal("idle").annotate({ title: "IdleThreadStatusType" }), + }).annotate({ title: "IdleThreadStatus" }), + Schema.Struct({ + type: Schema.Literal("systemError").annotate({ title: "SystemErrorThreadStatusType" }), + }).annotate({ title: "SystemErrorThreadStatus" }), + Schema.Struct({ + activeFlags: Schema.Array(V2ThreadListResponse__ThreadActiveFlag), + type: Schema.Literal("active").annotate({ title: "ActiveThreadStatusType" }), + }).annotate({ title: "ActiveThreadStatus" }), + ], + { mode: "oneOf" }, + ).annotate({ description: "Current runtime status for the thread." }), + turns: Schema.Array(V2ThreadListResponse__Turn).annotate({ + description: + "Only populated on `thread/resume`, `thread/rollback`, `thread/fork`, and `thread/read` (when `includeTurns` is true) responses. For all other responses and notifications returning a Thread, the turns field will be an empty list.", + }), + updatedAt: Schema.Number.annotate({ + description: "Unix timestamp (in seconds) when the thread was last updated.", + format: "int64", + }).check(Schema.isInt()), +}); + +export type V2ThreadMetadataUpdateResponse__Thread = { + readonly agentNickname?: string | null; + readonly agentRole?: string | null; + readonly cliVersion: string; + readonly createdAt: number; + readonly cwd: string; + readonly ephemeral: boolean; + readonly forkedFromId?: string | null; + readonly gitInfo?: V2ThreadMetadataUpdateResponse__GitInfo | null; + readonly id: string; + readonly modelProvider: string; + readonly name?: string | null; + readonly path?: string | null; + readonly preview: string; + readonly source: + | "cli" + | "vscode" + | "exec" + | "appServer" + | "unknown" + | { readonly custom: string } + | { readonly subAgent: V2ThreadMetadataUpdateResponse__SubAgentSource }; + readonly status: + | { readonly type: "notLoaded" } + | { readonly type: "idle" } + | { readonly type: "systemError" } + | { + readonly activeFlags: ReadonlyArray; + readonly type: "active"; + }; + readonly turns: ReadonlyArray; + readonly updatedAt: number; +}; +export const V2ThreadMetadataUpdateResponse__Thread = Schema.Struct({ + agentNickname: Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + description: + "Optional random unique nickname assigned to an AgentControl-spawned sub-agent.", + }), + Schema.Null, + ]), + ), + agentRole: Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + description: "Optional role (agent_role) assigned to an AgentControl-spawned sub-agent.", + }), + Schema.Null, + ]), + ), + cliVersion: Schema.String.annotate({ + description: "Version of the CLI that created the thread.", + }), + createdAt: Schema.Number.annotate({ + description: "Unix timestamp (in seconds) when the thread was created.", + format: "int64", + }).check(Schema.isInt()), + cwd: Schema.String.annotate({ description: "Working directory captured for the thread." }), + ephemeral: Schema.Boolean.annotate({ + description: "Whether the thread is ephemeral and should not be materialized on disk.", + }), + forkedFromId: Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + description: "Source thread id when this thread was created by forking another thread.", + }), + Schema.Null, + ]), + ), + gitInfo: Schema.optionalKey( + Schema.Union([V2ThreadMetadataUpdateResponse__GitInfo, Schema.Null]).annotate({ + description: "Optional Git metadata captured when the thread was created.", + }), + ), + id: Schema.String, + modelProvider: Schema.String.annotate({ + description: "Model provider used for this thread (for example, 'openai').", + }), + name: Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ description: "Optional user-facing thread title." }), + Schema.Null, + ]), + ), + path: Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ description: "[UNSTABLE] Path to the thread on disk." }), + Schema.Null, + ]), + ), + preview: Schema.String.annotate({ + description: "Usually the first user message in the thread, if available.", + }), + source: Schema.Union( + [ + Schema.Literals(["cli", "vscode", "exec", "appServer", "unknown"]), + Schema.Struct({ custom: Schema.String }).annotate({ title: "CustomSessionSource" }), + Schema.Struct({ subAgent: V2ThreadMetadataUpdateResponse__SubAgentSource }).annotate({ + title: "SubAgentSessionSource", + }), + ], + { mode: "oneOf" }, + ).annotate({ + description: "Origin of the thread (CLI, VSCode, codex exec, codex app-server, etc.).", + }), + status: Schema.Union( + [ + Schema.Struct({ + type: Schema.Literal("notLoaded").annotate({ title: "NotLoadedThreadStatusType" }), + }).annotate({ title: "NotLoadedThreadStatus" }), + Schema.Struct({ + type: Schema.Literal("idle").annotate({ title: "IdleThreadStatusType" }), + }).annotate({ title: "IdleThreadStatus" }), + Schema.Struct({ + type: Schema.Literal("systemError").annotate({ title: "SystemErrorThreadStatusType" }), + }).annotate({ title: "SystemErrorThreadStatus" }), + Schema.Struct({ + activeFlags: Schema.Array(V2ThreadMetadataUpdateResponse__ThreadActiveFlag), + type: Schema.Literal("active").annotate({ title: "ActiveThreadStatusType" }), + }).annotate({ title: "ActiveThreadStatus" }), + ], + { mode: "oneOf" }, + ).annotate({ description: "Current runtime status for the thread." }), + turns: Schema.Array(V2ThreadMetadataUpdateResponse__Turn).annotate({ + description: + "Only populated on `thread/resume`, `thread/rollback`, `thread/fork`, and `thread/read` (when `includeTurns` is true) responses. For all other responses and notifications returning a Thread, the turns field will be an empty list.", + }), + updatedAt: Schema.Number.annotate({ + description: "Unix timestamp (in seconds) when the thread was last updated.", + format: "int64", + }).check(Schema.isInt()), +}); + +export type V2ThreadReadResponse__Thread = { + readonly agentNickname?: string | null; + readonly agentRole?: string | null; + readonly cliVersion: string; + readonly createdAt: number; + readonly cwd: string; + readonly ephemeral: boolean; + readonly forkedFromId?: string | null; + readonly gitInfo?: V2ThreadReadResponse__GitInfo | null; + readonly id: string; + readonly modelProvider: string; + readonly name?: string | null; + readonly path?: string | null; + readonly preview: string; + readonly source: + | "cli" + | "vscode" + | "exec" + | "appServer" + | "unknown" + | { readonly custom: string } + | { readonly subAgent: V2ThreadReadResponse__SubAgentSource }; + readonly status: + | { readonly type: "notLoaded" } + | { readonly type: "idle" } + | { readonly type: "systemError" } + | { + readonly activeFlags: ReadonlyArray; + readonly type: "active"; + }; + readonly turns: ReadonlyArray; + readonly updatedAt: number; +}; +export const V2ThreadReadResponse__Thread = Schema.Struct({ + agentNickname: Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + description: + "Optional random unique nickname assigned to an AgentControl-spawned sub-agent.", + }), + Schema.Null, + ]), + ), + agentRole: Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + description: "Optional role (agent_role) assigned to an AgentControl-spawned sub-agent.", + }), + Schema.Null, + ]), + ), + cliVersion: Schema.String.annotate({ + description: "Version of the CLI that created the thread.", + }), + createdAt: Schema.Number.annotate({ + description: "Unix timestamp (in seconds) when the thread was created.", + format: "int64", + }).check(Schema.isInt()), + cwd: Schema.String.annotate({ description: "Working directory captured for the thread." }), + ephemeral: Schema.Boolean.annotate({ + description: "Whether the thread is ephemeral and should not be materialized on disk.", + }), + forkedFromId: Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + description: "Source thread id when this thread was created by forking another thread.", + }), + Schema.Null, + ]), + ), + gitInfo: Schema.optionalKey( + Schema.Union([V2ThreadReadResponse__GitInfo, Schema.Null]).annotate({ + description: "Optional Git metadata captured when the thread was created.", + }), + ), + id: Schema.String, + modelProvider: Schema.String.annotate({ + description: "Model provider used for this thread (for example, 'openai').", + }), + name: Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ description: "Optional user-facing thread title." }), + Schema.Null, + ]), + ), + path: Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ description: "[UNSTABLE] Path to the thread on disk." }), + Schema.Null, + ]), + ), + preview: Schema.String.annotate({ + description: "Usually the first user message in the thread, if available.", + }), + source: Schema.Union( + [ + Schema.Literals(["cli", "vscode", "exec", "appServer", "unknown"]), + Schema.Struct({ custom: Schema.String }).annotate({ title: "CustomSessionSource" }), + Schema.Struct({ subAgent: V2ThreadReadResponse__SubAgentSource }).annotate({ + title: "SubAgentSessionSource", + }), + ], + { mode: "oneOf" }, + ).annotate({ + description: "Origin of the thread (CLI, VSCode, codex exec, codex app-server, etc.).", + }), + status: Schema.Union( + [ + Schema.Struct({ + type: Schema.Literal("notLoaded").annotate({ title: "NotLoadedThreadStatusType" }), + }).annotate({ title: "NotLoadedThreadStatus" }), + Schema.Struct({ + type: Schema.Literal("idle").annotate({ title: "IdleThreadStatusType" }), + }).annotate({ title: "IdleThreadStatus" }), + Schema.Struct({ + type: Schema.Literal("systemError").annotate({ title: "SystemErrorThreadStatusType" }), + }).annotate({ title: "SystemErrorThreadStatus" }), + Schema.Struct({ + activeFlags: Schema.Array(V2ThreadReadResponse__ThreadActiveFlag), + type: Schema.Literal("active").annotate({ title: "ActiveThreadStatusType" }), + }).annotate({ title: "ActiveThreadStatus" }), + ], + { mode: "oneOf" }, + ).annotate({ description: "Current runtime status for the thread." }), + turns: Schema.Array(V2ThreadReadResponse__Turn).annotate({ + description: + "Only populated on `thread/resume`, `thread/rollback`, `thread/fork`, and `thread/read` (when `includeTurns` is true) responses. For all other responses and notifications returning a Thread, the turns field will be an empty list.", + }), + updatedAt: Schema.Number.annotate({ + description: "Unix timestamp (in seconds) when the thread was last updated.", + format: "int64", + }).check(Schema.isInt()), +}); + +export type V2ThreadResumeResponse__Thread = { + readonly agentNickname?: string | null; + readonly agentRole?: string | null; + readonly cliVersion: string; + readonly createdAt: number; + readonly cwd: string; + readonly ephemeral: boolean; + readonly forkedFromId?: string | null; + readonly gitInfo?: V2ThreadResumeResponse__GitInfo | null; + readonly id: string; + readonly modelProvider: string; + readonly name?: string | null; + readonly path?: string | null; + readonly preview: string; + readonly source: + | "cli" + | "vscode" + | "exec" + | "appServer" + | "unknown" + | { readonly custom: string } + | { readonly subAgent: V2ThreadResumeResponse__SubAgentSource }; + readonly status: + | { readonly type: "notLoaded" } + | { readonly type: "idle" } + | { readonly type: "systemError" } + | { + readonly activeFlags: ReadonlyArray; + readonly type: "active"; + }; + readonly turns: ReadonlyArray; + readonly updatedAt: number; +}; +export const V2ThreadResumeResponse__Thread = Schema.Struct({ + agentNickname: Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + description: + "Optional random unique nickname assigned to an AgentControl-spawned sub-agent.", + }), + Schema.Null, + ]), + ), + agentRole: Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + description: "Optional role (agent_role) assigned to an AgentControl-spawned sub-agent.", + }), + Schema.Null, + ]), + ), + cliVersion: Schema.String.annotate({ + description: "Version of the CLI that created the thread.", + }), + createdAt: Schema.Number.annotate({ + description: "Unix timestamp (in seconds) when the thread was created.", + format: "int64", + }).check(Schema.isInt()), + cwd: Schema.String.annotate({ description: "Working directory captured for the thread." }), + ephemeral: Schema.Boolean.annotate({ + description: "Whether the thread is ephemeral and should not be materialized on disk.", + }), + forkedFromId: Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + description: "Source thread id when this thread was created by forking another thread.", + }), + Schema.Null, + ]), + ), + gitInfo: Schema.optionalKey( + Schema.Union([V2ThreadResumeResponse__GitInfo, Schema.Null]).annotate({ + description: "Optional Git metadata captured when the thread was created.", + }), + ), + id: Schema.String, + modelProvider: Schema.String.annotate({ + description: "Model provider used for this thread (for example, 'openai').", + }), + name: Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ description: "Optional user-facing thread title." }), + Schema.Null, + ]), + ), + path: Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ description: "[UNSTABLE] Path to the thread on disk." }), + Schema.Null, + ]), + ), + preview: Schema.String.annotate({ + description: "Usually the first user message in the thread, if available.", + }), + source: Schema.Union( + [ + Schema.Literals(["cli", "vscode", "exec", "appServer", "unknown"]), + Schema.Struct({ custom: Schema.String }).annotate({ title: "CustomSessionSource" }), + Schema.Struct({ subAgent: V2ThreadResumeResponse__SubAgentSource }).annotate({ + title: "SubAgentSessionSource", + }), + ], + { mode: "oneOf" }, + ).annotate({ + description: "Origin of the thread (CLI, VSCode, codex exec, codex app-server, etc.).", + }), + status: Schema.Union( + [ + Schema.Struct({ + type: Schema.Literal("notLoaded").annotate({ title: "NotLoadedThreadStatusType" }), + }).annotate({ title: "NotLoadedThreadStatus" }), + Schema.Struct({ + type: Schema.Literal("idle").annotate({ title: "IdleThreadStatusType" }), + }).annotate({ title: "IdleThreadStatus" }), + Schema.Struct({ + type: Schema.Literal("systemError").annotate({ title: "SystemErrorThreadStatusType" }), + }).annotate({ title: "SystemErrorThreadStatus" }), + Schema.Struct({ + activeFlags: Schema.Array(V2ThreadResumeResponse__ThreadActiveFlag), + type: Schema.Literal("active").annotate({ title: "ActiveThreadStatusType" }), + }).annotate({ title: "ActiveThreadStatus" }), + ], + { mode: "oneOf" }, + ).annotate({ description: "Current runtime status for the thread." }), + turns: Schema.Array(V2ThreadResumeResponse__Turn).annotate({ + description: + "Only populated on `thread/resume`, `thread/rollback`, `thread/fork`, and `thread/read` (when `includeTurns` is true) responses. For all other responses and notifications returning a Thread, the turns field will be an empty list.", + }), + updatedAt: Schema.Number.annotate({ + description: "Unix timestamp (in seconds) when the thread was last updated.", + format: "int64", + }).check(Schema.isInt()), +}); + +export type V2ThreadStartedNotification__Thread = { + readonly agentNickname?: string | null; + readonly agentRole?: string | null; + readonly cliVersion: string; + readonly createdAt: number; + readonly cwd: string; + readonly ephemeral: boolean; + readonly forkedFromId?: string | null; + readonly gitInfo?: V2ThreadStartedNotification__GitInfo | null; + readonly id: string; + readonly modelProvider: string; + readonly name?: string | null; + readonly path?: string | null; + readonly preview: string; + readonly source: + | "cli" + | "vscode" + | "exec" + | "appServer" + | "unknown" + | { readonly custom: string } + | { readonly subAgent: V2ThreadStartedNotification__SubAgentSource }; + readonly status: + | { readonly type: "notLoaded" } + | { readonly type: "idle" } + | { readonly type: "systemError" } + | { + readonly activeFlags: ReadonlyArray; + readonly type: "active"; + }; + readonly turns: ReadonlyArray; + readonly updatedAt: number; +}; +export const V2ThreadStartedNotification__Thread = Schema.Struct({ + agentNickname: Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + description: + "Optional random unique nickname assigned to an AgentControl-spawned sub-agent.", + }), + Schema.Null, + ]), + ), + agentRole: Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + description: "Optional role (agent_role) assigned to an AgentControl-spawned sub-agent.", + }), + Schema.Null, + ]), + ), + cliVersion: Schema.String.annotate({ + description: "Version of the CLI that created the thread.", + }), + createdAt: Schema.Number.annotate({ + description: "Unix timestamp (in seconds) when the thread was created.", + format: "int64", + }).check(Schema.isInt()), + cwd: Schema.String.annotate({ description: "Working directory captured for the thread." }), + ephemeral: Schema.Boolean.annotate({ + description: "Whether the thread is ephemeral and should not be materialized on disk.", + }), + forkedFromId: Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + description: "Source thread id when this thread was created by forking another thread.", + }), + Schema.Null, + ]), + ), + gitInfo: Schema.optionalKey( + Schema.Union([V2ThreadStartedNotification__GitInfo, Schema.Null]).annotate({ + description: "Optional Git metadata captured when the thread was created.", + }), + ), + id: Schema.String, + modelProvider: Schema.String.annotate({ + description: "Model provider used for this thread (for example, 'openai').", + }), + name: Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ description: "Optional user-facing thread title." }), + Schema.Null, + ]), + ), + path: Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ description: "[UNSTABLE] Path to the thread on disk." }), + Schema.Null, + ]), + ), + preview: Schema.String.annotate({ + description: "Usually the first user message in the thread, if available.", + }), + source: Schema.Union( + [ + Schema.Literals(["cli", "vscode", "exec", "appServer", "unknown"]), + Schema.Struct({ custom: Schema.String }).annotate({ title: "CustomSessionSource" }), + Schema.Struct({ subAgent: V2ThreadStartedNotification__SubAgentSource }).annotate({ + title: "SubAgentSessionSource", + }), + ], + { mode: "oneOf" }, + ).annotate({ + description: "Origin of the thread (CLI, VSCode, codex exec, codex app-server, etc.).", + }), + status: Schema.Union( + [ + Schema.Struct({ + type: Schema.Literal("notLoaded").annotate({ title: "NotLoadedThreadStatusType" }), + }).annotate({ title: "NotLoadedThreadStatus" }), + Schema.Struct({ + type: Schema.Literal("idle").annotate({ title: "IdleThreadStatusType" }), + }).annotate({ title: "IdleThreadStatus" }), + Schema.Struct({ + type: Schema.Literal("systemError").annotate({ title: "SystemErrorThreadStatusType" }), + }).annotate({ title: "SystemErrorThreadStatus" }), + Schema.Struct({ + activeFlags: Schema.Array(V2ThreadStartedNotification__ThreadActiveFlag), + type: Schema.Literal("active").annotate({ title: "ActiveThreadStatusType" }), + }).annotate({ title: "ActiveThreadStatus" }), + ], + { mode: "oneOf" }, + ).annotate({ description: "Current runtime status for the thread." }), + turns: Schema.Array(V2ThreadStartedNotification__Turn).annotate({ + description: + "Only populated on `thread/resume`, `thread/rollback`, `thread/fork`, and `thread/read` (when `includeTurns` is true) responses. For all other responses and notifications returning a Thread, the turns field will be an empty list.", + }), + updatedAt: Schema.Number.annotate({ + description: "Unix timestamp (in seconds) when the thread was last updated.", + format: "int64", + }).check(Schema.isInt()), +}); + +export type V2ThreadStartResponse__Thread = { + readonly agentNickname?: string | null; + readonly agentRole?: string | null; + readonly cliVersion: string; + readonly createdAt: number; + readonly cwd: string; + readonly ephemeral: boolean; + readonly forkedFromId?: string | null; + readonly gitInfo?: V2ThreadStartResponse__GitInfo | null; + readonly id: string; + readonly modelProvider: string; + readonly name?: string | null; + readonly path?: string | null; + readonly preview: string; + readonly source: + | "cli" + | "vscode" + | "exec" + | "appServer" + | "unknown" + | { readonly custom: string } + | { readonly subAgent: V2ThreadStartResponse__SubAgentSource }; + readonly status: + | { readonly type: "notLoaded" } + | { readonly type: "idle" } + | { readonly type: "systemError" } + | { + readonly activeFlags: ReadonlyArray; + readonly type: "active"; + }; + readonly turns: ReadonlyArray; + readonly updatedAt: number; +}; +export const V2ThreadStartResponse__Thread = Schema.Struct({ + agentNickname: Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + description: + "Optional random unique nickname assigned to an AgentControl-spawned sub-agent.", + }), + Schema.Null, + ]), + ), + agentRole: Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + description: "Optional role (agent_role) assigned to an AgentControl-spawned sub-agent.", + }), + Schema.Null, + ]), + ), + cliVersion: Schema.String.annotate({ + description: "Version of the CLI that created the thread.", + }), + createdAt: Schema.Number.annotate({ + description: "Unix timestamp (in seconds) when the thread was created.", + format: "int64", + }).check(Schema.isInt()), + cwd: Schema.String.annotate({ description: "Working directory captured for the thread." }), + ephemeral: Schema.Boolean.annotate({ + description: "Whether the thread is ephemeral and should not be materialized on disk.", + }), + forkedFromId: Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + description: "Source thread id when this thread was created by forking another thread.", + }), + Schema.Null, + ]), + ), + gitInfo: Schema.optionalKey( + Schema.Union([V2ThreadStartResponse__GitInfo, Schema.Null]).annotate({ + description: "Optional Git metadata captured when the thread was created.", + }), + ), + id: Schema.String, + modelProvider: Schema.String.annotate({ + description: "Model provider used for this thread (for example, 'openai').", + }), + name: Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ description: "Optional user-facing thread title." }), + Schema.Null, + ]), + ), + path: Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ description: "[UNSTABLE] Path to the thread on disk." }), + Schema.Null, + ]), + ), + preview: Schema.String.annotate({ + description: "Usually the first user message in the thread, if available.", + }), + source: Schema.Union( + [ + Schema.Literals(["cli", "vscode", "exec", "appServer", "unknown"]), + Schema.Struct({ custom: Schema.String }).annotate({ title: "CustomSessionSource" }), + Schema.Struct({ subAgent: V2ThreadStartResponse__SubAgentSource }).annotate({ + title: "SubAgentSessionSource", + }), + ], + { mode: "oneOf" }, + ).annotate({ + description: "Origin of the thread (CLI, VSCode, codex exec, codex app-server, etc.).", + }), + status: Schema.Union( + [ + Schema.Struct({ + type: Schema.Literal("notLoaded").annotate({ title: "NotLoadedThreadStatusType" }), + }).annotate({ title: "NotLoadedThreadStatus" }), + Schema.Struct({ + type: Schema.Literal("idle").annotate({ title: "IdleThreadStatusType" }), + }).annotate({ title: "IdleThreadStatus" }), + Schema.Struct({ + type: Schema.Literal("systemError").annotate({ title: "SystemErrorThreadStatusType" }), + }).annotate({ title: "SystemErrorThreadStatus" }), + Schema.Struct({ + activeFlags: Schema.Array(V2ThreadStartResponse__ThreadActiveFlag), + type: Schema.Literal("active").annotate({ title: "ActiveThreadStatusType" }), + }).annotate({ title: "ActiveThreadStatus" }), + ], + { mode: "oneOf" }, + ).annotate({ description: "Current runtime status for the thread." }), + turns: Schema.Array(V2ThreadStartResponse__Turn).annotate({ + description: + "Only populated on `thread/resume`, `thread/rollback`, `thread/fork`, and `thread/read` (when `includeTurns` is true) responses. For all other responses and notifications returning a Thread, the turns field will be an empty list.", + }), + updatedAt: Schema.Number.annotate({ + description: "Unix timestamp (in seconds) when the thread was last updated.", + format: "int64", + }).check(Schema.isInt()), +}); + +export type V2ThreadUnarchiveResponse__Thread = { + readonly agentNickname?: string | null; + readonly agentRole?: string | null; + readonly cliVersion: string; + readonly createdAt: number; + readonly cwd: string; + readonly ephemeral: boolean; + readonly forkedFromId?: string | null; + readonly gitInfo?: V2ThreadUnarchiveResponse__GitInfo | null; + readonly id: string; + readonly modelProvider: string; + readonly name?: string | null; + readonly path?: string | null; + readonly preview: string; + readonly source: + | "cli" + | "vscode" + | "exec" + | "appServer" + | "unknown" + | { readonly custom: string } + | { readonly subAgent: V2ThreadUnarchiveResponse__SubAgentSource }; + readonly status: + | { readonly type: "notLoaded" } + | { readonly type: "idle" } + | { readonly type: "systemError" } + | { + readonly activeFlags: ReadonlyArray; + readonly type: "active"; + }; + readonly turns: ReadonlyArray; + readonly updatedAt: number; +}; +export const V2ThreadUnarchiveResponse__Thread = Schema.Struct({ + agentNickname: Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + description: + "Optional random unique nickname assigned to an AgentControl-spawned sub-agent.", + }), + Schema.Null, + ]), + ), + agentRole: Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + description: "Optional role (agent_role) assigned to an AgentControl-spawned sub-agent.", + }), + Schema.Null, + ]), + ), + cliVersion: Schema.String.annotate({ + description: "Version of the CLI that created the thread.", + }), + createdAt: Schema.Number.annotate({ + description: "Unix timestamp (in seconds) when the thread was created.", + format: "int64", + }).check(Schema.isInt()), + cwd: Schema.String.annotate({ description: "Working directory captured for the thread." }), + ephemeral: Schema.Boolean.annotate({ + description: "Whether the thread is ephemeral and should not be materialized on disk.", + }), + forkedFromId: Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + description: "Source thread id when this thread was created by forking another thread.", + }), + Schema.Null, + ]), + ), + gitInfo: Schema.optionalKey( + Schema.Union([V2ThreadUnarchiveResponse__GitInfo, Schema.Null]).annotate({ + description: "Optional Git metadata captured when the thread was created.", + }), + ), + id: Schema.String, + modelProvider: Schema.String.annotate({ + description: "Model provider used for this thread (for example, 'openai').", + }), + name: Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ description: "Optional user-facing thread title." }), + Schema.Null, + ]), + ), + path: Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ description: "[UNSTABLE] Path to the thread on disk." }), + Schema.Null, + ]), + ), + preview: Schema.String.annotate({ + description: "Usually the first user message in the thread, if available.", + }), + source: Schema.Union( + [ + Schema.Literals(["cli", "vscode", "exec", "appServer", "unknown"]), + Schema.Struct({ custom: Schema.String }).annotate({ title: "CustomSessionSource" }), + Schema.Struct({ subAgent: V2ThreadUnarchiveResponse__SubAgentSource }).annotate({ + title: "SubAgentSessionSource", + }), + ], + { mode: "oneOf" }, + ).annotate({ + description: "Origin of the thread (CLI, VSCode, codex exec, codex app-server, etc.).", + }), + status: Schema.Union( + [ + Schema.Struct({ + type: Schema.Literal("notLoaded").annotate({ title: "NotLoadedThreadStatusType" }), + }).annotate({ title: "NotLoadedThreadStatus" }), + Schema.Struct({ + type: Schema.Literal("idle").annotate({ title: "IdleThreadStatusType" }), + }).annotate({ title: "IdleThreadStatus" }), + Schema.Struct({ + type: Schema.Literal("systemError").annotate({ title: "SystemErrorThreadStatusType" }), + }).annotate({ title: "SystemErrorThreadStatus" }), + Schema.Struct({ + activeFlags: Schema.Array(V2ThreadUnarchiveResponse__ThreadActiveFlag), + type: Schema.Literal("active").annotate({ title: "ActiveThreadStatusType" }), + }).annotate({ title: "ActiveThreadStatus" }), + ], + { mode: "oneOf" }, + ).annotate({ description: "Current runtime status for the thread." }), + turns: Schema.Array(V2ThreadUnarchiveResponse__Turn).annotate({ + description: + "Only populated on `thread/resume`, `thread/rollback`, `thread/fork`, and `thread/read` (when `includeTurns` is true) responses. For all other responses and notifications returning a Thread, the turns field will be an empty list.", + }), + updatedAt: Schema.Number.annotate({ + description: "Unix timestamp (in seconds) when the thread was last updated.", + format: "int64", + }).check(Schema.isInt()), +}); + +export type McpServerElicitationRequestParams__McpElicitationPrimitiveSchema = + | McpServerElicitationRequestParams__McpElicitationEnumSchema + | McpServerElicitationRequestParams__McpElicitationStringSchema + | McpServerElicitationRequestParams__McpElicitationNumberSchema + | McpServerElicitationRequestParams__McpElicitationBooleanSchema; +export const McpServerElicitationRequestParams__McpElicitationPrimitiveSchema = Schema.Union([ + McpServerElicitationRequestParams__McpElicitationEnumSchema, + McpServerElicitationRequestParams__McpElicitationStringSchema, + McpServerElicitationRequestParams__McpElicitationNumberSchema, + McpServerElicitationRequestParams__McpElicitationBooleanSchema, +]); + +export type ServerNotification__ThreadStartedNotification = { + readonly thread: ServerNotification__Thread; +}; +export const ServerNotification__ThreadStartedNotification = Schema.Struct({ + thread: ServerNotification__Thread, +}); + +export type ServerRequest__McpElicitationPrimitiveSchema = + | ServerRequest__McpElicitationEnumSchema + | ServerRequest__McpElicitationStringSchema + | ServerRequest__McpElicitationNumberSchema + | ServerRequest__McpElicitationBooleanSchema; +export const ServerRequest__McpElicitationPrimitiveSchema = Schema.Union([ + ServerRequest__McpElicitationEnumSchema, + ServerRequest__McpElicitationStringSchema, + ServerRequest__McpElicitationNumberSchema, + ServerRequest__McpElicitationBooleanSchema, +]); + +export type McpServerElicitationRequestParams__McpElicitationSchema = { + readonly $schema?: string | null; + readonly properties: { + readonly [x: string]: McpServerElicitationRequestParams__McpElicitationPrimitiveSchema; + }; + readonly required?: ReadonlyArray | null; + readonly type: McpServerElicitationRequestParams__McpElicitationObjectType; +}; +export const McpServerElicitationRequestParams__McpElicitationSchema = Schema.Struct({ + $schema: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + properties: Schema.Record( + Schema.String, + McpServerElicitationRequestParams__McpElicitationPrimitiveSchema, + ), + required: Schema.optionalKey(Schema.Union([Schema.Array(Schema.String), Schema.Null])), + type: McpServerElicitationRequestParams__McpElicitationObjectType, +}).annotate({ + description: + "Typed form schema for MCP `elicitation/create` requests.\n\nThis matches the `requestedSchema` shape from the MCP 2025-11-25 `ElicitRequestFormParams` schema.", +}); + +export type ServerRequest__McpElicitationSchema = { + readonly $schema?: string | null; + readonly properties: { readonly [x: string]: ServerRequest__McpElicitationPrimitiveSchema }; + readonly required?: ReadonlyArray | null; + readonly type: ServerRequest__McpElicitationObjectType; +}; +export const ServerRequest__McpElicitationSchema = Schema.Struct({ + $schema: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + properties: Schema.Record(Schema.String, ServerRequest__McpElicitationPrimitiveSchema), + required: Schema.optionalKey(Schema.Union([Schema.Array(Schema.String), Schema.Null])), + type: ServerRequest__McpElicitationObjectType, +}).annotate({ + description: + "Typed form schema for MCP `elicitation/create` requests.\n\nThis matches the `requestedSchema` shape from the MCP 2025-11-25 `ElicitRequestFormParams` schema.", +}); + +export type ServerRequest__McpServerElicitationRequestParams = + | { + readonly _meta?: unknown; + readonly message: string; + readonly mode: "form"; + readonly requestedSchema: ServerRequest__McpElicitationSchema; + readonly serverName: string; + readonly threadId: string; + readonly turnId?: string | null; + } + | { + readonly _meta?: unknown; + readonly elicitationId: string; + readonly message: string; + readonly mode: "url"; + readonly url: string; + readonly serverName: string; + readonly threadId: string; + readonly turnId?: string | null; + }; +export const ServerRequest__McpServerElicitationRequestParams = Schema.Union( + [ + Schema.Struct({ + _meta: Schema.optionalKey(Schema.Unknown), + message: Schema.String, + mode: Schema.Literal("form"), + requestedSchema: ServerRequest__McpElicitationSchema, + serverName: Schema.String, + threadId: Schema.String, + turnId: Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + description: + "Active Codex turn when this elicitation was observed, if app-server could correlate one.\n\nThis is nullable because MCP models elicitation as a standalone server-to-client request identified by the MCP server request id. It may be triggered during a turn, but turn context is app-server correlation rather than part of the protocol identity of the elicitation itself.", + }), + Schema.Null, + ]), + ), + }), + Schema.Struct({ + _meta: Schema.optionalKey(Schema.Unknown), + elicitationId: Schema.String, + message: Schema.String, + mode: Schema.Literal("url"), + url: Schema.String, + serverName: Schema.String, + threadId: Schema.String, + turnId: Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + description: + "Active Codex turn when this elicitation was observed, if app-server could correlate one.\n\nThis is nullable because MCP models elicitation as a standalone server-to-client request identified by the MCP server request id. It may be triggered during a turn, but turn context is app-server correlation rather than part of the protocol identity of the elicitation itself.", + }), + Schema.Null, + ]), + ), + }), + ], + { mode: "oneOf" }, +); + +export type ApplyPatchApprovalParams = { + readonly callId: string; + readonly conversationId: ApplyPatchApprovalParams__ThreadId; + readonly fileChanges: { readonly [x: string]: ApplyPatchApprovalParams__FileChange }; + readonly grantRoot?: string | null; + readonly reason?: string | null; +}; +export const ApplyPatchApprovalParams = Schema.Struct({ + callId: Schema.String.annotate({ + description: + "Use to correlate this with [codex_protocol::protocol::PatchApplyBeginEvent] and [codex_protocol::protocol::PatchApplyEndEvent].", + }), + conversationId: ApplyPatchApprovalParams__ThreadId, + fileChanges: Schema.Record(Schema.String, ApplyPatchApprovalParams__FileChange), + grantRoot: Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + description: + "When set, the agent is asking the user to allow writes under this root for the remainder of the session (unclear if this is honored today).", + }), + Schema.Null, + ]), + ), + reason: Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + description: "Optional explanatory reason (e.g. request for extra write access).", + }), + Schema.Null, + ]), + ), +}).annotate({ title: "ApplyPatchApprovalParams" }); + +export type ApplyPatchApprovalResponse = { + readonly decision: ApplyPatchApprovalResponse__ReviewDecision; +}; +export const ApplyPatchApprovalResponse = Schema.Struct({ + decision: ApplyPatchApprovalResponse__ReviewDecision, +}).annotate({ title: "ApplyPatchApprovalResponse" }); + +export type ChatgptAuthTokensRefreshParams = { + readonly previousAccountId?: string | null; + readonly reason: ChatgptAuthTokensRefreshParams__ChatgptAuthTokensRefreshReason; +}; +export const ChatgptAuthTokensRefreshParams = Schema.Struct({ + previousAccountId: Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + description: + "Workspace/account identifier that Codex was previously using.\n\nClients that manage multiple accounts/workspaces can use this as a hint to refresh the token for the correct workspace.\n\nThis may be `null` when the prior auth state did not include a workspace identifier (`chatgpt_account_id`).", + }), + Schema.Null, + ]), + ), + reason: ChatgptAuthTokensRefreshParams__ChatgptAuthTokensRefreshReason, +}).annotate({ title: "ChatgptAuthTokensRefreshParams" }); + +export type ChatgptAuthTokensRefreshResponse = { + readonly accessToken: string; + readonly chatgptAccountId: string; + readonly chatgptPlanType?: string | null; +}; +export const ChatgptAuthTokensRefreshResponse = Schema.Struct({ + accessToken: Schema.String, + chatgptAccountId: Schema.String, + chatgptPlanType: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), +}).annotate({ title: "ChatgptAuthTokensRefreshResponse" }); + +export type ClientNotification = { readonly method: "initialized" }; +export const ClientNotification = Schema.Union( + [ + Schema.Struct({ + method: Schema.Literal("initialized").annotate({ title: "InitializedNotificationMethod" }), + }).annotate({ title: "InitializedNotification" }), + ], + { mode: "oneOf" }, +).annotate({ title: "ClientNotification" }); + +export type ClientRequest = + | { + readonly id: ClientRequest__RequestId; + readonly method: "initialize"; + readonly params: ClientRequest__InitializeParams; + } + | { + readonly id: ClientRequest__RequestId; + readonly method: "thread/start"; + readonly params: ClientRequest__ThreadStartParams; + } + | { + readonly id: ClientRequest__RequestId; + readonly method: "thread/resume"; + readonly params: ClientRequest__ThreadResumeParams; + } + | { + readonly id: ClientRequest__RequestId; + readonly method: "thread/fork"; + readonly params: ClientRequest__ThreadForkParams; + } + | { + readonly id: ClientRequest__RequestId; + readonly method: "thread/archive"; + readonly params: ClientRequest__ThreadArchiveParams; + } + | { + readonly id: ClientRequest__RequestId; + readonly method: "thread/unsubscribe"; + readonly params: ClientRequest__ThreadUnsubscribeParams; + } + | { + readonly id: ClientRequest__RequestId; + readonly method: "thread/name/set"; + readonly params: ClientRequest__ThreadSetNameParams; + } + | { + readonly id: ClientRequest__RequestId; + readonly method: "thread/metadata/update"; + readonly params: ClientRequest__ThreadMetadataUpdateParams; + } + | { + readonly id: ClientRequest__RequestId; + readonly method: "thread/unarchive"; + readonly params: ClientRequest__ThreadUnarchiveParams; + } + | { + readonly id: ClientRequest__RequestId; + readonly method: "thread/compact/start"; + readonly params: ClientRequest__ThreadCompactStartParams; + } + | { + readonly id: ClientRequest__RequestId; + readonly method: "thread/shellCommand"; + readonly params: ClientRequest__ThreadShellCommandParams; + } + | { + readonly id: ClientRequest__RequestId; + readonly method: "thread/rollback"; + readonly params: ClientRequest__ThreadRollbackParams; + } + | { + readonly id: ClientRequest__RequestId; + readonly method: "thread/list"; + readonly params: ClientRequest__ThreadListParams; + } + | { + readonly id: ClientRequest__RequestId; + readonly method: "thread/loaded/list"; + readonly params: ClientRequest__ThreadLoadedListParams; + } + | { + readonly id: ClientRequest__RequestId; + readonly method: "thread/read"; + readonly params: ClientRequest__ThreadReadParams; + } + | { + readonly id: ClientRequest__RequestId; + readonly method: "skills/list"; + readonly params: ClientRequest__SkillsListParams; + } + | { + readonly id: ClientRequest__RequestId; + readonly method: "plugin/list"; + readonly params: ClientRequest__PluginListParams; + } + | { + readonly id: ClientRequest__RequestId; + readonly method: "plugin/read"; + readonly params: ClientRequest__PluginReadParams; + } + | { + readonly id: ClientRequest__RequestId; + readonly method: "app/list"; + readonly params: ClientRequest__AppsListParams; + } + | { + readonly id: ClientRequest__RequestId; + readonly method: "fs/readFile"; + readonly params: ClientRequest__FsReadFileParams; + } + | { + readonly id: ClientRequest__RequestId; + readonly method: "fs/writeFile"; + readonly params: ClientRequest__FsWriteFileParams; + } + | { + readonly id: ClientRequest__RequestId; + readonly method: "fs/createDirectory"; + readonly params: ClientRequest__FsCreateDirectoryParams; + } + | { + readonly id: ClientRequest__RequestId; + readonly method: "fs/getMetadata"; + readonly params: ClientRequest__FsGetMetadataParams; + } + | { + readonly id: ClientRequest__RequestId; + readonly method: "fs/readDirectory"; + readonly params: ClientRequest__FsReadDirectoryParams; + } + | { + readonly id: ClientRequest__RequestId; + readonly method: "fs/remove"; + readonly params: ClientRequest__FsRemoveParams; + } + | { + readonly id: ClientRequest__RequestId; + readonly method: "fs/copy"; + readonly params: ClientRequest__FsCopyParams; + } + | { + readonly id: ClientRequest__RequestId; + readonly method: "fs/watch"; + readonly params: ClientRequest__FsWatchParams; + } + | { + readonly id: ClientRequest__RequestId; + readonly method: "fs/unwatch"; + readonly params: ClientRequest__FsUnwatchParams; + } + | { + readonly id: ClientRequest__RequestId; + readonly method: "skills/config/write"; + readonly params: ClientRequest__SkillsConfigWriteParams; + } + | { + readonly id: ClientRequest__RequestId; + readonly method: "plugin/install"; + readonly params: ClientRequest__PluginInstallParams; + } + | { + readonly id: ClientRequest__RequestId; + readonly method: "plugin/uninstall"; + readonly params: ClientRequest__PluginUninstallParams; + } + | { + readonly id: ClientRequest__RequestId; + readonly method: "turn/start"; + readonly params: ClientRequest__TurnStartParams; + } + | { + readonly id: ClientRequest__RequestId; + readonly method: "turn/steer"; + readonly params: ClientRequest__TurnSteerParams; + } + | { + readonly id: ClientRequest__RequestId; + readonly method: "turn/interrupt"; + readonly params: ClientRequest__TurnInterruptParams; + } + | { + readonly id: ClientRequest__RequestId; + readonly method: "review/start"; + readonly params: ClientRequest__ReviewStartParams; + } + | { + readonly id: ClientRequest__RequestId; + readonly method: "model/list"; + readonly params: ClientRequest__ModelListParams; + } + | { + readonly id: ClientRequest__RequestId; + readonly method: "experimentalFeature/list"; + readonly params: ClientRequest__ExperimentalFeatureListParams; + } + | { + readonly id: ClientRequest__RequestId; + readonly method: "experimentalFeature/enablement/set"; + readonly params: ClientRequest__ExperimentalFeatureEnablementSetParams; + } + | { + readonly id: ClientRequest__RequestId; + readonly method: "mcpServer/oauth/login"; + readonly params: ClientRequest__McpServerOauthLoginParams; + } + | { + readonly id: ClientRequest__RequestId; + readonly method: "config/mcpServer/reload"; + readonly params?: null; + } + | { + readonly id: ClientRequest__RequestId; + readonly method: "mcpServerStatus/list"; + readonly params: ClientRequest__ListMcpServerStatusParams; + } + | { + readonly id: ClientRequest__RequestId; + readonly method: "mcpServer/resource/read"; + readonly params: ClientRequest__McpResourceReadParams; + } + | { + readonly id: ClientRequest__RequestId; + readonly method: "mcpServer/tool/call"; + readonly params: ClientRequest__McpServerToolCallParams; + } + | { + readonly id: ClientRequest__RequestId; + readonly method: "windowsSandbox/setupStart"; + readonly params: ClientRequest__WindowsSandboxSetupStartParams; + } + | { + readonly id: ClientRequest__RequestId; + readonly method: "account/login/start"; + readonly params: ClientRequest__LoginAccountParams; + } + | { + readonly id: ClientRequest__RequestId; + readonly method: "account/login/cancel"; + readonly params: ClientRequest__CancelLoginAccountParams; + } + | { + readonly id: ClientRequest__RequestId; + readonly method: "account/logout"; + readonly params?: null; + } + | { + readonly id: ClientRequest__RequestId; + readonly method: "account/rateLimits/read"; + readonly params?: null; + } + | { + readonly id: ClientRequest__RequestId; + readonly method: "feedback/upload"; + readonly params: ClientRequest__FeedbackUploadParams; + } + | { + readonly id: ClientRequest__RequestId; + readonly method: "command/exec"; + readonly params: ClientRequest__CommandExecParams; + } + | { + readonly id: ClientRequest__RequestId; + readonly method: "command/exec/write"; + readonly params: ClientRequest__CommandExecWriteParams; + } + | { + readonly id: ClientRequest__RequestId; + readonly method: "command/exec/terminate"; + readonly params: ClientRequest__CommandExecTerminateParams; + } + | { + readonly id: ClientRequest__RequestId; + readonly method: "command/exec/resize"; + readonly params: ClientRequest__CommandExecResizeParams; + } + | { + readonly id: ClientRequest__RequestId; + readonly method: "config/read"; + readonly params: ClientRequest__ConfigReadParams; + } + | { + readonly id: ClientRequest__RequestId; + readonly method: "externalAgentConfig/detect"; + readonly params: ClientRequest__ExternalAgentConfigDetectParams; + } + | { + readonly id: ClientRequest__RequestId; + readonly method: "externalAgentConfig/import"; + readonly params: ClientRequest__ExternalAgentConfigImportParams; + } + | { + readonly id: ClientRequest__RequestId; + readonly method: "config/value/write"; + readonly params: ClientRequest__ConfigValueWriteParams; + } + | { + readonly id: ClientRequest__RequestId; + readonly method: "config/batchWrite"; + readonly params: ClientRequest__ConfigBatchWriteParams; + } + | { + readonly id: ClientRequest__RequestId; + readonly method: "configRequirements/read"; + readonly params?: null; + } + | { + readonly id: ClientRequest__RequestId; + readonly method: "account/read"; + readonly params: ClientRequest__GetAccountParams; + } + | { + readonly id: ClientRequest__RequestId; + readonly method: "fuzzyFileSearch"; + readonly params: ClientRequest__FuzzyFileSearchParams; + }; +export const ClientRequest = Schema.Union( + [ + Schema.Struct({ + id: ClientRequest__RequestId, + method: Schema.Literal("initialize").annotate({ title: "InitializeRequestMethod" }), + params: ClientRequest__InitializeParams, + }).annotate({ title: "InitializeRequest" }), + Schema.Struct({ + id: ClientRequest__RequestId, + method: Schema.Literal("thread/start").annotate({ title: "Thread/startRequestMethod" }), + params: ClientRequest__ThreadStartParams, + }).annotate({ title: "Thread/startRequest", description: "NEW APIs" }), + Schema.Struct({ + id: ClientRequest__RequestId, + method: Schema.Literal("thread/resume").annotate({ title: "Thread/resumeRequestMethod" }), + params: ClientRequest__ThreadResumeParams, + }).annotate({ title: "Thread/resumeRequest" }), + Schema.Struct({ + id: ClientRequest__RequestId, + method: Schema.Literal("thread/fork").annotate({ title: "Thread/forkRequestMethod" }), + params: ClientRequest__ThreadForkParams, + }).annotate({ title: "Thread/forkRequest" }), + Schema.Struct({ + id: ClientRequest__RequestId, + method: Schema.Literal("thread/archive").annotate({ title: "Thread/archiveRequestMethod" }), + params: ClientRequest__ThreadArchiveParams, + }).annotate({ title: "Thread/archiveRequest" }), + Schema.Struct({ + id: ClientRequest__RequestId, + method: Schema.Literal("thread/unsubscribe").annotate({ + title: "Thread/unsubscribeRequestMethod", + }), + params: ClientRequest__ThreadUnsubscribeParams, + }).annotate({ title: "Thread/unsubscribeRequest" }), + Schema.Struct({ + id: ClientRequest__RequestId, + method: Schema.Literal("thread/name/set").annotate({ title: "Thread/name/setRequestMethod" }), + params: ClientRequest__ThreadSetNameParams, + }).annotate({ title: "Thread/name/setRequest" }), + Schema.Struct({ + id: ClientRequest__RequestId, + method: Schema.Literal("thread/metadata/update").annotate({ + title: "Thread/metadata/updateRequestMethod", + }), + params: ClientRequest__ThreadMetadataUpdateParams, + }).annotate({ title: "Thread/metadata/updateRequest" }), + Schema.Struct({ + id: ClientRequest__RequestId, + method: Schema.Literal("thread/unarchive").annotate({ + title: "Thread/unarchiveRequestMethod", + }), + params: ClientRequest__ThreadUnarchiveParams, + }).annotate({ title: "Thread/unarchiveRequest" }), + Schema.Struct({ + id: ClientRequest__RequestId, + method: Schema.Literal("thread/compact/start").annotate({ + title: "Thread/compact/startRequestMethod", + }), + params: ClientRequest__ThreadCompactStartParams, + }).annotate({ title: "Thread/compact/startRequest" }), + Schema.Struct({ + id: ClientRequest__RequestId, + method: Schema.Literal("thread/shellCommand").annotate({ + title: "Thread/shellCommandRequestMethod", + }), + params: ClientRequest__ThreadShellCommandParams, + }).annotate({ title: "Thread/shellCommandRequest" }), + Schema.Struct({ + id: ClientRequest__RequestId, + method: Schema.Literal("thread/rollback").annotate({ title: "Thread/rollbackRequestMethod" }), + params: ClientRequest__ThreadRollbackParams, + }).annotate({ title: "Thread/rollbackRequest" }), + Schema.Struct({ + id: ClientRequest__RequestId, + method: Schema.Literal("thread/list").annotate({ title: "Thread/listRequestMethod" }), + params: ClientRequest__ThreadListParams, + }).annotate({ title: "Thread/listRequest" }), + Schema.Struct({ + id: ClientRequest__RequestId, + method: Schema.Literal("thread/loaded/list").annotate({ + title: "Thread/loaded/listRequestMethod", + }), + params: ClientRequest__ThreadLoadedListParams, + }).annotate({ title: "Thread/loaded/listRequest" }), + Schema.Struct({ + id: ClientRequest__RequestId, + method: Schema.Literal("thread/read").annotate({ title: "Thread/readRequestMethod" }), + params: ClientRequest__ThreadReadParams, + }).annotate({ title: "Thread/readRequest" }), + Schema.Struct({ + id: ClientRequest__RequestId, + method: Schema.Literal("skills/list").annotate({ title: "Skills/listRequestMethod" }), + params: ClientRequest__SkillsListParams, + }).annotate({ title: "Skills/listRequest" }), + Schema.Struct({ + id: ClientRequest__RequestId, + method: Schema.Literal("plugin/list").annotate({ title: "Plugin/listRequestMethod" }), + params: ClientRequest__PluginListParams, + }).annotate({ title: "Plugin/listRequest" }), + Schema.Struct({ + id: ClientRequest__RequestId, + method: Schema.Literal("plugin/read").annotate({ title: "Plugin/readRequestMethod" }), + params: ClientRequest__PluginReadParams, + }).annotate({ title: "Plugin/readRequest" }), + Schema.Struct({ + id: ClientRequest__RequestId, + method: Schema.Literal("app/list").annotate({ title: "App/listRequestMethod" }), + params: ClientRequest__AppsListParams, + }).annotate({ title: "App/listRequest" }), + Schema.Struct({ + id: ClientRequest__RequestId, + method: Schema.Literal("fs/readFile").annotate({ title: "Fs/readFileRequestMethod" }), + params: ClientRequest__FsReadFileParams, + }).annotate({ title: "Fs/readFileRequest" }), + Schema.Struct({ + id: ClientRequest__RequestId, + method: Schema.Literal("fs/writeFile").annotate({ title: "Fs/writeFileRequestMethod" }), + params: ClientRequest__FsWriteFileParams, + }).annotate({ title: "Fs/writeFileRequest" }), + Schema.Struct({ + id: ClientRequest__RequestId, + method: Schema.Literal("fs/createDirectory").annotate({ + title: "Fs/createDirectoryRequestMethod", + }), + params: ClientRequest__FsCreateDirectoryParams, + }).annotate({ title: "Fs/createDirectoryRequest" }), + Schema.Struct({ + id: ClientRequest__RequestId, + method: Schema.Literal("fs/getMetadata").annotate({ title: "Fs/getMetadataRequestMethod" }), + params: ClientRequest__FsGetMetadataParams, + }).annotate({ title: "Fs/getMetadataRequest" }), + Schema.Struct({ + id: ClientRequest__RequestId, + method: Schema.Literal("fs/readDirectory").annotate({ + title: "Fs/readDirectoryRequestMethod", + }), + params: ClientRequest__FsReadDirectoryParams, + }).annotate({ title: "Fs/readDirectoryRequest" }), + Schema.Struct({ + id: ClientRequest__RequestId, + method: Schema.Literal("fs/remove").annotate({ title: "Fs/removeRequestMethod" }), + params: ClientRequest__FsRemoveParams, + }).annotate({ title: "Fs/removeRequest" }), + Schema.Struct({ + id: ClientRequest__RequestId, + method: Schema.Literal("fs/copy").annotate({ title: "Fs/copyRequestMethod" }), + params: ClientRequest__FsCopyParams, + }).annotate({ title: "Fs/copyRequest" }), + Schema.Struct({ + id: ClientRequest__RequestId, + method: Schema.Literal("fs/watch").annotate({ title: "Fs/watchRequestMethod" }), + params: ClientRequest__FsWatchParams, + }).annotate({ title: "Fs/watchRequest" }), + Schema.Struct({ + id: ClientRequest__RequestId, + method: Schema.Literal("fs/unwatch").annotate({ title: "Fs/unwatchRequestMethod" }), + params: ClientRequest__FsUnwatchParams, + }).annotate({ title: "Fs/unwatchRequest" }), + Schema.Struct({ + id: ClientRequest__RequestId, + method: Schema.Literal("skills/config/write").annotate({ + title: "Skills/config/writeRequestMethod", + }), + params: ClientRequest__SkillsConfigWriteParams, + }).annotate({ title: "Skills/config/writeRequest" }), + Schema.Struct({ + id: ClientRequest__RequestId, + method: Schema.Literal("plugin/install").annotate({ title: "Plugin/installRequestMethod" }), + params: ClientRequest__PluginInstallParams, + }).annotate({ title: "Plugin/installRequest" }), + Schema.Struct({ + id: ClientRequest__RequestId, + method: Schema.Literal("plugin/uninstall").annotate({ + title: "Plugin/uninstallRequestMethod", + }), + params: ClientRequest__PluginUninstallParams, + }).annotate({ title: "Plugin/uninstallRequest" }), + Schema.Struct({ + id: ClientRequest__RequestId, + method: Schema.Literal("turn/start").annotate({ title: "Turn/startRequestMethod" }), + params: ClientRequest__TurnStartParams, + }).annotate({ title: "Turn/startRequest" }), + Schema.Struct({ + id: ClientRequest__RequestId, + method: Schema.Literal("turn/steer").annotate({ title: "Turn/steerRequestMethod" }), + params: ClientRequest__TurnSteerParams, + }).annotate({ title: "Turn/steerRequest" }), + Schema.Struct({ + id: ClientRequest__RequestId, + method: Schema.Literal("turn/interrupt").annotate({ title: "Turn/interruptRequestMethod" }), + params: ClientRequest__TurnInterruptParams, + }).annotate({ title: "Turn/interruptRequest" }), + Schema.Struct({ + id: ClientRequest__RequestId, + method: Schema.Literal("review/start").annotate({ title: "Review/startRequestMethod" }), + params: ClientRequest__ReviewStartParams, + }).annotate({ title: "Review/startRequest" }), + Schema.Struct({ + id: ClientRequest__RequestId, + method: Schema.Literal("model/list").annotate({ title: "Model/listRequestMethod" }), + params: ClientRequest__ModelListParams, + }).annotate({ title: "Model/listRequest" }), + Schema.Struct({ + id: ClientRequest__RequestId, + method: Schema.Literal("experimentalFeature/list").annotate({ + title: "ExperimentalFeature/listRequestMethod", + }), + params: ClientRequest__ExperimentalFeatureListParams, + }).annotate({ title: "ExperimentalFeature/listRequest" }), + Schema.Struct({ + id: ClientRequest__RequestId, + method: Schema.Literal("experimentalFeature/enablement/set").annotate({ + title: "ExperimentalFeature/enablement/setRequestMethod", + }), + params: ClientRequest__ExperimentalFeatureEnablementSetParams, + }).annotate({ title: "ExperimentalFeature/enablement/setRequest" }), + Schema.Struct({ + id: ClientRequest__RequestId, + method: Schema.Literal("mcpServer/oauth/login").annotate({ + title: "McpServer/oauth/loginRequestMethod", + }), + params: ClientRequest__McpServerOauthLoginParams, + }).annotate({ title: "McpServer/oauth/loginRequest" }), + Schema.Struct({ + id: ClientRequest__RequestId, + method: Schema.Literal("config/mcpServer/reload").annotate({ + title: "Config/mcpServer/reloadRequestMethod", + }), + params: Schema.optionalKey(Schema.Null), + }).annotate({ title: "Config/mcpServer/reloadRequest" }), + Schema.Struct({ + id: ClientRequest__RequestId, + method: Schema.Literal("mcpServerStatus/list").annotate({ + title: "McpServerStatus/listRequestMethod", + }), + params: ClientRequest__ListMcpServerStatusParams, + }).annotate({ title: "McpServerStatus/listRequest" }), + Schema.Struct({ + id: ClientRequest__RequestId, + method: Schema.Literal("mcpServer/resource/read").annotate({ + title: "McpServer/resource/readRequestMethod", + }), + params: ClientRequest__McpResourceReadParams, + }).annotate({ title: "McpServer/resource/readRequest" }), + Schema.Struct({ + id: ClientRequest__RequestId, + method: Schema.Literal("mcpServer/tool/call").annotate({ + title: "McpServer/tool/callRequestMethod", + }), + params: ClientRequest__McpServerToolCallParams, + }).annotate({ title: "McpServer/tool/callRequest" }), + Schema.Struct({ + id: ClientRequest__RequestId, + method: Schema.Literal("windowsSandbox/setupStart").annotate({ + title: "WindowsSandbox/setupStartRequestMethod", + }), + params: ClientRequest__WindowsSandboxSetupStartParams, + }).annotate({ title: "WindowsSandbox/setupStartRequest" }), + Schema.Struct({ + id: ClientRequest__RequestId, + method: Schema.Literal("account/login/start").annotate({ + title: "Account/login/startRequestMethod", + }), + params: ClientRequest__LoginAccountParams, + }).annotate({ title: "Account/login/startRequest" }), + Schema.Struct({ + id: ClientRequest__RequestId, + method: Schema.Literal("account/login/cancel").annotate({ + title: "Account/login/cancelRequestMethod", + }), + params: ClientRequest__CancelLoginAccountParams, + }).annotate({ title: "Account/login/cancelRequest" }), + Schema.Struct({ + id: ClientRequest__RequestId, + method: Schema.Literal("account/logout").annotate({ title: "Account/logoutRequestMethod" }), + params: Schema.optionalKey(Schema.Null), + }).annotate({ title: "Account/logoutRequest" }), + Schema.Struct({ + id: ClientRequest__RequestId, + method: Schema.Literal("account/rateLimits/read").annotate({ + title: "Account/rateLimits/readRequestMethod", + }), + params: Schema.optionalKey(Schema.Null), + }).annotate({ title: "Account/rateLimits/readRequest" }), + Schema.Struct({ + id: ClientRequest__RequestId, + method: Schema.Literal("feedback/upload").annotate({ title: "Feedback/uploadRequestMethod" }), + params: ClientRequest__FeedbackUploadParams, + }).annotate({ title: "Feedback/uploadRequest" }), + Schema.Struct({ + id: ClientRequest__RequestId, + method: Schema.Literal("command/exec").annotate({ title: "Command/execRequestMethod" }), + params: ClientRequest__CommandExecParams, + }).annotate({ + title: "Command/execRequest", + description: "Execute a standalone command (argv vector) under the server's sandbox.", + }), + Schema.Struct({ + id: ClientRequest__RequestId, + method: Schema.Literal("command/exec/write").annotate({ + title: "Command/exec/writeRequestMethod", + }), + params: ClientRequest__CommandExecWriteParams, + }).annotate({ + title: "Command/exec/writeRequest", + description: "Write stdin bytes to a running `command/exec` session or close stdin.", + }), + Schema.Struct({ + id: ClientRequest__RequestId, + method: Schema.Literal("command/exec/terminate").annotate({ + title: "Command/exec/terminateRequestMethod", + }), + params: ClientRequest__CommandExecTerminateParams, + }).annotate({ + title: "Command/exec/terminateRequest", + description: "Terminate a running `command/exec` session by client-supplied `processId`.", + }), + Schema.Struct({ + id: ClientRequest__RequestId, + method: Schema.Literal("command/exec/resize").annotate({ + title: "Command/exec/resizeRequestMethod", + }), + params: ClientRequest__CommandExecResizeParams, + }).annotate({ + title: "Command/exec/resizeRequest", + description: + "Resize a running PTY-backed `command/exec` session by client-supplied `processId`.", + }), + Schema.Struct({ + id: ClientRequest__RequestId, + method: Schema.Literal("config/read").annotate({ title: "Config/readRequestMethod" }), + params: ClientRequest__ConfigReadParams, + }).annotate({ title: "Config/readRequest" }), + Schema.Struct({ + id: ClientRequest__RequestId, + method: Schema.Literal("externalAgentConfig/detect").annotate({ + title: "ExternalAgentConfig/detectRequestMethod", + }), + params: ClientRequest__ExternalAgentConfigDetectParams, + }).annotate({ title: "ExternalAgentConfig/detectRequest" }), + Schema.Struct({ + id: ClientRequest__RequestId, + method: Schema.Literal("externalAgentConfig/import").annotate({ + title: "ExternalAgentConfig/importRequestMethod", + }), + params: ClientRequest__ExternalAgentConfigImportParams, + }).annotate({ title: "ExternalAgentConfig/importRequest" }), + Schema.Struct({ + id: ClientRequest__RequestId, + method: Schema.Literal("config/value/write").annotate({ + title: "Config/value/writeRequestMethod", + }), + params: ClientRequest__ConfigValueWriteParams, + }).annotate({ title: "Config/value/writeRequest" }), + Schema.Struct({ + id: ClientRequest__RequestId, + method: Schema.Literal("config/batchWrite").annotate({ + title: "Config/batchWriteRequestMethod", + }), + params: ClientRequest__ConfigBatchWriteParams, + }).annotate({ title: "Config/batchWriteRequest" }), + Schema.Struct({ + id: ClientRequest__RequestId, + method: Schema.Literal("configRequirements/read").annotate({ + title: "ConfigRequirements/readRequestMethod", + }), + params: Schema.optionalKey(Schema.Null), + }).annotate({ title: "ConfigRequirements/readRequest" }), + Schema.Struct({ + id: ClientRequest__RequestId, + method: Schema.Literal("account/read").annotate({ title: "Account/readRequestMethod" }), + params: ClientRequest__GetAccountParams, + }).annotate({ title: "Account/readRequest" }), + Schema.Struct({ + id: ClientRequest__RequestId, + method: Schema.Literal("fuzzyFileSearch").annotate({ title: "FuzzyFileSearchRequestMethod" }), + params: ClientRequest__FuzzyFileSearchParams, + }).annotate({ title: "FuzzyFileSearchRequest" }), + ], + { mode: "oneOf" }, +).annotate({ title: "ClientRequest", description: "Request from the client to the server." }); + +export type ClientRequest__ByteRange = { readonly end: number; readonly start: number }; +export const ClientRequest__ByteRange = Schema.Struct({ + end: Schema.Number.annotate({ format: "uint" }) + .check(Schema.isInt()) + .check(Schema.isGreaterThanOrEqualTo(0)), + start: Schema.Number.annotate({ format: "uint" }) + .check(Schema.isInt()) + .check(Schema.isGreaterThanOrEqualTo(0)), +}); + +export type ClientRequest__CollaborationMode = { + readonly mode: ClientRequest__ModeKind; + readonly settings: ClientRequest__Settings; +}; +export const ClientRequest__CollaborationMode = Schema.Struct({ + mode: ClientRequest__ModeKind, + settings: ClientRequest__Settings, +}).annotate({ description: "Collaboration mode for a Codex session." }); + +export type ClientRequest__DynamicToolSpec = { + readonly deferLoading?: boolean; + readonly description: string; + readonly inputSchema: unknown; + readonly name: string; +}; +export const ClientRequest__DynamicToolSpec = Schema.Struct({ + deferLoading: Schema.optionalKey(Schema.Boolean), + description: Schema.String, + inputSchema: Schema.Unknown, + name: Schema.String, +}); + +export type ClientRequest__NetworkAccess = "restricted" | "enabled"; +export const ClientRequest__NetworkAccess = Schema.Literals(["restricted", "enabled"]); + +export type ClientRequest__ReadOnlyAccess = + | { + readonly includePlatformDefaults?: boolean; + readonly readableRoots?: ReadonlyArray; + readonly type: "restricted"; + } + | { readonly type: "fullAccess" }; +export const ClientRequest__ReadOnlyAccess = Schema.Union( + [ + Schema.Struct({ + includePlatformDefaults: Schema.optionalKey(Schema.Boolean.annotate({ default: true })), + readableRoots: Schema.optionalKey( + Schema.Array(ClientRequest__AbsolutePathBuf).annotate({ default: [] }), + ), + type: Schema.Literal("restricted").annotate({ title: "RestrictedReadOnlyAccessType" }), + }).annotate({ title: "RestrictedReadOnlyAccess" }), + Schema.Struct({ + type: Schema.Literal("fullAccess").annotate({ title: "FullAccessReadOnlyAccessType" }), + }).annotate({ title: "FullAccessReadOnlyAccess" }), + ], + { mode: "oneOf" }, +); + +export type ClientRequest__RealtimeVoice = + | "alloy" + | "arbor" + | "ash" + | "ballad" + | "breeze" + | "cedar" + | "coral" + | "cove" + | "echo" + | "ember" + | "juniper" + | "maple" + | "marin" + | "sage" + | "shimmer" + | "sol" + | "spruce" + | "vale" + | "verse"; +export const ClientRequest__RealtimeVoice = Schema.Literals([ + "alloy", + "arbor", + "ash", + "ballad", + "breeze", + "cedar", + "coral", + "cove", + "echo", + "ember", + "juniper", + "maple", + "marin", + "sage", + "shimmer", + "sol", + "spruce", + "vale", + "verse", +]); + +export type ClientRequest__ResponseItem = + | { + readonly content: ReadonlyArray; + readonly end_turn?: boolean | null; + readonly id?: string | null; + readonly phase?: ClientRequest__MessagePhase | null; + readonly role: string; + readonly type: "message"; + } + | { + readonly content?: ReadonlyArray | null; + readonly encrypted_content?: string | null; + readonly summary: ReadonlyArray; + readonly type: "reasoning"; + } + | { + readonly action: ClientRequest__LocalShellAction; + readonly call_id?: string | null; + readonly id?: string | null; + readonly status: ClientRequest__LocalShellStatus; + readonly type: "local_shell_call"; + } + | { + readonly arguments: string; + readonly call_id: string; + readonly id?: string | null; + readonly name: string; + readonly namespace?: string | null; + readonly type: "function_call"; + } + | { + readonly arguments: unknown; + readonly call_id?: string | null; + readonly execution: string; + readonly id?: string | null; + readonly status?: string | null; + readonly type: "tool_search_call"; + } + | { + readonly call_id: string; + readonly output: ClientRequest__FunctionCallOutputBody; + readonly type: "function_call_output"; + } + | { + readonly call_id: string; + readonly id?: string | null; + readonly input: string; + readonly name: string; + readonly status?: string | null; + readonly type: "custom_tool_call"; + } + | { + readonly call_id: string; + readonly name?: string | null; + readonly output: ClientRequest__FunctionCallOutputBody; + readonly type: "custom_tool_call_output"; + } + | { + readonly call_id?: string | null; + readonly execution: string; + readonly status: string; + readonly tools: ReadonlyArray; + readonly type: "tool_search_output"; + } + | { + readonly action?: ClientRequest__ResponsesApiWebSearchAction | null; + readonly id?: string | null; + readonly status?: string | null; + readonly type: "web_search_call"; + } + | { + readonly id: string; + readonly result: string; + readonly revised_prompt?: string | null; + readonly status: string; + readonly type: "image_generation_call"; + } + | { readonly ghost_commit: ClientRequest__GhostCommit; readonly type: "ghost_snapshot" } + | { readonly encrypted_content: string; readonly type: "compaction" } + | { readonly type: "other" }; +export const ClientRequest__ResponseItem = Schema.Union( + [ + Schema.Struct({ + content: Schema.Array(ClientRequest__ContentItem), + end_turn: Schema.optionalKey(Schema.Union([Schema.Boolean, Schema.Null])), + id: Schema.optionalKey( + Schema.Union([Schema.String.annotate({ writeOnly: true }), Schema.Null]), + ), + phase: Schema.optionalKey(Schema.Union([ClientRequest__MessagePhase, Schema.Null])), + role: Schema.String, + type: Schema.Literal("message").annotate({ title: "MessageResponseItemType" }), + }).annotate({ title: "MessageResponseItem" }), + Schema.Struct({ + content: Schema.optionalKey( + Schema.Union([Schema.Array(ClientRequest__ReasoningItemContent), Schema.Null]), + ), + encrypted_content: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + summary: Schema.Array(ClientRequest__ReasoningItemReasoningSummary), + type: Schema.Literal("reasoning").annotate({ title: "ReasoningResponseItemType" }), + }).annotate({ title: "ReasoningResponseItem" }), + Schema.Struct({ + action: ClientRequest__LocalShellAction, + call_id: Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ description: "Set when using the Responses API." }), + Schema.Null, + ]), + ), + id: Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + description: "Legacy id field retained for compatibility with older payloads.", + writeOnly: true, + }), + Schema.Null, + ]), + ), + status: ClientRequest__LocalShellStatus, + type: Schema.Literal("local_shell_call").annotate({ + title: "LocalShellCallResponseItemType", + }), + }).annotate({ title: "LocalShellCallResponseItem" }), + Schema.Struct({ + arguments: Schema.String, + call_id: Schema.String, + id: Schema.optionalKey( + Schema.Union([Schema.String.annotate({ writeOnly: true }), Schema.Null]), + ), + name: Schema.String, + namespace: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + type: Schema.Literal("function_call").annotate({ title: "FunctionCallResponseItemType" }), + }).annotate({ title: "FunctionCallResponseItem" }), + Schema.Struct({ + arguments: Schema.Unknown, + call_id: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + execution: Schema.String, + id: Schema.optionalKey( + Schema.Union([Schema.String.annotate({ writeOnly: true }), Schema.Null]), + ), + status: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + type: Schema.Literal("tool_search_call").annotate({ + title: "ToolSearchCallResponseItemType", + }), + }).annotate({ title: "ToolSearchCallResponseItem" }), + Schema.Struct({ + call_id: Schema.String, + output: ClientRequest__FunctionCallOutputBody, + type: Schema.Literal("function_call_output").annotate({ + title: "FunctionCallOutputResponseItemType", + }), + }).annotate({ title: "FunctionCallOutputResponseItem" }), + Schema.Struct({ + call_id: Schema.String, + id: Schema.optionalKey( + Schema.Union([Schema.String.annotate({ writeOnly: true }), Schema.Null]), + ), + input: Schema.String, + name: Schema.String, + status: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + type: Schema.Literal("custom_tool_call").annotate({ + title: "CustomToolCallResponseItemType", + }), + }).annotate({ title: "CustomToolCallResponseItem" }), + Schema.Struct({ + call_id: Schema.String, + name: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + output: ClientRequest__FunctionCallOutputBody, + type: Schema.Literal("custom_tool_call_output").annotate({ + title: "CustomToolCallOutputResponseItemType", + }), + }).annotate({ title: "CustomToolCallOutputResponseItem" }), + Schema.Struct({ + call_id: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + execution: Schema.String, + status: Schema.String, + tools: Schema.Array(Schema.Unknown), + type: Schema.Literal("tool_search_output").annotate({ + title: "ToolSearchOutputResponseItemType", + }), + }).annotate({ title: "ToolSearchOutputResponseItem" }), + Schema.Struct({ + action: Schema.optionalKey( + Schema.Union([ClientRequest__ResponsesApiWebSearchAction, Schema.Null]), + ), + id: Schema.optionalKey( + Schema.Union([Schema.String.annotate({ writeOnly: true }), Schema.Null]), + ), + status: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + type: Schema.Literal("web_search_call").annotate({ title: "WebSearchCallResponseItemType" }), + }).annotate({ title: "WebSearchCallResponseItem" }), + Schema.Struct({ + id: Schema.String, + result: Schema.String, + revised_prompt: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + status: Schema.String, + type: Schema.Literal("image_generation_call").annotate({ + title: "ImageGenerationCallResponseItemType", + }), + }).annotate({ title: "ImageGenerationCallResponseItem" }), + Schema.Struct({ + ghost_commit: ClientRequest__GhostCommit, + type: Schema.Literal("ghost_snapshot").annotate({ title: "GhostSnapshotResponseItemType" }), + }).annotate({ title: "GhostSnapshotResponseItem" }), + Schema.Struct({ + encrypted_content: Schema.String, + type: Schema.Literal("compaction").annotate({ title: "CompactionResponseItemType" }), + }).annotate({ title: "CompactionResponseItem" }), + Schema.Struct({ + type: Schema.Literal("other").annotate({ title: "OtherResponseItemType" }), + }).annotate({ title: "OtherResponseItem" }), + ], + { mode: "oneOf" }, +); + +export type ClientRequest__ThreadRealtimeAudioChunk = { + readonly data: string; + readonly itemId?: string | null; + readonly numChannels: number; + readonly sampleRate: number; + readonly samplesPerChannel?: number | null; +}; +export const ClientRequest__ThreadRealtimeAudioChunk = Schema.Struct({ + data: Schema.String, + itemId: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + numChannels: Schema.Number.annotate({ format: "uint16" }) + .check(Schema.isInt()) + .check(Schema.isGreaterThanOrEqualTo(0)), + sampleRate: Schema.Number.annotate({ format: "uint32" }) + .check(Schema.isInt()) + .check(Schema.isGreaterThanOrEqualTo(0)), + samplesPerChannel: Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ format: "uint32" }) + .check(Schema.isInt()) + .check(Schema.isGreaterThanOrEqualTo(0)), + Schema.Null, + ]), + ), +}).annotate({ description: "EXPERIMENTAL - thread realtime audio chunk." }); + +export type ClientRequest__ThreadRealtimeStartTransport = + | { readonly type: "websocket" } + | { readonly sdp: string; readonly type: "webrtc" }; +export const ClientRequest__ThreadRealtimeStartTransport = Schema.Union( + [ + Schema.Struct({ + type: Schema.Literal("websocket").annotate({ + title: "WebsocketThreadRealtimeStartTransportType", + }), + }).annotate({ title: "WebsocketThreadRealtimeStartTransport" }), + Schema.Struct({ + sdp: Schema.String.annotate({ + description: + "SDP offer generated by a WebRTC RTCPeerConnection after configuring audio and the realtime events data channel.", + }), + type: Schema.Literal("webrtc").annotate({ title: "WebrtcThreadRealtimeStartTransportType" }), + }).annotate({ title: "WebrtcThreadRealtimeStartTransport" }), + ], + { mode: "oneOf" }, +).annotate({ description: "EXPERIMENTAL - transport used by thread realtime." }); + +export type CommandExecutionRequestApprovalParams = { + readonly approvalId?: string | null; + readonly command?: string | null; + readonly commandActions?: ReadonlyArray | null; + readonly cwd?: string | null; + readonly itemId: string; + readonly networkApprovalContext?: CommandExecutionRequestApprovalParams__NetworkApprovalContext | null; + readonly proposedExecpolicyAmendment?: ReadonlyArray | null; + readonly proposedNetworkPolicyAmendments?: ReadonlyArray | null; + readonly reason?: string | null; + readonly threadId: string; + readonly turnId: string; +}; +export const CommandExecutionRequestApprovalParams = Schema.Struct({ + approvalId: Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + description: + "Unique identifier for this specific approval callback.\n\nFor regular shell/unified_exec approvals, this is null.\n\nFor zsh-exec-bridge subcommand approvals, multiple callbacks can belong to one parent `itemId`, so `approvalId` is a distinct opaque callback id (a UUID) used to disambiguate routing.", + }), + Schema.Null, + ]), + ), + command: Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ description: "The command to be executed." }), + Schema.Null, + ]), + ), + commandActions: Schema.optionalKey( + Schema.Union([ + Schema.Array(CommandExecutionRequestApprovalParams__CommandAction).annotate({ + description: "Best-effort parsed command actions for friendly display.", + }), + Schema.Null, + ]), + ), + cwd: Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ description: "The command's working directory." }), + Schema.Null, + ]), + ), + itemId: Schema.String, + networkApprovalContext: Schema.optionalKey( + Schema.Union([ + CommandExecutionRequestApprovalParams__NetworkApprovalContext, + Schema.Null, + ]).annotate({ description: "Optional context for a managed-network approval prompt." }), + ), + proposedExecpolicyAmendment: Schema.optionalKey( + Schema.Union([ + Schema.Array(Schema.String).annotate({ + description: + "Optional proposed execpolicy amendment to allow similar commands without prompting.", + }), + Schema.Null, + ]), + ), + proposedNetworkPolicyAmendments: Schema.optionalKey( + Schema.Union([ + Schema.Array(CommandExecutionRequestApprovalParams__NetworkPolicyAmendment).annotate({ + description: + "Optional proposed network policy amendments (allow/deny host) for future requests.", + }), + Schema.Null, + ]), + ), + reason: Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + description: "Optional explanatory reason (e.g. request for network access).", + }), + Schema.Null, + ]), + ), + threadId: Schema.String, + turnId: Schema.String, +}).annotate({ title: "CommandExecutionRequestApprovalParams" }); + +export type CommandExecutionRequestApprovalParams__AdditionalPermissionProfile = { + readonly fileSystem?: CommandExecutionRequestApprovalParams__AdditionalFileSystemPermissions | null; + readonly network?: CommandExecutionRequestApprovalParams__AdditionalNetworkPermissions | null; +}; +export const CommandExecutionRequestApprovalParams__AdditionalPermissionProfile = Schema.Struct({ + fileSystem: Schema.optionalKey( + Schema.Union([ + CommandExecutionRequestApprovalParams__AdditionalFileSystemPermissions, + Schema.Null, + ]), + ), + network: Schema.optionalKey( + Schema.Union([ + CommandExecutionRequestApprovalParams__AdditionalNetworkPermissions, + Schema.Null, + ]), + ), +}); + +export type CommandExecutionRequestApprovalParams__CommandExecutionApprovalDecision = + | "accept" + | "acceptForSession" + | { + readonly acceptWithExecpolicyAmendment: { + readonly execpolicy_amendment: ReadonlyArray; + }; + } + | { + readonly applyNetworkPolicyAmendment: { + readonly network_policy_amendment: CommandExecutionRequestApprovalParams__NetworkPolicyAmendment; + }; + } + | "decline" + | "cancel"; +export const CommandExecutionRequestApprovalParams__CommandExecutionApprovalDecision = Schema.Union( + [ + Schema.Literal("accept").annotate({ description: "User approved the command." }), + Schema.Literal("acceptForSession").annotate({ + description: + "User approved the command and future prompts in the same session-scoped approval cache should run without prompting.", + }), + Schema.Struct({ + acceptWithExecpolicyAmendment: Schema.Struct({ + execpolicy_amendment: Schema.Array(Schema.String), + }), + }).annotate({ + title: "AcceptWithExecpolicyAmendmentCommandExecutionApprovalDecision", + description: + "User approved the command, and wants to apply the proposed execpolicy amendment so future matching commands can run without prompting.", + }), + Schema.Struct({ + applyNetworkPolicyAmendment: Schema.Struct({ + network_policy_amendment: CommandExecutionRequestApprovalParams__NetworkPolicyAmendment, + }), + }).annotate({ + title: "ApplyNetworkPolicyAmendmentCommandExecutionApprovalDecision", + description: "User chose a persistent network policy rule (allow/deny) for this host.", + }), + Schema.Literal("decline").annotate({ + description: "User denied the command. The agent will continue the turn.", + }), + Schema.Literal("cancel").annotate({ + description: "User denied the command. The turn will also be immediately interrupted.", + }), + ], + { mode: "oneOf" }, +); + +export type CommandExecutionRequestApprovalResponse = { + readonly decision: CommandExecutionRequestApprovalResponse__CommandExecutionApprovalDecision; +}; +export const CommandExecutionRequestApprovalResponse = Schema.Struct({ + decision: CommandExecutionRequestApprovalResponse__CommandExecutionApprovalDecision, +}).annotate({ title: "CommandExecutionRequestApprovalResponse" }); + +export type DynamicToolCallParams = { + readonly arguments: unknown; + readonly callId: string; + readonly threadId: string; + readonly tool: string; + readonly turnId: string; +}; +export const DynamicToolCallParams = Schema.Struct({ + arguments: Schema.Unknown, + callId: Schema.String, + threadId: Schema.String, + tool: Schema.String, + turnId: Schema.String, +}).annotate({ title: "DynamicToolCallParams" }); + +export type DynamicToolCallResponse = { + readonly contentItems: ReadonlyArray; + readonly success: boolean; +}; +export const DynamicToolCallResponse = Schema.Struct({ + contentItems: Schema.Array(DynamicToolCallResponse__DynamicToolCallOutputContentItem), + success: Schema.Boolean, +}).annotate({ title: "DynamicToolCallResponse" }); + +export type ExecCommandApprovalParams = { + readonly approvalId?: string | null; + readonly callId: string; + readonly command: ReadonlyArray; + readonly conversationId: ExecCommandApprovalParams__ThreadId; + readonly cwd: string; + readonly parsedCmd: ReadonlyArray; + readonly reason?: string | null; +}; +export const ExecCommandApprovalParams = Schema.Struct({ + approvalId: Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ description: "Identifier for this specific approval callback." }), + Schema.Null, + ]), + ), + callId: Schema.String.annotate({ + description: + "Use to correlate this with [codex_protocol::protocol::ExecCommandBeginEvent] and [codex_protocol::protocol::ExecCommandEndEvent].", + }), + command: Schema.Array(Schema.String), + conversationId: ExecCommandApprovalParams__ThreadId, + cwd: Schema.String, + parsedCmd: Schema.Array(ExecCommandApprovalParams__ParsedCommand), + reason: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), +}).annotate({ title: "ExecCommandApprovalParams" }); + +export type ExecCommandApprovalResponse = { + readonly decision: ExecCommandApprovalResponse__ReviewDecision; +}; +export const ExecCommandApprovalResponse = Schema.Struct({ + decision: ExecCommandApprovalResponse__ReviewDecision, +}).annotate({ title: "ExecCommandApprovalResponse" }); + +export type FileChangeRequestApprovalParams = { + readonly grantRoot?: string | null; + readonly itemId: string; + readonly reason?: string | null; + readonly threadId: string; + readonly turnId: string; +}; +export const FileChangeRequestApprovalParams = Schema.Struct({ + grantRoot: Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + description: + "[UNSTABLE] When set, the agent is asking the user to allow writes under this root for the remainder of the session (unclear if this is honored today).", + }), + Schema.Null, + ]), + ), + itemId: Schema.String, + reason: Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + description: "Optional explanatory reason (e.g. request for extra write access).", + }), + Schema.Null, + ]), + ), + threadId: Schema.String, + turnId: Schema.String, +}).annotate({ title: "FileChangeRequestApprovalParams" }); + +export type FileChangeRequestApprovalResponse = { + readonly decision: FileChangeRequestApprovalResponse__FileChangeApprovalDecision; +}; +export const FileChangeRequestApprovalResponse = Schema.Struct({ + decision: FileChangeRequestApprovalResponse__FileChangeApprovalDecision, +}).annotate({ title: "FileChangeRequestApprovalResponse" }); + +export type FuzzyFileSearchParams = { + readonly cancellationToken?: string | null; + readonly query: string; + readonly roots: ReadonlyArray; +}; +export const FuzzyFileSearchParams = Schema.Struct({ + cancellationToken: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + query: Schema.String, + roots: Schema.Array(Schema.String), +}).annotate({ title: "FuzzyFileSearchParams" }); + +export type FuzzyFileSearchResponse = { + readonly files: ReadonlyArray; +}; +export const FuzzyFileSearchResponse = Schema.Struct({ + files: Schema.Array(FuzzyFileSearchResponse__FuzzyFileSearchResult), +}).annotate({ title: "FuzzyFileSearchResponse" }); + +export type FuzzyFileSearchSessionCompletedNotification = { readonly sessionId: string }; +export const FuzzyFileSearchSessionCompletedNotification = Schema.Struct({ + sessionId: Schema.String, +}).annotate({ title: "FuzzyFileSearchSessionCompletedNotification" }); + +export type FuzzyFileSearchSessionUpdatedNotification = { + readonly files: ReadonlyArray; + readonly query: string; + readonly sessionId: string; +}; +export const FuzzyFileSearchSessionUpdatedNotification = Schema.Struct({ + files: Schema.Array(FuzzyFileSearchSessionUpdatedNotification__FuzzyFileSearchResult), + query: Schema.String, + sessionId: Schema.String, +}).annotate({ title: "FuzzyFileSearchSessionUpdatedNotification" }); + +export type GetAuthStatusParams = { + readonly includeToken?: boolean | null; + readonly refreshToken?: boolean | null; +}; +export const GetAuthStatusParams = Schema.Struct({ + includeToken: Schema.optionalKey(Schema.Union([Schema.Boolean, Schema.Null])), + refreshToken: Schema.optionalKey(Schema.Union([Schema.Boolean, Schema.Null])), +}).annotate({ title: "GetAuthStatusParams" }); + +export type GetAuthStatusResponse = { + readonly authMethod: unknown | null; + readonly authToken: string | null; + readonly requiresOpenaiAuth: boolean | null; +}; +export const GetAuthStatusResponse = Schema.Struct({ + authMethod: Schema.Union([Schema.Unknown, Schema.Null]), + authToken: Schema.Union([Schema.String, Schema.Null]), + requiresOpenaiAuth: Schema.Union([Schema.Boolean, Schema.Null]), +}).annotate({ title: "GetAuthStatusResponse" }); + +export type GetConversationSummaryParams = + | { readonly rolloutPath: string } + | { readonly conversationId: string }; +export const GetConversationSummaryParams = Schema.Union( + [Schema.Struct({ rolloutPath: Schema.String }), Schema.Struct({ conversationId: Schema.String })], + { mode: "oneOf" }, +).annotate({ title: "GetConversationSummaryParams" }); + +export type GetConversationSummaryResponse = { readonly summary: unknown }; +export const GetConversationSummaryResponse = Schema.Struct({ summary: Schema.Unknown }).annotate({ + title: "GetConversationSummaryResponse", +}); + +export type GitDiffToRemoteParams = { readonly cwd: string }; +export const GitDiffToRemoteParams = Schema.Struct({ cwd: Schema.String }).annotate({ + title: "GitDiffToRemoteParams", +}); + +export type GitDiffToRemoteResponse = { readonly sha: string; readonly diff: string }; +export const GitDiffToRemoteResponse = Schema.Struct({ + sha: Schema.String, + diff: Schema.String, +}).annotate({ title: "GitDiffToRemoteResponse" }); + +export type JSONRPCError = { + readonly error: JSONRPCError__JSONRPCErrorError; + readonly id: JSONRPCError__RequestId; +}; +export const JSONRPCError = Schema.Struct({ + error: JSONRPCError__JSONRPCErrorError, + id: JSONRPCError__RequestId, +}).annotate({ + title: "JSONRPCError", + description: "A response to a request that indicates an error occurred.", +}); + +export type JSONRPCErrorError = { + readonly code: number; + readonly data?: unknown; + readonly message: string; +}; +export const JSONRPCErrorError = Schema.Struct({ + code: Schema.Number.annotate({ format: "int64" }).check(Schema.isInt()), + data: Schema.optionalKey(Schema.Unknown), + message: Schema.String, +}).annotate({ title: "JSONRPCErrorError" }); + +export type JSONRPCMessage = + | JSONRPCMessage__JSONRPCRequest + | JSONRPCMessage__JSONRPCNotification + | JSONRPCMessage__JSONRPCResponse + | JSONRPCMessage__JSONRPCError; +export const JSONRPCMessage = Schema.Union([ + JSONRPCMessage__JSONRPCRequest, + JSONRPCMessage__JSONRPCNotification, + JSONRPCMessage__JSONRPCResponse, + JSONRPCMessage__JSONRPCError, +]).annotate({ + title: "JSONRPCMessage", + description: + "Refers to any valid JSON-RPC object that can be decoded off the wire, or encoded to be sent.", +}); + +export type JSONRPCNotification = { readonly method: string; readonly params?: unknown }; +export const JSONRPCNotification = Schema.Struct({ + method: Schema.String, + params: Schema.optionalKey(Schema.Unknown), +}).annotate({ + title: "JSONRPCNotification", + description: "A notification which does not expect a response.", +}); + +export type JSONRPCRequest = { + readonly id: JSONRPCRequest__RequestId; + readonly method: string; + readonly params?: unknown; + readonly trace?: JSONRPCRequest__W3cTraceContext | null; +}; +export const JSONRPCRequest = Schema.Struct({ + id: JSONRPCRequest__RequestId, + method: Schema.String, + params: Schema.optionalKey(Schema.Unknown), + trace: Schema.optionalKey( + Schema.Union([JSONRPCRequest__W3cTraceContext, Schema.Null]).annotate({ + description: "Optional W3C Trace Context for distributed tracing.", + }), + ), +}).annotate({ title: "JSONRPCRequest", description: "A request that expects a response." }); + +export type JSONRPCResponse = { readonly id: JSONRPCResponse__RequestId; readonly result: unknown }; +export const JSONRPCResponse = Schema.Struct({ + id: JSONRPCResponse__RequestId, + result: Schema.Unknown, +}).annotate({ + title: "JSONRPCResponse", + description: "A successful (non-error) response to a request.", +}); + +export type McpServerElicitationRequestParams = + | { + readonly _meta?: unknown; + readonly message: string; + readonly mode: "form"; + readonly requestedSchema: McpServerElicitationRequestParams__McpElicitationSchema; + readonly serverName: string; + readonly threadId: string; + readonly turnId?: string | null; + } + | { + readonly _meta?: unknown; + readonly elicitationId: string; + readonly message: string; + readonly mode: "url"; + readonly url: string; + readonly serverName: string; + readonly threadId: string; + readonly turnId?: string | null; + }; +export const McpServerElicitationRequestParams = Schema.Union( + [ + Schema.Struct({ + _meta: Schema.optionalKey(Schema.Unknown), + message: Schema.String, + mode: Schema.Literal("form"), + requestedSchema: McpServerElicitationRequestParams__McpElicitationSchema, + serverName: Schema.String, + threadId: Schema.String, + turnId: Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + description: + "Active Codex turn when this elicitation was observed, if app-server could correlate one.\n\nThis is nullable because MCP models elicitation as a standalone server-to-client request identified by the MCP server request id. It may be triggered during a turn, but turn context is app-server correlation rather than part of the protocol identity of the elicitation itself.", + }), + Schema.Null, + ]), + ), + }).annotate({ title: "McpServerElicitationRequestParams" }), + Schema.Struct({ + _meta: Schema.optionalKey(Schema.Unknown), + elicitationId: Schema.String, + message: Schema.String, + mode: Schema.Literal("url"), + url: Schema.String, + serverName: Schema.String, + threadId: Schema.String, + turnId: Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + description: + "Active Codex turn when this elicitation was observed, if app-server could correlate one.\n\nThis is nullable because MCP models elicitation as a standalone server-to-client request identified by the MCP server request id. It may be triggered during a turn, but turn context is app-server correlation rather than part of the protocol identity of the elicitation itself.", + }), + Schema.Null, + ]), + ), + }).annotate({ title: "McpServerElicitationRequestParams" }), + ], + { mode: "oneOf" }, +); + +export type McpServerElicitationRequestResponse = { + readonly _meta?: unknown; + readonly action: McpServerElicitationRequestResponse__McpServerElicitationAction; + readonly content?: unknown; +}; +export const McpServerElicitationRequestResponse = Schema.Struct({ + _meta: Schema.optionalKey( + Schema.Unknown.annotate({ + description: "Optional client metadata for form-mode action handling.", + }), + ), + action: McpServerElicitationRequestResponse__McpServerElicitationAction, + content: Schema.optionalKey( + Schema.Unknown.annotate({ + description: + "Structured user input for accepted elicitations, mirroring RMCP `CreateElicitationResult`.\n\nThis is nullable because decline/cancel responses have no content.", + }), + ), +}).annotate({ title: "McpServerElicitationRequestResponse" }); + +export type PermissionsRequestApprovalParams = { + readonly itemId: string; + readonly permissions: PermissionsRequestApprovalParams__RequestPermissionProfile; + readonly reason?: string | null; + readonly threadId: string; + readonly turnId: string; +}; +export const PermissionsRequestApprovalParams = Schema.Struct({ + itemId: Schema.String, + permissions: PermissionsRequestApprovalParams__RequestPermissionProfile, + reason: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + threadId: Schema.String, + turnId: Schema.String, +}).annotate({ title: "PermissionsRequestApprovalParams" }); + +export type PermissionsRequestApprovalResponse = { + readonly permissions: PermissionsRequestApprovalResponse__GrantedPermissionProfile; + readonly scope?: "turn" | "session"; +}; +export const PermissionsRequestApprovalResponse = Schema.Struct({ + permissions: PermissionsRequestApprovalResponse__GrantedPermissionProfile, + scope: Schema.optionalKey(Schema.Literals(["turn", "session"]).annotate({ default: "turn" })), +}).annotate({ title: "PermissionsRequestApprovalResponse" }); + +export type PermissionsRequestApprovalResponse__PermissionGrantScope = "turn" | "session"; +export const PermissionsRequestApprovalResponse__PermissionGrantScope = Schema.Literals([ + "turn", + "session", +]); + +export type RequestId = string | number; +export const RequestId = Schema.Union([ + Schema.String, + Schema.Number.annotate({ format: "int64" }).check(Schema.isInt()), +]).annotate({ title: "RequestId" }); + +export type ServerNotification = + | { readonly method: "error"; readonly params: ServerNotification__ErrorNotification } + | { + readonly method: "thread/started"; + readonly params: ServerNotification__ThreadStartedNotification; + } + | { + readonly method: "thread/status/changed"; + readonly params: ServerNotification__ThreadStatusChangedNotification; + } + | { + readonly method: "thread/archived"; + readonly params: ServerNotification__ThreadArchivedNotification; + } + | { + readonly method: "thread/unarchived"; + readonly params: ServerNotification__ThreadUnarchivedNotification; + } + | { + readonly method: "thread/closed"; + readonly params: ServerNotification__ThreadClosedNotification; + } + | { + readonly method: "skills/changed"; + readonly params: ServerNotification__SkillsChangedNotification; + } + | { + readonly method: "thread/name/updated"; + readonly params: ServerNotification__ThreadNameUpdatedNotification; + } + | { + readonly method: "thread/tokenUsage/updated"; + readonly params: ServerNotification__ThreadTokenUsageUpdatedNotification; + } + | { + readonly method: "turn/started"; + readonly params: ServerNotification__TurnStartedNotification; + } + | { + readonly method: "hook/started"; + readonly params: ServerNotification__HookStartedNotification; + } + | { + readonly method: "turn/completed"; + readonly params: ServerNotification__TurnCompletedNotification; + } + | { + readonly method: "hook/completed"; + readonly params: ServerNotification__HookCompletedNotification; + } + | { + readonly method: "turn/diff/updated"; + readonly params: ServerNotification__TurnDiffUpdatedNotification; + } + | { + readonly method: "turn/plan/updated"; + readonly params: ServerNotification__TurnPlanUpdatedNotification; + } + | { + readonly method: "item/started"; + readonly params: ServerNotification__ItemStartedNotification; + } + | { + readonly method: "item/autoApprovalReview/started"; + readonly params: ServerNotification__ItemGuardianApprovalReviewStartedNotification; + } + | { + readonly method: "item/autoApprovalReview/completed"; + readonly params: ServerNotification__ItemGuardianApprovalReviewCompletedNotification; + } + | { + readonly method: "item/completed"; + readonly params: ServerNotification__ItemCompletedNotification; + } + | { + readonly method: "item/agentMessage/delta"; + readonly params: ServerNotification__AgentMessageDeltaNotification; + } + | { + readonly method: "item/plan/delta"; + readonly params: ServerNotification__PlanDeltaNotification; + } + | { + readonly method: "command/exec/outputDelta"; + readonly params: ServerNotification__CommandExecOutputDeltaNotification; + } + | { + readonly method: "item/commandExecution/outputDelta"; + readonly params: ServerNotification__CommandExecutionOutputDeltaNotification; + } + | { + readonly method: "item/commandExecution/terminalInteraction"; + readonly params: ServerNotification__TerminalInteractionNotification; + } + | { + readonly method: "item/fileChange/outputDelta"; + readonly params: ServerNotification__FileChangeOutputDeltaNotification; + } + | { + readonly method: "serverRequest/resolved"; + readonly params: ServerNotification__ServerRequestResolvedNotification; + } + | { + readonly method: "item/mcpToolCall/progress"; + readonly params: ServerNotification__McpToolCallProgressNotification; + } + | { + readonly method: "mcpServer/oauthLogin/completed"; + readonly params: ServerNotification__McpServerOauthLoginCompletedNotification; + } + | { + readonly method: "mcpServer/startupStatus/updated"; + readonly params: ServerNotification__McpServerStatusUpdatedNotification; + } + | { + readonly method: "account/updated"; + readonly params: ServerNotification__AccountUpdatedNotification; + } + | { + readonly method: "account/rateLimits/updated"; + readonly params: ServerNotification__AccountRateLimitsUpdatedNotification; + } + | { + readonly method: "app/list/updated"; + readonly params: ServerNotification__AppListUpdatedNotification; + } + | { readonly method: "fs/changed"; readonly params: ServerNotification__FsChangedNotification } + | { + readonly method: "item/reasoning/summaryTextDelta"; + readonly params: ServerNotification__ReasoningSummaryTextDeltaNotification; + } + | { + readonly method: "item/reasoning/summaryPartAdded"; + readonly params: ServerNotification__ReasoningSummaryPartAddedNotification; + } + | { + readonly method: "item/reasoning/textDelta"; + readonly params: ServerNotification__ReasoningTextDeltaNotification; + } + | { + readonly method: "thread/compacted"; + readonly params: ServerNotification__ContextCompactedNotification; + } + | { + readonly method: "model/rerouted"; + readonly params: ServerNotification__ModelReroutedNotification; + } + | { + readonly method: "deprecationNotice"; + readonly params: ServerNotification__DeprecationNoticeNotification; + } + | { + readonly method: "configWarning"; + readonly params: ServerNotification__ConfigWarningNotification; + } + | { + readonly method: "fuzzyFileSearch/sessionUpdated"; + readonly params: ServerNotification__FuzzyFileSearchSessionUpdatedNotification; + } + | { + readonly method: "fuzzyFileSearch/sessionCompleted"; + readonly params: ServerNotification__FuzzyFileSearchSessionCompletedNotification; + } + | { + readonly method: "thread/realtime/started"; + readonly params: ServerNotification__ThreadRealtimeStartedNotification; + } + | { + readonly method: "thread/realtime/itemAdded"; + readonly params: ServerNotification__ThreadRealtimeItemAddedNotification; + } + | { + readonly method: "thread/realtime/transcriptUpdated"; + readonly params: ServerNotification__ThreadRealtimeTranscriptUpdatedNotification; + } + | { + readonly method: "thread/realtime/outputAudio/delta"; + readonly params: ServerNotification__ThreadRealtimeOutputAudioDeltaNotification; + } + | { + readonly method: "thread/realtime/sdp"; + readonly params: ServerNotification__ThreadRealtimeSdpNotification; + } + | { + readonly method: "thread/realtime/error"; + readonly params: ServerNotification__ThreadRealtimeErrorNotification; + } + | { + readonly method: "thread/realtime/closed"; + readonly params: ServerNotification__ThreadRealtimeClosedNotification; + } + | { + readonly method: "windows/worldWritableWarning"; + readonly params: ServerNotification__WindowsWorldWritableWarningNotification; + } + | { + readonly method: "windowsSandbox/setupCompleted"; + readonly params: ServerNotification__WindowsSandboxSetupCompletedNotification; + } + | { + readonly method: "account/login/completed"; + readonly params: ServerNotification__AccountLoginCompletedNotification; + }; +export const ServerNotification = Schema.Union( + [ + Schema.Struct({ + method: Schema.Literal("error").annotate({ title: "ErrorNotificationMethod" }), + params: ServerNotification__ErrorNotification, + }).annotate({ title: "ErrorNotification", description: "NEW NOTIFICATIONS" }), + Schema.Struct({ + method: Schema.Literal("thread/started").annotate({ + title: "Thread/startedNotificationMethod", + }), + params: ServerNotification__ThreadStartedNotification, + }).annotate({ title: "Thread/startedNotification" }), + Schema.Struct({ + method: Schema.Literal("thread/status/changed").annotate({ + title: "Thread/status/changedNotificationMethod", + }), + params: ServerNotification__ThreadStatusChangedNotification, + }).annotate({ title: "Thread/status/changedNotification" }), + Schema.Struct({ + method: Schema.Literal("thread/archived").annotate({ + title: "Thread/archivedNotificationMethod", + }), + params: ServerNotification__ThreadArchivedNotification, + }).annotate({ title: "Thread/archivedNotification" }), + Schema.Struct({ + method: Schema.Literal("thread/unarchived").annotate({ + title: "Thread/unarchivedNotificationMethod", + }), + params: ServerNotification__ThreadUnarchivedNotification, + }).annotate({ title: "Thread/unarchivedNotification" }), + Schema.Struct({ + method: Schema.Literal("thread/closed").annotate({ + title: "Thread/closedNotificationMethod", + }), + params: ServerNotification__ThreadClosedNotification, + }).annotate({ title: "Thread/closedNotification" }), + Schema.Struct({ + method: Schema.Literal("skills/changed").annotate({ + title: "Skills/changedNotificationMethod", + }), + params: ServerNotification__SkillsChangedNotification, + }).annotate({ title: "Skills/changedNotification" }), + Schema.Struct({ + method: Schema.Literal("thread/name/updated").annotate({ + title: "Thread/name/updatedNotificationMethod", + }), + params: ServerNotification__ThreadNameUpdatedNotification, + }).annotate({ title: "Thread/name/updatedNotification" }), + Schema.Struct({ + method: Schema.Literal("thread/tokenUsage/updated").annotate({ + title: "Thread/tokenUsage/updatedNotificationMethod", + }), + params: ServerNotification__ThreadTokenUsageUpdatedNotification, + }).annotate({ title: "Thread/tokenUsage/updatedNotification" }), + Schema.Struct({ + method: Schema.Literal("turn/started").annotate({ title: "Turn/startedNotificationMethod" }), + params: ServerNotification__TurnStartedNotification, + }).annotate({ title: "Turn/startedNotification" }), + Schema.Struct({ + method: Schema.Literal("hook/started").annotate({ title: "Hook/startedNotificationMethod" }), + params: ServerNotification__HookStartedNotification, + }).annotate({ title: "Hook/startedNotification" }), + Schema.Struct({ + method: Schema.Literal("turn/completed").annotate({ + title: "Turn/completedNotificationMethod", + }), + params: ServerNotification__TurnCompletedNotification, + }).annotate({ title: "Turn/completedNotification" }), + Schema.Struct({ + method: Schema.Literal("hook/completed").annotate({ + title: "Hook/completedNotificationMethod", + }), + params: ServerNotification__HookCompletedNotification, + }).annotate({ title: "Hook/completedNotification" }), + Schema.Struct({ + method: Schema.Literal("turn/diff/updated").annotate({ + title: "Turn/diff/updatedNotificationMethod", + }), + params: ServerNotification__TurnDiffUpdatedNotification, + }).annotate({ title: "Turn/diff/updatedNotification" }), + Schema.Struct({ + method: Schema.Literal("turn/plan/updated").annotate({ + title: "Turn/plan/updatedNotificationMethod", + }), + params: ServerNotification__TurnPlanUpdatedNotification, + }).annotate({ title: "Turn/plan/updatedNotification" }), + Schema.Struct({ + method: Schema.Literal("item/started").annotate({ title: "Item/startedNotificationMethod" }), + params: ServerNotification__ItemStartedNotification, + }).annotate({ title: "Item/startedNotification" }), + Schema.Struct({ + method: Schema.Literal("item/autoApprovalReview/started").annotate({ + title: "Item/autoApprovalReview/startedNotificationMethod", + }), + params: ServerNotification__ItemGuardianApprovalReviewStartedNotification, + }).annotate({ title: "Item/autoApprovalReview/startedNotification" }), + Schema.Struct({ + method: Schema.Literal("item/autoApprovalReview/completed").annotate({ + title: "Item/autoApprovalReview/completedNotificationMethod", + }), + params: ServerNotification__ItemGuardianApprovalReviewCompletedNotification, + }).annotate({ title: "Item/autoApprovalReview/completedNotification" }), + Schema.Struct({ + method: Schema.Literal("item/completed").annotate({ + title: "Item/completedNotificationMethod", + }), + params: ServerNotification__ItemCompletedNotification, + }).annotate({ title: "Item/completedNotification" }), + Schema.Struct({ + method: Schema.Literal("item/agentMessage/delta").annotate({ + title: "Item/agentMessage/deltaNotificationMethod", + }), + params: ServerNotification__AgentMessageDeltaNotification, + }).annotate({ title: "Item/agentMessage/deltaNotification" }), + Schema.Struct({ + method: Schema.Literal("item/plan/delta").annotate({ + title: "Item/plan/deltaNotificationMethod", + }), + params: ServerNotification__PlanDeltaNotification, + }).annotate({ + title: "Item/plan/deltaNotification", + description: "EXPERIMENTAL - proposed plan streaming deltas for plan items.", + }), + Schema.Struct({ + method: Schema.Literal("command/exec/outputDelta").annotate({ + title: "Command/exec/outputDeltaNotificationMethod", + }), + params: ServerNotification__CommandExecOutputDeltaNotification, + }).annotate({ + title: "Command/exec/outputDeltaNotification", + description: + "Stream base64-encoded stdout/stderr chunks for a running `command/exec` session.", + }), + Schema.Struct({ + method: Schema.Literal("item/commandExecution/outputDelta").annotate({ + title: "Item/commandExecution/outputDeltaNotificationMethod", + }), + params: ServerNotification__CommandExecutionOutputDeltaNotification, + }).annotate({ title: "Item/commandExecution/outputDeltaNotification" }), + Schema.Struct({ + method: Schema.Literal("item/commandExecution/terminalInteraction").annotate({ + title: "Item/commandExecution/terminalInteractionNotificationMethod", + }), + params: ServerNotification__TerminalInteractionNotification, + }).annotate({ title: "Item/commandExecution/terminalInteractionNotification" }), + Schema.Struct({ + method: Schema.Literal("item/fileChange/outputDelta").annotate({ + title: "Item/fileChange/outputDeltaNotificationMethod", + }), + params: ServerNotification__FileChangeOutputDeltaNotification, + }).annotate({ title: "Item/fileChange/outputDeltaNotification" }), + Schema.Struct({ + method: Schema.Literal("serverRequest/resolved").annotate({ + title: "ServerRequest/resolvedNotificationMethod", + }), + params: ServerNotification__ServerRequestResolvedNotification, + }).annotate({ title: "ServerRequest/resolvedNotification" }), + Schema.Struct({ + method: Schema.Literal("item/mcpToolCall/progress").annotate({ + title: "Item/mcpToolCall/progressNotificationMethod", + }), + params: ServerNotification__McpToolCallProgressNotification, + }).annotate({ title: "Item/mcpToolCall/progressNotification" }), + Schema.Struct({ + method: Schema.Literal("mcpServer/oauthLogin/completed").annotate({ + title: "McpServer/oauthLogin/completedNotificationMethod", + }), + params: ServerNotification__McpServerOauthLoginCompletedNotification, + }).annotate({ title: "McpServer/oauthLogin/completedNotification" }), + Schema.Struct({ + method: Schema.Literal("mcpServer/startupStatus/updated").annotate({ + title: "McpServer/startupStatus/updatedNotificationMethod", + }), + params: ServerNotification__McpServerStatusUpdatedNotification, + }).annotate({ title: "McpServer/startupStatus/updatedNotification" }), + Schema.Struct({ + method: Schema.Literal("account/updated").annotate({ + title: "Account/updatedNotificationMethod", + }), + params: ServerNotification__AccountUpdatedNotification, + }).annotate({ title: "Account/updatedNotification" }), + Schema.Struct({ + method: Schema.Literal("account/rateLimits/updated").annotate({ + title: "Account/rateLimits/updatedNotificationMethod", + }), + params: ServerNotification__AccountRateLimitsUpdatedNotification, + }).annotate({ title: "Account/rateLimits/updatedNotification" }), + Schema.Struct({ + method: Schema.Literal("app/list/updated").annotate({ + title: "App/list/updatedNotificationMethod", + }), + params: ServerNotification__AppListUpdatedNotification, + }).annotate({ title: "App/list/updatedNotification" }), + Schema.Struct({ + method: Schema.Literal("fs/changed").annotate({ title: "Fs/changedNotificationMethod" }), + params: ServerNotification__FsChangedNotification, + }).annotate({ title: "Fs/changedNotification" }), + Schema.Struct({ + method: Schema.Literal("item/reasoning/summaryTextDelta").annotate({ + title: "Item/reasoning/summaryTextDeltaNotificationMethod", + }), + params: ServerNotification__ReasoningSummaryTextDeltaNotification, + }).annotate({ title: "Item/reasoning/summaryTextDeltaNotification" }), + Schema.Struct({ + method: Schema.Literal("item/reasoning/summaryPartAdded").annotate({ + title: "Item/reasoning/summaryPartAddedNotificationMethod", + }), + params: ServerNotification__ReasoningSummaryPartAddedNotification, + }).annotate({ title: "Item/reasoning/summaryPartAddedNotification" }), + Schema.Struct({ + method: Schema.Literal("item/reasoning/textDelta").annotate({ + title: "Item/reasoning/textDeltaNotificationMethod", + }), + params: ServerNotification__ReasoningTextDeltaNotification, + }).annotate({ title: "Item/reasoning/textDeltaNotification" }), + Schema.Struct({ + method: Schema.Literal("thread/compacted").annotate({ + title: "Thread/compactedNotificationMethod", + }), + params: ServerNotification__ContextCompactedNotification, + }).annotate({ + title: "Thread/compactedNotification", + description: "Deprecated: Use `ContextCompaction` item type instead.", + }), + Schema.Struct({ + method: Schema.Literal("model/rerouted").annotate({ + title: "Model/reroutedNotificationMethod", + }), + params: ServerNotification__ModelReroutedNotification, + }).annotate({ title: "Model/reroutedNotification" }), + Schema.Struct({ + method: Schema.Literal("deprecationNotice").annotate({ + title: "DeprecationNoticeNotificationMethod", + }), + params: ServerNotification__DeprecationNoticeNotification, + }).annotate({ title: "DeprecationNoticeNotification" }), + Schema.Struct({ + method: Schema.Literal("configWarning").annotate({ + title: "ConfigWarningNotificationMethod", + }), + params: ServerNotification__ConfigWarningNotification, + }).annotate({ title: "ConfigWarningNotification" }), + Schema.Struct({ + method: Schema.Literal("fuzzyFileSearch/sessionUpdated").annotate({ + title: "FuzzyFileSearch/sessionUpdatedNotificationMethod", + }), + params: ServerNotification__FuzzyFileSearchSessionUpdatedNotification, + }).annotate({ title: "FuzzyFileSearch/sessionUpdatedNotification" }), + Schema.Struct({ + method: Schema.Literal("fuzzyFileSearch/sessionCompleted").annotate({ + title: "FuzzyFileSearch/sessionCompletedNotificationMethod", + }), + params: ServerNotification__FuzzyFileSearchSessionCompletedNotification, + }).annotate({ title: "FuzzyFileSearch/sessionCompletedNotification" }), + Schema.Struct({ + method: Schema.Literal("thread/realtime/started").annotate({ + title: "Thread/realtime/startedNotificationMethod", + }), + params: ServerNotification__ThreadRealtimeStartedNotification, + }).annotate({ title: "Thread/realtime/startedNotification" }), + Schema.Struct({ + method: Schema.Literal("thread/realtime/itemAdded").annotate({ + title: "Thread/realtime/itemAddedNotificationMethod", + }), + params: ServerNotification__ThreadRealtimeItemAddedNotification, + }).annotate({ title: "Thread/realtime/itemAddedNotification" }), + Schema.Struct({ + method: Schema.Literal("thread/realtime/transcriptUpdated").annotate({ + title: "Thread/realtime/transcriptUpdatedNotificationMethod", + }), + params: ServerNotification__ThreadRealtimeTranscriptUpdatedNotification, + }).annotate({ title: "Thread/realtime/transcriptUpdatedNotification" }), + Schema.Struct({ + method: Schema.Literal("thread/realtime/outputAudio/delta").annotate({ + title: "Thread/realtime/outputAudio/deltaNotificationMethod", + }), + params: ServerNotification__ThreadRealtimeOutputAudioDeltaNotification, + }).annotate({ title: "Thread/realtime/outputAudio/deltaNotification" }), + Schema.Struct({ + method: Schema.Literal("thread/realtime/sdp").annotate({ + title: "Thread/realtime/sdpNotificationMethod", + }), + params: ServerNotification__ThreadRealtimeSdpNotification, + }).annotate({ title: "Thread/realtime/sdpNotification" }), + Schema.Struct({ + method: Schema.Literal("thread/realtime/error").annotate({ + title: "Thread/realtime/errorNotificationMethod", + }), + params: ServerNotification__ThreadRealtimeErrorNotification, + }).annotate({ title: "Thread/realtime/errorNotification" }), + Schema.Struct({ + method: Schema.Literal("thread/realtime/closed").annotate({ + title: "Thread/realtime/closedNotificationMethod", + }), + params: ServerNotification__ThreadRealtimeClosedNotification, + }).annotate({ title: "Thread/realtime/closedNotification" }), + Schema.Struct({ + method: Schema.Literal("windows/worldWritableWarning").annotate({ + title: "Windows/worldWritableWarningNotificationMethod", + }), + params: ServerNotification__WindowsWorldWritableWarningNotification, + }).annotate({ + title: "Windows/worldWritableWarningNotification", + description: + "Notifies the user of world-writable directories on Windows, which cannot be protected by the sandbox.", + }), + Schema.Struct({ + method: Schema.Literal("windowsSandbox/setupCompleted").annotate({ + title: "WindowsSandbox/setupCompletedNotificationMethod", + }), + params: ServerNotification__WindowsSandboxSetupCompletedNotification, + }).annotate({ title: "WindowsSandbox/setupCompletedNotification" }), + Schema.Struct({ + method: Schema.Literal("account/login/completed").annotate({ + title: "Account/login/completedNotificationMethod", + }), + params: ServerNotification__AccountLoginCompletedNotification, + }).annotate({ title: "Account/login/completedNotification" }), + ], + { mode: "oneOf" }, +).annotate({ + title: "ServerNotification", + description: "Notification sent from the server to the client.", +}); + +export type ServerNotification__ByteRange = { readonly end: number; readonly start: number }; +export const ServerNotification__ByteRange = Schema.Struct({ + end: Schema.Number.annotate({ format: "uint" }) + .check(Schema.isInt()) + .check(Schema.isGreaterThanOrEqualTo(0)), + start: Schema.Number.annotate({ format: "uint" }) + .check(Schema.isInt()) + .check(Schema.isGreaterThanOrEqualTo(0)), +}); + +export type ServerNotification__CollabAgentTool = + | "spawnAgent" + | "sendInput" + | "resumeAgent" + | "wait" + | "closeAgent"; +export const ServerNotification__CollabAgentTool = Schema.Literals([ + "spawnAgent", + "sendInput", + "resumeAgent", + "wait", + "closeAgent", +]); + +export type ServerNotification__CollabAgentToolCallStatus = "inProgress" | "completed" | "failed"; +export const ServerNotification__CollabAgentToolCallStatus = Schema.Literals([ + "inProgress", + "completed", + "failed", +]); + +export type ServerNotification__CommandExecOutputStream = "stdout" | "stderr"; +export const ServerNotification__CommandExecOutputStream = Schema.Literals([ + "stdout", + "stderr", +]).annotate({ description: "Stream label for `command/exec/outputDelta` notifications." }); + +export type ServerNotification__CommandExecutionSource = + | "agent" + | "userShell" + | "unifiedExecStartup" + | "unifiedExecInteraction"; +export const ServerNotification__CommandExecutionSource = Schema.Literals([ + "agent", + "userShell", + "unifiedExecStartup", + "unifiedExecInteraction", +]); + +export type ServerNotification__SessionSource = + | "cli" + | "vscode" + | "exec" + | "appServer" + | "unknown" + | { readonly custom: string } + | { readonly subAgent: ServerNotification__SubAgentSource }; +export const ServerNotification__SessionSource = Schema.Union( + [ + Schema.Literals(["cli", "vscode", "exec", "appServer", "unknown"]), + Schema.Struct({ custom: Schema.String }).annotate({ title: "CustomSessionSource" }), + Schema.Struct({ subAgent: ServerNotification__SubAgentSource }).annotate({ + title: "SubAgentSessionSource", + }), + ], + { mode: "oneOf" }, +); + +export type ServerRequest = + | { + readonly id: ServerRequest__RequestId; + readonly method: "item/commandExecution/requestApproval"; + readonly params: ServerRequest__CommandExecutionRequestApprovalParams; + } + | { + readonly id: ServerRequest__RequestId; + readonly method: "item/fileChange/requestApproval"; + readonly params: ServerRequest__FileChangeRequestApprovalParams; + } + | { + readonly id: ServerRequest__RequestId; + readonly method: "item/tool/requestUserInput"; + readonly params: ServerRequest__ToolRequestUserInputParams; + } + | { + readonly id: ServerRequest__RequestId; + readonly method: "mcpServer/elicitation/request"; + readonly params: ServerRequest__McpServerElicitationRequestParams; + } + | { + readonly id: ServerRequest__RequestId; + readonly method: "item/permissions/requestApproval"; + readonly params: ServerRequest__PermissionsRequestApprovalParams; + } + | { + readonly id: ServerRequest__RequestId; + readonly method: "item/tool/call"; + readonly params: ServerRequest__DynamicToolCallParams; + } + | { + readonly id: ServerRequest__RequestId; + readonly method: "account/chatgptAuthTokens/refresh"; + readonly params: ServerRequest__ChatgptAuthTokensRefreshParams; + } + | { + readonly id: ServerRequest__RequestId; + readonly method: "applyPatchApproval"; + readonly params: ServerRequest__ApplyPatchApprovalParams; + } + | { + readonly id: ServerRequest__RequestId; + readonly method: "execCommandApproval"; + readonly params: ServerRequest__ExecCommandApprovalParams; + }; +export const ServerRequest = Schema.Union( + [ + Schema.Struct({ + id: ServerRequest__RequestId, + method: Schema.Literal("item/commandExecution/requestApproval").annotate({ + title: "Item/commandExecution/requestApprovalRequestMethod", + }), + params: ServerRequest__CommandExecutionRequestApprovalParams, + }).annotate({ + title: "Item/commandExecution/requestApprovalRequest", + description: + "NEW APIs Sent when approval is requested for a specific command execution. This request is used for Turns started via turn/start.", + }), + Schema.Struct({ + id: ServerRequest__RequestId, + method: Schema.Literal("item/fileChange/requestApproval").annotate({ + title: "Item/fileChange/requestApprovalRequestMethod", + }), + params: ServerRequest__FileChangeRequestApprovalParams, + }).annotate({ + title: "Item/fileChange/requestApprovalRequest", + description: + "Sent when approval is requested for a specific file change. This request is used for Turns started via turn/start.", + }), + Schema.Struct({ + id: ServerRequest__RequestId, + method: Schema.Literal("item/tool/requestUserInput").annotate({ + title: "Item/tool/requestUserInputRequestMethod", + }), + params: ServerRequest__ToolRequestUserInputParams, + }).annotate({ + title: "Item/tool/requestUserInputRequest", + description: "EXPERIMENTAL - Request input from the user for a tool call.", + }), + Schema.Struct({ + id: ServerRequest__RequestId, + method: Schema.Literal("mcpServer/elicitation/request").annotate({ + title: "McpServer/elicitation/requestRequestMethod", + }), + params: ServerRequest__McpServerElicitationRequestParams, + }).annotate({ + title: "McpServer/elicitation/requestRequest", + description: "Request input for an MCP server elicitation.", + }), + Schema.Struct({ + id: ServerRequest__RequestId, + method: Schema.Literal("item/permissions/requestApproval").annotate({ + title: "Item/permissions/requestApprovalRequestMethod", + }), + params: ServerRequest__PermissionsRequestApprovalParams, + }).annotate({ + title: "Item/permissions/requestApprovalRequest", + description: "Request approval for additional permissions from the user.", + }), + Schema.Struct({ + id: ServerRequest__RequestId, + method: Schema.Literal("item/tool/call").annotate({ title: "Item/tool/callRequestMethod" }), + params: ServerRequest__DynamicToolCallParams, + }).annotate({ + title: "Item/tool/callRequest", + description: "Execute a dynamic tool call on the client.", + }), + Schema.Struct({ + id: ServerRequest__RequestId, + method: Schema.Literal("account/chatgptAuthTokens/refresh").annotate({ + title: "Account/chatgptAuthTokens/refreshRequestMethod", + }), + params: ServerRequest__ChatgptAuthTokensRefreshParams, + }).annotate({ title: "Account/chatgptAuthTokens/refreshRequest" }), + Schema.Struct({ + id: ServerRequest__RequestId, + method: Schema.Literal("applyPatchApproval").annotate({ + title: "ApplyPatchApprovalRequestMethod", + }), + params: ServerRequest__ApplyPatchApprovalParams, + }).annotate({ + title: "ApplyPatchApprovalRequest", + description: + "DEPRECATED APIs below Request to approve a patch. This request is used for Turns started via the legacy APIs (i.e. SendUserTurn, SendUserMessage).", + }), + Schema.Struct({ + id: ServerRequest__RequestId, + method: Schema.Literal("execCommandApproval").annotate({ + title: "ExecCommandApprovalRequestMethod", + }), + params: ServerRequest__ExecCommandApprovalParams, + }).annotate({ + title: "ExecCommandApprovalRequest", + description: + "Request to exec a command. This request is used for Turns started via the legacy APIs (i.e. SendUserTurn, SendUserMessage).", + }), + ], + { mode: "oneOf" }, +).annotate({ + title: "ServerRequest", + description: "Request initiated from the server and sent to the client.", +}); + +export type ServerRequest__AdditionalPermissionProfile = { + readonly fileSystem?: ServerRequest__AdditionalFileSystemPermissions | null; + readonly network?: ServerRequest__AdditionalNetworkPermissions | null; +}; +export const ServerRequest__AdditionalPermissionProfile = Schema.Struct({ + fileSystem: Schema.optionalKey( + Schema.Union([ServerRequest__AdditionalFileSystemPermissions, Schema.Null]), + ), + network: Schema.optionalKey( + Schema.Union([ServerRequest__AdditionalNetworkPermissions, Schema.Null]), + ), +}); + +export type ServerRequest__CommandExecutionApprovalDecision = + | "accept" + | "acceptForSession" + | { + readonly acceptWithExecpolicyAmendment: { + readonly execpolicy_amendment: ReadonlyArray; + }; + } + | { + readonly applyNetworkPolicyAmendment: { + readonly network_policy_amendment: ServerRequest__NetworkPolicyAmendment; + }; + } + | "decline" + | "cancel"; +export const ServerRequest__CommandExecutionApprovalDecision = Schema.Union( + [ + Schema.Literal("accept").annotate({ description: "User approved the command." }), + Schema.Literal("acceptForSession").annotate({ + description: + "User approved the command and future prompts in the same session-scoped approval cache should run without prompting.", + }), + Schema.Struct({ + acceptWithExecpolicyAmendment: Schema.Struct({ + execpolicy_amendment: Schema.Array(Schema.String), + }), + }).annotate({ + title: "AcceptWithExecpolicyAmendmentCommandExecutionApprovalDecision", + description: + "User approved the command, and wants to apply the proposed execpolicy amendment so future matching commands can run without prompting.", + }), + Schema.Struct({ + applyNetworkPolicyAmendment: Schema.Struct({ + network_policy_amendment: ServerRequest__NetworkPolicyAmendment, + }), + }).annotate({ + title: "ApplyNetworkPolicyAmendmentCommandExecutionApprovalDecision", + description: "User chose a persistent network policy rule (allow/deny) for this host.", + }), + Schema.Literal("decline").annotate({ + description: "User denied the command. The agent will continue the turn.", + }), + Schema.Literal("cancel").annotate({ + description: "User denied the command. The turn will also be immediately interrupted.", + }), + ], + { mode: "oneOf" }, +); + +export type ToolRequestUserInputParams = { + readonly itemId: string; + readonly questions: ReadonlyArray; + readonly threadId: string; + readonly turnId: string; +}; +export const ToolRequestUserInputParams = Schema.Struct({ + itemId: Schema.String, + questions: Schema.Array(ToolRequestUserInputParams__ToolRequestUserInputQuestion), + threadId: Schema.String, + turnId: Schema.String, +}).annotate({ + title: "ToolRequestUserInputParams", + description: "EXPERIMENTAL. Params sent with a request_user_input event.", +}); + +export type ToolRequestUserInputResponse = { + readonly answers: { + readonly [x: string]: ToolRequestUserInputResponse__ToolRequestUserInputAnswer; + }; +}; +export const ToolRequestUserInputResponse = Schema.Struct({ + answers: Schema.Record(Schema.String, ToolRequestUserInputResponse__ToolRequestUserInputAnswer), +}).annotate({ + title: "ToolRequestUserInputResponse", + description: "EXPERIMENTAL. Response payload mapping question ids to answers.", +}); + +export type V1InitializeParams = { + readonly capabilities?: V1InitializeParams__InitializeCapabilities | null; + readonly clientInfo: V1InitializeParams__ClientInfo; +}; +export const V1InitializeParams = Schema.Struct({ + capabilities: Schema.optionalKey( + Schema.Union([V1InitializeParams__InitializeCapabilities, Schema.Null]), + ), + clientInfo: V1InitializeParams__ClientInfo, +}).annotate({ title: "InitializeParams" }); + +export type V1InitializeResponse = { + readonly codexHome: string; + readonly platformFamily: string; + readonly platformOs: string; + readonly userAgent: string; +}; +export const V1InitializeResponse = Schema.Struct({ + codexHome: Schema.String.annotate({ + description: + "A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\n\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.", + }), + platformFamily: Schema.String.annotate({ + description: + 'Platform family for the running app-server target, for example `"unix"` or `"windows"`.', + }), + platformOs: Schema.String.annotate({ + description: + 'Operating system for the running app-server target, for example `"macos"`, `"linux"`, or `"windows"`.', + }), + userAgent: Schema.String, +}).annotate({ title: "InitializeResponse" }); + +export type V1InitializeResponse__AbsolutePathBuf = string; +export const V1InitializeResponse__AbsolutePathBuf = Schema.String.annotate({ + description: + "A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\n\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.", +}); + +export type V2AccountLoginCompletedNotification = { + readonly error?: string | null; + readonly loginId?: string | null; + readonly success: boolean; +}; +export const V2AccountLoginCompletedNotification = Schema.Struct({ + error: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + loginId: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + success: Schema.Boolean, +}).annotate({ title: "AccountLoginCompletedNotification" }); + +export type V2AccountRateLimitsUpdatedNotification = { + readonly rateLimits: V2AccountRateLimitsUpdatedNotification__RateLimitSnapshot; +}; +export const V2AccountRateLimitsUpdatedNotification = Schema.Struct({ + rateLimits: V2AccountRateLimitsUpdatedNotification__RateLimitSnapshot, +}).annotate({ title: "AccountRateLimitsUpdatedNotification" }); + +export type V2AccountUpdatedNotification = { + readonly authMode?: V2AccountUpdatedNotification__AuthMode | null; + readonly planType?: V2AccountUpdatedNotification__PlanType | null; +}; +export const V2AccountUpdatedNotification = Schema.Struct({ + authMode: Schema.optionalKey(Schema.Union([V2AccountUpdatedNotification__AuthMode, Schema.Null])), + planType: Schema.optionalKey(Schema.Union([V2AccountUpdatedNotification__PlanType, Schema.Null])), +}).annotate({ title: "AccountUpdatedNotification" }); + +export type V2AgentMessageDeltaNotification = { + readonly delta: string; + readonly itemId: string; + readonly threadId: string; + readonly turnId: string; +}; +export const V2AgentMessageDeltaNotification = Schema.Struct({ + delta: Schema.String, + itemId: Schema.String, + threadId: Schema.String, + turnId: Schema.String, +}).annotate({ title: "AgentMessageDeltaNotification" }); + +export type V2AppListUpdatedNotification = { + readonly data: ReadonlyArray; +}; +export const V2AppListUpdatedNotification = Schema.Struct({ + data: Schema.Array(V2AppListUpdatedNotification__AppInfo), +}).annotate({ + title: "AppListUpdatedNotification", + description: "EXPERIMENTAL - notification emitted when the app list changes.", +}); + +export type V2AppsListParams = { + readonly cursor?: string | null; + readonly forceRefetch?: boolean; + readonly limit?: number | null; + readonly threadId?: string | null; +}; +export const V2AppsListParams = Schema.Struct({ + cursor: Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + description: "Opaque pagination cursor returned by a previous call.", + }), + Schema.Null, + ]), + ), + forceRefetch: Schema.optionalKey( + Schema.Boolean.annotate({ + description: "When true, bypass app caches and fetch the latest data from sources.", + }), + ), + limit: Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ + description: "Optional page size; defaults to a reasonable server-side value.", + format: "uint32", + }) + .check(Schema.isInt()) + .check(Schema.isGreaterThanOrEqualTo(0)), + Schema.Null, + ]), + ), + threadId: Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + description: + "Optional thread id used to evaluate app feature gating from that thread's config.", + }), + Schema.Null, + ]), + ), +}).annotate({ + title: "AppsListParams", + description: "EXPERIMENTAL - list available apps/connectors.", +}); + +export type V2AppsListResponse = { + readonly data: ReadonlyArray; + readonly nextCursor?: string | null; +}; +export const V2AppsListResponse = Schema.Struct({ + data: Schema.Array(V2AppsListResponse__AppInfo), + nextCursor: Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + description: + "Opaque cursor to pass to the next call to continue after the last item. If None, there are no more items to return.", + }), + Schema.Null, + ]), + ), +}).annotate({ title: "AppsListResponse", description: "EXPERIMENTAL - app list response." }); + +export type V2CancelLoginAccountParams = { readonly loginId: string }; +export const V2CancelLoginAccountParams = Schema.Struct({ loginId: Schema.String }).annotate({ + title: "CancelLoginAccountParams", +}); + +export type V2CancelLoginAccountResponse = { + readonly status: V2CancelLoginAccountResponse__CancelLoginAccountStatus; +}; +export const V2CancelLoginAccountResponse = Schema.Struct({ + status: V2CancelLoginAccountResponse__CancelLoginAccountStatus, +}).annotate({ title: "CancelLoginAccountResponse" }); + +export type V2CommandExecOutputDeltaNotification = { + readonly capReached: boolean; + readonly deltaBase64: string; + readonly processId: string; + readonly stream: "stdout" | "stderr"; +}; +export const V2CommandExecOutputDeltaNotification = Schema.Struct({ + capReached: Schema.Boolean.annotate({ + description: + "`true` on the final streamed chunk for a stream when `outputBytesCap` truncated later output on that stream.", + }), + deltaBase64: Schema.String.annotate({ description: "Base64-encoded output bytes." }), + processId: Schema.String.annotate({ + description: + "Client-supplied, connection-scoped `processId` from the original `command/exec` request.", + }), + stream: Schema.Literals(["stdout", "stderr"]).annotate({ + description: "Stream label for `command/exec/outputDelta` notifications.", + }), +}).annotate({ + title: "CommandExecOutputDeltaNotification", + description: + "Base64-encoded output chunk emitted for a streaming `command/exec` request.\n\nThese notifications are connection-scoped. If the originating connection closes, the server terminates the process.", +}); + +export type V2CommandExecOutputDeltaNotification__CommandExecOutputStream = "stdout" | "stderr"; +export const V2CommandExecOutputDeltaNotification__CommandExecOutputStream = Schema.Literals([ + "stdout", + "stderr", +]).annotate({ description: "Stream label for `command/exec/outputDelta` notifications." }); + +export type V2CommandExecParams = { + readonly command: ReadonlyArray; + readonly cwd?: string | null; + readonly disableOutputCap?: boolean; + readonly disableTimeout?: boolean; + readonly env?: { readonly [x: string]: string | null } | null; + readonly outputBytesCap?: number | null; + readonly processId?: string | null; + readonly sandboxPolicy?: V2CommandExecParams__SandboxPolicy | null; + readonly size?: V2CommandExecParams__CommandExecTerminalSize | null; + readonly streamStdin?: boolean; + readonly streamStdoutStderr?: boolean; + readonly timeoutMs?: number | null; + readonly tty?: boolean; +}; +export const V2CommandExecParams = Schema.Struct({ + command: Schema.Array(Schema.String).annotate({ + description: "Command argv vector. Empty arrays are rejected.", + }), + cwd: Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + description: "Optional working directory. Defaults to the server cwd.", + }), + Schema.Null, + ]), + ), + disableOutputCap: Schema.optionalKey( + Schema.Boolean.annotate({ + description: + "Disable stdout/stderr capture truncation for this request.\n\nCannot be combined with `outputBytesCap`.", + }), + ), + disableTimeout: Schema.optionalKey( + Schema.Boolean.annotate({ + description: + "Disable the timeout entirely for this request.\n\nCannot be combined with `timeoutMs`.", + }), + ), + env: Schema.optionalKey( + Schema.Union([ + Schema.Record(Schema.String, Schema.Union([Schema.String, Schema.Null])).annotate({ + description: + "Optional environment overrides merged into the server-computed environment.\n\nMatching names override inherited values. Set a key to `null` to unset an inherited variable.", + }), + Schema.Null, + ]), + ), + outputBytesCap: Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ + description: + "Optional per-stream stdout/stderr capture cap in bytes.\n\nWhen omitted, the server default applies. Cannot be combined with `disableOutputCap`.", + format: "uint", + }) + .check(Schema.isInt()) + .check(Schema.isGreaterThanOrEqualTo(0)), + Schema.Null, + ]), + ), + processId: Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + description: + "Optional client-supplied, connection-scoped process id.\n\nRequired for `tty`, `streamStdin`, `streamStdoutStderr`, and follow-up `command/exec/write`, `command/exec/resize`, and `command/exec/terminate` calls. When omitted, buffered execution gets an internal id that is not exposed to the client.", + }), + Schema.Null, + ]), + ), + sandboxPolicy: Schema.optionalKey( + Schema.Union([V2CommandExecParams__SandboxPolicy, Schema.Null]).annotate({ + description: + "Optional sandbox policy for this command.\n\nUses the same shape as thread/turn execution sandbox configuration and defaults to the user's configured policy when omitted.", + }), + ), + size: Schema.optionalKey( + Schema.Union([V2CommandExecParams__CommandExecTerminalSize, Schema.Null]).annotate({ + description: "Optional initial PTY size in character cells. Only valid when `tty` is true.", + }), + ), + streamStdin: Schema.optionalKey( + Schema.Boolean.annotate({ + description: + "Allow follow-up `command/exec/write` requests to write stdin bytes.\n\nRequires a client-supplied `processId`.", + }), + ), + streamStdoutStderr: Schema.optionalKey( + Schema.Boolean.annotate({ + description: + "Stream stdout/stderr via `command/exec/outputDelta` notifications.\n\nStreamed bytes are not duplicated into the final response and require a client-supplied `processId`.", + }), + ), + timeoutMs: Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ + description: + "Optional timeout in milliseconds.\n\nWhen omitted, the server default applies. Cannot be combined with `disableTimeout`.", + format: "int64", + }).check(Schema.isInt()), + Schema.Null, + ]), + ), + tty: Schema.optionalKey( + Schema.Boolean.annotate({ + description: "Enable PTY mode.\n\nThis implies `streamStdin` and `streamStdoutStderr`.", + }), + ), +}).annotate({ + title: "CommandExecParams", + description: + "Run a standalone command (argv vector) in the server sandbox without creating a thread or turn.\n\nThe final `command/exec` response is deferred until the process exits and is sent only after all `command/exec/outputDelta` notifications for that connection have been emitted.", +}); + +export type V2CommandExecParams__NetworkAccess = "restricted" | "enabled"; +export const V2CommandExecParams__NetworkAccess = Schema.Literals(["restricted", "enabled"]); + +export type V2CommandExecParams__ReadOnlyAccess = + | { + readonly includePlatformDefaults?: boolean; + readonly readableRoots?: ReadonlyArray; + readonly type: "restricted"; + } + | { readonly type: "fullAccess" }; +export const V2CommandExecParams__ReadOnlyAccess = Schema.Union( + [ + Schema.Struct({ + includePlatformDefaults: Schema.optionalKey(Schema.Boolean.annotate({ default: true })), + readableRoots: Schema.optionalKey( + Schema.Array(V2CommandExecParams__AbsolutePathBuf).annotate({ default: [] }), + ), + type: Schema.Literal("restricted").annotate({ title: "RestrictedReadOnlyAccessType" }), + }).annotate({ title: "RestrictedReadOnlyAccess" }), + Schema.Struct({ + type: Schema.Literal("fullAccess").annotate({ title: "FullAccessReadOnlyAccessType" }), + }).annotate({ title: "FullAccessReadOnlyAccess" }), + ], + { mode: "oneOf" }, +); + +export type V2CommandExecResizeParams = { + readonly processId: string; + readonly size: { readonly cols: number; readonly rows: number }; +}; +export const V2CommandExecResizeParams = Schema.Struct({ + processId: Schema.String.annotate({ + description: + "Client-supplied, connection-scoped `processId` from the original `command/exec` request.", + }), + size: Schema.Struct({ + cols: Schema.Number.annotate({ + description: "Terminal width in character cells.", + format: "uint16", + }) + .check(Schema.isInt()) + .check(Schema.isGreaterThanOrEqualTo(0)), + rows: Schema.Number.annotate({ + description: "Terminal height in character cells.", + format: "uint16", + }) + .check(Schema.isInt()) + .check(Schema.isGreaterThanOrEqualTo(0)), + }).annotate({ description: "PTY size in character cells for `command/exec` PTY sessions." }), +}).annotate({ + title: "CommandExecResizeParams", + description: "Resize a running PTY-backed `command/exec` session.", +}); + +export type V2CommandExecResizeParams__CommandExecTerminalSize = { + readonly cols: number; + readonly rows: number; +}; +export const V2CommandExecResizeParams__CommandExecTerminalSize = Schema.Struct({ + cols: Schema.Number.annotate({ + description: "Terminal width in character cells.", + format: "uint16", + }) + .check(Schema.isInt()) + .check(Schema.isGreaterThanOrEqualTo(0)), + rows: Schema.Number.annotate({ + description: "Terminal height in character cells.", + format: "uint16", + }) + .check(Schema.isInt()) + .check(Schema.isGreaterThanOrEqualTo(0)), +}).annotate({ description: "PTY size in character cells for `command/exec` PTY sessions." }); + +export type V2CommandExecResizeResponse = {}; +export const V2CommandExecResizeResponse = Schema.Struct({}).annotate({ + title: "CommandExecResizeResponse", + description: "Empty success response for `command/exec/resize`.", +}); + +export type V2CommandExecResponse = { + readonly exitCode: number; + readonly stderr: string; + readonly stdout: string; +}; +export const V2CommandExecResponse = Schema.Struct({ + exitCode: Schema.Number.annotate({ description: "Process exit code.", format: "int32" }).check( + Schema.isInt(), + ), + stderr: Schema.String.annotate({ + description: + "Buffered stderr capture.\n\nEmpty when stderr was streamed via `command/exec/outputDelta`.", + }), + stdout: Schema.String.annotate({ + description: + "Buffered stdout capture.\n\nEmpty when stdout was streamed via `command/exec/outputDelta`.", + }), +}).annotate({ + title: "CommandExecResponse", + description: "Final buffered result for `command/exec`.", +}); + +export type V2CommandExecTerminateParams = { readonly processId: string }; +export const V2CommandExecTerminateParams = Schema.Struct({ + processId: Schema.String.annotate({ + description: + "Client-supplied, connection-scoped `processId` from the original `command/exec` request.", + }), +}).annotate({ + title: "CommandExecTerminateParams", + description: "Terminate a running `command/exec` session.", +}); + +export type V2CommandExecTerminateResponse = {}; +export const V2CommandExecTerminateResponse = Schema.Struct({}).annotate({ + title: "CommandExecTerminateResponse", + description: "Empty success response for `command/exec/terminate`.", +}); + +export type V2CommandExecutionOutputDeltaNotification = { + readonly delta: string; + readonly itemId: string; + readonly threadId: string; + readonly turnId: string; +}; +export const V2CommandExecutionOutputDeltaNotification = Schema.Struct({ + delta: Schema.String, + itemId: Schema.String, + threadId: Schema.String, + turnId: Schema.String, +}).annotate({ title: "CommandExecutionOutputDeltaNotification" }); + +export type V2CommandExecWriteParams = { + readonly closeStdin?: boolean; + readonly deltaBase64?: string | null; + readonly processId: string; +}; +export const V2CommandExecWriteParams = Schema.Struct({ + closeStdin: Schema.optionalKey( + Schema.Boolean.annotate({ + description: "Close stdin after writing `deltaBase64`, if present.", + }), + ), + deltaBase64: Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ description: "Optional base64-encoded stdin bytes to write." }), + Schema.Null, + ]), + ), + processId: Schema.String.annotate({ + description: + "Client-supplied, connection-scoped `processId` from the original `command/exec` request.", + }), +}).annotate({ + title: "CommandExecWriteParams", + description: "Write stdin bytes to a running `command/exec` session, close stdin, or both.", +}); + +export type V2CommandExecWriteResponse = {}; +export const V2CommandExecWriteResponse = Schema.Struct({}).annotate({ + title: "CommandExecWriteResponse", + description: "Empty success response for `command/exec/write`.", +}); + +export type V2ConfigBatchWriteParams = { + readonly edits: ReadonlyArray; + readonly expectedVersion?: string | null; + readonly filePath?: string | null; + readonly reloadUserConfig?: boolean; +}; +export const V2ConfigBatchWriteParams = Schema.Struct({ + edits: Schema.Array(V2ConfigBatchWriteParams__ConfigEdit), + expectedVersion: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + filePath: Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + description: + "Path to the config file to write; defaults to the user's `config.toml` when omitted.", + }), + Schema.Null, + ]), + ), + reloadUserConfig: Schema.optionalKey( + Schema.Boolean.annotate({ + description: + "When true, hot-reload the updated user config into all loaded threads after writing.", + }), + ), +}).annotate({ title: "ConfigBatchWriteParams" }); + +export type V2ConfigReadParams = { readonly cwd?: string | null; readonly includeLayers?: boolean }; +export const V2ConfigReadParams = Schema.Struct({ + cwd: Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + description: + "Optional working directory to resolve project config layers. If specified, return the effective config as seen from that directory (i.e., including any project layers between `cwd` and the project/repo root).", + }), + Schema.Null, + ]), + ), + includeLayers: Schema.optionalKey(Schema.Boolean.annotate({ default: false })), +}).annotate({ title: "ConfigReadParams" }); + +export type V2ConfigReadResponse = { + readonly config: V2ConfigReadResponse__Config; + readonly layers?: ReadonlyArray | null; + readonly origins: { readonly [x: string]: V2ConfigReadResponse__ConfigLayerMetadata }; +}; +export const V2ConfigReadResponse = Schema.Struct({ + config: V2ConfigReadResponse__Config, + layers: Schema.optionalKey( + Schema.Union([Schema.Array(V2ConfigReadResponse__ConfigLayer), Schema.Null]), + ), + origins: Schema.Record(Schema.String, V2ConfigReadResponse__ConfigLayerMetadata), +}).annotate({ title: "ConfigReadResponse" }); + +export type V2ConfigReadResponse__AppConfig = { + readonly default_tools_approval_mode?: V2ConfigReadResponse__AppToolApproval | null; + readonly default_tools_enabled?: boolean | null; + readonly destructive_enabled?: boolean | null; + readonly enabled?: boolean; + readonly open_world_enabled?: boolean | null; + readonly tools?: V2ConfigReadResponse__AppToolsConfig | null; +}; +export const V2ConfigReadResponse__AppConfig = Schema.Struct({ + default_tools_approval_mode: Schema.optionalKey( + Schema.Union([V2ConfigReadResponse__AppToolApproval, Schema.Null]), + ), + default_tools_enabled: Schema.optionalKey(Schema.Union([Schema.Boolean, Schema.Null])), + destructive_enabled: Schema.optionalKey(Schema.Union([Schema.Boolean, Schema.Null])), + enabled: Schema.optionalKey(Schema.Boolean.annotate({ default: true })), + open_world_enabled: Schema.optionalKey(Schema.Union([Schema.Boolean, Schema.Null])), + tools: Schema.optionalKey(Schema.Union([V2ConfigReadResponse__AppToolsConfig, Schema.Null])), +}); + +export type V2ConfigReadResponse__AppsConfig = { + readonly _default?: V2ConfigReadResponse__AppsDefaultConfig | null; +}; +export const V2ConfigReadResponse__AppsConfig = Schema.Struct({ + _default: Schema.optionalKey( + Schema.Union([V2ConfigReadResponse__AppsDefaultConfig, Schema.Null]), + ), +}); + +export type V2ConfigReadResponse__AppToolConfig = { + readonly approval_mode?: V2ConfigReadResponse__AppToolApproval | null; + readonly enabled?: boolean | null; +}; +export const V2ConfigReadResponse__AppToolConfig = Schema.Struct({ + approval_mode: Schema.optionalKey( + Schema.Union([V2ConfigReadResponse__AppToolApproval, Schema.Null]), + ), + enabled: Schema.optionalKey(Schema.Union([Schema.Boolean, Schema.Null])), +}); + +export type V2ConfigRequirementsReadResponse = { + readonly requirements?: V2ConfigRequirementsReadResponse__ConfigRequirements | null; +}; +export const V2ConfigRequirementsReadResponse = Schema.Struct({ + requirements: Schema.optionalKey( + Schema.Union([V2ConfigRequirementsReadResponse__ConfigRequirements, Schema.Null]).annotate({ + description: + "Null if no requirements are configured (e.g. no requirements.toml/MDM entries).", + }), + ), +}).annotate({ title: "ConfigRequirementsReadResponse" }); + +export type V2ConfigRequirementsReadResponse__ApprovalsReviewer = "user" | "guardian_subagent"; +export const V2ConfigRequirementsReadResponse__ApprovalsReviewer = Schema.Literals([ + "user", + "guardian_subagent", +]).annotate({ + description: + "Configures who approval requests are routed to for review. Examples include sandbox escapes, blocked network access, MCP approval prompts, and ARC escalations. Defaults to `user`. `guardian_subagent` uses a carefully prompted subagent to gather relevant context and apply a risk-based decision framework before approving or denying the request.", +}); + +export type V2ConfigRequirementsReadResponse__NetworkRequirements = { + readonly allowLocalBinding?: boolean | null; + readonly allowUnixSockets?: ReadonlyArray | null; + readonly allowUpstreamProxy?: boolean | null; + readonly allowedDomains?: ReadonlyArray | null; + readonly dangerFullAccessDenylistOnly?: boolean | null; + readonly dangerouslyAllowAllUnixSockets?: boolean | null; + readonly dangerouslyAllowNonLoopbackProxy?: boolean | null; + readonly deniedDomains?: ReadonlyArray | null; + readonly domains?: { + readonly [x: string]: V2ConfigRequirementsReadResponse__NetworkDomainPermission; + } | null; + readonly enabled?: boolean | null; + readonly httpPort?: number | null; + readonly managedAllowedDomainsOnly?: boolean | null; + readonly socksPort?: number | null; + readonly unixSockets?: { + readonly [x: string]: V2ConfigRequirementsReadResponse__NetworkUnixSocketPermission; + } | null; +}; +export const V2ConfigRequirementsReadResponse__NetworkRequirements = Schema.Struct({ + allowLocalBinding: Schema.optionalKey(Schema.Union([Schema.Boolean, Schema.Null])), + allowUnixSockets: Schema.optionalKey( + Schema.Union([ + Schema.Array(Schema.String).annotate({ + description: "Legacy compatibility view derived from `unix_sockets`.", + }), + Schema.Null, + ]), + ), + allowUpstreamProxy: Schema.optionalKey(Schema.Union([Schema.Boolean, Schema.Null])), + allowedDomains: Schema.optionalKey( + Schema.Union([ + Schema.Array(Schema.String).annotate({ + description: "Legacy compatibility view derived from `domains`.", + }), + Schema.Null, + ]), + ), + dangerFullAccessDenylistOnly: Schema.optionalKey(Schema.Union([Schema.Boolean, Schema.Null])), + dangerouslyAllowAllUnixSockets: Schema.optionalKey(Schema.Union([Schema.Boolean, Schema.Null])), + dangerouslyAllowNonLoopbackProxy: Schema.optionalKey(Schema.Union([Schema.Boolean, Schema.Null])), + deniedDomains: Schema.optionalKey( + Schema.Union([ + Schema.Array(Schema.String).annotate({ + description: "Legacy compatibility view derived from `domains`.", + }), + Schema.Null, + ]), + ), + domains: Schema.optionalKey( + Schema.Union([ + Schema.Record( + Schema.String, + V2ConfigRequirementsReadResponse__NetworkDomainPermission, + ).annotate({ description: "Canonical network permission map for `experimental_network`." }), + Schema.Null, + ]), + ), + enabled: Schema.optionalKey(Schema.Union([Schema.Boolean, Schema.Null])), + httpPort: Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ format: "uint16" }) + .check(Schema.isInt()) + .check(Schema.isGreaterThanOrEqualTo(0)), + Schema.Null, + ]), + ), + managedAllowedDomainsOnly: Schema.optionalKey( + Schema.Union([ + Schema.Boolean.annotate({ + description: + "When true, only managed allowlist entries are respected while managed network enforcement is active.", + }), + Schema.Null, + ]), + ), + socksPort: Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ format: "uint16" }) + .check(Schema.isInt()) + .check(Schema.isGreaterThanOrEqualTo(0)), + Schema.Null, + ]), + ), + unixSockets: Schema.optionalKey( + Schema.Union([ + Schema.Record( + Schema.String, + V2ConfigRequirementsReadResponse__NetworkUnixSocketPermission, + ).annotate({ + description: "Canonical unix socket permission map for `experimental_network`.", + }), + Schema.Null, + ]), + ), +}); + +export type V2ConfigValueWriteParams = { + readonly expectedVersion?: string | null; + readonly filePath?: string | null; + readonly keyPath: string; + readonly mergeStrategy: V2ConfigValueWriteParams__MergeStrategy; + readonly value: unknown; +}; +export const V2ConfigValueWriteParams = Schema.Struct({ + expectedVersion: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + filePath: Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + description: + "Path to the config file to write; defaults to the user's `config.toml` when omitted.", + }), + Schema.Null, + ]), + ), + keyPath: Schema.String, + mergeStrategy: V2ConfigValueWriteParams__MergeStrategy, + value: Schema.Unknown, +}).annotate({ title: "ConfigValueWriteParams" }); + +export type V2ConfigWarningNotification = { + readonly details?: string | null; + readonly path?: string | null; + readonly range?: V2ConfigWarningNotification__TextRange | null; + readonly summary: string; +}; +export const V2ConfigWarningNotification = Schema.Struct({ + details: Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ description: "Optional extra guidance or error details." }), + Schema.Null, + ]), + ), + path: Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + description: "Optional path to the config file that triggered the warning.", + }), + Schema.Null, + ]), + ), + range: Schema.optionalKey( + Schema.Union([V2ConfigWarningNotification__TextRange, Schema.Null]).annotate({ + description: "Optional range for the error location inside the config file.", + }), + ), + summary: Schema.String.annotate({ description: "Concise summary of the warning." }), +}).annotate({ title: "ConfigWarningNotification" }); + +export type V2ConfigWriteResponse = { + readonly filePath: string; + readonly overriddenMetadata?: V2ConfigWriteResponse__OverriddenMetadata | null; + readonly status: V2ConfigWriteResponse__WriteStatus; + readonly version: string; +}; +export const V2ConfigWriteResponse = Schema.Struct({ + filePath: Schema.String.annotate({ + description: + "A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\n\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.", + }), + overriddenMetadata: Schema.optionalKey( + Schema.Union([V2ConfigWriteResponse__OverriddenMetadata, Schema.Null]), + ), + status: V2ConfigWriteResponse__WriteStatus, + version: Schema.String, +}).annotate({ title: "ConfigWriteResponse" }); + +export type V2ContextCompactedNotification = { readonly threadId: string; readonly turnId: string }; +export const V2ContextCompactedNotification = Schema.Struct({ + threadId: Schema.String, + turnId: Schema.String, +}).annotate({ + title: "ContextCompactedNotification", + description: "Deprecated: Use `ContextCompaction` item type instead.", +}); + +export type V2DeprecationNoticeNotification = { + readonly details?: string | null; + readonly summary: string; +}; +export const V2DeprecationNoticeNotification = Schema.Struct({ + details: Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + description: "Optional extra guidance, such as migration steps or rationale.", + }), + Schema.Null, + ]), + ), + summary: Schema.String.annotate({ description: "Concise summary of what is deprecated." }), +}).annotate({ title: "DeprecationNoticeNotification" }); + +export type V2ErrorNotification = { + readonly error: V2ErrorNotification__TurnError; + readonly threadId: string; + readonly turnId: string; + readonly willRetry: boolean; +}; +export const V2ErrorNotification = Schema.Struct({ + error: V2ErrorNotification__TurnError, + threadId: Schema.String, + turnId: Schema.String, + willRetry: Schema.Boolean, +}).annotate({ title: "ErrorNotification" }); + +export type V2ExperimentalFeatureEnablementSetParams = { + readonly enablement: { readonly [x: string]: boolean }; +}; +export const V2ExperimentalFeatureEnablementSetParams = Schema.Struct({ + enablement: Schema.Record(Schema.String, Schema.Boolean).annotate({ + description: + "Process-wide runtime feature enablement keyed by canonical feature name.\n\nOnly named features are updated. Omitted features are left unchanged. Send an empty map for a no-op.", + }), +}).annotate({ title: "ExperimentalFeatureEnablementSetParams" }); + +export type V2ExperimentalFeatureEnablementSetResponse = { + readonly enablement: { readonly [x: string]: boolean }; +}; +export const V2ExperimentalFeatureEnablementSetResponse = Schema.Struct({ + enablement: Schema.Record(Schema.String, Schema.Boolean).annotate({ + description: "Feature enablement entries updated by this request.", + }), +}).annotate({ title: "ExperimentalFeatureEnablementSetResponse" }); + +export type V2ExperimentalFeatureListParams = { + readonly cursor?: string | null; + readonly limit?: number | null; +}; +export const V2ExperimentalFeatureListParams = Schema.Struct({ + cursor: Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + description: "Opaque pagination cursor returned by a previous call.", + }), + Schema.Null, + ]), + ), + limit: Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ + description: "Optional page size; defaults to a reasonable server-side value.", + format: "uint32", + }) + .check(Schema.isInt()) + .check(Schema.isGreaterThanOrEqualTo(0)), + Schema.Null, + ]), + ), +}).annotate({ title: "ExperimentalFeatureListParams" }); + +export type V2ExperimentalFeatureListResponse = { + readonly data: ReadonlyArray; + readonly nextCursor?: string | null; +}; +export const V2ExperimentalFeatureListResponse = Schema.Struct({ + data: Schema.Array(V2ExperimentalFeatureListResponse__ExperimentalFeature), + nextCursor: Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + description: + "Opaque cursor to pass to the next call to continue after the last item. If None, there are no more items to return.", + }), + Schema.Null, + ]), + ), +}).annotate({ title: "ExperimentalFeatureListResponse" }); + +export type V2ExperimentalFeatureListResponse__ExperimentalFeatureStage = + | "beta" + | "underDevelopment" + | "stable" + | "deprecated" + | "removed"; +export const V2ExperimentalFeatureListResponse__ExperimentalFeatureStage = Schema.Literals([ + "beta", + "underDevelopment", + "stable", + "deprecated", + "removed", +]); + +export type V2ExternalAgentConfigDetectParams = { + readonly cwds?: ReadonlyArray | null; + readonly includeHome?: boolean; +}; +export const V2ExternalAgentConfigDetectParams = Schema.Struct({ + cwds: Schema.optionalKey( + Schema.Union([ + Schema.Array(Schema.String).annotate({ + description: "Zero or more working directories to include for repo-scoped detection.", + }), + Schema.Null, + ]), + ), + includeHome: Schema.optionalKey( + Schema.Boolean.annotate({ + description: "If true, include detection under the user's home (~/.claude, ~/.codex, etc.).", + }), + ), +}).annotate({ title: "ExternalAgentConfigDetectParams" }); + +export type V2ExternalAgentConfigDetectResponse = { + readonly items: ReadonlyArray; +}; +export const V2ExternalAgentConfigDetectResponse = Schema.Struct({ + items: Schema.Array(V2ExternalAgentConfigDetectResponse__ExternalAgentConfigMigrationItem), +}).annotate({ title: "ExternalAgentConfigDetectResponse" }); + +export type V2ExternalAgentConfigImportParams = { + readonly migrationItems: ReadonlyArray; +}; +export const V2ExternalAgentConfigImportParams = Schema.Struct({ + migrationItems: Schema.Array(V2ExternalAgentConfigImportParams__ExternalAgentConfigMigrationItem), +}).annotate({ title: "ExternalAgentConfigImportParams" }); + +export type V2ExternalAgentConfigImportResponse = {}; +export const V2ExternalAgentConfigImportResponse = Schema.Struct({}).annotate({ + title: "ExternalAgentConfigImportResponse", +}); + +export type V2FeedbackUploadParams = { + readonly classification: string; + readonly extraLogFiles?: ReadonlyArray | null; + readonly includeLogs: boolean; + readonly reason?: string | null; + readonly threadId?: string | null; +}; +export const V2FeedbackUploadParams = Schema.Struct({ + classification: Schema.String, + extraLogFiles: Schema.optionalKey(Schema.Union([Schema.Array(Schema.String), Schema.Null])), + includeLogs: Schema.Boolean, + reason: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + threadId: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), +}).annotate({ title: "FeedbackUploadParams" }); + +export type V2FeedbackUploadResponse = { readonly threadId: string }; +export const V2FeedbackUploadResponse = Schema.Struct({ threadId: Schema.String }).annotate({ + title: "FeedbackUploadResponse", +}); + +export type V2FileChangeOutputDeltaNotification = { + readonly delta: string; + readonly itemId: string; + readonly threadId: string; + readonly turnId: string; +}; +export const V2FileChangeOutputDeltaNotification = Schema.Struct({ + delta: Schema.String, + itemId: Schema.String, + threadId: Schema.String, + turnId: Schema.String, +}).annotate({ title: "FileChangeOutputDeltaNotification" }); + +export type V2FsChangedNotification = { + readonly changedPaths: ReadonlyArray; + readonly watchId: string; +}; +export const V2FsChangedNotification = Schema.Struct({ + changedPaths: Schema.Array(V2FsChangedNotification__AbsolutePathBuf).annotate({ + description: "File or directory paths associated with this event.", + }), + watchId: Schema.String.annotate({ + description: "Watch identifier previously provided to `fs/watch`.", + }), +}).annotate({ + title: "FsChangedNotification", + description: "Filesystem watch notification emitted for `fs/watch` subscribers.", +}); + +export type V2FsCopyParams = { + readonly destinationPath: string; + readonly recursive?: boolean; + readonly sourcePath: string; +}; +export const V2FsCopyParams = Schema.Struct({ + destinationPath: Schema.String.annotate({ + description: + "A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\n\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.", + }), + recursive: Schema.optionalKey( + Schema.Boolean.annotate({ + description: "Required for directory copies; ignored for file copies.", + }), + ), + sourcePath: Schema.String.annotate({ + description: + "A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\n\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.", + }), +}).annotate({ + title: "FsCopyParams", + description: "Copy a file or directory tree on the host filesystem.", +}); + +export type V2FsCopyParams__AbsolutePathBuf = string; +export const V2FsCopyParams__AbsolutePathBuf = Schema.String.annotate({ + description: + "A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\n\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.", +}); + +export type V2FsCopyResponse = {}; +export const V2FsCopyResponse = Schema.Struct({}).annotate({ + title: "FsCopyResponse", + description: "Successful response for `fs/copy`.", +}); + +export type V2FsCreateDirectoryParams = { + readonly path: string; + readonly recursive?: boolean | null; +}; +export const V2FsCreateDirectoryParams = Schema.Struct({ + path: Schema.String.annotate({ + description: + "A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\n\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.", + }), + recursive: Schema.optionalKey( + Schema.Union([ + Schema.Boolean.annotate({ + description: "Whether parent directories should also be created. Defaults to `true`.", + }), + Schema.Null, + ]), + ), +}).annotate({ + title: "FsCreateDirectoryParams", + description: "Create a directory on the host filesystem.", +}); + +export type V2FsCreateDirectoryParams__AbsolutePathBuf = string; +export const V2FsCreateDirectoryParams__AbsolutePathBuf = Schema.String.annotate({ + description: + "A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\n\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.", +}); + +export type V2FsCreateDirectoryResponse = {}; +export const V2FsCreateDirectoryResponse = Schema.Struct({}).annotate({ + title: "FsCreateDirectoryResponse", + description: "Successful response for `fs/createDirectory`.", +}); + +export type V2FsGetMetadataParams = { readonly path: string }; +export const V2FsGetMetadataParams = Schema.Struct({ + path: Schema.String.annotate({ + description: + "A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\n\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.", + }), +}).annotate({ + title: "FsGetMetadataParams", + description: "Request metadata for an absolute path.", +}); + +export type V2FsGetMetadataParams__AbsolutePathBuf = string; +export const V2FsGetMetadataParams__AbsolutePathBuf = Schema.String.annotate({ + description: + "A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\n\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.", +}); + +export type V2FsGetMetadataResponse = { + readonly createdAtMs: number; + readonly isDirectory: boolean; + readonly isFile: boolean; + readonly modifiedAtMs: number; +}; +export const V2FsGetMetadataResponse = Schema.Struct({ + createdAtMs: Schema.Number.annotate({ + description: "File creation time in Unix milliseconds when available, otherwise `0`.", + format: "int64", + }).check(Schema.isInt()), + isDirectory: Schema.Boolean.annotate({ + description: "Whether the path currently resolves to a directory.", + }), + isFile: Schema.Boolean.annotate({ + description: "Whether the path currently resolves to a regular file.", + }), + modifiedAtMs: Schema.Number.annotate({ + description: "File modification time in Unix milliseconds when available, otherwise `0`.", + format: "int64", + }).check(Schema.isInt()), +}).annotate({ + title: "FsGetMetadataResponse", + description: "Metadata returned by `fs/getMetadata`.", +}); + +export type V2FsReadDirectoryParams = { readonly path: string }; +export const V2FsReadDirectoryParams = Schema.Struct({ + path: Schema.String.annotate({ + description: + "A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\n\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.", + }), +}).annotate({ + title: "FsReadDirectoryParams", + description: "List direct child names for a directory.", +}); + +export type V2FsReadDirectoryParams__AbsolutePathBuf = string; +export const V2FsReadDirectoryParams__AbsolutePathBuf = Schema.String.annotate({ + description: + "A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\n\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.", +}); + +export type V2FsReadDirectoryResponse = { + readonly entries: ReadonlyArray; +}; +export const V2FsReadDirectoryResponse = Schema.Struct({ + entries: Schema.Array(V2FsReadDirectoryResponse__FsReadDirectoryEntry).annotate({ + description: "Direct child entries in the requested directory.", + }), +}).annotate({ + title: "FsReadDirectoryResponse", + description: "Directory entries returned by `fs/readDirectory`.", +}); + +export type V2FsReadFileParams = { readonly path: string }; +export const V2FsReadFileParams = Schema.Struct({ + path: Schema.String.annotate({ + description: + "A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\n\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.", + }), +}).annotate({ title: "FsReadFileParams", description: "Read a file from the host filesystem." }); + +export type V2FsReadFileParams__AbsolutePathBuf = string; +export const V2FsReadFileParams__AbsolutePathBuf = Schema.String.annotate({ + description: + "A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\n\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.", +}); + +export type V2FsReadFileResponse = { readonly dataBase64: string }; +export const V2FsReadFileResponse = Schema.Struct({ + dataBase64: Schema.String.annotate({ description: "File contents encoded as base64." }), +}).annotate({ + title: "FsReadFileResponse", + description: "Base64-encoded file contents returned by `fs/readFile`.", +}); + +export type V2FsRemoveParams = { + readonly force?: boolean | null; + readonly path: string; + readonly recursive?: boolean | null; +}; +export const V2FsRemoveParams = Schema.Struct({ + force: Schema.optionalKey( + Schema.Union([ + Schema.Boolean.annotate({ + description: "Whether missing paths should be ignored. Defaults to `true`.", + }), + Schema.Null, + ]), + ), + path: Schema.String.annotate({ + description: + "A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\n\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.", + }), + recursive: Schema.optionalKey( + Schema.Union([ + Schema.Boolean.annotate({ + description: "Whether directory removal should recurse. Defaults to `true`.", + }), + Schema.Null, + ]), + ), +}).annotate({ + title: "FsRemoveParams", + description: "Remove a file or directory tree from the host filesystem.", +}); + +export type V2FsRemoveParams__AbsolutePathBuf = string; +export const V2FsRemoveParams__AbsolutePathBuf = Schema.String.annotate({ + description: + "A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\n\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.", +}); + +export type V2FsRemoveResponse = {}; +export const V2FsRemoveResponse = Schema.Struct({}).annotate({ + title: "FsRemoveResponse", + description: "Successful response for `fs/remove`.", +}); + +export type V2FsUnwatchParams = { readonly watchId: string }; +export const V2FsUnwatchParams = Schema.Struct({ + watchId: Schema.String.annotate({ + description: "Watch identifier previously provided to `fs/watch`.", + }), +}).annotate({ + title: "FsUnwatchParams", + description: "Stop filesystem watch notifications for a prior `fs/watch`.", +}); + +export type V2FsUnwatchResponse = {}; +export const V2FsUnwatchResponse = Schema.Struct({}).annotate({ + title: "FsUnwatchResponse", + description: "Successful response for `fs/unwatch`.", +}); + +export type V2FsWatchParams = { readonly path: string; readonly watchId: string }; +export const V2FsWatchParams = Schema.Struct({ + path: Schema.String.annotate({ + description: + "A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\n\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.", + }), + watchId: Schema.String.annotate({ + description: "Connection-scoped watch identifier used for `fs/unwatch` and `fs/changed`.", + }), +}).annotate({ + title: "FsWatchParams", + description: "Start filesystem watch notifications for an absolute path.", +}); + +export type V2FsWatchParams__AbsolutePathBuf = string; +export const V2FsWatchParams__AbsolutePathBuf = Schema.String.annotate({ + description: + "A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\n\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.", +}); + +export type V2FsWatchResponse = { readonly path: string }; +export const V2FsWatchResponse = Schema.Struct({ + path: Schema.String.annotate({ + description: + "A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\n\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.", + }), +}).annotate({ title: "FsWatchResponse", description: "Successful response for `fs/watch`." }); + +export type V2FsWatchResponse__AbsolutePathBuf = string; +export const V2FsWatchResponse__AbsolutePathBuf = Schema.String.annotate({ + description: + "A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\n\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.", +}); + +export type V2FsWriteFileParams = { readonly dataBase64: string; readonly path: string }; +export const V2FsWriteFileParams = Schema.Struct({ + dataBase64: Schema.String.annotate({ description: "File contents encoded as base64." }), + path: Schema.String.annotate({ + description: + "A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\n\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.", + }), +}).annotate({ title: "FsWriteFileParams", description: "Write a file on the host filesystem." }); + +export type V2FsWriteFileParams__AbsolutePathBuf = string; +export const V2FsWriteFileParams__AbsolutePathBuf = Schema.String.annotate({ + description: + "A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\n\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.", +}); + +export type V2FsWriteFileResponse = {}; +export const V2FsWriteFileResponse = Schema.Struct({}).annotate({ + title: "FsWriteFileResponse", + description: "Successful response for `fs/writeFile`.", +}); + +export type V2GetAccountParams = { readonly refreshToken?: boolean }; +export const V2GetAccountParams = Schema.Struct({ + refreshToken: Schema.optionalKey( + Schema.Boolean.annotate({ + description: + "When `true`, requests a proactive token refresh before returning.\n\nIn managed auth mode this triggers the normal refresh-token flow. In external auth mode this flag is ignored. Clients should refresh tokens themselves and call `account/login/start` with `chatgptAuthTokens`.", + default: false, + }), + ), +}).annotate({ title: "GetAccountParams" }); + +export type V2GetAccountRateLimitsResponse = { + readonly rateLimits: { + readonly credits?: V2GetAccountRateLimitsResponse__CreditsSnapshot | null; + readonly limitId?: string | null; + readonly limitName?: string | null; + readonly planType?: V2GetAccountRateLimitsResponse__PlanType | null; + readonly primary?: V2GetAccountRateLimitsResponse__RateLimitWindow | null; + readonly secondary?: V2GetAccountRateLimitsResponse__RateLimitWindow | null; + }; + readonly rateLimitsByLimitId?: { + readonly [x: string]: V2GetAccountRateLimitsResponse__RateLimitSnapshot; + } | null; +}; +export const V2GetAccountRateLimitsResponse = Schema.Struct({ + rateLimits: Schema.Struct({ + credits: Schema.optionalKey( + Schema.Union([V2GetAccountRateLimitsResponse__CreditsSnapshot, Schema.Null]), + ), + limitId: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + limitName: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + planType: Schema.optionalKey( + Schema.Union([V2GetAccountRateLimitsResponse__PlanType, Schema.Null]), + ), + primary: Schema.optionalKey( + Schema.Union([V2GetAccountRateLimitsResponse__RateLimitWindow, Schema.Null]), + ), + secondary: Schema.optionalKey( + Schema.Union([V2GetAccountRateLimitsResponse__RateLimitWindow, Schema.Null]), + ), + }).annotate({ + description: "Backward-compatible single-bucket view; mirrors the historical payload.", + }), + rateLimitsByLimitId: Schema.optionalKey( + Schema.Union([ + Schema.Record(Schema.String, V2GetAccountRateLimitsResponse__RateLimitSnapshot).annotate({ + description: "Multi-bucket view keyed by metered `limit_id` (for example, `codex`).", + }), + Schema.Null, + ]), + ), +}).annotate({ title: "GetAccountRateLimitsResponse" }); + +export type V2GetAccountResponse = { + readonly account?: V2GetAccountResponse__Account | null; + readonly requiresOpenaiAuth: boolean; +}; +export const V2GetAccountResponse = Schema.Struct({ + account: Schema.optionalKey(Schema.Union([V2GetAccountResponse__Account, Schema.Null])), + requiresOpenaiAuth: Schema.Boolean, +}).annotate({ title: "GetAccountResponse" }); + +export type V2HookCompletedNotification = { + readonly run: V2HookCompletedNotification__HookRunSummary; + readonly threadId: string; + readonly turnId?: string | null; +}; +export const V2HookCompletedNotification = Schema.Struct({ + run: V2HookCompletedNotification__HookRunSummary, + threadId: Schema.String, + turnId: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), +}).annotate({ title: "HookCompletedNotification" }); + +export type V2HookStartedNotification = { + readonly run: V2HookStartedNotification__HookRunSummary; + readonly threadId: string; + readonly turnId?: string | null; +}; +export const V2HookStartedNotification = Schema.Struct({ + run: V2HookStartedNotification__HookRunSummary, + threadId: Schema.String, + turnId: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), +}).annotate({ title: "HookStartedNotification" }); + +export type V2ItemCompletedNotification = { + readonly item: V2ItemCompletedNotification__ThreadItem; + readonly threadId: string; + readonly turnId: string; +}; +export const V2ItemCompletedNotification = Schema.Struct({ + item: V2ItemCompletedNotification__ThreadItem, + threadId: Schema.String, + turnId: Schema.String, +}).annotate({ title: "ItemCompletedNotification" }); + +export type V2ItemCompletedNotification__ByteRange = { + readonly end: number; + readonly start: number; +}; +export const V2ItemCompletedNotification__ByteRange = Schema.Struct({ + end: Schema.Number.annotate({ format: "uint" }) + .check(Schema.isInt()) + .check(Schema.isGreaterThanOrEqualTo(0)), + start: Schema.Number.annotate({ format: "uint" }) + .check(Schema.isInt()) + .check(Schema.isGreaterThanOrEqualTo(0)), +}); + +export type V2ItemCompletedNotification__CollabAgentTool = + | "spawnAgent" + | "sendInput" + | "resumeAgent" + | "wait" + | "closeAgent"; +export const V2ItemCompletedNotification__CollabAgentTool = Schema.Literals([ + "spawnAgent", + "sendInput", + "resumeAgent", + "wait", + "closeAgent", +]); + +export type V2ItemCompletedNotification__CollabAgentToolCallStatus = + | "inProgress" + | "completed" + | "failed"; +export const V2ItemCompletedNotification__CollabAgentToolCallStatus = Schema.Literals([ + "inProgress", + "completed", + "failed", +]); + +export type V2ItemCompletedNotification__CommandExecutionSource = + | "agent" + | "userShell" + | "unifiedExecStartup" + | "unifiedExecInteraction"; +export const V2ItemCompletedNotification__CommandExecutionSource = Schema.Literals([ + "agent", + "userShell", + "unifiedExecStartup", + "unifiedExecInteraction", +]); + +export type V2ItemGuardianApprovalReviewCompletedNotification = { + readonly action: V2ItemGuardianApprovalReviewCompletedNotification__GuardianApprovalReviewAction; + readonly decisionSource: V2ItemGuardianApprovalReviewCompletedNotification__AutoReviewDecisionSource; + readonly review: V2ItemGuardianApprovalReviewCompletedNotification__GuardianApprovalReview; + readonly reviewId: string; + readonly targetItemId?: string | null; + readonly threadId: string; + readonly turnId: string; +}; +export const V2ItemGuardianApprovalReviewCompletedNotification = Schema.Struct({ + action: V2ItemGuardianApprovalReviewCompletedNotification__GuardianApprovalReviewAction, + decisionSource: V2ItemGuardianApprovalReviewCompletedNotification__AutoReviewDecisionSource, + review: V2ItemGuardianApprovalReviewCompletedNotification__GuardianApprovalReview, + reviewId: Schema.String.annotate({ description: "Stable identifier for this review." }), + targetItemId: Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + description: + "Identifier for the reviewed item or tool call when one exists.\n\nIn most cases, one review maps to one target item. The exceptions are - execve reviews, where a single command may contain multiple execve calls to review (only possible when using the shell_zsh_fork feature) - network policy reviews, where there is no target item\n\nA network call is triggered by a CommandExecution item, so having a target_item_id set to the CommandExecution item would be misleading because the review is about the network call, not the command execution. Therefore, target_item_id is set to None for network policy reviews.", + }), + Schema.Null, + ]), + ), + threadId: Schema.String, + turnId: Schema.String, +}).annotate({ + title: "ItemGuardianApprovalReviewCompletedNotification", + description: + "[UNSTABLE] Temporary notification payload for guardian automatic approval review. This shape is expected to change soon.", +}); + +export type V2ItemGuardianApprovalReviewStartedNotification = { + readonly action: V2ItemGuardianApprovalReviewStartedNotification__GuardianApprovalReviewAction; + readonly review: V2ItemGuardianApprovalReviewStartedNotification__GuardianApprovalReview; + readonly reviewId: string; + readonly targetItemId?: string | null; + readonly threadId: string; + readonly turnId: string; +}; +export const V2ItemGuardianApprovalReviewStartedNotification = Schema.Struct({ + action: V2ItemGuardianApprovalReviewStartedNotification__GuardianApprovalReviewAction, + review: V2ItemGuardianApprovalReviewStartedNotification__GuardianApprovalReview, + reviewId: Schema.String.annotate({ description: "Stable identifier for this review." }), + targetItemId: Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + description: + "Identifier for the reviewed item or tool call when one exists.\n\nIn most cases, one review maps to one target item. The exceptions are - execve reviews, where a single command may contain multiple execve calls to review (only possible when using the shell_zsh_fork feature) - network policy reviews, where there is no target item\n\nA network call is triggered by a CommandExecution item, so having a target_item_id set to the CommandExecution item would be misleading because the review is about the network call, not the command execution. Therefore, target_item_id is set to None for network policy reviews.", + }), + Schema.Null, + ]), + ), + threadId: Schema.String, + turnId: Schema.String, +}).annotate({ + title: "ItemGuardianApprovalReviewStartedNotification", + description: + "[UNSTABLE] Temporary notification payload for guardian automatic approval review. This shape is expected to change soon.", +}); + +export type V2ItemStartedNotification = { + readonly item: V2ItemStartedNotification__ThreadItem; + readonly threadId: string; + readonly turnId: string; +}; +export const V2ItemStartedNotification = Schema.Struct({ + item: V2ItemStartedNotification__ThreadItem, + threadId: Schema.String, + turnId: Schema.String, +}).annotate({ title: "ItemStartedNotification" }); + +export type V2ItemStartedNotification__ByteRange = { readonly end: number; readonly start: number }; +export const V2ItemStartedNotification__ByteRange = Schema.Struct({ + end: Schema.Number.annotate({ format: "uint" }) + .check(Schema.isInt()) + .check(Schema.isGreaterThanOrEqualTo(0)), + start: Schema.Number.annotate({ format: "uint" }) + .check(Schema.isInt()) + .check(Schema.isGreaterThanOrEqualTo(0)), +}); + +export type V2ItemStartedNotification__CollabAgentTool = + | "spawnAgent" + | "sendInput" + | "resumeAgent" + | "wait" + | "closeAgent"; +export const V2ItemStartedNotification__CollabAgentTool = Schema.Literals([ + "spawnAgent", + "sendInput", + "resumeAgent", + "wait", + "closeAgent", +]); + +export type V2ItemStartedNotification__CollabAgentToolCallStatus = + | "inProgress" + | "completed" + | "failed"; +export const V2ItemStartedNotification__CollabAgentToolCallStatus = Schema.Literals([ + "inProgress", + "completed", + "failed", +]); + +export type V2ItemStartedNotification__CommandExecutionSource = + | "agent" + | "userShell" + | "unifiedExecStartup" + | "unifiedExecInteraction"; +export const V2ItemStartedNotification__CommandExecutionSource = Schema.Literals([ + "agent", + "userShell", + "unifiedExecStartup", + "unifiedExecInteraction", +]); + +export type V2ListMcpServerStatusParams = { + readonly cursor?: string | null; + readonly detail?: V2ListMcpServerStatusParams__McpServerStatusDetail | null; + readonly limit?: number | null; +}; +export const V2ListMcpServerStatusParams = Schema.Struct({ + cursor: Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + description: "Opaque pagination cursor returned by a previous call.", + }), + Schema.Null, + ]), + ), + detail: Schema.optionalKey( + Schema.Union([V2ListMcpServerStatusParams__McpServerStatusDetail, Schema.Null]).annotate({ + description: + "Controls how much MCP inventory data to fetch for each server. Defaults to `Full` when omitted.", + }), + ), + limit: Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ + description: "Optional page size; defaults to a server-defined value.", + format: "uint32", + }) + .check(Schema.isInt()) + .check(Schema.isGreaterThanOrEqualTo(0)), + Schema.Null, + ]), + ), +}).annotate({ title: "ListMcpServerStatusParams" }); + +export type V2ListMcpServerStatusResponse = { + readonly data: ReadonlyArray; + readonly nextCursor?: string | null; +}; +export const V2ListMcpServerStatusResponse = Schema.Struct({ + data: Schema.Array(V2ListMcpServerStatusResponse__McpServerStatus), + nextCursor: Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + description: + "Opaque cursor to pass to the next call to continue after the last item. If None, there are no more items to return.", + }), + Schema.Null, + ]), + ), +}).annotate({ title: "ListMcpServerStatusResponse" }); + +export type V2LoginAccountParams = + | { readonly apiKey: string; readonly type: "apiKey" } + | { readonly type: "chatgpt" } + | { readonly type: "chatgptDeviceCode" } + | { + readonly accessToken: string; + readonly chatgptAccountId: string; + readonly chatgptPlanType?: string | null; + readonly type: "chatgptAuthTokens"; + }; +export const V2LoginAccountParams = Schema.Union( + [ + Schema.Struct({ + apiKey: Schema.String, + type: Schema.Literal("apiKey").annotate({ title: "ApiKeyv2::LoginAccountParamsType" }), + }).annotate({ title: "ApiKeyv2::LoginAccountParams" }), + Schema.Struct({ + type: Schema.Literal("chatgpt").annotate({ title: "Chatgptv2::LoginAccountParamsType" }), + }).annotate({ title: "Chatgptv2::LoginAccountParams" }), + Schema.Struct({ + type: Schema.Literal("chatgptDeviceCode").annotate({ + title: "ChatgptDeviceCodev2::LoginAccountParamsType", + }), + }).annotate({ title: "ChatgptDeviceCodev2::LoginAccountParams" }), + Schema.Struct({ + accessToken: Schema.String.annotate({ + description: + "Access token (JWT) supplied by the client. This token is used for backend API requests and email extraction.", + }), + chatgptAccountId: Schema.String.annotate({ + description: "Workspace/account identifier supplied by the client.", + }), + chatgptPlanType: Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + description: + "Optional plan type supplied by the client.\n\nWhen `null`, Codex attempts to derive the plan type from access-token claims. If unavailable, the plan defaults to `unknown`.", + }), + Schema.Null, + ]), + ), + type: Schema.Literal("chatgptAuthTokens").annotate({ + title: "ChatgptAuthTokensv2::LoginAccountParamsType", + }), + }).annotate({ + title: "ChatgptAuthTokensv2::LoginAccountParams", + description: + "[UNSTABLE] FOR OPENAI INTERNAL USE ONLY - DO NOT USE. The access token must contain the same scopes that Codex-managed ChatGPT auth tokens have.", + }), + ], + { mode: "oneOf" }, +).annotate({ title: "LoginAccountParams" }); + +export type V2LoginAccountResponse = + | { readonly type: "apiKey" } + | { readonly authUrl: string; readonly loginId: string; readonly type: "chatgpt" } + | { + readonly loginId: string; + readonly type: "chatgptDeviceCode"; + readonly userCode: string; + readonly verificationUrl: string; + } + | { readonly type: "chatgptAuthTokens" }; +export const V2LoginAccountResponse = Schema.Union( + [ + Schema.Struct({ + type: Schema.Literal("apiKey").annotate({ title: "ApiKeyv2::LoginAccountResponseType" }), + }).annotate({ title: "ApiKeyv2::LoginAccountResponse" }), + Schema.Struct({ + authUrl: Schema.String.annotate({ + description: "URL the client should open in a browser to initiate the OAuth flow.", + }), + loginId: Schema.String, + type: Schema.Literal("chatgpt").annotate({ title: "Chatgptv2::LoginAccountResponseType" }), + }).annotate({ title: "Chatgptv2::LoginAccountResponse" }), + Schema.Struct({ + loginId: Schema.String, + type: Schema.Literal("chatgptDeviceCode").annotate({ + title: "ChatgptDeviceCodev2::LoginAccountResponseType", + }), + userCode: Schema.String.annotate({ + description: "One-time code the user must enter after signing in.", + }), + verificationUrl: Schema.String.annotate({ + description: + "URL the client should open in a browser to complete device code authorization.", + }), + }).annotate({ title: "ChatgptDeviceCodev2::LoginAccountResponse" }), + Schema.Struct({ + type: Schema.Literal("chatgptAuthTokens").annotate({ + title: "ChatgptAuthTokensv2::LoginAccountResponseType", + }), + }).annotate({ title: "ChatgptAuthTokensv2::LoginAccountResponse" }), + ], + { mode: "oneOf" }, +).annotate({ title: "LoginAccountResponse" }); + +export type V2LogoutAccountResponse = {}; +export const V2LogoutAccountResponse = Schema.Struct({}).annotate({ + title: "LogoutAccountResponse", +}); + +export type V2McpResourceReadParams = { + readonly server: string; + readonly threadId: string; + readonly uri: string; +}; +export const V2McpResourceReadParams = Schema.Struct({ + server: Schema.String, + threadId: Schema.String, + uri: Schema.String, +}).annotate({ title: "McpResourceReadParams" }); + +export type V2McpResourceReadResponse = { + readonly contents: ReadonlyArray; +}; +export const V2McpResourceReadResponse = Schema.Struct({ + contents: Schema.Array(V2McpResourceReadResponse__ResourceContent), +}).annotate({ title: "McpResourceReadResponse" }); + +export type V2McpServerOauthLoginCompletedNotification = { + readonly error?: string | null; + readonly name: string; + readonly success: boolean; +}; +export const V2McpServerOauthLoginCompletedNotification = Schema.Struct({ + error: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + name: Schema.String, + success: Schema.Boolean, +}).annotate({ title: "McpServerOauthLoginCompletedNotification" }); + +export type V2McpServerOauthLoginParams = { + readonly name: string; + readonly scopes?: ReadonlyArray | null; + readonly timeoutSecs?: number | null; +}; +export const V2McpServerOauthLoginParams = Schema.Struct({ + name: Schema.String, + scopes: Schema.optionalKey(Schema.Union([Schema.Array(Schema.String), Schema.Null])), + timeoutSecs: Schema.optionalKey( + Schema.Union([Schema.Number.annotate({ format: "int64" }).check(Schema.isInt()), Schema.Null]), + ), +}).annotate({ title: "McpServerOauthLoginParams" }); + +export type V2McpServerOauthLoginResponse = { readonly authorizationUrl: string }; +export const V2McpServerOauthLoginResponse = Schema.Struct({ + authorizationUrl: Schema.String, +}).annotate({ title: "McpServerOauthLoginResponse" }); + +export type V2McpServerRefreshResponse = {}; +export const V2McpServerRefreshResponse = Schema.Struct({}).annotate({ + title: "McpServerRefreshResponse", +}); + +export type V2McpServerStatusUpdatedNotification = { + readonly error?: string | null; + readonly name: string; + readonly status: V2McpServerStatusUpdatedNotification__McpServerStartupState; +}; +export const V2McpServerStatusUpdatedNotification = Schema.Struct({ + error: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + name: Schema.String, + status: V2McpServerStatusUpdatedNotification__McpServerStartupState, +}).annotate({ title: "McpServerStatusUpdatedNotification" }); + +export type V2McpServerToolCallParams = { + readonly _meta?: unknown; + readonly arguments?: unknown; + readonly server: string; + readonly threadId: string; + readonly tool: string; +}; +export const V2McpServerToolCallParams = Schema.Struct({ + _meta: Schema.optionalKey(Schema.Unknown), + arguments: Schema.optionalKey(Schema.Unknown), + server: Schema.String, + threadId: Schema.String, + tool: Schema.String, +}).annotate({ title: "McpServerToolCallParams" }); + +export type V2McpServerToolCallResponse = { + readonly _meta?: unknown; + readonly content: ReadonlyArray; + readonly isError?: boolean | null; + readonly structuredContent?: unknown; +}; +export const V2McpServerToolCallResponse = Schema.Struct({ + _meta: Schema.optionalKey(Schema.Unknown), + content: Schema.Array(Schema.Unknown), + isError: Schema.optionalKey(Schema.Union([Schema.Boolean, Schema.Null])), + structuredContent: Schema.optionalKey(Schema.Unknown), +}).annotate({ title: "McpServerToolCallResponse" }); + +export type V2McpToolCallProgressNotification = { + readonly itemId: string; + readonly message: string; + readonly threadId: string; + readonly turnId: string; +}; +export const V2McpToolCallProgressNotification = Schema.Struct({ + itemId: Schema.String, + message: Schema.String, + threadId: Schema.String, + turnId: Schema.String, +}).annotate({ title: "McpToolCallProgressNotification" }); + +export type V2ModelListParams = { + readonly cursor?: string | null; + readonly includeHidden?: boolean | null; + readonly limit?: number | null; +}; +export const V2ModelListParams = Schema.Struct({ + cursor: Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + description: "Opaque pagination cursor returned by a previous call.", + }), + Schema.Null, + ]), + ), + includeHidden: Schema.optionalKey( + Schema.Union([ + Schema.Boolean.annotate({ + description: "When true, include models that are hidden from the default picker list.", + }), + Schema.Null, + ]), + ), + limit: Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ + description: "Optional page size; defaults to a reasonable server-side value.", + format: "uint32", + }) + .check(Schema.isInt()) + .check(Schema.isGreaterThanOrEqualTo(0)), + Schema.Null, + ]), + ), +}).annotate({ title: "ModelListParams" }); + +export type V2ModelListResponse = { + readonly data: ReadonlyArray; + readonly nextCursor?: string | null; +}; +export const V2ModelListResponse = Schema.Struct({ + data: Schema.Array(V2ModelListResponse__Model), + nextCursor: Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + description: + "Opaque cursor to pass to the next call to continue after the last item. If None, there are no more items to return.", + }), + Schema.Null, + ]), + ), +}).annotate({ title: "ModelListResponse" }); + +export type V2ModelReroutedNotification = { + readonly fromModel: string; + readonly reason: V2ModelReroutedNotification__ModelRerouteReason; + readonly threadId: string; + readonly toModel: string; + readonly turnId: string; +}; +export const V2ModelReroutedNotification = Schema.Struct({ + fromModel: Schema.String, + reason: V2ModelReroutedNotification__ModelRerouteReason, + threadId: Schema.String, + toModel: Schema.String, + turnId: Schema.String, +}).annotate({ title: "ModelReroutedNotification" }); + +export type V2PlanDeltaNotification = { + readonly delta: string; + readonly itemId: string; + readonly threadId: string; + readonly turnId: string; +}; +export const V2PlanDeltaNotification = Schema.Struct({ + delta: Schema.String, + itemId: Schema.String, + threadId: Schema.String, + turnId: Schema.String, +}).annotate({ + title: "PlanDeltaNotification", + description: + "EXPERIMENTAL - proposed plan streaming deltas for plan items. Clients should not assume concatenated deltas match the completed plan item content.", +}); + +export type V2PluginInstallParams = { + readonly forceRemoteSync?: boolean; + readonly marketplacePath: V2PluginInstallParams__AbsolutePathBuf; + readonly pluginName: string; +}; +export const V2PluginInstallParams = Schema.Struct({ + forceRemoteSync: Schema.optionalKey( + Schema.Boolean.annotate({ + description: "When true, apply the remote plugin change before the local install flow.", + }), + ), + marketplacePath: V2PluginInstallParams__AbsolutePathBuf, + pluginName: Schema.String, +}).annotate({ title: "PluginInstallParams" }); + +export type V2PluginInstallResponse = { + readonly appsNeedingAuth: ReadonlyArray; + readonly authPolicy: V2PluginInstallResponse__PluginAuthPolicy; +}; +export const V2PluginInstallResponse = Schema.Struct({ + appsNeedingAuth: Schema.Array(V2PluginInstallResponse__AppSummary), + authPolicy: V2PluginInstallResponse__PluginAuthPolicy, +}).annotate({ title: "PluginInstallResponse" }); + +export type V2PluginListParams = { + readonly cwds?: ReadonlyArray | null; + readonly forceRemoteSync?: boolean; +}; +export const V2PluginListParams = Schema.Struct({ + cwds: Schema.optionalKey( + Schema.Union([ + Schema.Array(V2PluginListParams__AbsolutePathBuf).annotate({ + description: + "Optional working directories used to discover repo marketplaces. When omitted, only home-scoped marketplaces and the official curated marketplace are considered.", + }), + Schema.Null, + ]), + ), + forceRemoteSync: Schema.optionalKey( + Schema.Boolean.annotate({ + description: + "When true, reconcile the official curated marketplace against the remote plugin state before listing marketplaces.", + }), + ), +}).annotate({ title: "PluginListParams" }); + +export type V2PluginListResponse = { + readonly featuredPluginIds?: ReadonlyArray; + readonly marketplaceLoadErrors?: ReadonlyArray; + readonly marketplaces: ReadonlyArray; + readonly remoteSyncError?: string | null; +}; +export const V2PluginListResponse = Schema.Struct({ + featuredPluginIds: Schema.optionalKey(Schema.Array(Schema.String).annotate({ default: [] })), + marketplaceLoadErrors: Schema.optionalKey( + Schema.Array(V2PluginListResponse__MarketplaceLoadErrorInfo).annotate({ default: [] }), + ), + marketplaces: Schema.Array(V2PluginListResponse__PluginMarketplaceEntry), + remoteSyncError: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), +}).annotate({ title: "PluginListResponse" }); + +export type V2PluginReadParams = { + readonly marketplacePath: V2PluginReadParams__AbsolutePathBuf; + readonly pluginName: string; +}; +export const V2PluginReadParams = Schema.Struct({ + marketplacePath: V2PluginReadParams__AbsolutePathBuf, + pluginName: Schema.String, +}).annotate({ title: "PluginReadParams" }); + +export type V2PluginReadResponse = { readonly plugin: V2PluginReadResponse__PluginDetail }; +export const V2PluginReadResponse = Schema.Struct({ + plugin: V2PluginReadResponse__PluginDetail, +}).annotate({ title: "PluginReadResponse" }); + +export type V2PluginUninstallParams = { + readonly forceRemoteSync?: boolean; + readonly pluginId: string; +}; +export const V2PluginUninstallParams = Schema.Struct({ + forceRemoteSync: Schema.optionalKey( + Schema.Boolean.annotate({ + description: "When true, apply the remote plugin change before the local uninstall flow.", + }), + ), + pluginId: Schema.String, +}).annotate({ title: "PluginUninstallParams" }); + +export type V2PluginUninstallResponse = {}; +export const V2PluginUninstallResponse = Schema.Struct({}).annotate({ + title: "PluginUninstallResponse", +}); + +export type V2RawResponseItemCompletedNotification = { + readonly item: V2RawResponseItemCompletedNotification__ResponseItem; + readonly threadId: string; + readonly turnId: string; +}; +export const V2RawResponseItemCompletedNotification = Schema.Struct({ + item: V2RawResponseItemCompletedNotification__ResponseItem, + threadId: Schema.String, + turnId: Schema.String, +}).annotate({ title: "RawResponseItemCompletedNotification" }); + +export type V2ReasoningSummaryPartAddedNotification = { + readonly itemId: string; + readonly summaryIndex: number; + readonly threadId: string; + readonly turnId: string; +}; +export const V2ReasoningSummaryPartAddedNotification = Schema.Struct({ + itemId: Schema.String, + summaryIndex: Schema.Number.annotate({ format: "int64" }).check(Schema.isInt()), + threadId: Schema.String, + turnId: Schema.String, +}).annotate({ title: "ReasoningSummaryPartAddedNotification" }); + +export type V2ReasoningSummaryTextDeltaNotification = { + readonly delta: string; + readonly itemId: string; + readonly summaryIndex: number; + readonly threadId: string; + readonly turnId: string; +}; +export const V2ReasoningSummaryTextDeltaNotification = Schema.Struct({ + delta: Schema.String, + itemId: Schema.String, + summaryIndex: Schema.Number.annotate({ format: "int64" }).check(Schema.isInt()), + threadId: Schema.String, + turnId: Schema.String, +}).annotate({ title: "ReasoningSummaryTextDeltaNotification" }); + +export type V2ReasoningTextDeltaNotification = { + readonly contentIndex: number; + readonly delta: string; + readonly itemId: string; + readonly threadId: string; + readonly turnId: string; +}; +export const V2ReasoningTextDeltaNotification = Schema.Struct({ + contentIndex: Schema.Number.annotate({ format: "int64" }).check(Schema.isInt()), + delta: Schema.String, + itemId: Schema.String, + threadId: Schema.String, + turnId: Schema.String, +}).annotate({ title: "ReasoningTextDeltaNotification" }); + +export type V2ReviewStartParams = { + readonly delivery?: V2ReviewStartParams__ReviewDelivery | null; + readonly target: V2ReviewStartParams__ReviewTarget; + readonly threadId: string; +}; +export const V2ReviewStartParams = Schema.Struct({ + delivery: Schema.optionalKey( + Schema.Union([V2ReviewStartParams__ReviewDelivery, Schema.Null]).annotate({ + description: + "Where to run the review: inline (default) on the current thread or detached on a new thread (returned in `reviewThreadId`).", + }), + ), + target: V2ReviewStartParams__ReviewTarget, + threadId: Schema.String, +}).annotate({ title: "ReviewStartParams" }); + +export type V2ReviewStartResponse = { + readonly reviewThreadId: string; + readonly turn: V2ReviewStartResponse__Turn; +}; +export const V2ReviewStartResponse = Schema.Struct({ + reviewThreadId: Schema.String.annotate({ + description: + "Identifies the thread where the review runs.\n\nFor inline reviews, this is the original thread id. For detached reviews, this is the id of the new review thread.", + }), + turn: V2ReviewStartResponse__Turn, +}).annotate({ title: "ReviewStartResponse" }); + +export type V2ReviewStartResponse__ByteRange = { readonly end: number; readonly start: number }; +export const V2ReviewStartResponse__ByteRange = Schema.Struct({ + end: Schema.Number.annotate({ format: "uint" }) + .check(Schema.isInt()) + .check(Schema.isGreaterThanOrEqualTo(0)), + start: Schema.Number.annotate({ format: "uint" }) + .check(Schema.isInt()) + .check(Schema.isGreaterThanOrEqualTo(0)), +}); + +export type V2ReviewStartResponse__CollabAgentTool = + | "spawnAgent" + | "sendInput" + | "resumeAgent" + | "wait" + | "closeAgent"; +export const V2ReviewStartResponse__CollabAgentTool = Schema.Literals([ + "spawnAgent", + "sendInput", + "resumeAgent", + "wait", + "closeAgent", +]); + +export type V2ReviewStartResponse__CollabAgentToolCallStatus = + | "inProgress" + | "completed" + | "failed"; +export const V2ReviewStartResponse__CollabAgentToolCallStatus = Schema.Literals([ + "inProgress", + "completed", + "failed", +]); + +export type V2ReviewStartResponse__CommandExecutionSource = + | "agent" + | "userShell" + | "unifiedExecStartup" + | "unifiedExecInteraction"; +export const V2ReviewStartResponse__CommandExecutionSource = Schema.Literals([ + "agent", + "userShell", + "unifiedExecStartup", + "unifiedExecInteraction", +]); + +export type V2ServerRequestResolvedNotification = { + readonly requestId: V2ServerRequestResolvedNotification__RequestId; + readonly threadId: string; +}; +export const V2ServerRequestResolvedNotification = Schema.Struct({ + requestId: V2ServerRequestResolvedNotification__RequestId, + threadId: Schema.String, +}).annotate({ title: "ServerRequestResolvedNotification" }); + +export type V2SkillsChangedNotification = {}; +export const V2SkillsChangedNotification = Schema.Struct({}).annotate({ + title: "SkillsChangedNotification", + description: + "Notification emitted when watched local skill files change.\n\nTreat this as an invalidation signal and re-run `skills/list` with the client's current parameters when refreshed skill metadata is needed.", +}); + +export type V2SkillsConfigWriteParams = { + readonly enabled: boolean; + readonly name?: string | null; + readonly path?: V2SkillsConfigWriteParams__AbsolutePathBuf | null; +}; +export const V2SkillsConfigWriteParams = Schema.Struct({ + enabled: Schema.Boolean, + name: Schema.optionalKey( + Schema.Union([Schema.String.annotate({ description: "Name-based selector." }), Schema.Null]), + ), + path: Schema.optionalKey( + Schema.Union([V2SkillsConfigWriteParams__AbsolutePathBuf, Schema.Null]).annotate({ + description: "Path-based selector.", + }), + ), +}).annotate({ title: "SkillsConfigWriteParams" }); + +export type V2SkillsConfigWriteResponse = { readonly effectiveEnabled: boolean }; +export const V2SkillsConfigWriteResponse = Schema.Struct({ + effectiveEnabled: Schema.Boolean, +}).annotate({ title: "SkillsConfigWriteResponse" }); + +export type V2SkillsListParams = { + readonly cwds?: ReadonlyArray; + readonly forceReload?: boolean; + readonly perCwdExtraUserRoots?: ReadonlyArray | null; +}; +export const V2SkillsListParams = Schema.Struct({ + cwds: Schema.optionalKey( + Schema.Array(Schema.String).annotate({ + description: "When empty, defaults to the current session working directory.", + }), + ), + forceReload: Schema.optionalKey( + Schema.Boolean.annotate({ + description: "When true, bypass the skills cache and re-scan skills from disk.", + }), + ), + perCwdExtraUserRoots: Schema.optionalKey( + Schema.Union([ + Schema.Array(V2SkillsListParams__SkillsListExtraRootsForCwd).annotate({ + description: "Optional per-cwd extra roots to scan as user-scoped skills.", + }), + Schema.Null, + ]), + ), +}).annotate({ title: "SkillsListParams" }); + +export type V2SkillsListResponse = { + readonly data: ReadonlyArray; +}; +export const V2SkillsListResponse = Schema.Struct({ + data: Schema.Array(V2SkillsListResponse__SkillsListEntry), +}).annotate({ title: "SkillsListResponse" }); + +export type V2TerminalInteractionNotification = { + readonly itemId: string; + readonly processId: string; + readonly stdin: string; + readonly threadId: string; + readonly turnId: string; +}; +export const V2TerminalInteractionNotification = Schema.Struct({ + itemId: Schema.String, + processId: Schema.String, + stdin: Schema.String, + threadId: Schema.String, + turnId: Schema.String, +}).annotate({ title: "TerminalInteractionNotification" }); + +export type V2ThreadArchivedNotification = { readonly threadId: string }; +export const V2ThreadArchivedNotification = Schema.Struct({ threadId: Schema.String }).annotate({ + title: "ThreadArchivedNotification", +}); + +export type V2ThreadArchiveParams = { readonly threadId: string }; +export const V2ThreadArchiveParams = Schema.Struct({ threadId: Schema.String }).annotate({ + title: "ThreadArchiveParams", +}); + +export type V2ThreadArchiveResponse = {}; +export const V2ThreadArchiveResponse = Schema.Struct({}).annotate({ + title: "ThreadArchiveResponse", +}); + +export type V2ThreadClosedNotification = { readonly threadId: string }; +export const V2ThreadClosedNotification = Schema.Struct({ threadId: Schema.String }).annotate({ + title: "ThreadClosedNotification", +}); + +export type V2ThreadCompactStartParams = { readonly threadId: string }; +export const V2ThreadCompactStartParams = Schema.Struct({ threadId: Schema.String }).annotate({ + title: "ThreadCompactStartParams", +}); + +export type V2ThreadCompactStartResponse = {}; +export const V2ThreadCompactStartResponse = Schema.Struct({}).annotate({ + title: "ThreadCompactStartResponse", +}); + +export type V2ThreadForkParams = { + readonly approvalPolicy?: V2ThreadForkParams__AskForApproval | null; + readonly approvalsReviewer?: V2ThreadForkParams__ApprovalsReviewer | null; + readonly baseInstructions?: string | null; + readonly config?: { readonly [x: string]: unknown } | null; + readonly cwd?: string | null; + readonly developerInstructions?: string | null; + readonly ephemeral?: boolean; + readonly model?: string | null; + readonly modelProvider?: string | null; + readonly sandbox?: V2ThreadForkParams__SandboxMode | null; + readonly serviceTier?: V2ThreadForkParams__ServiceTier | null | null; + readonly threadId: string; +}; +export const V2ThreadForkParams = Schema.Struct({ + approvalPolicy: Schema.optionalKey( + Schema.Union([V2ThreadForkParams__AskForApproval, Schema.Null]), + ), + approvalsReviewer: Schema.optionalKey( + Schema.Union([V2ThreadForkParams__ApprovalsReviewer, Schema.Null]).annotate({ + description: + "Override where approval requests are routed for review on this thread and subsequent turns.", + }), + ), + baseInstructions: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + config: Schema.optionalKey( + Schema.Union([Schema.Record(Schema.String, Schema.Unknown), Schema.Null]), + ), + cwd: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + developerInstructions: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + ephemeral: Schema.optionalKey(Schema.Boolean), + model: Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + description: "Configuration overrides for the forked thread, if any.", + }), + Schema.Null, + ]), + ), + modelProvider: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + sandbox: Schema.optionalKey(Schema.Union([V2ThreadForkParams__SandboxMode, Schema.Null])), + serviceTier: Schema.optionalKey( + Schema.Union([Schema.Union([V2ThreadForkParams__ServiceTier, Schema.Null]), Schema.Null]), + ), + threadId: Schema.String, +}).annotate({ + title: "ThreadForkParams", + description: + "There are two ways to fork a thread: 1. By thread_id: load the thread from disk by thread_id and fork it into a new thread. 2. By path: load the thread from disk by path and fork it into a new thread.\n\nIf using path, the thread_id param will be ignored.\n\nPrefer using thread_id whenever possible.", +}); + +export type V2ThreadForkResponse = { + readonly approvalPolicy: V2ThreadForkResponse__AskForApproval; + readonly approvalsReviewer: "user" | "guardian_subagent"; + readonly cwd: string; + readonly model: string; + readonly modelProvider: string; + readonly reasoningEffort?: V2ThreadForkResponse__ReasoningEffort | null; + readonly sandbox: V2ThreadForkResponse__SandboxPolicy; + readonly serviceTier?: V2ThreadForkResponse__ServiceTier | null; + readonly thread: V2ThreadForkResponse__Thread; +}; +export const V2ThreadForkResponse = Schema.Struct({ + approvalPolicy: V2ThreadForkResponse__AskForApproval, + approvalsReviewer: Schema.Literals(["user", "guardian_subagent"]).annotate({ + description: + "Configures who approval requests are routed to for review. Examples include sandbox escapes, blocked network access, MCP approval prompts, and ARC escalations. Defaults to `user`. `guardian_subagent` uses a carefully prompted subagent to gather relevant context and apply a risk-based decision framework before approving or denying the request.", + }), + cwd: Schema.String, + model: Schema.String, + modelProvider: Schema.String, + reasoningEffort: Schema.optionalKey( + Schema.Union([V2ThreadForkResponse__ReasoningEffort, Schema.Null]), + ), + sandbox: V2ThreadForkResponse__SandboxPolicy, + serviceTier: Schema.optionalKey(Schema.Union([V2ThreadForkResponse__ServiceTier, Schema.Null])), + thread: V2ThreadForkResponse__Thread, +}).annotate({ title: "ThreadForkResponse" }); + +export type V2ThreadForkResponse__ApprovalsReviewer = "user" | "guardian_subagent"; +export const V2ThreadForkResponse__ApprovalsReviewer = Schema.Literals([ + "user", + "guardian_subagent", +]).annotate({ + description: + "Configures who approval requests are routed to for review. Examples include sandbox escapes, blocked network access, MCP approval prompts, and ARC escalations. Defaults to `user`. `guardian_subagent` uses a carefully prompted subagent to gather relevant context and apply a risk-based decision framework before approving or denying the request.", +}); + +export type V2ThreadForkResponse__ByteRange = { readonly end: number; readonly start: number }; +export const V2ThreadForkResponse__ByteRange = Schema.Struct({ + end: Schema.Number.annotate({ format: "uint" }) + .check(Schema.isInt()) + .check(Schema.isGreaterThanOrEqualTo(0)), + start: Schema.Number.annotate({ format: "uint" }) + .check(Schema.isInt()) + .check(Schema.isGreaterThanOrEqualTo(0)), +}); + +export type V2ThreadForkResponse__CollabAgentTool = + | "spawnAgent" + | "sendInput" + | "resumeAgent" + | "wait" + | "closeAgent"; +export const V2ThreadForkResponse__CollabAgentTool = Schema.Literals([ + "spawnAgent", + "sendInput", + "resumeAgent", + "wait", + "closeAgent", +]); + +export type V2ThreadForkResponse__CollabAgentToolCallStatus = "inProgress" | "completed" | "failed"; +export const V2ThreadForkResponse__CollabAgentToolCallStatus = Schema.Literals([ + "inProgress", + "completed", + "failed", +]); + +export type V2ThreadForkResponse__CommandExecutionSource = + | "agent" + | "userShell" + | "unifiedExecStartup" + | "unifiedExecInteraction"; +export const V2ThreadForkResponse__CommandExecutionSource = Schema.Literals([ + "agent", + "userShell", + "unifiedExecStartup", + "unifiedExecInteraction", +]); + +export type V2ThreadForkResponse__NetworkAccess = "restricted" | "enabled"; +export const V2ThreadForkResponse__NetworkAccess = Schema.Literals(["restricted", "enabled"]); + +export type V2ThreadForkResponse__ReadOnlyAccess = + | { + readonly includePlatformDefaults?: boolean; + readonly readableRoots?: ReadonlyArray; + readonly type: "restricted"; + } + | { readonly type: "fullAccess" }; +export const V2ThreadForkResponse__ReadOnlyAccess = Schema.Union( + [ + Schema.Struct({ + includePlatformDefaults: Schema.optionalKey(Schema.Boolean.annotate({ default: true })), + readableRoots: Schema.optionalKey( + Schema.Array(V2ThreadForkResponse__AbsolutePathBuf).annotate({ default: [] }), + ), + type: Schema.Literal("restricted").annotate({ title: "RestrictedReadOnlyAccessType" }), + }).annotate({ title: "RestrictedReadOnlyAccess" }), + Schema.Struct({ + type: Schema.Literal("fullAccess").annotate({ title: "FullAccessReadOnlyAccessType" }), + }).annotate({ title: "FullAccessReadOnlyAccess" }), + ], + { mode: "oneOf" }, +); + +export type V2ThreadForkResponse__SessionSource = + | "cli" + | "vscode" + | "exec" + | "appServer" + | "unknown" + | { readonly custom: string } + | { readonly subAgent: V2ThreadForkResponse__SubAgentSource }; +export const V2ThreadForkResponse__SessionSource = Schema.Union( + [ + Schema.Literals(["cli", "vscode", "exec", "appServer", "unknown"]), + Schema.Struct({ custom: Schema.String }).annotate({ title: "CustomSessionSource" }), + Schema.Struct({ subAgent: V2ThreadForkResponse__SubAgentSource }).annotate({ + title: "SubAgentSessionSource", + }), + ], + { mode: "oneOf" }, +); + +export type V2ThreadForkResponse__ThreadStatus = + | { readonly type: "notLoaded" } + | { readonly type: "idle" } + | { readonly type: "systemError" } + | { + readonly activeFlags: ReadonlyArray; + readonly type: "active"; + }; +export const V2ThreadForkResponse__ThreadStatus = Schema.Union( + [ + Schema.Struct({ + type: Schema.Literal("notLoaded").annotate({ title: "NotLoadedThreadStatusType" }), + }).annotate({ title: "NotLoadedThreadStatus" }), + Schema.Struct({ + type: Schema.Literal("idle").annotate({ title: "IdleThreadStatusType" }), + }).annotate({ title: "IdleThreadStatus" }), + Schema.Struct({ + type: Schema.Literal("systemError").annotate({ title: "SystemErrorThreadStatusType" }), + }).annotate({ title: "SystemErrorThreadStatus" }), + Schema.Struct({ + activeFlags: Schema.Array(V2ThreadForkResponse__ThreadActiveFlag), + type: Schema.Literal("active").annotate({ title: "ActiveThreadStatusType" }), + }).annotate({ title: "ActiveThreadStatus" }), + ], + { mode: "oneOf" }, +); + +export type V2ThreadListParams = { + readonly archived?: boolean | null; + readonly cursor?: string | null; + readonly cwd?: string | null; + readonly limit?: number | null; + readonly modelProviders?: ReadonlyArray | null; + readonly searchTerm?: string | null; + readonly sortKey?: V2ThreadListParams__ThreadSortKey | null; + readonly sourceKinds?: ReadonlyArray | null; +}; +export const V2ThreadListParams = Schema.Struct({ + archived: Schema.optionalKey( + Schema.Union([ + Schema.Boolean.annotate({ + description: + "Optional archived filter; when set to true, only archived threads are returned. If false or null, only non-archived threads are returned.", + }), + Schema.Null, + ]), + ), + cursor: Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + description: "Opaque pagination cursor returned by a previous call.", + }), + Schema.Null, + ]), + ), + cwd: Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + description: + "Optional cwd filter; when set, only threads whose session cwd exactly matches this path are returned.", + }), + Schema.Null, + ]), + ), + limit: Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ + description: "Optional page size; defaults to a reasonable server-side value.", + format: "uint32", + }) + .check(Schema.isInt()) + .check(Schema.isGreaterThanOrEqualTo(0)), + Schema.Null, + ]), + ), + modelProviders: Schema.optionalKey( + Schema.Union([ + Schema.Array(Schema.String).annotate({ + description: + "Optional provider filter; when set, only sessions recorded under these providers are returned. When present but empty, includes all providers.", + }), + Schema.Null, + ]), + ), + searchTerm: Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + description: "Optional substring filter for the extracted thread title.", + }), + Schema.Null, + ]), + ), + sortKey: Schema.optionalKey( + Schema.Union([V2ThreadListParams__ThreadSortKey, Schema.Null]).annotate({ + description: "Optional sort key; defaults to created_at.", + }), + ), + sourceKinds: Schema.optionalKey( + Schema.Union([ + Schema.Array(V2ThreadListParams__ThreadSourceKind).annotate({ + description: + "Optional source filter; when set, only sessions from these source kinds are returned. When omitted or empty, defaults to interactive sources.", + }), + Schema.Null, + ]), + ), +}).annotate({ title: "ThreadListParams" }); + +export type V2ThreadListResponse = { + readonly data: ReadonlyArray; + readonly nextCursor?: string | null; +}; +export const V2ThreadListResponse = Schema.Struct({ + data: Schema.Array(V2ThreadListResponse__Thread), + nextCursor: Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + description: + "Opaque cursor to pass to the next call to continue after the last item. if None, there are no more items to return.", + }), + Schema.Null, + ]), + ), +}).annotate({ title: "ThreadListResponse" }); + +export type V2ThreadListResponse__ByteRange = { readonly end: number; readonly start: number }; +export const V2ThreadListResponse__ByteRange = Schema.Struct({ + end: Schema.Number.annotate({ format: "uint" }) + .check(Schema.isInt()) + .check(Schema.isGreaterThanOrEqualTo(0)), + start: Schema.Number.annotate({ format: "uint" }) + .check(Schema.isInt()) + .check(Schema.isGreaterThanOrEqualTo(0)), +}); + +export type V2ThreadListResponse__CollabAgentTool = + | "spawnAgent" + | "sendInput" + | "resumeAgent" + | "wait" + | "closeAgent"; +export const V2ThreadListResponse__CollabAgentTool = Schema.Literals([ + "spawnAgent", + "sendInput", + "resumeAgent", + "wait", + "closeAgent", +]); + +export type V2ThreadListResponse__CollabAgentToolCallStatus = "inProgress" | "completed" | "failed"; +export const V2ThreadListResponse__CollabAgentToolCallStatus = Schema.Literals([ + "inProgress", + "completed", + "failed", +]); + +export type V2ThreadListResponse__CommandExecutionSource = + | "agent" + | "userShell" + | "unifiedExecStartup" + | "unifiedExecInteraction"; +export const V2ThreadListResponse__CommandExecutionSource = Schema.Literals([ + "agent", + "userShell", + "unifiedExecStartup", + "unifiedExecInteraction", +]); + +export type V2ThreadListResponse__SessionSource = + | "cli" + | "vscode" + | "exec" + | "appServer" + | "unknown" + | { readonly custom: string } + | { readonly subAgent: V2ThreadListResponse__SubAgentSource }; +export const V2ThreadListResponse__SessionSource = Schema.Union( + [ + Schema.Literals(["cli", "vscode", "exec", "appServer", "unknown"]), + Schema.Struct({ custom: Schema.String }).annotate({ title: "CustomSessionSource" }), + Schema.Struct({ subAgent: V2ThreadListResponse__SubAgentSource }).annotate({ + title: "SubAgentSessionSource", + }), + ], + { mode: "oneOf" }, +); + +export type V2ThreadListResponse__ThreadStatus = + | { readonly type: "notLoaded" } + | { readonly type: "idle" } + | { readonly type: "systemError" } + | { + readonly activeFlags: ReadonlyArray; + readonly type: "active"; + }; +export const V2ThreadListResponse__ThreadStatus = Schema.Union( + [ + Schema.Struct({ + type: Schema.Literal("notLoaded").annotate({ title: "NotLoadedThreadStatusType" }), + }).annotate({ title: "NotLoadedThreadStatus" }), + Schema.Struct({ + type: Schema.Literal("idle").annotate({ title: "IdleThreadStatusType" }), + }).annotate({ title: "IdleThreadStatus" }), + Schema.Struct({ + type: Schema.Literal("systemError").annotate({ title: "SystemErrorThreadStatusType" }), + }).annotate({ title: "SystemErrorThreadStatus" }), + Schema.Struct({ + activeFlags: Schema.Array(V2ThreadListResponse__ThreadActiveFlag), + type: Schema.Literal("active").annotate({ title: "ActiveThreadStatusType" }), + }).annotate({ title: "ActiveThreadStatus" }), + ], + { mode: "oneOf" }, +); + +export type V2ThreadLoadedListParams = { + readonly cursor?: string | null; + readonly limit?: number | null; +}; +export const V2ThreadLoadedListParams = Schema.Struct({ + cursor: Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + description: "Opaque pagination cursor returned by a previous call.", + }), + Schema.Null, + ]), + ), + limit: Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ + description: "Optional page size; defaults to no limit.", + format: "uint32", + }) + .check(Schema.isInt()) + .check(Schema.isGreaterThanOrEqualTo(0)), + Schema.Null, + ]), + ), +}).annotate({ title: "ThreadLoadedListParams" }); + +export type V2ThreadLoadedListResponse = { + readonly data: ReadonlyArray; + readonly nextCursor?: string | null; +}; +export const V2ThreadLoadedListResponse = Schema.Struct({ + data: Schema.Array(Schema.String).annotate({ + description: "Thread ids for sessions currently loaded in memory.", + }), + nextCursor: Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + description: + "Opaque cursor to pass to the next call to continue after the last item. if None, there are no more items to return.", + }), + Schema.Null, + ]), + ), +}).annotate({ title: "ThreadLoadedListResponse" }); + +export type V2ThreadMetadataUpdateParams = { + readonly gitInfo?: V2ThreadMetadataUpdateParams__ThreadMetadataGitInfoUpdateParams | null; + readonly threadId: string; +}; +export const V2ThreadMetadataUpdateParams = Schema.Struct({ + gitInfo: Schema.optionalKey( + Schema.Union([ + V2ThreadMetadataUpdateParams__ThreadMetadataGitInfoUpdateParams, + Schema.Null, + ]).annotate({ + description: + "Patch the stored Git metadata for this thread. Omit a field to leave it unchanged, set it to `null` to clear it, or provide a string to replace the stored value.", + }), + ), + threadId: Schema.String, +}).annotate({ title: "ThreadMetadataUpdateParams" }); + +export type V2ThreadMetadataUpdateResponse = { + readonly thread: V2ThreadMetadataUpdateResponse__Thread; +}; +export const V2ThreadMetadataUpdateResponse = Schema.Struct({ + thread: V2ThreadMetadataUpdateResponse__Thread, +}).annotate({ title: "ThreadMetadataUpdateResponse" }); + +export type V2ThreadMetadataUpdateResponse__ByteRange = { + readonly end: number; + readonly start: number; +}; +export const V2ThreadMetadataUpdateResponse__ByteRange = Schema.Struct({ + end: Schema.Number.annotate({ format: "uint" }) + .check(Schema.isInt()) + .check(Schema.isGreaterThanOrEqualTo(0)), + start: Schema.Number.annotate({ format: "uint" }) + .check(Schema.isInt()) + .check(Schema.isGreaterThanOrEqualTo(0)), +}); + +export type V2ThreadMetadataUpdateResponse__CollabAgentTool = + | "spawnAgent" + | "sendInput" + | "resumeAgent" + | "wait" + | "closeAgent"; +export const V2ThreadMetadataUpdateResponse__CollabAgentTool = Schema.Literals([ + "spawnAgent", + "sendInput", + "resumeAgent", + "wait", + "closeAgent", +]); + +export type V2ThreadMetadataUpdateResponse__CollabAgentToolCallStatus = + | "inProgress" + | "completed" + | "failed"; +export const V2ThreadMetadataUpdateResponse__CollabAgentToolCallStatus = Schema.Literals([ + "inProgress", + "completed", + "failed", +]); + +export type V2ThreadMetadataUpdateResponse__CommandExecutionSource = + | "agent" + | "userShell" + | "unifiedExecStartup" + | "unifiedExecInteraction"; +export const V2ThreadMetadataUpdateResponse__CommandExecutionSource = Schema.Literals([ + "agent", + "userShell", + "unifiedExecStartup", + "unifiedExecInteraction", +]); + +export type V2ThreadMetadataUpdateResponse__SessionSource = + | "cli" + | "vscode" + | "exec" + | "appServer" + | "unknown" + | { readonly custom: string } + | { readonly subAgent: V2ThreadMetadataUpdateResponse__SubAgentSource }; +export const V2ThreadMetadataUpdateResponse__SessionSource = Schema.Union( + [ + Schema.Literals(["cli", "vscode", "exec", "appServer", "unknown"]), + Schema.Struct({ custom: Schema.String }).annotate({ title: "CustomSessionSource" }), + Schema.Struct({ subAgent: V2ThreadMetadataUpdateResponse__SubAgentSource }).annotate({ + title: "SubAgentSessionSource", + }), + ], + { mode: "oneOf" }, +); + +export type V2ThreadMetadataUpdateResponse__ThreadStatus = + | { readonly type: "notLoaded" } + | { readonly type: "idle" } + | { readonly type: "systemError" } + | { + readonly activeFlags: ReadonlyArray; + readonly type: "active"; + }; +export const V2ThreadMetadataUpdateResponse__ThreadStatus = Schema.Union( + [ + Schema.Struct({ + type: Schema.Literal("notLoaded").annotate({ title: "NotLoadedThreadStatusType" }), + }).annotate({ title: "NotLoadedThreadStatus" }), + Schema.Struct({ + type: Schema.Literal("idle").annotate({ title: "IdleThreadStatusType" }), + }).annotate({ title: "IdleThreadStatus" }), + Schema.Struct({ + type: Schema.Literal("systemError").annotate({ title: "SystemErrorThreadStatusType" }), + }).annotate({ title: "SystemErrorThreadStatus" }), + Schema.Struct({ + activeFlags: Schema.Array(V2ThreadMetadataUpdateResponse__ThreadActiveFlag), + type: Schema.Literal("active").annotate({ title: "ActiveThreadStatusType" }), + }).annotate({ title: "ActiveThreadStatus" }), + ], + { mode: "oneOf" }, +); + +export type V2ThreadNameUpdatedNotification = { + readonly threadId: string; + readonly threadName?: string | null; +}; +export const V2ThreadNameUpdatedNotification = Schema.Struct({ + threadId: Schema.String, + threadName: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), +}).annotate({ title: "ThreadNameUpdatedNotification" }); + +export type V2ThreadReadParams = { readonly includeTurns?: boolean; readonly threadId: string }; +export const V2ThreadReadParams = Schema.Struct({ + includeTurns: Schema.optionalKey( + Schema.Boolean.annotate({ + description: "When true, include turns and their items from rollout history.", + default: false, + }), + ), + threadId: Schema.String, +}).annotate({ title: "ThreadReadParams" }); + +export type V2ThreadReadResponse = { readonly thread: V2ThreadReadResponse__Thread }; +export const V2ThreadReadResponse = Schema.Struct({ + thread: V2ThreadReadResponse__Thread, +}).annotate({ title: "ThreadReadResponse" }); + +export type V2ThreadReadResponse__ByteRange = { readonly end: number; readonly start: number }; +export const V2ThreadReadResponse__ByteRange = Schema.Struct({ + end: Schema.Number.annotate({ format: "uint" }) + .check(Schema.isInt()) + .check(Schema.isGreaterThanOrEqualTo(0)), + start: Schema.Number.annotate({ format: "uint" }) + .check(Schema.isInt()) + .check(Schema.isGreaterThanOrEqualTo(0)), +}); + +export type V2ThreadReadResponse__CollabAgentTool = + | "spawnAgent" + | "sendInput" + | "resumeAgent" + | "wait" + | "closeAgent"; +export const V2ThreadReadResponse__CollabAgentTool = Schema.Literals([ + "spawnAgent", + "sendInput", + "resumeAgent", + "wait", + "closeAgent", +]); + +export type V2ThreadReadResponse__CollabAgentToolCallStatus = "inProgress" | "completed" | "failed"; +export const V2ThreadReadResponse__CollabAgentToolCallStatus = Schema.Literals([ + "inProgress", + "completed", + "failed", +]); + +export type V2ThreadReadResponse__CommandExecutionSource = + | "agent" + | "userShell" + | "unifiedExecStartup" + | "unifiedExecInteraction"; +export const V2ThreadReadResponse__CommandExecutionSource = Schema.Literals([ + "agent", + "userShell", + "unifiedExecStartup", + "unifiedExecInteraction", +]); + +export type V2ThreadReadResponse__SessionSource = + | "cli" + | "vscode" + | "exec" + | "appServer" + | "unknown" + | { readonly custom: string } + | { readonly subAgent: V2ThreadReadResponse__SubAgentSource }; +export const V2ThreadReadResponse__SessionSource = Schema.Union( + [ + Schema.Literals(["cli", "vscode", "exec", "appServer", "unknown"]), + Schema.Struct({ custom: Schema.String }).annotate({ title: "CustomSessionSource" }), + Schema.Struct({ subAgent: V2ThreadReadResponse__SubAgentSource }).annotate({ + title: "SubAgentSessionSource", + }), + ], + { mode: "oneOf" }, +); + +export type V2ThreadReadResponse__ThreadStatus = + | { readonly type: "notLoaded" } + | { readonly type: "idle" } + | { readonly type: "systemError" } + | { + readonly activeFlags: ReadonlyArray; + readonly type: "active"; + }; +export const V2ThreadReadResponse__ThreadStatus = Schema.Union( + [ + Schema.Struct({ + type: Schema.Literal("notLoaded").annotate({ title: "NotLoadedThreadStatusType" }), + }).annotate({ title: "NotLoadedThreadStatus" }), + Schema.Struct({ + type: Schema.Literal("idle").annotate({ title: "IdleThreadStatusType" }), + }).annotate({ title: "IdleThreadStatus" }), + Schema.Struct({ + type: Schema.Literal("systemError").annotate({ title: "SystemErrorThreadStatusType" }), + }).annotate({ title: "SystemErrorThreadStatus" }), + Schema.Struct({ + activeFlags: Schema.Array(V2ThreadReadResponse__ThreadActiveFlag), + type: Schema.Literal("active").annotate({ title: "ActiveThreadStatusType" }), + }).annotate({ title: "ActiveThreadStatus" }), + ], + { mode: "oneOf" }, +); + +export type V2ThreadRealtimeClosedNotification = { + readonly reason?: string | null; + readonly threadId: string; +}; +export const V2ThreadRealtimeClosedNotification = Schema.Struct({ + reason: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + threadId: Schema.String, +}).annotate({ + title: "ThreadRealtimeClosedNotification", + description: "EXPERIMENTAL - emitted when thread realtime transport closes.", +}); + +export type V2ThreadRealtimeErrorNotification = { + readonly message: string; + readonly threadId: string; +}; +export const V2ThreadRealtimeErrorNotification = Schema.Struct({ + message: Schema.String, + threadId: Schema.String, +}).annotate({ + title: "ThreadRealtimeErrorNotification", + description: "EXPERIMENTAL - emitted when thread realtime encounters an error.", +}); + +export type V2ThreadRealtimeItemAddedNotification = { + readonly item: unknown; + readonly threadId: string; +}; +export const V2ThreadRealtimeItemAddedNotification = Schema.Struct({ + item: Schema.Unknown, + threadId: Schema.String, +}).annotate({ + title: "ThreadRealtimeItemAddedNotification", + description: "EXPERIMENTAL - raw non-audio thread realtime item emitted by the backend.", +}); + +export type V2ThreadRealtimeOutputAudioDeltaNotification = { + readonly audio: V2ThreadRealtimeOutputAudioDeltaNotification__ThreadRealtimeAudioChunk; + readonly threadId: string; +}; +export const V2ThreadRealtimeOutputAudioDeltaNotification = Schema.Struct({ + audio: V2ThreadRealtimeOutputAudioDeltaNotification__ThreadRealtimeAudioChunk, + threadId: Schema.String, +}).annotate({ + title: "ThreadRealtimeOutputAudioDeltaNotification", + description: "EXPERIMENTAL - streamed output audio emitted by thread realtime.", +}); + +export type V2ThreadRealtimeSdpNotification = { readonly sdp: string; readonly threadId: string }; +export const V2ThreadRealtimeSdpNotification = Schema.Struct({ + sdp: Schema.String, + threadId: Schema.String, +}).annotate({ + title: "ThreadRealtimeSdpNotification", + description: "EXPERIMENTAL - emitted with the remote SDP for a WebRTC realtime session.", +}); + +export type V2ThreadRealtimeStartedNotification = { + readonly sessionId?: string | null; + readonly threadId: string; + readonly version: V2ThreadRealtimeStartedNotification__RealtimeConversationVersion; +}; +export const V2ThreadRealtimeStartedNotification = Schema.Struct({ + sessionId: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + threadId: Schema.String, + version: V2ThreadRealtimeStartedNotification__RealtimeConversationVersion, +}).annotate({ + title: "ThreadRealtimeStartedNotification", + description: "EXPERIMENTAL - emitted when thread realtime startup is accepted.", +}); + +export type V2ThreadRealtimeTranscriptUpdatedNotification = { + readonly role: string; + readonly text: string; + readonly threadId: string; +}; +export const V2ThreadRealtimeTranscriptUpdatedNotification = Schema.Struct({ + role: Schema.String, + text: Schema.String, + threadId: Schema.String, +}).annotate({ + title: "ThreadRealtimeTranscriptUpdatedNotification", + description: + "EXPERIMENTAL - flat transcript delta emitted whenever realtime transcript text changes.", +}); + +export type V2ThreadResumeParams = { + readonly approvalPolicy?: V2ThreadResumeParams__AskForApproval | null; + readonly approvalsReviewer?: V2ThreadResumeParams__ApprovalsReviewer | null; + readonly baseInstructions?: string | null; + readonly config?: { readonly [x: string]: unknown } | null; + readonly cwd?: string | null; + readonly developerInstructions?: string | null; + readonly model?: string | null; + readonly modelProvider?: string | null; + readonly personality?: V2ThreadResumeParams__Personality | null; + readonly sandbox?: V2ThreadResumeParams__SandboxMode | null; + readonly serviceTier?: V2ThreadResumeParams__ServiceTier | null | null; + readonly threadId: string; +}; +export const V2ThreadResumeParams = Schema.Struct({ + approvalPolicy: Schema.optionalKey( + Schema.Union([V2ThreadResumeParams__AskForApproval, Schema.Null]), + ), + approvalsReviewer: Schema.optionalKey( + Schema.Union([V2ThreadResumeParams__ApprovalsReviewer, Schema.Null]).annotate({ + description: + "Override where approval requests are routed for review on this thread and subsequent turns.", + }), + ), + baseInstructions: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + config: Schema.optionalKey( + Schema.Union([Schema.Record(Schema.String, Schema.Unknown), Schema.Null]), + ), + cwd: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + developerInstructions: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + model: Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + description: "Configuration overrides for the resumed thread, if any.", + }), + Schema.Null, + ]), + ), + modelProvider: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + personality: Schema.optionalKey(Schema.Union([V2ThreadResumeParams__Personality, Schema.Null])), + sandbox: Schema.optionalKey(Schema.Union([V2ThreadResumeParams__SandboxMode, Schema.Null])), + serviceTier: Schema.optionalKey( + Schema.Union([Schema.Union([V2ThreadResumeParams__ServiceTier, Schema.Null]), Schema.Null]), + ), + threadId: Schema.String, +}).annotate({ + title: "ThreadResumeParams", + description: + "There are three ways to resume a thread: 1. By thread_id: load the thread from disk by thread_id and resume it. 2. By history: instantiate the thread from memory and resume it. 3. By path: load the thread from disk by path and resume it.\n\nThe precedence is: history > path > thread_id. If using history or path, the thread_id param will be ignored.\n\nPrefer using thread_id whenever possible.", +}); + +export type V2ThreadResumeParams__ResponseItem = + | { + readonly content: ReadonlyArray; + readonly end_turn?: boolean | null; + readonly id?: string | null; + readonly phase?: V2ThreadResumeParams__MessagePhase | null; + readonly role: string; + readonly type: "message"; + } + | { + readonly content?: ReadonlyArray | null; + readonly encrypted_content?: string | null; + readonly summary: ReadonlyArray; + readonly type: "reasoning"; + } + | { + readonly action: V2ThreadResumeParams__LocalShellAction; + readonly call_id?: string | null; + readonly id?: string | null; + readonly status: V2ThreadResumeParams__LocalShellStatus; + readonly type: "local_shell_call"; + } + | { + readonly arguments: string; + readonly call_id: string; + readonly id?: string | null; + readonly name: string; + readonly namespace?: string | null; + readonly type: "function_call"; + } + | { + readonly arguments: unknown; + readonly call_id?: string | null; + readonly execution: string; + readonly id?: string | null; + readonly status?: string | null; + readonly type: "tool_search_call"; + } + | { + readonly call_id: string; + readonly output: V2ThreadResumeParams__FunctionCallOutputBody; + readonly type: "function_call_output"; + } + | { + readonly call_id: string; + readonly id?: string | null; + readonly input: string; + readonly name: string; + readonly status?: string | null; + readonly type: "custom_tool_call"; + } + | { + readonly call_id: string; + readonly name?: string | null; + readonly output: V2ThreadResumeParams__FunctionCallOutputBody; + readonly type: "custom_tool_call_output"; + } + | { + readonly call_id?: string | null; + readonly execution: string; + readonly status: string; + readonly tools: ReadonlyArray; + readonly type: "tool_search_output"; + } + | { + readonly action?: V2ThreadResumeParams__ResponsesApiWebSearchAction | null; + readonly id?: string | null; + readonly status?: string | null; + readonly type: "web_search_call"; + } + | { + readonly id: string; + readonly result: string; + readonly revised_prompt?: string | null; + readonly status: string; + readonly type: "image_generation_call"; + } + | { readonly ghost_commit: V2ThreadResumeParams__GhostCommit; readonly type: "ghost_snapshot" } + | { readonly encrypted_content: string; readonly type: "compaction" } + | { readonly type: "other" }; +export const V2ThreadResumeParams__ResponseItem = Schema.Union( + [ + Schema.Struct({ + content: Schema.Array(V2ThreadResumeParams__ContentItem), + end_turn: Schema.optionalKey(Schema.Union([Schema.Boolean, Schema.Null])), + id: Schema.optionalKey( + Schema.Union([Schema.String.annotate({ writeOnly: true }), Schema.Null]), + ), + phase: Schema.optionalKey(Schema.Union([V2ThreadResumeParams__MessagePhase, Schema.Null])), + role: Schema.String, + type: Schema.Literal("message").annotate({ title: "MessageResponseItemType" }), + }).annotate({ title: "MessageResponseItem" }), + Schema.Struct({ + content: Schema.optionalKey( + Schema.Union([Schema.Array(V2ThreadResumeParams__ReasoningItemContent), Schema.Null]), + ), + encrypted_content: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + summary: Schema.Array(V2ThreadResumeParams__ReasoningItemReasoningSummary), + type: Schema.Literal("reasoning").annotate({ title: "ReasoningResponseItemType" }), + }).annotate({ title: "ReasoningResponseItem" }), + Schema.Struct({ + action: V2ThreadResumeParams__LocalShellAction, + call_id: Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ description: "Set when using the Responses API." }), + Schema.Null, + ]), + ), + id: Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + description: "Legacy id field retained for compatibility with older payloads.", + writeOnly: true, + }), + Schema.Null, + ]), + ), + status: V2ThreadResumeParams__LocalShellStatus, + type: Schema.Literal("local_shell_call").annotate({ + title: "LocalShellCallResponseItemType", + }), + }).annotate({ title: "LocalShellCallResponseItem" }), + Schema.Struct({ + arguments: Schema.String, + call_id: Schema.String, + id: Schema.optionalKey( + Schema.Union([Schema.String.annotate({ writeOnly: true }), Schema.Null]), + ), + name: Schema.String, + namespace: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + type: Schema.Literal("function_call").annotate({ title: "FunctionCallResponseItemType" }), + }).annotate({ title: "FunctionCallResponseItem" }), + Schema.Struct({ + arguments: Schema.Unknown, + call_id: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + execution: Schema.String, + id: Schema.optionalKey( + Schema.Union([Schema.String.annotate({ writeOnly: true }), Schema.Null]), + ), + status: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + type: Schema.Literal("tool_search_call").annotate({ + title: "ToolSearchCallResponseItemType", + }), + }).annotate({ title: "ToolSearchCallResponseItem" }), + Schema.Struct({ + call_id: Schema.String, + output: V2ThreadResumeParams__FunctionCallOutputBody, + type: Schema.Literal("function_call_output").annotate({ + title: "FunctionCallOutputResponseItemType", + }), + }).annotate({ title: "FunctionCallOutputResponseItem" }), + Schema.Struct({ + call_id: Schema.String, + id: Schema.optionalKey( + Schema.Union([Schema.String.annotate({ writeOnly: true }), Schema.Null]), + ), + input: Schema.String, + name: Schema.String, + status: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + type: Schema.Literal("custom_tool_call").annotate({ + title: "CustomToolCallResponseItemType", + }), + }).annotate({ title: "CustomToolCallResponseItem" }), + Schema.Struct({ + call_id: Schema.String, + name: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + output: V2ThreadResumeParams__FunctionCallOutputBody, + type: Schema.Literal("custom_tool_call_output").annotate({ + title: "CustomToolCallOutputResponseItemType", + }), + }).annotate({ title: "CustomToolCallOutputResponseItem" }), + Schema.Struct({ + call_id: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + execution: Schema.String, + status: Schema.String, + tools: Schema.Array(Schema.Unknown), + type: Schema.Literal("tool_search_output").annotate({ + title: "ToolSearchOutputResponseItemType", + }), + }).annotate({ title: "ToolSearchOutputResponseItem" }), + Schema.Struct({ + action: Schema.optionalKey( + Schema.Union([V2ThreadResumeParams__ResponsesApiWebSearchAction, Schema.Null]), + ), + id: Schema.optionalKey( + Schema.Union([Schema.String.annotate({ writeOnly: true }), Schema.Null]), + ), + status: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + type: Schema.Literal("web_search_call").annotate({ title: "WebSearchCallResponseItemType" }), + }).annotate({ title: "WebSearchCallResponseItem" }), + Schema.Struct({ + id: Schema.String, + result: Schema.String, + revised_prompt: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + status: Schema.String, + type: Schema.Literal("image_generation_call").annotate({ + title: "ImageGenerationCallResponseItemType", + }), + }).annotate({ title: "ImageGenerationCallResponseItem" }), + Schema.Struct({ + ghost_commit: V2ThreadResumeParams__GhostCommit, + type: Schema.Literal("ghost_snapshot").annotate({ title: "GhostSnapshotResponseItemType" }), + }).annotate({ title: "GhostSnapshotResponseItem" }), + Schema.Struct({ + encrypted_content: Schema.String, + type: Schema.Literal("compaction").annotate({ title: "CompactionResponseItemType" }), + }).annotate({ title: "CompactionResponseItem" }), + Schema.Struct({ + type: Schema.Literal("other").annotate({ title: "OtherResponseItemType" }), + }).annotate({ title: "OtherResponseItem" }), + ], + { mode: "oneOf" }, +); + +export type V2ThreadResumeResponse = { + readonly approvalPolicy: V2ThreadResumeResponse__AskForApproval; + readonly approvalsReviewer: "user" | "guardian_subagent"; + readonly cwd: string; + readonly model: string; + readonly modelProvider: string; + readonly reasoningEffort?: V2ThreadResumeResponse__ReasoningEffort | null; + readonly sandbox: V2ThreadResumeResponse__SandboxPolicy; + readonly serviceTier?: V2ThreadResumeResponse__ServiceTier | null; + readonly thread: V2ThreadResumeResponse__Thread; +}; +export const V2ThreadResumeResponse = Schema.Struct({ + approvalPolicy: V2ThreadResumeResponse__AskForApproval, + approvalsReviewer: Schema.Literals(["user", "guardian_subagent"]).annotate({ + description: + "Configures who approval requests are routed to for review. Examples include sandbox escapes, blocked network access, MCP approval prompts, and ARC escalations. Defaults to `user`. `guardian_subagent` uses a carefully prompted subagent to gather relevant context and apply a risk-based decision framework before approving or denying the request.", + }), + cwd: Schema.String, + model: Schema.String, + modelProvider: Schema.String, + reasoningEffort: Schema.optionalKey( + Schema.Union([V2ThreadResumeResponse__ReasoningEffort, Schema.Null]), + ), + sandbox: V2ThreadResumeResponse__SandboxPolicy, + serviceTier: Schema.optionalKey(Schema.Union([V2ThreadResumeResponse__ServiceTier, Schema.Null])), + thread: V2ThreadResumeResponse__Thread, +}).annotate({ title: "ThreadResumeResponse" }); + +export type V2ThreadResumeResponse__ApprovalsReviewer = "user" | "guardian_subagent"; +export const V2ThreadResumeResponse__ApprovalsReviewer = Schema.Literals([ + "user", + "guardian_subagent", +]).annotate({ + description: + "Configures who approval requests are routed to for review. Examples include sandbox escapes, blocked network access, MCP approval prompts, and ARC escalations. Defaults to `user`. `guardian_subagent` uses a carefully prompted subagent to gather relevant context and apply a risk-based decision framework before approving or denying the request.", +}); + +export type V2ThreadResumeResponse__ByteRange = { readonly end: number; readonly start: number }; +export const V2ThreadResumeResponse__ByteRange = Schema.Struct({ + end: Schema.Number.annotate({ format: "uint" }) + .check(Schema.isInt()) + .check(Schema.isGreaterThanOrEqualTo(0)), + start: Schema.Number.annotate({ format: "uint" }) + .check(Schema.isInt()) + .check(Schema.isGreaterThanOrEqualTo(0)), +}); + +export type V2ThreadResumeResponse__CollabAgentTool = + | "spawnAgent" + | "sendInput" + | "resumeAgent" + | "wait" + | "closeAgent"; +export const V2ThreadResumeResponse__CollabAgentTool = Schema.Literals([ + "spawnAgent", + "sendInput", + "resumeAgent", + "wait", + "closeAgent", +]); + +export type V2ThreadResumeResponse__CollabAgentToolCallStatus = + | "inProgress" + | "completed" + | "failed"; +export const V2ThreadResumeResponse__CollabAgentToolCallStatus = Schema.Literals([ + "inProgress", + "completed", + "failed", +]); + +export type V2ThreadResumeResponse__CommandExecutionSource = + | "agent" + | "userShell" + | "unifiedExecStartup" + | "unifiedExecInteraction"; +export const V2ThreadResumeResponse__CommandExecutionSource = Schema.Literals([ + "agent", + "userShell", + "unifiedExecStartup", + "unifiedExecInteraction", +]); + +export type V2ThreadResumeResponse__NetworkAccess = "restricted" | "enabled"; +export const V2ThreadResumeResponse__NetworkAccess = Schema.Literals(["restricted", "enabled"]); + +export type V2ThreadResumeResponse__ReadOnlyAccess = + | { + readonly includePlatformDefaults?: boolean; + readonly readableRoots?: ReadonlyArray; + readonly type: "restricted"; + } + | { readonly type: "fullAccess" }; +export const V2ThreadResumeResponse__ReadOnlyAccess = Schema.Union( + [ + Schema.Struct({ + includePlatformDefaults: Schema.optionalKey(Schema.Boolean.annotate({ default: true })), + readableRoots: Schema.optionalKey( + Schema.Array(V2ThreadResumeResponse__AbsolutePathBuf).annotate({ default: [] }), + ), + type: Schema.Literal("restricted").annotate({ title: "RestrictedReadOnlyAccessType" }), + }).annotate({ title: "RestrictedReadOnlyAccess" }), + Schema.Struct({ + type: Schema.Literal("fullAccess").annotate({ title: "FullAccessReadOnlyAccessType" }), + }).annotate({ title: "FullAccessReadOnlyAccess" }), + ], + { mode: "oneOf" }, +); + +export type V2ThreadResumeResponse__SessionSource = + | "cli" + | "vscode" + | "exec" + | "appServer" + | "unknown" + | { readonly custom: string } + | { readonly subAgent: V2ThreadResumeResponse__SubAgentSource }; +export const V2ThreadResumeResponse__SessionSource = Schema.Union( + [ + Schema.Literals(["cli", "vscode", "exec", "appServer", "unknown"]), + Schema.Struct({ custom: Schema.String }).annotate({ title: "CustomSessionSource" }), + Schema.Struct({ subAgent: V2ThreadResumeResponse__SubAgentSource }).annotate({ + title: "SubAgentSessionSource", + }), + ], + { mode: "oneOf" }, +); + +export type V2ThreadResumeResponse__ThreadStatus = + | { readonly type: "notLoaded" } + | { readonly type: "idle" } + | { readonly type: "systemError" } + | { + readonly activeFlags: ReadonlyArray; + readonly type: "active"; + }; +export const V2ThreadResumeResponse__ThreadStatus = Schema.Union( + [ + Schema.Struct({ + type: Schema.Literal("notLoaded").annotate({ title: "NotLoadedThreadStatusType" }), + }).annotate({ title: "NotLoadedThreadStatus" }), + Schema.Struct({ + type: Schema.Literal("idle").annotate({ title: "IdleThreadStatusType" }), + }).annotate({ title: "IdleThreadStatus" }), + Schema.Struct({ + type: Schema.Literal("systemError").annotate({ title: "SystemErrorThreadStatusType" }), + }).annotate({ title: "SystemErrorThreadStatus" }), + Schema.Struct({ + activeFlags: Schema.Array(V2ThreadResumeResponse__ThreadActiveFlag), + type: Schema.Literal("active").annotate({ title: "ActiveThreadStatusType" }), + }).annotate({ title: "ActiveThreadStatus" }), + ], + { mode: "oneOf" }, +); + +export type V2ThreadRollbackParams = { readonly numTurns: number; readonly threadId: string }; +export const V2ThreadRollbackParams = Schema.Struct({ + numTurns: Schema.Number.annotate({ + description: + "The number of turns to drop from the end of the thread. Must be >= 1.\n\nThis only modifies the thread's history and does not revert local file changes that have been made by the agent. Clients are responsible for reverting these changes.", + format: "uint32", + }) + .check(Schema.isInt()) + .check(Schema.isGreaterThanOrEqualTo(0)), + threadId: Schema.String, +}).annotate({ title: "ThreadRollbackParams" }); + +export type V2ThreadRollbackResponse = { + readonly thread: { + readonly agentNickname?: string | null; + readonly agentRole?: string | null; + readonly cliVersion: string; + readonly createdAt: number; + readonly cwd: string; + readonly ephemeral: boolean; + readonly forkedFromId?: string | null; + readonly gitInfo?: V2ThreadRollbackResponse__GitInfo | null; + readonly id: string; + readonly modelProvider: string; + readonly name?: string | null; + readonly path?: string | null; + readonly preview: string; + readonly source: + | "cli" + | "vscode" + | "exec" + | "appServer" + | "unknown" + | { readonly custom: string } + | { readonly subAgent: V2ThreadRollbackResponse__SubAgentSource }; + readonly status: + | { readonly type: "notLoaded" } + | { readonly type: "idle" } + | { readonly type: "systemError" } + | { + readonly activeFlags: ReadonlyArray; + readonly type: "active"; + }; + readonly turns: ReadonlyArray; + readonly updatedAt: number; + }; +}; +export const V2ThreadRollbackResponse = Schema.Struct({ + thread: Schema.Struct({ + agentNickname: Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + description: + "Optional random unique nickname assigned to an AgentControl-spawned sub-agent.", + }), + Schema.Null, + ]), + ), + agentRole: Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + description: "Optional role (agent_role) assigned to an AgentControl-spawned sub-agent.", + }), + Schema.Null, + ]), + ), + cliVersion: Schema.String.annotate({ + description: "Version of the CLI that created the thread.", + }), + createdAt: Schema.Number.annotate({ + description: "Unix timestamp (in seconds) when the thread was created.", + format: "int64", + }).check(Schema.isInt()), + cwd: Schema.String.annotate({ description: "Working directory captured for the thread." }), + ephemeral: Schema.Boolean.annotate({ + description: "Whether the thread is ephemeral and should not be materialized on disk.", + }), + forkedFromId: Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + description: "Source thread id when this thread was created by forking another thread.", + }), + Schema.Null, + ]), + ), + gitInfo: Schema.optionalKey( + Schema.Union([V2ThreadRollbackResponse__GitInfo, Schema.Null]).annotate({ + description: "Optional Git metadata captured when the thread was created.", + }), + ), + id: Schema.String, + modelProvider: Schema.String.annotate({ + description: "Model provider used for this thread (for example, 'openai').", + }), + name: Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ description: "Optional user-facing thread title." }), + Schema.Null, + ]), + ), + path: Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ description: "[UNSTABLE] Path to the thread on disk." }), + Schema.Null, + ]), + ), + preview: Schema.String.annotate({ + description: "Usually the first user message in the thread, if available.", + }), + source: Schema.Union( + [ + Schema.Literals(["cli", "vscode", "exec", "appServer", "unknown"]), + Schema.Struct({ custom: Schema.String }).annotate({ title: "CustomSessionSource" }), + Schema.Struct({ subAgent: V2ThreadRollbackResponse__SubAgentSource }).annotate({ + title: "SubAgentSessionSource", + }), + ], + { mode: "oneOf" }, + ).annotate({ + description: "Origin of the thread (CLI, VSCode, codex exec, codex app-server, etc.).", + }), + status: Schema.Union( + [ + Schema.Struct({ + type: Schema.Literal("notLoaded").annotate({ title: "NotLoadedThreadStatusType" }), + }).annotate({ title: "NotLoadedThreadStatus" }), + Schema.Struct({ + type: Schema.Literal("idle").annotate({ title: "IdleThreadStatusType" }), + }).annotate({ title: "IdleThreadStatus" }), + Schema.Struct({ + type: Schema.Literal("systemError").annotate({ title: "SystemErrorThreadStatusType" }), + }).annotate({ title: "SystemErrorThreadStatus" }), + Schema.Struct({ + activeFlags: Schema.Array(V2ThreadRollbackResponse__ThreadActiveFlag), + type: Schema.Literal("active").annotate({ title: "ActiveThreadStatusType" }), + }).annotate({ title: "ActiveThreadStatus" }), + ], + { mode: "oneOf" }, + ).annotate({ description: "Current runtime status for the thread." }), + turns: Schema.Array(V2ThreadRollbackResponse__Turn).annotate({ + description: + "Only populated on `thread/resume`, `thread/rollback`, `thread/fork`, and `thread/read` (when `includeTurns` is true) responses. For all other responses and notifications returning a Thread, the turns field will be an empty list.", + }), + updatedAt: Schema.Number.annotate({ + description: "Unix timestamp (in seconds) when the thread was last updated.", + format: "int64", + }).check(Schema.isInt()), + }).annotate({ + description: + "The updated thread after applying the rollback, with `turns` populated.\n\nThe ThreadItems stored in each Turn are lossy since we explicitly do not persist all agent interactions, such as command executions. This is the same behavior as `thread/resume`.", + }), +}).annotate({ title: "ThreadRollbackResponse" }); + +export type V2ThreadRollbackResponse__ByteRange = { readonly end: number; readonly start: number }; +export const V2ThreadRollbackResponse__ByteRange = Schema.Struct({ + end: Schema.Number.annotate({ format: "uint" }) + .check(Schema.isInt()) + .check(Schema.isGreaterThanOrEqualTo(0)), + start: Schema.Number.annotate({ format: "uint" }) + .check(Schema.isInt()) + .check(Schema.isGreaterThanOrEqualTo(0)), +}); + +export type V2ThreadRollbackResponse__CollabAgentTool = + | "spawnAgent" + | "sendInput" + | "resumeAgent" + | "wait" + | "closeAgent"; +export const V2ThreadRollbackResponse__CollabAgentTool = Schema.Literals([ + "spawnAgent", + "sendInput", + "resumeAgent", + "wait", + "closeAgent", +]); + +export type V2ThreadRollbackResponse__CollabAgentToolCallStatus = + | "inProgress" + | "completed" + | "failed"; +export const V2ThreadRollbackResponse__CollabAgentToolCallStatus = Schema.Literals([ + "inProgress", + "completed", + "failed", +]); + +export type V2ThreadRollbackResponse__CommandExecutionSource = + | "agent" + | "userShell" + | "unifiedExecStartup" + | "unifiedExecInteraction"; +export const V2ThreadRollbackResponse__CommandExecutionSource = Schema.Literals([ + "agent", + "userShell", + "unifiedExecStartup", + "unifiedExecInteraction", +]); + +export type V2ThreadRollbackResponse__SessionSource = + | "cli" + | "vscode" + | "exec" + | "appServer" + | "unknown" + | { readonly custom: string } + | { readonly subAgent: V2ThreadRollbackResponse__SubAgentSource }; +export const V2ThreadRollbackResponse__SessionSource = Schema.Union( + [ + Schema.Literals(["cli", "vscode", "exec", "appServer", "unknown"]), + Schema.Struct({ custom: Schema.String }).annotate({ title: "CustomSessionSource" }), + Schema.Struct({ subAgent: V2ThreadRollbackResponse__SubAgentSource }).annotate({ + title: "SubAgentSessionSource", + }), + ], + { mode: "oneOf" }, +); + +export type V2ThreadRollbackResponse__Thread = { + readonly agentNickname?: string | null; + readonly agentRole?: string | null; + readonly cliVersion: string; + readonly createdAt: number; + readonly cwd: string; + readonly ephemeral: boolean; + readonly forkedFromId?: string | null; + readonly gitInfo?: V2ThreadRollbackResponse__GitInfo | null; + readonly id: string; + readonly modelProvider: string; + readonly name?: string | null; + readonly path?: string | null; + readonly preview: string; + readonly source: + | "cli" + | "vscode" + | "exec" + | "appServer" + | "unknown" + | { readonly custom: string } + | { readonly subAgent: V2ThreadRollbackResponse__SubAgentSource }; + readonly status: + | { readonly type: "notLoaded" } + | { readonly type: "idle" } + | { readonly type: "systemError" } + | { + readonly activeFlags: ReadonlyArray; + readonly type: "active"; + }; + readonly turns: ReadonlyArray; + readonly updatedAt: number; +}; +export const V2ThreadRollbackResponse__Thread = Schema.Struct({ + agentNickname: Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + description: + "Optional random unique nickname assigned to an AgentControl-spawned sub-agent.", + }), + Schema.Null, + ]), + ), + agentRole: Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + description: "Optional role (agent_role) assigned to an AgentControl-spawned sub-agent.", + }), + Schema.Null, + ]), + ), + cliVersion: Schema.String.annotate({ + description: "Version of the CLI that created the thread.", + }), + createdAt: Schema.Number.annotate({ + description: "Unix timestamp (in seconds) when the thread was created.", + format: "int64", + }).check(Schema.isInt()), + cwd: Schema.String.annotate({ description: "Working directory captured for the thread." }), + ephemeral: Schema.Boolean.annotate({ + description: "Whether the thread is ephemeral and should not be materialized on disk.", + }), + forkedFromId: Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + description: "Source thread id when this thread was created by forking another thread.", + }), + Schema.Null, + ]), + ), + gitInfo: Schema.optionalKey( + Schema.Union([V2ThreadRollbackResponse__GitInfo, Schema.Null]).annotate({ + description: "Optional Git metadata captured when the thread was created.", + }), + ), + id: Schema.String, + modelProvider: Schema.String.annotate({ + description: "Model provider used for this thread (for example, 'openai').", + }), + name: Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ description: "Optional user-facing thread title." }), + Schema.Null, + ]), + ), + path: Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ description: "[UNSTABLE] Path to the thread on disk." }), + Schema.Null, + ]), + ), + preview: Schema.String.annotate({ + description: "Usually the first user message in the thread, if available.", + }), + source: Schema.Union( + [ + Schema.Literals(["cli", "vscode", "exec", "appServer", "unknown"]), + Schema.Struct({ custom: Schema.String }).annotate({ title: "CustomSessionSource" }), + Schema.Struct({ subAgent: V2ThreadRollbackResponse__SubAgentSource }).annotate({ + title: "SubAgentSessionSource", + }), + ], + { mode: "oneOf" }, + ).annotate({ + description: "Origin of the thread (CLI, VSCode, codex exec, codex app-server, etc.).", + }), + status: Schema.Union( + [ + Schema.Struct({ + type: Schema.Literal("notLoaded").annotate({ title: "NotLoadedThreadStatusType" }), + }).annotate({ title: "NotLoadedThreadStatus" }), + Schema.Struct({ + type: Schema.Literal("idle").annotate({ title: "IdleThreadStatusType" }), + }).annotate({ title: "IdleThreadStatus" }), + Schema.Struct({ + type: Schema.Literal("systemError").annotate({ title: "SystemErrorThreadStatusType" }), + }).annotate({ title: "SystemErrorThreadStatus" }), + Schema.Struct({ + activeFlags: Schema.Array(V2ThreadRollbackResponse__ThreadActiveFlag), + type: Schema.Literal("active").annotate({ title: "ActiveThreadStatusType" }), + }).annotate({ title: "ActiveThreadStatus" }), + ], + { mode: "oneOf" }, + ).annotate({ description: "Current runtime status for the thread." }), + turns: Schema.Array(V2ThreadRollbackResponse__Turn).annotate({ + description: + "Only populated on `thread/resume`, `thread/rollback`, `thread/fork`, and `thread/read` (when `includeTurns` is true) responses. For all other responses and notifications returning a Thread, the turns field will be an empty list.", + }), + updatedAt: Schema.Number.annotate({ + description: "Unix timestamp (in seconds) when the thread was last updated.", + format: "int64", + }).check(Schema.isInt()), +}); + +export type V2ThreadRollbackResponse__ThreadStatus = + | { readonly type: "notLoaded" } + | { readonly type: "idle" } + | { readonly type: "systemError" } + | { + readonly activeFlags: ReadonlyArray; + readonly type: "active"; + }; +export const V2ThreadRollbackResponse__ThreadStatus = Schema.Union( + [ + Schema.Struct({ + type: Schema.Literal("notLoaded").annotate({ title: "NotLoadedThreadStatusType" }), + }).annotate({ title: "NotLoadedThreadStatus" }), + Schema.Struct({ + type: Schema.Literal("idle").annotate({ title: "IdleThreadStatusType" }), + }).annotate({ title: "IdleThreadStatus" }), + Schema.Struct({ + type: Schema.Literal("systemError").annotate({ title: "SystemErrorThreadStatusType" }), + }).annotate({ title: "SystemErrorThreadStatus" }), + Schema.Struct({ + activeFlags: Schema.Array(V2ThreadRollbackResponse__ThreadActiveFlag), + type: Schema.Literal("active").annotate({ title: "ActiveThreadStatusType" }), + }).annotate({ title: "ActiveThreadStatus" }), + ], + { mode: "oneOf" }, +); + +export type V2ThreadSetNameParams = { readonly name: string; readonly threadId: string }; +export const V2ThreadSetNameParams = Schema.Struct({ + name: Schema.String, + threadId: Schema.String, +}).annotate({ title: "ThreadSetNameParams" }); + +export type V2ThreadSetNameResponse = {}; +export const V2ThreadSetNameResponse = Schema.Struct({}).annotate({ + title: "ThreadSetNameResponse", +}); + +export type V2ThreadShellCommandParams = { readonly command: string; readonly threadId: string }; +export const V2ThreadShellCommandParams = Schema.Struct({ + command: Schema.String.annotate({ + description: + "Shell command string evaluated by the thread's configured shell. Unlike `command/exec`, this intentionally preserves shell syntax such as pipes, redirects, and quoting. This runs unsandboxed with full access rather than inheriting the thread sandbox policy.", + }), + threadId: Schema.String, +}).annotate({ title: "ThreadShellCommandParams" }); + +export type V2ThreadShellCommandResponse = {}; +export const V2ThreadShellCommandResponse = Schema.Struct({}).annotate({ + title: "ThreadShellCommandResponse", +}); + +export type V2ThreadStartedNotification = { readonly thread: V2ThreadStartedNotification__Thread }; +export const V2ThreadStartedNotification = Schema.Struct({ + thread: V2ThreadStartedNotification__Thread, +}).annotate({ title: "ThreadStartedNotification" }); + +export type V2ThreadStartedNotification__ByteRange = { + readonly end: number; + readonly start: number; +}; +export const V2ThreadStartedNotification__ByteRange = Schema.Struct({ + end: Schema.Number.annotate({ format: "uint" }) + .check(Schema.isInt()) + .check(Schema.isGreaterThanOrEqualTo(0)), + start: Schema.Number.annotate({ format: "uint" }) + .check(Schema.isInt()) + .check(Schema.isGreaterThanOrEqualTo(0)), +}); + +export type V2ThreadStartedNotification__CollabAgentTool = + | "spawnAgent" + | "sendInput" + | "resumeAgent" + | "wait" + | "closeAgent"; +export const V2ThreadStartedNotification__CollabAgentTool = Schema.Literals([ + "spawnAgent", + "sendInput", + "resumeAgent", + "wait", + "closeAgent", +]); + +export type V2ThreadStartedNotification__CollabAgentToolCallStatus = + | "inProgress" + | "completed" + | "failed"; +export const V2ThreadStartedNotification__CollabAgentToolCallStatus = Schema.Literals([ + "inProgress", + "completed", + "failed", +]); + +export type V2ThreadStartedNotification__CommandExecutionSource = + | "agent" + | "userShell" + | "unifiedExecStartup" + | "unifiedExecInteraction"; +export const V2ThreadStartedNotification__CommandExecutionSource = Schema.Literals([ + "agent", + "userShell", + "unifiedExecStartup", + "unifiedExecInteraction", +]); + +export type V2ThreadStartedNotification__SessionSource = + | "cli" + | "vscode" + | "exec" + | "appServer" + | "unknown" + | { readonly custom: string } + | { readonly subAgent: V2ThreadStartedNotification__SubAgentSource }; +export const V2ThreadStartedNotification__SessionSource = Schema.Union( + [ + Schema.Literals(["cli", "vscode", "exec", "appServer", "unknown"]), + Schema.Struct({ custom: Schema.String }).annotate({ title: "CustomSessionSource" }), + Schema.Struct({ subAgent: V2ThreadStartedNotification__SubAgentSource }).annotate({ + title: "SubAgentSessionSource", + }), + ], + { mode: "oneOf" }, +); + +export type V2ThreadStartedNotification__ThreadStatus = + | { readonly type: "notLoaded" } + | { readonly type: "idle" } + | { readonly type: "systemError" } + | { + readonly activeFlags: ReadonlyArray; + readonly type: "active"; + }; +export const V2ThreadStartedNotification__ThreadStatus = Schema.Union( + [ + Schema.Struct({ + type: Schema.Literal("notLoaded").annotate({ title: "NotLoadedThreadStatusType" }), + }).annotate({ title: "NotLoadedThreadStatus" }), + Schema.Struct({ + type: Schema.Literal("idle").annotate({ title: "IdleThreadStatusType" }), + }).annotate({ title: "IdleThreadStatus" }), + Schema.Struct({ + type: Schema.Literal("systemError").annotate({ title: "SystemErrorThreadStatusType" }), + }).annotate({ title: "SystemErrorThreadStatus" }), + Schema.Struct({ + activeFlags: Schema.Array(V2ThreadStartedNotification__ThreadActiveFlag), + type: Schema.Literal("active").annotate({ title: "ActiveThreadStatusType" }), + }).annotate({ title: "ActiveThreadStatus" }), + ], + { mode: "oneOf" }, +); + +export type V2ThreadStartParams = { + readonly approvalPolicy?: V2ThreadStartParams__AskForApproval | null; + readonly approvalsReviewer?: V2ThreadStartParams__ApprovalsReviewer | null; + readonly baseInstructions?: string | null; + readonly config?: { readonly [x: string]: unknown } | null; + readonly cwd?: string | null; + readonly developerInstructions?: string | null; + readonly ephemeral?: boolean | null; + readonly model?: string | null; + readonly modelProvider?: string | null; + readonly personality?: V2ThreadStartParams__Personality | null; + readonly sandbox?: V2ThreadStartParams__SandboxMode | null; + readonly serviceName?: string | null; + readonly serviceTier?: V2ThreadStartParams__ServiceTier | null | null; + readonly sessionStartSource?: V2ThreadStartParams__ThreadStartSource | null; +}; +export const V2ThreadStartParams = Schema.Struct({ + approvalPolicy: Schema.optionalKey( + Schema.Union([V2ThreadStartParams__AskForApproval, Schema.Null]), + ), + approvalsReviewer: Schema.optionalKey( + Schema.Union([V2ThreadStartParams__ApprovalsReviewer, Schema.Null]).annotate({ + description: + "Override where approval requests are routed for review on this thread and subsequent turns.", + }), + ), + baseInstructions: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + config: Schema.optionalKey( + Schema.Union([Schema.Record(Schema.String, Schema.Unknown), Schema.Null]), + ), + cwd: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + developerInstructions: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + ephemeral: Schema.optionalKey(Schema.Union([Schema.Boolean, Schema.Null])), + model: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + modelProvider: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + personality: Schema.optionalKey(Schema.Union([V2ThreadStartParams__Personality, Schema.Null])), + sandbox: Schema.optionalKey(Schema.Union([V2ThreadStartParams__SandboxMode, Schema.Null])), + serviceName: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + serviceTier: Schema.optionalKey( + Schema.Union([Schema.Union([V2ThreadStartParams__ServiceTier, Schema.Null]), Schema.Null]), + ), + sessionStartSource: Schema.optionalKey( + Schema.Union([V2ThreadStartParams__ThreadStartSource, Schema.Null]), + ), +}).annotate({ title: "ThreadStartParams" }); + +export type V2ThreadStartParams__DynamicToolSpec = { + readonly deferLoading?: boolean; + readonly description: string; + readonly inputSchema: unknown; + readonly name: string; +}; +export const V2ThreadStartParams__DynamicToolSpec = Schema.Struct({ + deferLoading: Schema.optionalKey(Schema.Boolean), + description: Schema.String, + inputSchema: Schema.Unknown, + name: Schema.String, +}); + +export type V2ThreadStartResponse = { + readonly approvalPolicy: V2ThreadStartResponse__AskForApproval; + readonly approvalsReviewer: "user" | "guardian_subagent"; + readonly cwd: string; + readonly model: string; + readonly modelProvider: string; + readonly reasoningEffort?: V2ThreadStartResponse__ReasoningEffort | null; + readonly sandbox: V2ThreadStartResponse__SandboxPolicy; + readonly serviceTier?: V2ThreadStartResponse__ServiceTier | null; + readonly thread: V2ThreadStartResponse__Thread; +}; +export const V2ThreadStartResponse = Schema.Struct({ + approvalPolicy: V2ThreadStartResponse__AskForApproval, + approvalsReviewer: Schema.Literals(["user", "guardian_subagent"]).annotate({ + description: + "Configures who approval requests are routed to for review. Examples include sandbox escapes, blocked network access, MCP approval prompts, and ARC escalations. Defaults to `user`. `guardian_subagent` uses a carefully prompted subagent to gather relevant context and apply a risk-based decision framework before approving or denying the request.", + }), + cwd: Schema.String, + model: Schema.String, + modelProvider: Schema.String, + reasoningEffort: Schema.optionalKey( + Schema.Union([V2ThreadStartResponse__ReasoningEffort, Schema.Null]), + ), + sandbox: V2ThreadStartResponse__SandboxPolicy, + serviceTier: Schema.optionalKey(Schema.Union([V2ThreadStartResponse__ServiceTier, Schema.Null])), + thread: V2ThreadStartResponse__Thread, +}).annotate({ title: "ThreadStartResponse" }); + +export type V2ThreadStartResponse__ApprovalsReviewer = "user" | "guardian_subagent"; +export const V2ThreadStartResponse__ApprovalsReviewer = Schema.Literals([ + "user", + "guardian_subagent", +]).annotate({ + description: + "Configures who approval requests are routed to for review. Examples include sandbox escapes, blocked network access, MCP approval prompts, and ARC escalations. Defaults to `user`. `guardian_subagent` uses a carefully prompted subagent to gather relevant context and apply a risk-based decision framework before approving or denying the request.", +}); + +export type V2ThreadStartResponse__ByteRange = { readonly end: number; readonly start: number }; +export const V2ThreadStartResponse__ByteRange = Schema.Struct({ + end: Schema.Number.annotate({ format: "uint" }) + .check(Schema.isInt()) + .check(Schema.isGreaterThanOrEqualTo(0)), + start: Schema.Number.annotate({ format: "uint" }) + .check(Schema.isInt()) + .check(Schema.isGreaterThanOrEqualTo(0)), +}); + +export type V2ThreadStartResponse__CollabAgentTool = + | "spawnAgent" + | "sendInput" + | "resumeAgent" + | "wait" + | "closeAgent"; +export const V2ThreadStartResponse__CollabAgentTool = Schema.Literals([ + "spawnAgent", + "sendInput", + "resumeAgent", + "wait", + "closeAgent", +]); + +export type V2ThreadStartResponse__CollabAgentToolCallStatus = + | "inProgress" + | "completed" + | "failed"; +export const V2ThreadStartResponse__CollabAgentToolCallStatus = Schema.Literals([ + "inProgress", + "completed", + "failed", +]); + +export type V2ThreadStartResponse__CommandExecutionSource = + | "agent" + | "userShell" + | "unifiedExecStartup" + | "unifiedExecInteraction"; +export const V2ThreadStartResponse__CommandExecutionSource = Schema.Literals([ + "agent", + "userShell", + "unifiedExecStartup", + "unifiedExecInteraction", +]); + +export type V2ThreadStartResponse__NetworkAccess = "restricted" | "enabled"; +export const V2ThreadStartResponse__NetworkAccess = Schema.Literals(["restricted", "enabled"]); + +export type V2ThreadStartResponse__ReadOnlyAccess = + | { + readonly includePlatformDefaults?: boolean; + readonly readableRoots?: ReadonlyArray; + readonly type: "restricted"; + } + | { readonly type: "fullAccess" }; +export const V2ThreadStartResponse__ReadOnlyAccess = Schema.Union( + [ + Schema.Struct({ + includePlatformDefaults: Schema.optionalKey(Schema.Boolean.annotate({ default: true })), + readableRoots: Schema.optionalKey( + Schema.Array(V2ThreadStartResponse__AbsolutePathBuf).annotate({ default: [] }), + ), + type: Schema.Literal("restricted").annotate({ title: "RestrictedReadOnlyAccessType" }), + }).annotate({ title: "RestrictedReadOnlyAccess" }), + Schema.Struct({ + type: Schema.Literal("fullAccess").annotate({ title: "FullAccessReadOnlyAccessType" }), + }).annotate({ title: "FullAccessReadOnlyAccess" }), + ], + { mode: "oneOf" }, +); + +export type V2ThreadStartResponse__SessionSource = + | "cli" + | "vscode" + | "exec" + | "appServer" + | "unknown" + | { readonly custom: string } + | { readonly subAgent: V2ThreadStartResponse__SubAgentSource }; +export const V2ThreadStartResponse__SessionSource = Schema.Union( + [ + Schema.Literals(["cli", "vscode", "exec", "appServer", "unknown"]), + Schema.Struct({ custom: Schema.String }).annotate({ title: "CustomSessionSource" }), + Schema.Struct({ subAgent: V2ThreadStartResponse__SubAgentSource }).annotate({ + title: "SubAgentSessionSource", + }), + ], + { mode: "oneOf" }, +); + +export type V2ThreadStartResponse__ThreadStatus = + | { readonly type: "notLoaded" } + | { readonly type: "idle" } + | { readonly type: "systemError" } + | { + readonly activeFlags: ReadonlyArray; + readonly type: "active"; + }; +export const V2ThreadStartResponse__ThreadStatus = Schema.Union( + [ + Schema.Struct({ + type: Schema.Literal("notLoaded").annotate({ title: "NotLoadedThreadStatusType" }), + }).annotate({ title: "NotLoadedThreadStatus" }), + Schema.Struct({ + type: Schema.Literal("idle").annotate({ title: "IdleThreadStatusType" }), + }).annotate({ title: "IdleThreadStatus" }), + Schema.Struct({ + type: Schema.Literal("systemError").annotate({ title: "SystemErrorThreadStatusType" }), + }).annotate({ title: "SystemErrorThreadStatus" }), + Schema.Struct({ + activeFlags: Schema.Array(V2ThreadStartResponse__ThreadActiveFlag), + type: Schema.Literal("active").annotate({ title: "ActiveThreadStatusType" }), + }).annotate({ title: "ActiveThreadStatus" }), + ], + { mode: "oneOf" }, +); + +export type V2ThreadStatusChangedNotification = { + readonly status: V2ThreadStatusChangedNotification__ThreadStatus; + readonly threadId: string; +}; +export const V2ThreadStatusChangedNotification = Schema.Struct({ + status: V2ThreadStatusChangedNotification__ThreadStatus, + threadId: Schema.String, +}).annotate({ title: "ThreadStatusChangedNotification" }); + +export type V2ThreadTokenUsageUpdatedNotification = { + readonly threadId: string; + readonly tokenUsage: V2ThreadTokenUsageUpdatedNotification__ThreadTokenUsage; + readonly turnId: string; +}; +export const V2ThreadTokenUsageUpdatedNotification = Schema.Struct({ + threadId: Schema.String, + tokenUsage: V2ThreadTokenUsageUpdatedNotification__ThreadTokenUsage, + turnId: Schema.String, +}).annotate({ title: "ThreadTokenUsageUpdatedNotification" }); + +export type V2ThreadUnarchivedNotification = { readonly threadId: string }; +export const V2ThreadUnarchivedNotification = Schema.Struct({ threadId: Schema.String }).annotate({ + title: "ThreadUnarchivedNotification", +}); + +export type V2ThreadUnarchiveParams = { readonly threadId: string }; +export const V2ThreadUnarchiveParams = Schema.Struct({ threadId: Schema.String }).annotate({ + title: "ThreadUnarchiveParams", +}); + +export type V2ThreadUnarchiveResponse = { readonly thread: V2ThreadUnarchiveResponse__Thread }; +export const V2ThreadUnarchiveResponse = Schema.Struct({ + thread: V2ThreadUnarchiveResponse__Thread, +}).annotate({ title: "ThreadUnarchiveResponse" }); + +export type V2ThreadUnarchiveResponse__ByteRange = { readonly end: number; readonly start: number }; +export const V2ThreadUnarchiveResponse__ByteRange = Schema.Struct({ + end: Schema.Number.annotate({ format: "uint" }) + .check(Schema.isInt()) + .check(Schema.isGreaterThanOrEqualTo(0)), + start: Schema.Number.annotate({ format: "uint" }) + .check(Schema.isInt()) + .check(Schema.isGreaterThanOrEqualTo(0)), +}); + +export type V2ThreadUnarchiveResponse__CollabAgentTool = + | "spawnAgent" + | "sendInput" + | "resumeAgent" + | "wait" + | "closeAgent"; +export const V2ThreadUnarchiveResponse__CollabAgentTool = Schema.Literals([ + "spawnAgent", + "sendInput", + "resumeAgent", + "wait", + "closeAgent", +]); + +export type V2ThreadUnarchiveResponse__CollabAgentToolCallStatus = + | "inProgress" + | "completed" + | "failed"; +export const V2ThreadUnarchiveResponse__CollabAgentToolCallStatus = Schema.Literals([ + "inProgress", + "completed", + "failed", +]); + +export type V2ThreadUnarchiveResponse__CommandExecutionSource = + | "agent" + | "userShell" + | "unifiedExecStartup" + | "unifiedExecInteraction"; +export const V2ThreadUnarchiveResponse__CommandExecutionSource = Schema.Literals([ + "agent", + "userShell", + "unifiedExecStartup", + "unifiedExecInteraction", +]); + +export type V2ThreadUnarchiveResponse__SessionSource = + | "cli" + | "vscode" + | "exec" + | "appServer" + | "unknown" + | { readonly custom: string } + | { readonly subAgent: V2ThreadUnarchiveResponse__SubAgentSource }; +export const V2ThreadUnarchiveResponse__SessionSource = Schema.Union( + [ + Schema.Literals(["cli", "vscode", "exec", "appServer", "unknown"]), + Schema.Struct({ custom: Schema.String }).annotate({ title: "CustomSessionSource" }), + Schema.Struct({ subAgent: V2ThreadUnarchiveResponse__SubAgentSource }).annotate({ + title: "SubAgentSessionSource", + }), + ], + { mode: "oneOf" }, +); + +export type V2ThreadUnarchiveResponse__ThreadStatus = + | { readonly type: "notLoaded" } + | { readonly type: "idle" } + | { readonly type: "systemError" } + | { + readonly activeFlags: ReadonlyArray; + readonly type: "active"; + }; +export const V2ThreadUnarchiveResponse__ThreadStatus = Schema.Union( + [ + Schema.Struct({ + type: Schema.Literal("notLoaded").annotate({ title: "NotLoadedThreadStatusType" }), + }).annotate({ title: "NotLoadedThreadStatus" }), + Schema.Struct({ + type: Schema.Literal("idle").annotate({ title: "IdleThreadStatusType" }), + }).annotate({ title: "IdleThreadStatus" }), + Schema.Struct({ + type: Schema.Literal("systemError").annotate({ title: "SystemErrorThreadStatusType" }), + }).annotate({ title: "SystemErrorThreadStatus" }), + Schema.Struct({ + activeFlags: Schema.Array(V2ThreadUnarchiveResponse__ThreadActiveFlag), + type: Schema.Literal("active").annotate({ title: "ActiveThreadStatusType" }), + }).annotate({ title: "ActiveThreadStatus" }), + ], + { mode: "oneOf" }, +); + +export type V2ThreadUnsubscribeParams = { readonly threadId: string }; +export const V2ThreadUnsubscribeParams = Schema.Struct({ threadId: Schema.String }).annotate({ + title: "ThreadUnsubscribeParams", +}); + +export type V2ThreadUnsubscribeResponse = { + readonly status: V2ThreadUnsubscribeResponse__ThreadUnsubscribeStatus; +}; +export const V2ThreadUnsubscribeResponse = Schema.Struct({ + status: V2ThreadUnsubscribeResponse__ThreadUnsubscribeStatus, +}).annotate({ title: "ThreadUnsubscribeResponse" }); + +export type V2TurnCompletedNotification = { + readonly threadId: string; + readonly turn: V2TurnCompletedNotification__Turn; +}; +export const V2TurnCompletedNotification = Schema.Struct({ + threadId: Schema.String, + turn: V2TurnCompletedNotification__Turn, +}).annotate({ title: "TurnCompletedNotification" }); + +export type V2TurnCompletedNotification__ByteRange = { + readonly end: number; + readonly start: number; +}; +export const V2TurnCompletedNotification__ByteRange = Schema.Struct({ + end: Schema.Number.annotate({ format: "uint" }) + .check(Schema.isInt()) + .check(Schema.isGreaterThanOrEqualTo(0)), + start: Schema.Number.annotate({ format: "uint" }) + .check(Schema.isInt()) + .check(Schema.isGreaterThanOrEqualTo(0)), +}); + +export type V2TurnCompletedNotification__CollabAgentTool = + | "spawnAgent" + | "sendInput" + | "resumeAgent" + | "wait" + | "closeAgent"; +export const V2TurnCompletedNotification__CollabAgentTool = Schema.Literals([ + "spawnAgent", + "sendInput", + "resumeAgent", + "wait", + "closeAgent", +]); + +export type V2TurnCompletedNotification__CollabAgentToolCallStatus = + | "inProgress" + | "completed" + | "failed"; +export const V2TurnCompletedNotification__CollabAgentToolCallStatus = Schema.Literals([ + "inProgress", + "completed", + "failed", +]); + +export type V2TurnCompletedNotification__CommandExecutionSource = + | "agent" + | "userShell" + | "unifiedExecStartup" + | "unifiedExecInteraction"; +export const V2TurnCompletedNotification__CommandExecutionSource = Schema.Literals([ + "agent", + "userShell", + "unifiedExecStartup", + "unifiedExecInteraction", +]); + +export type V2TurnDiffUpdatedNotification = { + readonly diff: string; + readonly threadId: string; + readonly turnId: string; +}; +export const V2TurnDiffUpdatedNotification = Schema.Struct({ + diff: Schema.String, + threadId: Schema.String, + turnId: Schema.String, +}).annotate({ + title: "TurnDiffUpdatedNotification", + description: + "Notification that the turn-level unified diff has changed. Contains the latest aggregated diff across all file changes in the turn.", +}); + +export type V2TurnInterruptParams = { readonly threadId: string; readonly turnId: string }; +export const V2TurnInterruptParams = Schema.Struct({ + threadId: Schema.String, + turnId: Schema.String, +}).annotate({ title: "TurnInterruptParams" }); + +export type V2TurnInterruptResponse = {}; +export const V2TurnInterruptResponse = Schema.Struct({}).annotate({ + title: "TurnInterruptResponse", +}); + +export type V2TurnPlanUpdatedNotification = { + readonly explanation?: string | null; + readonly plan: ReadonlyArray; + readonly threadId: string; + readonly turnId: string; +}; +export const V2TurnPlanUpdatedNotification = Schema.Struct({ + explanation: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + plan: Schema.Array(V2TurnPlanUpdatedNotification__TurnPlanStep), + threadId: Schema.String, + turnId: Schema.String, +}).annotate({ title: "TurnPlanUpdatedNotification" }); + +export type V2TurnStartedNotification = { + readonly threadId: string; + readonly turn: V2TurnStartedNotification__Turn; +}; +export const V2TurnStartedNotification = Schema.Struct({ + threadId: Schema.String, + turn: V2TurnStartedNotification__Turn, +}).annotate({ title: "TurnStartedNotification" }); + +export type V2TurnStartedNotification__ByteRange = { readonly end: number; readonly start: number }; +export const V2TurnStartedNotification__ByteRange = Schema.Struct({ + end: Schema.Number.annotate({ format: "uint" }) + .check(Schema.isInt()) + .check(Schema.isGreaterThanOrEqualTo(0)), + start: Schema.Number.annotate({ format: "uint" }) + .check(Schema.isInt()) + .check(Schema.isGreaterThanOrEqualTo(0)), +}); + +export type V2TurnStartedNotification__CollabAgentTool = + | "spawnAgent" + | "sendInput" + | "resumeAgent" + | "wait" + | "closeAgent"; +export const V2TurnStartedNotification__CollabAgentTool = Schema.Literals([ + "spawnAgent", + "sendInput", + "resumeAgent", + "wait", + "closeAgent", +]); + +export type V2TurnStartedNotification__CollabAgentToolCallStatus = + | "inProgress" + | "completed" + | "failed"; +export const V2TurnStartedNotification__CollabAgentToolCallStatus = Schema.Literals([ + "inProgress", + "completed", + "failed", +]); + +export type V2TurnStartedNotification__CommandExecutionSource = + | "agent" + | "userShell" + | "unifiedExecStartup" + | "unifiedExecInteraction"; +export const V2TurnStartedNotification__CommandExecutionSource = Schema.Literals([ + "agent", + "userShell", + "unifiedExecStartup", + "unifiedExecInteraction", +]); + +export type V2TurnStartParams = { + readonly approvalPolicy?: V2TurnStartParams__AskForApproval | null; + readonly approvalsReviewer?: V2TurnStartParams__ApprovalsReviewer | null; + readonly cwd?: string | null; + readonly effort?: V2TurnStartParams__ReasoningEffort | null; + readonly input: ReadonlyArray; + readonly model?: string | null; + readonly outputSchema?: unknown; + readonly personality?: V2TurnStartParams__Personality | null; + readonly sandboxPolicy?: V2TurnStartParams__SandboxPolicy | null; + readonly serviceTier?: V2TurnStartParams__ServiceTier | null | null; + readonly summary?: V2TurnStartParams__ReasoningSummary | null; + readonly threadId: string; +}; +export const V2TurnStartParams = Schema.Struct({ + approvalPolicy: Schema.optionalKey( + Schema.Union([V2TurnStartParams__AskForApproval, Schema.Null]).annotate({ + description: "Override the approval policy for this turn and subsequent turns.", + }), + ), + approvalsReviewer: Schema.optionalKey( + Schema.Union([V2TurnStartParams__ApprovalsReviewer, Schema.Null]).annotate({ + description: + "Override where approval requests are routed for review on this turn and subsequent turns.", + }), + ), + cwd: Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + description: "Override the working directory for this turn and subsequent turns.", + }), + Schema.Null, + ]), + ), + effort: Schema.optionalKey( + Schema.Union([V2TurnStartParams__ReasoningEffort, Schema.Null]).annotate({ + description: "Override the reasoning effort for this turn and subsequent turns.", + }), + ), + input: Schema.Array(V2TurnStartParams__UserInput), + model: Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + description: "Override the model for this turn and subsequent turns.", + }), + Schema.Null, + ]), + ), + outputSchema: Schema.optionalKey( + Schema.Unknown.annotate({ + description: + "Optional JSON Schema used to constrain the final assistant message for this turn.", + }), + ), + personality: Schema.optionalKey( + Schema.Union([V2TurnStartParams__Personality, Schema.Null]).annotate({ + description: "Override the personality for this turn and subsequent turns.", + }), + ), + sandboxPolicy: Schema.optionalKey( + Schema.Union([V2TurnStartParams__SandboxPolicy, Schema.Null]).annotate({ + description: "Override the sandbox policy for this turn and subsequent turns.", + }), + ), + serviceTier: Schema.optionalKey( + Schema.Union([ + Schema.Union([V2TurnStartParams__ServiceTier, Schema.Null]), + Schema.Null, + ]).annotate({ description: "Override the service tier for this turn and subsequent turns." }), + ), + summary: Schema.optionalKey( + Schema.Union([V2TurnStartParams__ReasoningSummary, Schema.Null]).annotate({ + description: "Override the reasoning summary for this turn and subsequent turns.", + }), + ), + threadId: Schema.String, +}).annotate({ title: "TurnStartParams" }); + +export type V2TurnStartParams__ByteRange = { readonly end: number; readonly start: number }; +export const V2TurnStartParams__ByteRange = Schema.Struct({ + end: Schema.Number.annotate({ format: "uint" }) + .check(Schema.isInt()) + .check(Schema.isGreaterThanOrEqualTo(0)), + start: Schema.Number.annotate({ format: "uint" }) + .check(Schema.isInt()) + .check(Schema.isGreaterThanOrEqualTo(0)), +}); + +export type V2TurnStartParams__CollaborationMode = { + readonly mode: V2TurnStartParams__ModeKind; + readonly settings: V2TurnStartParams__Settings; +}; +export const V2TurnStartParams__CollaborationMode = Schema.Struct({ + mode: V2TurnStartParams__ModeKind, + settings: V2TurnStartParams__Settings, +}).annotate({ description: "Collaboration mode for a Codex session." }); + +export type V2TurnStartParams__NetworkAccess = "restricted" | "enabled"; +export const V2TurnStartParams__NetworkAccess = Schema.Literals(["restricted", "enabled"]); + +export type V2TurnStartParams__ReadOnlyAccess = + | { + readonly includePlatformDefaults?: boolean; + readonly readableRoots?: ReadonlyArray; + readonly type: "restricted"; + } + | { readonly type: "fullAccess" }; +export const V2TurnStartParams__ReadOnlyAccess = Schema.Union( + [ + Schema.Struct({ + includePlatformDefaults: Schema.optionalKey(Schema.Boolean.annotate({ default: true })), + readableRoots: Schema.optionalKey( + Schema.Array(V2TurnStartParams__AbsolutePathBuf).annotate({ default: [] }), + ), + type: Schema.Literal("restricted").annotate({ title: "RestrictedReadOnlyAccessType" }), + }).annotate({ title: "RestrictedReadOnlyAccess" }), + Schema.Struct({ + type: Schema.Literal("fullAccess").annotate({ title: "FullAccessReadOnlyAccessType" }), + }).annotate({ title: "FullAccessReadOnlyAccess" }), + ], + { mode: "oneOf" }, +); + +export type V2TurnStartResponse = { readonly turn: V2TurnStartResponse__Turn }; +export const V2TurnStartResponse = Schema.Struct({ turn: V2TurnStartResponse__Turn }).annotate({ + title: "TurnStartResponse", +}); + +export type V2TurnStartResponse__ByteRange = { readonly end: number; readonly start: number }; +export const V2TurnStartResponse__ByteRange = Schema.Struct({ + end: Schema.Number.annotate({ format: "uint" }) + .check(Schema.isInt()) + .check(Schema.isGreaterThanOrEqualTo(0)), + start: Schema.Number.annotate({ format: "uint" }) + .check(Schema.isInt()) + .check(Schema.isGreaterThanOrEqualTo(0)), +}); + +export type V2TurnStartResponse__CollabAgentTool = + | "spawnAgent" + | "sendInput" + | "resumeAgent" + | "wait" + | "closeAgent"; +export const V2TurnStartResponse__CollabAgentTool = Schema.Literals([ + "spawnAgent", + "sendInput", + "resumeAgent", + "wait", + "closeAgent", +]); + +export type V2TurnStartResponse__CollabAgentToolCallStatus = "inProgress" | "completed" | "failed"; +export const V2TurnStartResponse__CollabAgentToolCallStatus = Schema.Literals([ + "inProgress", + "completed", + "failed", +]); + +export type V2TurnStartResponse__CommandExecutionSource = + | "agent" + | "userShell" + | "unifiedExecStartup" + | "unifiedExecInteraction"; +export const V2TurnStartResponse__CommandExecutionSource = Schema.Literals([ + "agent", + "userShell", + "unifiedExecStartup", + "unifiedExecInteraction", +]); + +export type V2TurnSteerParams = { + readonly expectedTurnId: string; + readonly input: ReadonlyArray; + readonly threadId: string; +}; +export const V2TurnSteerParams = Schema.Struct({ + expectedTurnId: Schema.String.annotate({ + description: + "Required active turn id precondition. The request fails when it does not match the currently active turn.", + }), + input: Schema.Array(V2TurnSteerParams__UserInput), + threadId: Schema.String, +}).annotate({ title: "TurnSteerParams" }); + +export type V2TurnSteerParams__ByteRange = { readonly end: number; readonly start: number }; +export const V2TurnSteerParams__ByteRange = Schema.Struct({ + end: Schema.Number.annotate({ format: "uint" }) + .check(Schema.isInt()) + .check(Schema.isGreaterThanOrEqualTo(0)), + start: Schema.Number.annotate({ format: "uint" }) + .check(Schema.isInt()) + .check(Schema.isGreaterThanOrEqualTo(0)), +}); + +export type V2TurnSteerResponse = { readonly turnId: string }; +export const V2TurnSteerResponse = Schema.Struct({ turnId: Schema.String }).annotate({ + title: "TurnSteerResponse", +}); + +export type V2WindowsSandboxSetupCompletedNotification = { + readonly error?: string | null; + readonly mode: V2WindowsSandboxSetupCompletedNotification__WindowsSandboxSetupMode; + readonly success: boolean; +}; +export const V2WindowsSandboxSetupCompletedNotification = Schema.Struct({ + error: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + mode: V2WindowsSandboxSetupCompletedNotification__WindowsSandboxSetupMode, + success: Schema.Boolean, +}).annotate({ title: "WindowsSandboxSetupCompletedNotification" }); + +export type V2WindowsSandboxSetupStartParams = { + readonly cwd?: V2WindowsSandboxSetupStartParams__AbsolutePathBuf | null; + readonly mode: V2WindowsSandboxSetupStartParams__WindowsSandboxSetupMode; +}; +export const V2WindowsSandboxSetupStartParams = Schema.Struct({ + cwd: Schema.optionalKey( + Schema.Union([V2WindowsSandboxSetupStartParams__AbsolutePathBuf, Schema.Null]), + ), + mode: V2WindowsSandboxSetupStartParams__WindowsSandboxSetupMode, +}).annotate({ title: "WindowsSandboxSetupStartParams" }); + +export type V2WindowsSandboxSetupStartResponse = { readonly started: boolean }; +export const V2WindowsSandboxSetupStartResponse = Schema.Struct({ + started: Schema.Boolean, +}).annotate({ title: "WindowsSandboxSetupStartResponse" }); + +export type V2WindowsWorldWritableWarningNotification = { + readonly extraCount: number; + readonly failedScan: boolean; + readonly samplePaths: ReadonlyArray; +}; +export const V2WindowsWorldWritableWarningNotification = Schema.Struct({ + extraCount: Schema.Number.annotate({ format: "uint" }) + .check(Schema.isInt()) + .check(Schema.isGreaterThanOrEqualTo(0)), + failedScan: Schema.Boolean, + samplePaths: Schema.Array(Schema.String), +}).annotate({ title: "WindowsWorldWritableWarningNotification" }); diff --git a/packages/effect-codex-app-server/src/_internal/shared.ts b/packages/effect-codex-app-server/src/_internal/shared.ts new file mode 100644 index 0000000000..99fe8e5360 --- /dev/null +++ b/packages/effect-codex-app-server/src/_internal/shared.ts @@ -0,0 +1,101 @@ +import * as Effect from "effect/Effect"; +import * as Schema from "effect/Schema"; +import * as SchemaIssue from "effect/SchemaIssue"; + +import * as CodexError from "../errors.ts"; + +const formatSchemaIssue = SchemaIssue.makeFormatterDefault(); + +export const JsonRpcId = Schema.Union([Schema.Number, Schema.String]); + +export const JsonRpcError = Schema.Struct({ + code: Schema.Number, + message: Schema.String, + data: Schema.optional(Schema.Unknown), +}); + +export const JsonRpcResponseEnvelope = Schema.Struct({ + id: JsonRpcId, + result: Schema.optional(Schema.Unknown), + error: Schema.optional(JsonRpcError), +}); + +export const decodeOptionalPayload = ( + method: string, + schema: Schema.Codec | undefined, + raw: unknown, +): Effect.Effect => { + if (!schema) { + if (raw === undefined) { + return Effect.sync(() => undefined as A); + } + return Effect.fail( + CodexError.CodexAppServerRequestError.invalidParams(`${method} does not accept params`, raw), + ); + } + + return Schema.decodeUnknownEffect(schema)(raw).pipe( + Effect.mapError((error) => + CodexError.CodexAppServerRequestError.invalidParams( + `Invalid ${method} payload: ${formatSchemaIssue(error.issue)}`, + { issue: error.issue }, + ), + ), + ); +}; + +export const encodeOptionalPayload = ( + method: string, + schema: Schema.Codec | undefined, + payload: A, +): Effect.Effect => { + if (!schema) { + if (payload === undefined) { + return Effect.sync(() => undefined); + } + return Effect.fail( + CodexError.CodexAppServerRequestError.invalidParams( + `${method} does not accept params`, + payload, + ), + ); + } + + return Schema.encodeEffect(schema)(payload).pipe( + Effect.mapError((error) => + CodexError.CodexAppServerRequestError.invalidParams( + `Invalid ${method} payload: ${formatSchemaIssue(error.issue)}`, + { issue: error.issue }, + ), + ), + ); +}; + +export const decodeNotificationPayload = ( + method: string, + schema: Schema.Codec | undefined, + raw: unknown, +): Effect.Effect => + decodeOptionalPayload(method, schema, raw).pipe( + Effect.mapError( + (error) => + new CodexError.CodexAppServerProtocolParseError({ + detail: error.message, + cause: error, + }), + ), + ); + +export const runHandler = Effect.fnUntraced(function* ( + handler: ((payload: A) => Effect.Effect) | undefined, + payload: A, + method: string, +) { + if (!handler) { + return yield* CodexError.CodexAppServerRequestError.methodNotFound(method); + } + + return yield* handler(payload).pipe( + Effect.mapError((error) => CodexError.normalizeToRequestError(error)), + ); +}); diff --git a/packages/effect-codex-app-server/src/_internal/stdio.ts b/packages/effect-codex-app-server/src/_internal/stdio.ts new file mode 100644 index 0000000000..ced07fb53e --- /dev/null +++ b/packages/effect-codex-app-server/src/_internal/stdio.ts @@ -0,0 +1,57 @@ +import * as Cause from "effect/Cause"; +import * as Effect from "effect/Effect"; +import * as Queue from "effect/Queue"; +import * as Sink from "effect/Sink"; +import * as Stdio from "effect/Stdio"; +import * as Stream from "effect/Stream"; +import { ChildProcessSpawner } from "effect/unstable/process"; + +import * as CodexError from "../errors.ts"; + +const encoder = new TextEncoder(); + +export const makeChildStdio = (handle: ChildProcessSpawner.ChildProcessHandle) => + Stdio.make({ + args: Effect.succeed([]), + stdin: handle.stdout, + stdout: () => + Sink.mapInput(handle.stdin, (chunk: string | Uint8Array) => + typeof chunk === "string" ? encoder.encode(chunk) : chunk, + ), + stderr: () => Sink.drain, + }); + +export const makeInMemoryStdio = Effect.fn("makeInMemoryStdio")(function* () { + const input = yield* Queue.unbounded>(); + const output = yield* Queue.unbounded(); + const decoder = new TextDecoder(); + + return { + stdio: Stdio.make({ + args: Effect.succeed([]), + stdin: Stream.fromQueue(input), + stdout: () => + Sink.forEach((chunk: string | Uint8Array) => + Queue.offer( + output, + typeof chunk === "string" ? chunk : decoder.decode(chunk, { stream: true }), + ), + ), + stderr: () => Sink.drain, + }), + input, + output, + }; +}); + +export const makeTerminationError = ( + handle: ChildProcessSpawner.ChildProcessHandle, +): Effect.Effect => + Effect.match(handle.exitCode, { + onFailure: (cause) => + new CodexError.CodexAppServerTransportError({ + detail: "Failed to determine Codex App Server process exit status", + cause, + }), + onSuccess: (code) => new CodexError.CodexAppServerProcessExitedError({ code }), + }); diff --git a/packages/effect-codex-app-server/src/client.test.ts b/packages/effect-codex-app-server/src/client.test.ts new file mode 100644 index 0000000000..0e0127b1a9 --- /dev/null +++ b/packages/effect-codex-app-server/src/client.test.ts @@ -0,0 +1,154 @@ +import * as Exit from "effect/Exit"; +import * as Layer from "effect/Layer"; +import * as Path from "effect/Path"; +import * as Effect from "effect/Effect"; +import * as Ref from "effect/Ref"; +import * as Scope from "effect/Scope"; +import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process"; + +import * as NodeServices from "@effect/platform-node/NodeServices"; +import { assert, it } from "@effect/vitest"; + +import * as CodexClient from "./client.ts"; + +const mockPeerPath = Effect.map(Effect.service(Path.Path), (path) => + path.join(import.meta.dirname, "../test/fixtures/codex-app-server-mock-peer.ts"), +); + +it.layer(NodeServices.layer)("effect-codex-app-server client", (it) => { + const makeHandle = () => + Effect.gen(function* () { + const spawner = yield* ChildProcessSpawner.ChildProcessSpawner; + const path = yield* Path.Path; + const command = ChildProcess.make("bun", ["run", yield* mockPeerPath], { + cwd: path.join(import.meta.dirname, ".."), + shell: process.platform === "win32", + }); + return yield* spawner.spawn(command); + }); + + it.effect("initializes, handles typed server requests, and reads account and skills data", () => + Effect.gen(function* () { + const userInputRequests = yield* Ref.make>([]); + const messageDeltas = yield* Ref.make>([]); + const handle = yield* makeHandle(); + const scope = yield* Scope.make(); + const clientLayer = CodexClient.layerChildProcess(handle); + const context = yield* Layer.buildWithScope(clientLayer, scope); + + const result = yield* Effect.gen(function* () { + const client = yield* CodexClient.CodexAppServerClient; + + yield* client.handleServerRequest("item/tool/requestUserInput", (payload) => + Ref.update(userInputRequests, (current) => [...current, payload]).pipe( + Effect.as({ + answers: { + approved: { + answers: ["yes"], + }, + }, + }), + ), + ); + + yield* client.handleServerNotification("item/agentMessage/delta", (payload) => + Ref.update(messageDeltas, (current) => [...current, payload]), + ); + + const initialized = yield* client.request("initialize", { + clientInfo: { + name: "effect-codex-app-server-test", + title: "Effect Codex App Server Test", + version: "0.0.0", + }, + capabilities: { + experimentalApi: true, + optOutNotificationMethods: null, + }, + }); + assert.equal(initialized.userAgent, "mock-codex-app-server"); + + yield* client.notify("initialized", undefined); + + const account = yield* client.request("account/read", {}); + assert.equal(account.requiresOpenaiAuth, false); + assert.deepEqual(account.account, { + type: "chatgpt", + email: "mock@example.com", + planType: "plus", + }); + + const skills = yield* client.request("skills/list", { + cwds: [process.cwd()], + }); + assert.equal(skills.data.length, 1); + assert.equal(skills.data[0]?.cwd, process.cwd()); + + return { + account, + skills, + }; + }).pipe(Effect.provide(context), Effect.ensuring(Scope.close(scope, Exit.void))); + + assert.equal(result.skills.data[0]?.skills.length, 0); + assert.deepEqual(yield* Ref.get(userInputRequests), [ + { + itemId: "item-approval-1", + threadId: "thread-1", + turnId: "turn-1", + questions: [ + { + id: "approved", + header: "Approve", + question: "Continue with the mock skills request?", + options: [ + { + label: "yes", + description: "Approve the request", + }, + ], + }, + ], + }, + ]); + assert.deepEqual(yield* Ref.get(messageDeltas), [ + { + delta: "Mock server is ready.", + itemId: "item-1", + threadId: "thread-1", + turnId: "turn-1", + }, + ]); + }), + ); + + it.effect("initializes a command-backed app-server client", () => + Effect.gen(function* () { + const path = yield* Path.Path; + const scope = yield* Scope.make(); + const clientLayer = CodexClient.layerCommand({ + command: "bun", + args: ["run", yield* mockPeerPath], + cwd: path.join(import.meta.dirname, ".."), + }); + const context = yield* Layer.buildWithScope(clientLayer, scope); + + const initialized = yield* Effect.gen(function* () { + const client = yield* CodexClient.CodexAppServerClient; + return yield* client.request("initialize", { + clientInfo: { + name: "effect-codex-app-server-test", + title: "Effect Codex App Server Test", + version: "0.0.0", + }, + capabilities: { + experimentalApi: true, + optOutNotificationMethods: null, + }, + }); + }).pipe(Effect.provide(context), Effect.ensuring(Scope.close(scope, Exit.void))); + + assert.equal(initialized.userAgent, "mock-codex-app-server"); + }), + ); +}); diff --git a/packages/effect-codex-app-server/src/client.ts b/packages/effect-codex-app-server/src/client.ts new file mode 100644 index 0000000000..9821fef8d8 --- /dev/null +++ b/packages/effect-codex-app-server/src/client.ts @@ -0,0 +1,300 @@ +import * as Context from "effect/Context"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import * as Schema from "effect/Schema"; +import * as Scope from "effect/Scope"; +import * as Stdio from "effect/Stdio"; +import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process"; + +import * as CodexRpc from "./_generated/meta.gen.ts"; +import * as CodexError from "./errors.ts"; +import * as CodexProtocol from "./protocol.ts"; +import { + decodeNotificationPayload, + decodeOptionalPayload, + encodeOptionalPayload, + runHandler, +} from "./_internal/shared.ts"; +import { makeChildStdio, makeTerminationError } from "./_internal/stdio.ts"; + +export interface CodexAppServerClientOptions { + readonly logIncoming?: boolean; + readonly logOutgoing?: boolean; + readonly logger?: ( + event: CodexProtocol.CodexAppServerProtocolLogEvent, + ) => Effect.Effect; +} + +interface CodexAppServerClientRaw { + readonly notifications: CodexProtocol.CodexAppServerPatchedProtocol["incomingNotifications"]; + readonly requests: CodexProtocol.CodexAppServerPatchedProtocol["incomingRequests"]; + readonly request: CodexProtocol.CodexAppServerPatchedProtocol["request"]; + readonly notify: CodexProtocol.CodexAppServerPatchedProtocol["notify"]; + readonly respond: CodexProtocol.CodexAppServerPatchedProtocol["respond"]; + readonly respondError: CodexProtocol.CodexAppServerPatchedProtocol["respondError"]; +} + +export interface CodexAppServerClientShape { + readonly raw: CodexAppServerClientRaw; + readonly request: ( + method: M, + payload: CodexRpc.ClientRequestParamsByMethod[M], + ) => Effect.Effect; + readonly notify: ( + method: M, + payload: CodexRpc.ClientNotificationParamsByMethod[M], + ) => Effect.Effect; + readonly handleServerRequest: ( + method: M, + handler: ( + payload: CodexRpc.ServerRequestParamsByMethod[M], + ) => Effect.Effect, + ) => Effect.Effect; + readonly handleServerNotification: ( + method: M, + handler: ( + payload: CodexRpc.ServerNotificationParamsByMethod[M], + ) => Effect.Effect, + ) => Effect.Effect; + readonly handleUnknownServerRequest: ( + handler: ( + method: string, + params: unknown, + ) => Effect.Effect, + ) => Effect.Effect; + readonly handleUnknownServerNotification: ( + handler: ( + method: string, + params: unknown, + ) => Effect.Effect, + ) => Effect.Effect; +} + +export class CodexAppServerClient extends Context.Service< + CodexAppServerClient, + CodexAppServerClientShape +>()("effect-codex-app-server/CodexAppServerClient") {} + +type ServerRequestHandler = ( + payload: unknown, +) => Effect.Effect; +type ServerNotificationHandler = ( + payload: unknown, +) => Effect.Effect; + +export const make = Effect.fn("effect-codex-app-server/CodexAppServerClient.make")(function* ( + stdio: Stdio.Stdio, + options: CodexAppServerClientOptions = {}, + terminationError?: Effect.Effect, +): Effect.fn.Return { + const requestHandlers = new Map(); + const notificationHandlers = new Map>(); + let unknownRequestHandler: + | ((method: string, params: unknown) => Effect.Effect) + | undefined; + let unknownNotificationHandler: + | ((method: string, params: unknown) => Effect.Effect) + | undefined; + + const getServerRequestParamSchema = ( + method: M, + ): + | Schema.Codec + | undefined => CodexRpc.SERVER_REQUEST_PARAMS[method] as never; + + const getServerRequestResponseSchema = ( + method: M, + ): + | Schema.Codec< + CodexRpc.ServerRequestResponsesByMethod[M], + CodexRpc.ServerRequestResponsesByMethod[M] + > + | undefined => CodexRpc.SERVER_REQUEST_RESPONSES[method] as never; + + const getClientRequestParamSchema = ( + method: M, + ): + | Schema.Codec + | undefined => CodexRpc.CLIENT_REQUEST_PARAMS[method] as never; + + const getClientRequestResponseSchema = ( + method: M, + ): + | Schema.Codec< + CodexRpc.ClientRequestResponsesByMethod[M], + CodexRpc.ClientRequestResponsesByMethod[M] + > + | undefined => CodexRpc.CLIENT_REQUEST_RESPONSES[method] as never; + + const getClientNotificationParamSchema = ( + method: M, + ): + | Schema.Codec< + CodexRpc.ClientNotificationParamsByMethod[M], + CodexRpc.ClientNotificationParamsByMethod[M] + > + | undefined => CodexRpc.CLIENT_NOTIFICATION_PARAMS[method] as never; + + const dispatchNotification = ( + notification: CodexProtocol.CodexAppServerIncomingNotification, + ): Effect.Effect => { + const schema = + notification.method in CodexRpc.SERVER_NOTIFICATION_PARAMS + ? CodexRpc.SERVER_NOTIFICATION_PARAMS[ + notification.method as CodexRpc.ServerNotificationMethod + ] + : undefined; + const handlers = notificationHandlers.get(notification.method) ?? []; + + if (schema) { + return decodeNotificationPayload(notification.method, schema, notification.params).pipe( + Effect.flatMap((decoded) => + Effect.forEach(handlers, (handler) => handler(decoded), { discard: true }), + ), + Effect.catch(() => Effect.void), + ); + } + + return unknownNotificationHandler + ? unknownNotificationHandler(notification.method, notification.params).pipe( + Effect.catch(() => Effect.void), + ) + : Effect.void; + }; + + const dispatchRequest = ( + request: CodexProtocol.CodexAppServerIncomingRequest, + ): Effect.Effect => { + if (request.method in CodexRpc.SERVER_REQUEST_PARAMS) { + const method = request.method as CodexRpc.ServerRequestMethod; + const payloadSchema = getServerRequestParamSchema(method); + const responseSchema = getServerRequestResponseSchema(method); + const handler = requestHandlers.get(method); + + return decodeOptionalPayload(method, payloadSchema, request.params).pipe( + Effect.flatMap((decoded) => runHandler(handler, decoded, method)), + Effect.flatMap((result) => encodeOptionalPayload(method, responseSchema, result)), + ); + } + + return unknownRequestHandler + ? unknownRequestHandler(request.method, request.params) + : Effect.fail(CodexError.CodexAppServerRequestError.methodNotFound(request.method)); + }; + + const transport = yield* CodexProtocol.makeCodexAppServerPatchedProtocol({ + stdio, + ...(terminationError ? { terminationError } : {}), + ...(options.logIncoming !== undefined ? { logIncoming: options.logIncoming } : {}), + ...(options.logOutgoing !== undefined ? { logOutgoing: options.logOutgoing } : {}), + ...(options.logger ? { logger: options.logger } : {}), + onNotification: dispatchNotification, + onRequest: dispatchRequest, + }); + + const request = ( + method: M, + payload: CodexRpc.ClientRequestParamsByMethod[M], + ): Effect.Effect => + encodeOptionalPayload(method, getClientRequestParamSchema(method), payload).pipe( + Effect.flatMap((encoded) => transport.request(method, encoded)), + Effect.flatMap( + ( + raw, + ): Effect.Effect< + CodexRpc.ClientRequestResponsesByMethod[M], + CodexError.CodexAppServerError + > => decodeOptionalPayload(method, getClientRequestResponseSchema(method), raw), + ), + ); + + const notify = ( + method: M, + payload: CodexRpc.ClientNotificationParamsByMethod[M], + ) => + encodeOptionalPayload(method, getClientNotificationParamSchema(method), payload).pipe( + Effect.flatMap((encoded) => transport.notify(method, encoded)), + ); + + return CodexAppServerClient.of({ + raw: { + notifications: transport.incomingNotifications, + requests: transport.incomingRequests, + request: transport.request, + notify: transport.notify, + respond: transport.respond, + respondError: transport.respondError, + }, + request, + notify, + handleServerRequest: (method, handler) => + Effect.sync(() => { + requestHandlers.set(method, handler as ServerRequestHandler); + }), + handleServerNotification: (method, handler) => + Effect.sync(() => { + const current = notificationHandlers.get(method) ?? []; + current.push(handler as ServerNotificationHandler); + notificationHandlers.set(method, current); + }), + handleUnknownServerRequest: (handler) => + Effect.sync(() => { + unknownRequestHandler = handler; + }), + handleUnknownServerNotification: (handler) => + Effect.sync(() => { + unknownNotificationHandler = handler; + }), + }); +}); + +export const layerChildProcess = ( + handle: ChildProcessSpawner.ChildProcessHandle, + options: CodexAppServerClientOptions = {}, +): Layer.Layer => { + const stdio = makeChildStdio(handle); + const terminationError = makeTerminationError(handle); + return Layer.effect(CodexAppServerClient, make(stdio, options, terminationError)); +}; + +export interface CodexAppServerCommandLayerOptions extends CodexAppServerClientOptions { + readonly command: string; + readonly args?: ReadonlyArray; + readonly cwd?: string; + readonly env?: Record; +} + +export const layerCommand = ( + options: CodexAppServerCommandLayerOptions, +): Layer.Layer< + CodexAppServerClient, + CodexError.CodexAppServerSpawnError, + ChildProcessSpawner.ChildProcessSpawner +> => + Layer.effect( + CodexAppServerClient, + Effect.acquireRelease( + Effect.gen(function* () { + const spawner = yield* ChildProcessSpawner.ChildProcessSpawner; + const command = ChildProcess.make(options.command, [...(options.args ?? [])], { + ...(options.cwd ? { cwd: options.cwd } : {}), + ...(options.env ? { env: { ...process.env, ...options.env } } : {}), + shell: process.platform === "win32", + }); + return yield* spawner.spawn(command).pipe( + Effect.mapError( + (cause) => + new CodexError.CodexAppServerSpawnError({ + command: [options.command, ...(options.args ?? [])].join(" "), + cause, + }), + ), + ); + }), + (handle) => handle.kill().pipe(Effect.orDie), + ).pipe( + Effect.flatMap((handle) => + make(makeChildStdio(handle), options, makeTerminationError(handle)), + ), + ), + ); diff --git a/packages/effect-codex-app-server/src/errors.ts b/packages/effect-codex-app-server/src/errors.ts new file mode 100644 index 0000000000..ff206c2e36 --- /dev/null +++ b/packages/effect-codex-app-server/src/errors.ts @@ -0,0 +1,151 @@ +import * as Schema from "effect/Schema"; + +export interface CodexAppServerProtocolErrorShape { + readonly code: number; + readonly message: string; + readonly data?: unknown; +} + +export class CodexAppServerSpawnError extends Schema.TaggedErrorClass()( + "CodexAppServerSpawnError", + { + command: Schema.optional(Schema.String), + cause: Schema.Defect, + }, +) { + override get message() { + return this.command + ? `Failed to spawn Codex App Server process for command: ${this.command}` + : "Failed to spawn Codex App Server process"; + } +} + +export class CodexAppServerProcessExitedError extends Schema.TaggedErrorClass()( + "CodexAppServerProcessExitedError", + { + code: Schema.optional(Schema.Number), + cause: Schema.optional(Schema.Defect), + }, +) { + override get message() { + return this.code === undefined + ? "Codex App Server process exited" + : `Codex App Server process exited with code ${this.code}`; + } +} + +export class CodexAppServerProtocolParseError extends Schema.TaggedErrorClass()( + "CodexAppServerProtocolParseError", + { + detail: Schema.String, + cause: Schema.optional(Schema.Defect), + }, +) { + override get message() { + return `Failed to parse Codex App Server protocol message: ${this.detail}`; + } +} + +export class CodexAppServerTransportError extends Schema.TaggedErrorClass()( + "CodexAppServerTransportError", + { + detail: Schema.String, + cause: Schema.Defect, + }, +) { + override get message() { + return this.detail; + } +} + +export class CodexAppServerRequestError extends Schema.TaggedErrorClass()( + "CodexAppServerRequestError", + { + code: Schema.Number, + errorMessage: Schema.String, + data: Schema.optional(Schema.Unknown), + }, +) { + override get message() { + return this.errorMessage; + } + + static fromProtocolError(error: CodexAppServerProtocolErrorShape) { + return new CodexAppServerRequestError({ + code: error.code, + errorMessage: error.message, + ...(error.data !== undefined ? { data: error.data } : {}), + }); + } + + static parseError(message = "Parse error", data?: unknown) { + return new CodexAppServerRequestError({ + code: -32700, + errorMessage: message, + ...(data !== undefined ? { data } : {}), + }); + } + + static invalidRequest(message = "Invalid request", data?: unknown) { + return new CodexAppServerRequestError({ + code: -32600, + errorMessage: message, + ...(data !== undefined ? { data } : {}), + }); + } + + static methodNotFound(method: string) { + return new CodexAppServerRequestError({ + code: -32601, + errorMessage: `Method not found: ${method}`, + }); + } + + static invalidParams(message = "Invalid params", data?: unknown) { + return new CodexAppServerRequestError({ + code: -32602, + errorMessage: message, + ...(data !== undefined ? { data } : {}), + }); + } + + static internalError(message = "Internal error", data?: unknown) { + return new CodexAppServerRequestError({ + code: -32603, + errorMessage: message, + ...(data !== undefined ? { data } : {}), + }); + } + + static overloaded(message = "Server overloaded; retry later.", data?: unknown) { + return new CodexAppServerRequestError({ + code: -32001, + errorMessage: message, + ...(data !== undefined ? { data } : {}), + }); + } + + toProtocolError(): CodexAppServerProtocolErrorShape { + return { + code: this.code, + message: this.errorMessage, + ...(this.data !== undefined ? { data: this.data } : {}), + }; + } +} + +export const CodexAppServerError = Schema.Union([ + CodexAppServerRequestError, + CodexAppServerSpawnError, + CodexAppServerProcessExitedError, + CodexAppServerProtocolParseError, + CodexAppServerTransportError, +]); + +export type CodexAppServerError = typeof CodexAppServerError.Type; + +export function normalizeToRequestError(error: CodexAppServerError): CodexAppServerRequestError { + return Schema.is(CodexAppServerRequestError)(error) + ? error + : CodexAppServerRequestError.internalError(error.message); +} diff --git a/packages/effect-codex-app-server/src/protocol.test.ts b/packages/effect-codex-app-server/src/protocol.test.ts new file mode 100644 index 0000000000..b0f2fd503e --- /dev/null +++ b/packages/effect-codex-app-server/src/protocol.test.ts @@ -0,0 +1,197 @@ +import * as Deferred from "effect/Deferred"; +import * as Effect from "effect/Effect"; +import * as Fiber from "effect/Fiber"; +import * as Queue from "effect/Queue"; +import * as Stream from "effect/Stream"; + +import * as NodeServices from "@effect/platform-node/NodeServices"; +import { assert, it } from "@effect/vitest"; + +import * as CodexError from "./errors.ts"; +import * as CodexProtocol from "./protocol.ts"; +import { makeInMemoryStdio } from "./_internal/stdio.ts"; + +const encoder = new TextEncoder(); + +const encodeJsonl = (value: unknown) => encoder.encode(`${JSON.stringify(value)}\n`); + +it.layer(NodeServices.layer)("effect-codex-app-server protocol", (it) => { + it.effect( + "encodes requests without a jsonrpc field and routes inbound requests and notifications", + () => + Effect.gen(function* () { + const { stdio, input, output } = yield* makeInMemoryStdio(); + const transport = yield* CodexProtocol.makeCodexAppServerPatchedProtocol({ stdio }); + + const notificationDeferred = + yield* Deferred.make>(); + const requestDeferred = + yield* Deferred.make>(); + + yield* transport.incomingNotifications.pipe( + Stream.take(1), + Stream.runCollect, + Effect.flatMap((notifications) => Deferred.succeed(notificationDeferred, notifications)), + Effect.forkScoped, + ); + + yield* transport.incomingRequests.pipe( + Stream.take(1), + Stream.runCollect, + Effect.flatMap((requests) => Deferred.succeed(requestDeferred, requests)), + Effect.forkScoped, + ); + + yield* transport.notify("initialized"); + assert.equal(yield* Queue.take(output), '{"method":"initialized"}\n'); + + const initializeParams = { + clientInfo: { + name: "effect-codex-app-server-test", + title: "Effect Codex App Server Test", + version: "0.0.0", + }, + capabilities: { + experimentalApi: true, + optOutNotificationMethods: null, + }, + }; + + const pendingInitialize = yield* transport + .request("initialize", initializeParams) + .pipe(Effect.forkScoped); + assert.deepEqual(JSON.parse(yield* Queue.take(output)), { + id: 1, + method: "initialize", + params: initializeParams, + }); + + yield* Queue.offer( + input, + encodeJsonl({ + method: "item/agentMessage/delta", + params: { + delta: "Hello from the mock peer.", + itemId: "item-1", + threadId: "thread-1", + turnId: "turn-1", + }, + }), + ); + yield* Queue.offer( + input, + encodeJsonl({ + id: 77, + method: "item/tool/requestUserInput", + params: { + itemId: "item-approval-1", + threadId: "thread-1", + turnId: "turn-1", + questions: [ + { + id: "approved", + header: "Approve", + question: "Continue?", + }, + ], + }, + }), + ); + yield* Queue.offer( + input, + encodeJsonl({ + id: 1, + result: { + userAgent: "mock-codex-app-server", + codexHome: "/tmp/codex-home", + platformFamily: "unix", + platformOs: "macos", + }, + }), + ); + + assert.deepEqual(yield* Fiber.join(pendingInitialize), { + userAgent: "mock-codex-app-server", + codexHome: "/tmp/codex-home", + platformFamily: "unix", + platformOs: "macos", + }); + assert.deepEqual(yield* Deferred.await(notificationDeferred), [ + { + method: "item/agentMessage/delta", + params: { + delta: "Hello from the mock peer.", + itemId: "item-1", + threadId: "thread-1", + turnId: "turn-1", + }, + }, + ]); + assert.deepEqual(yield* Deferred.await(requestDeferred), [ + { + id: 77, + method: "item/tool/requestUserInput", + params: { + itemId: "item-approval-1", + threadId: "thread-1", + turnId: "turn-1", + questions: [ + { + id: "approved", + header: "Approve", + question: "Continue?", + }, + ], + }, + }, + ]); + + yield* transport.respond(77, { + answers: { + approved: { + answers: ["yes"], + }, + }, + }); + assert.deepEqual(JSON.parse(yield* Queue.take(output)), { + id: 77, + result: { + answers: { + approved: { + answers: ["yes"], + }, + }, + }, + }); + + yield* transport.respondError( + 78, + CodexError.CodexAppServerRequestError.methodNotFound("x/test"), + ); + assert.deepEqual(JSON.parse(yield* Queue.take(output)), { + id: 78, + error: { + code: -32601, + message: "Method not found: x/test", + }, + }); + }), + ); + + it.effect("surfaces JSON encoding failures as protocol parse errors", () => + Effect.gen(function* () { + const { stdio } = yield* makeInMemoryStdio(); + const transport = yield* CodexProtocol.makeCodexAppServerPatchedProtocol({ stdio }); + + const bigintError = yield* transport.notify("x/test", 1n).pipe(Effect.flip); + assert.instanceOf(bigintError, CodexError.CodexAppServerProtocolParseError); + assert.equal(bigintError.detail, "Failed to encode Codex App Server message"); + + const circular: Record = {}; + circular.self = circular; + const circularError = yield* transport.notify("x/test", circular).pipe(Effect.flip); + assert.instanceOf(circularError, CodexError.CodexAppServerProtocolParseError); + assert.equal(circularError.detail, "Failed to encode Codex App Server message"); + }), + ); +}); diff --git a/packages/effect-codex-app-server/src/protocol.ts b/packages/effect-codex-app-server/src/protocol.ts new file mode 100644 index 0000000000..0b730aa988 --- /dev/null +++ b/packages/effect-codex-app-server/src/protocol.ts @@ -0,0 +1,394 @@ +import * as Cause from "effect/Cause"; +import * as Deferred from "effect/Deferred"; +import * as Effect from "effect/Effect"; +import * as Queue from "effect/Queue"; +import * as Ref from "effect/Ref"; +import * as Scope from "effect/Scope"; +import * as Schema from "effect/Schema"; +import * as Stdio from "effect/Stdio"; +import * as Stream from "effect/Stream"; + +import * as CodexError from "./errors.ts"; +import { JsonRpcId, JsonRpcResponseEnvelope } from "./_internal/shared.ts"; + +export interface CodexAppServerProtocolLogEvent { + readonly direction: "incoming" | "outgoing"; + readonly stage: "raw" | "decoded" | "decode_failed"; + readonly payload: unknown; +} + +export interface CodexAppServerIncomingNotification { + readonly method: string; + readonly params?: unknown; +} + +export interface CodexAppServerIncomingRequest { + readonly id: string | number; + readonly method: string; + readonly params?: unknown; +} + +export interface CodexAppServerPatchedProtocolOptions { + readonly stdio: Stdio.Stdio; + readonly terminationError?: Effect.Effect; + readonly logIncoming?: boolean; + readonly logOutgoing?: boolean; + readonly logger?: (event: CodexAppServerProtocolLogEvent) => Effect.Effect; + readonly onNotification?: ( + notification: CodexAppServerIncomingNotification, + ) => Effect.Effect; + readonly onRequest?: ( + request: CodexAppServerIncomingRequest, + ) => Effect.Effect; + readonly onTermination?: (error: CodexError.CodexAppServerError) => Effect.Effect; +} + +export interface CodexAppServerPatchedProtocol { + readonly incomingNotifications: Stream.Stream; + readonly incomingRequests: Stream.Stream; + readonly request: ( + method: string, + payload?: unknown, + ) => Effect.Effect; + readonly notify: ( + method: string, + payload?: unknown, + ) => Effect.Effect; + readonly respond: ( + requestId: string | number, + result: unknown, + ) => Effect.Effect; + readonly respondError: ( + requestId: string | number, + error: CodexError.CodexAppServerRequestError, + ) => Effect.Effect; +} + +function isObject(value: unknown): value is Record { + return typeof value === "object" && value !== null; +} + +function isIncomingRequest(value: unknown): value is CodexAppServerIncomingRequest { + if (!isObject(value) || typeof value.method !== "string") { + return false; + } + return Schema.is(JsonRpcId)(value.id); +} + +function isIncomingNotification(value: unknown): value is CodexAppServerIncomingNotification { + return isObject(value) && typeof value.method === "string" && !("id" in value); +} + +function isIncomingResponse(value: unknown): value is typeof JsonRpcResponseEnvelope.Type { + return Schema.is(JsonRpcResponseEnvelope)(value); +} + +const encodeWireMessage = ( + message: Record, +): Effect.Effect => + Effect.try({ + try: () => `${JSON.stringify(message)}\n`, + catch: (cause) => + new CodexError.CodexAppServerProtocolParseError({ + detail: "Failed to encode Codex App Server message", + cause, + }), + }); + +const normalizeIncomingError = (error: unknown, detail: string): CodexError.CodexAppServerError => + Schema.is(CodexError.CodexAppServerError)(error) + ? error + : new CodexError.CodexAppServerTransportError({ + detail, + cause: error, + }); + +const toProtocolMessage = ( + requestId: string | number, + fields: { + readonly result?: unknown; + readonly error?: CodexError.CodexAppServerProtocolErrorShape; + }, +): { readonly [key: string]: unknown } => ({ + id: requestId, + ...(fields.result !== undefined ? { result: fields.result } : {}), + ...(fields.error !== undefined ? { error: fields.error } : {}), +}); + +export const makeCodexAppServerPatchedProtocol = Effect.fn("makeCodexAppServerPatchedProtocol")( + function* ( + options: CodexAppServerPatchedProtocolOptions, + ): Effect.fn.Return { + const outgoing = yield* Queue.unbounded>(); + const incomingNotifications = yield* Queue.unbounded(); + const incomingRequests = yield* Queue.unbounded(); + const pending = yield* Ref.make( + new Map>(), + ); + const nextRequestId = yield* Ref.make(1); + const remainder = yield* Ref.make(""); + const terminationHandled = yield* Ref.make(false); + + const logProtocol = (event: CodexAppServerProtocolLogEvent) => { + if (event.direction === "incoming" && !options.logIncoming) { + return Effect.void; + } + if (event.direction === "outgoing" && !options.logOutgoing) { + return Effect.void; + } + return ( + options.logger?.(event) ?? + Effect.logDebug("Codex App Server protocol event").pipe(Effect.annotateLogs({ event })) + ); + }; + + const failAllPending = (error: CodexError.CodexAppServerError) => + Ref.get(pending).pipe( + Effect.flatMap((current) => + Effect.forEach([...current.values()], (deferred) => Deferred.fail(deferred, error), { + discard: true, + }), + ), + Effect.andThen(Ref.set(pending, new Map())), + ); + + const handleTermination = (classify: () => Effect.Effect) => + Ref.modify(terminationHandled, (handled) => { + if (handled) { + return [Effect.void, true] as const; + } + return [ + Effect.gen(function* () { + const error = yield* classify(); + yield* failAllPending(error); + yield* Queue.end(outgoing); + if (options.onTermination) { + yield* options.onTermination(error); + } + }), + true, + ] as const; + }).pipe(Effect.flatten); + + const offerOutgoing = (message: Record) => + Effect.gen(function* () { + yield* logProtocol({ + direction: "outgoing", + stage: "decoded", + payload: message, + }); + const encoded = yield* encodeWireMessage(message); + yield* logProtocol({ + direction: "outgoing", + stage: "raw", + payload: encoded, + }); + yield* Queue.offer(outgoing, encoded).pipe(Effect.asVoid); + }); + + const removePending = (requestId: string) => + Ref.update(pending, (current) => { + if (!current.has(requestId)) { + return current; + } + const next = new Map(current); + next.delete(requestId); + return next; + }); + + const resolvePending = ( + requestId: string, + handler: ( + deferred: Deferred.Deferred, + ) => Effect.Effect, + ) => + Ref.modify(pending, (current) => { + const deferred = current.get(requestId); + if (!deferred) { + return [Effect.void, current] as const; + } + const next = new Map(current); + next.delete(requestId); + return [handler(deferred), next] as const; + }).pipe(Effect.flatten); + + const respond = (requestId: string | number, result: unknown) => + offerOutgoing(toProtocolMessage(requestId, { result })); + + const respondError = ( + requestId: string | number, + error: CodexError.CodexAppServerRequestError, + ) => offerOutgoing(toProtocolMessage(requestId, { error: error.toProtocolError() })); + + const handleResponse = (response: typeof JsonRpcResponseEnvelope.Type) => { + const requestId = String(response.id); + const protocolError = response.error; + if (protocolError !== undefined) { + return resolvePending(requestId, (deferred) => + Deferred.fail( + deferred, + CodexError.CodexAppServerRequestError.fromProtocolError(protocolError), + ), + ); + } + return resolvePending(requestId, (deferred) => Deferred.succeed(deferred, response.result)); + }; + + const handleRequest = (request: CodexAppServerIncomingRequest) => + Queue.offer(incomingRequests, request).pipe( + Effect.andThen( + options.onRequest + ? options.onRequest(request).pipe( + Effect.matchEffect({ + onFailure: (error) => + respondError(request.id, CodexError.normalizeToRequestError(error)), + onSuccess: (result) => respond(request.id, result), + }), + ) + : Effect.void, + ), + Effect.asVoid, + ); + + const handleNotification = (notification: CodexAppServerIncomingNotification) => + Queue.offer(incomingNotifications, notification).pipe( + Effect.andThen(options.onNotification ? options.onNotification(notification) : Effect.void), + Effect.asVoid, + ); + + const routeMessage = ( + message: unknown, + ): Effect.Effect => { + if (isIncomingRequest(message)) { + return handleRequest(message); + } + if (isIncomingNotification(message)) { + return handleNotification(message); + } + if (isIncomingResponse(message)) { + return handleResponse(message); + } + return Effect.fail( + new CodexError.CodexAppServerProtocolParseError({ + detail: "Received protocol message in an unknown shape", + }), + ); + }; + + const handleLine = (line: string): Effect.Effect => { + if (line.trim().length === 0) { + return Effect.void; + } + return logProtocol({ + direction: "incoming", + stage: "raw", + payload: line, + }).pipe( + Effect.flatMap(() => + Effect.try({ + try: () => JSON.parse(line), + catch: (cause) => + new CodexError.CodexAppServerProtocolParseError({ + detail: "Failed to decode Codex App Server wire message", + cause, + }), + }), + ), + Effect.tap((decoded) => + logProtocol({ + direction: "incoming", + stage: "decoded", + payload: decoded, + }), + ), + Effect.tapErrorTag("CodexAppServerProtocolParseError", (error) => + logProtocol({ + direction: "incoming", + stage: "decode_failed", + payload: { + detail: error.detail, + cause: error.cause, + }, + }), + ), + Effect.flatMap(routeMessage), + ); + }; + + yield* options.stdio.stdin.pipe( + Stream.decodeText(), + Stream.runForEach((chunk) => + Ref.modify(remainder, (current) => { + const combined = current + chunk; + const lines = combined.split("\n"); + const nextRemainder = lines.pop() ?? ""; + return [lines.map((line) => line.replace(/\r$/, "")), nextRemainder] as const; + }).pipe(Effect.flatMap((lines) => Effect.forEach(lines, handleLine, { discard: true }))), + ), + Effect.matchEffect({ + onFailure: (error) => + handleTermination(() => + Effect.succeed(normalizeIncomingError(error, "Codex App Server input stream failed")), + ), + onSuccess: () => + Ref.get(remainder).pipe( + Effect.flatMap((line) => (line.trim().length === 0 ? Effect.void : handleLine(line))), + Effect.matchEffect({ + onFailure: (error) => handleTermination(() => Effect.succeed(error)), + onSuccess: () => + handleTermination( + () => + options.terminationError ?? + Effect.succeed( + new CodexError.CodexAppServerTransportError({ + detail: "Codex App Server input stream ended", + cause: new Error("Codex App Server input stream ended"), + }), + ), + ), + }), + ), + }), + Effect.forkScoped, + ); + + yield* Stream.fromQueue(outgoing).pipe(Stream.run(options.stdio.stdout()), Effect.forkScoped); + + const request = (method: string, payload?: unknown) => + Effect.gen(function* () { + const requestId = yield* Ref.modify( + nextRequestId, + (current) => [current, current + 1] as const, + ); + const deferred = yield* Deferred.make(); + yield* Ref.update(pending, (current) => new Map(current).set(String(requestId), deferred)); + yield* offerOutgoing({ + id: requestId, + method, + ...(payload !== undefined ? { params: payload } : {}), + }).pipe( + Effect.catch((error) => + removePending(String(requestId)).pipe(Effect.andThen(Effect.fail(error))), + ), + ); + return yield* Deferred.await(deferred).pipe( + Effect.onInterrupt(() => removePending(String(requestId))), + ); + }); + + const notify = (method: string, payload?: unknown) => + offerOutgoing({ + method, + ...(payload !== undefined ? { params: payload } : {}), + }); + + return { + incomingNotifications: Stream.fromQueue(incomingNotifications), + incomingRequests: Stream.fromQueue(incomingRequests), + request, + notify, + respond, + respondError, + } satisfies CodexAppServerPatchedProtocol; + }, +); diff --git a/packages/effect-codex-app-server/src/rpc.ts b/packages/effect-codex-app-server/src/rpc.ts new file mode 100644 index 0000000000..21dca8a7ea --- /dev/null +++ b/packages/effect-codex-app-server/src/rpc.ts @@ -0,0 +1 @@ +export * from "./_generated/meta.gen.ts"; diff --git a/packages/effect-codex-app-server/src/schema.ts b/packages/effect-codex-app-server/src/schema.ts new file mode 100644 index 0000000000..2d5349752a --- /dev/null +++ b/packages/effect-codex-app-server/src/schema.ts @@ -0,0 +1,3 @@ +export * from "./_generated/schema.gen.ts"; +export * from "./_generated/meta.gen.ts"; +export * from "./_generated/namespaces.gen.ts"; diff --git a/packages/effect-codex-app-server/test/examples/codex-app-server-probe.ts b/packages/effect-codex-app-server/test/examples/codex-app-server-probe.ts new file mode 100644 index 0000000000..a727c2ab03 --- /dev/null +++ b/packages/effect-codex-app-server/test/examples/codex-app-server-probe.ts @@ -0,0 +1,62 @@ +import * as Console from "effect/Console"; +import * as Effect from "effect/Effect"; + +import * as NodeRuntime from "@effect/platform-node/NodeRuntime"; +import * as NodeServices from "@effect/platform-node/NodeServices"; + +import * as CodexClient from "../../src/client.ts"; + +const program = Effect.gen(function* () { + const codexLayer = CodexClient.layerCommand({ + command: process.env.CODEX_BIN ?? "codex", + args: ["app-server"], + cwd: process.cwd(), + logIncoming: true, + logOutgoing: true, + }); + + yield* Effect.gen(function* () { + const client = yield* CodexClient.CodexAppServerClient; + + yield* client.handleServerRequest("item/tool/requestUserInput", (payload) => + Effect.succeed({ + answers: Object.fromEntries( + payload.questions.map((question) => [ + question.id, + { + answers: + question.options && question.options.length > 0 + ? [question.options[0]!.label] + : ["ok"], + }, + ]), + ), + }), + ); + + const initialized = yield* client.request("initialize", { + clientInfo: { + name: "effect-codex-app-server-probe", + title: "Effect Codex App Server Probe", + version: "0.0.0", + }, + capabilities: { + experimentalApi: true, + optOutNotificationMethods: null, + }, + }); + yield* Console.log("initialize", JSON.stringify(initialized, null, 2)); + + yield* client.notify("initialized", undefined); + + const account = yield* client.request("account/read", {}); + yield* Console.log("account/read", JSON.stringify(account, null, 2)); + + const skills = yield* client.request("skills/list", { + cwds: [process.cwd()], + }); + yield* Console.log("skills/list", JSON.stringify(skills, null, 2)); + }).pipe(Effect.provide(codexLayer)); +}); + +program.pipe(Effect.scoped, Effect.provide(NodeServices.layer), NodeRuntime.runMain); diff --git a/packages/effect-codex-app-server/test/fixtures/codex-app-server-mock-peer.ts b/packages/effect-codex-app-server/test/fixtures/codex-app-server-mock-peer.ts new file mode 100644 index 0000000000..51668b5e24 --- /dev/null +++ b/packages/effect-codex-app-server/test/fixtures/codex-app-server-mock-peer.ts @@ -0,0 +1,144 @@ +let nextServerRequestId = 10_000; +let pendingSkillsListRequestId: number | string | null = null; +let pendingUserInputRequestId: number | null = null; + +const writeMessage = (message: unknown) => { + process.stdout.write(`${JSON.stringify(message)}\n`); +}; + +const respond = (id: number | string, result: unknown) => { + writeMessage({ id, result }); +}; + +const respondError = (id: number | string, code: number, message: string) => { + writeMessage({ + id, + error: { + code, + message, + }, + }); +}; + +const sendRequest = (method: string, params: unknown) => { + const id = nextServerRequestId++; + writeMessage({ id, method, params }); + return id; +}; + +const handleMethod = (message: Record) => { + const method = message.method; + if (typeof method !== "string") { + return; + } + + switch (method) { + case "initialize": { + respond(message.id as number | string, { + userAgent: "mock-codex-app-server", + codexHome: process.cwd(), + platformFamily: process.platform === "win32" ? "windows" : "unix", + platformOs: process.platform === "darwin" ? "macos" : process.platform, + }); + return; + } + case "initialized": { + writeMessage({ + method: "item/agentMessage/delta", + params: { + delta: "Mock server is ready.", + itemId: "item-1", + threadId: "thread-1", + turnId: "turn-1", + }, + }); + return; + } + case "account/read": { + respond(message.id as number | string, { + account: { + type: "chatgpt", + email: "mock@example.com", + planType: "plus", + }, + requiresOpenaiAuth: false, + }); + return; + } + case "skills/list": { + pendingSkillsListRequestId = message.id as number | string; + pendingUserInputRequestId = sendRequest("item/tool/requestUserInput", { + itemId: "item-approval-1", + threadId: "thread-1", + turnId: "turn-1", + questions: [ + { + id: "approved", + header: "Approve", + question: "Continue with the mock skills request?", + options: [ + { + label: "yes", + description: "Approve the request", + }, + ], + }, + ], + }); + return; + } + default: { + if (message.id !== undefined) { + respondError(message.id as number | string, -32601, `Unhandled request: ${method}`); + } + } + } +}; + +const handleResponse = (message: Record) => { + if (message.id !== pendingUserInputRequestId) { + return; + } + + pendingUserInputRequestId = null; + + respond(pendingSkillsListRequestId!, { + data: [ + { + cwd: process.cwd(), + errors: [], + skills: [], + }, + ], + }); + pendingSkillsListRequestId = null; +}; + +let remainder = ""; + +process.stdin.setEncoding("utf8"); +process.stdin.on("data", (chunk) => { + remainder += chunk; + const lines = remainder.split("\n"); + remainder = lines.pop() ?? ""; + + for (const line of lines) { + const trimmed = line.trim(); + if (trimmed.length === 0) { + continue; + } + + const message = JSON.parse(trimmed) as Record; + if ("method" in message) { + handleMethod(message); + continue; + } + if ("id" in message) { + handleResponse(message); + } + } +}); + +process.stdin.on("end", () => { + process.exit(0); +}); diff --git a/packages/effect-codex-app-server/tsconfig.json b/packages/effect-codex-app-server/tsconfig.json new file mode 100644 index 0000000000..61162f9454 --- /dev/null +++ b/packages/effect-codex-app-server/tsconfig.json @@ -0,0 +1,18 @@ +{ + "extends": "../../tsconfig.base.json", + "compilerOptions": { + "plugins": [ + { + "name": "@effect/language-service", + "namespaceImportPackages": ["@effect/platform-node"], + "diagnosticSeverity": { + "importFromBarrel": "error", + "anyUnknownInErrorContext": "warning", + "instanceOfSchema": "warning", + "deterministicKeys": "warning" + } + } + ] + }, + "include": ["src", "scripts", "test"] +} diff --git a/scripts/release-smoke.ts b/scripts/release-smoke.ts index 362771d12e..1736abab37 100644 --- a/scripts/release-smoke.ts +++ b/scripts/release-smoke.ts @@ -25,6 +25,7 @@ const workspaceFiles = [ "packages/contracts/package.json", "packages/shared/package.json", "packages/effect-acp/package.json", + "packages/effect-codex-app-server/package.json", "scripts/package.json", ] as const; From 306ec4bb842fac22099192e964334fbf5368ad84 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sun, 19 Apr 2026 22:56:44 -0700 Subject: [PATCH 08/82] Refactor OpenCode lifecycle and structured output handling (#2218) Co-authored-by: Claude Opus 4.7 --- .../git/Layers/OpenCodeTextGeneration.test.ts | 130 +- .../src/git/Layers/OpenCodeTextGeneration.ts | 113 +- .../provider/Layers/OpenCodeAdapter.test.ts | 253 ++-- .../src/provider/Layers/OpenCodeAdapter.ts | 1218 +++++++++-------- .../provider/Layers/OpenCodeProvider.test.ts | 147 +- .../src/provider/Layers/OpenCodeProvider.ts | 474 ++++--- .../src/provider/Layers/ProviderRegistry.ts | 2 + .../src/provider/opencodeRuntime.test.ts | 37 - apps/server/src/provider/opencodeRuntime.ts | 741 +++++----- apps/server/src/server.test.ts | 9 +- apps/server/src/server.ts | 2 + .../components/chat/TraitsPicker.browser.tsx | 43 +- apps/web/src/components/chat/TraitsPicker.tsx | 24 +- packages/shared/src/model.ts | 2 +- 14 files changed, 1732 insertions(+), 1463 deletions(-) delete mode 100644 apps/server/src/provider/opencodeRuntime.test.ts diff --git a/apps/server/src/git/Layers/OpenCodeTextGeneration.test.ts b/apps/server/src/git/Layers/OpenCodeTextGeneration.test.ts index ab98024567..28ee0a3e6f 100644 --- a/apps/server/src/git/Layers/OpenCodeTextGeneration.test.ts +++ b/apps/server/src/git/Layers/OpenCodeTextGeneration.test.ts @@ -1,18 +1,22 @@ -import type { ChildProcess } from "node:child_process"; - import * as NodeServices from "@effect/platform-node/NodeServices"; import { it } from "@effect/vitest"; import { Duration, Effect, Layer } from "effect"; import { TestClock } from "effect/testing"; -import { beforeEach, expect, vi } from "vitest"; +import { NetService } from "@t3tools/shared/Net"; +import { beforeEach, expect } from "vitest"; import { ServerConfig } from "../../config.ts"; import { ServerSettingsService } from "../../serverSettings.ts"; +import { + OpenCodeRuntime, + OpenCodeRuntimeError, + type OpenCodeRuntimeShape, +} from "../../provider/opencodeRuntime.ts"; import { TextGeneration } from "../Services/TextGeneration.ts"; import { OpenCodeTextGenerationLive } from "./OpenCodeTextGeneration.ts"; -const runtimeMock = vi.hoisted(() => { - const state = { +const runtimeMock = { + state: { startCalls: [] as string[], promptUrls: [] as string[], authHeaders: [] as Array, @@ -20,69 +24,77 @@ const runtimeMock = vi.hoisted(() => { promptResult: undefined as | { data?: { info?: { error?: unknown }; parts?: Array<{ type: string; text?: string }> } } | undefined, - }; + }, + reset() { + this.state.startCalls.length = 0; + this.state.promptUrls.length = 0; + this.state.authHeaders.length = 0; + this.state.closeCalls.length = 0; + this.state.promptResult = undefined; + }, +}; - return { - state, - reset() { - state.startCalls.length = 0; - state.promptUrls.length = 0; - state.authHeaders.length = 0; - state.closeCalls.length = 0; - state.promptResult = undefined; - }, - }; -}); - -vi.mock("../../provider/opencodeRuntime.ts", async () => { - const actual = await vi.importActual( - "../../provider/opencodeRuntime.ts", - ); - - return { - ...actual, - startOpenCodeServerProcess: vi.fn(async ({ binaryPath }: { binaryPath: string }) => { +const OpenCodeRuntimeTestDouble: OpenCodeRuntimeShape = { + startOpenCodeServerProcess: ({ binaryPath }) => + Effect.gen(function* () { const index = runtimeMock.state.startCalls.length + 1; const url = `http://127.0.0.1:${4_300 + index}`; runtimeMock.state.startCalls.push(binaryPath); + // The production runtime binds server lifetime to the caller's scope. + // Mirror that here so the closeCalls probe observes scope close. + yield* Effect.addFinalizer(() => + Effect.sync(() => { + runtimeMock.state.closeCalls.push(url); + }), + ); return { url, - process: {} as ChildProcess, - close: () => { - runtimeMock.state.closeCalls.push(url); - }, + exitCode: Effect.never, }; }), - createOpenCodeSdkClient: vi.fn( - ({ baseUrl, serverPassword }: { baseUrl: string; serverPassword?: string }) => ({ - session: { - create: vi.fn(async () => ({ data: { id: `${baseUrl}/session` } })), - prompt: vi.fn(async () => { - runtimeMock.state.promptUrls.push(baseUrl); - runtimeMock.state.authHeaders.push( - serverPassword ? `Basic ${btoa(`opencode:${serverPassword}`)}` : null, - ); - return ( - runtimeMock.state.promptResult ?? { - data: { - parts: [ - { - type: "text", - text: JSON.stringify({ - subject: "Improve OpenCode reuse", - body: "Reuse one server for the full action.", - }), - }, - ], - }, - } - ); - }), + connectToOpenCodeServer: ({ serverUrl }) => + Effect.succeed({ + url: serverUrl ?? "http://127.0.0.1:4301", + exitCode: null, + external: Boolean(serverUrl), + }), + runOpenCodeCommand: () => Effect.succeed({ stdout: "", stderr: "", code: 0 }), + createOpenCodeSdkClient: ({ baseUrl, serverPassword }) => + ({ + session: { + create: async () => ({ data: { id: `${baseUrl}/session` } }), + prompt: async () => { + runtimeMock.state.promptUrls.push(baseUrl); + runtimeMock.state.authHeaders.push( + serverPassword ? `Basic ${btoa(`opencode:${serverPassword}`)}` : null, + ); + return ( + runtimeMock.state.promptResult ?? { + data: { + parts: [ + { + type: "text", + text: JSON.stringify({ + subject: "Improve OpenCode reuse", + body: "Reuse one server for the full action.", + }), + }, + ], + }, + } + ); }, + }, + }) as unknown as ReturnType, + loadOpenCodeInventory: () => + Effect.fail( + new OpenCodeRuntimeError({ + operation: "loadOpenCodeInventory", + detail: "OpenCodeRuntimeTestDouble.loadOpenCodeInventory not used in this test", + cause: null, }), ), - }; -}); +}; const DEFAULT_TEST_MODEL_SELECTION = { provider: "opencode" as const, @@ -92,6 +104,7 @@ const DEFAULT_TEST_MODEL_SELECTION = { const OPENCODE_TEXT_GENERATION_IDLE_TTL_MS = 30_000; const OpenCodeTextGenerationTestLayer = OpenCodeTextGenerationLive.pipe( + Layer.provideMerge(Layer.succeed(OpenCodeRuntime, OpenCodeRuntimeTestDouble)), Layer.provideMerge( ServerSettingsService.layerTest({ providers: { @@ -106,10 +119,12 @@ const OpenCodeTextGenerationTestLayer = OpenCodeTextGenerationLive.pipe( prefix: "t3code-opencode-text-generation-test-", }), ), + Layer.provideMerge(NetService.layer), Layer.provideMerge(NodeServices.layer), ); const OpenCodeTextGenerationExistingServerTestLayer = OpenCodeTextGenerationLive.pipe( + Layer.provideMerge(Layer.succeed(OpenCodeRuntime, OpenCodeRuntimeTestDouble)), Layer.provideMerge( ServerSettingsService.layerTest({ providers: { @@ -126,6 +141,7 @@ const OpenCodeTextGenerationExistingServerTestLayer = OpenCodeTextGenerationLive prefix: "t3code-opencode-text-generation-existing-server-test-", }), ), + Layer.provideMerge(NetService.layer), Layer.provideMerge(NodeServices.layer), ); diff --git a/apps/server/src/git/Layers/OpenCodeTextGeneration.ts b/apps/server/src/git/Layers/OpenCodeTextGeneration.ts index d206e59e8d..fd28188d60 100644 --- a/apps/server/src/git/Layers/OpenCodeTextGeneration.ts +++ b/apps/server/src/git/Layers/OpenCodeTextGeneration.ts @@ -1,4 +1,4 @@ -import { Duration, Effect, Exit, Fiber, Layer, Schema, Scope } from "effect"; +import { Effect, Exit, Fiber, Layer, Schema, Scope } from "effect"; import * as Semaphore from "effect/Semaphore"; import { @@ -25,15 +25,15 @@ import { sanitizeThreadTitle, } from "../Utils.ts"; import { - createOpenCodeSdkClient, + OpenCodeRuntime, type OpenCodeServerConnection, type OpenCodeServerProcess, + openCodeRuntimeErrorDetail, parseOpenCodeModelSlug, - startOpenCodeServerProcess, toOpenCodeFileParts, } from "../../provider/opencodeRuntime.ts"; -const OPENCODE_TEXT_GENERATION_IDLE_TTL_MS = 30_000; +const OPENCODE_TEXT_GENERATION_IDLE_TTL = "30 seconds"; function getOpenCodePromptErrorMessage(error: unknown): string | null { if (!error || typeof error !== "object") { @@ -80,6 +80,13 @@ function getOpenCodeTextResponse(parts: ReadonlyArray | undefined): str interface SharedOpenCodeTextGenerationServerState { server: OpenCodeServerProcess | null; + /** + * The scope that owns the shared server's lifetime. Closing this scope + * terminates the OpenCode child process and interrupts any fibers the + * runtime forked during startup. We don't hold a `close()` function on + * the server handle anymore — the scope is the only lifecycle handle. + */ + serverScope: Scope.Closeable | null; binaryPath: string | null; activeRequests: number; idleCloseFiber: Fiber.Fiber | null; @@ -88,24 +95,28 @@ interface SharedOpenCodeTextGenerationServerState { const makeOpenCodeTextGeneration = Effect.gen(function* () { const serverConfig = yield* ServerConfig; const serverSettingsService = yield* ServerSettingsService; + const openCodeRuntime = yield* OpenCodeRuntime; const idleFiberScope = yield* Effect.acquireRelease(Scope.make(), (scope) => Scope.close(scope, Exit.void), ); const sharedServerMutex = yield* Semaphore.make(1); const sharedServerState: SharedOpenCodeTextGenerationServerState = { server: null, + serverScope: null, binaryPath: null, activeRequests: 0, idleCloseFiber: null, }; - const closeSharedServer = (server: OpenCodeServerProcess) => { - if (sharedServerState.server === server) { - sharedServerState.server = null; - sharedServerState.binaryPath = null; + const closeSharedServer = Effect.fn("closeSharedServer")(function* () { + const scope = sharedServerState.serverScope; + sharedServerState.server = null; + sharedServerState.serverScope = null; + sharedServerState.binaryPath = null; + if (scope !== null) { + yield* Scope.close(scope, Exit.void).pipe(Effect.ignore); } - server.close(); - }; + }); const cancelIdleCloseFiber = Effect.fn("cancelIdleCloseFiber")(function* () { const idleCloseFiber = sharedServerState.idleCloseFiber; @@ -119,15 +130,15 @@ const makeOpenCodeTextGeneration = Effect.gen(function* () { server: OpenCodeServerProcess, ) { yield* cancelIdleCloseFiber(); - const fiber = yield* Effect.sleep(Duration.millis(OPENCODE_TEXT_GENERATION_IDLE_TTL_MS)).pipe( + const fiber = yield* Effect.sleep(OPENCODE_TEXT_GENERATION_IDLE_TTL).pipe( Effect.andThen( sharedServerMutex.withPermit( - Effect.sync(() => { + Effect.gen(function* () { if (sharedServerState.server !== server || sharedServerState.activeRequests > 0) { return; } sharedServerState.idleCloseFiber = null; - closeSharedServer(server); + yield* closeSharedServer(); }), ), ), @@ -154,7 +165,7 @@ const makeOpenCodeTextGeneration = Effect.gen(function* () { sharedServerState.binaryPath !== input.binaryPath && sharedServerState.activeRequests === 0 ) { - closeSharedServer(existingServer); + yield* closeSharedServer(); } else { if (sharedServerState.binaryPath !== input.binaryPath) { yield* Effect.logWarning( @@ -170,20 +181,53 @@ const makeOpenCodeTextGeneration = Effect.gen(function* () { } } - const server = yield* Effect.tryPromise({ - try: () => startOpenCodeServerProcess({ binaryPath: input.binaryPath }), - catch: (cause) => - new TextGenerationError({ - operation: input.operation, - detail: cause instanceof Error ? cause.message : "Failed to start OpenCode server.", - cause, - }), - }); + // Create a fresh scope that owns this shared server. The runtime + // will attach its child-process and fiber finalizers to this scope; + // closing it kills the server and interrupts those fibers. + // + // The `Scope.make` / spawn / record-or-close transitions run inside + // `uninterruptibleMask` so an interrupt arriving between any two + // steps can't orphan the scope (and the child process attached to + // it) before we either close it on failure or hand ownership to + // `sharedServerState`. `restore` keeps the actual spawn + // interruptible; an interrupt during the spawn is captured by + // `Effect.exit` and drives us through the failure branch that + // closes the fresh scope. + return yield* Effect.uninterruptibleMask((restore) => + Effect.gen(function* () { + const serverScope = yield* Scope.make(); + const startedExit = yield* Effect.exit( + restore( + openCodeRuntime + .startOpenCodeServerProcess({ + binaryPath: input.binaryPath, + }) + .pipe( + Effect.provideService(Scope.Scope, serverScope), + Effect.mapError( + (cause) => + new TextGenerationError({ + operation: input.operation, + detail: openCodeRuntimeErrorDetail(cause), + cause, + }), + ), + ), + ), + ); + if (startedExit._tag === "Failure") { + yield* Scope.close(serverScope, Exit.void).pipe(Effect.ignore); + return yield* Effect.failCause(startedExit.cause); + } - sharedServerState.server = server; - sharedServerState.binaryPath = input.binaryPath; - sharedServerState.activeRequests = 1; - return server; + const server = startedExit.value; + sharedServerState.server = server; + sharedServerState.serverScope = serverScope; + sharedServerState.binaryPath = input.binaryPath; + sharedServerState.activeRequests = 1; + return server; + }), + ); }), ); @@ -200,17 +244,15 @@ const makeOpenCodeTextGeneration = Effect.gen(function* () { }), ); + // Module-level finalizer: on layer shutdown, cancel the idle close fiber + // and close the shared server scope. Consumers therefore cannot leak + // the shared OpenCode server by forgetting to call anything. yield* Effect.addFinalizer(() => sharedServerMutex.withPermit( Effect.gen(function* () { yield* cancelIdleCloseFiber(); - const server = sharedServerState.server; - sharedServerState.server = null; - sharedServerState.binaryPath = null; sharedServerState.activeRequests = 0; - if (server !== null) { - server.close(); - } + yield* closeSharedServer(); }), ), ); @@ -264,7 +306,7 @@ const makeOpenCodeTextGeneration = Effect.gen(function* () { const runAgainstServer = (server: Pick) => Effect.tryPromise({ try: async () => { - const client = createOpenCodeSdkClient({ + const client = openCodeRuntime.createOpenCodeSdkClient({ baseUrl: server.url, directory: input.cwd, ...(settings.serverUrl.length > 0 && settings.serverPassword @@ -304,8 +346,7 @@ const makeOpenCodeTextGeneration = Effect.gen(function* () { catch: (cause) => new TextGenerationError({ operation: input.operation, - detail: - cause instanceof Error ? cause.message : "OpenCode text generation request failed.", + detail: openCodeRuntimeErrorDetail(cause), cause, }), }); diff --git a/apps/server/src/provider/Layers/OpenCodeAdapter.test.ts b/apps/server/src/provider/Layers/OpenCodeAdapter.test.ts index 98691082cf..9a391b5539 100644 --- a/apps/server/src/provider/Layers/OpenCodeAdapter.test.ts +++ b/apps/server/src/provider/Layers/OpenCodeAdapter.test.ts @@ -3,13 +3,18 @@ import assert from "node:assert/strict"; import * as NodeServices from "@effect/platform-node/NodeServices"; import { it } from "@effect/vitest"; import { Effect, Layer, Option } from "effect"; -import { beforeEach, vi } from "vitest"; +import { beforeEach } from "vitest"; import { ThreadId } from "@t3tools/contracts"; import { ServerConfig } from "../../config.ts"; import { ServerSettingsService } from "../../serverSettings.ts"; import { ProviderSessionDirectory } from "../Services/ProviderSessionDirectory.ts"; import { OpenCodeAdapter } from "../Services/OpenCodeAdapter.ts"; +import { + OpenCodeRuntime, + OpenCodeRuntimeError, + type OpenCodeRuntimeShape, +} from "../opencodeRuntime.ts"; import { appendOpenCodeAssistantTextDelta, makeOpenCodeAdapterLive, @@ -18,16 +23,16 @@ import { const asThreadId = (value: string): ThreadId => ThreadId.make(value); -const runtimeMock = vi.hoisted(() => { - type MessageEntry = { - info: { - id: string; - role: "user" | "assistant"; - }; - parts: Array; +type MessageEntry = { + info: { + id: string; + role: "user" | "assistant"; }; + parts: Array; +}; - const state = { +const runtimeMock = { + state: { startCalls: [] as string[], sessionCreateUrls: [] as string[], authHeaders: [] as Array, @@ -38,105 +43,118 @@ const runtimeMock = vi.hoisted(() => { closeError: null as Error | null, messages: [] as MessageEntry[], subscribedEvents: [] as unknown[], - }; + }, + reset() { + this.state.startCalls.length = 0; + this.state.sessionCreateUrls.length = 0; + this.state.authHeaders.length = 0; + this.state.abortCalls.length = 0; + this.state.closeCalls.length = 0; + this.state.revertCalls.length = 0; + this.state.promptAsyncError = null; + this.state.closeError = null; + this.state.messages = []; + this.state.subscribedEvents = []; + }, +}; - return { - state, - reset() { - state.startCalls.length = 0; - state.sessionCreateUrls.length = 0; - state.authHeaders.length = 0; - state.abortCalls.length = 0; - state.closeCalls.length = 0; - state.revertCalls.length = 0; - state.promptAsyncError = null; - state.closeError = null; - state.messages = []; - state.subscribedEvents = []; - }, - }; -}); - -vi.mock("../opencodeRuntime.ts", async () => { - const actual = - await vi.importActual("../opencodeRuntime.ts"); - - return { - ...actual, - startOpenCodeServerProcess: vi.fn(async ({ binaryPath }: { binaryPath: string }) => { +const OpenCodeRuntimeTestDouble: OpenCodeRuntimeShape = { + startOpenCodeServerProcess: ({ binaryPath }) => + Effect.gen(function* () { runtimeMock.state.startCalls.push(binaryPath); + const url = "http://127.0.0.1:4301"; + yield* Effect.addFinalizer(() => + Effect.sync(() => { + runtimeMock.state.closeCalls.push(url); + if (runtimeMock.state.closeError) { + throw runtimeMock.state.closeError; + } + }), + ); return { - url: "http://127.0.0.1:4301", - process: { - once() {}, - }, - close() {}, + url, + exitCode: Effect.never, }; }), - connectToOpenCodeServer: vi.fn(async ({ serverUrl }: { serverUrl?: string }) => ({ - url: serverUrl ?? "http://127.0.0.1:4301", - process: null, - external: Boolean(serverUrl), - close() { - runtimeMock.state.closeCalls.push(serverUrl ?? "http://127.0.0.1:4301"); - if (runtimeMock.state.closeError) { - throw runtimeMock.state.closeError; - } - }, - })), - createOpenCodeSdkClient: vi.fn( - ({ baseUrl, serverPassword }: { baseUrl: string; serverPassword?: string }) => ({ - session: { - create: vi.fn(async () => { - runtimeMock.state.sessionCreateUrls.push(baseUrl); - runtimeMock.state.authHeaders.push( - serverPassword ? `Basic ${btoa(`opencode:${serverPassword}`)}` : null, - ); - return { data: { id: `${baseUrl}/session` } }; - }), - abort: vi.fn(async ({ sessionID }: { sessionID: string }) => { - runtimeMock.state.abortCalls.push(sessionID); - }), - promptAsync: vi.fn(async () => { - if (runtimeMock.state.promptAsyncError) { - throw runtimeMock.state.promptAsyncError; - } - }), - messages: vi.fn(async () => ({ data: runtimeMock.state.messages })), - revert: vi.fn( - async ({ sessionID, messageID }: { sessionID: string; messageID?: string }) => { - runtimeMock.state.revertCalls.push({ - sessionID, - ...(messageID ? { messageID } : {}), - }); - if (!messageID) { - runtimeMock.state.messages = []; - return; - } + connectToOpenCodeServer: ({ serverUrl }) => + Effect.gen(function* () { + const url = serverUrl ?? "http://127.0.0.1:4301"; + // Unconditionally register a scope finalizer for test observability — + // preserves the `closeCalls` / `closeError` probes that the existing + // suites rely on. Production code never attaches a finalizer to an + // external server (it simply returns `Effect.succeed(...)`). + yield* Effect.addFinalizer(() => + Effect.sync(() => { + runtimeMock.state.closeCalls.push(url); + if (runtimeMock.state.closeError) { + throw runtimeMock.state.closeError; + } + }), + ); + return { + url, + exitCode: null, + external: Boolean(serverUrl), + }; + }), + runOpenCodeCommand: () => Effect.succeed({ stdout: "", stderr: "", code: 0 }), + createOpenCodeSdkClient: ({ baseUrl, serverPassword }) => + ({ + session: { + create: async () => { + runtimeMock.state.sessionCreateUrls.push(baseUrl); + runtimeMock.state.authHeaders.push( + serverPassword ? `Basic ${btoa(`opencode:${serverPassword}`)}` : null, + ); + return { data: { id: `${baseUrl}/session` } }; + }, + abort: async ({ sessionID }: { sessionID: string }) => { + runtimeMock.state.abortCalls.push(sessionID); + }, + promptAsync: async () => { + if (runtimeMock.state.promptAsyncError) { + throw runtimeMock.state.promptAsyncError; + } + }, + messages: async () => ({ data: runtimeMock.state.messages }), + revert: async ({ sessionID, messageID }: { sessionID: string; messageID?: string }) => { + runtimeMock.state.revertCalls.push({ + sessionID, + ...(messageID ? { messageID } : {}), + }); + if (!messageID) { + runtimeMock.state.messages = []; + return; + } - const targetIndex = runtimeMock.state.messages.findIndex( - (entry) => entry.info.id === messageID, - ); - runtimeMock.state.messages = - targetIndex >= 0 - ? runtimeMock.state.messages.slice(0, targetIndex + 1) - : runtimeMock.state.messages; - }, - ), - }, - event: { - subscribe: vi.fn(async () => ({ - stream: (async function* () { - for (const event of runtimeMock.state.subscribedEvents) { - yield event; - } - })(), - })), + const targetIndex = runtimeMock.state.messages.findIndex( + (entry) => entry.info.id === messageID, + ); + runtimeMock.state.messages = + targetIndex >= 0 + ? runtimeMock.state.messages.slice(0, targetIndex + 1) + : runtimeMock.state.messages; }, + }, + event: { + subscribe: async () => ({ + stream: (async function* () { + for (const event of runtimeMock.state.subscribedEvents) { + yield event; + } + })(), + }), + }, + }) as unknown as ReturnType, + loadOpenCodeInventory: () => + Effect.fail( + new OpenCodeRuntimeError({ + operation: "loadOpenCodeInventory", + detail: "OpenCodeRuntimeTestDouble.loadOpenCodeInventory not used in this test", + cause: null, }), ), - }; -}); +}; const providerSessionDirectoryTestLayer = Layer.succeed(ProviderSessionDirectory, { upsert: () => Effect.void, @@ -148,6 +166,7 @@ const providerSessionDirectoryTestLayer = Layer.succeed(ProviderSessionDirectory }); const OpenCodeAdapterTestLayer = makeOpenCodeAdapterLive().pipe( + Layer.provideMerge(Layer.succeed(OpenCodeRuntime, OpenCodeRuntimeTestDouble)), Layer.provideMerge(ServerConfig.layerTest(process.cwd(), process.cwd())), Layer.provideMerge( ServerSettingsService.layerTest({ @@ -211,7 +230,7 @@ it.layer(OpenCodeAdapterTestLayer)("OpenCodeAdapterLive", (it) => { }), ); - it.effect("clears session state when stopAll cleanup fails", () => + it.effect("clears session state even when cleanup finalizers throw", () => Effect.gen(function* () { const adapter = yield* OpenCodeAdapter; yield* adapter.startSession({ @@ -226,11 +245,14 @@ it.layer(OpenCodeAdapterTestLayer)("OpenCodeAdapterLive", (it) => { }); runtimeMock.state.closeError = new Error("close failed"); - const error = yield* adapter.stopAll().pipe(Effect.flip); + // `stopAll` relies on `stopOpenCodeContext`, which is typed as + // never-failing. A throwing finalizer surfaces as a defect — `Effect.exit` + // captures it so the assertions can still run. The key invariant we're + // validating is "the sessions map and close-call probes reflect cleanup + // attempts regardless of finalizer outcome". + yield* Effect.exit(adapter.stopAll()); const sessions = yield* adapter.listSessions(); - assert.equal(error._tag, "ProviderAdapterProcessError"); - assert.equal(error.detail, "Failed to stop 2 OpenCode sessions."); assert.deepEqual(runtimeMock.state.closeCalls, [ "http://127.0.0.1:9999", "http://127.0.0.1:9999", @@ -374,7 +396,10 @@ it.layer(OpenCodeAdapterTestLayer)("OpenCodeAdapterLive", (it) => { close: () => Effect.void, }; - const adapterLayer = makeOpenCodeAdapterLive({ nativeEventLogger }).pipe( + const adapterLayer = makeOpenCodeAdapterLive({ + nativeEventLogger, + }).pipe( + Layer.provideMerge(Layer.succeed(OpenCodeRuntime, OpenCodeRuntimeTestDouble)), Layer.provideMerge(ServerConfig.layerTest(process.cwd(), process.cwd())), Layer.provideMerge( ServerSettingsService.layerTest({ @@ -450,7 +475,10 @@ it.layer(OpenCodeAdapterTestLayer)("OpenCodeAdapterLive", (it) => { close: () => Effect.void, }; - const adapterLayer = makeOpenCodeAdapterLive({ nativeEventLogger }).pipe( + const adapterLayer = makeOpenCodeAdapterLive({ + nativeEventLogger, + }).pipe( + Layer.provideMerge(Layer.succeed(OpenCodeRuntime, OpenCodeRuntimeTestDouble)), Layer.provideMerge(ServerConfig.layerTest(process.cwd(), process.cwd())), Layer.provideMerge( ServerSettingsService.layerTest({ @@ -467,7 +495,13 @@ it.layer(OpenCodeAdapterTestLayer)("OpenCodeAdapterLive", (it) => { Layer.provideMerge(NodeServices.layer), ); - const sessions = yield* Effect.gen(function* () { + // Capture closeCalls *inside* the provided layer scope: the adapter's + // layer finalizer now tears down any live sessions when the layer + // closes (which is exactly what we want for leak prevention), so + // inspecting closeCalls after `Effect.provide` completes would observe + // the teardown — not the behavior under test. We care that the event + // pump kept the session alive while logging was failing. + const { sessions, closeCallsDuringRun } = yield* Effect.gen(function* () { const adapter = yield* OpenCodeAdapter; yield* adapter.startSession({ provider: "opencode", @@ -475,12 +509,15 @@ it.layer(OpenCodeAdapterTestLayer)("OpenCodeAdapterLive", (it) => { runtimeMode: "full-access", }); yield* sleep(10); - return yield* adapter.listSessions(); + return { + sessions: yield* adapter.listSessions(), + closeCallsDuringRun: [...runtimeMock.state.closeCalls], + }; }).pipe(Effect.provide(adapterLayer)); assert.equal(sessions.length, 1); assert.equal(sessions[0]?.threadId, "thread-native-log-failure"); - assert.deepEqual(runtimeMock.state.closeCalls, []); + assert.deepEqual(closeCallsDuringRun, []); }), ); }); diff --git a/apps/server/src/provider/Layers/OpenCodeAdapter.ts b/apps/server/src/provider/Layers/OpenCodeAdapter.ts index 4e3c12ef5d..5081495dcb 100644 --- a/apps/server/src/provider/Layers/OpenCodeAdapter.ts +++ b/apps/server/src/provider/Layers/OpenCodeAdapter.ts @@ -11,7 +11,7 @@ import { TurnId, type UserInputQuestion, } from "@t3tools/contracts"; -import { Cause, Effect, Layer, Queue, Stream } from "effect"; +import { Cause, Effect, Exit, Layer, Queue, Ref, Scope, Stream } from "effect"; import type { OpencodeClient, Part, PermissionRequest, QuestionRequest } from "@opencode-ai/sdk/v2"; import { resolveAttachmentPath } from "../../attachmentStore.ts"; @@ -28,10 +28,12 @@ import { import { OpenCodeAdapter, type OpenCodeAdapterShape } from "../Services/OpenCodeAdapter.ts"; import { buildOpenCodePermissionRules, - connectToOpenCodeServer, - createOpenCodeSdkClient, + OpenCodeRuntime, + OpenCodeRuntimeError, openCodeQuestionId, + openCodeRuntimeErrorDetail, parseOpenCodeModelSlug, + runOpenCodeSdk, toOpenCodeFileParts, toOpenCodePermissionReply, toOpenCodeQuestionAnswers, @@ -45,6 +47,13 @@ interface OpenCodeTurnSnapshot { readonly items: Array; } +type OpenCodeSubscribedEvent = + Awaited> extends { + readonly stream: AsyncIterable; + } + ? TEvent + : never; + interface OpenCodeSessionContext { session: ProviderSession; readonly client: OpencodeClient; @@ -61,8 +70,21 @@ interface OpenCodeSessionContext { activeTurnId: TurnId | undefined; activeAgent: string | undefined; activeVariant: string | undefined; - stopped: boolean; - readonly eventsAbortController: AbortController; + /** + * One-shot guard flipped by `stopOpenCodeContext` / `emitUnexpectedExit`. + * The session lifecycle is owned by `sessionScope`; this Ref exists only + * so concurrent callers can race the transition safely via `getAndSet`. + */ + readonly stopped: Ref.Ref; + /** + * Sole lifecycle handle for the session. Closing this scope: + * - aborts the `AbortController` registered as a finalizer + * (cancels the in-flight `event.subscribe` fetch), + * - interrupts the event-pump and server-exit fibers forked + * via `Effect.forkIn(sessionScope)`, + * - tears down the OpenCode server process for scope-owned servers. + */ + readonly sessionScope: Scope.Closeable; } export interface OpenCodeAdapterLiveOptions { @@ -74,14 +96,33 @@ function nowIso(): string { return new Date().toISOString(); } -function isProviderAdapterRequestError(cause: unknown): cause is ProviderAdapterRequestError { - return ( - typeof cause === "object" && - cause !== null && - "_tag" in cause && - cause._tag === "ProviderAdapterRequestError" - ); -} +/** + * Map a tagged OpenCodeRuntimeError produced by {@link runOpenCodeSdk} into + * the adapter-boundary `ProviderAdapterRequestError`. SDK-method-level call + * sites pipe through this in `Effect.mapError` so they never build the error + * shape by hand. + */ +const toRequestError = (cause: OpenCodeRuntimeError): ProviderAdapterRequestError => + new ProviderAdapterRequestError({ + provider: PROVIDER, + method: cause.operation, + detail: cause.detail, + cause: cause.cause, + }); + +/** + * Map a `Cause.squash`-ed failure into a `ProviderAdapterProcessError`. The + * typed cause is usually an `OpenCodeRuntimeError` (from {@link runOpenCodeSdk}), + * in which case we preserve its `detail`; otherwise we fall back to + * {@link openCodeRuntimeErrorDetail} for unknown causes (defects, etc.). + */ +const toProcessError = (threadId: ThreadId, cause: unknown): ProviderAdapterProcessError => + new ProviderAdapterProcessError({ + provider: PROVIDER, + threadId, + detail: OpenCodeRuntimeError.is(cause) ? cause.detail : openCodeRuntimeErrorDetail(cause), + cause, + }); function buildEventBase(input: { readonly threadId: ThreadId; @@ -205,7 +246,10 @@ function ensureSessionContext( if (!session) { throw new ProviderAdapterSessionNotFoundError({ provider: PROVIDER, threadId }); } - if (session.stopped) { + // `ensureSessionContext` is a sync gate used from both sync helpers and + // Effect bodies. `Ref.getUnsafe` is an atomic read of the backing cell — + // no fiber suspension required, which keeps this callable everywhere. + if (Ref.getUnsafe(session.stopped)) { throw new ProviderAdapterSessionClosedError({ provider: PROVIDER, threadId }); } return session; @@ -369,73 +413,119 @@ function updateProviderSession( return nextSession; } -async function stopOpenCodeContext(context: OpenCodeSessionContext): Promise { - context.stopped = true; - context.eventsAbortController.abort(); - try { - await context.client.session - .abort({ sessionID: context.openCodeSessionId }) - .catch(() => undefined); - } catch {} - context.server.close(); -} +const stopOpenCodeContext = Effect.fn("stopOpenCodeContext")(function* ( + context: OpenCodeSessionContext, +) { + // Race-safe one-shot: first caller flips the flag, everyone else no-ops. + if (yield* Ref.getAndSet(context.stopped, true)) { + return; + } -export function makeOpenCodeAdapterLive(_options?: OpenCodeAdapterLiveOptions) { + // Best-effort remote abort. The scope close below tears down the local + // handles (event-pump fiber, server-exit fiber, event-subscribe fetch), + // but we still want to tell OpenCode that this session is done. + yield* runOpenCodeSdk("session.abort", () => + context.client.session.abort({ sessionID: context.openCodeSessionId }), + ).pipe(Effect.ignore({ log: true })); + + // Closing the session scope interrupts every fiber forked into it and + // runs each finalizer we registered — the `AbortController.abort()` call, + // the child-process termination, etc. + yield* Scope.close(context.sessionScope, Exit.void); +}); + +export function makeOpenCodeAdapterLive(options?: OpenCodeAdapterLiveOptions) { return Layer.effect( OpenCodeAdapter, Effect.gen(function* () { const serverConfig = yield* ServerConfig; const serverSettings = yield* ServerSettingsService; - const services = yield* Effect.context(); + const openCodeRuntime = yield* OpenCodeRuntime; const nativeEventLogger = - _options?.nativeEventLogger ?? - (_options?.nativeEventLogPath !== undefined - ? yield* makeEventNdjsonLogger(_options.nativeEventLogPath, { + options?.nativeEventLogger ?? + (options?.nativeEventLogPath !== undefined + ? yield* makeEventNdjsonLogger(options.nativeEventLogPath, { stream: "native", }) : undefined); + // Only close loggers we created. If the caller passed one in via + // `options.nativeEventLogger`, they own its lifecycle. + const managedNativeEventLogger = + options?.nativeEventLogger === undefined ? nativeEventLogger : undefined; const runtimeEvents = yield* Queue.unbounded(); const sessions = new Map(); + // Layer-level finalizer: when the adapter layer shuts down, stop every + // session. Each session's `Scope.close` tears down its spawned OpenCode + // server (via the `ChildProcessSpawner` finalizer installed in + // `startOpenCodeServerProcess`) and interrupts the forked event/exit + // fibers. Consumers that can't reason about Effect scopes therefore + // cannot leak OpenCode child processes by forgetting to call `stopAll`. + yield* Effect.addFinalizer(() => + Effect.gen(function* () { + const contexts = [...sessions.values()]; + sessions.clear(); + // `ignoreCause` swallows both typed failures (none here) and defects + // from throwing scope finalizers so a sibling's death can't interrupt + // the remaining cleanups. + yield* Effect.forEach( + contexts, + (context) => Effect.ignoreCause(stopOpenCodeContext(context)), + { concurrency: "unbounded", discard: true }, + ); + // Close the logger AFTER session teardown so any final lifecycle + // events emitted during shutdown still get written. `close` flushes + // the `Logger.batched` window and closes each per-thread + // `RotatingFileSink` handle owned by the logger's internal scope. + if (managedNativeEventLogger !== undefined) { + yield* managedNativeEventLogger.close(); + } + }), + ); + const emit = (event: ProviderRuntimeEvent) => Queue.offer(runtimeEvents, event).pipe(Effect.asVoid); - const emitPromise = (event: ProviderRuntimeEvent) => - emit(event).pipe(Effect.runPromiseWith(services)); - const writeNativeEventPromise = ( + const writeNativeEvent = ( threadId: ThreadId, event: { readonly observedAt: string; readonly event: Record; }, - ) => - (nativeEventLogger ? nativeEventLogger.write(event, threadId) : Effect.void).pipe( - Effect.runPromiseWith(services), - ); + ) => (nativeEventLogger ? nativeEventLogger.write(event, threadId) : Effect.void); const writeNativeEventBestEffort = ( threadId: ThreadId, event: { readonly observedAt: string; readonly event: Record; }, - ) => writeNativeEventPromise(threadId, event).catch(() => undefined); + ) => writeNativeEvent(threadId, event).pipe(Effect.catchCause(() => Effect.void)); - const emitUnexpectedExit = (context: OpenCodeSessionContext, message: string) => { - if (context.stopped) { + const emitUnexpectedExit = Effect.fn("emitUnexpectedExit")(function* ( + context: OpenCodeSessionContext, + message: string, + ) { + // Atomic one-shot: two fibers can race here (the event-pump on stream + // failure and the server-exit watcher). `getAndSet` flips the flag in + // a single step so the loser observes `true` and returns; a plain + // `Ref.get` would let both racers slip past and emit duplicates. + if (yield* Ref.getAndSet(context.stopped, true)) { return; } - context.stopped = true; - sessions.delete(context.session.threadId); - context.server.close(); const turnId = context.activeTurnId; - void emitPromise({ + sessions.delete(context.session.threadId); + // Emit lifecycle events BEFORE tearing down the scope. Both call sites + // run this inside a fiber forked via `Effect.forkIn(context.sessionScope)`; + // closing that scope triggers the fiber-interrupt finalizer, so any + // subsequent yield point would unwind and silently drop these emits. + yield* emit({ ...buildEventBase({ threadId: context.session.threadId, turnId }), type: "runtime.error", payload: { message, class: "transport_error", }, - }).catch(() => undefined); - void emitPromise({ + }).pipe(Effect.ignore); + yield* emit({ ...buildEventBase({ threadId: context.session.threadId, turnId }), type: "session.exited", payload: { @@ -443,16 +533,23 @@ export function makeOpenCodeAdapterLive(_options?: OpenCodeAdapterLiveOptions) { recoverable: false, exitKind: "error", }, - }).catch(() => undefined); - }; + }).pipe(Effect.ignore); + // Inline the teardown that `stopOpenCodeContext` would do; we can't + // delegate to it because our `getAndSet` above already flipped the + // one-shot guard, so the call would no-op. + yield* runOpenCodeSdk("session.abort", () => + context.client.session.abort({ sessionID: context.openCodeSessionId }), + ).pipe(Effect.ignore({ log: true })); + yield* Scope.close(context.sessionScope, Exit.void); + }); /** Emit content.delta and item.completed events for an assistant text part. */ - const emitAssistantTextDelta = async ( + const emitAssistantTextDelta = Effect.fn("emitAssistantTextDelta")(function* ( context: OpenCodeSessionContext, part: Part, turnId: TurnId | undefined, raw: unknown, - ): Promise => { + ) { const text = textFromPart(part); if (text === undefined) { return; @@ -469,7 +566,7 @@ export function makeOpenCodeAdapterLive(_options?: OpenCodeAdapterLiveOptions) { ); } if (deltaToEmit.length > 0) { - await emitPromise({ + yield* emit({ ...buildEventBase({ threadId: context.session.threadId, turnId, @@ -494,7 +591,7 @@ export function makeOpenCodeAdapterLive(_options?: OpenCodeAdapterLiveOptions) { !context.completedAssistantPartIds.has(part.id) ) { context.completedAssistantPartIds.add(part.id); - await emitPromise({ + yield* emit({ ...buildEventBase({ threadId: context.session.threadId, turnId, @@ -511,346 +608,383 @@ export function makeOpenCodeAdapterLive(_options?: OpenCodeAdapterLiveOptions) { }, }); } - }; + }); - const startEventPump = (context: OpenCodeSessionContext) => { - void (async () => { - try { - const subscription = await context.client.event.subscribe(undefined, { - signal: context.eventsAbortController.signal, - }); + const handleSubscribedEvent = Effect.fn("handleSubscribedEvent")(function* ( + context: OpenCodeSessionContext, + event: OpenCodeSubscribedEvent, + ) { + const payloadSessionId = + "properties" in event + ? (event.properties as { sessionID?: unknown }).sessionID + : undefined; + if (payloadSessionId !== context.openCodeSessionId) { + return; + } - for await (const event of subscription.stream) { - const payloadSessionId = - "properties" in event - ? (event.properties as { sessionID?: unknown }).sessionID - : undefined; - if (payloadSessionId !== context.openCodeSessionId) { - continue; + const turnId = context.activeTurnId; + yield* writeNativeEventBestEffort(context.session.threadId, { + observedAt: nowIso(), + event: { + provider: PROVIDER, + threadId: context.session.threadId, + providerThreadId: context.openCodeSessionId, + type: event.type, + ...(turnId ? { turnId } : {}), + payload: event, + }, + }); + + switch (event.type) { + case "message.updated": { + context.messageRoleById.set(event.properties.info.id, event.properties.info.role); + if (event.properties.info.role === "assistant") { + for (const part of context.partById.values()) { + if (part.messageID !== event.properties.info.id) { + continue; + } + yield* emitAssistantTextDelta(context, part, turnId, event); } + } + break; + } - const turnId = context.activeTurnId; - await writeNativeEventBestEffort(context.session.threadId, { - observedAt: nowIso(), - event: { - provider: PROVIDER, + case "message.removed": { + context.messageRoleById.delete(event.properties.messageID); + break; + } + + case "message.part.delta": { + const existingPart = context.partById.get(event.properties.partID); + if (!existingPart) { + break; + } + const role = messageRoleForPart(context, existingPart); + if (role !== "assistant") { + break; + } + const streamKind = resolveTextStreamKind(existingPart); + const delta = event.properties.delta; + if (delta.length === 0) { + break; + } + const previousText = + context.emittedTextByPartId.get(event.properties.partID) ?? + textFromPart(existingPart) ?? + ""; + const { nextText, deltaToEmit } = appendOpenCodeAssistantTextDelta(previousText, delta); + if (deltaToEmit.length === 0) { + break; + } + context.emittedTextByPartId.set(event.properties.partID, nextText); + if (existingPart.type === "text" || existingPart.type === "reasoning") { + context.partById.set(event.properties.partID, { + ...existingPart, + text: nextText, + }); + } + yield* emit({ + ...buildEventBase({ + threadId: context.session.threadId, + turnId, + itemId: event.properties.partID, + raw: event, + }), + type: "content.delta", + payload: { + streamKind, + delta: deltaToEmit, + }, + }); + break; + } + + case "message.part.updated": { + const part = event.properties.part; + context.partById.set(part.id, part); + const messageRole = messageRoleForPart(context, part); + + if (messageRole === "assistant") { + yield* emitAssistantTextDelta(context, part, turnId, event); + } + + if (part.type === "tool") { + const itemType = toToolLifecycleItemType(part.tool); + const title = + part.state.status === "running" ? (part.state.title ?? part.tool) : part.tool; + const detail = detailFromToolPart(part); + const payload = { + itemType, + ...(part.state.status === "error" + ? { status: "failed" as const } + : part.state.status === "completed" + ? { status: "completed" as const } + : { status: "inProgress" as const }), + ...(title ? { title } : {}), + ...(detail ? { detail } : {}), + data: { + tool: part.tool, + state: part.state, + }, + }; + const runtimeEvent: ProviderRuntimeEvent = { + ...buildEventBase({ threadId: context.session.threadId, - providerThreadId: context.openCodeSessionId, - type: event.type, - ...(turnId ? { turnId } : {}), - payload: event, + turnId, + itemId: part.callID, + createdAt: toolStateCreatedAt(part), + raw: event, + }), + type: + part.state.status === "pending" + ? "item.started" + : part.state.status === "completed" || part.state.status === "error" + ? "item.completed" + : "item.updated", + payload, + }; + appendTurnItem(context, turnId, part); + yield* emit(runtimeEvent); + } + break; + } + + case "permission.asked": { + context.pendingPermissions.set(event.properties.id, event.properties); + yield* emit({ + ...buildEventBase({ + threadId: context.session.threadId, + turnId, + requestId: event.properties.id, + raw: event, + }), + type: "request.opened", + payload: { + requestType: mapPermissionToRequestType(event.properties.permission), + detail: + event.properties.patterns.length > 0 + ? event.properties.patterns.join("\n") + : event.properties.permission, + args: event.properties.metadata, + }, + }); + break; + } + + case "permission.replied": { + context.pendingPermissions.delete(event.properties.requestID); + yield* emit({ + ...buildEventBase({ + threadId: context.session.threadId, + turnId, + requestId: event.properties.requestID, + raw: event, + }), + type: "request.resolved", + payload: { + requestType: "unknown", + decision: mapPermissionDecision(event.properties.reply), + }, + }); + break; + } + + case "question.asked": { + context.pendingQuestions.set(event.properties.id, event.properties); + yield* emit({ + ...buildEventBase({ + threadId: context.session.threadId, + turnId, + requestId: event.properties.id, + raw: event, + }), + type: "user-input.requested", + payload: { + questions: normalizeQuestionRequest(event.properties), + }, + }); + break; + } + + case "question.replied": { + const request = context.pendingQuestions.get(event.properties.requestID); + context.pendingQuestions.delete(event.properties.requestID); + const answers = Object.fromEntries( + (request?.questions ?? []).map((question, index) => [ + openCodeQuestionId(index, question), + event.properties.answers[index]?.join(", ") ?? "", + ]), + ); + yield* emit({ + ...buildEventBase({ + threadId: context.session.threadId, + turnId, + requestId: event.properties.requestID, + raw: event, + }), + type: "user-input.resolved", + payload: { answers }, + }); + break; + } + + case "question.rejected": { + context.pendingQuestions.delete(event.properties.requestID); + yield* emit({ + ...buildEventBase({ + threadId: context.session.threadId, + turnId, + requestId: event.properties.requestID, + raw: event, + }), + type: "user-input.resolved", + payload: { answers: {} }, + }); + break; + } + + case "session.status": { + if (event.properties.status.type === "busy") { + updateProviderSession(context, { status: "running", activeTurnId: turnId }); + } + + if (event.properties.status.type === "retry") { + yield* emit({ + ...buildEventBase({ threadId: context.session.threadId, turnId, raw: event }), + type: "runtime.warning", + payload: { + message: event.properties.status.message, + detail: event.properties.status, }, }); - - switch (event.type) { - case "message.updated": { - context.messageRoleById.set(event.properties.info.id, event.properties.info.role); - if (event.properties.info.role === "assistant") { - for (const part of context.partById.values()) { - if (part.messageID !== event.properties.info.id) { - continue; - } - await emitAssistantTextDelta(context, part, turnId, event); - } - } - break; - } - - case "message.removed": { - context.messageRoleById.delete(event.properties.messageID); - break; - } - - case "message.part.delta": { - const existingPart = context.partById.get(event.properties.partID); - if (!existingPart) { - break; - } - const role = messageRoleForPart(context, existingPart); - if (role !== "assistant") { - break; - } - const streamKind = resolveTextStreamKind(existingPart); - const delta = event.properties.delta; - if (delta.length === 0) { - break; - } - const previousText = - context.emittedTextByPartId.get(event.properties.partID) ?? - textFromPart(existingPart) ?? - ""; - const { nextText, deltaToEmit } = appendOpenCodeAssistantTextDelta( - previousText, - delta, - ); - if (deltaToEmit.length === 0) { - break; - } - context.emittedTextByPartId.set(event.properties.partID, nextText); - if (existingPart.type === "text" || existingPart.type === "reasoning") { - context.partById.set(event.properties.partID, { - ...existingPart, - text: nextText, - }); - } - await emitPromise({ - ...buildEventBase({ - threadId: context.session.threadId, - turnId, - itemId: event.properties.partID, - raw: event, - }), - type: "content.delta", - payload: { - streamKind, - delta: deltaToEmit, - }, - }); - break; - } - - case "message.part.updated": { - const part = event.properties.part; - context.partById.set(part.id, part); - const messageRole = messageRoleForPart(context, part); - - if (messageRole === "assistant") { - await emitAssistantTextDelta(context, part, turnId, event); - } - - if (part.type === "tool") { - const itemType = toToolLifecycleItemType(part.tool); - const title = - part.state.status === "running" ? (part.state.title ?? part.tool) : part.tool; - const detail = detailFromToolPart(part); - const payload = { - itemType, - ...(part.state.status === "error" - ? { status: "failed" as const } - : part.state.status === "completed" - ? { status: "completed" as const } - : { status: "inProgress" as const }), - ...(title ? { title } : {}), - ...(detail ? { detail } : {}), - data: { - tool: part.tool, - state: part.state, - }, - }; - const runtimeEvent: ProviderRuntimeEvent = { - ...buildEventBase({ - threadId: context.session.threadId, - turnId, - itemId: part.callID, - createdAt: toolStateCreatedAt(part), - raw: event, - }), - type: - part.state.status === "pending" - ? "item.started" - : part.state.status === "completed" || part.state.status === "error" - ? "item.completed" - : "item.updated", - payload, - }; - appendTurnItem(context, turnId, part); - await emitPromise(runtimeEvent); - } - break; - } - - case "permission.asked": { - context.pendingPermissions.set(event.properties.id, event.properties); - await emitPromise({ - ...buildEventBase({ - threadId: context.session.threadId, - turnId, - requestId: event.properties.id, - raw: event, - }), - type: "request.opened", - payload: { - requestType: mapPermissionToRequestType(event.properties.permission), - detail: - event.properties.patterns.length > 0 - ? event.properties.patterns.join("\n") - : event.properties.permission, - args: event.properties.metadata, - }, - }); - break; - } - - case "permission.replied": { - context.pendingPermissions.delete(event.properties.requestID); - await emitPromise({ - ...buildEventBase({ - threadId: context.session.threadId, - turnId, - requestId: event.properties.requestID, - raw: event, - }), - type: "request.resolved", - payload: { - requestType: "unknown", - decision: mapPermissionDecision(event.properties.reply), - }, - }); - break; - } - - case "question.asked": { - context.pendingQuestions.set(event.properties.id, event.properties); - await emitPromise({ - ...buildEventBase({ - threadId: context.session.threadId, - turnId, - requestId: event.properties.id, - raw: event, - }), - type: "user-input.requested", - payload: { - questions: normalizeQuestionRequest(event.properties), - }, - }); - break; - } - - case "question.replied": { - const request = context.pendingQuestions.get(event.properties.requestID); - context.pendingQuestions.delete(event.properties.requestID); - const answers = Object.fromEntries( - (request?.questions ?? []).map((question, index) => [ - openCodeQuestionId(index, question), - event.properties.answers[index]?.join(", ") ?? "", - ]), - ); - await emitPromise({ - ...buildEventBase({ - threadId: context.session.threadId, - turnId, - requestId: event.properties.requestID, - raw: event, - }), - type: "user-input.resolved", - payload: { answers }, - }); - break; - } - - case "question.rejected": { - context.pendingQuestions.delete(event.properties.requestID); - await emitPromise({ - ...buildEventBase({ - threadId: context.session.threadId, - turnId, - requestId: event.properties.requestID, - raw: event, - }), - type: "user-input.resolved", - payload: { answers: {} }, - }); - break; - } - - case "session.status": { - if (event.properties.status.type === "busy") { - updateProviderSession(context, { status: "running", activeTurnId: turnId }); - } - - if (event.properties.status.type === "retry") { - await emitPromise({ - ...buildEventBase({ threadId: context.session.threadId, turnId, raw: event }), - type: "runtime.warning", - payload: { - message: event.properties.status.message, - detail: event.properties.status, - }, - }); - break; - } - - if (event.properties.status.type === "idle" && turnId) { - context.activeTurnId = undefined; - updateProviderSession( - context, - { status: "ready" }, - { clearActiveTurnId: true }, - ); - await emitPromise({ - ...buildEventBase({ threadId: context.session.threadId, turnId, raw: event }), - type: "turn.completed", - payload: { - state: "completed", - }, - }); - } - break; - } - - case "session.error": { - const message = sessionErrorMessage(event.properties.error); - const activeTurnId = context.activeTurnId; - context.activeTurnId = undefined; - updateProviderSession( - context, - { - status: "error", - lastError: message, - }, - { clearActiveTurnId: true }, - ); - if (activeTurnId) { - await emitPromise({ - ...buildEventBase({ - threadId: context.session.threadId, - turnId: activeTurnId, - raw: event, - }), - type: "turn.completed", - payload: { - state: "failed", - errorMessage: message, - }, - }); - } - await emitPromise({ - ...buildEventBase({ threadId: context.session.threadId, raw: event }), - type: "runtime.error", - payload: { - message, - class: "provider_error", - detail: event.properties.error, - }, - }); - break; - } - - default: - break; - } + break; } - } catch (error) { - if (context.eventsAbortController.signal.aborted || context.stopped) { - return; + + if (event.properties.status.type === "idle" && turnId) { + context.activeTurnId = undefined; + updateProviderSession(context, { status: "ready" }, { clearActiveTurnId: true }); + yield* emit({ + ...buildEventBase({ threadId: context.session.threadId, turnId, raw: event }), + type: "turn.completed", + payload: { + state: "completed", + }, + }); } - emitUnexpectedExit( + break; + } + + case "session.error": { + const message = sessionErrorMessage(event.properties.error); + const activeTurnId = context.activeTurnId; + context.activeTurnId = undefined; + updateProviderSession( context, - error instanceof Error ? error.message : "OpenCode event stream failed.", + { + status: "error", + lastError: message, + }, + { clearActiveTurnId: true }, ); + if (activeTurnId) { + yield* emit({ + ...buildEventBase({ + threadId: context.session.threadId, + turnId: activeTurnId, + raw: event, + }), + type: "turn.completed", + payload: { + state: "failed", + errorMessage: message, + }, + }); + } + yield* emit({ + ...buildEventBase({ threadId: context.session.threadId, raw: event }), + type: "runtime.error", + payload: { + message, + class: "provider_error", + detail: event.properties.error, + }, + }); + break; } - })(); - context.server.process?.once("exit", (code, signal) => { - if (context.stopped) { - return; - } - emitUnexpectedExit( - context, - `OpenCode server exited unexpectedly (${signal ?? code ?? "unknown"}).`, + default: + break; + } + }); + + const startEventPump = Effect.fn("startEventPump")(function* ( + context: OpenCodeSessionContext, + ) { + // One AbortController per session scope. The finalizer fires when + // the scope closes (explicit stop, unexpected exit, or layer + // shutdown) and cancels the in-flight `event.subscribe` fetch so + // the async iterable unwinds cleanly. + const eventsAbortController = new AbortController(); + yield* Scope.addFinalizer( + context.sessionScope, + Effect.sync(() => eventsAbortController.abort()), + ); + + // Fibers forked into `context.sessionScope` are interrupted + // automatically when the scope closes — no bookkeeping required. + yield* Effect.flatMap( + runOpenCodeSdk("event.subscribe", () => + context.client.event.subscribe(undefined, { + signal: eventsAbortController.signal, + }), + ), + (subscription) => + Stream.fromAsyncIterable( + subscription.stream, + (cause) => + new OpenCodeRuntimeError({ + operation: "event.subscribe", + detail: openCodeRuntimeErrorDetail(cause), + cause, + }), + ).pipe(Stream.runForEach((event) => handleSubscribedEvent(context, event))), + ).pipe( + Effect.exit, + Effect.flatMap((exit) => + Effect.gen(function* () { + // Expected paths: caller aborted the fetch or the session + // has already been marked stopped. Treat as a clean exit. + if (eventsAbortController.signal.aborted || (yield* Ref.get(context.stopped))) { + return; + } + if (Exit.isFailure(exit)) { + yield* emitUnexpectedExit( + context, + openCodeRuntimeErrorDetail(Cause.squash(exit.cause)), + ); + } + }), + ), + Effect.forkIn(context.sessionScope), + ); + + if (!context.server.external && context.server.exitCode !== null) { + yield* context.server.exitCode.pipe( + Effect.flatMap((code) => + Effect.gen(function* () { + if (yield* Ref.get(context.stopped)) { + return; + } + yield* emitUnexpectedExit( + context, + `OpenCode server exited unexpectedly (${code}).`, + ); + }), + ), + Effect.forkIn(context.sessionScope), ); - }); - }; + } + }); const startSession: OpenCodeAdapterShape["startSession"] = Effect.fn("startSession")( function* (input) { @@ -871,44 +1005,46 @@ export function makeOpenCodeAdapterLive(_options?: OpenCodeAdapterLiveOptions) { const directory = input.cwd ?? serverConfig.cwd; const existing = sessions.get(input.threadId); if (existing) { - yield* Effect.tryPromise({ - try: () => stopOpenCodeContext(existing), - catch: (cause) => - new ProviderAdapterProcessError({ - provider: PROVIDER, - threadId: input.threadId, - detail: "Failed to stop existing OpenCode session.", - cause, - }), - }); + yield* stopOpenCodeContext(existing); sessions.delete(input.threadId); } - const started = yield* Effect.tryPromise({ - try: async () => { - const server = await connectToOpenCodeServer({ binaryPath, serverUrl }); - const client = createOpenCodeSdkClient({ - baseUrl: server.url, - directory, - ...(server.external && serverPassword ? { serverPassword } : {}), - }); - const openCodeSession = await client.session.create({ - title: `T3 Code ${input.threadId}`, - permission: buildOpenCodePermissionRules(input.runtimeMode), - }); - if (!openCodeSession.data) { - throw new Error("OpenCode session.create returned no session payload."); - } - return { server, client, openCodeSession: openCodeSession.data }; - }, - catch: (cause) => - new ProviderAdapterProcessError({ - provider: PROVIDER, - threadId: input.threadId, - detail: - cause instanceof Error ? cause.message : "Failed to start OpenCode session.", - cause, - }), + const started = yield* Effect.gen(function* () { + const sessionScope = yield* Scope.make(); + const startedExit = yield* Effect.exit( + Effect.gen(function* () { + // The runtime binds the server's lifetime to the Scope.Scope + // we provide below — closing `sessionScope` kills the child + // process automatically. No manual `server.close()` needed. + const server = yield* openCodeRuntime.connectToOpenCodeServer({ + binaryPath, + serverUrl, + }); + const client = openCodeRuntime.createOpenCodeSdkClient({ + baseUrl: server.url, + directory, + ...(server.external && serverPassword ? { serverPassword } : {}), + }); + const openCodeSession = yield* runOpenCodeSdk("session.create", () => + client.session.create({ + title: `T3 Code ${input.threadId}`, + permission: buildOpenCodePermissionRules(input.runtimeMode), + }), + ); + if (!openCodeSession.data) { + return yield* new OpenCodeRuntimeError({ + operation: "session.create", + detail: "OpenCode session.create returned no session payload.", + }); + } + return { sessionScope, server, client, openCodeSession: openCodeSession.data }; + }).pipe(Effect.provideService(Scope.Scope, sessionScope)), + ); + if (Exit.isFailure(startedExit)) { + yield* Scope.close(sessionScope, Exit.void).pipe(Effect.ignore); + return yield* toProcessError(input.threadId, Cause.squash(startedExit.cause)); + } + return startedExit.value; }); // Guard against a concurrent startSession call that may have raced @@ -917,14 +1053,10 @@ export function makeOpenCodeAdapterLive(_options?: OpenCodeAdapterLiveOptions) { if (raceWinner) { // Another call won the race – clean up the session we just created // (including the remote SDK session) and return the existing one. - yield* Effect.tryPromise({ - try: () => - started.client.session - .abort({ sessionID: started.openCodeSession.id }) - .catch(() => undefined), - catch: () => undefined, - }).pipe(Effect.ignore); - started.server.close(); + yield* runOpenCodeSdk("session.abort", () => + started.client.session.abort({ sessionID: started.openCodeSession.id }), + ).pipe(Effect.ignore); + yield* Scope.close(started.sessionScope, Exit.void).pipe(Effect.ignore); return raceWinner.session; } @@ -956,11 +1088,11 @@ export function makeOpenCodeAdapterLive(_options?: OpenCodeAdapterLiveOptions) { activeTurnId: undefined, activeAgent: undefined, activeVariant: undefined, - stopped: false, - eventsAbortController: new AbortController(), + stopped: yield* Ref.make(false), + sessionScope: started.sessionScope, }; sessions.set(input.threadId, context); - startEventPump(context); + yield* startEventPump(context); yield* emit({ ...buildEventBase({ threadId: input.threadId }), @@ -1043,59 +1175,44 @@ export function makeOpenCodeAdapterLive(_options?: OpenCodeAdapterLiveOptions) { }, }); - const promptExit = yield* Effect.exit( - Effect.tryPromise({ - try: async () => { - await context.client.session.promptAsync({ - sessionID: context.openCodeSessionId, - model: parsedModel, - ...(context.activeAgent ? { agent: context.activeAgent } : {}), - ...(context.activeVariant ? { variant: context.activeVariant } : {}), - parts: [...(text ? [{ type: "text" as const, text }] : []), ...fileParts], - }); - }, - catch: (cause) => - new ProviderAdapterRequestError({ - provider: PROVIDER, - method: "session.promptAsync", - detail: cause instanceof Error ? cause.message : "Failed to send OpenCode turn.", - cause, - }), + yield* runOpenCodeSdk("session.promptAsync", () => + context.client.session.promptAsync({ + sessionID: context.openCodeSessionId, + model: parsedModel, + ...(context.activeAgent ? { agent: context.activeAgent } : {}), + ...(context.activeVariant ? { variant: context.activeVariant } : {}), + parts: [...(text ? [{ type: "text" as const, text }] : []), ...fileParts], }), - ); - if (promptExit._tag === "Failure") { - const failure = Cause.squash(promptExit.cause); - const requestError = isProviderAdapterRequestError(failure) - ? failure - : new ProviderAdapterRequestError({ - provider: PROVIDER, - method: "session.promptAsync", - detail: - failure instanceof Error ? failure.message : "Failed to send OpenCode turn.", - cause: failure, + ).pipe( + Effect.mapError(toRequestError), + // On failure: clear active-turn state, flip the session back to ready + // with lastError set, emit turn.aborted, then let the typed error + // propagate. We don't need to rebuild the error here — `toRequestError` + // already produced the right shape. + Effect.tapError((requestError) => + Effect.gen(function* () { + context.activeTurnId = undefined; + context.activeAgent = undefined; + context.activeVariant = undefined; + updateProviderSession( + context, + { + status: "ready", + model: modelSelection?.model ?? context.session.model, + lastError: requestError.detail, + }, + { clearActiveTurnId: true }, + ); + yield* emit({ + ...buildEventBase({ threadId: input.threadId, turnId }), + type: "turn.aborted", + payload: { + reason: requestError.detail, + }, }); - const failureMessage = requestError.detail; - context.activeTurnId = undefined; - context.activeAgent = undefined; - context.activeVariant = undefined; - updateProviderSession( - context, - { - status: "ready", - model: modelSelection?.model ?? context.session.model, - lastError: failureMessage, - }, - { clearActiveTurnId: true }, - ); - yield* emit({ - ...buildEventBase({ threadId: input.threadId, turnId }), - type: "turn.aborted", - payload: { - reason: failureMessage, - }, - }); - return yield* requestError; - } + }), + ), + ); return { threadId: input.threadId, @@ -1106,16 +1223,9 @@ export function makeOpenCodeAdapterLive(_options?: OpenCodeAdapterLiveOptions) { const interruptTurn: OpenCodeAdapterShape["interruptTurn"] = Effect.fn("interruptTurn")( function* (threadId, turnId) { const context = ensureSessionContext(sessions, threadId); - yield* Effect.tryPromise({ - try: () => context.client.session.abort({ sessionID: context.openCodeSessionId }), - catch: (cause) => - new ProviderAdapterRequestError({ - provider: PROVIDER, - method: "session.abort", - detail: cause instanceof Error ? cause.message : "Failed to abort OpenCode turn.", - cause, - }), - }); + yield* runOpenCodeSdk("session.abort", () => + context.client.session.abort({ sessionID: context.openCodeSessionId }), + ).pipe(Effect.mapError(toRequestError)); if (turnId ?? context.activeTurnId) { yield* emit({ ...buildEventBase({ threadId, turnId: turnId ?? context.activeTurnId }), @@ -1140,23 +1250,12 @@ export function makeOpenCodeAdapterLive(_options?: OpenCodeAdapterLiveOptions) { }); } - yield* Effect.tryPromise({ - try: () => - context.client.permission.reply({ - requestID: requestId, - reply: toOpenCodePermissionReply(decision), - }), - catch: (cause) => - new ProviderAdapterRequestError({ - provider: PROVIDER, - method: "permission.reply", - detail: - cause instanceof Error - ? cause.message - : "Failed to submit OpenCode permission reply.", - cause, - }), - }); + yield* runOpenCodeSdk("permission.reply", () => + context.client.permission.reply({ + requestID: requestId, + reply: toOpenCodePermissionReply(decision), + }), + ).pipe(Effect.mapError(toRequestError)); }); const respondToUserInput: OpenCodeAdapterShape["respondToUserInput"] = Effect.fn( @@ -1172,35 +1271,18 @@ export function makeOpenCodeAdapterLive(_options?: OpenCodeAdapterLiveOptions) { }); } - yield* Effect.tryPromise({ - try: () => - context.client.question.reply({ - requestID: requestId, - answers: toOpenCodeQuestionAnswers(request, answers), - }), - catch: (cause) => - new ProviderAdapterRequestError({ - provider: PROVIDER, - method: "question.reply", - detail: cause instanceof Error ? cause.message : "Failed to submit OpenCode answers.", - cause, - }), - }); + yield* runOpenCodeSdk("question.reply", () => + context.client.question.reply({ + requestID: requestId, + answers: toOpenCodeQuestionAnswers(request, answers), + }), + ).pipe(Effect.mapError(toRequestError)); }); const stopSession: OpenCodeAdapterShape["stopSession"] = Effect.fn("stopSession")( function* (threadId) { const context = ensureSessionContext(sessions, threadId); - yield* Effect.tryPromise({ - try: () => stopOpenCodeContext(context), - catch: (cause) => - new ProviderAdapterProcessError({ - provider: PROVIDER, - threadId, - detail: cause instanceof Error ? cause.message : "Failed to stop OpenCode session.", - cause, - }), - }); + yield* stopOpenCodeContext(context); sessions.delete(threadId); yield* emit({ ...buildEventBase({ threadId }), @@ -1223,16 +1305,9 @@ export function makeOpenCodeAdapterLive(_options?: OpenCodeAdapterLiveOptions) { const readThread: OpenCodeAdapterShape["readThread"] = Effect.fn("readThread")( function* (threadId) { const context = ensureSessionContext(sessions, threadId); - const messages = yield* Effect.tryPromise({ - try: () => context.client.session.messages({ sessionID: context.openCodeSessionId }), - catch: (cause) => - new ProviderAdapterRequestError({ - provider: PROVIDER, - method: "session.messages", - detail: cause instanceof Error ? cause.message : "Failed to read OpenCode thread.", - cause, - }), - }); + const messages = yield* runOpenCodeSdk("session.messages", () => + context.client.session.messages({ sessionID: context.openCodeSessionId }), + ).pipe(Effect.mapError(toRequestError)); const turns = (messages.data ?? []) .filter((entry) => entry.info.role === "assistant") @@ -1251,70 +1326,39 @@ export function makeOpenCodeAdapterLive(_options?: OpenCodeAdapterLiveOptions) { const rollbackThread: OpenCodeAdapterShape["rollbackThread"] = Effect.fn("rollbackThread")( function* (threadId, numTurns) { const context = ensureSessionContext(sessions, threadId); - const messages = yield* Effect.tryPromise({ - try: () => context.client.session.messages({ sessionID: context.openCodeSessionId }), - catch: (cause) => - new ProviderAdapterRequestError({ - provider: PROVIDER, - method: "session.messages", - detail: - cause instanceof Error ? cause.message : "Failed to inspect OpenCode thread.", - cause, - }), - }); + const messages = yield* runOpenCodeSdk("session.messages", () => + context.client.session.messages({ sessionID: context.openCodeSessionId }), + ).pipe(Effect.mapError(toRequestError)); const assistantMessages = (messages.data ?? []).filter( (entry) => entry.info.role === "assistant", ); const targetIndex = assistantMessages.length - numTurns - 1; const target = targetIndex >= 0 ? assistantMessages[targetIndex] : null; - yield* Effect.tryPromise({ - try: () => - context.client.session.revert({ - sessionID: context.openCodeSessionId, - ...(target ? { messageID: target.info.id } : {}), - }), - catch: (cause) => - new ProviderAdapterRequestError({ - provider: PROVIDER, - method: "session.revert", - detail: cause instanceof Error ? cause.message : "Failed to revert OpenCode turn.", - cause, - }), - }); + yield* runOpenCodeSdk("session.revert", () => + context.client.session.revert({ + sessionID: context.openCodeSessionId, + ...(target ? { messageID: target.info.id } : {}), + }), + ).pipe(Effect.mapError(toRequestError)); return yield* readThread(threadId); }, ); const stopAll: OpenCodeAdapterShape["stopAll"] = () => - Effect.tryPromise({ - try: async () => { - const contexts = [...sessions.values()]; - sessions.clear(); - const results = await Promise.allSettled( - contexts.map((context) => stopOpenCodeContext(context)), - ); - const errors = results - .filter((result): result is PromiseRejectedResult => result.status === "rejected") - .map((result) => result.reason); - if (errors.length === 1) { - throw errors[0]; - } - if (errors.length > 1) { - throw new AggregateError( - errors, - `Failed to stop ${errors.length} OpenCode sessions.`, - ); - } - }, - catch: (cause) => - new ProviderAdapterProcessError({ - provider: PROVIDER, - threadId: "*", - detail: cause instanceof Error ? cause.message : "Failed to stop OpenCode sessions.", - cause, - }), + Effect.gen(function* () { + const contexts = [...sessions.values()]; + sessions.clear(); + // `stopOpenCodeContext` is typed as never-failing — SDK aborts are + // already `Effect.ignore`'d inside it. `ignoreCause` here also + // swallows defects from throwing finalizers so one bad close can't + // interrupt the sibling fibers. Same pattern as the layer finalizer. + yield* Effect.forEach( + contexts, + (context) => Effect.ignoreCause(stopOpenCodeContext(context)), + { concurrency: "unbounded", discard: true }, + ); }); return { diff --git a/apps/server/src/provider/Layers/OpenCodeProvider.test.ts b/apps/server/src/provider/Layers/OpenCodeProvider.test.ts index cf3d588d9d..ffce708434 100644 --- a/apps/server/src/provider/Layers/OpenCodeProvider.test.ts +++ b/apps/server/src/provider/Layers/OpenCodeProvider.test.ts @@ -3,66 +3,81 @@ import assert from "node:assert/strict"; import * as NodeServices from "@effect/platform-node/NodeServices"; import { it } from "@effect/vitest"; import { Effect, Layer } from "effect"; -import { beforeEach, vi } from "vitest"; +import { beforeEach } from "vitest"; import { ServerConfig } from "../../config.ts"; import { ServerSettingsService } from "../../serverSettings.ts"; import { OpenCodeProvider } from "../Services/OpenCodeProvider.ts"; -import { makeOpenCodeProviderLive } from "./OpenCodeProvider.ts"; +import { + OpenCodeRuntime, + OpenCodeRuntimeError, + type OpenCodeRuntimeShape, +} from "../opencodeRuntime.ts"; +import { OpenCodeProviderLive } from "./OpenCodeProvider.ts"; +import type { OpenCodeInventory } from "../opencodeRuntime.ts"; -const runtimeMock = vi.hoisted(() => { - const state = { +const runtimeMock = { + state: { runVersionError: null as Error | null, inventoryError: null as Error | null, - }; + inventory: { + providerList: { connected: [] as string[], all: [] as unknown[], default: {} }, + agents: [] as unknown[], + } as unknown, + }, + reset() { + this.state.runVersionError = null; + this.state.inventoryError = null; + this.state.inventory = { + providerList: { connected: [], all: [] as unknown[], default: {} }, + agents: [] as unknown[], + }; + }, +}; - return { - state, - reset() { - state.runVersionError = null; - state.inventoryError = null; - }, - }; -}); - -vi.mock("../opencodeRuntime.ts", async () => { - const actual = - await vi.importActual("../opencodeRuntime.ts"); - - return { - ...actual, - runOpenCodeCommand: vi.fn(async () => { - if (runtimeMock.state.runVersionError) { - throw runtimeMock.state.runVersionError; - } - return { stdout: "opencode 1.0.0\n", stderr: "", code: 0 }; +const OpenCodeRuntimeTestDouble: OpenCodeRuntimeShape = { + startOpenCodeServerProcess: () => + Effect.succeed({ + url: "http://127.0.0.1:4301", + exitCode: Effect.never, }), - connectToOpenCodeServer: vi.fn(async ({ serverUrl }: { serverUrl?: string }) => ({ + connectToOpenCodeServer: ({ serverUrl }) => + Effect.succeed({ url: serverUrl ?? "http://127.0.0.1:4301", - process: null, + exitCode: null, external: Boolean(serverUrl), - close() {}, - })), - createOpenCodeSdkClient: vi.fn(() => ({})), - loadOpenCodeInventory: vi.fn(async () => { - if (runtimeMock.state.inventoryError) { - throw runtimeMock.state.inventoryError; - } - return { - providerList: { connected: [], all: [] }, - agents: [], - }; }), - flattenOpenCodeModels: vi.fn(() => []), - }; -}); + runOpenCodeCommand: () => + runtimeMock.state.runVersionError + ? Effect.fail( + new OpenCodeRuntimeError({ + operation: "runOpenCodeCommand", + detail: runtimeMock.state.runVersionError.message, + cause: runtimeMock.state.runVersionError, + }), + ) + : Effect.succeed({ stdout: "opencode 1.0.0\n", stderr: "", code: 0 }), + createOpenCodeSdkClient: () => + ({}) as unknown as ReturnType, + loadOpenCodeInventory: () => + runtimeMock.state.inventoryError + ? Effect.fail( + new OpenCodeRuntimeError({ + operation: "loadOpenCodeInventory", + detail: runtimeMock.state.inventoryError.message, + cause: runtimeMock.state.inventoryError, + }), + ) + : Effect.succeed(runtimeMock.state.inventory as OpenCodeInventory), +}; beforeEach(() => { runtimeMock.reset(); }); const makeTestLayer = (settingsOverrides?: Parameters[0]) => - makeOpenCodeProviderLive().pipe( + OpenCodeProviderLive.pipe( + Layer.provideMerge(Layer.succeed(OpenCodeRuntime, OpenCodeRuntimeTestDouble)), Layer.provideMerge(ServerConfig.layerTest(process.cwd(), process.cwd())), Layer.provideMerge(ServerSettingsService.layerTest(settingsOverrides)), Layer.provideMerge(NodeServices.layer), @@ -92,6 +107,54 @@ it.layer(makeTestLayer())("OpenCodeProviderLive", (it) => { assert.equal(snapshot.message, "Failed to execute OpenCode CLI health check."); }), ); + + it.effect("emits OpenCode variant defaults so trait picker can resolve a visible selection", () => + Effect.gen(function* () { + runtimeMock.state.inventory = { + providerList: { + connected: ["openai"], + all: [ + { + id: "openai", + name: "OpenAI", + models: { + "gpt-5.4": { + id: "gpt-5.4", + name: "GPT-5.4", + variants: { + none: {}, + low: {}, + medium: {}, + high: {}, + xhigh: {}, + }, + }, + }, + }, + ], + default: {}, + }, + agents: [ + { name: "build", hidden: false, mode: "primary" }, + { name: "plan", hidden: false, mode: "primary" }, + ], + }; + + const provider = yield* OpenCodeProvider; + const snapshot = yield* provider.refresh; + const model = snapshot.models.find((entry) => entry.slug === "openai/gpt-5.4"); + + assert.ok(model); + assert.equal( + model.capabilities?.variantOptions?.find((option) => option.isDefault)?.value, + "medium", + ); + assert.equal( + model.capabilities?.agentOptions?.find((option) => option.isDefault)?.value, + "build", + ); + }), + ); }); it.layer( diff --git a/apps/server/src/provider/Layers/OpenCodeProvider.ts b/apps/server/src/provider/Layers/OpenCodeProvider.ts index f196941257..5e51eae028 100644 --- a/apps/server/src/provider/Layers/OpenCodeProvider.ts +++ b/apps/server/src/provider/Layers/OpenCodeProvider.ts @@ -1,57 +1,58 @@ -import type { OpenCodeSettings, ServerProvider } from "@t3tools/contracts"; -import { Cause, Effect, Equal, Layer, Stream } from "effect"; +import type { + ModelCapabilities, + OpenCodeSettings, + ServerProvider, + ServerProviderModel, +} from "@t3tools/contracts"; +import { Cause, Data, Effect, Equal, Layer, Stream } from "effect"; import { ServerConfig } from "../../config.ts"; import { ServerSettingsService } from "../../serverSettings.ts"; import { makeManagedServerProvider } from "../makeManagedServerProvider.ts"; import { buildServerProvider, - isCommandMissingCause, parseGenericCliVersion, providerModelsFromSettings, } from "../providerSnapshot.ts"; import { OpenCodeProvider } from "../Services/OpenCodeProvider.ts"; import { - connectToOpenCodeServer, - DEFAULT_OPENCODE_MODEL_CAPABILITIES, - createOpenCodeSdkClient, - flattenOpenCodeModels, - loadOpenCodeInventory, - runOpenCodeCommand, + OpenCodeRuntime, + openCodeRuntimeErrorDetail, + type OpenCodeInventory, } from "../opencodeRuntime.ts"; +import type { Agent, ProviderListResponse } from "@opencode-ai/sdk/v2"; const PROVIDER = "opencode" as const; -class OpenCodeProbePromiseError extends Error { - override readonly cause: unknown; +class OpenCodeProbeError extends Data.TaggedError("OpenCodeProbeError")<{ + readonly cause: unknown; + readonly detail: string; +}> {} - constructor(cause: unknown) { - super(cause instanceof Error ? cause.message : String(cause)); - this.cause = cause; - this.name = "OpenCodeProbePromiseError"; +function normalizeProbeMessage(message: string): string | undefined { + const trimmed = message.trim(); + if (trimmed.length === 0) { + return undefined; } -} - -function toOpenCodeProbeError(cause: unknown): OpenCodeProbePromiseError { - return new OpenCodeProbePromiseError(cause); + if ( + trimmed === "An error occurred in Effect.tryPromise" || + trimmed === "An error occurred in Effect.try" + ) { + return undefined; + } + return trimmed; } function normalizedErrorMessage(cause: unknown): string | undefined { + if (cause instanceof OpenCodeProbeError) { + return normalizeProbeMessage(cause.detail); + } + if (!(cause instanceof Error)) { return undefined; } - const message = cause.message.trim(); - if (message.length === 0) { - return undefined; - } - if ( - message === "An error occurred in Effect.tryPromise" || - message === "An error occurred in Effect.try" - ) { - return undefined; - } - return message; + return normalizeProbeMessage(cause.message); } function formatOpenCodeProbeError(input: { @@ -59,8 +60,8 @@ function formatOpenCodeProbeError(input: { readonly isExternalServer: boolean; readonly serverUrl: string; }): { readonly installed: boolean; readonly message: string } { - const lower = input.cause instanceof Error ? input.cause.message.toLowerCase() : ""; const detail = normalizedErrorMessage(input.cause); + const lower = detail?.toLowerCase() ?? ""; if (input.isExternalServer) { if ( @@ -96,7 +97,7 @@ function formatOpenCodeProbeError(input: { }; } - if (input.cause instanceof Error && isCommandMissingCause(input.cause)) { + if (lower.includes("enoent") || lower.includes("notfound")) { return { installed: false, message: "OpenCode CLI (`opencode`) is not installed or not on PATH.", @@ -127,6 +128,99 @@ function formatOpenCodeProbeError(input: { }; } +function titleCaseSlug(value: string): string { + return value + .split(/[-_/]+/) + .filter((segment) => segment.length > 0) + .map((segment) => segment.charAt(0).toUpperCase() + segment.slice(1)) + .join(" "); +} + +function inferDefaultVariant( + providerID: string, + variants: ReadonlyArray, +): string | undefined { + if (variants.length === 1) { + return variants[0]; + } + if (providerID === "anthropic" || providerID.startsWith("google")) { + return variants.includes("high") ? "high" : undefined; + } + if (providerID === "openai" || providerID === "opencode") { + return variants.includes("medium") ? "medium" : variants.includes("high") ? "high" : undefined; + } + return undefined; +} + +function inferDefaultAgent(agents: ReadonlyArray): string | undefined { + return agents.find((agent) => agent.name === "build")?.name ?? agents[0]?.name ?? undefined; +} + +const DEFAULT_OPENCODE_MODEL_CAPABILITIES: ModelCapabilities = { + reasoningEffortLevels: [], + supportsFastMode: false, + supportsThinkingToggle: false, + contextWindowOptions: [], + promptInjectedEffortLevels: [], +}; + +function openCodeCapabilitiesForModel(input: { + readonly providerID: string; + readonly model: ProviderListResponse["all"][number]["models"][string]; + readonly agents: ReadonlyArray; +}): ModelCapabilities { + const variantValues = Object.keys(input.model.variants ?? {}); + const defaultVariant = inferDefaultVariant(input.providerID, variantValues); + const variantOptions: ModelCapabilities["variantOptions"] = variantValues.map((value) => + Object.assign( + { value, label: titleCaseSlug(value) }, + defaultVariant === value ? { isDefault: true } : {}, + ), + ); + const primaryAgents = input.agents.filter( + (agent) => !agent.hidden && (agent.mode === "primary" || agent.mode === "all"), + ); + const defaultAgent = inferDefaultAgent(primaryAgents); + const agentOptions: ModelCapabilities["agentOptions"] = primaryAgents.map((agent) => + Object.assign( + { value: agent.name, label: titleCaseSlug(agent.name) }, + defaultAgent === agent.name ? { isDefault: true } : {}, + ), + ); + return { + ...DEFAULT_OPENCODE_MODEL_CAPABILITIES, + ...(variantOptions.length > 0 ? { variantOptions } : {}), + ...(agentOptions.length > 0 ? { agentOptions } : {}), + }; +} + +function flattenOpenCodeModels(input: OpenCodeInventory): ReadonlyArray { + const connected = new Set(input.providerList.connected); + const models: Array = []; + + for (const provider of input.providerList.all) { + if (!connected.has(provider.id)) { + continue; + } + + for (const model of Object.values(provider.models)) { + models.push({ + slug: `${provider.id}/${model.id}`, + name: model.name, + subProvider: provider.name, + isCustom: false, + capabilities: openCodeCapabilitiesForModel({ + providerID: provider.id, + model, + agents: input.agents, + }), + }); + } + } + + return models.toSorted((left, right) => left.name.localeCompare(right.name)); +} + const makePendingOpenCodeProvider = (openCodeSettings: OpenCodeSettings): ServerProvider => { const checkedAt = new Date().toISOString(); const models = providerModelsFromSettings( @@ -170,173 +264,177 @@ const makePendingOpenCodeProvider = (openCodeSettings: OpenCodeSettings): Server }); }; -export function checkOpenCodeProviderStatus(input: { - readonly settings: OpenCodeSettings; - readonly cwd: string; -}): Effect.Effect { - const checkedAt = new Date().toISOString(); - const customModels = input.settings.customModels; - const isExternalServer = input.settings.serverUrl.trim().length > 0; +export const OpenCodeProviderLive = Layer.effect( + OpenCodeProvider, + Effect.gen(function* () { + const serverSettings = yield* ServerSettingsService; + const serverConfig = yield* ServerConfig; + const openCodeRuntime = yield* OpenCodeRuntime; - const fallback = (cause: unknown, version: string | null = null) => { - const failure = formatOpenCodeProbeError({ - cause, - isExternalServer, - serverUrl: input.settings.serverUrl, - }); - return buildServerProvider({ - provider: PROVIDER, - enabled: input.settings.enabled, - checkedAt, - models: providerModelsFromSettings( - [], + const checkOpenCodeProviderStatus = Effect.fn("checkOpenCodeProviderStatus")(function* (input: { + readonly settings: OpenCodeSettings; + readonly cwd: string; + }): Effect.fn.Return { + const checkedAt = new Date().toISOString(); + const customModels = input.settings.customModels; + const isExternalServer = input.settings.serverUrl.trim().length > 0; + + const fallback = (cause: unknown, version: string | null = null) => { + const failure = formatOpenCodeProbeError({ + cause, + isExternalServer, + serverUrl: input.settings.serverUrl, + }); + return buildServerProvider({ + provider: PROVIDER, + enabled: input.settings.enabled, + checkedAt, + models: providerModelsFromSettings( + [], + PROVIDER, + customModels, + DEFAULT_OPENCODE_MODEL_CAPABILITIES, + ), + probe: { + installed: failure.installed, + version, + status: "error", + auth: { status: "unknown" }, + message: failure.message, + }, + }); + }; + + if (!input.settings.enabled) { + return buildServerProvider({ + provider: PROVIDER, + enabled: false, + checkedAt, + models: providerModelsFromSettings( + [], + PROVIDER, + customModels, + DEFAULT_OPENCODE_MODEL_CAPABILITIES, + ), + probe: { + installed: false, + version: null, + status: "warning", + auth: { status: "unknown" }, + message: isExternalServer + ? "OpenCode is disabled in T3 Code settings. A server URL is configured." + : "OpenCode is disabled in T3 Code settings.", + }, + }); + } + + let version: string | null = null; + if (!isExternalServer) { + const versionExit = yield* Effect.exit( + openCodeRuntime + .runOpenCodeCommand({ + binaryPath: input.settings.binaryPath, + args: ["--version"], + }) + .pipe( + Effect.mapError( + (cause) => + new OpenCodeProbeError({ cause, detail: openCodeRuntimeErrorDetail(cause) }), + ), + ), + ); + if (versionExit._tag === "Failure") { + return fallback(Cause.squash(versionExit.cause)); + } + version = parseGenericCliVersion(versionExit.value.stdout) ?? null; + } + + const inventoryExit = yield* Effect.exit( + Effect.scoped( + Effect.gen(function* () { + const server = yield* openCodeRuntime + .connectToOpenCodeServer({ + binaryPath: input.settings.binaryPath, + serverUrl: input.settings.serverUrl, + }) + .pipe( + Effect.mapError( + (cause) => + new OpenCodeProbeError({ cause, detail: openCodeRuntimeErrorDetail(cause) }), + ), + ); + return yield* openCodeRuntime + .loadOpenCodeInventory( + openCodeRuntime.createOpenCodeSdkClient({ + baseUrl: server.url, + directory: input.cwd, + ...(isExternalServer && input.settings.serverPassword + ? { serverPassword: input.settings.serverPassword } + : {}), + }), + ) + .pipe( + Effect.mapError( + (cause) => + new OpenCodeProbeError({ cause, detail: openCodeRuntimeErrorDetail(cause) }), + ), + ); + }), + ), + ); + if (inventoryExit._tag === "Failure") { + return fallback(Cause.squash(inventoryExit.cause), version); + } + + const models = providerModelsFromSettings( + flattenOpenCodeModels(inventoryExit.value), PROVIDER, customModels, DEFAULT_OPENCODE_MODEL_CAPABILITIES, - ), - probe: { - installed: failure.installed, - version, - status: "error", - auth: { status: "unknown" }, - message: failure.message, - }, - }); - }; - - return Effect.gen(function* () { - if (!input.settings.enabled) { + ); + const connectedCount = inventoryExit.value.providerList.connected.length; return buildServerProvider({ provider: PROVIDER, - enabled: false, + enabled: true, checkedAt, - models: providerModelsFromSettings( - [], - PROVIDER, - customModels, - DEFAULT_OPENCODE_MODEL_CAPABILITIES, - ), + models, probe: { - installed: false, - version: null, - status: "warning", - auth: { status: "unknown" }, - message: isExternalServer - ? "OpenCode is disabled in T3 Code settings. A server URL is configured." - : "OpenCode is disabled in T3 Code settings.", + installed: true, + version, + status: connectedCount > 0 ? "ready" : "warning", + auth: { + status: connectedCount > 0 ? "authenticated" : "unknown", + type: "opencode", + }, + message: + connectedCount > 0 + ? `${connectedCount} upstream provider${connectedCount === 1 ? "" : "s"} connected through ${isExternalServer ? "the configured OpenCode server" : "OpenCode"}.` + : isExternalServer + ? "Connected to the configured OpenCode server, but it did not report any connected upstream providers." + : "OpenCode is available, but it did not report any connected upstream providers.", }, }); - } - - let version: string | null = null; - if (!isExternalServer) { - const versionExit = yield* Effect.exit( - Effect.tryPromise({ - try: () => - runOpenCodeCommand({ - binaryPath: input.settings.binaryPath, - args: ["--version"], - }), - catch: toOpenCodeProbeError, - }), - ); - if (versionExit._tag === "Failure") { - return fallback(Cause.squash(versionExit.cause)); - } - version = parseGenericCliVersion(versionExit.value.stdout) ?? null; - } - - const inventoryExit = yield* Effect.exit( - Effect.acquireUseRelease( - Effect.tryPromise({ - try: () => - connectToOpenCodeServer({ - binaryPath: input.settings.binaryPath, - serverUrl: input.settings.serverUrl, - }), - catch: toOpenCodeProbeError, - }), - (server) => - Effect.tryPromise({ - try: async () => { - const client = createOpenCodeSdkClient({ - baseUrl: server.url, - directory: input.cwd, - ...(isExternalServer && input.settings.serverPassword - ? { serverPassword: input.settings.serverPassword } - : {}), - }); - return await loadOpenCodeInventory(client); - }, - catch: toOpenCodeProbeError, - }), - (server) => Effect.sync(() => server.close()), - ), - ); - if (inventoryExit._tag === "Failure") { - return fallback(Cause.squash(inventoryExit.cause), version); - } - - const models = providerModelsFromSettings( - flattenOpenCodeModels(inventoryExit.value), - PROVIDER, - customModels, - DEFAULT_OPENCODE_MODEL_CAPABILITIES, - ); - const connectedCount = inventoryExit.value.providerList.connected.length; - return buildServerProvider({ - provider: PROVIDER, - enabled: true, - checkedAt, - models, - probe: { - installed: true, - version, - status: connectedCount > 0 ? "ready" : "warning", - auth: { - status: connectedCount > 0 ? "authenticated" : "unknown", - type: "opencode", - }, - message: - connectedCount > 0 - ? `${connectedCount} upstream provider${connectedCount === 1 ? "" : "s"} connected through ${isExternalServer ? "the configured OpenCode server" : "OpenCode"}.` - : isExternalServer - ? "Connected to the configured OpenCode server, but it did not report any connected upstream providers." - : "OpenCode is available, but it did not report any connected upstream providers.", - }, }); - }); -} -export function makeOpenCodeProviderLive() { - return Layer.effect( - OpenCodeProvider, - Effect.gen(function* () { - const serverSettings = yield* ServerSettingsService; - const serverConfig = yield* ServerConfig; + const getProviderSettings = serverSettings.getSettings.pipe( + Effect.map((settings) => settings.providers.opencode), + ); - const getProviderSettings = serverSettings.getSettings.pipe( - Effect.map((settings) => settings.providers.opencode), - ); - - return yield* makeManagedServerProvider({ - getSettings: getProviderSettings.pipe(Effect.orDie), - streamSettings: serverSettings.streamChanges.pipe( - Stream.map((settings) => settings.providers.opencode), + return yield* makeManagedServerProvider({ + getSettings: getProviderSettings.pipe(Effect.orDie), + streamSettings: serverSettings.streamChanges.pipe( + Stream.map((settings) => settings.providers.opencode), + ), + haveSettingsChanged: (previous, next) => !Equal.equals(previous, next), + initialSnapshot: makePendingOpenCodeProvider, + checkProvider: getProviderSettings.pipe( + Effect.flatMap((settings) => + checkOpenCodeProviderStatus({ + settings, + cwd: serverConfig.cwd, + }), ), - haveSettingsChanged: (previous, next) => !Equal.equals(previous, next), - initialSnapshot: makePendingOpenCodeProvider, - checkProvider: getProviderSettings.pipe( - Effect.flatMap((settings) => - checkOpenCodeProviderStatus({ - settings, - cwd: serverConfig.cwd, - }), - ), - ), - }); - }), - ); -} - -export const OpenCodeProviderLive = makeOpenCodeProviderLive(); + ), + }); + }), +); diff --git a/apps/server/src/provider/Layers/ProviderRegistry.ts b/apps/server/src/provider/Layers/ProviderRegistry.ts index d068335314..3f83419a38 100644 --- a/apps/server/src/provider/Layers/ProviderRegistry.ts +++ b/apps/server/src/provider/Layers/ProviderRegistry.ts @@ -16,6 +16,7 @@ import { CodexProvider } from "../Services/CodexProvider.ts"; import { CursorProvider } from "../Services/CursorProvider.ts"; import { OpenCodeProvider } from "../Services/OpenCodeProvider.ts"; import { ProviderRegistry, type ProviderRegistryShape } from "../Services/ProviderRegistry.ts"; +import { OpenCodeRuntimeLive } from "../opencodeRuntime.ts"; import { hydrateCachedProvider, PROVIDER_CACHE_IDS, @@ -287,6 +288,7 @@ export const ProviderRegistryLive = Layer.unwrap( Layer.provideMerge(CodexProviderLive), Layer.provideMerge(ClaudeProviderLive), Layer.provideMerge(OpenCodeProviderLive), + Layer.provideMerge(OpenCodeRuntimeLive), ), ), ); diff --git a/apps/server/src/provider/opencodeRuntime.test.ts b/apps/server/src/provider/opencodeRuntime.test.ts deleted file mode 100644 index 0e7024efc9..0000000000 --- a/apps/server/src/provider/opencodeRuntime.test.ts +++ /dev/null @@ -1,37 +0,0 @@ -import { describe, expect, it } from "vitest"; - -import { DEFAULT_OPENCODE_MODEL_CAPABILITIES, flattenOpenCodeModels } from "./opencodeRuntime.ts"; - -describe("flattenOpenCodeModels", () => { - it("keeps the canonical model name separate from the subprovider label", () => { - const models = flattenOpenCodeModels({ - providerList: { - connected: ["github-copilot"], - all: [ - { - id: "github-copilot", - name: "GitHub Copilot", - models: { - "claude-opus-4.5": { - id: "claude-opus-4.5", - name: "Claude Opus 4.5", - variants: {}, - }, - }, - }, - ], - }, - agents: [], - } as unknown as Parameters[0]); - - expect(models).toEqual([ - { - slug: "github-copilot/claude-opus-4.5", - name: "Claude Opus 4.5", - subProvider: "GitHub Copilot", - isCustom: false, - capabilities: DEFAULT_OPENCODE_MODEL_CAPABILITIES, - }, - ]); - }); -}); diff --git a/apps/server/src/provider/opencodeRuntime.ts b/apps/server/src/provider/opencodeRuntime.ts index 91a855bce6..9f10738dbf 100644 --- a/apps/server/src/provider/opencodeRuntime.ts +++ b/apps/server/src/provider/opencodeRuntime.ts @@ -1,17 +1,6 @@ -import { execFileSync, spawn, type ChildProcess } from "node:child_process"; -import * as FS from "node:fs"; -import { createServer, type AddressInfo } from "node:net"; -import * as OS from "node:os"; -import * as Path from "node:path"; import { pathToFileURL } from "node:url"; -import type { - ChatAttachment, - ModelCapabilities, - ProviderApprovalDecision, - RuntimeMode, - ServerProviderModel, -} from "@t3tools/contracts"; +import type { ChatAttachment, ProviderApprovalDecision, RuntimeMode } from "@t3tools/contracts"; import { createOpencodeClient, type Agent, @@ -22,40 +11,80 @@ import { type QuestionAnswer, type QuestionRequest, } from "@opencode-ai/sdk/v2"; +import { + Cause, + Context, + Data, + Deferred, + Effect, + Exit, + Fiber, + Layer, + Option, + Predicate as P, + Ref, + Result, + Scope, + Stream, +} from "effect"; +import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process"; + +import { isWindowsCommandNotFound } from "../processRunner.ts"; +import { collectStreamAsString } from "./providerSnapshot.ts"; +import { NetService } from "@t3tools/shared/Net"; const OPENCODE_SERVER_READY_PREFIX = "opencode server listening"; const DEFAULT_OPENCODE_SERVER_TIMEOUT_MS = 5_000; const DEFAULT_HOSTNAME = "127.0.0.1"; -const OPENAI_VARIANTS = ["none", "minimal", "low", "medium", "high", "xhigh"]; -const ANTHROPIC_VARIANTS = ["high", "max"]; -const GOOGLE_VARIANTS = ["low", "high"]; - -export const DEFAULT_OPENCODE_MODEL_CAPABILITIES: ModelCapabilities = { - reasoningEffortLevels: [], - supportsFastMode: false, - supportsThinkingToggle: false, - contextWindowOptions: [], - promptInjectedEffortLevels: [], -}; - export interface OpenCodeServerProcess { readonly url: string; - readonly process: ChildProcess; - close(): void; + readonly exitCode: Effect.Effect; } export interface OpenCodeServerConnection { readonly url: string; - readonly process: ChildProcess | null; + readonly exitCode: Effect.Effect | null; readonly external: boolean; - close(): void; } -function buildOpenCodeBasicAuthorizationHeader(password: string): string { - return `Basic ${Buffer.from(`opencode:${password}`, "utf8").toString("base64")}`; +const OPENCODE_RUNTIME_ERROR_TAG = "OpenCodeRuntimeError"; +export class OpenCodeRuntimeError extends Data.TaggedError(OPENCODE_RUNTIME_ERROR_TAG)<{ + readonly operation: string; + readonly cause?: unknown; + readonly detail: string; +}> { + static readonly is = (u: unknown): u is OpenCodeRuntimeError => + P.isTagged(u, OPENCODE_RUNTIME_ERROR_TAG); } +export function openCodeRuntimeErrorDetail(cause: unknown): string { + if (OpenCodeRuntimeError.is(cause)) return cause.detail; + if (cause instanceof Error && cause.message.trim().length > 0) return cause.message.trim(); + if (cause && typeof cause === "object") { + // SDK v2 throws { response, request, error? } shapes — extract what's useful + const anyCause = cause as Record; + const status = (anyCause.response as { status?: number } | undefined)?.status; + const body = anyCause.error ?? anyCause.data ?? anyCause.body; + try { + return `status=${status ?? "?"} body=${JSON.stringify(body ?? cause)}`; + } catch { + /* fall through */ + } + } + return String(cause); +} + +export const runOpenCodeSdk = ( + operation: string, + fn: () => Promise, +): Effect.Effect => + Effect.tryPromise({ + try: fn, + catch: (cause) => + new OpenCodeRuntimeError({ operation, detail: openCodeRuntimeErrorDetail(cause), cause }), + }).pipe(Effect.withSpan(`opencode.${operation}`)); + export interface OpenCodeCommandResult { readonly stdout: string; readonly stderr: string; @@ -72,12 +101,43 @@ export interface ParsedOpenCodeModelSlug { readonly modelID: string; } -function titleCaseSlug(value: string): string { - return value - .split(/[-_/]+/) - .filter((segment) => segment.length > 0) - .map((segment) => segment.charAt(0).toUpperCase() + segment.slice(1)) - .join(" "); +export interface OpenCodeRuntimeShape { + /** + * Spawns a local OpenCode server process. Its lifetime is bound to the caller's + * `Scope.Scope` — the child is killed automatically when that scope closes. + * Consumers that want a long-lived server must create and hold a scope explicitly + * (see {@link Scope.make}) and close it when done. + */ + readonly startOpenCodeServerProcess: (input: { + readonly binaryPath: string; + readonly port?: number; + readonly hostname?: string; + readonly timeoutMs?: number; + }) => Effect.Effect; + /** + * Returns a handle to either an externally-managed OpenCode server (when + * `serverUrl` is provided — no lifetime is attached to the caller's scope) or a + * freshly spawned local server whose lifetime is bound to the caller's scope. + */ + readonly connectToOpenCodeServer: (input: { + readonly binaryPath: string; + readonly serverUrl?: string | null; + readonly port?: number; + readonly hostname?: string; + readonly timeoutMs?: number; + }) => Effect.Effect; + readonly runOpenCodeCommand: (input: { + readonly binaryPath: string; + readonly args: ReadonlyArray; + }) => Effect.Effect; + readonly createOpenCodeSdkClient: (input: { + readonly baseUrl: string; + readonly directory: string; + readonly serverPassword?: string; + }) => OpencodeClient; + readonly loadOpenCodeInventory: ( + client: OpencodeClient, + ) => Effect.Effect; } function parseServerUrlFromOutput(output: string): string | null { @@ -91,92 +151,6 @@ function parseServerUrlFromOutput(output: string): string | null { return null; } -function isPrimaryAgent(agent: Agent): boolean { - return !agent.hidden && (agent.mode === "primary" || agent.mode === "all"); -} - -function inferVariantValues(providerID: string): ReadonlyArray { - if (providerID === "anthropic") { - return ANTHROPIC_VARIANTS; - } - if (providerID === "openai" || providerID === "opencode") { - return OPENAI_VARIANTS; - } - if (providerID.startsWith("google")) { - return GOOGLE_VARIANTS; - } - return []; -} - -function inferDefaultVariant( - providerID: string, - variants: ReadonlyArray, -): string | undefined { - if (variants.length === 1) { - return variants[0]; - } - if (providerID === "anthropic" || providerID.startsWith("google")) { - return variants.includes("high") ? "high" : undefined; - } - if (providerID === "openai" || providerID === "opencode") { - return variants.includes("medium") ? "medium" : variants.includes("high") ? "high" : undefined; - } - return undefined; -} - -function buildVariantOptions( - providerID: string, - model: ProviderListResponse["all"][number]["models"][string], -) { - const variantValues = Object.keys(model.variants ?? {}); - const resolvedValues = - variantValues.length > 0 ? variantValues : [...inferVariantValues(providerID)]; - const defaultVariant = inferDefaultVariant(providerID, resolvedValues); - - return resolvedValues.map((value) => { - const option: { value: string; label: string; isDefault?: boolean } = { - value, - label: titleCaseSlug(value), - }; - if (defaultVariant === value) { - option.isDefault = true; - } - return option; - }); -} - -function buildAgentOptions(agents: ReadonlyArray) { - const primaryAgents = agents.filter(isPrimaryAgent); - const defaultAgent = - primaryAgents.find((agent) => agent.name === "build")?.name ?? - primaryAgents[0]?.name ?? - undefined; - return primaryAgents.map((agent) => { - const option: { value: string; label: string; isDefault?: boolean } = { - value: agent.name, - label: titleCaseSlug(agent.name), - }; - if (defaultAgent === agent.name) { - option.isDefault = true; - } - return option; - }); -} - -function openCodeCapabilitiesForModel(input: { - readonly providerID: string; - readonly model: ProviderListResponse["all"][number]["models"][string]; - readonly agents: ReadonlyArray; -}): ModelCapabilities { - const variantOptions = buildVariantOptions(input.providerID, input.model); - const agentOptions = buildAgentOptions(input.agents); - return { - ...DEFAULT_OPENCODE_MODEL_CAPABILITIES, - ...(variantOptions.length > 0 ? { variantOptions } : {}), - ...(agentOptions.length > 0 ? { agentOptions } : {}), - }; -} - export function parseOpenCodeModelSlug( slug: string | null | undefined, ): ParsedOpenCodeModelSlug | null { @@ -196,10 +170,6 @@ export function parseOpenCodeModelSlug( }; } -export function toOpenCodeModelSlug(providerID: string, modelID: string): string { - return `${providerID}/${modelID}`; -} - export function openCodeQuestionId( index: number, question: QuestionRequest["questions"][number], @@ -286,289 +256,268 @@ export function toOpenCodeQuestionAnswers( }); } -export async function findAvailablePort(): Promise { - const server = createServer(); - await new Promise((resolve, reject) => { - server.once("error", reject); - server.listen(0, DEFAULT_HOSTNAME, () => resolve()); - }); - const address = server.address() as AddressInfo; - const port = address.port; - await new Promise((resolve, reject) => { - server.close((error) => (error ? reject(error) : resolve())); - }); - return port; +function ensureRuntimeError( + operation: OpenCodeRuntimeError["operation"], + detail: string, + cause: unknown, +): OpenCodeRuntimeError { + return OpenCodeRuntimeError.is(cause) + ? cause + : new OpenCodeRuntimeError({ operation, detail, cause }); } -export function resolveOpenCodeBinaryPath(binaryPath: string): string { - if (Path.isAbsolute(binaryPath)) { - return binaryPath; - } - return execFileSync("which", [binaryPath], { - encoding: "utf8", - timeout: 3_000, - }).trim(); -} +const makeOpenCodeRuntime = Effect.gen(function* () { + const spawner = yield* ChildProcessSpawner.ChildProcessSpawner; + const netService = yield* NetService; -export function detectMacosSigkillHint(binaryPath: string): string | null { - try { - // Check for quarantine xattr first. - const resolvedPath = resolveOpenCodeBinaryPath(binaryPath); - const xattr = execFileSync("xattr", ["-l", resolvedPath], { - encoding: "utf8", - timeout: 3_000, - }); - if (xattr.includes("com.apple.quarantine")) { - return ( - `macOS quarantine is blocking the OpenCode binary. ` + - `Run: xattr -d com.apple.quarantine ${resolvedPath}` + const runOpenCodeCommand: OpenCodeRuntimeShape["runOpenCodeCommand"] = (input) => + Effect.gen(function* () { + const child = yield* spawner.spawn( + ChildProcess.make(input.binaryPath, [...input.args], { + shell: process.platform === "win32", + env: process.env, + }), ); - } + const [stdout, stderr, code] = yield* Effect.all( + [collectStreamAsString(child.stdout), collectStreamAsString(child.stderr), child.exitCode], + { concurrency: "unbounded" }, + ); + const exitCode = Number(code); + if (isWindowsCommandNotFound(exitCode, stderr)) { + return yield* new OpenCodeRuntimeError({ + operation: "runOpenCodeCommand", + detail: `spawn ${input.binaryPath} ENOENT`, + }); + } + return { + stdout, + stderr, + code: exitCode, + } satisfies OpenCodeCommandResult; + }).pipe( + Effect.scoped, + Effect.mapError((cause) => + ensureRuntimeError( + "runOpenCodeCommand", + `Failed to execute '${input.binaryPath} ${input.args.join(" ")}': ${openCodeRuntimeErrorDetail(cause)}`, + cause, + ), + ), + ); - // Look for a recent crash report with the termination reason. - const crashDir = Path.join(OS.homedir(), "Library/Logs/DiagnosticReports"); - const binaryName = Path.basename(resolvedPath); - const recentReports = FS.readdirSync(crashDir) - .filter((f) => f.startsWith(binaryName) && f.endsWith(".ips")) - .toSorted() - .toReversed() - .slice(0, 1); + const startOpenCodeServerProcess: OpenCodeRuntimeShape["startOpenCodeServerProcess"] = (input) => + Effect.gen(function* () { + // Bind this server's lifetime to the caller's scope. When the caller's + // scope closes, the spawned child is killed and all associated fibers + // are interrupted automatically — no `close()` method needed. + const runtimeScope = yield* Scope.Scope; - for (const report of recentReports) { - const content = FS.readFileSync(Path.join(crashDir, report), "utf8"); - if (content.includes('"namespace":"CODESIGNING"')) { - return ( - "macOS killed the process due to an invalid code signature. " + - "The binary may be corrupted — try reinstalling OpenCode." + const hostname = input.hostname ?? DEFAULT_HOSTNAME; + const port = + input.port ?? + (yield* netService.findAvailablePort(0).pipe( + Effect.mapError( + (cause) => + new OpenCodeRuntimeError({ + operation: "startOpenCodeServerProcess", + detail: `Failed to find available port: ${openCodeRuntimeErrorDetail(cause)}`, + cause, + }), + ), + )); + const timeoutMs = input.timeoutMs ?? DEFAULT_OPENCODE_SERVER_TIMEOUT_MS; + const args = ["serve", `--hostname=${hostname}`, `--port=${port}`]; + + const child = yield* spawner + .spawn( + ChildProcess.make(input.binaryPath, args, { + env: { + ...process.env, + OPENCODE_CONFIG_CONTENT: JSON.stringify({}), + }, + }), + ) + .pipe( + Effect.provideService(Scope.Scope, runtimeScope), + Effect.mapError( + (cause) => + new OpenCodeRuntimeError({ + operation: "startOpenCodeServerProcess", + detail: `Failed to spawn OpenCode server process: ${openCodeRuntimeErrorDetail(cause)}`, + cause, + }), + ), + ); + + const stdoutRef = yield* Ref.make(""); + const stderrRef = yield* Ref.make(""); + const readyDeferred = yield* Deferred.make(); + + const setReadyFromStdoutChunk = (chunk: string) => + Ref.updateAndGet(stdoutRef, (stdout) => `${stdout}${chunk}`).pipe( + Effect.flatMap((nextStdout) => { + const parsed = parseServerUrlFromOutput(nextStdout); + return parsed + ? Deferred.succeed(readyDeferred, parsed).pipe(Effect.ignore) + : Effect.void; + }), + ); + + const stdoutFiber = yield* child.stdout.pipe( + Stream.decodeText(), + Stream.runForEach(setReadyFromStdoutChunk), + Effect.ignore, + Effect.forkIn(runtimeScope), + ); + const stderrFiber = yield* child.stderr.pipe( + Stream.decodeText(), + Stream.runForEach((chunk) => Ref.update(stderrRef, (stderr) => `${stderr}${chunk}`)), + Effect.ignore, + Effect.forkIn(runtimeScope), + ); + + const exitFiber = yield* child.exitCode.pipe( + Effect.flatMap((code) => + Effect.gen(function* () { + const stdout = yield* Ref.get(stdoutRef); + const stderr = yield* Ref.get(stderrRef); + const exitCode = Number(code); + yield* Deferred.fail( + readyDeferred, + new OpenCodeRuntimeError({ + operation: "startOpenCodeServerProcess", + detail: [ + `OpenCode server exited before startup completed (code: ${String(exitCode)}).`, + stdout.trim() ? `stdout:\n${stdout.trim()}` : null, + stderr.trim() ? `stderr:\n${stderr.trim()}` : null, + ] + .filter(Boolean) + .join("\n\n"), + cause: { exitCode, stdout, stderr }, + }), + ).pipe(Effect.ignore); + }), + ), + Effect.ignore, + Effect.forkIn(runtimeScope), + ); + + const readyExit = yield* Effect.exit( + Deferred.await(readyDeferred).pipe(Effect.timeoutOption(timeoutMs)), + ); + + // Startup-time fibers are no longer needed once ready has resolved (either + // way). The exit fiber is only interrupted on failure; on success it keeps + // the caller's `exitCode` effect observable until the scope closes. + yield* Fiber.interrupt(stdoutFiber).pipe(Effect.ignore); + yield* Fiber.interrupt(stderrFiber).pipe(Effect.ignore); + + if (Exit.isFailure(readyExit)) { + yield* Fiber.interrupt(exitFiber).pipe(Effect.ignore); + const squashed = Cause.squash(readyExit.cause); + return yield* ensureRuntimeError( + "startOpenCodeServerProcess", + `Failed while waiting for OpenCode server startup: ${openCodeRuntimeErrorDetail(squashed)}`, + squashed, ); } - } - } catch { - // Best-effort detection — don't fail the original error path. - } - return null; -} -export async function startOpenCodeServerProcess(input: { - readonly binaryPath: string; - readonly port?: number; - readonly hostname?: string; - readonly timeoutMs?: number; -}): Promise { - const hostname = input.hostname ?? DEFAULT_HOSTNAME; - const port = input.port ?? (await findAvailablePort()); - const timeoutMs = input.timeoutMs ?? DEFAULT_OPENCODE_SERVER_TIMEOUT_MS; - const args = ["serve", `--hostname=${hostname}`, `--port=${port}`]; - const child = spawn(input.binaryPath, args, { - stdio: ["ignore", "pipe", "pipe"], - env: { - ...process.env, - OPENCODE_CONFIG_CONTENT: JSON.stringify({}), - }, - }); - - child.stdout.setEncoding("utf8"); - child.stderr.setEncoding("utf8"); - - let stdout = ""; - let stderr = ""; - let closed = false; - const close = () => { - if (closed) { - return; - } - closed = true; - child.kill(); - }; - - const url = await new Promise((resolve, reject) => { - const timeout = setTimeout(() => { - close(); - reject(new Error(`Timed out waiting for OpenCode server start after ${timeoutMs}ms.`)); - }, timeoutMs); - - const cleanup = () => { - clearTimeout(timeout); - child.stdout.off("data", onStdout); - child.stderr.off("data", onStderr); - child.off("error", onError); - child.off("close", onClose); - }; - - const onStdout = (chunk: string) => { - stdout += chunk; - const parsed = parseServerUrlFromOutput(stdout); - if (!parsed) { - return; + const readyOption = readyExit.value; + if (Option.isNone(readyOption)) { + yield* Fiber.interrupt(exitFiber).pipe(Effect.ignore); + return yield* new OpenCodeRuntimeError({ + operation: "startOpenCodeServerProcess", + detail: `Timed out waiting for OpenCode server start after ${timeoutMs}ms.`, + }); } - cleanup(); - resolve(parsed); - }; - const onStderr = (chunk: string) => { - stderr += chunk; - }; - - const onError = (error: Error) => { - cleanup(); - reject(error); - }; - - const onClose = (code: number | null, signal: NodeJS.Signals | null) => { - cleanup(); - const exitReason = signal ? `signal: ${signal}` : `code: ${code ?? "unknown"}`; - const hint = - signal === "SIGKILL" && process.platform === "darwin" - ? detectMacosSigkillHint(input.binaryPath) - : null; - reject( - new Error( - [ - `OpenCode server exited before startup completed (${exitReason}).`, - hint, - stdout.trim() ? `stdout:\n${stdout.trim()}` : null, - stderr.trim() ? `stderr:\n${stderr.trim()}` : null, - ] - .filter(Boolean) - .join("\n\n"), + return { + url: readyOption.value, + exitCode: child.exitCode.pipe( + Effect.map(Number), + Effect.orElseSucceed(() => 0), ), - ); - }; + } satisfies OpenCodeServerProcess; + }); - child.stdout.on("data", onStdout); - child.stderr.on("data", onStderr); - child.once("error", onError); - child.once("close", onClose); - }); - - return { - url, - process: child, - close, - }; -} - -export async function connectToOpenCodeServer(input: { - readonly binaryPath: string; - readonly serverUrl?: string | null; - readonly port?: number; - readonly hostname?: string; - readonly timeoutMs?: number; -}): Promise { - const serverUrl = input.serverUrl?.trim(); - if (serverUrl) { - return { - url: serverUrl, - process: null, - external: true, - close() {}, - }; - } - - const server = await startOpenCodeServerProcess({ - binaryPath: input.binaryPath, - ...(input.port !== undefined ? { port: input.port } : {}), - ...(input.hostname !== undefined ? { hostname: input.hostname } : {}), - ...(input.timeoutMs !== undefined ? { timeoutMs: input.timeoutMs } : {}), - }); - - return { - url: server.url, - process: server.process, - external: false, - close: () => server.close(), - }; -} - -export async function runOpenCodeCommand(input: { - readonly binaryPath: string; - readonly args: ReadonlyArray; -}): Promise { - const child = spawn(input.binaryPath, [...input.args], { - stdio: ["ignore", "pipe", "pipe"], - shell: process.platform === "win32", - env: process.env, - }); - - child.stdout?.setEncoding("utf8"); - child.stderr?.setEncoding("utf8"); - - const stdoutChunks: Array = []; - const stderrChunks: Array = []; - - child.stdout?.on("data", (chunk: string) => stdoutChunks.push(chunk)); - child.stderr?.on("data", (chunk: string) => stderrChunks.push(chunk)); - - const code = await new Promise((resolve, reject) => { - child.once("error", reject); - child.once("exit", (exitCode) => resolve(exitCode ?? 0)); - }); - - return { - stdout: stdoutChunks.join(""), - stderr: stderrChunks.join(""), - code, - }; -} - -export function createOpenCodeSdkClient(input: { - readonly baseUrl: string; - readonly directory: string; - readonly serverPassword?: string; -}): OpencodeClient { - return createOpencodeClient({ - baseUrl: input.baseUrl, - directory: input.directory, - ...(input.serverPassword - ? { - headers: { - Authorization: buildOpenCodeBasicAuthorizationHeader(input.serverPassword), - }, - } - : {}), - throwOnError: true, - }); -} - -export async function loadOpenCodeInventory(client: OpencodeClient): Promise { - const [providerListResult, agentsResult] = await Promise.all([ - client.provider.list(), - client.app.agents(), - ]); - if (!providerListResult.data) { - throw new Error("OpenCode provider inventory was empty."); - } - return { - providerList: providerListResult.data, - agents: agentsResult.data ?? [], - }; -} - -export function flattenOpenCodeModels( - input: OpenCodeInventory, -): ReadonlyArray { - const connected = new Set(input.providerList.connected); - const models: Array = []; - - for (const provider of input.providerList.all) { - if (!connected.has(provider.id)) { - continue; - } - - for (const model of Object.values(provider.models)) { - models.push({ - slug: toOpenCodeModelSlug(provider.id, model.id), - name: model.name, - subProvider: provider.name, - isCustom: false, - capabilities: openCodeCapabilitiesForModel({ - providerID: provider.id, - model, - agents: input.agents, - }), + const connectToOpenCodeServer: OpenCodeRuntimeShape["connectToOpenCodeServer"] = (input) => { + const serverUrl = input.serverUrl?.trim(); + if (serverUrl) { + // We don't own externally-configured servers — no scope interaction. + return Effect.succeed({ + url: serverUrl, + exitCode: null, + external: true, }); } - } - return models.toSorted((left, right) => left.name.localeCompare(right.name)); -} + return startOpenCodeServerProcess({ + binaryPath: input.binaryPath, + ...(input.port !== undefined ? { port: input.port } : {}), + ...(input.hostname !== undefined ? { hostname: input.hostname } : {}), + ...(input.timeoutMs !== undefined ? { timeoutMs: input.timeoutMs } : {}), + }).pipe( + Effect.map((server) => ({ + url: server.url, + exitCode: server.exitCode, + external: false, + })), + ); + }; + + const createOpenCodeSdkClient: OpenCodeRuntimeShape["createOpenCodeSdkClient"] = (input) => + createOpencodeClient({ + baseUrl: input.baseUrl, + directory: input.directory, + ...(input.serverPassword + ? { + headers: { + Authorization: `Basic ${Buffer.from(`opencode:${input.serverPassword}`, "utf8").toString("base64")}`, + }, + } + : {}), + throwOnError: true, + }); + + const loadProviders = (client: OpencodeClient) => + runOpenCodeSdk("provider.list", () => client.provider.list()).pipe( + Effect.filterMapOrFail( + (list) => + list.data + ? Result.succeed(list.data) + : Result.fail( + new OpenCodeRuntimeError({ + operation: "provider.list", + detail: "OpenCode provider list was empty.", + }), + ), + (result) => result, + ), + ); + + const loadAgents = (client: OpencodeClient) => + runOpenCodeSdk("app.agents", () => client.app.agents()).pipe( + Effect.map((result) => result.data ?? []), + ); + + const loadOpenCodeInventory: OpenCodeRuntimeShape["loadOpenCodeInventory"] = (client) => + Effect.all([loadProviders(client), loadAgents(client)], { concurrency: "unbounded" }).pipe( + Effect.map(([providerList, agents]) => ({ providerList, agents })), + ); + + return { + startOpenCodeServerProcess, + connectToOpenCodeServer, + runOpenCodeCommand, + createOpenCodeSdkClient, + loadOpenCodeInventory, + } satisfies OpenCodeRuntimeShape; +}); + +export class OpenCodeRuntime extends Context.Service()( + "t3/provider/OpenCodeRuntime", +) {} + +export const OpenCodeRuntimeLive = Layer.effect(OpenCodeRuntime, makeOpenCodeRuntime).pipe( + Layer.provide(NetService.layer), +); diff --git a/apps/server/src/server.test.ts b/apps/server/src/server.test.ts index 66d776152e..47e159d303 100644 --- a/apps/server/src/server.test.ts +++ b/apps/server/src/server.test.ts @@ -1830,7 +1830,14 @@ it.layer(NodeServices.layer)("server router seam", (it) => { ); assertTrue(result._tag === "Failure"); - assertInclude(String(result.failure), "SocketOpenError"); + const failureMessage = String(result.failure); + assertTrue( + failureMessage.includes("SocketOpenError") || failureMessage.includes("SocketCloseError"), + ); + assertTrue( + failureMessage.includes("Unauthorized") || + failureMessage.includes("An error occurred during Open"), + ); }).pipe(Effect.provide(NodeHttpServer.layerTest)), ); diff --git a/apps/server/src/server.ts b/apps/server/src/server.ts index 9aee0b987f..f94bbb34b5 100644 --- a/apps/server/src/server.ts +++ b/apps/server/src/server.ts @@ -76,6 +76,7 @@ import { orchestrationDispatchRouteLayer, orchestrationSnapshotRouteLayer, } from "./orchestration/http.ts"; +import { NetService } from "@t3tools/shared/Net"; const PtyAdapterLive = Layer.unwrap( Effect.gen(function* () { @@ -243,6 +244,7 @@ const RuntimeDependenciesLive = ReactorLayerLive.pipe( Layer.provideMerge(AnalyticsServiceLayerLive), Layer.provideMerge(OpenLive), Layer.provideMerge(ServerLifecycleEventsLive), + Layer.provide(NetService.layer), ); const RuntimeServicesLive = ServerRuntimeStartupLive.pipe( diff --git a/apps/web/src/components/chat/TraitsPicker.browser.tsx b/apps/web/src/components/chat/TraitsPicker.browser.tsx index f39d0defc7..dbfbf09287 100644 --- a/apps/web/src/components/chat/TraitsPicker.browser.tsx +++ b/apps/web/src/components/chat/TraitsPicker.browser.tsx @@ -630,7 +630,11 @@ describe("TraitsPicker (Codex)", () => { // ── OpenCode TraitsPicker tests ─────────────────────────────────────── -async function mountOpenCodePicker(props: { model?: string; options?: OpenCodeModelOptions }) { +async function mountOpenCodePicker(props: { + model?: string; + options?: OpenCodeModelOptions; + models?: ServerProvider["models"]; +}) { const threadId = ThreadId.make("thread-opencode-traits"); const threadRef = scopeThreadRef(LOCAL_ENVIRONMENT_ID, threadId); const threadKey = scopedThreadKey(threadRef); @@ -665,7 +669,7 @@ async function mountOpenCodePicker(props: { model?: string; options?: OpenCodeMo const screen = await render( { expect(text).not.toContain("Medium · plan"); }); }); + + it("does not show a leading separator when only agent options are available", async () => { + await using _ = await mountOpenCodePicker({ + model: "openai/gpt-5.4", + models: [ + { + slug: "openai/gpt-5.4", + name: "OpenAI · GPT-5.4", + isCustom: false, + capabilities: { + reasoningEffortLevels: [], + supportsFastMode: false, + supportsThinkingToggle: false, + contextWindowOptions: [], + promptInjectedEffortLevels: [], + variantOptions: [], + agentOptions: [ + { value: "build", label: "Build", isDefault: true }, + { value: "plan", label: "Plan" }, + ], + }, + }, + ], + }); + + await page.getByRole("button").click(); + + await vi.waitFor(() => { + const text = document.body.textContent ?? ""; + expect(text).toContain("Agent"); + expect(text).toContain("Build (default)"); + expect(text).toContain("Plan"); + expect(document.querySelectorAll('[data-slot="menu-separator"]')).toHaveLength(0); + }); + }); }); describe("TraitsPicker (Cursor)", () => { diff --git a/apps/web/src/components/chat/TraitsPicker.tsx b/apps/web/src/components/chat/TraitsPicker.tsx index 77cb1b9a26..d30fba832e 100644 --- a/apps/web/src/components/chat/TraitsPicker.tsx +++ b/apps/web/src/components/chat/TraitsPicker.tsx @@ -91,7 +91,7 @@ function resolveNamedOption( return matchingOption; } } - return options.find((option) => option.isDefault) ?? null; + return options.find((option) => option.isDefault) ?? options[0] ?? null; } function getRawContextWindow( @@ -301,6 +301,12 @@ export const TraitsMenuContent = memo(function TraitsMenuContentImpl({ allowPromptInjectedEffort, }); const defaultEffort = getDefaultEffort(caps); + const showsEffortSection = showEffort; + const showsThinkingSection = !showEffort && showThinking; + const showsFastModeSection = showFastMode; + const showsContextWindowSection = showContextWindow; + const hasSectionsBeforeAgent = + showsEffortSection || showsThinkingSection || showsFastModeSection || showsContextWindowSection; const handleEffortChange = useCallback( (value: string) => { @@ -348,7 +354,7 @@ export const TraitsMenuContent = memo(function TraitsMenuContentImpl({ return ( <> - {showEffort ? ( + {showsEffortSection ? ( <>
@@ -378,7 +384,7 @@ export const TraitsMenuContent = memo(function TraitsMenuContentImpl({ - ) : showThinking ? ( + ) : showsThinkingSection ? (
Thinking
) : null} - {showFastMode ? ( + {showsFastModeSection ? ( <> - {showEffort || showThinking ? : null} + {showsEffortSection || showsThinkingSection ? : null}
Fast Mode
) : null} - {showContextWindow ? ( + {showsContextWindowSection ? ( <> - {showEffort || showThinking || showFastMode ? : null} + {showsEffortSection || showsThinkingSection || showsFastModeSection ? ( + + ) : null}
Context Window @@ -442,7 +450,7 @@ export const TraitsMenuContent = memo(function TraitsMenuContentImpl({ ) : null} {agentOptions.length > 0 ? ( <> - + {hasSectionsBeforeAgent ? : null}
Agent
option.value === raw)) { return raw; } - return options.find((option) => option.isDefault)?.value; + return options.find((option) => option.isDefault)?.value ?? options[0]?.value; } export function normalizeOpenCodeModelOptionsWithCapabilities( From 6d1505c9fb6ef9a7e147133bb9827f2f36e6945c Mon Sep 17 00:00:00 2001 From: Craig <11655707+CodeZeno@users.noreply.github.com> Date: Mon, 20 Apr 2026 16:25:39 +1000 Subject: [PATCH 09/82] fix: Change right panel sheet to be below title bar / action bar (#2224) Co-authored-by: Julius Marminge --- apps/web/src/components/DiffPanelShell.tsx | 4 ++-- apps/web/src/rightPanelLayout.ts | 3 ++- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/apps/web/src/components/DiffPanelShell.tsx b/apps/web/src/components/DiffPanelShell.tsx index b3ebb0fffd..829ed4159d 100644 --- a/apps/web/src/components/DiffPanelShell.tsx +++ b/apps/web/src/components/DiffPanelShell.tsx @@ -10,9 +10,9 @@ export type DiffPanelMode = "inline" | "sheet" | "sidebar"; function getDiffPanelHeaderRowClassName(mode: DiffPanelMode) { const shouldUseDragRegion = isElectron && mode !== "sheet"; return cn( - "flex items-center justify-between gap-2 px-4 wco:pr-[calc(100vw-env(titlebar-area-width)-env(titlebar-area-x)+1em)]", + "flex items-center justify-between gap-2 px-4", shouldUseDragRegion - ? "drag-region h-[52px] border-b border-border wco:h-[env(titlebar-area-height)]" + ? "drag-region h-[52px] border-b border-border wco:h-[env(titlebar-area-height)] wco:pr-[calc(100vw-env(titlebar-area-width)-env(titlebar-area-x)+1em)]" : "h-12 wco:max-h-[env(titlebar-area-height)]", ); } diff --git a/apps/web/src/rightPanelLayout.ts b/apps/web/src/rightPanelLayout.ts index c94f52a9cb..981006315e 100644 --- a/apps/web/src/rightPanelLayout.ts +++ b/apps/web/src/rightPanelLayout.ts @@ -1,2 +1,3 @@ export const RIGHT_PANEL_INLINE_LAYOUT_MEDIA_QUERY = "(max-width: 1180px)"; -export const RIGHT_PANEL_SHEET_CLASS_NAME = "w-[min(88vw,820px)] max-w-[820px] p-0"; +export const RIGHT_PANEL_SHEET_CLASS_NAME = + "w-[min(88vw,820px)] max-w-[820px] p-0 wco:mt-[env(titlebar-area-height)] wco:h-[calc(100%-env(titlebar-area-height))] wco:max-h-[calc(100%-env(titlebar-area-height))]"; From de05b0c94e257e69afc346ae6daaea85fcfb4e65 Mon Sep 17 00:00:00 2001 From: Mike Olson Date: Mon, 20 Apr 2026 02:29:56 -0400 Subject: [PATCH 10/82] fix(web): restore manual sort drag and keep per-group expand state (#2221) --- apps/web/src/components/Sidebar.logic.test.ts | 36 +++ apps/web/src/components/Sidebar.tsx | 8 +- apps/web/src/environments/runtime/service.ts | 10 +- apps/web/src/hooks/useHandleNewThread.ts | 4 +- apps/web/src/hooks/useSettings.ts | 9 + apps/web/src/logicalProject.ts | 7 + apps/web/src/uiStateStore.test.ts | 252 ++++++++++++++++-- apps/web/src/uiStateStore.ts | 116 ++++++-- 8 files changed, 398 insertions(+), 44 deletions(-) diff --git a/apps/web/src/components/Sidebar.logic.test.ts b/apps/web/src/components/Sidebar.logic.test.ts index 6aa042a169..f92f2f628c 100644 --- a/apps/web/src/components/Sidebar.logic.test.ts +++ b/apps/web/src/components/Sidebar.logic.test.ts @@ -309,6 +309,42 @@ describe("orderItemsByPreferredIds", () => { ProjectId.make("project-1"), ]); }); + + it("honors projectOrder physical keys via getProjectOrderKey", async () => { + // Regression guard for #1904 / the regression introduced by #2055: + // `projectOrder` is populated with physical keys (envId + cwd-derived) + // by the store and by drag-end handlers. Readers must identify projects + // with the same key format, or manual sort silently snaps back. + const { getProjectOrderKey } = await import("../logicalProject"); + const projects = [ + { + environmentId: EnvironmentId.make("environment-local"), + id: ProjectId.make("id-alpha"), + cwd: "/work/alpha", + }, + { + environmentId: EnvironmentId.make("environment-local"), + id: ProjectId.make("id-beta"), + cwd: "/work/beta", + }, + { + environmentId: EnvironmentId.make("environment-local"), + id: ProjectId.make("id-gamma"), + cwd: "/work/gamma", + }, + ]; + const ordered = orderItemsByPreferredIds({ + items: projects, + preferredIds: [getProjectOrderKey(projects[2]!), getProjectOrderKey(projects[0]!)], + getId: getProjectOrderKey, + }); + + expect(ordered.map((project) => project.cwd)).toEqual([ + "/work/gamma", + "/work/alpha", + "/work/beta", + ]); + }); }); describe("resolveAdjacentThreadId", () => { diff --git a/apps/web/src/components/Sidebar.tsx b/apps/web/src/components/Sidebar.tsx index 8335042c11..d25f930c0d 100644 --- a/apps/web/src/components/Sidebar.tsx +++ b/apps/web/src/components/Sidebar.tsx @@ -168,7 +168,11 @@ import { CommandDialogTrigger } from "./ui/command"; import { readEnvironmentApi } from "../environmentApi"; import { useSettings, useUpdateSettings } from "~/hooks/useSettings"; import { useServerKeybindings } from "../rpc/serverState"; -import { derivePhysicalProjectKey, deriveProjectGroupingOverrideKey } from "../logicalProject"; +import { + derivePhysicalProjectKey, + deriveProjectGroupingOverrideKey, + getProjectOrderKey, +} from "../logicalProject"; import { useSavedEnvironmentRegistryStore, useSavedEnvironmentRuntimeStore, @@ -2708,7 +2712,7 @@ export default function Sidebar() { return orderItemsByPreferredIds({ items: projects, preferredIds: projectOrder, - getId: (project) => scopedProjectKey(scopeProjectRef(project.environmentId, project.id)), + getId: getProjectOrderKey, }); }, [projectOrder, projects]); diff --git a/apps/web/src/environments/runtime/service.ts b/apps/web/src/environments/runtime/service.ts index 40f8f8f2c0..775df0184e 100644 --- a/apps/web/src/environments/runtime/service.ts +++ b/apps/web/src/environments/runtime/service.ts @@ -61,7 +61,11 @@ import { useTerminalStateStore } from "~/terminalStateStore"; import { useUiStateStore } from "~/uiStateStore"; import { WsTransport } from "../../rpc/wsTransport"; import { createWsRpcClient, type WsRpcClient } from "../../rpc/wsRpcClient"; -import { derivePhysicalProjectKey } from "../../logicalProject"; +import { + deriveLogicalProjectKeyFromSettings, + derivePhysicalProjectKey, +} from "../../logicalProject"; +import { getClientSettings } from "~/hooks/useSettings"; type EnvironmentServiceState = { readonly queryClient: QueryClient; @@ -468,9 +472,11 @@ function coalesceOrchestrationUiEvents( function syncProjectUiFromStore() { const projects = selectProjectsAcrossEnvironments(useStore.getState()); + const clientSettings = getClientSettings(); useUiStateStore.getState().syncProjects( projects.map((project) => ({ key: derivePhysicalProjectKey(project), + logicalKey: deriveLogicalProjectKeyFromSettings(project, clientSettings), cwd: project.cwd, })), ); @@ -541,9 +547,11 @@ function applyRecoveredEventBatch( useStore.getState().applyOrchestrationEvents(uiEvents, environmentId); if (needsProjectUiSync) { const projects = selectProjectsAcrossEnvironments(useStore.getState()); + const clientSettings = getClientSettings(); useUiStateStore.getState().syncProjects( projects.map((project) => ({ key: derivePhysicalProjectKey(project), + logicalKey: deriveLogicalProjectKeyFromSettings(project, clientSettings), cwd: project.cwd, })), ); diff --git a/apps/web/src/hooks/useHandleNewThread.ts b/apps/web/src/hooks/useHandleNewThread.ts index d512b6c7e7..3630171bf5 100644 --- a/apps/web/src/hooks/useHandleNewThread.ts +++ b/apps/web/src/hooks/useHandleNewThread.ts @@ -10,7 +10,7 @@ import { } from "../composerDraftStore"; import { newDraftId, newThreadId } from "../lib/utils"; import { orderItemsByPreferredIds } from "../components/Sidebar.logic"; -import { deriveLogicalProjectKeyFromSettings } from "../logicalProject"; +import { deriveLogicalProjectKeyFromSettings, getProjectOrderKey } from "../logicalProject"; import { selectProjectsAcrossEnvironments, useStore } from "../store"; import { createThreadSelectorByRef } from "../storeSelectors"; import { resolveThreadRouteTarget } from "../threadRoutes"; @@ -169,7 +169,7 @@ export function useHandleNewThread() { return orderItemsByPreferredIds({ items: projects, preferredIds: projectOrder, - getId: (project) => scopedProjectKey(scopeProjectRef(project.environmentId, project.id)), + getId: getProjectOrderKey, }); }, [projectOrder, projects]); const handleNewThread = useNewThreadState(); diff --git a/apps/web/src/hooks/useSettings.ts b/apps/web/src/hooks/useSettings.ts index 18b2668a60..37a6872bd9 100644 --- a/apps/web/src/hooks/useSettings.ts +++ b/apps/web/src/hooks/useSettings.ts @@ -123,6 +123,15 @@ function splitPatch(patch: Partial): { * only re-render when the slice they care about changes. */ +/** + * Non-hook accessor for the current merged client settings snapshot. + * Used by non-React code paths (e.g. runtime services) that need the latest + * settings without subscribing. + */ +export function getClientSettings(): ClientSettings { + return getClientSettingsSnapshot(); +} + export function useSettings(selector?: (s: UnifiedSettings) => T): T { const serverSettings = useServerSettings(); const clientSettings = useSyncExternalStore( diff --git a/apps/web/src/logicalProject.ts b/apps/web/src/logicalProject.ts index d30bb60ca0..f19b64ac80 100644 --- a/apps/web/src/logicalProject.ts +++ b/apps/web/src/logicalProject.ts @@ -65,6 +65,13 @@ export function deriveProjectGroupingOverrideKey( return derivePhysicalProjectKey(project); } +// Key under which a project's manual sort order (projectOrder) is stored. +// Must stay aligned with the writer side in `uiStateStore.syncProjects` and +// the drag handlers in `Sidebar` so readers and writers agree. +export function getProjectOrderKey(project: Pick): string { + return derivePhysicalProjectKey(project); +} + export function resolveProjectGroupingMode( project: Pick, settings: ProjectGroupingSettings, diff --git a/apps/web/src/uiStateStore.test.ts b/apps/web/src/uiStateStore.test.ts index c906bbc1d7..f63208d9ba 100644 --- a/apps/web/src/uiStateStore.test.ts +++ b/apps/web/src/uiStateStore.test.ts @@ -1,9 +1,13 @@ import { ProjectId, ThreadId } from "@t3tools/contracts"; -import { describe, expect, it } from "vitest"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import { clearThreadUi, + hydratePersistedProjectState, markThreadUnread, + PERSISTED_STATE_KEY, + type PersistedUiState, + persistState, reorderProjects, setProjectExpanded, setThreadChangedFilesExpanded, @@ -183,40 +187,43 @@ describe("uiStateStore pure functions", () => { }); const next = syncProjects(initialState, [ - { key: project1, cwd: "/tmp/project-1" }, - { key: project2, cwd: "/tmp/project-2" }, - { key: project3, cwd: "/tmp/project-3" }, + { key: project1, logicalKey: project1, cwd: "/tmp/project-1" }, + { key: project2, logicalKey: project2, cwd: "/tmp/project-2" }, + { key: project3, logicalKey: project3, cwd: "/tmp/project-3" }, ]); expect(next.projectOrder).toEqual([project2, project1, project3]); expect(next.projectExpandedById[project2]).toBe(false); }); - it("syncProjects preserves manual order when a project is recreated with the same cwd", () => { - const oldProject1 = ProjectId.make("project-1"); - const oldProject2 = ProjectId.make("project-2"); - const recreatedProject2 = ProjectId.make("project-2b"); + it("syncProjects preserves manual order across project id churn at the same cwd", () => { + // Under the current design, physical key and logical key are both + // cwd-derived, so an internal project-id change doesn't alter the store + // keys. This test locks in that stability: re-syncing the same cwds keeps + // manual order and collapse state. + const keyProject1 = "env-local:/tmp/project-1"; + const keyProject2 = "env-local:/tmp/project-2"; const initialState = syncProjects( makeUiState({ projectExpandedById: { - [oldProject1]: true, - [oldProject2]: false, + [keyProject1]: true, + [keyProject2]: false, }, - projectOrder: [oldProject2, oldProject1], + projectOrder: [keyProject2, keyProject1], }), [ - { key: oldProject1, cwd: "/tmp/project-1" }, - { key: oldProject2, cwd: "/tmp/project-2" }, + { key: keyProject1, logicalKey: keyProject1, cwd: "/tmp/project-1" }, + { key: keyProject2, logicalKey: keyProject2, cwd: "/tmp/project-2" }, ], ); const next = syncProjects(initialState, [ - { key: oldProject1, cwd: "/tmp/project-1" }, - { key: recreatedProject2, cwd: "/tmp/project-2" }, + { key: keyProject1, logicalKey: keyProject1, cwd: "/tmp/project-1" }, + { key: keyProject2, logicalKey: keyProject2, cwd: "/tmp/project-2" }, ]); - expect(next.projectOrder).toEqual([recreatedProject2, oldProject1]); - expect(next.projectExpandedById[recreatedProject2]).toBe(false); + expect(next.projectOrder).toEqual([keyProject2, keyProject1]); + expect(next.projectExpandedById[keyProject2]).toBe(false); }); it("syncProjects returns a new state when only project cwd changes", () => { @@ -228,16 +235,70 @@ describe("uiStateStore pure functions", () => { }, projectOrder: [project1], }), - [{ key: project1, cwd: "/tmp/project-1" }], + [{ key: project1, logicalKey: project1, cwd: "/tmp/project-1" }], ); - const next = syncProjects(initialState, [{ key: project1, cwd: "/tmp/project-1-renamed" }]); + const next = syncProjects(initialState, [ + { key: project1, logicalKey: project1, cwd: "/tmp/project-1-renamed" }, + ]); expect(next).not.toBe(initialState); expect(next.projectOrder).toEqual([project1]); expect(next.projectExpandedById[project1]).toBe(false); }); + it("syncProjects keys projectExpandedById by the logical key, not the physical key", () => { + // In repository grouping mode, multiple physical projects (different + // environments or different repo-relative paths) collapse into one + // logical group. The group's expand state must be keyed by the logical + // key so clicks on the grouped row toggle the shared state, and so the + // state survives subsequent syncProjects calls (which rebuild the map + // from incoming inputs). + const physicalLocal = "env-local:/repo/project"; + const physicalRemote = "env-remote:/repo/project"; + const logicalKey = "repo-canonical-key"; + + const initial = syncProjects(makeUiState(), [ + { key: physicalLocal, logicalKey, cwd: "/repo/project" }, + { key: physicalRemote, logicalKey, cwd: "/repo/project" }, + ]); + + expect(initial.projectExpandedById).toEqual({ [logicalKey]: true }); + + const afterCollapse = { ...initial, projectExpandedById: { [logicalKey]: false } }; + const next = syncProjects(afterCollapse, [ + { key: physicalLocal, logicalKey, cwd: "/repo/project" }, + { key: physicalRemote, logicalKey, cwd: "/repo/project" }, + ]); + + expect(next.projectExpandedById[logicalKey]).toBe(false); + }); + + it("syncProjects preserves expand state when a project's logical key changes", () => { + // Example: late-arriving repo metadata flips grouping identity from the + // physical key to a canonical repository key. The row did not actually + // change, so the user's collapse choice must carry over. + const physicalKey = "env-local:/repo/project"; + const previousLogicalKey = physicalKey; + const nextLogicalKey = "repo-canonical-key"; + + const initial = syncProjects(makeUiState(), [ + { key: physicalKey, logicalKey: previousLogicalKey, cwd: "/repo/project" }, + ]); + + expect(initial.projectExpandedById[previousLogicalKey]).toBe(true); + + const afterCollapse = { + ...initial, + projectExpandedById: { [previousLogicalKey]: false }, + }; + const next = syncProjects(afterCollapse, [ + { key: physicalKey, logicalKey: nextLogicalKey, cwd: "/repo/project" }, + ]); + + expect(next.projectExpandedById[nextLogicalKey]).toBe(false); + }); + it("syncThreads prunes missing thread UI state", () => { const thread1 = ThreadId.make("thread-1"); const thread2 = ThreadId.make("thread-2"); @@ -346,3 +407,156 @@ describe("uiStateStore pure functions", () => { expect(next.threadChangedFilesExpandedById).toEqual({}); }); }); + +describe("uiStateStore persistence round-trip", () => { + function createLocalStorageStub(): Storage { + const store = new Map(); + return { + clear: () => { + store.clear(); + }, + getItem: (key) => store.get(key) ?? null, + key: (index) => [...store.keys()][index] ?? null, + get length() { + return store.size; + }, + removeItem: (key) => { + store.delete(key); + }, + setItem: (key, value) => { + store.set(key, value); + }, + }; + } + + let localStorageStub: Storage; + + beforeEach(() => { + localStorageStub = createLocalStorageStub(); + vi.stubGlobal("window", { localStorage: localStorageStub }); + vi.stubGlobal("localStorage", localStorageStub); + // Reset module-level persistence state so tests don't bleed into each other. + hydratePersistedProjectState({ collapsedProjectCwds: [], expandedProjectCwds: [] }); + }); + + afterEach(() => { + vi.unstubAllGlobals(); + }); + + it("preserves all-collapsed project state across restart", () => { + // Regression: pre-fix, persistState only wrote `expandedProjectCwds`, so + // an empty array on rehydrate was indistinguishable from a fresh install + // and the syncProjects fallback re-expanded every row. + const projectA = { key: "kA", logicalKey: "kA", cwd: "/projA" }; + const projectB = { key: "kB", logicalKey: "kB", cwd: "/projB" }; + + let state = syncProjects(makeUiState(), [projectA, projectB]); + state = setProjectExpanded(state, projectA.key, false); + state = setProjectExpanded(state, projectB.key, false); + persistState(state); + + const persisted = JSON.parse( + localStorageStub.getItem(PERSISTED_STATE_KEY) ?? "{}", + ) as PersistedUiState; + hydratePersistedProjectState(persisted); + const rehydrated = syncProjects(makeUiState(), [projectA, projectB]); + + expect(rehydrated.projectExpandedById).toEqual({ + [projectA.key]: false, + [projectB.key]: false, + }); + }); + + it("respects mixed expand state on rehydrate and defaults new projects to expanded", () => { + const projectA = { key: "kA", logicalKey: "kA", cwd: "/projA" }; + const projectB = { key: "kB", logicalKey: "kB", cwd: "/projB" }; + const projectC = { key: "kC", logicalKey: "kC", cwd: "/projC" }; + + let state = syncProjects(makeUiState(), [projectA, projectB]); + state = setProjectExpanded(state, projectB.key, false); + persistState(state); + + const persisted = JSON.parse( + localStorageStub.getItem(PERSISTED_STATE_KEY) ?? "{}", + ) as PersistedUiState; + hydratePersistedProjectState(persisted); + const rehydrated = syncProjects(makeUiState(), [projectA, projectB, projectC]); + + expect(rehydrated.projectExpandedById).toEqual({ + [projectA.key]: true, + [projectB.key]: false, + [projectC.key]: true, + }); + }); + + it("preserves legacy not-in-expanded-list = collapsed for one upgrade session", () => { + // Pre-fix shape only stored expandedProjectCwds. Absence of + // collapsedProjectCwds opts the session into the legacy fallback so + // upgrade users do not see previously collapsed rows pop open. + hydratePersistedProjectState({ + expandedProjectCwds: ["/projA"], + }); + + const rehydrated = syncProjects(makeUiState(), [ + { key: "kA", logicalKey: "kA", cwd: "/projA" }, + { key: "kB", logicalKey: "kB", cwd: "/projB" }, + ]); + + expect(rehydrated.projectExpandedById).toEqual({ + kA: true, + kB: false, + }); + }); + + it("preserves manual project order across restart", () => { + const projectA = { key: "kOrderA", logicalKey: "kOrderA", cwd: "/order-projA" }; + const projectB = { key: "kOrderB", logicalKey: "kOrderB", cwd: "/order-projB" }; + const projectC = { key: "kOrderC", logicalKey: "kOrderC", cwd: "/order-projC" }; + + let state = syncProjects(makeUiState(), [projectA, projectB, projectC]); + state = reorderProjects(state, [projectC.key], [projectA.key]); + expect(state.projectOrder).toEqual([projectC.key, projectA.key, projectB.key]); + persistState(state); + + const persisted = JSON.parse( + localStorageStub.getItem(PERSISTED_STATE_KEY) ?? "{}", + ) as PersistedUiState; + expect(persisted.projectOrderCwds).toEqual([projectC.cwd, projectA.cwd, projectB.cwd]); + + hydratePersistedProjectState(persisted); + // Fresh state (empty projectOrder) so syncProjects derives order from + // persistedProjectOrderCwds rather than the in-memory projectOrder branch. + const rehydrated = syncProjects(makeUiState(), [projectA, projectB, projectC]); + + expect(rehydrated.projectOrder).toEqual([projectC.key, projectA.key, projectB.key]); + }); + + it("preserves expand state across restart when project's logical key changes", () => { + // After restart, in-memory previousExpandedById is empty, so the + // previousLogicalKey-to-state bridge in syncProjects cannot help. The + // persisted-cwd fallback is the only mechanism that can carry collapse + // state across a restart that also flips a project into a new logical + // group (e.g. late-arriving repo metadata). This locks in that path. + const physicalKey = "env-local:/lk-restart-proj"; + const previousLogicalKey = physicalKey; + const cwd = "/lk-restart-proj"; + + let state = syncProjects(makeUiState(), [ + { key: physicalKey, logicalKey: previousLogicalKey, cwd }, + ]); + state = setProjectExpanded(state, previousLogicalKey, false); + persistState(state); + + const persisted = JSON.parse( + localStorageStub.getItem(PERSISTED_STATE_KEY) ?? "{}", + ) as PersistedUiState; + hydratePersistedProjectState(persisted); + + const nextLogicalKey = "lk-restart-canonical"; + const rehydrated = syncProjects(makeUiState(), [ + { key: physicalKey, logicalKey: nextLogicalKey, cwd }, + ]); + + expect(rehydrated.projectExpandedById[nextLogicalKey]).toBe(false); + }); +}); diff --git a/apps/web/src/uiStateStore.ts b/apps/web/src/uiStateStore.ts index 7ae7232063..8bd65ffc56 100644 --- a/apps/web/src/uiStateStore.ts +++ b/apps/web/src/uiStateStore.ts @@ -1,7 +1,7 @@ import { Debouncer } from "@tanstack/react-pacer"; import { create } from "zustand"; -const PERSISTED_STATE_KEY = "t3code:ui-state:v1"; +export const PERSISTED_STATE_KEY = "t3code:ui-state:v1"; const LEGACY_PERSISTED_STATE_KEYS = [ "t3code:renderer-state:v8", "t3code:renderer-state:v7", @@ -15,7 +15,8 @@ const LEGACY_PERSISTED_STATE_KEYS = [ "codething:renderer-state:v1", ] as const; -interface PersistedUiState { +export interface PersistedUiState { + collapsedProjectCwds?: string[]; expandedProjectCwds?: string[]; projectOrderCwds?: string[]; threadChangedFilesExpandedById?: Record>; @@ -34,7 +35,10 @@ export interface UiThreadState { export interface UiState extends UiProjectState, UiThreadState {} export interface SyncProjectInput { + /** Physical project key (env + cwd). Used for manual sort order. */ key: string; + /** Logical group key. Used for expand/collapse state. */ + logicalKey: string; cwd: string; } @@ -50,9 +54,17 @@ const initialState: UiState = { threadChangedFilesExpandedById: {}, }; +const persistedCollapsedProjectCwds = new Set(); const persistedExpandedProjectCwds = new Set(); const persistedProjectOrderCwds: string[] = []; +// Pre-fix persisted shape only listed expanded cwds, so anything not listed +// was treated as collapsed. Track whether the loaded blob carried the new +// `collapsedProjectCwds` field so we can preserve that legacy semantic for +// one session after upgrade, until persistState rewrites in the new shape. +let persistedProjectStateUsesLegacyShape = false; const currentProjectCwdById = new Map(); +const currentProjectCwdsByLogicalKey = new Map(); +const currentLogicalKeyByPhysicalKey = new Map(); let legacyKeysCleanedUp = false; function readPersistedState(): UiState { @@ -113,9 +125,16 @@ function sanitizePersistedThreadChangedFilesExpanded( return nextState; } -function hydratePersistedProjectState(parsed: PersistedUiState): void { +export function hydratePersistedProjectState(parsed: PersistedUiState): void { + persistedCollapsedProjectCwds.clear(); persistedExpandedProjectCwds.clear(); persistedProjectOrderCwds.length = 0; + persistedProjectStateUsesLegacyShape = !Array.isArray(parsed.collapsedProjectCwds); + for (const cwd of parsed.collapsedProjectCwds ?? []) { + if (typeof cwd === "string" && cwd.length > 0) { + persistedCollapsedProjectCwds.add(cwd); + } + } for (const cwd of parsed.expandedProjectCwds ?? []) { if (typeof cwd === "string" && cwd.length > 0) { persistedExpandedProjectCwds.add(cwd); @@ -128,17 +147,20 @@ function hydratePersistedProjectState(parsed: PersistedUiState): void { } } -function persistState(state: UiState): void { +export function persistState(state: UiState): void { if (typeof window === "undefined") { return; } try { + // Persist collapsed cwds explicitly so an empty/missing field unambiguously + // means "first install" rather than "user collapsed everything"; without + // this, the syncProjects fallback would re-expand all rows on next launch. + const collapsedProjectCwds = Object.entries(state.projectExpandedById) + .filter(([, expanded]) => !expanded) + .flatMap(([logicalKey]) => currentProjectCwdsByLogicalKey.get(logicalKey) ?? []); const expandedProjectCwds = Object.entries(state.projectExpandedById) .filter(([, expanded]) => expanded) - .flatMap(([projectId]) => { - const cwd = currentProjectCwdById.get(projectId); - return cwd ? [cwd] : []; - }); + .flatMap(([logicalKey]) => currentProjectCwdsByLogicalKey.get(logicalKey) ?? []); const projectOrderCwds = state.projectOrder.flatMap((projectId) => { const cwd = currentProjectCwdById.get(projectId); return cwd ? [cwd] : []; @@ -154,6 +176,7 @@ function persistState(state: UiState): void { window.localStorage.setItem( PERSISTED_STATE_KEY, JSON.stringify({ + collapsedProjectCwds, expandedProjectCwds, projectOrderCwds, threadChangedFilesExpandedById, @@ -211,12 +234,40 @@ function nestedBooleanRecordsEqual( export function syncProjects(state: UiState, projects: readonly SyncProjectInput[]): UiState { const previousProjectCwdById = new Map(currentProjectCwdById); - const previousProjectIdByCwd = new Map( - [...previousProjectCwdById.entries()].map(([projectId, cwd]) => [cwd, projectId] as const), - ); + const previousLogicalKeyByPhysicalKey = new Map(currentLogicalKeyByPhysicalKey); currentProjectCwdById.clear(); + currentLogicalKeyByPhysicalKey.clear(); for (const project of projects) { currentProjectCwdById.set(project.key, project.cwd); + currentLogicalKeyByPhysicalKey.set(project.key, project.logicalKey); + } + currentProjectCwdsByLogicalKey.clear(); + for (const project of projects) { + const cwds = currentProjectCwdsByLogicalKey.get(project.logicalKey); + if (cwds) { + if (!cwds.includes(project.cwd)) { + cwds.push(project.cwd); + } + } else { + currentProjectCwdsByLogicalKey.set(project.logicalKey, [project.cwd]); + } + } + // Build reverse map: for each new logical key, which previous logical keys + // did its member projects live under? Lets us preserve expand state when a + // project's logical key changes (e.g. late-arriving repo metadata flips the + // group identity). + const previousLogicalKeysByNewLogicalKey = new Map>(); + for (const project of projects) { + const previousLogicalKey = previousLogicalKeyByPhysicalKey.get(project.key); + if (!previousLogicalKey || previousLogicalKey === project.logicalKey) { + continue; + } + const set = previousLogicalKeysByNewLogicalKey.get(project.logicalKey); + if (set) { + set.add(previousLogicalKey); + } else { + previousLogicalKeysByNewLogicalKey.set(project.logicalKey, new Set([previousLogicalKey])); + } } const cwdMappingChanged = previousProjectCwdById.size !== currentProjectCwdById.size || @@ -228,14 +279,38 @@ export function syncProjects(state: UiState, projects: readonly SyncProjectInput persistedProjectOrderCwds.map((cwd, index) => [cwd, index] as const), ); const mappedProjects = projects.map((project, index) => { - const previousProjectIdForCwd = previousProjectIdByCwd.get(project.cwd); - const expanded = - previousExpandedById[project.key] ?? - (previousProjectIdForCwd ? previousExpandedById[previousProjectIdForCwd] : undefined) ?? - (persistedExpandedProjectCwds.size > 0 - ? persistedExpandedProjectCwds.has(project.cwd) - : true); - nextExpandedById[project.key] = expanded; + if (!(project.logicalKey in nextExpandedById)) { + const groupCwds = currentProjectCwdsByLogicalKey.get(project.logicalKey) ?? [project.cwd]; + const fallbackFromPreviousLogicalKey = (() => { + const previousKeys = previousLogicalKeysByNewLogicalKey.get(project.logicalKey); + if (!previousKeys) { + return undefined; + } + for (const previousKey of previousKeys) { + if (previousKey in previousExpandedById) { + return previousExpandedById[previousKey]; + } + } + return undefined; + })(); + const fallbackFromPersistedShape = (() => { + if (groupCwds.some((cwd) => persistedExpandedProjectCwds.has(cwd))) { + return true; + } + if (groupCwds.some((cwd) => persistedCollapsedProjectCwds.has(cwd))) { + return false; + } + if (persistedProjectStateUsesLegacyShape && persistedExpandedProjectCwds.size > 0) { + return false; + } + return true; + })(); + const expanded = + previousExpandedById[project.logicalKey] ?? + fallbackFromPreviousLogicalKey ?? + fallbackFromPersistedShape; + nextExpandedById[project.logicalKey] = expanded; + } return { id: project.key, cwd: project.cwd, @@ -246,6 +321,7 @@ export function syncProjects(state: UiState, projects: readonly SyncProjectInput const nextProjectOrder = state.projectOrder.length > 0 ? (() => { + const currentProjectIds = new Set(mappedProjects.map((project) => project.id)); const nextProjectIdByCwd = new Map( mappedProjects.map((project) => [project.cwd, project.id] as const), ); @@ -254,7 +330,7 @@ export function syncProjects(state: UiState, projects: readonly SyncProjectInput for (const projectId of state.projectOrder) { const matchedProjectId = - (projectId in nextExpandedById ? projectId : undefined) ?? + (currentProjectIds.has(projectId) ? projectId : undefined) ?? (() => { const previousCwd = previousProjectCwdById.get(projectId); return previousCwd ? nextProjectIdByCwd.get(previousCwd) : undefined; From f6978db60553716a9974b9e85f855bae8124905d Mon Sep 17 00:00:00 2001 From: Adam Mansfield Date: Mon, 20 Apr 2026 02:35:37 -0400 Subject: [PATCH 11/82] chore(turbo): pass through PATHEXT (#2184) --- turbo.json | 1 + 1 file changed, 1 insertion(+) diff --git a/turbo.json b/turbo.json index d4d58c15e6..e6ebeee912 100644 --- a/turbo.json +++ b/turbo.json @@ -23,6 +23,7 @@ "T3CODE_OTLP_EXPORT_INTERVAL_MS", "T3CODE_OTLP_SERVICE_NAME" ], + "globalPassThroughEnv": ["PATHEXT"], "tasks": { "build": { "dependsOn": ["^build"], From 40b3a800347462405b2d322ed5c0c60331f9e70d Mon Sep 17 00:00:00 2001 From: Adin Schmidt <9936213+adinschmidt@users.noreply.github.com> Date: Mon, 20 Apr 2026 22:45:56 -0400 Subject: [PATCH 12/82] fix(server): trim OpenCode provider model names (#2252) --- apps/server/src/provider/Layers/OpenCodeProvider.ts | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/apps/server/src/provider/Layers/OpenCodeProvider.ts b/apps/server/src/provider/Layers/OpenCodeProvider.ts index 5e51eae028..d43372ec5c 100644 --- a/apps/server/src/provider/Layers/OpenCodeProvider.ts +++ b/apps/server/src/provider/Layers/OpenCodeProvider.ts @@ -11,6 +11,7 @@ import { ServerSettingsService } from "../../serverSettings.ts"; import { makeManagedServerProvider } from "../makeManagedServerProvider.ts"; import { buildServerProvider, + nonEmptyTrimmed, parseGenericCliVersion, providerModelsFromSettings, } from "../providerSnapshot.ts"; @@ -204,10 +205,16 @@ function flattenOpenCodeModels(input: OpenCodeInventory): ReadonlyArray Date: Tue, 21 Apr 2026 11:15:41 -0400 Subject: [PATCH 13/82] fix: enforce opencode >= 1.14.19 and reveal window on Wayland (#2262) --- apps/desktop/src/main.ts | 22 +++--- apps/desktop/src/windowReveal.test.ts | 74 +++++++++++++++++++ apps/desktop/src/windowReveal.ts | 28 +++++++ .../provider/Layers/OpenCodeProvider.test.ts | 33 ++++++++- .../src/provider/Layers/OpenCodeProvider.ts | 31 ++++++++ 5 files changed, 177 insertions(+), 11 deletions(-) create mode 100644 apps/desktop/src/windowReveal.test.ts create mode 100644 apps/desktop/src/windowReveal.ts diff --git a/apps/desktop/src/main.ts b/apps/desktop/src/main.ts index 529ed55d03..c5507c6fb0 100644 --- a/apps/desktop/src/main.ts +++ b/apps/desktop/src/main.ts @@ -75,6 +75,7 @@ import { } from "./updateMachine.ts"; import { isArm64HostRunningIntelBuild, resolveDesktopRuntimeInfo } from "./runtimeArch.ts"; import { resolveDesktopAppBranding } from "./appBranding.ts"; +import { bindFirstRevealTrigger, type RevealSubscription } from "./windowReveal.ts"; syncShellEnvironment(); @@ -1998,16 +1999,17 @@ function createWindow(): BrowserWindow { emitUpdateState(); }); - let initialRevealScheduled = false; - const revealInitialWindow = () => { - if (initialRevealScheduled) { - return; - } - initialRevealScheduled = true; - revealWindow(window); - }; - - window.once("ready-to-show", revealInitialWindow); + // On Linux/Wayland with `show: false`, Electron's `ready-to-show` only + // fires after `show()` is called, deadlocking the standard "wait for + // ready, then show" pattern. Add `did-finish-load` as a Linux-only + // fallback so the window still surfaces once the renderer has loaded + // the page. Other platforms keep the no-flash `ready-to-show` path, + // since `did-finish-load` typically fires before the first paint there. + const revealSubscribers: RevealSubscription[] = [(fire) => window.once("ready-to-show", fire)]; + if (process.platform === "linux") { + revealSubscribers.push((fire) => window.webContents.once("did-finish-load", fire)); + } + bindFirstRevealTrigger(revealSubscribers, () => revealWindow(window)); if (isDevelopment) { void window.loadURL(resolveDesktopDevServerUrl()); diff --git a/apps/desktop/src/windowReveal.test.ts b/apps/desktop/src/windowReveal.test.ts new file mode 100644 index 0000000000..88285fec0c --- /dev/null +++ b/apps/desktop/src/windowReveal.test.ts @@ -0,0 +1,74 @@ +import { EventEmitter } from "node:events"; + +import { describe, expect, it, vi } from "vitest"; + +import { bindFirstRevealTrigger } from "./windowReveal.ts"; + +describe("bindFirstRevealTrigger", () => { + it("reveals when the first trigger fires", () => { + const window = new EventEmitter(); + const webContents = new EventEmitter(); + const reveal = vi.fn(); + + bindFirstRevealTrigger( + [ + (fire) => window.once("ready-to-show", fire), + (fire) => webContents.once("did-finish-load", fire), + ], + reveal, + ); + + window.emit("ready-to-show"); + + expect(reveal).toHaveBeenCalledTimes(1); + }); + + it("reveals when only the fallback trigger fires (Wayland deadlock case)", () => { + const window = new EventEmitter(); + const webContents = new EventEmitter(); + const reveal = vi.fn(); + + bindFirstRevealTrigger( + [ + (fire) => window.once("ready-to-show", fire), + (fire) => webContents.once("did-finish-load", fire), + ], + reveal, + ); + + webContents.emit("did-finish-load"); + + expect(reveal).toHaveBeenCalledTimes(1); + }); + + it("only reveals once when multiple triggers fire", () => { + const window = new EventEmitter(); + const webContents = new EventEmitter(); + const reveal = vi.fn(); + + bindFirstRevealTrigger( + [ + (fire) => window.once("ready-to-show", fire), + (fire) => webContents.once("did-finish-load", fire), + ], + reveal, + ); + + webContents.emit("did-finish-load"); + window.emit("ready-to-show"); + + expect(reveal).toHaveBeenCalledTimes(1); + }); + + it("subscribers using `once` ignore re-emitted events after reveal", () => { + const window = new EventEmitter(); + const reveal = vi.fn(); + + bindFirstRevealTrigger([(fire) => window.once("ready-to-show", fire)], reveal); + + window.emit("ready-to-show"); + window.emit("ready-to-show"); + + expect(reveal).toHaveBeenCalledTimes(1); + }); +}); diff --git a/apps/desktop/src/windowReveal.ts b/apps/desktop/src/windowReveal.ts new file mode 100644 index 0000000000..8faf65aeb1 --- /dev/null +++ b/apps/desktop/src/windowReveal.ts @@ -0,0 +1,28 @@ +export type RevealSubscription = (listener: () => void) => void; + +/** + * Wire a reveal callback to fire exactly once, on whichever of the provided + * event subscribers fires first. Each subscriber is responsible for binding + * its own event source. + * + * Used by the desktop main window's first-paint reveal logic. The standard + * Electron pattern is to wait for `ready-to-show` before calling `show()`, + * but on Linux/Wayland with `show: false`, `ready-to-show` only fires after + * `show()` is called, deadlocking that pattern. Subscribing to both + * `ready-to-show` and `did-finish-load` (or any other "renderer is alive" + * signal) lets the window surface reliably across platforms. + */ +export function bindFirstRevealTrigger( + subscribers: readonly RevealSubscription[], + reveal: () => void, +): void { + let revealed = false; + const fire = () => { + if (revealed) return; + revealed = true; + reveal(); + }; + for (const subscribe of subscribers) { + subscribe(fire); + } +} diff --git a/apps/server/src/provider/Layers/OpenCodeProvider.test.ts b/apps/server/src/provider/Layers/OpenCodeProvider.test.ts index ffce708434..4a43c37b68 100644 --- a/apps/server/src/provider/Layers/OpenCodeProvider.test.ts +++ b/apps/server/src/provider/Layers/OpenCodeProvider.test.ts @@ -16,9 +16,12 @@ import { import { OpenCodeProviderLive } from "./OpenCodeProvider.ts"; import type { OpenCodeInventory } from "../opencodeRuntime.ts"; +const DEFAULT_VERSION_STDOUT = "opencode 1.14.19\n"; + const runtimeMock = { state: { runVersionError: null as Error | null, + versionStdout: DEFAULT_VERSION_STDOUT, inventoryError: null as Error | null, inventory: { providerList: { connected: [] as string[], all: [] as unknown[], default: {} }, @@ -27,6 +30,7 @@ const runtimeMock = { }, reset() { this.state.runVersionError = null; + this.state.versionStdout = DEFAULT_VERSION_STDOUT; this.state.inventoryError = null; this.state.inventory = { providerList: { connected: [], all: [] as unknown[], default: {} }, @@ -56,7 +60,7 @@ const OpenCodeRuntimeTestDouble: OpenCodeRuntimeShape = { cause: runtimeMock.state.runVersionError, }), ) - : Effect.succeed({ stdout: "opencode 1.0.0\n", stderr: "", code: 0 }), + : Effect.succeed({ stdout: runtimeMock.state.versionStdout, stderr: "", code: 0 }), createOpenCodeSdkClient: () => ({}) as unknown as ReturnType, loadOpenCodeInventory: () => @@ -108,6 +112,33 @@ it.layer(makeTestLayer())("OpenCodeProviderLive", (it) => { }), ); + it.effect("refuses to probe when opencode is older than the required minimum", () => + Effect.gen(function* () { + runtimeMock.state.versionStdout = "opencode 1.4.7\n"; + const provider = yield* OpenCodeProvider; + const snapshot = yield* provider.refresh; + + assert.equal(snapshot.status, "error"); + assert.equal(snapshot.installed, true); + assert.equal(snapshot.version, "1.4.7"); + assert.ok(snapshot.message?.includes("1.14.19")); + assert.ok(snapshot.message?.toLowerCase().includes("upgrade")); + }), + ); + + it.effect("refuses to probe when opencode --version output is unparseable", () => + Effect.gen(function* () { + runtimeMock.state.versionStdout = "garbled binary output\n"; + const provider = yield* OpenCodeProvider; + const snapshot = yield* provider.refresh; + + assert.equal(snapshot.status, "error"); + assert.equal(snapshot.installed, true); + assert.equal(snapshot.version, null); + assert.ok(snapshot.message?.includes("1.14.19")); + }), + ); + it.effect("emits OpenCode variant defaults so trait picker can resolve a visible selection", () => Effect.gen(function* () { runtimeMock.state.inventory = { diff --git a/apps/server/src/provider/Layers/OpenCodeProvider.ts b/apps/server/src/provider/Layers/OpenCodeProvider.ts index d43372ec5c..586bc3d6f4 100644 --- a/apps/server/src/provider/Layers/OpenCodeProvider.ts +++ b/apps/server/src/provider/Layers/OpenCodeProvider.ts @@ -15,6 +15,7 @@ import { parseGenericCliVersion, providerModelsFromSettings, } from "../providerSnapshot.ts"; +import { compareCliVersions } from "../cliVersion.ts"; import { OpenCodeProvider } from "../Services/OpenCodeProvider.ts"; import { OpenCodeRuntime, @@ -24,6 +25,7 @@ import { import type { Agent, ProviderListResponse } from "@opencode-ai/sdk/v2"; const PROVIDER = "opencode" as const; +const MINIMUM_OPENCODE_VERSION = "1.14.19"; class OpenCodeProbeError extends Data.TaggedError("OpenCodeProbeError")<{ readonly cause: unknown; @@ -354,6 +356,35 @@ export const OpenCodeProviderLive = Layer.effect( return fallback(Cause.squash(versionExit.cause)); } version = parseGenericCliVersion(versionExit.value.stdout) ?? null; + + if (!version) { + return fallback( + new Error( + `Unable to determine OpenCode version from \`opencode --version\` output. T3 Code requires OpenCode v${MINIMUM_OPENCODE_VERSION} or newer.`, + ), + null, + ); + } + if (compareCliVersions(version, MINIMUM_OPENCODE_VERSION) < 0) { + return buildServerProvider({ + provider: PROVIDER, + enabled: input.settings.enabled, + checkedAt, + models: providerModelsFromSettings( + [], + PROVIDER, + customModels, + DEFAULT_OPENCODE_MODEL_CAPABILITIES, + ), + probe: { + installed: true, + version, + status: "error", + auth: { status: "unknown" }, + message: `OpenCode v${version} is too old. Upgrade to v${MINIMUM_OPENCODE_VERSION} or newer.`, + }, + }); + } } const inventoryExit = yield* Effect.exit( From 3a1daa87ac103da0c176426e82eb576d87046bdf Mon Sep 17 00:00:00 2001 From: Noxire <59626436+noxire-dev@users.noreply.github.com> Date: Tue, 21 Apr 2026 18:32:08 +0300 Subject: [PATCH 14/82] Add close buttons to toasts (#2023) Co-authored-by: Julius Marminge --- .../BranchToolbarBranchSelector.tsx | 26 +- apps/web/src/components/ChatMarkdown.tsx | 38 +- apps/web/src/components/ChatView.tsx | 54 ++- apps/web/src/components/CommandPalette.tsx | 62 ++- .../components/GitActionsControl.browser.tsx | 1 + apps/web/src/components/GitActionsControl.tsx | 88 ++-- apps/web/src/components/PlanSidebar.tsx | 14 +- apps/web/src/components/Sidebar.tsx | 281 ++++++----- .../components/WebSocketConnectionSurface.tsx | 87 ++-- .../src/components/chat/ProposedPlanCard.tsx | 38 +- .../settings/ConnectionsSettings.tsx | 110 +++-- .../components/settings/SettingsPanels.tsx | 90 ++-- .../components/sidebar/SidebarUpdatePill.tsx | 50 +- .../web/src/components/ui/toast.logic.test.ts | 56 +++ apps/web/src/components/ui/toast.logic.ts | 62 ++- apps/web/src/components/ui/toast.tsx | 453 +++++++++++++----- apps/web/src/components/ui/toastHelpers.ts | 58 +++ apps/web/src/hooks/useThreadActions.ts | 14 +- apps/web/src/routes/__root.tsx | 68 +-- 19 files changed, 1099 insertions(+), 551 deletions(-) create mode 100644 apps/web/src/components/ui/toastHelpers.ts diff --git a/apps/web/src/components/BranchToolbarBranchSelector.tsx b/apps/web/src/components/BranchToolbarBranchSelector.tsx index 996fca4b39..828e6e122b 100644 --- a/apps/web/src/components/BranchToolbarBranchSelector.tsx +++ b/apps/web/src/components/BranchToolbarBranchSelector.tsx @@ -42,7 +42,7 @@ import { ComboboxStatus, ComboboxTrigger, } from "./ui/combobox"; -import { toastManager } from "./ui/toast"; +import { stackedThreadToast, toastManager } from "./ui/toast"; interface BranchToolbarBranchSelectorProps { environmentId: EnvironmentId; @@ -351,11 +351,13 @@ export function BranchToolbarBranchSelector({ setThreadBranch(nextBranchName, selectionTarget.nextWorktreePath); } catch (error) { setOptimisticBranch(previousBranch); - toastManager.add({ - type: "error", - title: "Failed to checkout branch.", - description: toBranchActionErrorMessage(error), - }); + toastManager.add( + stackedThreadToast({ + type: "error", + title: "Failed to checkout branch.", + description: toBranchActionErrorMessage(error), + }), + ); } }); }; @@ -381,11 +383,13 @@ export function BranchToolbarBranchSelector({ setThreadBranch(createBranchResult.branch, activeWorktreePath); } catch (error) { setOptimisticBranch(previousBranch); - toastManager.add({ - type: "error", - title: "Failed to create and checkout branch.", - description: toBranchActionErrorMessage(error), - }); + toastManager.add( + stackedThreadToast({ + type: "error", + title: "Failed to create and checkout branch.", + description: toBranchActionErrorMessage(error), + }), + ); } }); }; diff --git a/apps/web/src/components/ChatMarkdown.tsx b/apps/web/src/components/ChatMarkdown.tsx index ba1c944cc8..4b53f8534f 100644 --- a/apps/web/src/components/ChatMarkdown.tsx +++ b/apps/web/src/components/ChatMarkdown.tsx @@ -20,7 +20,7 @@ import { defaultUrlTransform } from "react-markdown"; import remarkGfm from "remark-gfm"; import { VscodeEntryIcon } from "./chat/VscodeEntryIcon"; import { Tooltip, TooltipPopup, TooltipTrigger } from "./ui/tooltip"; -import { toastManager } from "./ui/toast"; +import { stackedThreadToast, toastManager } from "./ui/toast"; import { openInPreferredEditor } from "../editorPreferences"; import { resolveDiffThemeName, type DiffThemeName } from "../lib/diffRendering"; import { fnv1a32 } from "../lib/diffRendering"; @@ -351,21 +351,25 @@ const MarkdownFileLink = memo(function MarkdownFileLink({ } void openInPreferredEditor(api, targetPath).catch((error) => { - toastManager.add({ - type: "error", - title: "Unable to open file", - description: error instanceof Error ? error.message : "An error occurred.", - }); + toastManager.add( + stackedThreadToast({ + type: "error", + title: "Unable to open file", + description: error instanceof Error ? error.message : "An error occurred.", + }), + ); }); }, [targetPath]); const handleCopy = useCallback((value: string, title: string) => { if (typeof window === "undefined" || !navigator.clipboard?.writeText) { - toastManager.add({ - type: "error", - title: `Failed to copy ${title.toLowerCase()}`, - description: "Clipboard API unavailable.", - }); + toastManager.add( + stackedThreadToast({ + type: "error", + title: `Failed to copy ${title.toLowerCase()}`, + description: "Clipboard API unavailable.", + }), + ); return; } @@ -378,11 +382,13 @@ const MarkdownFileLink = memo(function MarkdownFileLink({ }); }, (error) => { - toastManager.add({ - type: "error", - title: `Failed to copy ${title.toLowerCase()}`, - description: error instanceof Error ? error.message : "An error occurred.", - }); + toastManager.add( + stackedThreadToast({ + type: "error", + title: `Failed to copy ${title.toLowerCase()}`, + description: error instanceof Error ? error.message : "An error occurred.", + }), + ); }, ); }, []); diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsx index 535c0d9fca..0c76059b6a 100644 --- a/apps/web/src/components/ChatView.tsx +++ b/apps/web/src/components/ChatView.tsx @@ -101,7 +101,7 @@ import PlanSidebar from "./PlanSidebar"; import ThreadTerminalDrawer from "./ThreadTerminalDrawer"; import { ChevronDownIcon } from "lucide-react"; import { cn, randomUUID } from "~/lib/utils"; -import { toastManager } from "./ui/toast"; +import { stackedThreadToast, toastManager } from "./ui/toast"; import { decodeProjectScriptKeybindingRule } from "~/lib/projectScriptKeybindings"; import { type NewProjectScriptInput } from "./ProjectScriptsControl"; import { @@ -1855,11 +1855,13 @@ export default function ChatView(props: ChatViewProps) { title: `Deleted action "${deletedName ?? "Unknown"}"`, }); } catch (error) { - toastManager.add({ - type: "error", - title: "Could not delete action", - description: error instanceof Error ? error.message : "An unexpected error occurred.", - }); + toastManager.add( + stackedThreadToast({ + type: "error", + title: "Could not delete action", + description: error instanceof Error ? error.message : "An unexpected error occurred.", + }), + ); } }, [activeProject, persistProjectScripts], @@ -2426,11 +2428,13 @@ export default function ChatView(props: ChatViewProps) { expiredTerminalContextCount, "empty", ); - toastManager.add({ - type: "warning", - title: toastCopy.title, - description: toastCopy.description, - }); + toastManager.add( + stackedThreadToast({ + type: "warning", + title: toastCopy.title, + description: toastCopy.description, + }), + ); } return; } @@ -2512,11 +2516,13 @@ export default function ChatView(props: ChatViewProps) { expiredTerminalContextCount, "omitted", ); - toastManager.add({ - type: "warning", - title: toastCopy.title, - description: toastCopy.description, - }); + toastManager.add( + stackedThreadToast({ + type: "warning", + title: toastCopy.title, + description: toastCopy.description, + }), + ); } promptRef.current = ""; clearComposerDraftContent(composerDraftTarget); @@ -3082,12 +3088,16 @@ export default function ChatView(props: ChatViewProps) { threadId: nextThreadId, }) .catch(() => undefined); - toastManager.add({ - type: "error", - title: "Could not start implementation thread", - description: - err instanceof Error ? err.message : "An error occurred while creating the new thread.", - }); + toastManager.add( + stackedThreadToast({ + type: "error", + title: "Could not start implementation thread", + description: + err instanceof Error + ? err.message + : "An error occurred while creating the new thread.", + }), + ); }) .then(finish, finish); }, [ diff --git a/apps/web/src/components/CommandPalette.tsx b/apps/web/src/components/CommandPalette.tsx index 929a9f87e9..2b587afc51 100644 --- a/apps/web/src/components/CommandPalette.tsx +++ b/apps/web/src/components/CommandPalette.tsx @@ -102,7 +102,7 @@ import { } from "./ui/command"; import { Button } from "./ui/button"; import { Kbd, KbdGroup } from "./ui/kbd"; -import { toastManager } from "./ui/toast"; +import { stackedThreadToast, toastManager } from "./ui/toast"; import { ComposerHandleContext, useComposerHandleContext } from "../composerHandleContext"; import type { ChatComposerHandle } from "./chat/ChatComposer"; @@ -605,11 +605,13 @@ function OpenCommandPaletteDialog() { const environmentId = defaultAddProjectEnvironmentId; if (!environmentId) { - toastManager.add({ - type: "error", - title: "Unable to browse projects", - description: "No environment is available.", - }); + toastManager.add( + stackedThreadToast({ + type: "error", + title: "Unable to browse projects", + description: "No environment is available.", + }), + ); return; } @@ -724,20 +726,24 @@ function OpenCommandPaletteDialog() { if (!api) return; if (isUnsupportedWindowsProjectPath(rawCwd.trim(), browseEnvironmentPlatform)) { - toastManager.add({ - type: "error", - title: "Failed to add project", - description: "Windows-style paths are only supported on Windows.", - }); + toastManager.add( + stackedThreadToast({ + type: "error", + title: "Failed to add project", + description: "Windows-style paths are only supported on Windows.", + }), + ); return; } if (isExplicitRelativeProjectPath(rawCwd.trim()) && !currentProjectCwdForBrowse) { - toastManager.add({ - type: "error", - title: "Failed to add project", - description: "Relative paths require an active project.", - }); + toastManager.add( + stackedThreadToast({ + type: "error", + title: "Failed to add project", + description: "Relative paths require an active project.", + }), + ); return; } @@ -790,11 +796,13 @@ function OpenCommandPaletteDialog() { }).catch(() => undefined); setOpen(false); } catch (error) { - toastManager.add({ - type: "error", - title: "Failed to add project", - description: error instanceof Error ? error.message : "An error occurred.", - }); + toastManager.add( + stackedThreadToast({ + type: "error", + title: "Failed to add project", + description: error instanceof Error ? error.message : "An error occurred.", + }), + ); } }, [ @@ -934,11 +942,13 @@ function OpenCommandPaletteDialog() { } void item.run().catch((error: unknown) => { - toastManager.add({ - type: "error", - title: "Unable to run command", - description: error instanceof Error ? error.message : "An unexpected error occurred.", - }); + toastManager.add( + stackedThreadToast({ + type: "error", + title: "Unable to run command", + description: error instanceof Error ? error.message : "An unexpected error occurred.", + }), + ); }); } diff --git a/apps/web/src/components/GitActionsControl.browser.tsx b/apps/web/src/components/GitActionsControl.browser.tsx index 651b383fa0..beeb136a9c 100644 --- a/apps/web/src/components/GitActionsControl.browser.tsx +++ b/apps/web/src/components/GitActionsControl.browser.tsx @@ -90,6 +90,7 @@ vi.mock("~/components/ui/toast", () => ({ promise: toastPromiseSpy, update: toastUpdateSpy, }, + stackedThreadToast: vi.fn((options: unknown) => options), })); vi.mock("~/editorPreferences", () => ({ diff --git a/apps/web/src/components/GitActionsControl.tsx b/apps/web/src/components/GitActionsControl.tsx index 6d2312e4aa..3f39b129ac 100644 --- a/apps/web/src/components/GitActionsControl.tsx +++ b/apps/web/src/components/GitActionsControl.tsx @@ -38,7 +38,7 @@ import { Menu, MenuItem, MenuPopup, MenuTrigger } from "~/components/ui/menu"; import { Popover, PopoverPopup, PopoverTrigger } from "~/components/ui/popover"; import { ScrollArea } from "~/components/ui/scroll-area"; import { Textarea } from "~/components/ui/textarea"; -import { toastManager, type ThreadToastData } from "~/components/ui/toast"; +import { stackedThreadToast, toastManager, type ThreadToastData } from "~/components/ui/toast"; import { openInPreferredEditor } from "~/editorPreferences"; import { gitInitMutationOptions, @@ -474,12 +474,14 @@ export default function GitActionsControl({ return; } void api.shell.openExternal(prUrl).catch((err: unknown) => { - toastManager.add({ - type: "error", - title: "Unable to open PR link", - description: err instanceof Error ? err.message : "An error occurred.", - data: threadToastData, - }); + toastManager.add( + stackedThreadToast({ + type: "error", + title: "Unable to open PR link", + description: err instanceof Error ? err.message : "An error occurred.", + ...(threadToastData !== undefined ? { data: threadToastData } : {}), + }), + ); }); }, [gitStatusForActions, threadToastData]); @@ -670,33 +672,44 @@ export default function GitActionsControl({ }; } - const successToastBase = { - type: "success", - title: result.toast.title, - description: result.toast.description, - timeout: 0, - data: { - ...scopedToastData, - dismissAfterVisibleMs: 10_000, - }, - } as const; + const successToastData = { + ...scopedToastData, + dismissAfterVisibleMs: 10_000, + }; if (toastActionProps) { - toastManager.update(resolvedProgressToastId, { - ...successToastBase, - actionProps: toastActionProps, - }); + toastManager.update( + resolvedProgressToastId, + stackedThreadToast({ + type: "success", + title: result.toast.title, + description: result.toast.description, + timeout: 0, + actionProps: toastActionProps, + actionVariant: "outline", + data: successToastData, + }), + ); } else { - toastManager.update(resolvedProgressToastId, successToastBase); + toastManager.update(resolvedProgressToastId, { + type: "success", + title: result.toast.title, + description: result.toast.description, + timeout: 0, + data: successToastData, + }); } } catch (err) { activeGitActionProgressRef.current = null; - toastManager.update(resolvedProgressToastId, { - type: "error", - title: "Action failed", - description: err instanceof Error ? err.message : "An error occurred.", - data: scopedToastData, - }); + toastManager.update( + resolvedProgressToastId, + stackedThreadToast({ + type: "error", + title: "Action failed", + description: err instanceof Error ? err.message : "An error occurred.", + ...(scopedToastData !== undefined ? { data: scopedToastData } : {}), + }), + ); } }, ); @@ -753,7 +766,10 @@ export default function GitActionsControl({ } if (quickAction.kind === "run_pull") { const promise = pullMutation.mutateAsync(); - toastManager.promise(promise, { + void toastManager.promise< + Awaited>, + ThreadToastData + >(promise, { loading: { title: "Pulling...", data: threadToastData }, success: (result) => ({ title: result.status === "pulled" ? "Pulled" : "Already up to date", @@ -832,12 +848,14 @@ export default function GitActionsControl({ } const target = resolvePathLinkTarget(filePath, gitCwd); void openInPreferredEditor(api, target).catch((error) => { - toastManager.add({ - type: "error", - title: "Unable to open file", - description: error instanceof Error ? error.message : "An error occurred.", - data: threadToastData, - }); + toastManager.add( + stackedThreadToast({ + type: "error", + title: "Unable to open file", + description: error instanceof Error ? error.message : "An error occurred.", + ...(threadToastData !== undefined ? { data: threadToastData } : {}), + }), + ); }); }, [gitCwd, threadToastData], diff --git a/apps/web/src/components/PlanSidebar.tsx b/apps/web/src/components/PlanSidebar.tsx index 00b9da2b0c..afd4bb2e0b 100644 --- a/apps/web/src/components/PlanSidebar.tsx +++ b/apps/web/src/components/PlanSidebar.tsx @@ -26,7 +26,7 @@ import { } from "../proposedPlan"; import { Menu, MenuItem, MenuPopup, MenuTrigger } from "./ui/menu"; import { readEnvironmentApi } from "~/environmentApi"; -import { toastManager } from "./ui/toast"; +import { stackedThreadToast, toastManager } from "./ui/toast"; import { useCopyToClipboard } from "~/hooks/useCopyToClipboard"; function stepStatusIcon(status: string): React.ReactNode { @@ -112,11 +112,13 @@ const PlanSidebar = memo(function PlanSidebar({ }); }) .catch((error) => { - toastManager.add({ - type: "error", - title: "Could not save plan", - description: error instanceof Error ? error.message : "An error occurred.", - }); + toastManager.add( + stackedThreadToast({ + type: "error", + title: "Could not save plan", + description: error instanceof Error ? error.message : "An error occurred.", + }), + ); }) .then( () => setIsSavingToWorkspace(false), diff --git a/apps/web/src/components/Sidebar.tsx b/apps/web/src/components/Sidebar.tsx index d25f930c0d..5d778eec36 100644 --- a/apps/web/src/components/Sidebar.tsx +++ b/apps/web/src/components/Sidebar.tsx @@ -94,7 +94,7 @@ import { resolveThreadRouteRef, resolveThreadRouteTarget, } from "../threadRoutes"; -import { toastManager } from "./ui/toast"; +import { stackedThreadToast, toastManager } from "./ui/toast"; import { formatRelativeTimeLabel } from "../timestampFormat"; import { SettingsSidebarNav } from "./settings/SettingsSidebarNav"; import { Kbd } from "./ui/kbd"; @@ -950,11 +950,13 @@ const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjec }); }, onError: (error) => { - toastManager.add({ - type: "error", - title: "Failed to copy thread ID", - description: error instanceof Error ? error.message : "An error occurred.", - }); + toastManager.add( + stackedThreadToast({ + type: "error", + title: "Failed to copy thread ID", + description: error instanceof Error ? error.message : "An error occurred.", + }), + ); }, }); const { copyToClipboard: copyPathToClipboard } = useCopyToClipboard<{ @@ -968,11 +970,13 @@ const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjec }); }, onError: (error) => { - toastManager.add({ - type: "error", - title: "Failed to copy path", - description: error instanceof Error ? error.message : "An error occurred.", - }); + toastManager.add( + stackedThreadToast({ + type: "error", + title: "Failed to copy path", + description: error instanceof Error ? error.message : "An error occurred.", + }), + ); }, }); const openPrLink = useCallback((event: React.MouseEvent, prUrl: string) => { @@ -989,11 +993,13 @@ const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjec } void api.shell.openExternal(prUrl).catch((error) => { - toastManager.add({ - type: "error", - title: "Unable to open PR link", - description: error instanceof Error ? error.message : "An error occurred.", - }); + toastManager.add( + stackedThreadToast({ + type: "error", + title: "Unable to open PR link", + description: error instanceof Error ? error.message : "An error occurred.", + }), + ); }); }, []); const sidebarThreads = useStore( @@ -1299,72 +1305,73 @@ const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjec const memberProjectRef = scopeProjectRef(member.environmentId, member.id); const memberThreadCount = memberThreadCountByPhysicalKey.get(member.physicalProjectKey) ?? 0; if (memberThreadCount > 0) { - const warningToastId = toastManager.add({ - type: "warning", - title: "Project is not empty", - description: "Delete all threads in this project before removing it.", - data: { - actionLayout: "stacked-end", + const warningToastId = toastManager.add( + stackedThreadToast({ + type: "warning", + title: "Project is not empty", + description: "Delete all threads in this project before removing it.", actionVariant: "destructive", - }, - actionProps: { - children: "Delete anyway", - onClick: () => { - void (async () => { - toastManager.close(warningToastId); - await new Promise((resolve) => { - window.setTimeout(resolve, 180); - }); + actionProps: { + children: "Delete anyway", + onClick: () => { + void (async () => { + toastManager.close(warningToastId); + await new Promise((resolve) => { + window.setTimeout(resolve, 180); + }); - const latestProjectThreads = selectSidebarThreadsForProjectRefs( - useStore.getState(), - [memberProjectRef], - ); - const confirmed = await api.dialogs.confirm( - latestProjectThreads.length > 0 - ? [ - `Remove project "${member.name}" and delete its ${latestProjectThreads.length} thread${ - latestProjectThreads.length === 1 ? "" : "s" - }?`, - `Path: ${member.cwd}`, - ...(member.environmentLabel - ? [`Environment: ${member.environmentLabel}`] - : []), - "This permanently clears conversation history for those threads.", - "This removes only this project entry.", - "This action cannot be undone.", - ].join("\n") - : [ - `Remove project "${member.name}"?`, - `Path: ${member.cwd}`, - ...(member.environmentLabel - ? [`Environment: ${member.environmentLabel}`] - : []), - "This removes only this project entry.", - ].join("\n"), - ); - if (!confirmed) { - return; - } + const latestProjectThreads = selectSidebarThreadsForProjectRefs( + useStore.getState(), + [memberProjectRef], + ); + const confirmed = await api.dialogs.confirm( + latestProjectThreads.length > 0 + ? [ + `Remove project "${member.name}" and delete its ${latestProjectThreads.length} thread${ + latestProjectThreads.length === 1 ? "" : "s" + }?`, + `Path: ${member.cwd}`, + ...(member.environmentLabel + ? [`Environment: ${member.environmentLabel}`] + : []), + "This permanently clears conversation history for those threads.", + "This removes only this project entry.", + "This action cannot be undone.", + ].join("\n") + : [ + `Remove project "${member.name}"?`, + `Path: ${member.cwd}`, + ...(member.environmentLabel + ? [`Environment: ${member.environmentLabel}`] + : []), + "This removes only this project entry.", + ].join("\n"), + ); + if (!confirmed) { + return; + } - await removeProject(member, { force: true }); - })().catch((error) => { - const message = - error instanceof Error ? error.message : "Unknown error removing project."; - console.error("Failed to remove project", { - projectId: member.id, - environmentId: member.environmentId, - error, + await removeProject(member, { force: true }); + })().catch((error) => { + const message = + error instanceof Error ? error.message : "Unknown error removing project."; + console.error("Failed to remove project", { + projectId: member.id, + environmentId: member.environmentId, + error, + }); + toastManager.add( + stackedThreadToast({ + type: "error", + title: `Failed to remove "${member.name}"`, + description: message, + }), + ); }); - toastManager.add({ - type: "error", - title: `Failed to remove "${member.name}"`, - description: message, - }); - }); + }, }, - }, - }); + }), + ); return; } @@ -1388,11 +1395,13 @@ const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjec environmentId: member.environmentId, error, }); - toastManager.add({ - type: "error", - title: `Failed to remove "${member.name}"`, - description: message, - }); + toastManager.add( + stackedThreadToast({ + type: "error", + title: `Failed to remove "${member.name}"`, + description: message, + }), + ); } }, [memberThreadCountByPhysicalKey, removeProject], @@ -1705,11 +1714,13 @@ const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjec try { await archiveThread(threadRef); } catch (error) { - toastManager.add({ - type: "error", - title: "Failed to archive thread", - description: error instanceof Error ? error.message : "An error occurred.", - }); + toastManager.add( + stackedThreadToast({ + type: "error", + title: "Failed to archive thread", + description: error instanceof Error ? error.message : "An error occurred.", + }), + ); } }, [archiveThread], @@ -1757,11 +1768,13 @@ const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjec title: trimmed, }); } catch (error) { - toastManager.add({ - type: "error", - title: "Failed to rename thread", - description: error instanceof Error ? error.message : "An error occurred.", - }); + toastManager.add( + stackedThreadToast({ + type: "error", + title: "Failed to rename thread", + description: error instanceof Error ? error.message : "An error occurred.", + }), + ); } finishRename(); }, @@ -1794,11 +1807,13 @@ const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjec const api = readEnvironmentApi(projectRenameTarget.environmentId); if (!api) { - toastManager.add({ - type: "error", - title: "Failed to rename project", - description: "Project API unavailable.", - }); + toastManager.add( + stackedThreadToast({ + type: "error", + title: "Failed to rename project", + description: "Project API unavailable.", + }), + ); return; } @@ -1811,11 +1826,13 @@ const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjec }); closeProjectRenameDialog(); } catch (error) { - toastManager.add({ - type: "error", - title: "Failed to rename project", - description: error instanceof Error ? error.message : "An error occurred.", - }); + toastManager.add( + stackedThreadToast({ + type: "error", + title: "Failed to rename project", + description: error instanceof Error ? error.message : "An error occurred.", + }), + ); } }, [closeProjectRenameDialog, projectRenameTarget, projectRenameTitle]); @@ -1885,11 +1902,13 @@ const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjec } if (clicked === "copy-path") { if (!threadWorkspacePath) { - toastManager.add({ - type: "error", - title: "Path unavailable", - description: "This thread does not have a workspace path to copy.", - }); + toastManager.add( + stackedThreadToast({ + type: "error", + title: "Path unavailable", + description: "This thread does not have a workspace path to copy.", + }), + ); return; } copyPathToClipboard(threadWorkspacePath, { path: threadWorkspacePath }); @@ -3220,18 +3239,22 @@ export default function Sidebar() { if (!shouldToastDesktopUpdateActionResult(result)) return; const actionError = getDesktopUpdateActionError(result); if (!actionError) return; - toastManager.add({ - type: "error", - title: "Could not download update", - description: actionError, - }); + toastManager.add( + stackedThreadToast({ + type: "error", + title: "Could not download update", + description: actionError, + }), + ); }) .catch((error) => { - toastManager.add({ - type: "error", - title: "Could not start update download", - description: error instanceof Error ? error.message : "An unexpected error occurred.", - }); + toastManager.add( + stackedThreadToast({ + type: "error", + title: "Could not start update download", + description: error instanceof Error ? error.message : "An unexpected error occurred.", + }), + ); }); return; } @@ -3247,18 +3270,22 @@ export default function Sidebar() { if (!shouldToastDesktopUpdateActionResult(result)) return; const actionError = getDesktopUpdateActionError(result); if (!actionError) return; - toastManager.add({ - type: "error", - title: "Could not install update", - description: actionError, - }); + toastManager.add( + stackedThreadToast({ + type: "error", + title: "Could not install update", + description: actionError, + }), + ); }) .catch((error) => { - toastManager.add({ - type: "error", - title: "Could not install update", - description: error instanceof Error ? error.message : "An unexpected error occurred.", - }); + toastManager.add( + stackedThreadToast({ + type: "error", + title: "Could not install update", + description: error instanceof Error ? error.message : "An unexpected error occurred.", + }), + ); }); } }, [desktopUpdateButtonAction, desktopUpdateButtonDisabled, desktopUpdateState]); diff --git a/apps/web/src/components/WebSocketConnectionSurface.tsx b/apps/web/src/components/WebSocketConnectionSurface.tsx index 7b350e9849..e0bb560980 100644 --- a/apps/web/src/components/WebSocketConnectionSurface.tsx +++ b/apps/web/src/components/WebSocketConnectionSurface.tsx @@ -10,7 +10,7 @@ import { useWsConnectionStatus, WS_RECONNECT_MAX_ATTEMPTS, } from "../rpc/wsConnectionState"; -import { toastManager } from "./ui/toast"; +import { stackedThreadToast, toastManager } from "./ui/toast"; import { getPrimaryEnvironmentConnection } from "../environments/runtime"; const FORCED_WS_RECONNECT_DEBOUNCE_MS = 5_000; @@ -75,13 +75,34 @@ function describeRecoveredToast( return "Connection restored."; } -function describeSlowRpcAckToast(requests: ReadonlyArray): ReactNode { +function describeSlowRpcAckToast(requests: ReadonlyArray): string { const count = requests.length; const thresholdSeconds = Math.round((requests[0]?.thresholdMs ?? 0) / 1000); return `${count} request${count === 1 ? "" : "s"} waiting longer than ${thresholdSeconds}s.`; } +function SlowRpcAckRequestDetails({ requests }: { requests: ReadonlyArray }) { + return ( +
    + {requests.map((req) => ( +
  • +
    {req.tag}
    +
    + {req.requestId} +
    +
    + Started {formatConnectionMoment(req.startedAt) ?? req.startedAt} +
    +
  • + ))} +
+ ); +} + export function shouldAutoReconnect( status: WsConnectionStatus, trigger: WsAutoReconnectTrigger, @@ -138,15 +159,18 @@ export function WebSocketConnectionCoordinator() { console.warn("Automatic WebSocket reconnect failed", { error }); return; } - toastManager.add({ - type: "error", - title: "Reconnect failed", - description: error instanceof Error ? error.message : "Unable to restart the WebSocket.", - data: { - dismissAfterVisibleMs: 8_000, - hideCopyButton: true, - }, - }); + toastManager.add( + stackedThreadToast({ + type: "error", + title: "Reconnect failed", + description: + error instanceof Error ? error.message : "Unable to restart the WebSocket.", + data: { + dismissAfterVisibleMs: 8_000, + hideCopyButton: true, + }, + }), + ); }); }); const syncBrowserOnlineStatus = useEffectEvent(() => { @@ -253,45 +277,45 @@ export function WebSocketConnectionCoordinator() { if (shouldShowReconnectToast || shouldShowOfflineToast || shouldShowExhaustedToast) { const toastPayload = shouldShowOfflineToast - ? { - description: describeOfflineToast(), - timeout: 0, - title: "Offline", - type: "warning" as const, + ? stackedThreadToast({ data: { hideCopyButton: true, }, - } + description: describeOfflineToast(), + timeout: 0, + title: "Offline", + type: "warning", + }) : shouldShowExhaustedToast - ? { + ? stackedThreadToast({ actionProps: { children: "Retry", onClick: triggerManualReconnect, }, - description: describeExhaustedToast(), - timeout: 0, - title: "Disconnected from T3 Server", - type: "error" as const, data: { hideCopyButton: true, }, - } - : { + description: describeExhaustedToast(), + timeout: 0, + title: "Disconnected from T3 Server", + type: "error", + }) + : stackedThreadToast({ actionProps: { children: "Retry now", onClick: triggerManualReconnect, }, + data: { + hideCopyButton: true, + }, description: status.nextRetryAt === null ? `Reconnecting... ${formatReconnectAttemptLabel(status)}` : `Reconnecting in ${formatRetryCountdown(status.nextRetryAt, nowMs)}... ${formatReconnectAttemptLabel(status)}`, timeout: 0, title: buildReconnectTitle(status), - type: "loading" as const, - data: { - hideCopyButton: true, - }, - }; + type: "loading", + }); if (toastIdRef.current) { toastManager.update(toastIdRef.current, toastPayload); @@ -369,6 +393,11 @@ export function SlowRpcAckToastCoordinator() { } const nextToast = { + data: { + expandableContent: , + expandableDescriptionTrigger: true, + expandableLabels: { collapse: "Hide requests", expand: "Show requests" }, + }, description: describeSlowRpcAckToast(slowRequests), timeout: 0, title: "Some requests are slow", diff --git a/apps/web/src/components/chat/ProposedPlanCard.tsx b/apps/web/src/components/chat/ProposedPlanCard.tsx index a36cb097cb..e53ee93b91 100644 --- a/apps/web/src/components/chat/ProposedPlanCard.tsx +++ b/apps/web/src/components/chat/ProposedPlanCard.tsx @@ -24,7 +24,7 @@ import { DialogPopup, DialogTitle, } from "../ui/dialog"; -import { toastManager } from "../ui/toast"; +import { stackedThreadToast, toastManager } from "../ui/toast"; import { readEnvironmentApi } from "~/environmentApi"; import { useCopyToClipboard } from "~/hooks/useCopyToClipboard"; @@ -45,11 +45,13 @@ export const ProposedPlanCard = memo(function ProposedPlanCard({ const [isSavingToWorkspace, setIsSavingToWorkspace] = useState(false); const { copyToClipboard, isCopied } = useCopyToClipboard({ onError: (error) => { - toastManager.add({ - type: "error", - title: "Could not copy plan", - description: error instanceof Error ? error.message : "An error occurred while copying.", - }); + toastManager.add( + stackedThreadToast({ + type: "error", + title: "Could not copy plan", + description: error instanceof Error ? error.message : "An error occurred while copying.", + }), + ); }, }); const savePathInputId = useId(); @@ -73,11 +75,13 @@ export const ProposedPlanCard = memo(function ProposedPlanCard({ const openSaveDialog = () => { if (!workspaceRoot) { - toastManager.add({ - type: "error", - title: "Workspace path is unavailable", - description: "This thread does not have a workspace path to save into.", - }); + toastManager.add( + stackedThreadToast({ + type: "error", + title: "Workspace path is unavailable", + description: "This thread does not have a workspace path to save into.", + }), + ); return; } setSavePath((existing) => (existing.length > 0 ? existing : downloadFilename)); @@ -114,11 +118,13 @@ export const ProposedPlanCard = memo(function ProposedPlanCard({ }); }) .catch((error) => { - toastManager.add({ - type: "error", - title: "Could not save plan", - description: error instanceof Error ? error.message : "An error occurred while saving.", - }); + toastManager.add( + stackedThreadToast({ + type: "error", + title: "Could not save plan", + description: error instanceof Error ? error.message : "An error occurred while saving.", + }), + ); }) .then( () => { diff --git a/apps/web/src/components/settings/ConnectionsSettings.tsx b/apps/web/src/components/settings/ConnectionsSettings.tsx index ab31fe7e17..880c4376e2 100644 --- a/apps/web/src/components/settings/ConnectionsSettings.tsx +++ b/apps/web/src/components/settings/ConnectionsSettings.tsx @@ -41,7 +41,7 @@ import { Popover, PopoverPopup, PopoverTrigger } from "../ui/popover"; import { QRCodeSvg } from "../ui/qr-code"; import { Spinner } from "../ui/spinner"; import { Switch } from "../ui/switch"; -import { toastManager } from "../ui/toast"; +import { stackedThreadToast, toastManager } from "../ui/toast"; import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip"; import { Button } from "../ui/button"; import { Textarea } from "../ui/textarea"; @@ -302,11 +302,13 @@ const PairingLinkListRow = memo(function PairingLinkListRow({ }, onError: (error) => { setIsRevealDialogOpen(true); - toastManager.add({ - type: "error", - title: canCopyToClipboard ? "Could not copy pairing URL" : "Clipboard copy unavailable", - description: canCopyToClipboard ? error.message : "Showing the full value instead.", - }); + toastManager.add( + stackedThreadToast({ + type: "error", + title: canCopyToClipboard ? "Could not copy pairing URL" : "Clipboard copy unavailable", + description: canCopyToClipboard ? error.message : "Showing the full value instead.", + }), + ); }, }); @@ -535,11 +537,13 @@ const AuthorizedClientsHeaderAction = memo(function AuthorizedClientsHeaderActio setDialogOpen(false); } catch (error) { const message = error instanceof Error ? error.message : "Failed to create pairing URL."; - toastManager.add({ - type: "error", - title: "Could not create pairing URL", - description: message, - }); + toastManager.add( + stackedThreadToast({ + type: "error", + title: "Could not create pairing URL", + description: message, + }), + ); } finally { setIsCreatingPairingLink(false); } @@ -828,11 +832,13 @@ export function ConnectionsSettings() { error instanceof Error ? error.message : "Failed to update network exposure."; setPendingDesktopServerExposureMode(null); setDesktopServerExposureError(message); - toastManager.add({ - type: "error", - title: "Could not update network access", - description: message, - }); + toastManager.add( + stackedThreadToast({ + type: "error", + title: "Could not update network access", + description: message, + }), + ); setIsUpdatingDesktopServerExposure(false); } }, @@ -853,11 +859,13 @@ export function ConnectionsSettings() { } catch (error) { const message = error instanceof Error ? error.message : "Failed to revoke pairing link."; setDesktopAccessManagementError(message); - toastManager.add({ - type: "error", - title: "Could not revoke pairing link", - description: message, - }); + toastManager.add( + stackedThreadToast({ + type: "error", + title: "Could not revoke pairing link", + description: message, + }), + ); } finally { setRevokingDesktopPairingLinkId(null); } @@ -872,11 +880,13 @@ export function ConnectionsSettings() { } catch (error) { const message = error instanceof Error ? error.message : "Failed to revoke client access."; setDesktopAccessManagementError(message); - toastManager.add({ - type: "error", - title: "Could not revoke client access", - description: message, - }); + toastManager.add( + stackedThreadToast({ + type: "error", + title: "Could not revoke client access", + description: message, + }), + ); } finally { setRevokingDesktopClientSessionId(null); } @@ -897,11 +907,13 @@ export function ConnectionsSettings() { } catch (error) { const message = error instanceof Error ? error.message : "Failed to revoke other clients."; setDesktopAccessManagementError(message); - toastManager.add({ - type: "error", - title: "Could not revoke other clients", - description: message, - }); + toastManager.add( + stackedThreadToast({ + type: "error", + title: "Could not revoke other clients", + description: message, + }), + ); } finally { setIsRevokingOtherDesktopClients(false); } @@ -933,11 +945,13 @@ export function ConnectionsSettings() { } catch (error) { const message = error instanceof Error ? error.message : "Failed to add backend."; setSavedBackendError(message); - toastManager.add({ - type: "error", - title: "Could not add backend", - description: message, - }); + toastManager.add( + stackedThreadToast({ + type: "error", + title: "Could not add backend", + description: message, + }), + ); } finally { setIsAddingSavedBackend(false); } @@ -957,11 +971,13 @@ export function ConnectionsSettings() { } catch (error) { const message = error instanceof Error ? error.message : "Failed to reconnect backend."; setSavedBackendError(message); - toastManager.add({ - type: "error", - title: "Could not reconnect backend", - description: message, - }); + toastManager.add( + stackedThreadToast({ + type: "error", + title: "Could not reconnect backend", + description: message, + }), + ); } finally { setReconnectingSavedEnvironmentId(null); } @@ -975,11 +991,13 @@ export function ConnectionsSettings() { } catch (error) { const message = error instanceof Error ? error.message : "Failed to remove backend."; setSavedBackendError(message); - toastManager.add({ - type: "error", - title: "Could not remove backend", - description: message, - }); + toastManager.add( + stackedThreadToast({ + type: "error", + title: "Could not remove backend", + description: message, + }), + ); } finally { setRemovingSavedEnvironmentId(null); } diff --git a/apps/web/src/components/settings/SettingsPanels.tsx b/apps/web/src/components/settings/SettingsPanels.tsx index 230b0a9965..b1e7cf81f6 100644 --- a/apps/web/src/components/settings/SettingsPanels.tsx +++ b/apps/web/src/components/settings/SettingsPanels.tsx @@ -63,7 +63,7 @@ import { Empty, EmptyDescription, EmptyHeader, EmptyMedia, EmptyTitle } from ".. import { Input } from "../ui/input"; import { Select, SelectItem, SelectPopup, SelectTrigger, SelectValue } from "../ui/select"; import { Switch } from "../ui/switch"; -import { toastManager } from "../ui/toast"; +import { stackedThreadToast, toastManager } from "../ui/toast"; import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip"; import { SettingResetButton, @@ -282,11 +282,13 @@ function AboutVersionSection() { setDesktopUpdateStateQueryData(queryClient, state); }) .catch((error: unknown) => { - toastManager.add({ - type: "error", - title: "Could not change update track", - description: error instanceof Error ? error.message : "Update track change failed.", - }); + toastManager.add( + stackedThreadToast({ + type: "error", + title: "Could not change update track", + description: error instanceof Error ? error.message : "Update track change failed.", + }), + ); }) .finally(() => { setIsChangingUpdateChannel(false); @@ -308,11 +310,13 @@ function AboutVersionSection() { setDesktopUpdateStateQueryData(queryClient, result.state); }) .catch((error: unknown) => { - toastManager.add({ - type: "error", - title: "Could not download update", - description: error instanceof Error ? error.message : "Download failed.", - }); + toastManager.add( + stackedThreadToast({ + type: "error", + title: "Could not download update", + description: error instanceof Error ? error.message : "Download failed.", + }), + ); }); return; } @@ -330,11 +334,13 @@ function AboutVersionSection() { setDesktopUpdateStateQueryData(queryClient, result.state); }) .catch((error: unknown) => { - toastManager.add({ - type: "error", - title: "Could not install update", - description: error instanceof Error ? error.message : "Install failed.", - }); + toastManager.add( + stackedThreadToast({ + type: "error", + title: "Could not install update", + description: error instanceof Error ? error.message : "Install failed.", + }), + ); }); return; } @@ -345,20 +351,24 @@ function AboutVersionSection() { .then((result) => { setDesktopUpdateStateQueryData(queryClient, result.state); if (!result.checked) { - toastManager.add({ - type: "error", - title: "Could not check for updates", - description: - result.state.message ?? "Automatic updates are not available in this build.", - }); + toastManager.add( + stackedThreadToast({ + type: "error", + title: "Could not check for updates", + description: + result.state.message ?? "Automatic updates are not available in this build.", + }), + ); } }) .catch((error: unknown) => { - toastManager.add({ - type: "error", - title: "Could not check for updates", - description: error instanceof Error ? error.message : "Update check failed.", - }); + toastManager.add( + stackedThreadToast({ + type: "error", + title: "Could not check for updates", + description: error instanceof Error ? error.message : "Update check failed.", + }), + ); }); }, [queryClient, updateState]); @@ -1688,11 +1698,13 @@ export function ArchivedThreadsPanel() { try { await unarchiveThread(threadRef); } catch (error) { - toastManager.add({ - type: "error", - title: "Failed to unarchive thread", - description: error instanceof Error ? error.message : "An error occurred.", - }); + toastManager.add( + stackedThreadToast({ + type: "error", + title: "Failed to unarchive thread", + description: error instanceof Error ? error.message : "An error occurred.", + }), + ); } return; } @@ -1756,12 +1768,14 @@ export function ArchivedThreadsPanel() { onClick={() => void unarchiveThread(scopeThreadRef(thread.environmentId, thread.id)).catch( (error) => { - toastManager.add({ - type: "error", - title: "Failed to unarchive thread", - description: - error instanceof Error ? error.message : "An error occurred.", - }); + toastManager.add( + stackedThreadToast({ + type: "error", + title: "Failed to unarchive thread", + description: + error instanceof Error ? error.message : "An error occurred.", + }), + ); }, ) } diff --git a/apps/web/src/components/sidebar/SidebarUpdatePill.tsx b/apps/web/src/components/sidebar/SidebarUpdatePill.tsx index 2f9aec112a..d7e5b74d42 100644 --- a/apps/web/src/components/sidebar/SidebarUpdatePill.tsx +++ b/apps/web/src/components/sidebar/SidebarUpdatePill.tsx @@ -6,7 +6,7 @@ import { setDesktopUpdateStateQueryData, useDesktopUpdateState, } from "../../lib/desktopUpdateReactQuery"; -import { toastManager } from "../ui/toast"; +import { stackedThreadToast, toastManager } from "../ui/toast"; import { getArm64IntelBuildWarningDescription, getDesktopUpdateActionError, @@ -55,18 +55,22 @@ export function SidebarUpdatePill() { if (!shouldToastDesktopUpdateActionResult(result)) return; const actionError = getDesktopUpdateActionError(result); if (!actionError) return; - toastManager.add({ - type: "error", - title: "Could not download update", - description: actionError, - }); + toastManager.add( + stackedThreadToast({ + type: "error", + title: "Could not download update", + description: actionError, + }), + ); }) .catch((error) => { - toastManager.add({ - type: "error", - title: "Could not start update download", - description: error instanceof Error ? error.message : "An unexpected error occurred.", - }); + toastManager.add( + stackedThreadToast({ + type: "error", + title: "Could not start update download", + description: error instanceof Error ? error.message : "An unexpected error occurred.", + }), + ); }); return; } @@ -81,18 +85,22 @@ export function SidebarUpdatePill() { if (!shouldToastDesktopUpdateActionResult(result)) return; const actionError = getDesktopUpdateActionError(result); if (!actionError) return; - toastManager.add({ - type: "error", - title: "Could not install update", - description: actionError, - }); + toastManager.add( + stackedThreadToast({ + type: "error", + title: "Could not install update", + description: actionError, + }), + ); }) .catch((error) => { - toastManager.add({ - type: "error", - title: "Could not install update", - description: error instanceof Error ? error.message : "An unexpected error occurred.", - }); + toastManager.add( + stackedThreadToast({ + type: "error", + title: "Could not install update", + description: error instanceof Error ? error.message : "An unexpected error occurred.", + }), + ); }); } }, [action, disabled, queryClient, state]); diff --git a/apps/web/src/components/ui/toast.logic.test.ts b/apps/web/src/components/ui/toast.logic.test.ts index e634d7d946..fefb61196b 100644 --- a/apps/web/src/components/ui/toast.logic.test.ts +++ b/apps/web/src/components/ui/toast.logic.test.ts @@ -45,6 +45,62 @@ describe("buildVisibleToastLayout", () => { ); }); + it("reflows live toasts forward when the front toast is dismissed", () => { + const visibleToasts = [ + { id: "a", height: 48, transitionStatus: "ending" as const }, + { id: "b", height: 72 }, + { id: "c", height: 24 }, + ]; + + const layout = buildVisibleToastLayout(visibleToasts); + + // frontmost height should be the first live toast, not the ending one + assert.equal(layout.frontmostHeight, 72); + assert.deepEqual( + layout.items.map(({ toast, visibleIndex, offsetY }) => ({ + id: toast.id, + visibleIndex, + offsetY, + })), + [ + // Ending toast stays at its front slot; data-ending-style drives its exit + { id: "a", visibleIndex: 0, offsetY: 0 }, + // Live toasts get fresh indices starting at 0 so they move up in sync + { id: "b", visibleIndex: 0, offsetY: 0 }, + { id: "c", visibleIndex: 1, offsetY: 72 }, + ], + ); + }); + + it("keeps a non-front ending toast at its current slot so it exits straight", () => { + const visibleToasts = [ + { id: "a", height: 48 }, + { id: "b", height: 72, transitionStatus: "ending" as const }, + { id: "c", height: 24 }, + ]; + + const layout = buildVisibleToastLayout(visibleToasts); + + // front toast stays, so frontmost height is unchanged + assert.equal(layout.frontmostHeight, 48); + assert.deepEqual( + layout.items.map(({ toast, visibleIndex, offsetY }) => ({ + id: toast.id, + visibleIndex, + offsetY, + })), + [ + // Front live toast — unaffected + { id: "a", visibleIndex: 0, offsetY: 0 }, + // Ending toast keeps its pre-dismissal slot so its horizontal exit + // originates from where the user saw it (not from Y=0). + { id: "b", visibleIndex: 1, offsetY: 48 }, + // Live toast behind "b" slides forward into the vacated slot. + { id: "c", visibleIndex: 1, offsetY: 48 }, + ], + ); + }); + it("treats missing heights as zero", () => { const layout = buildVisibleToastLayout([ { id: "a" }, diff --git a/apps/web/src/components/ui/toast.logic.ts b/apps/web/src/components/ui/toast.logic.ts index 09905a7a67..80f23970ce 100644 --- a/apps/web/src/components/ui/toast.logic.ts +++ b/apps/web/src/components/ui/toast.logic.ts @@ -14,6 +14,12 @@ type ToastWithHeight = { height?: number | null | undefined; }; +type ToastWithTransitionStatus = { + transitionStatus?: "starting" | "ending" | undefined; +}; + +type ToastWithLayoutProps = ToastWithHeight & ToastWithTransitionStatus; + type VisibleToastLayoutItem = { toast: TToast; visibleIndex: number; @@ -21,25 +27,61 @@ type VisibleToastLayoutItem = { }; export function buildVisibleToastLayout( - visibleToasts: readonly (TToast & ToastWithHeight)[], + visibleToasts: readonly (TToast & ToastWithLayoutProps)[], ): { frontmostHeight: number; - items: VisibleToastLayoutItem[]; + items: VisibleToastLayoutItem[]; } { - let offsetY = 0; + // Two parallel cursors: + // - `full*` advances on every toast, so an ending toast keeps the slot it + // occupied before dismissal and its data-ending-style exit transform + // originates from the correct position (critical for dismissing a + // non-front toast in the expanded stack — otherwise it would snap to + // Y=0 and slide off diagonally). + // - `live*` advances only on non-ending toasts, so live toasts reflow + // past the vacated slot in parallel with the exit animation instead of + // waiting for it to finish (which caused a visible "stop and bump"). + let fullIndex = 0; + let fullOffsetY = 0; + let liveIndex = 0; + let liveOffsetY = 0; + + const items: VisibleToastLayoutItem[] = visibleToasts.map( + (toast) => { + const height = normalizeToastHeight(toast.height); + + if (toast.transitionStatus === "ending") { + const item = { + toast, + visibleIndex: fullIndex, + offsetY: fullOffsetY, + }; + fullOffsetY += height; + fullIndex += 1; + return item; + } - return { - frontmostHeight: normalizeToastHeight(visibleToasts[0]?.height), - items: visibleToasts.map((toast, visibleIndex) => { const item = { toast, - visibleIndex, - offsetY, + visibleIndex: liveIndex, + offsetY: liveOffsetY, }; - offsetY += normalizeToastHeight(toast.height); + fullOffsetY += height; + fullIndex += 1; + liveOffsetY += height; + liveIndex += 1; return item; - }), + }, + ); + + // Frontmost height should reflect the first non-ending (live) toast so the + // stack sizes to what's actually staying on screen. + const frontmostLiveToast = visibleToasts.find((toast) => toast.transitionStatus !== "ending"); + + return { + frontmostHeight: normalizeToastHeight(frontmostLiveToast?.height), + items, }; } diff --git a/apps/web/src/components/ui/toast.tsx b/apps/web/src/components/ui/toast.tsx index 083ca48007..dd0eba432b 100644 --- a/apps/web/src/components/ui/toast.tsx +++ b/apps/web/src/components/ui/toast.tsx @@ -1,17 +1,27 @@ "use client"; import { Toast } from "@base-ui/react/toast"; -import { useEffect, useMemo, type CSSProperties } from "react"; +import { + useEffect, + useMemo, + useState, + type CSSProperties, + type KeyboardEvent, + type ReactNode, +} from "react"; import { useParams } from "@tanstack/react-router"; import { type ScopedThreadRef, type ThreadId } from "@t3tools/contracts"; import { CheckIcon, + ChevronDownIcon, + ChevronUpIcon, CircleAlertIcon, CircleCheckIcon, CopyIcon, InfoIcon, LoaderCircleIcon, TriangleAlertIcon, + XIcon, } from "lucide-react"; import { cn } from "~/lib/utils"; @@ -31,6 +41,11 @@ export type ThreadToastData = { tooltipStyle?: boolean; dismissAfterVisibleMs?: number; hideCopyButton?: boolean; + /** Optional extra body shown after toggling “Show details” (e.g. a list of pending RPCs). */ + expandableContent?: ReactNode; + expandableLabels?: { expand?: string; collapse?: string }; + /** When set with `expandableContent`, the summary + label act as one text disclosure (no separate chevron row). */ + expandableDescriptionTrigger?: boolean; actionLayout?: "inline" | "stacked-end"; actionVariant?: | "default" @@ -55,25 +70,265 @@ const TOAST_ICONS = { warning: TriangleAlertIcon, } as const; +/** Visually shorten long error bodies; clipboard copy still uses the full `description` string. */ +const ERROR_DESCRIPTION_CLAMP_MIN_CHARS = 180; +function errorDescriptionClampClass(type: unknown, description: unknown): string | undefined { + if (type !== "error" || typeof description !== "string") { + return undefined; + } + if (description.length < ERROR_DESCRIPTION_CLAMP_MIN_CHARS) { + return undefined; + } + return "line-clamp-4"; +} + +/** Dismiss-only: circular control overlapping the card corner (iOS notification–style). */ +const toastCornerDismissClass = "absolute z-20 -top-1.5 -right-1.5"; +const toastCornerOrbClass = cn( + "inline-flex size-6 shrink-0 cursor-pointer items-center justify-center rounded-full border border-border/60 bg-popover/92 text-muted-foreground shadow-sm outline-none backdrop-blur-sm", + "transition-[color,background-color,box-shadow] hover:bg-popover hover:text-foreground", + "focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-1 focus-visible:ring-offset-background", +); + function CopyErrorButton({ text }: { text: string }) { const { copyToClipboard, isCopied } = useCopyToClipboard(); return ( ); } +/** Scrollable cap for long expandable lists (~10rem); keeps the toast from growing without bound. */ +const toastExpandablePanelClassName = + "mt-2 max-h-40 min-h-0 overflow-y-auto overscroll-contain pr-0.5 select-text"; + +function ToastExpandableSection({ + children, + labels, +}: { + children: ReactNode; + labels: { expand?: string; collapse?: string }; +}) { + const [open, setOpen] = useState(false); + const expandLabel = labels.expand ?? "Show details"; + const collapseLabel = labels.collapse ?? "Hide details"; + + return ( +
+ + {open ?
{children}
: null} +
+ ); +} + +function ToastDescriptionAndExpandable({ + toastData, + toastDescription, + toastType, +}: { + toastData: ThreadToastData | undefined; + toastDescription: unknown; + toastType: unknown; +}) { + const expandableContent = toastData?.expandableContent; + const labels = toastData?.expandableLabels ?? {}; + const descriptionTrigger = toastData?.expandableDescriptionTrigger ?? false; + const descriptionClassName = cn( + "min-w-0 select-text wrap-break-word text-muted-foreground", + errorDescriptionClampClass(toastType, toastDescription), + ); + const [open, setOpen] = useState(false); + + if (!expandableContent) { + return ; + } + + if (!descriptionTrigger) { + return ( + <> + + {expandableContent} + + ); + } + + const expandLabel = labels.expand ?? "Show details"; + const collapseLabel = labels.collapse ?? "Hide details"; + + const toggle = () => setOpen((v) => !v); + const onKeyDown = (event: KeyboardEvent) => { + if (event.key === "Enter" || event.key === " ") { + event.preventDefault(); + toggle(); + } + }; + + return ( + <> +
+
+ +
+ {open ? ( + + ) : ( + + )} +
+ {open ?
{expandableContent}
: null} + + ); +} + +type ToastIconComponent = (typeof TOAST_ICONS)[keyof typeof TOAST_ICONS]; + +interface ToastBodyDescriptor { + readonly Icon: ToastIconComponent | null | undefined; + readonly stackedActionLayout: boolean; + readonly actionVariant: NonNullable; + readonly copyErrorText: string | null; + readonly hasTrailingControls: boolean; + readonly inlineContentEndPad: string; +} + +function deriveToastBodyDescriptor(toast: { + readonly type?: string | undefined; + readonly description?: unknown; + readonly actionProps?: unknown; + readonly data?: ThreadToastData | undefined; +}): ToastBodyDescriptor { + const Icon = toast.type ? TOAST_ICONS[toast.type as keyof typeof TOAST_ICONS] : null; + const stackedActionLayout = + toast.actionProps !== undefined && toast.data?.actionLayout === "stacked-end"; + const actionVariant: NonNullable = + toast.data?.actionVariant ?? "default"; + const copyErrorText = + toast.type === "error" && typeof toast.description === "string" && !toast.data?.hideCopyButton + ? toast.description + : null; + const hasTrailingControls = copyErrorText !== null || toast.actionProps !== undefined; + const inlineContentEndPad = hasTrailingControls ? "pr-6" : "pr-10"; + return { + Icon, + stackedActionLayout, + actionVariant, + copyErrorText, + hasTrailingControls, + inlineContentEndPad, + }; +} + +interface ToastBodyContentProps extends ToastBodyDescriptor { + readonly actionProps: { readonly children?: ReactNode } | undefined; + readonly toastData: ThreadToastData | undefined; + readonly toastDescription: unknown; + readonly toastType: unknown; +} + +function ToastBodyContent({ + stackedActionLayout, + Icon, + copyErrorText, + actionProps, + actionVariant, + hasTrailingControls, + toastData, + toastDescription, + toastType, +}: ToastBodyContentProps) { + return ( + <> +
+ {Icon && ( +
+ +
+ )} +
+ + +
+
+ {hasTrailingControls ? ( +
+ {copyErrorText !== null ? : null} + {actionProps ? ( + + {actionProps.children} + + ) : null} +
+ ) : null} + + ); +} + type ToastPosition = | "top-left" | "top-center" @@ -236,19 +491,17 @@ function Toasts({ position = "top-right" }: { position: ToastPosition }) { } > {visibleToastLayout.items.map(({ toast, visibleIndex, offsetY }) => { - const Icon = toast.type ? TOAST_ICONS[toast.type as keyof typeof TOAST_ICONS] : null; const hideCollapsedContent = shouldHideCollapsedToastContent( visibleIndex, visibleToastLayout.items.length, ); - const stackedActionLayout = - toast.actionProps !== undefined && toast.data?.actionLayout === "stacked-end"; - const actionVariant = toast.data?.actionVariant ?? "default"; + const bodyDescriptor = deriveToastBodyDescriptor(toast); + const { stackedActionLayout, inlineContentEndPad } = bodyDescriptor; return ( 0 + ? "not-data-expanded:[--toast-calc-height:var(--toast-frontmost-height)] data-expanded:[--toast-calc-height:max(var(--toast-frontmost-height,var(--toast-height)),var(--toast-height))]" + : "[--toast-calc-height:max(var(--toast-frontmost-height,var(--toast-height)),var(--toast-height))]", + "[--toast-gap:--spacing(3)] [--toast-peek:--spacing(3)] [--toast-scale:calc(max(0,1-(var(--toast-index)*.1)))] [--toast-shrink:calc(1-var(--toast-scale))]", + // Root height: never `min-h-(--toast-height)` — Base UI measures height by briefly forcing + // `height: auto` on this node; an old `min-height` from `--toast-height` blocks shrinking, + // so `recalculateHeight` keeps the inflated value after an expandable closes. + // Behind + collapsed: fixed peek. Otherwise natural height (expand/collapse, hover stack). + visibleIndex > 0 + ? "not-data-expanded:h-(--toast-calc-height) data-expanded:h-auto" + : "h-auto", // Define offset-y variable "data-[position*=top]:[--toast-calc-offset-y:calc(var(--toast-offset-y)+var(--toast-index)*var(--toast-gap)+var(--toast-swipe-movement-y))]", "data-[position*=bottom]:[--toast-calc-offset-y:calc(var(--toast-offset-y)*-1+var(--toast-index)*var(--toast-gap)*-1+var(--toast-swipe-movement-y))]", @@ -272,8 +533,7 @@ function Toasts({ position = "top-right" }: { position: ToastPosition }) { "data-[position*=bottom]:transform-[translateX(var(--toast-swipe-movement-x))_translateY(calc(var(--toast-swipe-movement-y)-(var(--toast-index)*var(--toast-peek))-(var(--toast-shrink)*var(--toast-calc-height))))_scale(var(--toast-scale))]", // Limited state "data-limited:opacity-0", - // Expanded state - "data-expanded:h-(--toast-height)", + // Expanded stack "data-position:data-expanded:transform-[translateX(var(--toast-swipe-movement-x))_translateY(var(--toast-calc-offset-y))]", // Starting and ending animations "data-[position*=top]:data-starting-style:transform-[translateY(calc(-100%-var(--toast-inset)))]", @@ -314,54 +574,36 @@ function Toasts({ position = "top-right" }: { position: ToastPosition }) { dismissAfterVisibleMs={toast.data?.dismissAfterVisibleMs} toastId={toast.id} /> +
+ +
-
- {Icon && ( -
- -
- )} - -
-
- - {toast.type === "error" && - typeof toast.description === "string" && - !toast.data?.hideCopyButton && } -
- -
-
- {toast.actionProps && ( - - {toast.actionProps.children} - - )} +
); @@ -390,12 +632,10 @@ function AnchoredToasts() { {toasts .filter((toast) => shouldRenderThreadScopedToast(toast.data, activeThreadRef)) .map((toast) => { - const Icon = toast.type ? TOAST_ICONS[toast.type as keyof typeof TOAST_ICONS] : null; const tooltipStyle = toast.data?.tooltipStyle ?? false; const positionerProps = toast.positionerProps; - const stackedActionLayout = - toast.actionProps !== undefined && toast.data?.actionLayout === "stacked-end"; - const actionVariant = toast.data?.actionVariant ?? "default"; + const bodyDescriptor = deriveToastBodyDescriptor(toast); + const { stackedActionLayout, inlineContentEndPad } = bodyDescriptor; if (!positionerProps?.anchor) { return null; @@ -411,7 +651,7 @@ function AnchoredToasts() { > ) : ( - -
- {Icon && ( -
- -
- )} - -
-
- - {toast.type === "error" && - typeof toast.description === "string" && - !toast.data?.hideCopyButton && ( - - )} -
- -
-
- {toast.actionProps && ( - +
+ +
+ + + + )}
@@ -483,6 +707,9 @@ function AnchoredToasts() { ); } +export { stackedThreadToast } from "./toastHelpers"; +export type { StackedThreadToastOptions } from "./toastHelpers"; + export { ToastProvider, type ToastPosition, diff --git a/apps/web/src/components/ui/toastHelpers.ts b/apps/web/src/components/ui/toastHelpers.ts new file mode 100644 index 0000000000..4ec5d14106 --- /dev/null +++ b/apps/web/src/components/ui/toastHelpers.ts @@ -0,0 +1,58 @@ +"use client"; + +import type { ToastManagerAddOptions } from "@base-ui/react/toast"; +import type { ComponentPropsWithoutRef, ReactNode } from "react"; + +import type { ThreadToastData } from "./toast"; + +export type StackedThreadToastOptions = { + type: "error" | "warning" | "success" | "info" | "loading"; + title: ReactNode; + description?: ReactNode; + timeout?: number; + priority?: "low" | "high"; + actionProps?: ComponentPropsWithoutRef<"button">; + /** Merged into `data`; `actionLayout` is always forced to `"stacked-end"` by the helper. */ + actionVariant?: ThreadToastData["actionVariant"]; + data?: Omit; +}; + +/** + * Thread toast using the stacked body + bottom action row (copy for errors, CTA on its own row). + */ +export function stackedThreadToast( + options: StackedThreadToastOptions, +): ToastManagerAddOptions { + const { type, title, description, timeout, priority, actionProps, actionVariant, data } = options; + + // Helper-owned `actionLayout` must win over any caller-provided `data`, so spread + // the caller's data first and apply `actionLayout: "stacked-end"` last. + const mergedData: ThreadToastData = { + ...(data !== undefined ? data : {}), + actionLayout: "stacked-end", + }; + if (actionVariant !== undefined) { + mergedData.actionVariant = actionVariant; + } + + const payload: ToastManagerAddOptions = { + type, + title, + data: mergedData, + }; + + if (description !== undefined) { + payload.description = description; + } + if (timeout !== undefined) { + payload.timeout = timeout; + } + if (priority !== undefined) { + payload.priority = priority; + } + if (actionProps !== undefined) { + payload.actionProps = actionProps; + } + + return payload; +} diff --git a/apps/web/src/hooks/useThreadActions.ts b/apps/web/src/hooks/useThreadActions.ts index 60b1be85a7..de60ffb18d 100644 --- a/apps/web/src/hooks/useThreadActions.ts +++ b/apps/web/src/hooks/useThreadActions.ts @@ -20,7 +20,7 @@ import { import { useTerminalStateStore } from "../terminalStateStore"; import { buildThreadRouteParams, resolveThreadRouteRef } from "../threadRoutes"; import { formatWorktreePathForDisplay, getOrphanedWorktreePathForThread } from "../worktreeCleanup"; -import { toastManager } from "../components/ui/toast"; +import { stackedThreadToast, toastManager } from "../components/ui/toast"; import { useSettings } from "./useSettings"; export function useThreadActions() { @@ -225,11 +225,13 @@ export function useThreadActions() { worktreePath: orphanedWorktreePath, error, }); - toastManager.add({ - type: "error", - title: "Thread deleted, but worktree removal failed", - description: `Could not remove ${displayWorktreePath ?? orphanedWorktreePath}. ${message}`, - }); + toastManager.add( + stackedThreadToast({ + type: "error", + title: "Thread deleted, but worktree removal failed", + description: `Could not remove ${displayWorktreePath ?? orphanedWorktreePath}. ${message}`, + }), + ); } }, [ diff --git a/apps/web/src/routes/__root.tsx b/apps/web/src/routes/__root.tsx index b0c0713fe3..87e8667901 100644 --- a/apps/web/src/routes/__root.tsx +++ b/apps/web/src/routes/__root.tsx @@ -19,7 +19,12 @@ import { WebSocketConnectionSurface, } from "../components/WebSocketConnectionSurface"; import { Button } from "../components/ui/button"; -import { AnchoredToastProvider, ToastProvider, toastManager } from "../components/ui/toast"; +import { + AnchoredToastProvider, + stackedThreadToast, + ToastProvider, + toastManager, +} from "../components/ui/toast"; import { resolveAndPersistPreferredEditor } from "../editorPreferences"; import { readLocalApi } from "../localApi"; import { useSettings } from "../hooks/useSettings"; @@ -290,37 +295,42 @@ function EventRouter() { return; } - toastManager.add({ - type: "warning", - title: "Invalid keybindings configuration", - description: issue.message, - actionProps: { - children: "Open keybindings.json", - onClick: () => { - const api = readLocalApi(); - if (!api) { - return; - } + toastManager.add( + stackedThreadToast({ + type: "warning", + title: "Invalid keybindings configuration", + description: issue.message, + actionVariant: "outline", + actionProps: { + children: "Open keybindings.json", + onClick: () => { + const api = readLocalApi(); + if (!api) { + return; + } - void Promise.resolve(serverConfig ?? api.server.getConfig()) - .then((config) => { - const editor = resolveAndPersistPreferredEditor(config.availableEditors); - if (!editor) { - throw new Error("No available editors found."); - } - return api.shell.openInEditor(config.keybindingsConfigPath, editor); - }) - .catch((error) => { - toastManager.add({ - type: "error", - title: "Unable to open keybindings file", - description: - error instanceof Error ? error.message : "Unknown error opening file.", + void Promise.resolve(serverConfig ?? api.server.getConfig()) + .then((config) => { + const editor = resolveAndPersistPreferredEditor(config.availableEditors); + if (!editor) { + throw new Error("No available editors found."); + } + return api.shell.openInEditor(config.keybindingsConfigPath, editor); + }) + .catch((error) => { + toastManager.add( + stackedThreadToast({ + type: "error", + title: "Unable to open keybindings file", + description: + error instanceof Error ? error.message : "Unknown error opening file.", + }), + ); }); - }); + }, }, - }, - }); + }), + ); }, ); From b7c89cf496d4c47baa3af2f72042eec5885ea770 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Tue, 21 Apr 2026 15:30:54 -0700 Subject: [PATCH 15/82] Refresh Codex protocol bindings to `be75785504ff152fa6333e380a2d50642f42fba0` (#2276) Co-authored-by: Cursor Agent --- .../src/provider/Layers/CodexProvider.ts | 4 +- .../provider/Layers/CodexSessionRuntime.ts | 5 +- .../provider/Layers/ProviderRegistry.test.ts | 2 +- .../scripts/generate.ts | 2 +- .../src/_generated/meta.gen.ts | 61 +- .../src/_generated/namespaces.gen.ts | 27 +- .../src/_generated/schema.gen.ts | 6455 +++++++++++++---- 7 files changed, 5007 insertions(+), 1549 deletions(-) diff --git a/apps/server/src/provider/Layers/CodexProvider.ts b/apps/server/src/provider/Layers/CodexProvider.ts index cea768266d..13069952ae 100644 --- a/apps/server/src/provider/Layers/CodexProvider.ts +++ b/apps/server/src/provider/Layers/CodexProvider.ts @@ -62,7 +62,9 @@ function codexAccountAuthLabel(account: CodexSchema.V2GetAccountResponse["accoun case "plus": return "ChatGPT Plus Subscription"; case "pro": - return "ChatGPT Pro Subscription"; + return "ChatGPT Pro 20x Subscription"; + case "prolite": + return "ChatGPT Pro 5x Subscription"; case "team": return "ChatGPT Team Subscription"; case "self_serve_business_usage_based": diff --git a/apps/server/src/provider/Layers/CodexSessionRuntime.ts b/apps/server/src/provider/Layers/CodexSessionRuntime.ts index 29b22e16f8..fbf4aa3dee 100644 --- a/apps/server/src/provider/Layers/CodexSessionRuntime.ts +++ b/apps/server/src/provider/Layers/CodexSessionRuntime.ts @@ -468,6 +468,7 @@ function readNotificationThreadId(notification: CodexServerNotification): string case "item/commandExecution/outputDelta": case "item/commandExecution/terminalInteraction": case "item/fileChange/outputDelta": + case "item/fileChange/patchUpdated": case "serverRequest/resolved": case "item/mcpToolCall/progress": case "item/reasoning/summaryTextDelta": @@ -476,7 +477,8 @@ function readNotificationThreadId(notification: CodexServerNotification): string case "thread/compacted": case "thread/realtime/started": case "thread/realtime/itemAdded": - case "thread/realtime/transcriptUpdated": + case "thread/realtime/transcript/delta": + case "thread/realtime/transcript/done": case "thread/realtime/outputAudio/delta": case "thread/realtime/sdp": case "thread/realtime/error": @@ -530,6 +532,7 @@ function readRouteFields(notification: CodexServerNotification): { case "item/commandExecution/outputDelta": case "item/commandExecution/terminalInteraction": case "item/fileChange/outputDelta": + case "item/fileChange/patchUpdated": case "item/reasoning/summaryTextDelta": case "item/reasoning/summaryPartAdded": case "item/reasoning/textDelta": diff --git a/apps/server/src/provider/Layers/ProviderRegistry.test.ts b/apps/server/src/provider/Layers/ProviderRegistry.test.ts index 2d6855f914..8fe28351a4 100644 --- a/apps/server/src/provider/Layers/ProviderRegistry.test.ts +++ b/apps/server/src/provider/Layers/ProviderRegistry.test.ts @@ -179,7 +179,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))( assert.strictEqual(status.version, "1.0.0"); assert.strictEqual(status.auth.status, "authenticated"); assert.strictEqual(status.auth.type, "chatgpt"); - assert.strictEqual(status.auth.label, "ChatGPT Pro Subscription"); + assert.strictEqual(status.auth.label, "ChatGPT Pro 20x Subscription"); assert.deepStrictEqual(status.models, [ { slug: "gpt-live-codex", diff --git a/packages/effect-codex-app-server/scripts/generate.ts b/packages/effect-codex-app-server/scripts/generate.ts index 5f0991c39f..54ce0866f1 100644 --- a/packages/effect-codex-app-server/scripts/generate.ts +++ b/packages/effect-codex-app-server/scripts/generate.ts @@ -6,7 +6,7 @@ import { make as makeJsonSchemaGenerator } from "@effect/openapi-generator/JsonS import { Effect, FileSystem, Layer, Logger, Path, Schema } from "effect"; import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process"; -const UPSTREAM_REF = "dbfe855f4fd0f5dcdf079882652a8efe622b0595"; +const UPSTREAM_REF = "be75785504ff152fa6333e380a2d50642f42fba0"; const USER_AGENT = "effect-codex-app-server-generator"; const GITHUB_API_BASE = "https://api.github.com/repos/openai/codex/contents/codex-rs/app-server-protocol"; diff --git a/packages/effect-codex-app-server/src/_generated/meta.gen.ts b/packages/effect-codex-app-server/src/_generated/meta.gen.ts index d0b7376495..1afa46859e 100644 --- a/packages/effect-codex-app-server/src/_generated/meta.gen.ts +++ b/packages/effect-codex-app-server/src/_generated/meta.gen.ts @@ -1,5 +1,5 @@ // This file is generated by the effect-codex-app-server package. Do not edit manually. -// Upstream protocol ref: dbfe855f4fd0f5dcdf079882652a8efe622b0595 +// Upstream protocol ref: be75785504ff152fa6333e380a2d50642f42fba0 import * as CodexSchema from "./schema.gen.ts"; @@ -19,10 +19,17 @@ export const CLIENT_REQUEST_METHODS = { "thread/list": "thread/list", "thread/loaded/list": "thread/loaded/list", "thread/read": "thread/read", + "thread/turns/list": "thread/turns/list", + "thread/inject_items": "thread/inject_items", "skills/list": "skills/list", + "marketplace/add": "marketplace/add", + "marketplace/remove": "marketplace/remove", "plugin/list": "plugin/list", "plugin/read": "plugin/read", "app/list": "app/list", + "device/key/create": "device/key/create", + "device/key/public": "device/key/public", + "device/key/sign": "device/key/sign", "fs/readFile": "fs/readFile", "fs/writeFile": "fs/writeFile", "fs/createDirectory": "fs/createDirectory", @@ -52,6 +59,7 @@ export const CLIENT_REQUEST_METHODS = { "account/login/cancel": "account/login/cancel", "account/logout": "account/logout", "account/rateLimits/read": "account/rateLimits/read", + "account/sendAddCreditsNudgeEmail": "account/sendAddCreditsNudgeEmail", "feedback/upload": "feedback/upload", "command/exec": "command/exec", "command/exec/write": "command/exec/write", @@ -113,6 +121,7 @@ export const SERVER_NOTIFICATION_METHODS = { "item/commandExecution/outputDelta": "item/commandExecution/outputDelta", "item/commandExecution/terminalInteraction": "item/commandExecution/terminalInteraction", "item/fileChange/outputDelta": "item/fileChange/outputDelta", + "item/fileChange/patchUpdated": "item/fileChange/patchUpdated", "serverRequest/resolved": "serverRequest/resolved", "item/mcpToolCall/progress": "item/mcpToolCall/progress", "mcpServer/oauthLogin/completed": "mcpServer/oauthLogin/completed", @@ -120,19 +129,22 @@ export const SERVER_NOTIFICATION_METHODS = { "account/updated": "account/updated", "account/rateLimits/updated": "account/rateLimits/updated", "app/list/updated": "app/list/updated", + "externalAgentConfig/import/completed": "externalAgentConfig/import/completed", "fs/changed": "fs/changed", "item/reasoning/summaryTextDelta": "item/reasoning/summaryTextDelta", "item/reasoning/summaryPartAdded": "item/reasoning/summaryPartAdded", "item/reasoning/textDelta": "item/reasoning/textDelta", "thread/compacted": "thread/compacted", "model/rerouted": "model/rerouted", + warning: "warning", deprecationNotice: "deprecationNotice", configWarning: "configWarning", "fuzzyFileSearch/sessionUpdated": "fuzzyFileSearch/sessionUpdated", "fuzzyFileSearch/sessionCompleted": "fuzzyFileSearch/sessionCompleted", "thread/realtime/started": "thread/realtime/started", "thread/realtime/itemAdded": "thread/realtime/itemAdded", - "thread/realtime/transcriptUpdated": "thread/realtime/transcriptUpdated", + "thread/realtime/transcript/delta": "thread/realtime/transcript/delta", + "thread/realtime/transcript/done": "thread/realtime/transcript/done", "thread/realtime/outputAudio/delta": "thread/realtime/outputAudio/delta", "thread/realtime/sdp": "thread/realtime/sdp", "thread/realtime/error": "thread/realtime/error", @@ -163,10 +175,17 @@ export interface ClientRequestParamsByMethod { readonly "thread/list": typeof CodexSchema.V2ThreadListParams.Type; readonly "thread/loaded/list": typeof CodexSchema.V2ThreadLoadedListParams.Type; readonly "thread/read": typeof CodexSchema.V2ThreadReadParams.Type; + readonly "thread/turns/list": typeof CodexSchema.V2ThreadTurnsListParams.Type; + readonly "thread/inject_items": typeof CodexSchema.V2ThreadInjectItemsParams.Type; readonly "skills/list": typeof CodexSchema.V2SkillsListParams.Type; + readonly "marketplace/add": typeof CodexSchema.V2MarketplaceAddParams.Type; + readonly "marketplace/remove": typeof CodexSchema.V2MarketplaceRemoveParams.Type; readonly "plugin/list": typeof CodexSchema.V2PluginListParams.Type; readonly "plugin/read": typeof CodexSchema.V2PluginReadParams.Type; readonly "app/list": typeof CodexSchema.V2AppsListParams.Type; + readonly "device/key/create": typeof CodexSchema.V2DeviceKeyCreateParams.Type; + readonly "device/key/public": typeof CodexSchema.V2DeviceKeyPublicParams.Type; + readonly "device/key/sign": typeof CodexSchema.V2DeviceKeySignParams.Type; readonly "fs/readFile": typeof CodexSchema.V2FsReadFileParams.Type; readonly "fs/writeFile": typeof CodexSchema.V2FsWriteFileParams.Type; readonly "fs/createDirectory": typeof CodexSchema.V2FsCreateDirectoryParams.Type; @@ -196,6 +215,7 @@ export interface ClientRequestParamsByMethod { readonly "account/login/cancel": typeof CodexSchema.V2CancelLoginAccountParams.Type; readonly "account/logout": undefined; readonly "account/rateLimits/read": undefined; + readonly "account/sendAddCreditsNudgeEmail": typeof CodexSchema.V2SendAddCreditsNudgeEmailParams.Type; readonly "feedback/upload": typeof CodexSchema.V2FeedbackUploadParams.Type; readonly "command/exec": typeof CodexSchema.V2CommandExecParams.Type; readonly "command/exec/write": typeof CodexSchema.V2CommandExecWriteParams.Type; @@ -230,10 +250,17 @@ export interface ClientRequestResponsesByMethod { readonly "thread/list": typeof CodexSchema.V2ThreadListResponse.Type; readonly "thread/loaded/list": typeof CodexSchema.V2ThreadLoadedListResponse.Type; readonly "thread/read": typeof CodexSchema.V2ThreadReadResponse.Type; + readonly "thread/turns/list": typeof CodexSchema.V2ThreadTurnsListResponse.Type; + readonly "thread/inject_items": typeof CodexSchema.V2ThreadInjectItemsResponse.Type; readonly "skills/list": typeof CodexSchema.V2SkillsListResponse.Type; + readonly "marketplace/add": typeof CodexSchema.V2MarketplaceAddResponse.Type; + readonly "marketplace/remove": typeof CodexSchema.V2MarketplaceRemoveResponse.Type; readonly "plugin/list": typeof CodexSchema.V2PluginListResponse.Type; readonly "plugin/read": typeof CodexSchema.V2PluginReadResponse.Type; readonly "app/list": typeof CodexSchema.V2AppsListResponse.Type; + readonly "device/key/create": typeof CodexSchema.V2DeviceKeyCreateResponse.Type; + readonly "device/key/public": typeof CodexSchema.V2DeviceKeyPublicResponse.Type; + readonly "device/key/sign": typeof CodexSchema.V2DeviceKeySignResponse.Type; readonly "fs/readFile": typeof CodexSchema.V2FsReadFileResponse.Type; readonly "fs/writeFile": typeof CodexSchema.V2FsWriteFileResponse.Type; readonly "fs/createDirectory": typeof CodexSchema.V2FsCreateDirectoryResponse.Type; @@ -263,6 +290,7 @@ export interface ClientRequestResponsesByMethod { readonly "account/login/cancel": typeof CodexSchema.V2CancelLoginAccountResponse.Type; readonly "account/logout": typeof CodexSchema.V2LogoutAccountResponse.Type; readonly "account/rateLimits/read": typeof CodexSchema.V2GetAccountRateLimitsResponse.Type; + readonly "account/sendAddCreditsNudgeEmail": typeof CodexSchema.V2SendAddCreditsNudgeEmailResponse.Type; readonly "feedback/upload": typeof CodexSchema.V2FeedbackUploadResponse.Type; readonly "command/exec": typeof CodexSchema.V2CommandExecResponse.Type; readonly "command/exec/write": typeof CodexSchema.V2CommandExecWriteResponse.Type; @@ -336,6 +364,7 @@ export interface ServerNotificationParamsByMethod { readonly "item/commandExecution/outputDelta": typeof CodexSchema.V2CommandExecutionOutputDeltaNotification.Type; readonly "item/commandExecution/terminalInteraction": typeof CodexSchema.V2TerminalInteractionNotification.Type; readonly "item/fileChange/outputDelta": typeof CodexSchema.V2FileChangeOutputDeltaNotification.Type; + readonly "item/fileChange/patchUpdated": typeof CodexSchema.V2FileChangePatchUpdatedNotification.Type; readonly "serverRequest/resolved": typeof CodexSchema.V2ServerRequestResolvedNotification.Type; readonly "item/mcpToolCall/progress": typeof CodexSchema.V2McpToolCallProgressNotification.Type; readonly "mcpServer/oauthLogin/completed": typeof CodexSchema.V2McpServerOauthLoginCompletedNotification.Type; @@ -343,19 +372,22 @@ export interface ServerNotificationParamsByMethod { readonly "account/updated": typeof CodexSchema.V2AccountUpdatedNotification.Type; readonly "account/rateLimits/updated": typeof CodexSchema.V2AccountRateLimitsUpdatedNotification.Type; readonly "app/list/updated": typeof CodexSchema.V2AppListUpdatedNotification.Type; + readonly "externalAgentConfig/import/completed": typeof CodexSchema.V2ExternalAgentConfigImportCompletedNotification.Type; readonly "fs/changed": typeof CodexSchema.V2FsChangedNotification.Type; readonly "item/reasoning/summaryTextDelta": typeof CodexSchema.V2ReasoningSummaryTextDeltaNotification.Type; readonly "item/reasoning/summaryPartAdded": typeof CodexSchema.V2ReasoningSummaryPartAddedNotification.Type; readonly "item/reasoning/textDelta": typeof CodexSchema.V2ReasoningTextDeltaNotification.Type; readonly "thread/compacted": typeof CodexSchema.V2ContextCompactedNotification.Type; readonly "model/rerouted": typeof CodexSchema.V2ModelReroutedNotification.Type; + readonly warning: typeof CodexSchema.V2WarningNotification.Type; readonly deprecationNotice: typeof CodexSchema.V2DeprecationNoticeNotification.Type; readonly configWarning: typeof CodexSchema.V2ConfigWarningNotification.Type; readonly "fuzzyFileSearch/sessionUpdated": typeof CodexSchema.FuzzyFileSearchSessionUpdatedNotification.Type; readonly "fuzzyFileSearch/sessionCompleted": typeof CodexSchema.FuzzyFileSearchSessionCompletedNotification.Type; readonly "thread/realtime/started": typeof CodexSchema.V2ThreadRealtimeStartedNotification.Type; readonly "thread/realtime/itemAdded": typeof CodexSchema.V2ThreadRealtimeItemAddedNotification.Type; - readonly "thread/realtime/transcriptUpdated": typeof CodexSchema.V2ThreadRealtimeTranscriptUpdatedNotification.Type; + readonly "thread/realtime/transcript/delta": typeof CodexSchema.V2ThreadRealtimeTranscriptDeltaNotification.Type; + readonly "thread/realtime/transcript/done": typeof CodexSchema.V2ThreadRealtimeTranscriptDoneNotification.Type; readonly "thread/realtime/outputAudio/delta": typeof CodexSchema.V2ThreadRealtimeOutputAudioDeltaNotification.Type; readonly "thread/realtime/sdp": typeof CodexSchema.V2ThreadRealtimeSdpNotification.Type; readonly "thread/realtime/error": typeof CodexSchema.V2ThreadRealtimeErrorNotification.Type; @@ -381,10 +413,17 @@ export const CLIENT_REQUEST_PARAMS = { "thread/list": CodexSchema.V2ThreadListParams, "thread/loaded/list": CodexSchema.V2ThreadLoadedListParams, "thread/read": CodexSchema.V2ThreadReadParams, + "thread/turns/list": CodexSchema.V2ThreadTurnsListParams, + "thread/inject_items": CodexSchema.V2ThreadInjectItemsParams, "skills/list": CodexSchema.V2SkillsListParams, + "marketplace/add": CodexSchema.V2MarketplaceAddParams, + "marketplace/remove": CodexSchema.V2MarketplaceRemoveParams, "plugin/list": CodexSchema.V2PluginListParams, "plugin/read": CodexSchema.V2PluginReadParams, "app/list": CodexSchema.V2AppsListParams, + "device/key/create": CodexSchema.V2DeviceKeyCreateParams, + "device/key/public": CodexSchema.V2DeviceKeyPublicParams, + "device/key/sign": CodexSchema.V2DeviceKeySignParams, "fs/readFile": CodexSchema.V2FsReadFileParams, "fs/writeFile": CodexSchema.V2FsWriteFileParams, "fs/createDirectory": CodexSchema.V2FsCreateDirectoryParams, @@ -414,6 +453,7 @@ export const CLIENT_REQUEST_PARAMS = { "account/login/cancel": CodexSchema.V2CancelLoginAccountParams, "account/logout": undefined, "account/rateLimits/read": undefined, + "account/sendAddCreditsNudgeEmail": CodexSchema.V2SendAddCreditsNudgeEmailParams, "feedback/upload": CodexSchema.V2FeedbackUploadParams, "command/exec": CodexSchema.V2CommandExecParams, "command/exec/write": CodexSchema.V2CommandExecWriteParams, @@ -448,10 +488,17 @@ export const CLIENT_REQUEST_RESPONSES = { "thread/list": CodexSchema.V2ThreadListResponse, "thread/loaded/list": CodexSchema.V2ThreadLoadedListResponse, "thread/read": CodexSchema.V2ThreadReadResponse, + "thread/turns/list": CodexSchema.V2ThreadTurnsListResponse, + "thread/inject_items": CodexSchema.V2ThreadInjectItemsResponse, "skills/list": CodexSchema.V2SkillsListResponse, + "marketplace/add": CodexSchema.V2MarketplaceAddResponse, + "marketplace/remove": CodexSchema.V2MarketplaceRemoveResponse, "plugin/list": CodexSchema.V2PluginListResponse, "plugin/read": CodexSchema.V2PluginReadResponse, "app/list": CodexSchema.V2AppsListResponse, + "device/key/create": CodexSchema.V2DeviceKeyCreateResponse, + "device/key/public": CodexSchema.V2DeviceKeyPublicResponse, + "device/key/sign": CodexSchema.V2DeviceKeySignResponse, "fs/readFile": CodexSchema.V2FsReadFileResponse, "fs/writeFile": CodexSchema.V2FsWriteFileResponse, "fs/createDirectory": CodexSchema.V2FsCreateDirectoryResponse, @@ -481,6 +528,7 @@ export const CLIENT_REQUEST_RESPONSES = { "account/login/cancel": CodexSchema.V2CancelLoginAccountResponse, "account/logout": CodexSchema.V2LogoutAccountResponse, "account/rateLimits/read": CodexSchema.V2GetAccountRateLimitsResponse, + "account/sendAddCreditsNudgeEmail": CodexSchema.V2SendAddCreditsNudgeEmailResponse, "feedback/upload": CodexSchema.V2FeedbackUploadResponse, "command/exec": CodexSchema.V2CommandExecResponse, "command/exec/write": CodexSchema.V2CommandExecWriteResponse, @@ -555,6 +603,7 @@ export const SERVER_NOTIFICATION_PARAMS = { "item/commandExecution/outputDelta": CodexSchema.V2CommandExecutionOutputDeltaNotification, "item/commandExecution/terminalInteraction": CodexSchema.V2TerminalInteractionNotification, "item/fileChange/outputDelta": CodexSchema.V2FileChangeOutputDeltaNotification, + "item/fileChange/patchUpdated": CodexSchema.V2FileChangePatchUpdatedNotification, "serverRequest/resolved": CodexSchema.V2ServerRequestResolvedNotification, "item/mcpToolCall/progress": CodexSchema.V2McpToolCallProgressNotification, "mcpServer/oauthLogin/completed": CodexSchema.V2McpServerOauthLoginCompletedNotification, @@ -562,19 +611,23 @@ export const SERVER_NOTIFICATION_PARAMS = { "account/updated": CodexSchema.V2AccountUpdatedNotification, "account/rateLimits/updated": CodexSchema.V2AccountRateLimitsUpdatedNotification, "app/list/updated": CodexSchema.V2AppListUpdatedNotification, + "externalAgentConfig/import/completed": + CodexSchema.V2ExternalAgentConfigImportCompletedNotification, "fs/changed": CodexSchema.V2FsChangedNotification, "item/reasoning/summaryTextDelta": CodexSchema.V2ReasoningSummaryTextDeltaNotification, "item/reasoning/summaryPartAdded": CodexSchema.V2ReasoningSummaryPartAddedNotification, "item/reasoning/textDelta": CodexSchema.V2ReasoningTextDeltaNotification, "thread/compacted": CodexSchema.V2ContextCompactedNotification, "model/rerouted": CodexSchema.V2ModelReroutedNotification, + warning: CodexSchema.V2WarningNotification, deprecationNotice: CodexSchema.V2DeprecationNoticeNotification, configWarning: CodexSchema.V2ConfigWarningNotification, "fuzzyFileSearch/sessionUpdated": CodexSchema.FuzzyFileSearchSessionUpdatedNotification, "fuzzyFileSearch/sessionCompleted": CodexSchema.FuzzyFileSearchSessionCompletedNotification, "thread/realtime/started": CodexSchema.V2ThreadRealtimeStartedNotification, "thread/realtime/itemAdded": CodexSchema.V2ThreadRealtimeItemAddedNotification, - "thread/realtime/transcriptUpdated": CodexSchema.V2ThreadRealtimeTranscriptUpdatedNotification, + "thread/realtime/transcript/delta": CodexSchema.V2ThreadRealtimeTranscriptDeltaNotification, + "thread/realtime/transcript/done": CodexSchema.V2ThreadRealtimeTranscriptDoneNotification, "thread/realtime/outputAudio/delta": CodexSchema.V2ThreadRealtimeOutputAudioDeltaNotification, "thread/realtime/sdp": CodexSchema.V2ThreadRealtimeSdpNotification, "thread/realtime/error": CodexSchema.V2ThreadRealtimeErrorNotification, diff --git a/packages/effect-codex-app-server/src/_generated/namespaces.gen.ts b/packages/effect-codex-app-server/src/_generated/namespaces.gen.ts index baa94c8797..fd18e9d4d0 100644 --- a/packages/effect-codex-app-server/src/_generated/namespaces.gen.ts +++ b/packages/effect-codex-app-server/src/_generated/namespaces.gen.ts @@ -1,5 +1,5 @@ // This file is generated by the effect-codex-app-server package. Do not edit manually. -// Upstream protocol ref: dbfe855f4fd0f5dcdf079882652a8efe622b0595 +// Upstream protocol ref: be75785504ff152fa6333e380a2d50642f42fba0 import * as CodexSchema from "./schema.gen.ts"; @@ -37,6 +37,12 @@ export const v2 = { ConfigWriteResponse: CodexSchema.V2ConfigWriteResponse, ContextCompactedNotification: CodexSchema.V2ContextCompactedNotification, DeprecationNoticeNotification: CodexSchema.V2DeprecationNoticeNotification, + DeviceKeyCreateParams: CodexSchema.V2DeviceKeyCreateParams, + DeviceKeyCreateResponse: CodexSchema.V2DeviceKeyCreateResponse, + DeviceKeyPublicParams: CodexSchema.V2DeviceKeyPublicParams, + DeviceKeyPublicResponse: CodexSchema.V2DeviceKeyPublicResponse, + DeviceKeySignParams: CodexSchema.V2DeviceKeySignParams, + DeviceKeySignResponse: CodexSchema.V2DeviceKeySignResponse, ErrorNotification: CodexSchema.V2ErrorNotification, ExperimentalFeatureEnablementSetParams: CodexSchema.V2ExperimentalFeatureEnablementSetParams, ExperimentalFeatureEnablementSetResponse: CodexSchema.V2ExperimentalFeatureEnablementSetResponse, @@ -44,11 +50,14 @@ export const v2 = { ExperimentalFeatureListResponse: CodexSchema.V2ExperimentalFeatureListResponse, ExternalAgentConfigDetectParams: CodexSchema.V2ExternalAgentConfigDetectParams, ExternalAgentConfigDetectResponse: CodexSchema.V2ExternalAgentConfigDetectResponse, + ExternalAgentConfigImportCompletedNotification: + CodexSchema.V2ExternalAgentConfigImportCompletedNotification, ExternalAgentConfigImportParams: CodexSchema.V2ExternalAgentConfigImportParams, ExternalAgentConfigImportResponse: CodexSchema.V2ExternalAgentConfigImportResponse, FeedbackUploadParams: CodexSchema.V2FeedbackUploadParams, FeedbackUploadResponse: CodexSchema.V2FeedbackUploadResponse, FileChangeOutputDeltaNotification: CodexSchema.V2FileChangeOutputDeltaNotification, + FileChangePatchUpdatedNotification: CodexSchema.V2FileChangePatchUpdatedNotification, FsChangedNotification: CodexSchema.V2FsChangedNotification, FsCopyParams: CodexSchema.V2FsCopyParams, FsCopyResponse: CodexSchema.V2FsCopyResponse, @@ -84,6 +93,10 @@ export const v2 = { LoginAccountParams: CodexSchema.V2LoginAccountParams, LoginAccountResponse: CodexSchema.V2LoginAccountResponse, LogoutAccountResponse: CodexSchema.V2LogoutAccountResponse, + MarketplaceAddParams: CodexSchema.V2MarketplaceAddParams, + MarketplaceAddResponse: CodexSchema.V2MarketplaceAddResponse, + MarketplaceRemoveParams: CodexSchema.V2MarketplaceRemoveParams, + MarketplaceRemoveResponse: CodexSchema.V2MarketplaceRemoveResponse, McpResourceReadParams: CodexSchema.V2McpResourceReadParams, McpResourceReadResponse: CodexSchema.V2McpResourceReadResponse, McpServerOauthLoginCompletedNotification: CodexSchema.V2McpServerOauthLoginCompletedNotification, @@ -112,6 +125,8 @@ export const v2 = { ReasoningTextDeltaNotification: CodexSchema.V2ReasoningTextDeltaNotification, ReviewStartParams: CodexSchema.V2ReviewStartParams, ReviewStartResponse: CodexSchema.V2ReviewStartResponse, + SendAddCreditsNudgeEmailParams: CodexSchema.V2SendAddCreditsNudgeEmailParams, + SendAddCreditsNudgeEmailResponse: CodexSchema.V2SendAddCreditsNudgeEmailResponse, ServerRequestResolvedNotification: CodexSchema.V2ServerRequestResolvedNotification, SkillsChangedNotification: CodexSchema.V2SkillsChangedNotification, SkillsConfigWriteParams: CodexSchema.V2SkillsConfigWriteParams, @@ -127,6 +142,8 @@ export const v2 = { ThreadCompactStartResponse: CodexSchema.V2ThreadCompactStartResponse, ThreadForkParams: CodexSchema.V2ThreadForkParams, ThreadForkResponse: CodexSchema.V2ThreadForkResponse, + ThreadInjectItemsParams: CodexSchema.V2ThreadInjectItemsParams, + ThreadInjectItemsResponse: CodexSchema.V2ThreadInjectItemsResponse, ThreadListParams: CodexSchema.V2ThreadListParams, ThreadListResponse: CodexSchema.V2ThreadListResponse, ThreadLoadedListParams: CodexSchema.V2ThreadLoadedListParams, @@ -143,8 +160,9 @@ export const v2 = { CodexSchema.V2ThreadRealtimeOutputAudioDeltaNotification, ThreadRealtimeSdpNotification: CodexSchema.V2ThreadRealtimeSdpNotification, ThreadRealtimeStartedNotification: CodexSchema.V2ThreadRealtimeStartedNotification, - ThreadRealtimeTranscriptUpdatedNotification: - CodexSchema.V2ThreadRealtimeTranscriptUpdatedNotification, + ThreadRealtimeTranscriptDeltaNotification: + CodexSchema.V2ThreadRealtimeTranscriptDeltaNotification, + ThreadRealtimeTranscriptDoneNotification: CodexSchema.V2ThreadRealtimeTranscriptDoneNotification, ThreadResumeParams: CodexSchema.V2ThreadResumeParams, ThreadResumeResponse: CodexSchema.V2ThreadResumeResponse, ThreadRollbackParams: CodexSchema.V2ThreadRollbackParams, @@ -158,6 +176,8 @@ export const v2 = { ThreadStartResponse: CodexSchema.V2ThreadStartResponse, ThreadStatusChangedNotification: CodexSchema.V2ThreadStatusChangedNotification, ThreadTokenUsageUpdatedNotification: CodexSchema.V2ThreadTokenUsageUpdatedNotification, + ThreadTurnsListParams: CodexSchema.V2ThreadTurnsListParams, + ThreadTurnsListResponse: CodexSchema.V2ThreadTurnsListResponse, ThreadUnarchivedNotification: CodexSchema.V2ThreadUnarchivedNotification, ThreadUnarchiveParams: CodexSchema.V2ThreadUnarchiveParams, ThreadUnarchiveResponse: CodexSchema.V2ThreadUnarchiveResponse, @@ -173,6 +193,7 @@ export const v2 = { TurnStartResponse: CodexSchema.V2TurnStartResponse, TurnSteerParams: CodexSchema.V2TurnSteerParams, TurnSteerResponse: CodexSchema.V2TurnSteerResponse, + WarningNotification: CodexSchema.V2WarningNotification, WindowsSandboxSetupCompletedNotification: CodexSchema.V2WindowsSandboxSetupCompletedNotification, WindowsSandboxSetupStartParams: CodexSchema.V2WindowsSandboxSetupStartParams, WindowsSandboxSetupStartResponse: CodexSchema.V2WindowsSandboxSetupStartResponse, diff --git a/packages/effect-codex-app-server/src/_generated/schema.gen.ts b/packages/effect-codex-app-server/src/_generated/schema.gen.ts index 5f2119a19b..3af37c0785 100644 --- a/packages/effect-codex-app-server/src/_generated/schema.gen.ts +++ b/packages/effect-codex-app-server/src/_generated/schema.gen.ts @@ -1,5 +1,5 @@ // This file is generated by the effect-codex-app-server package. Do not edit manually. -// Upstream protocol ref: dbfe855f4fd0f5dcdf079882652a8efe622b0595 +// Upstream protocol ref: be75785504ff152fa6333e380a2d50642f42fba0 import * as Schema from "effect/Schema"; @@ -45,6 +45,9 @@ export const ClientRequest__AbsolutePathBuf = Schema.String.annotate({ "A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\n\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.", }); +export type ClientRequest__AddCreditsNudgeCreditType = "credits" | "usage_limit"; +export const ClientRequest__AddCreditsNudgeCreditType = Schema.Literals(["credits", "usage_limit"]); + export type ClientRequest__ApprovalsReviewer = "user" | "guardian_subagent"; export const ClientRequest__ApprovalsReviewer = Schema.Literals([ "user", @@ -234,27 +237,20 @@ export const ClientRequest__ConfigReadParams = Schema.Struct({ includeLayers: Schema.optionalKey(Schema.Boolean.annotate({ default: false })), }); -export type ClientRequest__ContentItem = - | { readonly text: string; readonly type: "input_text" } - | { readonly image_url: string; readonly type: "input_image" } - | { readonly text: string; readonly type: "output_text" }; -export const ClientRequest__ContentItem = Schema.Union( - [ - Schema.Struct({ - text: Schema.String, - type: Schema.Literal("input_text").annotate({ title: "InputTextContentItemType" }), - }).annotate({ title: "InputTextContentItem" }), - Schema.Struct({ - image_url: Schema.String, - type: Schema.Literal("input_image").annotate({ title: "InputImageContentItemType" }), - }).annotate({ title: "InputImageContentItem" }), - Schema.Struct({ - text: Schema.String, - type: Schema.Literal("output_text").annotate({ title: "OutputTextContentItemType" }), - }).annotate({ title: "OutputTextContentItem" }), - ], - { mode: "oneOf" }, -); +export type ClientRequest__DeviceKeyProtectionPolicy = + | "hardware_only" + | "allow_os_protected_nonextractable"; +export const ClientRequest__DeviceKeyProtectionPolicy = Schema.Literals([ + "hardware_only", + "allow_os_protected_nonextractable", +]).annotate({ + description: "Protection policy for creating or loading a controller-local device key.", +}); + +export type ClientRequest__DeviceKeyPublicParams = { readonly keyId: string }; +export const ClientRequest__DeviceKeyPublicParams = Schema.Struct({ + keyId: Schema.String, +}).annotate({ description: "Fetch a controller-local device key public key by id." }); export type ClientRequest__ExperimentalFeatureEnablementSetParams = { readonly enablement: { readonly [x: string]: boolean }; @@ -316,11 +312,13 @@ export type ClientRequest__ExternalAgentConfigMigrationItemType = | "AGENTS_MD" | "CONFIG" | "SKILLS" + | "PLUGINS" | "MCP_SERVER_CONFIG"; export const ClientRequest__ExternalAgentConfigMigrationItemType = Schema.Literals([ "AGENTS_MD", "CONFIG", "SKILLS", + "PLUGINS", "MCP_SERVER_CONFIG", ]); @@ -329,6 +327,7 @@ export type ClientRequest__FeedbackUploadParams = { readonly extraLogFiles?: ReadonlyArray | null; readonly includeLogs: boolean; readonly reason?: string | null; + readonly tags?: { readonly [x: string]: string } | null; readonly threadId?: string | null; }; export const ClientRequest__FeedbackUploadParams = Schema.Struct({ @@ -336,6 +335,9 @@ export const ClientRequest__FeedbackUploadParams = Schema.Struct({ extraLogFiles: Schema.optionalKey(Schema.Union([Schema.Array(Schema.String), Schema.Null])), includeLogs: Schema.Boolean, reason: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + tags: Schema.optionalKey( + Schema.Union([Schema.Record(Schema.String, Schema.String), Schema.Null]), + ), threadId: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), }); @@ -612,14 +614,30 @@ export const ClientRequest__LoginAccountParams = Schema.Union( { mode: "oneOf" }, ); +export type ClientRequest__MarketplaceAddParams = { + readonly refName?: string | null; + readonly source: string; + readonly sparsePaths?: ReadonlyArray | null; +}; +export const ClientRequest__MarketplaceAddParams = Schema.Struct({ + refName: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + source: Schema.String, + sparsePaths: Schema.optionalKey(Schema.Union([Schema.Array(Schema.String), Schema.Null])), +}); + +export type ClientRequest__MarketplaceRemoveParams = { readonly marketplaceName: string }; +export const ClientRequest__MarketplaceRemoveParams = Schema.Struct({ + marketplaceName: Schema.String, +}); + export type ClientRequest__McpResourceReadParams = { readonly server: string; - readonly threadId: string; + readonly threadId?: string | null; readonly uri: string; }; export const ClientRequest__McpResourceReadParams = Schema.Struct({ server: Schema.String, - threadId: Schema.String, + threadId: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), uri: Schema.String, }); @@ -708,17 +726,16 @@ export const ClientRequest__ModelListParams = Schema.Struct({ export type ClientRequest__Personality = "none" | "friendly" | "pragmatic"; export const ClientRequest__Personality = Schema.Literals(["none", "friendly", "pragmatic"]); -export type ClientRequest__PluginUninstallParams = { - readonly forceRemoteSync?: boolean; - readonly pluginId: string; +export type ClientRequest__PluginUninstallParams = { readonly pluginId: string }; +export const ClientRequest__PluginUninstallParams = Schema.Struct({ pluginId: Schema.String }); + +export type ClientRequest__PluginsMigration = { + readonly marketplaceName: string; + readonly pluginNames: ReadonlyArray; }; -export const ClientRequest__PluginUninstallParams = Schema.Struct({ - forceRemoteSync: Schema.optionalKey( - Schema.Boolean.annotate({ - description: "When true, apply the remote plugin change before the local uninstall flow.", - }), - ), - pluginId: Schema.String, +export const ClientRequest__PluginsMigration = Schema.Struct({ + marketplaceName: Schema.String, + pluginNames: Schema.Array(Schema.String), }); export type ClientRequest__ReasoningEffort = @@ -787,6 +804,18 @@ export const ClientRequest__ReasoningSummary = Schema.Union( "A summary of the reasoning performed by the model. This can be useful for debugging and understanding the model's reasoning process. See https://platform.openai.com/docs/guides/reasoning?api-mode=responses#reasoning-summaries", }); +export type ClientRequest__RemoteControlClientConnectionAudience = + "remote_control_client_websocket"; +export const ClientRequest__RemoteControlClientConnectionAudience = Schema.Literal( + "remote_control_client_websocket", +).annotate({ description: "Audience for a remote-control client connection device-key proof." }); + +export type ClientRequest__RemoteControlClientEnrollmentAudience = + "remote_control_client_enrollment"; +export const ClientRequest__RemoteControlClientEnrollmentAudience = Schema.Literal( + "remote_control_client_enrollment", +).annotate({ description: "Audience for a remote-control client enrollment device-key proof." }); + export type ClientRequest__RequestId = string | number; export const ClientRequest__RequestId = Schema.Union([ Schema.String, @@ -903,6 +932,9 @@ export const ClientRequest__SkillsListExtraRootsForCwd = Schema.Struct({ extraUserRoots: Schema.Array(Schema.String), }); +export type ClientRequest__SortDirection = "asc" | "desc"; +export const ClientRequest__SortDirection = Schema.Literals(["asc", "desc"]); + export type ClientRequest__TextElement = { readonly byteRange: { readonly end: number; readonly start: number }; readonly placeholder?: string | null; @@ -934,6 +966,17 @@ export const ClientRequest__ThreadArchiveParams = Schema.Struct({ threadId: Sche export type ClientRequest__ThreadCompactStartParams = { readonly threadId: string }; export const ClientRequest__ThreadCompactStartParams = Schema.Struct({ threadId: Schema.String }); +export type ClientRequest__ThreadInjectItemsParams = { + readonly items: ReadonlyArray; + readonly threadId: string; +}; +export const ClientRequest__ThreadInjectItemsParams = Schema.Struct({ + items: Schema.Array(Schema.Unknown).annotate({ + description: "Raw Responses API items to append to the thread's model-visible history.", + }), + threadId: Schema.String, +}); + export type ClientRequest__ThreadLoadedListParams = { readonly cursor?: string | null; readonly limit?: number | null; @@ -1106,44 +1149,47 @@ export const CommandExecutionRequestApprovalParams__AdditionalNetworkPermissions enabled: Schema.optionalKey(Schema.Union([Schema.Boolean, Schema.Null])), }); -export type CommandExecutionRequestApprovalParams__CommandAction = - | { - readonly command: string; - readonly name: string; - readonly path: string; - readonly type: "read"; - } - | { readonly command: string; readonly path?: string | null; readonly type: "listFiles" } - | { - readonly command: string; - readonly path?: string | null; - readonly query?: string | null; - readonly type: "search"; - } - | { readonly command: string; readonly type: "unknown" }; -export const CommandExecutionRequestApprovalParams__CommandAction = Schema.Union( +export type CommandExecutionRequestApprovalParams__FileSystemAccessMode = "read" | "write" | "none"; +export const CommandExecutionRequestApprovalParams__FileSystemAccessMode = Schema.Literals([ + "read", + "write", + "none", +]); + +export type CommandExecutionRequestApprovalParams__FileSystemSpecialPath = + | { readonly kind: "root" } + | { readonly kind: "minimal" } + | { readonly kind: "current_working_directory" } + | { readonly kind: "project_roots"; readonly subpath?: string | null } + | { readonly kind: "tmpdir" } + | { readonly kind: "slash_tmp" } + | { readonly kind: "unknown"; readonly path: string; readonly subpath?: string | null }; +export const CommandExecutionRequestApprovalParams__FileSystemSpecialPath = Schema.Union( [ + Schema.Struct({ kind: Schema.Literal("root") }).annotate({ + title: "RootFileSystemSpecialPath", + }), + Schema.Struct({ kind: Schema.Literal("minimal") }).annotate({ + title: "MinimalFileSystemSpecialPath", + }), + Schema.Struct({ kind: Schema.Literal("current_working_directory") }).annotate({ + title: "CurrentWorkingDirectoryFileSystemSpecialPath", + }), Schema.Struct({ - command: Schema.String, - name: Schema.String, + kind: Schema.Literal("project_roots"), + subpath: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + }).annotate({ title: "KindFileSystemSpecialPath" }), + Schema.Struct({ kind: Schema.Literal("tmpdir") }).annotate({ + title: "TmpdirFileSystemSpecialPath", + }), + Schema.Struct({ kind: Schema.Literal("slash_tmp") }).annotate({ + title: "SlashTmpFileSystemSpecialPath", + }), + Schema.Struct({ + kind: Schema.Literal("unknown"), path: Schema.String, - type: Schema.Literal("read").annotate({ title: "ReadCommandActionType" }), - }).annotate({ title: "ReadCommandAction" }), - Schema.Struct({ - command: Schema.String, - path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), - type: Schema.Literal("listFiles").annotate({ title: "ListFilesCommandActionType" }), - }).annotate({ title: "ListFilesCommandAction" }), - Schema.Struct({ - command: Schema.String, - path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), - query: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), - type: Schema.Literal("search").annotate({ title: "SearchCommandActionType" }), - }).annotate({ title: "SearchCommandAction" }), - Schema.Struct({ - command: Schema.String, - type: Schema.Literal("unknown").annotate({ title: "UnknownCommandActionType" }), - }).annotate({ title: "UnknownCommandAction" }), + subpath: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + }), ], { mode: "oneOf" }, ); @@ -1404,6 +1450,51 @@ export const PermissionsRequestApprovalParams__AdditionalNetworkPermissions = Sc enabled: Schema.optionalKey(Schema.Union([Schema.Boolean, Schema.Null])), }); +export type PermissionsRequestApprovalParams__FileSystemAccessMode = "read" | "write" | "none"; +export const PermissionsRequestApprovalParams__FileSystemAccessMode = Schema.Literals([ + "read", + "write", + "none", +]); + +export type PermissionsRequestApprovalParams__FileSystemSpecialPath = + | { readonly kind: "root" } + | { readonly kind: "minimal" } + | { readonly kind: "current_working_directory" } + | { readonly kind: "project_roots"; readonly subpath?: string | null } + | { readonly kind: "tmpdir" } + | { readonly kind: "slash_tmp" } + | { readonly kind: "unknown"; readonly path: string; readonly subpath?: string | null }; +export const PermissionsRequestApprovalParams__FileSystemSpecialPath = Schema.Union( + [ + Schema.Struct({ kind: Schema.Literal("root") }).annotate({ + title: "RootFileSystemSpecialPath", + }), + Schema.Struct({ kind: Schema.Literal("minimal") }).annotate({ + title: "MinimalFileSystemSpecialPath", + }), + Schema.Struct({ kind: Schema.Literal("current_working_directory") }).annotate({ + title: "CurrentWorkingDirectoryFileSystemSpecialPath", + }), + Schema.Struct({ + kind: Schema.Literal("project_roots"), + subpath: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + }).annotate({ title: "KindFileSystemSpecialPath" }), + Schema.Struct({ kind: Schema.Literal("tmpdir") }).annotate({ + title: "TmpdirFileSystemSpecialPath", + }), + Schema.Struct({ kind: Schema.Literal("slash_tmp") }).annotate({ + title: "SlashTmpFileSystemSpecialPath", + }), + Schema.Struct({ + kind: Schema.Literal("unknown"), + path: Schema.String, + subpath: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + }), + ], + { mode: "oneOf" }, +); + export type PermissionsRequestApprovalResponse__AbsolutePathBuf = string; export const PermissionsRequestApprovalResponse__AbsolutePathBuf = Schema.String.annotate({ description: @@ -1417,6 +1508,51 @@ export const PermissionsRequestApprovalResponse__AdditionalNetworkPermissions = enabled: Schema.optionalKey(Schema.Union([Schema.Boolean, Schema.Null])), }); +export type PermissionsRequestApprovalResponse__FileSystemAccessMode = "read" | "write" | "none"; +export const PermissionsRequestApprovalResponse__FileSystemAccessMode = Schema.Literals([ + "read", + "write", + "none", +]); + +export type PermissionsRequestApprovalResponse__FileSystemSpecialPath = + | { readonly kind: "root" } + | { readonly kind: "minimal" } + | { readonly kind: "current_working_directory" } + | { readonly kind: "project_roots"; readonly subpath?: string | null } + | { readonly kind: "tmpdir" } + | { readonly kind: "slash_tmp" } + | { readonly kind: "unknown"; readonly path: string; readonly subpath?: string | null }; +export const PermissionsRequestApprovalResponse__FileSystemSpecialPath = Schema.Union( + [ + Schema.Struct({ kind: Schema.Literal("root") }).annotate({ + title: "RootFileSystemSpecialPath", + }), + Schema.Struct({ kind: Schema.Literal("minimal") }).annotate({ + title: "MinimalFileSystemSpecialPath", + }), + Schema.Struct({ kind: Schema.Literal("current_working_directory") }).annotate({ + title: "CurrentWorkingDirectoryFileSystemSpecialPath", + }), + Schema.Struct({ + kind: Schema.Literal("project_roots"), + subpath: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + }).annotate({ title: "KindFileSystemSpecialPath" }), + Schema.Struct({ kind: Schema.Literal("tmpdir") }).annotate({ + title: "TmpdirFileSystemSpecialPath", + }), + Schema.Struct({ kind: Schema.Literal("slash_tmp") }).annotate({ + title: "SlashTmpFileSystemSpecialPath", + }), + Schema.Struct({ + kind: Schema.Literal("unknown"), + path: Schema.String, + subpath: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + }), + ], + { mode: "oneOf" }, +); + export type ServerNotification__AbsolutePathBuf = string; export const ServerNotification__AbsolutePathBuf = Schema.String.annotate({ description: @@ -1434,6 +1570,13 @@ export const ServerNotification__AccountLoginCompletedNotification = Schema.Stru success: Schema.Boolean, }); +export type ServerNotification__AdditionalNetworkPermissions = { + readonly enabled?: boolean | null; +}; +export const ServerNotification__AdditionalNetworkPermissions = Schema.Struct({ + enabled: Schema.optionalKey(Schema.Union([Schema.Boolean, Schema.Null])), +}); + export type ServerNotification__AgentMessageDeltaNotification = { readonly delta: string; readonly itemId: string; @@ -1490,7 +1633,7 @@ export const ServerNotification__AuthMode = Schema.Literals([ export type ServerNotification__AutoReviewDecisionSource = "agent"; export const ServerNotification__AutoReviewDecisionSource = Schema.Literal("agent").annotate({ - description: "[UNSTABLE] Source that produced a terminal guardian approval review decision.", + description: "[UNSTABLE] Source that produced a terminal approval auto-review decision.", }); export type ServerNotification__CollabAgentStatus = @@ -1511,48 +1654,6 @@ export const ServerNotification__CollabAgentStatus = Schema.Literals([ "notFound", ]); -export type ServerNotification__CommandAction = - | { - readonly command: string; - readonly name: string; - readonly path: string; - readonly type: "read"; - } - | { readonly command: string; readonly path?: string | null; readonly type: "listFiles" } - | { - readonly command: string; - readonly path?: string | null; - readonly query?: string | null; - readonly type: "search"; - } - | { readonly command: string; readonly type: "unknown" }; -export const ServerNotification__CommandAction = Schema.Union( - [ - Schema.Struct({ - command: Schema.String, - name: Schema.String, - path: Schema.String, - type: Schema.Literal("read").annotate({ title: "ReadCommandActionType" }), - }).annotate({ title: "ReadCommandAction" }), - Schema.Struct({ - command: Schema.String, - path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), - type: Schema.Literal("listFiles").annotate({ title: "ListFilesCommandActionType" }), - }).annotate({ title: "ListFilesCommandAction" }), - Schema.Struct({ - command: Schema.String, - path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), - query: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), - type: Schema.Literal("search").annotate({ title: "SearchCommandActionType" }), - }).annotate({ title: "SearchCommandAction" }), - Schema.Struct({ - command: Schema.String, - type: Schema.Literal("unknown").annotate({ title: "UnknownCommandActionType" }), - }).annotate({ title: "UnknownCommandAction" }), - ], - { mode: "oneOf" }, -); - export type ServerNotification__CommandExecOutputDeltaNotification = { readonly capReached: boolean; readonly deltaBase64: string; @@ -1666,6 +1767,9 @@ export const ServerNotification__DynamicToolCallStatus = Schema.Literals([ "failed", ]); +export type ServerNotification__ExternalAgentConfigImportCompletedNotification = {}; +export const ServerNotification__ExternalAgentConfigImportCompletedNotification = Schema.Struct({}); + export type ServerNotification__FileChangeOutputDeltaNotification = { readonly delta: string; readonly itemId: string; @@ -1679,6 +1783,47 @@ export const ServerNotification__FileChangeOutputDeltaNotification = Schema.Stru turnId: Schema.String, }); +export type ServerNotification__FileSystemAccessMode = "read" | "write" | "none"; +export const ServerNotification__FileSystemAccessMode = Schema.Literals(["read", "write", "none"]); + +export type ServerNotification__FileSystemSpecialPath = + | { readonly kind: "root" } + | { readonly kind: "minimal" } + | { readonly kind: "current_working_directory" } + | { readonly kind: "project_roots"; readonly subpath?: string | null } + | { readonly kind: "tmpdir" } + | { readonly kind: "slash_tmp" } + | { readonly kind: "unknown"; readonly path: string; readonly subpath?: string | null }; +export const ServerNotification__FileSystemSpecialPath = Schema.Union( + [ + Schema.Struct({ kind: Schema.Literal("root") }).annotate({ + title: "RootFileSystemSpecialPath", + }), + Schema.Struct({ kind: Schema.Literal("minimal") }).annotate({ + title: "MinimalFileSystemSpecialPath", + }), + Schema.Struct({ kind: Schema.Literal("current_working_directory") }).annotate({ + title: "CurrentWorkingDirectoryFileSystemSpecialPath", + }), + Schema.Struct({ + kind: Schema.Literal("project_roots"), + subpath: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + }).annotate({ title: "KindFileSystemSpecialPath" }), + Schema.Struct({ kind: Schema.Literal("tmpdir") }).annotate({ + title: "TmpdirFileSystemSpecialPath", + }), + Schema.Struct({ kind: Schema.Literal("slash_tmp") }).annotate({ + title: "SlashTmpFileSystemSpecialPath", + }), + Schema.Struct({ + kind: Schema.Literal("unknown"), + path: Schema.String, + subpath: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + }), + ], + { mode: "oneOf" }, +); + export type ServerNotification__FuzzyFileSearchMatchType = "file" | "directory"; export const ServerNotification__FuzzyFileSearchMatchType = Schema.Literals(["file", "directory"]); @@ -1712,7 +1857,7 @@ export const ServerNotification__GuardianApprovalReviewStatus = Schema.Literals( "denied", "timedOut", "aborted", -]).annotate({ description: "[UNSTABLE] Lifecycle state for a guardian approval review." }); +]).annotate({ description: "[UNSTABLE] Lifecycle state for an approval auto-review." }); export type ServerNotification__GuardianCommandSource = "shell" | "unifiedExec"; export const ServerNotification__GuardianCommandSource = Schema.Literals(["shell", "unifiedExec"]); @@ -1723,7 +1868,7 @@ export const ServerNotification__GuardianRiskLevel = Schema.Literals([ "medium", "high", "critical", -]).annotate({ description: "[UNSTABLE] Risk level assigned by guardian approval review." }); +]).annotate({ description: "[UNSTABLE] Risk level assigned by approval auto-review." }); export type ServerNotification__GuardianUserAuthorization = "unknown" | "low" | "medium" | "high"; export const ServerNotification__GuardianUserAuthorization = Schema.Literals([ @@ -1731,18 +1876,18 @@ export const ServerNotification__GuardianUserAuthorization = Schema.Literals([ "low", "medium", "high", -]).annotate({ - description: "[UNSTABLE] Authorization level assigned by guardian approval review.", -}); +]).annotate({ description: "[UNSTABLE] Authorization level assigned by approval auto-review." }); export type ServerNotification__HookEventName = | "preToolUse" + | "permissionRequest" | "postToolUse" | "sessionStart" | "userPromptSubmit" | "stop"; export const ServerNotification__HookEventName = Schema.Literals([ "preToolUse", + "permissionRequest", "postToolUse", "sessionStart", "userPromptSubmit", @@ -1949,6 +2094,7 @@ export type ServerNotification__PlanType = | "go" | "plus" | "pro" + | "prolite" | "team" | "self_serve_business_usage_based" | "business" @@ -1961,6 +2107,7 @@ export const ServerNotification__PlanType = Schema.Literals([ "go", "plus", "pro", + "prolite", "team", "self_serve_business_usage_based", "business", @@ -1970,6 +2117,20 @@ export const ServerNotification__PlanType = Schema.Literals([ "unknown", ]); +export type ServerNotification__RateLimitReachedType = + | "rate_limit_reached" + | "workspace_owner_credits_depleted" + | "workspace_member_credits_depleted" + | "workspace_owner_usage_limit_reached" + | "workspace_member_usage_limit_reached"; +export const ServerNotification__RateLimitReachedType = Schema.Literals([ + "rate_limit_reached", + "workspace_owner_credits_depleted", + "workspace_member_credits_depleted", + "workspace_owner_usage_limit_reached", + "workspace_member_usage_limit_reached", +]); + export type ServerNotification__RateLimitWindow = { readonly resetsAt?: number | null; readonly usedPercent: number; @@ -2209,20 +2370,34 @@ export const ServerNotification__ThreadRealtimeSdpNotification = Schema.Struct({ description: "EXPERIMENTAL - emitted with the remote SDP for a WebRTC realtime session.", }); -export type ServerNotification__ThreadRealtimeTranscriptUpdatedNotification = { +export type ServerNotification__ThreadRealtimeTranscriptDeltaNotification = { + readonly delta: string; readonly role: string; - readonly text: string; readonly threadId: string; }; -export const ServerNotification__ThreadRealtimeTranscriptUpdatedNotification = Schema.Struct({ +export const ServerNotification__ThreadRealtimeTranscriptDeltaNotification = Schema.Struct({ + delta: Schema.String.annotate({ description: "Live transcript delta from the realtime event." }), role: Schema.String, - text: Schema.String, threadId: Schema.String, }).annotate({ description: "EXPERIMENTAL - flat transcript delta emitted whenever realtime transcript text changes.", }); +export type ServerNotification__ThreadRealtimeTranscriptDoneNotification = { + readonly role: string; + readonly text: string; + readonly threadId: string; +}; +export const ServerNotification__ThreadRealtimeTranscriptDoneNotification = Schema.Struct({ + role: Schema.String, + text: Schema.String.annotate({ description: "Final complete text for the transcript part." }), + threadId: Schema.String, +}).annotate({ + description: + "EXPERIMENTAL - final transcript text emitted when realtime completes a transcript part.", +}); + export type ServerNotification__ThreadUnarchivedNotification = { readonly threadId: string }; export const ServerNotification__ThreadUnarchivedNotification = Schema.Struct({ threadId: Schema.String, @@ -2272,6 +2447,22 @@ export const ServerNotification__TurnStatus = Schema.Literals([ "inProgress", ]); +export type ServerNotification__WarningNotification = { + readonly message: string; + readonly threadId?: string | null; +}; +export const ServerNotification__WarningNotification = Schema.Struct({ + message: Schema.String.annotate({ description: "Concise warning message for the user." }), + threadId: Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + description: "Optional thread target when the warning applies to a specific thread.", + }), + Schema.Null, + ]), + ), +}); + export type ServerNotification__WebSearchAction = | { readonly queries?: ReadonlyArray | null; @@ -2337,51 +2528,10 @@ export const ServerRequest__AdditionalNetworkPermissions = Schema.Struct({ export type ServerRequest__ChatgptAuthTokensRefreshReason = "unauthorized"; export const ServerRequest__ChatgptAuthTokensRefreshReason = Schema.Literal("unauthorized"); -export type ServerRequest__CommandAction = - | { - readonly command: string; - readonly name: string; - readonly path: string; - readonly type: "read"; - } - | { readonly command: string; readonly path?: string | null; readonly type: "listFiles" } - | { - readonly command: string; - readonly path?: string | null; - readonly query?: string | null; - readonly type: "search"; - } - | { readonly command: string; readonly type: "unknown" }; -export const ServerRequest__CommandAction = Schema.Union( - [ - Schema.Struct({ - command: Schema.String, - name: Schema.String, - path: Schema.String, - type: Schema.Literal("read").annotate({ title: "ReadCommandActionType" }), - }).annotate({ title: "ReadCommandAction" }), - Schema.Struct({ - command: Schema.String, - path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), - type: Schema.Literal("listFiles").annotate({ title: "ListFilesCommandActionType" }), - }).annotate({ title: "ListFilesCommandAction" }), - Schema.Struct({ - command: Schema.String, - path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), - query: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), - type: Schema.Literal("search").annotate({ title: "SearchCommandActionType" }), - }).annotate({ title: "SearchCommandAction" }), - Schema.Struct({ - command: Schema.String, - type: Schema.Literal("unknown").annotate({ title: "UnknownCommandActionType" }), - }).annotate({ title: "UnknownCommandAction" }), - ], - { mode: "oneOf" }, -); - export type ServerRequest__DynamicToolCallParams = { readonly arguments: unknown; readonly callId: string; + readonly namespace?: string | null; readonly threadId: string; readonly tool: string; readonly turnId: string; @@ -2389,6 +2539,7 @@ export type ServerRequest__DynamicToolCallParams = { export const ServerRequest__DynamicToolCallParams = Schema.Struct({ arguments: Schema.Unknown, callId: Schema.String, + namespace: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), threadId: Schema.String, tool: Schema.String, turnId: Schema.String, @@ -2447,6 +2598,47 @@ export const ServerRequest__FileChangeRequestApprovalParams = Schema.Struct({ turnId: Schema.String, }); +export type ServerRequest__FileSystemAccessMode = "read" | "write" | "none"; +export const ServerRequest__FileSystemAccessMode = Schema.Literals(["read", "write", "none"]); + +export type ServerRequest__FileSystemSpecialPath = + | { readonly kind: "root" } + | { readonly kind: "minimal" } + | { readonly kind: "current_working_directory" } + | { readonly kind: "project_roots"; readonly subpath?: string | null } + | { readonly kind: "tmpdir" } + | { readonly kind: "slash_tmp" } + | { readonly kind: "unknown"; readonly path: string; readonly subpath?: string | null }; +export const ServerRequest__FileSystemSpecialPath = Schema.Union( + [ + Schema.Struct({ kind: Schema.Literal("root") }).annotate({ + title: "RootFileSystemSpecialPath", + }), + Schema.Struct({ kind: Schema.Literal("minimal") }).annotate({ + title: "MinimalFileSystemSpecialPath", + }), + Schema.Struct({ kind: Schema.Literal("current_working_directory") }).annotate({ + title: "CurrentWorkingDirectoryFileSystemSpecialPath", + }), + Schema.Struct({ + kind: Schema.Literal("project_roots"), + subpath: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + }).annotate({ title: "KindFileSystemSpecialPath" }), + Schema.Struct({ kind: Schema.Literal("tmpdir") }).annotate({ + title: "TmpdirFileSystemSpecialPath", + }), + Schema.Struct({ kind: Schema.Literal("slash_tmp") }).annotate({ + title: "SlashTmpFileSystemSpecialPath", + }), + Schema.Struct({ + kind: Schema.Literal("unknown"), + path: Schema.String, + subpath: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + }), + ], + { mode: "oneOf" }, +); + export type ServerRequest__McpElicitationArrayType = "array"; export const ServerRequest__McpElicitationArrayType = Schema.Literal("array"); @@ -2619,6 +2811,7 @@ export type V2AccountRateLimitsUpdatedNotification__PlanType = | "go" | "plus" | "pro" + | "prolite" | "team" | "self_serve_business_usage_based" | "business" @@ -2631,6 +2824,7 @@ export const V2AccountRateLimitsUpdatedNotification__PlanType = Schema.Literals( "go", "plus", "pro", + "prolite", "team", "self_serve_business_usage_based", "business", @@ -2640,6 +2834,20 @@ export const V2AccountRateLimitsUpdatedNotification__PlanType = Schema.Literals( "unknown", ]); +export type V2AccountRateLimitsUpdatedNotification__RateLimitReachedType = + | "rate_limit_reached" + | "workspace_owner_credits_depleted" + | "workspace_member_credits_depleted" + | "workspace_owner_usage_limit_reached" + | "workspace_member_usage_limit_reached"; +export const V2AccountRateLimitsUpdatedNotification__RateLimitReachedType = Schema.Literals([ + "rate_limit_reached", + "workspace_owner_credits_depleted", + "workspace_member_credits_depleted", + "workspace_owner_usage_limit_reached", + "workspace_member_usage_limit_reached", +]); + export type V2AccountRateLimitsUpdatedNotification__RateLimitWindow = { readonly resetsAt?: number | null; readonly usedPercent: number; @@ -2667,6 +2875,7 @@ export type V2AccountUpdatedNotification__PlanType = | "go" | "plus" | "pro" + | "prolite" | "team" | "self_serve_business_usage_based" | "business" @@ -2679,6 +2888,7 @@ export const V2AccountUpdatedNotification__PlanType = Schema.Literals([ "go", "plus", "pro", + "prolite", "team", "self_serve_business_usage_based", "business", @@ -3034,6 +3244,63 @@ export const V2ConfigWriteResponse__AbsolutePathBuf = Schema.String.annotate({ export type V2ConfigWriteResponse__WriteStatus = "ok" | "okOverridden"; export const V2ConfigWriteResponse__WriteStatus = Schema.Literals(["ok", "okOverridden"]); +export type V2DeviceKeyCreateParams__DeviceKeyProtectionPolicy = + | "hardware_only" + | "allow_os_protected_nonextractable"; +export const V2DeviceKeyCreateParams__DeviceKeyProtectionPolicy = Schema.Literals([ + "hardware_only", + "allow_os_protected_nonextractable", +]).annotate({ + description: "Protection policy for creating or loading a controller-local device key.", +}); + +export type V2DeviceKeyCreateResponse__DeviceKeyAlgorithm = "ecdsa_p256_sha256"; +export const V2DeviceKeyCreateResponse__DeviceKeyAlgorithm = Schema.Literal( + "ecdsa_p256_sha256", +).annotate({ description: "Device-key algorithm reported at enrollment and signing boundaries." }); + +export type V2DeviceKeyCreateResponse__DeviceKeyProtectionClass = + | "hardware_secure_enclave" + | "hardware_tpm" + | "os_protected_nonextractable"; +export const V2DeviceKeyCreateResponse__DeviceKeyProtectionClass = Schema.Literals([ + "hardware_secure_enclave", + "hardware_tpm", + "os_protected_nonextractable", +]).annotate({ description: "Platform protection class for a controller-local device key." }); + +export type V2DeviceKeyPublicResponse__DeviceKeyAlgorithm = "ecdsa_p256_sha256"; +export const V2DeviceKeyPublicResponse__DeviceKeyAlgorithm = Schema.Literal( + "ecdsa_p256_sha256", +).annotate({ description: "Device-key algorithm reported at enrollment and signing boundaries." }); + +export type V2DeviceKeyPublicResponse__DeviceKeyProtectionClass = + | "hardware_secure_enclave" + | "hardware_tpm" + | "os_protected_nonextractable"; +export const V2DeviceKeyPublicResponse__DeviceKeyProtectionClass = Schema.Literals([ + "hardware_secure_enclave", + "hardware_tpm", + "os_protected_nonextractable", +]).annotate({ description: "Platform protection class for a controller-local device key." }); + +export type V2DeviceKeySignParams__RemoteControlClientConnectionAudience = + "remote_control_client_websocket"; +export const V2DeviceKeySignParams__RemoteControlClientConnectionAudience = Schema.Literal( + "remote_control_client_websocket", +).annotate({ description: "Audience for a remote-control client connection device-key proof." }); + +export type V2DeviceKeySignParams__RemoteControlClientEnrollmentAudience = + "remote_control_client_enrollment"; +export const V2DeviceKeySignParams__RemoteControlClientEnrollmentAudience = Schema.Literal( + "remote_control_client_enrollment", +).annotate({ description: "Audience for a remote-control client enrollment device-key proof." }); + +export type V2DeviceKeySignResponse__DeviceKeyAlgorithm = "ecdsa_p256_sha256"; +export const V2DeviceKeySignResponse__DeviceKeyAlgorithm = Schema.Literal( + "ecdsa_p256_sha256", +).annotate({ description: "Device-key algorithm reported at enrollment and signing boundaries." }); + export type V2ErrorNotification__NonSteerableTurnKind = "review" | "compact"; export const V2ErrorNotification__NonSteerableTurnKind = Schema.Literals(["review", "compact"]); @@ -3092,17 +3359,57 @@ export type V2ExternalAgentConfigDetectResponse__ExternalAgentConfigMigrationIte | "AGENTS_MD" | "CONFIG" | "SKILLS" + | "PLUGINS" | "MCP_SERVER_CONFIG"; export const V2ExternalAgentConfigDetectResponse__ExternalAgentConfigMigrationItemType = - Schema.Literals(["AGENTS_MD", "CONFIG", "SKILLS", "MCP_SERVER_CONFIG"]); + Schema.Literals(["AGENTS_MD", "CONFIG", "SKILLS", "PLUGINS", "MCP_SERVER_CONFIG"]); + +export type V2ExternalAgentConfigDetectResponse__PluginsMigration = { + readonly marketplaceName: string; + readonly pluginNames: ReadonlyArray; +}; +export const V2ExternalAgentConfigDetectResponse__PluginsMigration = Schema.Struct({ + marketplaceName: Schema.String, + pluginNames: Schema.Array(Schema.String), +}); export type V2ExternalAgentConfigImportParams__ExternalAgentConfigMigrationItemType = | "AGENTS_MD" | "CONFIG" | "SKILLS" + | "PLUGINS" | "MCP_SERVER_CONFIG"; export const V2ExternalAgentConfigImportParams__ExternalAgentConfigMigrationItemType = - Schema.Literals(["AGENTS_MD", "CONFIG", "SKILLS", "MCP_SERVER_CONFIG"]); + Schema.Literals(["AGENTS_MD", "CONFIG", "SKILLS", "PLUGINS", "MCP_SERVER_CONFIG"]); + +export type V2ExternalAgentConfigImportParams__PluginsMigration = { + readonly marketplaceName: string; + readonly pluginNames: ReadonlyArray; +}; +export const V2ExternalAgentConfigImportParams__PluginsMigration = Schema.Struct({ + marketplaceName: Schema.String, + pluginNames: Schema.Array(Schema.String), +}); + +export type V2FileChangePatchUpdatedNotification__PatchChangeKind = + | { readonly type: "add" } + | { readonly type: "delete" } + | { readonly move_path?: string | null; readonly type: "update" }; +export const V2FileChangePatchUpdatedNotification__PatchChangeKind = Schema.Union( + [ + Schema.Struct({ + type: Schema.Literal("add").annotate({ title: "AddPatchChangeKindType" }), + }).annotate({ title: "AddPatchChangeKind" }), + Schema.Struct({ + type: Schema.Literal("delete").annotate({ title: "DeletePatchChangeKindType" }), + }).annotate({ title: "DeletePatchChangeKind" }), + Schema.Struct({ + move_path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + type: Schema.Literal("update").annotate({ title: "UpdatePatchChangeKindType" }), + }).annotate({ title: "UpdatePatchChangeKind" }), + ], + { mode: "oneOf" }, +); export type V2FsChangedNotification__AbsolutePathBuf = string; export const V2FsChangedNotification__AbsolutePathBuf = Schema.String.annotate({ @@ -3143,6 +3450,7 @@ export type V2GetAccountRateLimitsResponse__PlanType = | "go" | "plus" | "pro" + | "prolite" | "team" | "self_serve_business_usage_based" | "business" @@ -3155,6 +3463,7 @@ export const V2GetAccountRateLimitsResponse__PlanType = Schema.Literals([ "go", "plus", "pro", + "prolite", "team", "self_serve_business_usage_based", "business", @@ -3164,6 +3473,20 @@ export const V2GetAccountRateLimitsResponse__PlanType = Schema.Literals([ "unknown", ]); +export type V2GetAccountRateLimitsResponse__RateLimitReachedType = + | "rate_limit_reached" + | "workspace_owner_credits_depleted" + | "workspace_member_credits_depleted" + | "workspace_owner_usage_limit_reached" + | "workspace_member_usage_limit_reached"; +export const V2GetAccountRateLimitsResponse__RateLimitReachedType = Schema.Literals([ + "rate_limit_reached", + "workspace_owner_credits_depleted", + "workspace_member_credits_depleted", + "workspace_owner_usage_limit_reached", + "workspace_member_usage_limit_reached", +]); + export type V2GetAccountRateLimitsResponse__RateLimitWindow = { readonly resetsAt?: number | null; readonly usedPercent: number; @@ -3184,6 +3507,7 @@ export type V2GetAccountResponse__PlanType = | "go" | "plus" | "pro" + | "prolite" | "team" | "self_serve_business_usage_based" | "business" @@ -3196,6 +3520,7 @@ export const V2GetAccountResponse__PlanType = Schema.Literals([ "go", "plus", "pro", + "prolite", "team", "self_serve_business_usage_based", "business", @@ -3205,14 +3530,22 @@ export const V2GetAccountResponse__PlanType = Schema.Literals([ "unknown", ]); +export type V2HookCompletedNotification__AbsolutePathBuf = string; +export const V2HookCompletedNotification__AbsolutePathBuf = Schema.String.annotate({ + description: + "A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\n\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.", +}); + export type V2HookCompletedNotification__HookEventName = | "preToolUse" + | "permissionRequest" | "postToolUse" | "sessionStart" | "userPromptSubmit" | "stop"; export const V2HookCompletedNotification__HookEventName = Schema.Literals([ "preToolUse", + "permissionRequest", "postToolUse", "sessionStart", "userPromptSubmit", @@ -3260,14 +3593,22 @@ export const V2HookCompletedNotification__HookRunStatus = Schema.Literals([ export type V2HookCompletedNotification__HookScope = "thread" | "turn"; export const V2HookCompletedNotification__HookScope = Schema.Literals(["thread", "turn"]); +export type V2HookStartedNotification__AbsolutePathBuf = string; +export const V2HookStartedNotification__AbsolutePathBuf = Schema.String.annotate({ + description: + "A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\n\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.", +}); + export type V2HookStartedNotification__HookEventName = | "preToolUse" + | "permissionRequest" | "postToolUse" | "sessionStart" | "userPromptSubmit" | "stop"; export const V2HookStartedNotification__HookEventName = Schema.Literals([ "preToolUse", + "permissionRequest", "postToolUse", "sessionStart", "userPromptSubmit", @@ -3315,6 +3656,12 @@ export const V2HookStartedNotification__HookRunStatus = Schema.Literals([ export type V2HookStartedNotification__HookScope = "thread" | "turn"; export const V2HookStartedNotification__HookScope = Schema.Literals(["thread", "turn"]); +export type V2ItemCompletedNotification__AbsolutePathBuf = string; +export const V2ItemCompletedNotification__AbsolutePathBuf = Schema.String.annotate({ + description: + "A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\n\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.", +}); + export type V2ItemCompletedNotification__CollabAgentStatus = | "pendingInit" | "running" @@ -3333,48 +3680,6 @@ export const V2ItemCompletedNotification__CollabAgentStatus = Schema.Literals([ "notFound", ]); -export type V2ItemCompletedNotification__CommandAction = - | { - readonly command: string; - readonly name: string; - readonly path: string; - readonly type: "read"; - } - | { readonly command: string; readonly path?: string | null; readonly type: "listFiles" } - | { - readonly command: string; - readonly path?: string | null; - readonly query?: string | null; - readonly type: "search"; - } - | { readonly command: string; readonly type: "unknown" }; -export const V2ItemCompletedNotification__CommandAction = Schema.Union( - [ - Schema.Struct({ - command: Schema.String, - name: Schema.String, - path: Schema.String, - type: Schema.Literal("read").annotate({ title: "ReadCommandActionType" }), - }).annotate({ title: "ReadCommandAction" }), - Schema.Struct({ - command: Schema.String, - path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), - type: Schema.Literal("listFiles").annotate({ title: "ListFilesCommandActionType" }), - }).annotate({ title: "ListFilesCommandAction" }), - Schema.Struct({ - command: Schema.String, - path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), - query: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), - type: Schema.Literal("search").annotate({ title: "SearchCommandActionType" }), - }).annotate({ title: "SearchCommandAction" }), - Schema.Struct({ - command: Schema.String, - type: Schema.Literal("unknown").annotate({ title: "UnknownCommandActionType" }), - }).annotate({ title: "UnknownCommandAction" }), - ], - { mode: "oneOf" }, -); - export type V2ItemCompletedNotification__CommandExecutionStatus = | "inProgress" | "completed" @@ -3584,12 +3889,71 @@ export const V2ItemCompletedNotification__WebSearchAction = Schema.Union( { mode: "oneOf" }, ); +export type V2ItemGuardianApprovalReviewCompletedNotification__AbsolutePathBuf = string; +export const V2ItemGuardianApprovalReviewCompletedNotification__AbsolutePathBuf = + Schema.String.annotate({ + description: + "A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\n\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.", + }); + +export type V2ItemGuardianApprovalReviewCompletedNotification__AdditionalNetworkPermissions = { + readonly enabled?: boolean | null; +}; +export const V2ItemGuardianApprovalReviewCompletedNotification__AdditionalNetworkPermissions = + Schema.Struct({ enabled: Schema.optionalKey(Schema.Union([Schema.Boolean, Schema.Null])) }); + export type V2ItemGuardianApprovalReviewCompletedNotification__AutoReviewDecisionSource = "agent"; export const V2ItemGuardianApprovalReviewCompletedNotification__AutoReviewDecisionSource = Schema.Literal("agent").annotate({ - description: "[UNSTABLE] Source that produced a terminal guardian approval review decision.", + description: "[UNSTABLE] Source that produced a terminal approval auto-review decision.", }); +export type V2ItemGuardianApprovalReviewCompletedNotification__FileSystemAccessMode = + | "read" + | "write" + | "none"; +export const V2ItemGuardianApprovalReviewCompletedNotification__FileSystemAccessMode = + Schema.Literals(["read", "write", "none"]); + +export type V2ItemGuardianApprovalReviewCompletedNotification__FileSystemSpecialPath = + | { readonly kind: "root" } + | { readonly kind: "minimal" } + | { readonly kind: "current_working_directory" } + | { readonly kind: "project_roots"; readonly subpath?: string | null } + | { readonly kind: "tmpdir" } + | { readonly kind: "slash_tmp" } + | { readonly kind: "unknown"; readonly path: string; readonly subpath?: string | null }; +export const V2ItemGuardianApprovalReviewCompletedNotification__FileSystemSpecialPath = + Schema.Union( + [ + Schema.Struct({ kind: Schema.Literal("root") }).annotate({ + title: "RootFileSystemSpecialPath", + }), + Schema.Struct({ kind: Schema.Literal("minimal") }).annotate({ + title: "MinimalFileSystemSpecialPath", + }), + Schema.Struct({ kind: Schema.Literal("current_working_directory") }).annotate({ + title: "CurrentWorkingDirectoryFileSystemSpecialPath", + }), + Schema.Struct({ + kind: Schema.Literal("project_roots"), + subpath: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + }).annotate({ title: "KindFileSystemSpecialPath" }), + Schema.Struct({ kind: Schema.Literal("tmpdir") }).annotate({ + title: "TmpdirFileSystemSpecialPath", + }), + Schema.Struct({ kind: Schema.Literal("slash_tmp") }).annotate({ + title: "SlashTmpFileSystemSpecialPath", + }), + Schema.Struct({ + kind: Schema.Literal("unknown"), + path: Schema.String, + subpath: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + }), + ], + { mode: "oneOf" }, + ); + export type V2ItemGuardianApprovalReviewCompletedNotification__GuardianApprovalReviewStatus = | "inProgress" | "approved" @@ -3598,7 +3962,7 @@ export type V2ItemGuardianApprovalReviewCompletedNotification__GuardianApprovalR | "aborted"; export const V2ItemGuardianApprovalReviewCompletedNotification__GuardianApprovalReviewStatus = Schema.Literals(["inProgress", "approved", "denied", "timedOut", "aborted"]).annotate({ - description: "[UNSTABLE] Lifecycle state for a guardian approval review.", + description: "[UNSTABLE] Lifecycle state for an approval auto-review.", }); export type V2ItemGuardianApprovalReviewCompletedNotification__GuardianCommandSource = @@ -3614,7 +3978,7 @@ export type V2ItemGuardianApprovalReviewCompletedNotification__GuardianRiskLevel | "critical"; export const V2ItemGuardianApprovalReviewCompletedNotification__GuardianRiskLevel = Schema.Literals( ["low", "medium", "high", "critical"], -).annotate({ description: "[UNSTABLE] Risk level assigned by guardian approval review." }); +).annotate({ description: "[UNSTABLE] Risk level assigned by approval auto-review." }); export type V2ItemGuardianApprovalReviewCompletedNotification__GuardianUserAuthorization = | "unknown" @@ -3623,7 +3987,7 @@ export type V2ItemGuardianApprovalReviewCompletedNotification__GuardianUserAutho | "high"; export const V2ItemGuardianApprovalReviewCompletedNotification__GuardianUserAuthorization = Schema.Literals(["unknown", "low", "medium", "high"]).annotate({ - description: "[UNSTABLE] Authorization level assigned by guardian approval review.", + description: "[UNSTABLE] Authorization level assigned by approval auto-review.", }); export type V2ItemGuardianApprovalReviewCompletedNotification__NetworkApprovalProtocol = @@ -3634,6 +3998,64 @@ export type V2ItemGuardianApprovalReviewCompletedNotification__NetworkApprovalPr export const V2ItemGuardianApprovalReviewCompletedNotification__NetworkApprovalProtocol = Schema.Literals(["http", "https", "socks5Tcp", "socks5Udp"]); +export type V2ItemGuardianApprovalReviewStartedNotification__AbsolutePathBuf = string; +export const V2ItemGuardianApprovalReviewStartedNotification__AbsolutePathBuf = + Schema.String.annotate({ + description: + "A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\n\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.", + }); + +export type V2ItemGuardianApprovalReviewStartedNotification__AdditionalNetworkPermissions = { + readonly enabled?: boolean | null; +}; +export const V2ItemGuardianApprovalReviewStartedNotification__AdditionalNetworkPermissions = + Schema.Struct({ enabled: Schema.optionalKey(Schema.Union([Schema.Boolean, Schema.Null])) }); + +export type V2ItemGuardianApprovalReviewStartedNotification__FileSystemAccessMode = + | "read" + | "write" + | "none"; +export const V2ItemGuardianApprovalReviewStartedNotification__FileSystemAccessMode = + Schema.Literals(["read", "write", "none"]); + +export type V2ItemGuardianApprovalReviewStartedNotification__FileSystemSpecialPath = + | { readonly kind: "root" } + | { readonly kind: "minimal" } + | { readonly kind: "current_working_directory" } + | { readonly kind: "project_roots"; readonly subpath?: string | null } + | { readonly kind: "tmpdir" } + | { readonly kind: "slash_tmp" } + | { readonly kind: "unknown"; readonly path: string; readonly subpath?: string | null }; +export const V2ItemGuardianApprovalReviewStartedNotification__FileSystemSpecialPath = Schema.Union( + [ + Schema.Struct({ kind: Schema.Literal("root") }).annotate({ + title: "RootFileSystemSpecialPath", + }), + Schema.Struct({ kind: Schema.Literal("minimal") }).annotate({ + title: "MinimalFileSystemSpecialPath", + }), + Schema.Struct({ kind: Schema.Literal("current_working_directory") }).annotate({ + title: "CurrentWorkingDirectoryFileSystemSpecialPath", + }), + Schema.Struct({ + kind: Schema.Literal("project_roots"), + subpath: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + }).annotate({ title: "KindFileSystemSpecialPath" }), + Schema.Struct({ kind: Schema.Literal("tmpdir") }).annotate({ + title: "TmpdirFileSystemSpecialPath", + }), + Schema.Struct({ kind: Schema.Literal("slash_tmp") }).annotate({ + title: "SlashTmpFileSystemSpecialPath", + }), + Schema.Struct({ + kind: Schema.Literal("unknown"), + path: Schema.String, + subpath: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + }), + ], + { mode: "oneOf" }, +); + export type V2ItemGuardianApprovalReviewStartedNotification__GuardianApprovalReviewStatus = | "inProgress" | "approved" @@ -3642,7 +4064,7 @@ export type V2ItemGuardianApprovalReviewStartedNotification__GuardianApprovalRev | "aborted"; export const V2ItemGuardianApprovalReviewStartedNotification__GuardianApprovalReviewStatus = Schema.Literals(["inProgress", "approved", "denied", "timedOut", "aborted"]).annotate({ - description: "[UNSTABLE] Lifecycle state for a guardian approval review.", + description: "[UNSTABLE] Lifecycle state for an approval auto-review.", }); export type V2ItemGuardianApprovalReviewStartedNotification__GuardianCommandSource = @@ -3661,7 +4083,7 @@ export const V2ItemGuardianApprovalReviewStartedNotification__GuardianRiskLevel "medium", "high", "critical", -]).annotate({ description: "[UNSTABLE] Risk level assigned by guardian approval review." }); +]).annotate({ description: "[UNSTABLE] Risk level assigned by approval auto-review." }); export type V2ItemGuardianApprovalReviewStartedNotification__GuardianUserAuthorization = | "unknown" @@ -3670,7 +4092,7 @@ export type V2ItemGuardianApprovalReviewStartedNotification__GuardianUserAuthori | "high"; export const V2ItemGuardianApprovalReviewStartedNotification__GuardianUserAuthorization = Schema.Literals(["unknown", "low", "medium", "high"]).annotate({ - description: "[UNSTABLE] Authorization level assigned by guardian approval review.", + description: "[UNSTABLE] Authorization level assigned by approval auto-review.", }); export type V2ItemGuardianApprovalReviewStartedNotification__NetworkApprovalProtocol = @@ -3681,6 +4103,12 @@ export type V2ItemGuardianApprovalReviewStartedNotification__NetworkApprovalProt export const V2ItemGuardianApprovalReviewStartedNotification__NetworkApprovalProtocol = Schema.Literals(["http", "https", "socks5Tcp", "socks5Udp"]); +export type V2ItemStartedNotification__AbsolutePathBuf = string; +export const V2ItemStartedNotification__AbsolutePathBuf = Schema.String.annotate({ + description: + "A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\n\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.", +}); + export type V2ItemStartedNotification__CollabAgentStatus = | "pendingInit" | "running" @@ -3699,48 +4127,6 @@ export const V2ItemStartedNotification__CollabAgentStatus = Schema.Literals([ "notFound", ]); -export type V2ItemStartedNotification__CommandAction = - | { - readonly command: string; - readonly name: string; - readonly path: string; - readonly type: "read"; - } - | { readonly command: string; readonly path?: string | null; readonly type: "listFiles" } - | { - readonly command: string; - readonly path?: string | null; - readonly query?: string | null; - readonly type: "search"; - } - | { readonly command: string; readonly type: "unknown" }; -export const V2ItemStartedNotification__CommandAction = Schema.Union( - [ - Schema.Struct({ - command: Schema.String, - name: Schema.String, - path: Schema.String, - type: Schema.Literal("read").annotate({ title: "ReadCommandActionType" }), - }).annotate({ title: "ReadCommandAction" }), - Schema.Struct({ - command: Schema.String, - path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), - type: Schema.Literal("listFiles").annotate({ title: "ListFilesCommandActionType" }), - }).annotate({ title: "ListFilesCommandAction" }), - Schema.Struct({ - command: Schema.String, - path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), - query: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), - type: Schema.Literal("search").annotate({ title: "SearchCommandActionType" }), - }).annotate({ title: "SearchCommandAction" }), - Schema.Struct({ - command: Schema.String, - type: Schema.Literal("unknown").annotate({ title: "UnknownCommandActionType" }), - }).annotate({ title: "UnknownCommandAction" }), - ], - { mode: "oneOf" }, -); - export type V2ItemStartedNotification__CommandExecutionStatus = | "inProgress" | "completed" @@ -4031,6 +4417,18 @@ export const V2ListMcpServerStatusResponse__Tool = Schema.Struct({ title: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), }).annotate({ description: "Definition for a tool the client can call." }); +export type V2MarketplaceAddResponse__AbsolutePathBuf = string; +export const V2MarketplaceAddResponse__AbsolutePathBuf = Schema.String.annotate({ + description: + "A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\n\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.", +}); + +export type V2MarketplaceRemoveResponse__AbsolutePathBuf = string; +export const V2MarketplaceRemoveResponse__AbsolutePathBuf = Schema.String.annotate({ + description: + "A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\n\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.", +}); + export type V2McpResourceReadResponse__ResourceContent = | { readonly _meta?: unknown; @@ -4209,45 +4607,6 @@ export const V2PluginReadResponse__PluginInstallPolicy = Schema.Literals([ "INSTALLED_BY_DEFAULT", ]); -export type V2PluginReadResponse__SkillInterface = { - readonly brandColor?: string | null; - readonly defaultPrompt?: string | null; - readonly displayName?: string | null; - readonly iconLarge?: string | null; - readonly iconSmall?: string | null; - readonly shortDescription?: string | null; -}; -export const V2PluginReadResponse__SkillInterface = Schema.Struct({ - brandColor: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), - defaultPrompt: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), - displayName: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), - iconLarge: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), - iconSmall: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), - shortDescription: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), -}); - -export type V2RawResponseItemCompletedNotification__ContentItem = - | { readonly text: string; readonly type: "input_text" } - | { readonly image_url: string; readonly type: "input_image" } - | { readonly text: string; readonly type: "output_text" }; -export const V2RawResponseItemCompletedNotification__ContentItem = Schema.Union( - [ - Schema.Struct({ - text: Schema.String, - type: Schema.Literal("input_text").annotate({ title: "InputTextContentItemType" }), - }).annotate({ title: "InputTextContentItem" }), - Schema.Struct({ - image_url: Schema.String, - type: Schema.Literal("input_image").annotate({ title: "InputImageContentItemType" }), - }).annotate({ title: "InputImageContentItem" }), - Schema.Struct({ - text: Schema.String, - type: Schema.Literal("output_text").annotate({ title: "OutputTextContentItemType" }), - }).annotate({ title: "OutputTextContentItem" }), - ], - { mode: "oneOf" }, -); - export type V2RawResponseItemCompletedNotification__GhostCommit = { readonly id: string; readonly parent?: string | null; @@ -4449,6 +4808,12 @@ export const V2ReviewStartParams__ReviewTarget = Schema.Union( { mode: "oneOf" }, ); +export type V2ReviewStartResponse__AbsolutePathBuf = string; +export const V2ReviewStartResponse__AbsolutePathBuf = Schema.String.annotate({ + description: + "A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\n\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.", +}); + export type V2ReviewStartResponse__CollabAgentStatus = | "pendingInit" | "running" @@ -4467,48 +4832,6 @@ export const V2ReviewStartResponse__CollabAgentStatus = Schema.Literals([ "notFound", ]); -export type V2ReviewStartResponse__CommandAction = - | { - readonly command: string; - readonly name: string; - readonly path: string; - readonly type: "read"; - } - | { readonly command: string; readonly path?: string | null; readonly type: "listFiles" } - | { - readonly command: string; - readonly path?: string | null; - readonly query?: string | null; - readonly type: "search"; - } - | { readonly command: string; readonly type: "unknown" }; -export const V2ReviewStartResponse__CommandAction = Schema.Union( - [ - Schema.Struct({ - command: Schema.String, - name: Schema.String, - path: Schema.String, - type: Schema.Literal("read").annotate({ title: "ReadCommandActionType" }), - }).annotate({ title: "ReadCommandAction" }), - Schema.Struct({ - command: Schema.String, - path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), - type: Schema.Literal("listFiles").annotate({ title: "ListFilesCommandActionType" }), - }).annotate({ title: "ListFilesCommandAction" }), - Schema.Struct({ - command: Schema.String, - path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), - query: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), - type: Schema.Literal("search").annotate({ title: "SearchCommandActionType" }), - }).annotate({ title: "SearchCommandAction" }), - Schema.Struct({ - command: Schema.String, - type: Schema.Literal("unknown").annotate({ title: "UnknownCommandActionType" }), - }).annotate({ title: "UnknownCommandAction" }), - ], - { mode: "oneOf" }, -); - export type V2ReviewStartResponse__CommandExecutionStatus = | "inProgress" | "completed" @@ -4728,6 +5051,20 @@ export const V2ReviewStartResponse__WebSearchAction = Schema.Union( { mode: "oneOf" }, ); +export type V2SendAddCreditsNudgeEmailParams__AddCreditsNudgeCreditType = "credits" | "usage_limit"; +export const V2SendAddCreditsNudgeEmailParams__AddCreditsNudgeCreditType = Schema.Literals([ + "credits", + "usage_limit", +]); + +export type V2SendAddCreditsNudgeEmailResponse__AddCreditsNudgeEmailStatus = + | "sent" + | "cooldown_active"; +export const V2SendAddCreditsNudgeEmailResponse__AddCreditsNudgeEmailStatus = Schema.Literals([ + "sent", + "cooldown_active", +]); + export type V2ServerRequestResolvedNotification__RequestId = string | number; export const V2ServerRequestResolvedNotification__RequestId = Schema.Union([ Schema.String, @@ -4749,6 +5086,12 @@ export const V2SkillsListParams__SkillsListExtraRootsForCwd = Schema.Struct({ extraUserRoots: Schema.Array(Schema.String), }); +export type V2SkillsListResponse__AbsolutePathBuf = string; +export const V2SkillsListResponse__AbsolutePathBuf = Schema.String.annotate({ + description: + "A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\n\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.", +}); + export type V2SkillsListResponse__SkillErrorInfo = { readonly message: string; readonly path: string; @@ -4758,23 +5101,6 @@ export const V2SkillsListResponse__SkillErrorInfo = Schema.Struct({ path: Schema.String, }); -export type V2SkillsListResponse__SkillInterface = { - readonly brandColor?: string | null; - readonly defaultPrompt?: string | null; - readonly displayName?: string | null; - readonly iconLarge?: string | null; - readonly iconSmall?: string | null; - readonly shortDescription?: string | null; -}; -export const V2SkillsListResponse__SkillInterface = Schema.Struct({ - brandColor: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), - defaultPrompt: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), - displayName: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), - iconLarge: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), - iconSmall: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), - shortDescription: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), -}); - export type V2SkillsListResponse__SkillScope = "user" | "repo" | "system" | "admin"; export const V2SkillsListResponse__SkillScope = Schema.Literals([ "user", @@ -4909,48 +5235,6 @@ export const V2ThreadForkResponse__CollabAgentStatus = Schema.Literals([ "notFound", ]); -export type V2ThreadForkResponse__CommandAction = - | { - readonly command: string; - readonly name: string; - readonly path: string; - readonly type: "read"; - } - | { readonly command: string; readonly path?: string | null; readonly type: "listFiles" } - | { - readonly command: string; - readonly path?: string | null; - readonly query?: string | null; - readonly type: "search"; - } - | { readonly command: string; readonly type: "unknown" }; -export const V2ThreadForkResponse__CommandAction = Schema.Union( - [ - Schema.Struct({ - command: Schema.String, - name: Schema.String, - path: Schema.String, - type: Schema.Literal("read").annotate({ title: "ReadCommandActionType" }), - }).annotate({ title: "ReadCommandAction" }), - Schema.Struct({ - command: Schema.String, - path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), - type: Schema.Literal("listFiles").annotate({ title: "ListFilesCommandActionType" }), - }).annotate({ title: "ListFilesCommandAction" }), - Schema.Struct({ - command: Schema.String, - path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), - query: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), - type: Schema.Literal("search").annotate({ title: "SearchCommandActionType" }), - }).annotate({ title: "SearchCommandAction" }), - Schema.Struct({ - command: Schema.String, - type: Schema.Literal("unknown").annotate({ title: "UnknownCommandActionType" }), - }).annotate({ title: "UnknownCommandAction" }), - ], - { mode: "oneOf" }, -); - export type V2ThreadForkResponse__CommandExecutionStatus = | "inProgress" | "completed" @@ -5193,6 +5477,9 @@ export const V2ThreadForkResponse__WebSearchAction = Schema.Union( { mode: "oneOf" }, ); +export type V2ThreadListParams__SortDirection = "asc" | "desc"; +export const V2ThreadListParams__SortDirection = Schema.Literals(["asc", "desc"]); + export type V2ThreadListParams__ThreadSortKey = "created_at" | "updated_at"; export const V2ThreadListParams__ThreadSortKey = Schema.Literals(["created_at", "updated_at"]); @@ -5220,6 +5507,12 @@ export const V2ThreadListParams__ThreadSourceKind = Schema.Literals([ "unknown", ]); +export type V2ThreadListResponse__AbsolutePathBuf = string; +export const V2ThreadListResponse__AbsolutePathBuf = Schema.String.annotate({ + description: + "A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\n\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.", +}); + export type V2ThreadListResponse__AgentPath = string; export const V2ThreadListResponse__AgentPath = Schema.String; @@ -5241,48 +5534,6 @@ export const V2ThreadListResponse__CollabAgentStatus = Schema.Literals([ "notFound", ]); -export type V2ThreadListResponse__CommandAction = - | { - readonly command: string; - readonly name: string; - readonly path: string; - readonly type: "read"; - } - | { readonly command: string; readonly path?: string | null; readonly type: "listFiles" } - | { - readonly command: string; - readonly path?: string | null; - readonly query?: string | null; - readonly type: "search"; - } - | { readonly command: string; readonly type: "unknown" }; -export const V2ThreadListResponse__CommandAction = Schema.Union( - [ - Schema.Struct({ - command: Schema.String, - name: Schema.String, - path: Schema.String, - type: Schema.Literal("read").annotate({ title: "ReadCommandActionType" }), - }).annotate({ title: "ReadCommandAction" }), - Schema.Struct({ - command: Schema.String, - path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), - type: Schema.Literal("listFiles").annotate({ title: "ListFilesCommandActionType" }), - }).annotate({ title: "ListFilesCommandAction" }), - Schema.Struct({ - command: Schema.String, - path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), - query: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), - type: Schema.Literal("search").annotate({ title: "SearchCommandActionType" }), - }).annotate({ title: "SearchCommandAction" }), - Schema.Struct({ - command: Schema.String, - type: Schema.Literal("unknown").annotate({ title: "UnknownCommandActionType" }), - }).annotate({ title: "UnknownCommandAction" }), - ], - { mode: "oneOf" }, -); - export type V2ThreadListResponse__CommandExecutionStatus = | "inProgress" | "completed" @@ -5557,6 +5808,12 @@ export const V2ThreadMetadataUpdateParams__ThreadMetadataGitInfoUpdateParams = S ), }); +export type V2ThreadMetadataUpdateResponse__AbsolutePathBuf = string; +export const V2ThreadMetadataUpdateResponse__AbsolutePathBuf = Schema.String.annotate({ + description: + "A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\n\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.", +}); + export type V2ThreadMetadataUpdateResponse__AgentPath = string; export const V2ThreadMetadataUpdateResponse__AgentPath = Schema.String; @@ -5578,48 +5835,6 @@ export const V2ThreadMetadataUpdateResponse__CollabAgentStatus = Schema.Literals "notFound", ]); -export type V2ThreadMetadataUpdateResponse__CommandAction = - | { - readonly command: string; - readonly name: string; - readonly path: string; - readonly type: "read"; - } - | { readonly command: string; readonly path?: string | null; readonly type: "listFiles" } - | { - readonly command: string; - readonly path?: string | null; - readonly query?: string | null; - readonly type: "search"; - } - | { readonly command: string; readonly type: "unknown" }; -export const V2ThreadMetadataUpdateResponse__CommandAction = Schema.Union( - [ - Schema.Struct({ - command: Schema.String, - name: Schema.String, - path: Schema.String, - type: Schema.Literal("read").annotate({ title: "ReadCommandActionType" }), - }).annotate({ title: "ReadCommandAction" }), - Schema.Struct({ - command: Schema.String, - path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), - type: Schema.Literal("listFiles").annotate({ title: "ListFilesCommandActionType" }), - }).annotate({ title: "ListFilesCommandAction" }), - Schema.Struct({ - command: Schema.String, - path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), - query: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), - type: Schema.Literal("search").annotate({ title: "SearchCommandActionType" }), - }).annotate({ title: "SearchCommandAction" }), - Schema.Struct({ - command: Schema.String, - type: Schema.Literal("unknown").annotate({ title: "UnknownCommandActionType" }), - }).annotate({ title: "UnknownCommandAction" }), - ], - { mode: "oneOf" }, -); - export type V2ThreadMetadataUpdateResponse__CommandExecutionStatus = | "inProgress" | "completed" @@ -5872,6 +6087,12 @@ export const V2ThreadMetadataUpdateResponse__WebSearchAction = Schema.Union( { mode: "oneOf" }, ); +export type V2ThreadReadResponse__AbsolutePathBuf = string; +export const V2ThreadReadResponse__AbsolutePathBuf = Schema.String.annotate({ + description: + "A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\n\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.", +}); + export type V2ThreadReadResponse__AgentPath = string; export const V2ThreadReadResponse__AgentPath = Schema.String; @@ -5893,48 +6114,6 @@ export const V2ThreadReadResponse__CollabAgentStatus = Schema.Literals([ "notFound", ]); -export type V2ThreadReadResponse__CommandAction = - | { - readonly command: string; - readonly name: string; - readonly path: string; - readonly type: "read"; - } - | { readonly command: string; readonly path?: string | null; readonly type: "listFiles" } - | { - readonly command: string; - readonly path?: string | null; - readonly query?: string | null; - readonly type: "search"; - } - | { readonly command: string; readonly type: "unknown" }; -export const V2ThreadReadResponse__CommandAction = Schema.Union( - [ - Schema.Struct({ - command: Schema.String, - name: Schema.String, - path: Schema.String, - type: Schema.Literal("read").annotate({ title: "ReadCommandActionType" }), - }).annotate({ title: "ReadCommandAction" }), - Schema.Struct({ - command: Schema.String, - path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), - type: Schema.Literal("listFiles").annotate({ title: "ListFilesCommandActionType" }), - }).annotate({ title: "ListFilesCommandAction" }), - Schema.Struct({ - command: Schema.String, - path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), - query: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), - type: Schema.Literal("search").annotate({ title: "SearchCommandActionType" }), - }).annotate({ title: "SearchCommandAction" }), - Schema.Struct({ - command: Schema.String, - type: Schema.Literal("unknown").annotate({ title: "UnknownCommandActionType" }), - }).annotate({ title: "UnknownCommandAction" }), - ], - { mode: "oneOf" }, -); - export type V2ThreadReadResponse__CommandExecutionStatus = | "inProgress" | "completed" @@ -6247,28 +6426,6 @@ export const V2ThreadResumeParams__AskForApproval = Schema.Union( { mode: "oneOf" }, ); -export type V2ThreadResumeParams__ContentItem = - | { readonly text: string; readonly type: "input_text" } - | { readonly image_url: string; readonly type: "input_image" } - | { readonly text: string; readonly type: "output_text" }; -export const V2ThreadResumeParams__ContentItem = Schema.Union( - [ - Schema.Struct({ - text: Schema.String, - type: Schema.Literal("input_text").annotate({ title: "InputTextContentItemType" }), - }).annotate({ title: "InputTextContentItem" }), - Schema.Struct({ - image_url: Schema.String, - type: Schema.Literal("input_image").annotate({ title: "InputImageContentItemType" }), - }).annotate({ title: "InputImageContentItem" }), - Schema.Struct({ - text: Schema.String, - type: Schema.Literal("output_text").annotate({ title: "OutputTextContentItemType" }), - }).annotate({ title: "OutputTextContentItem" }), - ], - { mode: "oneOf" }, -); - export type V2ThreadResumeParams__GhostCommit = { readonly id: string; readonly parent?: string | null; @@ -6485,48 +6642,6 @@ export const V2ThreadResumeResponse__CollabAgentStatus = Schema.Literals([ "notFound", ]); -export type V2ThreadResumeResponse__CommandAction = - | { - readonly command: string; - readonly name: string; - readonly path: string; - readonly type: "read"; - } - | { readonly command: string; readonly path?: string | null; readonly type: "listFiles" } - | { - readonly command: string; - readonly path?: string | null; - readonly query?: string | null; - readonly type: "search"; - } - | { readonly command: string; readonly type: "unknown" }; -export const V2ThreadResumeResponse__CommandAction = Schema.Union( - [ - Schema.Struct({ - command: Schema.String, - name: Schema.String, - path: Schema.String, - type: Schema.Literal("read").annotate({ title: "ReadCommandActionType" }), - }).annotate({ title: "ReadCommandAction" }), - Schema.Struct({ - command: Schema.String, - path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), - type: Schema.Literal("listFiles").annotate({ title: "ListFilesCommandActionType" }), - }).annotate({ title: "ListFilesCommandAction" }), - Schema.Struct({ - command: Schema.String, - path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), - query: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), - type: Schema.Literal("search").annotate({ title: "SearchCommandActionType" }), - }).annotate({ title: "SearchCommandAction" }), - Schema.Struct({ - command: Schema.String, - type: Schema.Literal("unknown").annotate({ title: "UnknownCommandActionType" }), - }).annotate({ title: "UnknownCommandAction" }), - ], - { mode: "oneOf" }, -); - export type V2ThreadResumeResponse__CommandExecutionStatus = | "inProgress" | "completed" @@ -6769,6 +6884,12 @@ export const V2ThreadResumeResponse__WebSearchAction = Schema.Union( { mode: "oneOf" }, ); +export type V2ThreadRollbackResponse__AbsolutePathBuf = string; +export const V2ThreadRollbackResponse__AbsolutePathBuf = Schema.String.annotate({ + description: + "A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\n\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.", +}); + export type V2ThreadRollbackResponse__AgentPath = string; export const V2ThreadRollbackResponse__AgentPath = Schema.String; @@ -6790,48 +6911,6 @@ export const V2ThreadRollbackResponse__CollabAgentStatus = Schema.Literals([ "notFound", ]); -export type V2ThreadRollbackResponse__CommandAction = - | { - readonly command: string; - readonly name: string; - readonly path: string; - readonly type: "read"; - } - | { readonly command: string; readonly path?: string | null; readonly type: "listFiles" } - | { - readonly command: string; - readonly path?: string | null; - readonly query?: string | null; - readonly type: "search"; - } - | { readonly command: string; readonly type: "unknown" }; -export const V2ThreadRollbackResponse__CommandAction = Schema.Union( - [ - Schema.Struct({ - command: Schema.String, - name: Schema.String, - path: Schema.String, - type: Schema.Literal("read").annotate({ title: "ReadCommandActionType" }), - }).annotate({ title: "ReadCommandAction" }), - Schema.Struct({ - command: Schema.String, - path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), - type: Schema.Literal("listFiles").annotate({ title: "ListFilesCommandActionType" }), - }).annotate({ title: "ListFilesCommandAction" }), - Schema.Struct({ - command: Schema.String, - path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), - query: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), - type: Schema.Literal("search").annotate({ title: "SearchCommandActionType" }), - }).annotate({ title: "SearchCommandAction" }), - Schema.Struct({ - command: Schema.String, - type: Schema.Literal("unknown").annotate({ title: "UnknownCommandActionType" }), - }).annotate({ title: "UnknownCommandAction" }), - ], - { mode: "oneOf" }, -); - export type V2ThreadRollbackResponse__CommandExecutionStatus = | "inProgress" | "completed" @@ -7074,6 +7153,12 @@ export const V2ThreadRollbackResponse__WebSearchAction = Schema.Union( { mode: "oneOf" }, ); +export type V2ThreadStartedNotification__AbsolutePathBuf = string; +export const V2ThreadStartedNotification__AbsolutePathBuf = Schema.String.annotate({ + description: + "A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\n\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.", +}); + export type V2ThreadStartedNotification__AgentPath = string; export const V2ThreadStartedNotification__AgentPath = Schema.String; @@ -7095,48 +7180,6 @@ export const V2ThreadStartedNotification__CollabAgentStatus = Schema.Literals([ "notFound", ]); -export type V2ThreadStartedNotification__CommandAction = - | { - readonly command: string; - readonly name: string; - readonly path: string; - readonly type: "read"; - } - | { readonly command: string; readonly path?: string | null; readonly type: "listFiles" } - | { - readonly command: string; - readonly path?: string | null; - readonly query?: string | null; - readonly type: "search"; - } - | { readonly command: string; readonly type: "unknown" }; -export const V2ThreadStartedNotification__CommandAction = Schema.Union( - [ - Schema.Struct({ - command: Schema.String, - name: Schema.String, - path: Schema.String, - type: Schema.Literal("read").annotate({ title: "ReadCommandActionType" }), - }).annotate({ title: "ReadCommandAction" }), - Schema.Struct({ - command: Schema.String, - path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), - type: Schema.Literal("listFiles").annotate({ title: "ListFilesCommandActionType" }), - }).annotate({ title: "ListFilesCommandAction" }), - Schema.Struct({ - command: Schema.String, - path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), - query: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), - type: Schema.Literal("search").annotate({ title: "SearchCommandActionType" }), - }).annotate({ title: "SearchCommandAction" }), - Schema.Struct({ - command: Schema.String, - type: Schema.Literal("unknown").annotate({ title: "UnknownCommandActionType" }), - }).annotate({ title: "UnknownCommandAction" }), - ], - { mode: "oneOf" }, -); - export type V2ThreadStartedNotification__CommandExecutionStatus = | "inProgress" | "completed" @@ -7501,48 +7544,6 @@ export const V2ThreadStartResponse__CollabAgentStatus = Schema.Literals([ "notFound", ]); -export type V2ThreadStartResponse__CommandAction = - | { - readonly command: string; - readonly name: string; - readonly path: string; - readonly type: "read"; - } - | { readonly command: string; readonly path?: string | null; readonly type: "listFiles" } - | { - readonly command: string; - readonly path?: string | null; - readonly query?: string | null; - readonly type: "search"; - } - | { readonly command: string; readonly type: "unknown" }; -export const V2ThreadStartResponse__CommandAction = Schema.Union( - [ - Schema.Struct({ - command: Schema.String, - name: Schema.String, - path: Schema.String, - type: Schema.Literal("read").annotate({ title: "ReadCommandActionType" }), - }).annotate({ title: "ReadCommandAction" }), - Schema.Struct({ - command: Schema.String, - path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), - type: Schema.Literal("listFiles").annotate({ title: "ListFilesCommandActionType" }), - }).annotate({ title: "ListFilesCommandAction" }), - Schema.Struct({ - command: Schema.String, - path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), - query: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), - type: Schema.Literal("search").annotate({ title: "SearchCommandActionType" }), - }).annotate({ title: "SearchCommandAction" }), - Schema.Struct({ - command: Schema.String, - type: Schema.Literal("unknown").annotate({ title: "UnknownCommandActionType" }), - }).annotate({ title: "UnknownCommandAction" }), - ], - { mode: "oneOf" }, -); - export type V2ThreadStartResponse__CommandExecutionStatus = | "inProgress" | "completed" @@ -7808,6 +7809,266 @@ export const V2ThreadTokenUsageUpdatedNotification__TokenUsageBreakdown = Schema totalTokens: Schema.Number.annotate({ format: "int64" }).check(Schema.isInt()), }); +export type V2ThreadTurnsListParams__SortDirection = "asc" | "desc"; +export const V2ThreadTurnsListParams__SortDirection = Schema.Literals(["asc", "desc"]); + +export type V2ThreadTurnsListResponse__AbsolutePathBuf = string; +export const V2ThreadTurnsListResponse__AbsolutePathBuf = Schema.String.annotate({ + description: + "A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\n\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.", +}); + +export type V2ThreadTurnsListResponse__CollabAgentStatus = + | "pendingInit" + | "running" + | "interrupted" + | "completed" + | "errored" + | "shutdown" + | "notFound"; +export const V2ThreadTurnsListResponse__CollabAgentStatus = Schema.Literals([ + "pendingInit", + "running", + "interrupted", + "completed", + "errored", + "shutdown", + "notFound", +]); + +export type V2ThreadTurnsListResponse__CommandExecutionStatus = + | "inProgress" + | "completed" + | "failed" + | "declined"; +export const V2ThreadTurnsListResponse__CommandExecutionStatus = Schema.Literals([ + "inProgress", + "completed", + "failed", + "declined", +]); + +export type V2ThreadTurnsListResponse__DynamicToolCallOutputContentItem = + | { readonly text: string; readonly type: "inputText" } + | { readonly imageUrl: string; readonly type: "inputImage" }; +export const V2ThreadTurnsListResponse__DynamicToolCallOutputContentItem = Schema.Union( + [ + Schema.Struct({ + text: Schema.String, + type: Schema.Literal("inputText").annotate({ + title: "InputTextDynamicToolCallOutputContentItemType", + }), + }).annotate({ title: "InputTextDynamicToolCallOutputContentItem" }), + Schema.Struct({ + imageUrl: Schema.String, + type: Schema.Literal("inputImage").annotate({ + title: "InputImageDynamicToolCallOutputContentItemType", + }), + }).annotate({ title: "InputImageDynamicToolCallOutputContentItem" }), + ], + { mode: "oneOf" }, +); + +export type V2ThreadTurnsListResponse__DynamicToolCallStatus = + | "inProgress" + | "completed" + | "failed"; +export const V2ThreadTurnsListResponse__DynamicToolCallStatus = Schema.Literals([ + "inProgress", + "completed", + "failed", +]); + +export type V2ThreadTurnsListResponse__HookPromptFragment = { + readonly hookRunId: string; + readonly text: string; +}; +export const V2ThreadTurnsListResponse__HookPromptFragment = Schema.Struct({ + hookRunId: Schema.String, + text: Schema.String, +}); + +export type V2ThreadTurnsListResponse__McpToolCallError = { readonly message: string }; +export const V2ThreadTurnsListResponse__McpToolCallError = Schema.Struct({ + message: Schema.String, +}); + +export type V2ThreadTurnsListResponse__McpToolCallResult = { + readonly _meta?: unknown; + readonly content: ReadonlyArray; + readonly structuredContent?: unknown; +}; +export const V2ThreadTurnsListResponse__McpToolCallResult = Schema.Struct({ + _meta: Schema.optionalKey(Schema.Unknown), + content: Schema.Array(Schema.Unknown), + structuredContent: Schema.optionalKey(Schema.Unknown), +}); + +export type V2ThreadTurnsListResponse__McpToolCallStatus = "inProgress" | "completed" | "failed"; +export const V2ThreadTurnsListResponse__McpToolCallStatus = Schema.Literals([ + "inProgress", + "completed", + "failed", +]); + +export type V2ThreadTurnsListResponse__MemoryCitationEntry = { + readonly lineEnd: number; + readonly lineStart: number; + readonly note: string; + readonly path: string; +}; +export const V2ThreadTurnsListResponse__MemoryCitationEntry = Schema.Struct({ + lineEnd: Schema.Number.annotate({ format: "uint32" }) + .check(Schema.isInt()) + .check(Schema.isGreaterThanOrEqualTo(0)), + lineStart: Schema.Number.annotate({ format: "uint32" }) + .check(Schema.isInt()) + .check(Schema.isGreaterThanOrEqualTo(0)), + note: Schema.String, + path: Schema.String, +}); + +export type V2ThreadTurnsListResponse__MessagePhase = "commentary" | "final_answer"; +export const V2ThreadTurnsListResponse__MessagePhase = Schema.Literals([ + "commentary", + "final_answer", +]).annotate({ + description: + 'Classifies an assistant message as interim commentary or final answer text.\n\nProviders do not emit this consistently, so callers must treat `None` as "phase unknown" and keep compatibility behavior for legacy models.', +}); + +export type V2ThreadTurnsListResponse__NonSteerableTurnKind = "review" | "compact"; +export const V2ThreadTurnsListResponse__NonSteerableTurnKind = Schema.Literals([ + "review", + "compact", +]); + +export type V2ThreadTurnsListResponse__PatchApplyStatus = + | "inProgress" + | "completed" + | "failed" + | "declined"; +export const V2ThreadTurnsListResponse__PatchApplyStatus = Schema.Literals([ + "inProgress", + "completed", + "failed", + "declined", +]); + +export type V2ThreadTurnsListResponse__PatchChangeKind = + | { readonly type: "add" } + | { readonly type: "delete" } + | { readonly move_path?: string | null; readonly type: "update" }; +export const V2ThreadTurnsListResponse__PatchChangeKind = Schema.Union( + [ + Schema.Struct({ + type: Schema.Literal("add").annotate({ title: "AddPatchChangeKindType" }), + }).annotate({ title: "AddPatchChangeKind" }), + Schema.Struct({ + type: Schema.Literal("delete").annotate({ title: "DeletePatchChangeKindType" }), + }).annotate({ title: "DeletePatchChangeKind" }), + Schema.Struct({ + move_path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + type: Schema.Literal("update").annotate({ title: "UpdatePatchChangeKindType" }), + }).annotate({ title: "UpdatePatchChangeKind" }), + ], + { mode: "oneOf" }, +); + +export type V2ThreadTurnsListResponse__ReasoningEffort = + | "none" + | "minimal" + | "low" + | "medium" + | "high" + | "xhigh"; +export const V2ThreadTurnsListResponse__ReasoningEffort = Schema.Literals([ + "none", + "minimal", + "low", + "medium", + "high", + "xhigh", +]).annotate({ + description: + "See https://platform.openai.com/docs/guides/reasoning?api-mode=responses#get-started-with-reasoning", +}); + +export type V2ThreadTurnsListResponse__TextElement = { + readonly byteRange: { readonly end: number; readonly start: number }; + readonly placeholder?: string | null; +}; +export const V2ThreadTurnsListResponse__TextElement = Schema.Struct({ + byteRange: Schema.Struct({ + end: Schema.Number.annotate({ format: "uint" }) + .check(Schema.isInt()) + .check(Schema.isGreaterThanOrEqualTo(0)), + start: Schema.Number.annotate({ format: "uint" }) + .check(Schema.isInt()) + .check(Schema.isGreaterThanOrEqualTo(0)), + }).annotate({ + description: "Byte range in the parent `text` buffer that this element occupies.", + }), + placeholder: Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + description: "Optional human-readable placeholder for the element, displayed in the UI.", + }), + Schema.Null, + ]), + ), +}); + +export type V2ThreadTurnsListResponse__TurnStatus = + | "completed" + | "interrupted" + | "failed" + | "inProgress"; +export const V2ThreadTurnsListResponse__TurnStatus = Schema.Literals([ + "completed", + "interrupted", + "failed", + "inProgress", +]); + +export type V2ThreadTurnsListResponse__WebSearchAction = + | { + readonly queries?: ReadonlyArray | null; + readonly query?: string | null; + readonly type: "search"; + } + | { readonly type: "openPage"; readonly url?: string | null } + | { readonly pattern?: string | null; readonly type: "findInPage"; readonly url?: string | null } + | { readonly type: "other" }; +export const V2ThreadTurnsListResponse__WebSearchAction = Schema.Union( + [ + Schema.Struct({ + queries: Schema.optionalKey(Schema.Union([Schema.Array(Schema.String), Schema.Null])), + query: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + type: Schema.Literal("search").annotate({ title: "SearchWebSearchActionType" }), + }).annotate({ title: "SearchWebSearchAction" }), + Schema.Struct({ + type: Schema.Literal("openPage").annotate({ title: "OpenPageWebSearchActionType" }), + url: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + }).annotate({ title: "OpenPageWebSearchAction" }), + Schema.Struct({ + pattern: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + type: Schema.Literal("findInPage").annotate({ title: "FindInPageWebSearchActionType" }), + url: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + }).annotate({ title: "FindInPageWebSearchAction" }), + Schema.Struct({ + type: Schema.Literal("other").annotate({ title: "OtherWebSearchActionType" }), + }).annotate({ title: "OtherWebSearchAction" }), + ], + { mode: "oneOf" }, +); + +export type V2ThreadUnarchiveResponse__AbsolutePathBuf = string; +export const V2ThreadUnarchiveResponse__AbsolutePathBuf = Schema.String.annotate({ + description: + "A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\n\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.", +}); + export type V2ThreadUnarchiveResponse__AgentPath = string; export const V2ThreadUnarchiveResponse__AgentPath = Schema.String; @@ -7829,48 +8090,6 @@ export const V2ThreadUnarchiveResponse__CollabAgentStatus = Schema.Literals([ "notFound", ]); -export type V2ThreadUnarchiveResponse__CommandAction = - | { - readonly command: string; - readonly name: string; - readonly path: string; - readonly type: "read"; - } - | { readonly command: string; readonly path?: string | null; readonly type: "listFiles" } - | { - readonly command: string; - readonly path?: string | null; - readonly query?: string | null; - readonly type: "search"; - } - | { readonly command: string; readonly type: "unknown" }; -export const V2ThreadUnarchiveResponse__CommandAction = Schema.Union( - [ - Schema.Struct({ - command: Schema.String, - name: Schema.String, - path: Schema.String, - type: Schema.Literal("read").annotate({ title: "ReadCommandActionType" }), - }).annotate({ title: "ReadCommandAction" }), - Schema.Struct({ - command: Schema.String, - path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), - type: Schema.Literal("listFiles").annotate({ title: "ListFilesCommandActionType" }), - }).annotate({ title: "ListFilesCommandAction" }), - Schema.Struct({ - command: Schema.String, - path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), - query: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), - type: Schema.Literal("search").annotate({ title: "SearchCommandActionType" }), - }).annotate({ title: "SearchCommandAction" }), - Schema.Struct({ - command: Schema.String, - type: Schema.Literal("unknown").annotate({ title: "UnknownCommandActionType" }), - }).annotate({ title: "UnknownCommandAction" }), - ], - { mode: "oneOf" }, -); - export type V2ThreadUnarchiveResponse__CommandExecutionStatus = | "inProgress" | "completed" @@ -8130,6 +8349,12 @@ export const V2ThreadUnsubscribeResponse__ThreadUnsubscribeStatus = Schema.Liter "unsubscribed", ]); +export type V2TurnCompletedNotification__AbsolutePathBuf = string; +export const V2TurnCompletedNotification__AbsolutePathBuf = Schema.String.annotate({ + description: + "A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\n\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.", +}); + export type V2TurnCompletedNotification__CollabAgentStatus = | "pendingInit" | "running" @@ -8148,48 +8373,6 @@ export const V2TurnCompletedNotification__CollabAgentStatus = Schema.Literals([ "notFound", ]); -export type V2TurnCompletedNotification__CommandAction = - | { - readonly command: string; - readonly name: string; - readonly path: string; - readonly type: "read"; - } - | { readonly command: string; readonly path?: string | null; readonly type: "listFiles" } - | { - readonly command: string; - readonly path?: string | null; - readonly query?: string | null; - readonly type: "search"; - } - | { readonly command: string; readonly type: "unknown" }; -export const V2TurnCompletedNotification__CommandAction = Schema.Union( - [ - Schema.Struct({ - command: Schema.String, - name: Schema.String, - path: Schema.String, - type: Schema.Literal("read").annotate({ title: "ReadCommandActionType" }), - }).annotate({ title: "ReadCommandAction" }), - Schema.Struct({ - command: Schema.String, - path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), - type: Schema.Literal("listFiles").annotate({ title: "ListFilesCommandActionType" }), - }).annotate({ title: "ListFilesCommandAction" }), - Schema.Struct({ - command: Schema.String, - path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), - query: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), - type: Schema.Literal("search").annotate({ title: "SearchCommandActionType" }), - }).annotate({ title: "SearchCommandAction" }), - Schema.Struct({ - command: Schema.String, - type: Schema.Literal("unknown").annotate({ title: "UnknownCommandActionType" }), - }).annotate({ title: "UnknownCommandAction" }), - ], - { mode: "oneOf" }, -); - export type V2TurnCompletedNotification__CommandExecutionStatus = | "inProgress" | "completed" @@ -8427,6 +8610,12 @@ export const V2TurnPlanUpdatedNotification__TurnPlanStepStatus = Schema.Literals "completed", ]); +export type V2TurnStartedNotification__AbsolutePathBuf = string; +export const V2TurnStartedNotification__AbsolutePathBuf = Schema.String.annotate({ + description: + "A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\n\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.", +}); + export type V2TurnStartedNotification__CollabAgentStatus = | "pendingInit" | "running" @@ -8445,48 +8634,6 @@ export const V2TurnStartedNotification__CollabAgentStatus = Schema.Literals([ "notFound", ]); -export type V2TurnStartedNotification__CommandAction = - | { - readonly command: string; - readonly name: string; - readonly path: string; - readonly type: "read"; - } - | { readonly command: string; readonly path?: string | null; readonly type: "listFiles" } - | { - readonly command: string; - readonly path?: string | null; - readonly query?: string | null; - readonly type: "search"; - } - | { readonly command: string; readonly type: "unknown" }; -export const V2TurnStartedNotification__CommandAction = Schema.Union( - [ - Schema.Struct({ - command: Schema.String, - name: Schema.String, - path: Schema.String, - type: Schema.Literal("read").annotate({ title: "ReadCommandActionType" }), - }).annotate({ title: "ReadCommandAction" }), - Schema.Struct({ - command: Schema.String, - path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), - type: Schema.Literal("listFiles").annotate({ title: "ListFilesCommandActionType" }), - }).annotate({ title: "ListFilesCommandAction" }), - Schema.Struct({ - command: Schema.String, - path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), - query: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), - type: Schema.Literal("search").annotate({ title: "SearchCommandActionType" }), - }).annotate({ title: "SearchCommandAction" }), - Schema.Struct({ - command: Schema.String, - type: Schema.Literal("unknown").annotate({ title: "UnknownCommandActionType" }), - }).annotate({ title: "UnknownCommandAction" }), - ], - { mode: "oneOf" }, -); - export type V2TurnStartedNotification__CommandExecutionStatus = | "inProgress" | "completed" @@ -8826,6 +8973,12 @@ export const V2TurnStartParams__TextElement = Schema.Struct({ ), }); +export type V2TurnStartResponse__AbsolutePathBuf = string; +export const V2TurnStartResponse__AbsolutePathBuf = Schema.String.annotate({ + description: + "A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\n\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.", +}); + export type V2TurnStartResponse__CollabAgentStatus = | "pendingInit" | "running" @@ -8844,48 +8997,6 @@ export const V2TurnStartResponse__CollabAgentStatus = Schema.Literals([ "notFound", ]); -export type V2TurnStartResponse__CommandAction = - | { - readonly command: string; - readonly name: string; - readonly path: string; - readonly type: "read"; - } - | { readonly command: string; readonly path?: string | null; readonly type: "listFiles" } - | { - readonly command: string; - readonly path?: string | null; - readonly query?: string | null; - readonly type: "search"; - } - | { readonly command: string; readonly type: "unknown" }; -export const V2TurnStartResponse__CommandAction = Schema.Union( - [ - Schema.Struct({ - command: Schema.String, - name: Schema.String, - path: Schema.String, - type: Schema.Literal("read").annotate({ title: "ReadCommandActionType" }), - }).annotate({ title: "ReadCommandAction" }), - Schema.Struct({ - command: Schema.String, - path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), - type: Schema.Literal("listFiles").annotate({ title: "ListFilesCommandActionType" }), - }).annotate({ title: "ListFilesCommandAction" }), - Schema.Struct({ - command: Schema.String, - path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), - query: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), - type: Schema.Literal("search").annotate({ title: "SearchCommandActionType" }), - }).annotate({ title: "SearchCommandAction" }), - Schema.Struct({ - command: Schema.String, - type: Schema.Literal("unknown").annotate({ title: "UnknownCommandActionType" }), - }).annotate({ title: "UnknownCommandAction" }), - ], - { mode: "oneOf" }, -); - export type V2TurnStartResponse__CommandExecutionStatus = | "inProgress" | "completed" @@ -9156,23 +9267,18 @@ export const ApplyPatchApprovalResponse__NetworkPolicyAmendment = Schema.Struct( }); export type ClientRequest__PluginInstallParams = { - readonly forceRemoteSync?: boolean; - readonly marketplacePath: ClientRequest__AbsolutePathBuf; + readonly marketplacePath?: ClientRequest__AbsolutePathBuf | null; readonly pluginName: string; + readonly remoteMarketplaceName?: string | null; }; export const ClientRequest__PluginInstallParams = Schema.Struct({ - forceRemoteSync: Schema.optionalKey( - Schema.Boolean.annotate({ - description: "When true, apply the remote plugin change before the local install flow.", - }), - ), - marketplacePath: ClientRequest__AbsolutePathBuf, + marketplacePath: Schema.optionalKey(Schema.Union([ClientRequest__AbsolutePathBuf, Schema.Null])), pluginName: Schema.String, + remoteMarketplaceName: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), }); export type ClientRequest__PluginListParams = { readonly cwds?: ReadonlyArray | null; - readonly forceRemoteSync?: boolean; }; export const ClientRequest__PluginListParams = Schema.Struct({ cwds: Schema.optionalKey( @@ -9184,21 +9290,17 @@ export const ClientRequest__PluginListParams = Schema.Struct({ Schema.Null, ]), ), - forceRemoteSync: Schema.optionalKey( - Schema.Boolean.annotate({ - description: - "When true, reconcile the official curated marketplace against the remote plugin state before listing marketplaces.", - }), - ), }); export type ClientRequest__PluginReadParams = { - readonly marketplacePath: ClientRequest__AbsolutePathBuf; + readonly marketplacePath?: ClientRequest__AbsolutePathBuf | null; readonly pluginName: string; + readonly remoteMarketplaceName?: string | null; }; export const ClientRequest__PluginReadParams = Schema.Struct({ - marketplacePath: ClientRequest__AbsolutePathBuf, + marketplacePath: Schema.optionalKey(Schema.Union([ClientRequest__AbsolutePathBuf, Schema.Null])), pluginName: Schema.String, + remoteMarketplaceName: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), }); export type ClientRequest__SandboxPolicy = @@ -9324,25 +9426,55 @@ export const ClientRequest__SkillsConfigWriteParams = Schema.Struct({ ), }); -export type ClientRequest__ExternalAgentConfigMigrationItem = { - readonly cwd?: string | null; - readonly description: string; - readonly itemType: ClientRequest__ExternalAgentConfigMigrationItemType; +export type ClientRequest__SendAddCreditsNudgeEmailParams = { + readonly creditType: ClientRequest__AddCreditsNudgeCreditType; }; -export const ClientRequest__ExternalAgentConfigMigrationItem = Schema.Struct({ - cwd: Schema.optionalKey( - Schema.Union([ - Schema.String.annotate({ - description: - "Null or empty means home-scoped migration; non-empty means repo-scoped migration.", - }), - Schema.Null, - ]), - ), - description: Schema.String, - itemType: ClientRequest__ExternalAgentConfigMigrationItemType, +export const ClientRequest__SendAddCreditsNudgeEmailParams = Schema.Struct({ + creditType: ClientRequest__AddCreditsNudgeCreditType, }); +export type ClientRequest__DeviceKeyCreateParams = { + readonly accountUserId: string; + readonly clientId: string; + readonly protectionPolicy?: ClientRequest__DeviceKeyProtectionPolicy | null; +}; +export const ClientRequest__DeviceKeyCreateParams = Schema.Struct({ + accountUserId: Schema.String, + clientId: Schema.String, + protectionPolicy: Schema.optionalKey( + Schema.Union([ClientRequest__DeviceKeyProtectionPolicy, Schema.Null]).annotate({ + description: "Defaults to `hardware_only` when omitted.", + }), + ), +}).annotate({ description: "Create a controller-local device key with a random key id." }); + +export type ClientRequest__ContentItem = + | { readonly text: string; readonly type: "input_text" } + | { + readonly detail?: ClientRequest__ImageDetail | null; + readonly image_url: string; + readonly type: "input_image"; + } + | { readonly text: string; readonly type: "output_text" }; +export const ClientRequest__ContentItem = Schema.Union( + [ + Schema.Struct({ + text: Schema.String, + type: Schema.Literal("input_text").annotate({ title: "InputTextContentItemType" }), + }).annotate({ title: "InputTextContentItem" }), + Schema.Struct({ + detail: Schema.optionalKey(Schema.Union([ClientRequest__ImageDetail, Schema.Null])), + image_url: Schema.String, + type: Schema.Literal("input_image").annotate({ title: "InputImageContentItemType" }), + }).annotate({ title: "InputImageContentItem" }), + Schema.Struct({ + text: Schema.String, + type: Schema.Literal("output_text").annotate({ title: "OutputTextContentItemType" }), + }).annotate({ title: "OutputTextContentItem" }), + ], + { mode: "oneOf" }, +); + export type ClientRequest__FunctionCallOutputContentItem = | { readonly text: string; readonly type: "input_text" } | { @@ -9450,6 +9582,13 @@ export const ClientRequest__ConfigValueWriteParams = Schema.Struct({ value: Schema.Unknown, }); +export type ClientRequest__MigrationDetails = { + readonly plugins: ReadonlyArray; +}; +export const ClientRequest__MigrationDetails = Schema.Struct({ + plugins: Schema.Array(ClientRequest__PluginsMigration), +}); + export type ClientRequest__Settings = { readonly developer_instructions?: string | null; readonly model: string; @@ -9461,6 +9600,102 @@ export const ClientRequest__Settings = Schema.Struct({ reasoning_effort: Schema.optionalKey(Schema.Union([ClientRequest__ReasoningEffort, Schema.Null])), }).annotate({ description: "Settings for a collaboration mode." }); +export type ClientRequest__DeviceKeySignPayload = + | { + readonly accountUserId: string; + readonly audience: ClientRequest__RemoteControlClientConnectionAudience; + readonly clientId: string; + readonly nonce: string; + readonly scopes: ReadonlyArray; + readonly sessionId: string; + readonly targetOrigin: string; + readonly targetPath: string; + readonly tokenExpiresAt: number; + readonly tokenSha256Base64url: string; + readonly type: "remoteControlClientConnection"; + } + | { + readonly accountUserId: string; + readonly audience: ClientRequest__RemoteControlClientEnrollmentAudience; + readonly challengeExpiresAt: number; + readonly challengeId: string; + readonly clientId: string; + readonly deviceIdentitySha256Base64url: string; + readonly nonce: string; + readonly targetOrigin: string; + readonly targetPath: string; + readonly type: "remoteControlClientEnrollment"; + }; +export const ClientRequest__DeviceKeySignPayload = Schema.Union( + [ + Schema.Struct({ + accountUserId: Schema.String, + audience: ClientRequest__RemoteControlClientConnectionAudience, + clientId: Schema.String, + nonce: Schema.String, + scopes: Schema.Array(Schema.String).annotate({ + description: "Must contain exactly `remote_control_controller_websocket`.", + }), + sessionId: Schema.String.annotate({ + description: "Backend-issued websocket session id that this proof authorizes.", + }), + targetOrigin: Schema.String.annotate({ + description: + "Origin of the backend endpoint that issued the challenge and will verify this proof.", + }), + targetPath: Schema.String.annotate({ + description: "Websocket route path that this proof authorizes.", + }), + tokenExpiresAt: Schema.Number.annotate({ + description: "Remote-control token expiration as Unix seconds.", + format: "int64", + }).check(Schema.isInt()), + tokenSha256Base64url: Schema.String.annotate({ + description: + "SHA-256 of the controller-scoped remote-control token, encoded as unpadded base64url.", + }), + type: Schema.Literal("remoteControlClientConnection").annotate({ + title: "RemoteControlClientConnectionDeviceKeySignPayloadType", + }), + }).annotate({ + title: "RemoteControlClientConnectionDeviceKeySignPayload", + description: + "Payload bound to one remote-control controller websocket `/client` connection challenge.", + }), + Schema.Struct({ + accountUserId: Schema.String, + audience: ClientRequest__RemoteControlClientEnrollmentAudience, + challengeExpiresAt: Schema.Number.annotate({ + description: "Enrollment challenge expiration as Unix seconds.", + format: "int64", + }).check(Schema.isInt()), + challengeId: Schema.String.annotate({ + description: "Backend-issued enrollment challenge id that this proof authorizes.", + }), + clientId: Schema.String, + deviceIdentitySha256Base64url: Schema.String.annotate({ + description: + "SHA-256 of the requested device identity operation, encoded as unpadded base64url.", + }), + nonce: Schema.String, + targetOrigin: Schema.String.annotate({ + description: + "Origin of the backend endpoint that issued the challenge and will verify this proof.", + }), + targetPath: Schema.String.annotate({ + description: "HTTP route path that this proof authorizes.", + }), + type: Schema.Literal("remoteControlClientEnrollment").annotate({ + title: "RemoteControlClientEnrollmentDeviceKeySignPayloadType", + }), + }).annotate({ + title: "RemoteControlClientEnrollmentDeviceKeySignPayload", + description: "Payload bound to a remote-control client `/client/enroll` ownership challenge.", + }), + ], + { mode: "oneOf" }, +).annotate({ description: "Structured payloads accepted by `device/key/sign`." }); + export type ClientRequest__ReviewStartParams = { readonly delivery?: ClientRequest__ReviewDelivery | null; readonly target: ClientRequest__ReviewTarget; @@ -9599,6 +9834,37 @@ export const ClientRequest__SkillsListParams = Schema.Struct({ ), }); +export type ClientRequest__ThreadTurnsListParams = { + readonly cursor?: string | null; + readonly limit?: number | null; + readonly sortDirection?: ClientRequest__SortDirection | null; + readonly threadId: string; +}; +export const ClientRequest__ThreadTurnsListParams = Schema.Struct({ + cursor: Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + description: "Opaque cursor to pass to the next call to continue after the last turn.", + }), + Schema.Null, + ]), + ), + limit: Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ description: "Optional turn page size.", format: "uint32" }) + .check(Schema.isInt()) + .check(Schema.isGreaterThanOrEqualTo(0)), + Schema.Null, + ]), + ), + sortDirection: Schema.optionalKey( + Schema.Union([ClientRequest__SortDirection, Schema.Null]).annotate({ + description: "Optional turn pagination direction; defaults to descending.", + }), + ), + threadId: Schema.String, +}); + export type ClientRequest__UserInput = | { readonly text: string; @@ -9664,6 +9930,7 @@ export type ClientRequest__ThreadListParams = { readonly limit?: number | null; readonly modelProviders?: ReadonlyArray | null; readonly searchTerm?: string | null; + readonly sortDirection?: ClientRequest__SortDirection | null; readonly sortKey?: ClientRequest__ThreadSortKey | null; readonly sourceKinds?: ReadonlyArray | null; }; @@ -9722,6 +9989,11 @@ export const ClientRequest__ThreadListParams = Schema.Struct({ Schema.Null, ]), ), + sortDirection: Schema.optionalKey( + Schema.Union([ClientRequest__SortDirection, Schema.Null]).annotate({ + description: "Optional sort direction; defaults to descending (newest first).", + }), + ), sortKey: Schema.optionalKey( Schema.Union([ClientRequest__ThreadSortKey, Schema.Null]).annotate({ description: "Optional sort key; defaults to created_at.", @@ -9791,25 +10063,71 @@ export const ClientRequest__WindowsSandboxSetupStartParams = Schema.Struct({ mode: ClientRequest__WindowsSandboxSetupMode, }); -export type CommandExecutionRequestApprovalParams__AdditionalFileSystemPermissions = { - readonly read?: ReadonlyArray | null; - readonly write?: ReadonlyArray | null; -}; -export const CommandExecutionRequestApprovalParams__AdditionalFileSystemPermissions = Schema.Struct( - { - read: Schema.optionalKey( - Schema.Union([ - Schema.Array(CommandExecutionRequestApprovalParams__AbsolutePathBuf), - Schema.Null, - ]), - ), - write: Schema.optionalKey( - Schema.Union([ - Schema.Array(CommandExecutionRequestApprovalParams__AbsolutePathBuf), - Schema.Null, - ]), - ), - }, +export type CommandExecutionRequestApprovalParams__CommandAction = + | { + readonly command: string; + readonly name: string; + readonly path: CommandExecutionRequestApprovalParams__AbsolutePathBuf; + readonly type: "read"; + } + | { readonly command: string; readonly path?: string | null; readonly type: "listFiles" } + | { + readonly command: string; + readonly path?: string | null; + readonly query?: string | null; + readonly type: "search"; + } + | { readonly command: string; readonly type: "unknown" }; +export const CommandExecutionRequestApprovalParams__CommandAction = Schema.Union( + [ + Schema.Struct({ + command: Schema.String, + name: Schema.String, + path: CommandExecutionRequestApprovalParams__AbsolutePathBuf, + type: Schema.Literal("read").annotate({ title: "ReadCommandActionType" }), + }).annotate({ title: "ReadCommandAction" }), + Schema.Struct({ + command: Schema.String, + path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + type: Schema.Literal("listFiles").annotate({ title: "ListFilesCommandActionType" }), + }).annotate({ title: "ListFilesCommandAction" }), + Schema.Struct({ + command: Schema.String, + path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + query: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + type: Schema.Literal("search").annotate({ title: "SearchCommandActionType" }), + }).annotate({ title: "SearchCommandAction" }), + Schema.Struct({ + command: Schema.String, + type: Schema.Literal("unknown").annotate({ title: "UnknownCommandActionType" }), + }).annotate({ title: "UnknownCommandAction" }), + ], + { mode: "oneOf" }, +); + +export type CommandExecutionRequestApprovalParams__FileSystemPath = + | { readonly path: CommandExecutionRequestApprovalParams__AbsolutePathBuf; readonly type: "path" } + | { readonly pattern: string; readonly type: "glob_pattern" } + | { + readonly type: "special"; + readonly value: CommandExecutionRequestApprovalParams__FileSystemSpecialPath; + }; +export const CommandExecutionRequestApprovalParams__FileSystemPath = Schema.Union( + [ + Schema.Struct({ + path: CommandExecutionRequestApprovalParams__AbsolutePathBuf, + type: Schema.Literal("path").annotate({ title: "PathFileSystemPathType" }), + }).annotate({ title: "PathFileSystemPath" }), + Schema.Struct({ + pattern: Schema.String, + type: Schema.Literal("glob_pattern").annotate({ title: "GlobPatternFileSystemPathType" }), + }).annotate({ title: "GlobPatternFileSystemPath" }), + Schema.Struct({ + type: Schema.Literal("special").annotate({ title: "SpecialFileSystemPathType" }), + value: CommandExecutionRequestApprovalParams__FileSystemSpecialPath, + }).annotate({ title: "SpecialFileSystemPath" }), + ], + { mode: "oneOf" }, ); export type CommandExecutionRequestApprovalParams__NetworkApprovalContext = { @@ -10085,31 +10403,97 @@ export const McpServerElicitationRequestParams__McpElicitationUntitledSingleSele type: McpServerElicitationRequestParams__McpElicitationStringType, }); -export type PermissionsRequestApprovalParams__AdditionalFileSystemPermissions = { - readonly read?: ReadonlyArray | null; - readonly write?: ReadonlyArray | null; -}; -export const PermissionsRequestApprovalParams__AdditionalFileSystemPermissions = Schema.Struct({ - read: Schema.optionalKey( - Schema.Union([Schema.Array(PermissionsRequestApprovalParams__AbsolutePathBuf), Schema.Null]), - ), - write: Schema.optionalKey( - Schema.Union([Schema.Array(PermissionsRequestApprovalParams__AbsolutePathBuf), Schema.Null]), - ), -}); +export type PermissionsRequestApprovalParams__FileSystemPath = + | { readonly path: PermissionsRequestApprovalParams__AbsolutePathBuf; readonly type: "path" } + | { readonly pattern: string; readonly type: "glob_pattern" } + | { + readonly type: "special"; + readonly value: PermissionsRequestApprovalParams__FileSystemSpecialPath; + }; +export const PermissionsRequestApprovalParams__FileSystemPath = Schema.Union( + [ + Schema.Struct({ + path: PermissionsRequestApprovalParams__AbsolutePathBuf, + type: Schema.Literal("path").annotate({ title: "PathFileSystemPathType" }), + }).annotate({ title: "PathFileSystemPath" }), + Schema.Struct({ + pattern: Schema.String, + type: Schema.Literal("glob_pattern").annotate({ title: "GlobPatternFileSystemPathType" }), + }).annotate({ title: "GlobPatternFileSystemPath" }), + Schema.Struct({ + type: Schema.Literal("special").annotate({ title: "SpecialFileSystemPathType" }), + value: PermissionsRequestApprovalParams__FileSystemSpecialPath, + }).annotate({ title: "SpecialFileSystemPath" }), + ], + { mode: "oneOf" }, +); -export type PermissionsRequestApprovalResponse__AdditionalFileSystemPermissions = { - readonly read?: ReadonlyArray | null; - readonly write?: ReadonlyArray | null; -}; -export const PermissionsRequestApprovalResponse__AdditionalFileSystemPermissions = Schema.Struct({ - read: Schema.optionalKey( - Schema.Union([Schema.Array(PermissionsRequestApprovalResponse__AbsolutePathBuf), Schema.Null]), - ), - write: Schema.optionalKey( - Schema.Union([Schema.Array(PermissionsRequestApprovalResponse__AbsolutePathBuf), Schema.Null]), - ), -}); +export type PermissionsRequestApprovalResponse__FileSystemPath = + | { readonly path: PermissionsRequestApprovalResponse__AbsolutePathBuf; readonly type: "path" } + | { readonly pattern: string; readonly type: "glob_pattern" } + | { + readonly type: "special"; + readonly value: PermissionsRequestApprovalResponse__FileSystemSpecialPath; + }; +export const PermissionsRequestApprovalResponse__FileSystemPath = Schema.Union( + [ + Schema.Struct({ + path: PermissionsRequestApprovalResponse__AbsolutePathBuf, + type: Schema.Literal("path").annotate({ title: "PathFileSystemPathType" }), + }).annotate({ title: "PathFileSystemPath" }), + Schema.Struct({ + pattern: Schema.String, + type: Schema.Literal("glob_pattern").annotate({ title: "GlobPatternFileSystemPathType" }), + }).annotate({ title: "GlobPatternFileSystemPath" }), + Schema.Struct({ + type: Schema.Literal("special").annotate({ title: "SpecialFileSystemPathType" }), + value: PermissionsRequestApprovalResponse__FileSystemSpecialPath, + }).annotate({ title: "SpecialFileSystemPath" }), + ], + { mode: "oneOf" }, +); + +export type ServerNotification__CommandAction = + | { + readonly command: string; + readonly name: string; + readonly path: ServerNotification__AbsolutePathBuf; + readonly type: "read"; + } + | { readonly command: string; readonly path?: string | null; readonly type: "listFiles" } + | { + readonly command: string; + readonly path?: string | null; + readonly query?: string | null; + readonly type: "search"; + } + | { readonly command: string; readonly type: "unknown" }; +export const ServerNotification__CommandAction = Schema.Union( + [ + Schema.Struct({ + command: Schema.String, + name: Schema.String, + path: ServerNotification__AbsolutePathBuf, + type: Schema.Literal("read").annotate({ title: "ReadCommandActionType" }), + }).annotate({ title: "ReadCommandAction" }), + Schema.Struct({ + command: Schema.String, + path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + type: Schema.Literal("listFiles").annotate({ title: "ListFilesCommandActionType" }), + }).annotate({ title: "ListFilesCommandAction" }), + Schema.Struct({ + command: Schema.String, + path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + query: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + type: Schema.Literal("search").annotate({ title: "SearchCommandActionType" }), + }).annotate({ title: "SearchCommandAction" }), + Schema.Struct({ + command: Schema.String, + type: Schema.Literal("unknown").annotate({ title: "UnknownCommandActionType" }), + }).annotate({ title: "UnknownCommandAction" }), + ], + { mode: "oneOf" }, +); export type ServerNotification__FsChangedNotification = { readonly changedPaths: ReadonlyArray; @@ -10164,6 +10548,28 @@ export const ServerNotification__CollabAgentState = Schema.Struct({ status: ServerNotification__CollabAgentStatus, }); +export type ServerNotification__FileSystemPath = + | { readonly path: ServerNotification__AbsolutePathBuf; readonly type: "path" } + | { readonly pattern: string; readonly type: "glob_pattern" } + | { readonly type: "special"; readonly value: ServerNotification__FileSystemSpecialPath }; +export const ServerNotification__FileSystemPath = Schema.Union( + [ + Schema.Struct({ + path: ServerNotification__AbsolutePathBuf, + type: Schema.Literal("path").annotate({ title: "PathFileSystemPathType" }), + }).annotate({ title: "PathFileSystemPath" }), + Schema.Struct({ + pattern: Schema.String, + type: Schema.Literal("glob_pattern").annotate({ title: "GlobPatternFileSystemPathType" }), + }).annotate({ title: "GlobPatternFileSystemPath" }), + Schema.Struct({ + type: Schema.Literal("special").annotate({ title: "SpecialFileSystemPathType" }), + value: ServerNotification__FileSystemSpecialPath, + }).annotate({ title: "SpecialFileSystemPath" }), + ], + { mode: "oneOf" }, +); + export type ServerNotification__FuzzyFileSearchResult = { readonly file_name: string; readonly indices?: ReadonlyArray | null; @@ -10207,7 +10613,7 @@ export const ServerNotification__GuardianApprovalReview = Schema.Struct({ ), }).annotate({ description: - "[UNSTABLE] Temporary guardian approval review payload used by `item/autoApprovalReview/*` notifications. This shape is expected to change soon.", + "[UNSTABLE] Temporary approval auto-review payload used by `item/autoApprovalReview/*` notifications. This shape is expected to change soon.", }); export type ServerNotification__HookOutputEntry = { @@ -10254,85 +10660,6 @@ export const ServerNotification__ModelReroutedNotification = Schema.Struct({ turnId: Schema.String, }); -export type ServerNotification__GuardianApprovalReviewAction = - | { - readonly command: string; - readonly cwd: string; - readonly source: ServerNotification__GuardianCommandSource; - readonly type: "command"; - } - | { - readonly argv: ReadonlyArray; - readonly cwd: string; - readonly program: string; - readonly source: ServerNotification__GuardianCommandSource; - readonly type: "execve"; - } - | { readonly cwd: string; readonly files: ReadonlyArray; readonly type: "applyPatch" } - | { - readonly host: string; - readonly port: number; - readonly protocol: ServerNotification__NetworkApprovalProtocol; - readonly target: string; - readonly type: "networkAccess"; - } - | { - readonly connectorId?: string | null; - readonly connectorName?: string | null; - readonly server: string; - readonly toolName: string; - readonly toolTitle?: string | null; - readonly type: "mcpToolCall"; - }; -export const ServerNotification__GuardianApprovalReviewAction = Schema.Union( - [ - Schema.Struct({ - command: Schema.String, - cwd: Schema.String, - source: ServerNotification__GuardianCommandSource, - type: Schema.Literal("command").annotate({ - title: "CommandGuardianApprovalReviewActionType", - }), - }).annotate({ title: "CommandGuardianApprovalReviewAction" }), - Schema.Struct({ - argv: Schema.Array(Schema.String), - cwd: Schema.String, - program: Schema.String, - source: ServerNotification__GuardianCommandSource, - type: Schema.Literal("execve").annotate({ title: "ExecveGuardianApprovalReviewActionType" }), - }).annotate({ title: "ExecveGuardianApprovalReviewAction" }), - Schema.Struct({ - cwd: Schema.String, - files: Schema.Array(Schema.String), - type: Schema.Literal("applyPatch").annotate({ - title: "ApplyPatchGuardianApprovalReviewActionType", - }), - }).annotate({ title: "ApplyPatchGuardianApprovalReviewAction" }), - Schema.Struct({ - host: Schema.String, - port: Schema.Number.annotate({ format: "uint16" }) - .check(Schema.isInt()) - .check(Schema.isGreaterThanOrEqualTo(0)), - protocol: ServerNotification__NetworkApprovalProtocol, - target: Schema.String, - type: Schema.Literal("networkAccess").annotate({ - title: "NetworkAccessGuardianApprovalReviewActionType", - }), - }).annotate({ title: "NetworkAccessGuardianApprovalReviewAction" }), - Schema.Struct({ - connectorId: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), - connectorName: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), - server: Schema.String, - toolName: Schema.String, - toolTitle: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), - type: Schema.Literal("mcpToolCall").annotate({ - title: "McpToolCallGuardianApprovalReviewActionType", - }), - }).annotate({ title: "McpToolCallGuardianApprovalReviewAction" }), - ], - { mode: "oneOf" }, -); - export type ServerNotification__CodexErrorInfo = | "contextWindowExceeded" | "usageLimitExceeded" @@ -10463,6 +10790,7 @@ export type ServerNotification__RateLimitSnapshot = { readonly limitName?: string | null; readonly planType?: ServerNotification__PlanType | null; readonly primary?: ServerNotification__RateLimitWindow | null; + readonly rateLimitReachedType?: ServerNotification__RateLimitReachedType | null; readonly secondary?: ServerNotification__RateLimitWindow | null; }; export const ServerNotification__RateLimitSnapshot = Schema.Struct({ @@ -10471,6 +10799,9 @@ export const ServerNotification__RateLimitSnapshot = Schema.Struct({ limitName: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), planType: Schema.optionalKey(Schema.Union([ServerNotification__PlanType, Schema.Null])), primary: Schema.optionalKey(Schema.Union([ServerNotification__RateLimitWindow, Schema.Null])), + rateLimitReachedType: Schema.optionalKey( + Schema.Union([ServerNotification__RateLimitReachedType, Schema.Null]), + ), secondary: Schema.optionalKey(Schema.Union([ServerNotification__RateLimitWindow, Schema.Null])), }); @@ -10647,18 +10978,47 @@ export const ServerNotification__WindowsSandboxSetupCompletedNotification = Sche success: Schema.Boolean, }); -export type ServerRequest__AdditionalFileSystemPermissions = { - readonly read?: ReadonlyArray | null; - readonly write?: ReadonlyArray | null; -}; -export const ServerRequest__AdditionalFileSystemPermissions = Schema.Struct({ - read: Schema.optionalKey( - Schema.Union([Schema.Array(ServerRequest__AbsolutePathBuf), Schema.Null]), - ), - write: Schema.optionalKey( - Schema.Union([Schema.Array(ServerRequest__AbsolutePathBuf), Schema.Null]), - ), -}); +export type ServerRequest__CommandAction = + | { + readonly command: string; + readonly name: string; + readonly path: ServerRequest__AbsolutePathBuf; + readonly type: "read"; + } + | { readonly command: string; readonly path?: string | null; readonly type: "listFiles" } + | { + readonly command: string; + readonly path?: string | null; + readonly query?: string | null; + readonly type: "search"; + } + | { readonly command: string; readonly type: "unknown" }; +export const ServerRequest__CommandAction = Schema.Union( + [ + Schema.Struct({ + command: Schema.String, + name: Schema.String, + path: ServerRequest__AbsolutePathBuf, + type: Schema.Literal("read").annotate({ title: "ReadCommandActionType" }), + }).annotate({ title: "ReadCommandAction" }), + Schema.Struct({ + command: Schema.String, + path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + type: Schema.Literal("listFiles").annotate({ title: "ListFilesCommandActionType" }), + }).annotate({ title: "ListFilesCommandAction" }), + Schema.Struct({ + command: Schema.String, + path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + query: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + type: Schema.Literal("search").annotate({ title: "SearchCommandActionType" }), + }).annotate({ title: "SearchCommandAction" }), + Schema.Struct({ + command: Schema.String, + type: Schema.Literal("unknown").annotate({ title: "UnknownCommandActionType" }), + }).annotate({ title: "UnknownCommandAction" }), + ], + { mode: "oneOf" }, +); export type ServerRequest__ChatgptAuthTokensRefreshParams = { readonly previousAccountId?: string | null; @@ -10677,6 +11037,28 @@ export const ServerRequest__ChatgptAuthTokensRefreshParams = Schema.Struct({ reason: ServerRequest__ChatgptAuthTokensRefreshReason, }); +export type ServerRequest__FileSystemPath = + | { readonly path: ServerRequest__AbsolutePathBuf; readonly type: "path" } + | { readonly pattern: string; readonly type: "glob_pattern" } + | { readonly type: "special"; readonly value: ServerRequest__FileSystemSpecialPath }; +export const ServerRequest__FileSystemPath = Schema.Union( + [ + Schema.Struct({ + path: ServerRequest__AbsolutePathBuf, + type: Schema.Literal("path").annotate({ title: "PathFileSystemPathType" }), + }).annotate({ title: "PathFileSystemPath" }), + Schema.Struct({ + pattern: Schema.String, + type: Schema.Literal("glob_pattern").annotate({ title: "GlobPatternFileSystemPathType" }), + }).annotate({ title: "GlobPatternFileSystemPath" }), + Schema.Struct({ + type: Schema.Literal("special").annotate({ title: "SpecialFileSystemPathType" }), + value: ServerRequest__FileSystemSpecialPath, + }).annotate({ title: "SpecialFileSystemPath" }), + ], + { mode: "oneOf" }, +); + export type ServerRequest__McpElicitationBooleanSchema = { readonly default?: boolean | null; readonly description?: string | null; @@ -10949,6 +11331,7 @@ export type V2AccountRateLimitsUpdatedNotification__RateLimitSnapshot = { readonly limitName?: string | null; readonly planType?: V2AccountRateLimitsUpdatedNotification__PlanType | null; readonly primary?: V2AccountRateLimitsUpdatedNotification__RateLimitWindow | null; + readonly rateLimitReachedType?: V2AccountRateLimitsUpdatedNotification__RateLimitReachedType | null; readonly secondary?: V2AccountRateLimitsUpdatedNotification__RateLimitWindow | null; }; export const V2AccountRateLimitsUpdatedNotification__RateLimitSnapshot = Schema.Struct({ @@ -10963,6 +11346,9 @@ export const V2AccountRateLimitsUpdatedNotification__RateLimitSnapshot = Schema. primary: Schema.optionalKey( Schema.Union([V2AccountRateLimitsUpdatedNotification__RateLimitWindow, Schema.Null]), ), + rateLimitReachedType: Schema.optionalKey( + Schema.Union([V2AccountRateLimitsUpdatedNotification__RateLimitReachedType, Schema.Null]), + ), secondary: Schema.optionalKey( Schema.Union([V2AccountRateLimitsUpdatedNotification__RateLimitWindow, Schema.Null]), ), @@ -11346,6 +11732,102 @@ export const V2ConfigWriteResponse__ConfigLayerSource = Schema.Union( { mode: "oneOf" }, ); +export type V2DeviceKeySignParams__DeviceKeySignPayload = + | { + readonly accountUserId: string; + readonly audience: V2DeviceKeySignParams__RemoteControlClientConnectionAudience; + readonly clientId: string; + readonly nonce: string; + readonly scopes: ReadonlyArray; + readonly sessionId: string; + readonly targetOrigin: string; + readonly targetPath: string; + readonly tokenExpiresAt: number; + readonly tokenSha256Base64url: string; + readonly type: "remoteControlClientConnection"; + } + | { + readonly accountUserId: string; + readonly audience: V2DeviceKeySignParams__RemoteControlClientEnrollmentAudience; + readonly challengeExpiresAt: number; + readonly challengeId: string; + readonly clientId: string; + readonly deviceIdentitySha256Base64url: string; + readonly nonce: string; + readonly targetOrigin: string; + readonly targetPath: string; + readonly type: "remoteControlClientEnrollment"; + }; +export const V2DeviceKeySignParams__DeviceKeySignPayload = Schema.Union( + [ + Schema.Struct({ + accountUserId: Schema.String, + audience: V2DeviceKeySignParams__RemoteControlClientConnectionAudience, + clientId: Schema.String, + nonce: Schema.String, + scopes: Schema.Array(Schema.String).annotate({ + description: "Must contain exactly `remote_control_controller_websocket`.", + }), + sessionId: Schema.String.annotate({ + description: "Backend-issued websocket session id that this proof authorizes.", + }), + targetOrigin: Schema.String.annotate({ + description: + "Origin of the backend endpoint that issued the challenge and will verify this proof.", + }), + targetPath: Schema.String.annotate({ + description: "Websocket route path that this proof authorizes.", + }), + tokenExpiresAt: Schema.Number.annotate({ + description: "Remote-control token expiration as Unix seconds.", + format: "int64", + }).check(Schema.isInt()), + tokenSha256Base64url: Schema.String.annotate({ + description: + "SHA-256 of the controller-scoped remote-control token, encoded as unpadded base64url.", + }), + type: Schema.Literal("remoteControlClientConnection").annotate({ + title: "RemoteControlClientConnectionDeviceKeySignPayloadType", + }), + }).annotate({ + title: "RemoteControlClientConnectionDeviceKeySignPayload", + description: + "Payload bound to one remote-control controller websocket `/client` connection challenge.", + }), + Schema.Struct({ + accountUserId: Schema.String, + audience: V2DeviceKeySignParams__RemoteControlClientEnrollmentAudience, + challengeExpiresAt: Schema.Number.annotate({ + description: "Enrollment challenge expiration as Unix seconds.", + format: "int64", + }).check(Schema.isInt()), + challengeId: Schema.String.annotate({ + description: "Backend-issued enrollment challenge id that this proof authorizes.", + }), + clientId: Schema.String, + deviceIdentitySha256Base64url: Schema.String.annotate({ + description: + "SHA-256 of the requested device identity operation, encoded as unpadded base64url.", + }), + nonce: Schema.String, + targetOrigin: Schema.String.annotate({ + description: + "Origin of the backend endpoint that issued the challenge and will verify this proof.", + }), + targetPath: Schema.String.annotate({ + description: "HTTP route path that this proof authorizes.", + }), + type: Schema.Literal("remoteControlClientEnrollment").annotate({ + title: "RemoteControlClientEnrollmentDeviceKeySignPayloadType", + }), + }).annotate({ + title: "RemoteControlClientEnrollmentDeviceKeySignPayload", + description: "Payload bound to a remote-control client `/client/enroll` ownership challenge.", + }), + ], + { mode: "oneOf" }, +).annotate({ description: "Structured payloads accepted by `device/key/sign`." }); + export type V2ErrorNotification__CodexErrorInfo = | "contextWindowExceeded" | "usageLimitExceeded" @@ -11452,42 +11934,29 @@ export const V2ErrorNotification__CodexErrorInfo = Schema.Union( "This translation layer make sure that we expose codex error code in camel case.\n\nWhen an upstream HTTP status is available (for example, from the Responses API or a provider), it is forwarded in `httpStatusCode` on the relevant `codexErrorInfo` variant.", }); -export type V2ExternalAgentConfigDetectResponse__ExternalAgentConfigMigrationItem = { - readonly cwd?: string | null; - readonly description: string; - readonly itemType: V2ExternalAgentConfigDetectResponse__ExternalAgentConfigMigrationItemType; +export type V2ExternalAgentConfigDetectResponse__MigrationDetails = { + readonly plugins: ReadonlyArray; }; -export const V2ExternalAgentConfigDetectResponse__ExternalAgentConfigMigrationItem = Schema.Struct({ - cwd: Schema.optionalKey( - Schema.Union([ - Schema.String.annotate({ - description: - "Null or empty means home-scoped migration; non-empty means repo-scoped migration.", - }), - Schema.Null, - ]), - ), - description: Schema.String, - itemType: V2ExternalAgentConfigDetectResponse__ExternalAgentConfigMigrationItemType, +export const V2ExternalAgentConfigDetectResponse__MigrationDetails = Schema.Struct({ + plugins: Schema.Array(V2ExternalAgentConfigDetectResponse__PluginsMigration), }); -export type V2ExternalAgentConfigImportParams__ExternalAgentConfigMigrationItem = { - readonly cwd?: string | null; - readonly description: string; - readonly itemType: V2ExternalAgentConfigImportParams__ExternalAgentConfigMigrationItemType; +export type V2ExternalAgentConfigImportParams__MigrationDetails = { + readonly plugins: ReadonlyArray; }; -export const V2ExternalAgentConfigImportParams__ExternalAgentConfigMigrationItem = Schema.Struct({ - cwd: Schema.optionalKey( - Schema.Union([ - Schema.String.annotate({ - description: - "Null or empty means home-scoped migration; non-empty means repo-scoped migration.", - }), - Schema.Null, - ]), - ), - description: Schema.String, - itemType: V2ExternalAgentConfigImportParams__ExternalAgentConfigMigrationItemType, +export const V2ExternalAgentConfigImportParams__MigrationDetails = Schema.Struct({ + plugins: Schema.Array(V2ExternalAgentConfigImportParams__PluginsMigration), +}); + +export type V2FileChangePatchUpdatedNotification__FileUpdateChange = { + readonly diff: string; + readonly kind: V2FileChangePatchUpdatedNotification__PatchChangeKind; + readonly path: string; +}; +export const V2FileChangePatchUpdatedNotification__FileUpdateChange = Schema.Struct({ + diff: Schema.String, + kind: V2FileChangePatchUpdatedNotification__PatchChangeKind, + path: Schema.String, }); export type V2GetAccountRateLimitsResponse__RateLimitSnapshot = { @@ -11496,6 +11965,7 @@ export type V2GetAccountRateLimitsResponse__RateLimitSnapshot = { readonly limitName?: string | null; readonly planType?: V2GetAccountRateLimitsResponse__PlanType | null; readonly primary?: V2GetAccountRateLimitsResponse__RateLimitWindow | null; + readonly rateLimitReachedType?: V2GetAccountRateLimitsResponse__RateLimitReachedType | null; readonly secondary?: V2GetAccountRateLimitsResponse__RateLimitWindow | null; }; export const V2GetAccountRateLimitsResponse__RateLimitSnapshot = Schema.Struct({ @@ -11510,6 +11980,9 @@ export const V2GetAccountRateLimitsResponse__RateLimitSnapshot = Schema.Struct({ primary: Schema.optionalKey( Schema.Union([V2GetAccountRateLimitsResponse__RateLimitWindow, Schema.Null]), ), + rateLimitReachedType: Schema.optionalKey( + Schema.Union([V2GetAccountRateLimitsResponse__RateLimitReachedType, Schema.Null]), + ), secondary: Schema.optionalKey( Schema.Union([V2GetAccountRateLimitsResponse__RateLimitWindow, Schema.Null]), ), @@ -11554,6 +12027,48 @@ export const V2HookStartedNotification__HookOutputEntry = Schema.Struct({ text: Schema.String, }); +export type V2ItemCompletedNotification__CommandAction = + | { + readonly command: string; + readonly name: string; + readonly path: V2ItemCompletedNotification__AbsolutePathBuf; + readonly type: "read"; + } + | { readonly command: string; readonly path?: string | null; readonly type: "listFiles" } + | { + readonly command: string; + readonly path?: string | null; + readonly query?: string | null; + readonly type: "search"; + } + | { readonly command: string; readonly type: "unknown" }; +export const V2ItemCompletedNotification__CommandAction = Schema.Union( + [ + Schema.Struct({ + command: Schema.String, + name: Schema.String, + path: V2ItemCompletedNotification__AbsolutePathBuf, + type: Schema.Literal("read").annotate({ title: "ReadCommandActionType" }), + }).annotate({ title: "ReadCommandAction" }), + Schema.Struct({ + command: Schema.String, + path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + type: Schema.Literal("listFiles").annotate({ title: "ListFilesCommandActionType" }), + }).annotate({ title: "ListFilesCommandAction" }), + Schema.Struct({ + command: Schema.String, + path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + query: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + type: Schema.Literal("search").annotate({ title: "SearchCommandActionType" }), + }).annotate({ title: "SearchCommandAction" }), + Schema.Struct({ + command: Schema.String, + type: Schema.Literal("unknown").annotate({ title: "UnknownCommandActionType" }), + }).annotate({ title: "UnknownCommandAction" }), + ], + { mode: "oneOf" }, +); + export type V2ItemCompletedNotification__CollabAgentState = { readonly message?: string | null; readonly status: V2ItemCompletedNotification__CollabAgentStatus; @@ -11627,6 +12142,34 @@ export const V2ItemCompletedNotification__UserInput = Schema.Union( { mode: "oneOf" }, ); +export type V2ItemGuardianApprovalReviewCompletedNotification__FileSystemPath = + | { + readonly path: V2ItemGuardianApprovalReviewCompletedNotification__AbsolutePathBuf; + readonly type: "path"; + } + | { readonly pattern: string; readonly type: "glob_pattern" } + | { + readonly type: "special"; + readonly value: V2ItemGuardianApprovalReviewCompletedNotification__FileSystemSpecialPath; + }; +export const V2ItemGuardianApprovalReviewCompletedNotification__FileSystemPath = Schema.Union( + [ + Schema.Struct({ + path: V2ItemGuardianApprovalReviewCompletedNotification__AbsolutePathBuf, + type: Schema.Literal("path").annotate({ title: "PathFileSystemPathType" }), + }).annotate({ title: "PathFileSystemPath" }), + Schema.Struct({ + pattern: Schema.String, + type: Schema.Literal("glob_pattern").annotate({ title: "GlobPatternFileSystemPathType" }), + }).annotate({ title: "GlobPatternFileSystemPath" }), + Schema.Struct({ + type: Schema.Literal("special").annotate({ title: "SpecialFileSystemPathType" }), + value: V2ItemGuardianApprovalReviewCompletedNotification__FileSystemSpecialPath, + }).annotate({ title: "SpecialFileSystemPath" }), + ], + { mode: "oneOf" }, +); + export type V2ItemGuardianApprovalReviewCompletedNotification__GuardianApprovalReview = { readonly rationale?: string | null; readonly riskLevel?: V2ItemGuardianApprovalReviewCompletedNotification__GuardianRiskLevel | null; @@ -11651,90 +12194,36 @@ export const V2ItemGuardianApprovalReviewCompletedNotification__GuardianApproval ), }).annotate({ description: - "[UNSTABLE] Temporary guardian approval review payload used by `item/autoApprovalReview/*` notifications. This shape is expected to change soon.", + "[UNSTABLE] Temporary approval auto-review payload used by `item/autoApprovalReview/*` notifications. This shape is expected to change soon.", }); -export type V2ItemGuardianApprovalReviewCompletedNotification__GuardianApprovalReviewAction = +export type V2ItemGuardianApprovalReviewStartedNotification__FileSystemPath = | { - readonly command: string; - readonly cwd: string; - readonly source: V2ItemGuardianApprovalReviewCompletedNotification__GuardianCommandSource; - readonly type: "command"; + readonly path: V2ItemGuardianApprovalReviewStartedNotification__AbsolutePathBuf; + readonly type: "path"; } + | { readonly pattern: string; readonly type: "glob_pattern" } | { - readonly argv: ReadonlyArray; - readonly cwd: string; - readonly program: string; - readonly source: V2ItemGuardianApprovalReviewCompletedNotification__GuardianCommandSource; - readonly type: "execve"; - } - | { readonly cwd: string; readonly files: ReadonlyArray; readonly type: "applyPatch" } - | { - readonly host: string; - readonly port: number; - readonly protocol: V2ItemGuardianApprovalReviewCompletedNotification__NetworkApprovalProtocol; - readonly target: string; - readonly type: "networkAccess"; - } - | { - readonly connectorId?: string | null; - readonly connectorName?: string | null; - readonly server: string; - readonly toolName: string; - readonly toolTitle?: string | null; - readonly type: "mcpToolCall"; + readonly type: "special"; + readonly value: V2ItemGuardianApprovalReviewStartedNotification__FileSystemSpecialPath; }; -export const V2ItemGuardianApprovalReviewCompletedNotification__GuardianApprovalReviewAction = - Schema.Union( - [ - Schema.Struct({ - command: Schema.String, - cwd: Schema.String, - source: V2ItemGuardianApprovalReviewCompletedNotification__GuardianCommandSource, - type: Schema.Literal("command").annotate({ - title: "CommandGuardianApprovalReviewActionType", - }), - }).annotate({ title: "CommandGuardianApprovalReviewAction" }), - Schema.Struct({ - argv: Schema.Array(Schema.String), - cwd: Schema.String, - program: Schema.String, - source: V2ItemGuardianApprovalReviewCompletedNotification__GuardianCommandSource, - type: Schema.Literal("execve").annotate({ - title: "ExecveGuardianApprovalReviewActionType", - }), - }).annotate({ title: "ExecveGuardianApprovalReviewAction" }), - Schema.Struct({ - cwd: Schema.String, - files: Schema.Array(Schema.String), - type: Schema.Literal("applyPatch").annotate({ - title: "ApplyPatchGuardianApprovalReviewActionType", - }), - }).annotate({ title: "ApplyPatchGuardianApprovalReviewAction" }), - Schema.Struct({ - host: Schema.String, - port: Schema.Number.annotate({ format: "uint16" }) - .check(Schema.isInt()) - .check(Schema.isGreaterThanOrEqualTo(0)), - protocol: V2ItemGuardianApprovalReviewCompletedNotification__NetworkApprovalProtocol, - target: Schema.String, - type: Schema.Literal("networkAccess").annotate({ - title: "NetworkAccessGuardianApprovalReviewActionType", - }), - }).annotate({ title: "NetworkAccessGuardianApprovalReviewAction" }), - Schema.Struct({ - connectorId: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), - connectorName: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), - server: Schema.String, - toolName: Schema.String, - toolTitle: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), - type: Schema.Literal("mcpToolCall").annotate({ - title: "McpToolCallGuardianApprovalReviewActionType", - }), - }).annotate({ title: "McpToolCallGuardianApprovalReviewAction" }), - ], - { mode: "oneOf" }, - ); +export const V2ItemGuardianApprovalReviewStartedNotification__FileSystemPath = Schema.Union( + [ + Schema.Struct({ + path: V2ItemGuardianApprovalReviewStartedNotification__AbsolutePathBuf, + type: Schema.Literal("path").annotate({ title: "PathFileSystemPathType" }), + }).annotate({ title: "PathFileSystemPath" }), + Schema.Struct({ + pattern: Schema.String, + type: Schema.Literal("glob_pattern").annotate({ title: "GlobPatternFileSystemPathType" }), + }).annotate({ title: "GlobPatternFileSystemPath" }), + Schema.Struct({ + type: Schema.Literal("special").annotate({ title: "SpecialFileSystemPathType" }), + value: V2ItemGuardianApprovalReviewStartedNotification__FileSystemSpecialPath, + }).annotate({ title: "SpecialFileSystemPath" }), + ], + { mode: "oneOf" }, +); export type V2ItemGuardianApprovalReviewStartedNotification__GuardianApprovalReview = { readonly rationale?: string | null; @@ -11760,90 +12249,50 @@ export const V2ItemGuardianApprovalReviewStartedNotification__GuardianApprovalRe ), }).annotate({ description: - "[UNSTABLE] Temporary guardian approval review payload used by `item/autoApprovalReview/*` notifications. This shape is expected to change soon.", + "[UNSTABLE] Temporary approval auto-review payload used by `item/autoApprovalReview/*` notifications. This shape is expected to change soon.", }); -export type V2ItemGuardianApprovalReviewStartedNotification__GuardianApprovalReviewAction = +export type V2ItemStartedNotification__CommandAction = | { readonly command: string; - readonly cwd: string; - readonly source: V2ItemGuardianApprovalReviewStartedNotification__GuardianCommandSource; - readonly type: "command"; + readonly name: string; + readonly path: V2ItemStartedNotification__AbsolutePathBuf; + readonly type: "read"; } + | { readonly command: string; readonly path?: string | null; readonly type: "listFiles" } | { - readonly argv: ReadonlyArray; - readonly cwd: string; - readonly program: string; - readonly source: V2ItemGuardianApprovalReviewStartedNotification__GuardianCommandSource; - readonly type: "execve"; + readonly command: string; + readonly path?: string | null; + readonly query?: string | null; + readonly type: "search"; } - | { readonly cwd: string; readonly files: ReadonlyArray; readonly type: "applyPatch" } - | { - readonly host: string; - readonly port: number; - readonly protocol: V2ItemGuardianApprovalReviewStartedNotification__NetworkApprovalProtocol; - readonly target: string; - readonly type: "networkAccess"; - } - | { - readonly connectorId?: string | null; - readonly connectorName?: string | null; - readonly server: string; - readonly toolName: string; - readonly toolTitle?: string | null; - readonly type: "mcpToolCall"; - }; -export const V2ItemGuardianApprovalReviewStartedNotification__GuardianApprovalReviewAction = - Schema.Union( - [ - Schema.Struct({ - command: Schema.String, - cwd: Schema.String, - source: V2ItemGuardianApprovalReviewStartedNotification__GuardianCommandSource, - type: Schema.Literal("command").annotate({ - title: "CommandGuardianApprovalReviewActionType", - }), - }).annotate({ title: "CommandGuardianApprovalReviewAction" }), - Schema.Struct({ - argv: Schema.Array(Schema.String), - cwd: Schema.String, - program: Schema.String, - source: V2ItemGuardianApprovalReviewStartedNotification__GuardianCommandSource, - type: Schema.Literal("execve").annotate({ - title: "ExecveGuardianApprovalReviewActionType", - }), - }).annotate({ title: "ExecveGuardianApprovalReviewAction" }), - Schema.Struct({ - cwd: Schema.String, - files: Schema.Array(Schema.String), - type: Schema.Literal("applyPatch").annotate({ - title: "ApplyPatchGuardianApprovalReviewActionType", - }), - }).annotate({ title: "ApplyPatchGuardianApprovalReviewAction" }), - Schema.Struct({ - host: Schema.String, - port: Schema.Number.annotate({ format: "uint16" }) - .check(Schema.isInt()) - .check(Schema.isGreaterThanOrEqualTo(0)), - protocol: V2ItemGuardianApprovalReviewStartedNotification__NetworkApprovalProtocol, - target: Schema.String, - type: Schema.Literal("networkAccess").annotate({ - title: "NetworkAccessGuardianApprovalReviewActionType", - }), - }).annotate({ title: "NetworkAccessGuardianApprovalReviewAction" }), - Schema.Struct({ - connectorId: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), - connectorName: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), - server: Schema.String, - toolName: Schema.String, - toolTitle: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), - type: Schema.Literal("mcpToolCall").annotate({ - title: "McpToolCallGuardianApprovalReviewActionType", - }), - }).annotate({ title: "McpToolCallGuardianApprovalReviewAction" }), - ], - { mode: "oneOf" }, - ); + | { readonly command: string; readonly type: "unknown" }; +export const V2ItemStartedNotification__CommandAction = Schema.Union( + [ + Schema.Struct({ + command: Schema.String, + name: Schema.String, + path: V2ItemStartedNotification__AbsolutePathBuf, + type: Schema.Literal("read").annotate({ title: "ReadCommandActionType" }), + }).annotate({ title: "ReadCommandAction" }), + Schema.Struct({ + command: Schema.String, + path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + type: Schema.Literal("listFiles").annotate({ title: "ListFilesCommandActionType" }), + }).annotate({ title: "ListFilesCommandAction" }), + Schema.Struct({ + command: Schema.String, + path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + query: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + type: Schema.Literal("search").annotate({ title: "SearchCommandActionType" }), + }).annotate({ title: "SearchCommandAction" }), + Schema.Struct({ + command: Schema.String, + type: Schema.Literal("unknown").annotate({ title: "UnknownCommandActionType" }), + }).annotate({ title: "UnknownCommandAction" }), + ], + { mode: "oneOf" }, +); export type V2ItemStartedNotification__CollabAgentState = { readonly message?: string | null; @@ -11956,12 +12405,15 @@ export type V2PluginListResponse__PluginInterface = { readonly capabilities: ReadonlyArray; readonly category?: string | null; readonly composerIcon?: V2PluginListResponse__AbsolutePathBuf | null; + readonly composerIconUrl?: string | null; readonly defaultPrompt?: ReadonlyArray | null; readonly developerName?: string | null; readonly displayName?: string | null; readonly logo?: V2PluginListResponse__AbsolutePathBuf | null; + readonly logoUrl?: string | null; readonly longDescription?: string | null; readonly privacyPolicyUrl?: string | null; + readonly screenshotUrls: ReadonlyArray; readonly screenshots: ReadonlyArray; readonly shortDescription?: string | null; readonly termsOfServiceUrl?: string | null; @@ -11972,7 +12424,15 @@ export const V2PluginListResponse__PluginInterface = Schema.Struct({ capabilities: Schema.Array(Schema.String), category: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), composerIcon: Schema.optionalKey( - Schema.Union([V2PluginListResponse__AbsolutePathBuf, Schema.Null]), + Schema.Union([V2PluginListResponse__AbsolutePathBuf, Schema.Null]).annotate({ + description: "Local composer icon path, resolved from the installed plugin package.", + }), + ), + composerIconUrl: Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ description: "Remote composer icon URL from the plugin catalog." }), + Schema.Null, + ]), ), defaultPrompt: Schema.optionalKey( Schema.Union([ @@ -11985,25 +12445,60 @@ export const V2PluginListResponse__PluginInterface = Schema.Struct({ ), developerName: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), displayName: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), - logo: Schema.optionalKey(Schema.Union([V2PluginListResponse__AbsolutePathBuf, Schema.Null])), + logo: Schema.optionalKey( + Schema.Union([V2PluginListResponse__AbsolutePathBuf, Schema.Null]).annotate({ + description: "Local logo path, resolved from the installed plugin package.", + }), + ), + logoUrl: Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ description: "Remote logo URL from the plugin catalog." }), + Schema.Null, + ]), + ), longDescription: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), privacyPolicyUrl: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), - screenshots: Schema.Array(V2PluginListResponse__AbsolutePathBuf), + screenshotUrls: Schema.Array(Schema.String).annotate({ + description: "Remote screenshot URLs from the plugin catalog.", + }), + screenshots: Schema.Array(V2PluginListResponse__AbsolutePathBuf).annotate({ + description: "Local screenshot paths, resolved from the installed plugin package.", + }), shortDescription: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), termsOfServiceUrl: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), websiteUrl: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), }); -export type V2PluginListResponse__PluginSource = { - readonly path: V2PluginListResponse__AbsolutePathBuf; - readonly type: "local"; -}; +export type V2PluginListResponse__PluginSource = + | { readonly path: V2PluginListResponse__AbsolutePathBuf; readonly type: "local" } + | { + readonly path?: string | null; + readonly refName?: string | null; + readonly sha?: string | null; + readonly type: "git"; + readonly url: string; + } + | { readonly type: "remote" }; export const V2PluginListResponse__PluginSource = Schema.Union( [ Schema.Struct({ path: V2PluginListResponse__AbsolutePathBuf, type: Schema.Literal("local").annotate({ title: "LocalPluginSourceType" }), }).annotate({ title: "LocalPluginSource" }), + Schema.Struct({ + path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + refName: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + sha: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + type: Schema.Literal("git").annotate({ title: "GitPluginSourceType" }), + url: Schema.String, + }).annotate({ title: "GitPluginSource" }), + Schema.Struct({ + type: Schema.Literal("remote").annotate({ title: "RemotePluginSourceType" }), + }).annotate({ + title: "RemotePluginSource", + description: + "The plugin is available in the remote catalog. Download metadata is kept server-side and is not exposed through the app-server API.", + }), ], { mode: "oneOf" }, ); @@ -12013,12 +12508,15 @@ export type V2PluginReadResponse__PluginInterface = { readonly capabilities: ReadonlyArray; readonly category?: string | null; readonly composerIcon?: V2PluginReadResponse__AbsolutePathBuf | null; + readonly composerIconUrl?: string | null; readonly defaultPrompt?: ReadonlyArray | null; readonly developerName?: string | null; readonly displayName?: string | null; readonly logo?: V2PluginReadResponse__AbsolutePathBuf | null; + readonly logoUrl?: string | null; readonly longDescription?: string | null; readonly privacyPolicyUrl?: string | null; + readonly screenshotUrls: ReadonlyArray; readonly screenshots: ReadonlyArray; readonly shortDescription?: string | null; readonly termsOfServiceUrl?: string | null; @@ -12029,7 +12527,15 @@ export const V2PluginReadResponse__PluginInterface = Schema.Struct({ capabilities: Schema.Array(Schema.String), category: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), composerIcon: Schema.optionalKey( - Schema.Union([V2PluginReadResponse__AbsolutePathBuf, Schema.Null]), + Schema.Union([V2PluginReadResponse__AbsolutePathBuf, Schema.Null]).annotate({ + description: "Local composer icon path, resolved from the installed plugin package.", + }), + ), + composerIconUrl: Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ description: "Remote composer icon URL from the plugin catalog." }), + Schema.Null, + ]), ), defaultPrompt: Schema.optionalKey( Schema.Union([ @@ -12042,46 +12548,110 @@ export const V2PluginReadResponse__PluginInterface = Schema.Struct({ ), developerName: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), displayName: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), - logo: Schema.optionalKey(Schema.Union([V2PluginReadResponse__AbsolutePathBuf, Schema.Null])), + logo: Schema.optionalKey( + Schema.Union([V2PluginReadResponse__AbsolutePathBuf, Schema.Null]).annotate({ + description: "Local logo path, resolved from the installed plugin package.", + }), + ), + logoUrl: Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ description: "Remote logo URL from the plugin catalog." }), + Schema.Null, + ]), + ), longDescription: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), privacyPolicyUrl: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), - screenshots: Schema.Array(V2PluginReadResponse__AbsolutePathBuf), + screenshotUrls: Schema.Array(Schema.String).annotate({ + description: "Remote screenshot URLs from the plugin catalog.", + }), + screenshots: Schema.Array(V2PluginReadResponse__AbsolutePathBuf).annotate({ + description: "Local screenshot paths, resolved from the installed plugin package.", + }), shortDescription: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), termsOfServiceUrl: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), websiteUrl: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), }); -export type V2PluginReadResponse__PluginSource = { - readonly path: V2PluginReadResponse__AbsolutePathBuf; - readonly type: "local"; -}; +export type V2PluginReadResponse__PluginSource = + | { readonly path: V2PluginReadResponse__AbsolutePathBuf; readonly type: "local" } + | { + readonly path?: string | null; + readonly refName?: string | null; + readonly sha?: string | null; + readonly type: "git"; + readonly url: string; + } + | { readonly type: "remote" }; export const V2PluginReadResponse__PluginSource = Schema.Union( [ Schema.Struct({ path: V2PluginReadResponse__AbsolutePathBuf, type: Schema.Literal("local").annotate({ title: "LocalPluginSourceType" }), }).annotate({ title: "LocalPluginSource" }), + Schema.Struct({ + path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + refName: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + sha: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + type: Schema.Literal("git").annotate({ title: "GitPluginSourceType" }), + url: Schema.String, + }).annotate({ title: "GitPluginSource" }), + Schema.Struct({ + type: Schema.Literal("remote").annotate({ title: "RemotePluginSourceType" }), + }).annotate({ + title: "RemotePluginSource", + description: + "The plugin is available in the remote catalog. Download metadata is kept server-side and is not exposed through the app-server API.", + }), ], { mode: "oneOf" }, ); -export type V2PluginReadResponse__SkillSummary = { - readonly description: string; - readonly enabled: boolean; - readonly interface?: V2PluginReadResponse__SkillInterface | null; - readonly name: string; - readonly path: string; +export type V2PluginReadResponse__SkillInterface = { + readonly brandColor?: string | null; + readonly defaultPrompt?: string | null; + readonly displayName?: string | null; + readonly iconLarge?: V2PluginReadResponse__AbsolutePathBuf | null; + readonly iconSmall?: V2PluginReadResponse__AbsolutePathBuf | null; readonly shortDescription?: string | null; }; -export const V2PluginReadResponse__SkillSummary = Schema.Struct({ - description: Schema.String, - enabled: Schema.Boolean, - interface: Schema.optionalKey(Schema.Union([V2PluginReadResponse__SkillInterface, Schema.Null])), - name: Schema.String, - path: Schema.String, +export const V2PluginReadResponse__SkillInterface = Schema.Struct({ + brandColor: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + defaultPrompt: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + displayName: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + iconLarge: Schema.optionalKey(Schema.Union([V2PluginReadResponse__AbsolutePathBuf, Schema.Null])), + iconSmall: Schema.optionalKey(Schema.Union([V2PluginReadResponse__AbsolutePathBuf, Schema.Null])), shortDescription: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), }); +export type V2RawResponseItemCompletedNotification__ContentItem = + | { readonly text: string; readonly type: "input_text" } + | { + readonly detail?: V2RawResponseItemCompletedNotification__ImageDetail | null; + readonly image_url: string; + readonly type: "input_image"; + } + | { readonly text: string; readonly type: "output_text" }; +export const V2RawResponseItemCompletedNotification__ContentItem = Schema.Union( + [ + Schema.Struct({ + text: Schema.String, + type: Schema.Literal("input_text").annotate({ title: "InputTextContentItemType" }), + }).annotate({ title: "InputTextContentItem" }), + Schema.Struct({ + detail: Schema.optionalKey( + Schema.Union([V2RawResponseItemCompletedNotification__ImageDetail, Schema.Null]), + ), + image_url: Schema.String, + type: Schema.Literal("input_image").annotate({ title: "InputImageContentItemType" }), + }).annotate({ title: "InputImageContentItem" }), + Schema.Struct({ + text: Schema.String, + type: Schema.Literal("output_text").annotate({ title: "OutputTextContentItemType" }), + }).annotate({ title: "OutputTextContentItem" }), + ], + { mode: "oneOf" }, +); + export type V2RawResponseItemCompletedNotification__FunctionCallOutputContentItem = | { readonly text: string; readonly type: "input_text" } | { @@ -12113,6 +12683,48 @@ export const V2RawResponseItemCompletedNotification__FunctionCallOutputContentIt "Responses API compatible content items that can be returned by a tool call. This is a subset of ContentItem with the types we support as function call outputs.", }); +export type V2ReviewStartResponse__CommandAction = + | { + readonly command: string; + readonly name: string; + readonly path: V2ReviewStartResponse__AbsolutePathBuf; + readonly type: "read"; + } + | { readonly command: string; readonly path?: string | null; readonly type: "listFiles" } + | { + readonly command: string; + readonly path?: string | null; + readonly query?: string | null; + readonly type: "search"; + } + | { readonly command: string; readonly type: "unknown" }; +export const V2ReviewStartResponse__CommandAction = Schema.Union( + [ + Schema.Struct({ + command: Schema.String, + name: Schema.String, + path: V2ReviewStartResponse__AbsolutePathBuf, + type: Schema.Literal("read").annotate({ title: "ReadCommandActionType" }), + }).annotate({ title: "ReadCommandAction" }), + Schema.Struct({ + command: Schema.String, + path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + type: Schema.Literal("listFiles").annotate({ title: "ListFilesCommandActionType" }), + }).annotate({ title: "ListFilesCommandAction" }), + Schema.Struct({ + command: Schema.String, + path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + query: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + type: Schema.Literal("search").annotate({ title: "SearchCommandActionType" }), + }).annotate({ title: "SearchCommandAction" }), + Schema.Struct({ + command: Schema.String, + type: Schema.Literal("unknown").annotate({ title: "UnknownCommandActionType" }), + }).annotate({ title: "UnknownCommandAction" }), + ], + { mode: "oneOf" }, +); + export type V2ReviewStartResponse__CollabAgentState = { readonly message?: string | null; readonly status: V2ReviewStartResponse__CollabAgentStatus; @@ -12292,6 +12904,23 @@ export const V2ReviewStartResponse__UserInput = Schema.Union( { mode: "oneOf" }, ); +export type V2SkillsListResponse__SkillInterface = { + readonly brandColor?: string | null; + readonly defaultPrompt?: string | null; + readonly displayName?: string | null; + readonly iconLarge?: V2SkillsListResponse__AbsolutePathBuf | null; + readonly iconSmall?: V2SkillsListResponse__AbsolutePathBuf | null; + readonly shortDescription?: string | null; +}; +export const V2SkillsListResponse__SkillInterface = Schema.Struct({ + brandColor: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + defaultPrompt: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + displayName: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + iconLarge: Schema.optionalKey(Schema.Union([V2SkillsListResponse__AbsolutePathBuf, Schema.Null])), + iconSmall: Schema.optionalKey(Schema.Union([V2SkillsListResponse__AbsolutePathBuf, Schema.Null])), + shortDescription: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), +}); + export type V2SkillsListResponse__SkillDependencies = { readonly tools: ReadonlyArray; }; @@ -12299,6 +12928,48 @@ export const V2SkillsListResponse__SkillDependencies = Schema.Struct({ tools: Schema.Array(V2SkillsListResponse__SkillToolDependency), }); +export type V2ThreadForkResponse__CommandAction = + | { + readonly command: string; + readonly name: string; + readonly path: V2ThreadForkResponse__AbsolutePathBuf; + readonly type: "read"; + } + | { readonly command: string; readonly path?: string | null; readonly type: "listFiles" } + | { + readonly command: string; + readonly path?: string | null; + readonly query?: string | null; + readonly type: "search"; + } + | { readonly command: string; readonly type: "unknown" }; +export const V2ThreadForkResponse__CommandAction = Schema.Union( + [ + Schema.Struct({ + command: Schema.String, + name: Schema.String, + path: V2ThreadForkResponse__AbsolutePathBuf, + type: Schema.Literal("read").annotate({ title: "ReadCommandActionType" }), + }).annotate({ title: "ReadCommandAction" }), + Schema.Struct({ + command: Schema.String, + path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + type: Schema.Literal("listFiles").annotate({ title: "ListFilesCommandActionType" }), + }).annotate({ title: "ListFilesCommandAction" }), + Schema.Struct({ + command: Schema.String, + path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + query: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + type: Schema.Literal("search").annotate({ title: "SearchCommandActionType" }), + }).annotate({ title: "SearchCommandAction" }), + Schema.Struct({ + command: Schema.String, + type: Schema.Literal("unknown").annotate({ title: "UnknownCommandActionType" }), + }).annotate({ title: "UnknownCommandAction" }), + ], + { mode: "oneOf" }, +); + export type V2ThreadForkResponse__SandboxPolicy = | { readonly type: "dangerFullAccess" } | { @@ -12617,6 +13288,48 @@ export const V2ThreadForkResponse__SubAgentSource = Schema.Union( { mode: "oneOf" }, ); +export type V2ThreadListResponse__CommandAction = + | { + readonly command: string; + readonly name: string; + readonly path: V2ThreadListResponse__AbsolutePathBuf; + readonly type: "read"; + } + | { readonly command: string; readonly path?: string | null; readonly type: "listFiles" } + | { + readonly command: string; + readonly path?: string | null; + readonly query?: string | null; + readonly type: "search"; + } + | { readonly command: string; readonly type: "unknown" }; +export const V2ThreadListResponse__CommandAction = Schema.Union( + [ + Schema.Struct({ + command: Schema.String, + name: Schema.String, + path: V2ThreadListResponse__AbsolutePathBuf, + type: Schema.Literal("read").annotate({ title: "ReadCommandActionType" }), + }).annotate({ title: "ReadCommandAction" }), + Schema.Struct({ + command: Schema.String, + path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + type: Schema.Literal("listFiles").annotate({ title: "ListFilesCommandActionType" }), + }).annotate({ title: "ListFilesCommandAction" }), + Schema.Struct({ + command: Schema.String, + path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + query: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + type: Schema.Literal("search").annotate({ title: "SearchCommandActionType" }), + }).annotate({ title: "SearchCommandAction" }), + Schema.Struct({ + command: Schema.String, + type: Schema.Literal("unknown").annotate({ title: "UnknownCommandActionType" }), + }).annotate({ title: "UnknownCommandAction" }), + ], + { mode: "oneOf" }, +); + export type V2ThreadListResponse__CollabAgentState = { readonly message?: string | null; readonly status: V2ThreadListResponse__CollabAgentStatus; @@ -12829,6 +13542,48 @@ export const V2ThreadListResponse__SubAgentSource = Schema.Union( { mode: "oneOf" }, ); +export type V2ThreadMetadataUpdateResponse__CommandAction = + | { + readonly command: string; + readonly name: string; + readonly path: V2ThreadMetadataUpdateResponse__AbsolutePathBuf; + readonly type: "read"; + } + | { readonly command: string; readonly path?: string | null; readonly type: "listFiles" } + | { + readonly command: string; + readonly path?: string | null; + readonly query?: string | null; + readonly type: "search"; + } + | { readonly command: string; readonly type: "unknown" }; +export const V2ThreadMetadataUpdateResponse__CommandAction = Schema.Union( + [ + Schema.Struct({ + command: Schema.String, + name: Schema.String, + path: V2ThreadMetadataUpdateResponse__AbsolutePathBuf, + type: Schema.Literal("read").annotate({ title: "ReadCommandActionType" }), + }).annotate({ title: "ReadCommandAction" }), + Schema.Struct({ + command: Schema.String, + path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + type: Schema.Literal("listFiles").annotate({ title: "ListFilesCommandActionType" }), + }).annotate({ title: "ListFilesCommandAction" }), + Schema.Struct({ + command: Schema.String, + path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + query: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + type: Schema.Literal("search").annotate({ title: "SearchCommandActionType" }), + }).annotate({ title: "SearchCommandAction" }), + Schema.Struct({ + command: Schema.String, + type: Schema.Literal("unknown").annotate({ title: "UnknownCommandActionType" }), + }).annotate({ title: "UnknownCommandAction" }), + ], + { mode: "oneOf" }, +); + export type V2ThreadMetadataUpdateResponse__CollabAgentState = { readonly message?: string | null; readonly status: V2ThreadMetadataUpdateResponse__CollabAgentStatus; @@ -13041,6 +13796,48 @@ export const V2ThreadMetadataUpdateResponse__SubAgentSource = Schema.Union( { mode: "oneOf" }, ); +export type V2ThreadReadResponse__CommandAction = + | { + readonly command: string; + readonly name: string; + readonly path: V2ThreadReadResponse__AbsolutePathBuf; + readonly type: "read"; + } + | { readonly command: string; readonly path?: string | null; readonly type: "listFiles" } + | { + readonly command: string; + readonly path?: string | null; + readonly query?: string | null; + readonly type: "search"; + } + | { readonly command: string; readonly type: "unknown" }; +export const V2ThreadReadResponse__CommandAction = Schema.Union( + [ + Schema.Struct({ + command: Schema.String, + name: Schema.String, + path: V2ThreadReadResponse__AbsolutePathBuf, + type: Schema.Literal("read").annotate({ title: "ReadCommandActionType" }), + }).annotate({ title: "ReadCommandAction" }), + Schema.Struct({ + command: Schema.String, + path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + type: Schema.Literal("listFiles").annotate({ title: "ListFilesCommandActionType" }), + }).annotate({ title: "ListFilesCommandAction" }), + Schema.Struct({ + command: Schema.String, + path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + query: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + type: Schema.Literal("search").annotate({ title: "SearchCommandActionType" }), + }).annotate({ title: "SearchCommandAction" }), + Schema.Struct({ + command: Schema.String, + type: Schema.Literal("unknown").annotate({ title: "UnknownCommandActionType" }), + }).annotate({ title: "UnknownCommandAction" }), + ], + { mode: "oneOf" }, +); + export type V2ThreadReadResponse__CollabAgentState = { readonly message?: string | null; readonly status: V2ThreadReadResponse__CollabAgentStatus; @@ -13253,6 +14050,33 @@ export const V2ThreadReadResponse__SubAgentSource = Schema.Union( { mode: "oneOf" }, ); +export type V2ThreadResumeParams__ContentItem = + | { readonly text: string; readonly type: "input_text" } + | { + readonly detail?: V2ThreadResumeParams__ImageDetail | null; + readonly image_url: string; + readonly type: "input_image"; + } + | { readonly text: string; readonly type: "output_text" }; +export const V2ThreadResumeParams__ContentItem = Schema.Union( + [ + Schema.Struct({ + text: Schema.String, + type: Schema.Literal("input_text").annotate({ title: "InputTextContentItemType" }), + }).annotate({ title: "InputTextContentItem" }), + Schema.Struct({ + detail: Schema.optionalKey(Schema.Union([V2ThreadResumeParams__ImageDetail, Schema.Null])), + image_url: Schema.String, + type: Schema.Literal("input_image").annotate({ title: "InputImageContentItemType" }), + }).annotate({ title: "InputImageContentItem" }), + Schema.Struct({ + text: Schema.String, + type: Schema.Literal("output_text").annotate({ title: "OutputTextContentItemType" }), + }).annotate({ title: "OutputTextContentItem" }), + ], + { mode: "oneOf" }, +); + export type V2ThreadResumeParams__FunctionCallOutputContentItem = | { readonly text: string; readonly type: "input_text" } | { @@ -13282,6 +14106,48 @@ export const V2ThreadResumeParams__FunctionCallOutputContentItem = Schema.Union( "Responses API compatible content items that can be returned by a tool call. This is a subset of ContentItem with the types we support as function call outputs.", }); +export type V2ThreadResumeResponse__CommandAction = + | { + readonly command: string; + readonly name: string; + readonly path: V2ThreadResumeResponse__AbsolutePathBuf; + readonly type: "read"; + } + | { readonly command: string; readonly path?: string | null; readonly type: "listFiles" } + | { + readonly command: string; + readonly path?: string | null; + readonly query?: string | null; + readonly type: "search"; + } + | { readonly command: string; readonly type: "unknown" }; +export const V2ThreadResumeResponse__CommandAction = Schema.Union( + [ + Schema.Struct({ + command: Schema.String, + name: Schema.String, + path: V2ThreadResumeResponse__AbsolutePathBuf, + type: Schema.Literal("read").annotate({ title: "ReadCommandActionType" }), + }).annotate({ title: "ReadCommandAction" }), + Schema.Struct({ + command: Schema.String, + path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + type: Schema.Literal("listFiles").annotate({ title: "ListFilesCommandActionType" }), + }).annotate({ title: "ListFilesCommandAction" }), + Schema.Struct({ + command: Schema.String, + path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + query: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + type: Schema.Literal("search").annotate({ title: "SearchCommandActionType" }), + }).annotate({ title: "SearchCommandAction" }), + Schema.Struct({ + command: Schema.String, + type: Schema.Literal("unknown").annotate({ title: "UnknownCommandActionType" }), + }).annotate({ title: "UnknownCommandAction" }), + ], + { mode: "oneOf" }, +); + export type V2ThreadResumeResponse__SandboxPolicy = | { readonly type: "dangerFullAccess" } | { @@ -13600,6 +14466,48 @@ export const V2ThreadResumeResponse__SubAgentSource = Schema.Union( { mode: "oneOf" }, ); +export type V2ThreadRollbackResponse__CommandAction = + | { + readonly command: string; + readonly name: string; + readonly path: V2ThreadRollbackResponse__AbsolutePathBuf; + readonly type: "read"; + } + | { readonly command: string; readonly path?: string | null; readonly type: "listFiles" } + | { + readonly command: string; + readonly path?: string | null; + readonly query?: string | null; + readonly type: "search"; + } + | { readonly command: string; readonly type: "unknown" }; +export const V2ThreadRollbackResponse__CommandAction = Schema.Union( + [ + Schema.Struct({ + command: Schema.String, + name: Schema.String, + path: V2ThreadRollbackResponse__AbsolutePathBuf, + type: Schema.Literal("read").annotate({ title: "ReadCommandActionType" }), + }).annotate({ title: "ReadCommandAction" }), + Schema.Struct({ + command: Schema.String, + path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + type: Schema.Literal("listFiles").annotate({ title: "ListFilesCommandActionType" }), + }).annotate({ title: "ListFilesCommandAction" }), + Schema.Struct({ + command: Schema.String, + path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + query: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + type: Schema.Literal("search").annotate({ title: "SearchCommandActionType" }), + }).annotate({ title: "SearchCommandAction" }), + Schema.Struct({ + command: Schema.String, + type: Schema.Literal("unknown").annotate({ title: "UnknownCommandActionType" }), + }).annotate({ title: "UnknownCommandAction" }), + ], + { mode: "oneOf" }, +); + export type V2ThreadRollbackResponse__CollabAgentState = { readonly message?: string | null; readonly status: V2ThreadRollbackResponse__CollabAgentStatus; @@ -13812,6 +14720,48 @@ export const V2ThreadRollbackResponse__SubAgentSource = Schema.Union( { mode: "oneOf" }, ); +export type V2ThreadStartedNotification__CommandAction = + | { + readonly command: string; + readonly name: string; + readonly path: V2ThreadStartedNotification__AbsolutePathBuf; + readonly type: "read"; + } + | { readonly command: string; readonly path?: string | null; readonly type: "listFiles" } + | { + readonly command: string; + readonly path?: string | null; + readonly query?: string | null; + readonly type: "search"; + } + | { readonly command: string; readonly type: "unknown" }; +export const V2ThreadStartedNotification__CommandAction = Schema.Union( + [ + Schema.Struct({ + command: Schema.String, + name: Schema.String, + path: V2ThreadStartedNotification__AbsolutePathBuf, + type: Schema.Literal("read").annotate({ title: "ReadCommandActionType" }), + }).annotate({ title: "ReadCommandAction" }), + Schema.Struct({ + command: Schema.String, + path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + type: Schema.Literal("listFiles").annotate({ title: "ListFilesCommandActionType" }), + }).annotate({ title: "ListFilesCommandAction" }), + Schema.Struct({ + command: Schema.String, + path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + query: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + type: Schema.Literal("search").annotate({ title: "SearchCommandActionType" }), + }).annotate({ title: "SearchCommandAction" }), + Schema.Struct({ + command: Schema.String, + type: Schema.Literal("unknown").annotate({ title: "UnknownCommandActionType" }), + }).annotate({ title: "UnknownCommandAction" }), + ], + { mode: "oneOf" }, +); + export type V2ThreadStartedNotification__CollabAgentState = { readonly message?: string | null; readonly status: V2ThreadStartedNotification__CollabAgentStatus; @@ -14024,6 +14974,48 @@ export const V2ThreadStartedNotification__SubAgentSource = Schema.Union( { mode: "oneOf" }, ); +export type V2ThreadStartResponse__CommandAction = + | { + readonly command: string; + readonly name: string; + readonly path: V2ThreadStartResponse__AbsolutePathBuf; + readonly type: "read"; + } + | { readonly command: string; readonly path?: string | null; readonly type: "listFiles" } + | { + readonly command: string; + readonly path?: string | null; + readonly query?: string | null; + readonly type: "search"; + } + | { readonly command: string; readonly type: "unknown" }; +export const V2ThreadStartResponse__CommandAction = Schema.Union( + [ + Schema.Struct({ + command: Schema.String, + name: Schema.String, + path: V2ThreadStartResponse__AbsolutePathBuf, + type: Schema.Literal("read").annotate({ title: "ReadCommandActionType" }), + }).annotate({ title: "ReadCommandAction" }), + Schema.Struct({ + command: Schema.String, + path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + type: Schema.Literal("listFiles").annotate({ title: "ListFilesCommandActionType" }), + }).annotate({ title: "ListFilesCommandAction" }), + Schema.Struct({ + command: Schema.String, + path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + query: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + type: Schema.Literal("search").annotate({ title: "SearchCommandActionType" }), + }).annotate({ title: "SearchCommandAction" }), + Schema.Struct({ + command: Schema.String, + type: Schema.Literal("unknown").annotate({ title: "UnknownCommandActionType" }), + }).annotate({ title: "UnknownCommandAction" }), + ], + { mode: "oneOf" }, +); + export type V2ThreadStartResponse__SandboxPolicy = | { readonly type: "dangerFullAccess" } | { @@ -14382,6 +15374,269 @@ export const V2ThreadTokenUsageUpdatedNotification__ThreadTokenUsage = Schema.St total: V2ThreadTokenUsageUpdatedNotification__TokenUsageBreakdown, }); +export type V2ThreadTurnsListResponse__CommandAction = + | { + readonly command: string; + readonly name: string; + readonly path: V2ThreadTurnsListResponse__AbsolutePathBuf; + readonly type: "read"; + } + | { readonly command: string; readonly path?: string | null; readonly type: "listFiles" } + | { + readonly command: string; + readonly path?: string | null; + readonly query?: string | null; + readonly type: "search"; + } + | { readonly command: string; readonly type: "unknown" }; +export const V2ThreadTurnsListResponse__CommandAction = Schema.Union( + [ + Schema.Struct({ + command: Schema.String, + name: Schema.String, + path: V2ThreadTurnsListResponse__AbsolutePathBuf, + type: Schema.Literal("read").annotate({ title: "ReadCommandActionType" }), + }).annotate({ title: "ReadCommandAction" }), + Schema.Struct({ + command: Schema.String, + path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + type: Schema.Literal("listFiles").annotate({ title: "ListFilesCommandActionType" }), + }).annotate({ title: "ListFilesCommandAction" }), + Schema.Struct({ + command: Schema.String, + path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + query: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + type: Schema.Literal("search").annotate({ title: "SearchCommandActionType" }), + }).annotate({ title: "SearchCommandAction" }), + Schema.Struct({ + command: Schema.String, + type: Schema.Literal("unknown").annotate({ title: "UnknownCommandActionType" }), + }).annotate({ title: "UnknownCommandAction" }), + ], + { mode: "oneOf" }, +); + +export type V2ThreadTurnsListResponse__CollabAgentState = { + readonly message?: string | null; + readonly status: V2ThreadTurnsListResponse__CollabAgentStatus; +}; +export const V2ThreadTurnsListResponse__CollabAgentState = Schema.Struct({ + message: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + status: V2ThreadTurnsListResponse__CollabAgentStatus, +}); + +export type V2ThreadTurnsListResponse__MemoryCitation = { + readonly entries: ReadonlyArray; + readonly threadIds: ReadonlyArray; +}; +export const V2ThreadTurnsListResponse__MemoryCitation = Schema.Struct({ + entries: Schema.Array(V2ThreadTurnsListResponse__MemoryCitationEntry), + threadIds: Schema.Array(Schema.String), +}); + +export type V2ThreadTurnsListResponse__CodexErrorInfo = + | "contextWindowExceeded" + | "usageLimitExceeded" + | "serverOverloaded" + | "internalServerError" + | "unauthorized" + | "badRequest" + | "threadRollbackFailed" + | "sandboxError" + | "other" + | { readonly httpConnectionFailed: { readonly httpStatusCode?: number | null } } + | { readonly responseStreamConnectionFailed: { readonly httpStatusCode?: number | null } } + | { readonly responseStreamDisconnected: { readonly httpStatusCode?: number | null } } + | { readonly responseTooManyFailedAttempts: { readonly httpStatusCode?: number | null } } + | { + readonly activeTurnNotSteerable: { + readonly turnKind: V2ThreadTurnsListResponse__NonSteerableTurnKind; + }; + }; +export const V2ThreadTurnsListResponse__CodexErrorInfo = Schema.Union( + [ + Schema.Literals([ + "contextWindowExceeded", + "usageLimitExceeded", + "serverOverloaded", + "internalServerError", + "unauthorized", + "badRequest", + "threadRollbackFailed", + "sandboxError", + "other", + ]), + Schema.Struct({ + httpConnectionFailed: Schema.Struct({ + httpStatusCode: Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ format: "uint16" }) + .check(Schema.isInt()) + .check(Schema.isGreaterThanOrEqualTo(0)), + Schema.Null, + ]), + ), + }), + }).annotate({ title: "HttpConnectionFailedCodexErrorInfo" }), + Schema.Struct({ + responseStreamConnectionFailed: Schema.Struct({ + httpStatusCode: Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ format: "uint16" }) + .check(Schema.isInt()) + .check(Schema.isGreaterThanOrEqualTo(0)), + Schema.Null, + ]), + ), + }), + }).annotate({ + title: "ResponseStreamConnectionFailedCodexErrorInfo", + description: "Failed to connect to the response SSE stream.", + }), + Schema.Struct({ + responseStreamDisconnected: Schema.Struct({ + httpStatusCode: Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ format: "uint16" }) + .check(Schema.isInt()) + .check(Schema.isGreaterThanOrEqualTo(0)), + Schema.Null, + ]), + ), + }), + }).annotate({ + title: "ResponseStreamDisconnectedCodexErrorInfo", + description: + "The response SSE stream disconnected in the middle of a turn before completion.", + }), + Schema.Struct({ + responseTooManyFailedAttempts: Schema.Struct({ + httpStatusCode: Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ format: "uint16" }) + .check(Schema.isInt()) + .check(Schema.isGreaterThanOrEqualTo(0)), + Schema.Null, + ]), + ), + }), + }).annotate({ + title: "ResponseTooManyFailedAttemptsCodexErrorInfo", + description: "Reached the retry limit for responses.", + }), + Schema.Struct({ + activeTurnNotSteerable: Schema.Struct({ + turnKind: V2ThreadTurnsListResponse__NonSteerableTurnKind, + }), + }).annotate({ + title: "ActiveTurnNotSteerableCodexErrorInfo", + description: + "Returned when `turn/start` or `turn/steer` is submitted while the current active turn cannot accept same-turn steering, for example `/review` or manual `/compact`.", + }), + ], + { mode: "oneOf" }, +).annotate({ + description: + "This translation layer make sure that we expose codex error code in camel case.\n\nWhen an upstream HTTP status is available (for example, from the Responses API or a provider), it is forwarded in `httpStatusCode` on the relevant `codexErrorInfo` variant.", +}); + +export type V2ThreadTurnsListResponse__FileUpdateChange = { + readonly diff: string; + readonly kind: V2ThreadTurnsListResponse__PatchChangeKind; + readonly path: string; +}; +export const V2ThreadTurnsListResponse__FileUpdateChange = Schema.Struct({ + diff: Schema.String, + kind: V2ThreadTurnsListResponse__PatchChangeKind, + path: Schema.String, +}); + +export type V2ThreadTurnsListResponse__UserInput = + | { + readonly text: string; + readonly text_elements?: ReadonlyArray; + readonly type: "text"; + } + | { readonly type: "image"; readonly url: string } + | { readonly path: string; readonly type: "localImage" } + | { readonly name: string; readonly path: string; readonly type: "skill" } + | { readonly name: string; readonly path: string; readonly type: "mention" }; +export const V2ThreadTurnsListResponse__UserInput = Schema.Union( + [ + Schema.Struct({ + text: Schema.String, + text_elements: Schema.optionalKey( + Schema.Array(V2ThreadTurnsListResponse__TextElement).annotate({ + description: "UI-defined spans within `text` used to render or persist special elements.", + default: [], + }), + ), + type: Schema.Literal("text").annotate({ title: "TextUserInputType" }), + }).annotate({ title: "TextUserInput" }), + Schema.Struct({ + type: Schema.Literal("image").annotate({ title: "ImageUserInputType" }), + url: Schema.String, + }).annotate({ title: "ImageUserInput" }), + Schema.Struct({ + path: Schema.String, + type: Schema.Literal("localImage").annotate({ title: "LocalImageUserInputType" }), + }).annotate({ title: "LocalImageUserInput" }), + Schema.Struct({ + name: Schema.String, + path: Schema.String, + type: Schema.Literal("skill").annotate({ title: "SkillUserInputType" }), + }).annotate({ title: "SkillUserInput" }), + Schema.Struct({ + name: Schema.String, + path: Schema.String, + type: Schema.Literal("mention").annotate({ title: "MentionUserInputType" }), + }).annotate({ title: "MentionUserInput" }), + ], + { mode: "oneOf" }, +); + +export type V2ThreadUnarchiveResponse__CommandAction = + | { + readonly command: string; + readonly name: string; + readonly path: V2ThreadUnarchiveResponse__AbsolutePathBuf; + readonly type: "read"; + } + | { readonly command: string; readonly path?: string | null; readonly type: "listFiles" } + | { + readonly command: string; + readonly path?: string | null; + readonly query?: string | null; + readonly type: "search"; + } + | { readonly command: string; readonly type: "unknown" }; +export const V2ThreadUnarchiveResponse__CommandAction = Schema.Union( + [ + Schema.Struct({ + command: Schema.String, + name: Schema.String, + path: V2ThreadUnarchiveResponse__AbsolutePathBuf, + type: Schema.Literal("read").annotate({ title: "ReadCommandActionType" }), + }).annotate({ title: "ReadCommandAction" }), + Schema.Struct({ + command: Schema.String, + path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + type: Schema.Literal("listFiles").annotate({ title: "ListFilesCommandActionType" }), + }).annotate({ title: "ListFilesCommandAction" }), + Schema.Struct({ + command: Schema.String, + path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + query: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + type: Schema.Literal("search").annotate({ title: "SearchCommandActionType" }), + }).annotate({ title: "SearchCommandAction" }), + Schema.Struct({ + command: Schema.String, + type: Schema.Literal("unknown").annotate({ title: "UnknownCommandActionType" }), + }).annotate({ title: "UnknownCommandAction" }), + ], + { mode: "oneOf" }, +); + export type V2ThreadUnarchiveResponse__CollabAgentState = { readonly message?: string | null; readonly status: V2ThreadUnarchiveResponse__CollabAgentStatus; @@ -14594,6 +15849,48 @@ export const V2ThreadUnarchiveResponse__SubAgentSource = Schema.Union( { mode: "oneOf" }, ); +export type V2TurnCompletedNotification__CommandAction = + | { + readonly command: string; + readonly name: string; + readonly path: V2TurnCompletedNotification__AbsolutePathBuf; + readonly type: "read"; + } + | { readonly command: string; readonly path?: string | null; readonly type: "listFiles" } + | { + readonly command: string; + readonly path?: string | null; + readonly query?: string | null; + readonly type: "search"; + } + | { readonly command: string; readonly type: "unknown" }; +export const V2TurnCompletedNotification__CommandAction = Schema.Union( + [ + Schema.Struct({ + command: Schema.String, + name: Schema.String, + path: V2TurnCompletedNotification__AbsolutePathBuf, + type: Schema.Literal("read").annotate({ title: "ReadCommandActionType" }), + }).annotate({ title: "ReadCommandAction" }), + Schema.Struct({ + command: Schema.String, + path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + type: Schema.Literal("listFiles").annotate({ title: "ListFilesCommandActionType" }), + }).annotate({ title: "ListFilesCommandAction" }), + Schema.Struct({ + command: Schema.String, + path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + query: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + type: Schema.Literal("search").annotate({ title: "SearchCommandActionType" }), + }).annotate({ title: "SearchCommandAction" }), + Schema.Struct({ + command: Schema.String, + type: Schema.Literal("unknown").annotate({ title: "UnknownCommandActionType" }), + }).annotate({ title: "UnknownCommandAction" }), + ], + { mode: "oneOf" }, +); + export type V2TurnCompletedNotification__CollabAgentState = { readonly message?: string | null; readonly status: V2TurnCompletedNotification__CollabAgentStatus; @@ -14782,6 +16079,48 @@ export const V2TurnPlanUpdatedNotification__TurnPlanStep = Schema.Struct({ step: Schema.String, }); +export type V2TurnStartedNotification__CommandAction = + | { + readonly command: string; + readonly name: string; + readonly path: V2TurnStartedNotification__AbsolutePathBuf; + readonly type: "read"; + } + | { readonly command: string; readonly path?: string | null; readonly type: "listFiles" } + | { + readonly command: string; + readonly path?: string | null; + readonly query?: string | null; + readonly type: "search"; + } + | { readonly command: string; readonly type: "unknown" }; +export const V2TurnStartedNotification__CommandAction = Schema.Union( + [ + Schema.Struct({ + command: Schema.String, + name: Schema.String, + path: V2TurnStartedNotification__AbsolutePathBuf, + type: Schema.Literal("read").annotate({ title: "ReadCommandActionType" }), + }).annotate({ title: "ReadCommandAction" }), + Schema.Struct({ + command: Schema.String, + path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + type: Schema.Literal("listFiles").annotate({ title: "ListFilesCommandActionType" }), + }).annotate({ title: "ListFilesCommandAction" }), + Schema.Struct({ + command: Schema.String, + path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + query: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + type: Schema.Literal("search").annotate({ title: "SearchCommandActionType" }), + }).annotate({ title: "SearchCommandAction" }), + Schema.Struct({ + command: Schema.String, + type: Schema.Literal("unknown").annotate({ title: "UnknownCommandActionType" }), + }).annotate({ title: "UnknownCommandAction" }), + ], + { mode: "oneOf" }, +); + export type V2TurnStartedNotification__CollabAgentState = { readonly message?: string | null; readonly status: V2TurnStartedNotification__CollabAgentStatus; @@ -15124,6 +16463,48 @@ export const V2TurnStartParams__UserInput = Schema.Union( { mode: "oneOf" }, ); +export type V2TurnStartResponse__CommandAction = + | { + readonly command: string; + readonly name: string; + readonly path: V2TurnStartResponse__AbsolutePathBuf; + readonly type: "read"; + } + | { readonly command: string; readonly path?: string | null; readonly type: "listFiles" } + | { + readonly command: string; + readonly path?: string | null; + readonly query?: string | null; + readonly type: "search"; + } + | { readonly command: string; readonly type: "unknown" }; +export const V2TurnStartResponse__CommandAction = Schema.Union( + [ + Schema.Struct({ + command: Schema.String, + name: Schema.String, + path: V2TurnStartResponse__AbsolutePathBuf, + type: Schema.Literal("read").annotate({ title: "ReadCommandActionType" }), + }).annotate({ title: "ReadCommandAction" }), + Schema.Struct({ + command: Schema.String, + path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + type: Schema.Literal("listFiles").annotate({ title: "ListFilesCommandActionType" }), + }).annotate({ title: "ListFilesCommandAction" }), + Schema.Struct({ + command: Schema.String, + path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + query: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + type: Schema.Literal("search").annotate({ title: "SearchCommandActionType" }), + }).annotate({ title: "SearchCommandAction" }), + Schema.Struct({ + command: Schema.String, + type: Schema.Literal("unknown").annotate({ title: "UnknownCommandActionType" }), + }).annotate({ title: "UnknownCommandAction" }), + ], + { mode: "oneOf" }, +); + export type V2TurnStartResponse__CollabAgentState = { readonly message?: string | null; readonly status: V2TurnStartResponse__CollabAgentStatus; @@ -15517,13 +16898,6 @@ export const ClientRequest__CommandExecParams = Schema.Struct({ "Run a standalone command (argv vector) in the server sandbox without creating a thread or turn.\n\nThe final `command/exec` response is deferred until the process exits and is sent only after all `command/exec/outputDelta` notifications for that connection have been emitted.", }); -export type ClientRequest__ExternalAgentConfigImportParams = { - readonly migrationItems: ReadonlyArray; -}; -export const ClientRequest__ExternalAgentConfigImportParams = Schema.Struct({ - migrationItems: Schema.Array(ClientRequest__ExternalAgentConfigMigrationItem), -}); - export type ClientRequest__FunctionCallOutputBody = | string | ReadonlyArray; @@ -15558,6 +16932,38 @@ export const ClientRequest__ConfigBatchWriteParams = Schema.Struct({ ), }); +export type ClientRequest__ExternalAgentConfigMigrationItem = { + readonly cwd?: string | null; + readonly description: string; + readonly details?: ClientRequest__MigrationDetails | null; + readonly itemType: ClientRequest__ExternalAgentConfigMigrationItemType; +}; +export const ClientRequest__ExternalAgentConfigMigrationItem = Schema.Struct({ + cwd: Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + description: + "Null or empty means home-scoped migration; non-empty means repo-scoped migration.", + }), + Schema.Null, + ]), + ), + description: Schema.String, + details: Schema.optionalKey(Schema.Union([ClientRequest__MigrationDetails, Schema.Null])), + itemType: ClientRequest__ExternalAgentConfigMigrationItemType, +}); + +export type ClientRequest__DeviceKeySignParams = { + readonly keyId: string; + readonly payload: ClientRequest__DeviceKeySignPayload; +}; +export const ClientRequest__DeviceKeySignParams = Schema.Struct({ + keyId: Schema.String, + payload: ClientRequest__DeviceKeySignPayload, +}).annotate({ + description: "Sign an accepted structured payload with a controller-local device key.", +}); + export type ClientRequest__TurnStartParams = { readonly approvalPolicy?: ClientRequest__AskForApproval | null; readonly approvalsReviewer?: ClientRequest__ApprovalsReviewer | null; @@ -15649,6 +17055,15 @@ export const ClientRequest__TurnSteerParams = Schema.Struct({ threadId: Schema.String, }); +export type CommandExecutionRequestApprovalParams__FileSystemSandboxEntry = { + readonly access: CommandExecutionRequestApprovalParams__FileSystemAccessMode; + readonly path: CommandExecutionRequestApprovalParams__FileSystemPath; +}; +export const CommandExecutionRequestApprovalParams__FileSystemSandboxEntry = Schema.Struct({ + access: CommandExecutionRequestApprovalParams__FileSystemAccessMode, + path: CommandExecutionRequestApprovalParams__FileSystemPath, +}); + export type CommandExecutionRequestApprovalResponse__CommandExecutionApprovalDecision = | "accept" | "acceptForSession" @@ -15835,33 +17250,22 @@ export const McpServerElicitationRequestParams__McpElicitationSingleSelectEnumSc ], ); -export type PermissionsRequestApprovalParams__RequestPermissionProfile = { - readonly fileSystem?: PermissionsRequestApprovalParams__AdditionalFileSystemPermissions | null; - readonly network?: PermissionsRequestApprovalParams__AdditionalNetworkPermissions | null; +export type PermissionsRequestApprovalParams__FileSystemSandboxEntry = { + readonly access: PermissionsRequestApprovalParams__FileSystemAccessMode; + readonly path: PermissionsRequestApprovalParams__FileSystemPath; }; -export const PermissionsRequestApprovalParams__RequestPermissionProfile = Schema.Struct({ - fileSystem: Schema.optionalKey( - Schema.Union([PermissionsRequestApprovalParams__AdditionalFileSystemPermissions, Schema.Null]), - ), - network: Schema.optionalKey( - Schema.Union([PermissionsRequestApprovalParams__AdditionalNetworkPermissions, Schema.Null]), - ), +export const PermissionsRequestApprovalParams__FileSystemSandboxEntry = Schema.Struct({ + access: PermissionsRequestApprovalParams__FileSystemAccessMode, + path: PermissionsRequestApprovalParams__FileSystemPath, }); -export type PermissionsRequestApprovalResponse__GrantedPermissionProfile = { - readonly fileSystem?: PermissionsRequestApprovalResponse__AdditionalFileSystemPermissions | null; - readonly network?: PermissionsRequestApprovalResponse__AdditionalNetworkPermissions | null; +export type PermissionsRequestApprovalResponse__FileSystemSandboxEntry = { + readonly access: PermissionsRequestApprovalResponse__FileSystemAccessMode; + readonly path: PermissionsRequestApprovalResponse__FileSystemPath; }; -export const PermissionsRequestApprovalResponse__GrantedPermissionProfile = Schema.Struct({ - fileSystem: Schema.optionalKey( - Schema.Union([ - PermissionsRequestApprovalResponse__AdditionalFileSystemPermissions, - Schema.Null, - ]), - ), - network: Schema.optionalKey( - Schema.Union([PermissionsRequestApprovalResponse__AdditionalNetworkPermissions, Schema.Null]), - ), +export const PermissionsRequestApprovalResponse__FileSystemSandboxEntry = Schema.Struct({ + access: PermissionsRequestApprovalResponse__FileSystemAccessMode, + path: PermissionsRequestApprovalResponse__FileSystemPath, }); export type ServerNotification__AppInfo = { @@ -15903,6 +17307,15 @@ export const ServerNotification__AppInfo = Schema.Struct({ pluginDisplayNames: Schema.optionalKey(Schema.Array(Schema.String).annotate({ default: [] })), }).annotate({ description: "EXPERIMENTAL - app metadata returned by app-list APIs." }); +export type ServerNotification__FileSystemSandboxEntry = { + readonly access: ServerNotification__FileSystemAccessMode; + readonly path: ServerNotification__FileSystemPath; +}; +export const ServerNotification__FileSystemSandboxEntry = Schema.Struct({ + access: ServerNotification__FileSystemAccessMode, + path: ServerNotification__FileSystemPath, +}); + export type ServerNotification__FuzzyFileSearchSessionUpdatedNotification = { readonly files: ReadonlyArray; readonly query: string; @@ -15924,7 +17337,16 @@ export type ServerNotification__HookRunSummary = { readonly handlerType: ServerNotification__HookHandlerType; readonly id: string; readonly scope: ServerNotification__HookScope; - readonly sourcePath: string; + readonly source?: + | "system" + | "user" + | "project" + | "mdm" + | "sessionFlags" + | "legacyManagedConfigFile" + | "legacyManagedConfigMdm" + | "unknown"; + readonly sourcePath: ServerNotification__AbsolutePathBuf; readonly startedAt: number; readonly status: ServerNotification__HookRunStatus; readonly statusMessage?: string | null; @@ -15943,70 +17365,24 @@ export const ServerNotification__HookRunSummary = Schema.Struct({ handlerType: ServerNotification__HookHandlerType, id: Schema.String, scope: ServerNotification__HookScope, - sourcePath: Schema.String, + source: Schema.optionalKey( + Schema.Literals([ + "system", + "user", + "project", + "mdm", + "sessionFlags", + "legacyManagedConfigFile", + "legacyManagedConfigMdm", + "unknown", + ]).annotate({ default: "unknown" }), + ), + sourcePath: ServerNotification__AbsolutePathBuf, startedAt: Schema.Number.annotate({ format: "int64" }).check(Schema.isInt()), status: ServerNotification__HookRunStatus, statusMessage: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), }); -export type ServerNotification__ItemGuardianApprovalReviewCompletedNotification = { - readonly action: ServerNotification__GuardianApprovalReviewAction; - readonly decisionSource: ServerNotification__AutoReviewDecisionSource; - readonly review: ServerNotification__GuardianApprovalReview; - readonly reviewId: string; - readonly targetItemId?: string | null; - readonly threadId: string; - readonly turnId: string; -}; -export const ServerNotification__ItemGuardianApprovalReviewCompletedNotification = Schema.Struct({ - action: ServerNotification__GuardianApprovalReviewAction, - decisionSource: ServerNotification__AutoReviewDecisionSource, - review: ServerNotification__GuardianApprovalReview, - reviewId: Schema.String.annotate({ description: "Stable identifier for this review." }), - targetItemId: Schema.optionalKey( - Schema.Union([ - Schema.String.annotate({ - description: - "Identifier for the reviewed item or tool call when one exists.\n\nIn most cases, one review maps to one target item. The exceptions are - execve reviews, where a single command may contain multiple execve calls to review (only possible when using the shell_zsh_fork feature) - network policy reviews, where there is no target item\n\nA network call is triggered by a CommandExecution item, so having a target_item_id set to the CommandExecution item would be misleading because the review is about the network call, not the command execution. Therefore, target_item_id is set to None for network policy reviews.", - }), - Schema.Null, - ]), - ), - threadId: Schema.String, - turnId: Schema.String, -}).annotate({ - description: - "[UNSTABLE] Temporary notification payload for guardian automatic approval review. This shape is expected to change soon.", -}); - -export type ServerNotification__ItemGuardianApprovalReviewStartedNotification = { - readonly action: ServerNotification__GuardianApprovalReviewAction; - readonly review: ServerNotification__GuardianApprovalReview; - readonly reviewId: string; - readonly targetItemId?: string | null; - readonly threadId: string; - readonly turnId: string; -}; -export const ServerNotification__ItemGuardianApprovalReviewStartedNotification = Schema.Struct({ - action: ServerNotification__GuardianApprovalReviewAction, - review: ServerNotification__GuardianApprovalReview, - reviewId: Schema.String.annotate({ description: "Stable identifier for this review." }), - targetItemId: Schema.optionalKey( - Schema.Union([ - Schema.String.annotate({ - description: - "Identifier for the reviewed item or tool call when one exists.\n\nIn most cases, one review maps to one target item. The exceptions are - execve reviews, where a single command may contain multiple execve calls to review (only possible when using the shell_zsh_fork feature) - network policy reviews, where there is no target item\n\nA network call is triggered by a CommandExecution item, so having a target_item_id set to the CommandExecution item would be misleading because the review is about the network call, not the command execution. Therefore, target_item_id is set to None for network policy reviews.", - }), - Schema.Null, - ]), - ), - threadId: Schema.String, - turnId: Schema.String, -}).annotate({ - description: - "[UNSTABLE] Temporary notification payload for guardian automatic approval review. This shape is expected to change soon.", -}); - export type ServerNotification__TurnError = { readonly additionalDetails?: string | null; readonly codexErrorInfo?: ServerNotification__CodexErrorInfo | null; @@ -16020,6 +17396,19 @@ export const ServerNotification__TurnError = Schema.Struct({ message: Schema.String, }); +export type ServerNotification__FileChangePatchUpdatedNotification = { + readonly changes: ReadonlyArray; + readonly itemId: string; + readonly threadId: string; + readonly turnId: string; +}; +export const ServerNotification__FileChangePatchUpdatedNotification = Schema.Struct({ + changes: Schema.Array(ServerNotification__FileUpdateChange), + itemId: Schema.String, + threadId: Schema.String, + turnId: Schema.String, +}); + export type ServerNotification__AccountRateLimitsUpdatedNotification = { readonly rateLimits: ServerNotification__RateLimitSnapshot; }; @@ -16076,6 +17465,7 @@ export type ServerNotification__ThreadItem = readonly durationMs?: number | null; readonly error?: ServerNotification__McpToolCallError | null; readonly id: string; + readonly mcpAppResourceUri?: string | null; readonly result?: ServerNotification__McpToolCallResult | null; readonly server: string; readonly status: ServerNotification__McpToolCallStatus; @@ -16087,6 +17477,7 @@ export type ServerNotification__ThreadItem = readonly contentItems?: ReadonlyArray | null; readonly durationMs?: number | null; readonly id: string; + readonly namespace?: string | null; readonly status: ServerNotification__DynamicToolCallStatus; readonly success?: boolean | null; readonly tool: string; @@ -16110,12 +17501,16 @@ export type ServerNotification__ThreadItem = readonly query: string; readonly type: "webSearch"; } - | { readonly id: string; readonly path: string; readonly type: "imageView" } + | { + readonly id: string; + readonly path: ServerNotification__AbsolutePathBuf; + readonly type: "imageView"; + } | { readonly id: string; readonly result: string; readonly revisedPrompt?: string | null; - readonly savedPath?: string | null; + readonly savedPath?: ServerNotification__AbsolutePathBuf | null; readonly status: string; readonly type: "imageGeneration"; } @@ -16172,7 +17567,10 @@ export const ServerNotification__ThreadItem = Schema.Union( description: "A best-effort parsing of the command to understand the action(s) it will perform. This returns a list of CommandAction objects because a single shell command may be composed of many commands piped together.", }), - cwd: Schema.String.annotate({ description: "The command's working directory." }), + cwd: Schema.String.annotate({ + description: + "A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\n\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.", + }), durationMs: Schema.optionalKey( Schema.Union([ Schema.Number.annotate({ @@ -16232,6 +17630,7 @@ export const ServerNotification__ThreadItem = Schema.Union( ), error: Schema.optionalKey(Schema.Union([ServerNotification__McpToolCallError, Schema.Null])), id: Schema.String, + mcpAppResourceUri: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), result: Schema.optionalKey( Schema.Union([ServerNotification__McpToolCallResult, Schema.Null]), ), @@ -16258,6 +17657,7 @@ export const ServerNotification__ThreadItem = Schema.Union( ]), ), id: Schema.String, + namespace: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), status: ServerNotification__DynamicToolCallStatus, success: Schema.optionalKey(Schema.Union([Schema.Boolean, Schema.Null])), tool: Schema.String, @@ -16318,14 +17718,16 @@ export const ServerNotification__ThreadItem = Schema.Union( }).annotate({ title: "WebSearchThreadItem" }), Schema.Struct({ id: Schema.String, - path: Schema.String, + path: ServerNotification__AbsolutePathBuf, type: Schema.Literal("imageView").annotate({ title: "ImageViewThreadItemType" }), }).annotate({ title: "ImageViewThreadItem" }), Schema.Struct({ id: Schema.String, result: Schema.String, revisedPrompt: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), - savedPath: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + savedPath: Schema.optionalKey( + Schema.Union([ServerNotification__AbsolutePathBuf, Schema.Null]), + ), status: Schema.String, type: Schema.Literal("imageGeneration").annotate({ title: "ImageGenerationThreadItemType" }), }).annotate({ title: "ImageGenerationThreadItem" }), @@ -16415,17 +17817,13 @@ export const ServerNotification__TurnPlanUpdatedNotification = Schema.Struct({ turnId: Schema.String, }); -export type ServerRequest__RequestPermissionProfile = { - readonly fileSystem?: ServerRequest__AdditionalFileSystemPermissions | null; - readonly network?: ServerRequest__AdditionalNetworkPermissions | null; +export type ServerRequest__FileSystemSandboxEntry = { + readonly access: ServerRequest__FileSystemAccessMode; + readonly path: ServerRequest__FileSystemPath; }; -export const ServerRequest__RequestPermissionProfile = Schema.Struct({ - fileSystem: Schema.optionalKey( - Schema.Union([ServerRequest__AdditionalFileSystemPermissions, Schema.Null]), - ), - network: Schema.optionalKey( - Schema.Union([ServerRequest__AdditionalNetworkPermissions, Schema.Null]), - ), +export const ServerRequest__FileSystemSandboxEntry = Schema.Struct({ + access: ServerRequest__FileSystemAccessMode, + path: ServerRequest__FileSystemPath, }); export type ServerRequest__McpElicitationTitledMultiSelectEnumSchema = { @@ -16506,7 +17904,7 @@ export type ServerRequest__CommandExecutionRequestApprovalParams = { readonly approvalId?: string | null; readonly command?: string | null; readonly commandActions?: ReadonlyArray | null; - readonly cwd?: string | null; + readonly cwd?: ServerRequest__AbsolutePathBuf | null; readonly itemId: string; readonly networkApprovalContext?: ServerRequest__NetworkApprovalContext | null; readonly proposedExecpolicyAmendment?: ReadonlyArray | null; @@ -16540,10 +17938,9 @@ export const ServerRequest__CommandExecutionRequestApprovalParams = Schema.Struc ]), ), cwd: Schema.optionalKey( - Schema.Union([ - Schema.String.annotate({ description: "The command's working directory." }), - Schema.Null, - ]), + Schema.Union([ServerRequest__AbsolutePathBuf, Schema.Null]).annotate({ + description: "The command's working directory.", + }), ), itemId: Schema.String, networkApprovalContext: Schema.optionalKey( @@ -16731,6 +18128,52 @@ export const V2ErrorNotification__TurnError = Schema.Struct({ message: Schema.String, }); +export type V2ExternalAgentConfigDetectResponse__ExternalAgentConfigMigrationItem = { + readonly cwd?: string | null; + readonly description: string; + readonly details?: V2ExternalAgentConfigDetectResponse__MigrationDetails | null; + readonly itemType: V2ExternalAgentConfigDetectResponse__ExternalAgentConfigMigrationItemType; +}; +export const V2ExternalAgentConfigDetectResponse__ExternalAgentConfigMigrationItem = Schema.Struct({ + cwd: Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + description: + "Null or empty means home-scoped migration; non-empty means repo-scoped migration.", + }), + Schema.Null, + ]), + ), + description: Schema.String, + details: Schema.optionalKey( + Schema.Union([V2ExternalAgentConfigDetectResponse__MigrationDetails, Schema.Null]), + ), + itemType: V2ExternalAgentConfigDetectResponse__ExternalAgentConfigMigrationItemType, +}); + +export type V2ExternalAgentConfigImportParams__ExternalAgentConfigMigrationItem = { + readonly cwd?: string | null; + readonly description: string; + readonly details?: V2ExternalAgentConfigImportParams__MigrationDetails | null; + readonly itemType: V2ExternalAgentConfigImportParams__ExternalAgentConfigMigrationItemType; +}; +export const V2ExternalAgentConfigImportParams__ExternalAgentConfigMigrationItem = Schema.Struct({ + cwd: Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + description: + "Null or empty means home-scoped migration; non-empty means repo-scoped migration.", + }), + Schema.Null, + ]), + ), + description: Schema.String, + details: Schema.optionalKey( + Schema.Union([V2ExternalAgentConfigImportParams__MigrationDetails, Schema.Null]), + ), + itemType: V2ExternalAgentConfigImportParams__ExternalAgentConfigMigrationItemType, +}); + export type V2HookCompletedNotification__HookRunSummary = { readonly completedAt?: number | null; readonly displayOrder: number; @@ -16741,7 +18184,16 @@ export type V2HookCompletedNotification__HookRunSummary = { readonly handlerType: V2HookCompletedNotification__HookHandlerType; readonly id: string; readonly scope: V2HookCompletedNotification__HookScope; - readonly sourcePath: string; + readonly source?: + | "system" + | "user" + | "project" + | "mdm" + | "sessionFlags" + | "legacyManagedConfigFile" + | "legacyManagedConfigMdm" + | "unknown"; + readonly sourcePath: V2HookCompletedNotification__AbsolutePathBuf; readonly startedAt: number; readonly status: V2HookCompletedNotification__HookRunStatus; readonly statusMessage?: string | null; @@ -16760,7 +18212,19 @@ export const V2HookCompletedNotification__HookRunSummary = Schema.Struct({ handlerType: V2HookCompletedNotification__HookHandlerType, id: Schema.String, scope: V2HookCompletedNotification__HookScope, - sourcePath: Schema.String, + source: Schema.optionalKey( + Schema.Literals([ + "system", + "user", + "project", + "mdm", + "sessionFlags", + "legacyManagedConfigFile", + "legacyManagedConfigMdm", + "unknown", + ]).annotate({ default: "unknown" }), + ), + sourcePath: V2HookCompletedNotification__AbsolutePathBuf, startedAt: Schema.Number.annotate({ format: "int64" }).check(Schema.isInt()), status: V2HookCompletedNotification__HookRunStatus, statusMessage: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), @@ -16776,7 +18240,16 @@ export type V2HookStartedNotification__HookRunSummary = { readonly handlerType: V2HookStartedNotification__HookHandlerType; readonly id: string; readonly scope: V2HookStartedNotification__HookScope; - readonly sourcePath: string; + readonly source?: + | "system" + | "user" + | "project" + | "mdm" + | "sessionFlags" + | "legacyManagedConfigFile" + | "legacyManagedConfigMdm" + | "unknown"; + readonly sourcePath: V2HookStartedNotification__AbsolutePathBuf; readonly startedAt: number; readonly status: V2HookStartedNotification__HookRunStatus; readonly statusMessage?: string | null; @@ -16795,7 +18268,19 @@ export const V2HookStartedNotification__HookRunSummary = Schema.Struct({ handlerType: V2HookStartedNotification__HookHandlerType, id: Schema.String, scope: V2HookStartedNotification__HookScope, - sourcePath: Schema.String, + source: Schema.optionalKey( + Schema.Literals([ + "system", + "user", + "project", + "mdm", + "sessionFlags", + "legacyManagedConfigFile", + "legacyManagedConfigMdm", + "unknown", + ]).annotate({ default: "unknown" }), + ), + sourcePath: V2HookStartedNotification__AbsolutePathBuf, startedAt: Schema.Number.annotate({ format: "int64" }).check(Schema.isInt()), status: V2HookStartedNotification__HookRunStatus, statusMessage: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), @@ -16850,6 +18335,7 @@ export type V2ItemCompletedNotification__ThreadItem = readonly durationMs?: number | null; readonly error?: V2ItemCompletedNotification__McpToolCallError | null; readonly id: string; + readonly mcpAppResourceUri?: string | null; readonly result?: V2ItemCompletedNotification__McpToolCallResult | null; readonly server: string; readonly status: V2ItemCompletedNotification__McpToolCallStatus; @@ -16861,6 +18347,7 @@ export type V2ItemCompletedNotification__ThreadItem = readonly contentItems?: ReadonlyArray | null; readonly durationMs?: number | null; readonly id: string; + readonly namespace?: string | null; readonly status: V2ItemCompletedNotification__DynamicToolCallStatus; readonly success?: boolean | null; readonly tool: string; @@ -16886,12 +18373,16 @@ export type V2ItemCompletedNotification__ThreadItem = readonly query: string; readonly type: "webSearch"; } - | { readonly id: string; readonly path: string; readonly type: "imageView" } + | { + readonly id: string; + readonly path: V2ItemCompletedNotification__AbsolutePathBuf; + readonly type: "imageView"; + } | { readonly id: string; readonly result: string; readonly revisedPrompt?: string | null; - readonly savedPath?: string | null; + readonly savedPath?: V2ItemCompletedNotification__AbsolutePathBuf | null; readonly status: string; readonly type: "imageGeneration"; } @@ -16950,7 +18441,10 @@ export const V2ItemCompletedNotification__ThreadItem = Schema.Union( description: "A best-effort parsing of the command to understand the action(s) it will perform. This returns a list of CommandAction objects because a single shell command may be composed of many commands piped together.", }), - cwd: Schema.String.annotate({ description: "The command's working directory." }), + cwd: Schema.String.annotate({ + description: + "A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\n\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.", + }), durationMs: Schema.optionalKey( Schema.Union([ Schema.Number.annotate({ @@ -17012,6 +18506,7 @@ export const V2ItemCompletedNotification__ThreadItem = Schema.Union( Schema.Union([V2ItemCompletedNotification__McpToolCallError, Schema.Null]), ), id: Schema.String, + mcpAppResourceUri: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), result: Schema.optionalKey( Schema.Union([V2ItemCompletedNotification__McpToolCallResult, Schema.Null]), ), @@ -17038,6 +18533,7 @@ export const V2ItemCompletedNotification__ThreadItem = Schema.Union( ]), ), id: Schema.String, + namespace: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), status: V2ItemCompletedNotification__DynamicToolCallStatus, success: Schema.optionalKey(Schema.Union([Schema.Boolean, Schema.Null])), tool: Schema.String, @@ -17101,14 +18597,16 @@ export const V2ItemCompletedNotification__ThreadItem = Schema.Union( }).annotate({ title: "WebSearchThreadItem" }), Schema.Struct({ id: Schema.String, - path: Schema.String, + path: V2ItemCompletedNotification__AbsolutePathBuf, type: Schema.Literal("imageView").annotate({ title: "ImageViewThreadItemType" }), }).annotate({ title: "ImageViewThreadItem" }), Schema.Struct({ id: Schema.String, result: Schema.String, revisedPrompt: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), - savedPath: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + savedPath: Schema.optionalKey( + Schema.Union([V2ItemCompletedNotification__AbsolutePathBuf, Schema.Null]), + ), status: Schema.String, type: Schema.Literal("imageGeneration").annotate({ title: "ImageGenerationThreadItemType" }), }).annotate({ title: "ImageGenerationThreadItem" }), @@ -17136,6 +18634,26 @@ export const V2ItemCompletedNotification__ThreadItem = Schema.Union( { mode: "oneOf" }, ); +export type V2ItemGuardianApprovalReviewCompletedNotification__FileSystemSandboxEntry = { + readonly access: V2ItemGuardianApprovalReviewCompletedNotification__FileSystemAccessMode; + readonly path: V2ItemGuardianApprovalReviewCompletedNotification__FileSystemPath; +}; +export const V2ItemGuardianApprovalReviewCompletedNotification__FileSystemSandboxEntry = + Schema.Struct({ + access: V2ItemGuardianApprovalReviewCompletedNotification__FileSystemAccessMode, + path: V2ItemGuardianApprovalReviewCompletedNotification__FileSystemPath, + }); + +export type V2ItemGuardianApprovalReviewStartedNotification__FileSystemSandboxEntry = { + readonly access: V2ItemGuardianApprovalReviewStartedNotification__FileSystemAccessMode; + readonly path: V2ItemGuardianApprovalReviewStartedNotification__FileSystemPath; +}; +export const V2ItemGuardianApprovalReviewStartedNotification__FileSystemSandboxEntry = + Schema.Struct({ + access: V2ItemGuardianApprovalReviewStartedNotification__FileSystemAccessMode, + path: V2ItemGuardianApprovalReviewStartedNotification__FileSystemPath, + }); + export type V2ItemStartedNotification__ThreadItem = | { readonly content: ReadonlyArray; @@ -17185,6 +18703,7 @@ export type V2ItemStartedNotification__ThreadItem = readonly durationMs?: number | null; readonly error?: V2ItemStartedNotification__McpToolCallError | null; readonly id: string; + readonly mcpAppResourceUri?: string | null; readonly result?: V2ItemStartedNotification__McpToolCallResult | null; readonly server: string; readonly status: V2ItemStartedNotification__McpToolCallStatus; @@ -17196,6 +18715,7 @@ export type V2ItemStartedNotification__ThreadItem = readonly contentItems?: ReadonlyArray | null; readonly durationMs?: number | null; readonly id: string; + readonly namespace?: string | null; readonly status: V2ItemStartedNotification__DynamicToolCallStatus; readonly success?: boolean | null; readonly tool: string; @@ -17219,12 +18739,16 @@ export type V2ItemStartedNotification__ThreadItem = readonly query: string; readonly type: "webSearch"; } - | { readonly id: string; readonly path: string; readonly type: "imageView" } + | { + readonly id: string; + readonly path: V2ItemStartedNotification__AbsolutePathBuf; + readonly type: "imageView"; + } | { readonly id: string; readonly result: string; readonly revisedPrompt?: string | null; - readonly savedPath?: string | null; + readonly savedPath?: V2ItemStartedNotification__AbsolutePathBuf | null; readonly status: string; readonly type: "imageGeneration"; } @@ -17283,7 +18807,10 @@ export const V2ItemStartedNotification__ThreadItem = Schema.Union( description: "A best-effort parsing of the command to understand the action(s) it will perform. This returns a list of CommandAction objects because a single shell command may be composed of many commands piped together.", }), - cwd: Schema.String.annotate({ description: "The command's working directory." }), + cwd: Schema.String.annotate({ + description: + "A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\n\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.", + }), durationMs: Schema.optionalKey( Schema.Union([ Schema.Number.annotate({ @@ -17345,6 +18872,7 @@ export const V2ItemStartedNotification__ThreadItem = Schema.Union( Schema.Union([V2ItemStartedNotification__McpToolCallError, Schema.Null]), ), id: Schema.String, + mcpAppResourceUri: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), result: Schema.optionalKey( Schema.Union([V2ItemStartedNotification__McpToolCallResult, Schema.Null]), ), @@ -17371,6 +18899,7 @@ export const V2ItemStartedNotification__ThreadItem = Schema.Union( ]), ), id: Schema.String, + namespace: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), status: V2ItemStartedNotification__DynamicToolCallStatus, success: Schema.optionalKey(Schema.Union([Schema.Boolean, Schema.Null])), tool: Schema.String, @@ -17434,14 +18963,16 @@ export const V2ItemStartedNotification__ThreadItem = Schema.Union( }).annotate({ title: "WebSearchThreadItem" }), Schema.Struct({ id: Schema.String, - path: Schema.String, + path: V2ItemStartedNotification__AbsolutePathBuf, type: Schema.Literal("imageView").annotate({ title: "ImageViewThreadItemType" }), }).annotate({ title: "ImageViewThreadItem" }), Schema.Struct({ id: Schema.String, result: Schema.String, revisedPrompt: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), - savedPath: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + savedPath: Schema.optionalKey( + Schema.Union([V2ItemStartedNotification__AbsolutePathBuf, Schema.Null]), + ), status: Schema.String, type: Schema.Literal("imageGeneration").annotate({ title: "ImageGenerationThreadItemType" }), }).annotate({ title: "ImageGenerationThreadItem" }), @@ -17550,6 +19081,23 @@ export const V2PluginReadResponse__PluginSummary = Schema.Struct({ source: V2PluginReadResponse__PluginSource, }); +export type V2PluginReadResponse__SkillSummary = { + readonly description: string; + readonly enabled: boolean; + readonly interface?: V2PluginReadResponse__SkillInterface | null; + readonly name: string; + readonly path: V2PluginReadResponse__AbsolutePathBuf; + readonly shortDescription?: string | null; +}; +export const V2PluginReadResponse__SkillSummary = Schema.Struct({ + description: Schema.String, + enabled: Schema.Boolean, + interface: Schema.optionalKey(Schema.Union([V2PluginReadResponse__SkillInterface, Schema.Null])), + name: Schema.String, + path: V2PluginReadResponse__AbsolutePathBuf, + shortDescription: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), +}); + export type V2RawResponseItemCompletedNotification__FunctionCallOutputBody = | string | ReadonlyArray; @@ -17620,6 +19168,7 @@ export type V2ReviewStartResponse__ThreadItem = readonly durationMs?: number | null; readonly error?: V2ReviewStartResponse__McpToolCallError | null; readonly id: string; + readonly mcpAppResourceUri?: string | null; readonly result?: V2ReviewStartResponse__McpToolCallResult | null; readonly server: string; readonly status: V2ReviewStartResponse__McpToolCallStatus; @@ -17631,6 +19180,7 @@ export type V2ReviewStartResponse__ThreadItem = readonly contentItems?: ReadonlyArray | null; readonly durationMs?: number | null; readonly id: string; + readonly namespace?: string | null; readonly status: V2ReviewStartResponse__DynamicToolCallStatus; readonly success?: boolean | null; readonly tool: string; @@ -17654,12 +19204,16 @@ export type V2ReviewStartResponse__ThreadItem = readonly query: string; readonly type: "webSearch"; } - | { readonly id: string; readonly path: string; readonly type: "imageView" } + | { + readonly id: string; + readonly path: V2ReviewStartResponse__AbsolutePathBuf; + readonly type: "imageView"; + } | { readonly id: string; readonly result: string; readonly revisedPrompt?: string | null; - readonly savedPath?: string | null; + readonly savedPath?: V2ReviewStartResponse__AbsolutePathBuf | null; readonly status: string; readonly type: "imageGeneration"; } @@ -17716,7 +19270,10 @@ export const V2ReviewStartResponse__ThreadItem = Schema.Union( description: "A best-effort parsing of the command to understand the action(s) it will perform. This returns a list of CommandAction objects because a single shell command may be composed of many commands piped together.", }), - cwd: Schema.String.annotate({ description: "The command's working directory." }), + cwd: Schema.String.annotate({ + description: + "A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\n\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.", + }), durationMs: Schema.optionalKey( Schema.Union([ Schema.Number.annotate({ @@ -17778,6 +19335,7 @@ export const V2ReviewStartResponse__ThreadItem = Schema.Union( Schema.Union([V2ReviewStartResponse__McpToolCallError, Schema.Null]), ), id: Schema.String, + mcpAppResourceUri: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), result: Schema.optionalKey( Schema.Union([V2ReviewStartResponse__McpToolCallResult, Schema.Null]), ), @@ -17804,6 +19362,7 @@ export const V2ReviewStartResponse__ThreadItem = Schema.Union( ]), ), id: Schema.String, + namespace: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), status: V2ReviewStartResponse__DynamicToolCallStatus, success: Schema.optionalKey(Schema.Union([Schema.Boolean, Schema.Null])), tool: Schema.String, @@ -17866,14 +19425,16 @@ export const V2ReviewStartResponse__ThreadItem = Schema.Union( }).annotate({ title: "WebSearchThreadItem" }), Schema.Struct({ id: Schema.String, - path: Schema.String, + path: V2ReviewStartResponse__AbsolutePathBuf, type: Schema.Literal("imageView").annotate({ title: "ImageViewThreadItemType" }), }).annotate({ title: "ImageViewThreadItem" }), Schema.Struct({ id: Schema.String, result: Schema.String, revisedPrompt: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), - savedPath: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + savedPath: Schema.optionalKey( + Schema.Union([V2ReviewStartResponse__AbsolutePathBuf, Schema.Null]), + ), status: Schema.String, type: Schema.Literal("imageGeneration").annotate({ title: "ImageGenerationThreadItemType" }), }).annotate({ title: "ImageGenerationThreadItem" }), @@ -17907,7 +19468,7 @@ export type V2SkillsListResponse__SkillMetadata = { readonly enabled: boolean; readonly interface?: V2SkillsListResponse__SkillInterface | null; readonly name: string; - readonly path: string; + readonly path: V2SkillsListResponse__AbsolutePathBuf; readonly scope: V2SkillsListResponse__SkillScope; readonly shortDescription?: string | null; }; @@ -17919,7 +19480,7 @@ export const V2SkillsListResponse__SkillMetadata = Schema.Struct({ enabled: Schema.Boolean, interface: Schema.optionalKey(Schema.Union([V2SkillsListResponse__SkillInterface, Schema.Null])), name: Schema.String, - path: Schema.String, + path: V2SkillsListResponse__AbsolutePathBuf, scope: V2SkillsListResponse__SkillScope, shortDescription: Schema.optionalKey( Schema.Union([ @@ -17994,6 +19555,7 @@ export type V2ThreadForkResponse__ThreadItem = readonly durationMs?: number | null; readonly error?: V2ThreadForkResponse__McpToolCallError | null; readonly id: string; + readonly mcpAppResourceUri?: string | null; readonly result?: V2ThreadForkResponse__McpToolCallResult | null; readonly server: string; readonly status: V2ThreadForkResponse__McpToolCallStatus; @@ -18005,6 +19567,7 @@ export type V2ThreadForkResponse__ThreadItem = readonly contentItems?: ReadonlyArray | null; readonly durationMs?: number | null; readonly id: string; + readonly namespace?: string | null; readonly status: V2ThreadForkResponse__DynamicToolCallStatus; readonly success?: boolean | null; readonly tool: string; @@ -18028,12 +19591,16 @@ export type V2ThreadForkResponse__ThreadItem = readonly query: string; readonly type: "webSearch"; } - | { readonly id: string; readonly path: string; readonly type: "imageView" } + | { + readonly id: string; + readonly path: V2ThreadForkResponse__AbsolutePathBuf; + readonly type: "imageView"; + } | { readonly id: string; readonly result: string; readonly revisedPrompt?: string | null; - readonly savedPath?: string | null; + readonly savedPath?: V2ThreadForkResponse__AbsolutePathBuf | null; readonly status: string; readonly type: "imageGeneration"; } @@ -18090,7 +19657,10 @@ export const V2ThreadForkResponse__ThreadItem = Schema.Union( description: "A best-effort parsing of the command to understand the action(s) it will perform. This returns a list of CommandAction objects because a single shell command may be composed of many commands piped together.", }), - cwd: Schema.String.annotate({ description: "The command's working directory." }), + cwd: Schema.String.annotate({ + description: + "A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\n\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.", + }), durationMs: Schema.optionalKey( Schema.Union([ Schema.Number.annotate({ @@ -18152,6 +19722,7 @@ export const V2ThreadForkResponse__ThreadItem = Schema.Union( Schema.Union([V2ThreadForkResponse__McpToolCallError, Schema.Null]), ), id: Schema.String, + mcpAppResourceUri: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), result: Schema.optionalKey( Schema.Union([V2ThreadForkResponse__McpToolCallResult, Schema.Null]), ), @@ -18178,6 +19749,7 @@ export const V2ThreadForkResponse__ThreadItem = Schema.Union( ]), ), id: Schema.String, + namespace: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), status: V2ThreadForkResponse__DynamicToolCallStatus, success: Schema.optionalKey(Schema.Union([Schema.Boolean, Schema.Null])), tool: Schema.String, @@ -18240,14 +19812,16 @@ export const V2ThreadForkResponse__ThreadItem = Schema.Union( }).annotate({ title: "WebSearchThreadItem" }), Schema.Struct({ id: Schema.String, - path: Schema.String, + path: V2ThreadForkResponse__AbsolutePathBuf, type: Schema.Literal("imageView").annotate({ title: "ImageViewThreadItemType" }), }).annotate({ title: "ImageViewThreadItem" }), Schema.Struct({ id: Schema.String, result: Schema.String, revisedPrompt: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), - savedPath: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + savedPath: Schema.optionalKey( + Schema.Union([V2ThreadForkResponse__AbsolutePathBuf, Schema.Null]), + ), status: Schema.String, type: Schema.Literal("imageGeneration").annotate({ title: "ImageGenerationThreadItemType" }), }).annotate({ title: "ImageGenerationThreadItem" }), @@ -18337,6 +19911,7 @@ export type V2ThreadListResponse__ThreadItem = readonly durationMs?: number | null; readonly error?: V2ThreadListResponse__McpToolCallError | null; readonly id: string; + readonly mcpAppResourceUri?: string | null; readonly result?: V2ThreadListResponse__McpToolCallResult | null; readonly server: string; readonly status: V2ThreadListResponse__McpToolCallStatus; @@ -18348,6 +19923,7 @@ export type V2ThreadListResponse__ThreadItem = readonly contentItems?: ReadonlyArray | null; readonly durationMs?: number | null; readonly id: string; + readonly namespace?: string | null; readonly status: V2ThreadListResponse__DynamicToolCallStatus; readonly success?: boolean | null; readonly tool: string; @@ -18371,12 +19947,16 @@ export type V2ThreadListResponse__ThreadItem = readonly query: string; readonly type: "webSearch"; } - | { readonly id: string; readonly path: string; readonly type: "imageView" } + | { + readonly id: string; + readonly path: V2ThreadListResponse__AbsolutePathBuf; + readonly type: "imageView"; + } | { readonly id: string; readonly result: string; readonly revisedPrompt?: string | null; - readonly savedPath?: string | null; + readonly savedPath?: V2ThreadListResponse__AbsolutePathBuf | null; readonly status: string; readonly type: "imageGeneration"; } @@ -18433,7 +20013,10 @@ export const V2ThreadListResponse__ThreadItem = Schema.Union( description: "A best-effort parsing of the command to understand the action(s) it will perform. This returns a list of CommandAction objects because a single shell command may be composed of many commands piped together.", }), - cwd: Schema.String.annotate({ description: "The command's working directory." }), + cwd: Schema.String.annotate({ + description: + "A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\n\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.", + }), durationMs: Schema.optionalKey( Schema.Union([ Schema.Number.annotate({ @@ -18495,6 +20078,7 @@ export const V2ThreadListResponse__ThreadItem = Schema.Union( Schema.Union([V2ThreadListResponse__McpToolCallError, Schema.Null]), ), id: Schema.String, + mcpAppResourceUri: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), result: Schema.optionalKey( Schema.Union([V2ThreadListResponse__McpToolCallResult, Schema.Null]), ), @@ -18521,6 +20105,7 @@ export const V2ThreadListResponse__ThreadItem = Schema.Union( ]), ), id: Schema.String, + namespace: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), status: V2ThreadListResponse__DynamicToolCallStatus, success: Schema.optionalKey(Schema.Union([Schema.Boolean, Schema.Null])), tool: Schema.String, @@ -18583,14 +20168,16 @@ export const V2ThreadListResponse__ThreadItem = Schema.Union( }).annotate({ title: "WebSearchThreadItem" }), Schema.Struct({ id: Schema.String, - path: Schema.String, + path: V2ThreadListResponse__AbsolutePathBuf, type: Schema.Literal("imageView").annotate({ title: "ImageViewThreadItemType" }), }).annotate({ title: "ImageViewThreadItem" }), Schema.Struct({ id: Schema.String, result: Schema.String, revisedPrompt: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), - savedPath: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + savedPath: Schema.optionalKey( + Schema.Union([V2ThreadListResponse__AbsolutePathBuf, Schema.Null]), + ), status: Schema.String, type: Schema.Literal("imageGeneration").annotate({ title: "ImageGenerationThreadItemType" }), }).annotate({ title: "ImageGenerationThreadItem" }), @@ -18680,6 +20267,7 @@ export type V2ThreadMetadataUpdateResponse__ThreadItem = readonly durationMs?: number | null; readonly error?: V2ThreadMetadataUpdateResponse__McpToolCallError | null; readonly id: string; + readonly mcpAppResourceUri?: string | null; readonly result?: V2ThreadMetadataUpdateResponse__McpToolCallResult | null; readonly server: string; readonly status: V2ThreadMetadataUpdateResponse__McpToolCallStatus; @@ -18691,6 +20279,7 @@ export type V2ThreadMetadataUpdateResponse__ThreadItem = readonly contentItems?: ReadonlyArray | null; readonly durationMs?: number | null; readonly id: string; + readonly namespace?: string | null; readonly status: V2ThreadMetadataUpdateResponse__DynamicToolCallStatus; readonly success?: boolean | null; readonly tool: string; @@ -18716,12 +20305,16 @@ export type V2ThreadMetadataUpdateResponse__ThreadItem = readonly query: string; readonly type: "webSearch"; } - | { readonly id: string; readonly path: string; readonly type: "imageView" } + | { + readonly id: string; + readonly path: V2ThreadMetadataUpdateResponse__AbsolutePathBuf; + readonly type: "imageView"; + } | { readonly id: string; readonly result: string; readonly revisedPrompt?: string | null; - readonly savedPath?: string | null; + readonly savedPath?: V2ThreadMetadataUpdateResponse__AbsolutePathBuf | null; readonly status: string; readonly type: "imageGeneration"; } @@ -18780,7 +20373,10 @@ export const V2ThreadMetadataUpdateResponse__ThreadItem = Schema.Union( description: "A best-effort parsing of the command to understand the action(s) it will perform. This returns a list of CommandAction objects because a single shell command may be composed of many commands piped together.", }), - cwd: Schema.String.annotate({ description: "The command's working directory." }), + cwd: Schema.String.annotate({ + description: + "A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\n\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.", + }), durationMs: Schema.optionalKey( Schema.Union([ Schema.Number.annotate({ @@ -18842,6 +20438,7 @@ export const V2ThreadMetadataUpdateResponse__ThreadItem = Schema.Union( Schema.Union([V2ThreadMetadataUpdateResponse__McpToolCallError, Schema.Null]), ), id: Schema.String, + mcpAppResourceUri: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), result: Schema.optionalKey( Schema.Union([V2ThreadMetadataUpdateResponse__McpToolCallResult, Schema.Null]), ), @@ -18868,6 +20465,7 @@ export const V2ThreadMetadataUpdateResponse__ThreadItem = Schema.Union( ]), ), id: Schema.String, + namespace: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), status: V2ThreadMetadataUpdateResponse__DynamicToolCallStatus, success: Schema.optionalKey(Schema.Union([Schema.Boolean, Schema.Null])), tool: Schema.String, @@ -18931,14 +20529,16 @@ export const V2ThreadMetadataUpdateResponse__ThreadItem = Schema.Union( }).annotate({ title: "WebSearchThreadItem" }), Schema.Struct({ id: Schema.String, - path: Schema.String, + path: V2ThreadMetadataUpdateResponse__AbsolutePathBuf, type: Schema.Literal("imageView").annotate({ title: "ImageViewThreadItemType" }), }).annotate({ title: "ImageViewThreadItem" }), Schema.Struct({ id: Schema.String, result: Schema.String, revisedPrompt: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), - savedPath: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + savedPath: Schema.optionalKey( + Schema.Union([V2ThreadMetadataUpdateResponse__AbsolutePathBuf, Schema.Null]), + ), status: Schema.String, type: Schema.Literal("imageGeneration").annotate({ title: "ImageGenerationThreadItemType" }), }).annotate({ title: "ImageGenerationThreadItem" }), @@ -19028,6 +20628,7 @@ export type V2ThreadReadResponse__ThreadItem = readonly durationMs?: number | null; readonly error?: V2ThreadReadResponse__McpToolCallError | null; readonly id: string; + readonly mcpAppResourceUri?: string | null; readonly result?: V2ThreadReadResponse__McpToolCallResult | null; readonly server: string; readonly status: V2ThreadReadResponse__McpToolCallStatus; @@ -19039,6 +20640,7 @@ export type V2ThreadReadResponse__ThreadItem = readonly contentItems?: ReadonlyArray | null; readonly durationMs?: number | null; readonly id: string; + readonly namespace?: string | null; readonly status: V2ThreadReadResponse__DynamicToolCallStatus; readonly success?: boolean | null; readonly tool: string; @@ -19062,12 +20664,16 @@ export type V2ThreadReadResponse__ThreadItem = readonly query: string; readonly type: "webSearch"; } - | { readonly id: string; readonly path: string; readonly type: "imageView" } + | { + readonly id: string; + readonly path: V2ThreadReadResponse__AbsolutePathBuf; + readonly type: "imageView"; + } | { readonly id: string; readonly result: string; readonly revisedPrompt?: string | null; - readonly savedPath?: string | null; + readonly savedPath?: V2ThreadReadResponse__AbsolutePathBuf | null; readonly status: string; readonly type: "imageGeneration"; } @@ -19124,7 +20730,10 @@ export const V2ThreadReadResponse__ThreadItem = Schema.Union( description: "A best-effort parsing of the command to understand the action(s) it will perform. This returns a list of CommandAction objects because a single shell command may be composed of many commands piped together.", }), - cwd: Schema.String.annotate({ description: "The command's working directory." }), + cwd: Schema.String.annotate({ + description: + "A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\n\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.", + }), durationMs: Schema.optionalKey( Schema.Union([ Schema.Number.annotate({ @@ -19186,6 +20795,7 @@ export const V2ThreadReadResponse__ThreadItem = Schema.Union( Schema.Union([V2ThreadReadResponse__McpToolCallError, Schema.Null]), ), id: Schema.String, + mcpAppResourceUri: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), result: Schema.optionalKey( Schema.Union([V2ThreadReadResponse__McpToolCallResult, Schema.Null]), ), @@ -19212,6 +20822,7 @@ export const V2ThreadReadResponse__ThreadItem = Schema.Union( ]), ), id: Schema.String, + namespace: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), status: V2ThreadReadResponse__DynamicToolCallStatus, success: Schema.optionalKey(Schema.Union([Schema.Boolean, Schema.Null])), tool: Schema.String, @@ -19274,14 +20885,16 @@ export const V2ThreadReadResponse__ThreadItem = Schema.Union( }).annotate({ title: "WebSearchThreadItem" }), Schema.Struct({ id: Schema.String, - path: Schema.String, + path: V2ThreadReadResponse__AbsolutePathBuf, type: Schema.Literal("imageView").annotate({ title: "ImageViewThreadItemType" }), }).annotate({ title: "ImageViewThreadItem" }), Schema.Struct({ id: Schema.String, result: Schema.String, revisedPrompt: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), - savedPath: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + savedPath: Schema.optionalKey( + Schema.Union([V2ThreadReadResponse__AbsolutePathBuf, Schema.Null]), + ), status: Schema.String, type: Schema.Literal("imageGeneration").annotate({ title: "ImageGenerationThreadItemType" }), }).annotate({ title: "ImageGenerationThreadItem" }), @@ -19379,6 +20992,7 @@ export type V2ThreadResumeResponse__ThreadItem = readonly durationMs?: number | null; readonly error?: V2ThreadResumeResponse__McpToolCallError | null; readonly id: string; + readonly mcpAppResourceUri?: string | null; readonly result?: V2ThreadResumeResponse__McpToolCallResult | null; readonly server: string; readonly status: V2ThreadResumeResponse__McpToolCallStatus; @@ -19390,6 +21004,7 @@ export type V2ThreadResumeResponse__ThreadItem = readonly contentItems?: ReadonlyArray | null; readonly durationMs?: number | null; readonly id: string; + readonly namespace?: string | null; readonly status: V2ThreadResumeResponse__DynamicToolCallStatus; readonly success?: boolean | null; readonly tool: string; @@ -19413,12 +21028,16 @@ export type V2ThreadResumeResponse__ThreadItem = readonly query: string; readonly type: "webSearch"; } - | { readonly id: string; readonly path: string; readonly type: "imageView" } + | { + readonly id: string; + readonly path: V2ThreadResumeResponse__AbsolutePathBuf; + readonly type: "imageView"; + } | { readonly id: string; readonly result: string; readonly revisedPrompt?: string | null; - readonly savedPath?: string | null; + readonly savedPath?: V2ThreadResumeResponse__AbsolutePathBuf | null; readonly status: string; readonly type: "imageGeneration"; } @@ -19475,7 +21094,10 @@ export const V2ThreadResumeResponse__ThreadItem = Schema.Union( description: "A best-effort parsing of the command to understand the action(s) it will perform. This returns a list of CommandAction objects because a single shell command may be composed of many commands piped together.", }), - cwd: Schema.String.annotate({ description: "The command's working directory." }), + cwd: Schema.String.annotate({ + description: + "A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\n\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.", + }), durationMs: Schema.optionalKey( Schema.Union([ Schema.Number.annotate({ @@ -19537,6 +21159,7 @@ export const V2ThreadResumeResponse__ThreadItem = Schema.Union( Schema.Union([V2ThreadResumeResponse__McpToolCallError, Schema.Null]), ), id: Schema.String, + mcpAppResourceUri: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), result: Schema.optionalKey( Schema.Union([V2ThreadResumeResponse__McpToolCallResult, Schema.Null]), ), @@ -19563,6 +21186,7 @@ export const V2ThreadResumeResponse__ThreadItem = Schema.Union( ]), ), id: Schema.String, + namespace: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), status: V2ThreadResumeResponse__DynamicToolCallStatus, success: Schema.optionalKey(Schema.Union([Schema.Boolean, Schema.Null])), tool: Schema.String, @@ -19625,14 +21249,16 @@ export const V2ThreadResumeResponse__ThreadItem = Schema.Union( }).annotate({ title: "WebSearchThreadItem" }), Schema.Struct({ id: Schema.String, - path: Schema.String, + path: V2ThreadResumeResponse__AbsolutePathBuf, type: Schema.Literal("imageView").annotate({ title: "ImageViewThreadItemType" }), }).annotate({ title: "ImageViewThreadItem" }), Schema.Struct({ id: Schema.String, result: Schema.String, revisedPrompt: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), - savedPath: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + savedPath: Schema.optionalKey( + Schema.Union([V2ThreadResumeResponse__AbsolutePathBuf, Schema.Null]), + ), status: Schema.String, type: Schema.Literal("imageGeneration").annotate({ title: "ImageGenerationThreadItemType" }), }).annotate({ title: "ImageGenerationThreadItem" }), @@ -19722,6 +21348,7 @@ export type V2ThreadRollbackResponse__ThreadItem = readonly durationMs?: number | null; readonly error?: V2ThreadRollbackResponse__McpToolCallError | null; readonly id: string; + readonly mcpAppResourceUri?: string | null; readonly result?: V2ThreadRollbackResponse__McpToolCallResult | null; readonly server: string; readonly status: V2ThreadRollbackResponse__McpToolCallStatus; @@ -19733,6 +21360,7 @@ export type V2ThreadRollbackResponse__ThreadItem = readonly contentItems?: ReadonlyArray | null; readonly durationMs?: number | null; readonly id: string; + readonly namespace?: string | null; readonly status: V2ThreadRollbackResponse__DynamicToolCallStatus; readonly success?: boolean | null; readonly tool: string; @@ -19756,12 +21384,16 @@ export type V2ThreadRollbackResponse__ThreadItem = readonly query: string; readonly type: "webSearch"; } - | { readonly id: string; readonly path: string; readonly type: "imageView" } + | { + readonly id: string; + readonly path: V2ThreadRollbackResponse__AbsolutePathBuf; + readonly type: "imageView"; + } | { readonly id: string; readonly result: string; readonly revisedPrompt?: string | null; - readonly savedPath?: string | null; + readonly savedPath?: V2ThreadRollbackResponse__AbsolutePathBuf | null; readonly status: string; readonly type: "imageGeneration"; } @@ -19820,7 +21452,10 @@ export const V2ThreadRollbackResponse__ThreadItem = Schema.Union( description: "A best-effort parsing of the command to understand the action(s) it will perform. This returns a list of CommandAction objects because a single shell command may be composed of many commands piped together.", }), - cwd: Schema.String.annotate({ description: "The command's working directory." }), + cwd: Schema.String.annotate({ + description: + "A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\n\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.", + }), durationMs: Schema.optionalKey( Schema.Union([ Schema.Number.annotate({ @@ -19882,6 +21517,7 @@ export const V2ThreadRollbackResponse__ThreadItem = Schema.Union( Schema.Union([V2ThreadRollbackResponse__McpToolCallError, Schema.Null]), ), id: Schema.String, + mcpAppResourceUri: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), result: Schema.optionalKey( Schema.Union([V2ThreadRollbackResponse__McpToolCallResult, Schema.Null]), ), @@ -19908,6 +21544,7 @@ export const V2ThreadRollbackResponse__ThreadItem = Schema.Union( ]), ), id: Schema.String, + namespace: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), status: V2ThreadRollbackResponse__DynamicToolCallStatus, success: Schema.optionalKey(Schema.Union([Schema.Boolean, Schema.Null])), tool: Schema.String, @@ -19971,14 +21608,16 @@ export const V2ThreadRollbackResponse__ThreadItem = Schema.Union( }).annotate({ title: "WebSearchThreadItem" }), Schema.Struct({ id: Schema.String, - path: Schema.String, + path: V2ThreadRollbackResponse__AbsolutePathBuf, type: Schema.Literal("imageView").annotate({ title: "ImageViewThreadItemType" }), }).annotate({ title: "ImageViewThreadItem" }), Schema.Struct({ id: Schema.String, result: Schema.String, revisedPrompt: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), - savedPath: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + savedPath: Schema.optionalKey( + Schema.Union([V2ThreadRollbackResponse__AbsolutePathBuf, Schema.Null]), + ), status: Schema.String, type: Schema.Literal("imageGeneration").annotate({ title: "ImageGenerationThreadItemType" }), }).annotate({ title: "ImageGenerationThreadItem" }), @@ -20068,6 +21707,7 @@ export type V2ThreadStartedNotification__ThreadItem = readonly durationMs?: number | null; readonly error?: V2ThreadStartedNotification__McpToolCallError | null; readonly id: string; + readonly mcpAppResourceUri?: string | null; readonly result?: V2ThreadStartedNotification__McpToolCallResult | null; readonly server: string; readonly status: V2ThreadStartedNotification__McpToolCallStatus; @@ -20079,6 +21719,7 @@ export type V2ThreadStartedNotification__ThreadItem = readonly contentItems?: ReadonlyArray | null; readonly durationMs?: number | null; readonly id: string; + readonly namespace?: string | null; readonly status: V2ThreadStartedNotification__DynamicToolCallStatus; readonly success?: boolean | null; readonly tool: string; @@ -20104,12 +21745,16 @@ export type V2ThreadStartedNotification__ThreadItem = readonly query: string; readonly type: "webSearch"; } - | { readonly id: string; readonly path: string; readonly type: "imageView" } + | { + readonly id: string; + readonly path: V2ThreadStartedNotification__AbsolutePathBuf; + readonly type: "imageView"; + } | { readonly id: string; readonly result: string; readonly revisedPrompt?: string | null; - readonly savedPath?: string | null; + readonly savedPath?: V2ThreadStartedNotification__AbsolutePathBuf | null; readonly status: string; readonly type: "imageGeneration"; } @@ -20168,7 +21813,10 @@ export const V2ThreadStartedNotification__ThreadItem = Schema.Union( description: "A best-effort parsing of the command to understand the action(s) it will perform. This returns a list of CommandAction objects because a single shell command may be composed of many commands piped together.", }), - cwd: Schema.String.annotate({ description: "The command's working directory." }), + cwd: Schema.String.annotate({ + description: + "A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\n\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.", + }), durationMs: Schema.optionalKey( Schema.Union([ Schema.Number.annotate({ @@ -20230,6 +21878,7 @@ export const V2ThreadStartedNotification__ThreadItem = Schema.Union( Schema.Union([V2ThreadStartedNotification__McpToolCallError, Schema.Null]), ), id: Schema.String, + mcpAppResourceUri: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), result: Schema.optionalKey( Schema.Union([V2ThreadStartedNotification__McpToolCallResult, Schema.Null]), ), @@ -20256,6 +21905,7 @@ export const V2ThreadStartedNotification__ThreadItem = Schema.Union( ]), ), id: Schema.String, + namespace: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), status: V2ThreadStartedNotification__DynamicToolCallStatus, success: Schema.optionalKey(Schema.Union([Schema.Boolean, Schema.Null])), tool: Schema.String, @@ -20319,14 +21969,16 @@ export const V2ThreadStartedNotification__ThreadItem = Schema.Union( }).annotate({ title: "WebSearchThreadItem" }), Schema.Struct({ id: Schema.String, - path: Schema.String, + path: V2ThreadStartedNotification__AbsolutePathBuf, type: Schema.Literal("imageView").annotate({ title: "ImageViewThreadItemType" }), }).annotate({ title: "ImageViewThreadItem" }), Schema.Struct({ id: Schema.String, result: Schema.String, revisedPrompt: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), - savedPath: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + savedPath: Schema.optionalKey( + Schema.Union([V2ThreadStartedNotification__AbsolutePathBuf, Schema.Null]), + ), status: Schema.String, type: Schema.Literal("imageGeneration").annotate({ title: "ImageGenerationThreadItemType" }), }).annotate({ title: "ImageGenerationThreadItem" }), @@ -20416,6 +22068,7 @@ export type V2ThreadStartResponse__ThreadItem = readonly durationMs?: number | null; readonly error?: V2ThreadStartResponse__McpToolCallError | null; readonly id: string; + readonly mcpAppResourceUri?: string | null; readonly result?: V2ThreadStartResponse__McpToolCallResult | null; readonly server: string; readonly status: V2ThreadStartResponse__McpToolCallStatus; @@ -20427,6 +22080,7 @@ export type V2ThreadStartResponse__ThreadItem = readonly contentItems?: ReadonlyArray | null; readonly durationMs?: number | null; readonly id: string; + readonly namespace?: string | null; readonly status: V2ThreadStartResponse__DynamicToolCallStatus; readonly success?: boolean | null; readonly tool: string; @@ -20450,12 +22104,16 @@ export type V2ThreadStartResponse__ThreadItem = readonly query: string; readonly type: "webSearch"; } - | { readonly id: string; readonly path: string; readonly type: "imageView" } + | { + readonly id: string; + readonly path: V2ThreadStartResponse__AbsolutePathBuf; + readonly type: "imageView"; + } | { readonly id: string; readonly result: string; readonly revisedPrompt?: string | null; - readonly savedPath?: string | null; + readonly savedPath?: V2ThreadStartResponse__AbsolutePathBuf | null; readonly status: string; readonly type: "imageGeneration"; } @@ -20512,7 +22170,10 @@ export const V2ThreadStartResponse__ThreadItem = Schema.Union( description: "A best-effort parsing of the command to understand the action(s) it will perform. This returns a list of CommandAction objects because a single shell command may be composed of many commands piped together.", }), - cwd: Schema.String.annotate({ description: "The command's working directory." }), + cwd: Schema.String.annotate({ + description: + "A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\n\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.", + }), durationMs: Schema.optionalKey( Schema.Union([ Schema.Number.annotate({ @@ -20574,6 +22235,7 @@ export const V2ThreadStartResponse__ThreadItem = Schema.Union( Schema.Union([V2ThreadStartResponse__McpToolCallError, Schema.Null]), ), id: Schema.String, + mcpAppResourceUri: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), result: Schema.optionalKey( Schema.Union([V2ThreadStartResponse__McpToolCallResult, Schema.Null]), ), @@ -20600,6 +22262,7 @@ export const V2ThreadStartResponse__ThreadItem = Schema.Union( ]), ), id: Schema.String, + namespace: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), status: V2ThreadStartResponse__DynamicToolCallStatus, success: Schema.optionalKey(Schema.Union([Schema.Boolean, Schema.Null])), tool: Schema.String, @@ -20662,14 +22325,375 @@ export const V2ThreadStartResponse__ThreadItem = Schema.Union( }).annotate({ title: "WebSearchThreadItem" }), Schema.Struct({ id: Schema.String, - path: Schema.String, + path: V2ThreadStartResponse__AbsolutePathBuf, type: Schema.Literal("imageView").annotate({ title: "ImageViewThreadItemType" }), }).annotate({ title: "ImageViewThreadItem" }), Schema.Struct({ id: Schema.String, result: Schema.String, revisedPrompt: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), - savedPath: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + savedPath: Schema.optionalKey( + Schema.Union([V2ThreadStartResponse__AbsolutePathBuf, Schema.Null]), + ), + status: Schema.String, + type: Schema.Literal("imageGeneration").annotate({ title: "ImageGenerationThreadItemType" }), + }).annotate({ title: "ImageGenerationThreadItem" }), + Schema.Struct({ + id: Schema.String, + review: Schema.String, + type: Schema.Literal("enteredReviewMode").annotate({ + title: "EnteredReviewModeThreadItemType", + }), + }).annotate({ title: "EnteredReviewModeThreadItem" }), + Schema.Struct({ + id: Schema.String, + review: Schema.String, + type: Schema.Literal("exitedReviewMode").annotate({ + title: "ExitedReviewModeThreadItemType", + }), + }).annotate({ title: "ExitedReviewModeThreadItem" }), + Schema.Struct({ + id: Schema.String, + type: Schema.Literal("contextCompaction").annotate({ + title: "ContextCompactionThreadItemType", + }), + }).annotate({ title: "ContextCompactionThreadItem" }), + ], + { mode: "oneOf" }, +); + +export type V2ThreadTurnsListResponse__TurnError = { + readonly additionalDetails?: string | null; + readonly codexErrorInfo?: V2ThreadTurnsListResponse__CodexErrorInfo | null; + readonly message: string; +}; +export const V2ThreadTurnsListResponse__TurnError = Schema.Struct({ + additionalDetails: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + codexErrorInfo: Schema.optionalKey( + Schema.Union([V2ThreadTurnsListResponse__CodexErrorInfo, Schema.Null]), + ), + message: Schema.String, +}); + +export type V2ThreadTurnsListResponse__ThreadItem = + | { + readonly content: ReadonlyArray; + readonly id: string; + readonly type: "userMessage"; + } + | { + readonly fragments: ReadonlyArray; + readonly id: string; + readonly type: "hookPrompt"; + } + | { + readonly id: string; + readonly memoryCitation?: V2ThreadTurnsListResponse__MemoryCitation | null; + readonly phase?: V2ThreadTurnsListResponse__MessagePhase | null; + readonly text: string; + readonly type: "agentMessage"; + } + | { readonly id: string; readonly text: string; readonly type: "plan" } + | { + readonly content?: ReadonlyArray; + readonly id: string; + readonly summary?: ReadonlyArray; + readonly type: "reasoning"; + } + | { + readonly aggregatedOutput?: string | null; + readonly command: string; + readonly commandActions: ReadonlyArray; + readonly cwd: string; + readonly durationMs?: number | null; + readonly exitCode?: number | null; + readonly id: string; + readonly processId?: string | null; + readonly source?: "agent" | "userShell" | "unifiedExecStartup" | "unifiedExecInteraction"; + readonly status: V2ThreadTurnsListResponse__CommandExecutionStatus; + readonly type: "commandExecution"; + } + | { + readonly changes: ReadonlyArray; + readonly id: string; + readonly status: V2ThreadTurnsListResponse__PatchApplyStatus; + readonly type: "fileChange"; + } + | { + readonly arguments: unknown; + readonly durationMs?: number | null; + readonly error?: V2ThreadTurnsListResponse__McpToolCallError | null; + readonly id: string; + readonly mcpAppResourceUri?: string | null; + readonly result?: V2ThreadTurnsListResponse__McpToolCallResult | null; + readonly server: string; + readonly status: V2ThreadTurnsListResponse__McpToolCallStatus; + readonly tool: string; + readonly type: "mcpToolCall"; + } + | { + readonly arguments: unknown; + readonly contentItems?: ReadonlyArray | null; + readonly durationMs?: number | null; + readonly id: string; + readonly namespace?: string | null; + readonly status: V2ThreadTurnsListResponse__DynamicToolCallStatus; + readonly success?: boolean | null; + readonly tool: string; + readonly type: "dynamicToolCall"; + } + | { + readonly agentsStates: { readonly [x: string]: V2ThreadTurnsListResponse__CollabAgentState }; + readonly id: string; + readonly model?: string | null; + readonly prompt?: string | null; + readonly reasoningEffort?: V2ThreadTurnsListResponse__ReasoningEffort | null; + readonly receiverThreadIds: ReadonlyArray; + readonly senderThreadId: string; + readonly status: "inProgress" | "completed" | "failed"; + readonly tool: "spawnAgent" | "sendInput" | "resumeAgent" | "wait" | "closeAgent"; + readonly type: "collabAgentToolCall"; + } + | { + readonly action?: V2ThreadTurnsListResponse__WebSearchAction | null; + readonly id: string; + readonly query: string; + readonly type: "webSearch"; + } + | { + readonly id: string; + readonly path: V2ThreadTurnsListResponse__AbsolutePathBuf; + readonly type: "imageView"; + } + | { + readonly id: string; + readonly result: string; + readonly revisedPrompt?: string | null; + readonly savedPath?: V2ThreadTurnsListResponse__AbsolutePathBuf | null; + readonly status: string; + readonly type: "imageGeneration"; + } + | { readonly id: string; readonly review: string; readonly type: "enteredReviewMode" } + | { readonly id: string; readonly review: string; readonly type: "exitedReviewMode" } + | { readonly id: string; readonly type: "contextCompaction" }; +export const V2ThreadTurnsListResponse__ThreadItem = Schema.Union( + [ + Schema.Struct({ + content: Schema.Array(V2ThreadTurnsListResponse__UserInput), + id: Schema.String, + type: Schema.Literal("userMessage").annotate({ title: "UserMessageThreadItemType" }), + }).annotate({ title: "UserMessageThreadItem" }), + Schema.Struct({ + fragments: Schema.Array(V2ThreadTurnsListResponse__HookPromptFragment), + id: Schema.String, + type: Schema.Literal("hookPrompt").annotate({ title: "HookPromptThreadItemType" }), + }).annotate({ title: "HookPromptThreadItem" }), + Schema.Struct({ + id: Schema.String, + memoryCitation: Schema.optionalKey( + Schema.Union([V2ThreadTurnsListResponse__MemoryCitation, Schema.Null]), + ), + phase: Schema.optionalKey( + Schema.Union([V2ThreadTurnsListResponse__MessagePhase, Schema.Null]), + ), + text: Schema.String, + type: Schema.Literal("agentMessage").annotate({ title: "AgentMessageThreadItemType" }), + }).annotate({ title: "AgentMessageThreadItem" }), + Schema.Struct({ + id: Schema.String, + text: Schema.String, + type: Schema.Literal("plan").annotate({ title: "PlanThreadItemType" }), + }).annotate({ + title: "PlanThreadItem", + description: + "EXPERIMENTAL - proposed plan item content. The completed plan item is authoritative and may not match the concatenation of `PlanDelta` text.", + }), + Schema.Struct({ + content: Schema.optionalKey(Schema.Array(Schema.String).annotate({ default: [] })), + id: Schema.String, + summary: Schema.optionalKey(Schema.Array(Schema.String).annotate({ default: [] })), + type: Schema.Literal("reasoning").annotate({ title: "ReasoningThreadItemType" }), + }).annotate({ title: "ReasoningThreadItem" }), + Schema.Struct({ + aggregatedOutput: Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + description: "The command's output, aggregated from stdout and stderr.", + }), + Schema.Null, + ]), + ), + command: Schema.String.annotate({ description: "The command to be executed." }), + commandActions: Schema.Array(V2ThreadTurnsListResponse__CommandAction).annotate({ + description: + "A best-effort parsing of the command to understand the action(s) it will perform. This returns a list of CommandAction objects because a single shell command may be composed of many commands piped together.", + }), + cwd: Schema.String.annotate({ + description: + "A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\n\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.", + }), + durationMs: Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ + description: "The duration of the command execution in milliseconds.", + format: "int64", + }).check(Schema.isInt()), + Schema.Null, + ]), + ), + exitCode: Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ + description: "The command's exit code.", + format: "int32", + }).check(Schema.isInt()), + Schema.Null, + ]), + ), + id: Schema.String, + processId: Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + description: "Identifier for the underlying PTY process (when available).", + }), + Schema.Null, + ]), + ), + source: Schema.optionalKey( + Schema.Literals([ + "agent", + "userShell", + "unifiedExecStartup", + "unifiedExecInteraction", + ]).annotate({ default: "agent" }), + ), + status: V2ThreadTurnsListResponse__CommandExecutionStatus, + type: Schema.Literal("commandExecution").annotate({ + title: "CommandExecutionThreadItemType", + }), + }).annotate({ title: "CommandExecutionThreadItem" }), + Schema.Struct({ + changes: Schema.Array(V2ThreadTurnsListResponse__FileUpdateChange), + id: Schema.String, + status: V2ThreadTurnsListResponse__PatchApplyStatus, + type: Schema.Literal("fileChange").annotate({ title: "FileChangeThreadItemType" }), + }).annotate({ title: "FileChangeThreadItem" }), + Schema.Struct({ + arguments: Schema.Unknown, + durationMs: Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ + description: "The duration of the MCP tool call in milliseconds.", + format: "int64", + }).check(Schema.isInt()), + Schema.Null, + ]), + ), + error: Schema.optionalKey( + Schema.Union([V2ThreadTurnsListResponse__McpToolCallError, Schema.Null]), + ), + id: Schema.String, + mcpAppResourceUri: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + result: Schema.optionalKey( + Schema.Union([V2ThreadTurnsListResponse__McpToolCallResult, Schema.Null]), + ), + server: Schema.String, + status: V2ThreadTurnsListResponse__McpToolCallStatus, + tool: Schema.String, + type: Schema.Literal("mcpToolCall").annotate({ title: "McpToolCallThreadItemType" }), + }).annotate({ title: "McpToolCallThreadItem" }), + Schema.Struct({ + arguments: Schema.Unknown, + contentItems: Schema.optionalKey( + Schema.Union([ + Schema.Array(V2ThreadTurnsListResponse__DynamicToolCallOutputContentItem), + Schema.Null, + ]), + ), + durationMs: Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ + description: "The duration of the dynamic tool call in milliseconds.", + format: "int64", + }).check(Schema.isInt()), + Schema.Null, + ]), + ), + id: Schema.String, + namespace: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + status: V2ThreadTurnsListResponse__DynamicToolCallStatus, + success: Schema.optionalKey(Schema.Union([Schema.Boolean, Schema.Null])), + tool: Schema.String, + type: Schema.Literal("dynamicToolCall").annotate({ title: "DynamicToolCallThreadItemType" }), + }).annotate({ title: "DynamicToolCallThreadItem" }), + Schema.Struct({ + agentsStates: Schema.Record( + Schema.String, + V2ThreadTurnsListResponse__CollabAgentState, + ).annotate({ description: "Last known status of the target agents, when available." }), + id: Schema.String.annotate({ description: "Unique identifier for this collab tool call." }), + model: Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + description: "Model requested for the spawned agent, when applicable.", + }), + Schema.Null, + ]), + ), + prompt: Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + description: "Prompt text sent as part of the collab tool call, when available.", + }), + Schema.Null, + ]), + ), + reasoningEffort: Schema.optionalKey( + Schema.Union([V2ThreadTurnsListResponse__ReasoningEffort, Schema.Null]).annotate({ + description: "Reasoning effort requested for the spawned agent, when applicable.", + }), + ), + receiverThreadIds: Schema.Array(Schema.String).annotate({ + description: + "Thread ID of the receiving agent, when applicable. In case of spawn operation, this corresponds to the newly spawned agent.", + }), + senderThreadId: Schema.String.annotate({ + description: "Thread ID of the agent issuing the collab request.", + }), + status: Schema.Literals(["inProgress", "completed", "failed"]).annotate({ + description: "Current status of the collab tool call.", + }), + tool: Schema.Literals([ + "spawnAgent", + "sendInput", + "resumeAgent", + "wait", + "closeAgent", + ]).annotate({ description: "Name of the collab tool that was invoked." }), + type: Schema.Literal("collabAgentToolCall").annotate({ + title: "CollabAgentToolCallThreadItemType", + }), + }).annotate({ title: "CollabAgentToolCallThreadItem" }), + Schema.Struct({ + action: Schema.optionalKey( + Schema.Union([V2ThreadTurnsListResponse__WebSearchAction, Schema.Null]), + ), + id: Schema.String, + query: Schema.String, + type: Schema.Literal("webSearch").annotate({ title: "WebSearchThreadItemType" }), + }).annotate({ title: "WebSearchThreadItem" }), + Schema.Struct({ + id: Schema.String, + path: V2ThreadTurnsListResponse__AbsolutePathBuf, + type: Schema.Literal("imageView").annotate({ title: "ImageViewThreadItemType" }), + }).annotate({ title: "ImageViewThreadItem" }), + Schema.Struct({ + id: Schema.String, + result: Schema.String, + revisedPrompt: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + savedPath: Schema.optionalKey( + Schema.Union([V2ThreadTurnsListResponse__AbsolutePathBuf, Schema.Null]), + ), status: Schema.String, type: Schema.Literal("imageGeneration").annotate({ title: "ImageGenerationThreadItemType" }), }).annotate({ title: "ImageGenerationThreadItem" }), @@ -20759,6 +22783,7 @@ export type V2ThreadUnarchiveResponse__ThreadItem = readonly durationMs?: number | null; readonly error?: V2ThreadUnarchiveResponse__McpToolCallError | null; readonly id: string; + readonly mcpAppResourceUri?: string | null; readonly result?: V2ThreadUnarchiveResponse__McpToolCallResult | null; readonly server: string; readonly status: V2ThreadUnarchiveResponse__McpToolCallStatus; @@ -20770,6 +22795,7 @@ export type V2ThreadUnarchiveResponse__ThreadItem = readonly contentItems?: ReadonlyArray | null; readonly durationMs?: number | null; readonly id: string; + readonly namespace?: string | null; readonly status: V2ThreadUnarchiveResponse__DynamicToolCallStatus; readonly success?: boolean | null; readonly tool: string; @@ -20793,12 +22819,16 @@ export type V2ThreadUnarchiveResponse__ThreadItem = readonly query: string; readonly type: "webSearch"; } - | { readonly id: string; readonly path: string; readonly type: "imageView" } + | { + readonly id: string; + readonly path: V2ThreadUnarchiveResponse__AbsolutePathBuf; + readonly type: "imageView"; + } | { readonly id: string; readonly result: string; readonly revisedPrompt?: string | null; - readonly savedPath?: string | null; + readonly savedPath?: V2ThreadUnarchiveResponse__AbsolutePathBuf | null; readonly status: string; readonly type: "imageGeneration"; } @@ -20857,7 +22887,10 @@ export const V2ThreadUnarchiveResponse__ThreadItem = Schema.Union( description: "A best-effort parsing of the command to understand the action(s) it will perform. This returns a list of CommandAction objects because a single shell command may be composed of many commands piped together.", }), - cwd: Schema.String.annotate({ description: "The command's working directory." }), + cwd: Schema.String.annotate({ + description: + "A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\n\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.", + }), durationMs: Schema.optionalKey( Schema.Union([ Schema.Number.annotate({ @@ -20919,6 +22952,7 @@ export const V2ThreadUnarchiveResponse__ThreadItem = Schema.Union( Schema.Union([V2ThreadUnarchiveResponse__McpToolCallError, Schema.Null]), ), id: Schema.String, + mcpAppResourceUri: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), result: Schema.optionalKey( Schema.Union([V2ThreadUnarchiveResponse__McpToolCallResult, Schema.Null]), ), @@ -20945,6 +22979,7 @@ export const V2ThreadUnarchiveResponse__ThreadItem = Schema.Union( ]), ), id: Schema.String, + namespace: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), status: V2ThreadUnarchiveResponse__DynamicToolCallStatus, success: Schema.optionalKey(Schema.Union([Schema.Boolean, Schema.Null])), tool: Schema.String, @@ -21008,14 +23043,16 @@ export const V2ThreadUnarchiveResponse__ThreadItem = Schema.Union( }).annotate({ title: "WebSearchThreadItem" }), Schema.Struct({ id: Schema.String, - path: Schema.String, + path: V2ThreadUnarchiveResponse__AbsolutePathBuf, type: Schema.Literal("imageView").annotate({ title: "ImageViewThreadItemType" }), }).annotate({ title: "ImageViewThreadItem" }), Schema.Struct({ id: Schema.String, result: Schema.String, revisedPrompt: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), - savedPath: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + savedPath: Schema.optionalKey( + Schema.Union([V2ThreadUnarchiveResponse__AbsolutePathBuf, Schema.Null]), + ), status: Schema.String, type: Schema.Literal("imageGeneration").annotate({ title: "ImageGenerationThreadItemType" }), }).annotate({ title: "ImageGenerationThreadItem" }), @@ -21105,6 +23142,7 @@ export type V2TurnCompletedNotification__ThreadItem = readonly durationMs?: number | null; readonly error?: V2TurnCompletedNotification__McpToolCallError | null; readonly id: string; + readonly mcpAppResourceUri?: string | null; readonly result?: V2TurnCompletedNotification__McpToolCallResult | null; readonly server: string; readonly status: V2TurnCompletedNotification__McpToolCallStatus; @@ -21116,6 +23154,7 @@ export type V2TurnCompletedNotification__ThreadItem = readonly contentItems?: ReadonlyArray | null; readonly durationMs?: number | null; readonly id: string; + readonly namespace?: string | null; readonly status: V2TurnCompletedNotification__DynamicToolCallStatus; readonly success?: boolean | null; readonly tool: string; @@ -21141,12 +23180,16 @@ export type V2TurnCompletedNotification__ThreadItem = readonly query: string; readonly type: "webSearch"; } - | { readonly id: string; readonly path: string; readonly type: "imageView" } + | { + readonly id: string; + readonly path: V2TurnCompletedNotification__AbsolutePathBuf; + readonly type: "imageView"; + } | { readonly id: string; readonly result: string; readonly revisedPrompt?: string | null; - readonly savedPath?: string | null; + readonly savedPath?: V2TurnCompletedNotification__AbsolutePathBuf | null; readonly status: string; readonly type: "imageGeneration"; } @@ -21205,7 +23248,10 @@ export const V2TurnCompletedNotification__ThreadItem = Schema.Union( description: "A best-effort parsing of the command to understand the action(s) it will perform. This returns a list of CommandAction objects because a single shell command may be composed of many commands piped together.", }), - cwd: Schema.String.annotate({ description: "The command's working directory." }), + cwd: Schema.String.annotate({ + description: + "A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\n\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.", + }), durationMs: Schema.optionalKey( Schema.Union([ Schema.Number.annotate({ @@ -21267,6 +23313,7 @@ export const V2TurnCompletedNotification__ThreadItem = Schema.Union( Schema.Union([V2TurnCompletedNotification__McpToolCallError, Schema.Null]), ), id: Schema.String, + mcpAppResourceUri: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), result: Schema.optionalKey( Schema.Union([V2TurnCompletedNotification__McpToolCallResult, Schema.Null]), ), @@ -21293,6 +23340,7 @@ export const V2TurnCompletedNotification__ThreadItem = Schema.Union( ]), ), id: Schema.String, + namespace: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), status: V2TurnCompletedNotification__DynamicToolCallStatus, success: Schema.optionalKey(Schema.Union([Schema.Boolean, Schema.Null])), tool: Schema.String, @@ -21356,14 +23404,16 @@ export const V2TurnCompletedNotification__ThreadItem = Schema.Union( }).annotate({ title: "WebSearchThreadItem" }), Schema.Struct({ id: Schema.String, - path: Schema.String, + path: V2TurnCompletedNotification__AbsolutePathBuf, type: Schema.Literal("imageView").annotate({ title: "ImageViewThreadItemType" }), }).annotate({ title: "ImageViewThreadItem" }), Schema.Struct({ id: Schema.String, result: Schema.String, revisedPrompt: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), - savedPath: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + savedPath: Schema.optionalKey( + Schema.Union([V2TurnCompletedNotification__AbsolutePathBuf, Schema.Null]), + ), status: Schema.String, type: Schema.Literal("imageGeneration").annotate({ title: "ImageGenerationThreadItemType" }), }).annotate({ title: "ImageGenerationThreadItem" }), @@ -21453,6 +23503,7 @@ export type V2TurnStartedNotification__ThreadItem = readonly durationMs?: number | null; readonly error?: V2TurnStartedNotification__McpToolCallError | null; readonly id: string; + readonly mcpAppResourceUri?: string | null; readonly result?: V2TurnStartedNotification__McpToolCallResult | null; readonly server: string; readonly status: V2TurnStartedNotification__McpToolCallStatus; @@ -21464,6 +23515,7 @@ export type V2TurnStartedNotification__ThreadItem = readonly contentItems?: ReadonlyArray | null; readonly durationMs?: number | null; readonly id: string; + readonly namespace?: string | null; readonly status: V2TurnStartedNotification__DynamicToolCallStatus; readonly success?: boolean | null; readonly tool: string; @@ -21487,12 +23539,16 @@ export type V2TurnStartedNotification__ThreadItem = readonly query: string; readonly type: "webSearch"; } - | { readonly id: string; readonly path: string; readonly type: "imageView" } + | { + readonly id: string; + readonly path: V2TurnStartedNotification__AbsolutePathBuf; + readonly type: "imageView"; + } | { readonly id: string; readonly result: string; readonly revisedPrompt?: string | null; - readonly savedPath?: string | null; + readonly savedPath?: V2TurnStartedNotification__AbsolutePathBuf | null; readonly status: string; readonly type: "imageGeneration"; } @@ -21551,7 +23607,10 @@ export const V2TurnStartedNotification__ThreadItem = Schema.Union( description: "A best-effort parsing of the command to understand the action(s) it will perform. This returns a list of CommandAction objects because a single shell command may be composed of many commands piped together.", }), - cwd: Schema.String.annotate({ description: "The command's working directory." }), + cwd: Schema.String.annotate({ + description: + "A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\n\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.", + }), durationMs: Schema.optionalKey( Schema.Union([ Schema.Number.annotate({ @@ -21613,6 +23672,7 @@ export const V2TurnStartedNotification__ThreadItem = Schema.Union( Schema.Union([V2TurnStartedNotification__McpToolCallError, Schema.Null]), ), id: Schema.String, + mcpAppResourceUri: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), result: Schema.optionalKey( Schema.Union([V2TurnStartedNotification__McpToolCallResult, Schema.Null]), ), @@ -21639,6 +23699,7 @@ export const V2TurnStartedNotification__ThreadItem = Schema.Union( ]), ), id: Schema.String, + namespace: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), status: V2TurnStartedNotification__DynamicToolCallStatus, success: Schema.optionalKey(Schema.Union([Schema.Boolean, Schema.Null])), tool: Schema.String, @@ -21702,14 +23763,16 @@ export const V2TurnStartedNotification__ThreadItem = Schema.Union( }).annotate({ title: "WebSearchThreadItem" }), Schema.Struct({ id: Schema.String, - path: Schema.String, + path: V2TurnStartedNotification__AbsolutePathBuf, type: Schema.Literal("imageView").annotate({ title: "ImageViewThreadItemType" }), }).annotate({ title: "ImageViewThreadItem" }), Schema.Struct({ id: Schema.String, result: Schema.String, revisedPrompt: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), - savedPath: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + savedPath: Schema.optionalKey( + Schema.Union([V2TurnStartedNotification__AbsolutePathBuf, Schema.Null]), + ), status: Schema.String, type: Schema.Literal("imageGeneration").annotate({ title: "ImageGenerationThreadItemType" }), }).annotate({ title: "ImageGenerationThreadItem" }), @@ -21799,6 +23862,7 @@ export type V2TurnStartResponse__ThreadItem = readonly durationMs?: number | null; readonly error?: V2TurnStartResponse__McpToolCallError | null; readonly id: string; + readonly mcpAppResourceUri?: string | null; readonly result?: V2TurnStartResponse__McpToolCallResult | null; readonly server: string; readonly status: V2TurnStartResponse__McpToolCallStatus; @@ -21810,6 +23874,7 @@ export type V2TurnStartResponse__ThreadItem = readonly contentItems?: ReadonlyArray | null; readonly durationMs?: number | null; readonly id: string; + readonly namespace?: string | null; readonly status: V2TurnStartResponse__DynamicToolCallStatus; readonly success?: boolean | null; readonly tool: string; @@ -21833,12 +23898,16 @@ export type V2TurnStartResponse__ThreadItem = readonly query: string; readonly type: "webSearch"; } - | { readonly id: string; readonly path: string; readonly type: "imageView" } + | { + readonly id: string; + readonly path: V2TurnStartResponse__AbsolutePathBuf; + readonly type: "imageView"; + } | { readonly id: string; readonly result: string; readonly revisedPrompt?: string | null; - readonly savedPath?: string | null; + readonly savedPath?: V2TurnStartResponse__AbsolutePathBuf | null; readonly status: string; readonly type: "imageGeneration"; } @@ -21895,7 +23964,10 @@ export const V2TurnStartResponse__ThreadItem = Schema.Union( description: "A best-effort parsing of the command to understand the action(s) it will perform. This returns a list of CommandAction objects because a single shell command may be composed of many commands piped together.", }), - cwd: Schema.String.annotate({ description: "The command's working directory." }), + cwd: Schema.String.annotate({ + description: + "A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\n\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.", + }), durationMs: Schema.optionalKey( Schema.Union([ Schema.Number.annotate({ @@ -21955,6 +24027,7 @@ export const V2TurnStartResponse__ThreadItem = Schema.Union( ), error: Schema.optionalKey(Schema.Union([V2TurnStartResponse__McpToolCallError, Schema.Null])), id: Schema.String, + mcpAppResourceUri: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), result: Schema.optionalKey( Schema.Union([V2TurnStartResponse__McpToolCallResult, Schema.Null]), ), @@ -21981,6 +24054,7 @@ export const V2TurnStartResponse__ThreadItem = Schema.Union( ]), ), id: Schema.String, + namespace: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), status: V2TurnStartResponse__DynamicToolCallStatus, success: Schema.optionalKey(Schema.Union([Schema.Boolean, Schema.Null])), tool: Schema.String, @@ -22041,14 +24115,16 @@ export const V2TurnStartResponse__ThreadItem = Schema.Union( }).annotate({ title: "WebSearchThreadItem" }), Schema.Struct({ id: Schema.String, - path: Schema.String, + path: V2TurnStartResponse__AbsolutePathBuf, type: Schema.Literal("imageView").annotate({ title: "ImageViewThreadItemType" }), }).annotate({ title: "ImageViewThreadItem" }), Schema.Struct({ id: Schema.String, result: Schema.String, revisedPrompt: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), - savedPath: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + savedPath: Schema.optionalKey( + Schema.Union([V2TurnStartResponse__AbsolutePathBuf, Schema.Null]), + ), status: Schema.String, type: Schema.Literal("imageGeneration").annotate({ title: "ImageGenerationThreadItemType" }), }).annotate({ title: "ImageGenerationThreadItem" }), @@ -22076,6 +24152,50 @@ export const V2TurnStartResponse__ThreadItem = Schema.Union( { mode: "oneOf" }, ); +export type ClientRequest__ExternalAgentConfigImportParams = { + readonly migrationItems: ReadonlyArray; +}; +export const ClientRequest__ExternalAgentConfigImportParams = Schema.Struct({ + migrationItems: Schema.Array(ClientRequest__ExternalAgentConfigMigrationItem), +}); + +export type CommandExecutionRequestApprovalParams__AdditionalFileSystemPermissions = { + readonly entries?: ReadonlyArray | null; + readonly globScanMaxDepth?: number | null; + readonly read?: ReadonlyArray | null; + readonly write?: ReadonlyArray | null; +}; +export const CommandExecutionRequestApprovalParams__AdditionalFileSystemPermissions = Schema.Struct( + { + entries: Schema.optionalKey( + Schema.Union([ + Schema.Array(CommandExecutionRequestApprovalParams__FileSystemSandboxEntry), + Schema.Null, + ]), + ), + globScanMaxDepth: Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ format: "uint" }) + .check(Schema.isInt()) + .check(Schema.isGreaterThanOrEqualTo(1)), + Schema.Null, + ]), + ), + read: Schema.optionalKey( + Schema.Union([ + Schema.Array(CommandExecutionRequestApprovalParams__AbsolutePathBuf), + Schema.Null, + ]), + ), + write: Schema.optionalKey( + Schema.Union([ + Schema.Array(CommandExecutionRequestApprovalParams__AbsolutePathBuf), + Schema.Null, + ]), + ), + }, +); + export type McpServerElicitationRequestParams__McpElicitationMultiSelectEnumSchema = | McpServerElicitationRequestParams__McpElicitationUntitledMultiSelectEnumSchema | McpServerElicitationRequestParams__McpElicitationTitledMultiSelectEnumSchema; @@ -22084,6 +24204,64 @@ export const McpServerElicitationRequestParams__McpElicitationMultiSelectEnumSch McpServerElicitationRequestParams__McpElicitationTitledMultiSelectEnumSchema, ]); +export type PermissionsRequestApprovalParams__AdditionalFileSystemPermissions = { + readonly entries?: ReadonlyArray | null; + readonly globScanMaxDepth?: number | null; + readonly read?: ReadonlyArray | null; + readonly write?: ReadonlyArray | null; +}; +export const PermissionsRequestApprovalParams__AdditionalFileSystemPermissions = Schema.Struct({ + entries: Schema.optionalKey( + Schema.Union([ + Schema.Array(PermissionsRequestApprovalParams__FileSystemSandboxEntry), + Schema.Null, + ]), + ), + globScanMaxDepth: Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ format: "uint" }) + .check(Schema.isInt()) + .check(Schema.isGreaterThanOrEqualTo(1)), + Schema.Null, + ]), + ), + read: Schema.optionalKey( + Schema.Union([Schema.Array(PermissionsRequestApprovalParams__AbsolutePathBuf), Schema.Null]), + ), + write: Schema.optionalKey( + Schema.Union([Schema.Array(PermissionsRequestApprovalParams__AbsolutePathBuf), Schema.Null]), + ), +}); + +export type PermissionsRequestApprovalResponse__AdditionalFileSystemPermissions = { + readonly entries?: ReadonlyArray | null; + readonly globScanMaxDepth?: number | null; + readonly read?: ReadonlyArray | null; + readonly write?: ReadonlyArray | null; +}; +export const PermissionsRequestApprovalResponse__AdditionalFileSystemPermissions = Schema.Struct({ + entries: Schema.optionalKey( + Schema.Union([ + Schema.Array(PermissionsRequestApprovalResponse__FileSystemSandboxEntry), + Schema.Null, + ]), + ), + globScanMaxDepth: Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ format: "uint" }) + .check(Schema.isInt()) + .check(Schema.isGreaterThanOrEqualTo(1)), + Schema.Null, + ]), + ), + read: Schema.optionalKey( + Schema.Union([Schema.Array(PermissionsRequestApprovalResponse__AbsolutePathBuf), Schema.Null]), + ), + write: Schema.optionalKey( + Schema.Union([Schema.Array(PermissionsRequestApprovalResponse__AbsolutePathBuf), Schema.Null]), + ), +}); + export type ServerNotification__AppListUpdatedNotification = { readonly data: ReadonlyArray; }; @@ -22091,6 +24269,32 @@ export const ServerNotification__AppListUpdatedNotification = Schema.Struct({ data: Schema.Array(ServerNotification__AppInfo), }).annotate({ description: "EXPERIMENTAL - notification emitted when the app list changes." }); +export type ServerNotification__AdditionalFileSystemPermissions = { + readonly entries?: ReadonlyArray | null; + readonly globScanMaxDepth?: number | null; + readonly read?: ReadonlyArray | null; + readonly write?: ReadonlyArray | null; +}; +export const ServerNotification__AdditionalFileSystemPermissions = Schema.Struct({ + entries: Schema.optionalKey( + Schema.Union([Schema.Array(ServerNotification__FileSystemSandboxEntry), Schema.Null]), + ), + globScanMaxDepth: Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ format: "uint" }) + .check(Schema.isInt()) + .check(Schema.isGreaterThanOrEqualTo(1)), + Schema.Null, + ]), + ), + read: Schema.optionalKey( + Schema.Union([Schema.Array(ServerNotification__AbsolutePathBuf), Schema.Null]), + ), + write: Schema.optionalKey( + Schema.Union([Schema.Array(ServerNotification__AbsolutePathBuf), Schema.Null]), + ), +}); + export type ServerNotification__HookCompletedNotification = { readonly run: ServerNotification__HookRunSummary; readonly threadId: string; @@ -22198,19 +24402,30 @@ export const ServerNotification__Turn = Schema.Struct({ status: ServerNotification__TurnStatus, }); -export type ServerRequest__PermissionsRequestApprovalParams = { - readonly itemId: string; - readonly permissions: ServerRequest__RequestPermissionProfile; - readonly reason?: string | null; - readonly threadId: string; - readonly turnId: string; +export type ServerRequest__AdditionalFileSystemPermissions = { + readonly entries?: ReadonlyArray | null; + readonly globScanMaxDepth?: number | null; + readonly read?: ReadonlyArray | null; + readonly write?: ReadonlyArray | null; }; -export const ServerRequest__PermissionsRequestApprovalParams = Schema.Struct({ - itemId: Schema.String, - permissions: ServerRequest__RequestPermissionProfile, - reason: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), - threadId: Schema.String, - turnId: Schema.String, +export const ServerRequest__AdditionalFileSystemPermissions = Schema.Struct({ + entries: Schema.optionalKey( + Schema.Union([Schema.Array(ServerRequest__FileSystemSandboxEntry), Schema.Null]), + ), + globScanMaxDepth: Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ format: "uint" }) + .check(Schema.isInt()) + .check(Schema.isGreaterThanOrEqualTo(1)), + Schema.Null, + ]), + ), + read: Schema.optionalKey( + Schema.Union([Schema.Array(ServerRequest__AbsolutePathBuf), Schema.Null]), + ), + write: Schema.optionalKey( + Schema.Union([Schema.Array(ServerRequest__AbsolutePathBuf), Schema.Null]), + ), }); export type ServerRequest__McpElicitationMultiSelectEnumSchema = @@ -22280,10 +24495,82 @@ export const V2ConfigWriteResponse__OverriddenMetadata = Schema.Struct({ overridingLayer: V2ConfigWriteResponse__ConfigLayerMetadata, }); +export type V2ItemGuardianApprovalReviewCompletedNotification__AdditionalFileSystemPermissions = { + readonly entries?: ReadonlyArray | null; + readonly globScanMaxDepth?: number | null; + readonly read?: ReadonlyArray | null; + readonly write?: ReadonlyArray | null; +}; +export const V2ItemGuardianApprovalReviewCompletedNotification__AdditionalFileSystemPermissions = + Schema.Struct({ + entries: Schema.optionalKey( + Schema.Union([ + Schema.Array(V2ItemGuardianApprovalReviewCompletedNotification__FileSystemSandboxEntry), + Schema.Null, + ]), + ), + globScanMaxDepth: Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ format: "uint" }) + .check(Schema.isInt()) + .check(Schema.isGreaterThanOrEqualTo(1)), + Schema.Null, + ]), + ), + read: Schema.optionalKey( + Schema.Union([ + Schema.Array(V2ItemGuardianApprovalReviewCompletedNotification__AbsolutePathBuf), + Schema.Null, + ]), + ), + write: Schema.optionalKey( + Schema.Union([ + Schema.Array(V2ItemGuardianApprovalReviewCompletedNotification__AbsolutePathBuf), + Schema.Null, + ]), + ), + }); + +export type V2ItemGuardianApprovalReviewStartedNotification__AdditionalFileSystemPermissions = { + readonly entries?: ReadonlyArray | null; + readonly globScanMaxDepth?: number | null; + readonly read?: ReadonlyArray | null; + readonly write?: ReadonlyArray | null; +}; +export const V2ItemGuardianApprovalReviewStartedNotification__AdditionalFileSystemPermissions = + Schema.Struct({ + entries: Schema.optionalKey( + Schema.Union([ + Schema.Array(V2ItemGuardianApprovalReviewStartedNotification__FileSystemSandboxEntry), + Schema.Null, + ]), + ), + globScanMaxDepth: Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ format: "uint" }) + .check(Schema.isInt()) + .check(Schema.isGreaterThanOrEqualTo(1)), + Schema.Null, + ]), + ), + read: Schema.optionalKey( + Schema.Union([ + Schema.Array(V2ItemGuardianApprovalReviewStartedNotification__AbsolutePathBuf), + Schema.Null, + ]), + ), + write: Schema.optionalKey( + Schema.Union([ + Schema.Array(V2ItemGuardianApprovalReviewStartedNotification__AbsolutePathBuf), + Schema.Null, + ]), + ), + }); + export type V2PluginListResponse__PluginMarketplaceEntry = { readonly interface?: V2PluginListResponse__MarketplaceInterface | null; readonly name: string; - readonly path: V2PluginListResponse__AbsolutePathBuf; + readonly path?: V2PluginListResponse__AbsolutePathBuf | null; readonly plugins: ReadonlyArray; }; export const V2PluginListResponse__PluginMarketplaceEntry = Schema.Struct({ @@ -22291,7 +24578,12 @@ export const V2PluginListResponse__PluginMarketplaceEntry = Schema.Struct({ Schema.Union([V2PluginListResponse__MarketplaceInterface, Schema.Null]), ), name: Schema.String, - path: V2PluginListResponse__AbsolutePathBuf, + path: Schema.optionalKey( + Schema.Union([V2PluginListResponse__AbsolutePathBuf, Schema.Null]).annotate({ + description: + "Local marketplace file path when the marketplace is backed by a local file. Remote-only catalog marketplaces do not have a local path.", + }), + ), plugins: Schema.Array(V2PluginListResponse__PluginSummary), }); @@ -23000,6 +25292,56 @@ export const V2ThreadStartResponse__Turn = Schema.Struct({ status: V2ThreadStartResponse__TurnStatus, }); +export type V2ThreadTurnsListResponse__Turn = { + readonly completedAt?: number | null; + readonly durationMs?: number | null; + readonly error?: V2ThreadTurnsListResponse__TurnError | null; + readonly id: string; + readonly items: ReadonlyArray; + readonly startedAt?: number | null; + readonly status: V2ThreadTurnsListResponse__TurnStatus; +}; +export const V2ThreadTurnsListResponse__Turn = Schema.Struct({ + completedAt: Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ + description: "Unix timestamp (in seconds) when the turn completed.", + format: "int64", + }).check(Schema.isInt()), + Schema.Null, + ]), + ), + durationMs: Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ + description: "Duration between turn start and completion in milliseconds, if known.", + format: "int64", + }).check(Schema.isInt()), + Schema.Null, + ]), + ), + error: Schema.optionalKey( + Schema.Union([V2ThreadTurnsListResponse__TurnError, Schema.Null]).annotate({ + description: "Only populated when the Turn's status is failed.", + }), + ), + id: Schema.String, + items: Schema.Array(V2ThreadTurnsListResponse__ThreadItem).annotate({ + description: + "Only populated on a `thread/resume` or `thread/fork` response. For all other responses and notifications returning a Turn, the items field will be an empty list.", + }), + startedAt: Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ + description: "Unix timestamp (in seconds) when the turn started.", + format: "int64", + }).check(Schema.isInt()), + Schema.Null, + ]), + ), + status: V2ThreadTurnsListResponse__TurnStatus, +}); + export type V2ThreadUnarchiveResponse__Turn = { readonly completedAt?: number | null; readonly durationMs?: number | null; @@ -23210,6 +25552,48 @@ export const McpServerElicitationRequestParams__McpElicitationEnumSchema = Schem McpServerElicitationRequestParams__McpElicitationLegacyTitledEnumSchema, ]); +export type PermissionsRequestApprovalParams__RequestPermissionProfile = { + readonly fileSystem?: PermissionsRequestApprovalParams__AdditionalFileSystemPermissions | null; + readonly network?: PermissionsRequestApprovalParams__AdditionalNetworkPermissions | null; +}; +export const PermissionsRequestApprovalParams__RequestPermissionProfile = Schema.Struct({ + fileSystem: Schema.optionalKey( + Schema.Union([PermissionsRequestApprovalParams__AdditionalFileSystemPermissions, Schema.Null]), + ), + network: Schema.optionalKey( + Schema.Union([PermissionsRequestApprovalParams__AdditionalNetworkPermissions, Schema.Null]), + ), +}); + +export type PermissionsRequestApprovalResponse__GrantedPermissionProfile = { + readonly fileSystem?: PermissionsRequestApprovalResponse__AdditionalFileSystemPermissions | null; + readonly network?: PermissionsRequestApprovalResponse__AdditionalNetworkPermissions | null; +}; +export const PermissionsRequestApprovalResponse__GrantedPermissionProfile = Schema.Struct({ + fileSystem: Schema.optionalKey( + Schema.Union([ + PermissionsRequestApprovalResponse__AdditionalFileSystemPermissions, + Schema.Null, + ]), + ), + network: Schema.optionalKey( + Schema.Union([PermissionsRequestApprovalResponse__AdditionalNetworkPermissions, Schema.Null]), + ), +}); + +export type ServerNotification__RequestPermissionProfile = { + readonly fileSystem?: ServerNotification__AdditionalFileSystemPermissions | null; + readonly network?: ServerNotification__AdditionalNetworkPermissions | null; +}; +export const ServerNotification__RequestPermissionProfile = Schema.Struct({ + fileSystem: Schema.optionalKey( + Schema.Union([ServerNotification__AdditionalFileSystemPermissions, Schema.Null]), + ), + network: Schema.optionalKey( + Schema.Union([ServerNotification__AdditionalNetworkPermissions, Schema.Null]), + ), +}); + export type ServerNotification__Thread = { readonly agentNickname?: string | null; readonly agentRole?: string | null; @@ -23268,7 +25652,10 @@ export const ServerNotification__Thread = Schema.Struct({ description: "Unix timestamp (in seconds) when the thread was created.", format: "int64", }).check(Schema.isInt()), - cwd: Schema.String.annotate({ description: "Working directory captured for the thread." }), + cwd: Schema.String.annotate({ + description: + "A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\n\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.", + }), ephemeral: Schema.Boolean.annotate({ description: "Whether the thread is ephemeral and should not be materialized on disk.", }), @@ -23362,6 +25749,19 @@ export const ServerNotification__TurnStartedNotification = Schema.Struct({ turn: ServerNotification__Turn, }); +export type ServerRequest__RequestPermissionProfile = { + readonly fileSystem?: ServerRequest__AdditionalFileSystemPermissions | null; + readonly network?: ServerRequest__AdditionalNetworkPermissions | null; +}; +export const ServerRequest__RequestPermissionProfile = Schema.Struct({ + fileSystem: Schema.optionalKey( + Schema.Union([ServerRequest__AdditionalFileSystemPermissions, Schema.Null]), + ), + network: Schema.optionalKey( + Schema.Union([ServerRequest__AdditionalNetworkPermissions, Schema.Null]), + ), +}); + export type ServerRequest__McpElicitationEnumSchema = | ServerRequest__McpElicitationSingleSelectEnumSchema | ServerRequest__McpElicitationMultiSelectEnumSchema @@ -23464,6 +25864,46 @@ export const V2ConfigReadResponse__Config = Schema.StructWithRest( [Schema.Record(Schema.String, Schema.Unknown)], ); +export type V2ItemGuardianApprovalReviewCompletedNotification__RequestPermissionProfile = { + readonly fileSystem?: V2ItemGuardianApprovalReviewCompletedNotification__AdditionalFileSystemPermissions | null; + readonly network?: V2ItemGuardianApprovalReviewCompletedNotification__AdditionalNetworkPermissions | null; +}; +export const V2ItemGuardianApprovalReviewCompletedNotification__RequestPermissionProfile = + Schema.Struct({ + fileSystem: Schema.optionalKey( + Schema.Union([ + V2ItemGuardianApprovalReviewCompletedNotification__AdditionalFileSystemPermissions, + Schema.Null, + ]), + ), + network: Schema.optionalKey( + Schema.Union([ + V2ItemGuardianApprovalReviewCompletedNotification__AdditionalNetworkPermissions, + Schema.Null, + ]), + ), + }); + +export type V2ItemGuardianApprovalReviewStartedNotification__RequestPermissionProfile = { + readonly fileSystem?: V2ItemGuardianApprovalReviewStartedNotification__AdditionalFileSystemPermissions | null; + readonly network?: V2ItemGuardianApprovalReviewStartedNotification__AdditionalNetworkPermissions | null; +}; +export const V2ItemGuardianApprovalReviewStartedNotification__RequestPermissionProfile = + Schema.Struct({ + fileSystem: Schema.optionalKey( + Schema.Union([ + V2ItemGuardianApprovalReviewStartedNotification__AdditionalFileSystemPermissions, + Schema.Null, + ]), + ), + network: Schema.optionalKey( + Schema.Union([ + V2ItemGuardianApprovalReviewStartedNotification__AdditionalNetworkPermissions, + Schema.Null, + ]), + ), + }); + export type V2ThreadForkResponse__Thread = { readonly agentNickname?: string | null; readonly agentRole?: string | null; @@ -23522,7 +25962,10 @@ export const V2ThreadForkResponse__Thread = Schema.Struct({ description: "Unix timestamp (in seconds) when the thread was created.", format: "int64", }).check(Schema.isInt()), - cwd: Schema.String.annotate({ description: "Working directory captured for the thread." }), + cwd: Schema.String.annotate({ + description: + "A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\n\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.", + }), ephemeral: Schema.Boolean.annotate({ description: "Whether the thread is ephemeral and should not be materialized on disk.", }), @@ -23656,7 +26099,10 @@ export const V2ThreadListResponse__Thread = Schema.Struct({ description: "Unix timestamp (in seconds) when the thread was created.", format: "int64", }).check(Schema.isInt()), - cwd: Schema.String.annotate({ description: "Working directory captured for the thread." }), + cwd: Schema.String.annotate({ + description: + "A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\n\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.", + }), ephemeral: Schema.Boolean.annotate({ description: "Whether the thread is ephemeral and should not be materialized on disk.", }), @@ -23790,7 +26236,10 @@ export const V2ThreadMetadataUpdateResponse__Thread = Schema.Struct({ description: "Unix timestamp (in seconds) when the thread was created.", format: "int64", }).check(Schema.isInt()), - cwd: Schema.String.annotate({ description: "Working directory captured for the thread." }), + cwd: Schema.String.annotate({ + description: + "A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\n\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.", + }), ephemeral: Schema.Boolean.annotate({ description: "Whether the thread is ephemeral and should not be materialized on disk.", }), @@ -23924,7 +26373,10 @@ export const V2ThreadReadResponse__Thread = Schema.Struct({ description: "Unix timestamp (in seconds) when the thread was created.", format: "int64", }).check(Schema.isInt()), - cwd: Schema.String.annotate({ description: "Working directory captured for the thread." }), + cwd: Schema.String.annotate({ + description: + "A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\n\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.", + }), ephemeral: Schema.Boolean.annotate({ description: "Whether the thread is ephemeral and should not be materialized on disk.", }), @@ -24058,7 +26510,10 @@ export const V2ThreadResumeResponse__Thread = Schema.Struct({ description: "Unix timestamp (in seconds) when the thread was created.", format: "int64", }).check(Schema.isInt()), - cwd: Schema.String.annotate({ description: "Working directory captured for the thread." }), + cwd: Schema.String.annotate({ + description: + "A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\n\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.", + }), ephemeral: Schema.Boolean.annotate({ description: "Whether the thread is ephemeral and should not be materialized on disk.", }), @@ -24192,7 +26647,10 @@ export const V2ThreadStartedNotification__Thread = Schema.Struct({ description: "Unix timestamp (in seconds) when the thread was created.", format: "int64", }).check(Schema.isInt()), - cwd: Schema.String.annotate({ description: "Working directory captured for the thread." }), + cwd: Schema.String.annotate({ + description: + "A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\n\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.", + }), ephemeral: Schema.Boolean.annotate({ description: "Whether the thread is ephemeral and should not be materialized on disk.", }), @@ -24326,7 +26784,10 @@ export const V2ThreadStartResponse__Thread = Schema.Struct({ description: "Unix timestamp (in seconds) when the thread was created.", format: "int64", }).check(Schema.isInt()), - cwd: Schema.String.annotate({ description: "Working directory captured for the thread." }), + cwd: Schema.String.annotate({ + description: + "A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\n\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.", + }), ephemeral: Schema.Boolean.annotate({ description: "Whether the thread is ephemeral and should not be materialized on disk.", }), @@ -24460,7 +26921,10 @@ export const V2ThreadUnarchiveResponse__Thread = Schema.Struct({ description: "Unix timestamp (in seconds) when the thread was created.", format: "int64", }).check(Schema.isInt()), - cwd: Schema.String.annotate({ description: "Working directory captured for the thread." }), + cwd: Schema.String.annotate({ + description: + "A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\n\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.", + }), ephemeral: Schema.Boolean.annotate({ description: "Whether the thread is ephemeral and should not be materialized on disk.", }), @@ -24548,6 +27012,101 @@ export const McpServerElicitationRequestParams__McpElicitationPrimitiveSchema = McpServerElicitationRequestParams__McpElicitationBooleanSchema, ]); +export type ServerNotification__GuardianApprovalReviewAction = + | { + readonly command: string; + readonly cwd: ServerNotification__AbsolutePathBuf; + readonly source: ServerNotification__GuardianCommandSource; + readonly type: "command"; + } + | { + readonly argv: ReadonlyArray; + readonly cwd: ServerNotification__AbsolutePathBuf; + readonly program: string; + readonly source: ServerNotification__GuardianCommandSource; + readonly type: "execve"; + } + | { + readonly cwd: ServerNotification__AbsolutePathBuf; + readonly files: ReadonlyArray; + readonly type: "applyPatch"; + } + | { + readonly host: string; + readonly port: number; + readonly protocol: ServerNotification__NetworkApprovalProtocol; + readonly target: string; + readonly type: "networkAccess"; + } + | { + readonly connectorId?: string | null; + readonly connectorName?: string | null; + readonly server: string; + readonly toolName: string; + readonly toolTitle?: string | null; + readonly type: "mcpToolCall"; + } + | { + readonly permissions: ServerNotification__RequestPermissionProfile; + readonly reason?: string | null; + readonly type: "requestPermissions"; + }; +export const ServerNotification__GuardianApprovalReviewAction = Schema.Union( + [ + Schema.Struct({ + command: Schema.String, + cwd: ServerNotification__AbsolutePathBuf, + source: ServerNotification__GuardianCommandSource, + type: Schema.Literal("command").annotate({ + title: "CommandGuardianApprovalReviewActionType", + }), + }).annotate({ title: "CommandGuardianApprovalReviewAction" }), + Schema.Struct({ + argv: Schema.Array(Schema.String), + cwd: ServerNotification__AbsolutePathBuf, + program: Schema.String, + source: ServerNotification__GuardianCommandSource, + type: Schema.Literal("execve").annotate({ title: "ExecveGuardianApprovalReviewActionType" }), + }).annotate({ title: "ExecveGuardianApprovalReviewAction" }), + Schema.Struct({ + cwd: ServerNotification__AbsolutePathBuf, + files: Schema.Array(ServerNotification__AbsolutePathBuf), + type: Schema.Literal("applyPatch").annotate({ + title: "ApplyPatchGuardianApprovalReviewActionType", + }), + }).annotate({ title: "ApplyPatchGuardianApprovalReviewAction" }), + Schema.Struct({ + host: Schema.String, + port: Schema.Number.annotate({ format: "uint16" }) + .check(Schema.isInt()) + .check(Schema.isGreaterThanOrEqualTo(0)), + protocol: ServerNotification__NetworkApprovalProtocol, + target: Schema.String, + type: Schema.Literal("networkAccess").annotate({ + title: "NetworkAccessGuardianApprovalReviewActionType", + }), + }).annotate({ title: "NetworkAccessGuardianApprovalReviewAction" }), + Schema.Struct({ + connectorId: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + connectorName: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + server: Schema.String, + toolName: Schema.String, + toolTitle: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + type: Schema.Literal("mcpToolCall").annotate({ + title: "McpToolCallGuardianApprovalReviewActionType", + }), + }).annotate({ title: "McpToolCallGuardianApprovalReviewAction" }), + Schema.Struct({ + permissions: ServerNotification__RequestPermissionProfile, + reason: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + type: Schema.Literal("requestPermissions").annotate({ + title: "RequestPermissionsGuardianApprovalReviewActionType", + }), + }).annotate({ title: "RequestPermissionsGuardianApprovalReviewAction" }), + ], + { mode: "oneOf" }, +); + export type ServerNotification__ThreadStartedNotification = { readonly thread: ServerNotification__Thread; }; @@ -24555,6 +27114,23 @@ export const ServerNotification__ThreadStartedNotification = Schema.Struct({ thread: ServerNotification__Thread, }); +export type ServerRequest__PermissionsRequestApprovalParams = { + readonly cwd: ServerRequest__AbsolutePathBuf; + readonly itemId: string; + readonly permissions: ServerRequest__RequestPermissionProfile; + readonly reason?: string | null; + readonly threadId: string; + readonly turnId: string; +}; +export const ServerRequest__PermissionsRequestApprovalParams = Schema.Struct({ + cwd: ServerRequest__AbsolutePathBuf, + itemId: Schema.String, + permissions: ServerRequest__RequestPermissionProfile, + reason: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + threadId: Schema.String, + turnId: Schema.String, +}); + export type ServerRequest__McpElicitationPrimitiveSchema = | ServerRequest__McpElicitationEnumSchema | ServerRequest__McpElicitationStringSchema @@ -24567,6 +27143,202 @@ export const ServerRequest__McpElicitationPrimitiveSchema = Schema.Union([ ServerRequest__McpElicitationBooleanSchema, ]); +export type V2ItemGuardianApprovalReviewCompletedNotification__GuardianApprovalReviewAction = + | { + readonly command: string; + readonly cwd: V2ItemGuardianApprovalReviewCompletedNotification__AbsolutePathBuf; + readonly source: V2ItemGuardianApprovalReviewCompletedNotification__GuardianCommandSource; + readonly type: "command"; + } + | { + readonly argv: ReadonlyArray; + readonly cwd: V2ItemGuardianApprovalReviewCompletedNotification__AbsolutePathBuf; + readonly program: string; + readonly source: V2ItemGuardianApprovalReviewCompletedNotification__GuardianCommandSource; + readonly type: "execve"; + } + | { + readonly cwd: V2ItemGuardianApprovalReviewCompletedNotification__AbsolutePathBuf; + readonly files: ReadonlyArray; + readonly type: "applyPatch"; + } + | { + readonly host: string; + readonly port: number; + readonly protocol: V2ItemGuardianApprovalReviewCompletedNotification__NetworkApprovalProtocol; + readonly target: string; + readonly type: "networkAccess"; + } + | { + readonly connectorId?: string | null; + readonly connectorName?: string | null; + readonly server: string; + readonly toolName: string; + readonly toolTitle?: string | null; + readonly type: "mcpToolCall"; + } + | { + readonly permissions: V2ItemGuardianApprovalReviewCompletedNotification__RequestPermissionProfile; + readonly reason?: string | null; + readonly type: "requestPermissions"; + }; +export const V2ItemGuardianApprovalReviewCompletedNotification__GuardianApprovalReviewAction = + Schema.Union( + [ + Schema.Struct({ + command: Schema.String, + cwd: V2ItemGuardianApprovalReviewCompletedNotification__AbsolutePathBuf, + source: V2ItemGuardianApprovalReviewCompletedNotification__GuardianCommandSource, + type: Schema.Literal("command").annotate({ + title: "CommandGuardianApprovalReviewActionType", + }), + }).annotate({ title: "CommandGuardianApprovalReviewAction" }), + Schema.Struct({ + argv: Schema.Array(Schema.String), + cwd: V2ItemGuardianApprovalReviewCompletedNotification__AbsolutePathBuf, + program: Schema.String, + source: V2ItemGuardianApprovalReviewCompletedNotification__GuardianCommandSource, + type: Schema.Literal("execve").annotate({ + title: "ExecveGuardianApprovalReviewActionType", + }), + }).annotate({ title: "ExecveGuardianApprovalReviewAction" }), + Schema.Struct({ + cwd: V2ItemGuardianApprovalReviewCompletedNotification__AbsolutePathBuf, + files: Schema.Array(V2ItemGuardianApprovalReviewCompletedNotification__AbsolutePathBuf), + type: Schema.Literal("applyPatch").annotate({ + title: "ApplyPatchGuardianApprovalReviewActionType", + }), + }).annotate({ title: "ApplyPatchGuardianApprovalReviewAction" }), + Schema.Struct({ + host: Schema.String, + port: Schema.Number.annotate({ format: "uint16" }) + .check(Schema.isInt()) + .check(Schema.isGreaterThanOrEqualTo(0)), + protocol: V2ItemGuardianApprovalReviewCompletedNotification__NetworkApprovalProtocol, + target: Schema.String, + type: Schema.Literal("networkAccess").annotate({ + title: "NetworkAccessGuardianApprovalReviewActionType", + }), + }).annotate({ title: "NetworkAccessGuardianApprovalReviewAction" }), + Schema.Struct({ + connectorId: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + connectorName: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + server: Schema.String, + toolName: Schema.String, + toolTitle: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + type: Schema.Literal("mcpToolCall").annotate({ + title: "McpToolCallGuardianApprovalReviewActionType", + }), + }).annotate({ title: "McpToolCallGuardianApprovalReviewAction" }), + Schema.Struct({ + permissions: V2ItemGuardianApprovalReviewCompletedNotification__RequestPermissionProfile, + reason: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + type: Schema.Literal("requestPermissions").annotate({ + title: "RequestPermissionsGuardianApprovalReviewActionType", + }), + }).annotate({ title: "RequestPermissionsGuardianApprovalReviewAction" }), + ], + { mode: "oneOf" }, + ); + +export type V2ItemGuardianApprovalReviewStartedNotification__GuardianApprovalReviewAction = + | { + readonly command: string; + readonly cwd: V2ItemGuardianApprovalReviewStartedNotification__AbsolutePathBuf; + readonly source: V2ItemGuardianApprovalReviewStartedNotification__GuardianCommandSource; + readonly type: "command"; + } + | { + readonly argv: ReadonlyArray; + readonly cwd: V2ItemGuardianApprovalReviewStartedNotification__AbsolutePathBuf; + readonly program: string; + readonly source: V2ItemGuardianApprovalReviewStartedNotification__GuardianCommandSource; + readonly type: "execve"; + } + | { + readonly cwd: V2ItemGuardianApprovalReviewStartedNotification__AbsolutePathBuf; + readonly files: ReadonlyArray; + readonly type: "applyPatch"; + } + | { + readonly host: string; + readonly port: number; + readonly protocol: V2ItemGuardianApprovalReviewStartedNotification__NetworkApprovalProtocol; + readonly target: string; + readonly type: "networkAccess"; + } + | { + readonly connectorId?: string | null; + readonly connectorName?: string | null; + readonly server: string; + readonly toolName: string; + readonly toolTitle?: string | null; + readonly type: "mcpToolCall"; + } + | { + readonly permissions: V2ItemGuardianApprovalReviewStartedNotification__RequestPermissionProfile; + readonly reason?: string | null; + readonly type: "requestPermissions"; + }; +export const V2ItemGuardianApprovalReviewStartedNotification__GuardianApprovalReviewAction = + Schema.Union( + [ + Schema.Struct({ + command: Schema.String, + cwd: V2ItemGuardianApprovalReviewStartedNotification__AbsolutePathBuf, + source: V2ItemGuardianApprovalReviewStartedNotification__GuardianCommandSource, + type: Schema.Literal("command").annotate({ + title: "CommandGuardianApprovalReviewActionType", + }), + }).annotate({ title: "CommandGuardianApprovalReviewAction" }), + Schema.Struct({ + argv: Schema.Array(Schema.String), + cwd: V2ItemGuardianApprovalReviewStartedNotification__AbsolutePathBuf, + program: Schema.String, + source: V2ItemGuardianApprovalReviewStartedNotification__GuardianCommandSource, + type: Schema.Literal("execve").annotate({ + title: "ExecveGuardianApprovalReviewActionType", + }), + }).annotate({ title: "ExecveGuardianApprovalReviewAction" }), + Schema.Struct({ + cwd: V2ItemGuardianApprovalReviewStartedNotification__AbsolutePathBuf, + files: Schema.Array(V2ItemGuardianApprovalReviewStartedNotification__AbsolutePathBuf), + type: Schema.Literal("applyPatch").annotate({ + title: "ApplyPatchGuardianApprovalReviewActionType", + }), + }).annotate({ title: "ApplyPatchGuardianApprovalReviewAction" }), + Schema.Struct({ + host: Schema.String, + port: Schema.Number.annotate({ format: "uint16" }) + .check(Schema.isInt()) + .check(Schema.isGreaterThanOrEqualTo(0)), + protocol: V2ItemGuardianApprovalReviewStartedNotification__NetworkApprovalProtocol, + target: Schema.String, + type: Schema.Literal("networkAccess").annotate({ + title: "NetworkAccessGuardianApprovalReviewActionType", + }), + }).annotate({ title: "NetworkAccessGuardianApprovalReviewAction" }), + Schema.Struct({ + connectorId: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + connectorName: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + server: Schema.String, + toolName: Schema.String, + toolTitle: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + type: Schema.Literal("mcpToolCall").annotate({ + title: "McpToolCallGuardianApprovalReviewActionType", + }), + }).annotate({ title: "McpToolCallGuardianApprovalReviewAction" }), + Schema.Struct({ + permissions: V2ItemGuardianApprovalReviewStartedNotification__RequestPermissionProfile, + reason: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + type: Schema.Literal("requestPermissions").annotate({ + title: "RequestPermissionsGuardianApprovalReviewActionType", + }), + }).annotate({ title: "RequestPermissionsGuardianApprovalReviewAction" }), + ], + { mode: "oneOf" }, + ); + export type McpServerElicitationRequestParams__McpElicitationSchema = { readonly $schema?: string | null; readonly properties: { @@ -24588,6 +27360,64 @@ export const McpServerElicitationRequestParams__McpElicitationSchema = Schema.St "Typed form schema for MCP `elicitation/create` requests.\n\nThis matches the `requestedSchema` shape from the MCP 2025-11-25 `ElicitRequestFormParams` schema.", }); +export type ServerNotification__ItemGuardianApprovalReviewCompletedNotification = { + readonly action: ServerNotification__GuardianApprovalReviewAction; + readonly decisionSource: ServerNotification__AutoReviewDecisionSource; + readonly review: ServerNotification__GuardianApprovalReview; + readonly reviewId: string; + readonly targetItemId?: string | null; + readonly threadId: string; + readonly turnId: string; +}; +export const ServerNotification__ItemGuardianApprovalReviewCompletedNotification = Schema.Struct({ + action: ServerNotification__GuardianApprovalReviewAction, + decisionSource: ServerNotification__AutoReviewDecisionSource, + review: ServerNotification__GuardianApprovalReview, + reviewId: Schema.String.annotate({ description: "Stable identifier for this review." }), + targetItemId: Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + description: + "Identifier for the reviewed item or tool call when one exists.\n\nIn most cases, one review maps to one target item. The exceptions are - execve reviews, where a single command may contain multiple execve calls to review (only possible when using the shell_zsh_fork feature) - network policy reviews, where there is no target item\n\nA network call is triggered by a CommandExecution item, so having a target_item_id set to the CommandExecution item would be misleading because the review is about the network call, not the command execution. Therefore, target_item_id is set to None for network policy reviews.", + }), + Schema.Null, + ]), + ), + threadId: Schema.String, + turnId: Schema.String, +}).annotate({ + description: + "[UNSTABLE] Temporary notification payload for approval auto-review. This shape is expected to change soon.", +}); + +export type ServerNotification__ItemGuardianApprovalReviewStartedNotification = { + readonly action: ServerNotification__GuardianApprovalReviewAction; + readonly review: ServerNotification__GuardianApprovalReview; + readonly reviewId: string; + readonly targetItemId?: string | null; + readonly threadId: string; + readonly turnId: string; +}; +export const ServerNotification__ItemGuardianApprovalReviewStartedNotification = Schema.Struct({ + action: ServerNotification__GuardianApprovalReviewAction, + review: ServerNotification__GuardianApprovalReview, + reviewId: Schema.String.annotate({ description: "Stable identifier for this review." }), + targetItemId: Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + description: + "Identifier for the reviewed item or tool call when one exists.\n\nIn most cases, one review maps to one target item. The exceptions are - execve reviews, where a single command may contain multiple execve calls to review (only possible when using the shell_zsh_fork feature) - network policy reviews, where there is no target item\n\nA network call is triggered by a CommandExecution item, so having a target_item_id set to the CommandExecution item would be misleading because the review is about the network call, not the command execution. Therefore, target_item_id is set to None for network policy reviews.", + }), + Schema.Null, + ]), + ), + threadId: Schema.String, + turnId: Schema.String, +}).annotate({ + description: + "[UNSTABLE] Temporary notification payload for approval auto-review. This shape is expected to change soon.", +}); + export type ServerRequest__McpElicitationSchema = { readonly $schema?: string | null; readonly properties: { readonly [x: string]: ServerRequest__McpElicitationPrimitiveSchema }; @@ -24819,11 +27649,31 @@ export type ClientRequest = readonly method: "thread/read"; readonly params: ClientRequest__ThreadReadParams; } + | { + readonly id: ClientRequest__RequestId; + readonly method: "thread/turns/list"; + readonly params: ClientRequest__ThreadTurnsListParams; + } + | { + readonly id: ClientRequest__RequestId; + readonly method: "thread/inject_items"; + readonly params: ClientRequest__ThreadInjectItemsParams; + } | { readonly id: ClientRequest__RequestId; readonly method: "skills/list"; readonly params: ClientRequest__SkillsListParams; } + | { + readonly id: ClientRequest__RequestId; + readonly method: "marketplace/add"; + readonly params: ClientRequest__MarketplaceAddParams; + } + | { + readonly id: ClientRequest__RequestId; + readonly method: "marketplace/remove"; + readonly params: ClientRequest__MarketplaceRemoveParams; + } | { readonly id: ClientRequest__RequestId; readonly method: "plugin/list"; @@ -24839,6 +27689,21 @@ export type ClientRequest = readonly method: "app/list"; readonly params: ClientRequest__AppsListParams; } + | { + readonly id: ClientRequest__RequestId; + readonly method: "device/key/create"; + readonly params: ClientRequest__DeviceKeyCreateParams; + } + | { + readonly id: ClientRequest__RequestId; + readonly method: "device/key/public"; + readonly params: ClientRequest__DeviceKeyPublicParams; + } + | { + readonly id: ClientRequest__RequestId; + readonly method: "device/key/sign"; + readonly params: ClientRequest__DeviceKeySignParams; + } | { readonly id: ClientRequest__RequestId; readonly method: "fs/readFile"; @@ -24984,6 +27849,11 @@ export type ClientRequest = readonly method: "account/rateLimits/read"; readonly params?: null; } + | { + readonly id: ClientRequest__RequestId; + readonly method: "account/sendAddCreditsNudgeEmail"; + readonly params: ClientRequest__SendAddCreditsNudgeEmailParams; + } | { readonly id: ClientRequest__RequestId; readonly method: "feedback/upload"; @@ -25138,11 +28008,41 @@ export const ClientRequest = Schema.Union( method: Schema.Literal("thread/read").annotate({ title: "Thread/readRequestMethod" }), params: ClientRequest__ThreadReadParams, }).annotate({ title: "Thread/readRequest" }), + Schema.Struct({ + id: ClientRequest__RequestId, + method: Schema.Literal("thread/turns/list").annotate({ + title: "Thread/turns/listRequestMethod", + }), + params: ClientRequest__ThreadTurnsListParams, + }).annotate({ title: "Thread/turns/listRequest" }), + Schema.Struct({ + id: ClientRequest__RequestId, + method: Schema.Literal("thread/inject_items").annotate({ + title: "Thread/injectItemsRequestMethod", + }), + params: ClientRequest__ThreadInjectItemsParams, + }).annotate({ + title: "Thread/injectItemsRequest", + description: + "Append raw Responses API items to the thread history without starting a user turn.", + }), Schema.Struct({ id: ClientRequest__RequestId, method: Schema.Literal("skills/list").annotate({ title: "Skills/listRequestMethod" }), params: ClientRequest__SkillsListParams, }).annotate({ title: "Skills/listRequest" }), + Schema.Struct({ + id: ClientRequest__RequestId, + method: Schema.Literal("marketplace/add").annotate({ title: "Marketplace/addRequestMethod" }), + params: ClientRequest__MarketplaceAddParams, + }).annotate({ title: "Marketplace/addRequest" }), + Schema.Struct({ + id: ClientRequest__RequestId, + method: Schema.Literal("marketplace/remove").annotate({ + title: "Marketplace/removeRequestMethod", + }), + params: ClientRequest__MarketplaceRemoveParams, + }).annotate({ title: "Marketplace/removeRequest" }), Schema.Struct({ id: ClientRequest__RequestId, method: Schema.Literal("plugin/list").annotate({ title: "Plugin/listRequestMethod" }), @@ -25158,6 +28058,25 @@ export const ClientRequest = Schema.Union( method: Schema.Literal("app/list").annotate({ title: "App/listRequestMethod" }), params: ClientRequest__AppsListParams, }).annotate({ title: "App/listRequest" }), + Schema.Struct({ + id: ClientRequest__RequestId, + method: Schema.Literal("device/key/create").annotate({ + title: "Device/key/createRequestMethod", + }), + params: ClientRequest__DeviceKeyCreateParams, + }).annotate({ title: "Device/key/createRequest" }), + Schema.Struct({ + id: ClientRequest__RequestId, + method: Schema.Literal("device/key/public").annotate({ + title: "Device/key/publicRequestMethod", + }), + params: ClientRequest__DeviceKeyPublicParams, + }).annotate({ title: "Device/key/publicRequest" }), + Schema.Struct({ + id: ClientRequest__RequestId, + method: Schema.Literal("device/key/sign").annotate({ title: "Device/key/signRequestMethod" }), + params: ClientRequest__DeviceKeySignParams, + }).annotate({ title: "Device/key/signRequest" }), Schema.Struct({ id: ClientRequest__RequestId, method: Schema.Literal("fs/readFile").annotate({ title: "Fs/readFileRequestMethod" }), @@ -25333,6 +28252,13 @@ export const ClientRequest = Schema.Union( }), params: Schema.optionalKey(Schema.Null), }).annotate({ title: "Account/rateLimits/readRequest" }), + Schema.Struct({ + id: ClientRequest__RequestId, + method: Schema.Literal("account/sendAddCreditsNudgeEmail").annotate({ + title: "Account/sendAddCreditsNudgeEmailRequestMethod", + }), + params: ClientRequest__SendAddCreditsNudgeEmailParams, + }).annotate({ title: "Account/sendAddCreditsNudgeEmailRequest" }), Schema.Struct({ id: ClientRequest__RequestId, method: Schema.Literal("feedback/upload").annotate({ title: "Feedback/uploadRequestMethod" }), @@ -25455,12 +28381,14 @@ export type ClientRequest__DynamicToolSpec = { readonly description: string; readonly inputSchema: unknown; readonly name: string; + readonly namespace?: string | null; }; export const ClientRequest__DynamicToolSpec = Schema.Struct({ deferLoading: Schema.optionalKey(Schema.Boolean), description: Schema.String, inputSchema: Schema.Unknown, name: Schema.String, + namespace: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), }); export type ClientRequest__NetworkAccess = "restricted" | "enabled"; @@ -25489,6 +28417,9 @@ export const ClientRequest__ReadOnlyAccess = Schema.Union( { mode: "oneOf" }, ); +export type ClientRequest__RealtimeOutputModality = "text" | "audio"; +export const ClientRequest__RealtimeOutputModality = Schema.Literals(["text", "audio"]); + export type ClientRequest__RealtimeVoice = | "alloy" | "arbor" @@ -25745,6 +28676,9 @@ export const ClientRequest__ResponseItem = Schema.Union( { mode: "oneOf" }, ); +export type ClientRequest__ThreadMemoryMode = "enabled" | "disabled"; +export const ClientRequest__ThreadMemoryMode = Schema.Literals(["enabled", "disabled"]); + export type ClientRequest__ThreadRealtimeAudioChunk = { readonly data: string; readonly itemId?: string | null; @@ -25796,7 +28730,7 @@ export type CommandExecutionRequestApprovalParams = { readonly approvalId?: string | null; readonly command?: string | null; readonly commandActions?: ReadonlyArray | null; - readonly cwd?: string | null; + readonly cwd?: CommandExecutionRequestApprovalParams__AbsolutePathBuf | null; readonly itemId: string; readonly networkApprovalContext?: CommandExecutionRequestApprovalParams__NetworkApprovalContext | null; readonly proposedExecpolicyAmendment?: ReadonlyArray | null; @@ -25830,10 +28764,9 @@ export const CommandExecutionRequestApprovalParams = Schema.Struct({ ]), ), cwd: Schema.optionalKey( - Schema.Union([ - Schema.String.annotate({ description: "The command's working directory." }), - Schema.Null, - ]), + Schema.Union([CommandExecutionRequestApprovalParams__AbsolutePathBuf, Schema.Null]).annotate({ + description: "The command's working directory.", + }), ), itemId: Schema.String, networkApprovalContext: Schema.optionalKey( @@ -25950,6 +28883,7 @@ export const CommandExecutionRequestApprovalResponse = Schema.Struct({ export type DynamicToolCallParams = { readonly arguments: unknown; readonly callId: string; + readonly namespace?: string | null; readonly threadId: string; readonly tool: string; readonly turnId: string; @@ -25957,6 +28891,7 @@ export type DynamicToolCallParams = { export const DynamicToolCallParams = Schema.Struct({ arguments: Schema.Unknown, callId: Schema.String, + namespace: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), threadId: Schema.String, tool: Schema.String, turnId: Schema.String, @@ -26276,6 +29211,7 @@ export const McpServerElicitationRequestResponse = Schema.Struct({ }).annotate({ title: "McpServerElicitationRequestResponse" }); export type PermissionsRequestApprovalParams = { + readonly cwd: PermissionsRequestApprovalParams__AbsolutePathBuf; readonly itemId: string; readonly permissions: PermissionsRequestApprovalParams__RequestPermissionProfile; readonly reason?: string | null; @@ -26283,6 +29219,7 @@ export type PermissionsRequestApprovalParams = { readonly turnId: string; }; export const PermissionsRequestApprovalParams = Schema.Struct({ + cwd: PermissionsRequestApprovalParams__AbsolutePathBuf, itemId: Schema.String, permissions: PermissionsRequestApprovalParams__RequestPermissionProfile, reason: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), @@ -26409,6 +29346,10 @@ export type ServerNotification = readonly method: "item/fileChange/outputDelta"; readonly params: ServerNotification__FileChangeOutputDeltaNotification; } + | { + readonly method: "item/fileChange/patchUpdated"; + readonly params: ServerNotification__FileChangePatchUpdatedNotification; + } | { readonly method: "serverRequest/resolved"; readonly params: ServerNotification__ServerRequestResolvedNotification; @@ -26437,6 +29378,10 @@ export type ServerNotification = readonly method: "app/list/updated"; readonly params: ServerNotification__AppListUpdatedNotification; } + | { + readonly method: "externalAgentConfig/import/completed"; + readonly params: ServerNotification__ExternalAgentConfigImportCompletedNotification; + } | { readonly method: "fs/changed"; readonly params: ServerNotification__FsChangedNotification } | { readonly method: "item/reasoning/summaryTextDelta"; @@ -26458,6 +29403,7 @@ export type ServerNotification = readonly method: "model/rerouted"; readonly params: ServerNotification__ModelReroutedNotification; } + | { readonly method: "warning"; readonly params: ServerNotification__WarningNotification } | { readonly method: "deprecationNotice"; readonly params: ServerNotification__DeprecationNoticeNotification; @@ -26483,8 +29429,12 @@ export type ServerNotification = readonly params: ServerNotification__ThreadRealtimeItemAddedNotification; } | { - readonly method: "thread/realtime/transcriptUpdated"; - readonly params: ServerNotification__ThreadRealtimeTranscriptUpdatedNotification; + readonly method: "thread/realtime/transcript/delta"; + readonly params: ServerNotification__ThreadRealtimeTranscriptDeltaNotification; + } + | { + readonly method: "thread/realtime/transcript/done"; + readonly params: ServerNotification__ThreadRealtimeTranscriptDoneNotification; } | { readonly method: "thread/realtime/outputAudio/delta"; @@ -26665,6 +29615,12 @@ export const ServerNotification = Schema.Union( }), params: ServerNotification__FileChangeOutputDeltaNotification, }).annotate({ title: "Item/fileChange/outputDeltaNotification" }), + Schema.Struct({ + method: Schema.Literal("item/fileChange/patchUpdated").annotate({ + title: "Item/fileChange/patchUpdatedNotificationMethod", + }), + params: ServerNotification__FileChangePatchUpdatedNotification, + }).annotate({ title: "Item/fileChange/patchUpdatedNotification" }), Schema.Struct({ method: Schema.Literal("serverRequest/resolved").annotate({ title: "ServerRequest/resolvedNotificationMethod", @@ -26707,6 +29663,12 @@ export const ServerNotification = Schema.Union( }), params: ServerNotification__AppListUpdatedNotification, }).annotate({ title: "App/list/updatedNotification" }), + Schema.Struct({ + method: Schema.Literal("externalAgentConfig/import/completed").annotate({ + title: "ExternalAgentConfig/import/completedNotificationMethod", + }), + params: ServerNotification__ExternalAgentConfigImportCompletedNotification, + }).annotate({ title: "ExternalAgentConfig/import/completedNotification" }), Schema.Struct({ method: Schema.Literal("fs/changed").annotate({ title: "Fs/changedNotificationMethod" }), params: ServerNotification__FsChangedNotification, @@ -26744,6 +29706,10 @@ export const ServerNotification = Schema.Union( }), params: ServerNotification__ModelReroutedNotification, }).annotate({ title: "Model/reroutedNotification" }), + Schema.Struct({ + method: Schema.Literal("warning").annotate({ title: "WarningNotificationMethod" }), + params: ServerNotification__WarningNotification, + }).annotate({ title: "WarningNotification" }), Schema.Struct({ method: Schema.Literal("deprecationNotice").annotate({ title: "DeprecationNoticeNotificationMethod", @@ -26781,11 +29747,17 @@ export const ServerNotification = Schema.Union( params: ServerNotification__ThreadRealtimeItemAddedNotification, }).annotate({ title: "Thread/realtime/itemAddedNotification" }), Schema.Struct({ - method: Schema.Literal("thread/realtime/transcriptUpdated").annotate({ - title: "Thread/realtime/transcriptUpdatedNotificationMethod", + method: Schema.Literal("thread/realtime/transcript/delta").annotate({ + title: "Thread/realtime/transcript/deltaNotificationMethod", }), - params: ServerNotification__ThreadRealtimeTranscriptUpdatedNotification, - }).annotate({ title: "Thread/realtime/transcriptUpdatedNotification" }), + params: ServerNotification__ThreadRealtimeTranscriptDeltaNotification, + }).annotate({ title: "Thread/realtime/transcript/deltaNotification" }), + Schema.Struct({ + method: Schema.Literal("thread/realtime/transcript/done").annotate({ + title: "Thread/realtime/transcript/doneNotificationMethod", + }), + params: ServerNotification__ThreadRealtimeTranscriptDoneNotification, + }).annotate({ title: "Thread/realtime/transcript/doneNotification" }), Schema.Struct({ method: Schema.Literal("thread/realtime/outputAudio/delta").annotate({ title: "Thread/realtime/outputAudio/deltaNotificationMethod", @@ -26888,6 +29860,26 @@ export const ServerNotification__CommandExecutionSource = Schema.Literals([ "unifiedExecInteraction", ]); +export type ServerNotification__HookSource = + | "system" + | "user" + | "project" + | "mdm" + | "sessionFlags" + | "legacyManagedConfigFile" + | "legacyManagedConfigMdm" + | "unknown"; +export const ServerNotification__HookSource = Schema.Literals([ + "system", + "user", + "project", + "mdm", + "sessionFlags", + "legacyManagedConfigFile", + "legacyManagedConfigMdm", + "unknown", +]); + export type ServerNotification__SessionSource = | "cli" | "vscode" @@ -27729,7 +30721,6 @@ export type V2ConfigRequirementsReadResponse__NetworkRequirements = { readonly allowUnixSockets?: ReadonlyArray | null; readonly allowUpstreamProxy?: boolean | null; readonly allowedDomains?: ReadonlyArray | null; - readonly dangerFullAccessDenylistOnly?: boolean | null; readonly dangerouslyAllowAllUnixSockets?: boolean | null; readonly dangerouslyAllowNonLoopbackProxy?: boolean | null; readonly deniedDomains?: ReadonlyArray | null; @@ -27763,7 +30754,6 @@ export const V2ConfigRequirementsReadResponse__NetworkRequirements = Schema.Stru Schema.Null, ]), ), - dangerFullAccessDenylistOnly: Schema.optionalKey(Schema.Union([Schema.Boolean, Schema.Null])), dangerouslyAllowAllUnixSockets: Schema.optionalKey(Schema.Union([Schema.Boolean, Schema.Null])), dangerouslyAllowNonLoopbackProxy: Schema.optionalKey(Schema.Union([Schema.Boolean, Schema.Null])), deniedDomains: Schema.optionalKey( @@ -27917,6 +30907,97 @@ export const V2DeprecationNoticeNotification = Schema.Struct({ summary: Schema.String.annotate({ description: "Concise summary of what is deprecated." }), }).annotate({ title: "DeprecationNoticeNotification" }); +export type V2DeviceKeyCreateParams = { + readonly accountUserId: string; + readonly clientId: string; + readonly protectionPolicy?: V2DeviceKeyCreateParams__DeviceKeyProtectionPolicy | null; +}; +export const V2DeviceKeyCreateParams = Schema.Struct({ + accountUserId: Schema.String, + clientId: Schema.String, + protectionPolicy: Schema.optionalKey( + Schema.Union([V2DeviceKeyCreateParams__DeviceKeyProtectionPolicy, Schema.Null]).annotate({ + description: "Defaults to `hardware_only` when omitted.", + }), + ), +}).annotate({ + title: "DeviceKeyCreateParams", + description: "Create a controller-local device key with a random key id.", +}); + +export type V2DeviceKeyCreateResponse = { + readonly algorithm: V2DeviceKeyCreateResponse__DeviceKeyAlgorithm; + readonly keyId: string; + readonly protectionClass: V2DeviceKeyCreateResponse__DeviceKeyProtectionClass; + readonly publicKeySpkiDerBase64: string; +}; +export const V2DeviceKeyCreateResponse = Schema.Struct({ + algorithm: V2DeviceKeyCreateResponse__DeviceKeyAlgorithm, + keyId: Schema.String, + protectionClass: V2DeviceKeyCreateResponse__DeviceKeyProtectionClass, + publicKeySpkiDerBase64: Schema.String.annotate({ + description: "SubjectPublicKeyInfo DER encoded as base64.", + }), +}).annotate({ + title: "DeviceKeyCreateResponse", + description: "Device-key metadata and public key returned by create/public APIs.", +}); + +export type V2DeviceKeyPublicParams = { readonly keyId: string }; +export const V2DeviceKeyPublicParams = Schema.Struct({ keyId: Schema.String }).annotate({ + title: "DeviceKeyPublicParams", + description: "Fetch a controller-local device key public key by id.", +}); + +export type V2DeviceKeyPublicResponse = { + readonly algorithm: V2DeviceKeyPublicResponse__DeviceKeyAlgorithm; + readonly keyId: string; + readonly protectionClass: V2DeviceKeyPublicResponse__DeviceKeyProtectionClass; + readonly publicKeySpkiDerBase64: string; +}; +export const V2DeviceKeyPublicResponse = Schema.Struct({ + algorithm: V2DeviceKeyPublicResponse__DeviceKeyAlgorithm, + keyId: Schema.String, + protectionClass: V2DeviceKeyPublicResponse__DeviceKeyProtectionClass, + publicKeySpkiDerBase64: Schema.String.annotate({ + description: "SubjectPublicKeyInfo DER encoded as base64.", + }), +}).annotate({ + title: "DeviceKeyPublicResponse", + description: "Device-key public metadata returned by `device/key/public`.", +}); + +export type V2DeviceKeySignParams = { + readonly keyId: string; + readonly payload: V2DeviceKeySignParams__DeviceKeySignPayload; +}; +export const V2DeviceKeySignParams = Schema.Struct({ + keyId: Schema.String, + payload: V2DeviceKeySignParams__DeviceKeySignPayload, +}).annotate({ + title: "DeviceKeySignParams", + description: "Sign an accepted structured payload with a controller-local device key.", +}); + +export type V2DeviceKeySignResponse = { + readonly algorithm: V2DeviceKeySignResponse__DeviceKeyAlgorithm; + readonly signatureDerBase64: string; + readonly signedPayloadBase64: string; +}; +export const V2DeviceKeySignResponse = Schema.Struct({ + algorithm: V2DeviceKeySignResponse__DeviceKeyAlgorithm, + signatureDerBase64: Schema.String.annotate({ + description: "ECDSA signature DER encoded as base64.", + }), + signedPayloadBase64: Schema.String.annotate({ + description: + "Exact bytes signed by the device key, encoded as base64. Verifiers must verify this byte string directly and must not reserialize `payload`.", + }), +}).annotate({ + title: "DeviceKeySignResponse", + description: "ASN.1 DER signature returned by `device/key/sign`.", +}); + export type V2ErrorNotification = { readonly error: V2ErrorNotification__TurnError; readonly threadId: string; @@ -28033,6 +31114,11 @@ export const V2ExternalAgentConfigDetectResponse = Schema.Struct({ items: Schema.Array(V2ExternalAgentConfigDetectResponse__ExternalAgentConfigMigrationItem), }).annotate({ title: "ExternalAgentConfigDetectResponse" }); +export type V2ExternalAgentConfigImportCompletedNotification = {}; +export const V2ExternalAgentConfigImportCompletedNotification = Schema.Struct({}).annotate({ + title: "ExternalAgentConfigImportCompletedNotification", +}); + export type V2ExternalAgentConfigImportParams = { readonly migrationItems: ReadonlyArray; }; @@ -28050,6 +31136,7 @@ export type V2FeedbackUploadParams = { readonly extraLogFiles?: ReadonlyArray | null; readonly includeLogs: boolean; readonly reason?: string | null; + readonly tags?: { readonly [x: string]: string } | null; readonly threadId?: string | null; }; export const V2FeedbackUploadParams = Schema.Struct({ @@ -28057,6 +31144,9 @@ export const V2FeedbackUploadParams = Schema.Struct({ extraLogFiles: Schema.optionalKey(Schema.Union([Schema.Array(Schema.String), Schema.Null])), includeLogs: Schema.Boolean, reason: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + tags: Schema.optionalKey( + Schema.Union([Schema.Record(Schema.String, Schema.String), Schema.Null]), + ), threadId: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), }).annotate({ title: "FeedbackUploadParams" }); @@ -28078,6 +31168,19 @@ export const V2FileChangeOutputDeltaNotification = Schema.Struct({ turnId: Schema.String, }).annotate({ title: "FileChangeOutputDeltaNotification" }); +export type V2FileChangePatchUpdatedNotification = { + readonly changes: ReadonlyArray; + readonly itemId: string; + readonly threadId: string; + readonly turnId: string; +}; +export const V2FileChangePatchUpdatedNotification = Schema.Struct({ + changes: Schema.Array(V2FileChangePatchUpdatedNotification__FileUpdateChange), + itemId: Schema.String, + threadId: Schema.String, + turnId: Schema.String, +}).annotate({ title: "FileChangePatchUpdatedNotification" }); + export type V2FsChangedNotification = { readonly changedPaths: ReadonlyArray; readonly watchId: string; @@ -28185,6 +31288,7 @@ export type V2FsGetMetadataResponse = { readonly createdAtMs: number; readonly isDirectory: boolean; readonly isFile: boolean; + readonly isSymlink: boolean; readonly modifiedAtMs: number; }; export const V2FsGetMetadataResponse = Schema.Struct({ @@ -28193,10 +31297,11 @@ export const V2FsGetMetadataResponse = Schema.Struct({ format: "int64", }).check(Schema.isInt()), isDirectory: Schema.Boolean.annotate({ - description: "Whether the path currently resolves to a directory.", + description: "Whether the path resolves to a directory.", }), - isFile: Schema.Boolean.annotate({ - description: "Whether the path currently resolves to a regular file.", + isFile: Schema.Boolean.annotate({ description: "Whether the path resolves to a regular file." }), + isSymlink: Schema.Boolean.annotate({ + description: "Whether the path itself is a symbolic link.", }), modifiedAtMs: Schema.Number.annotate({ description: "File modification time in Unix milliseconds when available, otherwise `0`.", @@ -28390,6 +31495,7 @@ export type V2GetAccountRateLimitsResponse = { readonly limitName?: string | null; readonly planType?: V2GetAccountRateLimitsResponse__PlanType | null; readonly primary?: V2GetAccountRateLimitsResponse__RateLimitWindow | null; + readonly rateLimitReachedType?: V2GetAccountRateLimitsResponse__RateLimitReachedType | null; readonly secondary?: V2GetAccountRateLimitsResponse__RateLimitWindow | null; }; readonly rateLimitsByLimitId?: { @@ -28409,6 +31515,9 @@ export const V2GetAccountRateLimitsResponse = Schema.Struct({ primary: Schema.optionalKey( Schema.Union([V2GetAccountRateLimitsResponse__RateLimitWindow, Schema.Null]), ), + rateLimitReachedType: Schema.optionalKey( + Schema.Union([V2GetAccountRateLimitsResponse__RateLimitReachedType, Schema.Null]), + ), secondary: Schema.optionalKey( Schema.Union([V2GetAccountRateLimitsResponse__RateLimitWindow, Schema.Null]), ), @@ -28445,6 +31554,26 @@ export const V2HookCompletedNotification = Schema.Struct({ turnId: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), }).annotate({ title: "HookCompletedNotification" }); +export type V2HookCompletedNotification__HookSource = + | "system" + | "user" + | "project" + | "mdm" + | "sessionFlags" + | "legacyManagedConfigFile" + | "legacyManagedConfigMdm" + | "unknown"; +export const V2HookCompletedNotification__HookSource = Schema.Literals([ + "system", + "user", + "project", + "mdm", + "sessionFlags", + "legacyManagedConfigFile", + "legacyManagedConfigMdm", + "unknown", +]); + export type V2HookStartedNotification = { readonly run: V2HookStartedNotification__HookRunSummary; readonly threadId: string; @@ -28456,6 +31585,26 @@ export const V2HookStartedNotification = Schema.Struct({ turnId: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), }).annotate({ title: "HookStartedNotification" }); +export type V2HookStartedNotification__HookSource = + | "system" + | "user" + | "project" + | "mdm" + | "sessionFlags" + | "legacyManagedConfigFile" + | "legacyManagedConfigMdm" + | "unknown"; +export const V2HookStartedNotification__HookSource = Schema.Literals([ + "system", + "user", + "project", + "mdm", + "sessionFlags", + "legacyManagedConfigFile", + "legacyManagedConfigMdm", + "unknown", +]); + export type V2ItemCompletedNotification = { readonly item: V2ItemCompletedNotification__ThreadItem; readonly threadId: string; @@ -28544,7 +31693,7 @@ export const V2ItemGuardianApprovalReviewCompletedNotification = Schema.Struct({ }).annotate({ title: "ItemGuardianApprovalReviewCompletedNotification", description: - "[UNSTABLE] Temporary notification payload for guardian automatic approval review. This shape is expected to change soon.", + "[UNSTABLE] Temporary notification payload for approval auto-review. This shape is expected to change soon.", }); export type V2ItemGuardianApprovalReviewStartedNotification = { @@ -28573,7 +31722,7 @@ export const V2ItemGuardianApprovalReviewStartedNotification = Schema.Struct({ }).annotate({ title: "ItemGuardianApprovalReviewStartedNotification", description: - "[UNSTABLE] Temporary notification payload for guardian automatic approval review. This shape is expected to change soon.", + "[UNSTABLE] Temporary notification payload for approval auto-review. This shape is expected to change soon.", }); export type V2ItemStartedNotification = { @@ -28785,14 +31934,52 @@ export const V2LogoutAccountResponse = Schema.Struct({}).annotate({ title: "LogoutAccountResponse", }); +export type V2MarketplaceAddParams = { + readonly refName?: string | null; + readonly source: string; + readonly sparsePaths?: ReadonlyArray | null; +}; +export const V2MarketplaceAddParams = Schema.Struct({ + refName: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + source: Schema.String, + sparsePaths: Schema.optionalKey(Schema.Union([Schema.Array(Schema.String), Schema.Null])), +}).annotate({ title: "MarketplaceAddParams" }); + +export type V2MarketplaceAddResponse = { + readonly alreadyAdded: boolean; + readonly installedRoot: V2MarketplaceAddResponse__AbsolutePathBuf; + readonly marketplaceName: string; +}; +export const V2MarketplaceAddResponse = Schema.Struct({ + alreadyAdded: Schema.Boolean, + installedRoot: V2MarketplaceAddResponse__AbsolutePathBuf, + marketplaceName: Schema.String, +}).annotate({ title: "MarketplaceAddResponse" }); + +export type V2MarketplaceRemoveParams = { readonly marketplaceName: string }; +export const V2MarketplaceRemoveParams = Schema.Struct({ marketplaceName: Schema.String }).annotate( + { title: "MarketplaceRemoveParams" }, +); + +export type V2MarketplaceRemoveResponse = { + readonly installedRoot?: V2MarketplaceRemoveResponse__AbsolutePathBuf | null; + readonly marketplaceName: string; +}; +export const V2MarketplaceRemoveResponse = Schema.Struct({ + installedRoot: Schema.optionalKey( + Schema.Union([V2MarketplaceRemoveResponse__AbsolutePathBuf, Schema.Null]), + ), + marketplaceName: Schema.String, +}).annotate({ title: "MarketplaceRemoveResponse" }); + export type V2McpResourceReadParams = { readonly server: string; - readonly threadId: string; + readonly threadId?: string | null; readonly uri: string; }; export const V2McpResourceReadParams = Schema.Struct({ server: Schema.String, - threadId: Schema.String, + threadId: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), uri: Schema.String, }).annotate({ title: "McpResourceReadParams" }); @@ -28974,18 +32161,16 @@ export const V2PlanDeltaNotification = Schema.Struct({ }); export type V2PluginInstallParams = { - readonly forceRemoteSync?: boolean; - readonly marketplacePath: V2PluginInstallParams__AbsolutePathBuf; + readonly marketplacePath?: V2PluginInstallParams__AbsolutePathBuf | null; readonly pluginName: string; + readonly remoteMarketplaceName?: string | null; }; export const V2PluginInstallParams = Schema.Struct({ - forceRemoteSync: Schema.optionalKey( - Schema.Boolean.annotate({ - description: "When true, apply the remote plugin change before the local install flow.", - }), + marketplacePath: Schema.optionalKey( + Schema.Union([V2PluginInstallParams__AbsolutePathBuf, Schema.Null]), ), - marketplacePath: V2PluginInstallParams__AbsolutePathBuf, pluginName: Schema.String, + remoteMarketplaceName: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), }).annotate({ title: "PluginInstallParams" }); export type V2PluginInstallResponse = { @@ -28999,7 +32184,6 @@ export const V2PluginInstallResponse = Schema.Struct({ export type V2PluginListParams = { readonly cwds?: ReadonlyArray | null; - readonly forceRemoteSync?: boolean; }; export const V2PluginListParams = Schema.Struct({ cwds: Schema.optionalKey( @@ -29011,19 +32195,12 @@ export const V2PluginListParams = Schema.Struct({ Schema.Null, ]), ), - forceRemoteSync: Schema.optionalKey( - Schema.Boolean.annotate({ - description: - "When true, reconcile the official curated marketplace against the remote plugin state before listing marketplaces.", - }), - ), }).annotate({ title: "PluginListParams" }); export type V2PluginListResponse = { readonly featuredPluginIds?: ReadonlyArray; readonly marketplaceLoadErrors?: ReadonlyArray; readonly marketplaces: ReadonlyArray; - readonly remoteSyncError?: string | null; }; export const V2PluginListResponse = Schema.Struct({ featuredPluginIds: Schema.optionalKey(Schema.Array(Schema.String).annotate({ default: [] })), @@ -29031,16 +32208,19 @@ export const V2PluginListResponse = Schema.Struct({ Schema.Array(V2PluginListResponse__MarketplaceLoadErrorInfo).annotate({ default: [] }), ), marketplaces: Schema.Array(V2PluginListResponse__PluginMarketplaceEntry), - remoteSyncError: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), }).annotate({ title: "PluginListResponse" }); export type V2PluginReadParams = { - readonly marketplacePath: V2PluginReadParams__AbsolutePathBuf; + readonly marketplacePath?: V2PluginReadParams__AbsolutePathBuf | null; readonly pluginName: string; + readonly remoteMarketplaceName?: string | null; }; export const V2PluginReadParams = Schema.Struct({ - marketplacePath: V2PluginReadParams__AbsolutePathBuf, + marketplacePath: Schema.optionalKey( + Schema.Union([V2PluginReadParams__AbsolutePathBuf, Schema.Null]), + ), pluginName: Schema.String, + remoteMarketplaceName: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), }).annotate({ title: "PluginReadParams" }); export type V2PluginReadResponse = { readonly plugin: V2PluginReadResponse__PluginDetail }; @@ -29048,18 +32228,10 @@ export const V2PluginReadResponse = Schema.Struct({ plugin: V2PluginReadResponse__PluginDetail, }).annotate({ title: "PluginReadResponse" }); -export type V2PluginUninstallParams = { - readonly forceRemoteSync?: boolean; - readonly pluginId: string; -}; -export const V2PluginUninstallParams = Schema.Struct({ - forceRemoteSync: Schema.optionalKey( - Schema.Boolean.annotate({ - description: "When true, apply the remote plugin change before the local uninstall flow.", - }), - ), - pluginId: Schema.String, -}).annotate({ title: "PluginUninstallParams" }); +export type V2PluginUninstallParams = { readonly pluginId: string }; +export const V2PluginUninstallParams = Schema.Struct({ pluginId: Schema.String }).annotate({ + title: "PluginUninstallParams", +}); export type V2PluginUninstallResponse = {}; export const V2PluginUninstallResponse = Schema.Struct({}).annotate({ @@ -29194,6 +32366,20 @@ export const V2ReviewStartResponse__CommandExecutionSource = Schema.Literals([ "unifiedExecInteraction", ]); +export type V2SendAddCreditsNudgeEmailParams = { + readonly creditType: V2SendAddCreditsNudgeEmailParams__AddCreditsNudgeCreditType; +}; +export const V2SendAddCreditsNudgeEmailParams = Schema.Struct({ + creditType: V2SendAddCreditsNudgeEmailParams__AddCreditsNudgeCreditType, +}).annotate({ title: "SendAddCreditsNudgeEmailParams" }); + +export type V2SendAddCreditsNudgeEmailResponse = { + readonly status: V2SendAddCreditsNudgeEmailResponse__AddCreditsNudgeEmailStatus; +}; +export const V2SendAddCreditsNudgeEmailResponse = Schema.Struct({ + status: V2SendAddCreditsNudgeEmailResponse__AddCreditsNudgeEmailStatus, +}).annotate({ title: "SendAddCreditsNudgeEmailResponse" }); + export type V2ServerRequestResolvedNotification = { readonly requestId: V2ServerRequestResolvedNotification__RequestId; readonly threadId: string; @@ -29364,7 +32550,8 @@ export const V2ThreadForkParams = Schema.Struct({ export type V2ThreadForkResponse = { readonly approvalPolicy: V2ThreadForkResponse__AskForApproval; readonly approvalsReviewer: "user" | "guardian_subagent"; - readonly cwd: string; + readonly cwd: V2ThreadForkResponse__AbsolutePathBuf; + readonly instructionSources?: ReadonlyArray; readonly model: string; readonly modelProvider: string; readonly reasoningEffort?: V2ThreadForkResponse__ReasoningEffort | null; @@ -29378,7 +32565,13 @@ export const V2ThreadForkResponse = Schema.Struct({ description: "Configures who approval requests are routed to for review. Examples include sandbox escapes, blocked network access, MCP approval prompts, and ARC escalations. Defaults to `user`. `guardian_subagent` uses a carefully prompted subagent to gather relevant context and apply a risk-based decision framework before approving or denying the request.", }), - cwd: Schema.String, + cwd: V2ThreadForkResponse__AbsolutePathBuf, + instructionSources: Schema.optionalKey( + Schema.Array(V2ThreadForkResponse__AbsolutePathBuf).annotate({ + description: "Instruction source files currently loaded for this thread.", + default: [], + }), + ), model: Schema.String, modelProvider: Schema.String, reasoningEffort: Schema.optionalKey( @@ -29513,6 +32706,22 @@ export const V2ThreadForkResponse__ThreadStatus = Schema.Union( { mode: "oneOf" }, ); +export type V2ThreadInjectItemsParams = { + readonly items: ReadonlyArray; + readonly threadId: string; +}; +export const V2ThreadInjectItemsParams = Schema.Struct({ + items: Schema.Array(Schema.Unknown).annotate({ + description: "Raw Responses API items to append to the thread's model-visible history.", + }), + threadId: Schema.String, +}).annotate({ title: "ThreadInjectItemsParams" }); + +export type V2ThreadInjectItemsResponse = {}; +export const V2ThreadInjectItemsResponse = Schema.Struct({}).annotate({ + title: "ThreadInjectItemsResponse", +}); + export type V2ThreadListParams = { readonly archived?: boolean | null; readonly cursor?: string | null; @@ -29520,6 +32729,7 @@ export type V2ThreadListParams = { readonly limit?: number | null; readonly modelProviders?: ReadonlyArray | null; readonly searchTerm?: string | null; + readonly sortDirection?: V2ThreadListParams__SortDirection | null; readonly sortKey?: V2ThreadListParams__ThreadSortKey | null; readonly sourceKinds?: ReadonlyArray | null; }; @@ -29578,6 +32788,11 @@ export const V2ThreadListParams = Schema.Struct({ Schema.Null, ]), ), + sortDirection: Schema.optionalKey( + Schema.Union([V2ThreadListParams__SortDirection, Schema.Null]).annotate({ + description: "Optional sort direction; defaults to descending (newest first).", + }), + ), sortKey: Schema.optionalKey( Schema.Union([V2ThreadListParams__ThreadSortKey, Schema.Null]).annotate({ description: "Optional sort key; defaults to created_at.", @@ -29595,10 +32810,20 @@ export const V2ThreadListParams = Schema.Struct({ }).annotate({ title: "ThreadListParams" }); export type V2ThreadListResponse = { + readonly backwardsCursor?: string | null; readonly data: ReadonlyArray; readonly nextCursor?: string | null; }; export const V2ThreadListResponse = Schema.Struct({ + backwardsCursor: Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + description: + "Opaque cursor to pass as `cursor` when reversing `sortDirection`. This is only populated when the page contains at least one thread. Use it with the opposite `sortDirection`; for timestamp sorts it anchors at the start of the page timestamp so same-second updates are not skipped.", + }), + Schema.Null, + ]), + ), data: Schema.Array(V2ThreadListResponse__Thread), nextCursor: Schema.optionalKey( Schema.Union([ @@ -30049,19 +33274,34 @@ export const V2ThreadRealtimeStartedNotification = Schema.Struct({ description: "EXPERIMENTAL - emitted when thread realtime startup is accepted.", }); -export type V2ThreadRealtimeTranscriptUpdatedNotification = { +export type V2ThreadRealtimeTranscriptDeltaNotification = { + readonly delta: string; + readonly role: string; + readonly threadId: string; +}; +export const V2ThreadRealtimeTranscriptDeltaNotification = Schema.Struct({ + delta: Schema.String.annotate({ description: "Live transcript delta from the realtime event." }), + role: Schema.String, + threadId: Schema.String, +}).annotate({ + title: "ThreadRealtimeTranscriptDeltaNotification", + description: + "EXPERIMENTAL - flat transcript delta emitted whenever realtime transcript text changes.", +}); + +export type V2ThreadRealtimeTranscriptDoneNotification = { readonly role: string; readonly text: string; readonly threadId: string; }; -export const V2ThreadRealtimeTranscriptUpdatedNotification = Schema.Struct({ +export const V2ThreadRealtimeTranscriptDoneNotification = Schema.Struct({ role: Schema.String, - text: Schema.String, + text: Schema.String.annotate({ description: "Final complete text for the transcript part." }), threadId: Schema.String, }).annotate({ - title: "ThreadRealtimeTranscriptUpdatedNotification", + title: "ThreadRealtimeTranscriptDoneNotification", description: - "EXPERIMENTAL - flat transcript delta emitted whenever realtime transcript text changes.", + "EXPERIMENTAL - final transcript text emitted when realtime completes a transcript part.", }); export type V2ThreadResumeParams = { @@ -30332,7 +33572,8 @@ export const V2ThreadResumeParams__ResponseItem = Schema.Union( export type V2ThreadResumeResponse = { readonly approvalPolicy: V2ThreadResumeResponse__AskForApproval; readonly approvalsReviewer: "user" | "guardian_subagent"; - readonly cwd: string; + readonly cwd: V2ThreadResumeResponse__AbsolutePathBuf; + readonly instructionSources?: ReadonlyArray; readonly model: string; readonly modelProvider: string; readonly reasoningEffort?: V2ThreadResumeResponse__ReasoningEffort | null; @@ -30346,7 +33587,13 @@ export const V2ThreadResumeResponse = Schema.Struct({ description: "Configures who approval requests are routed to for review. Examples include sandbox escapes, blocked network access, MCP approval prompts, and ARC escalations. Defaults to `user`. `guardian_subagent` uses a carefully prompted subagent to gather relevant context and apply a risk-based decision framework before approving or denying the request.", }), - cwd: Schema.String, + cwd: V2ThreadResumeResponse__AbsolutePathBuf, + instructionSources: Schema.optionalKey( + Schema.Array(V2ThreadResumeResponse__AbsolutePathBuf).annotate({ + description: "Instruction source files currently loaded for this thread.", + default: [], + }), + ), model: Schema.String, modelProvider: Schema.String, reasoningEffort: Schema.optionalKey( @@ -30557,7 +33804,10 @@ export const V2ThreadRollbackResponse = Schema.Struct({ description: "Unix timestamp (in seconds) when the thread was created.", format: "int64", }).check(Schema.isInt()), - cwd: Schema.String.annotate({ description: "Working directory captured for the thread." }), + cwd: Schema.String.annotate({ + description: + "A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\n\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.", + }), ephemeral: Schema.Boolean.annotate({ description: "Whether the thread is ephemeral and should not be materialized on disk.", }), @@ -30760,7 +34010,10 @@ export const V2ThreadRollbackResponse__Thread = Schema.Struct({ description: "Unix timestamp (in seconds) when the thread was created.", format: "int64", }).check(Schema.isInt()), - cwd: Schema.String.annotate({ description: "Working directory captured for the thread." }), + cwd: Schema.String.annotate({ + description: + "A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\n\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.", + }), ephemeral: Schema.Boolean.annotate({ description: "Whether the thread is ephemeral and should not be materialized on disk.", }), @@ -31039,18 +34292,21 @@ export type V2ThreadStartParams__DynamicToolSpec = { readonly description: string; readonly inputSchema: unknown; readonly name: string; + readonly namespace?: string | null; }; export const V2ThreadStartParams__DynamicToolSpec = Schema.Struct({ deferLoading: Schema.optionalKey(Schema.Boolean), description: Schema.String, inputSchema: Schema.Unknown, name: Schema.String, + namespace: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), }); export type V2ThreadStartResponse = { readonly approvalPolicy: V2ThreadStartResponse__AskForApproval; readonly approvalsReviewer: "user" | "guardian_subagent"; - readonly cwd: string; + readonly cwd: V2ThreadStartResponse__AbsolutePathBuf; + readonly instructionSources?: ReadonlyArray; readonly model: string; readonly modelProvider: string; readonly reasoningEffort?: V2ThreadStartResponse__ReasoningEffort | null; @@ -31064,7 +34320,13 @@ export const V2ThreadStartResponse = Schema.Struct({ description: "Configures who approval requests are routed to for review. Examples include sandbox escapes, blocked network access, MCP approval prompts, and ARC escalations. Defaults to `user`. `guardian_subagent` uses a carefully prompted subagent to gather relevant context and apply a risk-based decision framework before approving or denying the request.", }), - cwd: Schema.String, + cwd: V2ThreadStartResponse__AbsolutePathBuf, + instructionSources: Schema.optionalKey( + Schema.Array(V2ThreadStartResponse__AbsolutePathBuf).annotate({ + description: "Instruction source files currently loaded for this thread.", + default: [], + }), + ), model: Schema.String, modelProvider: Schema.String, reasoningEffort: Schema.optionalKey( @@ -31222,6 +34484,110 @@ export const V2ThreadTokenUsageUpdatedNotification = Schema.Struct({ turnId: Schema.String, }).annotate({ title: "ThreadTokenUsageUpdatedNotification" }); +export type V2ThreadTurnsListParams = { + readonly cursor?: string | null; + readonly limit?: number | null; + readonly sortDirection?: V2ThreadTurnsListParams__SortDirection | null; + readonly threadId: string; +}; +export const V2ThreadTurnsListParams = Schema.Struct({ + cursor: Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + description: "Opaque cursor to pass to the next call to continue after the last turn.", + }), + Schema.Null, + ]), + ), + limit: Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ description: "Optional turn page size.", format: "uint32" }) + .check(Schema.isInt()) + .check(Schema.isGreaterThanOrEqualTo(0)), + Schema.Null, + ]), + ), + sortDirection: Schema.optionalKey( + Schema.Union([V2ThreadTurnsListParams__SortDirection, Schema.Null]).annotate({ + description: "Optional turn pagination direction; defaults to descending.", + }), + ), + threadId: Schema.String, +}).annotate({ title: "ThreadTurnsListParams" }); + +export type V2ThreadTurnsListResponse = { + readonly backwardsCursor?: string | null; + readonly data: ReadonlyArray; + readonly nextCursor?: string | null; +}; +export const V2ThreadTurnsListResponse = Schema.Struct({ + backwardsCursor: Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + description: + "Opaque cursor to pass as `cursor` when reversing `sortDirection`. This is only populated when the page contains at least one turn. Use it with the opposite `sortDirection` to include the anchor turn again and catch updates to that turn.", + }), + Schema.Null, + ]), + ), + data: Schema.Array(V2ThreadTurnsListResponse__Turn), + nextCursor: Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + description: + "Opaque cursor to pass to the next call to continue after the last turn. if None, there are no more turns to return.", + }), + Schema.Null, + ]), + ), +}).annotate({ title: "ThreadTurnsListResponse" }); + +export type V2ThreadTurnsListResponse__ByteRange = { readonly end: number; readonly start: number }; +export const V2ThreadTurnsListResponse__ByteRange = Schema.Struct({ + end: Schema.Number.annotate({ format: "uint" }) + .check(Schema.isInt()) + .check(Schema.isGreaterThanOrEqualTo(0)), + start: Schema.Number.annotate({ format: "uint" }) + .check(Schema.isInt()) + .check(Schema.isGreaterThanOrEqualTo(0)), +}); + +export type V2ThreadTurnsListResponse__CollabAgentTool = + | "spawnAgent" + | "sendInput" + | "resumeAgent" + | "wait" + | "closeAgent"; +export const V2ThreadTurnsListResponse__CollabAgentTool = Schema.Literals([ + "spawnAgent", + "sendInput", + "resumeAgent", + "wait", + "closeAgent", +]); + +export type V2ThreadTurnsListResponse__CollabAgentToolCallStatus = + | "inProgress" + | "completed" + | "failed"; +export const V2ThreadTurnsListResponse__CollabAgentToolCallStatus = Schema.Literals([ + "inProgress", + "completed", + "failed", +]); + +export type V2ThreadTurnsListResponse__CommandExecutionSource = + | "agent" + | "userShell" + | "unifiedExecStartup" + | "unifiedExecInteraction"; +export const V2ThreadTurnsListResponse__CommandExecutionSource = Schema.Literals([ + "agent", + "userShell", + "unifiedExecStartup", + "unifiedExecInteraction", +]); + export type V2ThreadUnarchivedNotification = { readonly threadId: string }; export const V2ThreadUnarchivedNotification = Schema.Struct({ threadId: Schema.String }).annotate({ title: "ThreadUnarchivedNotification", @@ -31693,6 +35059,19 @@ export const V2TurnSteerResponse = Schema.Struct({ turnId: Schema.String }).anno title: "TurnSteerResponse", }); +export type V2WarningNotification = { readonly message: string; readonly threadId?: string | null }; +export const V2WarningNotification = Schema.Struct({ + message: Schema.String.annotate({ description: "Concise warning message for the user." }), + threadId: Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + description: "Optional thread target when the warning applies to a specific thread.", + }), + Schema.Null, + ]), + ), +}).annotate({ title: "WarningNotification" }); + export type V2WindowsSandboxSetupCompletedNotification = { readonly error?: string | null; readonly mode: V2WindowsSandboxSetupCompletedNotification__WindowsSandboxSetupMode; From b8305afa29309e52045987caab91db9b7e481ac0 Mon Sep 17 00:00:00 2001 From: Heinz-G Date: Wed, 22 Apr 2026 03:04:50 +0200 Subject: [PATCH 16/82] fix: increase Claude auth probe timeout to 10s (#2272) Co-authored-by: Heinz Gericke <115458264+heinzgericke@users.noreply.github.com> --- apps/server/src/provider/Layers/ClaudeProvider.ts | 3 ++- apps/server/src/provider/providerSnapshot.ts | 2 ++ 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/apps/server/src/provider/Layers/ClaudeProvider.ts b/apps/server/src/provider/Layers/ClaudeProvider.ts index 7c8a4c27a6..60836210b5 100644 --- a/apps/server/src/provider/Layers/ClaudeProvider.ts +++ b/apps/server/src/provider/Layers/ClaudeProvider.ts @@ -19,6 +19,7 @@ import { import { buildServerProvider, + AUTH_PROBE_TIMEOUT_MS, DEFAULT_TIMEOUT_MS, detailFromResult, extractAuthBoolean, @@ -674,7 +675,7 @@ export const checkClaudeProviderStatus = Effect.fn("checkClaudeProviderStatus")( // ── Auth check + subscription detection ──────────────────────────── const authProbe = yield* runClaudeCommand(["auth", "status"]).pipe( - Effect.timeoutOption(DEFAULT_TIMEOUT_MS), + Effect.timeoutOption(AUTH_PROBE_TIMEOUT_MS), Effect.result, ); diff --git a/apps/server/src/provider/providerSnapshot.ts b/apps/server/src/provider/providerSnapshot.ts index 068b7c1157..fcea249e6e 100644 --- a/apps/server/src/provider/providerSnapshot.ts +++ b/apps/server/src/provider/providerSnapshot.ts @@ -13,6 +13,8 @@ import { normalizeModelSlug } from "@t3tools/shared/model"; import { isWindowsCommandNotFound } from "../processRunner.ts"; export const DEFAULT_TIMEOUT_MS = 4_000; +// Auth status checks involve disk/network lookups and can be slow on first run (especially Windows) +export const AUTH_PROBE_TIMEOUT_MS = 10_000; export interface CommandResult { readonly stdout: string; From e25db3a572a6718a1f3c5a64529395cc88cd5249 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Wed, 22 Apr 2026 21:33:16 -0700 Subject: [PATCH 17/82] Fix provider cache atomic write temp path collisions (#2291) Co-authored-by: Cursor Agent Co-authored-by: Julius Marminge --- apps/server/src/atomicWrite.ts | 25 +++++++++++++++++ apps/server/src/keybindings.ts | 16 +++++++---- .../src/provider/providerStatusCache.ts | 28 ++++++------------- apps/server/src/serverRuntimeState.ts | 15 ++++------ apps/server/src/serverSettings.ts | 13 +++++---- 5 files changed, 55 insertions(+), 42 deletions(-) create mode 100644 apps/server/src/atomicWrite.ts diff --git a/apps/server/src/atomicWrite.ts b/apps/server/src/atomicWrite.ts new file mode 100644 index 0000000000..431b2f4a01 --- /dev/null +++ b/apps/server/src/atomicWrite.ts @@ -0,0 +1,25 @@ +import { Effect, FileSystem, Path } from "effect"; +import * as Random from "effect/Random"; + +export const writeFileStringAtomically = (input: { + readonly filePath: string; + readonly contents: string; +}) => + Effect.scoped( + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const tempFileId = yield* Random.nextUUIDv4; + const targetDirectory = path.dirname(input.filePath); + + yield* fs.makeDirectory(targetDirectory, { recursive: true }); + const tempDirectory = yield* fs.makeTempDirectoryScoped({ + directory: targetDirectory, + prefix: `${path.basename(input.filePath)}.`, + }); + const tempPath = path.join(tempDirectory, `${tempFileId}.tmp`); + + yield* fs.writeFileString(tempPath, input.contents); + yield* fs.rename(tempPath, input.filePath); + }), + ); diff --git a/apps/server/src/keybindings.ts b/apps/server/src/keybindings.ts index 9689254c17..165b2edeb0 100644 --- a/apps/server/src/keybindings.ts +++ b/apps/server/src/keybindings.ts @@ -46,6 +46,7 @@ import { } from "effect"; import * as Semaphore from "effect/Semaphore"; import { ServerConfig } from "./config.ts"; +import { writeFileStringAtomically } from "./atomicWrite.ts"; import { fromLenientJson } from "@t3tools/shared/schemaJson"; type WhenToken = @@ -670,14 +671,17 @@ const makeKeybindings = Effect.gen(function* () { }); const writeConfigAtomically = (rules: readonly KeybindingRule[]) => { - const tempPath = `${keybindingsConfigPath}.${process.pid}.${Date.now()}.tmp`; - return Schema.encodeEffect(KeybindingsConfigPrettyJson)(rules).pipe( Effect.map((encoded) => `${encoded}\n`), - Effect.tap(() => fs.makeDirectory(path.dirname(keybindingsConfigPath), { recursive: true })), - Effect.tap((encoded) => fs.writeFileString(tempPath, encoded)), - Effect.flatMap(() => fs.rename(tempPath, keybindingsConfigPath)), - Effect.ensuring(fs.remove(tempPath, { force: true }).pipe(Effect.ignore({ log: true }))), + Effect.flatMap((encoded) => + writeFileStringAtomically({ + filePath: keybindingsConfigPath, + contents: encoded, + }).pipe( + Effect.provideService(FileSystem.FileSystem, fs), + Effect.provideService(Path.Path, path), + ), + ), Effect.mapError( (cause) => new KeybindingsConfigError({ diff --git a/apps/server/src/provider/providerStatusCache.ts b/apps/server/src/provider/providerStatusCache.ts index 369fca6218..fdb31eecbe 100644 --- a/apps/server/src/provider/providerStatusCache.ts +++ b/apps/server/src/provider/providerStatusCache.ts @@ -1,6 +1,8 @@ import * as nodePath from "node:path"; import { type ServerProvider, ServerProvider as ServerProviderSchema } from "@t3tools/contracts"; -import { Cause, Effect, FileSystem, Path, Schema } from "effect"; +import { Cause, Effect, FileSystem, Schema } from "effect"; + +import { writeFileStringAtomically } from "../atomicWrite.ts"; export const PROVIDER_CACHE_IDS = [ "codex", @@ -96,22 +98,8 @@ export const readProviderStatusCache = (filePath: string) => export const writeProviderStatusCache = (input: { readonly filePath: string; readonly provider: ServerProvider; -}) => { - const tempPath = `${input.filePath}.${process.pid}.${Date.now()}.tmp`; - return Effect.gen(function* () { - const fs = yield* FileSystem.FileSystem; - const path = yield* Path.Path; - const encoded = `${JSON.stringify(input.provider, null, 2)}\n`; - - yield* fs.makeDirectory(path.dirname(input.filePath), { recursive: true }); - yield* fs.writeFileString(tempPath, encoded); - yield* fs.rename(tempPath, input.filePath); - }).pipe( - Effect.ensuring( - Effect.gen(function* () { - const fs = yield* FileSystem.FileSystem; - yield* fs.remove(tempPath, { force: true }).pipe(Effect.ignore({ log: true })); - }), - ), - ); -}; +}) => + writeFileStringAtomically({ + filePath: input.filePath, + contents: `${JSON.stringify(input.provider, null, 2)}\n`, + }); diff --git a/apps/server/src/serverRuntimeState.ts b/apps/server/src/serverRuntimeState.ts index 569e4ac117..4b300f29c2 100644 --- a/apps/server/src/serverRuntimeState.ts +++ b/apps/server/src/serverRuntimeState.ts @@ -1,5 +1,6 @@ -import { Effect, FileSystem, Option, Path, Schema } from "effect"; +import { Effect, FileSystem, Option, Schema } from "effect"; +import { writeFileStringAtomically } from "./atomicWrite.ts"; import { type ServerConfigShape } from "./config.ts"; import { formatHostForUrl, isWildcardHost } from "./startupAccess.ts"; @@ -42,15 +43,9 @@ export const persistServerRuntimeState = (input: { readonly path: string; readonly state: PersistedServerRuntimeState; }) => - Effect.gen(function* () { - const fs = yield* FileSystem.FileSystem; - const pathService = yield* Path.Path; - const tempPath = `${input.path}.${process.pid}.${Date.now()}.tmp`; - return yield* fs.makeDirectory(pathService.dirname(input.path), { recursive: true }).pipe( - Effect.flatMap(() => fs.writeFileString(tempPath, `${JSON.stringify(input.state)}\n`)), - Effect.flatMap(() => fs.rename(tempPath, input.path)), - Effect.ensuring(fs.remove(tempPath, { force: true }).pipe(Effect.ignore({ log: true }))), - ); + writeFileStringAtomically({ + filePath: input.path, + contents: `${JSON.stringify(input.state)}\n`, }); export const clearPersistedServerRuntimeState = (path: string) => diff --git a/apps/server/src/serverSettings.ts b/apps/server/src/serverSettings.ts index c47c442a86..c2147a0f45 100644 --- a/apps/server/src/serverSettings.ts +++ b/apps/server/src/serverSettings.ts @@ -39,6 +39,7 @@ import { Cause, } from "effect"; import * as Semaphore from "effect/Semaphore"; +import { writeFileStringAtomically } from "./atomicWrite.ts"; import { ServerConfig } from "./config.ts"; import { type DeepPartial, deepMerge } from "@t3tools/shared/Struct"; import { fromLenientJson } from "@t3tools/shared/schemaJson"; @@ -233,14 +234,14 @@ const makeServerSettings = Effect.gen(function* () { const getSettingsFromCache = Cache.get(settingsCache, cacheKey); const writeSettingsAtomically = (settings: ServerSettings) => { - const tempPath = `${settingsPath}.${process.pid}.${Date.now()}.tmp`; const sparseSettings = stripDefaultServerSettings(settings, DEFAULT_SERVER_SETTINGS) ?? {}; - return Effect.succeed(`${JSON.stringify(sparseSettings, null, 2)}\n`).pipe( - Effect.tap(() => fs.makeDirectory(pathService.dirname(settingsPath), { recursive: true })), - Effect.tap((encoded) => fs.writeFileString(tempPath, encoded)), - Effect.flatMap(() => fs.rename(tempPath, settingsPath)), - Effect.ensuring(fs.remove(tempPath, { force: true }).pipe(Effect.ignore({ log: true }))), + return writeFileStringAtomically({ + filePath: settingsPath, + contents: `${JSON.stringify(sparseSettings, null, 2)}\n`, + }).pipe( + Effect.provideService(FileSystem.FileSystem, fs), + Effect.provideService(Path.Path, pathService), Effect.mapError( (cause) => new ServerSettingsError({ From aa2d385a626c5c659e64f7e1a5bf6b568c3b840f Mon Sep 17 00:00:00 2001 From: Hauke Schnau Date: Thu, 23 Apr 2026 06:37:58 +0200 Subject: [PATCH 18/82] fix(server): restore CODEX_HOME tilde expansion for Codex launches (#2255) --- apps/server/src/provider/Layers/CodexProvider.ts | 3 ++- apps/server/src/provider/Layers/CodexSessionRuntime.ts | 5 ++++- 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/apps/server/src/provider/Layers/CodexProvider.ts b/apps/server/src/provider/Layers/CodexProvider.ts index 13069952ae..1e48847c52 100644 --- a/apps/server/src/provider/Layers/CodexProvider.ts +++ b/apps/server/src/provider/Layers/CodexProvider.ts @@ -28,6 +28,7 @@ import { ServerSettingsError } from "@t3tools/contracts"; import { makeManagedServerProvider } from "../makeManagedServerProvider.ts"; import { buildServerProvider } from "../providerSnapshot.ts"; import { CodexProvider } from "../Services/CodexProvider.ts"; +import { expandHomePath } from "../../pathExpansion.ts"; import { ServerSettingsService } from "../../serverSettings.ts"; import packageJson from "../../../package.json" with { type: "json" }; @@ -222,7 +223,7 @@ const probeCodexAppServerProvider = Effect.fn("probeCodexAppServerProvider")(fun command: input.binaryPath, args: ["app-server"], cwd: input.cwd, - ...(input.homePath ? { env: { CODEX_HOME: input.homePath } } : {}), + ...(input.homePath ? { env: { CODEX_HOME: expandHomePath(input.homePath) } } : {}), }), ); const client = yield* Effect.service(CodexClient.CodexAppServerClient).pipe( diff --git a/apps/server/src/provider/Layers/CodexSessionRuntime.ts b/apps/server/src/provider/Layers/CodexSessionRuntime.ts index fbf4aa3dee..e45e1825ee 100644 --- a/apps/server/src/provider/Layers/CodexSessionRuntime.ts +++ b/apps/server/src/provider/Layers/CodexSessionRuntime.ts @@ -30,6 +30,7 @@ import { CODEX_DEFAULT_MODE_DEVELOPER_INSTRUCTIONS, CODEX_PLAN_MODE_DEVELOPER_INSTRUCTIONS, } from "../CodexDeveloperInstructions.ts"; +import { expandHomePath } from "../../pathExpansion.ts"; const PROVIDER = "codex" as const; @@ -683,7 +684,9 @@ export const makeCodexSessionRuntime = ( .spawn( ChildProcess.make(options.binaryPath, ["app-server"], { cwd: options.cwd, - ...(options.homePath ? { env: { ...process.env, CODEX_HOME: options.homePath } } : {}), + ...(options.homePath + ? { env: { ...process.env, CODEX_HOME: expandHomePath(options.homePath) } } + : {}), shell: process.platform === "win32", }), ) From fd3b96b487a9aac8a011c27f977067d63d942ac1 Mon Sep 17 00:00:00 2001 From: Bas Milius Date: Thu, 23 Apr 2026 06:40:27 +0200 Subject: [PATCH 19/82] Add IntelliJ project icon to the list of possible favicon paths (#1651) --- apps/server/src/project/Layers/ProjectFaviconResolver.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/apps/server/src/project/Layers/ProjectFaviconResolver.ts b/apps/server/src/project/Layers/ProjectFaviconResolver.ts index 3004a7a45c..f2d44a7609 100644 --- a/apps/server/src/project/Layers/ProjectFaviconResolver.ts +++ b/apps/server/src/project/Layers/ProjectFaviconResolver.ts @@ -27,6 +27,7 @@ const FAVICON_CANDIDATES = [ "assets/icon.png", "assets/logo.svg", "assets/logo.png", + ".idea/icon.svg", ] as const; // Files that may contain a or icon metadata declaration. From b0b7b38da1dc4b19833d13f84eb907b1e2adfb63 Mon Sep 17 00:00:00 2001 From: Raul Pereira da Silva <38929917+raulpesilva@users.noreply.github.com> Date: Thu, 23 Apr 2026 01:42:19 -0300 Subject: [PATCH 20/82] fix(server): detect localized Windows command errors (#2152) Co-authored-by: macroscopeapp[bot] <170038800+macroscopeapp[bot]@users.noreply.github.com> --- apps/server/src/processRunner.test.ts | 20 +++++++++++++++++++- apps/server/src/processRunner.ts | 15 ++++++++++++++- 2 files changed, 33 insertions(+), 2 deletions(-) diff --git a/apps/server/src/processRunner.test.ts b/apps/server/src/processRunner.test.ts index 15ad4daf09..af4ff528ee 100644 --- a/apps/server/src/processRunner.test.ts +++ b/apps/server/src/processRunner.test.ts @@ -1,6 +1,6 @@ import { describe, expect, it } from "vitest"; -import { runProcess } from "./processRunner.ts"; +import { isWindowsCommandNotFound, runProcess } from "./processRunner.ts"; describe("runProcess", () => { it("fails when output exceeds max buffer in default mode", async () => { @@ -21,3 +21,21 @@ describe("runProcess", () => { expect(result.stderrTruncated).toBe(false); }); }); + +describe("isWindowsCommandNotFound", () => { + it("matches the localized German cmd.exe error text", () => { + const originalPlatform = process.platform; + Object.defineProperty(process, "platform", { value: "win32", configurable: true }); + + try { + expect( + isWindowsCommandNotFound( + 1, + "wird nicht als interner oder externer Befehl, betriebsfahiges Programm oder Batch-Datei erkannt", + ), + ).toBe(true); + } finally { + Object.defineProperty(process, "platform", { value: originalPlatform, configurable: true }); + } + }); +}); diff --git a/apps/server/src/processRunner.ts b/apps/server/src/processRunner.ts index 5402612887..03b164fc24 100644 --- a/apps/server/src/processRunner.ts +++ b/apps/server/src/processRunner.ts @@ -37,10 +37,23 @@ function normalizeSpawnError(command: string, args: readonly string[], error: un return new Error(`Failed to run ${commandLabel(command, args)}: ${error.message}`); } +const WINDOWS_COMMAND_NOT_FOUND_PATTERNS = [ + /is not recognized as an internal or external command/i, + /n.o . reconhecido como um comando interno/i, + /non . riconosciuto come comando interno o esterno/i, + /n.est pas reconnu en tant que commande interne/i, + /no se reconoce como un comando interno o externo/i, + /wird nicht als interner oder externer befehl/i, +] as const; + +function hasWindowsCommandNotFoundMessage(output: string): boolean { + return WINDOWS_COMMAND_NOT_FOUND_PATTERNS.some((pattern) => pattern.test(output)); +} + export function isWindowsCommandNotFound(code: number | null, stderr: string): boolean { if (process.platform !== "win32") return false; if (code === 9009) return true; - return /is not recognized as an internal or external command/i.test(stderr); + return hasWindowsCommandNotFoundMessage(stderr); } function normalizeExitError( From 8d1d699f88279066f085f95908c845334715830e Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Thu, 23 Apr 2026 06:35:40 -0700 Subject: [PATCH 21/82] Refactor provider model selections to option arrays (#2246) Co-authored-by: Cursor Agent Co-authored-by: cursor[bot] <206951365+cursor[bot]@users.noreply.github.com> Co-authored-by: codex --- .cursor/.gitignore | 1 + .../git/Layers/ClaudeTextGeneration.test.ts | 21 +- .../src/git/Layers/ClaudeTextGeneration.ts | 40 +- .../git/Layers/CodexTextGeneration.test.ts | 13 +- .../src/git/Layers/CodexTextGeneration.ts | 11 +- .../git/Layers/CursorTextGeneration.test.ts | 13 +- .../src/git/Layers/CursorTextGeneration.ts | 2 +- .../src/git/Layers/OpenCodeTextGeneration.ts | 14 +- .../src/git/Layers/RoutingTextGeneration.ts | 36 +- .../Layers/ProviderCommandReactor.test.ts | 127 +-- .../decider.projectScripts.test.ts | 25 +- apps/server/src/persistence/Migrations.ts | 2 + ..._CanonicalizeModelSelectionOptions.test.ts | 450 ++++++++++ .../026_CanonicalizeModelSelectionOptions.ts | 138 +++ .../src/provider/Layers/ClaudeAdapter.test.ts | 111 +-- .../src/provider/Layers/ClaudeAdapter.ts | 64 +- .../src/provider/Layers/ClaudeProvider.ts | 227 +++-- .../src/provider/Layers/CodexAdapter.test.ts | 23 +- .../src/provider/Layers/CodexAdapter.ts | 27 +- .../src/provider/Layers/CodexProvider.ts | 61 +- .../src/provider/Layers/CursorAdapter.test.ts | 27 +- .../src/provider/Layers/CursorAdapter.ts | 6 +- .../provider/Layers/CursorProvider.test.ts | 195 ++--- .../src/provider/Layers/CursorProvider.ts | 144 ++- .../src/provider/Layers/OpenCodeAdapter.ts | 5 +- .../provider/Layers/OpenCodeProvider.test.ts | 14 +- .../src/provider/Layers/OpenCodeProvider.ts | 71 +- .../Layers/ProviderAdapterRegistry.ts | 13 +- .../provider/Layers/ProviderRegistry.test.ts | 93 +- .../src/provider/Layers/ProviderRegistry.ts | 47 +- .../provider/Layers/ProviderService.test.ts | 22 +- .../src/provider/acp/CursorAcpSupport.test.ts | 10 +- .../src/provider/acp/CursorAcpSupport.ts | 6 +- .../src/provider/builtInProviderCatalog.ts | 49 ++ .../makeManagedServerProvider.test.ts | 28 +- apps/server/src/provider/opencodeRuntime.ts | 1 - .../src/provider/providerSnapshot.test.ts | 28 +- apps/server/src/provider/providerSnapshot.ts | 55 ++ .../src/provider/providerStatusCache.test.ts | 27 +- apps/server/src/serverSettings.test.ts | 99 ++- apps/web/src/components/ChatView.browser.tsx | 127 ++- apps/web/src/components/ChatView.tsx | 13 +- apps/web/src/components/chat/ChatComposer.tsx | 20 +- .../CompactComposerControlsMenu.browser.tsx | 195 +++-- .../chat/ProviderModelPicker.browser.tsx | 258 +++--- .../components/chat/ProviderStatusBanner.tsx | 5 +- .../components/chat/TraitsPicker.browser.tsx | 821 ------------------ apps/web/src/components/chat/TraitsPicker.tsx | 522 ++++------- .../chat/composerProviderRegistry.test.tsx | 516 ----------- .../chat/composerProviderRegistry.tsx | 216 ----- .../chat/composerProviderState.test.tsx | 242 ++++++ .../components/chat/composerProviderState.tsx | 108 +++ .../components/settings/SettingsPanels.tsx | 28 +- apps/web/src/composerDraftStore.test.ts | 141 +-- apps/web/src/composerDraftStore.ts | 401 ++++----- apps/web/src/modelSelection.ts | 47 +- apps/web/src/providerModels.ts | 68 +- packages/contracts/src/model.ts | 184 ++-- packages/contracts/src/orchestration.test.ts | 97 ++- packages/contracts/src/orchestration.ts | 15 +- packages/contracts/src/provider.test.ts | 63 +- packages/contracts/src/server.ts | 3 + packages/contracts/src/settings.ts | 37 +- packages/shared/src/model.test.ts | 286 +++--- packages/shared/src/model.ts | 387 +++++---- packages/shared/src/serverSettings.test.ts | 71 +- packages/shared/src/serverSettings.ts | 68 +- 67 files changed, 3430 insertions(+), 3855 deletions(-) create mode 100644 .cursor/.gitignore create mode 100644 apps/server/src/persistence/Migrations/026_CanonicalizeModelSelectionOptions.test.ts create mode 100644 apps/server/src/persistence/Migrations/026_CanonicalizeModelSelectionOptions.ts create mode 100644 apps/server/src/provider/builtInProviderCatalog.ts delete mode 100644 apps/web/src/components/chat/TraitsPicker.browser.tsx delete mode 100644 apps/web/src/components/chat/composerProviderRegistry.test.tsx delete mode 100644 apps/web/src/components/chat/composerProviderRegistry.tsx create mode 100644 apps/web/src/components/chat/composerProviderState.test.tsx create mode 100644 apps/web/src/components/chat/composerProviderState.tsx diff --git a/.cursor/.gitignore b/.cursor/.gitignore new file mode 100644 index 0000000000..8bf7cc27a1 --- /dev/null +++ b/.cursor/.gitignore @@ -0,0 +1 @@ +plans/ diff --git a/apps/server/src/git/Layers/ClaudeTextGeneration.test.ts b/apps/server/src/git/Layers/ClaudeTextGeneration.test.ts index 0847134698..773f781eed 100644 --- a/apps/server/src/git/Layers/ClaudeTextGeneration.test.ts +++ b/apps/server/src/git/Layers/ClaudeTextGeneration.test.ts @@ -1,6 +1,7 @@ import * as NodeServices from "@effect/platform-node/NodeServices"; import { it } from "@effect/vitest"; import { Effect, FileSystem, Layer, Path } from "effect"; +import { createModelSelection } from "@t3tools/shared/model"; import { expect } from "vitest"; import { ServerConfig } from "../../config.ts"; @@ -199,12 +200,10 @@ it.layer(ClaudeTextGenerationTestLayer)("ClaudeTextGenerationLive", (it) => { stagedSummary: "M README.md", stagedPatch: "diff --git a/README.md b/README.md", modelSelection: { - provider: "claudeAgent", - model: "claude-haiku-4-5", - options: { - thinking: false, - effort: "high", - }, + ...createModelSelection("claudeAgent", "claude-haiku-4-5", [ + { id: "thinking", value: false }, + { id: "effort", value: "high" }, + ]), }, }); @@ -235,12 +234,10 @@ it.layer(ClaudeTextGenerationTestLayer)("ClaudeTextGenerationLive", (it) => { diffSummary: "1 file changed", diffPatch: "diff --git a/README.md b/README.md", modelSelection: { - provider: "claudeAgent", - model: "claude-opus-4-6", - options: { - effort: "max", - fastMode: true, - }, + ...createModelSelection("claudeAgent", "claude-opus-4-6", [ + { id: "effort", value: "max" }, + { id: "fastMode", value: true }, + ]), }, }); diff --git a/apps/server/src/git/Layers/ClaudeTextGeneration.ts b/apps/server/src/git/Layers/ClaudeTextGeneration.ts index 97e18c3e78..8175dc54b2 100644 --- a/apps/server/src/git/Layers/ClaudeTextGeneration.ts +++ b/apps/server/src/git/Layers/ClaudeTextGeneration.ts @@ -28,10 +28,17 @@ import { sanitizeThreadTitle, toJsonSchemaObject, } from "../Utils.ts"; -import { normalizeClaudeModelOptionsWithCapabilities } from "@t3tools/shared/model"; -import { resolveClaudeApiModelId } from "../../provider/Layers/ClaudeProvider.ts"; +import { + getModelSelectionStringOptionValue, + getProviderOptionDescriptors, +} from "@t3tools/shared/model"; +import { + getClaudeModelCapabilities, + normalizeClaudeCliEffort, + resolveClaudeApiModelId, + resolveClaudeEffort, +} from "../../provider/Layers/ClaudeProvider.ts"; import { ServerSettingsService } from "../../serverSettings.ts"; -import { getClaudeModelCapabilities } from "../../provider/Layers/ClaudeProvider.ts"; const CLAUDE_TIMEOUT_MS = 180_000; @@ -84,15 +91,24 @@ const makeClaudeTextGeneration = Effect.gen(function* () { modelSelection: ClaudeModelSelection; }): Effect.fn.Return { const jsonSchemaStr = JSON.stringify(toJsonSchemaObject(outputSchemaJson)); - const normalizedOptions = normalizeClaudeModelOptionsWithCapabilities( - getClaudeModelCapabilities(modelSelection.model), - modelSelection.options, - ); + const caps = getClaudeModelCapabilities(modelSelection.model); + const descriptors = getProviderOptionDescriptors({ + caps, + selections: modelSelection.options, + }); + const findDescriptor = (id: string) => descriptors.find((descriptor) => descriptor.id === id); + const rawEffortSelection = getModelSelectionStringOptionValue(modelSelection, "effort"); + const resolvedEffort = resolveClaudeEffort(caps, rawEffortSelection); + const cliEffort = normalizeClaudeCliEffort(resolvedEffort); + const thinkingDescriptor = findDescriptor("thinking"); + const fastModeDescriptor = findDescriptor("fastMode"); + const thinking = + thinkingDescriptor?.type === "boolean" ? thinkingDescriptor.currentValue : undefined; + const fastMode = + fastModeDescriptor?.type === "boolean" ? fastModeDescriptor.currentValue : undefined; const settings = { - ...(typeof normalizedOptions?.thinking === "boolean" - ? { alwaysThinkingEnabled: normalizedOptions.thinking } - : {}), - ...(normalizedOptions?.fastMode ? { fastMode: true } : {}), + ...(typeof thinking === "boolean" ? { alwaysThinkingEnabled: thinking } : {}), + ...(fastMode ? { fastMode: true } : {}), }; const claudeSettings = yield* Effect.map( @@ -111,7 +127,7 @@ const makeClaudeTextGeneration = Effect.gen(function* () { jsonSchemaStr, "--model", resolveClaudeApiModelId(modelSelection), - ...(normalizedOptions?.effort ? ["--effort", normalizedOptions.effort] : []), + ...(cliEffort ? ["--effort", cliEffort] : []), ...(Object.keys(settings).length > 0 ? ["--settings", JSON.stringify(settings)] : []), "--dangerously-skip-permissions", ], diff --git a/apps/server/src/git/Layers/CodexTextGeneration.test.ts b/apps/server/src/git/Layers/CodexTextGeneration.test.ts index a07505f025..2adfcca848 100644 --- a/apps/server/src/git/Layers/CodexTextGeneration.test.ts +++ b/apps/server/src/git/Layers/CodexTextGeneration.test.ts @@ -1,6 +1,7 @@ import * as NodeServices from "@effect/platform-node/NodeServices"; import { it } from "@effect/vitest"; import { Effect, FileSystem, Layer, Path, Result } from "effect"; +import { createModelSelection } from "@t3tools/shared/model"; import { expect } from "vitest"; import { ServerConfig } from "../../config.ts"; @@ -244,14 +245,10 @@ it.layer(CodexTextGenerationTestLayer)("CodexTextGenerationLive", (it) => { branch: "feature/codex-effect", stagedSummary: "M README.md", stagedPatch: "diff --git a/README.md b/README.md", - modelSelection: { - provider: "codex", - model: "gpt-5.4", - options: { - reasoningEffort: "xhigh", - fastMode: true, - }, - }, + modelSelection: createModelSelection("codex", "gpt-5.4", [ + { id: "reasoningEffort", value: "xhigh" }, + { id: "fastMode", value: true }, + ]), }); }), ), diff --git a/apps/server/src/git/Layers/CodexTextGeneration.ts b/apps/server/src/git/Layers/CodexTextGeneration.ts index 8f15bfa186..ee1e39d0fa 100644 --- a/apps/server/src/git/Layers/CodexTextGeneration.ts +++ b/apps/server/src/git/Layers/CodexTextGeneration.ts @@ -30,6 +30,10 @@ import { toJsonSchemaObject, } from "../Utils.ts"; import { ServerSettingsService } from "../../serverSettings.ts"; +import { + getModelSelectionBooleanOptionValue, + getModelSelectionStringOptionValue, +} from "@t3tools/shared/model"; const CODEX_GIT_TEXT_GENERATION_REASONING_EFFORT = "low"; const CODEX_TIMEOUT_MS = 180_000; @@ -155,7 +159,8 @@ const makeCodexTextGeneration = Effect.gen(function* () { const runCodexCommand = Effect.fn("runCodexJson.runCodexCommand")(function* () { const reasoningEffort = - modelSelection.options?.reasoningEffort ?? CODEX_GIT_TEXT_GENERATION_REASONING_EFFORT; + getModelSelectionStringOptionValue(modelSelection, "reasoningEffort") ?? + CODEX_GIT_TEXT_GENERATION_REASONING_EFFORT; const command = ChildProcess.make( codexSettings?.binaryPath || "codex", [ @@ -168,7 +173,9 @@ const makeCodexTextGeneration = Effect.gen(function* () { modelSelection.model, "--config", `model_reasoning_effort="${reasoningEffort}"`, - ...(modelSelection.options?.fastMode ? ["--config", `service_tier="fast"`] : []), + ...(getModelSelectionBooleanOptionValue(modelSelection, "fastMode") === true + ? ["--config", `service_tier="fast"`] + : []), "--output-schema", schemaPath, "--output-last-message", diff --git a/apps/server/src/git/Layers/CursorTextGeneration.test.ts b/apps/server/src/git/Layers/CursorTextGeneration.test.ts index e7bce11347..b8d974fd94 100644 --- a/apps/server/src/git/Layers/CursorTextGeneration.test.ts +++ b/apps/server/src/git/Layers/CursorTextGeneration.test.ts @@ -6,6 +6,7 @@ import { chmodSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync import * as NodeServices from "@effect/platform-node/NodeServices"; import { it } from "@effect/vitest"; import { Effect, Layer } from "effect"; +import { createModelSelection } from "@t3tools/shared/model"; import { expect } from "vitest"; import { ServerSettingsError } from "@t3tools/contracts"; @@ -135,13 +136,11 @@ it.layer(CursorTextGenerationTestLayer)("CursorTextGenerationLive", (it) => { stagedPatch: "diff --git a/apps/server/src/git/Layers/CursorTextGeneration.ts b/apps/server/src/git/Layers/CursorTextGeneration.ts", modelSelection: { - provider: "cursor", - model: "gpt-5.4", - options: { - reasoning: "xhigh", - fastMode: true, - contextWindow: "1m", - }, + ...createModelSelection("cursor", "gpt-5.4", [ + { id: "reasoning", value: "xhigh" }, + { id: "fastMode", value: true }, + { id: "contextWindow", value: "1m" }, + ]), }, }); diff --git a/apps/server/src/git/Layers/CursorTextGeneration.ts b/apps/server/src/git/Layers/CursorTextGeneration.ts index 24f066059c..6b78728b95 100644 --- a/apps/server/src/git/Layers/CursorTextGeneration.ts +++ b/apps/server/src/git/Layers/CursorTextGeneration.ts @@ -108,7 +108,7 @@ const makeCursorTextGeneration = Effect.gen(function* () { yield* applyCursorAcpModelSelection({ runtime, model: modelSelection.model, - modelOptions: modelSelection.options, + selections: modelSelection.options, mapError: ({ cause, configId, step }) => mapCursorAcpError( operation, diff --git a/apps/server/src/git/Layers/OpenCodeTextGeneration.ts b/apps/server/src/git/Layers/OpenCodeTextGeneration.ts index fd28188d60..d9ebb094e7 100644 --- a/apps/server/src/git/Layers/OpenCodeTextGeneration.ts +++ b/apps/server/src/git/Layers/OpenCodeTextGeneration.ts @@ -7,6 +7,7 @@ import { type OpenCodeModelSelection, } from "@t3tools/contracts"; import { sanitizeBranchFragment, sanitizeFeatureBranchName } from "@t3tools/shared/git"; +import { getModelSelectionStringOptionValue } from "@t3tools/shared/model"; import { ServerConfig } from "../../config.ts"; import { resolveAttachmentPath } from "../../attachmentStore.ts"; @@ -320,16 +321,17 @@ const makeOpenCodeTextGeneration = Effect.gen(function* () { if (!session.data) { throw new Error("OpenCode session.create returned no session payload."); } + const selectedAgent = getModelSelectionStringOptionValue(input.modelSelection, "agent"); + const selectedVariant = getModelSelectionStringOptionValue( + input.modelSelection, + "variant", + ); const result = await client.session.prompt({ sessionID: session.data.id, model: parsedModel, - ...(input.modelSelection.options?.agent - ? { agent: input.modelSelection.options.agent } - : {}), - ...(input.modelSelection.options?.variant - ? { variant: input.modelSelection.options.variant } - : {}), + ...(selectedAgent ? { agent: selectedAgent } : {}), + ...(selectedVariant ? { variant: selectedVariant } : {}), parts: [{ type: "text", text: input.prompt }, ...fileParts], }); const info = result.data?.info; diff --git a/apps/server/src/git/Layers/RoutingTextGeneration.ts b/apps/server/src/git/Layers/RoutingTextGeneration.ts index 8f5c166d81..873d616f39 100644 --- a/apps/server/src/git/Layers/RoutingTextGeneration.ts +++ b/apps/server/src/git/Layers/RoutingTextGeneration.ts @@ -11,11 +11,7 @@ */ import { Effect, Layer, Context } from "effect"; -import { - TextGeneration, - type TextGenerationProvider, - type TextGenerationShape, -} from "../Services/TextGeneration.ts"; +import { TextGeneration, type TextGenerationShape } from "../Services/TextGeneration.ts"; import { CodexTextGenerationLive } from "./CodexTextGeneration.ts"; import { ClaudeTextGenerationLive } from "./ClaudeTextGeneration.ts"; import { CursorTextGenerationLive } from "./CursorTextGeneration.ts"; @@ -46,26 +42,22 @@ class OpenCodeTextGen extends Context.Service - provider === "claudeAgent" - ? claude - : provider === "opencode" - ? openCode - : provider === "cursor" - ? cursor - : codex; + const byProvider = { + codex: yield* CodexTextGen, + claudeAgent: yield* ClaudeTextGen, + cursor: yield* CursorTextGen, + opencode: yield* OpenCodeTextGen, + }; return { generateCommitMessage: (input) => - route(input.modelSelection.provider).generateCommitMessage(input), - generatePrContent: (input) => route(input.modelSelection.provider).generatePrContent(input), - generateBranchName: (input) => route(input.modelSelection.provider).generateBranchName(input), - generateThreadTitle: (input) => route(input.modelSelection.provider).generateThreadTitle(input), + byProvider[input.modelSelection.provider].generateCommitMessage(input), + generatePrContent: (input) => + byProvider[input.modelSelection.provider].generatePrContent(input), + generateBranchName: (input) => + byProvider[input.modelSelection.provider].generateBranchName(input), + generateThreadTitle: (input) => + byProvider[input.modelSelection.provider].generateThreadTitle(input), } satisfies TextGenerationShape; }); diff --git a/apps/server/src/orchestration/Layers/ProviderCommandReactor.test.ts b/apps/server/src/orchestration/Layers/ProviderCommandReactor.test.ts index dfdfab926f..a52ed5856e 100644 --- a/apps/server/src/orchestration/Layers/ProviderCommandReactor.test.ts +++ b/apps/server/src/orchestration/Layers/ProviderCommandReactor.test.ts @@ -3,6 +3,7 @@ import os from "node:os"; import path from "node:path"; import type { ModelSelection, ProviderRuntimeEvent, ProviderSession } from "@t3tools/contracts"; +import { createModelSelection } from "@t3tools/shared/model"; import { ApprovalRequestId, CommandId, @@ -567,14 +568,10 @@ describe("ProviderCommandReactor", () => { text: "hello fast mode", attachments: [], }, - modelSelection: { - provider: "codex", - model: "gpt-5.3-codex", - options: { - reasoningEffort: "high", - fastMode: true, - }, - }, + modelSelection: createModelSelection("codex", "gpt-5.3-codex", [ + { id: "reasoningEffort", value: "high" }, + { id: "fastMode", value: true }, + ]), interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE, runtimeMode: "approval-required", createdAt: now, @@ -584,25 +581,17 @@ describe("ProviderCommandReactor", () => { await waitFor(() => harness.startSession.mock.calls.length === 1); await waitFor(() => harness.sendTurn.mock.calls.length === 1); expect(harness.startSession.mock.calls[0]?.[1]).toMatchObject({ - modelSelection: { - provider: "codex", - model: "gpt-5.3-codex", - options: { - reasoningEffort: "high", - fastMode: true, - }, - }, + modelSelection: createModelSelection("codex", "gpt-5.3-codex", [ + { id: "reasoningEffort", value: "high" }, + { id: "fastMode", value: true }, + ]), }); expect(harness.sendTurn.mock.calls[0]?.[0]).toMatchObject({ threadId: ThreadId.make("thread-1"), - modelSelection: { - provider: "codex", - model: "gpt-5.3-codex", - options: { - reasoningEffort: "high", - fastMode: true, - }, - }, + modelSelection: createModelSelection("codex", "gpt-5.3-codex", [ + { id: "reasoningEffort", value: "high" }, + { id: "fastMode", value: true }, + ]), }); }); @@ -623,13 +612,9 @@ describe("ProviderCommandReactor", () => { text: "hello with effort", attachments: [], }, - modelSelection: { - provider: "claudeAgent", - model: "claude-sonnet-4-6", - options: { - effort: "max", - }, - }, + modelSelection: createModelSelection("claudeAgent", "claude-sonnet-4-6", [ + { id: "effort", value: "max" }, + ]), interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE, runtimeMode: "approval-required", createdAt: now, @@ -639,23 +624,15 @@ describe("ProviderCommandReactor", () => { await waitFor(() => harness.startSession.mock.calls.length === 1); await waitFor(() => harness.sendTurn.mock.calls.length === 1); expect(harness.startSession.mock.calls[0]?.[1]).toMatchObject({ - modelSelection: { - provider: "claudeAgent", - model: "claude-sonnet-4-6", - options: { - effort: "max", - }, - }, + modelSelection: createModelSelection("claudeAgent", "claude-sonnet-4-6", [ + { id: "effort", value: "max" }, + ]), }); expect(harness.sendTurn.mock.calls[0]?.[0]).toMatchObject({ threadId: ThreadId.make("thread-1"), - modelSelection: { - provider: "claudeAgent", - model: "claude-sonnet-4-6", - options: { - effort: "max", - }, - }, + modelSelection: createModelSelection("claudeAgent", "claude-sonnet-4-6", [ + { id: "effort", value: "max" }, + ]), }); }); @@ -676,13 +653,9 @@ describe("ProviderCommandReactor", () => { text: "hello with fast mode", attachments: [], }, - modelSelection: { - provider: "claudeAgent", - model: "claude-opus-4-6", - options: { - fastMode: true, - }, - }, + modelSelection: createModelSelection("claudeAgent", "claude-opus-4-6", [ + { id: "fastMode", value: true }, + ]), interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE, runtimeMode: "approval-required", createdAt: now, @@ -692,23 +665,15 @@ describe("ProviderCommandReactor", () => { await waitFor(() => harness.startSession.mock.calls.length === 1); await waitFor(() => harness.sendTurn.mock.calls.length === 1); expect(harness.startSession.mock.calls[0]?.[1]).toMatchObject({ - modelSelection: { - provider: "claudeAgent", - model: "claude-opus-4-6", - options: { - fastMode: true, - }, - }, + modelSelection: createModelSelection("claudeAgent", "claude-opus-4-6", [ + { id: "fastMode", value: true }, + ]), }); expect(harness.sendTurn.mock.calls[0]?.[0]).toMatchObject({ threadId: ThreadId.make("thread-1"), - modelSelection: { - provider: "claudeAgent", - model: "claude-opus-4-6", - options: { - fastMode: true, - }, - }, + modelSelection: createModelSelection("claudeAgent", "claude-opus-4-6", [ + { id: "fastMode", value: true }, + ]), }); }); @@ -916,13 +881,9 @@ describe("ProviderCommandReactor", () => { text: "first claude turn", attachments: [], }, - modelSelection: { - provider: "claudeAgent", - model: "claude-sonnet-4-6", - options: { - effort: "medium", - }, - }, + modelSelection: createModelSelection("claudeAgent", "claude-sonnet-4-6", [ + { id: "effort", value: "medium" }, + ]), interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE, runtimeMode: "approval-required", createdAt: now, @@ -943,13 +904,9 @@ describe("ProviderCommandReactor", () => { text: "second claude turn", attachments: [], }, - modelSelection: { - provider: "claudeAgent", - model: "claude-sonnet-4-6", - options: { - effort: "max", - }, - }, + modelSelection: createModelSelection("claudeAgent", "claude-sonnet-4-6", [ + { id: "effort", value: "max" }, + ]), interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE, runtimeMode: "approval-required", createdAt: now, @@ -960,13 +917,9 @@ describe("ProviderCommandReactor", () => { await waitFor(() => harness.sendTurn.mock.calls.length === 2); expect(harness.startSession.mock.calls[1]?.[1]).toMatchObject({ resumeCursor: { opaque: "resume-1" }, - modelSelection: { - provider: "claudeAgent", - model: "claude-sonnet-4-6", - options: { - effort: "max", - }, - }, + modelSelection: createModelSelection("claudeAgent", "claude-sonnet-4-6", [ + { id: "effort", value: "max" }, + ]), }); }); diff --git a/apps/server/src/orchestration/decider.projectScripts.test.ts b/apps/server/src/orchestration/decider.projectScripts.test.ts index a85e21c53f..1feabb0ed8 100644 --- a/apps/server/src/orchestration/decider.projectScripts.test.ts +++ b/apps/server/src/orchestration/decider.projectScripts.test.ts @@ -6,6 +6,7 @@ import { ProjectId, ThreadId, } from "@t3tools/contracts"; +import { createModelSelection } from "@t3tools/shared/model"; import { describe, expect, it } from "vitest"; import { Effect } from "effect"; @@ -162,14 +163,10 @@ describe("decider project scripts", () => { text: "hello", attachments: [], }, - modelSelection: { - provider: "codex", - model: "gpt-5.3-codex", - options: { - reasoningEffort: "high", - fastMode: true, - }, - }, + modelSelection: createModelSelection("codex", "gpt-5.3-codex", [ + { id: "reasoningEffort", value: "high" }, + { id: "fastMode", value: true }, + ]), interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE, runtimeMode: "approval-required", createdAt: now, @@ -191,14 +188,10 @@ describe("decider project scripts", () => { expect(turnStartEvent.payload).toMatchObject({ threadId: ThreadId.make("thread-1"), messageId: asMessageId("message-user-1"), - modelSelection: { - provider: "codex", - model: "gpt-5.3-codex", - options: { - reasoningEffort: "high", - fastMode: true, - }, - }, + modelSelection: createModelSelection("codex", "gpt-5.3-codex", [ + { id: "reasoningEffort", value: "high" }, + { id: "fastMode", value: true }, + ]), runtimeMode: "approval-required", }); }); diff --git a/apps/server/src/persistence/Migrations.ts b/apps/server/src/persistence/Migrations.ts index 023e3bca05..c8d4647fb7 100644 --- a/apps/server/src/persistence/Migrations.ts +++ b/apps/server/src/persistence/Migrations.ts @@ -38,6 +38,7 @@ import Migration0022 from "./Migrations/022_AuthSessionLastConnectedAt.ts"; import Migration0023 from "./Migrations/023_ProjectionThreadShellSummary.ts"; import Migration0024 from "./Migrations/024_BackfillProjectionThreadShellSummary.ts"; import Migration0025 from "./Migrations/025_CleanupInvalidProjectionPendingApprovals.ts"; +import Migration0026 from "./Migrations/026_CanonicalizeModelSelectionOptions.ts"; /** * Migration loader with all migrations defined inline. @@ -75,6 +76,7 @@ export const migrationEntries = [ [23, "ProjectionThreadShellSummary", Migration0023], [24, "BackfillProjectionThreadShellSummary", Migration0024], [25, "CleanupInvalidProjectionPendingApprovals", Migration0025], + [26, "CanonicalizeModelSelectionOptions", Migration0026], ] as const; export const makeMigrationLoader = (throughId?: number) => diff --git a/apps/server/src/persistence/Migrations/026_CanonicalizeModelSelectionOptions.test.ts b/apps/server/src/persistence/Migrations/026_CanonicalizeModelSelectionOptions.test.ts new file mode 100644 index 0000000000..ffc42521c9 --- /dev/null +++ b/apps/server/src/persistence/Migrations/026_CanonicalizeModelSelectionOptions.test.ts @@ -0,0 +1,450 @@ +import { assert, it } from "@effect/vitest"; +import { Effect, Layer } from "effect"; +import * as SqlClient from "effect/unstable/sql/SqlClient"; + +import { runMigrations } from "../Migrations.ts"; +import * as NodeSqliteClient from "../NodeSqliteClient.ts"; + +const layer = it.layer(Layer.mergeAll(NodeSqliteClient.layerMemory())); + +layer("026_CanonicalizeModelSelectionOptions", (it) => { + it.effect("converts legacy object-shape options into array-shape on projections and events", () => + Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + + yield* runMigrations({ toMigrationInclusive: 25 }); + + yield* sql` + INSERT INTO projection_projects ( + project_id, + title, + workspace_root, + default_model_selection_json, + scripts_json, + created_at, + updated_at, + deleted_at + ) + VALUES + ( + 'project-legacy', + 'Legacy options project', + '/tmp/legacy', + '{"provider":"claudeAgent","model":"claude-opus-4-6","options":{"effort":"max","fastMode":true}}', + '[]', + '2026-01-01T00:00:00.000Z', + '2026-01-01T00:00:00.000Z', + NULL + ), + ( + 'project-no-options', + 'No options project', + '/tmp/no-options', + '{"provider":"codex","model":"gpt-5.4"}', + '[]', + '2026-01-01T00:00:00.000Z', + '2026-01-01T00:00:00.000Z', + NULL + ), + ( + 'project-null-selection', + 'Null model selection project', + '/tmp/null-selection', + NULL, + '[]', + '2026-01-01T00:00:00.000Z', + '2026-01-01T00:00:00.000Z', + NULL + ), + ( + 'project-already-array', + 'Already-canonical options project', + '/tmp/already-array', + '{"provider":"codex","model":"gpt-5.4","options":[{"id":"reasoningEffort","value":"high"}]}', + '[]', + '2026-01-01T00:00:00.000Z', + '2026-01-01T00:00:00.000Z', + NULL + ) + `; + + yield* sql` + INSERT INTO projection_threads ( + thread_id, + project_id, + title, + model_selection_json, + branch, + worktree_path, + latest_turn_id, + created_at, + updated_at, + archived_at, + latest_user_message_at, + pending_approval_count, + pending_user_input_count, + has_actionable_proposed_plan, + deleted_at, + runtime_mode, + interaction_mode + ) + VALUES + ( + 'thread-legacy', + 'project-legacy', + 'Legacy thread', + '{"provider":"claudeAgent","model":"claude-opus-4-6","options":{"effort":"max","thinking":false,"contextWindow":"1m"}}', + NULL, NULL, NULL, + '2026-01-01T00:00:00.000Z', + '2026-01-01T00:00:00.000Z', + NULL, NULL, 0, 0, 0, NULL, + 'full-access', 'default' + ), + ( + 'thread-empty-options', + 'project-legacy', + 'Empty options thread', + '{"provider":"codex","model":"gpt-5.4","options":{}}', + NULL, NULL, NULL, + '2026-01-01T00:00:00.000Z', + '2026-01-01T00:00:00.000Z', + NULL, NULL, 0, 0, 0, NULL, + 'full-access', 'default' + ), + ( + 'thread-drop-garbage', + 'project-legacy', + 'Thread with non-scalar entries', + '{"provider":"claudeAgent","model":"claude-opus-4-6","options":{"effort":"high","thinking":{"enabled":true,"budgetTokens":2000},"emptyStr":" ","nullish":null}}', + NULL, NULL, NULL, + '2026-01-01T00:00:00.000Z', + '2026-01-01T00:00:00.000Z', + NULL, NULL, 0, 0, 0, NULL, + 'full-access', 'default' + ), + ( + 'thread-no-options', + 'project-legacy', + 'No options thread', + '{"provider":"codex","model":"gpt-5.4"}', + NULL, NULL, NULL, + '2026-01-01T00:00:00.000Z', + '2026-01-01T00:00:00.000Z', + NULL, NULL, 0, 0, 0, NULL, + 'full-access', 'default' + ), + ( + 'thread-already-array', + 'project-legacy', + 'Already array thread', + '{"provider":"codex","model":"gpt-5.4","options":[{"id":"fastMode","value":true}]}', + NULL, NULL, NULL, + '2026-01-01T00:00:00.000Z', + '2026-01-01T00:00:00.000Z', + NULL, NULL, 0, 0, 0, NULL, + 'full-access', 'default' + ) + `; + + yield* sql` + INSERT INTO orchestration_events ( + event_id, + aggregate_kind, + stream_id, + stream_version, + event_type, + occurred_at, + command_id, + causation_event_id, + correlation_id, + actor_kind, + payload_json, + metadata_json + ) + VALUES + ( + 'event-project-created', + 'project', + 'project-legacy', + 1, + 'project.created', + '2026-01-01T00:00:00.000Z', + 'cmd-pc', + NULL, + 'corr-pc', + 'user', + '{"projectId":"project-legacy","title":"Project","workspaceRoot":"/tmp/legacy","defaultModelSelection":{"provider":"claudeAgent","model":"claude-opus-4-6","options":{"effort":"max","fastMode":true}},"scripts":[],"createdAt":"2026-01-01T00:00:00.000Z","updatedAt":"2026-01-01T00:00:00.000Z"}', + '{}' + ), + ( + 'event-project-meta-updated', + 'project', + 'project-legacy', + 2, + 'project.meta-updated', + '2026-01-01T00:00:00.000Z', + 'cmd-pmu', + NULL, + 'corr-pmu', + 'user', + '{"projectId":"project-legacy","defaultModelSelection":{"provider":"codex","model":"gpt-5.4","options":{"reasoningEffort":"low"}},"updatedAt":"2026-01-01T00:00:00.000Z"}', + '{}' + ), + ( + 'event-project-null-selection', + 'project', + 'project-legacy', + 3, + 'project.meta-updated', + '2026-01-01T00:00:00.000Z', + 'cmd-null', + NULL, + 'corr-null', + 'user', + '{"projectId":"project-legacy","defaultModelSelection":null,"updatedAt":"2026-01-01T00:00:00.000Z"}', + '{}' + ), + ( + 'event-thread-created', + 'thread', + 'thread-legacy', + 1, + 'thread.created', + '2026-01-01T00:00:00.000Z', + 'cmd-tc', + NULL, + 'corr-tc', + 'user', + '{"threadId":"thread-legacy","projectId":"project-legacy","title":"Thread","modelSelection":{"provider":"claudeAgent","model":"claude-opus-4-6","options":{"effort":"max","thinking":false}},"runtimeMode":"full-access","interactionMode":"default","branch":null,"worktreePath":null,"createdAt":"2026-01-01T00:00:00.000Z","updatedAt":"2026-01-01T00:00:00.000Z"}', + '{}' + ), + ( + 'event-thread-meta-updated', + 'thread', + 'thread-legacy', + 2, + 'thread.meta-updated', + '2026-01-01T00:00:00.000Z', + 'cmd-tmu', + NULL, + 'corr-tmu', + 'user', + '{"threadId":"thread-legacy","modelSelection":{"provider":"codex","model":"gpt-5.4","options":{"fastMode":true}},"updatedAt":"2026-01-01T00:00:00.000Z"}', + '{}' + ), + ( + 'event-thread-turn-start', + 'thread', + 'thread-legacy', + 3, + 'thread.turn-start-requested', + '2026-01-01T00:00:00.000Z', + 'cmd-tts', + NULL, + 'corr-tts', + 'user', + '{"threadId":"thread-legacy","messageId":"msg-1","modelSelection":{"provider":"claudeAgent","model":"claude-opus-4-6","options":{"effort":"high","contextWindow":"1m"}},"runtimeMode":"full-access","interactionMode":"default","createdAt":"2026-01-01T00:00:00.000Z"}', + '{}' + ), + ( + 'event-thread-already-array', + 'thread', + 'thread-legacy', + 4, + 'thread.created', + '2026-01-01T00:00:00.000Z', + 'cmd-taa', + NULL, + 'corr-taa', + 'user', + '{"threadId":"thread-already-array","projectId":"project-legacy","title":"Already Array","modelSelection":{"provider":"codex","model":"gpt-5.4","options":[{"id":"reasoningEffort","value":"medium"}]},"runtimeMode":"full-access","interactionMode":"default","branch":null,"worktreePath":null,"createdAt":"2026-01-01T00:00:00.000Z","updatedAt":"2026-01-01T00:00:00.000Z"}', + '{}' + ), + ( + 'event-activity-append', + 'thread', + 'thread-legacy', + 5, + 'thread.activity-appended', + '2026-01-01T00:00:00.000Z', + 'cmd-aa', + NULL, + 'corr-aa', + 'user', + '{"threadId":"thread-legacy","activity":{"id":"a","tone":"info","kind":"k","summary":"s","payload":null,"turnId":null,"createdAt":"2026-01-01T00:00:00.000Z"}}', + '{}' + ) + `; + + yield* runMigrations({ toMigrationInclusive: 26 }); + + // Projection projects + const projectRows = yield* sql<{ + readonly projectId: string; + readonly defaultModelSelection: string | null; + }>` + SELECT + project_id AS "projectId", + default_model_selection_json AS "defaultModelSelection" + FROM projection_projects + ORDER BY project_id + `; + assert.deepStrictEqual( + projectRows.map((row) => ({ + projectId: row.projectId, + selection: row.defaultModelSelection ? JSON.parse(row.defaultModelSelection) : null, + })), + [ + { + projectId: "project-already-array", + selection: { + provider: "codex", + model: "gpt-5.4", + options: [{ id: "reasoningEffort", value: "high" }], + }, + }, + { + projectId: "project-legacy", + selection: { + provider: "claudeAgent", + model: "claude-opus-4-6", + options: [ + { id: "effort", value: "max" }, + { id: "fastMode", value: true }, + ], + }, + }, + { + projectId: "project-no-options", + selection: { provider: "codex", model: "gpt-5.4" }, + }, + { projectId: "project-null-selection", selection: null }, + ], + ); + + // Projection threads + const threadRows = yield* sql<{ + readonly threadId: string; + readonly modelSelection: string | null; + }>` + SELECT + thread_id AS "threadId", + model_selection_json AS "modelSelection" + FROM projection_threads + ORDER BY thread_id + `; + assert.deepStrictEqual( + threadRows.map((row) => ({ + threadId: row.threadId, + selection: row.modelSelection ? JSON.parse(row.modelSelection) : null, + })), + [ + { + threadId: "thread-already-array", + selection: { + provider: "codex", + model: "gpt-5.4", + options: [{ id: "fastMode", value: true }], + }, + }, + { + threadId: "thread-drop-garbage", + selection: { + provider: "claudeAgent", + model: "claude-opus-4-6", + // Only the scalar string survives; nested object, whitespace + // string, and null are dropped. + options: [{ id: "effort", value: "high" }], + }, + }, + { + threadId: "thread-empty-options", + selection: { provider: "codex", model: "gpt-5.4", options: [] }, + }, + { + threadId: "thread-legacy", + selection: { + provider: "claudeAgent", + model: "claude-opus-4-6", + options: [ + { id: "effort", value: "max" }, + { id: "thinking", value: false }, + { id: "contextWindow", value: "1m" }, + ], + }, + }, + { + threadId: "thread-no-options", + selection: { provider: "codex", model: "gpt-5.4" }, + }, + ], + ); + + // Orchestration events + const eventRows = yield* sql<{ + readonly eventId: string; + readonly payloadJson: string; + }>` + SELECT event_id AS "eventId", payload_json AS "payloadJson" + FROM orchestration_events + ORDER BY event_id + `; + + const payloads = Object.fromEntries( + eventRows.map((row) => [row.eventId, JSON.parse(row.payloadJson)]), + ); + + assert.deepStrictEqual(payloads["event-project-created"].defaultModelSelection, { + provider: "claudeAgent", + model: "claude-opus-4-6", + options: [ + { id: "effort", value: "max" }, + { id: "fastMode", value: true }, + ], + }); + + assert.deepStrictEqual(payloads["event-project-meta-updated"].defaultModelSelection, { + provider: "codex", + model: "gpt-5.4", + options: [{ id: "reasoningEffort", value: "low" }], + }); + + assert.strictEqual(payloads["event-project-null-selection"].defaultModelSelection, null); + + assert.deepStrictEqual(payloads["event-thread-created"].modelSelection, { + provider: "claudeAgent", + model: "claude-opus-4-6", + options: [ + { id: "effort", value: "max" }, + { id: "thinking", value: false }, + ], + }); + + assert.deepStrictEqual(payloads["event-thread-meta-updated"].modelSelection, { + provider: "codex", + model: "gpt-5.4", + options: [{ id: "fastMode", value: true }], + }); + + assert.deepStrictEqual(payloads["event-thread-turn-start"].modelSelection, { + provider: "claudeAgent", + model: "claude-opus-4-6", + options: [ + { id: "effort", value: "high" }, + { id: "contextWindow", value: "1m" }, + ], + }); + + // Already-array records are left untouched. + assert.deepStrictEqual(payloads["event-thread-already-array"].modelSelection, { + provider: "codex", + model: "gpt-5.4", + options: [{ id: "reasoningEffort", value: "medium" }], + }); + + // Events with no modelSelection at all are untouched. + assert.isUndefined(payloads["event-activity-append"].modelSelection); + assert.isUndefined(payloads["event-activity-append"].defaultModelSelection); + }), + ); +}); diff --git a/apps/server/src/persistence/Migrations/026_CanonicalizeModelSelectionOptions.ts b/apps/server/src/persistence/Migrations/026_CanonicalizeModelSelectionOptions.ts new file mode 100644 index 0000000000..15c08debf6 --- /dev/null +++ b/apps/server/src/persistence/Migrations/026_CanonicalizeModelSelectionOptions.ts @@ -0,0 +1,138 @@ +import * as Effect from "effect/Effect"; +import * as SqlClient from "effect/unstable/sql/SqlClient"; + +/** + * Canonicalize `modelSelection.options` / `defaultModelSelection.options` from + * the legacy object shape (`{ effort: "max", fastMode: true, ... }`) to the + * current array-of-selections shape (`[{ id: "effort", value: "max" }, ...]`). + * + * Migration 016 introduced `modelSelection` with `options` stored as a + * per-provider object. Later the schema was reshaped so that options are a + * generic `Array<{ id, value }>` of user-selected option entries. Stored rows + * from before the reshape still have the object shape and fail to decode. + * + * For each value in the legacy object: + * - string values are kept if non-empty after trim + * - boolean values are always kept (true | false) + * - any other value type (number, null, nested object/array) is dropped, + * matching the permissive client-side normalizer in composerDraftStore. + * + * Touched storage: + * - `projection_threads.model_selection_json.options` + * - `projection_projects.default_model_selection_json.options` + * - `orchestration_events.payload_json.$.modelSelection.options` + * (thread.created | thread.meta-updated | thread.turn-start-requested) + * - `orchestration_events.payload_json.$.defaultModelSelection.options` + * (project.created | project.meta-updated) + */ +export default Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + + yield* sql` + UPDATE projection_threads + SET model_selection_json = json_set( + model_selection_json, + '$.options', + ( + SELECT json_group_array( + json_object( + 'id', key, + 'value', + CASE type + WHEN 'true' THEN json('true') + WHEN 'false' THEN json('false') + ELSE atom + END + ) + ) + FROM json_each(json_extract(model_selection_json, '$.options')) + WHERE (type = 'text' AND trim(coalesce(atom, '')) != '') + OR type IN ('true', 'false') + ) + ) + WHERE model_selection_json IS NOT NULL + AND json_type(model_selection_json, '$.options') = 'object' + `; + + yield* sql` + UPDATE projection_projects + SET default_model_selection_json = json_set( + default_model_selection_json, + '$.options', + ( + SELECT json_group_array( + json_object( + 'id', key, + 'value', + CASE type + WHEN 'true' THEN json('true') + WHEN 'false' THEN json('false') + ELSE atom + END + ) + ) + FROM json_each(json_extract(default_model_selection_json, '$.options')) + WHERE (type = 'text' AND trim(coalesce(atom, '')) != '') + OR type IN ('true', 'false') + ) + ) + WHERE default_model_selection_json IS NOT NULL + AND json_type(default_model_selection_json, '$.options') = 'object' + `; + + yield* sql` + UPDATE orchestration_events + SET payload_json = json_set( + payload_json, + '$.modelSelection.options', + ( + SELECT json_group_array( + json_object( + 'id', key, + 'value', + CASE type + WHEN 'true' THEN json('true') + WHEN 'false' THEN json('false') + ELSE atom + END + ) + ) + FROM json_each(json_extract(payload_json, '$.modelSelection.options')) + WHERE (type = 'text' AND trim(coalesce(atom, '')) != '') + OR type IN ('true', 'false') + ) + ) + WHERE event_type IN ( + 'thread.created', + 'thread.meta-updated', + 'thread.turn-start-requested' + ) + AND json_type(payload_json, '$.modelSelection.options') = 'object' + `; + + yield* sql` + UPDATE orchestration_events + SET payload_json = json_set( + payload_json, + '$.defaultModelSelection.options', + ( + SELECT json_group_array( + json_object( + 'id', key, + 'value', + CASE type + WHEN 'true' THEN json('true') + WHEN 'false' THEN json('false') + ELSE atom + END + ) + ) + FROM json_each(json_extract(payload_json, '$.defaultModelSelection.options')) + WHERE (type = 'text' AND trim(coalesce(atom, '')) != '') + OR type IN ('true', 'false') + ) + ) + WHERE event_type IN ('project.created', 'project.meta-updated') + AND json_type(payload_json, '$.defaultModelSelection.options') = 'object' + `; +}); diff --git a/apps/server/src/provider/Layers/ClaudeAdapter.test.ts b/apps/server/src/provider/Layers/ClaudeAdapter.test.ts index 79c66bdfcf..07ea11f0d6 100644 --- a/apps/server/src/provider/Layers/ClaudeAdapter.test.ts +++ b/apps/server/src/provider/Layers/ClaudeAdapter.test.ts @@ -17,6 +17,7 @@ import { type RuntimeMode, ThreadId, } from "@t3tools/contracts"; +import { createModelSelection } from "@t3tools/shared/model"; import { assert, describe, it } from "@effect/vitest"; import { Effect, Fiber, Layer, Random, Stream } from "effect"; @@ -333,13 +334,9 @@ describe("ClaudeAdapterLive", () => { yield* adapter.startSession({ threadId: THREAD_ID, provider: "claudeAgent", - modelSelection: { - provider: "claudeAgent", - model: "claude-opus-4-6", - options: { - effort: "max", - }, - }, + modelSelection: createModelSelection("claudeAgent", "claude-opus-4-6", [ + { id: "effort", value: "max" }, + ]), runtimeMode: "full-access", }); @@ -380,13 +377,9 @@ describe("ClaudeAdapterLive", () => { yield* adapter.startSession({ threadId: THREAD_ID, provider: "claudeAgent", - modelSelection: { - provider: "claudeAgent", - model: "claude-opus-4-7", - options: { - effort: "xhigh", - }, - }, + modelSelection: createModelSelection("claudeAgent", "claude-opus-4-7", [ + { id: "effort", value: "xhigh" }, + ]), runtimeMode: "full-access", }); @@ -405,13 +398,9 @@ describe("ClaudeAdapterLive", () => { yield* adapter.startSession({ threadId: THREAD_ID, provider: "claudeAgent", - modelSelection: { - provider: "claudeAgent", - model: "claude-sonnet-4-6", - options: { - effort: "max", - }, - }, + modelSelection: createModelSelection("claudeAgent", "claude-sonnet-4-6", [ + { id: "effort", value: "max" }, + ]), runtimeMode: "full-access", }); @@ -430,13 +419,9 @@ describe("ClaudeAdapterLive", () => { yield* adapter.startSession({ threadId: THREAD_ID, provider: "claudeAgent", - modelSelection: { - provider: "claudeAgent", - model: "claude-haiku-4-5", - options: { - effort: "high", - }, - }, + modelSelection: createModelSelection("claudeAgent", "claude-haiku-4-5", [ + { id: "effort", value: "high" }, + ]), runtimeMode: "full-access", }); @@ -455,13 +440,9 @@ describe("ClaudeAdapterLive", () => { yield* adapter.startSession({ threadId: THREAD_ID, provider: "claudeAgent", - modelSelection: { - provider: "claudeAgent", - model: "claude-haiku-4-5", - options: { - thinking: false, - }, - }, + modelSelection: createModelSelection("claudeAgent", "claude-haiku-4-5", [ + { id: "thinking", value: false }, + ]), runtimeMode: "full-access", }); @@ -482,13 +463,9 @@ describe("ClaudeAdapterLive", () => { yield* adapter.startSession({ threadId: THREAD_ID, provider: "claudeAgent", - modelSelection: { - provider: "claudeAgent", - model: "claude-sonnet-4-6", - options: { - thinking: false, - }, - }, + modelSelection: createModelSelection("claudeAgent", "claude-sonnet-4-6", [ + { id: "thinking", value: false }, + ]), runtimeMode: "full-access", }); @@ -507,13 +484,9 @@ describe("ClaudeAdapterLive", () => { yield* adapter.startSession({ threadId: THREAD_ID, provider: "claudeAgent", - modelSelection: { - provider: "claudeAgent", - model: "claude-opus-4-6", - options: { - fastMode: true, - }, - }, + modelSelection: createModelSelection("claudeAgent", "claude-opus-4-6", [ + { id: "fastMode", value: true }, + ]), runtimeMode: "full-access", }); @@ -534,13 +507,9 @@ describe("ClaudeAdapterLive", () => { yield* adapter.startSession({ threadId: THREAD_ID, provider: "claudeAgent", - modelSelection: { - provider: "claudeAgent", - model: "claude-sonnet-4-6", - options: { - fastMode: true, - }, - }, + modelSelection: createModelSelection("claudeAgent", "claude-sonnet-4-6", [ + { id: "fastMode", value: true }, + ]), runtimeMode: "full-access", }); @@ -559,13 +528,9 @@ describe("ClaudeAdapterLive", () => { const session = yield* adapter.startSession({ threadId: THREAD_ID, provider: "claudeAgent", - modelSelection: { - provider: "claudeAgent", - model: "claude-sonnet-4-6", - options: { - effort: "ultrathink", - }, - }, + modelSelection: createModelSelection("claudeAgent", "claude-sonnet-4-6", [ + { id: "effort", value: "ultrathink" }, + ]), runtimeMode: "full-access", }); @@ -573,13 +538,9 @@ describe("ClaudeAdapterLive", () => { threadId: session.threadId, input: "Investigate the edge cases", attachments: [], - modelSelection: { - provider: "claudeAgent", - model: "claude-sonnet-4-6", - options: { - effort: "ultrathink", - }, - }, + modelSelection: createModelSelection("claudeAgent", "claude-sonnet-4-6", [ + { id: "effort", value: "ultrathink" }, + ]), }); const createInput = harness.getLastCreateQueryInput(); @@ -2794,13 +2755,9 @@ describe("ClaudeAdapterLive", () => { yield* adapter.sendTurn({ threadId: session.threadId, input: "hello", - modelSelection: { - provider: "claudeAgent", - model: "claude-opus-4-6", - options: { - contextWindow: "1m", - }, - }, + modelSelection: createModelSelection("claudeAgent", "claude-opus-4-6", [ + { id: "contextWindow", value: "1m" }, + ]), attachments: [], }); yield* adapter.sendTurn({ diff --git a/apps/server/src/provider/Layers/ClaudeAdapter.ts b/apps/server/src/provider/Layers/ClaudeAdapter.ts index 81980acb9b..03dfffa042 100644 --- a/apps/server/src/provider/Layers/ClaudeAdapter.ts +++ b/apps/server/src/provider/Layers/ClaudeAdapter.ts @@ -40,9 +40,14 @@ import { ThreadId, TurnId, type UserInputQuestion, - ClaudeAgentEffort, } from "@t3tools/contracts"; -import { applyClaudePromptEffortPrefix, resolveEffort, trimOrNull } from "@t3tools/shared/model"; +import { + applyClaudePromptEffortPrefix, + getModelSelectionBooleanOptionValue, + getModelSelectionStringOptionValue, + getProviderOptionDescriptors, + resolvePromptInjectedEffort, +} from "@t3tools/shared/model"; import { Cause, DateTime, @@ -61,7 +66,12 @@ import { import { resolveAttachmentPath } from "../../attachmentStore.ts"; import { ServerConfig } from "../../config.ts"; import { ServerSettingsService } from "../../serverSettings.ts"; -import { getClaudeModelCapabilities, resolveClaudeApiModelId } from "./ClaudeProvider.ts"; +import { + getClaudeModelCapabilities, + normalizeClaudeCliEffort, + resolveClaudeApiModelId, + resolveClaudeEffort, +} from "./ClaudeProvider.ts"; import { ProviderAdapterProcessError, ProviderAdapterRequestError, @@ -211,19 +221,9 @@ function normalizeClaudeStreamMessages(cause: Cause.Cause): ReadonlyArray return squashed.length > 0 ? [squashed] : []; } -function getEffectiveClaudeAgentEffort( - effort: ClaudeAgentEffort | null | undefined, -): ClaudeSdkEffort | null { - if (!effort) { - return null; - } - if (effort === "ultrathink") { - return null; - } - if (effort === "xhigh") { - return "max"; - } - return effort; +function getEffectiveClaudeAgentEffort(effort: string | null | undefined): ClaudeSdkEffort | null { + const normalized = normalizeClaudeCliEffort(effort); + return normalized ? (normalized as ClaudeSdkEffort) : null; } function isClaudeInterruptedMessage(message: string): boolean { @@ -555,16 +555,14 @@ const CLAUDE_SETTING_SOURCES = [ function buildPromptText(input: ProviderSendTurnInput): string { const rawEffort = - input.modelSelection?.provider === "claudeAgent" ? input.modelSelection.options?.effort : null; + input.modelSelection?.provider === "claudeAgent" + ? getModelSelectionStringOptionValue(input.modelSelection, "effort") + : null; const claudeModel = input.modelSelection?.provider === "claudeAgent" ? input.modelSelection.model : undefined; const caps = getClaudeModelCapabilities(claudeModel); - // For prompt injection, we check if the raw effort is a prompt-injected level (e.g. "ultrathink"). - // resolveEffort strips prompt-injected values (returning the default instead), so we check the raw value directly. - const trimmedEffort = trimOrNull(rawEffort); - const promptEffort = - trimmedEffort && caps.promptInjectedEffortLevels.includes(trimmedEffort) ? trimmedEffort : null; + const promptEffort = resolvePromptInjectedEffort(caps, rawEffort); return applyClaudePromptEffortPrefix(input.input?.trim() ?? "", promptEffort); } @@ -2824,14 +2822,22 @@ const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* ( const modelSelection = input.modelSelection?.provider === "claudeAgent" ? input.modelSelection : undefined; const caps = getClaudeModelCapabilities(modelSelection?.model); + const descriptors = getProviderOptionDescriptors({ caps }); const apiModelId = modelSelection ? resolveClaudeApiModelId(modelSelection) : undefined; - const effort = (resolveEffort(caps, modelSelection?.options?.effort) ?? - null) as ClaudeAgentEffort | null; - const fastMode = modelSelection?.options?.fastMode === true && caps.supportsFastMode; - const thinking = - typeof modelSelection?.options?.thinking === "boolean" && caps.supportsThinkingToggle - ? modelSelection.options.thinking - : undefined; + const rawEffort = getModelSelectionStringOptionValue(modelSelection, "effort"); + const effort = resolveClaudeEffort(caps, rawEffort) ?? null; + const fastModeSupported = descriptors.some( + (descriptor) => descriptor.type === "boolean" && descriptor.id === "fastMode", + ); + const thinkingSupported = descriptors.some( + (descriptor) => descriptor.type === "boolean" && descriptor.id === "thinking", + ); + const fastMode = + getModelSelectionBooleanOptionValue(modelSelection, "fastMode") === true && + fastModeSupported; + const thinking = thinkingSupported + ? getModelSelectionBooleanOptionValue(modelSelection, "thinking") + : undefined; const effectiveEffort = getEffectiveClaudeAgentEffort(effort); const runtimeModeToPermission: Record = { "auto-accept-edits": "acceptEdits", diff --git a/apps/server/src/provider/Layers/ClaudeProvider.ts b/apps/server/src/provider/Layers/ClaudeProvider.ts index 60836210b5..f41082bbba 100644 --- a/apps/server/src/provider/Layers/ClaudeProvider.ts +++ b/apps/server/src/provider/Layers/ClaudeProvider.ts @@ -11,6 +11,12 @@ import type { import { Cache, Duration, Effect, Equal, Layer, Option, Result, Schema, Stream } from "effect"; import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process"; import { decodeJsonResult } from "@t3tools/shared/schemaJson"; +import { + createModelCapabilities, + getModelSelectionStringOptionValue, + getProviderOptionCurrentValue, + getProviderOptionDescriptors, +} from "@t3tools/shared/model"; import { query as claudeQuery, type SlashCommand as ClaudeSlashCommand, @@ -18,6 +24,8 @@ import { } from "@anthropic-ai/claude-agent-sdk"; import { + buildBooleanOptionDescriptor, + buildSelectOptionDescriptor, buildServerProvider, AUTH_PROBE_TIMEOUT_MS, DEFAULT_TIMEOUT_MS, @@ -35,108 +43,143 @@ import { ClaudeProvider } from "../Services/ClaudeProvider.ts"; import { ServerSettingsService } from "../../serverSettings.ts"; import { ServerSettingsError } from "@t3tools/contracts"; -const DEFAULT_CLAUDE_MODEL_CAPABILITIES: ModelCapabilities = { - reasoningEffortLevels: [], - supportsFastMode: false, - supportsThinkingToggle: false, - contextWindowOptions: [], - promptInjectedEffortLevels: [], -}; +const DEFAULT_CLAUDE_MODEL_CAPABILITIES: ModelCapabilities = createModelCapabilities({ + optionDescriptors: [], +}); const PROVIDER = "claudeAgent" as const; +const CLAUDE_PRESENTATION = { + displayName: "Claude", + showInteractionModeToggle: true, +} as const; const MINIMUM_CLAUDE_OPUS_4_7_VERSION = "2.1.111"; const BUILT_IN_MODELS: ReadonlyArray = [ { slug: "claude-opus-4-7", name: "Claude Opus 4.7", isCustom: false, - capabilities: { - reasoningEffortLevels: [ - { value: "low", label: "Low" }, - { value: "medium", label: "Medium" }, - { value: "high", label: "High" }, - { value: "xhigh", label: "Extra High", isDefault: true }, - { value: "max", label: "Max" }, - { value: "ultrathink", label: "Ultrathink" }, + capabilities: createModelCapabilities({ + optionDescriptors: [ + buildSelectOptionDescriptor({ + id: "effort", + label: "Reasoning", + options: [ + { value: "low", label: "Low" }, + { value: "medium", label: "Medium" }, + { value: "high", label: "High" }, + { value: "xhigh", label: "Extra High", isDefault: true }, + { value: "max", label: "Max" }, + { value: "ultrathink", label: "Ultrathink" }, + ], + promptInjectedValues: ["ultrathink"], + }), + buildSelectOptionDescriptor({ + id: "contextWindow", + label: "Context Window", + options: [ + { value: "200k", label: "200k", isDefault: true }, + { value: "1m", label: "1M" }, + ], + }), ], - supportsFastMode: false, - supportsThinkingToggle: false, - contextWindowOptions: [ - { value: "200k", label: "200k", isDefault: true }, - { value: "1m", label: "1M" }, - ], - promptInjectedEffortLevels: ["ultrathink"], - } satisfies ModelCapabilities, + }), }, { slug: "claude-opus-4-6", name: "Claude Opus 4.6", isCustom: false, - capabilities: { - reasoningEffortLevels: [ - { value: "low", label: "Low" }, - { value: "medium", label: "Medium" }, - { value: "high", label: "High", isDefault: true }, - { value: "max", label: "Max" }, - { value: "ultrathink", label: "Ultrathink" }, + capabilities: createModelCapabilities({ + optionDescriptors: [ + buildSelectOptionDescriptor({ + id: "effort", + label: "Reasoning", + options: [ + { value: "low", label: "Low" }, + { value: "medium", label: "Medium" }, + { value: "high", label: "High", isDefault: true }, + { value: "max", label: "Max" }, + { value: "ultrathink", label: "Ultrathink" }, + ], + promptInjectedValues: ["ultrathink"], + }), + buildBooleanOptionDescriptor({ + id: "fastMode", + label: "Fast Mode", + }), + buildSelectOptionDescriptor({ + id: "contextWindow", + label: "Context Window", + options: [ + { value: "200k", label: "200k", isDefault: true }, + { value: "1m", label: "1M" }, + ], + }), ], - supportsFastMode: true, - supportsThinkingToggle: false, - contextWindowOptions: [ - { value: "200k", label: "200k", isDefault: true }, - { value: "1m", label: "1M" }, - ], - promptInjectedEffortLevels: ["ultrathink"], - } satisfies ModelCapabilities, + }), }, { slug: "claude-opus-4-5", name: "Claude Opus 4.5", isCustom: false, - capabilities: { - reasoningEffortLevels: [ - { value: "low", label: "Low" }, - { value: "medium", label: "Medium" }, - { value: "high", label: "High", isDefault: true }, - { value: "max", label: "Max" }, + capabilities: createModelCapabilities({ + optionDescriptors: [ + buildSelectOptionDescriptor({ + id: "effort", + label: "Reasoning", + options: [ + { value: "low", label: "Low" }, + { value: "medium", label: "Medium" }, + { value: "high", label: "High", isDefault: true }, + { value: "max", label: "Max" }, + ], + }), + buildBooleanOptionDescriptor({ + id: "fastMode", + label: "Fast Mode", + }), ], - supportsFastMode: true, - supportsThinkingToggle: false, - contextWindowOptions: [], - promptInjectedEffortLevels: [], - } satisfies ModelCapabilities, + }), }, { slug: "claude-sonnet-4-6", name: "Claude Sonnet 4.6", isCustom: false, - capabilities: { - reasoningEffortLevels: [ - { value: "low", label: "Low" }, - { value: "medium", label: "Medium" }, - { value: "high", label: "High", isDefault: true }, - { value: "ultrathink", label: "Ultrathink" }, + capabilities: createModelCapabilities({ + optionDescriptors: [ + buildSelectOptionDescriptor({ + id: "effort", + label: "Reasoning", + options: [ + { value: "low", label: "Low" }, + { value: "medium", label: "Medium" }, + { value: "high", label: "High", isDefault: true }, + { value: "ultrathink", label: "Ultrathink" }, + ], + promptInjectedValues: ["ultrathink"], + }), + buildSelectOptionDescriptor({ + id: "contextWindow", + label: "Context Window", + options: [ + { value: "200k", label: "200k", isDefault: true }, + { value: "1m", label: "1M" }, + ], + }), ], - supportsFastMode: false, - supportsThinkingToggle: false, - contextWindowOptions: [ - { value: "200k", label: "200k", isDefault: true }, - { value: "1m", label: "1M" }, - ], - promptInjectedEffortLevels: ["ultrathink"], - } satisfies ModelCapabilities, + }), }, { slug: "claude-haiku-4-5", name: "Claude Haiku 4.5", isCustom: false, - capabilities: { - reasoningEffortLevels: [], - supportsFastMode: false, - supportsThinkingToggle: true, - contextWindowOptions: [], - promptInjectedEffortLevels: [], - } satisfies ModelCapabilities, + capabilities: createModelCapabilities({ + optionDescriptors: [ + buildBooleanOptionDescriptor({ + id: "thinking", + label: "Thinking", + }), + ], + }), }, ]; @@ -166,8 +209,41 @@ export function getClaudeModelCapabilities(model: string | null | undefined): Mo ); } +export function resolveClaudeEffort( + caps: ModelCapabilities, + raw: string | null | undefined, +): string | undefined { + const descriptors = getProviderOptionDescriptors({ + caps, + ...(raw ? { selections: [{ id: "effort", value: raw }] } : {}), + }); + const effortDescriptor = descriptors.find((descriptor) => descriptor.id === "effort"); + const value = getProviderOptionCurrentValue(effortDescriptor); + return typeof value === "string" ? value : undefined; +} + +/** + * Normalize a resolved Claude effort value into one suitable for the Claude + * CLI's `--effort` flag. + * + * Mirrors the mapping used when invoking the Claude Agent SDK + * ({@link getEffectiveClaudeAgentEffort} in ClaudeAdapter): the Opus 4.7 + * capability `"xhigh"` is rewritten to the accepted CLI value `"max"`, and + * `"ultrathink"` is filtered out because it is a prompt-prefix mode rather + * than a CLI-effort value. Returns `undefined` when no flag should be passed. + */ +export function normalizeClaudeCliEffort(effort: string | null | undefined): string | undefined { + if (!effort || effort === "ultrathink") { + return undefined; + } + if (effort === "xhigh") { + return "max"; + } + return effort; +} + export function resolveClaudeApiModelId(modelSelection: ClaudeModelSelection): string { - switch (modelSelection.options?.contextWindow) { + switch (getModelSelectionStringOptionValue(modelSelection, "contextWindow")) { case "1m": return `${modelSelection.model}[1m]`; default: @@ -579,6 +655,7 @@ export const checkClaudeProviderStatus = Effect.fn("checkClaudeProviderStatus")( if (!claudeSettings.enabled) { return buildServerProvider({ provider: PROVIDER, + presentation: CLAUDE_PRESENTATION, enabled: false, checkedAt, models: allModels, @@ -601,6 +678,7 @@ export const checkClaudeProviderStatus = Effect.fn("checkClaudeProviderStatus")( const error = versionProbe.failure; return buildServerProvider({ provider: PROVIDER, + presentation: CLAUDE_PRESENTATION, enabled: claudeSettings.enabled, checkedAt, models: allModels, @@ -619,6 +697,7 @@ export const checkClaudeProviderStatus = Effect.fn("checkClaudeProviderStatus")( if (Option.isNone(versionProbe.success)) { return buildServerProvider({ provider: PROVIDER, + presentation: CLAUDE_PRESENTATION, enabled: claudeSettings.enabled, checkedAt, models: allModels, @@ -639,6 +718,7 @@ export const checkClaudeProviderStatus = Effect.fn("checkClaudeProviderStatus")( const detail = detailFromResult(version); return buildServerProvider({ provider: PROVIDER, + presentation: CLAUDE_PRESENTATION, enabled: claudeSettings.enabled, checkedAt, models: allModels, @@ -703,6 +783,7 @@ export const checkClaudeProviderStatus = Effect.fn("checkClaudeProviderStatus")( const error = authProbe.failure; return buildServerProvider({ provider: PROVIDER, + presentation: CLAUDE_PRESENTATION, enabled: claudeSettings.enabled, checkedAt, models, @@ -723,6 +804,7 @@ export const checkClaudeProviderStatus = Effect.fn("checkClaudeProviderStatus")( if (Option.isNone(authProbe.success)) { return buildServerProvider({ provider: PROVIDER, + presentation: CLAUDE_PRESENTATION, enabled: claudeSettings.enabled, checkedAt, models, @@ -741,6 +823,7 @@ export const checkClaudeProviderStatus = Effect.fn("checkClaudeProviderStatus")( const authMetadata = claudeAuthMetadata({ subscriptionType, authMethod }); return buildServerProvider({ provider: PROVIDER, + presentation: CLAUDE_PRESENTATION, enabled: claudeSettings.enabled, checkedAt, models, @@ -774,6 +857,7 @@ const makePendingClaudeProvider = (claudeSettings: ClaudeSettings): ServerProvid if (!claudeSettings.enabled) { return buildServerProvider({ provider: PROVIDER, + presentation: CLAUDE_PRESENTATION, enabled: false, checkedAt, models, @@ -789,6 +873,7 @@ const makePendingClaudeProvider = (claudeSettings: ClaudeSettings): ServerProvid return buildServerProvider({ provider: PROVIDER, + presentation: CLAUDE_PRESENTATION, enabled: true, checkedAt, models, diff --git a/apps/server/src/provider/Layers/CodexAdapter.test.ts b/apps/server/src/provider/Layers/CodexAdapter.test.ts index 03d4155934..ad6fddab1c 100644 --- a/apps/server/src/provider/Layers/CodexAdapter.test.ts +++ b/apps/server/src/provider/Layers/CodexAdapter.test.ts @@ -14,6 +14,7 @@ import { ThreadId, TurnId, } from "@t3tools/contracts"; +import { createModelSelection } from "@t3tools/shared/model"; import * as NodeServices from "@effect/platform-node/NodeServices"; import { it, vi } from "@effect/vitest"; @@ -242,13 +243,9 @@ validationLayer("CodexAdapterLive validation", (it) => { yield* adapter.startSession({ provider: "codex", threadId: asThreadId("thread-1"), - modelSelection: { - provider: "codex", - model: "gpt-5.3-codex", - options: { - fastMode: true, - }, - }, + modelSelection: createModelSelection("codex", "gpt-5.3-codex", [ + { id: "fastMode", value: true }, + ]), runtimeMode: "full-access", }); @@ -309,14 +306,10 @@ sessionErrorLayer("CodexAdapterLive session errors", (it) => { adapter.sendTurn({ threadId: asThreadId("sess-missing"), input: "hello", - modelSelection: { - provider: "codex", - model: "gpt-5.3-codex", - options: { - reasoningEffort: "high", - fastMode: true, - }, - }, + modelSelection: createModelSelection("codex", "gpt-5.3-codex", [ + { id: "reasoningEffort", value: "high" }, + { id: "fastMode", value: true }, + ]), attachments: [], }), ); diff --git a/apps/server/src/provider/Layers/CodexAdapter.ts b/apps/server/src/provider/Layers/CodexAdapter.ts index 0111cd013c..5c824dc730 100644 --- a/apps/server/src/provider/Layers/CodexAdapter.ts +++ b/apps/server/src/provider/Layers/CodexAdapter.ts @@ -26,6 +26,11 @@ import { ChildProcessSpawner } from "effect/unstable/process"; import * as CodexErrors from "effect-codex-app-server/errors"; import * as EffectCodexSchema from "effect-codex-app-server/schema"; +import { + getModelSelectionBooleanOptionValue, + getModelSelectionStringOptionValue, +} from "@t3tools/shared/model"; + import { ProviderAdapterRequestError, ProviderAdapterProcessError, @@ -1372,7 +1377,8 @@ const makeCodexAdapter = Effect.fn("makeCodexAdapter")(function* ( ...(input.modelSelection?.provider === "codex" ? { model: input.modelSelection.model } : {}), - ...(input.modelSelection?.provider === "codex" && input.modelSelection.options?.fastMode + ...(input.modelSelection?.provider === "codex" && + getModelSelectionBooleanOptionValue(input.modelSelection, "fastMode") === true ? { serviceTier: "fast" } : {}), }; @@ -1485,19 +1491,26 @@ const makeCodexAdapter = Effect.fn("makeCodexAdapter")(function* ( ); const session = yield* requireSession(input.threadId); + const reasoningEffort = + input.modelSelection?.provider === "codex" + ? getModelSelectionStringOptionValue(input.modelSelection, "reasoningEffort") + : undefined; + const fastMode = + input.modelSelection?.provider === "codex" + ? getModelSelectionBooleanOptionValue(input.modelSelection, "fastMode") + : undefined; return yield* session.runtime .sendTurn({ ...(input.input !== undefined ? { input: input.input } : {}), ...(input.modelSelection?.provider === "codex" ? { model: input.modelSelection.model } : {}), - ...(input.modelSelection?.provider === "codex" && - input.modelSelection.options?.reasoningEffort !== undefined - ? { effort: input.modelSelection.options.reasoningEffort } - : {}), - ...(input.modelSelection?.provider === "codex" && input.modelSelection.options?.fastMode - ? { serviceTier: "fast" } + ...(reasoningEffort + ? { + effort: reasoningEffort as EffectCodexSchema.V2TurnStartParams__ReasoningEffort, + } : {}), + ...(fastMode === true ? { serviceTier: "fast" } : {}), ...(input.interactionMode !== undefined ? { interactionMode: input.interactionMode } : {}), ...(codexAttachments.length > 0 ? { attachments: codexAttachments } : {}), }) diff --git a/apps/server/src/provider/Layers/CodexProvider.ts b/apps/server/src/provider/Layers/CodexProvider.ts index 1e48847c52..915609ca21 100644 --- a/apps/server/src/provider/Layers/CodexProvider.ts +++ b/apps/server/src/provider/Layers/CodexProvider.ts @@ -25,6 +25,8 @@ import type { } from "@t3tools/contracts"; import { ServerSettingsError } from "@t3tools/contracts"; +import { createModelCapabilities } from "@t3tools/shared/model"; + import { makeManagedServerProvider } from "../makeManagedServerProvider.ts"; import { buildServerProvider } from "../providerSnapshot.ts"; import { CodexProvider } from "../Services/CodexProvider.ts"; @@ -34,6 +36,10 @@ import packageJson from "../../../package.json" with { type: "json" }; const PROVIDER = "codex" as const; const PROVIDER_PROBE_TIMEOUT_MS = 8_000; +const CODEX_PRESENTATION = { + displayName: "Codex", + showInteractionModeToggle: true, +} as const; export interface CodexAppServerProviderSnapshot { readonly account: CodexSchema.V2GetAccountResponse; @@ -87,17 +93,44 @@ function codexAccountAuthLabel(account: CodexSchema.V2GetAccountResponse["accoun function mapCodexModelCapabilities( model: CodexSchema.V2ModelListResponse__Model, ): ModelCapabilities { - return { - reasoningEffortLevels: model.supportedReasoningEfforts.map(({ reasoningEffort }) => ({ - value: reasoningEffort, - label: REASONING_EFFORT_LABELS[reasoningEffort], - ...(reasoningEffort === model.defaultReasoningEffort ? { isDefault: true } : {}), - })), - supportsFastMode: (model.additionalSpeedTiers ?? []).includes("fast"), - supportsThinkingToggle: false, - contextWindowOptions: [], - promptInjectedEffortLevels: [], - }; + const reasoningOptions = model.supportedReasoningEfforts.map(({ reasoningEffort }) => + reasoningEffort === model.defaultReasoningEffort + ? { + id: reasoningEffort, + label: REASONING_EFFORT_LABELS[reasoningEffort], + isDefault: true, + } + : { + id: reasoningEffort, + label: REASONING_EFFORT_LABELS[reasoningEffort], + }, + ); + const defaultReasoning = reasoningOptions.find((option) => option.isDefault)?.id; + const supportsFastMode = (model.additionalSpeedTiers ?? []).includes("fast"); + return createModelCapabilities({ + optionDescriptors: [ + ...(reasoningOptions.length > 0 + ? [ + { + id: "reasoningEffort", + label: "Reasoning", + type: "select" as const, + options: reasoningOptions, + ...(defaultReasoning ? { currentValue: defaultReasoning } : {}), + }, + ] + : []), + ...(supportsFastMode + ? [ + { + id: "fastMode", + label: "Fast Mode", + type: "boolean" as const, + }, + ] + : []), + ], + }); } const toDisplayName = (model: CodexSchema.V2ModelListResponse__Model): string => { @@ -292,6 +325,7 @@ const makePendingCodexProvider = (codexSettings: CodexSettings): ServerProvider if (!codexSettings.enabled) { return buildServerProvider({ provider: PROVIDER, + presentation: CODEX_PRESENTATION, enabled: false, checkedAt, models, @@ -308,6 +342,7 @@ const makePendingCodexProvider = (codexSettings: CodexSettings): ServerProvider return buildServerProvider({ provider: PROVIDER, + presentation: CODEX_PRESENTATION, enabled: true, checkedAt, models, @@ -375,6 +410,7 @@ export const checkCodexProviderStatus = Effect.fn("checkCodexProviderStatus")(fu if (!codexSettings.enabled) { return buildServerProvider({ provider: PROVIDER, + presentation: CODEX_PRESENTATION, enabled: false, checkedAt, models: emptyModels, @@ -401,6 +437,7 @@ export const checkCodexProviderStatus = Effect.fn("checkCodexProviderStatus")(fu const installed = !Schema.is(CodexErrors.CodexAppServerSpawnError)(error); return buildServerProvider({ provider: PROVIDER, + presentation: CODEX_PRESENTATION, enabled: codexSettings.enabled, checkedAt, models: emptyModels, @@ -420,6 +457,7 @@ export const checkCodexProviderStatus = Effect.fn("checkCodexProviderStatus")(fu if (Option.isNone(probeResult.success)) { return buildServerProvider({ provider: PROVIDER, + presentation: CODEX_PRESENTATION, enabled: codexSettings.enabled, checkedAt, models: emptyModels, @@ -439,6 +477,7 @@ export const checkCodexProviderStatus = Effect.fn("checkCodexProviderStatus")(fu return buildServerProvider({ provider: PROVIDER, + presentation: CODEX_PRESENTATION, enabled: codexSettings.enabled, checkedAt, models: snapshot.models, diff --git a/apps/server/src/provider/Layers/CursorAdapter.test.ts b/apps/server/src/provider/Layers/CursorAdapter.test.ts index e6bbd7569a..1f619d49f1 100644 --- a/apps/server/src/provider/Layers/CursorAdapter.test.ts +++ b/apps/server/src/provider/Layers/CursorAdapter.test.ts @@ -6,6 +6,7 @@ import { fileURLToPath } from "node:url"; import * as NodeServices from "@effect/platform-node/NodeServices"; import { assert, it } from "@effect/vitest"; import { Deferred, Effect, Fiber, Layer, Stream } from "effect"; +import { createModelSelection } from "@t3tools/shared/model"; import { ApprovalRequestId, type ProviderRuntimeEvent, ThreadId } from "@t3tools/contracts"; @@ -357,15 +358,11 @@ cursorAdapterTestLayer("CursorAdapterLive", (it) => { providers: { cursor: { binaryPath: wrapperPath } }, }); - const modelSelection = { - provider: "cursor" as const, - model: "gpt-5.4", - options: { - reasoning: "xhigh" as const, - contextWindow: "1m", - fastMode: true, - }, - }; + const modelSelection = createModelSelection("cursor", "gpt-5.4", [ + { id: "reasoning", value: "xhigh" }, + { id: "contextWindow", value: "1m" }, + { id: "fastMode", value: true }, + ]); yield* adapter.startSession({ threadId, @@ -1092,7 +1089,9 @@ cursorAdapterTestLayer("CursorAdapterLive", (it) => { threadId, input: "second turn after switching model", attachments: [], - modelSelection: { provider: "cursor", model: "composer-2", options: { fastMode: true } }, + modelSelection: createModelSelection("cursor", "composer-2", [ + { id: "fastMode", value: true }, + ]), }); const argvRuns = yield* Effect.promise(() => readArgvLog(argvLogPath)); @@ -1147,14 +1146,18 @@ cursorAdapterTestLayer("CursorAdapterLive", (it) => { threadId, input: "first turn with fast mode", attachments: [], - modelSelection: { provider: "cursor", model: "composer-2", options: { fastMode: true } }, + modelSelection: createModelSelection("cursor", "composer-2", [ + { id: "fastMode", value: true }, + ]), }); yield* adapter.sendTurn({ threadId, input: "second turn without fast mode", attachments: [], - modelSelection: { provider: "cursor", model: "composer-2", options: { fastMode: false } }, + modelSelection: createModelSelection("cursor", "composer-2", [ + { id: "fastMode", value: false }, + ]), }); const requests = yield* Effect.promise(() => readJsonLines(requestLogPath)); diff --git a/apps/server/src/provider/Layers/CursorAdapter.ts b/apps/server/src/provider/Layers/CursorAdapter.ts index b09e0356bf..5e12bfbefe 100644 --- a/apps/server/src/provider/Layers/CursorAdapter.ts +++ b/apps/server/src/provider/Layers/CursorAdapter.ts @@ -7,7 +7,7 @@ import * as nodePath from "node:path"; import { ApprovalRequestId, - type CursorModelOptions, + type ProviderOptionSelection, EventId, type ProviderApprovalDecision, type ProviderInteractionMode, @@ -222,7 +222,7 @@ function applyRequestedSessionConfiguration(input: { readonly modelSelection: | { readonly model: string; - readonly options?: CursorModelOptions | null | undefined; + readonly options?: ReadonlyArray | null | undefined; } | undefined; readonly mapError: (context: { @@ -235,7 +235,7 @@ function applyRequestedSessionConfiguration(input: { yield* applyCursorAcpModelSelection({ runtime: input.runtime, model: input.modelSelection.model, - modelOptions: input.modelSelection.options, + selections: input.modelSelection.options, mapError: ({ cause }) => input.mapError({ cause, diff --git a/apps/server/src/provider/Layers/CursorProvider.test.ts b/apps/server/src/provider/Layers/CursorProvider.test.ts index be90e3c856..c0ac5d20b0 100644 --- a/apps/server/src/provider/Layers/CursorProvider.test.ts +++ b/apps/server/src/provider/Layers/CursorProvider.test.ts @@ -8,6 +8,7 @@ import { Effect } from "effect"; import { describe, expect, it } from "vitest"; import type * as EffectAcpSchema from "effect-acp/schema"; import type { CursorSettings, ServerProviderModel } from "@t3tools/contracts"; +import { createModelCapabilities } from "@t3tools/shared/model"; import { buildCursorProviderSnapshot, @@ -27,6 +28,31 @@ import { const __dirname = path.dirname(fileURLToPath(import.meta.url)); const mockAgentPath = path.join(__dirname, "../../../scripts/acp-mock-agent.ts"); +function selectDescriptor( + id: string, + label: string, + options: ReadonlyArray<{ id: string; label: string; isDefault?: boolean }>, +) { + return { + id, + label, + type: "select" as const, + options: [...options], + ...(options.find((option) => option.isDefault)?.id + ? { currentValue: options.find((option) => option.isDefault)?.id } + : {}), + }; +} + +function booleanDescriptor(id: string, label: string, currentValue?: boolean) { + return { + id, + label, + type: "boolean" as const, + ...(typeof currentValue === "boolean" ? { currentValue } : {}), + }; +} + async function makeMockAgentWrapper(extraEnv?: Record) { const dir = await mkdtemp(path.join(os.tmpdir(), "cursor-provider-mock-")); const wrapperPath = path.join(dir, "fake-agent.sh"); @@ -239,13 +265,7 @@ const baseCursorSettings: CursorSettings = { customModels: [], }; -const emptyCapabilities = { - reasoningEffortLevels: [], - supportsFastMode: false, - supportsThinkingToggle: false, - contextWindowOptions: [], - promptInjectedEffortLevels: [], -} as const; +const emptyCapabilities = createModelCapabilities({ optionDescriptors: [] }); describe("getCursorFallbackModels", () => { it("does not publish any built-in cursor models before ACP discovery", () => { @@ -309,52 +329,57 @@ describe("buildCursorProviderSnapshot", () => { describe("buildCursorCapabilitiesFromConfigOptions", () => { it("derives model capabilities from parameterized Cursor ACP config options", () => { - expect(buildCursorCapabilitiesFromConfigOptions(parameterizedGpt54ConfigOptions)).toEqual({ - reasoningEffortLevels: [ - { value: "low", label: "Low" }, - { value: "medium", label: "Medium", isDefault: true }, - { value: "high", label: "High" }, - { value: "xhigh", label: "Extra High" }, - ], - supportsFastMode: true, - supportsThinkingToggle: false, - contextWindowOptions: [ - { value: "272k", label: "272K", isDefault: true }, - { value: "1m", label: "1M" }, - ], - promptInjectedEffortLevels: [], - }); + expect(buildCursorCapabilitiesFromConfigOptions(parameterizedGpt54ConfigOptions)).toEqual( + createModelCapabilities({ + optionDescriptors: [ + selectDescriptor("reasoning", "Reasoning", [ + { id: "low", label: "Low" }, + { id: "medium", label: "Medium", isDefault: true }, + { id: "high", label: "High" }, + { id: "xhigh", label: "Extra High" }, + ]), + selectDescriptor("contextWindow", "Context", [ + { id: "272k", label: "272K", isDefault: true }, + { id: "1m", label: "1M" }, + ]), + booleanDescriptor("fastMode", "Fast", false), + ], + }), + ); }); it("detects boolean thinking toggles from model_config options", () => { - expect(buildCursorCapabilitiesFromConfigOptions(parameterizedClaudeConfigOptions)).toEqual({ - reasoningEffortLevels: [ - { value: "low", label: "Low" }, - { value: "medium", label: "Medium" }, - { value: "high", label: "High", isDefault: true }, - ], - supportsFastMode: false, - supportsThinkingToggle: true, - contextWindowOptions: [], - promptInjectedEffortLevels: [], - }); + expect(buildCursorCapabilitiesFromConfigOptions(parameterizedClaudeConfigOptions)).toEqual( + createModelCapabilities({ + optionDescriptors: [ + selectDescriptor("reasoning", "Reasoning", [ + { id: "low", label: "Low" }, + { id: "medium", label: "Medium" }, + { id: "high", label: "High", isDefault: true }, + ]), + booleanDescriptor("thinking", "Thinking", true), + ], + }), + ); }); it("prefers the newer model_option effort control over legacy thought_level", () => { expect( buildCursorCapabilitiesFromConfigOptions(parameterizedClaudeModelOptionConfigOptions), - ).toEqual({ - reasoningEffortLevels: [ - { value: "low", label: "Low" }, - { value: "medium", label: "Medium" }, - { value: "high", label: "High" }, - { value: "max", label: "Max", isDefault: true }, - ], - supportsFastMode: true, - supportsThinkingToggle: true, - contextWindowOptions: [], - promptInjectedEffortLevels: [], - }); + ).toEqual( + createModelCapabilities({ + optionDescriptors: [ + selectDescriptor("reasoning", "Effort", [ + { id: "low", label: "Low" }, + { id: "medium", label: "Medium" }, + { id: "high", label: "High" }, + { id: "max", label: "Max", isDefault: true }, + ]), + booleanDescriptor("fastMode", "Fast", true), + booleanDescriptor("thinking", "Thinking", true), + ], + }), + ); }); }); @@ -365,73 +390,39 @@ describe("buildCursorDiscoveredModelsFromConfigOptions", () => { slug: "default", name: "Auto", isCustom: false, - capabilities: { - reasoningEffortLevels: [], - supportsFastMode: false, - supportsThinkingToggle: false, - contextWindowOptions: [], - promptInjectedEffortLevels: [], - }, + capabilities: emptyCapabilities, }, { slug: "composer-2", name: "Composer 2", isCustom: false, - capabilities: { - reasoningEffortLevels: [], - supportsFastMode: true, - supportsThinkingToggle: false, - contextWindowOptions: [], - promptInjectedEffortLevels: [], - }, + capabilities: createModelCapabilities({ + optionDescriptors: [booleanDescriptor("fastMode", "Fast", true)], + }), }, { slug: "gpt-5.4", name: "GPT-5.4", isCustom: false, - capabilities: { - reasoningEffortLevels: [], - supportsFastMode: false, - supportsThinkingToggle: false, - contextWindowOptions: [], - promptInjectedEffortLevels: [], - }, + capabilities: emptyCapabilities, }, { slug: "claude-sonnet-4-6", name: "Sonnet 4.6", isCustom: false, - capabilities: { - reasoningEffortLevels: [], - supportsFastMode: false, - supportsThinkingToggle: false, - contextWindowOptions: [], - promptInjectedEffortLevels: [], - }, + capabilities: emptyCapabilities, }, { slug: "claude-opus-4-6", name: "Opus 4.6", isCustom: false, - capabilities: { - reasoningEffortLevels: [], - supportsFastMode: false, - supportsThinkingToggle: false, - contextWindowOptions: [], - promptInjectedEffortLevels: [], - }, + capabilities: emptyCapabilities, }, { slug: "gpt-5.3-codex-spark", name: "Codex 5.3 Spark", isCustom: false, - capabilities: { - reasoningEffortLevels: [], - supportsFastMode: false, - supportsThinkingToggle: false, - contextWindowOptions: [], - promptInjectedEffortLevels: [], - }, + capabilities: emptyCapabilities, }, ]); }); @@ -645,11 +636,11 @@ describe("resolveCursorAcpBaseModelId", () => { describe("resolveCursorAcpConfigUpdates", () => { it("maps Cursor model options onto separate ACP config option updates", () => { expect( - resolveCursorAcpConfigUpdates(parameterizedGpt54ConfigOptions, { - reasoning: "xhigh", - fastMode: true, - contextWindow: "1m", - }), + resolveCursorAcpConfigUpdates(parameterizedGpt54ConfigOptions, [ + { id: "reasoning", value: "xhigh" }, + { id: "fastMode", value: true }, + { id: "contextWindow", value: "1m" }, + ]), ).toEqual([ { configId: "reasoning", value: "extra-high" }, { configId: "context", value: "1m" }, @@ -659,26 +650,26 @@ describe("resolveCursorAcpConfigUpdates", () => { it("maps boolean thinking toggles when the model exposes them separately", () => { expect( - resolveCursorAcpConfigUpdates(parameterizedClaudeConfigOptions, { - thinking: false, - }), + resolveCursorAcpConfigUpdates(parameterizedClaudeConfigOptions, [ + { id: "thinking", value: false }, + ]), ).toEqual([{ configId: "thinking", value: false }]); }); it("maps explicit fastMode: false so the adapter can clear a prior fast selection", () => { expect( - resolveCursorAcpConfigUpdates(parameterizedGpt54ConfigOptions, { - fastMode: false, - }), + resolveCursorAcpConfigUpdates(parameterizedGpt54ConfigOptions, [ + { id: "fastMode", value: false }, + ]), ).toEqual([{ configId: "fast", value: "false" }]); }); it("writes Cursor effort changes through the newer model_option config when available", () => { expect( - resolveCursorAcpConfigUpdates(parameterizedClaudeModelOptionConfigOptions, { - reasoning: "max", - thinking: false, - }), + resolveCursorAcpConfigUpdates(parameterizedClaudeModelOptionConfigOptions, [ + { id: "reasoning", value: "max" }, + { id: "thinking", value: false }, + ]), ).toEqual([ { configId: "effort", value: "max" }, { configId: "thinking", value: "false" }, diff --git a/apps/server/src/provider/Layers/CursorProvider.ts b/apps/server/src/provider/Layers/CursorProvider.ts index 70d5656b3e..4225023f7d 100644 --- a/apps/server/src/provider/Layers/CursorProvider.ts +++ b/apps/server/src/provider/Layers/CursorProvider.ts @@ -3,9 +3,9 @@ import * as nodeOs from "node:os"; import * as nodePath from "node:path"; import type { - CursorModelOptions, CursorSettings, ModelCapabilities, + ProviderOptionSelection, ServerProvider, ServerProviderAuth, ServerProviderModel, @@ -15,8 +15,15 @@ import type { import type * as EffectAcpSchema from "effect-acp/schema"; import { Cause, Effect, Equal, Exit, Layer, Option, Result, Stream } from "effect"; import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process"; +import { + createModelCapabilities, + getProviderOptionBooleanSelectionValue, + getProviderOptionStringSelectionValue, +} from "@t3tools/shared/model"; import { + buildBooleanOptionDescriptor, + buildSelectOptionDescriptor, buildServerProvider, collectStreamAsString, isCommandMissingCause, @@ -29,13 +36,14 @@ import { AcpSessionRuntime } from "../acp/AcpSessionRuntime.ts"; import { ServerSettingsService } from "../../serverSettings.ts"; const PROVIDER = "cursor" as const; -const EMPTY_CAPABILITIES: ModelCapabilities = { - reasoningEffortLevels: [], - supportsFastMode: false, - supportsThinkingToggle: false, - contextWindowOptions: [], - promptInjectedEffortLevels: [], -}; +const CURSOR_PRESENTATION = { + displayName: "Cursor", + badgeLabel: "Early Access", + showInteractionModeToggle: true, +} as const; +const EMPTY_CAPABILITIES: ModelCapabilities = createModelCapabilities({ + optionDescriptors: [], +}); const CURSOR_ACP_MODEL_DISCOVERY_TIMEOUT_MS = 15_000; const CURSOR_ACP_MODEL_CAPABILITY_TIMEOUT = "4 seconds"; @@ -55,6 +63,7 @@ function buildInitialCursorProviderSnapshot(cursorSettings: CursorSettings): Ser if (!cursorSettings.enabled) { return buildServerProvider({ provider: PROVIDER, + presentation: CURSOR_PRESENTATION, enabled: false, checkedAt, models, @@ -70,6 +79,7 @@ function buildInitialCursorProviderSnapshot(cursorSettings: CursorSettings): Ser return buildServerProvider({ provider: PROVIDER, + presentation: CURSOR_PRESENTATION, enabled: true, checkedAt, models, @@ -198,6 +208,28 @@ function isBooleanLikeConfigOption(option: EffectAcpSchema.SessionConfigOption): return values.has("true") && values.has("false"); } +function getBooleanCurrentValue( + option: EffectAcpSchema.SessionConfigOption | undefined, +): boolean | undefined { + if (!option) { + return undefined; + } + if (option.type === "boolean") { + return option.currentValue; + } + if (option.type !== "select") { + return undefined; + } + const normalized = option.currentValue?.trim().toLowerCase(); + if (normalized === "true") { + return true; + } + if (normalized === "false") { + return false; + } + return undefined; +} + export function buildCursorCapabilitiesFromConfigOptions( configOptions: ReadonlyArray | null | undefined, ): ModelCapabilities { @@ -251,14 +283,60 @@ export function buildCursorCapabilitiesFromConfigOptions( const thinkingOption = configOptions.find( (option) => option.category === "model_config" && isCursorThinkingConfigOption(option), ); + const fastCurrentValue = getBooleanCurrentValue(fastOption); + const thinkingCurrentValue = getBooleanCurrentValue(thinkingOption); + const optionDescriptors = [ + ...(reasoningEffortLevels.length > 0 + ? [ + buildSelectOptionDescriptor({ + id: "reasoning", + label: reasoningConfig?.name?.trim() || "Reasoning", + options: reasoningEffortLevels, + }), + ] + : []), + ...(contextWindowOptions.length > 0 + ? [ + buildSelectOptionDescriptor({ + id: "contextWindow", + label: contextOption?.name?.trim() || "Context Window", + options: contextWindowOptions, + }), + ] + : []), + ...(fastOption && isBooleanLikeConfigOption(fastOption) + ? [ + typeof fastCurrentValue === "boolean" + ? buildBooleanOptionDescriptor({ + id: "fastMode", + label: fastOption.name?.trim() || "Fast Mode", + currentValue: fastCurrentValue, + }) + : buildBooleanOptionDescriptor({ + id: "fastMode", + label: fastOption.name?.trim() || "Fast Mode", + }), + ] + : []), + ...(thinkingOption && isBooleanLikeConfigOption(thinkingOption) + ? [ + typeof thinkingCurrentValue === "boolean" + ? buildBooleanOptionDescriptor({ + id: "thinking", + label: thinkingOption.name?.trim() || "Thinking", + currentValue: thinkingCurrentValue, + }) + : buildBooleanOptionDescriptor({ + id: "thinking", + label: thinkingOption.name?.trim() || "Thinking", + }), + ] + : []), + ]; - return { - reasoningEffortLevels, - supportsFastMode: fastOption ? isBooleanLikeConfigOption(fastOption) : false, - supportsThinkingToggle: thinkingOption ? isBooleanLikeConfigOption(thinkingOption) : false, - contextWindowOptions, - promptInjectedEffortLevels: [], - }; + return createModelCapabilities({ + optionDescriptors, + }); } function buildCursorDiscoveredModels( @@ -282,13 +360,7 @@ function buildCursorDiscoveredModels( } function hasCursorModelCapabilities(model: Pick): boolean { - return ( - (model.capabilities?.reasoningEffortLevels.length ?? 0) > 0 || - model.capabilities?.supportsFastMode === true || - model.capabilities?.supportsThinkingToggle === true || - (model.capabilities?.contextWindowOptions.length ?? 0) > 0 || - (model.capabilities?.promptInjectedEffortLevels.length ?? 0) > 0 - ); + return (model.capabilities?.optionDescriptors?.length ?? 0) > 0; } export function buildCursorDiscoveredModelsFromConfigOptions( @@ -387,7 +459,7 @@ export function resolveCursorAcpBaseModelId(model: string | null | undefined): s export function resolveCursorAcpConfigUpdates( configOptions: ReadonlyArray | null | undefined, - modelOptions: CursorModelOptions | null | undefined, + selections: ReadonlyArray | null | undefined, ): ReadonlyArray<{ readonly configId: string; readonly value: string | boolean }> { if (!configOptions || configOptions.length === 0) { return []; @@ -396,7 +468,9 @@ export function resolveCursorAcpConfigUpdates( const updates: Array<{ readonly configId: string; readonly value: string | boolean }> = []; const reasoningOption = findCursorEffortConfigOption(configOptions); - const requestedReasoning = normalizeCursorReasoningValue(modelOptions?.reasoning); + const requestedReasoning = normalizeCursorReasoningValue( + getProviderOptionStringSelectionValue(selections, "reasoning"), + ); if (reasoningOption && requestedReasoning) { const value = findCursorSelectOptionValue(reasoningOption, (option) => { const normalizedValue = normalizeCursorReasoningValue(option.value); @@ -411,14 +485,15 @@ export function resolveCursorAcpConfigUpdates( const contextOption = configOptions.find( (option) => option.category === "model_config" && isCursorContextConfigOption(option), ); - if (contextOption && modelOptions?.contextWindow) { + const requestedContextWindow = getProviderOptionStringSelectionValue(selections, "contextWindow"); + if (contextOption && requestedContextWindow) { const value = findCursorSelectOptionValue( contextOption, (option) => normalizeCursorConfigOptionToken(option.value) === - normalizeCursorConfigOptionToken(modelOptions.contextWindow) || + normalizeCursorConfigOptionToken(requestedContextWindow) || normalizeCursorConfigOptionToken(option.name) === - normalizeCursorConfigOptionToken(modelOptions.contextWindow), + normalizeCursorConfigOptionToken(requestedContextWindow), ); if (value) { updates.push({ configId: contextOption.id, value }); @@ -428,8 +503,9 @@ export function resolveCursorAcpConfigUpdates( const fastOption = configOptions.find( (option) => option.category === "model_config" && isCursorFastConfigOption(option), ); - if (fastOption && typeof modelOptions?.fastMode === "boolean") { - const value = findCursorBooleanConfigValue(fastOption, modelOptions.fastMode); + const requestedFastMode = getProviderOptionBooleanSelectionValue(selections, "fastMode"); + if (fastOption && typeof requestedFastMode === "boolean") { + const value = findCursorBooleanConfigValue(fastOption, requestedFastMode); if (value !== undefined) { updates.push({ configId: fastOption.id, value }); } @@ -438,8 +514,9 @@ export function resolveCursorAcpConfigUpdates( const thinkingOption = configOptions.find( (option) => option.category === "model_config" && isCursorThinkingConfigOption(option), ); - if (thinkingOption && typeof modelOptions?.thinking === "boolean") { - const value = findCursorBooleanConfigValue(thinkingOption, modelOptions.thinking); + const requestedThinking = getProviderOptionBooleanSelectionValue(selections, "thinking"); + if (thinkingOption && typeof requestedThinking === "boolean") { + const value = findCursorBooleanConfigValue(thinkingOption, requestedThinking); if (value !== undefined) { updates.push({ configId: thinkingOption.id, value }); } @@ -610,6 +687,7 @@ export function buildCursorProviderSnapshot(input: { const message = joinProviderMessages(input.parsed.message, input.discoveryWarning); return buildServerProvider({ provider: PROVIDER, + presentation: CURSOR_PRESENTATION, enabled: input.cursorSettings.enabled, checkedAt: input.checkedAt, models: providerModelsFromSettings( @@ -962,6 +1040,7 @@ export const checkCursorProviderStatus = Effect.fn("checkCursorProviderStatus")( if (!cursorSettings.enabled) { return buildServerProvider({ provider: PROVIDER, + presentation: CURSOR_PRESENTATION, enabled: false, checkedAt, models: fallbackModels, @@ -985,6 +1064,7 @@ export const checkCursorProviderStatus = Effect.fn("checkCursorProviderStatus")( const error = aboutProbe.failure; return buildServerProvider({ provider: PROVIDER, + presentation: CURSOR_PRESENTATION, enabled: cursorSettings.enabled, checkedAt, models: fallbackModels, @@ -1003,6 +1083,7 @@ export const checkCursorProviderStatus = Effect.fn("checkCursorProviderStatus")( if (Option.isNone(aboutProbe.success)) { return buildServerProvider({ provider: PROVIDER, + presentation: CURSOR_PRESENTATION, enabled: cursorSettings.enabled, checkedAt, models: fallbackModels, @@ -1025,6 +1106,7 @@ export const checkCursorProviderStatus = Effect.fn("checkCursorProviderStatus")( if (parameterizedModelPickerUnsupportedMessage) { return buildServerProvider({ provider: PROVIDER, + presentation: CURSOR_PRESENTATION, enabled: cursorSettings.enabled, checkedAt, models: fallbackModels, diff --git a/apps/server/src/provider/Layers/OpenCodeAdapter.ts b/apps/server/src/provider/Layers/OpenCodeAdapter.ts index 5081495dcb..aa504d5b96 100644 --- a/apps/server/src/provider/Layers/OpenCodeAdapter.ts +++ b/apps/server/src/provider/Layers/OpenCodeAdapter.ts @@ -13,6 +13,7 @@ import { } from "@t3tools/contracts"; import { Cause, Effect, Exit, Layer, Queue, Ref, Scope, Stream } from "effect"; import type { OpencodeClient, Part, PermissionRequest, QuestionRequest } from "@opencode-ai/sdk/v2"; +import { getModelSelectionStringOptionValue } from "@t3tools/shared/model"; import { resolveAttachmentPath } from "../../attachmentStore.ts"; import { ServerConfig } from "../../config.ts"; @@ -1146,11 +1147,11 @@ export function makeOpenCodeAdapterLive(options?: OpenCodeAdapterLiveOptions) { const agent = input.modelSelection?.provider === PROVIDER - ? input.modelSelection.options?.agent + ? getModelSelectionStringOptionValue(input.modelSelection, "agent") : undefined; const variant = input.modelSelection?.provider === PROVIDER - ? input.modelSelection.options?.variant + ? getModelSelectionStringOptionValue(input.modelSelection, "variant") : undefined; context.activeTurnId = turnId; diff --git a/apps/server/src/provider/Layers/OpenCodeProvider.test.ts b/apps/server/src/provider/Layers/OpenCodeProvider.test.ts index 4a43c37b68..f32fd6f49e 100644 --- a/apps/server/src/provider/Layers/OpenCodeProvider.test.ts +++ b/apps/server/src/provider/Layers/OpenCodeProvider.test.ts @@ -176,14 +176,16 @@ it.layer(makeTestLayer())("OpenCodeProviderLive", (it) => { const model = snapshot.models.find((entry) => entry.slug === "openai/gpt-5.4"); assert.ok(model); - assert.equal( - model.capabilities?.variantOptions?.find((option) => option.isDefault)?.value, - "medium", + const variantDescriptor = model.capabilities?.optionDescriptors?.find( + (descriptor) => descriptor.id === "variant" && descriptor.type === "select", ); - assert.equal( - model.capabilities?.agentOptions?.find((option) => option.isDefault)?.value, - "build", + assert.ok(variantDescriptor && variantDescriptor.type === "select"); + assert.equal(variantDescriptor.options.find((option) => option.isDefault)?.id, "medium"); + const agentDescriptor = model.capabilities?.optionDescriptors?.find( + (descriptor) => descriptor.id === "agent" && descriptor.type === "select", ); + assert.ok(agentDescriptor && agentDescriptor.type === "select"); + assert.equal(agentDescriptor.options.find((option) => option.isDefault)?.id, "build"); }), ); }); diff --git a/apps/server/src/provider/Layers/OpenCodeProvider.ts b/apps/server/src/provider/Layers/OpenCodeProvider.ts index 586bc3d6f4..b94840015e 100644 --- a/apps/server/src/provider/Layers/OpenCodeProvider.ts +++ b/apps/server/src/provider/Layers/OpenCodeProvider.ts @@ -6,6 +6,8 @@ import type { } from "@t3tools/contracts"; import { Cause, Data, Effect, Equal, Layer, Stream } from "effect"; +import { createModelCapabilities } from "@t3tools/shared/model"; + import { ServerConfig } from "../../config.ts"; import { ServerSettingsService } from "../../serverSettings.ts"; import { makeManagedServerProvider } from "../makeManagedServerProvider.ts"; @@ -25,6 +27,10 @@ import { import type { Agent, ProviderListResponse } from "@opencode-ai/sdk/v2"; const PROVIDER = "opencode" as const; +const OPENCODE_PRESENTATION = { + displayName: "OpenCode", + showInteractionModeToggle: false, +} as const; const MINIMUM_OPENCODE_VERSION = "1.14.19"; class OpenCodeProbeError extends Data.TaggedError("OpenCodeProbeError")<{ @@ -159,13 +165,9 @@ function inferDefaultAgent(agents: ReadonlyArray): string | undefined { return agents.find((agent) => agent.name === "build")?.name ?? agents[0]?.name ?? undefined; } -const DEFAULT_OPENCODE_MODEL_CAPABILITIES: ModelCapabilities = { - reasoningEffortLevels: [], - supportsFastMode: false, - supportsThinkingToggle: false, - contextWindowOptions: [], - promptInjectedEffortLevels: [], -}; +const DEFAULT_OPENCODE_MODEL_CAPABILITIES: ModelCapabilities = createModelCapabilities({ + optionDescriptors: [], +}); function openCodeCapabilitiesForModel(input: { readonly providerID: string; @@ -174,27 +176,46 @@ function openCodeCapabilitiesForModel(input: { }): ModelCapabilities { const variantValues = Object.keys(input.model.variants ?? {}); const defaultVariant = inferDefaultVariant(input.providerID, variantValues); - const variantOptions: ModelCapabilities["variantOptions"] = variantValues.map((value) => - Object.assign( - { value, label: titleCaseSlug(value) }, - defaultVariant === value ? { isDefault: true } : {}, - ), + const variantOptions = variantValues.map((value) => + defaultVariant === value + ? { id: value, label: titleCaseSlug(value), isDefault: true as const } + : { id: value, label: titleCaseSlug(value) }, ); const primaryAgents = input.agents.filter( (agent) => !agent.hidden && (agent.mode === "primary" || agent.mode === "all"), ); const defaultAgent = inferDefaultAgent(primaryAgents); - const agentOptions: ModelCapabilities["agentOptions"] = primaryAgents.map((agent) => - Object.assign( - { value: agent.name, label: titleCaseSlug(agent.name) }, - defaultAgent === agent.name ? { isDefault: true } : {}, - ), + const agentOptions = primaryAgents.map((agent) => + defaultAgent === agent.name + ? { id: agent.name, label: titleCaseSlug(agent.name), isDefault: true as const } + : { id: agent.name, label: titleCaseSlug(agent.name) }, ); - return { - ...DEFAULT_OPENCODE_MODEL_CAPABILITIES, - ...(variantOptions.length > 0 ? { variantOptions } : {}), - ...(agentOptions.length > 0 ? { agentOptions } : {}), - }; + return createModelCapabilities({ + optionDescriptors: [ + ...(variantOptions.length > 0 + ? [ + { + id: "variant", + label: "Variant", + type: "select" as const, + options: variantOptions, + ...(defaultVariant ? { currentValue: defaultVariant } : {}), + }, + ] + : []), + ...(agentOptions.length > 0 + ? [ + { + id: "agent", + label: "Agent", + type: "select" as const, + options: agentOptions, + ...(defaultAgent ? { currentValue: defaultAgent } : {}), + }, + ] + : []), + ], + }); } function flattenOpenCodeModels(input: OpenCodeInventory): ReadonlyArray { @@ -242,6 +263,7 @@ const makePendingOpenCodeProvider = (openCodeSettings: OpenCodeSettings): Server if (!openCodeSettings.enabled) { return buildServerProvider({ provider: PROVIDER, + presentation: OPENCODE_PRESENTATION, enabled: false, checkedAt, models, @@ -260,6 +282,7 @@ const makePendingOpenCodeProvider = (openCodeSettings: OpenCodeSettings): Server return buildServerProvider({ provider: PROVIDER, + presentation: OPENCODE_PRESENTATION, enabled: true, checkedAt, models, @@ -296,6 +319,7 @@ export const OpenCodeProviderLive = Layer.effect( }); return buildServerProvider({ provider: PROVIDER, + presentation: OPENCODE_PRESENTATION, enabled: input.settings.enabled, checkedAt, models: providerModelsFromSettings( @@ -317,6 +341,7 @@ export const OpenCodeProviderLive = Layer.effect( if (!input.settings.enabled) { return buildServerProvider({ provider: PROVIDER, + presentation: OPENCODE_PRESENTATION, enabled: false, checkedAt, models: providerModelsFromSettings( @@ -368,6 +393,7 @@ export const OpenCodeProviderLive = Layer.effect( if (compareCliVersions(version, MINIMUM_OPENCODE_VERSION) < 0) { return buildServerProvider({ provider: PROVIDER, + presentation: OPENCODE_PRESENTATION, enabled: input.settings.enabled, checkedAt, models: providerModelsFromSettings( @@ -433,6 +459,7 @@ export const OpenCodeProviderLive = Layer.effect( const connectedCount = inventoryExit.value.providerList.connected.length; return buildServerProvider({ provider: PROVIDER, + presentation: OPENCODE_PRESENTATION, enabled: true, checkedAt, models, diff --git a/apps/server/src/provider/Layers/ProviderAdapterRegistry.ts b/apps/server/src/provider/Layers/ProviderAdapterRegistry.ts index 22fc0b7fda..dabe5b8581 100644 --- a/apps/server/src/provider/Layers/ProviderAdapterRegistry.ts +++ b/apps/server/src/provider/Layers/ProviderAdapterRegistry.ts @@ -19,6 +19,7 @@ import { ClaudeAdapter } from "../Services/ClaudeAdapter.ts"; import { CodexAdapter } from "../Services/CodexAdapter.ts"; import { CursorAdapter } from "../Services/CursorAdapter.ts"; import { OpenCodeAdapter } from "../Services/OpenCodeAdapter.ts"; +import { createBuiltInAdapterList } from "../builtInProviderCatalog.ts"; export interface ProviderAdapterRegistryLiveOptions { readonly adapters?: ReadonlyArray>; @@ -31,12 +32,12 @@ const makeProviderAdapterRegistry = Effect.fn("makeProviderAdapterRegistry")(fun const adapters = options?.adapters !== undefined ? options.adapters - : [ - yield* CodexAdapter, - yield* ClaudeAdapter, - yield* OpenCodeAdapter, - ...(cursorAdapterOption._tag === "Some" ? [cursorAdapterOption.value] : []), - ]; + : createBuiltInAdapterList({ + codex: yield* CodexAdapter, + claudeAgent: yield* ClaudeAdapter, + opencode: yield* OpenCodeAdapter, + ...(cursorAdapterOption._tag === "Some" ? { cursor: cursorAdapterOption.value } : {}), + }); const byProvider = new Map(adapters.map((adapter) => [adapter.provider, adapter])); const getByProvider: ProviderAdapterRegistryShape["getByProvider"] = (provider) => { diff --git a/apps/server/src/provider/Layers/ProviderRegistry.test.ts b/apps/server/src/provider/Layers/ProviderRegistry.test.ts index 8fe28351a4..1df9da6774 100644 --- a/apps/server/src/provider/Layers/ProviderRegistry.test.ts +++ b/apps/server/src/provider/Layers/ProviderRegistry.test.ts @@ -11,6 +11,7 @@ import { import * as PlatformError from "effect/PlatformError"; import { ChildProcessSpawner } from "effect/unstable/process"; import { deepMerge } from "@t3tools/shared/Struct"; +import { createModelCapabilities } from "@t3tools/shared/model"; import { checkCodexProviderStatus, type CodexAppServerProviderSnapshot } from "./CodexProvider.ts"; import { checkClaudeProviderStatus, parseClaudeAuthStatusFromOutput } from "./ClaudeProvider.ts"; @@ -29,6 +30,30 @@ process.env.T3CODE_CURSOR_ENABLED = "1"; const encoder = new TextEncoder(); +function selectDescriptor( + id: string, + label: string, + options: ReadonlyArray<{ id: string; label: string; isDefault?: boolean }>, +) { + return { + id, + label, + type: "select" as const, + options: [...options], + ...(options.find((option) => option.isDefault)?.id + ? { currentValue: options.find((option) => option.isDefault)?.id } + : {}), + }; +} + +function booleanDescriptor(id: string, label: string) { + return { + id, + label, + type: "boolean" as const, + }; +} + function mockHandle(result: { stdout: string; stderr: string; code: number }) { return ChildProcessSpawner.makeHandle({ pid: ChildProcessSpawner.ProcessId(1), @@ -88,16 +113,15 @@ function failingSpawnerLayer(description: string) { ); } -const codexModelCapabilities = { - reasoningEffortLevels: [ - { value: "high", label: "High", isDefault: true }, - { value: "low", label: "Low" }, +const codexModelCapabilities = createModelCapabilities({ + optionDescriptors: [ + selectDescriptor("reasoningEffort", "Reasoning", [ + { id: "high", label: "High", isDefault: true }, + { id: "low", label: "Low" }, + ]), + booleanDescriptor("fastMode", "Fast Mode"), ], - supportsFastMode: true, - supportsThinkingToggle: false, - contextWindowOptions: [], - promptInjectedEffortLevels: [], -} satisfies NonNullable; +}) satisfies NonNullable; function makeCodexProbeSnapshot( input: Partial = {}, @@ -330,13 +354,15 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))( slug: "claude-opus-4-6", name: "Opus 4.6", isCustom: false, - capabilities: { - reasoningEffortLevels: [{ value: "high", label: "High", isDefault: true }], - supportsFastMode: true, - supportsThinkingToggle: true, - contextWindowOptions: [], - promptInjectedEffortLevels: [], - }, + capabilities: createModelCapabilities({ + optionDescriptors: [ + selectDescriptor("reasoning", "Reasoning", [ + { id: "high", label: "High", isDefault: true }, + ]), + booleanDescriptor("fastMode", "Fast Mode"), + booleanDescriptor("thinking", "Thinking"), + ], + }), }, ], slashCommands: [], @@ -367,13 +393,15 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))( slug: "claude-opus-4-6", name: "Opus 4.6", isCustom: false, - capabilities: { - reasoningEffortLevels: [{ value: "high", label: "High", isDefault: true }], - supportsFastMode: true, - supportsThinkingToggle: true, - contextWindowOptions: [], - promptInjectedEffortLevels: [], - }, + capabilities: createModelCapabilities({ + optionDescriptors: [ + selectDescriptor("reasoning", "Reasoning", [ + { id: "high", label: "High", isDefault: true }, + ]), + booleanDescriptor("fastMode", "Fast Mode"), + booleanDescriptor("thinking", "Thinking"), + ], + }), }, ], slashCommands: [], @@ -387,13 +415,9 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))( slug: "claude-opus-4-6", name: "Opus 4.6", isCustom: false, - capabilities: { - reasoningEffortLevels: [], - supportsFastMode: false, - supportsThinkingToggle: false, - contextWindowOptions: [], - promptInjectedEffortLevels: [], - }, + capabilities: createModelCapabilities({ + optionDescriptors: [], + }), }, ], } satisfies ServerProvider; @@ -603,9 +627,14 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))( "Expected Claude Opus 4.7 capabilities to be present for Claude Code v2.1.111.", ); } + const effortDescriptor = opus47.capabilities.optionDescriptors?.find( + (descriptor) => descriptor.type === "select" && descriptor.id === "effort", + ); assert.deepStrictEqual( - opus47.capabilities.reasoningEffortLevels.find((level) => level.isDefault), - { value: "xhigh", label: "Extra High", isDefault: true }, + effortDescriptor?.type === "select" + ? effortDescriptor.options.find((option) => option.isDefault) + : undefined, + { id: "xhigh", label: "Extra High", isDefault: true }, ); }).pipe( Effect.provide( diff --git a/apps/server/src/provider/Layers/ProviderRegistry.ts b/apps/server/src/provider/Layers/ProviderRegistry.ts index 3f83419a38..ddd1701a94 100644 --- a/apps/server/src/provider/Layers/ProviderRegistry.ts +++ b/apps/server/src/provider/Layers/ProviderRegistry.ts @@ -25,13 +25,8 @@ import { resolveProviderStatusCachePath, writeProviderStatusCache, } from "../providerStatusCache.ts"; - -type ProviderSnapshotSource = { - readonly provider: ProviderKind; - readonly getSnapshot: Effect.Effect; - readonly refresh: Effect.Effect; - readonly streamChanges: Stream.Stream; -}; +import { createBuiltInProviderSources } from "../builtInProviderCatalog.ts"; +import type { ProviderSnapshotSource } from "../builtInProviderCatalog.ts"; const loadProviders = ( providerSources: ReadonlyArray, @@ -41,11 +36,7 @@ const loadProviders = ( }); const hasModelCapabilities = (model: ServerProvider["models"][number]): boolean => - (model.capabilities?.reasoningEffortLevels.length ?? 0) > 0 || - model.capabilities?.supportsFastMode === true || - model.capabilities?.supportsThinkingToggle === true || - (model.capabilities?.contextWindowOptions.length ?? 0) > 0 || - (model.capabilities?.promptInjectedEffortLevels.length ?? 0) > 0; + (model.capabilities?.optionDescriptors?.length ?? 0) > 0; const mergeProviderModels = ( previousModels: ReadonlyArray, @@ -98,32 +89,12 @@ const ProviderRegistryLiveBase = Layer.effect( const cursorProvider = yield* CursorProvider; - const providerSources = [ - { - provider: "codex", - getSnapshot: codexProvider.getSnapshot, - refresh: codexProvider.refresh, - streamChanges: codexProvider.streamChanges, - }, - { - provider: "claudeAgent", - getSnapshot: claudeProvider.getSnapshot, - refresh: claudeProvider.refresh, - streamChanges: claudeProvider.streamChanges, - }, - { - provider: "opencode", - getSnapshot: openCodeProvider.getSnapshot, - refresh: openCodeProvider.refresh, - streamChanges: openCodeProvider.streamChanges, - }, - { - provider: "cursor", - getSnapshot: cursorProvider.getSnapshot, - refresh: cursorProvider.refresh, - streamChanges: cursorProvider.streamChanges, - }, - ] satisfies ReadonlyArray; + const providerSources = createBuiltInProviderSources({ + codex: codexProvider, + claudeAgent: claudeProvider, + opencode: openCodeProvider, + cursor: cursorProvider, + }) satisfies ReadonlyArray; const activeProviders = PROVIDER_CACHE_IDS; const changesPubSub = yield* Effect.acquireRelease( PubSub.unbounded>(), diff --git a/apps/server/src/provider/Layers/ProviderService.test.ts b/apps/server/src/provider/Layers/ProviderService.test.ts index 089ae9da99..d7b8c1cb38 100644 --- a/apps/server/src/provider/Layers/ProviderService.test.ts +++ b/apps/server/src/provider/Layers/ProviderService.test.ts @@ -17,6 +17,7 @@ import { ThreadId, TurnId, } from "@t3tools/contracts"; +import { createModelSelection } from "@t3tools/shared/model"; import { it, assert, vi } from "@effect/vitest"; import { Effect, Fiber, Layer, Metric, Option, PubSub, Ref, Stream } from "effect"; @@ -860,13 +861,9 @@ routing.layer("ProviderServiceLive routing", (it) => { provider: "claudeAgent", threadId: asThreadId("thread-claude-send-turn"), cwd: "/tmp/project-claude-send-turn", - modelSelection: { - provider: "claudeAgent", - model: "claude-opus-4-6", - options: { - effort: "max", - }, - }, + modelSelection: createModelSelection("claudeAgent", "claude-opus-4-6", [ + { id: "effort", value: "max" }, + ]), runtimeMode: "full-access", }); @@ -893,13 +890,10 @@ routing.layer("ProviderServiceLive routing", (it) => { }; assert.equal(startPayload.provider, "claudeAgent"); assert.equal(startPayload.cwd, "/tmp/project-claude-send-turn"); - assert.deepEqual(startPayload.modelSelection, { - provider: "claudeAgent", - model: "claude-opus-4-6", - options: { - effort: "max", - }, - }); + assert.deepEqual( + startPayload.modelSelection, + createModelSelection("claudeAgent", "claude-opus-4-6", [{ id: "effort", value: "max" }]), + ); assert.deepEqual(startPayload.resumeCursor, initial.resumeCursor); assert.equal(startPayload.threadId, initial.threadId); } diff --git a/apps/server/src/provider/acp/CursorAcpSupport.test.ts b/apps/server/src/provider/acp/CursorAcpSupport.test.ts index 94de569b2b..30941acbfd 100644 --- a/apps/server/src/provider/acp/CursorAcpSupport.test.ts +++ b/apps/server/src/provider/acp/CursorAcpSupport.test.ts @@ -99,11 +99,11 @@ describe("applyCursorAcpModelSelection", () => { applyCursorAcpModelSelection({ runtime, model: "gpt-5.4-medium-fast[reasoning=medium,context=272k]", - modelOptions: { - reasoning: "xhigh", - contextWindow: "1m", - fastMode: true, - }, + selections: [ + { id: "reasoning", value: "xhigh" }, + { id: "contextWindow", value: "1m" }, + { id: "fastMode", value: true }, + ], mapError: ({ step, configId, cause }) => new Error( step === "set-config-option" diff --git a/apps/server/src/provider/acp/CursorAcpSupport.ts b/apps/server/src/provider/acp/CursorAcpSupport.ts index 72b9af394b..25e342f0d0 100644 --- a/apps/server/src/provider/acp/CursorAcpSupport.ts +++ b/apps/server/src/provider/acp/CursorAcpSupport.ts @@ -1,4 +1,4 @@ -import { type CursorModelOptions, type CursorSettings } from "@t3tools/contracts"; +import { type CursorSettings, type ProviderOptionSelection } from "@t3tools/contracts"; import { Effect, Layer, Scope } from "effect"; import { ChildProcessSpawner } from "effect/unstable/process"; import type * as EffectAcpErrors from "effect-acp/errors"; @@ -76,7 +76,7 @@ interface CursorAcpModelSelectionRuntime { export function applyCursorAcpModelSelection(input: { readonly runtime: CursorAcpModelSelectionRuntime; readonly model: string | null | undefined; - readonly modelOptions: CursorModelOptions | null | undefined; + readonly selections: ReadonlyArray | null | undefined; readonly mapError: (context: CursorAcpModelSelectionErrorContext) => E; }): Effect.Effect { return Effect.gen(function* () { @@ -91,7 +91,7 @@ export function applyCursorAcpModelSelection(input: { const configUpdates = resolveCursorAcpConfigUpdates( yield* input.runtime.getConfigOptions, - input.modelOptions, + input.selections, ); for (const update of configUpdates) { yield* input.runtime.setConfigOption(update.configId, update.value).pipe( diff --git a/apps/server/src/provider/builtInProviderCatalog.ts b/apps/server/src/provider/builtInProviderCatalog.ts new file mode 100644 index 0000000000..1fd10a85d9 --- /dev/null +++ b/apps/server/src/provider/builtInProviderCatalog.ts @@ -0,0 +1,49 @@ +import type { ProviderKind, ServerProvider } from "@t3tools/contracts"; +import type { Stream } from "effect"; +import type { ProviderAdapterError } from "./Errors.ts"; +import type { ProviderAdapterShape } from "./Services/ProviderAdapter.ts"; +import type { ServerProviderShape } from "./Services/ServerProvider.ts"; + +export type ProviderSnapshotSource = { + readonly provider: ProviderKind; + readonly getSnapshot: ServerProviderShape["getSnapshot"]; + readonly refresh: ServerProviderShape["refresh"]; + readonly streamChanges: Stream.Stream; +}; + +type BuiltInProviderServiceMap = Record; +type BuiltInAdapterMap = { + readonly codex: ProviderAdapterShape; + readonly claudeAgent: ProviderAdapterShape; + readonly opencode: ProviderAdapterShape; + readonly cursor?: ProviderAdapterShape; +}; + +export const BUILT_IN_PROVIDER_ORDER = [ + "codex", + "claudeAgent", + "opencode", + "cursor", +] as const satisfies ReadonlyArray; + +export function createBuiltInProviderSources( + services: BuiltInProviderServiceMap, +): ReadonlyArray { + return BUILT_IN_PROVIDER_ORDER.map((provider) => ({ + provider, + getSnapshot: services[provider].getSnapshot, + refresh: services[provider].refresh, + streamChanges: services[provider].streamChanges, + })); +} + +export function createBuiltInAdapterList( + adapters: BuiltInAdapterMap, +): ReadonlyArray> { + return [ + adapters.codex, + adapters.claudeAgent, + adapters.opencode, + ...(adapters.cursor ? [adapters.cursor] : []), + ]; +} diff --git a/apps/server/src/provider/makeManagedServerProvider.test.ts b/apps/server/src/provider/makeManagedServerProvider.test.ts index 31fe73a467..5d50d12e37 100644 --- a/apps/server/src/provider/makeManagedServerProvider.test.ts +++ b/apps/server/src/provider/makeManagedServerProvider.test.ts @@ -1,9 +1,21 @@ import { describe, it, assert } from "@effect/vitest"; import type { ServerProvider } from "@t3tools/contracts"; +import { createModelCapabilities } from "@t3tools/shared/model"; import { Deferred, Effect, Fiber, PubSub, Ref, Stream } from "effect"; import { makeManagedServerProvider } from "./makeManagedServerProvider.ts"; +const emptyCapabilities = createModelCapabilities({ optionDescriptors: [] }); +const fastModeCapabilities = createModelCapabilities({ + optionDescriptors: [ + { + id: "fastMode", + label: "Fast Mode", + type: "boolean", + }, + ], +}); + interface TestSettings { readonly enabled: boolean; } @@ -43,13 +55,7 @@ const enrichedSnapshot: ServerProvider = { slug: "composer-2", name: "Composer 2", isCustom: false, - capabilities: { - reasoningEffortLevels: [], - supportsFastMode: true, - supportsThinkingToggle: false, - contextWindowOptions: [], - promptInjectedEffortLevels: [], - }, + capabilities: fastModeCapabilities, }, ], }; @@ -68,13 +74,7 @@ const enrichedSnapshotSecond: ServerProvider = { slug: "gpt-5.4", name: "GPT-5.4", isCustom: false, - capabilities: { - reasoningEffortLevels: [], - supportsFastMode: false, - supportsThinkingToggle: false, - contextWindowOptions: [], - promptInjectedEffortLevels: [], - }, + capabilities: emptyCapabilities, }, ], }; diff --git a/apps/server/src/provider/opencodeRuntime.ts b/apps/server/src/provider/opencodeRuntime.ts index 9f10738dbf..41ec5102c3 100644 --- a/apps/server/src/provider/opencodeRuntime.ts +++ b/apps/server/src/provider/opencodeRuntime.ts @@ -36,7 +36,6 @@ import { NetService } from "@t3tools/shared/Net"; const OPENCODE_SERVER_READY_PREFIX = "opencode server listening"; const DEFAULT_OPENCODE_SERVER_TIMEOUT_MS = 5_000; const DEFAULT_HOSTNAME = "127.0.0.1"; - export interface OpenCodeServerProcess { readonly url: string; readonly exitCode: Effect.Effect; diff --git a/apps/server/src/provider/providerSnapshot.test.ts b/apps/server/src/provider/providerSnapshot.test.ts index 0a0d31ccb5..f990afb2d6 100644 --- a/apps/server/src/provider/providerSnapshot.test.ts +++ b/apps/server/src/provider/providerSnapshot.test.ts @@ -1,17 +1,27 @@ import { describe, expect, it } from "vitest"; import type { ModelCapabilities } from "@t3tools/contracts"; +import { createModelCapabilities } from "@t3tools/shared/model"; import { providerModelsFromSettings } from "./providerSnapshot.ts"; -const OPENCODE_CUSTOM_MODEL_CAPABILITIES: ModelCapabilities = { - reasoningEffortLevels: [], - supportsFastMode: false, - supportsThinkingToggle: false, - contextWindowOptions: [], - promptInjectedEffortLevels: [], - variantOptions: [{ value: "medium", label: "Medium", isDefault: true }], - agentOptions: [{ value: "build", label: "Build", isDefault: true }], -}; +const OPENCODE_CUSTOM_MODEL_CAPABILITIES: ModelCapabilities = createModelCapabilities({ + optionDescriptors: [ + { + id: "variant", + label: "Reasoning", + type: "select", + options: [{ id: "medium", label: "Medium", isDefault: true }], + currentValue: "medium", + }, + { + id: "agent", + label: "Agent", + type: "select", + options: [{ id: "build", label: "Build", isDefault: true }], + currentValue: "build", + }, + ], +}); describe("providerModelsFromSettings", () => { it("applies the provided capabilities to custom models", () => { diff --git a/apps/server/src/provider/providerSnapshot.ts b/apps/server/src/provider/providerSnapshot.ts index fcea249e6e..f1f0307485 100644 --- a/apps/server/src/provider/providerSnapshot.ts +++ b/apps/server/src/provider/providerSnapshot.ts @@ -30,6 +30,12 @@ export interface ProviderProbeResult { readonly message?: string; } +export interface ServerProviderPresentation { + readonly displayName: string; + readonly badgeLabel?: string; + readonly showInteractionModeToggle?: boolean; +} + export function nonEmptyTrimmed(value: string | undefined): string | undefined { if (!value) return undefined; const trimmed = value.trim(); @@ -129,8 +135,52 @@ export function providerModelsFromSettings( return [...resolvedBuiltInModels, ...customEntries]; } +export function buildSelectOptionDescriptor(input: { + readonly id: string; + readonly label: string; + readonly options: + | ReadonlyArray<{ value: string; label: string; isDefault?: boolean | undefined }> + | undefined; + readonly description?: string; + readonly promptInjectedValues?: ReadonlyArray; +}) { + const options = (input.options ?? []).map((option) => + option.isDefault + ? { id: option.value, label: option.label, isDefault: true } + : { id: option.value, label: option.label }, + ); + const currentValue = options.find((option) => option.isDefault)?.id; + return { + id: input.id, + label: input.label, + type: "select" as const, + options, + ...(currentValue ? { currentValue } : {}), + ...(input.description ? { description: input.description } : {}), + ...(input.promptInjectedValues && input.promptInjectedValues.length > 0 + ? { promptInjectedValues: [...input.promptInjectedValues] } + : {}), + }; +} + +export function buildBooleanOptionDescriptor(input: { + readonly id: string; + readonly label: string; + readonly currentValue?: boolean; + readonly description?: string; +}) { + return { + id: input.id, + label: input.label, + type: "boolean" as const, + ...(input.description ? { description: input.description } : {}), + ...(typeof input.currentValue === "boolean" ? { currentValue: input.currentValue } : {}), + }; +} + export function buildServerProvider(input: { provider: ServerProvider["provider"]; + presentation: ServerProviderPresentation; enabled: boolean; checkedAt: string; models: ReadonlyArray; @@ -140,6 +190,11 @@ export function buildServerProvider(input: { }): ServerProvider { return { provider: input.provider, + displayName: input.presentation.displayName, + ...(input.presentation.badgeLabel ? { badgeLabel: input.presentation.badgeLabel } : {}), + ...(typeof input.presentation.showInteractionModeToggle === "boolean" + ? { showInteractionModeToggle: input.presentation.showInteractionModeToggle } + : {}), enabled: input.enabled, installed: input.probe.installed, version: input.probe.version, diff --git a/apps/server/src/provider/providerStatusCache.test.ts b/apps/server/src/provider/providerStatusCache.test.ts index b0cb5bc663..5a81341f6d 100644 --- a/apps/server/src/provider/providerStatusCache.test.ts +++ b/apps/server/src/provider/providerStatusCache.test.ts @@ -1,5 +1,6 @@ import * as NodeServices from "@effect/platform-node/NodeServices"; import type { ServerProvider } from "@t3tools/contracts"; +import { createModelCapabilities } from "@t3tools/shared/model"; import { assert, it } from "@effect/vitest"; import { Effect, FileSystem } from "effect"; @@ -10,6 +11,8 @@ import { writeProviderStatusCache, } from "./providerStatusCache.ts"; +const emptyCapabilities = createModelCapabilities({ optionDescriptors: [] }); + const makeProvider = ( provider: ServerProvider["provider"], overrides?: Partial, @@ -81,13 +84,7 @@ it.layer(NodeServices.layer)("providerStatusCache", (it) => { slug: "gpt-5-mini", name: "GPT-5 Mini", isCustom: false, - capabilities: { - reasoningEffortLevels: [], - supportsFastMode: false, - supportsThinkingToggle: false, - contextWindowOptions: [], - promptInjectedEffortLevels: [], - }, + capabilities: emptyCapabilities, }, ], message: "Cached message", @@ -106,13 +103,7 @@ it.layer(NodeServices.layer)("providerStatusCache", (it) => { slug: "gpt-5.4", name: "GPT-5.4", isCustom: false, - capabilities: { - reasoningEffortLevels: [], - supportsFastMode: false, - supportsThinkingToggle: false, - contextWindowOptions: [], - promptInjectedEffortLevels: [], - }, + capabilities: emptyCapabilities, }, ], message: "Pending refresh", @@ -131,13 +122,7 @@ it.layer(NodeServices.layer)("providerStatusCache", (it) => { slug: "gpt-5-mini", name: "GPT-5 Mini", isCustom: false, - capabilities: { - reasoningEffortLevels: [], - supportsFastMode: false, - supportsThinkingToggle: false, - contextWindowOptions: [], - promptInjectedEffortLevels: [], - }, + capabilities: emptyCapabilities, }, ], installed: cachedCodex.installed, diff --git a/apps/server/src/serverSettings.test.ts b/apps/server/src/serverSettings.test.ts index 655ede9441..55f598054b 100644 --- a/apps/server/src/serverSettings.test.ts +++ b/apps/server/src/serverSettings.test.ts @@ -1,5 +1,6 @@ import * as NodeServices from "@effect/platform-node/NodeServices"; -import { DEFAULT_SERVER_SETTINGS, ServerSettingsPatch } from "@t3tools/contracts"; +import { DEFAULT_SERVER_SETTINGS, ServerSettings, ServerSettingsPatch } from "@t3tools/contracts"; +import { createModelSelection } from "@t3tools/shared/model"; import { assert, it } from "@effect/vitest"; import { Effect, FileSystem, Layer, Schema } from "effect"; import { ServerConfig } from "./config.ts"; @@ -28,22 +29,40 @@ it.layer(NodeServices.layer)("server settings", (it) => { assert.deepEqual( decodePatch({ textGenerationModelSelection: { - options: { - fastMode: false, - }, + options: [{ id: "fastMode", value: false }], }, }), { textGenerationModelSelection: { - options: { - fastMode: false, - }, + options: [{ id: "fastMode", value: false }], }, }, ); }), ); + it.effect( + "decodes legacy object-shaped textGenerationModelSelection.options from settings.json", + () => + Effect.sync(() => { + const decode = Schema.decodeUnknownSync(ServerSettings); + + const decoded = decode({ + textGenerationModelSelection: { + provider: "codex", + model: "gpt-5.4-mini", + options: { reasoningEffort: "low" }, + }, + }); + + assert.deepEqual(decoded.textGenerationModelSelection, { + provider: "codex", + model: "gpt-5.4-mini", + options: [{ id: "reasoningEffort", value: "low" }], + }); + }), + ); + it.effect("deep merges nested settings updates without dropping siblings", () => Effect.gen(function* () { const serverSettings = yield* ServerSettingsService; @@ -62,10 +81,14 @@ it.layer(NodeServices.layer)("server settings", (it) => { textGenerationModelSelection: { provider: "codex", model: DEFAULT_SERVER_SETTINGS.textGenerationModelSelection.model, - options: { - reasoningEffort: "high", - fastMode: true, - }, + options: createModelSelection( + "codex", + DEFAULT_SERVER_SETTINGS.textGenerationModelSelection.model, + [ + { id: "reasoningEffort", value: "high" }, + { id: "fastMode", value: true }, + ], + ).options!, }, }); @@ -76,9 +99,7 @@ it.layer(NodeServices.layer)("server settings", (it) => { }, }, textGenerationModelSelection: { - options: { - fastMode: false, - }, + options: [{ id: "fastMode", value: false }], }, }); @@ -94,14 +115,13 @@ it.layer(NodeServices.layer)("server settings", (it) => { customModels: ["claude-custom"], launchArgs: "", }); - assert.deepEqual(next.textGenerationModelSelection, { - provider: "codex", - model: DEFAULT_SERVER_SETTINGS.textGenerationModelSelection.model, - options: { - reasoningEffort: "high", - fastMode: false, - }, - }); + assert.deepEqual( + next.textGenerationModelSelection, + createModelSelection("codex", DEFAULT_SERVER_SETTINGS.textGenerationModelSelection.model, [ + { id: "reasoningEffort", value: "high" }, + { id: "fastMode", value: false }, + ]), + ); }).pipe(Effect.provide(makeServerSettingsLayer())), ); @@ -114,9 +134,9 @@ it.layer(NodeServices.layer)("server settings", (it) => { textGenerationModelSelection: { provider: "claudeAgent", model: "claude-sonnet-4-6", - options: { - effort: "high", - }, + options: createModelSelection("claudeAgent", "claude-sonnet-4-6", [ + { id: "effort", value: "high" }, + ]).options!, }, }); @@ -126,19 +146,16 @@ it.layer(NodeServices.layer)("server settings", (it) => { textGenerationModelSelection: { provider: "codex", model: "gpt-5.4", - options: { - reasoningEffort: "high", - }, + options: createModelSelection("codex", "gpt-5.4", [ + { id: "reasoningEffort", value: "high" }, + ]).options!, }, }); - assert.deepEqual(next.textGenerationModelSelection, { - provider: "codex", - model: "gpt-5.4", - options: { - reasoningEffort: "high", - }, - }); + assert.deepEqual( + next.textGenerationModelSelection, + createModelSelection("codex", "gpt-5.4", [{ id: "reasoningEffort", value: "high" }]), + ); }).pipe(Effect.provide(makeServerSettingsLayer())), ); @@ -150,10 +167,14 @@ it.layer(NodeServices.layer)("server settings", (it) => { textGenerationModelSelection: { provider: "codex", model: DEFAULT_SERVER_SETTINGS.textGenerationModelSelection.model, - options: { - reasoningEffort: "high", - fastMode: true, - }, + options: createModelSelection( + "codex", + DEFAULT_SERVER_SETTINGS.textGenerationModelSelection.model, + [ + { id: "reasoningEffort", value: "high" }, + { id: "fastMode", value: true }, + ], + ).options!, }, }); diff --git a/apps/web/src/components/ChatView.browser.tsx b/apps/web/src/components/ChatView.browser.tsx index 6857a51b51..f5cc79b88a 100644 --- a/apps/web/src/components/ChatView.browser.tsx +++ b/apps/web/src/components/ChatView.browser.tsx @@ -18,6 +18,7 @@ import { DEFAULT_SERVER_SETTINGS, } from "@t3tools/contracts"; import { scopedThreadKey, scopeThreadRef } from "@t3tools/client-runtime"; +import { createModelCapabilities, createModelSelection } from "@t3tools/shared/model"; import { RouterProvider, createMemoryHistory } from "@tanstack/react-router"; import { HttpResponse, http, ws } from "msw"; import { setupWorker } from "msw/browser"; @@ -3777,14 +3778,10 @@ describe("ChatView timeline estimator parity (full app)", () => { it("snapshots sticky codex settings into a new draft thread", async () => { useComposerDraftStore.setState({ stickyModelSelectionByProvider: { - codex: { - provider: "codex", - model: "gpt-5.3-codex", - options: { - reasoningEffort: "medium", - fastMode: true, - }, - }, + codex: createModelSelection("codex", "gpt-5.3-codex", [ + { id: "reasoningEffort", value: "medium" }, + { id: "fastMode", value: true }, + ]), }, stickyActiveProvider: "codex", }); @@ -3810,14 +3807,16 @@ describe("ChatView timeline estimator parity (full app)", () => { ); const newDraftId = draftIdFromPath(newThreadPath); + // `toMatchObject` matches objects loosely (extras ignored) but compares + // arrays strictly, so wrap `options` in `arrayContaining` to keep the + // assertion focused on sticky `fastMode` carrying over without asserting + // on exactly which other options are preserved. expect(composerDraftFor(newDraftId)).toMatchObject({ modelSelectionByProvider: { codex: { provider: "codex", model: "gpt-5.3-codex", - options: { - fastMode: true, - }, + options: expect.arrayContaining([{ id: "fastMode", value: true }]), }, }, activeProvider: "codex", @@ -3830,14 +3829,10 @@ describe("ChatView timeline estimator parity (full app)", () => { it("hydrates the provider alongside a sticky claude model", async () => { useComposerDraftStore.setState({ stickyModelSelectionByProvider: { - claudeAgent: { - provider: "claudeAgent", - model: "claude-opus-4-6", - options: { - effort: "max", - fastMode: true, - }, - }, + claudeAgent: createModelSelection("claudeAgent", "claude-opus-4-6", [ + { id: "effort", value: "max" }, + { id: "fastMode", value: true }, + ]), }, stickyActiveProvider: "claudeAgent", }); @@ -3865,14 +3860,10 @@ describe("ChatView timeline estimator parity (full app)", () => { expect(composerDraftFor(newDraftId)).toMatchObject({ modelSelectionByProvider: { - claudeAgent: { - provider: "claudeAgent", - model: "claude-opus-4-6", - options: { - effort: "max", - fastMode: true, - }, - }, + claudeAgent: createModelSelection("claudeAgent", "claude-opus-4-6", [ + { id: "effort", value: "max" }, + { id: "fastMode", value: true }, + ]), }, activeProvider: "claudeAgent", }); @@ -3912,14 +3903,10 @@ describe("ChatView timeline estimator parity (full app)", () => { it("prefers draft state over sticky composer settings and defaults", async () => { useComposerDraftStore.setState({ stickyModelSelectionByProvider: { - codex: { - provider: "codex", - model: "gpt-5.3-codex", - options: { - reasoningEffort: "medium", - fastMode: true, - }, - }, + codex: createModelSelection("codex", "gpt-5.3-codex", [ + { id: "reasoningEffort", value: "medium" }, + { id: "fastMode", value: true }, + ]), }, stickyActiveProvider: "codex", }); @@ -3945,27 +3932,27 @@ describe("ChatView timeline estimator parity (full app)", () => { ); const draftId = draftIdFromPath(threadPath); + // See the note on the sibling sticky-codex test: arrays match strictly + // under `toMatchObject`, so use `arrayContaining` to keep the assertion + // scoped to the sticky trait (`fastMode`) that must carry over. expect(composerDraftFor(draftId)).toMatchObject({ modelSelectionByProvider: { codex: { provider: "codex", model: "gpt-5.3-codex", - options: { - fastMode: true, - }, + options: expect.arrayContaining([{ id: "fastMode", value: true }]), }, }, activeProvider: "codex", }); - useComposerDraftStore.getState().setModelSelection(draftId, { - provider: "codex", - model: "gpt-5.4", - options: { - reasoningEffort: "low", - fastMode: true, - }, - }); + useComposerDraftStore.getState().setModelSelection( + draftId, + createModelSelection("codex", "gpt-5.4", [ + { id: "reasoningEffort", value: "low" }, + { id: "fastMode", value: true }, + ]), + ); await newThreadButton.click(); @@ -3976,14 +3963,10 @@ describe("ChatView timeline estimator parity (full app)", () => { ); expect(composerDraftFor(draftId)).toMatchObject({ modelSelectionByProvider: { - codex: { - provider: "codex", - model: "gpt-5.4", - options: { - reasoningEffort: "low", - fastMode: true, - }, - }, + codex: createModelSelection("codex", "gpt-5.4", [ + { id: "reasoningEffort", value: "low" }, + { id: "fastMode", value: true }, + ]), }, activeProvider: "codex", }); @@ -5670,37 +5653,31 @@ describe("ChatView timeline estimator parity (full app)", () => { slug: "gpt-5.1-codex-max", name: "GPT-5.1 Codex Max", isCustom: false, - capabilities: { - supportsFastMode: true, - supportsThinkingToggle: false, - reasoningEffortLevels: [], - promptInjectedEffortLevels: [], - contextWindowOptions: [], - }, + capabilities: createModelCapabilities({ + optionDescriptors: [ + { id: "fastMode", label: "Fast Mode", type: "boolean" as const }, + ], + }), }, { slug: "gpt-5.3-codex", name: "GPT-5.3 Codex", isCustom: false, - capabilities: { - supportsFastMode: true, - supportsThinkingToggle: false, - reasoningEffortLevels: [], - promptInjectedEffortLevels: [], - contextWindowOptions: [], - }, + capabilities: createModelCapabilities({ + optionDescriptors: [ + { id: "fastMode", label: "Fast Mode", type: "boolean" as const }, + ], + }), }, { slug: "gpt-5.4", name: "GPT-5.4", isCustom: false, - capabilities: { - supportsFastMode: true, - supportsThinkingToggle: false, - reasoningEffortLevels: [], - promptInjectedEffortLevels: [], - contextWindowOptions: [], - }, + capabilities: createModelCapabilities({ + optionDescriptors: [ + { id: "fastMode", label: "Fast Mode", type: "boolean" as const }, + ], + }), }, ], }, diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsx index 0c76059b6a..3a71922706 100644 --- a/apps/web/src/components/ChatView.tsx +++ b/apps/web/src/components/ChatView.tsx @@ -1,7 +1,6 @@ import { type ApprovalRequestId, DEFAULT_MODEL_BY_PROVIDER, - type ClaudeAgentEffort, type EnvironmentId, type MessageId, type ModelSelection, @@ -26,7 +25,11 @@ import { scopeProjectRef, scopeThreadRef, } from "@t3tools/client-runtime"; -import { applyClaudePromptEffortPrefix, createModelSelection } from "@t3tools/shared/model"; +import { + applyClaudePromptEffortPrefix, + createModelSelection, + resolvePromptInjectedEffort, +} from "@t3tools/shared/model"; import { projectScriptCwd, projectScriptRuntimeEnv } from "@t3tools/shared/projectScripts"; import { truncate } from "@t3tools/shared/String"; import { Debouncer } from "@tanstack/react-pacer"; @@ -306,10 +309,8 @@ function formatOutgoingPrompt(params: { text: string; }): string { const caps = getProviderModelCapabilities(params.models, params.model, params.provider); - if (params.effort && caps.promptInjectedEffortLevels.includes(params.effort)) { - return applyClaudePromptEffortPrefix(params.text, params.effort as ClaudeAgentEffort | null); - } - return params.text; + const promptEffort = resolvePromptInjectedEffort(caps, params.effort); + return applyClaudePromptEffortPrefix(params.text, promptEffort); } const SCRIPT_TERMINAL_COLS = 120; const SCRIPT_TERMINAL_ROWS = 30; diff --git a/apps/web/src/components/chat/ChatComposer.tsx b/apps/web/src/components/chat/ChatComposer.tsx index 3d3b081af9..3b47b2067c 100644 --- a/apps/web/src/components/chat/ChatComposer.tsx +++ b/apps/web/src/components/chat/ChatComposer.tsx @@ -71,11 +71,10 @@ import { ComposerPlanFollowUpBanner } from "./ComposerPlanFollowUpBanner"; import { resolveComposerMenuActiveItemId } from "./composerMenuHighlight"; import { searchSlashCommandItems } from "./composerSlashCommandSearch"; import { - getComposerProviderControls, getComposerProviderState, renderProviderTraitsMenuContent, renderProviderTraitsPicker, -} from "./composerProviderRegistry"; +} from "./composerProviderState"; import { ContextWindowMeter } from "./ContextWindowMeter"; import { buildExpandedImagePreview, type ExpandedImagePreview } from "./ExpandedImagePreview"; import { basenameOfPath } from "../../vscode-icons"; @@ -96,7 +95,11 @@ import { XIcon, } from "lucide-react"; import { proposedPlanTitle } from "../../proposedPlan"; -import { resolveSelectableProvider, getProviderModels } from "../../providerModels"; +import { + getProviderInteractionModeToggle, + getProviderModels, + resolveSelectableProvider, +} from "../../providerModels"; import type { UnifiedSettings } from "@t3tools/contracts/settings"; import type { SessionPhase, Thread } from "../../types"; import type { PendingUserInputDraftAnswer } from "../../pendingUserInput"; @@ -595,7 +598,7 @@ export const ChatComposer = memo( model: selectedModel, models: selectedProviderModels, prompt, - modelOptions: composerModelOptions, + modelOptions: composerModelOptions?.[selectedProvider], }), [composerModelOptions, prompt, selectedModel, selectedProvider, selectedProviderModels], ); @@ -603,8 +606,13 @@ export const ChatComposer = memo( const selectedPromptEffort = composerProviderState.promptEffort; const selectedModelOptionsForDispatch = composerProviderState.modelOptionsForDispatch; const composerProviderControls = useMemo( - () => getComposerProviderControls(selectedProvider), - [selectedProvider], + () => ({ + showInteractionModeToggle: getProviderInteractionModeToggle( + providerStatuses, + selectedProvider, + ), + }), + [providerStatuses, selectedProvider], ); const selectedModelSelection = useMemo( () => createModelSelection(selectedProvider, selectedModel, selectedModelOptionsForDispatch), diff --git a/apps/web/src/components/chat/CompactComposerControlsMenu.browser.tsx b/apps/web/src/components/chat/CompactComposerControlsMenu.browser.tsx index 7619a63554..1808b94033 100644 --- a/apps/web/src/components/chat/CompactComposerControlsMenu.browser.tsx +++ b/apps/web/src/components/chat/CompactComposerControlsMenu.browser.tsx @@ -10,6 +10,7 @@ import "../../index.css"; import { page } from "vitest/browser"; import { afterEach, describe, expect, it, vi } from "vitest"; import { render } from "vitest-browser-react"; +import { createModelCapabilities, createModelSelection } from "@t3tools/shared/model"; import { CompactComposerControlsMenu } from "./CompactComposerControlsMenu"; import { TraitsMenuContent } from "./TraitsPicker"; @@ -17,6 +18,34 @@ import { useComposerDraftStore } from "../../composerDraftStore"; const LOCAL_ENVIRONMENT_ID = EnvironmentId.make("environment-local"); +function selectDescriptor( + id: string, + label: string, + options: ReadonlyArray<{ id: string; label: string; isDefault?: boolean }>, + promptInjectedValues?: ReadonlyArray, +) { + return { + id, + label, + type: "select" as const, + options: [...options], + ...(options.find((option) => option.isDefault)?.id + ? { currentValue: options.find((option) => option.isDefault)?.id } + : {}), + ...(promptInjectedValues && promptInjectedValues.length > 0 + ? { promptInjectedValues: [...promptInjectedValues] } + : {}), + }; +} + +function booleanDescriptor(id: string, label: string) { + return { + id, + label, + type: "boolean" as const, + }; +} + async function mountMenu(props?: { modelSelection?: ModelSelection; prompt?: string }) { const threadId = ThreadId.make("thread-compact-menu"); const threadRef = scopeThreadRef(LOCAL_ENVIRONMENT_ID, threadId); @@ -33,11 +62,7 @@ async function mountMenu(props?: { modelSelection?: ModelSelection; prompt?: str persistedAttachments: [], terminalContexts: [], modelSelectionByProvider: { - [provider]: { - provider, - model, - ...(props?.modelSelection?.options ? { options: props.modelSelection.options } : {}), - }, + [provider]: createModelSelection(provider, model, props?.modelSelection?.options), }, activeProvider: provider, runtimeMode: null, @@ -51,74 +76,58 @@ async function mountMenu(props?: { modelSelection?: ModelSelection; prompt?: str document.body.append(host); const onPromptChange = vi.fn(); const providerOptions = props?.modelSelection?.options; - const models = - provider === "claudeAgent" - ? [ - { - slug: "claude-opus-4-6", - name: "Claude Opus 4.6", - isCustom: false, - capabilities: { - reasoningEffortLevels: [ - { value: "low", label: "Low" }, - { value: "medium", label: "Medium" }, - { value: "high", label: "High", isDefault: true }, - { value: "max", label: "Max" }, - { value: "ultrathink", label: "Ultrathink" }, - ], - supportsFastMode: true, - supportsThinkingToggle: false, - contextWindowOptions: [], - promptInjectedEffortLevels: ["ultrathink"], - }, - }, - { - slug: "claude-haiku-4-5", - name: "Claude Haiku 4.5", - isCustom: false, - capabilities: { - reasoningEffortLevels: [], - supportsFastMode: false, - supportsThinkingToggle: true, - contextWindowOptions: [], - promptInjectedEffortLevels: [], - }, - }, - { - slug: "claude-sonnet-4-6", - name: "Claude Sonnet 4.6", - isCustom: false, - capabilities: { - reasoningEffortLevels: [ - { value: "low", label: "Low" }, - { value: "medium", label: "Medium" }, - { value: "high", label: "High", isDefault: true }, - { value: "ultrathink", label: "Ultrathink" }, - ], - supportsFastMode: false, - supportsThinkingToggle: false, - contextWindowOptions: [], - promptInjectedEffortLevels: ["ultrathink"], - }, - }, - ] - : [ - { - slug: "gpt-5.4", - name: "GPT-5.4", - isCustom: false, - capabilities: { - reasoningEffortLevels: [ - { value: "xhigh", label: "Extra High" }, - { value: "high", label: "High", isDefault: true }, - ], - supportsFastMode: true, - supportsThinkingToggle: false, - contextWindowOptions: [], - promptInjectedEffortLevels: [], - }, - }, - ]; + const models = [ + { + slug: "claude-opus-4-6", + name: "Claude Opus 4.6", + isCustom: false, + capabilities: createModelCapabilities({ + optionDescriptors: [ + selectDescriptor( + "effort", + "Reasoning", + [ + { id: "low", label: "Low" }, + { id: "medium", label: "Medium" }, + { id: "high", label: "High", isDefault: true }, + { id: "max", label: "Max" }, + { id: "ultrathink", label: "Ultrathink" }, + ], + ["ultrathink"], + ), + booleanDescriptor("fastMode", "Fast Mode"), + ], + }), + }, + { + slug: "claude-haiku-4-5", + name: "Claude Haiku 4.5", + isCustom: false, + capabilities: createModelCapabilities({ + optionDescriptors: [booleanDescriptor("thinking", "Thinking")], + }), + }, + { + slug: "claude-sonnet-4-6", + name: "Claude Sonnet 4.6", + isCustom: false, + capabilities: createModelCapabilities({ + optionDescriptors: [ + selectDescriptor( + "effort", + "Reasoning", + [ + { id: "low", label: "Low" }, + { id: "medium", label: "Medium" }, + { id: "high", label: "High", isDefault: true }, + { id: "ultrathink", label: "Ultrathink" }, + ], + ["ultrathink"], + ), + ], + }), + }, + ]; const screen = await render( { it("shows fast mode controls for Opus", async () => { await using _ = await mountMenu({ - modelSelection: { provider: "claudeAgent", model: "claude-opus-4-6" }, + modelSelection: createModelSelection("claudeAgent", "claude-opus-4-6"), }); await page.getByLabelText("More composer controls").click(); @@ -177,14 +186,14 @@ describe("CompactComposerControlsMenu", () => { await vi.waitFor(() => { const text = document.body.textContent ?? ""; expect(text).toContain("Fast Mode"); - expect(text).toContain("off"); - expect(text).toContain("on"); + expect(text).toContain("On"); + expect(text).toContain("Off"); }); }); it("hides fast mode controls for non-Opus Claude models", async () => { await using _ = await mountMenu({ - modelSelection: { provider: "claudeAgent", model: "claude-sonnet-4-6" }, + modelSelection: createModelSelection("claudeAgent", "claude-sonnet-4-6"), }); await page.getByLabelText("More composer controls").click(); @@ -196,7 +205,7 @@ describe("CompactComposerControlsMenu", () => { it("shows only the provided effort options", async () => { await using _ = await mountMenu({ - modelSelection: { provider: "claudeAgent", model: "claude-sonnet-4-6" }, + modelSelection: createModelSelection("claudeAgent", "claude-sonnet-4-6"), }); await page.getByLabelText("More composer controls").click(); @@ -213,11 +222,9 @@ describe("CompactComposerControlsMenu", () => { it("shows a Claude thinking on/off section for Haiku", async () => { await using _ = await mountMenu({ - modelSelection: { - provider: "claudeAgent", - model: "claude-haiku-4-5", - options: { thinking: true }, - }, + modelSelection: createModelSelection("claudeAgent", "claude-haiku-4-5", [ + { id: "thinking", value: true }, + ]), }); await page.getByLabelText("More composer controls").click(); @@ -225,18 +232,16 @@ describe("CompactComposerControlsMenu", () => { await vi.waitFor(() => { const text = document.body.textContent ?? ""; expect(text).toContain("Thinking"); - expect(text).toContain("On (default)"); + expect(text).toContain("On"); expect(text).toContain("Off"); }); }); it("shows prompt-controlled Ultrathink state with selectable effort controls", async () => { await using _ = await mountMenu({ - modelSelection: { - provider: "claudeAgent", - model: "claude-opus-4-6", - options: { effort: "high" }, - }, + modelSelection: createModelSelection("claudeAgent", "claude-opus-4-6", [ + { id: "effort", value: "high" }, + ]), prompt: "Ultrathink:\nInvestigate this", }); @@ -244,18 +249,16 @@ describe("CompactComposerControlsMenu", () => { await vi.waitFor(() => { const text = document.body.textContent ?? ""; - expect(text).toContain("Effort"); + expect(text).toContain("Reasoning"); expect(text).not.toContain("ultrathink"); }); }); it("warns when ultrathink appears in prompt body text", async () => { await using _ = await mountMenu({ - modelSelection: { - provider: "claudeAgent", - model: "claude-opus-4-6", - options: { effort: "high" }, - }, + modelSelection: createModelSelection("claudeAgent", "claude-opus-4-6", [ + { id: "effort", value: "high" }, + ]), prompt: "Ultrathink:\nplease ultrathink about this problem", }); @@ -264,7 +267,7 @@ describe("CompactComposerControlsMenu", () => { await vi.waitFor(() => { const text = document.body.textContent ?? ""; expect(text).toContain( - 'Your prompt contains "ultrathink" in the text. Remove it to change effort.', + 'Your prompt contains "ultrathink" in the text. Remove it to change this option.', ); }); }); diff --git a/apps/web/src/components/chat/ProviderModelPicker.browser.tsx b/apps/web/src/components/chat/ProviderModelPicker.browser.tsx index f4854dd9a6..a5f539ae5a 100644 --- a/apps/web/src/components/chat/ProviderModelPicker.browser.tsx +++ b/apps/web/src/components/chat/ProviderModelPicker.browser.tsx @@ -1,5 +1,6 @@ import { type ProviderKind, type ServerProvider } from "@t3tools/contracts"; import { EnvironmentId } from "@t3tools/contracts"; +import { createModelCapabilities } from "@t3tools/shared/model"; import { page, userEvent } from "vitest/browser"; import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import { render } from "vitest-browser-react"; @@ -66,17 +67,34 @@ vi.mock("../../environments/runtime", () => { }; }); -function effort(value: string, isDefault = false) { +function selectDescriptor( + id: string, + label: string, + options: ReadonlyArray<{ id: string; label: string; isDefault?: boolean }>, +) { return { - value, - label: value, - ...(isDefault ? { isDefault: true } : {}), + id, + label, + type: "select" as const, + options: [...options], + ...(options.find((option) => option.isDefault)?.id + ? { currentValue: options.find((option) => option.isDefault)?.id } + : {}), + }; +} + +function booleanDescriptor(id: string, label: string) { + return { + id, + label, + type: "boolean" as const, }; } const TEST_PROVIDERS: ReadonlyArray = [ { provider: "codex", + displayName: "Codex", enabled: true, installed: true, version: "0.116.0", @@ -90,30 +108,37 @@ const TEST_PROVIDERS: ReadonlyArray = [ slug: "gpt-5-codex", name: "GPT-5 Codex", isCustom: false, - capabilities: { - reasoningEffortLevels: [effort("low"), effort("medium", true), effort("high")], - supportsFastMode: true, - supportsThinkingToggle: false, - contextWindowOptions: [], - promptInjectedEffortLevels: [], - }, + capabilities: createModelCapabilities({ + optionDescriptors: [ + selectDescriptor("reasoningEffort", "Reasoning", [ + { id: "low", label: "low" }, + { id: "medium", label: "medium", isDefault: true }, + { id: "high", label: "high" }, + ]), + booleanDescriptor("fastMode", "Fast Mode"), + ], + }), }, { slug: "gpt-5.3-codex", name: "GPT-5.3 Codex", isCustom: false, - capabilities: { - reasoningEffortLevels: [effort("low"), effort("medium", true), effort("high")], - supportsFastMode: true, - supportsThinkingToggle: false, - contextWindowOptions: [], - promptInjectedEffortLevels: [], - }, + capabilities: createModelCapabilities({ + optionDescriptors: [ + selectDescriptor("reasoningEffort", "Reasoning", [ + { id: "low", label: "low" }, + { id: "medium", label: "medium", isDefault: true }, + { id: "high", label: "high" }, + ]), + booleanDescriptor("fastMode", "Fast Mode"), + ], + }), }, ], }, { provider: "claudeAgent", + displayName: "Claude", enabled: true, installed: true, version: "1.0.0", @@ -127,47 +152,48 @@ const TEST_PROVIDERS: ReadonlyArray = [ slug: "claude-opus-4-6", name: "Claude Opus 4.6", isCustom: false, - capabilities: { - reasoningEffortLevels: [ - effort("low"), - effort("medium", true), - effort("high"), - effort("max"), + capabilities: createModelCapabilities({ + optionDescriptors: [ + selectDescriptor("effort", "Reasoning", [ + { id: "low", label: "low" }, + { id: "medium", label: "medium", isDefault: true }, + { id: "high", label: "high" }, + { id: "max", label: "max" }, + ]), + booleanDescriptor("thinking", "Thinking"), ], - supportsFastMode: false, - supportsThinkingToggle: true, - contextWindowOptions: [], - promptInjectedEffortLevels: [], - }, + }), }, { slug: "claude-sonnet-4-6", name: "Claude Sonnet 4.6", isCustom: false, - capabilities: { - reasoningEffortLevels: [ - effort("low"), - effort("medium", true), - effort("high"), - effort("max"), + capabilities: createModelCapabilities({ + optionDescriptors: [ + selectDescriptor("effort", "Reasoning", [ + { id: "low", label: "low" }, + { id: "medium", label: "medium", isDefault: true }, + { id: "high", label: "high" }, + { id: "max", label: "max" }, + ]), + booleanDescriptor("thinking", "Thinking"), ], - supportsFastMode: false, - supportsThinkingToggle: true, - contextWindowOptions: [], - promptInjectedEffortLevels: [], - }, + }), }, { slug: "claude-haiku-4-5", name: "Claude Haiku 4.5", isCustom: false, - capabilities: { - reasoningEffortLevels: [effort("low"), effort("medium", true), effort("high")], - supportsFastMode: false, - supportsThinkingToggle: true, - contextWindowOptions: [], - promptInjectedEffortLevels: [], - }, + capabilities: createModelCapabilities({ + optionDescriptors: [ + selectDescriptor("effort", "Reasoning", [ + { id: "low", label: "low" }, + { id: "medium", label: "medium", isDefault: true }, + { id: "high", label: "high" }, + ]), + booleanDescriptor("thinking", "Thinking"), + ], + }), }, ], }, @@ -176,6 +202,7 @@ const TEST_PROVIDERS: ReadonlyArray = [ function buildCodexProvider(models: ServerProvider["models"]): ServerProvider { return { provider: "codex", + displayName: "Codex", enabled: true, installed: true, version: "0.116.0", @@ -464,13 +491,15 @@ describe("ProviderModelPicker", () => { subProvider: "GitHub Copilot", shortName: "Opus 4.5", isCustom: false, - capabilities: { - reasoningEffortLevels: [effort("low"), effort("medium", true), effort("high")], - supportsFastMode: false, - supportsThinkingToggle: false, - contextWindowOptions: [], - promptInjectedEffortLevels: [], - }, + capabilities: createModelCapabilities({ + optionDescriptors: [ + selectDescriptor("reasoningEffort", "Reasoning", [ + { id: "low", label: "low" }, + { id: "medium", label: "medium", isDefault: true }, + { id: "high", label: "high" }, + ]), + ], + }), }, ]), ]; @@ -658,13 +687,16 @@ describe("ProviderModelPicker", () => { slug: "gpt-5-codex", name: "GPT-5 Codex", isCustom: false, - capabilities: { - reasoningEffortLevels: [effort("low"), effort("medium", true), effort("high")], - supportsFastMode: true, - supportsThinkingToggle: false, - contextWindowOptions: [], - promptInjectedEffortLevels: [], - }, + capabilities: createModelCapabilities({ + optionDescriptors: [ + selectDescriptor("reasoningEffort", "Reasoning", [ + { id: "low", label: "low" }, + { id: "medium", label: "medium", isDefault: true }, + { id: "high", label: "high" }, + ]), + booleanDescriptor("fastMode", "Fast Mode"), + ], + }), }, ]), buildOpenCodeProvider([ @@ -673,13 +705,15 @@ describe("ProviderModelPicker", () => { name: "Claude Opus 4.7", subProvider: "GitHub Copilot", isCustom: false, - capabilities: { - reasoningEffortLevels: [effort("low"), effort("medium", true), effort("high")], - supportsFastMode: false, - supportsThinkingToggle: false, - contextWindowOptions: [], - promptInjectedEffortLevels: [], - }, + capabilities: createModelCapabilities({ + optionDescriptors: [ + selectDescriptor("reasoningEffort", "Reasoning", [ + { id: "low", label: "low" }, + { id: "medium", label: "medium", isDefault: true }, + { id: "high", label: "high" }, + ]), + ], + }), }, ]), ]; @@ -712,13 +746,15 @@ describe("ProviderModelPicker", () => { name: "Claude Opus 4.7", subProvider: "GitHub Copilot", isCustom: false, - capabilities: { - reasoningEffortLevels: [effort("low"), effort("medium", true), effort("high")], - supportsFastMode: false, - supportsThinkingToggle: false, - contextWindowOptions: [], - promptInjectedEffortLevels: [], - }, + capabilities: createModelCapabilities({ + optionDescriptors: [ + selectDescriptor("reasoningEffort", "Reasoning", [ + { id: "low", label: "low" }, + { id: "medium", label: "medium", isDefault: true }, + { id: "high", label: "high" }, + ]), + ], + }), }, ]), { @@ -728,18 +764,17 @@ describe("ProviderModelPicker", () => { slug: "claude-opus-4-6", name: "Claude Opus 4.6", isCustom: false, - capabilities: { - reasoningEffortLevels: [ - effort("low"), - effort("medium", true), - effort("high"), - effort("max"), + capabilities: createModelCapabilities({ + optionDescriptors: [ + selectDescriptor("effort", "Reasoning", [ + { id: "low", label: "low" }, + { id: "medium", label: "medium", isDefault: true }, + { id: "high", label: "high" }, + { id: "max", label: "max" }, + ]), + booleanDescriptor("thinking", "Thinking"), ], - supportsFastMode: false, - supportsThinkingToggle: true, - contextWindowOptions: [], - promptInjectedEffortLevels: [], - }, + }), }, ], }, @@ -909,13 +944,16 @@ describe("ProviderModelPicker", () => { slug: "gpt-5.3-codex", name: "GPT-5.3 Codex", isCustom: false, - capabilities: { - reasoningEffortLevels: [effort("low"), effort("medium", true), effort("high")], - supportsFastMode: true, - supportsThinkingToggle: false, - contextWindowOptions: [], - promptInjectedEffortLevels: [], - }, + capabilities: createModelCapabilities({ + optionDescriptors: [ + selectDescriptor("reasoningEffort", "Reasoning", [ + { id: "low", label: "low" }, + { id: "medium", label: "medium", isDefault: true }, + { id: "high", label: "high" }, + ]), + booleanDescriptor("fastMode", "Fast Mode"), + ], + }), }, ]), TEST_PROVIDERS[1]!, @@ -926,25 +964,31 @@ describe("ProviderModelPicker", () => { slug: "gpt-5.3-codex", name: "GPT-5.3 Codex", isCustom: false, - capabilities: { - reasoningEffortLevels: [effort("low"), effort("medium", true), effort("high")], - supportsFastMode: true, - supportsThinkingToggle: false, - contextWindowOptions: [], - promptInjectedEffortLevels: [], - }, + capabilities: createModelCapabilities({ + optionDescriptors: [ + selectDescriptor("reasoningEffort", "Reasoning", [ + { id: "low", label: "low" }, + { id: "medium", label: "medium", isDefault: true }, + { id: "high", label: "high" }, + ]), + booleanDescriptor("fastMode", "Fast Mode"), + ], + }), }, { slug: "gpt-5.3-codex-spark", name: "GPT-5.3 Codex Spark", isCustom: false, - capabilities: { - reasoningEffortLevels: [effort("low"), effort("medium", true), effort("high")], - supportsFastMode: true, - supportsThinkingToggle: false, - contextWindowOptions: [], - promptInjectedEffortLevels: [], - }, + capabilities: createModelCapabilities({ + optionDescriptors: [ + selectDescriptor("reasoningEffort", "Reasoning", [ + { id: "low", label: "low" }, + { id: "medium", label: "medium", isDefault: true }, + { id: "high", label: "high" }, + ]), + booleanDescriptor("fastMode", "Fast Mode"), + ], + }), }, ]), TEST_PROVIDERS[1]!, diff --git a/apps/web/src/components/chat/ProviderStatusBanner.tsx b/apps/web/src/components/chat/ProviderStatusBanner.tsx index e709e75da3..5eaacafe05 100644 --- a/apps/web/src/components/chat/ProviderStatusBanner.tsx +++ b/apps/web/src/components/chat/ProviderStatusBanner.tsx @@ -1,7 +1,8 @@ -import { PROVIDER_DISPLAY_NAMES, type ServerProvider } from "@t3tools/contracts"; +import { type ServerProvider } from "@t3tools/contracts"; import { memo } from "react"; import { Alert, AlertDescription, AlertTitle } from "../ui/alert"; import { CircleAlertIcon } from "lucide-react"; +import { formatProviderKindLabel } from "../../providerModels"; export const ProviderStatusBanner = memo(function ProviderStatusBanner({ status, @@ -12,7 +13,7 @@ export const ProviderStatusBanner = memo(function ProviderStatusBanner({ return null; } - const providerLabel = PROVIDER_DISPLAY_NAMES[status.provider] ?? status.provider; + const providerLabel = status.displayName?.trim() || formatProviderKindLabel(status.provider); const defaultMessage = status.status === "error" ? `${providerLabel} provider is unavailable.` diff --git a/apps/web/src/components/chat/TraitsPicker.browser.tsx b/apps/web/src/components/chat/TraitsPicker.browser.tsx deleted file mode 100644 index dbfbf09287..0000000000 --- a/apps/web/src/components/chat/TraitsPicker.browser.tsx +++ /dev/null @@ -1,821 +0,0 @@ -import "../../index.css"; - -import { - type ModelSelection, - ClaudeModelOptions, - CodexModelOptions, - CursorModelOptions, - DEFAULT_MODEL_BY_PROVIDER, - DEFAULT_SERVER_SETTINGS, - OpenCodeModelOptions, - EnvironmentId, - type ServerProvider, - ThreadId, -} from "@t3tools/contracts"; -import { scopedThreadKey, scopeThreadRef } from "@t3tools/client-runtime"; -import { page } from "vitest/browser"; -import { useCallback } from "react"; -import { afterEach, describe, expect, it, vi } from "vitest"; -import { render } from "vitest-browser-react"; - -import { TraitsPicker } from "./TraitsPicker"; -import { - COMPOSER_DRAFT_STORAGE_KEY, - ComposerThreadDraftState, - useComposerDraftStore, - useComposerThreadDraft, - useEffectiveComposerModelState, -} from "../../composerDraftStore"; -import { DEFAULT_CLIENT_SETTINGS } from "@t3tools/contracts/settings"; - -// ── Claude TraitsPicker tests ───────────────────────────────────────── - -const LOCAL_ENVIRONMENT_ID = EnvironmentId.make("environment-local"); -const CLAUDE_THREAD_ID = ThreadId.make("thread-claude-traits"); -const CLAUDE_THREAD_REF = scopeThreadRef(LOCAL_ENVIRONMENT_ID, CLAUDE_THREAD_ID); -const CLAUDE_THREAD_KEY = scopedThreadKey(CLAUDE_THREAD_REF); -const CODEX_THREAD_ID = ThreadId.make("thread-codex-traits"); -const CODEX_THREAD_REF = scopeThreadRef(LOCAL_ENVIRONMENT_ID, CODEX_THREAD_ID); -const CODEX_THREAD_KEY = scopedThreadKey(CODEX_THREAD_REF); -const TEST_PROVIDERS: ReadonlyArray = [ - { - provider: "codex", - enabled: true, - installed: true, - version: "0.1.0", - status: "ready", - auth: { status: "authenticated" }, - checkedAt: "2026-01-01T00:00:00.000Z", - slashCommands: [], - skills: [], - models: [ - { - slug: "gpt-5.4", - name: "GPT-5.4", - isCustom: false, - capabilities: { - reasoningEffortLevels: [ - { value: "xhigh", label: "Extra High" }, - { value: "high", label: "High", isDefault: true }, - ], - supportsFastMode: true, - supportsThinkingToggle: false, - contextWindowOptions: [], - promptInjectedEffortLevels: [], - }, - }, - ], - }, - { - provider: "opencode", - enabled: true, - installed: true, - version: "0.1.0", - status: "ready", - auth: { status: "authenticated" }, - checkedAt: "2026-01-01T00:00:00.000Z", - slashCommands: [], - skills: [], - models: [ - { - slug: "openai/gpt-5", - name: "GPT-5", - isCustom: false, - capabilities: { - reasoningEffortLevels: [], - supportsFastMode: false, - supportsThinkingToggle: false, - contextWindowOptions: [], - promptInjectedEffortLevels: [], - variantOptions: [ - { value: "low", label: "Low" }, - { value: "medium", label: "Medium", isDefault: true }, - ], - agentOptions: [ - { value: "build", label: "Build", isDefault: true }, - { value: "plan", label: "Plan" }, - ], - }, - }, - ], - }, - { - provider: "claudeAgent", - enabled: true, - installed: true, - version: "0.1.0", - status: "ready", - auth: { status: "authenticated" }, - checkedAt: "2026-01-01T00:00:00.000Z", - slashCommands: [], - skills: [], - models: [ - { - slug: "claude-opus-4-6", - name: "Claude Opus 4.6", - isCustom: false, - capabilities: { - reasoningEffortLevels: [ - { value: "low", label: "Low" }, - { value: "medium", label: "Medium" }, - { value: "high", label: "High", isDefault: true }, - { value: "max", label: "Max" }, - { value: "ultrathink", label: "Ultrathink" }, - ], - supportsFastMode: true, - supportsThinkingToggle: false, - contextWindowOptions: [], - promptInjectedEffortLevels: ["ultrathink"], - }, - }, - { - slug: "claude-sonnet-4-6", - name: "Claude Sonnet 4.6", - isCustom: false, - capabilities: { - reasoningEffortLevels: [ - { value: "low", label: "Low" }, - { value: "medium", label: "Medium" }, - { value: "high", label: "High", isDefault: true }, - { value: "ultrathink", label: "Ultrathink" }, - ], - supportsFastMode: false, - supportsThinkingToggle: false, - contextWindowOptions: [], - promptInjectedEffortLevels: ["ultrathink"], - }, - }, - { - slug: "claude-haiku-4-5", - name: "Claude Haiku 4.5", - isCustom: false, - capabilities: { - reasoningEffortLevels: [], - supportsFastMode: false, - supportsThinkingToggle: true, - contextWindowOptions: [], - promptInjectedEffortLevels: [], - }, - }, - ], - }, -]; -const findTestProvider = (provider: ServerProvider["provider"]) => { - const testProvider = TEST_PROVIDERS.find((candidate) => candidate.provider === provider); - if (!testProvider) { - throw new Error(`Missing test provider fixture: ${provider}`); - } - return testProvider; -}; - -function ClaudeTraitsPickerHarness(props: { - model: string; - fallbackModelSelection: ModelSelection | null; - triggerVariant?: "ghost" | "outline"; -}) { - const prompt = useComposerThreadDraft(CLAUDE_THREAD_REF).prompt; - const setPrompt = useComposerDraftStore((store) => store.setPrompt); - const { modelOptions, selectedModel } = useEffectiveComposerModelState({ - threadRef: CLAUDE_THREAD_REF, - providers: TEST_PROVIDERS, - selectedProvider: "claudeAgent", - threadModelSelection: props.fallbackModelSelection, - projectModelSelection: null, - settings: { - ...DEFAULT_SERVER_SETTINGS, - ...DEFAULT_CLIENT_SETTINGS, - }, - }); - const handlePromptChange = useCallback( - (nextPrompt: string) => { - setPrompt(CLAUDE_THREAD_REF, nextPrompt); - }, - [setPrompt], - ); - - return ( - - ); -} - -async function mountClaudePicker(props?: { - model?: string; - prompt?: string; - options?: ClaudeModelOptions; - fallbackModelOptions?: { - effort?: "low" | "medium" | "high" | "max" | "ultrathink"; - thinking?: boolean; - fastMode?: boolean; - } | null; - skipDraftModelOptions?: boolean; - triggerVariant?: "ghost" | "outline"; -}) { - const model = props?.model ?? "claude-opus-4-6"; - const claudeOptions = !props?.skipDraftModelOptions ? props?.options : undefined; - const draftsByThreadKey: Record = { - [CLAUDE_THREAD_KEY]: { - prompt: props?.prompt ?? "", - images: [], - nonPersistedImageIds: [], - persistedAttachments: [], - terminalContexts: [], - modelSelectionByProvider: props?.skipDraftModelOptions - ? {} - : { - claudeAgent: { - provider: "claudeAgent", - model, - ...(claudeOptions && Object.keys(claudeOptions).length > 0 - ? { options: claudeOptions } - : {}), - }, - }, - activeProvider: "claudeAgent", - runtimeMode: null, - interactionMode: null, - }, - }; - useComposerDraftStore.setState({ - draftsByThreadKey, - draftThreadsByThreadKey: {}, - logicalProjectDraftThreadKeyByLogicalProjectKey: {}, - }); - const host = document.createElement("div"); - document.body.append(host); - const fallbackModelSelection = - props?.fallbackModelOptions !== undefined - ? ({ - provider: "claudeAgent", - model, - ...(props.fallbackModelOptions ? { options: props.fallbackModelOptions } : {}), - } satisfies ModelSelection) - : null; - const screen = await render( - , - { container: host }, - ); - - const cleanup = async () => { - await screen.unmount(); - host.remove(); - }; - - return { - [Symbol.asyncDispose]: cleanup, - cleanup, - }; -} - -describe("TraitsPicker (Claude)", () => { - afterEach(() => { - document.body.innerHTML = ""; - useComposerDraftStore.setState({ - draftsByThreadKey: {}, - draftThreadsByThreadKey: {}, - logicalProjectDraftThreadKeyByLogicalProjectKey: {}, - stickyModelSelectionByProvider: {}, - }); - }); - - it("shows fast mode controls for Opus", async () => { - await using _ = await mountClaudePicker(); - - await page.getByRole("button").click(); - - await vi.waitFor(() => { - const text = document.body.textContent ?? ""; - expect(text).toContain("Fast Mode"); - expect(text).toContain("off"); - expect(text).toContain("on"); - }); - }); - - it("hides fast mode controls for non-Opus models", async () => { - await using _ = await mountClaudePicker({ model: "claude-sonnet-4-6" }); - - await page.getByRole("button").click(); - - await vi.waitFor(() => { - expect(document.body.textContent ?? "").not.toContain("Fast Mode"); - }); - }); - - it("shows only the provided effort options", async () => { - await using _ = await mountClaudePicker({ - model: "claude-sonnet-4-6", - }); - - await page.getByRole("button").click(); - - await vi.waitFor(() => { - const text = document.body.textContent ?? ""; - expect(text).toContain("Low"); - expect(text).toContain("Medium"); - expect(text).toContain("High"); - expect(text).not.toContain("Max"); - expect(text).toContain("Ultrathink"); - }); - }); - - it("shows a th inking on/off dropdown for Haiku", async () => { - await using _ = await mountClaudePicker({ - model: "claude-haiku-4-5", - options: { thinking: true }, - }); - - await vi.waitFor(() => { - expect(document.body.textContent ?? "").toContain("Thinking On"); - }); - await page.getByRole("button").click(); - - await vi.waitFor(() => { - const text = document.body.textContent ?? ""; - expect(text).toContain("Thinking"); - expect(text).toContain("On (default)"); - expect(text).toContain("Off"); - }); - }); - - it("shows prompt-controlled Ultrathink state with selectable effort controls", async () => { - await using _ = await mountClaudePicker({ - model: "claude-opus-4-6", - options: { effort: "high" }, - prompt: "Ultrathink:\nInvestigate this", - }); - - await vi.waitFor(() => { - expect(document.body.textContent ?? "").toContain("Ultrathink"); - expect(document.body.textContent ?? "").not.toContain("Ultrathink · Prompt"); - }); - await page.getByRole("button").click(); - - await vi.waitFor(() => { - const text = document.body.textContent ?? ""; - expect(text).toContain("Effort"); - expect(text).not.toContain("ultrathink"); - }); - }); - - it("warns when ultrathink appears in prompt body text", async () => { - await using _ = await mountClaudePicker({ - model: "claude-opus-4-6", - options: { effort: "high" }, - prompt: "Ultrathink:\nplease ultrathink about this problem", - }); - - await page.getByRole("button").click(); - - await vi.waitFor(() => { - const text = document.body.textContent ?? ""; - expect(text).toContain( - 'Your prompt contains "ultrathink" in the text. Remove it to change effort.', - ); - }); - }); - - it("persists sticky claude model options when traits change", async () => { - await using _ = await mountClaudePicker({ - model: "claude-opus-4-6", - options: { effort: "medium", fastMode: false }, - }); - - await page.getByRole("button").click(); - await page.getByRole("menuitemradio", { name: "Max" }).click(); - - expect( - useComposerDraftStore.getState().stickyModelSelectionByProvider.claudeAgent, - ).toMatchObject({ - provider: "claudeAgent", - options: { - effort: "max", - }, - }); - }); - - it("accepts outline trigger styling", async () => { - await using _ = await mountClaudePicker({ - triggerVariant: "outline", - }); - - const button = document.querySelector("button"); - if (!(button instanceof HTMLButtonElement)) { - throw new Error("Expected traits trigger button to be rendered."); - } - expect(button.className).toContain("border-input"); - expect(button.className).toContain("bg-popover"); - }); -}); - -// ── Codex TraitsPicker tests ────────────────────────────────────────── - -async function mountCodexPicker(props: { model?: string; options?: CodexModelOptions }) { - const model = props.model ?? DEFAULT_MODEL_BY_PROVIDER.codex; - const draftsByThreadKey: Record = { - [CODEX_THREAD_KEY]: { - prompt: "", - images: [], - nonPersistedImageIds: [], - persistedAttachments: [], - terminalContexts: [], - modelSelectionByProvider: { - codex: { - provider: "codex", - model, - ...(props.options ? { options: props.options } : {}), - }, - }, - activeProvider: "codex", - runtimeMode: null, - interactionMode: null, - }, - }; - - useComposerDraftStore.setState({ - draftsByThreadKey, - draftThreadsByThreadKey: {}, - logicalProjectDraftThreadKeyByLogicalProjectKey: { - "environment-local:project-codex-traits": CODEX_THREAD_KEY, - }, - }); - const host = document.createElement("div"); - document.body.append(host); - const screen = await render( - {}} - />, - { container: host }, - ); - - const cleanup = async () => { - await screen.unmount(); - host.remove(); - }; - - return { - [Symbol.asyncDispose]: cleanup, - cleanup, - }; -} - -async function mountCursorPicker(props: { model?: string; options?: CursorModelOptions }) { - const model = props.model ?? DEFAULT_MODEL_BY_PROVIDER.cursor; - const cursorThreadId = ThreadId.make("thread-cursor-traits"); - const cursorThreadRef = scopeThreadRef(LOCAL_ENVIRONMENT_ID, cursorThreadId); - const cursorThreadKey = scopedThreadKey(cursorThreadRef); - const host = document.createElement("div"); - document.body.append(host); - - useComposerDraftStore.setState({ - draftsByThreadKey: { - [cursorThreadKey]: { - prompt: "", - images: [], - nonPersistedImageIds: [], - persistedAttachments: [], - terminalContexts: [], - modelSelectionByProvider: { - cursor: { - provider: "cursor", - model, - ...(props.options ? { options: props.options } : {}), - }, - }, - activeProvider: "cursor", - runtimeMode: null, - interactionMode: null, - }, - }, - draftThreadsByThreadKey: {}, - logicalProjectDraftThreadKeyByLogicalProjectKey: {}, - }); - - const screen = await render( - {}} - />, - { container: host }, - ); - - const cleanup = async () => { - await screen.unmount(); - host.remove(); - }; - - return { - [Symbol.asyncDispose]: cleanup, - cleanup, - }; -} - -describe("TraitsPicker (Codex)", () => { - afterEach(() => { - document.body.innerHTML = ""; - localStorage.removeItem(COMPOSER_DRAFT_STORAGE_KEY); - useComposerDraftStore.setState({ - draftsByThreadKey: {}, - draftThreadsByThreadKey: {}, - logicalProjectDraftThreadKeyByLogicalProjectKey: {}, - stickyModelSelectionByProvider: {}, - }); - }); - - it("shows fast mode controls", async () => { - await using _ = await mountCodexPicker({ - options: { fastMode: false }, - }); - - await page.getByRole("button").click(); - - await vi.waitFor(() => { - const text = document.body.textContent ?? ""; - expect(text).toContain("Fast Mode"); - expect(text).toContain("off"); - expect(text).toContain("on"); - }); - }); - - it("shows Fast in the trigger label when fast mode is active", async () => { - await using _ = await mountCodexPicker({ - options: { fastMode: true }, - }); - - await vi.waitFor(() => { - expect(document.body.textContent ?? "").toContain("High · Fast"); - }); - }); - - it("shows only the provided effort options", async () => { - await using _ = await mountCodexPicker({ - options: { fastMode: false }, - }); - - await page.getByRole("button").click(); - - await vi.waitFor(() => { - const text = document.body.textContent ?? ""; - expect(text).toContain("Extra High"); - expect(text).toContain("High"); - expect(text).not.toContain("Low"); - expect(text).not.toContain("Medium"); - }); - }); - - it("persists sticky codex model options when traits change", async () => { - await using _ = await mountCodexPicker({ - options: { fastMode: false }, - }); - - await page.getByRole("button").click(); - await page.getByRole("menuitemradio", { name: "on" }).click(); - - expect(useComposerDraftStore.getState().stickyModelSelectionByProvider.codex).toMatchObject({ - provider: "codex", - options: { fastMode: true }, - }); - }); -}); - -// ── OpenCode TraitsPicker tests ─────────────────────────────────────── - -async function mountOpenCodePicker(props: { - model?: string; - options?: OpenCodeModelOptions; - models?: ServerProvider["models"]; -}) { - const threadId = ThreadId.make("thread-opencode-traits"); - const threadRef = scopeThreadRef(LOCAL_ENVIRONMENT_ID, threadId); - const threadKey = scopedThreadKey(threadRef); - const model = props.model ?? DEFAULT_MODEL_BY_PROVIDER.opencode; - const draftsByThreadKey: Record = { - [threadKey]: { - prompt: "", - images: [], - nonPersistedImageIds: [], - persistedAttachments: [], - terminalContexts: [], - modelSelectionByProvider: { - opencode: { - provider: "opencode", - model, - ...(props.options ? { options: props.options } : {}), - }, - }, - activeProvider: "opencode", - runtimeMode: null, - interactionMode: null, - }, - }; - - useComposerDraftStore.setState({ - draftsByThreadKey, - draftThreadsByThreadKey: {}, - logicalProjectDraftThreadKeyByLogicalProjectKey: {}, - }); - const host = document.createElement("div"); - document.body.append(host); - const screen = await render( - {}} - />, - { container: host }, - ); - - const cleanup = async () => { - await screen.unmount(); - host.remove(); - }; - - return { - [Symbol.asyncDispose]: cleanup, - cleanup, - }; -} - -describe("TraitsPicker (OpenCode)", () => { - afterEach(() => { - document.body.innerHTML = ""; - localStorage.removeItem(COMPOSER_DRAFT_STORAGE_KEY); - useComposerDraftStore.setState({ - draftsByThreadKey: {}, - draftThreadsByThreadKey: {}, - logicalProjectDraftThreadKeyByLogicalProjectKey: {}, - stickyModelSelectionByProvider: {}, - }); - }); - - it("shows the selected agent label with capitalization in the trigger", async () => { - await using _ = await mountOpenCodePicker({ - options: { - variant: "medium", - agent: "plan", - }, - }); - - await vi.waitFor(() => { - const text = document.body.textContent ?? ""; - expect(text).toContain("Medium · Plan"); - expect(text).not.toContain("Medium · plan"); - }); - }); - - it("does not show a leading separator when only agent options are available", async () => { - await using _ = await mountOpenCodePicker({ - model: "openai/gpt-5.4", - models: [ - { - slug: "openai/gpt-5.4", - name: "OpenAI · GPT-5.4", - isCustom: false, - capabilities: { - reasoningEffortLevels: [], - supportsFastMode: false, - supportsThinkingToggle: false, - contextWindowOptions: [], - promptInjectedEffortLevels: [], - variantOptions: [], - agentOptions: [ - { value: "build", label: "Build", isDefault: true }, - { value: "plan", label: "Plan" }, - ], - }, - }, - ], - }); - - await page.getByRole("button").click(); - - await vi.waitFor(() => { - const text = document.body.textContent ?? ""; - expect(text).toContain("Agent"); - expect(text).toContain("Build (default)"); - expect(text).toContain("Plan"); - expect(document.querySelectorAll('[data-slot="menu-separator"]')).toHaveLength(0); - }); - }); -}); - -describe("TraitsPicker (Cursor)", () => { - afterEach(() => { - document.body.innerHTML = ""; - localStorage.removeItem(COMPOSER_DRAFT_STORAGE_KEY); - useComposerDraftStore.setState({ - draftsByThreadKey: {}, - draftThreadsByThreadKey: {}, - logicalProjectDraftThreadKeyByLogicalProjectKey: {}, - stickyModelSelectionByProvider: {}, - }); - }); - - it("uses the selected fast mode menu label for the trigger in fast-only state", async () => { - await using _ = await mountCursorPicker({ - model: "composer-2", - options: { fastMode: false }, - }); - - await vi.waitFor(() => { - const text = document.body.textContent ?? ""; - expect(text).toContain("Normal"); - }); - - await page.getByRole("button").click(); - - await vi.waitFor(() => { - const text = document.body.textContent ?? ""; - expect(text).toContain("Fast Mode"); - expect(text).toContain("off"); - expect(text).toContain("on"); - }); - }); - - it("shows Normal for Cursor Opus 4.6 when fast mode and context window are both at defaults", async () => { - await using _ = await mountCursorPicker({ - model: "claude-opus-4-6", - options: { fastMode: false }, - }); - - await vi.waitFor(() => { - const text = document.body.textContent ?? ""; - expect(text).toContain("Normal"); - }); - - await page.getByRole("button").click(); - - await vi.waitFor(() => { - const text = document.body.textContent ?? ""; - expect(text).toContain("Fast Mode"); - expect(text).toContain("Context Window"); - expect(text).toContain("200K (default)"); - expect(text).toContain("1M"); - }); - }); - - it("shows Normal · 1M for Cursor Opus 4.6 when fast mode is off and context window is overridden", async () => { - await using _ = await mountCursorPicker({ - model: "claude-opus-4-6", - options: { fastMode: false, contextWindow: "1m" }, - }); - - await vi.waitFor(() => { - expect(document.body.textContent ?? "").toContain("Normal · 1M"); - }); - }); -}); diff --git a/apps/web/src/components/chat/TraitsPicker.tsx b/apps/web/src/components/chat/TraitsPicker.tsx index d30fba832e..1b54da76da 100644 --- a/apps/web/src/components/chat/TraitsPicker.tsx +++ b/apps/web/src/components/chat/TraitsPicker.tsx @@ -1,21 +1,17 @@ import { - type ClaudeModelOptions, - type CodexModelOptions, - type CursorModelOptions, - type OpenCodeModelOptions, type ProviderKind, - type ProviderModelOptions, + type ProviderOptionDescriptor, + type ProviderOptionSelection, type ScopedThreadRef, type ServerProviderModel, } from "@t3tools/contracts"; import { applyClaudePromptEffortPrefix, + buildProviderOptionSelectionsFromDescriptors, + getProviderOptionCurrentLabel, + getProviderOptionCurrentValue, + getProviderOptionDescriptors, isClaudeUltrathinkPrompt, - trimOrNull, - getDefaultEffort, - getDefaultContextWindow, - hasContextWindowOption, - resolveEffort, } from "@t3tools/shared/model"; import { memo, useCallback, useState } from "react"; import type { VariantProps } from "class-variance-authority"; @@ -34,12 +30,7 @@ import { useComposerDraftStore, DraftId } from "../../composerDraftStore"; import { getProviderModelCapabilities } from "../../providerModels"; import { cn } from "~/lib/utils"; -type ProviderOptions = ProviderModelOptions[ProviderKind]; -type NamedOption = { - value: string; - label: string; - isDefault?: boolean | undefined; -}; +type ProviderOptions = ReadonlyArray; type TraitsPersistence = | { @@ -54,62 +45,34 @@ type TraitsPersistence = const ULTRATHINK_PROMPT_PREFIX = "Ultrathink:\n"; -function getRawEffort( - provider: ProviderKind, - modelOptions: ProviderOptions | null | undefined, +function replaceDescriptorCurrentValue( + descriptors: ReadonlyArray, + descriptorId: string, + currentValue: string | boolean | undefined, +): ReadonlyArray { + return descriptors.map((descriptor) => + descriptor.id !== descriptorId + ? descriptor + : descriptor.type === "boolean" + ? { + ...descriptor, + ...(typeof currentValue === "boolean" ? { currentValue } : {}), + } + : { + ...descriptor, + ...(typeof currentValue === "string" ? { currentValue } : {}), + }, + ); +} + +function getDescriptorStringValue( + descriptor: Extract | null, ): string | null { - if (provider === "codex") { - return trimOrNull((modelOptions as CodexModelOptions | undefined)?.reasoningEffort); + if (!descriptor) { + return null; } - if (provider === "cursor") { - return trimOrNull((modelOptions as CursorModelOptions | undefined)?.reasoning); - } - if (provider === "opencode") { - return trimOrNull((modelOptions as OpenCodeModelOptions | undefined)?.variant); - } - return trimOrNull((modelOptions as ClaudeModelOptions | undefined)?.effort); -} - -function getEffortKey(provider: ProviderKind): string { - if (provider === "codex") return "reasoningEffort"; - if (provider === "cursor") return "reasoning"; - if (provider === "opencode") return "variant"; - return "effort"; -} - -function getRawAgent(modelOptions: ProviderOptions | null | undefined): string | null { - return trimOrNull((modelOptions as OpenCodeModelOptions | undefined)?.agent); -} - -function resolveNamedOption( - options: ReadonlyArray, - raw: string | null, -): NamedOption | null { - if (raw) { - const matchingOption = options.find((option) => option.value === raw); - if (matchingOption) { - return matchingOption; - } - } - return options.find((option) => option.isDefault) ?? options[0] ?? null; -} - -function getRawContextWindow( - provider: ProviderKind, - modelOptions: ProviderOptions | null | undefined, -): string | null { - if (modelOptions && "contextWindow" in modelOptions) { - return trimOrNull(modelOptions.contextWindow); - } - return null; -} - -function buildNextOptions( - provider: ProviderKind, - modelOptions: ProviderOptions | null | undefined, - patch: Record, -): ProviderOptions { - return { ...(modelOptions as Record | undefined), ...patch } as ProviderOptions; + const value = getProviderOptionCurrentValue(descriptor); + return typeof value === "string" ? value : null; } function getSelectedTraits( @@ -121,71 +84,68 @@ function getSelectedTraits( allowPromptInjectedEffort: boolean, ) { const caps = getProviderModelCapabilities(models, model, provider); - const effortLevels = - provider === "opencode" - ? (caps.variantOptions ?? []) - : allowPromptInjectedEffort - ? caps.reasoningEffortLevels - : caps.reasoningEffortLevels.filter( - (option) => !caps.promptInjectedEffortLevels.includes(option.value), - ); - - // Resolve effort from options (provider-specific key) - const rawEffort = getRawEffort(provider, modelOptions); - const effort = - provider === "opencode" - ? (resolveNamedOption(effortLevels, rawEffort)?.value ?? null) - : (resolveEffort(caps, rawEffort) ?? null); - - // Thinking toggle (only for models that support it) - const thinkingEnabled = caps.supportsThinkingToggle - ? modelOptions && "thinking" in modelOptions - ? modelOptions.thinking === true - : null - : null; - - // Fast mode - const fastModeEnabled = - caps.supportsFastMode && - (modelOptions as { fastMode?: boolean } | undefined)?.fastMode === true; - - // Context window - const contextWindowOptions = caps.contextWindowOptions; - const rawContextWindow = getRawContextWindow(provider, modelOptions); - const defaultContextWindow = getDefaultContextWindow(caps); - const contextWindow = - rawContextWindow && hasContextWindowOption(caps, rawContextWindow) - ? rawContextWindow - : defaultContextWindow; + const descriptors = getProviderOptionDescriptors({ + caps, + selections: modelOptions, + }); + const selectDescriptors = descriptors.filter( + (descriptor): descriptor is Extract => + descriptor.type === "select", + ); + const booleanDescriptors = descriptors.filter( + (descriptor): descriptor is Extract => + descriptor.type === "boolean", + ); + const primarySelectDescriptor = selectDescriptors[0] ?? null; + const contextWindowDescriptor = + selectDescriptors.find((descriptor) => descriptor.id === "contextWindow") ?? null; + const agentDescriptor = selectDescriptors.find((descriptor) => descriptor.id === "agent") ?? null; + const fastModeDescriptor = + booleanDescriptors.find((descriptor) => descriptor.id === "fastMode") ?? null; + const thinkingDescriptor = + booleanDescriptors.find((descriptor) => descriptor.id === "thinking") ?? null; // Prompt-controlled effort (e.g. ultrathink in prompt text) const ultrathinkPromptControlled = allowPromptInjectedEffort && - caps.promptInjectedEffortLevels.length > 0 && + (primarySelectDescriptor?.promptInjectedValues?.length ?? 0) > 0 && isClaudeUltrathinkPrompt(prompt); // Check if "ultrathink" appears in the body text (not just our prefix) const ultrathinkInBodyText = ultrathinkPromptControlled && isClaudeUltrathinkPrompt(prompt.replace(/^Ultrathink:\s*/i, "")); - - const agentOptions = caps.agentOptions ?? []; - const selectedAgentOption = - provider === "opencode" ? resolveNamedOption(agentOptions, getRawAgent(modelOptions)) : null; + const effort = + (ultrathinkPromptControlled + ? "ultrathink" + : getDescriptorStringValue(primarySelectDescriptor)) ?? null; + const thinkingEnabled = + typeof thinkingDescriptor?.currentValue === "boolean" ? thinkingDescriptor.currentValue : null; + const fastModeEnabled = + typeof fastModeDescriptor?.currentValue === "boolean" ? fastModeDescriptor.currentValue : false; + const contextWindow = getDescriptorStringValue(contextWindowDescriptor); + const selectedAgent = getDescriptorStringValue(agentDescriptor); + const selectedAgentLabel = agentDescriptor + ? getProviderOptionCurrentLabel(agentDescriptor) + : null; return { caps, + descriptors, + selectDescriptors, + booleanDescriptors, + primarySelectDescriptor, + contextWindowDescriptor, + agentDescriptor, + fastModeDescriptor, + thinkingDescriptor, effort, - effortLevels, thinkingEnabled, fastModeEnabled, - contextWindowOptions, contextWindow, - defaultContextWindow, ultrathinkPromptControlled, ultrathinkInBodyText, - agentOptions, - selectedAgent: selectedAgentOption?.value ?? null, - selectedAgentLabel: selectedAgentOption?.label ?? null, + selectedAgent, + selectedAgentLabel, }; } @@ -206,11 +166,11 @@ function getTraitsSectionVisibility(input: { input.allowPromptInjectedEffort ?? true, ); - const showEffort = selected.effort !== null; - const showThinking = selected.thinkingEnabled !== null; - const showFastMode = selected.caps.supportsFastMode; - const showContextWindow = selected.contextWindowOptions.length > 1; - const showAgent = selected.agentOptions.length > 0; + const showEffort = selected.primarySelectDescriptor !== null; + const showThinking = selected.thinkingDescriptor !== null; + const showFastMode = selected.fastModeDescriptor !== null; + const showContextWindow = selected.contextWindowDescriptor !== null; + const showAgent = selected.agentDescriptor !== null; return { ...selected, @@ -275,22 +235,12 @@ export const TraitsMenuContent = memo(function TraitsMenuContentImpl({ [model, persistence, provider, setProviderModelOptions], ); const { - caps, - effort, - effortLevels, - thinkingEnabled, - fastModeEnabled, - contextWindowOptions, - contextWindow, - defaultContextWindow, + descriptors, + selectDescriptors, + booleanDescriptors, + primarySelectDescriptor, ultrathinkPromptControlled, - showEffort, - showThinking, - showFastMode, - showContextWindow, ultrathinkInBodyText, - agentOptions, - selectedAgent, hasAnyControls, } = getTraitsSectionVisibility({ provider, @@ -300,53 +250,30 @@ export const TraitsMenuContent = memo(function TraitsMenuContentImpl({ modelOptions, allowPromptInjectedEffort, }); - const defaultEffort = getDefaultEffort(caps); - const showsEffortSection = showEffort; - const showsThinkingSection = !showEffort && showThinking; - const showsFastModeSection = showFastMode; - const showsContextWindowSection = showContextWindow; - const hasSectionsBeforeAgent = - showsEffortSection || showsThinkingSection || showsFastModeSection || showsContextWindowSection; + const updateDescriptors = (nextDescriptors: ReadonlyArray) => { + updateModelOptions(buildProviderOptionSelectionsFromDescriptors(nextDescriptors)); + }; - const handleEffortChange = useCallback( - (value: string) => { - if (!value) return; - const nextOption = effortLevels.find((option) => option.value === value); - if (!nextOption) return; - if (provider === "opencode") { - updateModelOptions(buildNextOptions(provider, modelOptions, { variant: nextOption.value })); - return; - } - if (caps.promptInjectedEffortLevels.includes(nextOption.value)) { - const nextPrompt = - prompt.trim().length === 0 - ? ULTRATHINK_PROMPT_PREFIX - : applyClaudePromptEffortPrefix(prompt, "ultrathink"); - onPromptChange(nextPrompt); - return; - } - if (ultrathinkInBodyText) return; - if (ultrathinkPromptControlled) { - const stripped = prompt.replace(/^Ultrathink:\s*/i, ""); - onPromptChange(stripped); - } - const effortKey = getEffortKey(provider); - updateModelOptions( - buildNextOptions(provider, modelOptions, { [effortKey]: nextOption.value }), - ); - }, - [ - ultrathinkPromptControlled, - ultrathinkInBodyText, - modelOptions, - onPromptChange, - updateModelOptions, - effortLevels, - prompt, - caps.promptInjectedEffortLevels, - provider, - ], - ); + const handleSelectChange = ( + descriptor: Extract, + value: string, + ) => { + if (!value) return; + if (descriptor.promptInjectedValues?.includes(value)) { + const nextPrompt = + prompt.trim().length === 0 + ? ULTRATHINK_PROMPT_PREFIX + : applyClaudePromptEffortPrefix(prompt, "ultrathink"); + onPromptChange(nextPrompt); + return; + } + if (ultrathinkInBodyText && descriptor.id === primarySelectDescriptor?.id) return; + if (ultrathinkPromptControlled && descriptor.id === primarySelectDescriptor?.id) { + const stripped = prompt.replace(/^Ultrathink:\s*/i, ""); + onPromptChange(stripped); + } + updateDescriptors(replaceDescriptorCurrentValue(descriptors, descriptor.id, value)); + }; if (!hasAnyControls) { return null; @@ -354,121 +281,62 @@ export const TraitsMenuContent = memo(function TraitsMenuContentImpl({ return ( <> - {showsEffortSection ? ( - <> + {selectDescriptors.map((descriptor, index) => ( +
+ {index > 0 ? : null}
- {provider === "opencode" ? "Variant" : "Effort"} + {descriptor.label}
- {ultrathinkInBodyText ? ( + {ultrathinkInBodyText && descriptor.id === primarySelectDescriptor?.id ? (
- Your prompt contains "ultrathink" in the text. Remove it to change effort. + Your prompt contains "ultrathink" in the text. Remove it to change this + option.
) : null} handleSelectChange(descriptor, value)} > - {effortLevels.map((option) => ( + {descriptor.options.map((option) => ( - {option.label} - {(provider === "opencode" ? option.isDefault : option.value === defaultEffort) - ? " (default)" - : ""} - - ))} - -
- - ) : showsThinkingSection ? ( - -
Thinking
- { - updateModelOptions( - buildNextOptions(provider, modelOptions, { thinking: value === "on" }), - ); - }} - > - On (default) - Off - -
- ) : null} - {showsFastModeSection ? ( - <> - {showsEffortSection || showsThinkingSection ? : null} - -
Fast Mode
- { - updateModelOptions( - buildNextOptions(provider, modelOptions, { fastMode: value === "on" }), - ); - }} - > - off - on - -
- - ) : null} - {showsContextWindowSection ? ( - <> - {showsEffortSection || showsThinkingSection || showsFastModeSection ? ( - - ) : null} - -
- Context Window -
- { - updateModelOptions( - buildNextOptions(provider, modelOptions, { - contextWindow: value, - }), - ); - }} - > - {contextWindowOptions.map((option) => ( - - {option.label} - {option.value === defaultContextWindow ? " (default)" : ""} - - ))} - -
- - ) : null} - {agentOptions.length > 0 ? ( - <> - {hasSectionsBeforeAgent ? : null} - -
Agent
- { - updateModelOptions(buildNextOptions(provider, modelOptions, { agent: value })); - }} - > - {agentOptions.map((option) => ( - {option.label} {option.isDefault ? " (default)" : ""} ))}
- - ) : null} +
+ ))} + {booleanDescriptors.map((descriptor, index) => ( +
+ {index > 0 || selectDescriptors.length > 0 ? : null} + +
+ {descriptor.label} +
+ { + updateDescriptors( + replaceDescriptorCurrentValue(descriptors, descriptor.id, value === "on"), + ); + }} + > + On + Off + +
+
+ ))} ); }); @@ -486,52 +354,15 @@ export const TraitsPicker = memo(function TraitsPicker({ ...persistence }: TraitsMenuContentProps & TraitsPersistence) { const [isMenuOpen, setIsMenuOpen] = useState(false); - const { - caps, - effort, - effortLevels, - thinkingEnabled, - fastModeEnabled, - contextWindowOptions, - contextWindow, - defaultContextWindow, - ultrathinkPromptControlled, - showEffort, - showThinking, - showContextWindow, - } = getTraitsSectionVisibility({ - provider, - models, - model, - prompt, - modelOptions, - allowPromptInjectedEffort, - }); - const { selectedAgentLabel } = getSelectedTraits( - provider, - models, - model, - prompt, - modelOptions, - allowPromptInjectedEffort, - ); - - const effortLabel = effort - ? (effortLevels.find((l) => l.value === effort)?.label ?? effort) - : null; - const primaryTraitLabel = ultrathinkPromptControlled - ? "Ultrathink" - : effortLabel - ? effortLabel - : thinkingEnabled === null - ? null - : `Thinking ${thinkingEnabled ? "On" : "Off"}`; - const contextWindowLabel = - showContextWindow && contextWindow !== defaultContextWindow - ? (contextWindowOptions.find((o) => o.value === contextWindow)?.label ?? null) - : null; - const fastOnlyControl = - caps.supportsFastMode && !showEffort && !showThinking && !showContextWindow; + const { descriptors, primarySelectDescriptor, ultrathinkPromptControlled } = + getTraitsSectionVisibility({ + provider, + models, + model, + prompt, + modelOptions, + allowPromptInjectedEffort, + }); if ( !shouldRenderTraitsControls({ provider, @@ -545,27 +376,22 @@ export const TraitsPicker = memo(function TraitsPicker({ return null; } - const selectedTriggerTraits = [ - primaryTraitLabel, - ...(caps.supportsFastMode && - (fastModeEnabled || (primaryTraitLabel === null && contextWindowLabel !== null)) - ? [fastModeEnabled ? "Fast" : "Normal"] - : []), - ...(contextWindowLabel ? [contextWindowLabel] : []), - ...(selectedAgentLabel ? [selectedAgentLabel] : []), - ].filter(Boolean); - const triggerLabel = fastOnlyControl - ? fastModeEnabled - ? "Fast" - : "Normal" - : selectedTriggerTraits.length > 0 - ? selectedTriggerTraits.join(" · ") - : caps.supportsFastMode - ? "Normal" - : defaultContextWindow - ? (contextWindowOptions.find((option) => option.value === defaultContextWindow)?.label ?? - defaultContextWindow) - : (selectedAgentLabel ?? ""); + const triggerLabel = + descriptors + .map((descriptor) => { + if (ultrathinkPromptControlled && descriptor.id === primarySelectDescriptor?.id) { + return "Ultrathink"; + } + if (descriptor.type === "boolean") { + if (descriptor.id === "fastMode") { + return descriptor.currentValue === true ? "Fast" : "Normal"; + } + return `${descriptor.label} ${descriptor.currentValue === true ? "On" : "Off"}`; + } + return getProviderOptionCurrentLabel(descriptor); + }) + .filter((label): label is string => typeof label === "string" && label.length > 0) + .join(" · ") || ""; const isCodexStyle = provider === "codex"; diff --git a/apps/web/src/components/chat/composerProviderRegistry.test.tsx b/apps/web/src/components/chat/composerProviderRegistry.test.tsx deleted file mode 100644 index c4dd2cbb6e..0000000000 --- a/apps/web/src/components/chat/composerProviderRegistry.test.tsx +++ /dev/null @@ -1,516 +0,0 @@ -import { describe, expect, it } from "vitest"; -import type { ServerProviderModel } from "@t3tools/contracts"; -import { - getComposerProviderControls, - getComposerProviderState, - renderProviderTraitsMenuContent, - renderProviderTraitsPicker, -} from "./composerProviderRegistry"; - -const CODEX_MODELS: ReadonlyArray = [ - { - slug: "gpt-5.4", - name: "GPT-5.4", - isCustom: false, - capabilities: { - reasoningEffortLevels: [ - { value: "xhigh", label: "Extra High" }, - { value: "high", label: "High", isDefault: true }, - { value: "medium", label: "Medium" }, - { value: "low", label: "Low" }, - ], - supportsFastMode: true, - supportsThinkingToggle: false, - contextWindowOptions: [], - promptInjectedEffortLevels: [], - }, - }, -]; - -const CLAUDE_MODELS: ReadonlyArray = [ - { - slug: "claude-opus-4-6", - name: "Claude Opus 4.6", - isCustom: false, - capabilities: { - reasoningEffortLevels: [ - { value: "medium", label: "Medium" }, - { value: "high", label: "High", isDefault: true }, - { value: "max", label: "Max" }, - { value: "ultrathink", label: "Ultrathink" }, - ], - supportsFastMode: true, - supportsThinkingToggle: false, - contextWindowOptions: [], - promptInjectedEffortLevels: ["ultrathink"], - }, - }, - { - slug: "claude-sonnet-4-6", - name: "Claude Sonnet 4.6", - isCustom: false, - capabilities: { - reasoningEffortLevels: [ - { value: "low", label: "Low" }, - { value: "medium", label: "Medium" }, - { value: "high", label: "High", isDefault: true }, - { value: "ultrathink", label: "Ultrathink" }, - ], - supportsFastMode: false, - supportsThinkingToggle: false, - contextWindowOptions: [], - promptInjectedEffortLevels: ["ultrathink"], - }, - }, - { - slug: "claude-haiku-4-5", - name: "Claude Haiku 4.5", - isCustom: false, - capabilities: { - reasoningEffortLevels: [], - supportsFastMode: false, - supportsThinkingToggle: true, - contextWindowOptions: [], - promptInjectedEffortLevels: [], - }, - }, -]; - -const CLAUDE_MODELS_WITH_CONTEXT_WINDOW: ReadonlyArray = [ - { - slug: "claude-opus-4-6", - name: "Claude Opus 4.6", - isCustom: false, - capabilities: { - reasoningEffortLevels: [ - { value: "medium", label: "Medium" }, - { value: "high", label: "High", isDefault: true }, - { value: "max", label: "Max" }, - { value: "ultrathink", label: "Ultrathink" }, - ], - supportsFastMode: true, - supportsThinkingToggle: false, - contextWindowOptions: [ - { value: "200k", label: "200k", isDefault: true }, - { value: "1m", label: "1M" }, - ], - promptInjectedEffortLevels: ["ultrathink"], - }, - }, - { - slug: "claude-haiku-4-5", - name: "Claude Haiku 4.5", - isCustom: false, - capabilities: { - reasoningEffortLevels: [], - supportsFastMode: false, - supportsThinkingToggle: true, - contextWindowOptions: [], - promptInjectedEffortLevels: [], - }, - }, -]; - -const OPENCODE_MODELS: ReadonlyArray = [ - { - slug: "openai/gpt-5", - name: "GPT-5", - isCustom: false, - capabilities: { - reasoningEffortLevels: [], - supportsFastMode: false, - supportsThinkingToggle: false, - contextWindowOptions: [], - promptInjectedEffortLevels: [], - variantOptions: [ - { value: "low", label: "Low" }, - { value: "medium", label: "Medium", isDefault: true }, - ], - agentOptions: [ - { value: "build", label: "Build", isDefault: true }, - { value: "plan", label: "Plan" }, - ], - }, - }, -]; - -describe("getComposerProviderState", () => { - it("returns codex defaults when no codex draft options exist", () => { - const state = getComposerProviderState({ - provider: "codex", - model: "gpt-5.4", - models: CODEX_MODELS, - prompt: "", - modelOptions: undefined, - }); - - expect(state).toEqual({ - provider: "codex", - promptEffort: "high", - modelOptionsForDispatch: { - reasoningEffort: "high", - }, - }); - }); - - it("normalizes codex dispatch options while preserving the selected effort", () => { - const state = getComposerProviderState({ - provider: "codex", - model: "gpt-5.4", - models: CODEX_MODELS, - prompt: "", - modelOptions: { - codex: { - reasoningEffort: "low", - fastMode: true, - }, - }, - }); - - expect(state).toEqual({ - provider: "codex", - promptEffort: "low", - modelOptionsForDispatch: { - reasoningEffort: "low", - fastMode: true, - }, - }); - }); - - it("preserves codex fast mode when it is the only active option", () => { - const state = getComposerProviderState({ - provider: "codex", - model: "gpt-5.4", - models: CODEX_MODELS, - prompt: "", - modelOptions: { - codex: { - fastMode: true, - }, - }, - }); - - expect(state).toEqual({ - provider: "codex", - promptEffort: "high", - modelOptionsForDispatch: { - reasoningEffort: "high", - fastMode: true, - }, - }); - }); - - it("preserves codex default effort explicitly in dispatch options", () => { - const state = getComposerProviderState({ - provider: "codex", - model: "gpt-5.4", - models: CODEX_MODELS, - prompt: "", - modelOptions: { - codex: { - reasoningEffort: "high", - fastMode: false, - }, - }, - }); - - expect(state).toEqual({ - provider: "codex", - promptEffort: "high", - modelOptionsForDispatch: { - reasoningEffort: "high", - fastMode: false, - }, - }); - }); - - it("returns Claude defaults for effort-capable models", () => { - const state = getComposerProviderState({ - provider: "claudeAgent", - model: "claude-sonnet-4-6", - models: CLAUDE_MODELS, - prompt: "", - modelOptions: undefined, - }); - - expect(state).toEqual({ - provider: "claudeAgent", - promptEffort: "high", - modelOptionsForDispatch: { - effort: "high", - }, - }); - }); - - it("tracks Claude ultrathink from the prompt without changing dispatch effort", () => { - const state = getComposerProviderState({ - provider: "claudeAgent", - model: "claude-sonnet-4-6", - models: CLAUDE_MODELS, - prompt: "Ultrathink:\nInvestigate this failure", - modelOptions: { - claudeAgent: { - effort: "medium", - }, - }, - }); - - expect(state).toEqual({ - provider: "claudeAgent", - promptEffort: "medium", - modelOptionsForDispatch: { - effort: "medium", - }, - composerFrameClassName: "ultrathink-frame", - composerSurfaceClassName: "shadow-[0_0_0_1px_rgba(255,255,255,0.04)_inset]", - modelPickerIconClassName: "ultrathink-chroma", - }); - }); - - it("drops unsupported Claude effort options for models without effort controls", () => { - const state = getComposerProviderState({ - provider: "claudeAgent", - model: "claude-haiku-4-5", - models: CLAUDE_MODELS, - prompt: "", - modelOptions: { - claudeAgent: { - effort: "max", - thinking: false, - }, - }, - }); - - expect(state).toEqual({ - provider: "claudeAgent", - promptEffort: null, - modelOptionsForDispatch: { - thinking: false, - }, - }); - }); - - it("preserves Claude fast mode when it is the only active option", () => { - const state = getComposerProviderState({ - provider: "claudeAgent", - model: "claude-opus-4-6", - models: CLAUDE_MODELS, - prompt: "", - modelOptions: { - claudeAgent: { - fastMode: true, - }, - }, - }); - - expect(state).toEqual({ - provider: "claudeAgent", - promptEffort: "high", - modelOptionsForDispatch: { - effort: "high", - fastMode: true, - }, - }); - }); - - it("preserves Claude default effort explicitly in dispatch options", () => { - const state = getComposerProviderState({ - provider: "claudeAgent", - model: "claude-opus-4-6", - models: CLAUDE_MODELS, - prompt: "", - modelOptions: { - claudeAgent: { - effort: "high", - fastMode: false, - }, - }, - }); - - expect(state).toEqual({ - provider: "claudeAgent", - promptEffort: "high", - modelOptionsForDispatch: { - effort: "high", - fastMode: false, - }, - }); - }); - - it("preserves explicit fastMode: false so deepMerge can overwrite a prior true", () => { - // Regression: normalizeClaudeModelOptionsWithCapabilities used to strip - // fastMode: false, which meant deepMerge could never clear a previous true. - const state = getComposerProviderState({ - provider: "claudeAgent", - model: "claude-opus-4-6", - models: CLAUDE_MODELS, - prompt: "", - modelOptions: { - claudeAgent: { - effort: "high", - fastMode: false, - }, - }, - }); - - expect(state.modelOptionsForDispatch).toHaveProperty("fastMode", false); - }); - - it("preserves explicit thinking: true so deepMerge can overwrite a prior false", () => { - // Regression: thinking: true (the default) used to be stripped, which - // meant deepMerge could never clear a previous thinking: false. - const state = getComposerProviderState({ - provider: "claudeAgent", - model: "claude-haiku-4-5", - models: CLAUDE_MODELS, - prompt: "", - modelOptions: { - claudeAgent: { - thinking: true, - }, - }, - }); - - expect(state.modelOptionsForDispatch).toHaveProperty("thinking", true); - }); - - it("preserves Claude default context window explicitly in dispatch options", () => { - const state = getComposerProviderState({ - provider: "claudeAgent", - model: "claude-opus-4-6", - models: CLAUDE_MODELS_WITH_CONTEXT_WINDOW, - prompt: "", - modelOptions: { - claudeAgent: { - effort: "high", - contextWindow: "200k", - }, - }, - }); - - expect(state.modelOptionsForDispatch).toMatchObject({ - effort: "high", - contextWindow: "200k", - }); - }); - - it("preserves explicit contextWindow default so deepMerge can overwrite a prior 1m", () => { - // Regression: the default contextWindow must survive normalization so - // deepMerge can clear an older non-default 1m selection. - const state = getComposerProviderState({ - provider: "claudeAgent", - model: "claude-opus-4-6", - models: CLAUDE_MODELS_WITH_CONTEXT_WINDOW, - prompt: "", - modelOptions: { - claudeAgent: { - contextWindow: "200k", - }, - }, - }); - - expect(state.modelOptionsForDispatch).toHaveProperty("contextWindow", "200k"); - }); - - it("omits contextWindow when the model does not support it", () => { - const state = getComposerProviderState({ - provider: "claudeAgent", - model: "claude-haiku-4-5", - models: CLAUDE_MODELS_WITH_CONTEXT_WINDOW, - prompt: "", - modelOptions: { - claudeAgent: { - contextWindow: "1m", - }, - }, - }); - - expect(state.modelOptionsForDispatch).toBeUndefined(); - }); - - it("omits fastMode when the model does not support it", () => { - const state = getComposerProviderState({ - provider: "claudeAgent", - model: "claude-sonnet-4-6", - models: CLAUDE_MODELS, - prompt: "", - modelOptions: { - claudeAgent: { - effort: "high", - fastMode: true, - }, - }, - }); - - expect(state.modelOptionsForDispatch).not.toHaveProperty("fastMode"); - }); - - it("preserves OpenCode variant and agent options for dispatch", () => { - const state = getComposerProviderState({ - provider: "opencode", - model: "openai/gpt-5", - models: OPENCODE_MODELS, - prompt: "", - modelOptions: { - opencode: { - variant: "medium", - agent: "plan", - }, - }, - }); - - expect(state).toEqual({ - provider: "opencode", - promptEffort: "medium", - modelOptionsForDispatch: { - variant: "medium", - agent: "plan", - }, - }); - }); -}); - -describe("getComposerProviderControls", () => { - it("hides the interaction mode toggle for OpenCode", () => { - expect(getComposerProviderControls("opencode")).toEqual({ - showInteractionModeToggle: false, - }); - }); - - it("keeps the interaction mode toggle for Codex and Claude", () => { - expect(getComposerProviderControls("codex")).toEqual({ - showInteractionModeToggle: true, - }); - expect(getComposerProviderControls("claudeAgent")).toEqual({ - showInteractionModeToggle: true, - }); - }); -}); - -describe("provider traits render guards", () => { - it("returns null for codex traits picker when no thread target is provided", () => { - const content = renderProviderTraitsPicker({ - provider: "codex", - model: "gpt-5.4", - models: CODEX_MODELS, - modelOptions: undefined, - prompt: "", - onPromptChange: () => {}, - }); - - expect(content).toBeNull(); - }); - - it("returns null for claude traits menu content when no thread target is provided", () => { - const content = renderProviderTraitsMenuContent({ - provider: "claudeAgent", - model: "claude-sonnet-4-6", - models: CLAUDE_MODELS, - modelOptions: undefined, - prompt: "", - onPromptChange: () => {}, - }); - - expect(content).toBeNull(); - }); -}); diff --git a/apps/web/src/components/chat/composerProviderRegistry.tsx b/apps/web/src/components/chat/composerProviderRegistry.tsx deleted file mode 100644 index af03c99a5e..0000000000 --- a/apps/web/src/components/chat/composerProviderRegistry.tsx +++ /dev/null @@ -1,216 +0,0 @@ -import { - type ProviderKind, - type ProviderModelOptions, - type ScopedThreadRef, - type ServerProviderModel, -} from "@t3tools/contracts"; -import { - isClaudeUltrathinkPrompt, - normalizeProviderModelOptionsWithCapabilities, - resolveEffort, - trimOrNull, -} from "@t3tools/shared/model"; -import type { ReactNode } from "react"; - -import type { DraftId } from "../../composerDraftStore"; -import { getProviderModelCapabilities } from "../../providerModels"; -import { shouldRenderTraitsControls, TraitsMenuContent, TraitsPicker } from "./TraitsPicker"; - -export type ComposerProviderStateInput = { - provider: ProviderKind; - model: string; - models: ReadonlyArray; - prompt: string; - modelOptions: ProviderModelOptions | null | undefined; -}; - -export type ComposerProviderState = { - provider: ProviderKind; - promptEffort: string | null; - modelOptionsForDispatch: ProviderModelOptions[ProviderKind] | undefined; - composerFrameClassName?: string; - composerSurfaceClassName?: string; - modelPickerIconClassName?: string; -}; - -type TraitsRenderInput = { - threadRef?: ScopedThreadRef; - draftId?: DraftId; - model: string; - models: ReadonlyArray; - modelOptions: ProviderModelOptions[ProviderKind] | undefined; - prompt: string; - onPromptChange: (prompt: string) => void; -}; - -export type ComposerProviderControls = { - showInteractionModeToggle: boolean; -}; - -type ProviderRegistryEntry = { - controls: ComposerProviderControls; - getState: (input: ComposerProviderStateInput) => ComposerProviderState; - renderTraitsMenuContent: (input: TraitsRenderInput) => ReactNode; - renderTraitsPicker: (input: TraitsRenderInput) => ReactNode; -}; - -function hasComposerTraitsTarget(input: { - threadRef: ScopedThreadRef | undefined; - draftId: DraftId | undefined; -}): boolean { - return input.threadRef !== undefined || input.draftId !== undefined; -} - -function renderTraitsControl( - Component: typeof TraitsMenuContent | typeof TraitsPicker, - provider: ProviderKind, - input: TraitsRenderInput, -): ReactNode { - const { threadRef, draftId, model, models, modelOptions, prompt, onPromptChange } = input; - if ( - !hasComposerTraitsTarget({ threadRef, draftId }) || - !shouldRenderTraitsControls({ - provider, - models, - model, - modelOptions, - prompt, - }) - ) { - return null; - } - - return ( - - ); -} - -function getProviderStateFromCapabilities( - input: ComposerProviderStateInput, -): ComposerProviderState { - const { provider, model, models, prompt, modelOptions } = input; - const caps = getProviderModelCapabilities(models, model, provider); - const providerOptions = modelOptions?.[provider]; - const rawEffort = providerOptions - ? "effort" in providerOptions - ? providerOptions.effort - : "reasoningEffort" in providerOptions - ? providerOptions.reasoningEffort - : "reasoning" in providerOptions - ? providerOptions.reasoning - : "variant" in providerOptions - ? providerOptions.variant - : null - : null; - const normalizedOptions = normalizeProviderModelOptionsWithCapabilities( - provider, - caps, - providerOptions, - ); - const promptEffort = - provider === "opencode" - ? (trimOrNull( - normalizedOptions && "variant" in normalizedOptions ? normalizedOptions.variant : null, - ) ?? null) - : (resolveEffort(caps, rawEffort) ?? null); - const ultrathinkActive = - caps.promptInjectedEffortLevels.length > 0 && isClaudeUltrathinkPrompt(prompt); - - return { - provider, - promptEffort, - modelOptionsForDispatch: normalizedOptions, - ...(ultrathinkActive ? { composerFrameClassName: "ultrathink-frame" } : {}), - ...(ultrathinkActive - ? { composerSurfaceClassName: "shadow-[0_0_0_1px_rgba(255,255,255,0.04)_inset]" } - : {}), - ...(ultrathinkActive ? { modelPickerIconClassName: "ultrathink-chroma" } : {}), - }; -} - -const DEFAULT_PROVIDER_CONTROLS: ComposerProviderControls = { - showInteractionModeToggle: true, -}; - -function createProviderRegistryEntry( - provider: ProviderKind, - controls?: Partial, -): ProviderRegistryEntry { - return { - controls: { - ...DEFAULT_PROVIDER_CONTROLS, - ...controls, - }, - getState: (input) => getProviderStateFromCapabilities(input), - renderTraitsMenuContent: (input) => renderTraitsControl(TraitsMenuContent, provider, input), - renderTraitsPicker: (input) => renderTraitsControl(TraitsPicker, provider, input), - }; -} - -const composerProviderRegistry: Record = { - codex: createProviderRegistryEntry("codex"), - claudeAgent: createProviderRegistryEntry("claudeAgent"), - cursor: createProviderRegistryEntry("cursor"), - opencode: createProviderRegistryEntry("opencode", { - showInteractionModeToggle: false, - }), -}; - -export function getComposerProviderState(input: ComposerProviderStateInput): ComposerProviderState { - return composerProviderRegistry[input.provider].getState(input); -} - -export function getComposerProviderControls(provider: ProviderKind): ComposerProviderControls { - return composerProviderRegistry[provider].controls; -} - -export function renderProviderTraitsMenuContent(input: { - provider: ProviderKind; - threadRef?: ScopedThreadRef; - draftId?: DraftId; - model: string; - models: ReadonlyArray; - modelOptions: ProviderModelOptions[ProviderKind] | undefined; - prompt: string; - onPromptChange: (prompt: string) => void; -}): ReactNode { - return composerProviderRegistry[input.provider].renderTraitsMenuContent({ - ...(input.threadRef ? { threadRef: input.threadRef } : {}), - ...(input.draftId ? { draftId: input.draftId } : {}), - model: input.model, - models: input.models, - modelOptions: input.modelOptions, - prompt: input.prompt, - onPromptChange: input.onPromptChange, - }); -} - -export function renderProviderTraitsPicker(input: { - provider: ProviderKind; - threadRef?: ScopedThreadRef; - draftId?: DraftId; - model: string; - models: ReadonlyArray; - modelOptions: ProviderModelOptions[ProviderKind] | undefined; - prompt: string; - onPromptChange: (prompt: string) => void; -}): ReactNode { - return composerProviderRegistry[input.provider].renderTraitsPicker({ - ...(input.threadRef ? { threadRef: input.threadRef } : {}), - ...(input.draftId ? { draftId: input.draftId } : {}), - model: input.model, - models: input.models, - modelOptions: input.modelOptions, - prompt: input.prompt, - onPromptChange: input.onPromptChange, - }); -} diff --git a/apps/web/src/components/chat/composerProviderState.test.tsx b/apps/web/src/components/chat/composerProviderState.test.tsx new file mode 100644 index 0000000000..cc49cbf5df --- /dev/null +++ b/apps/web/src/components/chat/composerProviderState.test.tsx @@ -0,0 +1,242 @@ +import { describe, expect, it } from "vitest"; +import type { + ProviderKind, + ProviderOptionDescriptor, + ProviderOptionSelection, + ServerProviderModel, +} from "@t3tools/contracts"; +import { + getComposerProviderState, + renderProviderTraitsMenuContent, + renderProviderTraitsPicker, +} from "./composerProviderState"; + +// Everything in composerProviderState is now data-driven by the model's +// optionDescriptors, so these tests use a single synthetic provider/model and +// vary only the descriptor shape per scenario. + +const PROVIDER: ProviderKind = "codex"; +const MODEL = "test-model"; + +function selectDescriptor( + id: string, + options: ReadonlyArray<{ id: string; label: string; isDefault?: boolean }>, + promptInjectedValues?: ReadonlyArray, +): Extract { + const defaultId = options.find((option) => option.isDefault)?.id; + return { + id, + label: id, + type: "select", + options: [...options], + ...(defaultId ? { currentValue: defaultId } : {}), + ...(promptInjectedValues && promptInjectedValues.length > 0 + ? { promptInjectedValues: [...promptInjectedValues] } + : {}), + }; +} + +function booleanDescriptor(id: string): Extract { + return { id, label: id, type: "boolean" }; +} + +function modelWith( + descriptors: ReadonlyArray, +): ReadonlyArray { + return [ + { slug: MODEL, name: MODEL, isCustom: false, capabilities: { optionDescriptors: descriptors } }, + ]; +} + +function selections( + ...entries: Array<[string, string | boolean]> +): ReadonlyArray { + return entries.map(([id, value]) => ({ id, value })); +} + +const ULTRATHINK_FRAME_CLASSES = { + composerFrameClassName: "ultrathink-frame", + composerSurfaceClassName: "shadow-[0_0_0_1px_rgba(255,255,255,0.04)_inset]", + modelPickerIconClassName: "ultrathink-chroma", +} as const; + +describe("getComposerProviderState", () => { + it("returns descriptor defaults when no selections are provided", () => { + const state = getComposerProviderState({ + provider: PROVIDER, + model: MODEL, + models: modelWith([ + selectDescriptor("effort", [ + { id: "low", label: "Low" }, + { id: "high", label: "High", isDefault: true }, + ]), + ]), + prompt: "", + modelOptions: undefined, + }); + + expect(state).toEqual({ + provider: PROVIDER, + promptEffort: "high", + modelOptionsForDispatch: selections(["effort", "high"]), + }); + }); + + it("lets selections override defaults and propagates them through dispatch", () => { + const state = getComposerProviderState({ + provider: PROVIDER, + model: MODEL, + models: modelWith([ + selectDescriptor("effort", [ + { id: "low", label: "Low" }, + { id: "high", label: "High", isDefault: true }, + ]), + booleanDescriptor("fastMode"), + ]), + prompt: "", + modelOptions: selections(["effort", "low"], ["fastMode", true]), + }); + + expect(state).toEqual({ + provider: PROVIDER, + promptEffort: "low", + modelOptionsForDispatch: selections(["effort", "low"], ["fastMode", true]), + }); + }); + + it("preserves selections that match defaults so deepMerge can overwrite prior state", () => { + const state = getComposerProviderState({ + provider: PROVIDER, + model: MODEL, + models: modelWith([ + selectDescriptor("effort", [{ id: "high", label: "High", isDefault: true }]), + booleanDescriptor("fastMode"), + ]), + prompt: "", + modelOptions: selections(["effort", "high"], ["fastMode", false]), + }); + + expect(state.modelOptionsForDispatch).toEqual( + selections(["effort", "high"], ["fastMode", false]), + ); + }); + + it("drops selections for descriptors the model does not declare", () => { + const state = getComposerProviderState({ + provider: PROVIDER, + model: MODEL, + models: modelWith([booleanDescriptor("thinking")]), + prompt: "", + modelOptions: selections(["effort", "max"], ["thinking", false]), + }); + + expect(state).toEqual({ + provider: PROVIDER, + promptEffort: null, + modelOptionsForDispatch: selections(["thinking", false]), + }); + }); + + it("derives promptEffort from the first select descriptor and preserves all others for dispatch", () => { + const state = getComposerProviderState({ + provider: PROVIDER, + model: MODEL, + models: modelWith([ + selectDescriptor("effort", [{ id: "high", label: "High", isDefault: true }]), + selectDescriptor("contextWindow", [ + { id: "200k", label: "200k", isDefault: true }, + { id: "1m", label: "1M" }, + ]), + selectDescriptor("agent", [ + { id: "build", label: "Build", isDefault: true }, + { id: "plan", label: "Plan" }, + ]), + ]), + prompt: "", + modelOptions: selections(["agent", "plan"]), + }); + + expect(state.promptEffort).toBe("high"); + expect(state.modelOptionsForDispatch).toEqual( + selections(["effort", "high"], ["contextWindow", "200k"], ["agent", "plan"]), + ); + }); + + it("returns undefined dispatch options when the model declares no descriptors", () => { + const state = getComposerProviderState({ + provider: PROVIDER, + model: MODEL, + models: modelWith([]), + prompt: "", + modelOptions: selections(["anything", "value"]), + }); + + expect(state).toEqual({ + provider: PROVIDER, + promptEffort: null, + modelOptionsForDispatch: undefined, + }); + }); + + it("adds ultrathink class names when the prompt triggers a promptInjectedValues descriptor", () => { + const state = getComposerProviderState({ + provider: PROVIDER, + model: MODEL, + models: modelWith([ + selectDescriptor( + "effort", + [ + { id: "medium", label: "Medium" }, + { id: "high", label: "High", isDefault: true }, + { id: "ultrathink", label: "Ultrathink" }, + ], + ["ultrathink"], + ), + ]), + prompt: "Ultrathink:\nInvestigate this failure", + modelOptions: selections(["effort", "medium"]), + }); + + expect(state).toEqual({ + provider: PROVIDER, + promptEffort: "medium", + modelOptionsForDispatch: selections(["effort", "medium"]), + ...ULTRATHINK_FRAME_CLASSES, + }); + }); + + it("does not add ultrathink class names when the descriptor has no promptInjectedValues", () => { + const state = getComposerProviderState({ + provider: PROVIDER, + model: MODEL, + models: modelWith([ + selectDescriptor("effort", [{ id: "high", label: "High", isDefault: true }]), + ]), + prompt: "Ultrathink:\nInvestigate this failure", + modelOptions: undefined, + }); + + expect(state).not.toHaveProperty("composerFrameClassName"); + expect(state).not.toHaveProperty("composerSurfaceClassName"); + expect(state).not.toHaveProperty("modelPickerIconClassName"); + }); +}); + +describe("provider traits render guards", () => { + it("returns null when no thread target is provided", () => { + const models = modelWith([ + selectDescriptor("effort", [{ id: "high", label: "High", isDefault: true }]), + ]); + const args = { + provider: PROVIDER, + model: MODEL, + models, + modelOptions: undefined, + prompt: "", + onPromptChange: () => {}, + }; + + expect(renderProviderTraitsPicker(args)).toBeNull(); + expect(renderProviderTraitsMenuContent(args)).toBeNull(); + }); +}); diff --git a/apps/web/src/components/chat/composerProviderState.tsx b/apps/web/src/components/chat/composerProviderState.tsx new file mode 100644 index 0000000000..b817786563 --- /dev/null +++ b/apps/web/src/components/chat/composerProviderState.tsx @@ -0,0 +1,108 @@ +import { + type ProviderKind, + type ProviderOptionSelection, + type ScopedThreadRef, + type ServerProviderModel, +} from "@t3tools/contracts"; +import { + buildProviderOptionSelectionsFromDescriptors, + getProviderOptionCurrentValue, + getProviderOptionDescriptors, + isClaudeUltrathinkPrompt, +} from "@t3tools/shared/model"; +import type { ReactNode } from "react"; + +import type { DraftId } from "../../composerDraftStore"; +import { getProviderModelCapabilities } from "../../providerModels"; +import { shouldRenderTraitsControls, TraitsMenuContent, TraitsPicker } from "./TraitsPicker"; + +export type ComposerProviderStateInput = { + provider: ProviderKind; + model: string; + models: ReadonlyArray; + prompt: string; + modelOptions: ReadonlyArray | null | undefined; +}; + +export type ComposerProviderState = { + provider: ProviderKind; + promptEffort: string | null; + modelOptionsForDispatch: ReadonlyArray | undefined; + composerFrameClassName?: string; + composerSurfaceClassName?: string; + modelPickerIconClassName?: string; +}; + +type TraitsRenderInput = { + provider: ProviderKind; + threadRef?: ScopedThreadRef; + draftId?: DraftId; + model: string; + models: ReadonlyArray; + modelOptions: ReadonlyArray | undefined; + prompt: string; + onPromptChange: (prompt: string) => void; +}; + +export function getComposerProviderState(input: ComposerProviderStateInput): ComposerProviderState { + const { provider, model, models, prompt, modelOptions } = input; + const caps = getProviderModelCapabilities(models, model, provider); + const descriptors = getProviderOptionDescriptors({ caps, selections: modelOptions }); + const primarySelectDescriptor = descriptors.find( + (descriptor): descriptor is Extract<(typeof descriptors)[number], { type: "select" }> => + descriptor.type === "select", + ); + const primaryValue = getProviderOptionCurrentValue(primarySelectDescriptor ?? null); + const promptEffort = typeof primaryValue === "string" ? primaryValue : null; + const ultrathinkActive = + (primarySelectDescriptor?.promptInjectedValues?.length ?? 0) > 0 && + isClaudeUltrathinkPrompt(prompt); + + return { + provider, + promptEffort, + modelOptionsForDispatch: buildProviderOptionSelectionsFromDescriptors(descriptors), + ...(ultrathinkActive + ? { + composerFrameClassName: "ultrathink-frame", + composerSurfaceClassName: "shadow-[0_0_0_1px_rgba(255,255,255,0.04)_inset]", + modelPickerIconClassName: "ultrathink-chroma", + } + : {}), + }; +} + +function renderTraitsControl( + Component: typeof TraitsMenuContent | typeof TraitsPicker, + input: TraitsRenderInput, +): ReactNode { + const { provider, threadRef, draftId, model, models, modelOptions, prompt, onPromptChange } = + input; + const hasTarget = threadRef !== undefined || draftId !== undefined; + if ( + !hasTarget || + !shouldRenderTraitsControls({ provider, models, model, modelOptions, prompt }) + ) { + return null; + } + return ( + + ); +} + +export function renderProviderTraitsMenuContent(input: TraitsRenderInput): ReactNode { + return renderTraitsControl(TraitsMenuContent, input); +} + +export function renderProviderTraitsPicker(input: TraitsRenderInput): ReactNode { + return renderTraitsControl(TraitsPicker, input); +} diff --git a/apps/web/src/components/settings/SettingsPanels.tsx b/apps/web/src/components/settings/SettingsPanels.tsx index b1e7cf81f6..1e8cffd0c4 100644 --- a/apps/web/src/components/settings/SettingsPanels.tsx +++ b/apps/web/src/components/settings/SettingsPanels.tsx @@ -11,7 +11,6 @@ import { import { useQueryClient } from "@tanstack/react-query"; import { type ReactNode, useCallback, useMemo, useRef, useState } from "react"; import { - PROVIDER_DISPLAY_NAMES, type DesktopUpdateChannel, type ScopedThreadRef, type ProviderKind, @@ -20,8 +19,7 @@ import { } from "@t3tools/contracts"; import { scopeThreadRef } from "@t3tools/client-runtime"; import { DEFAULT_UNIFIED_SETTINGS } from "@t3tools/contracts/settings"; -import { normalizeModelSlug } from "@t3tools/shared/model"; -import { createModelSelection } from "@t3tools/shared/model"; +import { createModelSelection, normalizeModelSlug } from "@t3tools/shared/model"; import { Equal } from "effect"; import { APP_VERSION } from "../../branding"; import { @@ -79,6 +77,7 @@ import { useServerObservability, useServerProviders, } from "../../rpc/serverState"; +import { formatProviderKindLabel } from "../../providerModels"; const THEME_OPTIONS = [ { @@ -1172,7 +1171,9 @@ export function GeneralSettingsPanel() { const customModelInput = customModelInputByProvider[providerCard.provider]; const customModelError = customModelErrorByProvider[providerCard.provider] ?? null; const providerDisplayName = - PROVIDER_DISPLAY_NAMES[providerCard.provider] ?? providerCard.title; + providerCard.liveProvider?.displayName?.trim() || + providerCard.title || + formatProviderKindLabel(providerCard.provider); return (
@@ -1471,11 +1472,22 @@ export function GeneralSettingsPanel() { {providerCard.models.map((model) => { const caps = model.capabilities; const capLabels: string[] = []; - if (caps?.supportsFastMode) capLabels.push("Fast mode"); - if (caps?.supportsThinkingToggle) capLabels.push("Thinking"); + const descriptors = caps?.optionDescriptors ?? []; + if (descriptors.some((descriptor) => descriptor.id === "fastMode")) { + capLabels.push("Fast mode"); + } + if (descriptors.some((descriptor) => descriptor.id === "thinking")) { + capLabels.push("Thinking"); + } if ( - caps?.reasoningEffortLevels && - caps.reasoningEffortLevels.length > 0 + descriptors.some( + (descriptor) => + descriptor.type === "select" && + (descriptor.id === "reasoningEffort" || + descriptor.id === "effort" || + descriptor.id === "reasoning" || + descriptor.id === "variant"), + ) ) { capLabels.push("Reasoning"); } diff --git a/apps/web/src/composerDraftStore.test.ts b/apps/web/src/composerDraftStore.test.ts index d789d7d510..9416b42ff9 100644 --- a/apps/web/src/composerDraftStore.test.ts +++ b/apps/web/src/composerDraftStore.test.ts @@ -10,8 +10,38 @@ import { ProjectId, ThreadId, type ModelSelection, - type ProviderModelOptions, + type ProviderKind, + type ProviderOptionSelection, } from "@t3tools/contracts"; +import { createModelSelection } from "@t3tools/shared/model"; + +type ProviderOptionSelectionBag = ReadonlyArray; +type ProviderOptionSelectionsByProvider = Partial>; + +function toSelections( + options: Record | undefined, +): ReadonlyArray { + const result: Array = []; + if (!options) return result; + for (const [id, value] of Object.entries(options)) { + if (typeof value === "string" || typeof value === "boolean") { + result.push({ id, value }); + } + } + return result; +} + +function selectionsByProvider( + options: Partial>>, +): ProviderOptionSelectionsByProvider { + const result: ProviderOptionSelectionsByProvider = {}; + for (const [provider, bag] of Object.entries(options) as Array< + [ProviderKind, Record] + >) { + result[provider] = toSelections(bag); + } + return result; +} import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import { @@ -93,17 +123,15 @@ function resetComposerDraftStore() { function modelSelection( provider: "codex" | "claudeAgent" | "cursor", model: string, - options?: ModelSelection["options"], + options?: Record, ): ModelSelection { - return { - provider, - model, - ...(options ? { options } : {}), - } as ModelSelection; + return createModelSelection(provider, model, toSelections(options)); } -function providerModelOptions(options: ProviderModelOptions): ProviderModelOptions { - return options; +function providerModelOptions( + options: Partial>>, +): ProviderOptionSelectionsByProvider { + return selectionsByProvider(options); } const TEST_ENVIRONMENT_ID = EnvironmentId.make("environment-local"); @@ -941,14 +969,9 @@ describe("composerDraftStore modelSelection", () => { }), ); - store.setProviderModelOptions( - threadRef, - "claudeAgent", - { - thinking: false, - }, - { persistSticky: true }, - ); + store.setProviderModelOptions(threadRef, "claudeAgent", toSelections({ thinking: false }), { + persistSticky: true, + }); expect(draftFor(threadId, TEST_ENVIRONMENT_ID)?.modelSelectionByProvider.claudeAgent).toEqual( modelSelection("claudeAgent", "claude-opus-4-6", { @@ -972,9 +995,7 @@ describe("composerDraftStore modelSelection", () => { }), ); - store.setProviderModelOptions(threadRef, "claudeAgent", { - thinking: true, - }); + store.setProviderModelOptions(threadRef, "claudeAgent", toSelections({ thinking: true })); expect(draftFor(threadId, TEST_ENVIRONMENT_ID)?.modelSelectionByProvider.claudeAgent).toEqual( modelSelection("claudeAgent", "claude-opus-4-6", { @@ -989,10 +1010,11 @@ describe("composerDraftStore modelSelection", () => { store.setModelSelection(threadRef, modelSelection("codex", "gpt-5.4", { fastMode: true })); - store.setProviderModelOptions(threadRef, "codex", { - reasoningEffort: "high", - fastMode: false, - }); + store.setProviderModelOptions( + threadRef, + "codex", + toSelections({ reasoningEffort: "high", fastMode: false }), + ); expect(draftFor(threadId, TEST_ENVIRONMENT_ID)?.modelSelectionByProvider.codex).toEqual( modelSelection("codex", "gpt-5.4", { @@ -1014,11 +1036,11 @@ describe("composerDraftStore modelSelection", () => { }), ); - store.setProviderModelOptions(threadRef, "cursor", { - reasoning: "medium", - fastMode: false, - thinking: true, - }); + store.setProviderModelOptions( + threadRef, + "cursor", + toSelections({ reasoning: "medium", fastMode: false, thinking: true }), + ); expect(draftFor(threadId, TEST_ENVIRONMENT_ID)?.modelSelectionByProvider.cursor).toEqual( modelSelection("cursor", "claude-opus-4-6", { @@ -1032,17 +1054,10 @@ describe("composerDraftStore modelSelection", () => { it("preserves the selected Cursor model when only traits change", () => { const store = useComposerDraftStore.getState(); - store.setProviderModelOptions( - threadRef, - "cursor", - { - reasoning: "high", - }, - { - model: "gpt-5.4", - persistSticky: true, - }, - ); + store.setProviderModelOptions(threadRef, "cursor", toSelections({ reasoning: "high" }), { + model: "gpt-5.4", + persistSticky: true, + }); expect(draftFor(threadId, TEST_ENVIRONMENT_ID)?.modelSelectionByProvider.cursor).toEqual( modelSelection("cursor", "gpt-5.4", { @@ -1067,9 +1082,7 @@ describe("composerDraftStore modelSelection", () => { modelSelection("claudeAgent", "claude-opus-4-6", { effort: "max" }), ); - store.setProviderModelOptions(threadRef, "claudeAgent", { - thinking: false, - }); + store.setProviderModelOptions(threadRef, "claudeAgent", toSelections({ thinking: false })); expect(draftFor(threadId, TEST_ENVIRONMENT_ID)?.modelSelectionByProvider.claudeAgent).toEqual( modelSelection("claudeAgent", "claude-opus-4-6", { @@ -1097,8 +1110,13 @@ describe("composerDraftStore modelSelection", () => { store.setModelOptions(threadRef, providerModelOptions({ codex: { reasoningEffort: "xhigh" } })); const draft = draftFor(threadId, TEST_ENVIRONMENT_ID); - expect(draft?.modelSelectionByProvider.codex?.options).toEqual({ reasoningEffort: "xhigh" }); - expect(draft?.modelSelectionByProvider.claudeAgent?.options).toEqual({ effort: "max" }); + expect(draft?.modelSelectionByProvider.codex?.options).toEqual( + createModelSelection("codex", "gpt-5.4", toSelections({ reasoningEffort: "xhigh" })).options, + ); + expect(draft?.modelSelectionByProvider.claudeAgent?.options).toEqual( + createModelSelection("claudeAgent", "claude-opus-4-6", toSelections({ effort: "max" })) + .options, + ); }); it("preserves other provider options when switching the active model selection", () => { @@ -1118,7 +1136,9 @@ describe("composerDraftStore modelSelection", () => { expect(draft?.modelSelectionByProvider.claudeAgent).toEqual( modelSelection("claudeAgent", "claude-opus-4-6", { effort: "max" }), ); - expect(draft?.modelSelectionByProvider.codex?.options).toEqual({ fastMode: true }); + expect(draft?.modelSelectionByProvider.codex?.options).toEqual( + createModelSelection("codex", "gpt-5.4", toSelections({ fastMode: true })).options, + ); expect(draft?.activeProvider).toBe("claudeAgent"); }); @@ -1127,14 +1147,9 @@ describe("composerDraftStore modelSelection", () => { store.setModelSelection(threadRef, modelSelection("codex", "gpt-5.4")); - store.setProviderModelOptions( - threadRef, - "codex", - { - fastMode: true, - }, - { persistSticky: true }, - ); + store.setProviderModelOptions(threadRef, "codex", toSelections({ fastMode: true }), { + persistSticky: true, + }); expect(useComposerDraftStore.getState().stickyModelSelectionByProvider.codex).toEqual( modelSelection("codex", "gpt-5.4", { @@ -1154,14 +1169,9 @@ describe("composerDraftStore modelSelection", () => { modelSelection("claudeAgent", "claude-opus-4-6", { effort: "max" }), ); - store.setProviderModelOptions( - threadRef, - "claudeAgent", - { - thinking: false, - }, - { persistSticky: false }, - ); + store.setProviderModelOptions(threadRef, "claudeAgent", toSelections({ thinking: false }), { + persistSticky: false, + }); expect(draftFor(threadId, TEST_ENVIRONMENT_ID)?.modelSelectionByProvider.claudeAgent).toEqual( modelSelection("claudeAgent", "claude-opus-4-6", { @@ -1279,12 +1289,15 @@ describe("composerDraftStore provider-scoped option updates", () => { reasoningEffort: "medium", }), ); - store.setProviderModelOptions(threadRef, "claudeAgent", { effort: "max" }); + store.setProviderModelOptions(threadRef, "claudeAgent", toSelections({ effort: "max" })); const draft = draftFor(threadId, TEST_ENVIRONMENT_ID); expect(draft?.modelSelectionByProvider.codex).toEqual( modelSelection("codex", "gpt-5.3-codex", { reasoningEffort: "medium" }), ); - expect(draft?.modelSelectionByProvider.claudeAgent?.options).toEqual({ effort: "max" }); + expect(draft?.modelSelectionByProvider.claudeAgent?.options).toEqual( + createModelSelection("claudeAgent", "claude-opus-4-6", toSelections({ effort: "max" })) + .options, + ); expect(draft?.activeProvider).toBe("codex"); }); }); diff --git a/apps/web/src/composerDraftStore.ts b/apps/web/src/composerDraftStore.ts index 36304fc023..cdd11a77b1 100644 --- a/apps/web/src/composerDraftStore.ts +++ b/apps/web/src/composerDraftStore.ts @@ -1,16 +1,11 @@ import { - CURSOR_REASONING_OPTIONS, DEFAULT_MODEL_BY_PROVIDER, - type CursorModelOptions, - type CursorReasoningOption, - ClaudeAgentEffort, - CodexReasoningEffort, type EnvironmentId, ModelSelection, ProjectId, ProviderInteractionMode, ProviderKind, - ProviderModelOptions, + ProviderOptionSelection, RuntimeMode, type ServerProvider, type ScopedProjectRef, @@ -46,7 +41,7 @@ import { getDefaultServerModel } from "./providerModels"; import { UnifiedSettings } from "@t3tools/contracts/settings"; export const COMPOSER_DRAFT_STORAGE_KEY = "t3code:composer-drafts:v1"; -const COMPOSER_DRAFT_STORAGE_VERSION = 5; +const COMPOSER_DRAFT_STORAGE_VERSION = 6; const DraftThreadEnvModeSchema = Schema.Literals(["local", "worktree"]); const isRuntimeMode = Schema.is(RuntimeMode); export type DraftThreadEnvMode = typeof DraftThreadEnvModeSchema.Type; @@ -106,23 +101,30 @@ const PersistedComposerThreadDraftState = Schema.Struct({ }); type PersistedComposerThreadDraftState = typeof PersistedComposerThreadDraftState.Type; -const LegacyCodexFields = Schema.Struct({ - effort: Schema.optionalKey(CodexReasoningEffort), - codexFastMode: Schema.optionalKey(Schema.Boolean), - serviceTier: Schema.optionalKey(Schema.String), -}); -type LegacyCodexFields = typeof LegacyCodexFields.Type; +/** + * Per-provider record of generic option selections. Used as a transient + * representation when migrating legacy v2 storage payloads and when + * deriving per-provider option bundles for downstream consumers. + */ +type ProviderOptionSelectionsByProvider = Partial< + Record> +>; -const LegacyThreadModelFields = Schema.Struct({ - provider: Schema.optionalKey(ProviderKind), - model: Schema.optionalKey(Schema.String), - modelOptions: Schema.optionalKey(Schema.NullOr(ProviderModelOptions)), -}); -type LegacyThreadModelFields = typeof LegacyThreadModelFields.Type; +type LegacyCodexFields = { + effort?: unknown; + codexFastMode?: unknown; + serviceTier?: unknown; +}; + +type LegacyThreadModelFields = { + provider?: unknown; + model?: unknown; + modelOptions?: unknown; +}; type LegacyV2ThreadDraftFields = { modelSelection?: ModelSelection | null; - modelOptions?: ProviderModelOptions | null; + modelOptions?: unknown; }; type LegacyPersistedComposerThreadDraftState = PersistedComposerThreadDraftState & @@ -130,16 +132,15 @@ type LegacyPersistedComposerThreadDraftState = PersistedComposerThreadDraftState LegacyThreadModelFields & LegacyV2ThreadDraftFields; -const LegacyStickyModelFields = Schema.Struct({ - stickyProvider: Schema.optionalKey(ProviderKind), - stickyModel: Schema.optionalKey(Schema.String), - stickyModelOptions: Schema.optionalKey(Schema.NullOr(ProviderModelOptions)), -}); -type LegacyStickyModelFields = typeof LegacyStickyModelFields.Type; +type LegacyStickyModelFields = { + stickyProvider?: unknown; + stickyModel?: unknown; + stickyModelOptions?: unknown; +}; type LegacyV2StoreFields = { stickyModelSelection?: ModelSelection | null; - stickyModelOptions?: ProviderModelOptions | null; + stickyModelOptions?: unknown; projectDraftThreadIdByProjectId?: Record | null; draftsByThreadId?: Record | null; draftThreadsByThreadId?: Record | null; @@ -334,15 +335,19 @@ interface ComposerDraftStoreState { threadRef: ComposerThreadTarget, modelSelection: ModelSelection | null | undefined, ) => void; + /** Replace the model options for one or more providers in the draft. */ setModelOptions: ( threadRef: ComposerThreadTarget, - modelOptions: ProviderModelOptions | null | undefined, + modelOptions: + | Partial>> + | null + | undefined, ) => void; applyStickyState: (threadRef: ComposerThreadTarget) => void; setProviderModelOptions: ( threadRef: ComposerThreadTarget, provider: ProviderKind, - nextProviderOptions: ProviderModelOptions[ProviderKind] | null | undefined, + nextProviderOptions: ReadonlyArray | null | undefined, options?: { model?: string | null | undefined; persistSticky?: boolean; @@ -379,7 +384,7 @@ interface ComposerDraftStoreState { export interface EffectiveComposerModelState { selectedModel: string; - modelOptions: ProviderModelOptions | null; + modelOptions: ProviderOptionSelectionsByProvider | null; } interface ComposerDraftModelState { @@ -387,29 +392,48 @@ interface ComposerDraftModelState { modelSelectionByProvider: Partial>; } -function providerModelOptionsFromSelection( +function providerSelectionsFromModelSelection( modelSelection: ModelSelection | null | undefined, -): ProviderModelOptions | null { - if (!modelSelection?.options) { +): ProviderOptionSelectionsByProvider | null { + if (!modelSelection) { return null; } - - return { - [modelSelection.provider]: modelSelection.options, - }; + const options = modelSelection.options; + if (!options || options.length === 0) { + return null; + } + return { [modelSelection.provider]: options } as ProviderOptionSelectionsByProvider; } function modelSelectionByProviderToOptions( map: Partial> | null | undefined, -): ProviderModelOptions | null { +): ProviderOptionSelectionsByProvider | null { if (!map) return null; - const result: Record = {}; + const result: Partial>> = {}; for (const [provider, selection] of Object.entries(map)) { - if (selection?.options) { - result[provider] = selection.options; + if (selection?.options && selection.options.length > 0) { + result[provider as ProviderKind] = selection.options; } } - return Object.keys(result).length > 0 ? (result as ProviderModelOptions) : null; + return Object.keys(result).length > 0 ? result : null; +} + +function cloneModelSelection(selection: ModelSelection): DeepMutable { + return { + ...selection, + ...(selection.options ? { options: selection.options.map((option) => ({ ...option })) } : {}), + } as DeepMutable; +} + +function cloneModelSelectionByProvider( + selections: Partial>, +): DeepMutable>> { + return Object.fromEntries( + Object.entries(selections).map(([provider, selection]) => [ + provider, + selection ? cloneModelSelection(selection) : selection, + ]), + ) as DeepMutable>>; } const EMPTY_PERSISTED_DRAFT_STORE_STATE = Object.freeze({ @@ -536,149 +560,92 @@ function normalizeProviderKind(value: unknown): ProviderKind | null { : null; } +/** + * Coerce an unknown value into a `ReadonlyArray`. + * Accepts either: + * - the v3 representation: an array of `{ id, value }` entries + * - the legacy v2 representation: a record of `{ id: string | boolean }` + * + * Validation is intentionally permissive: descriptors are the source of truth + * for which option ids are meaningful for a given provider/model. Anything + * outside the descriptor list is harmless trailing data and will simply be + * ignored downstream. + */ +function coerceProviderOptionSelections( + value: unknown, +): ReadonlyArray | undefined { + if (Array.isArray(value)) { + const out: ProviderOptionSelection[] = []; + for (const entry of value) { + if (!entry || typeof entry !== "object") continue; + const record = entry as Record; + const id = record.id; + const optionValue = record.value; + if (typeof id !== "string" || id.length === 0) continue; + if (typeof optionValue === "string" || typeof optionValue === "boolean") { + out.push({ id, value: optionValue }); + } + } + return out.length > 0 ? out : undefined; + } + if (value && typeof value === "object") { + const record = value as Record; + const out: ProviderOptionSelection[] = []; + for (const [id, raw] of Object.entries(record)) { + if (typeof raw === "string" || typeof raw === "boolean") { + out.push({ id, value: raw }); + } + } + return out.length > 0 ? out : undefined; + } + return undefined; +} + +/** + * Normalize a per-provider options bag from either the v3 or legacy v2 shape. + * + * `provider` and `legacy` parameters are migration-only inputs used to + * recover legacy codex fields (effort/codexFastMode/serviceTier) that lived + * directly on the draft instead of inside `modelOptions.codex`. + */ function normalizeProviderModelOptions( value: unknown, provider?: ProviderKind | null, legacy?: LegacyCodexFields, -): ProviderModelOptions | null { +): ProviderOptionSelectionsByProvider | null { const candidate = value && typeof value === "object" ? (value as Record) : null; - const codexCandidate = - candidate?.codex && typeof candidate.codex === "object" - ? (candidate.codex as Record) - : null; - const claudeCandidate = - candidate?.claudeAgent && typeof candidate.claudeAgent === "object" - ? (candidate.claudeAgent as Record) - : null; - const cursorCandidate = - candidate?.cursor && typeof candidate.cursor === "object" - ? (candidate.cursor as Record) - : null; - const openCodeCandidate = - candidate?.opencode && typeof candidate.opencode === "object" - ? (candidate.opencode as Record) - : null; - - const isCodexReasoningEffort = Schema.is(CodexReasoningEffort); - const isClaudeAgentEffort = Schema.is(ClaudeAgentEffort); - - const codexReasoningEffort = isCodexReasoningEffort(codexCandidate?.reasoningEffort) - ? codexCandidate.reasoningEffort - : provider === "codex" - ? isCodexReasoningEffort(legacy?.effort) - ? legacy.effort - : undefined - : undefined; - const codexFastMode = - codexCandidate?.fastMode === true - ? true - : codexCandidate?.fastMode === false - ? false - : (provider === "codex" && legacy?.codexFastMode === true) || - (typeof legacy?.serviceTier === "string" && legacy.serviceTier === "fast") - ? true - : undefined; - const codex = - codexReasoningEffort !== undefined || codexFastMode !== undefined - ? { - ...(codexReasoningEffort !== undefined ? { reasoningEffort: codexReasoningEffort } : {}), - ...(codexFastMode !== undefined ? { fastMode: codexFastMode } : {}), - } - : undefined; - - const claudeThinking = - claudeCandidate?.thinking === true - ? true - : claudeCandidate?.thinking === false - ? false - : undefined; - const claudeEffort = isClaudeAgentEffort(claudeCandidate?.effort) - ? claudeCandidate.effort - : undefined; - const claudeFastMode = - claudeCandidate?.fastMode === true - ? true - : claudeCandidate?.fastMode === false - ? false - : undefined; - const claudeContextWindow = - typeof claudeCandidate?.contextWindow === "string" && claudeCandidate.contextWindow.length > 0 - ? claudeCandidate.contextWindow - : undefined; - const claude = - claudeThinking !== undefined || - claudeEffort !== undefined || - claudeFastMode !== undefined || - claudeContextWindow !== undefined - ? { - ...(claudeThinking !== undefined ? { thinking: claudeThinking } : {}), - ...(claudeEffort !== undefined ? { effort: claudeEffort } : {}), - ...(claudeFastMode !== undefined ? { fastMode: claudeFastMode } : {}), - ...(claudeContextWindow !== undefined ? { contextWindow: claudeContextWindow } : {}), - } - : undefined; - - const cursorReasoningRaw = cursorCandidate?.reasoning; - const cursorReasoning: CursorReasoningOption | undefined = - typeof cursorReasoningRaw === "string" && - (CURSOR_REASONING_OPTIONS as readonly string[]).includes(cursorReasoningRaw) - ? (cursorReasoningRaw as CursorReasoningOption) - : undefined; - const cursorFastMode = - cursorCandidate?.fastMode === true - ? true - : cursorCandidate?.fastMode === false - ? false - : undefined; - const cursorThinking = - cursorCandidate?.thinking === true - ? true - : cursorCandidate?.thinking === false - ? false - : undefined; - const cursorContextWindow = - typeof cursorCandidate?.contextWindow === "string" && cursorCandidate.contextWindow.length > 0 - ? cursorCandidate.contextWindow - : undefined; - - const cursor: CursorModelOptions | undefined = - cursorCandidate !== null - ? (() => { - const nextCursor = { - ...(cursorReasoning ? { reasoning: cursorReasoning } : {}), - ...(cursorFastMode !== undefined ? { fastMode: cursorFastMode } : {}), - ...(cursorThinking !== undefined ? { thinking: cursorThinking } : {}), - ...(cursorContextWindow !== undefined ? { contextWindow: cursorContextWindow } : {}), - } satisfies CursorModelOptions; - return Object.keys(nextCursor).length > 0 ? nextCursor : undefined; - })() - : undefined; - - const openCodeVariant = - typeof openCodeCandidate?.variant === "string" && openCodeCandidate.variant.length > 0 - ? openCodeCandidate.variant - : undefined; - const openCodeAgent = - typeof openCodeCandidate?.agent === "string" && openCodeCandidate.agent.length > 0 - ? openCodeCandidate.agent - : undefined; - const opencode = - openCodeVariant !== undefined || openCodeAgent !== undefined - ? { - ...(openCodeVariant !== undefined ? { variant: openCodeVariant } : {}), - ...(openCodeAgent !== undefined ? { agent: openCodeAgent } : {}), - } - : undefined; - - if (!codex && !claude && cursor === undefined && !opencode) { - return null; + const result: Partial>> = {}; + for (const providerKey of ["codex", "claudeAgent", "cursor", "opencode"] as const) { + const selections = coerceProviderOptionSelections(candidate?.[providerKey]); + if (selections) { + result[providerKey] = selections; + } } - return { - ...(codex ? { codex } : {}), - ...(claude ? { claudeAgent: claude } : {}), - ...(cursor !== undefined ? { cursor } : {}), - ...(opencode ? { opencode } : {}), - }; + + // Recover legacy codex fields that lived outside modelOptions. + if (provider === "codex" && legacy) { + const codexExtras: ProviderOptionSelection[] = []; + if (typeof legacy.effort === "string" && legacy.effort.length > 0) { + codexExtras.push({ id: "reasoningEffort", value: legacy.effort }); + } + const fastMode = + legacy.codexFastMode === true || + (typeof legacy.serviceTier === "string" && legacy.serviceTier === "fast"); + if (fastMode) { + codexExtras.push({ id: "fastMode", value: true }); + } + if (codexExtras.length > 0) { + const existing = result.codex ?? []; + const existingIds = new Set(existing.map((entry) => entry.id)); + const merged = [...existing]; + for (const extra of codexExtras) { + if (!existingIds.has(extra.id)) merged.push(extra); + } + result.codex = merged; + } + } + + return Object.keys(result).length > 0 ? result : null; } function normalizeModelSelection( @@ -703,6 +670,10 @@ function normalizeModelSelection( if (!model) { return null; } + if (Array.isArray(candidate?.options)) { + const selections = coerceProviderOptionSelections(candidate.options); + return createModelSelection(provider, model, selections); + } const modelOptions = normalizeProviderModelOptions( candidate?.options ? { [provider]: candidate.options } : legacy?.modelOptions, provider, @@ -716,7 +687,7 @@ function normalizeModelSelection( function legacySyncModelSelectionOptions( modelSelection: ModelSelection | null, - modelOptions: ProviderModelOptions | null | undefined, + modelOptions: ProviderOptionSelectionsByProvider | null | undefined, ): ModelSelection | null { if (modelSelection === null) { return null; @@ -727,9 +698,9 @@ function legacySyncModelSelectionOptions( function legacyMergeModelSelectionIntoProviderModelOptions( modelSelection: ModelSelection | null, - currentModelOptions: ProviderModelOptions | null | undefined, -): ProviderModelOptions | null { - if (modelSelection?.options === undefined) { + currentModelOptions: ProviderOptionSelectionsByProvider | null | undefined, +): ProviderOptionSelectionsByProvider | null { + if (!modelSelection?.options || modelSelection.options.length === 0) { return normalizeProviderModelOptions(currentModelOptions); } return legacyReplaceProviderModelOptions( @@ -740,35 +711,30 @@ function legacyMergeModelSelectionIntoProviderModelOptions( } function legacyReplaceProviderModelOptions( - currentModelOptions: ProviderModelOptions | null | undefined, + currentModelOptions: ProviderOptionSelectionsByProvider | null | undefined, provider: ProviderKind, - nextProviderOptions: ProviderModelOptions[ProviderKind] | null | undefined, -): ProviderModelOptions | null { + nextProviderOptions: ReadonlyArray | null | undefined, +): ProviderOptionSelectionsByProvider | null { const { [provider]: _discardedProviderModelOptions, ...otherProviderModelOptions } = currentModelOptions ?? {}; - const normalizedNextProviderOptions = normalizeProviderModelOptions( - { [provider]: nextProviderOptions }, - provider, - ); - - return normalizeProviderModelOptions({ - ...otherProviderModelOptions, - ...(normalizedNextProviderOptions ? normalizedNextProviderOptions : {}), - }); + const merged: ProviderOptionSelectionsByProvider = { ...otherProviderModelOptions }; + if (nextProviderOptions && nextProviderOptions.length > 0) { + merged[provider] = nextProviderOptions; + } + return Object.keys(merged).length > 0 ? merged : null; } // ── New helpers for the consolidated representation ──────────────────── function legacyToModelSelectionByProvider( modelSelection: ModelSelection | null, - modelOptions: ProviderModelOptions | null | undefined, + modelOptions: ProviderOptionSelectionsByProvider | null | undefined, ): Partial> { const result: Partial> = {}; - // Add entries from the options bag (for non-active providers) if (modelOptions) { for (const provider of ["codex", "claudeAgent", "cursor", "opencode"] as const) { const options = modelOptions[provider]; - if (options && Object.keys(options).length > 0) { + if (options && options.length > 0) { result[provider] = createModelSelection( provider, modelSelection?.provider === provider @@ -779,7 +745,6 @@ function legacyToModelSelectionByProvider( } } } - // Add/overwrite the active selection (it's authoritative for its provider) if (modelSelection) { result[modelSelection.provider] = modelSelection; } @@ -813,8 +778,8 @@ export function deriveEffectiveComposerModelState(input: { : baseModel; const modelOptions = modelSelectionByProviderToOptions(input.draft?.modelSelectionByProvider) ?? - providerModelOptionsFromSelection(input.threadModelSelection) ?? - providerModelOptionsFromSelection(input.projectModelSelection) ?? + providerSelectionsFromModelSelection(input.threadModelSelection) ?? + providerSelectionsFromModelSelection(input.projectModelSelection) ?? null; return { @@ -1425,7 +1390,7 @@ function normalizePersistedDraftsByThreadId( { provider: legacyDraftCandidate.provider, model: legacyDraftCandidate.model, - modelOptions: normalizedModelOptions ?? legacyDraftCandidate.modelOptions, + modelOptions: normalizedModelOptions ?? (legacyDraftCandidate.modelOptions as unknown), legacyCodex: legacyDraftCandidate, }, ); @@ -1472,7 +1437,12 @@ function normalizePersistedDraftsByThreadId( prompt, attachments, ...(terminalContexts.length > 0 ? { terminalContexts } : {}), - ...(hasModelData ? { modelSelectionByProvider, activeProvider } : {}), + ...(hasModelData + ? { + modelSelectionByProvider: cloneModelSelectionByProvider(modelSelectionByProvider), + activeProvider, + } + : {}), ...(runtimeMode ? { runtimeMode } : {}), ...(interactionMode ? { interactionMode } : {}), }; @@ -1573,7 +1543,7 @@ function partializeComposerDraftStoreState( : {}), ...(hasModelData ? { - modelSelectionByProvider: draft.modelSelectionByProvider, + modelSelectionByProvider: cloneModelSelectionByProvider(draft.modelSelectionByProvider), activeProvider: draft.activeProvider, } : {}), @@ -2304,27 +2274,24 @@ const composerDraftStore = create()( if (threadKey.length === 0) { return; } - const normalizedOpts = normalizeProviderModelOptions(modelOptions); set((state) => { const existing = state.draftsByThreadKey[threadKey]; - if (!existing && normalizedOpts === null) { + if (!existing && (!modelOptions || Object.keys(modelOptions).length === 0)) { return state; } const base = existing ?? createEmptyThreadDraft(); const nextMap = { ...base.modelSelectionByProvider }; for (const provider of ["codex", "claudeAgent", "cursor", "opencode"] as const) { - // Only touch providers explicitly present in the input - if (!normalizedOpts || !(provider in normalizedOpts)) continue; - const opts = normalizedOpts[provider]; + if (!modelOptions || !(provider in modelOptions)) continue; + const opts = modelOptions[provider]; const current = nextMap[provider]; - if (opts) { + if (opts && opts.length > 0) { nextMap[provider] = createModelSelection( provider, current?.model ?? DEFAULT_MODEL_BY_PROVIDER[provider], opts, ); } else if (current?.options) { - // Remove options but keep the selection const { options: _, ...rest } = current; nextMap[provider] = rest as ModelSelection; } @@ -2357,12 +2324,8 @@ const composerDraftStore = create()( const fallbackModel = normalizeModelSlug(options?.model, normalizedProvider) ?? DEFAULT_MODEL_BY_PROVIDER[normalizedProvider]; - // Normalize just this provider's options - const normalizedOpts = normalizeProviderModelOptions( - { [normalizedProvider]: nextProviderOptions }, - normalizedProvider, - ); - const providerOpts = normalizedOpts?.[normalizedProvider]; + const providerOpts = + nextProviderOptions && nextProviderOptions.length > 0 ? nextProviderOptions : undefined; set((state) => { const existing = state.draftsByThreadKey[threadKey]; @@ -2377,7 +2340,7 @@ const composerDraftStore = create()( currentForProvider?.model ?? fallbackModel, providerOpts, ); - } else if (currentForProvider?.options) { + } else if (currentForProvider && (currentForProvider.options?.length ?? 0) > 0) { const { options: _, ...rest } = currentForProvider; nextMap[normalizedProvider] = rest as ModelSelection; } @@ -2397,7 +2360,7 @@ const composerDraftStore = create()( stickyBase.model, providerOpts, ); - } else if (stickyBase.options) { + } else if ((stickyBase.options?.length ?? 0) > 0) { const { options: _, ...rest } = stickyBase; nextStickyMap[normalizedProvider] = rest as ModelSelection; } diff --git a/apps/web/src/modelSelection.ts b/apps/web/src/modelSelection.ts index 2ffa8e2014..80e9e241e7 100644 --- a/apps/web/src/modelSelection.ts +++ b/apps/web/src/modelSelection.ts @@ -9,7 +9,7 @@ import { normalizeModelSlug, resolveSelectableModel, } from "@t3tools/shared/model"; -import { getComposerProviderState } from "./components/chat/composerProviderRegistry"; +import { getComposerProviderState } from "./components/chat/composerProviderState"; import { UnifiedSettings } from "@t3tools/contracts/settings"; import { getDefaultServerModel, @@ -21,14 +21,6 @@ import { ModelEsque } from "./components/chat/providerIconUtils"; const MAX_CUSTOM_MODEL_COUNT = 32; export const MAX_CUSTOM_MODEL_LENGTH = 256; -export type ProviderCustomModelConfig = { - provider: ProviderKind; - title: string; - description: string; - placeholder: string; - example: string; -}; - export interface AppModelOption { slug: string; name: string; @@ -37,39 +29,6 @@ export interface AppModelOption { isCustom: boolean; } -const PROVIDER_CUSTOM_MODEL_CONFIG: Record = { - codex: { - provider: "codex", - title: "Codex", - description: "Save additional Codex model slugs for the picker and `/model` command.", - placeholder: "your-codex-model-slug", - example: "gpt-6.7-codex-ultra-preview", - }, - claudeAgent: { - provider: "claudeAgent", - title: "Claude", - description: "Save additional Claude model slugs for the picker and `/model` command.", - placeholder: "your-claude-model-slug", - example: "claude-sonnet-5-0", - }, - cursor: { - provider: "cursor", - title: "Cursor", - description: "Save additional Cursor model slugs for the picker and `/model` command.", - placeholder: "your-cursor-model-slug", - example: "claude-sonnet-4-6", - }, - opencode: { - provider: "opencode", - title: "OpenCode", - description: "Save additional OpenCode model slugs in `provider/model` format.", - placeholder: "openai/gpt-5", - example: "anthropic/claude-sonnet-4-5-20250929", - }, -}; - -export const MODEL_PROVIDER_SETTINGS = Object.values(PROVIDER_CUSTOM_MODEL_CONFIG); - export function normalizeCustomModelSlugs( models: Iterable, builtInModelSlugs: ReadonlySet, @@ -222,9 +181,7 @@ export function resolveAppModelSelectionState( model, models: getProviderModels(providers, provider), prompt: "", - modelOptions: { - [provider]: provider === selection.provider ? selection.options : undefined, - }, + modelOptions: provider === selection.provider ? selection.options : undefined, }); return createModelSelection(provider, model, modelOptionsForDispatch); diff --git a/apps/web/src/providerModels.ts b/apps/web/src/providerModels.ts index e901a895f4..229d61ca56 100644 --- a/apps/web/src/providerModels.ts +++ b/apps/web/src/providerModels.ts @@ -1,25 +1,23 @@ import { DEFAULT_MODEL_BY_PROVIDER, - type CursorModelOptions, type ModelCapabilities, type ProviderKind, type ServerProvider, type ServerProviderModel, } from "@t3tools/contracts"; -import { - hasEffortLevel, - normalizeModelSlug, - resolveContextWindow, - trimOrNull, -} from "@t3tools/shared/model"; +import { createModelCapabilities, normalizeModelSlug } from "@t3tools/shared/model"; -const EMPTY_CAPABILITIES: ModelCapabilities = { - reasoningEffortLevels: [], - supportsFastMode: false, - supportsThinkingToggle: false, - contextWindowOptions: [], - promptInjectedEffortLevels: [], -}; +const EMPTY_CAPABILITIES: ModelCapabilities = createModelCapabilities({ + optionDescriptors: [], +}); + +export function formatProviderKindLabel(provider: ProviderKind): string { + return provider + .replace(/([a-z])([A-Z])/g, "$1 $2") + .replace(/[_-]+/g, " ") + .trim() + .replace(/\b\w/g, (char) => char.toUpperCase()); +} export function getProviderModels( providers: ReadonlyArray, @@ -35,6 +33,21 @@ export function getProviderSnapshot( return providers.find((candidate) => candidate.provider === provider); } +export function getProviderDisplayName( + providers: ReadonlyArray, + provider: ProviderKind, +): string { + const snapshot = getProviderSnapshot(providers, provider); + return snapshot?.displayName?.trim() || formatProviderKindLabel(provider); +} + +export function getProviderInteractionModeToggle( + providers: ReadonlyArray, + provider: ProviderKind, +): boolean { + return getProviderSnapshot(providers, provider)?.showInteractionModeToggle ?? true; +} + export function isProviderEnabled( providers: ReadonlyArray, provider: ProviderKind, @@ -76,30 +89,3 @@ export function getDefaultServerModel( DEFAULT_MODEL_BY_PROVIDER[provider] ); } - -export function normalizeCursorModelOptionsWithCapabilities( - caps: ModelCapabilities, - modelOptions: CursorModelOptions | null | undefined, -): CursorModelOptions | undefined { - const reasoning = trimOrNull(modelOptions?.reasoning); - const reasoningValue = - reasoning && hasEffortLevel(caps, reasoning) - ? (reasoning as CursorModelOptions["reasoning"]) - : undefined; - const fastMode = - caps.supportsFastMode && typeof modelOptions?.fastMode === "boolean" - ? modelOptions.fastMode - : undefined; - const thinking = - caps.supportsThinkingToggle && typeof modelOptions?.thinking === "boolean" - ? modelOptions.thinking - : undefined; - const contextWindow = resolveContextWindow(caps, modelOptions?.contextWindow); - const nextOptions: CursorModelOptions = { - ...(reasoningValue ? { reasoning: reasoningValue } : {}), - ...(fastMode !== undefined ? { fastMode } : {}), - ...(thinking !== undefined ? { thinking } : {}), - ...(contextWindow ? { contextWindow } : {}), - }; - return Object.keys(nextOptions).length > 0 ? nextOptions : undefined; -} diff --git a/packages/contracts/src/model.ts b/packages/contracts/src/model.ts index 5bb82caf42..92de00bea3 100644 --- a/packages/contracts/src/model.ts +++ b/packages/contracts/src/model.ts @@ -1,87 +1,127 @@ -import { Schema } from "effect"; +import { Effect, Schema, SchemaTransformation } from "effect"; import { TrimmedNonEmptyString } from "./baseSchemas.ts"; import type { ProviderKind } from "./orchestration.ts"; -export const CODEX_REASONING_EFFORT_OPTIONS = ["xhigh", "high", "medium", "low"] as const; -export const CodexReasoningEffort = Schema.Literals(CODEX_REASONING_EFFORT_OPTIONS); -export type CodexReasoningEffort = typeof CodexReasoningEffort.Type; -export const CLAUDE_AGENT_EFFORT_OPTIONS = [ - "low", - "medium", - "high", - "xhigh", - "max", - "ultrathink", -] as const; -export const ClaudeAgentEffort = Schema.Literals(CLAUDE_AGENT_EFFORT_OPTIONS); -export type ClaudeAgentEffort = typeof ClaudeAgentEffort.Type; -export type ClaudeCodeEffort = ClaudeAgentEffort; -export const CURSOR_REASONING_OPTIONS = ["low", "medium", "high", "max", "xhigh"] as const; -export const CursorReasoningOption = Schema.Literals(CURSOR_REASONING_OPTIONS); -export type CursorReasoningOption = typeof CursorReasoningOption.Type; +export const ProviderOptionDescriptorType = Schema.Literals(["select", "boolean"]); +export type ProviderOptionDescriptorType = typeof ProviderOptionDescriptorType.Type; -export type ProviderReasoningEffort = - | CodexReasoningEffort - | ClaudeAgentEffort - | CursorReasoningOption; - -export const CodexModelOptions = Schema.Struct({ - reasoningEffort: Schema.optional(CodexReasoningEffort), - fastMode: Schema.optional(Schema.Boolean), -}); -export type CodexModelOptions = typeof CodexModelOptions.Type; - -export const ClaudeModelOptions = Schema.Struct({ - thinking: Schema.optional(Schema.Boolean), - effort: Schema.optional(ClaudeAgentEffort), - fastMode: Schema.optional(Schema.Boolean), - contextWindow: Schema.optional(Schema.String), -}); -export type ClaudeModelOptions = typeof ClaudeModelOptions.Type; - -export const CursorModelOptions = Schema.Struct({ - reasoning: Schema.optional(CursorReasoningOption), - fastMode: Schema.optional(Schema.Boolean), - thinking: Schema.optional(Schema.Boolean), - contextWindow: Schema.optional(Schema.String), -}); -export type CursorModelOptions = typeof CursorModelOptions.Type; -export const OpenCodeModelOptions = Schema.Struct({ - variant: Schema.optional(TrimmedNonEmptyString), - agent: Schema.optional(TrimmedNonEmptyString), -}); -export type OpenCodeModelOptions = typeof OpenCodeModelOptions.Type; - -export const ProviderModelOptions = Schema.Struct({ - codex: Schema.optional(CodexModelOptions), - claudeAgent: Schema.optional(ClaudeModelOptions), - cursor: Schema.optional(CursorModelOptions), - opencode: Schema.optional(OpenCodeModelOptions), -}); -export type ProviderModelOptions = typeof ProviderModelOptions.Type; - -export const EffortOption = Schema.Struct({ - value: TrimmedNonEmptyString, +export const ProviderOptionChoice = Schema.Struct({ + id: TrimmedNonEmptyString, label: TrimmedNonEmptyString, + description: Schema.optional(TrimmedNonEmptyString), isDefault: Schema.optional(Schema.Boolean), }); -export type EffortOption = typeof EffortOption.Type; +export type ProviderOptionChoice = typeof ProviderOptionChoice.Type; -export const ContextWindowOption = Schema.Struct({ - value: TrimmedNonEmptyString, +const ProviderOptionDescriptorBase = { + id: TrimmedNonEmptyString, label: TrimmedNonEmptyString, - isDefault: Schema.optional(Schema.Boolean), + description: Schema.optional(TrimmedNonEmptyString), +} as const; + +export const SelectProviderOptionDescriptor = Schema.Struct({ + ...ProviderOptionDescriptorBase, + type: Schema.Literal("select"), + options: Schema.Array(ProviderOptionChoice), + currentValue: Schema.optional(TrimmedNonEmptyString), + promptInjectedValues: Schema.optional(Schema.Array(TrimmedNonEmptyString)), }); -export type ContextWindowOption = typeof ContextWindowOption.Type; +export type SelectProviderOptionDescriptor = typeof SelectProviderOptionDescriptor.Type; + +export const BooleanProviderOptionDescriptor = Schema.Struct({ + ...ProviderOptionDescriptorBase, + type: Schema.Literal("boolean"), + currentValue: Schema.optional(Schema.Boolean), +}); +export type BooleanProviderOptionDescriptor = typeof BooleanProviderOptionDescriptor.Type; + +export const ProviderOptionDescriptor = Schema.Union([ + SelectProviderOptionDescriptor, + BooleanProviderOptionDescriptor, +]); +export type ProviderOptionDescriptor = typeof ProviderOptionDescriptor.Type; + +export const ProviderOptionSelectionValue = Schema.Union([TrimmedNonEmptyString, Schema.Boolean]); +export type ProviderOptionSelectionValue = typeof ProviderOptionSelectionValue.Type; + +export const ProviderOptionSelection = Schema.Struct({ + id: TrimmedNonEmptyString, + value: ProviderOptionSelectionValue, +}); +export type ProviderOptionSelection = typeof ProviderOptionSelection.Type; + +/** + * Legacy on-disk shape for provider option selections, kept readable by the + * decoder so we can tolerate stored data written before the v3 array shape. + * + * Persisted historically as `{ effort: "max", fastMode: true, ... }` inside + * `modelSelection.options`. Migration 026 rewrites stored rows to the + * canonical array shape, but we still see the legacy form in: + * - `settings.json` files from older client builds, + * - SQLite databases that have not yet run migration 026, + * - any future regression that re-introduces the legacy shape. + */ +const LegacyProviderOptionSelectionsObject = Schema.Record(Schema.String, Schema.Unknown); + +const ProviderOptionSelectionsFromLegacyObject = LegacyProviderOptionSelectionsObject.pipe( + Schema.decodeTo( + Schema.Array(ProviderOptionSelection), + SchemaTransformation.transformOrFail({ + decode: (record) => Effect.succeed(coerceLegacyOptionsObjectToArray(record)), + encode: (selections) => Effect.succeed(canonicalSelectionsToLegacyObject(selections)), + }), + ), +); + +/** + * Schema for the `options` field of every `ModelSelection` variant. + * + * Accepts both: + * - the canonical array shape `Array<{ id, value }>` (preferred), and + * - the legacy object shape `Record` from + * pre-migration data. + * + * Always normalizes to the canonical array on decode and re-encodes as the + * canonical array, so any legacy storage gets cleaned up the next time the + * containing record is written back. + */ +export const ProviderOptionSelections = Schema.Union([ + Schema.Array(ProviderOptionSelection), + ProviderOptionSelectionsFromLegacyObject, +]); +export type ProviderOptionSelections = typeof ProviderOptionSelections.Type; + +function coerceLegacyOptionsObjectToArray( + record: Record, +): ReadonlyArray { + const entries: Array = []; + for (const [rawKey, rawValue] of Object.entries(record)) { + const id = typeof rawKey === "string" ? rawKey.trim() : ""; + if (!id) continue; + if (typeof rawValue === "string") { + const trimmed = rawValue.trim(); + if (trimmed) entries.push({ id, value: trimmed }); + } else if (typeof rawValue === "boolean") { + entries.push({ id, value: rawValue }); + } + // Drop anything else (numbers, null, nested objects/arrays) to match the + // permissive normalization performed by migration 026. + } + return entries; +} + +function canonicalSelectionsToLegacyObject( + selections: ReadonlyArray, +): Record { + const out: Record = {}; + for (const { id, value } of selections) { + out[id] = value; + } + return out; +} export const ModelCapabilities = Schema.Struct({ - reasoningEffortLevels: Schema.Array(EffortOption), - supportsFastMode: Schema.Boolean, - supportsThinkingToggle: Schema.Boolean, - contextWindowOptions: Schema.Array(ContextWindowOption), - promptInjectedEffortLevels: Schema.Array(TrimmedNonEmptyString), - variantOptions: Schema.optional(Schema.Array(EffortOption)), - agentOptions: Schema.optional(Schema.Array(EffortOption)), + optionDescriptors: Schema.optional(Schema.Array(ProviderOptionDescriptor)), }); export type ModelCapabilities = typeof ModelCapabilities.Type; diff --git a/packages/contracts/src/orchestration.test.ts b/packages/contracts/src/orchestration.test.ts index 223efd6d27..190e09aa63 100644 --- a/packages/contracts/src/orchestration.test.ts +++ b/packages/contracts/src/orchestration.test.ts @@ -33,6 +33,13 @@ const decodeThreadTurnStartRequestedPayload = Schema.decodeUnknownEffect( const decodeOrchestrationLatestTurn = Schema.decodeUnknownEffect(OrchestrationLatestTurn); const decodeOrchestrationProposedPlan = Schema.decodeUnknownEffect(OrchestrationProposedPlan); const decodeOrchestrationSession = Schema.decodeUnknownEffect(OrchestrationSession); + +function getOptionValue( + options: ReadonlyArray<{ id: string; value: unknown }> | undefined, + id: string, +): unknown { + return options?.find((option) => option.id === id)?.value; +} const decodeThreadCreatedPayload = Schema.decodeUnknownEffect(ThreadCreatedPayload); const decodeOrchestrationCommand = Schema.decodeUnknownEffect(OrchestrationCommand); const decodeOrchestrationEvent = Schema.decodeUnknownEffect(OrchestrationEvent); @@ -364,19 +371,97 @@ it.effect("accepts provider-scoped model options in thread.turn.start", () => modelSelection: { provider: "codex", model: "gpt-5.3-codex", - options: { - reasoningEffort: "high", - fastMode: true, - }, + options: [ + { id: "reasoningEffort", value: "high" }, + { id: "fastMode", value: true }, + ], }, createdAt: "2026-01-01T00:00:00.000Z", }); assert.strictEqual(parsed.modelSelection?.provider, "codex"); - assert.strictEqual(parsed.modelSelection?.options?.reasoningEffort, "high"); - assert.strictEqual(parsed.modelSelection?.options?.fastMode, true); + assert.strictEqual(getOptionValue(parsed.modelSelection?.options, "reasoningEffort"), "high"); + assert.strictEqual(getOptionValue(parsed.modelSelection?.options, "fastMode"), true); }), ); +it.effect("normalizes legacy object-shaped modelSelection.options on decode", () => + Effect.gen(function* () { + const parsed = yield* decodeThreadCreatedPayload({ + threadId: "thread-1", + projectId: "project-1", + title: "Legacy options thread", + modelSelection: { + provider: "claudeAgent", + model: "claude-opus-4-6", + options: { + effort: "max", + fastMode: true, + // Falsy/garbage entries are dropped, matching migration 026. + emptyStr: " ", + nullish: null, + nested: { foo: 1 }, + }, + }, + branch: null, + worktreePath: null, + createdAt: "2026-01-01T00:00:00.000Z", + updatedAt: "2026-01-01T00:00:00.000Z", + }); + + assert.strictEqual(parsed.modelSelection.provider, "claudeAgent"); + assert.deepStrictEqual(parsed.modelSelection.options, [ + { id: "effort", value: "max" }, + { id: "fastMode", value: true }, + ]); + }), +); + +it.effect("normalizes legacy object-shaped defaultModelSelection.options on decode", () => + Effect.gen(function* () { + const parsed = yield* decodeProjectCreatedPayload({ + projectId: "project-1", + title: "Legacy default project", + workspaceRoot: "/tmp/legacy", + defaultModelSelection: { + provider: "codex", + model: "gpt-5.4", + options: { reasoningEffort: "low" }, + }, + scripts: [], + createdAt: "2026-01-01T00:00:00.000Z", + updatedAt: "2026-01-01T00:00:00.000Z", + }); + + assert.deepStrictEqual(parsed.defaultModelSelection?.options, [ + { id: "reasoningEffort", value: "low" }, + ]); + }), +); + +it.effect( + "normalizes legacy object-shaped options on decode and re-encodes as canonical array", + () => + Effect.gen(function* () { + const decoded = yield* decodeThreadCreatedPayload({ + threadId: "thread-1", + projectId: "project-1", + title: "Round trip thread", + modelSelection: { + provider: "codex", + model: "gpt-5.4", + options: { fastMode: true }, + }, + branch: null, + worktreePath: null, + createdAt: "2026-01-01T00:00:00.000Z", + updatedAt: "2026-01-01T00:00:00.000Z", + }); + + const encoded = yield* Schema.encodeEffect(ThreadCreatedPayload)(decoded); + assert.deepStrictEqual(encoded.modelSelection.options, [{ id: "fastMode", value: true }]); + }), +); + it.effect("accepts a title seed in thread.turn.start", () => Effect.gen(function* () { const parsed = yield* decodeThreadTurnStartCommand({ diff --git a/packages/contracts/src/orchestration.ts b/packages/contracts/src/orchestration.ts index 087a667090..c201d6c82a 100644 --- a/packages/contracts/src/orchestration.ts +++ b/packages/contracts/src/orchestration.ts @@ -1,10 +1,5 @@ import { Effect, Option, Schema, SchemaIssue, Struct } from "effect"; -import { - ClaudeModelOptions, - CodexModelOptions, - CursorModelOptions, - OpenCodeModelOptions, -} from "./model.ts"; +import { ProviderOptionSelections } from "./model.ts"; import { RepositoryIdentity } from "./environment.ts"; import { ApprovalRequestId, @@ -51,27 +46,27 @@ export const DEFAULT_PROVIDER_KIND: ProviderKind = "codex"; export const CodexModelSelection = Schema.Struct({ provider: Schema.Literal("codex"), model: TrimmedNonEmptyString, - options: Schema.optionalKey(CodexModelOptions), + options: Schema.optionalKey(ProviderOptionSelections), }); export type CodexModelSelection = typeof CodexModelSelection.Type; export const ClaudeModelSelection = Schema.Struct({ provider: Schema.Literal("claudeAgent"), model: TrimmedNonEmptyString, - options: Schema.optionalKey(ClaudeModelOptions), + options: Schema.optionalKey(ProviderOptionSelections), }); export type ClaudeModelSelection = typeof ClaudeModelSelection.Type; export const CursorModelSelection = Schema.Struct({ provider: Schema.Literal("cursor"), model: TrimmedNonEmptyString, - options: Schema.optionalKey(CursorModelOptions), + options: Schema.optionalKey(ProviderOptionSelections), }); export type CursorModelSelection = typeof CursorModelSelection.Type; export const OpenCodeModelSelection = Schema.Struct({ provider: Schema.Literal("opencode"), model: TrimmedNonEmptyString, - options: Schema.optionalKey(OpenCodeModelOptions), + options: Schema.optionalKey(ProviderOptionSelections), }); export type OpenCodeModelSelection = typeof OpenCodeModelSelection.Type; diff --git a/packages/contracts/src/provider.test.ts b/packages/contracts/src/provider.test.ts index f91d0c89e0..9bbc3ff10b 100644 --- a/packages/contracts/src/provider.test.ts +++ b/packages/contracts/src/provider.test.ts @@ -6,6 +6,13 @@ import { ProviderSendTurnInput, ProviderSessionStartInput } from "./provider.ts" const decodeProviderSessionStartInput = Schema.decodeUnknownSync(ProviderSessionStartInput); const decodeProviderSendTurnInput = Schema.decodeUnknownSync(ProviderSendTurnInput); +function getOptionValue( + options: ReadonlyArray<{ id: string; value: unknown }> | undefined, + id: string, +): unknown { + return options?.find((option) => option.id === id)?.value; +} + describe("ProviderSessionStartInput", () => { it("accepts codex-compatible payloads", () => { const parsed = decodeProviderSessionStartInput({ @@ -15,10 +22,10 @@ describe("ProviderSessionStartInput", () => { modelSelection: { provider: "codex", model: "gpt-5.3-codex", - options: { - reasoningEffort: "high", - fastMode: true, - }, + options: [ + { id: "reasoningEffort", value: "high" }, + { id: "fastMode", value: true }, + ], }, runtimeMode: "full-access", }); @@ -28,8 +35,8 @@ describe("ProviderSessionStartInput", () => { if (parsed.modelSelection?.provider !== "codex") { throw new Error("Expected codex modelSelection"); } - expect(parsed.modelSelection.options?.reasoningEffort).toBe("high"); - expect(parsed.modelSelection.options?.fastMode).toBe(true); + expect(getOptionValue(parsed.modelSelection.options, "reasoningEffort")).toBe("high"); + expect(getOptionValue(parsed.modelSelection.options, "fastMode")).toBe(true); }); it("rejects payloads without runtime mode", () => { @@ -49,11 +56,11 @@ describe("ProviderSessionStartInput", () => { modelSelection: { provider: "claudeAgent", model: "claude-sonnet-4-6", - options: { - thinking: true, - effort: "max", - fastMode: true, - }, + options: [ + { id: "thinking", value: true }, + { id: "effort", value: "max" }, + { id: "fastMode", value: true }, + ], }, runtimeMode: "full-access", }); @@ -63,9 +70,9 @@ describe("ProviderSessionStartInput", () => { if (parsed.modelSelection?.provider !== "claudeAgent") { throw new Error("Expected claude modelSelection"); } - expect(parsed.modelSelection.options?.thinking).toBe(true); - expect(parsed.modelSelection.options?.effort).toBe("max"); - expect(parsed.modelSelection.options?.fastMode).toBe(true); + expect(getOptionValue(parsed.modelSelection.options, "thinking")).toBe(true); + expect(getOptionValue(parsed.modelSelection.options, "effort")).toBe("max"); + expect(getOptionValue(parsed.modelSelection.options, "fastMode")).toBe(true); expect(parsed.runtimeMode).toBe("full-access"); }); @@ -78,14 +85,14 @@ describe("ProviderSessionStartInput", () => { modelSelection: { provider: "cursor", model: "composer-2", - options: { fastMode: true }, + options: [{ id: "fastMode", value: true }], }, }); expect(parsed.provider).toBe("cursor"); expect(parsed.modelSelection?.provider).toBe("cursor"); expect(parsed.modelSelection?.model).toBe("composer-2"); if (parsed.modelSelection?.provider === "cursor") { - expect(parsed.modelSelection.options?.fastMode).toBe(true); + expect(getOptionValue(parsed.modelSelection.options, "fastMode")).toBe(true); } }); }); @@ -97,10 +104,10 @@ describe("ProviderSendTurnInput", () => { modelSelection: { provider: "codex", model: "gpt-5.3-codex", - options: { - reasoningEffort: "xhigh", - fastMode: true, - }, + options: [ + { id: "reasoningEffort", value: "xhigh" }, + { id: "fastMode", value: true }, + ], }, }); @@ -109,8 +116,8 @@ describe("ProviderSendTurnInput", () => { if (parsed.modelSelection?.provider !== "codex") { throw new Error("Expected codex modelSelection"); } - expect(parsed.modelSelection.options?.reasoningEffort).toBe("xhigh"); - expect(parsed.modelSelection.options?.fastMode).toBe(true); + expect(getOptionValue(parsed.modelSelection.options, "reasoningEffort")).toBe("xhigh"); + expect(getOptionValue(parsed.modelSelection.options, "fastMode")).toBe(true); }); it("accepts claude modelSelection including ultrathink", () => { @@ -119,10 +126,10 @@ describe("ProviderSendTurnInput", () => { modelSelection: { provider: "claudeAgent", model: "claude-sonnet-4-6", - options: { - effort: "ultrathink", - fastMode: true, - }, + options: [ + { id: "effort", value: "ultrathink" }, + { id: "fastMode", value: true }, + ], }, }); @@ -130,7 +137,7 @@ describe("ProviderSendTurnInput", () => { if (parsed.modelSelection?.provider !== "claudeAgent") { throw new Error("Expected claude modelSelection"); } - expect(parsed.modelSelection.options?.effort).toBe("ultrathink"); - expect(parsed.modelSelection.options?.fastMode).toBe(true); + expect(getOptionValue(parsed.modelSelection.options, "effort")).toBe("ultrathink"); + expect(getOptionValue(parsed.modelSelection.options, "fastMode")).toBe(true); }); }); diff --git a/packages/contracts/src/server.ts b/packages/contracts/src/server.ts index 3cd25f2e8e..1f048c1340 100644 --- a/packages/contracts/src/server.ts +++ b/packages/contracts/src/server.ts @@ -85,6 +85,9 @@ export type ServerProviderSkill = typeof ServerProviderSkill.Type; export const ServerProvider = Schema.Struct({ provider: ProviderKind, + displayName: Schema.optional(TrimmedNonEmptyString), + badgeLabel: Schema.optional(TrimmedNonEmptyString), + showInteractionModeToggle: Schema.optional(Schema.Boolean), enabled: Schema.Boolean, installed: Schema.Boolean, version: Schema.NullOr(TrimmedNonEmptyString), diff --git a/packages/contracts/src/settings.ts b/packages/contracts/src/settings.ts index cad1d197c1..6301364f33 100644 --- a/packages/contracts/src/settings.ts +++ b/packages/contracts/src/settings.ts @@ -3,11 +3,8 @@ import * as Schema from "effect/Schema"; import * as SchemaTransformation from "effect/SchemaTransformation"; import { TrimmedNonEmptyString, TrimmedString } from "./baseSchemas.ts"; import { - ClaudeModelOptions, - CodexModelOptions, - CursorModelOptions, DEFAULT_GIT_TEXT_GENERATION_MODEL_BY_PROVIDER, - OpenCodeModelOptions, + ProviderOptionSelections, } from "./model.ts"; import { ModelSelection, ProviderKind } from "./orchestration.ts"; @@ -170,50 +167,26 @@ export const DEFAULT_UNIFIED_SETTINGS: UnifiedSettings = { // ── Server Settings Patch (replace with a Schema.deepPartial if available) ────────────────────────────────────────── -const CodexModelOptionsPatch = Schema.Struct({ - reasoningEffort: Schema.optionalKey(CodexModelOptions.fields.reasoningEffort), - fastMode: Schema.optionalKey(CodexModelOptions.fields.fastMode), -}); - -const ClaudeModelOptionsPatch = Schema.Struct({ - thinking: Schema.optionalKey(ClaudeModelOptions.fields.thinking), - effort: Schema.optionalKey(ClaudeModelOptions.fields.effort), - fastMode: Schema.optionalKey(ClaudeModelOptions.fields.fastMode), - contextWindow: Schema.optionalKey(ClaudeModelOptions.fields.contextWindow), -}); - -const CursorModelOptionsPatch = Schema.Struct({ - reasoning: Schema.optionalKey(CursorModelOptions.fields.reasoning), - fastMode: Schema.optionalKey(CursorModelOptions.fields.fastMode), - thinking: Schema.optionalKey(CursorModelOptions.fields.thinking), - contextWindow: Schema.optionalKey(CursorModelOptions.fields.contextWindow), -}); - -const OpenCodeModelOptionsPatch = Schema.Struct({ - variant: Schema.optionalKey(OpenCodeModelOptions.fields.variant), - agent: Schema.optionalKey(OpenCodeModelOptions.fields.agent), -}); - const ModelSelectionPatch = Schema.Union([ Schema.Struct({ provider: Schema.optionalKey(Schema.Literal("codex")), model: Schema.optionalKey(TrimmedNonEmptyString), - options: Schema.optionalKey(CodexModelOptionsPatch), + options: Schema.optionalKey(ProviderOptionSelections), }), Schema.Struct({ provider: Schema.optionalKey(Schema.Literal("claudeAgent")), model: Schema.optionalKey(TrimmedNonEmptyString), - options: Schema.optionalKey(ClaudeModelOptionsPatch), + options: Schema.optionalKey(ProviderOptionSelections), }), Schema.Struct({ provider: Schema.optionalKey(Schema.Literal("cursor")), model: Schema.optionalKey(TrimmedNonEmptyString), - options: Schema.optionalKey(CursorModelOptionsPatch), + options: Schema.optionalKey(ProviderOptionSelections), }), Schema.Struct({ provider: Schema.optionalKey(Schema.Literal("opencode")), model: Schema.optionalKey(TrimmedNonEmptyString), - options: Schema.optionalKey(OpenCodeModelOptionsPatch), + options: Schema.optionalKey(ProviderOptionSelections), }), ]); diff --git a/packages/shared/src/model.test.ts b/packages/shared/src/model.test.ts index 426ceca865..242e798223 100644 --- a/packages/shared/src/model.test.ts +++ b/packages/shared/src/model.test.ts @@ -3,46 +3,67 @@ import { DEFAULT_MODEL_BY_PROVIDER, type ModelCapabilities } from "@t3tools/cont import { applyClaudePromptEffortPrefix, - getDefaultContextWindow, - getDefaultEffort, - hasContextWindowOption, - hasEffortLevel, + buildProviderOptionSelectionsFromDescriptors, + createModelCapabilities, + createModelSelection, + getModelSelectionBooleanOptionValue, + getModelSelectionStringOptionValue, + getProviderOptionDescriptors, + getProviderOptionBooleanSelectionValue, + getProviderOptionStringSelectionValue, isClaudeUltrathinkPrompt, - normalizeClaudeModelOptionsWithCapabilities, - normalizeCodexModelOptionsWithCapabilities, normalizeModelSlug, - resolveContextWindow, - resolveEffort, resolveModelSlugForProvider, resolveSelectableModel, trimOrNull, } from "./model.ts"; -const codexCaps: ModelCapabilities = { - reasoningEffortLevels: [ - { value: "xhigh", label: "Extra High" }, - { value: "high", label: "High", isDefault: true }, +const codexCaps: ModelCapabilities = createModelCapabilities({ + optionDescriptors: [ + { + id: "reasoningEffort", + label: "Reasoning", + type: "select", + options: [ + { id: "xhigh", label: "Extra High" }, + { id: "high", label: "High", isDefault: true }, + ], + currentValue: "high", + }, + { + id: "fastMode", + label: "Fast Mode", + type: "boolean", + }, ], - supportsFastMode: true, - supportsThinkingToggle: false, - contextWindowOptions: [], - promptInjectedEffortLevels: [], -}; +}); -const claudeCaps: ModelCapabilities = { - reasoningEffortLevels: [ - { value: "medium", label: "Medium" }, - { value: "high", label: "High", isDefault: true }, - { value: "ultrathink", label: "Ultrathink" }, +const claudeCaps: ModelCapabilities = createModelCapabilities({ + optionDescriptors: [ + { + id: "effort", + label: "Reasoning", + type: "select", + options: [ + { id: "medium", label: "Medium" }, + { id: "high", label: "High", isDefault: true }, + { id: "ultrathink", label: "Ultrathink" }, + ], + currentValue: "high", + promptInjectedValues: ["ultrathink"], + }, + { + id: "contextWindow", + label: "Context Window", + type: "select", + options: [ + { id: "200k", label: "200k" }, + { id: "1m", label: "1M", isDefault: true }, + ], + currentValue: "1m", + }, ], - supportsFastMode: false, - supportsThinkingToggle: false, - contextWindowOptions: [ - { value: "200k", label: "200k" }, - { value: "1m", label: "1M", isDefault: true }, - ], - promptInjectedEffortLevels: ["ultrathink"], -}; +}); describe("normalizeModelSlug", () => { it("maps known aliases to canonical slugs", () => { @@ -86,54 +107,6 @@ describe("resolveSelectableModel", () => { }); }); -describe("capability helpers", () => { - it("reads default efforts", () => { - expect(getDefaultEffort(codexCaps)).toBe("high"); - expect(getDefaultEffort(claudeCaps)).toBe("high"); - }); - - it("checks effort support", () => { - expect(hasEffortLevel(codexCaps, "xhigh")).toBe(true); - expect(hasEffortLevel(codexCaps, "max")).toBe(false); - }); -}); - -describe("resolveEffort", () => { - it("returns the explicit value when supported and not prompt-injected", () => { - expect(resolveEffort(codexCaps, "xhigh")).toBe("xhigh"); - expect(resolveEffort(codexCaps, "high")).toBe("high"); - expect(resolveEffort(claudeCaps, "medium")).toBe("medium"); - }); - - it("falls back to default when value is unsupported", () => { - expect(resolveEffort(codexCaps, "bogus")).toBe("high"); - expect(resolveEffort(claudeCaps, "bogus")).toBe("high"); - }); - - it("returns the default when no value is provided", () => { - expect(resolveEffort(codexCaps, undefined)).toBe("high"); - expect(resolveEffort(codexCaps, null)).toBe("high"); - expect(resolveEffort(codexCaps, "")).toBe("high"); - expect(resolveEffort(codexCaps, " ")).toBe("high"); - }); - - it("excludes prompt-injected efforts and falls back to default", () => { - expect(resolveEffort(claudeCaps, "ultrathink")).toBe("high"); - }); - - it("returns undefined for models with no effort levels", () => { - const noCaps: ModelCapabilities = { - reasoningEffortLevels: [], - supportsFastMode: false, - supportsThinkingToggle: false, - contextWindowOptions: [], - promptInjectedEffortLevels: [], - }; - expect(resolveEffort(noCaps, undefined)).toBeUndefined(); - expect(resolveEffort(noCaps, "high")).toBeUndefined(); - }); -}); - describe("misc helpers", () => { it("detects ultrathink prompts", () => { expect(isClaudeUltrathinkPrompt("Please ultrathink about this")).toBe(true); @@ -156,95 +129,88 @@ describe("misc helpers", () => { }); }); -describe("context window helpers", () => { - it("reads default context window", () => { - expect(getDefaultContextWindow(claudeCaps)).toBe("1m"); - }); - - it("returns null for models without context window options", () => { - expect(getDefaultContextWindow(codexCaps)).toBeNull(); - }); - - it("checks context window support", () => { - expect(hasContextWindowOption(claudeCaps, "1m")).toBe(true); - expect(hasContextWindowOption(claudeCaps, "200k")).toBe(true); - expect(hasContextWindowOption(claudeCaps, "bogus")).toBe(false); - expect(hasContextWindowOption(codexCaps, "1m")).toBe(false); - }); -}); - -describe("resolveContextWindow", () => { - it("returns the explicit value when supported", () => { - expect(resolveContextWindow(claudeCaps, "200k")).toBe("200k"); - expect(resolveContextWindow(claudeCaps, "1m")).toBe("1m"); - }); - - it("falls back to default when value is unsupported", () => { - expect(resolveContextWindow(claudeCaps, "bogus")).toBe("1m"); - }); - - it("returns the default when no value is provided", () => { - expect(resolveContextWindow(claudeCaps, undefined)).toBe("1m"); - expect(resolveContextWindow(claudeCaps, null)).toBe("1m"); - expect(resolveContextWindow(claudeCaps, "")).toBe("1m"); - }); - - it("returns undefined for models with no context window options", () => { - expect(resolveContextWindow(codexCaps, undefined)).toBeUndefined(); - expect(resolveContextWindow(codexCaps, "1m")).toBeUndefined(); - }); -}); - -describe("normalize*ModelOptionsWithCapabilities", () => { - it("preserves explicit false codex fast mode", () => { +describe("descriptor helpers", () => { + it("applies selection values to capability descriptors", () => { expect( - normalizeCodexModelOptionsWithCapabilities(codexCaps, { - reasoningEffort: "high", - fastMode: false, + getProviderOptionDescriptors({ + caps: claudeCaps, + selections: [ + { id: "effort", value: "medium" }, + { id: "contextWindow", value: "200k" }, + ], }), + ).toEqual([ + { + id: "effort", + label: "Reasoning", + type: "select", + options: [ + { id: "medium", label: "Medium" }, + { id: "high", label: "High", isDefault: true }, + { id: "ultrathink", label: "Ultrathink" }, + ], + currentValue: "medium", + promptInjectedValues: ["ultrathink"], + }, + { + id: "contextWindow", + label: "Context Window", + type: "select", + options: [ + { id: "200k", label: "200k" }, + { id: "1m", label: "1M", isDefault: true }, + ], + currentValue: "200k", + }, + ]); + }); + + it("builds wire-format option selections from descriptors", () => { + const descriptors = getProviderOptionDescriptors({ + caps: codexCaps, + selections: [ + { id: "reasoningEffort", value: "high" }, + { id: "fastMode", value: true }, + ], + }); + + expect(buildProviderOptionSelectionsFromDescriptors(descriptors)).toEqual([ + { id: "reasoningEffort", value: "high" }, + { id: "fastMode", value: true }, + ]); + }); + + it("stores option selection arrays in model selections", () => { + expect( + createModelSelection("codex", "gpt-5.4", [ + { id: "reasoningEffort", value: "high" }, + { id: "fastMode", value: true }, + ]), ).toEqual({ - reasoningEffort: "high", - fastMode: false, + provider: "codex", + model: "gpt-5.4", + options: [ + { id: "reasoningEffort", value: "high" }, + { id: "fastMode", value: true }, + ], }); }); - it("preserves the default Claude context window explicitly", () => { - expect( - normalizeClaudeModelOptionsWithCapabilities( - { - ...claudeCaps, - contextWindowOptions: [ - { value: "200k", label: "200k", isDefault: true }, - { value: "1m", label: "1M" }, - ], - }, - { - effort: "high", - contextWindow: "200k", - }, - ), - ).toEqual({ - effort: "high", - contextWindow: "200k", - }); - }); + it("reads typed option selection values", () => { + const selection = createModelSelection("codex", "gpt-5.4", [ + { id: "reasoningEffort", value: "high" }, + { id: "fastMode", value: true }, + ]); - it("omits unsupported Claude context window options", () => { + expect(getProviderOptionStringSelectionValue(selection.options, "reasoningEffort")).toBe( + "high", + ); + expect(getProviderOptionStringSelectionValue(selection.options, "fastMode")).toBeUndefined(); + expect(getProviderOptionBooleanSelectionValue(selection.options, "fastMode")).toBe(true); expect( - normalizeClaudeModelOptionsWithCapabilities( - { - ...claudeCaps, - reasoningEffortLevels: [], - supportsThinkingToggle: true, - contextWindowOptions: [], - }, - { - thinking: true, - contextWindow: "1m", - }, - ), - ).toEqual({ - thinking: true, - }); + getProviderOptionBooleanSelectionValue(selection.options, "reasoningEffort"), + ).toBeUndefined(); + expect(getModelSelectionStringOptionValue(selection, "reasoningEffort")).toBe("high"); + expect(getModelSelectionBooleanOptionValue(selection, "fastMode")).toBe(true); }); }); diff --git a/packages/shared/src/model.ts b/packages/shared/src/model.ts index ad62debf68..4f61fc33e8 100644 --- a/packages/shared/src/model.ts +++ b/packages/shared/src/model.ts @@ -1,15 +1,11 @@ import { DEFAULT_MODEL_BY_PROVIDER, MODEL_SLUG_ALIASES_BY_PROVIDER, - type ClaudeAgentEffort, - type ClaudeModelOptions, - type CodexModelOptions, - type CursorModelOptions, type ModelCapabilities, type ModelSelection, - type OpenCodeModelOptions, + type ProviderOptionDescriptor, + type ProviderOptionSelection, type ProviderKind, - type ProviderModelOptions, } from "@t3tools/contracts"; export interface SelectableModelOption { @@ -17,157 +13,215 @@ export interface SelectableModelOption { name: string; } -/** Check whether a capabilities object includes a given effort value. */ -export function hasEffortLevel(caps: ModelCapabilities, value: string): boolean { - return caps.reasoningEffortLevels.some((l) => l.value === value); +export function createModelCapabilities(input: { + optionDescriptors: ReadonlyArray; +}): ModelCapabilities { + return { + optionDescriptors: input.optionDescriptors.map(cloneDescriptor), + }; } -/** Return the default effort value for a capabilities object, or null if none. */ -export function getDefaultEffort(caps: ModelCapabilities): string | null { - return caps.reasoningEffortLevels.find((l) => l.isDefault)?.value ?? null; +function getRawSelectionValueById( + selections: ReadonlyArray | null | undefined, + id: string, +): string | boolean | undefined { + const selection = selections?.find((candidate) => candidate.id === id); + return selection?.value; } -/** - * Resolve a raw effort option against capabilities. - * - * Returns the explicit supported value when present and not prompt-injected, - * otherwise the model default. Returns `undefined` when the model exposes no - * effort levels. - */ -export function resolveEffort( - caps: ModelCapabilities, +export function getProviderOptionSelectionValue( + selections: ReadonlyArray | null | undefined, + id: string, +): string | boolean | undefined { + return getRawSelectionValueById(selections, id); +} + +export function getProviderOptionStringSelectionValue( + selections: ReadonlyArray | null | undefined, + id: string, +): string | undefined { + const value = getProviderOptionSelectionValue(selections, id); + return typeof value === "string" ? value : undefined; +} + +export function getProviderOptionBooleanSelectionValue( + selections: ReadonlyArray | null | undefined, + id: string, +): boolean | undefined { + const value = getProviderOptionSelectionValue(selections, id); + return typeof value === "boolean" ? value : undefined; +} + +export function getModelSelectionOptionValue( + modelSelection: ModelSelection | null | undefined, + id: string, +): string | boolean | undefined { + return getProviderOptionSelectionValue(modelSelection?.options, id); +} + +export function getModelSelectionStringOptionValue( + modelSelection: ModelSelection | null | undefined, + id: string, +): string | undefined { + return getProviderOptionStringSelectionValue(modelSelection?.options, id); +} + +export function getModelSelectionBooleanOptionValue( + modelSelection: ModelSelection | null | undefined, + id: string, +): boolean | undefined { + return getProviderOptionBooleanSelectionValue(modelSelection?.options, id); +} + +function resolveDescriptorChoiceValue( + descriptor: Extract, raw: string | null | undefined, ): string | undefined { - const defaultValue = getDefaultEffort(caps); - const trimmed = typeof raw === "string" ? raw.trim() : null; - if ( - trimmed && - !caps.promptInjectedEffortLevels.includes(trimmed) && - hasEffortLevel(caps, trimmed) - ) { + const trimmed = trimOrNull(raw); + if (!trimmed) { + return descriptor.currentValue ?? descriptor.options.find((option) => option.isDefault)?.id; + } + if (descriptor.options.length === 0) { return trimmed; } - return defaultValue ?? undefined; + if ( + descriptor.promptInjectedValues?.includes(trimmed) && + descriptor.options.some((option) => option.id === trimmed) + ) { + return descriptor.options.find((option) => option.isDefault)?.id; + } + if (descriptor.options.some((option) => option.id === trimmed)) { + return trimmed; + } + return descriptor.currentValue ?? descriptor.options.find((option) => option.isDefault)?.id; } -/** Check whether a capabilities object includes a given context window value. */ -export function hasContextWindowOption(caps: ModelCapabilities, value: string): boolean { - return caps.contextWindowOptions.some((o) => o.value === value); +function cloneDescriptor(descriptor: ProviderOptionDescriptor): ProviderOptionDescriptor { + return descriptor.type === "select" + ? { + ...descriptor, + options: [...descriptor.options], + ...(descriptor.promptInjectedValues + ? { promptInjectedValues: [...descriptor.promptInjectedValues] } + : {}), + } + : { ...descriptor }; } -/** Return the default context window value, or `null` if none is defined. */ -export function getDefaultContextWindow(caps: ModelCapabilities): string | null { - return caps.contextWindowOptions.find((o) => o.isDefault)?.value ?? null; +function cloneSelection(selection: ProviderOptionSelection): ProviderOptionSelection { + return { ...selection }; } -/** - * Resolve a raw `contextWindow` option against capabilities. - * - * Returns the explicit supported value when present, otherwise the model - * default. Returns `undefined` when the model exposes no context window options. - */ -export function resolveContextWindow( - caps: ModelCapabilities, - raw: string | null | undefined, +function withDescriptorCurrentValue( + descriptor: ProviderOptionDescriptor, + rawCurrentValue: string | boolean | undefined, +): ProviderOptionDescriptor { + if (descriptor.type === "boolean") { + if (typeof rawCurrentValue === "boolean") { + return { + ...descriptor, + currentValue: rawCurrentValue, + }; + } + return descriptor; + } + const currentValue = + typeof rawCurrentValue === "string" + ? resolveDescriptorChoiceValue(descriptor, rawCurrentValue) + : resolveDescriptorChoiceValue(descriptor, descriptor.currentValue); + if (!currentValue) { + const { currentValue: _unusedCurrentValue, ...rest } = descriptor; + return rest; + } + return { + ...descriptor, + currentValue, + }; +} + +export function getProviderOptionDescriptors(input: { + caps: ModelCapabilities; + selections?: ReadonlyArray | null | undefined; +}): ReadonlyArray { + const { caps, selections } = input; + const baseDescriptors = (caps.optionDescriptors ?? []).map(cloneDescriptor); + + return baseDescriptors.map((descriptor) => + withDescriptorCurrentValue( + descriptor, + getRawSelectionValueById(selections, descriptor.id) ?? descriptor.currentValue, + ), + ); +} + +export function getProviderOptionCurrentValue( + descriptor: ProviderOptionDescriptor | null | undefined, +): string | boolean | undefined { + if (!descriptor) { + return undefined; + } + if (descriptor.type === "boolean") { + return descriptor.currentValue; + } + if (descriptor.currentValue) { + return descriptor.currentValue; + } + return descriptor.options.find((option) => option.isDefault)?.id; +} + +export function getProviderOptionCurrentLabel( + descriptor: ProviderOptionDescriptor | null | undefined, ): string | undefined { - const defaultValue = getDefaultContextWindow(caps); - if (!raw) return defaultValue ?? undefined; - return hasContextWindowOption(caps, raw) ? raw : (defaultValue ?? undefined); -} - -export function normalizeCodexModelOptionsWithCapabilities( - caps: ModelCapabilities, - modelOptions: CodexModelOptions | null | undefined, -): CodexModelOptions | undefined { - const reasoningEffort = resolveEffort(caps, modelOptions?.reasoningEffort); - const fastMode = caps.supportsFastMode ? modelOptions?.fastMode : undefined; - const nextOptions: CodexModelOptions = { - ...(reasoningEffort - ? { reasoningEffort: reasoningEffort as CodexModelOptions["reasoningEffort"] } - : {}), - ...(fastMode !== undefined ? { fastMode } : {}), - }; - return Object.keys(nextOptions).length > 0 ? nextOptions : undefined; -} - -export function normalizeClaudeModelOptionsWithCapabilities( - caps: ModelCapabilities, - modelOptions: ClaudeModelOptions | null | undefined, -): ClaudeModelOptions | undefined { - const effort = resolveEffort(caps, modelOptions?.effort); - const thinking = caps.supportsThinkingToggle ? modelOptions?.thinking : undefined; - const fastMode = caps.supportsFastMode ? modelOptions?.fastMode : undefined; - const contextWindow = resolveContextWindow(caps, modelOptions?.contextWindow); - const nextOptions: ClaudeModelOptions = { - ...(thinking !== undefined ? { thinking } : {}), - ...(effort ? { effort: effort as ClaudeModelOptions["effort"] } : {}), - ...(fastMode !== undefined ? { fastMode } : {}), - ...(contextWindow !== undefined ? { contextWindow } : {}), - }; - return Object.keys(nextOptions).length > 0 ? nextOptions : undefined; -} - -export function normalizeCursorModelOptionsWithCapabilities( - caps: ModelCapabilities, - modelOptions: CursorModelOptions | null | undefined, -): CursorModelOptions | undefined { - const reasoning = resolveEffort(caps, modelOptions?.reasoning); - const thinking = caps.supportsThinkingToggle ? modelOptions?.thinking : undefined; - const fastMode = caps.supportsFastMode ? modelOptions?.fastMode : undefined; - const contextWindow = resolveContextWindow(caps, modelOptions?.contextWindow); - const nextOptions: CursorModelOptions = { - ...(reasoning ? { reasoning: reasoning as CursorModelOptions["reasoning"] } : {}), - ...(fastMode !== undefined ? { fastMode } : {}), - ...(thinking !== undefined ? { thinking } : {}), - ...(contextWindow !== undefined ? { contextWindow } : {}), - }; - return Object.keys(nextOptions).length > 0 ? nextOptions : undefined; -} - -function resolveLabeledOption( - options: ReadonlyArray<{ value: string; isDefault?: boolean | undefined }> | undefined, - raw: string | null | undefined, -): string | undefined { - if (!options || options.length === 0) { - return raw ?? undefined; + if (!descriptor) { + return undefined; } - if (raw && options.some((option) => option.value === raw)) { - return raw; + if (descriptor.type === "boolean") { + return typeof descriptor.currentValue === "boolean" + ? descriptor.currentValue + ? "On" + : "Off" + : undefined; } - return options.find((option) => option.isDefault)?.value ?? options[0]?.value; + const currentValue = getProviderOptionCurrentValue(descriptor); + if (typeof currentValue !== "string") { + return undefined; + } + return descriptor.options.find((option) => option.id === currentValue)?.label; } -export function normalizeOpenCodeModelOptionsWithCapabilities( - caps: ModelCapabilities, - modelOptions: OpenCodeModelOptions | null | undefined, -): OpenCodeModelOptions | undefined { - const variant = resolveLabeledOption(caps.variantOptions, trimOrNull(modelOptions?.variant)); - const agent = resolveLabeledOption(caps.agentOptions, trimOrNull(modelOptions?.agent)); - const nextOptions: OpenCodeModelOptions = { - ...(variant ? { variant } : {}), - ...(agent ? { agent } : {}), - }; - return Object.keys(nextOptions).length > 0 ? nextOptions : undefined; +export function buildProviderOptionSelectionsFromDescriptors( + descriptors: ReadonlyArray | null | undefined, +): Array | undefined { + if (!descriptors || descriptors.length === 0) { + return undefined; + } + + const nextSelections: Array = []; + + for (const descriptor of descriptors) { + const value = getProviderOptionCurrentValue(descriptor); + if (typeof value === "string" || typeof value === "boolean") { + nextSelections.push({ id: descriptor.id, value }); + } + } + + return nextSelections.length > 0 ? nextSelections : undefined; } -export function normalizeProviderModelOptionsWithCapabilities( - provider: ProviderKind, - caps: ModelCapabilities, - modelOptions: ProviderModelOptions[ProviderKind] | null | undefined, -): ProviderModelOptions[ProviderKind] | undefined { - switch (provider) { - case "codex": - return normalizeCodexModelOptionsWithCapabilities(caps, modelOptions as CodexModelOptions); - case "claudeAgent": - return normalizeClaudeModelOptionsWithCapabilities(caps, modelOptions as ClaudeModelOptions); - case "cursor": - return normalizeCursorModelOptionsWithCapabilities(caps, modelOptions as CursorModelOptions); - case "opencode": - return normalizeOpenCodeModelOptionsWithCapabilities( - caps, - modelOptions as OpenCodeModelOptions, - ); +export function getModelSelectionOptionDescriptors( + modelSelection: ModelSelection | null | undefined, + caps?: ModelCapabilities | null | undefined, +): ReadonlyArray { + if (!modelSelection) { + return []; } + if (!caps) { + return []; + } + return getProviderOptionDescriptors({ + caps, + selections: modelSelection.options, + }); } export function isClaudeUltrathinkPrompt(text: string | null | undefined): boolean { @@ -249,42 +303,51 @@ export function trimOrNull(value: T | null | undefined): T | n return trimmed || null; } +function cloneSelections( + selections: ReadonlyArray, +): Array { + return selections.map(cloneSelection); +} + export function createModelSelection( provider: ProviderKind, model: string, - options?: ProviderModelOptions[ProviderKind] | undefined, + options?: ReadonlyArray | null, ): ModelSelection { - switch (provider) { - case "codex": - return { - provider, - model, - ...(options ? { options: options as CodexModelOptions } : {}), - }; - case "claudeAgent": - return { - provider, - model, - ...(options ? { options: options as ClaudeModelOptions } : {}), - }; - case "cursor": - return { - provider, - model, - ...(options ? { options: options as CursorModelOptions } : {}), - }; - case "opencode": - return { - provider, - model, - ...(options ? { options: options as OpenCodeModelOptions } : {}), - }; + const selections = options ? cloneSelections(options) : []; + return { + provider, + model, + ...(selections.length > 0 ? { options: selections } : {}), + } as ModelSelection; +} + +/** + * Returns the effort value if it is a prompt-injected value according to + * any select descriptor in the given capabilities, or null otherwise. + * + * Unlike a single `find`, this checks every descriptor so that the + * correct descriptor's `promptInjectedValues` list is consulted even when + * multiple select descriptors exist. + */ +export function resolvePromptInjectedEffort( + caps: ModelCapabilities, + rawEffort: string | null | undefined, +): string | null { + const trimmed = trimOrNull(rawEffort); + if (!trimmed) return null; + const descriptors = getProviderOptionDescriptors({ caps }); + for (const descriptor of descriptors) { + if (descriptor.type === "select" && descriptor.promptInjectedValues?.includes(trimmed)) { + return trimmed; + } } + return null; } export function applyClaudePromptEffortPrefix( text: string, - effort: ClaudeAgentEffort | null | undefined, + effort: string | null | undefined, ): string { const trimmed = text.trim(); if (!trimmed) { diff --git a/packages/shared/src/serverSettings.test.ts b/packages/shared/src/serverSettings.test.ts index bbe5d8dc2a..ccae816cf5 100644 --- a/packages/shared/src/serverSettings.test.ts +++ b/packages/shared/src/serverSettings.test.ts @@ -1,5 +1,6 @@ import { DEFAULT_SERVER_SETTINGS } from "@t3tools/contracts"; import { describe, expect, it } from "vitest"; +import { createModelSelection } from "./model.ts"; import { applyServerSettingsPatch, extractPersistedServerObservabilitySettings, @@ -56,14 +57,10 @@ describe("serverSettings helpers", () => { it("replaces text generation selection when provider/model are provided", () => { const current = { ...DEFAULT_SERVER_SETTINGS, - textGenerationModelSelection: { - provider: "codex" as const, - model: "gpt-5.4-mini", - options: { - reasoningEffort: "high" as const, - fastMode: true, - }, - }, + textGenerationModelSelection: createModelSelection("codex", "gpt-5.4-mini", [ + { id: "reasoningEffort", value: "high" }, + { id: "fastMode", value: true }, + ]), }; expect( @@ -82,45 +79,35 @@ describe("serverSettings helpers", () => { it("still deep merges text generation selection when only options are provided", () => { const current = { ...DEFAULT_SERVER_SETTINGS, - textGenerationModelSelection: { - provider: "codex" as const, - model: "gpt-5.4-mini", - options: { - reasoningEffort: "high" as const, - fastMode: true, - }, - }, + textGenerationModelSelection: createModelSelection("codex", "gpt-5.4-mini", [ + { id: "reasoningEffort", value: "high" }, + { id: "fastMode", value: true }, + ]), }; expect( applyServerSettingsPatch(current, { textGenerationModelSelection: { - options: { - fastMode: false, - }, + options: [{ id: "fastMode", value: false }], }, }).textGenerationModelSelection, ).toEqual({ provider: "codex", model: "gpt-5.4-mini", - options: { - reasoningEffort: "high", - fastMode: false, - }, + options: [ + { id: "reasoningEffort", value: "high" }, + { id: "fastMode", value: false }, + ], }); }); it("replaces text generation selection across providers without leaking stale options", () => { const current = { ...DEFAULT_SERVER_SETTINGS, - textGenerationModelSelection: { - provider: "codex" as const, - model: "gpt-5.4-mini", - options: { - reasoningEffort: "high" as const, - fastMode: true, - }, - }, + textGenerationModelSelection: createModelSelection("codex", "gpt-5.4-mini", [ + { id: "reasoningEffort", value: "high" }, + { id: "fastMode", value: true }, + ]), }; expect( @@ -135,4 +122,26 @@ describe("serverSettings helpers", () => { model: "openai/gpt-5", }); }); + + it("accepts array-based text generation selection patches", () => { + expect( + applyServerSettingsPatch(DEFAULT_SERVER_SETTINGS, { + textGenerationModelSelection: { + provider: "opencode", + model: "openai/gpt-5", + options: [ + { id: "variant", value: "prod" }, + { id: "agent", value: "build" }, + ], + }, + }).textGenerationModelSelection, + ).toEqual({ + provider: "opencode", + model: "openai/gpt-5", + options: [ + { id: "variant", value: "prod" }, + { id: "agent", value: "build" }, + ], + }); + }); }); diff --git a/packages/shared/src/serverSettings.ts b/packages/shared/src/serverSettings.ts index cb9d937357..2488f60293 100644 --- a/packages/shared/src/serverSettings.ts +++ b/packages/shared/src/serverSettings.ts @@ -1,14 +1,8 @@ -import { - ServerSettings, - type ClaudeModelOptions, - type CodexModelOptions, - type CursorModelOptions, - type OpenCodeModelOptions, - type ServerSettingsPatch, -} from "@t3tools/contracts"; +import { ServerSettings, type ServerSettingsPatch } from "@t3tools/contracts"; import { Schema } from "effect"; import { deepMerge } from "./Struct.ts"; import { fromLenientJson } from "./schemaJson.ts"; +import { createModelSelection } from "./model.ts"; const ServerSettingsJson = fromLenientJson(ServerSettings); @@ -53,8 +47,23 @@ function shouldReplaceTextGenerationModelSelection( return Boolean(patch && (patch.provider !== undefined || patch.model !== undefined)); } -const withModelSelectionOptions = (options: Options | undefined) => - options ? { options } : {}; +function mergeModelSelectionOptionsById(input: { + current: ReadonlyArray<{ readonly id: string; readonly value: string | boolean }> | undefined; + patch: ReadonlyArray<{ readonly id: string; readonly value: string | boolean }> | undefined; +}): Array<{ id: string; value: string | boolean }> | undefined { + if (input.patch === undefined) { + return input.current ? [...input.current] : undefined; + } + if (input.patch.length === 0) { + return undefined; + } + + const merged = new Map((input.current ?? []).map((selection) => [selection.id, selection.value])); + for (const selection of input.patch) { + merged.set(selection.id, selection.value); + } + return [...merged.entries()].map(([id, value]) => ({ id, value })); +} /** * Applies a server settings patch while treating textGenerationModelSelection as @@ -67,44 +76,21 @@ export function applyServerSettingsPatch( ): ServerSettings { const selectionPatch = patch.textGenerationModelSelection; const next = deepMerge(current, patch); - if (!selectionPatch || !shouldReplaceTextGenerationModelSelection(selectionPatch)) { + if (!selectionPatch) { return next; } const provider = selectionPatch.provider ?? current.textGenerationModelSelection.provider; const model = selectionPatch.model ?? current.textGenerationModelSelection.model; + const options = shouldReplaceTextGenerationModelSelection(selectionPatch) + ? selectionPatch.options + : mergeModelSelectionOptionsById({ + current: current.textGenerationModelSelection.options, + patch: selectionPatch.options, + }); return { ...next, - textGenerationModelSelection: - provider === "codex" - ? { - provider, - model, - ...withModelSelectionOptions(selectionPatch.options as CodexModelOptions | undefined), - } - : provider === "claudeAgent" - ? { - provider, - model, - ...withModelSelectionOptions( - selectionPatch.options as ClaudeModelOptions | undefined, - ), - } - : provider === "cursor" - ? { - provider, - model, - ...withModelSelectionOptions( - selectionPatch.options as CursorModelOptions | undefined, - ), - } - : { - provider, - model, - ...withModelSelectionOptions( - selectionPatch.options as OpenCodeModelOptions | undefined, - ), - }, + textGenerationModelSelection: createModelSelection(provider, model, options), }; } From d5b7690f95504a04c12d10acfefd59f32515dbf2 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Thu, 23 Apr 2026 11:24:06 -0400 Subject: [PATCH 22/82] Exclude subscribe RPCs from latency tracking (#2313) --- apps/web/src/rpc/requestLatencyState.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/apps/web/src/rpc/requestLatencyState.ts b/apps/web/src/rpc/requestLatencyState.ts index d21e37b529..ecc3b88275 100644 --- a/apps/web/src/rpc/requestLatencyState.ts +++ b/apps/web/src/rpc/requestLatencyState.ts @@ -36,7 +36,7 @@ function getSlowRpcAckRequestsValue(): ReadonlyArray { } function shouldTrackRpcAck(tag: string): boolean { - return !tag.startsWith("subscribe"); + return !tag.includes("subscribe"); } export function getSlowRpcAckRequests(): ReadonlyArray { From 0ee302e24de2ff0a0f88b3478a3274560e28f3c9 Mon Sep 17 00:00:00 2001 From: Thimo Sietsma Date: Thu, 23 Apr 2026 17:42:35 +0200 Subject: [PATCH 23/82] fix(request-permission): add `dynamic_tool_call` to command request (#2311) --- apps/web/src/session-logic.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/apps/web/src/session-logic.ts b/apps/web/src/session-logic.ts index 44e0498d7b..fc009f9393 100644 --- a/apps/web/src/session-logic.ts +++ b/apps/web/src/session-logic.ts @@ -169,6 +169,7 @@ function requestKindFromRequestType(requestType: unknown): PendingApproval["requ switch (requestType) { case "command_execution_approval": case "exec_command_approval": + case "dynamic_tool_call": return "command"; case "file_read_approval": return "file-read"; From 0d55a42840231122f8d7414b35f155343031f82d Mon Sep 17 00:00:00 2001 From: Pedro Silva Date: Thu, 23 Apr 2026 16:52:02 +0100 Subject: [PATCH 24/82] fix(web): ignore stale runtime projection snapshots (#2301) --- .../src/environments/runtime/service.test.ts | 109 +++++++++++++++- apps/web/src/environments/runtime/service.ts | 121 ++++++++++++++++++ 2 files changed, 229 insertions(+), 1 deletion(-) diff --git a/apps/web/src/environments/runtime/service.test.ts b/apps/web/src/environments/runtime/service.test.ts index 7a4af40498..40ec455adc 100644 --- a/apps/web/src/environments/runtime/service.test.ts +++ b/apps/web/src/environments/runtime/service.test.ts @@ -1,6 +1,10 @@ import { describe, expect, it } from "vitest"; -import { shouldApplyTerminalEvent } from "./service"; +import { + shouldApplyProjectionEvent, + shouldApplyProjectionSnapshot, + shouldApplyTerminalEvent, +} from "./service"; describe("shouldApplyTerminalEvent", () => { it("applies terminal events for draft-only threads", () => { @@ -39,3 +43,106 @@ describe("shouldApplyTerminalEvent", () => { ).toBe(true); }); }); + +describe("shouldApplyProjectionSnapshot", () => { + it("accepts the first snapshot for an environment", () => { + expect( + shouldApplyProjectionSnapshot({ + current: null, + next: { + snapshotSequence: 1, + updatedAt: "2026-04-22T10:00:00.000Z", + }, + }), + ).toBe(true); + }); + + it("drops snapshots with an older sequence", () => { + expect( + shouldApplyProjectionSnapshot({ + current: { + sequence: 5, + updatedAt: "2026-04-22T10:05:00.000Z", + }, + next: { + snapshotSequence: 4, + updatedAt: "2026-04-22T10:06:00.000Z", + }, + }), + ).toBe(false); + }); + + it("drops snapshots with the same sequence and older timestamp", () => { + expect( + shouldApplyProjectionSnapshot({ + current: { + sequence: 5, + updatedAt: "2026-04-22T10:05:00.000Z", + }, + next: { + snapshotSequence: 5, + updatedAt: "2026-04-22T10:04:59.000Z", + }, + }), + ).toBe(false); + }); + + it("accepts snapshots with the same sequence and a newer timestamp", () => { + expect( + shouldApplyProjectionSnapshot({ + current: { + sequence: 5, + updatedAt: "2026-04-22T10:05:00.000Z", + }, + next: { + snapshotSequence: 5, + updatedAt: "2026-04-22T10:05:01.000Z", + }, + }), + ).toBe(true); + }); +}); + +describe("shouldApplyProjectionEvent", () => { + it("accepts the first event for an environment", () => { + expect( + shouldApplyProjectionEvent({ + current: null, + sequence: 1, + }), + ).toBe(true); + }); + + it("drops stale or duplicate events", () => { + expect( + shouldApplyProjectionEvent({ + current: { + sequence: 5, + updatedAt: "2026-04-22T10:05:00.000Z", + }, + sequence: 5, + }), + ).toBe(false); + expect( + shouldApplyProjectionEvent({ + current: { + sequence: 5, + updatedAt: "2026-04-22T10:05:00.000Z", + }, + sequence: 4, + }), + ).toBe(false); + }); + + it("accepts newer events", () => { + expect( + shouldApplyProjectionEvent({ + current: { + sequence: 5, + updatedAt: "2026-04-22T10:05:00.000Z", + }, + sequence: 6, + }), + ).toBe(true); + }); +}); diff --git a/apps/web/src/environments/runtime/service.ts b/apps/web/src/environments/runtime/service.ts index 775df0184e..d724eeff33 100644 --- a/apps/web/src/environments/runtime/service.ts +++ b/apps/web/src/environments/runtime/service.ts @@ -87,6 +87,13 @@ type ThreadDetailSubscriptionEntry = { const environmentConnections = new Map(); const environmentConnectionListeners = new Set<() => void>(); const threadDetailSubscriptions = new Map(); +const lastAppliedProjectionVersionByEnvironment = new Map< + EnvironmentId, + { + readonly sequence: number; + readonly updatedAt: string | null; + } +>(); let activeService: EnvironmentServiceState | null = null; let needsProviderInvalidation = false; @@ -102,6 +109,98 @@ const THREAD_DETAIL_SUBSCRIPTION_IDLE_EVICTION_MS = 15 * 60 * 1000; const MAX_CACHED_THREAD_DETAIL_SUBSCRIPTIONS = 32; const NOOP = () => undefined; +function compareAppliedProjectionVersion( + left: { readonly sequence: number; readonly updatedAt: string | null }, + right: { readonly sequence: number; readonly updatedAt: string | null }, +): number { + if (left.sequence !== right.sequence) { + return left.sequence - right.sequence; + } + + const leftUpdatedAt = left.updatedAt ?? ""; + const rightUpdatedAt = right.updatedAt ?? ""; + if (leftUpdatedAt === rightUpdatedAt) { + return 0; + } + + return leftUpdatedAt < rightUpdatedAt ? -1 : 1; +} + +function toAppliedProjectionVersion( + snapshot: Pick, +): { + readonly sequence: number; + readonly updatedAt: string; +} { + return { + sequence: snapshot.snapshotSequence, + updatedAt: snapshot.updatedAt, + }; +} + +export function shouldApplyProjectionSnapshot(input: { + readonly current: { + readonly sequence: number; + readonly updatedAt: string | null; + } | null; + readonly next: Pick; +}): boolean { + if (input.current === null) { + return true; + } + + return compareAppliedProjectionVersion(input.current, toAppliedProjectionVersion(input.next)) < 0; +} + +export function shouldApplyProjectionEvent(input: { + readonly current: { + readonly sequence: number; + readonly updatedAt: string | null; + } | null; + readonly sequence: number; +}): boolean { + if (input.current === null) { + return true; + } + + return input.sequence > input.current.sequence; +} + +function readLastAppliedProjectionVersion(environmentId: EnvironmentId): { + readonly sequence: number; + readonly updatedAt: string | null; +} | null { + return lastAppliedProjectionVersionByEnvironment.get(environmentId) ?? null; +} + +function markAppliedProjectionSnapshot( + environmentId: EnvironmentId, + snapshot: Pick, +): void { + const nextVersion = toAppliedProjectionVersion(snapshot); + const currentVersion = readLastAppliedProjectionVersion(environmentId); + if ( + currentVersion !== null && + compareAppliedProjectionVersion(currentVersion, nextVersion) >= 0 + ) { + return; + } + + lastAppliedProjectionVersionByEnvironment.set(environmentId, nextVersion); +} + +function markAppliedProjectionEvent(environmentId: EnvironmentId, sequence: number): void { + const currentVersion = readLastAppliedProjectionVersion(environmentId); + if (currentVersion !== null && sequence <= currentVersion.sequence) { + return; + } + + lastAppliedProjectionVersionByEnvironment.set(environmentId, { + sequence, + updatedAt: currentVersion?.updatedAt ?? null, + }); +} + function getThreadDetailSubscriptionKey(environmentId: EnvironmentId, threadId: ThreadId): string { return scopedThreadKey(scopeThreadRef(environmentId, threadId)); } @@ -600,6 +699,15 @@ export function applyEnvironmentThreadDetailEvent( } function applyShellEvent(event: OrchestrationShellStreamEvent, environmentId: EnvironmentId) { + if ( + !shouldApplyProjectionEvent({ + current: readLastAppliedProjectionVersion(environmentId), + sequence: event.sequence, + }) + ) { + return; + } + const threadId = event.kind === "thread-upserted" ? event.thread.id @@ -610,6 +718,7 @@ function applyShellEvent(event: OrchestrationShellStreamEvent, environmentId: En const previousThread = threadRef ? selectThreadByRef(useStore.getState(), threadRef) : undefined; useStore.getState().applyShellEvent(event, environmentId); + markAppliedProjectionEvent(environmentId, event.sequence); switch (event.kind) { case "project-upserted": @@ -643,7 +752,17 @@ function createEnvironmentConnectionHandlers() { return { applyShellEvent, syncShellSnapshot: (snapshot: OrchestrationShellSnapshot, environmentId: EnvironmentId) => { + if ( + !shouldApplyProjectionSnapshot({ + current: readLastAppliedProjectionVersion(environmentId), + next: snapshot, + }) + ) { + return; + } + useStore.getState().syncServerShellSnapshot(snapshot, environmentId); + markAppliedProjectionSnapshot(environmentId, snapshot); reconcileThreadDetailSubscriptionsForEnvironment( environmentId, snapshot.threads.map((thread) => thread.id), @@ -758,6 +877,7 @@ async function removeConnection(environmentId: EnvironmentId): Promise } disposeThreadDetailSubscriptionsForEnvironment(environmentId); + lastAppliedProjectionVersionByEnvironment.delete(environmentId); environmentConnections.delete(environmentId); emitEnvironmentConnectionRegistryChange(); await connection.dispose(); @@ -1086,6 +1206,7 @@ export function startEnvironmentConnectionService(queryClient: QueryClient): () export async function resetEnvironmentServiceForTests(): Promise { stopActiveService(); + lastAppliedProjectionVersionByEnvironment.clear(); for (const key of Array.from(threadDetailSubscriptions.keys())) { disposeThreadDetailSubscriptionByKey(key); } From 188df6da074bf60af765881bdfd6e886ef83e6ee Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Thu, 23 Apr 2026 13:29:54 -0400 Subject: [PATCH 25/82] Fix Claude session cwd resume drift (#2292) Co-authored-by: Cursor Agent Co-authored-by: Julius Marminge Co-authored-by: codex --- .../Layers/ProviderCommandReactor.test.ts | 76 +++++++++++++++ .../Layers/ProviderCommandReactor.ts | 6 ++ .../src/provider/Layers/ClaudeAdapter.test.ts | 90 ++++++++++++++++++ .../src/provider/Layers/ClaudeAdapter.ts | 40 ++++++++ .../provider/Layers/ProviderService.test.ts | 95 ++++++++++++++++++- .../src/provider/Layers/ProviderService.ts | 24 ++++- 6 files changed, 327 insertions(+), 4 deletions(-) diff --git a/apps/server/src/orchestration/Layers/ProviderCommandReactor.test.ts b/apps/server/src/orchestration/Layers/ProviderCommandReactor.test.ts index a52ed5856e..80f571285d 100644 --- a/apps/server/src/orchestration/Layers/ProviderCommandReactor.test.ts +++ b/apps/server/src/orchestration/Layers/ProviderCommandReactor.test.ts @@ -138,6 +138,12 @@ describe("ProviderCommandReactor", () => { (input.runtimeMode === "approval-required" || input.runtimeMode === "full-access") ? input.runtimeMode : "full-access", + ...(typeof input === "object" && + input !== null && + "cwd" in input && + typeof input.cwd === "string" + ? { cwd: input.cwd } + : {}), ...(modelSelection.model !== undefined ? { model: modelSelection.model } : {}), threadId, resumeCursor: resumeCursor ?? { opaque: `resume-${sessionIndex}` }, @@ -864,6 +870,76 @@ describe("ProviderCommandReactor", () => { expect(harness.stopSession.mock.calls.length).toBe(0); }); + it("restarts the provider session when the thread workspace changes", async () => { + const harness = await createHarness({ + threadModelSelection: { provider: "claudeAgent", model: "claude-sonnet-4-6" }, + }); + const now = new Date().toISOString(); + + await Effect.runPromise( + harness.engine.dispatch({ + type: "thread.turn.start", + commandId: CommandId.make("cmd-turn-start-workspace-1"), + threadId: ThreadId.make("thread-1"), + message: { + messageId: asMessageId("user-message-workspace-1"), + role: "user", + text: "first in project root", + attachments: [], + }, + interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE, + runtimeMode: "approval-required", + createdAt: now, + }), + ); + + await waitFor(() => harness.startSession.mock.calls.length === 1); + await waitFor(() => harness.sendTurn.mock.calls.length === 1); + expect(harness.startSession.mock.calls[0]?.[1]).toMatchObject({ + cwd: "/tmp/provider-project", + }); + + await Effect.runPromise( + harness.engine.dispatch({ + type: "thread.meta.update", + commandId: CommandId.make("cmd-thread-worktree-change"), + threadId: ThreadId.make("thread-1"), + worktreePath: "/tmp/provider-project-worktree", + }), + ); + + await Effect.runPromise( + harness.engine.dispatch({ + type: "thread.turn.start", + commandId: CommandId.make("cmd-turn-start-workspace-2"), + threadId: ThreadId.make("thread-1"), + message: { + messageId: asMessageId("user-message-workspace-2"), + role: "user", + text: "second in worktree", + attachments: [], + }, + interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE, + runtimeMode: "approval-required", + createdAt: now, + }), + ); + + await waitFor(() => harness.startSession.mock.calls.length === 2); + await waitFor(() => harness.sendTurn.mock.calls.length === 2); + expect(harness.stopSession.mock.calls.length).toBe(0); + expect(harness.startSession.mock.calls[1]?.[1]).toMatchObject({ + threadId: ThreadId.make("thread-1"), + cwd: "/tmp/provider-project-worktree", + resumeCursor: { opaque: "resume-1" }, + modelSelection: { + provider: "claudeAgent", + model: "claude-sonnet-4-6", + }, + runtimeMode: "approval-required", + }); + }); + it("restarts claude sessions when claude effort changes", async () => { const harness = await createHarness({ threadModelSelection: { provider: "claudeAgent", model: "claude-sonnet-4-6" }, diff --git a/apps/server/src/orchestration/Layers/ProviderCommandReactor.ts b/apps/server/src/orchestration/Layers/ProviderCommandReactor.ts index 8b3321ec3e..f7ae38b2d2 100644 --- a/apps/server/src/orchestration/Layers/ProviderCommandReactor.ts +++ b/apps/server/src/orchestration/Layers/ProviderCommandReactor.ts @@ -334,6 +334,7 @@ const make = Effect.gen(function* () { thread.session && thread.session.status !== "stopped" && activeSession ? thread.id : null; if (existingSessionThreadId) { const runtimeModeChanged = thread.runtimeMode !== thread.session?.runtimeMode; + const cwdChanged = effectiveCwd !== activeSession?.cwd; const sessionModelSwitch = currentProvider === undefined ? "in-session" @@ -350,6 +351,7 @@ const make = Effect.gen(function* () { if ( !runtimeModeChanged && + !cwdChanged && !shouldRestartForModelChange && !shouldRestartForModelSelectionChange ) { @@ -367,6 +369,9 @@ const make = Effect.gen(function* () { currentRuntimeMode: thread.session?.runtimeMode, desiredRuntimeMode: thread.runtimeMode, runtimeModeChanged, + previousCwd: activeSession?.cwd, + desiredCwd: effectiveCwd, + cwdChanged, modelChanged, shouldRestartForModelChange, shouldRestartForModelSelectionChange, @@ -381,6 +386,7 @@ const make = Effect.gen(function* () { restartedSessionThreadId: restartedSession.threadId, provider: restartedSession.provider, runtimeMode: restartedSession.runtimeMode, + cwd: restartedSession.cwd, }); yield* bindSessionToThread(restartedSession); return restartedSession.threadId; diff --git a/apps/server/src/provider/Layers/ClaudeAdapter.test.ts b/apps/server/src/provider/Layers/ClaudeAdapter.test.ts index 07ea11f0d6..9c83bce858 100644 --- a/apps/server/src/provider/Layers/ClaudeAdapter.test.ts +++ b/apps/server/src/provider/Layers/ClaudeAdapter.test.ts @@ -2561,6 +2561,96 @@ describe("ClaudeAdapterLive", () => { ); }); + it.effect("preserves durable resume ids across Claude resume hooks", () => { + const harness = makeHarness(); + return Effect.gen(function* () { + const adapter = yield* ClaudeAdapter; + const durableSessionId = "550e8400-e29b-41d4-a716-446655440000"; + const transientHookSessionId = "7368d0c7-40a3-4d8a-bcc1-ac80c49f2719"; + + const runtimeEventsFiber = yield* Stream.take(adapter.streamEvents, 7).pipe( + Stream.runCollect, + Effect.forkChild, + ); + + yield* adapter.startSession({ + threadId: RESUME_THREAD_ID, + provider: "claudeAgent", + resumeCursor: { + threadId: RESUME_THREAD_ID, + resume: durableSessionId, + resumeSessionAt: "assistant-99", + turnCount: 3, + }, + runtimeMode: "full-access", + }); + + harness.query.emit({ + type: "system", + subtype: "hook_started", + hook_id: "resume-hook-1", + hook_name: "SessionStart:resume", + hook_event: "SessionStart", + session_id: transientHookSessionId, + uuid: "resume-hook-started", + } as unknown as SDKMessage); + + harness.query.emit({ + type: "system", + subtype: "hook_response", + hook_id: "resume-hook-1", + hook_name: "SessionStart:resume", + hook_event: "SessionStart", + output: "", + stdout: "", + stderr: "", + outcome: "success", + session_id: transientHookSessionId, + uuid: "resume-hook-response", + } as unknown as SDKMessage); + + harness.query.emit({ + type: "system", + subtype: "init", + apiKeySource: "none", + claude_code_version: "test", + cwd: "/tmp/claude-adapter-test", + tools: [], + mcp_servers: [], + model: "claude-sonnet-4-5", + permissionMode: "bypassPermissions", + slash_commands: [], + output_style: "default", + skills: [], + plugins: [], + session_id: durableSessionId, + uuid: "resume-init", + } as unknown as SDKMessage); + + const runtimeEvents = Array.from(yield* Fiber.join(runtimeEventsFiber)); + const threadStartedEvents = runtimeEvents.filter((event) => event.type === "thread.started"); + assert.equal(threadStartedEvents.length, 1); + const threadStarted = threadStartedEvents[0]; + assert.equal(threadStarted?.type, "thread.started"); + if (threadStarted?.type === "thread.started") { + assert.deepEqual(threadStarted.payload, { + providerThreadId: durableSessionId, + }); + } + + const activeSessions = yield* adapter.listSessions(); + const resumeCursor = activeSessions[0]?.resumeCursor as + | { + readonly resume?: string; + } + | undefined; + assert.equal(resumeCursor?.resume, durableSessionId); + }).pipe( + Effect.provideService(Random.Random, makeDeterministicRandomService()), + Effect.provide(harness.layer), + ); + }); + it.effect("uses an app-generated Claude session id for fresh sessions", () => { const harness = makeHarness(); return Effect.gen(function* () { diff --git a/apps/server/src/provider/Layers/ClaudeAdapter.ts b/apps/server/src/provider/Layers/ClaudeAdapter.ts index 03dfffa042..35f326af07 100644 --- a/apps/server/src/provider/Layers/ClaudeAdapter.ts +++ b/apps/server/src/provider/Layers/ClaudeAdapter.ts @@ -198,6 +198,18 @@ function isSyntheticClaudeThreadId(value: string): boolean { return value.startsWith("claude-thread-"); } +function hasDurableClaudeSessionId(message: SDKMessage): boolean { + if (message.type !== "system") { + return true; + } + + return ( + message.subtype !== "hook_started" && + message.subtype !== "hook_progress" && + message.subtype !== "hook_response" + ); +} + function toMessage(cause: unknown, fallback: string): string { if (cause instanceof Error && cause.message.length > 0) { return cause.message; @@ -1249,6 +1261,9 @@ const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* ( if (typeof message.session_id !== "string" || message.session_id.length === 0) { return; } + if (!hasDurableClaudeSessionId(message)) { + return; + } const nextThreadId = message.session_id; context.resumeSessionId = message.session_id; yield* updateResumeCursor(context); @@ -2875,6 +2890,31 @@ const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* ( ...(Object.keys(extraArgs).length > 0 ? { extraArgs } : {}), }; + yield* Effect.annotateCurrentSpan({ + "provider.kind": PROVIDER, + "provider.thread_id": threadId, + "provider.runtime_mode": input.runtimeMode, + "claude.resume.source": + existingResumeSessionId !== undefined ? "resume-session" : "generated-session", + "claude.resume.thread_id": resumeState?.threadId ?? "", + "claude.resume.session_id": existingResumeSessionId ?? "", + "claude.resume.session_at": resumeState?.resumeSessionAt ?? "", + "claude.resume.turn_count": resumeState?.turnCount ?? -1, + "claude.query.cwd": input.cwd ?? "", + "claude.query.model": apiModelId ?? "", + "claude.query.effort": effectiveEffort ?? "", + "claude.query.permission_mode": permissionMode ?? "", + "claude.query.allow_dangerously_skip_permissions": permissionMode === "bypassPermissions", + "claude.query.resume": existingResumeSessionId ?? "", + "claude.query.session_id": newSessionId ?? "", + "claude.query.include_partial_messages": true, + "claude.query.additional_directories": input.cwd ? [input.cwd] : [], + "claude.query.setting_sources": [...CLAUDE_SETTING_SOURCES], + "claude.query.settings_json": JSON.stringify(settings), + "claude.query.extra_args_json": JSON.stringify(extraArgs), + "claude.query.path_to_executable": claudeBinaryPath, + }); + const queryRuntime = yield* Effect.try({ try: () => createQuery({ diff --git a/apps/server/src/provider/Layers/ProviderService.test.ts b/apps/server/src/provider/Layers/ProviderService.test.ts index d7b8c1cb38..09606ba35a 100644 --- a/apps/server/src/provider/Layers/ProviderService.test.ts +++ b/apps/server/src/provider/Layers/ProviderService.test.ts @@ -929,9 +929,10 @@ routing.layer("ProviderServiceLive routing", (it) => { const provider = yield* ProviderService; const runtimeRepository = yield* ProviderSessionRuntimeRepository; - const session = yield* provider.startSession(asThreadId("thread-1"), { + const threadId = asThreadId("thread-runtime-status"); + const session = yield* provider.startSession(threadId, { provider: "codex", - threadId: asThreadId("thread-1"), + threadId, runtimeMode: "full-access", }); yield* provider.sendTurn({ @@ -957,7 +958,7 @@ routing.layer("ProviderServiceLive routing", (it) => { lastError: string | null; lastRuntimeEvent: string | null; }; - assert.equal(runtimePayload.cwd, process.cwd()); + assert.equal(runtimePayload.cwd, session.cwd); assert.equal(runtimePayload.model, null); assert.equal(runtimePayload.activeTurnId, `turn-${String(session.threadId)}`); assert.equal(runtimePayload.lastError, null); @@ -1058,6 +1059,94 @@ routing.layer("ProviderServiceLive routing", (it) => { fs.rmSync(tempDir, { recursive: true, force: true }); }).pipe(Effect.provide(NodeServices.layer)), ); + + it.effect( + "reuses persisted cwd when startSession resumes a claude session without cwd input", + () => + Effect.gen(function* () { + const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), "t3-provider-service-cwd-")); + const dbPath = path.join(tempDir, "orchestration.sqlite"); + const persistenceLayer = makeSqlitePersistenceLive(dbPath); + const runtimeRepositoryLayer = ProviderSessionRuntimeRepositoryLive.pipe( + Layer.provide(persistenceLayer), + ); + + const firstClaude = makeFakeCodexAdapter("claudeAgent"); + const firstRegistry: typeof ProviderAdapterRegistry.Service = { + getByProvider: (provider) => + provider === "claudeAgent" + ? Effect.succeed(firstClaude.adapter) + : Effect.fail(new ProviderUnsupportedError({ provider })), + listProviders: () => Effect.succeed(["claudeAgent"]), + }; + const firstDirectoryLayer = ProviderSessionDirectoryLive.pipe( + Layer.provide(runtimeRepositoryLayer), + ); + const firstProviderLayer = makeProviderServiceLive().pipe( + Layer.provide(Layer.succeed(ProviderAdapterRegistry, firstRegistry)), + Layer.provide(firstDirectoryLayer), + Layer.provide(defaultServerSettingsLayer), + Layer.provide(AnalyticsService.layerTest), + ); + + const initial = yield* Effect.gen(function* () { + const provider = yield* ProviderService; + return yield* provider.startSession(asThreadId("thread-claude-cwd"), { + provider: "claudeAgent", + threadId: asThreadId("thread-claude-cwd"), + cwd: "/tmp/project-claude-cwd", + runtimeMode: "full-access", + }); + }).pipe(Effect.provide(firstProviderLayer)); + + const secondClaude = makeFakeCodexAdapter("claudeAgent"); + const secondRegistry: typeof ProviderAdapterRegistry.Service = { + getByProvider: (provider) => + provider === "claudeAgent" + ? Effect.succeed(secondClaude.adapter) + : Effect.fail(new ProviderUnsupportedError({ provider })), + listProviders: () => Effect.succeed(["claudeAgent"]), + }; + const secondDirectoryLayer = ProviderSessionDirectoryLive.pipe( + Layer.provide(runtimeRepositoryLayer), + ); + const secondProviderLayer = makeProviderServiceLive().pipe( + Layer.provide(Layer.succeed(ProviderAdapterRegistry, secondRegistry)), + Layer.provide(secondDirectoryLayer), + Layer.provide(defaultServerSettingsLayer), + Layer.provide(AnalyticsService.layerTest), + ); + + secondClaude.startSession.mockClear(); + + yield* Effect.gen(function* () { + const provider = yield* ProviderService; + yield* provider.startSession(initial.threadId, { + provider: "claudeAgent", + threadId: initial.threadId, + runtimeMode: "full-access", + }); + }).pipe(Effect.provide(secondProviderLayer)); + + assert.equal(secondClaude.startSession.mock.calls.length, 1); + const resumedStartInput = secondClaude.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, "claudeAgent"); + assert.equal(startPayload.cwd, "/tmp/project-claude-cwd"); + assert.deepEqual(startPayload.resumeCursor, initial.resumeCursor); + assert.equal(startPayload.threadId, initial.threadId); + } + + fs.rmSync(tempDir, { recursive: true, force: true }); + }).pipe(Effect.provide(NodeServices.layer)), + ); }); const fanout = makeProviderServiceLayer(); diff --git a/apps/server/src/provider/Layers/ProviderService.ts b/apps/server/src/provider/Layers/ProviderService.ts index a38a24655f..94630d3bca 100644 --- a/apps/server/src/provider/Layers/ProviderService.ts +++ b/apps/server/src/provider/Layers/ProviderService.ts @@ -374,9 +374,31 @@ const makeProviderService = Effect.fn("makeProviderService")(function* ( (persistedBinding?.provider === input.provider ? persistedBinding.resumeCursor : undefined); + const effectiveCwd = + input.cwd ?? + (persistedBinding?.provider === input.provider + ? readPersistedCwd(persistedBinding.runtimePayload) + : undefined); + yield* Effect.annotateCurrentSpan({ + "provider.resume_cursor.source": + input.resumeCursor !== undefined + ? "request" + : effectiveResumeCursor !== undefined && persistedBinding?.provider === input.provider + ? "persisted" + : "none", + "provider.resume_cursor.present": effectiveResumeCursor !== undefined, + "provider.cwd.source": + input.cwd !== undefined + ? "request" + : effectiveCwd !== undefined && persistedBinding?.provider === input.provider + ? "persisted" + : "none", + "provider.cwd.effective": effectiveCwd ?? "", + }); const adapter = yield* registry.getByProvider(input.provider); const session = yield* adapter.startSession({ ...input, + ...(effectiveCwd !== undefined ? { cwd: effectiveCwd } : {}), ...(effectiveResumeCursor !== undefined ? { resumeCursor: effectiveResumeCursor } : {}), }); @@ -398,7 +420,7 @@ const makeProviderService = Effect.fn("makeProviderService")(function* ( provider: session.provider, runtimeMode: input.runtimeMode, hasResumeCursor: session.resumeCursor !== undefined, - hasCwd: typeof input.cwd === "string" && input.cwd.trim().length > 0, + hasCwd: typeof effectiveCwd === "string" && effectiveCwd.trim().length > 0, hasModel: typeof input.modelSelection?.model === "string" && input.modelSelection.model.trim().length > 0, From 00b5c3e1b3b06888282e5d5e0678a2e3a88eb607 Mon Sep 17 00:00:00 2001 From: legs <145564979+justsomelegs@users.noreply.github.com> Date: Thu, 23 Apr 2026 18:59:08 +0100 Subject: [PATCH 26/82] Add task sidebar auto-open setting (#2314) --- apps/desktop/src/clientPersistence.test.ts | 1 + apps/web/src/components/ChatView.tsx | 19 +++++++++--- .../components/settings/SettingsPanels.tsx | 30 +++++++++++++++++++ apps/web/src/localApi.test.ts | 2 ++ packages/contracts/src/settings.ts | 2 ++ 5 files changed, 50 insertions(+), 4 deletions(-) diff --git a/apps/desktop/src/clientPersistence.test.ts b/apps/desktop/src/clientPersistence.test.ts index 19f9b09f9f..192d7ac106 100644 --- a/apps/desktop/src/clientPersistence.test.ts +++ b/apps/desktop/src/clientPersistence.test.ts @@ -49,6 +49,7 @@ function makeSecretStorage(available: boolean): DesktopSecretStorage { } const clientSettings: ClientSettings = { + autoOpenPlanSidebar: false, confirmThreadArchive: true, confirmThreadDelete: false, diffWordWrap: true, diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsx index 3a71922706..c27afda975 100644 --- a/apps/web/src/components/ChatView.tsx +++ b/apps/web/src/components/ChatView.tsx @@ -616,6 +616,7 @@ export default function ChatView(props: ChatViewProps) { (store) => store.setStickyModelSelection, ); const timestampFormat = settings.timestampFormat; + const autoOpenPlanSidebar = settings.autoOpenPlanSidebar; const navigate = useNavigate(); const rawSearch = useSearch({ strict: false, @@ -2010,6 +2011,7 @@ export default function ChatView(props: ChatViewProps) { planSidebarOpenOnNextThreadRef.current = false; setPlanSidebarOpen(true); } else { + planSidebarOpenOnNextThreadRef.current = false; setPlanSidebarOpen(false); } planSidebarDismissedForTurnRef.current = null; @@ -2018,6 +2020,7 @@ export default function ChatView(props: ChatViewProps) { // Auto-open the plan sidebar when plan/todo steps arrive for the current turn. // Don't auto-open for plans carried over from a previous turn (the user can open manually). useEffect(() => { + if (!autoOpenPlanSidebar) return; if (!activePlan) return; if (planSidebarOpen) return; const latestTurnId = activeLatestTurn?.turnId ?? null; @@ -2025,7 +2028,13 @@ export default function ChatView(props: ChatViewProps) { const turnKey = activePlan.turnId ?? sidebarProposedPlan?.turnId ?? "__dismissed__"; if (planSidebarDismissedForTurnRef.current === turnKey) return; setPlanSidebarOpen(true); - }, [activePlan, activeLatestTurn?.turnId, planSidebarOpen, sidebarProposedPlan?.turnId]); + }, [ + activePlan, + activeLatestTurn?.turnId, + autoOpenPlanSidebar, + planSidebarOpen, + sidebarProposedPlan?.turnId, + ]); useEffect(() => { setIsRevertingCheckpoint(false); @@ -2950,7 +2959,7 @@ export default function ChatView(props: ChatViewProps) { // Optimistically open the plan sidebar when implementing (not refining). // "default" mode here means the agent is executing the plan, which produces // step-tracking activities that the sidebar will display. - if (nextInteractionMode === "default") { + if (nextInteractionMode === "default" && autoOpenPlanSidebar) { planSidebarDismissedForTurnRef.current = null; setPlanSidebarOpen(true); } @@ -2979,6 +2988,7 @@ export default function ChatView(props: ChatViewProps) { runtimeMode, setComposerDraftInteractionMode, setThreadError, + autoOpenPlanSidebar, environmentId, ], ); @@ -3071,8 +3081,8 @@ export default function ChatView(props: ChatViewProps) { return waitForStartedServerThread(scopeThreadRef(activeThread.environmentId, nextThreadId)); }) .then(() => { - // Signal that the plan sidebar should open on the new thread. - planSidebarOpenOnNextThreadRef.current = true; + // Signal that the plan sidebar should open on the new thread when enabled. + planSidebarOpenOnNextThreadRef.current = autoOpenPlanSidebar; return navigate({ to: "/$environmentId/$threadId", params: { @@ -3113,6 +3123,7 @@ export default function ChatView(props: ChatViewProps) { navigate, resetLocalDispatch, runtimeMode, + autoOpenPlanSidebar, environmentId, ]); diff --git a/apps/web/src/components/settings/SettingsPanels.tsx b/apps/web/src/components/settings/SettingsPanels.tsx index 1e8cffd0c4..29d09a5cdc 100644 --- a/apps/web/src/components/settings/SettingsPanels.tsx +++ b/apps/web/src/components/settings/SettingsPanels.tsx @@ -472,6 +472,9 @@ export function useSettingsRestore(onRestored?: () => void) { ...(settings.diffWordWrap !== DEFAULT_UNIFIED_SETTINGS.diffWordWrap ? ["Diff line wrapping"] : []), + ...(settings.autoOpenPlanSidebar !== DEFAULT_UNIFIED_SETTINGS.autoOpenPlanSidebar + ? ["Task sidebar"] + : []), ...(settings.enableAssistantStreaming !== DEFAULT_UNIFIED_SETTINGS.enableAssistantStreaming ? ["Assistant output"] : []), @@ -493,6 +496,7 @@ export function useSettingsRestore(onRestored?: () => void) { [ areProviderSettingsDirty, isGitWritingModelDirty, + settings.autoOpenPlanSidebar, settings.confirmThreadArchive, settings.confirmThreadDelete, settings.addProjectBaseDirectory, @@ -945,6 +949,32 @@ export function GeneralSettingsPanel() { } /> + + updateSettings({ + autoOpenPlanSidebar: DEFAULT_UNIFIED_SETTINGS.autoOpenPlanSidebar, + }) + } + /> + ) : null + } + control={ + + updateSettings({ autoOpenPlanSidebar: Boolean(checked) }) + } + aria-label="Open the task sidebar automatically" + /> + } + /> + { it("reads and writes persistence through the desktop bridge when available", async () => { const clientSettings = { + autoOpenPlanSidebar: false, confirmThreadArchive: true, confirmThreadDelete: false, diffWordWrap: true, @@ -587,6 +588,7 @@ describe("wsApi", () => { const { createLocalApi } = await import("./localApi"); const api = createLocalApi(rpcClientMock as never); const clientSettings = { + autoOpenPlanSidebar: false, confirmThreadArchive: true, confirmThreadDelete: false, diffWordWrap: true, diff --git a/packages/contracts/src/settings.ts b/packages/contracts/src/settings.ts index 6301364f33..2b50957a79 100644 --- a/packages/contracts/src/settings.ts +++ b/packages/contracts/src/settings.ts @@ -31,6 +31,7 @@ export type SidebarProjectGroupingMode = typeof SidebarProjectGroupingMode.Type; export const DEFAULT_SIDEBAR_PROJECT_GROUPING_MODE: SidebarProjectGroupingMode = "repository"; export const ClientSettingsSchema = Schema.Struct({ + autoOpenPlanSidebar: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(true))), confirmThreadArchive: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(false))), confirmThreadDelete: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(true))), diffWordWrap: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(false))), @@ -243,6 +244,7 @@ export const ServerSettingsPatch = Schema.Struct({ export type ServerSettingsPatch = typeof ServerSettingsPatch.Type; export const ClientSettingsPatch = Schema.Struct({ + autoOpenPlanSidebar: Schema.optionalKey(Schema.Boolean), confirmThreadArchive: Schema.optionalKey(Schema.Boolean), confirmThreadDelete: Schema.optionalKey(Schema.Boolean), diffWordWrap: Schema.optionalKey(Schema.Boolean), From ada410bccff144ce4cfed0e2c6e18974b045f968 Mon Sep 17 00:00:00 2001 From: "t3-code[bot]" <269035359+t3-code[bot]@users.noreply.github.com> Date: Thu, 23 Apr 2026 18:05:15 +0000 Subject: [PATCH 27/82] chore(release): prepare v0.0.21 --- apps/desktop/package.json | 2 +- apps/server/package.json | 2 +- apps/web/package.json | 2 +- bun.lock | 8 ++++---- packages/contracts/package.json | 2 +- 5 files changed, 8 insertions(+), 8 deletions(-) diff --git a/apps/desktop/package.json b/apps/desktop/package.json index 2a4ced70e7..165395507e 100644 --- a/apps/desktop/package.json +++ b/apps/desktop/package.json @@ -1,6 +1,6 @@ { "name": "@t3tools/desktop", - "version": "0.0.20", + "version": "0.0.21", "private": true, "type": "module", "main": "dist-electron/main.cjs", diff --git a/apps/server/package.json b/apps/server/package.json index 14dbe35bcb..13a8124cb2 100644 --- a/apps/server/package.json +++ b/apps/server/package.json @@ -1,6 +1,6 @@ { "name": "t3", - "version": "0.0.20", + "version": "0.0.21", "license": "MIT", "repository": { "type": "git", diff --git a/apps/web/package.json b/apps/web/package.json index b18defebbe..11e69d1248 100644 --- a/apps/web/package.json +++ b/apps/web/package.json @@ -1,6 +1,6 @@ { "name": "@t3tools/web", - "version": "0.0.20", + "version": "0.0.21", "private": true, "type": "module", "scripts": { diff --git a/bun.lock b/bun.lock index e9b7511e34..a8dc482f46 100644 --- a/bun.lock +++ b/bun.lock @@ -14,7 +14,7 @@ }, "apps/desktop": { "name": "@t3tools/desktop", - "version": "0.0.20", + "version": "0.0.21", "dependencies": { "effect": "catalog:", "electron": "40.6.0", @@ -43,7 +43,7 @@ }, "apps/server": { "name": "t3", - "version": "0.0.20", + "version": "0.0.21", "bin": { "t3": "./dist/bin.mjs", }, @@ -75,7 +75,7 @@ }, "apps/web": { "name": "@t3tools/web", - "version": "0.0.20", + "version": "0.0.21", "dependencies": { "@base-ui/react": "^1.2.0", "@dnd-kit/core": "^6.3.1", @@ -140,7 +140,7 @@ }, "packages/contracts": { "name": "@t3tools/contracts", - "version": "0.0.20", + "version": "0.0.21", "dependencies": { "effect": "catalog:", }, diff --git a/packages/contracts/package.json b/packages/contracts/package.json index 8b499267f6..0e436d64d5 100644 --- a/packages/contracts/package.json +++ b/packages/contracts/package.json @@ -1,6 +1,6 @@ { "name": "@t3tools/contracts", - "version": "0.0.20", + "version": "0.0.21", "private": true, "files": [ "dist" From 5cf83ffe8f9d5eabd1c17721bd1f9597c97d98fe Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sun, 26 Apr 2026 19:30:18 -0700 Subject: [PATCH 28/82] fix(release): use configured node for smoke manifest merge (#2364) Co-authored-by: codex --- scripts/release-smoke.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/scripts/release-smoke.ts b/scripts/release-smoke.ts index 1736abab37..7aff0a2f65 100644 --- a/scripts/release-smoke.ts +++ b/scripts/release-smoke.ts @@ -292,7 +292,7 @@ try { fi found_windows_manifest=true - node ${JSON.stringify(resolve(repoRoot, "scripts/merge-update-manifests.ts"))} --platform win \ + ${JSON.stringify(process.execPath)} ${JSON.stringify(resolve(repoRoot, "scripts/merge-update-manifests.ts"))} --platform win \ "$arm64_manifest" \ "$x64_manifest" \ "$output_manifest" From dbebc387dd458dd7062380ccb862a5cdac7aba66 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Mon, 27 Apr 2026 09:50:19 -0700 Subject: [PATCH 29/82] Ignore stale WebSocket lifecycle events after reconnect (#2372) --- apps/web/src/rpc/protocol.ts | 16 ++++++++ apps/web/src/rpc/wsTransport.test.ts | 57 ++++++++++++++++++++++++++++ apps/web/src/rpc/wsTransport.ts | 13 ++++++- 3 files changed, 85 insertions(+), 1 deletion(-) diff --git a/apps/web/src/rpc/protocol.ts b/apps/web/src/rpc/protocol.ts index 5c5c51d899..0a4288df39 100644 --- a/apps/web/src/rpc/protocol.ts +++ b/apps/web/src/rpc/protocol.ts @@ -18,6 +18,7 @@ import { } from "./wsConnectionState"; export interface WsProtocolLifecycleHandlers { + readonly isActive?: () => boolean; readonly onAttempt?: (socketUrl: string) => void; readonly onOpen?: () => void; readonly onError?: (message: string) => void; @@ -49,6 +50,7 @@ function resolveWsRpcSocketUrl(rawUrl: string): string { function defaultLifecycleHandlers(): Required { return { + isActive: () => true, onAttempt: recordWsConnectionAttempt, onOpen: recordWsConnectionOpened, onError: (message) => { @@ -66,21 +68,35 @@ function composeLifecycleHandlers( handlers?: WsProtocolLifecycleHandlers, ): Required { const defaults = defaultLifecycleHandlers(); + const isActive = handlers?.isActive ?? (() => true); return { + isActive, onAttempt: (socketUrl) => { + if (!isActive()) { + return; + } defaults.onAttempt(socketUrl); handlers?.onAttempt?.(socketUrl); }, onOpen: () => { + if (!isActive()) { + return; + } defaults.onOpen(); handlers?.onOpen?.(); }, onError: (message) => { + if (!isActive()) { + return; + } defaults.onError(message); handlers?.onError?.(message); }, onClose: (details) => { + if (!isActive()) { + return; + } defaults.onClose(details); handlers?.onClose?.(details); }, diff --git a/apps/web/src/rpc/wsTransport.test.ts b/apps/web/src/rpc/wsTransport.test.ts index a5610a931f..c9632d3f78 100644 --- a/apps/web/src/rpc/wsTransport.test.ts +++ b/apps/web/src/rpc/wsTransport.test.ts @@ -324,6 +324,11 @@ describe("WsTransport", () => { const secondSocket = getSocket(); expect(secondSocket).not.toBe(firstSocket); expect(firstSocket.readyState).toBe(MockWebSocket.CLOSED); + expect(getWsConnectionStatus()).toMatchObject({ + closeCode: null, + closeReason: null, + phase: "connecting", + }); const requestPromise = transport.request((client) => client[WS_METHODS.serverUpsertKeybinding]({ @@ -361,6 +366,58 @@ describe("WsTransport", () => { await transport.dispose(); }); + it("ignores stale socket lifecycle events after a reconnect starts a new session", async () => { + const onClose = vi.fn(); + const transport = createTransport("ws://localhost:3020", { onClose }); + + await waitFor(() => { + expect(sockets).toHaveLength(1); + }); + + const firstSocket = getSocket(); + firstSocket.open(); + + await waitFor(() => { + expect(getWsConnectionStatus()).toMatchObject({ + hasConnected: true, + phase: "connected", + }); + }); + + await transport.reconnect(); + + await waitFor(() => { + expect(sockets).toHaveLength(2); + }); + + expect(onClose).not.toHaveBeenCalled(); + expect(getWsConnectionStatus()).toMatchObject({ + closeCode: null, + closeReason: null, + phase: "connecting", + }); + + const secondSocket = getSocket(); + secondSocket.open(); + + await waitFor(() => { + expect(getWsConnectionStatus()).toMatchObject({ + phase: "connected", + }); + }); + + firstSocket.close(1006, "stale close"); + + expect(onClose).not.toHaveBeenCalled(); + expect(getWsConnectionStatus()).toMatchObject({ + closeCode: null, + closeReason: null, + phase: "connected", + }); + + await transport.dispose(); + }); + it("marks unary requests as slow until the first server ack arrives", async () => { const slowAckThresholdMs = 25; setSlowRpcAckThresholdMsForTests(slowAckThresholdMs); diff --git a/apps/web/src/rpc/wsTransport.ts b/apps/web/src/rpc/wsTransport.ts index d9a50a9fad..0b90b22431 100644 --- a/apps/web/src/rpc/wsTransport.ts +++ b/apps/web/src/rpc/wsTransport.ts @@ -53,6 +53,8 @@ export class WsTransport { private disposed = false; private hasReportedTransportDisconnect = false; private reconnectChain: Promise = Promise.resolve(); + private nextSessionId = 0; + private activeSessionId = 0; private session: TransportSession; constructor( @@ -215,8 +217,17 @@ export class WsTransport { } private createSession(): TransportSession { + const sessionId = this.nextSessionId + 1; + this.nextSessionId = sessionId; + this.activeSessionId = sessionId; const runtime = ManagedRuntime.make( - Layer.mergeAll(createWsRpcProtocolLayer(this.url, this.lifecycleHandlers), ClientTracingLive), + Layer.mergeAll( + createWsRpcProtocolLayer(this.url, { + ...this.lifecycleHandlers, + isActive: () => !this.disposed && this.activeSessionId === sessionId, + }), + ClientTracingLive, + ), ); const clientScope = runtime.runSync(Scope.make()); return { From 35822884d19ba64c6529d7736fb0182b361f3e4c Mon Sep 17 00:00:00 2001 From: Josh Meads <8870827+joshmeads@users.noreply.github.com> Date: Sun, 26 Apr 2026 17:13:04 -0700 Subject: [PATCH 30/82] Stop OpenCode refresh from leaking serve processes OpenCode can leave the long-lived serve child in the spawned process group after the wrapper exits. Provider refresh owns only a scoped inventory probe, so cleanup targets that local process group when the refresh scope closes. Constraint: Keep active OpenCode thread sessions scoped to their own session lifecycle. Rejected: Disable provider refresh | would hide model and auth state changes. Confidence: high Scope-risk: narrow Tested: bun run test src/provider/Layers/OpenCodeProvider.test.ts src/provider/Layers/OpenCodeAdapter.test.ts Tested: bun fmt Tested: bun lint Tested: bun typecheck Tested: bun run build:desktop --- .../provider/Layers/OpenCodeProvider.test.ts | 28 ++++++++++++++++--- apps/server/src/provider/opencodeRuntime.ts | 20 +++++++++++++ 2 files changed, 44 insertions(+), 4 deletions(-) diff --git a/apps/server/src/provider/Layers/OpenCodeProvider.test.ts b/apps/server/src/provider/Layers/OpenCodeProvider.test.ts index f32fd6f49e..75622281c5 100644 --- a/apps/server/src/provider/Layers/OpenCodeProvider.test.ts +++ b/apps/server/src/provider/Layers/OpenCodeProvider.test.ts @@ -23,6 +23,7 @@ const runtimeMock = { runVersionError: null as Error | null, versionStdout: DEFAULT_VERSION_STDOUT, inventoryError: null as Error | null, + closeCalls: 0, inventory: { providerList: { connected: [] as string[], all: [] as unknown[], default: {} }, agents: [] as unknown[], @@ -32,6 +33,7 @@ const runtimeMock = { this.state.runVersionError = null; this.state.versionStdout = DEFAULT_VERSION_STDOUT; this.state.inventoryError = null; + this.state.closeCalls = 0; this.state.inventory = { providerList: { connected: [], all: [] as unknown[], default: {} }, agents: [] as unknown[], @@ -46,10 +48,19 @@ const OpenCodeRuntimeTestDouble: OpenCodeRuntimeShape = { exitCode: Effect.never, }), connectToOpenCodeServer: ({ serverUrl }) => - Effect.succeed({ - url: serverUrl ?? "http://127.0.0.1:4301", - exitCode: null, - external: Boolean(serverUrl), + Effect.gen(function* () { + if (!serverUrl) { + yield* Effect.addFinalizer(() => + Effect.sync(() => { + runtimeMock.state.closeCalls += 1; + }), + ); + } + return { + url: serverUrl ?? "http://127.0.0.1:4301", + exitCode: null, + external: Boolean(serverUrl), + }; }), runOpenCodeCommand: () => runtimeMock.state.runVersionError @@ -188,6 +199,15 @@ it.layer(makeTestLayer())("OpenCodeProviderLive", (it) => { assert.equal(agentDescriptor.options.find((option) => option.isDefault)?.id, "build"); }), ); + + it.effect("closes the local OpenCode server scope after provider refresh", () => + Effect.gen(function* () { + const provider = yield* OpenCodeProvider; + yield* provider.refresh; + + assert.equal(runtimeMock.state.closeCalls, 1); + }), + ); }); it.layer( diff --git a/apps/server/src/provider/opencodeRuntime.ts b/apps/server/src/provider/opencodeRuntime.ts index 41ec5102c3..086584893c 100644 --- a/apps/server/src/provider/opencodeRuntime.ts +++ b/apps/server/src/provider/opencodeRuntime.ts @@ -330,6 +330,7 @@ const makeOpenCodeRuntime = Effect.gen(function* () { const child = yield* spawner .spawn( ChildProcess.make(input.binaryPath, args, { + detached: process.platform !== "win32", env: { ...process.env, OPENCODE_CONFIG_CONTENT: JSON.stringify({}), @@ -348,6 +349,25 @@ const makeOpenCodeRuntime = Effect.gen(function* () { ), ); + const killOpenCodeProcessGroup = (signal: NodeJS.Signals) => + process.platform === "win32" + ? child.kill({ killSignal: signal, forceKillAfter: "1 second" }).pipe(Effect.asVoid) + : Effect.sync(() => { + try { + process.kill(-Number(child.pid), signal); + } catch { + // The direct child may already have exited after starting the + // server; the process group kill is best-effort cleanup for + // any serve process left in that group. + } + }); + const terminateChild = killOpenCodeProcessGroup("SIGTERM").pipe( + Effect.andThen(Effect.sleep("1 second")), + Effect.andThen(killOpenCodeProcessGroup("SIGKILL")), + Effect.ignore, + ); + yield* Scope.addFinalizer(runtimeScope, terminateChild); + const stdoutRef = yield* Ref.make(""); const stderrRef = yield* Ref.make(""); const readyDeferred = yield* Deferred.make(); From 08e6d4cfbfe55af83fe5fb6b9e75364f42f1f22f Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Wed, 29 Apr 2026 16:13:55 -0700 Subject: [PATCH 31/82] feat: Multi-Provider support (#2277) Co-authored-by: Claude Opus 4.7 Co-authored-by: codex --- apps/desktop/src/clientPersistence.test.ts | 1 + .../OrchestrationEngineHarness.integration.ts | 44 +- .../TestProviderAdapter.integration.ts | 17 +- .../integration/fixtures/providerRuntime.ts | 4 +- .../orchestrationEngine.integration.test.ts | 178 +- .../providerService.integration.test.ts | 37 +- .../git/Layers/ClaudeTextGeneration.test.ts | 319 +-- .../src/git/Layers/ClaudeTextGeneration.ts | 55 +- .../git/Layers/CodexTextGeneration.test.ts | 524 +++-- .../src/git/Layers/CodexTextGeneration.ts | 97 +- .../git/Layers/CursorTextGeneration.test.ts | 313 ++- .../src/git/Layers/CursorTextGeneration.ts | 56 +- .../git/Layers/OpenCodeTextGeneration.test.ts | 348 ++-- .../src/git/Layers/OpenCodeTextGeneration.ts | 77 +- .../src/git/Layers/RoutingTextGeneration.ts | 104 - .../src/git/Layers/TextGenerationLive.test.ts | 117 ++ .../src/git/Layers/TextGenerationLive.ts | 101 + apps/server/src/observability/Metrics.test.ts | 10 +- .../Layers/CheckpointReactor.test.ts | 60 +- .../Layers/OrchestrationEngine.test.ts | 51 +- .../Layers/ProjectionPipeline.test.ts | 33 +- .../Layers/ProjectionPipeline.ts | 1 + .../Layers/ProjectionSnapshotQuery.test.ts | 18 +- .../Layers/ProjectionSnapshotQuery.ts | 6 + .../Layers/ProviderCommandReactor.test.ts | 438 +++- .../Layers/ProviderCommandReactor.ts | 197 +- .../Layers/ProviderRuntimeIngestion.test.ts | 229 +- .../Layers/ProviderRuntimeIngestion.ts | 6 + .../orchestration/commandInvariants.test.ts | 13 +- .../src/orchestration/decider.delete.test.ts | 5 +- .../decider.projectScripts.test.ts | 11 +- .../src/orchestration/projector.test.ts | 21 +- .../Layers/ProjectionRepositories.test.ts | 14 +- .../Layers/ProjectionThreadSessions.ts | 4 + .../Layers/ProviderSessionRuntime.ts | 5 + apps/server/src/persistence/Migrations.ts | 4 + .../027_028_ProviderInstanceIdColumns.test.ts | 74 + .../027_ProviderSessionRuntimeInstanceId.ts | 38 + .../028_ProjectionThreadSessionInstanceId.ts | 21 + .../Services/ProjectionThreadSessions.ts | 2 + .../Services/ProviderSessionRuntime.ts | 9 + .../src/provider/Drivers/ClaudeDriver.ts | 157 ++ .../src/provider/Drivers/ClaudeHome.test.ts | 52 + .../server/src/provider/Drivers/ClaudeHome.ts | 43 + .../src/provider/Drivers/CodexDriver.ts | 171 ++ .../provider/Drivers/CodexHomeLayout.test.ts | 209 ++ .../src/provider/Drivers/CodexHomeLayout.ts | 263 +++ .../src/provider/Drivers/CursorDriver.ts | 148 ++ .../src/provider/Drivers/OpenCodeDriver.ts | 135 ++ apps/server/src/provider/Errors.ts | 41 + .../src/provider/Layers/ClaudeAdapter.test.ts | 339 +-- .../src/provider/Layers/ClaudeAdapter.ts | 63 +- .../src/provider/Layers/ClaudeProvider.ts | 486 ++--- .../src/provider/Layers/CodexAdapter.test.ts | 186 +- .../src/provider/Layers/CodexAdapter.ts | 65 +- .../src/provider/Layers/CodexProvider.ts | 99 +- .../provider/Layers/CodexSessionRuntime.ts | 61 +- .../src/provider/Layers/CursorAdapter.test.ts | 213 +- .../src/provider/Layers/CursorAdapter.ts | 73 +- .../provider/Layers/CursorProvider.test.ts | 159 +- .../src/provider/Layers/CursorProvider.ts | 679 +++--- .../provider/Layers/OpenCodeAdapter.test.ts | 286 ++- .../src/provider/Layers/OpenCodeAdapter.ts | 1836 +++++++++-------- .../provider/Layers/OpenCodeProvider.test.ts | 117 +- .../src/provider/Layers/OpenCodeProvider.ts | 378 ++-- .../Layers/ProviderAdapterRegistry.test.ts | 148 +- .../Layers/ProviderAdapterRegistry.ts | 127 +- .../provider/Layers/ProviderEventLoggers.ts | 83 + .../ProviderInstanceRegistryHydration.ts | 176 ++ .../ProviderInstanceRegistryLive.test.ts | 357 ++++ .../Layers/ProviderInstanceRegistryLive.ts | 434 ++++ .../provider/Layers/ProviderRegistry.test.ts | 856 ++++++-- .../src/provider/Layers/ProviderRegistry.ts | 546 +++-- .../provider/Layers/ProviderService.test.ts | 583 ++++-- .../src/provider/Layers/ProviderService.ts | 418 +++- .../Layers/ProviderSessionDirectory.test.ts | 25 +- .../Layers/ProviderSessionDirectory.ts | 24 +- .../Layers/ProviderSessionReaper.test.ts | 31 +- .../Layers/scopedSafeTeardown.test.ts | 94 + .../src/provider/Layers/scopedSafeTeardown.ts | 61 + apps/server/src/provider/ProviderDriver.ts | 167 ++ .../ProviderInstanceEnvironment.test.ts | 21 + .../provider/ProviderInstanceEnvironment.ts | 16 + .../src/provider/Services/ClaudeAdapter.ts | 29 +- .../src/provider/Services/ClaudeProvider.ts | 9 - .../src/provider/Services/CodexAdapter.ts | 29 +- .../src/provider/Services/CodexProvider.ts | 9 - .../src/provider/Services/CursorAdapter.ts | 25 +- .../src/provider/Services/CursorProvider.ts | 9 - .../src/provider/Services/OpenCodeAdapter.ts | 25 +- .../src/provider/Services/OpenCodeProvider.ts | 9 - .../src/provider/Services/ProviderAdapter.ts | 4 +- .../Services/ProviderAdapterRegistry.ts | 81 +- .../Services/ProviderInstanceRegistry.ts | 84 + .../ProviderInstanceRegistryMutator.ts | 52 + .../src/provider/Services/ProviderRegistry.ts | 29 +- .../src/provider/Services/ProviderService.ts | 11 +- .../Services/ProviderSessionDirectory.ts | 13 +- .../provider/acp/AcpAdapterSupport.test.ts | 3 +- .../src/provider/acp/AcpAdapterSupport.ts | 4 +- .../provider/acp/AcpCoreRuntimeEvents.test.ts | 14 +- .../src/provider/acp/AcpCoreRuntimeEvents.ts | 14 +- .../src/provider/acp/AcpNativeLogging.ts | 6 +- .../src/provider/acp/AcpSessionRuntime.ts | 2 +- .../src/provider/acp/CursorAcpSupport.ts | 5 +- apps/server/src/provider/builtInDrivers.ts | 50 + .../src/provider/builtInProviderCatalog.ts | 50 +- .../makeManagedServerProvider.test.ts | 8 +- apps/server/src/provider/opencodeRuntime.ts | 8 +- .../src/provider/providerSnapshot.test.ts | 4 +- apps/server/src/provider/providerSnapshot.ts | 9 +- .../src/provider/providerStatusCache.test.ts | 106 +- .../src/provider/providerStatusCache.ts | 80 +- .../testUtils/providerAdapterRegistryMock.ts | 95 + .../provider/unavailableProviderSnapshot.ts | 72 + apps/server/src/server.test.ts | 12 +- apps/server/src/server.ts | 76 +- apps/server/src/serverRuntimeStartup.test.ts | 6 +- apps/server/src/serverRuntimeStartup.ts | 7 +- apps/server/src/serverSettings.test.ts | 242 ++- apps/server/src/serverSettings.ts | 246 ++- apps/server/src/ws.ts | 42 +- apps/web/src/components/ChatView.browser.tsx | 221 +- .../web/src/components/ChatView.logic.test.ts | 27 +- apps/web/src/components/ChatView.logic.ts | 35 +- apps/web/src/components/ChatView.tsx | 89 +- .../components/CommandPalette.logic.test.ts | 4 +- apps/web/src/components/CommandPalette.tsx | 7 +- apps/web/src/components/Icons.tsx | 23 + .../components/KeybindingsToast.browser.tsx | 30 +- apps/web/src/components/Sidebar.logic.test.ts | 15 +- apps/web/src/components/chat/ChatComposer.tsx | 187 +- .../CompactComposerControlsMenu.browser.tsx | 52 +- .../components/chat/ComposerCommandMenu.tsx | 6 +- apps/web/src/components/chat/ModelListRow.tsx | 33 +- .../components/chat/ModelPickerContent.tsx | 370 ++-- .../components/chat/ModelPickerSidebar.tsx | 375 ++-- .../components/chat/ProviderInstanceIcon.tsx | 73 + .../chat/ProviderModelPicker.browser.tsx | 252 ++- .../components/chat/ProviderModelPicker.tsx | 83 +- .../components/chat/ProviderStatusBanner.tsx | 4 +- apps/web/src/components/chat/TraitsPicker.tsx | 10 +- .../chat/composerProviderState.test.tsx | 12 +- .../components/chat/composerProviderState.tsx | 8 +- .../chat/composerSlashCommandSearch.test.ts | 11 +- .../chat/modelPickerModelHighlights.ts | 4 +- .../components/chat/modelPickerSearch.test.ts | 40 +- .../src/components/chat/modelPickerSearch.ts | 22 +- .../src/components/chat/providerIconUtils.ts | 19 +- .../settings/AddProviderInstanceDialog.tsx | 493 +++++ .../settings/ProviderInstanceCard.test.ts | 36 + .../settings/ProviderInstanceCard.tsx | 814 ++++++++ .../settings/ProviderModelsSection.tsx | 411 ++++ .../settings/SettingsPanels.browser.tsx | 10 +- .../settings/SettingsPanels.logic.test.ts | 63 + .../settings/SettingsPanels.logic.ts | 43 + .../components/settings/SettingsPanels.tsx | 1128 ++++------ .../components/settings/providerDriverMeta.ts | 151 ++ .../src/components/settings/providerStatus.ts | 91 + apps/web/src/components/ui/draft-input.tsx | 21 + apps/web/src/composerDraftStore.test.ts | 243 ++- apps/web/src/composerDraftStore.ts | 382 ++-- apps/web/src/environmentGrouping.test.ts | 4 +- .../service.threadSubscriptions.test.ts | 3 +- apps/web/src/hooks/useCommitOnBlur.ts | 49 + apps/web/src/lib/threadSort.test.ts | 10 +- apps/web/src/localApi.test.ts | 11 +- apps/web/src/modelOrdering.test.ts | 52 + apps/web/src/modelOrdering.ts | 86 + apps/web/src/modelSelection.test.ts | 251 +++ apps/web/src/modelSelection.ts | 271 ++- .../web/src/orchestrationEventEffects.test.ts | 5 +- apps/web/src/providerInstances.test.ts | 132 ++ apps/web/src/providerInstances.ts | 248 +++ apps/web/src/providerModels.ts | 47 +- apps/web/src/rpc/serverState.test.ts | 5 +- apps/web/src/rpc/wsRpcClient.ts | 12 +- apps/web/src/session-logic.ts | 22 +- apps/web/src/store.test.ts | 27 +- apps/web/src/store.ts | 21 +- apps/web/src/types.ts | 6 +- apps/web/src/worktreeCleanup.test.ts | 4 +- apps/web/vite.config.ts | 8 +- docs/providers/claude.md | 224 ++ docs/providers/codex.md | 140 ++ packages/contracts/src/index.ts | 1 + packages/contracts/src/ipc.ts | 10 +- packages/contracts/src/model.ts | 56 +- packages/contracts/src/orchestration.test.ts | 111 +- packages/contracts/src/orchestration.ts | 95 +- packages/contracts/src/provider.test.ts | 145 +- packages/contracts/src/provider.ts | 16 +- .../contracts/src/providerInstance.test.ts | 192 ++ packages/contracts/src/providerInstance.ts | 148 ++ .../contracts/src/providerRuntime.test.ts | 17 + packages/contracts/src/providerRuntime.ts | 8 +- packages/contracts/src/rpc.ts | 11 +- packages/contracts/src/server.test.ts | 24 +- packages/contracts/src/server.ts | 55 +- packages/contracts/src/settings.test.ts | 94 + packages/contracts/src/settings.ts | 99 +- packages/shared/src/model.test.ts | 42 +- packages/shared/src/model.ts | 28 +- packages/shared/src/serverSettings.test.ts | 90 +- packages/shared/src/serverSettings.ts | 17 +- 205 files changed, 17898 insertions(+), 6564 deletions(-) delete mode 100644 apps/server/src/git/Layers/RoutingTextGeneration.ts create mode 100644 apps/server/src/git/Layers/TextGenerationLive.test.ts create mode 100644 apps/server/src/git/Layers/TextGenerationLive.ts create mode 100644 apps/server/src/persistence/Migrations/027_028_ProviderInstanceIdColumns.test.ts create mode 100644 apps/server/src/persistence/Migrations/027_ProviderSessionRuntimeInstanceId.ts create mode 100644 apps/server/src/persistence/Migrations/028_ProjectionThreadSessionInstanceId.ts create mode 100644 apps/server/src/provider/Drivers/ClaudeDriver.ts create mode 100644 apps/server/src/provider/Drivers/ClaudeHome.test.ts create mode 100644 apps/server/src/provider/Drivers/ClaudeHome.ts create mode 100644 apps/server/src/provider/Drivers/CodexDriver.ts create mode 100644 apps/server/src/provider/Drivers/CodexHomeLayout.test.ts create mode 100644 apps/server/src/provider/Drivers/CodexHomeLayout.ts create mode 100644 apps/server/src/provider/Drivers/CursorDriver.ts create mode 100644 apps/server/src/provider/Drivers/OpenCodeDriver.ts create mode 100644 apps/server/src/provider/Layers/ProviderEventLoggers.ts create mode 100644 apps/server/src/provider/Layers/ProviderInstanceRegistryHydration.ts create mode 100644 apps/server/src/provider/Layers/ProviderInstanceRegistryLive.test.ts create mode 100644 apps/server/src/provider/Layers/ProviderInstanceRegistryLive.ts create mode 100644 apps/server/src/provider/Layers/scopedSafeTeardown.test.ts create mode 100644 apps/server/src/provider/Layers/scopedSafeTeardown.ts create mode 100644 apps/server/src/provider/ProviderDriver.ts create mode 100644 apps/server/src/provider/ProviderInstanceEnvironment.test.ts create mode 100644 apps/server/src/provider/ProviderInstanceEnvironment.ts delete mode 100644 apps/server/src/provider/Services/ClaudeProvider.ts delete mode 100644 apps/server/src/provider/Services/CodexProvider.ts delete mode 100644 apps/server/src/provider/Services/CursorProvider.ts delete mode 100644 apps/server/src/provider/Services/OpenCodeProvider.ts create mode 100644 apps/server/src/provider/Services/ProviderInstanceRegistry.ts create mode 100644 apps/server/src/provider/Services/ProviderInstanceRegistryMutator.ts create mode 100644 apps/server/src/provider/builtInDrivers.ts create mode 100644 apps/server/src/provider/testUtils/providerAdapterRegistryMock.ts create mode 100644 apps/server/src/provider/unavailableProviderSnapshot.ts create mode 100644 apps/web/src/components/chat/ProviderInstanceIcon.tsx create mode 100644 apps/web/src/components/settings/AddProviderInstanceDialog.tsx create mode 100644 apps/web/src/components/settings/ProviderInstanceCard.test.ts create mode 100644 apps/web/src/components/settings/ProviderInstanceCard.tsx create mode 100644 apps/web/src/components/settings/ProviderModelsSection.tsx create mode 100644 apps/web/src/components/settings/SettingsPanels.logic.test.ts create mode 100644 apps/web/src/components/settings/SettingsPanels.logic.ts create mode 100644 apps/web/src/components/settings/providerDriverMeta.ts create mode 100644 apps/web/src/components/settings/providerStatus.ts create mode 100644 apps/web/src/components/ui/draft-input.tsx create mode 100644 apps/web/src/hooks/useCommitOnBlur.ts create mode 100644 apps/web/src/modelOrdering.test.ts create mode 100644 apps/web/src/modelOrdering.ts create mode 100644 apps/web/src/modelSelection.test.ts create mode 100644 apps/web/src/providerInstances.test.ts create mode 100644 apps/web/src/providerInstances.ts create mode 100644 docs/providers/claude.md create mode 100644 docs/providers/codex.md create mode 100644 packages/contracts/src/providerInstance.test.ts create mode 100644 packages/contracts/src/providerInstance.ts create mode 100644 packages/contracts/src/settings.test.ts diff --git a/apps/desktop/src/clientPersistence.test.ts b/apps/desktop/src/clientPersistence.test.ts index 192d7ac106..71b6b7df4e 100644 --- a/apps/desktop/src/clientPersistence.test.ts +++ b/apps/desktop/src/clientPersistence.test.ts @@ -54,6 +54,7 @@ const clientSettings: ClientSettings = { confirmThreadDelete: false, diffWordWrap: true, favorites: [], + providerModelPreferences: {}, sidebarProjectGroupingMode: "repository_path", sidebarProjectGroupingOverrides: { "environment-1:/tmp/project-a": "separate", diff --git a/apps/server/integration/OrchestrationEngineHarness.integration.ts b/apps/server/integration/OrchestrationEngineHarness.integration.ts index 6f9f4c6f44..d650f62308 100644 --- a/apps/server/integration/OrchestrationEngineHarness.integration.ts +++ b/apps/server/integration/OrchestrationEngineHarness.integration.ts @@ -3,7 +3,8 @@ import { execFileSync } from "node:child_process"; import * as NodeServices from "@effect/platform-node/NodeServices"; import { ApprovalRequestId, - ProviderKind, + CodexSettings, + ProviderDriverKind, type OrchestrationEvent, type OrchestrationThread, } from "@t3tools/contracts"; @@ -36,13 +37,16 @@ import { ProviderSessionRuntimeRepositoryLive } from "../src/persistence/Layers/ import { makeSqlitePersistenceLive } from "../src/persistence/Layers/Sqlite.ts"; import { ProjectionCheckpointRepository } from "../src/persistence/Services/ProjectionCheckpoints.ts"; import { ProjectionPendingApprovalRepository } from "../src/persistence/Services/ProjectionPendingApprovals.ts"; -import { ProviderUnsupportedError } from "../src/provider/Errors.ts"; +import { makeAdapterRegistryMock } from "../src/provider/testUtils/providerAdapterRegistryMock.ts"; import { ProviderAdapterRegistry } from "../src/provider/Services/ProviderAdapterRegistry.ts"; import { ProviderSessionDirectoryLive } from "../src/provider/Layers/ProviderSessionDirectory.ts"; import { ServerSettingsService } from "../src/serverSettings.ts"; import { makeProviderServiceLive } from "../src/provider/Layers/ProviderService.ts"; -import { makeCodexAdapterLive } from "../src/provider/Layers/CodexAdapter.ts"; -import { CodexAdapter } from "../src/provider/Services/CodexAdapter.ts"; +import { makeCodexAdapter } from "../src/provider/Layers/CodexAdapter.ts"; +import { + NoOpProviderEventLoggers, + ProviderEventLoggers, +} from "../src/provider/Layers/ProviderEventLoggers.ts"; import { ProviderService } from "../src/provider/Services/ProviderService.ts"; import { AnalyticsService } from "../src/telemetry/Services/AnalyticsService.ts"; import { CheckpointReactorLive } from "../src/orchestration/Layers/CheckpointReactor.ts"; @@ -214,7 +218,7 @@ export interface OrchestrationIntegrationHarness { } interface MakeOrchestrationIntegrationHarnessOptions { - readonly provider?: ProviderKind; + readonly provider?: ProviderDriverKind; readonly realCodex?: boolean; } @@ -225,7 +229,7 @@ export const makeOrchestrationIntegrationHarness = ( const path = yield* Path.Path; const fileSystem = yield* FileSystem.FileSystem; - const provider = options?.provider ?? "codex"; + const provider = options?.provider ?? ProviderDriverKind.make("codex"); const useRealCodex = options?.realCodex === true; const adapterHarness = useRealCodex ? null @@ -233,13 +237,10 @@ export const makeOrchestrationIntegrationHarness = ( provider, }); const fakeRegistry = adapterHarness - ? Layer.succeed(ProviderAdapterRegistry, { - getByProvider: (resolvedProvider) => - resolvedProvider === adapterHarness.provider - ? Effect.succeed(adapterHarness.adapter) - : Effect.fail(new ProviderUnsupportedError({ provider: resolvedProvider })), - listProviders: () => Effect.succeed([adapterHarness.provider]), - } as typeof ProviderAdapterRegistry.Service) + ? Layer.succeed( + ProviderAdapterRegistry, + makeAdapterRegistryMock({ [adapterHarness.provider]: adapterHarness.adapter }), + ) : null; const rootDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-orchestration-integration-", @@ -264,31 +265,30 @@ export const makeOrchestrationIntegrationHarness = ( const realCodexRegistry = Layer.effect( ProviderAdapterRegistry, Effect.gen(function* () { - const codexAdapter = yield* CodexAdapter; - return { - getByProvider: (resolvedProvider) => - resolvedProvider === "codex" - ? Effect.succeed(codexAdapter) - : Effect.fail(new ProviderUnsupportedError({ provider: resolvedProvider })), - listProviders: () => Effect.succeed(["codex"] as const), - } as typeof ProviderAdapterRegistry.Service; + const codexSettings = Schema.decodeSync(CodexSettings)({}); + const codexAdapter = yield* makeCodexAdapter(codexSettings); + return makeAdapterRegistryMock({ + [ProviderDriverKind.make("codex")]: codexAdapter, + }); }), ).pipe( - Layer.provide(makeCodexAdapterLive()), Layer.provideMerge(ServerConfig.layerTest(workspaceDir, rootDir)), Layer.provideMerge(NodeServices.layer), Layer.provideMerge(providerSessionDirectoryLayer), ); + const providerEventLoggersLayer = Layer.succeed(ProviderEventLoggers, NoOpProviderEventLoggers); const providerLayer = useRealCodex ? makeProviderServiceLive().pipe( Layer.provide(providerSessionDirectoryLayer), Layer.provide(realCodexRegistry), Layer.provide(AnalyticsService.layerTest), + Layer.provide(providerEventLoggersLayer), ) : makeProviderServiceLive().pipe( Layer.provide(providerSessionDirectoryLayer), Layer.provide(fakeRegistry!), Layer.provide(AnalyticsService.layerTest), + Layer.provide(providerEventLoggersLayer), ); const checkpointStoreLayer = CheckpointStoreLive.pipe(Layer.provide(GitCoreLive)); diff --git a/apps/server/integration/TestProviderAdapter.integration.ts b/apps/server/integration/TestProviderAdapter.integration.ts index f497395307..9ed58c0a5b 100644 --- a/apps/server/integration/TestProviderAdapter.integration.ts +++ b/apps/server/integration/TestProviderAdapter.integration.ts @@ -10,7 +10,7 @@ import { ProviderTurnStartResult, ThreadId, TurnId, - ProviderKind, + ProviderDriverKind, } from "@t3tools/contracts"; import { Effect, Queue, Stream } from "effect"; @@ -36,7 +36,7 @@ export interface TestTurnResponse { export type FixtureProviderRuntimeEvent = { readonly type: string; readonly eventId: EventId; - readonly provider: ProviderKind; + readonly provider: ProviderDriverKind; readonly createdAt: string; readonly threadId: string; readonly turnId?: string | undefined; @@ -178,7 +178,7 @@ function normalizeFixtureEvent(rawEvent: Record): ProviderRunti export interface TestProviderAdapterHarness { readonly adapter: ProviderAdapterShape; - readonly provider: ProviderKind; + readonly provider: ProviderDriverKind; readonly queueTurnResponse: ( threadId: ThreadId, response: TestTurnResponse, @@ -198,7 +198,7 @@ export interface TestProviderAdapterHarness { } interface MakeTestProviderAdapterHarnessOptions { - readonly provider?: ProviderKind; + readonly provider?: ProviderDriverKind; } function nowIso(): string { @@ -206,7 +206,7 @@ function nowIso(): string { } function sessionNotFound( - provider: ProviderKind, + provider: ProviderDriverKind, threadId: ThreadId, ): ProviderAdapterSessionNotFoundError { return new ProviderAdapterSessionNotFoundError({ @@ -216,7 +216,7 @@ function sessionNotFound( } function missingSessionEffect( - provider: ProviderKind, + provider: ProviderDriverKind, threadId: ThreadId, ): Effect.Effect { return Effect.fail(sessionNotFound(provider, threadId)); @@ -224,7 +224,7 @@ function missingSessionEffect( export const makeTestProviderAdapterHarness = (options?: MakeTestProviderAdapterHarnessOptions) => Effect.gen(function* () { - const provider = options?.provider ?? "codex"; + const provider = options?.provider ?? ProviderDriverKind.make("codex"); const runtimeEvents = yield* Queue.unbounded(); let sessionCount = 0; const sessions = new Map(); @@ -257,6 +257,9 @@ export const makeTestProviderAdapterHarness = (options?: MakeTestProviderAdapter const session: ProviderSession = { provider, + ...(input.providerInstanceId !== undefined + ? { providerInstanceId: input.providerInstanceId } + : {}), status: "ready", runtimeMode: input.runtimeMode, threadId, diff --git a/apps/server/integration/fixtures/providerRuntime.ts b/apps/server/integration/fixtures/providerRuntime.ts index 14a45518c3..e1258c4cc6 100644 --- a/apps/server/integration/fixtures/providerRuntime.ts +++ b/apps/server/integration/fixtures/providerRuntime.ts @@ -1,7 +1,7 @@ -import { EventId, RuntimeRequestId } from "@t3tools/contracts"; +import { EventId, ProviderDriverKind, RuntimeRequestId } from "@t3tools/contracts"; import type { LegacyProviderRuntimeEvent } from "../TestProviderAdapter.integration.ts"; -const PROVIDER = "codex" as const; +const PROVIDER = ProviderDriverKind.make("codex"); const SESSION_ID = "fixture-session"; const THREAD_ID = "fixture-thread"; const TURN_ID = "fixture-turn"; diff --git a/apps/server/integration/orchestrationEngine.integration.test.ts b/apps/server/integration/orchestrationEngine.integration.test.ts index a7f845672c..6ea4d84908 100644 --- a/apps/server/integration/orchestrationEngine.integration.test.ts +++ b/apps/server/integration/orchestrationEngine.integration.test.ts @@ -4,14 +4,17 @@ import path from "node:path"; import { ApprovalRequestId, CommandId, + defaultInstanceIdForDriver, DEFAULT_PROVIDER_INTERACTION_MODE, + DEFAULT_MODEL, DEFAULT_MODEL_BY_PROVIDER, EventId, MessageId, ProjectId, - ProviderKind, + ProviderDriverKind, ThreadId, ModelSelection, + ProviderInstanceId, } from "@t3tools/contracts"; import { assert, it } from "@effect/vitest"; import { Effect, Option, Schema } from "effect"; @@ -39,7 +42,9 @@ const PROJECT_ID = asProjectId("project-1"); const THREAD_ID = ThreadId.make("thread-1"); const FIXTURE_TURN_ID = "fixture-turn"; const APPROVAL_REQUEST_ID = asApprovalRequestId("req-approval-1"); -type IntegrationProvider = ProviderKind; +type IntegrationProvider = ProviderDriverKind; +const CODEX_PROVIDER = ProviderDriverKind.make("codex"); +const CLAUDE_AGENT_PROVIDER = ProviderDriverKind.make("claudeAgent"); function nowIso() { return new Date().toISOString(); @@ -74,7 +79,11 @@ function waitForSync( }); } -function runtimeBase(eventId: string, createdAt: string, provider: IntegrationProvider = "codex") { +function runtimeBase( + eventId: string, + createdAt: string, + provider: IntegrationProvider = CODEX_PROVIDER, +) { return { eventId: asEventId(eventId), provider, @@ -84,7 +93,7 @@ function runtimeBase(eventId: string, createdAt: string, provider: IntegrationPr function withHarness( use: (harness: OrchestrationIntegrationHarness) => Effect.Effect, - provider: IntegrationProvider = "codex", + provider: IntegrationProvider = CODEX_PROVIDER, ) { return Effect.acquireUseRelease( makeOrchestrationIntegrationHarness({ provider }), @@ -97,7 +106,7 @@ function withRealCodexHarness( use: (harness: OrchestrationIntegrationHarness) => Effect.Effect, ) { return Effect.acquireUseRelease( - makeOrchestrationIntegrationHarness({ provider: "codex", realCodex: true }), + makeOrchestrationIntegrationHarness({ provider: CODEX_PROVIDER, realCodex: true }), use, (harness) => harness.dispose, ).pipe(Effect.provide(NodeServices.layer)); @@ -106,8 +115,9 @@ function withRealCodexHarness( const seedProjectAndThread = (harness: OrchestrationIntegrationHarness) => Effect.gen(function* () { const createdAt = nowIso(); - const provider = harness.adapterHarness?.provider ?? "codex"; - const defaultModel = DEFAULT_MODEL_BY_PROVIDER[provider]; + const provider = harness.adapterHarness?.provider ?? CODEX_PROVIDER; + const defaultModel = DEFAULT_MODEL_BY_PROVIDER[provider] ?? DEFAULT_MODEL; + const instanceId = defaultInstanceIdForDriver(provider); yield* harness.engine.dispatch({ type: "project.create", @@ -116,7 +126,7 @@ const seedProjectAndThread = (harness: OrchestrationIntegrationHarness) => title: "Integration Project", workspaceRoot: harness.workspaceDir, defaultModelSelection: { - provider, + instanceId, model: defaultModel, }, createdAt, @@ -129,7 +139,7 @@ const seedProjectAndThread = (harness: OrchestrationIntegrationHarness) => projectId: PROJECT_ID, title: "Integration Thread", modelSelection: { - provider, + instanceId, model: defaultModel, }, interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE, @@ -265,7 +275,7 @@ it.live.skipIf(!process.env.CODEX_BINARY_PATH)( title: "Integration Project", workspaceRoot: harness.workspaceDir, defaultModelSelection: { - provider: "codex", + instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.3-codex", }, createdAt, @@ -278,7 +288,7 @@ it.live.skipIf(!process.env.CODEX_BINARY_PATH)( projectId: PROJECT_ID, title: "Integration Thread", modelSelection: { - provider: "codex", + instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.3-codex", }, interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE, @@ -912,20 +922,32 @@ it.live("starts a claudeAgent session on first turn when provider is requested", events: [ { type: "turn.started", - ...runtimeBase("evt-claude-start-1", "2026-02-24T10:10:00.000Z", "claudeAgent"), + ...runtimeBase( + "evt-claude-start-1", + "2026-02-24T10:10:00.000Z", + CLAUDE_AGENT_PROVIDER, + ), threadId: THREAD_ID, turnId: FIXTURE_TURN_ID, }, { type: "message.delta", - ...runtimeBase("evt-claude-start-2", "2026-02-24T10:10:00.050Z", "claudeAgent"), + ...runtimeBase( + "evt-claude-start-2", + "2026-02-24T10:10:00.050Z", + CLAUDE_AGENT_PROVIDER, + ), threadId: THREAD_ID, turnId: FIXTURE_TURN_ID, delta: "Claude first turn.\n", }, { type: "turn.completed", - ...runtimeBase("evt-claude-start-3", "2026-02-24T10:10:00.100Z", "claudeAgent"), + ...runtimeBase( + "evt-claude-start-3", + "2026-02-24T10:10:00.100Z", + CLAUDE_AGENT_PROVIDER, + ), threadId: THREAD_ID, turnId: FIXTURE_TURN_ID, status: "completed", @@ -939,7 +961,7 @@ it.live("starts a claudeAgent session on first turn when provider is requested", messageId: "msg-user-claude-initial", text: "Use Claude", modelSelection: { - provider: "claudeAgent", + instanceId: ProviderInstanceId.make("claudeAgent"), model: "claude-sonnet-4-6", }, }); @@ -955,7 +977,7 @@ it.live("starts a claudeAgent session on first turn when provider is requested", ); assert.equal(thread.session?.providerName, "claudeAgent"); }), - "claudeAgent", + CLAUDE_AGENT_PROVIDER, ), ); @@ -969,20 +991,32 @@ it.live("recovers claudeAgent sessions after provider stopAll using persisted re events: [ { type: "turn.started", - ...runtimeBase("evt-claude-recover-1", "2026-02-24T10:11:00.000Z", "claudeAgent"), + ...runtimeBase( + "evt-claude-recover-1", + "2026-02-24T10:11:00.000Z", + CLAUDE_AGENT_PROVIDER, + ), threadId: THREAD_ID, turnId: FIXTURE_TURN_ID, }, { type: "message.delta", - ...runtimeBase("evt-claude-recover-2", "2026-02-24T10:11:00.050Z", "claudeAgent"), + ...runtimeBase( + "evt-claude-recover-2", + "2026-02-24T10:11:00.050Z", + CLAUDE_AGENT_PROVIDER, + ), threadId: THREAD_ID, turnId: FIXTURE_TURN_ID, delta: "Turn before restart.\n", }, { type: "turn.completed", - ...runtimeBase("evt-claude-recover-3", "2026-02-24T10:11:00.100Z", "claudeAgent"), + ...runtimeBase( + "evt-claude-recover-3", + "2026-02-24T10:11:00.100Z", + CLAUDE_AGENT_PROVIDER, + ), threadId: THREAD_ID, turnId: FIXTURE_TURN_ID, status: "completed", @@ -996,7 +1030,7 @@ it.live("recovers claudeAgent sessions after provider stopAll using persisted re messageId: "msg-user-claude-recover-1", text: "Before restart", modelSelection: { - provider: "claudeAgent", + instanceId: ProviderInstanceId.make("claudeAgent"), model: "claude-sonnet-4-6", }, }); @@ -1018,20 +1052,32 @@ it.live("recovers claudeAgent sessions after provider stopAll using persisted re events: [ { type: "turn.started", - ...runtimeBase("evt-claude-recover-4", "2026-02-24T10:11:01.000Z", "claudeAgent"), + ...runtimeBase( + "evt-claude-recover-4", + "2026-02-24T10:11:01.000Z", + CLAUDE_AGENT_PROVIDER, + ), threadId: THREAD_ID, turnId: FIXTURE_TURN_ID, }, { type: "message.delta", - ...runtimeBase("evt-claude-recover-5", "2026-02-24T10:11:01.050Z", "claudeAgent"), + ...runtimeBase( + "evt-claude-recover-5", + "2026-02-24T10:11:01.050Z", + CLAUDE_AGENT_PROVIDER, + ), threadId: THREAD_ID, turnId: FIXTURE_TURN_ID, delta: "Turn after restart.\n", }, { type: "turn.completed", - ...runtimeBase("evt-claude-recover-6", "2026-02-24T10:11:01.100Z", "claudeAgent"), + ...runtimeBase( + "evt-claude-recover-6", + "2026-02-24T10:11:01.100Z", + CLAUDE_AGENT_PROVIDER, + ), threadId: THREAD_ID, turnId: FIXTURE_TURN_ID, status: "completed", @@ -1063,7 +1109,7 @@ it.live("recovers claudeAgent sessions after provider stopAll using persisted re assert.equal(recoveredThread.session?.providerName, "claudeAgent"); assert.equal(recoveredThread.session?.threadId, "thread-1"); }), - "claudeAgent", + CLAUDE_AGENT_PROVIDER, ), ); @@ -1077,13 +1123,21 @@ it.live("forwards claudeAgent approval responses to the provider session", () => events: [ { type: "turn.started", - ...runtimeBase("evt-claude-approval-1", "2026-02-24T10:12:00.000Z", "claudeAgent"), + ...runtimeBase( + "evt-claude-approval-1", + "2026-02-24T10:12:00.000Z", + CLAUDE_AGENT_PROVIDER, + ), threadId: THREAD_ID, turnId: FIXTURE_TURN_ID, }, { type: "approval.requested", - ...runtimeBase("evt-claude-approval-2", "2026-02-24T10:12:00.050Z", "claudeAgent"), + ...runtimeBase( + "evt-claude-approval-2", + "2026-02-24T10:12:00.050Z", + CLAUDE_AGENT_PROVIDER, + ), threadId: THREAD_ID, turnId: FIXTURE_TURN_ID, requestId: APPROVAL_REQUEST_ID, @@ -1092,7 +1146,11 @@ it.live("forwards claudeAgent approval responses to the provider session", () => }, { type: "turn.completed", - ...runtimeBase("evt-claude-approval-3", "2026-02-24T10:12:00.100Z", "claudeAgent"), + ...runtimeBase( + "evt-claude-approval-3", + "2026-02-24T10:12:00.100Z", + CLAUDE_AGENT_PROVIDER, + ), threadId: THREAD_ID, turnId: FIXTURE_TURN_ID, status: "completed", @@ -1106,7 +1164,7 @@ it.live("forwards claudeAgent approval responses to the provider session", () => messageId: "msg-user-claude-approval", text: "Need approval", modelSelection: { - provider: "claudeAgent", + instanceId: ProviderInstanceId.make("claudeAgent"), model: "claude-sonnet-4-6", }, }); @@ -1137,7 +1195,7 @@ it.live("forwards claudeAgent approval responses to the provider session", () => ); assert.equal(approvalResponses[0]?.decision, "accept"); }), - "claudeAgent", + CLAUDE_AGENT_PROVIDER, ), ); @@ -1151,20 +1209,32 @@ it.live("forwards thread.turn.interrupt to claudeAgent provider sessions", () => events: [ { type: "turn.started", - ...runtimeBase("evt-claude-interrupt-1", "2026-02-24T10:13:00.000Z", "claudeAgent"), + ...runtimeBase( + "evt-claude-interrupt-1", + "2026-02-24T10:13:00.000Z", + CLAUDE_AGENT_PROVIDER, + ), threadId: THREAD_ID, turnId: FIXTURE_TURN_ID, }, { type: "message.delta", - ...runtimeBase("evt-claude-interrupt-2", "2026-02-24T10:13:00.050Z", "claudeAgent"), + ...runtimeBase( + "evt-claude-interrupt-2", + "2026-02-24T10:13:00.050Z", + CLAUDE_AGENT_PROVIDER, + ), threadId: THREAD_ID, turnId: FIXTURE_TURN_ID, delta: "Long running output.\n", }, { type: "turn.completed", - ...runtimeBase("evt-claude-interrupt-3", "2026-02-24T10:13:00.100Z", "claudeAgent"), + ...runtimeBase( + "evt-claude-interrupt-3", + "2026-02-24T10:13:00.100Z", + CLAUDE_AGENT_PROVIDER, + ), threadId: THREAD_ID, turnId: FIXTURE_TURN_ID, status: "completed", @@ -1178,7 +1248,7 @@ it.live("forwards thread.turn.interrupt to claudeAgent provider sessions", () => messageId: "msg-user-claude-interrupt", text: "Start long turn", modelSelection: { - provider: "claudeAgent", + instanceId: ProviderInstanceId.make("claudeAgent"), model: "claude-sonnet-4-6", }, }); @@ -1206,7 +1276,7 @@ it.live("forwards thread.turn.interrupt to claudeAgent provider sessions", () => ); assert.equal(interruptCalls.length, 1); }), - "claudeAgent", + CLAUDE_AGENT_PROVIDER, ), ); @@ -1220,20 +1290,32 @@ it.live("reverts claudeAgent turns and rolls back provider conversation state", events: [ { type: "turn.started", - ...runtimeBase("evt-claude-revert-1", "2026-02-24T10:14:00.000Z", "claudeAgent"), + ...runtimeBase( + "evt-claude-revert-1", + "2026-02-24T10:14:00.000Z", + CLAUDE_AGENT_PROVIDER, + ), threadId: THREAD_ID, turnId: FIXTURE_TURN_ID, }, { type: "message.delta", - ...runtimeBase("evt-claude-revert-2", "2026-02-24T10:14:00.050Z", "claudeAgent"), + ...runtimeBase( + "evt-claude-revert-2", + "2026-02-24T10:14:00.050Z", + CLAUDE_AGENT_PROVIDER, + ), threadId: THREAD_ID, turnId: FIXTURE_TURN_ID, delta: "README -> v2\n", }, { type: "turn.completed", - ...runtimeBase("evt-claude-revert-3", "2026-02-24T10:14:00.100Z", "claudeAgent"), + ...runtimeBase( + "evt-claude-revert-3", + "2026-02-24T10:14:00.100Z", + CLAUDE_AGENT_PROVIDER, + ), threadId: THREAD_ID, turnId: FIXTURE_TURN_ID, status: "completed", @@ -1251,7 +1333,7 @@ it.live("reverts claudeAgent turns and rolls back provider conversation state", messageId: "msg-user-claude-revert-1", text: "First Claude edit", modelSelection: { - provider: "claudeAgent", + instanceId: ProviderInstanceId.make("claudeAgent"), model: "claude-sonnet-4-6", }, }); @@ -1266,20 +1348,32 @@ it.live("reverts claudeAgent turns and rolls back provider conversation state", events: [ { type: "turn.started", - ...runtimeBase("evt-claude-revert-4", "2026-02-24T10:14:01.000Z", "claudeAgent"), + ...runtimeBase( + "evt-claude-revert-4", + "2026-02-24T10:14:01.000Z", + CLAUDE_AGENT_PROVIDER, + ), threadId: THREAD_ID, turnId: FIXTURE_TURN_ID, }, { type: "message.delta", - ...runtimeBase("evt-claude-revert-5", "2026-02-24T10:14:01.050Z", "claudeAgent"), + ...runtimeBase( + "evt-claude-revert-5", + "2026-02-24T10:14:01.050Z", + CLAUDE_AGENT_PROVIDER, + ), threadId: THREAD_ID, turnId: FIXTURE_TURN_ID, delta: "README -> v3\n", }, { type: "turn.completed", - ...runtimeBase("evt-claude-revert-6", "2026-02-24T10:14:01.100Z", "claudeAgent"), + ...runtimeBase( + "evt-claude-revert-6", + "2026-02-24T10:14:01.100Z", + CLAUDE_AGENT_PROVIDER, + ), threadId: THREAD_ID, turnId: FIXTURE_TURN_ID, status: "completed", @@ -1330,6 +1424,6 @@ it.live("reverts claudeAgent turns and rolls back provider conversation state", ); assert.deepEqual(harness.adapterHarness!.getRollbackCalls(THREAD_ID), [1]); }), - "claudeAgent", + CLAUDE_AGENT_PROVIDER, ), ); diff --git a/apps/server/integration/providerService.integration.test.ts b/apps/server/integration/providerService.integration.test.ts index 89cf6ac153..60fe01d4c2 100644 --- a/apps/server/integration/providerService.integration.test.ts +++ b/apps/server/integration/providerService.integration.test.ts @@ -1,13 +1,17 @@ import type { ProviderRuntimeEvent } from "@t3tools/contracts"; -import { ThreadId } from "@t3tools/contracts"; +import { ProviderDriverKind, ProviderInstanceId, ThreadId } from "@t3tools/contracts"; import { DEFAULT_SERVER_SETTINGS } from "@t3tools/contracts/settings"; import * as NodeServices from "@effect/platform-node/NodeServices"; import { it, assert } from "@effect/vitest"; import { Effect, FileSystem, Layer, Path, Queue, Stream } from "effect"; -import { ProviderUnsupportedError } from "../src/provider/Errors.ts"; import { ProviderAdapterRegistry } from "../src/provider/Services/ProviderAdapterRegistry.ts"; +import { makeAdapterRegistryMock } from "../src/provider/testUtils/providerAdapterRegistryMock.ts"; import { ProviderSessionDirectoryLive } from "../src/provider/Layers/ProviderSessionDirectory.ts"; +import { + NoOpProviderEventLoggers, + ProviderEventLoggers, +} from "../src/provider/Layers/ProviderEventLoggers.ts"; import { makeProviderServiceLive } from "../src/provider/Layers/ProviderService.ts"; import { ProviderService, @@ -29,6 +33,8 @@ import { codexTurnTextFixture, } from "./fixtures/providerRuntime.ts"; +const codexInstanceId = ProviderInstanceId.make("codex"); + const makeWorkspaceDirectory = Effect.gen(function* () { const fs = yield* FileSystem.FileSystem; const pathService = yield* Path.Path; @@ -47,13 +53,9 @@ const makeIntegrationFixture = Effect.gen(function* () { const cwd = yield* makeWorkspaceDirectory; const harness = yield* makeTestProviderAdapterHarness(); - const registry: typeof ProviderAdapterRegistry.Service = { - getByProvider: (provider) => - provider === "codex" - ? Effect.succeed(harness.adapter) - : Effect.fail(new ProviderUnsupportedError({ provider })), - listProviders: () => Effect.succeed(["codex"]), - }; + const registry = makeAdapterRegistryMock({ + [ProviderDriverKind.make("codex")]: harness.adapter, + }); const directoryLayer = ProviderSessionDirectoryLive.pipe( Layer.provide(ProviderSessionRuntimeRepositoryLive), @@ -64,6 +66,7 @@ const makeIntegrationFixture = Effect.gen(function* () { Layer.succeed(ProviderAdapterRegistry, registry), ServerSettingsService.layerTest(DEFAULT_SERVER_SETTINGS), AnalyticsService.layerTest, + Layer.succeed(ProviderEventLoggers, NoOpProviderEventLoggers), ).pipe(Layer.provide(SqlitePersistenceMemory)); const layer = makeProviderServiceLive().pipe(Layer.provide(shared)); @@ -124,7 +127,8 @@ it.live("replays typed runtime fixture events", () => const provider = yield* ProviderService; const session = yield* provider.startSession(ThreadId.make("thread-integration-typed"), { threadId: ThreadId.make("thread-integration-typed"), - provider: "codex", + provider: ProviderDriverKind.make("codex"), + providerInstanceId: codexInstanceId, cwd: fixture.cwd, runtimeMode: "full-access", }); @@ -142,6 +146,10 @@ it.live("replays typed runtime fixture events", () => observedEvents.map((event) => event.type), codexTurnTextFixture.map((event) => event.type), ); + assert.deepEqual( + observedEvents.map((event) => event.providerInstanceId), + codexTurnTextFixture.map(() => codexInstanceId), + ); }).pipe(Effect.provide(fixture.layer)); }).pipe(Effect.provide(NodeServices.layer)), ); @@ -156,7 +164,8 @@ it.live("replays file-changing fixture turn events", () => const provider = yield* ProviderService; const session = yield* provider.startSession(ThreadId.make("thread-integration-tools"), { threadId: ThreadId.make("thread-integration-tools"), - provider: "codex", + provider: ProviderDriverKind.make("codex"), + providerInstanceId: codexInstanceId, cwd: fixture.cwd, runtimeMode: "full-access", }); @@ -192,7 +201,8 @@ it.live("runs multi-turn tool/approval flow", () => const provider = yield* ProviderService; const session = yield* provider.startSession(ThreadId.make("thread-integration-multi"), { threadId: ThreadId.make("thread-integration-multi"), - provider: "codex", + provider: ProviderDriverKind.make("codex"), + providerInstanceId: codexInstanceId, cwd: fixture.cwd, runtimeMode: "full-access", }); @@ -243,7 +253,8 @@ it.live("rolls back provider conversation state only", () => const provider = yield* ProviderService; const session = yield* provider.startSession(ThreadId.make("thread-integration-rollback"), { threadId: ThreadId.make("thread-integration-rollback"), - provider: "codex", + provider: ProviderDriverKind.make("codex"), + providerInstanceId: codexInstanceId, cwd: fixture.cwd, runtimeMode: "full-access", }); diff --git a/apps/server/src/git/Layers/ClaudeTextGeneration.test.ts b/apps/server/src/git/Layers/ClaudeTextGeneration.test.ts index 773f781eed..eb7bf62ad4 100644 --- a/apps/server/src/git/Layers/ClaudeTextGeneration.test.ts +++ b/apps/server/src/git/Layers/ClaudeTextGeneration.test.ts @@ -1,24 +1,18 @@ +import { ClaudeSettings, ProviderInstanceId } from "@t3tools/contracts"; import * as NodeServices from "@effect/platform-node/NodeServices"; import { it } from "@effect/vitest"; -import { Effect, FileSystem, Layer, Path } from "effect"; +import { Effect, FileSystem, Layer, Path, Schema } from "effect"; import { createModelSelection } from "@t3tools/shared/model"; import { expect } from "vitest"; import { ServerConfig } from "../../config.ts"; -import { TextGeneration } from "../Services/TextGeneration.ts"; +import { type TextGenerationShape } from "../Services/TextGeneration.ts"; import { sanitizeThreadTitle } from "../Utils.ts"; -import { ClaudeTextGenerationLive } from "./ClaudeTextGeneration.ts"; -import { ServerSettingsService } from "../../serverSettings.ts"; +import { makeClaudeTextGeneration } from "./ClaudeTextGeneration.ts"; -const ClaudeTextGenerationTestLayer = ClaudeTextGenerationLive.pipe( - Layer.provideMerge(ServerSettingsService.layerTest()), - Layer.provideMerge( - ServerConfig.layerTest(process.cwd(), { - prefix: "t3code-claude-text-generation-test-", - }), - ), - Layer.provideMerge(NodeServices.layer), -); +const ClaudeTextGenerationTestLayer = ServerConfig.layerTest(process.cwd(), { + prefix: "t3code-claude-text-generation-test-", +}).pipe(Layer.provideMerge(NodeServices.layer)); function makeFakeClaudeBinary(dir: string) { return Effect.gen(function* () { @@ -52,6 +46,10 @@ function makeFakeClaudeBinary(dir: string) { " exit 4", " }", "fi", + 'if [ -n "$T3_FAKE_CLAUDE_HOME_MUST_BE" ] && [ "$HOME" != "$T3_FAKE_CLAUDE_HOME_MUST_BE" ]; then', + ' printf "%s\\n" "HOME was $HOME" >&2', + " exit 5", + "fi", 'if [ -n "$T3_FAKE_CLAUDE_STDERR" ]; then', ' printf "%s\\n" "$T3_FAKE_CLAUDE_STDERR" >&2', "fi", @@ -73,23 +71,26 @@ function withFakeClaudeEnv( argsMustContain?: string; argsMustNotContain?: string; stdinMustContain?: string; + homeMustBe?: string; + claudeConfig?: Partial; }, - effect: Effect.Effect, + effectFn: (textGeneration: TextGenerationShape) => Effect.Effect, ) { - return Effect.acquireUseRelease( - Effect.gen(function* () { - const fs = yield* FileSystem.FileSystem; - const tempDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3code-claude-text-" }); - const binDir = yield* makeFakeClaudeBinary(tempDir); - const previousPath = process.env.PATH; - const previousOutput = process.env.T3_FAKE_CLAUDE_OUTPUT; - const previousExitCode = process.env.T3_FAKE_CLAUDE_EXIT_CODE; - const previousStderr = process.env.T3_FAKE_CLAUDE_STDERR; - const previousArgsMustContain = process.env.T3_FAKE_CLAUDE_ARGS_MUST_CONTAIN; - const previousArgsMustNotContain = process.env.T3_FAKE_CLAUDE_ARGS_MUST_NOT_CONTAIN; - const previousStdinMustContain = process.env.T3_FAKE_CLAUDE_STDIN_MUST_CONTAIN; + return Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const tempDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3code-claude-text-" }); + const binDir = yield* makeFakeClaudeBinary(tempDir); + const previousPath = process.env.PATH; + const previousOutput = process.env.T3_FAKE_CLAUDE_OUTPUT; + const previousExitCode = process.env.T3_FAKE_CLAUDE_EXIT_CODE; + const previousStderr = process.env.T3_FAKE_CLAUDE_STDERR; + const previousArgsMustContain = process.env.T3_FAKE_CLAUDE_ARGS_MUST_CONTAIN; + const previousArgsMustNotContain = process.env.T3_FAKE_CLAUDE_ARGS_MUST_NOT_CONTAIN; + const previousStdinMustContain = process.env.T3_FAKE_CLAUDE_STDIN_MUST_CONTAIN; + const previousHomeMustBe = process.env.T3_FAKE_CLAUDE_HOME_MUST_BE; - yield* Effect.sync(() => { + yield* Effect.acquireRelease( + Effect.sync(() => { process.env.PATH = `${binDir}:${previousPath ?? ""}`; process.env.T3_FAKE_CLAUDE_OUTPUT = input.output; @@ -122,60 +123,65 @@ function withFakeClaudeEnv( } else { delete process.env.T3_FAKE_CLAUDE_STDIN_MUST_CONTAIN; } - }); - return { - previousPath, - previousOutput, - previousExitCode, - previousStderr, - previousArgsMustContain, - previousArgsMustNotContain, - previousStdinMustContain, - }; - }), - () => effect, - (previous) => - Effect.sync(() => { - process.env.PATH = previous.previousPath; - - if (previous.previousOutput === undefined) { - delete process.env.T3_FAKE_CLAUDE_OUTPUT; + if (input.homeMustBe !== undefined) { + process.env.T3_FAKE_CLAUDE_HOME_MUST_BE = input.homeMustBe; } else { - process.env.T3_FAKE_CLAUDE_OUTPUT = previous.previousOutput; - } - - if (previous.previousExitCode === undefined) { - delete process.env.T3_FAKE_CLAUDE_EXIT_CODE; - } else { - process.env.T3_FAKE_CLAUDE_EXIT_CODE = previous.previousExitCode; - } - - if (previous.previousStderr === undefined) { - delete process.env.T3_FAKE_CLAUDE_STDERR; - } else { - process.env.T3_FAKE_CLAUDE_STDERR = previous.previousStderr; - } - - if (previous.previousArgsMustContain === undefined) { - delete process.env.T3_FAKE_CLAUDE_ARGS_MUST_CONTAIN; - } else { - process.env.T3_FAKE_CLAUDE_ARGS_MUST_CONTAIN = previous.previousArgsMustContain; - } - - if (previous.previousArgsMustNotContain === undefined) { - delete process.env.T3_FAKE_CLAUDE_ARGS_MUST_NOT_CONTAIN; - } else { - process.env.T3_FAKE_CLAUDE_ARGS_MUST_NOT_CONTAIN = previous.previousArgsMustNotContain; - } - - if (previous.previousStdinMustContain === undefined) { - delete process.env.T3_FAKE_CLAUDE_STDIN_MUST_CONTAIN; - } else { - process.env.T3_FAKE_CLAUDE_STDIN_MUST_CONTAIN = previous.previousStdinMustContain; + delete process.env.T3_FAKE_CLAUDE_HOME_MUST_BE; } }), - ); + () => + Effect.sync(() => { + process.env.PATH = previousPath; + + if (previousOutput === undefined) { + delete process.env.T3_FAKE_CLAUDE_OUTPUT; + } else { + process.env.T3_FAKE_CLAUDE_OUTPUT = previousOutput; + } + + if (previousExitCode === undefined) { + delete process.env.T3_FAKE_CLAUDE_EXIT_CODE; + } else { + process.env.T3_FAKE_CLAUDE_EXIT_CODE = previousExitCode; + } + + if (previousStderr === undefined) { + delete process.env.T3_FAKE_CLAUDE_STDERR; + } else { + process.env.T3_FAKE_CLAUDE_STDERR = previousStderr; + } + + if (previousArgsMustContain === undefined) { + delete process.env.T3_FAKE_CLAUDE_ARGS_MUST_CONTAIN; + } else { + process.env.T3_FAKE_CLAUDE_ARGS_MUST_CONTAIN = previousArgsMustContain; + } + + if (previousArgsMustNotContain === undefined) { + delete process.env.T3_FAKE_CLAUDE_ARGS_MUST_NOT_CONTAIN; + } else { + process.env.T3_FAKE_CLAUDE_ARGS_MUST_NOT_CONTAIN = previousArgsMustNotContain; + } + + if (previousStdinMustContain === undefined) { + delete process.env.T3_FAKE_CLAUDE_STDIN_MUST_CONTAIN; + } else { + process.env.T3_FAKE_CLAUDE_STDIN_MUST_CONTAIN = previousStdinMustContain; + } + + if (previousHomeMustBe === undefined) { + delete process.env.T3_FAKE_CLAUDE_HOME_MUST_BE; + } else { + process.env.T3_FAKE_CLAUDE_HOME_MUST_BE = previousHomeMustBe; + } + }), + ); + + const config = Schema.decodeSync(ClaudeSettings)(input.claudeConfig ?? {}); + const textGeneration = yield* makeClaudeTextGeneration(config); + return yield* effectFn(textGeneration); + }).pipe(Effect.scoped); } it.layer(ClaudeTextGenerationTestLayer)("ClaudeTextGenerationLive", (it) => { @@ -191,24 +197,23 @@ it.layer(ClaudeTextGenerationTestLayer)("ClaudeTextGenerationLive", (it) => { argsMustContain: '--settings {"alwaysThinkingEnabled":false}', argsMustNotContain: "--effort", }, - Effect.gen(function* () { - const textGeneration = yield* TextGeneration; + (textGeneration) => + Effect.gen(function* () { + const generated = yield* textGeneration.generateCommitMessage({ + cwd: process.cwd(), + branch: "feature/claude-effect", + stagedSummary: "M README.md", + stagedPatch: "diff --git a/README.md b/README.md", + modelSelection: { + ...createModelSelection(ProviderInstanceId.make("claudeAgent"), "claude-haiku-4-5", [ + { id: "thinking", value: false }, + { id: "effort", value: "high" }, + ]), + }, + }); - const generated = yield* textGeneration.generateCommitMessage({ - cwd: process.cwd(), - branch: "feature/claude-effect", - stagedSummary: "M README.md", - stagedPatch: "diff --git a/README.md b/README.md", - modelSelection: { - ...createModelSelection("claudeAgent", "claude-haiku-4-5", [ - { id: "thinking", value: false }, - { id: "effort", value: "high" }, - ]), - }, - }); - - expect(generated.subject).toBe("Add important change"); - }), + expect(generated.subject).toBe("Add important change"); + }), ), ); @@ -223,26 +228,25 @@ it.layer(ClaudeTextGenerationTestLayer)("ClaudeTextGenerationLive", (it) => { }), argsMustContain: '--effort max --settings {"fastMode":true}', }, - Effect.gen(function* () { - const textGeneration = yield* TextGeneration; + (textGeneration) => + Effect.gen(function* () { + const generated = yield* textGeneration.generatePrContent({ + cwd: process.cwd(), + baseBranch: "main", + headBranch: "feature/claude-effect", + commitSummary: "Improve orchestration", + diffSummary: "1 file changed", + diffPatch: "diff --git a/README.md b/README.md", + modelSelection: { + ...createModelSelection(ProviderInstanceId.make("claudeAgent"), "claude-opus-4-6", [ + { id: "effort", value: "max" }, + { id: "fastMode", value: true }, + ]), + }, + }); - const generated = yield* textGeneration.generatePrContent({ - cwd: process.cwd(), - baseBranch: "main", - headBranch: "feature/claude-effect", - commitSummary: "Improve orchestration", - diffSummary: "1 file changed", - diffPatch: "diff --git a/README.md b/README.md", - modelSelection: { - ...createModelSelection("claudeAgent", "claude-opus-4-6", [ - { id: "effort", value: "max" }, - { id: "fastMode", value: true }, - ]), - }, - }); - - expect(generated.title).toBe("Improve orchestration flow"); - }), + expect(generated.title).toBe("Improve orchestration flow"); + }), ), ); @@ -257,27 +261,57 @@ it.layer(ClaudeTextGenerationTestLayer)("ClaudeTextGenerationLive", (it) => { }), stdinMustContain: "You write concise thread titles for coding conversations.", }, - Effect.gen(function* () { - const textGeneration = yield* TextGeneration; + (textGeneration) => + Effect.gen(function* () { + const generated = yield* textGeneration.generateThreadTitle({ + cwd: process.cwd(), + message: "Please investigate reconnect failures after restarting the session.", + modelSelection: { + instanceId: ProviderInstanceId.make("claudeAgent"), + model: "claude-sonnet-4-6", + }, + }); - const generated = yield* textGeneration.generateThreadTitle({ - cwd: process.cwd(), - message: "Please investigate reconnect failures after restarting the session.", - modelSelection: { - provider: "claudeAgent", - model: "claude-sonnet-4-6", - }, - }); - - expect(generated.title).toBe( - sanitizeThreadTitle( - '"Reconnect failures after restart because the session state does not recover"', - ), - ); - }), + expect(generated.title).toBe( + sanitizeThreadTitle( + '"Reconnect failures after restart because the session state does not recover"', + ), + ); + }), ), ); + it.effect("runs Claude text generation with the configured Claude HOME", () => + Effect.gen(function* () { + const path = yield* Path.Path; + const claudeHome = path.join(process.cwd(), ".claude-work-test"); + return yield* withFakeClaudeEnv( + { + output: JSON.stringify({ + structured_output: { + title: "Use Claude home", + }, + }), + homeMustBe: claudeHome, + claudeConfig: { homePath: claudeHome }, + }, + (textGeneration) => + Effect.gen(function* () { + const generated = yield* textGeneration.generateThreadTitle({ + cwd: process.cwd(), + message: "thread title", + modelSelection: { + instanceId: ProviderInstanceId.make("claudeAgent"), + model: "claude-sonnet-4-6", + }, + }); + + expect(generated.title).toBe(sanitizeThreadTitle("Use Claude home")); + }), + ); + }), + ); + it.effect("falls back when Claude thread title normalization becomes whitespace-only", () => withFakeClaudeEnv( { @@ -287,20 +321,19 @@ it.layer(ClaudeTextGenerationTestLayer)("ClaudeTextGenerationLive", (it) => { }, }), }, - Effect.gen(function* () { - const textGeneration = yield* TextGeneration; + (textGeneration) => + Effect.gen(function* () { + const generated = yield* textGeneration.generateThreadTitle({ + cwd: process.cwd(), + message: "Name this thread.", + modelSelection: { + instanceId: ProviderInstanceId.make("claudeAgent"), + model: "claude-sonnet-4-6", + }, + }); - const generated = yield* textGeneration.generateThreadTitle({ - cwd: process.cwd(), - message: "Name this thread.", - modelSelection: { - provider: "claudeAgent", - model: "claude-sonnet-4-6", - }, - }); - - expect(generated.title).toBe("New thread"); - }), + expect(generated.title).toBe("New thread"); + }), ), ); }); diff --git a/apps/server/src/git/Layers/ClaudeTextGeneration.ts b/apps/server/src/git/Layers/ClaudeTextGeneration.ts index 8175dc54b2..33bf7bc014 100644 --- a/apps/server/src/git/Layers/ClaudeTextGeneration.ts +++ b/apps/server/src/git/Layers/ClaudeTextGeneration.ts @@ -7,14 +7,14 @@ * * @module ClaudeTextGeneration */ -import { Effect, Layer, Option, Schema, Stream } from "effect"; +import { Effect, Option, Schema, Stream } from "effect"; import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process"; -import { ClaudeModelSelection } from "@t3tools/contracts"; +import { type ClaudeSettings, type ModelSelection } from "@t3tools/contracts"; import { sanitizeBranchFragment, sanitizeFeatureBranchName } from "@t3tools/shared/git"; import { TextGenerationError } from "@t3tools/contracts"; -import { type TextGenerationShape, TextGeneration } from "../Services/TextGeneration.ts"; +import { type TextGenerationShape } from "../Services/TextGeneration.ts"; import { buildBranchNamePrompt, buildCommitMessagePrompt, @@ -38,7 +38,7 @@ import { resolveClaudeApiModelId, resolveClaudeEffort, } from "../../provider/Layers/ClaudeProvider.ts"; -import { ServerSettingsService } from "../../serverSettings.ts"; +import { makeClaudeEnvironment } from "../../provider/Drivers/ClaudeHome.ts"; const CLAUDE_TIMEOUT_MS = 180_000; @@ -50,9 +50,12 @@ const ClaudeOutputEnvelope = Schema.Struct({ structured_output: Schema.Unknown, }); -const makeClaudeTextGeneration = Effect.gen(function* () { +export const makeClaudeTextGeneration = Effect.fn("makeClaudeTextGeneration")(function* ( + claudeSettings: ClaudeSettings, + environment: NodeJS.ProcessEnv = process.env, +) { const commandSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; - const serverSettingsService = yield* Effect.service(ServerSettingsService); + const claudeEnvironment = yield* makeClaudeEnvironment(claudeSettings, environment); const readStreamAsString = ( operation: string, @@ -88,7 +91,7 @@ const makeClaudeTextGeneration = Effect.gen(function* () { cwd: string; prompt: string; outputSchemaJson: S; - modelSelection: ClaudeModelSelection; + modelSelection: ModelSelection; }): Effect.fn.Return { const jsonSchemaStr = JSON.stringify(toJsonSchemaObject(outputSchemaJson)); const caps = getClaudeModelCapabilities(modelSelection.model); @@ -111,14 +114,9 @@ const makeClaudeTextGeneration = Effect.gen(function* () { ...(fastMode ? { fastMode: true } : {}), }; - const claudeSettings = yield* Effect.map( - serverSettingsService.getSettings, - (settings) => settings.providers.claudeAgent, - ).pipe(Effect.catch(() => Effect.undefined)); - const runClaudeCommand = Effect.fn("runClaudeJson.runClaudeCommand")(function* () { const command = ChildProcess.make( - claudeSettings?.binaryPath || "claude", + claudeSettings.binaryPath || "claude", [ "-p", "--output-format", @@ -132,6 +130,7 @@ const makeClaudeTextGeneration = Effect.gen(function* () { "--dangerously-skip-permissions", ], { + env: claudeEnvironment, cwd, shell: process.platform === "win32", stdin: { @@ -232,13 +231,6 @@ const makeClaudeTextGeneration = Effect.gen(function* () { includeBranch: input.includeBranch === true, }); - if (input.modelSelection.provider !== "claudeAgent") { - return yield* new TextGenerationError({ - operation: "generateCommitMessage", - detail: "Invalid model selection.", - }); - } - const generated = yield* runClaudeJson({ operation: "generateCommitMessage", cwd: input.cwd, @@ -267,13 +259,6 @@ const makeClaudeTextGeneration = Effect.gen(function* () { diffPatch: input.diffPatch, }); - if (input.modelSelection.provider !== "claudeAgent") { - return yield* new TextGenerationError({ - operation: "generatePrContent", - detail: "Invalid model selection.", - }); - } - const generated = yield* runClaudeJson({ operation: "generatePrContent", cwd: input.cwd, @@ -296,13 +281,6 @@ const makeClaudeTextGeneration = Effect.gen(function* () { attachments: input.attachments, }); - if (input.modelSelection.provider !== "claudeAgent") { - return yield* new TextGenerationError({ - operation: "generateBranchName", - detail: "Invalid model selection.", - }); - } - const generated = yield* runClaudeJson({ operation: "generateBranchName", cwd: input.cwd, @@ -324,13 +302,6 @@ const makeClaudeTextGeneration = Effect.gen(function* () { attachments: input.attachments, }); - if (input.modelSelection.provider !== "claudeAgent") { - return yield* new TextGenerationError({ - operation: "generateThreadTitle", - detail: "Invalid model selection.", - }); - } - const generated = yield* runClaudeJson({ operation: "generateThreadTitle", cwd: input.cwd, @@ -351,5 +322,3 @@ const makeClaudeTextGeneration = Effect.gen(function* () { generateThreadTitle, } satisfies TextGenerationShape; }); - -export const ClaudeTextGenerationLive = Layer.effect(TextGeneration, makeClaudeTextGeneration); diff --git a/apps/server/src/git/Layers/CodexTextGeneration.test.ts b/apps/server/src/git/Layers/CodexTextGeneration.test.ts index 2adfcca848..f38d6a68a8 100644 --- a/apps/server/src/git/Layers/CodexTextGeneration.test.ts +++ b/apps/server/src/git/Layers/CodexTextGeneration.test.ts @@ -1,30 +1,24 @@ import * as NodeServices from "@effect/platform-node/NodeServices"; import { it } from "@effect/vitest"; -import { Effect, FileSystem, Layer, Path, Result } from "effect"; +import { Effect, FileSystem, Layer, Path, Result, Schema } from "effect"; import { createModelSelection } from "@t3tools/shared/model"; import { expect } from "vitest"; +import { CodexSettings, ProviderInstanceId, TextGenerationError } from "@t3tools/contracts"; + import { ServerConfig } from "../../config.ts"; -import { CodexTextGenerationLive } from "./CodexTextGeneration.ts"; -import { TextGenerationError } from "@t3tools/contracts"; -import { TextGeneration } from "../Services/TextGeneration.ts"; -import { ServerSettingsService } from "../../serverSettings.ts"; +import { type TextGenerationShape } from "../Services/TextGeneration.ts"; +import { makeCodexTextGeneration } from "./CodexTextGeneration.ts"; -const DEFAULT_TEST_MODEL_SELECTION = { - provider: "codex" as const, - model: "gpt-5.4-mini", -}; - -const CodexTextGenerationTestLayer = CodexTextGenerationLive.pipe( - Layer.provideMerge(ServerSettingsService.layerTest()), - Layer.provideMerge( - ServerConfig.layerTest(process.cwd(), { - prefix: "t3code-codex-text-generation-test-", - }), - ), - Layer.provideMerge(NodeServices.layer), +const DEFAULT_TEST_MODEL_SELECTION = createModelSelection( + ProviderInstanceId.make("codex"), + "gpt-5.4-mini", ); +const CodexTextGenerationTestLayer = ServerConfig.layerTest(process.cwd(), { + prefix: "t3code-codex-text-generation-test-", +}).pipe(Layer.provideMerge(NodeServices.layer)); + function makeFakeCodexBinary( dir: string, input: { @@ -162,36 +156,16 @@ function withFakeCodexEnv( stdinMustContain?: string; stdinMustNotContain?: string; }, - effect: Effect.Effect, + effectFn: (textGeneration: TextGenerationShape) => Effect.Effect, ) { - return Effect.acquireUseRelease( - Effect.gen(function* () { - const fs = yield* FileSystem.FileSystem; - const tempDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3code-codex-text-" }); - const codexPath = yield* makeFakeCodexBinary(tempDir, input); - const serverSettings = yield* ServerSettingsService; - const previousSettings = yield* serverSettings.getSettings; - yield* serverSettings.updateSettings({ - providers: { - codex: { - binaryPath: codexPath, - }, - }, - }); - return { serverSettings, previousBinaryPath: previousSettings.providers.codex.binaryPath }; - }), - () => effect, - ({ serverSettings, previousBinaryPath }) => - serverSettings - .updateSettings({ - providers: { - codex: { - binaryPath: previousBinaryPath, - }, - }, - }) - .pipe(Effect.asVoid), - ); + return Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const tempDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3code-codex-text-" }); + const codexPath = yield* makeFakeCodexBinary(tempDir, input); + const config = Schema.decodeSync(CodexSettings)({ binaryPath: codexPath }); + const textGeneration = yield* makeCodexTextGeneration(config); + return yield* effectFn(textGeneration); + }).pipe(Effect.scoped); } it.layer(CodexTextGenerationTestLayer)("CodexTextGenerationLive", (it) => { @@ -205,22 +179,21 @@ it.layer(CodexTextGenerationTestLayer)("CodexTextGenerationLive", (it) => { }), stdinMustNotContain: "branch must be a short semantic git branch fragment", }, - Effect.gen(function* () { - const textGeneration = yield* TextGeneration; + (textGeneration) => + Effect.gen(function* () { + const generated = yield* textGeneration.generateCommitMessage({ + cwd: process.cwd(), + branch: "feature/codex-effect", + stagedSummary: "M README.md", + stagedPatch: "diff --git a/README.md b/README.md", + modelSelection: DEFAULT_TEST_MODEL_SELECTION, + }); - const generated = yield* textGeneration.generateCommitMessage({ - cwd: process.cwd(), - branch: "feature/codex-effect", - stagedSummary: "M README.md", - stagedPatch: "diff --git a/README.md b/README.md", - modelSelection: DEFAULT_TEST_MODEL_SELECTION, - }); - - expect(generated.subject.length).toBeLessThanOrEqual(72); - expect(generated.subject.endsWith(".")).toBe(false); - expect(generated.body).toBe("- added migration\n- updated tests"); - expect(generated.branch).toBeUndefined(); - }), + expect(generated.subject.length).toBeLessThanOrEqual(72); + expect(generated.subject.endsWith(".")).toBe(false); + expect(generated.body).toBe("- added migration\n- updated tests"); + expect(generated.branch).toBeUndefined(); + }), ), ); @@ -237,20 +210,17 @@ it.layer(CodexTextGenerationTestLayer)("CodexTextGenerationLive", (it) => { requireReasoningEffort: "xhigh", stdinMustNotContain: "branch must be a short semantic git branch fragment", }, - Effect.gen(function* () { - const textGeneration = yield* TextGeneration; - - yield* textGeneration.generateCommitMessage({ + (textGeneration) => + textGeneration.generateCommitMessage({ cwd: process.cwd(), branch: "feature/codex-effect", stagedSummary: "M README.md", stagedPatch: "diff --git a/README.md b/README.md", - modelSelection: createModelSelection("codex", "gpt-5.4", [ + modelSelection: createModelSelection(ProviderInstanceId.make("codex"), "gpt-5.4", [ { id: "reasoningEffort", value: "xhigh" }, { id: "fastMode", value: true }, ]), - }); - }), + }), ), ); @@ -263,17 +233,14 @@ it.layer(CodexTextGenerationTestLayer)("CodexTextGenerationLive", (it) => { }), requireReasoningEffort: "low", }, - Effect.gen(function* () { - const textGeneration = yield* TextGeneration; - - yield* textGeneration.generateCommitMessage({ + (textGeneration) => + textGeneration.generateCommitMessage({ cwd: process.cwd(), branch: "feature/codex-effect", stagedSummary: "M README.md", stagedPatch: "diff --git a/README.md b/README.md", modelSelection: DEFAULT_TEST_MODEL_SELECTION, - }); - }), + }), ), ); @@ -287,21 +254,20 @@ it.layer(CodexTextGenerationTestLayer)("CodexTextGenerationLive", (it) => { }), stdinMustContain: "branch must be a short semantic git branch fragment", }, - Effect.gen(function* () { - const textGeneration = yield* TextGeneration; + (textGeneration) => + Effect.gen(function* () { + const generated = yield* textGeneration.generateCommitMessage({ + cwd: process.cwd(), + branch: "feature/codex-effect", + stagedSummary: "M README.md", + stagedPatch: "diff --git a/README.md b/README.md", + includeBranch: true, + modelSelection: DEFAULT_TEST_MODEL_SELECTION, + }); - const generated = yield* textGeneration.generateCommitMessage({ - cwd: process.cwd(), - branch: "feature/codex-effect", - stagedSummary: "M README.md", - stagedPatch: "diff --git a/README.md b/README.md", - includeBranch: true, - modelSelection: DEFAULT_TEST_MODEL_SELECTION, - }); - - expect(generated.subject).toBe("Add important change"); - expect(generated.branch).toBe("feature/fix/important-system-change"); - }), + expect(generated.subject).toBe("Add important change"); + expect(generated.branch).toBe("feature/fix/important-system-change"); + }), ), ); @@ -313,23 +279,22 @@ it.layer(CodexTextGenerationTestLayer)("CodexTextGenerationLive", (it) => { body: "\n## Summary\n- improve flow\n\n## Testing\n- bun test\n\n", }), }, - Effect.gen(function* () { - const textGeneration = yield* TextGeneration; + (textGeneration) => + Effect.gen(function* () { + const generated = yield* textGeneration.generatePrContent({ + cwd: process.cwd(), + baseBranch: "main", + headBranch: "feature/codex-effect", + commitSummary: "feat: improve orchestration flow", + diffSummary: "2 files changed", + diffPatch: "diff --git a/a.ts b/a.ts", + modelSelection: DEFAULT_TEST_MODEL_SELECTION, + }); - const generated = yield* textGeneration.generatePrContent({ - cwd: process.cwd(), - baseBranch: "main", - headBranch: "feature/codex-effect", - commitSummary: "feat: improve orchestration flow", - diffSummary: "2 files changed", - diffPatch: "diff --git a/a.ts b/a.ts", - modelSelection: DEFAULT_TEST_MODEL_SELECTION, - }); - - expect(generated.title).toBe("Improve orchestration flow"); - expect(generated.body.startsWith("## Summary")).toBe(true); - expect(generated.body.endsWith("\n\n")).toBe(false); - }), + expect(generated.title).toBe("Improve orchestration flow"); + expect(generated.body.startsWith("## Summary")).toBe(true); + expect(generated.body.endsWith("\n\n")).toBe(false); + }), ), ); @@ -341,17 +306,16 @@ it.layer(CodexTextGenerationTestLayer)("CodexTextGenerationLive", (it) => { }), stdinMustNotContain: "Image attachments supplied to the model", }, - Effect.gen(function* () { - const textGeneration = yield* TextGeneration; + (textGeneration) => + Effect.gen(function* () { + const generated = yield* textGeneration.generateBranchName({ + cwd: process.cwd(), + message: "Please update session handling.", + modelSelection: DEFAULT_TEST_MODEL_SELECTION, + }); - const generated = yield* textGeneration.generateBranchName({ - cwd: process.cwd(), - message: "Please update session handling.", - modelSelection: DEFAULT_TEST_MODEL_SELECTION, - }); - - expect(generated.branch).toBe("feat/session"); - }), + expect(generated.branch).toBe("feat/session"); + }), ), ); @@ -363,17 +327,16 @@ it.layer(CodexTextGenerationTestLayer)("CodexTextGenerationLive", (it) => { ' "Investigate websocket reconnect regressions after worktree restore" \nignored line', }), }, - Effect.gen(function* () { - const textGeneration = yield* TextGeneration; + (textGeneration) => + Effect.gen(function* () { + const generated = yield* textGeneration.generateThreadTitle({ + cwd: process.cwd(), + message: "Please investigate websocket reconnect regressions after a worktree restore.", + modelSelection: DEFAULT_TEST_MODEL_SELECTION, + }); - const generated = yield* textGeneration.generateThreadTitle({ - cwd: process.cwd(), - message: "Please investigate websocket reconnect regressions after a worktree restore.", - modelSelection: DEFAULT_TEST_MODEL_SELECTION, - }); - - expect(generated.title).toBe("Investigate websocket reconnect regressions aft..."); - }), + expect(generated.title).toBe("Investigate websocket reconnect regressions aft..."); + }), ), ); @@ -384,17 +347,16 @@ it.layer(CodexTextGenerationTestLayer)("CodexTextGenerationLive", (it) => { title: ' """ """ ', }), }, - Effect.gen(function* () { - const textGeneration = yield* TextGeneration; + (textGeneration) => + Effect.gen(function* () { + const generated = yield* textGeneration.generateThreadTitle({ + cwd: process.cwd(), + message: "Name this thread.", + modelSelection: DEFAULT_TEST_MODEL_SELECTION, + }); - const generated = yield* textGeneration.generateThreadTitle({ - cwd: process.cwd(), - message: "Name this thread.", - modelSelection: DEFAULT_TEST_MODEL_SELECTION, - }); - - expect(generated.title).toBe("New thread"); - }), + expect(generated.title).toBe("New thread"); + }), ), ); @@ -405,17 +367,16 @@ it.layer(CodexTextGenerationTestLayer)("CodexTextGenerationLive", (it) => { title: ` "' hello world '" `, }), }, - Effect.gen(function* () { - const textGeneration = yield* TextGeneration; + (textGeneration) => + Effect.gen(function* () { + const generated = yield* textGeneration.generateThreadTitle({ + cwd: process.cwd(), + message: "Name this thread.", + modelSelection: DEFAULT_TEST_MODEL_SELECTION, + }); - const generated = yield* textGeneration.generateThreadTitle({ - cwd: process.cwd(), - message: "Name this thread.", - modelSelection: DEFAULT_TEST_MODEL_SELECTION, - }); - - expect(generated.title).toBe("hello world"); - }), + expect(generated.title).toBe("hello world"); + }), ), ); @@ -427,17 +388,16 @@ it.layer(CodexTextGenerationTestLayer)("CodexTextGenerationLive", (it) => { }), stdinMustNotContain: "Attachment metadata:", }, - Effect.gen(function* () { - const textGeneration = yield* TextGeneration; + (textGeneration) => + Effect.gen(function* () { + const generated = yield* textGeneration.generateBranchName({ + cwd: process.cwd(), + message: "Fix timeout behavior.", + modelSelection: DEFAULT_TEST_MODEL_SELECTION, + }); - const generated = yield* textGeneration.generateBranchName({ - cwd: process.cwd(), - message: "Fix timeout behavior.", - modelSelection: DEFAULT_TEST_MODEL_SELECTION, - }); - - expect(generated.branch).toBe("fix/session-timeout"); - }), + expect(generated.branch).toBe("fix/session-timeout"); + }), ), ); @@ -450,56 +410,17 @@ it.layer(CodexTextGenerationTestLayer)("CodexTextGenerationLive", (it) => { requireImage: true, stdinMustContain: "Attachment metadata:", }, - Effect.gen(function* () { - const fs = yield* FileSystem.FileSystem; - const path = yield* Path.Path; - const { attachmentsDir } = yield* ServerConfig; - const attachmentId = `thread-branch-image-${Date.now()}-${Math.random().toString(36).slice(2, 10)}`; - const attachmentPath = path.join(attachmentsDir, `${attachmentId}.png`); - yield* fs.makeDirectory(attachmentsDir, { recursive: true }); - yield* fs.writeFile(attachmentPath, Buffer.from("hello")); + (textGeneration) => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const { attachmentsDir } = yield* ServerConfig; + const attachmentId = `thread-branch-image-${Date.now()}-${Math.random().toString(36).slice(2, 10)}`; + const attachmentPath = path.join(attachmentsDir, `${attachmentId}.png`); + yield* fs.makeDirectory(attachmentsDir, { recursive: true }); + yield* fs.writeFile(attachmentPath, Buffer.from("hello")); - const textGeneration = yield* TextGeneration; - const generated = yield* textGeneration.generateBranchName({ - modelSelection: DEFAULT_TEST_MODEL_SELECTION, - cwd: process.cwd(), - message: "Fix layout bug from screenshot.", - attachments: [ - { - type: "image", - id: attachmentId, - name: "bug.png", - mimeType: "image/png", - sizeBytes: 5, - }, - ], - }); - - expect(generated.branch).toBe("fix/ui-regression"); - }), - ), - ); - - it.effect("resolves persisted attachment ids to files for codex image inputs", () => - withFakeCodexEnv( - { - output: JSON.stringify({ - branch: "fix/ui-regression", - }), - requireImage: true, - }, - Effect.gen(function* () { - const fs = yield* FileSystem.FileSystem; - const path = yield* Path.Path; - const { attachmentsDir } = yield* ServerConfig; - const attachmentId = `thread-1-${Date.now()}-${Math.random().toString(36).slice(2, 10)}`; - const imagePath = path.join(attachmentsDir, `${attachmentId}.png`); - yield* fs.makeDirectory(attachmentsDir, { recursive: true }); - yield* fs.writeFile(imagePath, Buffer.from("hello")); - - const textGeneration = yield* TextGeneration; - const generated = yield* textGeneration - .generateBranchName({ + const generated = yield* textGeneration.generateBranchName({ modelSelection: DEFAULT_TEST_MODEL_SELECTION, cwd: process.cwd(), message: "Fix layout bug from screenshot.", @@ -512,20 +433,59 @@ it.layer(CodexTextGenerationTestLayer)("CodexTextGenerationLive", (it) => { sizeBytes: 5, }, ], - }) - .pipe( - Effect.tap(() => - fs.stat(imagePath).pipe( - Effect.map((fileInfo) => { - expect(fileInfo.type).toBe("File"); - }), - ), - ), - Effect.ensuring(fs.remove(imagePath).pipe(Effect.catch(() => Effect.void))), - ); + }); - expect(generated.branch).toBe("fix/ui-regression"); - }), + expect(generated.branch).toBe("fix/ui-regression"); + }), + ), + ); + + it.effect("resolves persisted attachment ids to files for codex image inputs", () => + withFakeCodexEnv( + { + output: JSON.stringify({ + branch: "fix/ui-regression", + }), + requireImage: true, + }, + (textGeneration) => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const { attachmentsDir } = yield* ServerConfig; + const attachmentId = `thread-1-${Date.now()}-${Math.random().toString(36).slice(2, 10)}`; + const imagePath = path.join(attachmentsDir, `${attachmentId}.png`); + yield* fs.makeDirectory(attachmentsDir, { recursive: true }); + yield* fs.writeFile(imagePath, Buffer.from("hello")); + + const generated = yield* textGeneration + .generateBranchName({ + modelSelection: DEFAULT_TEST_MODEL_SELECTION, + cwd: process.cwd(), + message: "Fix layout bug from screenshot.", + attachments: [ + { + type: "image", + id: attachmentId, + name: "bug.png", + mimeType: "image/png", + sizeBytes: 5, + }, + ], + }) + .pipe( + Effect.tap(() => + fs.stat(imagePath).pipe( + Effect.map((fileInfo) => { + expect(fileInfo.type).toBe("File"); + }), + ), + ), + Effect.ensuring(fs.remove(imagePath).pipe(Effect.catch(() => Effect.void))), + ); + + expect(generated.branch).toBe("fix/ui-regression"); + }), ), ); @@ -537,38 +497,38 @@ it.layer(CodexTextGenerationTestLayer)("CodexTextGenerationLive", (it) => { }), requireImage: true, }, - Effect.gen(function* () { - const fs = yield* FileSystem.FileSystem; - const path = yield* Path.Path; - const { attachmentsDir } = yield* ServerConfig; - const missingAttachmentId = `thread-missing-${Date.now()}-${Math.random().toString(36).slice(2, 10)}`; - const missingPath = path.join(attachmentsDir, `${missingAttachmentId}.png`); - yield* fs.remove(missingPath).pipe(Effect.catch(() => Effect.void)); + (textGeneration) => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const { attachmentsDir } = yield* ServerConfig; + const missingAttachmentId = `thread-missing-${Date.now()}-${Math.random().toString(36).slice(2, 10)}`; + const missingPath = path.join(attachmentsDir, `${missingAttachmentId}.png`); + yield* fs.remove(missingPath).pipe(Effect.catch(() => Effect.void)); - const textGeneration = yield* TextGeneration; - const result = yield* textGeneration - .generateBranchName({ - modelSelection: DEFAULT_TEST_MODEL_SELECTION, - cwd: process.cwd(), - message: "Fix layout bug from screenshot.", - attachments: [ - { - type: "image", - id: missingAttachmentId, - name: "outside.png", - mimeType: "image/png", - sizeBytes: 5, - }, - ], - }) - .pipe(Effect.result); + const result = yield* textGeneration + .generateBranchName({ + modelSelection: DEFAULT_TEST_MODEL_SELECTION, + cwd: process.cwd(), + message: "Fix layout bug from screenshot.", + attachments: [ + { + type: "image", + id: missingAttachmentId, + name: "outside.png", + mimeType: "image/png", + sizeBytes: 5, + }, + ], + }) + .pipe(Effect.result); - expect(Result.isFailure(result)).toBe(true); - if (Result.isFailure(result)) { - expect(result.failure).toBeInstanceOf(TextGenerationError); - expect(result.failure.message).toContain("missing --image input"); - } - }), + expect(Result.isFailure(result)).toBe(true); + if (Result.isFailure(result)) { + expect(result.failure).toBeInstanceOf(TextGenerationError); + expect(result.failure.message).toContain("missing --image input"); + } + }), ), ); @@ -581,23 +541,22 @@ it.layer(CodexTextGenerationTestLayer)("CodexTextGenerationLive", (it) => { title: "This is not a branch payload", }), }, - Effect.gen(function* () { - const textGeneration = yield* TextGeneration; + (textGeneration) => + Effect.gen(function* () { + const result = yield* textGeneration + .generateBranchName({ + cwd: process.cwd(), + message: "Fix websocket reconnect flake", + modelSelection: DEFAULT_TEST_MODEL_SELECTION, + }) + .pipe(Effect.result); - const result = yield* textGeneration - .generateBranchName({ - cwd: process.cwd(), - message: "Fix websocket reconnect flake", - modelSelection: DEFAULT_TEST_MODEL_SELECTION, - }) - .pipe(Effect.result); - - expect(Result.isFailure(result)).toBe(true); - if (Result.isFailure(result)) { - expect(result.failure).toBeInstanceOf(TextGenerationError); - expect(result.failure.message).toContain("Codex returned invalid structured output"); - } - }), + expect(Result.isFailure(result)).toBe(true); + if (Result.isFailure(result)) { + expect(result.failure).toBeInstanceOf(TextGenerationError); + expect(result.failure.message).toContain("Codex returned invalid structured output"); + } + }), ), ); @@ -608,27 +567,26 @@ it.layer(CodexTextGenerationTestLayer)("CodexTextGenerationLive", (it) => { exitCode: 1, stderr: "codex execution failed", }, - Effect.gen(function* () { - const textGeneration = yield* TextGeneration; + (textGeneration) => + Effect.gen(function* () { + const result = yield* textGeneration + .generateCommitMessage({ + cwd: process.cwd(), + branch: "feature/codex-error", + stagedSummary: "M README.md", + stagedPatch: "diff --git a/README.md b/README.md", + modelSelection: DEFAULT_TEST_MODEL_SELECTION, + }) + .pipe(Effect.result); - const result = yield* textGeneration - .generateCommitMessage({ - cwd: process.cwd(), - branch: "feature/codex-error", - stagedSummary: "M README.md", - stagedPatch: "diff --git a/README.md b/README.md", - modelSelection: DEFAULT_TEST_MODEL_SELECTION, - }) - .pipe(Effect.result); - - expect(Result.isFailure(result)).toBe(true); - if (Result.isFailure(result)) { - expect(result.failure).toBeInstanceOf(TextGenerationError); - expect(result.failure.message).toContain( - "Codex CLI command failed: codex execution failed", - ); - } - }), + expect(Result.isFailure(result)).toBe(true); + if (Result.isFailure(result)) { + expect(result.failure).toBeInstanceOf(TextGenerationError); + expect(result.failure.message).toContain( + "Codex CLI command failed: codex execution failed", + ); + } + }), ), ); }); diff --git a/apps/server/src/git/Layers/CodexTextGeneration.ts b/apps/server/src/git/Layers/CodexTextGeneration.ts index ee1e39d0fa..d4bc8f1632 100644 --- a/apps/server/src/git/Layers/CodexTextGeneration.ts +++ b/apps/server/src/git/Layers/CodexTextGeneration.ts @@ -1,9 +1,7 @@ -import { randomUUID } from "node:crypto"; - -import { Effect, FileSystem, Layer, Option, Path, Schema, Scope, Stream } from "effect"; +import { Effect, FileSystem, Option, Path, Random, Schema, Scope, Stream } from "effect"; import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process"; -import { CodexModelSelection } from "@t3tools/contracts"; +import { type CodexSettings, type ModelSelection } from "@t3tools/contracts"; import { sanitizeBranchFragment, sanitizeFeatureBranchName } from "@t3tools/shared/git"; import { resolveAttachmentPath } from "../../attachmentStore.ts"; @@ -14,7 +12,6 @@ import { type BranchNameGenerationInput, type ThreadTitleGenerationResult, type TextGenerationShape, - TextGeneration, } from "../Services/TextGeneration.ts"; import { buildBranchNamePrompt, @@ -29,7 +26,6 @@ import { sanitizeThreadTitle, toJsonSchemaObject, } from "../Utils.ts"; -import { ServerSettingsService } from "../../serverSettings.ts"; import { getModelSelectionBooleanOptionValue, getModelSelectionStringOptionValue, @@ -37,12 +33,18 @@ import { const CODEX_GIT_TEXT_GENERATION_REASONING_EFFORT = "low"; const CODEX_TIMEOUT_MS = 180_000; -const makeCodexTextGeneration = Effect.gen(function* () { +/** + * Build a Codex text-generation closure bound to a specific `CodexSettings` + * payload. See `makeCodexAdapter` for the overall per-instance rationale. + */ +export const makeCodexTextGeneration = Effect.fn("makeCodexTextGeneration")(function* ( + codexConfig: CodexSettings, + environment: NodeJS.ProcessEnv = process.env, +) { const fileSystem = yield* FileSystem.FileSystem; const path = yield* Path.Path; const commandSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; const serverConfig = yield* Effect.service(ServerConfig); - const serverSettingsService = yield* Effect.service(ServerSettingsService); type MaterializedImageAttachments = { readonly imagePaths: ReadonlyArray; @@ -68,21 +70,23 @@ const makeCodexTextGeneration = Effect.gen(function* () { prefix: string, content: string, ): Effect.Effect => { - return fileSystem - .makeTempFileScoped({ - prefix: `t3code-${prefix}-${process.pid}-${randomUUID()}.tmp`, - }) - .pipe( - Effect.tap((filePath) => fileSystem.writeFileString(filePath, content)), - Effect.mapError( - (cause) => - new TextGenerationError({ - operation, - detail: `Failed to write temp file`, - cause, - }), - ), - ); + return Effect.gen(function* () { + const tempFileId = yield* Random.nextUUIDv4; + return yield* fileSystem + .makeTempFileScoped({ + prefix: `t3code-${prefix}-${process.pid}-${tempFileId}.tmp`, + }) + .pipe(Effect.tap((filePath) => fileSystem.writeFileString(filePath, content))); + }).pipe( + Effect.mapError( + (cause) => + new TextGenerationError({ + operation, + detail: `Failed to write temp file`, + cause, + }), + ), + ); }; const safeUnlink = (filePath: string): Effect.Effect => @@ -143,7 +147,7 @@ const makeCodexTextGeneration = Effect.gen(function* () { outputSchemaJson: S; imagePaths?: ReadonlyArray; cleanupPaths?: ReadonlyArray; - modelSelection: CodexModelSelection; + modelSelection: ModelSelection; }): Effect.fn.Return { const schemaPath = yield* writeTempFile( operation, @@ -152,17 +156,12 @@ const makeCodexTextGeneration = Effect.gen(function* () { ); const outputPath = yield* writeTempFile(operation, "codex-output", ""); - const codexSettings = yield* Effect.map( - serverSettingsService.getSettings, - (settings) => settings.providers.codex, - ).pipe(Effect.catch(() => Effect.undefined)); - const runCodexCommand = Effect.fn("runCodexJson.runCodexCommand")(function* () { const reasoningEffort = getModelSelectionStringOptionValue(modelSelection, "reasoningEffort") ?? CODEX_GIT_TEXT_GENERATION_REASONING_EFFORT; const command = ChildProcess.make( - codexSettings?.binaryPath || "codex", + codexConfig.binaryPath || "codex", [ "exec", "--ephemeral", @@ -185,10 +184,8 @@ const makeCodexTextGeneration = Effect.gen(function* () { ], { env: { - ...process.env, - ...(codexSettings?.homePath - ? { CODEX_HOME: expandHomePath(codexSettings.homePath) } - : {}), + ...environment, + ...(codexConfig.homePath ? { CODEX_HOME: expandHomePath(codexConfig.homePath) } : {}), }, cwd, shell: process.platform === "win32", @@ -288,13 +285,6 @@ const makeCodexTextGeneration = Effect.gen(function* () { includeBranch: input.includeBranch === true, }); - if (input.modelSelection.provider !== "codex") { - return yield* new TextGenerationError({ - operation: "generateCommitMessage", - detail: "Invalid model selection.", - }); - } - const generated = yield* runCodexJson({ operation: "generateCommitMessage", cwd: input.cwd, @@ -323,13 +313,6 @@ const makeCodexTextGeneration = Effect.gen(function* () { diffPatch: input.diffPatch, }); - if (input.modelSelection.provider !== "codex") { - return yield* new TextGenerationError({ - operation: "generatePrContent", - detail: "Invalid model selection.", - }); - } - const generated = yield* runCodexJson({ operation: "generatePrContent", cwd: input.cwd, @@ -356,13 +339,6 @@ const makeCodexTextGeneration = Effect.gen(function* () { attachments: input.attachments, }); - if (input.modelSelection.provider !== "codex") { - return yield* new TextGenerationError({ - operation: "generateBranchName", - detail: "Invalid model selection.", - }); - } - const generated = yield* runCodexJson({ operation: "generateBranchName", cwd: input.cwd, @@ -389,13 +365,6 @@ const makeCodexTextGeneration = Effect.gen(function* () { attachments: input.attachments, }); - if (input.modelSelection.provider !== "codex") { - return yield* new TextGenerationError({ - operation: "generateThreadTitle", - detail: "Invalid model selection.", - }); - } - const generated = yield* runCodexJson({ operation: "generateThreadTitle", cwd: input.cwd, @@ -418,4 +387,6 @@ const makeCodexTextGeneration = Effect.gen(function* () { } satisfies TextGenerationShape; }); -export const CodexTextGenerationLive = Layer.effect(TextGeneration, makeCodexTextGeneration); +// NOTE: `CodexTextGenerationLive` (the singleton Layer) has been removed. +// `makeCodexTextGeneration(codexConfig)` is now invoked directly by +// `CodexDriver.create()` for each configured instance. diff --git a/apps/server/src/git/Layers/CursorTextGeneration.test.ts b/apps/server/src/git/Layers/CursorTextGeneration.test.ts index b8d974fd94..3718557664 100644 --- a/apps/server/src/git/Layers/CursorTextGeneration.test.ts +++ b/apps/server/src/git/Layers/CursorTextGeneration.test.ts @@ -5,16 +5,15 @@ import { chmodSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync import * as NodeServices from "@effect/platform-node/NodeServices"; import { it } from "@effect/vitest"; -import { Effect, Layer } from "effect"; +import { Effect, Layer, Schema } from "effect"; import { createModelSelection } from "@t3tools/shared/model"; import { expect } from "vitest"; -import { ServerSettingsError } from "@t3tools/contracts"; +import { CursorSettings, ProviderInstanceId } from "@t3tools/contracts"; import { ServerConfig } from "../../config.ts"; -import { TextGeneration } from "../Services/TextGeneration.ts"; -import { CursorTextGenerationLive } from "./CursorTextGeneration.ts"; -import { ServerSettingsService } from "../../serverSettings.ts"; +import { type TextGenerationShape } from "../Services/TextGeneration.ts"; +import { makeCursorTextGeneration } from "./CursorTextGeneration.ts"; const __dirname = path.dirname(fileURLToPath(import.meta.url)); const mockAgentPath = path.join(__dirname, "../../../scripts/acp-mock-agent.ts"); @@ -23,15 +22,9 @@ function shellSingleQuote(value: string): string { return `'${value.replaceAll("'", `'"'"'`)}'`; } -const CursorTextGenerationTestLayer = CursorTextGenerationLive.pipe( - Layer.provideMerge(ServerSettingsService.layerTest()), - Layer.provideMerge( - ServerConfig.layerTest(process.cwd(), { - prefix: "t3code-cursor-text-generation-test-", - }), - ), - Layer.provideMerge(NodeServices.layer), -); +const CursorTextGenerationTestLayer = ServerConfig.layerTest(process.cwd(), { + prefix: "t3code-cursor-text-generation-test-", +}).pipe(Layer.provideMerge(NodeServices.layer)); function makeAcpAgentWrapper(dir: string, env: Record): string { const binDir = path.join(dir, "bin"); @@ -57,44 +50,20 @@ function makeAcpAgentWrapper(dir: string, env: Record): string { function withFakeAcpAgent( env: Record, - effect: Effect.Effect, -): Effect.Effect { + effectFn: (textGeneration: TextGenerationShape) => Effect.Effect, +) { return Effect.gen(function* () { const tempDir = mkdtempSync(path.join(os.tmpdir(), "t3code-cursor-text-acp-")); - const agentPath = makeAcpAgentWrapper(tempDir, env); - const serverSettings = yield* ServerSettingsService; - const previousSettings = yield* serverSettings.getSettings; - - yield* serverSettings.updateSettings({ - providers: { - cursor: { - binaryPath: agentPath, - }, - }, - }); - - return yield* effect.pipe( - Effect.ensuring( - serverSettings - .updateSettings({ - providers: { - cursor: { - binaryPath: previousSettings.providers.cursor.binaryPath, - }, - }, - }) - .pipe( - Effect.catch(() => Effect.void), - Effect.ensuring( - Effect.sync(() => { - rmSync(tempDir, { recursive: true, force: true }); - }), - ), - Effect.asVoid, - ), - ), + yield* Effect.addFinalizer(() => + Effect.sync(() => { + rmSync(tempDir, { recursive: true, force: true }); + }), ); - }); + const agentPath = makeAcpAgentWrapper(tempDir, env); + const config = Schema.decodeSync(CursorSettings)({ binaryPath: agentPath }); + const textGeneration = yield* makeCursorTextGeneration(config); + return yield* effectFn(textGeneration); + }).pipe(Effect.scoped); } function waitForFileContent(path: string): Effect.Effect { @@ -126,85 +95,86 @@ it.layer(CursorTextGenerationTestLayer)("CursorTextGenerationLive", (it) => { body: "- verify cursor acp model config path", }), }, - Effect.gen(function* () { - const textGeneration = yield* TextGeneration; + (textGeneration) => + Effect.gen(function* () { + const generated = yield* textGeneration.generateCommitMessage({ + cwd: process.cwd(), + branch: "feature/cursor-text-generation", + stagedSummary: "M apps/server/src/git/Layers/CursorTextGeneration.ts", + stagedPatch: + "diff --git a/apps/server/src/git/Layers/CursorTextGeneration.ts b/apps/server/src/git/Layers/CursorTextGeneration.ts", + modelSelection: { + ...createModelSelection(ProviderInstanceId.make("cursor"), "gpt-5.4", [ + { id: "reasoning", value: "xhigh" }, + { id: "fastMode", value: true }, + { id: "contextWindow", value: "1m" }, + ]), + }, + }); - const generated = yield* textGeneration.generateCommitMessage({ - cwd: process.cwd(), - branch: "feature/cursor-text-generation", - stagedSummary: "M apps/server/src/git/Layers/CursorTextGeneration.ts", - stagedPatch: - "diff --git a/apps/server/src/git/Layers/CursorTextGeneration.ts b/apps/server/src/git/Layers/CursorTextGeneration.ts", - modelSelection: { - ...createModelSelection("cursor", "gpt-5.4", [ - { id: "reasoning", value: "xhigh" }, - { id: "fastMode", value: true }, - { id: "contextWindow", value: "1m" }, + expect(generated.subject).toBe("Add generated commit message"); + expect(generated.body).toBe("- verify cursor acp model config path"); + + const requests = readFileSync(requestLogPath, "utf8") + .trim() + .split("\n") + .filter((line) => line.length > 0) + .map( + (line) => JSON.parse(line) as { method?: string; params?: Record }, + ); + + expect( + requests.find((request) => request.method === "initialize")?.params?.clientCapabilities, + ).toMatchObject({ + _meta: { + parameterizedModelPicker: true, + }, + }); + expect( + requests.some( + (request) => + request.method === "session/set_config_option" && + request.params?.configId === "model" && + request.params?.value === "gpt-5.4", + ), + ).toBe(true); + expect( + requests.some( + (request) => + request.method === "session/set_config_option" && + request.params?.configId === "reasoning" && + request.params?.value === "extra-high", + ), + ).toBe(true); + expect( + requests.some( + (request) => + request.method === "session/set_config_option" && + request.params?.configId === "context" && + request.params?.value === "1m", + ), + ).toBe(true); + expect( + requests.some( + (request) => + request.method === "session/set_config_option" && + request.params?.configId === "fast" && + request.params?.value === "true", + ), + ).toBe(true); + expect( + requests.find((request) => request.method === "session/prompt")?.params?.prompt, + ).toEqual( + expect.arrayContaining([ + expect.objectContaining({ + type: "text", + text: expect.stringContaining("Staged patch:"), + }), ]), - }, - }); + ); - expect(generated.subject).toBe("Add generated commit message"); - expect(generated.body).toBe("- verify cursor acp model config path"); - - const requests = readFileSync(requestLogPath, "utf8") - .trim() - .split("\n") - .filter((line) => line.length > 0) - .map((line) => JSON.parse(line) as { method?: string; params?: Record }); - - expect( - requests.find((request) => request.method === "initialize")?.params?.clientCapabilities, - ).toMatchObject({ - _meta: { - parameterizedModelPicker: true, - }, - }); - expect( - requests.some( - (request) => - request.method === "session/set_config_option" && - request.params?.configId === "model" && - request.params?.value === "gpt-5.4", - ), - ).toBe(true); - expect( - requests.some( - (request) => - request.method === "session/set_config_option" && - request.params?.configId === "reasoning" && - request.params?.value === "extra-high", - ), - ).toBe(true); - expect( - requests.some( - (request) => - request.method === "session/set_config_option" && - request.params?.configId === "context" && - request.params?.value === "1m", - ), - ).toBe(true); - expect( - requests.some( - (request) => - request.method === "session/set_config_option" && - request.params?.configId === "fast" && - request.params?.value === "true", - ), - ).toBe(true); - expect( - requests.find((request) => request.method === "session/prompt")?.params?.prompt, - ).toEqual( - expect.arrayContaining([ - expect.objectContaining({ - type: "text", - text: expect.stringContaining("Staged patch:"), - }), - ]), - ); - - rmSync(requestLogDir, { recursive: true, force: true }); - }), + rmSync(requestLogDir, { recursive: true, force: true }); + }), ); }); @@ -214,23 +184,22 @@ it.layer(CursorTextGenerationTestLayer)("CursorTextGenerationLive", (it) => { T3_ACP_PROMPT_RESPONSE_TEXT: 'Sure, here is the JSON:\n```json\n{\n "subject": "Update README dummy comment with attribution and date",\n "body": ""\n}\n```\nDone.', }, - Effect.gen(function* () { - const textGeneration = yield* TextGeneration; + (textGeneration) => + Effect.gen(function* () { + const generated = yield* textGeneration.generateCommitMessage({ + cwd: process.cwd(), + branch: "feature/cursor-noisy-json", + stagedSummary: "M README.md", + stagedPatch: "diff --git a/README.md b/README.md", + modelSelection: { + instanceId: ProviderInstanceId.make("cursor"), + model: "composer-2", + }, + }); - const generated = yield* textGeneration.generateCommitMessage({ - cwd: process.cwd(), - branch: "feature/cursor-noisy-json", - stagedSummary: "M README.md", - stagedPatch: "diff --git a/README.md b/README.md", - modelSelection: { - provider: "cursor", - model: "composer-2", - }, - }); - - expect(generated.subject).toBe("Update README dummy comment with attribution and date"); - expect(generated.body).toBe(""); - }), + expect(generated.subject).toBe("Update README dummy comment with attribution and date"); + expect(generated.body).toBe(""); + }), ), ); @@ -241,20 +210,19 @@ it.layer(CursorTextGenerationTestLayer)("CursorTextGenerationLive", (it) => { title: '"Trim reconnect spinner status after resume."', }), }, - Effect.gen(function* () { - const textGeneration = yield* TextGeneration; + (textGeneration) => + Effect.gen(function* () { + const generated = yield* textGeneration.generateThreadTitle({ + cwd: process.cwd(), + message: "Fix the reconnect spinner after a resumed session.", + modelSelection: { + instanceId: ProviderInstanceId.make("cursor"), + model: "composer-2", + }, + }); - const generated = yield* textGeneration.generateThreadTitle({ - cwd: process.cwd(), - message: "Fix the reconnect spinner after a resumed session.", - modelSelection: { - provider: "cursor", - model: "composer-2", - }, - }); - - expect(generated.title).toBe("Trim reconnect spinner status after resume."); - }), + expect(generated.title).toBe("Trim reconnect spinner status after resume."); + }), ), ); @@ -270,28 +238,27 @@ it.layer(CursorTextGenerationTestLayer)("CursorTextGenerationLive", (it) => { body: "", }), }, - Effect.gen(function* () { - const textGeneration = yield* TextGeneration; + (textGeneration) => + Effect.gen(function* () { + const generated = yield* textGeneration.generateCommitMessage({ + cwd: process.cwd(), + branch: "feature/cursor-runtime-close", + stagedSummary: "M apps/server/src/git/Layers/CursorTextGeneration.ts", + stagedPatch: + "diff --git a/apps/server/src/git/Layers/CursorTextGeneration.ts b/apps/server/src/git/Layers/CursorTextGeneration.ts", + modelSelection: { + instanceId: ProviderInstanceId.make("cursor"), + model: "composer-2", + }, + }); - const generated = yield* textGeneration.generateCommitMessage({ - cwd: process.cwd(), - branch: "feature/cursor-runtime-close", - stagedSummary: "M apps/server/src/git/Layers/CursorTextGeneration.ts", - stagedPatch: - "diff --git a/apps/server/src/git/Layers/CursorTextGeneration.ts b/apps/server/src/git/Layers/CursorTextGeneration.ts", - modelSelection: { - provider: "cursor", - model: "composer-2", - }, - }); + expect(generated.subject).toBe("Close runtime after generation"); - expect(generated.subject).toBe("Close runtime after generation"); + const exitLog = yield* waitForFileContent(exitLogPath); + expect(exitLog).toContain("exit:0"); - const exitLog = yield* waitForFileContent(exitLogPath); - expect(exitLog).toContain("exit:0"); - - rmSync(exitLogDir, { recursive: true, force: true }); - }), + rmSync(exitLogDir, { recursive: true, force: true }); + }), ); }); }); diff --git a/apps/server/src/git/Layers/CursorTextGeneration.ts b/apps/server/src/git/Layers/CursorTextGeneration.ts index 6b78728b95..c94c6dd180 100644 --- a/apps/server/src/git/Layers/CursorTextGeneration.ts +++ b/apps/server/src/git/Layers/CursorTextGeneration.ts @@ -1,14 +1,13 @@ -import { Effect, Layer, Option, Ref, Schema } from "effect"; +import { Effect, Option, Ref, Schema } from "effect"; import { ChildProcessSpawner } from "effect/unstable/process"; -import { CursorModelSelection } from "@t3tools/contracts"; +import { type CursorSettings, type ModelSelection } from "@t3tools/contracts"; import { sanitizeBranchFragment, sanitizeFeatureBranchName } from "@t3tools/shared/git"; import { TextGenerationError } from "@t3tools/contracts"; import { type ThreadTitleGenerationResult, type TextGenerationShape, - TextGeneration, } from "../Services/TextGeneration.ts"; import { buildBranchNamePrompt, @@ -26,7 +25,6 @@ import { applyCursorAcpModelSelection, makeCursorAcpRuntime, } from "../../provider/acp/CursorAcpSupport.ts"; -import { ServerSettingsService } from "../../serverSettings.ts"; const CURSOR_TIMEOUT_MS = 180_000; @@ -55,9 +53,15 @@ function isTextGenerationError(error: unknown): error is TextGenerationError { ); } -const makeCursorTextGeneration = Effect.gen(function* () { +/** + * Build a Cursor text-generation closure bound to a specific `CursorSettings` + * payload. See `makeCodexAdapter` for the overall per-instance rationale. + */ +export const makeCursorTextGeneration = Effect.fn("makeCursorTextGeneration")(function* ( + cursorSettings: CursorSettings, + environment: NodeJS.ProcessEnv = process.env, +) { const commandSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; - const serverSettingsService = yield* Effect.service(ServerSettingsService); const runCursorJson = ({ operation, @@ -74,17 +78,13 @@ const makeCursorTextGeneration = Effect.gen(function* () { cwd: string; prompt: string; outputSchemaJson: S; - modelSelection: CursorModelSelection; + modelSelection: ModelSelection; }): Effect.Effect => Effect.gen(function* () { - const cursorSettings = yield* Effect.map( - serverSettingsService.getSettings, - (settings) => settings.providers.cursor, - ).pipe(Effect.catch(() => Effect.undefined)); - const outputRef = yield* Ref.make(""); const runtime = yield* makeCursorAcpRuntime({ cursorSettings, + environment, childProcessSpawner: commandSpawner, cwd, clientInfo: { name: "t3-code-git-text", version: "0.0.0" }, @@ -186,13 +186,6 @@ const makeCursorTextGeneration = Effect.gen(function* () { includeBranch: input.includeBranch === true, }); - if (input.modelSelection.provider !== "cursor") { - return yield* new TextGenerationError({ - operation: "generateCommitMessage", - detail: "Invalid model selection.", - }); - } - const generated = yield* runCursorJson({ operation: "generateCommitMessage", cwd: input.cwd, @@ -221,13 +214,6 @@ const makeCursorTextGeneration = Effect.gen(function* () { diffPatch: input.diffPatch, }); - if (input.modelSelection.provider !== "cursor") { - return yield* new TextGenerationError({ - operation: "generatePrContent", - detail: "Invalid model selection.", - }); - } - const generated = yield* runCursorJson({ operation: "generatePrContent", cwd: input.cwd, @@ -250,13 +236,6 @@ const makeCursorTextGeneration = Effect.gen(function* () { attachments: input.attachments, }); - if (input.modelSelection.provider !== "cursor") { - return yield* new TextGenerationError({ - operation: "generateBranchName", - detail: "Invalid model selection.", - }); - } - const generated = yield* runCursorJson({ operation: "generateBranchName", cwd: input.cwd, @@ -278,13 +257,6 @@ const makeCursorTextGeneration = Effect.gen(function* () { attachments: input.attachments, }); - if (input.modelSelection.provider !== "cursor") { - return yield* new TextGenerationError({ - operation: "generateThreadTitle", - detail: "Invalid model selection.", - }); - } - const generated = yield* runCursorJson({ operation: "generateThreadTitle", cwd: input.cwd, @@ -306,4 +278,6 @@ const makeCursorTextGeneration = Effect.gen(function* () { } satisfies TextGenerationShape; }); -export const CursorTextGenerationLive = Layer.effect(TextGeneration, makeCursorTextGeneration); +// NOTE: `CursorTextGenerationLive` (the singleton Layer) has been removed. +// `makeCursorTextGeneration(cursorConfig)` is now invoked directly by +// `CursorDriver.create()` so each provider instance owns its own closure. diff --git a/apps/server/src/git/Layers/OpenCodeTextGeneration.test.ts b/apps/server/src/git/Layers/OpenCodeTextGeneration.test.ts index 28ee0a3e6f..c3bdd6035e 100644 --- a/apps/server/src/git/Layers/OpenCodeTextGeneration.test.ts +++ b/apps/server/src/git/Layers/OpenCodeTextGeneration.test.ts @@ -1,19 +1,19 @@ +import { OpenCodeSettings, ProviderInstanceId } from "@t3tools/contracts"; import * as NodeServices from "@effect/platform-node/NodeServices"; import { it } from "@effect/vitest"; -import { Duration, Effect, Layer } from "effect"; +import { Duration, Effect, Layer, Schema } from "effect"; import { TestClock } from "effect/testing"; import { NetService } from "@t3tools/shared/Net"; import { beforeEach, expect } from "vitest"; import { ServerConfig } from "../../config.ts"; -import { ServerSettingsService } from "../../serverSettings.ts"; import { OpenCodeRuntime, OpenCodeRuntimeError, type OpenCodeRuntimeShape, } from "../../provider/opencodeRuntime.ts"; -import { TextGeneration } from "../Services/TextGeneration.ts"; -import { OpenCodeTextGenerationLive } from "./OpenCodeTextGeneration.ts"; +import { type TextGenerationShape } from "../Services/TextGeneration.ts"; +import { makeOpenCodeTextGeneration } from "./OpenCodeTextGeneration.ts"; const runtimeMock = { state: { @@ -97,23 +97,16 @@ const OpenCodeRuntimeTestDouble: OpenCodeRuntimeShape = { }; const DEFAULT_TEST_MODEL_SELECTION = { - provider: "opencode" as const, + instanceId: ProviderInstanceId.make("opencode"), model: "openai/gpt-5", }; const OPENCODE_TEXT_GENERATION_IDLE_TTL_MS = 30_000; -const OpenCodeTextGenerationTestLayer = OpenCodeTextGenerationLive.pipe( - Layer.provideMerge(Layer.succeed(OpenCodeRuntime, OpenCodeRuntimeTestDouble)), - Layer.provideMerge( - ServerSettingsService.layerTest({ - providers: { - opencode: { - binaryPath: "fake-opencode", - }, - }, - }), - ), +const OpenCodeTextGenerationTestLayer = Layer.succeed( + OpenCodeRuntime, + OpenCodeRuntimeTestDouble, +).pipe( Layer.provideMerge( ServerConfig.layerTest(process.cwd(), { prefix: "t3code-opencode-text-generation-test-", @@ -123,19 +116,10 @@ const OpenCodeTextGenerationTestLayer = OpenCodeTextGenerationLive.pipe( Layer.provideMerge(NodeServices.layer), ); -const OpenCodeTextGenerationExistingServerTestLayer = OpenCodeTextGenerationLive.pipe( - Layer.provideMerge(Layer.succeed(OpenCodeRuntime, OpenCodeRuntimeTestDouble)), - Layer.provideMerge( - ServerSettingsService.layerTest({ - providers: { - opencode: { - binaryPath: "fake-opencode", - serverUrl: "http://127.0.0.1:9999", - serverPassword: "secret-password", - }, - }, - }), - ), +const OpenCodeTextGenerationExistingServerTestLayer = Layer.succeed( + OpenCodeRuntime, + OpenCodeRuntimeTestDouble, +).pipe( Layer.provideMerge( ServerConfig.layerTest(process.cwd(), { prefix: "t3code-opencode-text-generation-existing-server-test-", @@ -145,6 +129,25 @@ const OpenCodeTextGenerationExistingServerTestLayer = OpenCodeTextGenerationLive Layer.provideMerge(NodeServices.layer), ); +const DEFAULT_OPENCODE_SETTINGS = Schema.decodeSync(OpenCodeSettings)({ + binaryPath: "fake-opencode", +}); +const EXISTING_SERVER_OPENCODE_SETTINGS = Schema.decodeSync(OpenCodeSettings)({ + binaryPath: "fake-opencode", + serverUrl: "http://127.0.0.1:9999", + serverPassword: "secret-password", +}); + +function withOpenCodeTextGeneration( + settings: OpenCodeSettings, + effectFn: (textGeneration: TextGenerationShape) => Effect.Effect, +) { + return Effect.gen(function* () { + const textGeneration = yield* makeOpenCodeTextGeneration(settings); + return yield* effectFn(textGeneration); + }).pipe(Effect.scoped); +} + beforeEach(() => { runtimeMock.reset(); }); @@ -157,145 +160,148 @@ const advanceIdleClock = Effect.gen(function* () { it.layer(OpenCodeTextGenerationTestLayer)("OpenCodeTextGenerationLive", (it) => { it.effect("reuses a warm server across back-to-back requests and closes it after idling", () => - Effect.gen(function* () { - const textGeneration = yield* TextGeneration; + withOpenCodeTextGeneration(DEFAULT_OPENCODE_SETTINGS, (textGeneration) => + Effect.gen(function* () { + yield* textGeneration.generateCommitMessage({ + cwd: process.cwd(), + branch: "feature/opencode-reuse", + stagedSummary: "M README.md", + stagedPatch: "diff --git a/README.md b/README.md", + modelSelection: DEFAULT_TEST_MODEL_SELECTION, + }); + yield* textGeneration.generateCommitMessage({ + cwd: process.cwd(), + branch: "feature/opencode-reuse", + stagedSummary: "M README.md", + stagedPatch: "diff --git a/README.md b/README.md", + modelSelection: DEFAULT_TEST_MODEL_SELECTION, + }); - yield* textGeneration.generateCommitMessage({ - cwd: process.cwd(), - branch: "feature/opencode-reuse", - stagedSummary: "M README.md", - stagedPatch: "diff --git a/README.md b/README.md", - modelSelection: DEFAULT_TEST_MODEL_SELECTION, - }); - yield* textGeneration.generateCommitMessage({ - cwd: process.cwd(), - branch: "feature/opencode-reuse", - stagedSummary: "M README.md", - stagedPatch: "diff --git a/README.md b/README.md", - modelSelection: DEFAULT_TEST_MODEL_SELECTION, - }); + expect(runtimeMock.state.startCalls).toEqual(["fake-opencode"]); + expect(runtimeMock.state.promptUrls).toEqual([ + "http://127.0.0.1:4301", + "http://127.0.0.1:4301", + ]); + expect(runtimeMock.state.closeCalls).toEqual([]); - expect(runtimeMock.state.startCalls).toEqual(["fake-opencode"]); - expect(runtimeMock.state.promptUrls).toEqual([ - "http://127.0.0.1:4301", - "http://127.0.0.1:4301", - ]); - expect(runtimeMock.state.closeCalls).toEqual([]); + yield* advanceIdleClock; - yield* advanceIdleClock; - - expect(runtimeMock.state.closeCalls).toEqual(["http://127.0.0.1:4301"]); - }).pipe(Effect.provide(TestClock.layer())), + expect(runtimeMock.state.closeCalls).toEqual(["http://127.0.0.1:4301"]); + }), + ).pipe(Effect.provide(TestClock.layer())), ); it.effect("starts a new server after the warm server idles out", () => - Effect.gen(function* () { - const textGeneration = yield* TextGeneration; + withOpenCodeTextGeneration(DEFAULT_OPENCODE_SETTINGS, (textGeneration) => + Effect.gen(function* () { + yield* textGeneration.generateCommitMessage({ + cwd: process.cwd(), + branch: "feature/opencode-reuse", + stagedSummary: "M README.md", + stagedPatch: "diff --git a/README.md b/README.md", + modelSelection: DEFAULT_TEST_MODEL_SELECTION, + }); - yield* textGeneration.generateCommitMessage({ - cwd: process.cwd(), - branch: "feature/opencode-reuse", - stagedSummary: "M README.md", - stagedPatch: "diff --git a/README.md b/README.md", - modelSelection: DEFAULT_TEST_MODEL_SELECTION, - }); + yield* advanceIdleClock; - yield* advanceIdleClock; + yield* textGeneration.generateCommitMessage({ + cwd: process.cwd(), + branch: "feature/opencode-reuse", + stagedSummary: "M README.md", + stagedPatch: "diff --git a/README.md b/README.md", + modelSelection: DEFAULT_TEST_MODEL_SELECTION, + }); - yield* textGeneration.generateCommitMessage({ - cwd: process.cwd(), - branch: "feature/opencode-reuse", - stagedSummary: "M README.md", - stagedPatch: "diff --git a/README.md b/README.md", - modelSelection: DEFAULT_TEST_MODEL_SELECTION, - }); - - expect(runtimeMock.state.startCalls).toEqual(["fake-opencode", "fake-opencode"]); - expect(runtimeMock.state.promptUrls).toEqual([ - "http://127.0.0.1:4301", - "http://127.0.0.1:4302", - ]); - expect(runtimeMock.state.closeCalls).toEqual(["http://127.0.0.1:4301"]); - }).pipe(Effect.provide(TestClock.layer())), + expect(runtimeMock.state.startCalls).toEqual(["fake-opencode", "fake-opencode"]); + expect(runtimeMock.state.promptUrls).toEqual([ + "http://127.0.0.1:4301", + "http://127.0.0.1:4302", + ]); + expect(runtimeMock.state.closeCalls).toEqual(["http://127.0.0.1:4301"]); + }), + ).pipe(Effect.provide(TestClock.layer())), ); it.effect("returns a typed empty-output error when OpenCode returns no text parts", () => - Effect.gen(function* () { - runtimeMock.state.promptResult = { data: {} }; - const textGeneration = yield* TextGeneration; + withOpenCodeTextGeneration(DEFAULT_OPENCODE_SETTINGS, (textGeneration) => + Effect.gen(function* () { + runtimeMock.state.promptResult = { data: {} }; - const error = yield* textGeneration - .generateCommitMessage({ - cwd: process.cwd(), - branch: "feature/opencode-reuse", - stagedSummary: "M README.md", - stagedPatch: "diff --git a/README.md b/README.md", - modelSelection: DEFAULT_TEST_MODEL_SELECTION, - }) - .pipe(Effect.flip); + const error = yield* textGeneration + .generateCommitMessage({ + cwd: process.cwd(), + branch: "feature/opencode-reuse", + stagedSummary: "M README.md", + stagedPatch: "diff --git a/README.md b/README.md", + modelSelection: DEFAULT_TEST_MODEL_SELECTION, + }) + .pipe(Effect.flip); - expect(error.message).toContain("OpenCode returned empty output."); - }), + expect(error.message).toContain("OpenCode returned empty output."); + }), + ), ); it.effect("parses JSON returned as plain text output", () => - Effect.gen(function* () { - runtimeMock.state.promptResult = { - data: { - parts: [ - { - type: "text", - text: 'Here is the result:\n{"subject":"Tighten OpenCode parsing","body":"Handle JSON text output locally."}', - }, - ], - }, - }; - const textGeneration = yield* TextGeneration; - - const result = yield* textGeneration.generateCommitMessage({ - cwd: process.cwd(), - branch: "feature/opencode-reuse", - stagedSummary: "M README.md", - stagedPatch: "diff --git a/README.md b/README.md", - modelSelection: DEFAULT_TEST_MODEL_SELECTION, - }); - - expect(result).toEqual({ - subject: "Tighten OpenCode parsing", - body: "Handle JSON text output locally.", - }); - }), - ); - - it.effect("surfaces the upstream OpenCode structured-output error message", () => - Effect.gen(function* () { - runtimeMock.state.promptResult = { - data: { - info: { - error: { - name: "StructuredOutputError", - data: { - message: "Model did not produce structured output", - retries: 2, + withOpenCodeTextGeneration(DEFAULT_OPENCODE_SETTINGS, (textGeneration) => + Effect.gen(function* () { + runtimeMock.state.promptResult = { + data: { + parts: [ + { + type: "text", + text: 'Here is the result:\n{"subject":"Tighten OpenCode parsing","body":"Handle JSON text output locally."}', }, - }, + ], }, - }, - }; - const textGeneration = yield* TextGeneration; + }; - const error = yield* textGeneration - .generateCommitMessage({ + const result = yield* textGeneration.generateCommitMessage({ cwd: process.cwd(), branch: "feature/opencode-reuse", stagedSummary: "M README.md", stagedPatch: "diff --git a/README.md b/README.md", modelSelection: DEFAULT_TEST_MODEL_SELECTION, - }) - .pipe(Effect.flip); + }); - expect(error.message).toContain("Model did not produce structured output"); - }), + expect(result).toEqual({ + subject: "Tighten OpenCode parsing", + body: "Handle JSON text output locally.", + }); + }), + ), + ); + + it.effect("surfaces the upstream OpenCode structured-output error message", () => + withOpenCodeTextGeneration(DEFAULT_OPENCODE_SETTINGS, (textGeneration) => + Effect.gen(function* () { + runtimeMock.state.promptResult = { + data: { + info: { + error: { + name: "StructuredOutputError", + data: { + message: "Model did not produce structured output", + retries: 2, + }, + }, + }, + }, + }; + + const error = yield* textGeneration + .generateCommitMessage({ + cwd: process.cwd(), + branch: "feature/opencode-reuse", + stagedSummary: "M README.md", + stagedPatch: "diff --git a/README.md b/README.md", + modelSelection: DEFAULT_TEST_MODEL_SELECTION, + }) + .pipe(Effect.flip); + + expect(error.message).toContain("Model did not produce structured output"); + }), + ), ); }); @@ -303,38 +309,38 @@ it.layer(OpenCodeTextGenerationExistingServerTestLayer)( "OpenCodeTextGenerationLive with configured server URL", (it) => { it.effect("reuses a configured OpenCode server URL without spawning or applying idle TTL", () => - Effect.gen(function* () { - const textGeneration = yield* TextGeneration; + withOpenCodeTextGeneration(EXISTING_SERVER_OPENCODE_SETTINGS, (textGeneration) => + Effect.gen(function* () { + yield* textGeneration.generateCommitMessage({ + cwd: process.cwd(), + branch: "feature/opencode-reuse", + stagedSummary: "M README.md", + stagedPatch: "diff --git a/README.md b/README.md", + modelSelection: DEFAULT_TEST_MODEL_SELECTION, + }); + yield* textGeneration.generateCommitMessage({ + cwd: process.cwd(), + branch: "feature/opencode-reuse", + stagedSummary: "M README.md", + stagedPatch: "diff --git a/README.md b/README.md", + modelSelection: DEFAULT_TEST_MODEL_SELECTION, + }); - yield* textGeneration.generateCommitMessage({ - cwd: process.cwd(), - branch: "feature/opencode-reuse", - stagedSummary: "M README.md", - stagedPatch: "diff --git a/README.md b/README.md", - modelSelection: DEFAULT_TEST_MODEL_SELECTION, - }); - yield* textGeneration.generateCommitMessage({ - cwd: process.cwd(), - branch: "feature/opencode-reuse", - stagedSummary: "M README.md", - stagedPatch: "diff --git a/README.md b/README.md", - modelSelection: DEFAULT_TEST_MODEL_SELECTION, - }); + expect(runtimeMock.state.startCalls).toEqual([]); + expect(runtimeMock.state.promptUrls).toEqual([ + "http://127.0.0.1:9999", + "http://127.0.0.1:9999", + ]); + expect(runtimeMock.state.authHeaders).toEqual([ + `Basic ${btoa("opencode:secret-password")}`, + `Basic ${btoa("opencode:secret-password")}`, + ]); - expect(runtimeMock.state.startCalls).toEqual([]); - expect(runtimeMock.state.promptUrls).toEqual([ - "http://127.0.0.1:9999", - "http://127.0.0.1:9999", - ]); - expect(runtimeMock.state.authHeaders).toEqual([ - `Basic ${btoa("opencode:secret-password")}`, - `Basic ${btoa("opencode:secret-password")}`, - ]); + yield* advanceIdleClock; - yield* advanceIdleClock; - - expect(runtimeMock.state.closeCalls).toEqual([]); - }).pipe(Effect.provide(TestClock.layer())), + expect(runtimeMock.state.closeCalls).toEqual([]); + }), + ).pipe(Effect.provide(TestClock.layer())), ); }, ); diff --git a/apps/server/src/git/Layers/OpenCodeTextGeneration.ts b/apps/server/src/git/Layers/OpenCodeTextGeneration.ts index d9ebb094e7..f2d0b4b272 100644 --- a/apps/server/src/git/Layers/OpenCodeTextGeneration.ts +++ b/apps/server/src/git/Layers/OpenCodeTextGeneration.ts @@ -1,24 +1,24 @@ -import { Effect, Exit, Fiber, Layer, Schema, Scope } from "effect"; +import { Effect, Exit, Fiber, Schema, Scope } from "effect"; import * as Semaphore from "effect/Semaphore"; import { TextGenerationError, type ChatAttachment, - type OpenCodeModelSelection, + type ModelSelection, + type OpenCodeSettings, } from "@t3tools/contracts"; import { sanitizeBranchFragment, sanitizeFeatureBranchName } from "@t3tools/shared/git"; import { getModelSelectionStringOptionValue } from "@t3tools/shared/model"; import { ServerConfig } from "../../config.ts"; import { resolveAttachmentPath } from "../../attachmentStore.ts"; -import { ServerSettingsService } from "../../serverSettings.ts"; import { buildBranchNamePrompt, buildCommitMessagePrompt, buildPrContentPrompt, buildThreadTitlePrompt, } from "../Prompts.ts"; -import { type TextGenerationShape, TextGeneration } from "../Services/TextGeneration.ts"; +import { type TextGenerationShape } from "../Services/TextGeneration.ts"; import { extractJsonObject, sanitizeCommitSubject, @@ -93,9 +93,11 @@ interface SharedOpenCodeTextGenerationServerState { idleCloseFiber: Fiber.Fiber | null; } -const makeOpenCodeTextGeneration = Effect.gen(function* () { +export const makeOpenCodeTextGeneration = Effect.fn("makeOpenCodeTextGeneration")(function* ( + openCodeSettings: OpenCodeSettings, + environment: NodeJS.ProcessEnv = process.env, +) { const serverConfig = yield* ServerConfig; - const serverSettingsService = yield* ServerSettingsService; const openCodeRuntime = yield* OpenCodeRuntime; const idleFiberScope = yield* Effect.acquireRelease(Scope.make(), (scope) => Scope.close(scope, Exit.void), @@ -202,6 +204,7 @@ const makeOpenCodeTextGeneration = Effect.gen(function* () { openCodeRuntime .startOpenCodeServerProcess({ binaryPath: input.binaryPath, + environment, }) .pipe( Effect.provideService(Scope.Scope, serverScope), @@ -267,7 +270,7 @@ const makeOpenCodeTextGeneration = Effect.gen(function* () { readonly cwd: string; readonly prompt: string; readonly outputSchemaJson: S; - readonly modelSelection: OpenCodeModelSelection; + readonly modelSelection: ModelSelection; readonly attachments?: ReadonlyArray | undefined; }) { const parsedModel = parseOpenCodeModelSlug(input.modelSelection.model); @@ -278,26 +281,6 @@ const makeOpenCodeTextGeneration = Effect.gen(function* () { }); } - const settings = yield* serverSettingsService.getSettings.pipe( - Effect.map( - (value) => - value.providers?.opencode ?? { - enabled: true, - binaryPath: "opencode", - serverUrl: "", - serverPassword: "", - customModels: [], - }, - ), - Effect.orElseSucceed(() => ({ - enabled: true, - binaryPath: "opencode", - serverUrl: "", - serverPassword: "", - customModels: [], - })), - ); - const fileParts = toOpenCodeFileParts({ attachments: input.attachments, resolveAttachmentPath: (attachment) => @@ -310,8 +293,8 @@ const makeOpenCodeTextGeneration = Effect.gen(function* () { const client = openCodeRuntime.createOpenCodeSdkClient({ baseUrl: server.url, directory: input.cwd, - ...(settings.serverUrl.length > 0 && settings.serverPassword - ? { serverPassword: settings.serverPassword } + ...(openCodeSettings.serverUrl.length > 0 && openCodeSettings.serverPassword + ? { serverPassword: openCodeSettings.serverPassword } : {}), }); const session = await client.session.create({ @@ -354,11 +337,11 @@ const makeOpenCodeTextGeneration = Effect.gen(function* () { }); const rawOutput = - settings.serverUrl.length > 0 - ? yield* runAgainstServer({ url: settings.serverUrl }) + openCodeSettings.serverUrl.length > 0 + ? yield* runAgainstServer({ url: openCodeSettings.serverUrl }) : yield* Effect.acquireUseRelease( acquireSharedServer({ - binaryPath: settings.binaryPath, + binaryPath: openCodeSettings.binaryPath, operation: input.operation, }), runAgainstServer, @@ -383,13 +366,6 @@ const makeOpenCodeTextGeneration = Effect.gen(function* () { const generateCommitMessage: TextGenerationShape["generateCommitMessage"] = Effect.fn( "OpenCodeTextGeneration.generateCommitMessage", )(function* (input) { - if (input.modelSelection.provider !== "opencode") { - return yield* new TextGenerationError({ - operation: "generateCommitMessage", - detail: "Invalid model selection.", - }); - } - const { prompt, outputSchema } = buildCommitMessagePrompt({ branch: input.branch, stagedSummary: input.stagedSummary, @@ -416,13 +392,6 @@ const makeOpenCodeTextGeneration = Effect.gen(function* () { const generatePrContent: TextGenerationShape["generatePrContent"] = Effect.fn( "OpenCodeTextGeneration.generatePrContent", )(function* (input) { - if (input.modelSelection.provider !== "opencode") { - return yield* new TextGenerationError({ - operation: "generatePrContent", - detail: "Invalid model selection.", - }); - } - const { prompt, outputSchema } = buildPrContentPrompt({ baseBranch: input.baseBranch, headBranch: input.headBranch, @@ -447,13 +416,6 @@ const makeOpenCodeTextGeneration = Effect.gen(function* () { const generateBranchName: TextGenerationShape["generateBranchName"] = Effect.fn( "OpenCodeTextGeneration.generateBranchName", )(function* (input) { - if (input.modelSelection.provider !== "opencode") { - return yield* new TextGenerationError({ - operation: "generateBranchName", - detail: "Invalid model selection.", - }); - } - const { prompt, outputSchema } = buildBranchNamePrompt({ message: input.message, attachments: input.attachments, @@ -475,13 +437,6 @@ const makeOpenCodeTextGeneration = Effect.gen(function* () { const generateThreadTitle: TextGenerationShape["generateThreadTitle"] = Effect.fn( "OpenCodeTextGeneration.generateThreadTitle", )(function* (input) { - if (input.modelSelection.provider !== "opencode") { - return yield* new TextGenerationError({ - operation: "generateThreadTitle", - detail: "Invalid model selection.", - }); - } - const { prompt, outputSchema } = buildThreadTitlePrompt({ message: input.message, attachments: input.attachments, @@ -507,5 +462,3 @@ const makeOpenCodeTextGeneration = Effect.gen(function* () { generateThreadTitle, } satisfies TextGenerationShape; }); - -export const OpenCodeTextGenerationLive = Layer.effect(TextGeneration, makeOpenCodeTextGeneration); diff --git a/apps/server/src/git/Layers/RoutingTextGeneration.ts b/apps/server/src/git/Layers/RoutingTextGeneration.ts deleted file mode 100644 index 873d616f39..0000000000 --- a/apps/server/src/git/Layers/RoutingTextGeneration.ts +++ /dev/null @@ -1,104 +0,0 @@ -/** - * RoutingTextGeneration – Dispatches text generation requests to either the - * Codex CLI or Claude CLI implementation based on the provider in each - * request input. - * - * When `modelSelection.provider` is `"claudeAgent"` the request is forwarded to - * the Claude layer; for any other value (including the default `undefined`) it - * falls through to the Codex layer. - * - * @module RoutingTextGeneration - */ -import { Effect, Layer, Context } from "effect"; - -import { TextGeneration, type TextGenerationShape } from "../Services/TextGeneration.ts"; -import { CodexTextGenerationLive } from "./CodexTextGeneration.ts"; -import { ClaudeTextGenerationLive } from "./ClaudeTextGeneration.ts"; -import { CursorTextGenerationLive } from "./CursorTextGeneration.ts"; -import { OpenCodeTextGenerationLive } from "./OpenCodeTextGeneration.ts"; - -// --------------------------------------------------------------------------- -// Internal service tags so both concrete layers can coexist. -// --------------------------------------------------------------------------- - -class CodexTextGen extends Context.Service()( - "t3/git/Layers/RoutingTextGeneration/CodexTextGen", -) {} - -class ClaudeTextGen extends Context.Service()( - "t3/git/Layers/RoutingTextGeneration/ClaudeTextGen", -) {} - -class CursorTextGen extends Context.Service()( - "t3/git/Layers/RoutingTextGeneration/CursorTextGen", -) {} - -class OpenCodeTextGen extends Context.Service()( - "t3/git/Layers/RoutingTextGeneration/OpenCodeTextGen", -) {} - -// --------------------------------------------------------------------------- -// Routing implementation -// --------------------------------------------------------------------------- - -const makeRoutingTextGeneration = Effect.gen(function* () { - const byProvider = { - codex: yield* CodexTextGen, - claudeAgent: yield* ClaudeTextGen, - cursor: yield* CursorTextGen, - opencode: yield* OpenCodeTextGen, - }; - - return { - generateCommitMessage: (input) => - byProvider[input.modelSelection.provider].generateCommitMessage(input), - generatePrContent: (input) => - byProvider[input.modelSelection.provider].generatePrContent(input), - generateBranchName: (input) => - byProvider[input.modelSelection.provider].generateBranchName(input), - generateThreadTitle: (input) => - byProvider[input.modelSelection.provider].generateThreadTitle(input), - } satisfies TextGenerationShape; -}); - -const InternalCodexLayer = Layer.effect( - CodexTextGen, - Effect.gen(function* () { - const svc = yield* TextGeneration; - return svc; - }), -).pipe(Layer.provide(CodexTextGenerationLive)); - -const InternalClaudeLayer = Layer.effect( - ClaudeTextGen, - Effect.gen(function* () { - const svc = yield* TextGeneration; - return svc; - }), -).pipe(Layer.provide(ClaudeTextGenerationLive)); - -const InternalCursorLayer = Layer.effect( - CursorTextGen, - Effect.gen(function* () { - const svc = yield* TextGeneration; - return svc; - }), -).pipe(Layer.provide(CursorTextGenerationLive)); - -const InternalOpenCodeLayer = Layer.effect( - OpenCodeTextGen, - Effect.gen(function* () { - const svc = yield* TextGeneration; - return svc; - }), -).pipe(Layer.provide(OpenCodeTextGenerationLive)); - -export const RoutingTextGenerationLive = Layer.effect( - TextGeneration, - makeRoutingTextGeneration, -).pipe( - Layer.provide(InternalCodexLayer), - Layer.provide(InternalClaudeLayer), - Layer.provide(InternalCursorLayer), - Layer.provide(InternalOpenCodeLayer), -); diff --git a/apps/server/src/git/Layers/TextGenerationLive.test.ts b/apps/server/src/git/Layers/TextGenerationLive.test.ts new file mode 100644 index 0000000000..3b03696eb4 --- /dev/null +++ b/apps/server/src/git/Layers/TextGenerationLive.test.ts @@ -0,0 +1,117 @@ +import { it } from "@effect/vitest"; +import { Effect, PubSub, Result, Stream } from "effect"; +import { describe, expect } from "vitest"; + +import { ProviderInstanceId } from "@t3tools/contracts"; +import { createModelSelection } from "@t3tools/shared/model"; + +import type { ProviderInstance } from "../../provider/ProviderDriver.ts"; +import type { ProviderInstanceRegistryShape } from "../../provider/Services/ProviderInstanceRegistry.ts"; +import type { TextGenerationShape } from "../Services/TextGeneration.ts"; + +import { makeTextGenerationFromRegistry } from "./TextGenerationLive.ts"; + +const makeStubTextGeneration = (overrides: Partial): TextGenerationShape => ({ + generateCommitMessage: () => + Effect.die("generateCommitMessage stub not configured for this test"), + generatePrContent: () => Effect.die("generatePrContent stub not configured for this test"), + generateBranchName: () => Effect.die("generateBranchName stub not configured for this test"), + generateThreadTitle: () => Effect.die("generateThreadTitle stub not configured for this test"), + ...overrides, +}); + +const makeStubInstance = ( + instanceId: ProviderInstanceId, + textGeneration: TextGenerationShape, +): ProviderInstance => + ({ + instanceId, + driverKind: instanceId as unknown as ProviderInstance["driverKind"], + continuationIdentity: { + driverKind: instanceId as unknown as ProviderInstance["driverKind"], + continuationKey: `${instanceId}:test`, + }, + displayName: undefined, + enabled: true, + snapshot: {} as ProviderInstance["snapshot"], + adapter: {} as ProviderInstance["adapter"], + textGeneration, + }) satisfies ProviderInstance; + +const makeStubRegistry = ( + instances: ReadonlyArray, +): ProviderInstanceRegistryShape => { + const byId = new Map(instances.map((instance) => [instance.instanceId, instance] as const)); + return { + getInstance: (id) => Effect.succeed(byId.get(id)), + listInstances: Effect.succeed(instances), + listUnavailable: Effect.succeed([]), + streamChanges: Stream.empty, + // Tests never drive changes through this stub; acquire a throwaway + // subscription on an unused PubSub so the shape is satisfied. + subscribeChanges: Effect.flatMap(PubSub.unbounded(), (pubsub) => + PubSub.subscribe(pubsub), + ), + }; +}; + +describe("makeTextGenerationFromRegistry", () => { + it.effect("delegates to the matching instance's textGeneration closure", () => + Effect.gen(function* () { + const personalId = ProviderInstanceId.make("codex_personal"); + const personalCalls: string[] = []; + const personal = makeStubInstance( + personalId, + makeStubTextGeneration({ + generateBranchName: (input) => { + personalCalls.push(input.message); + return Effect.succeed({ branch: "personal-branch" }); + }, + }), + ); + + const workId = ProviderInstanceId.make("codex_work"); + const work = makeStubInstance( + workId, + makeStubTextGeneration({ + generateBranchName: () => Effect.succeed({ branch: "work-branch" }), + }), + ); + + const tg = makeTextGenerationFromRegistry(makeStubRegistry([personal, work])); + + const result = yield* tg.generateBranchName({ + cwd: process.cwd(), + message: "Refactor the routing layer", + modelSelection: createModelSelection(ProviderInstanceId.make("codex_personal"), "gpt-5"), + }); + + expect(result.branch).toBe("personal-branch"); + expect(personalCalls).toEqual(["Refactor the routing layer"]); + }), + ); + + it.effect("fails with TextGenerationError when the instance is unknown", () => + Effect.gen(function* () { + const tg = makeTextGenerationFromRegistry(makeStubRegistry([])); + + const result = yield* tg + .generateBranchName({ + cwd: process.cwd(), + message: "anything", + modelSelection: createModelSelection( + ProviderInstanceId.make("missing_instance"), + "gpt-5", + ), + }) + .pipe(Effect.result); + + expect(Result.isFailure(result)).toBe(true); + if (Result.isFailure(result)) { + expect(result.failure._tag).toBe("TextGenerationError"); + expect(result.failure.operation).toBe("generateBranchName"); + expect(result.failure.detail).toContain("missing_instance"); + } + }), + ); +}); diff --git a/apps/server/src/git/Layers/TextGenerationLive.ts b/apps/server/src/git/Layers/TextGenerationLive.ts new file mode 100644 index 0000000000..58e1541d55 --- /dev/null +++ b/apps/server/src/git/Layers/TextGenerationLive.ts @@ -0,0 +1,101 @@ +/** + * TextGenerationLive — registry-backed implementation of the `TextGeneration` + * service tag. + * + * The `TextGeneration` tag is kept as a thin facade over + * `ProviderInstanceRegistry`. Every op pulls `modelSelection.instanceId`, + * looks up the matching `ProviderInstance`, and delegates to that instance's + * own `textGeneration` closure (built by its driver's `create()`). + * + * There is deliberately no per-driver dispatch here — the registry already + * knows which driver backs each instance, and each `ProviderInstance` + * carries the fully-bound `TextGenerationShape` produced by its driver. + * That means: + * + * - Multiple instances of the same driver (e.g. `codex_personal`, + * `codex_work`) each get their own text-generation closure bound to + * their own settings — the routing is by instance, not by driver. + * - Unknown or disabled instances surface a `TextGenerationError` with + * the missing `instanceId`, instead of silently falling back to a + * default. + * + * This replaces the old `RoutingTextGenerationLive`, which tried to route + * by driver-kind and misused `modelSelection.instanceId` as a driver-id + * literal. + * + * @module git/Layers/TextGenerationLive + */ +import { Effect, Layer } from "effect"; + +import { TextGenerationError } from "@t3tools/contracts"; +import type { ProviderInstanceId } from "@t3tools/contracts"; + +import { + ProviderInstanceRegistry, + type ProviderInstanceRegistryShape, +} from "../../provider/Services/ProviderInstanceRegistry.ts"; +import type { ProviderInstance } from "../../provider/ProviderDriver.ts"; +import { TextGeneration, type TextGenerationShape } from "../Services/TextGeneration.ts"; + +type TextGenerationOp = + | "generateCommitMessage" + | "generatePrContent" + | "generateBranchName" + | "generateThreadTitle"; + +const resolveInstance = ( + registry: ProviderInstanceRegistryShape, + operation: TextGenerationOp, + instanceId: ProviderInstanceId, +): Effect.Effect => + registry.getInstance(instanceId).pipe( + Effect.flatMap((instance) => + instance + ? Effect.succeed(instance.textGeneration) + : Effect.fail( + new TextGenerationError({ + operation, + detail: `No provider instance registered for id '${instanceId}'.`, + }), + ), + ), + ); + +/** + * Build a `TextGenerationShape` that routes every call through the + * registry. Exposed separately from the Layer so tests can construct it + * against a stub registry without layering gymnastics. + */ +export const makeTextGenerationFromRegistry = ( + registry: ProviderInstanceRegistryShape, +): TextGenerationShape => ({ + generateCommitMessage: (input) => + resolveInstance(registry, "generateCommitMessage", input.modelSelection.instanceId).pipe( + Effect.flatMap((tg) => tg.generateCommitMessage(input)), + ), + generatePrContent: (input) => + resolveInstance(registry, "generatePrContent", input.modelSelection.instanceId).pipe( + Effect.flatMap((tg) => tg.generatePrContent(input)), + ), + generateBranchName: (input) => + resolveInstance(registry, "generateBranchName", input.modelSelection.instanceId).pipe( + Effect.flatMap((tg) => tg.generateBranchName(input)), + ), + generateThreadTitle: (input) => + resolveInstance(registry, "generateThreadTitle", input.modelSelection.instanceId).pipe( + Effect.flatMap((tg) => tg.generateThreadTitle(input)), + ), +}); + +/** + * `TextGeneration` Layer wired to the `ProviderInstanceRegistry`. The rest + * of the server keeps using `yield* TextGeneration` — only the underlying + * wiring changed from kind-based routing to instance-based routing. + */ +export const TextGenerationLive = Layer.effect( + TextGeneration, + Effect.gen(function* () { + const registry = yield* ProviderInstanceRegistry; + return makeTextGenerationFromRegistry(registry); + }), +); diff --git a/apps/server/src/observability/Metrics.test.ts b/apps/server/src/observability/Metrics.test.ts index 4604f43b63..b5eeedaaa4 100644 --- a/apps/server/src/observability/Metrics.test.ts +++ b/apps/server/src/observability/Metrics.test.ts @@ -1,4 +1,5 @@ import { assert, describe, it } from "@effect/vitest"; +import { ProviderDriverKind } from "@t3tools/contracts"; import { Effect, Metric } from "effect"; import { withMetrics } from "./Metrics.ts"; @@ -75,10 +76,11 @@ describe("withMetrics", () => { Effect.gen(function* () { const counter = Metric.counter("with_metrics_lazy_total"); const timer = Metric.timer("with_metrics_lazy_duration"); - let provider = "unknown"; + let provider = ProviderDriverKind.make("unknown"); + const lazyInittedProvider = ProviderDriverKind.make("codex"); yield* Effect.sync(() => { - provider = "codex"; + provider = lazyInittedProvider; }).pipe( withMetrics({ counter, @@ -93,7 +95,7 @@ describe("withMetrics", () => { const snapshots = yield* Metric.snapshot; assert.equal( hasMetricSnapshot(snapshots, "with_metrics_lazy_total", { - provider: "codex", + provider: lazyInittedProvider, operation: "lazy", outcome: "success", }), @@ -101,7 +103,7 @@ describe("withMetrics", () => { ); assert.equal( hasMetricSnapshot(snapshots, "with_metrics_lazy_duration", { - provider: "codex", + provider: lazyInittedProvider, operation: "lazy", }), true, diff --git a/apps/server/src/orchestration/Layers/CheckpointReactor.test.ts b/apps/server/src/orchestration/Layers/CheckpointReactor.test.ts index 12e11450dd..5603ce6325 100644 --- a/apps/server/src/orchestration/Layers/CheckpointReactor.test.ts +++ b/apps/server/src/orchestration/Layers/CheckpointReactor.test.ts @@ -3,7 +3,12 @@ import os from "node:os"; import path from "node:path"; import { execFileSync } from "node:child_process"; -import type { ProviderKind, ProviderRuntimeEvent, ProviderSession } from "@t3tools/contracts"; +import { + ProviderDriverKind, + ProviderRuntimeEvent, + ProviderSession, + ProviderInstanceId, +} from "@t3tools/contracts"; import { CommandId, DEFAULT_PROVIDER_INTERACTION_MODE, @@ -50,7 +55,7 @@ const asTurnId = (value: string): TurnId => TurnId.make(value); type LegacyProviderRuntimeEvent = { readonly type: string; readonly eventId: EventId; - readonly provider: ProviderKind; + readonly provider: ProviderDriverKind; readonly createdAt: string; readonly threadId: ThreadId; readonly turnId?: string | undefined; @@ -64,7 +69,7 @@ function createProviderServiceHarness( cwd: string, hasSession = true, sessionCwd = cwd, - providerName: ProviderSession["provider"] = "codex", + providerName: ProviderSession["provider"] = ProviderDriverKind.make("codex"), ) { const now = new Date().toISOString(); const runtimeEventPubSub = Effect.runSync(PubSub.unbounded()); @@ -97,6 +102,17 @@ function createProviderServiceHarness( stopSession: () => unsupported(), listSessions, getCapabilities: () => Effect.succeed({ sessionModelSwitch: "in-session" }), + getInstanceInfo: (instanceId) => + Effect.succeed({ + instanceId, + driverKind: ProviderDriverKind.make(providerName), + displayName: undefined, + enabled: true, + continuationIdentity: { + driverKind: ProviderDriverKind.make(providerName), + continuationKey: `${providerName}:instance:${instanceId}`, + }, + }), rollbackConversation, get streamEvents() { return Stream.fromPubSub(runtimeEventPubSub); @@ -243,7 +259,7 @@ describe("CheckpointReactor", () => { readonly projectWorkspaceRoot?: string; readonly threadWorktreePath?: string | null; readonly providerSessionCwd?: string; - readonly providerName?: ProviderKind; + readonly providerName?: ProviderDriverKind; readonly gitStatusRefreshCalls?: Array; }) { const cwd = createGitRepository(); @@ -252,7 +268,7 @@ describe("CheckpointReactor", () => { cwd, options?.hasSession ?? true, options?.providerSessionCwd ?? cwd, - options?.providerName ?? "codex", + options?.providerName ?? ProviderDriverKind.make("codex"), ); const orchestrationLayer = OrchestrationEngineLive.pipe( Layer.provide(OrchestrationProjectionSnapshotQueryLive), @@ -315,7 +331,7 @@ describe("CheckpointReactor", () => { title: "Test Project", workspaceRoot: options?.projectWorkspaceRoot ?? cwd, defaultModelSelection: { - provider: "codex", + instanceId: ProviderInstanceId.make("codex"), model: "gpt-5-codex", }, createdAt, @@ -329,7 +345,7 @@ describe("CheckpointReactor", () => { projectId: asProjectId("project-1"), title: "Thread", modelSelection: { - provider: "codex", + instanceId: ProviderInstanceId.make("codex"), model: "gpt-5-codex", }, interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE, @@ -396,7 +412,7 @@ describe("CheckpointReactor", () => { harness.provider.emit({ type: "turn.started", eventId: EventId.make("evt-turn-started-1"), - provider: "codex", + provider: ProviderDriverKind.make("codex"), createdAt: new Date().toISOString(), threadId: ThreadId.make("thread-1"), @@ -411,7 +427,7 @@ describe("CheckpointReactor", () => { harness.provider.emit({ type: "turn.completed", eventId: EventId.make("evt-turn-completed-1"), - provider: "codex", + provider: ProviderDriverKind.make("codex"), createdAt: new Date().toISOString(), threadId: ThreadId.make("thread-1"), @@ -457,7 +473,7 @@ describe("CheckpointReactor", () => { harness.provider.emit({ type: "turn.completed", eventId: EventId.make("evt-turn-completed-refresh-local-status"), - provider: "codex", + provider: ProviderDriverKind.make("codex"), createdAt: new Date().toISOString(), threadId: ThreadId.make("thread-1"), turnId: asTurnId("turn-refresh-local-status"), @@ -494,7 +510,7 @@ describe("CheckpointReactor", () => { harness.provider.emit({ type: "turn.started", eventId: EventId.make("evt-turn-started-main"), - provider: "codex", + provider: ProviderDriverKind.make("codex"), createdAt: new Date().toISOString(), threadId: ThreadId.make("thread-1"), @@ -510,7 +526,7 @@ describe("CheckpointReactor", () => { harness.provider.emit({ type: "turn.completed", eventId: EventId.make("evt-turn-completed-aux"), - provider: "codex", + provider: ProviderDriverKind.make("codex"), createdAt: new Date().toISOString(), threadId: ThreadId.make("thread-1"), @@ -526,7 +542,7 @@ describe("CheckpointReactor", () => { harness.provider.emit({ type: "turn.completed", eventId: EventId.make("evt-turn-completed-main"), - provider: "codex", + provider: ProviderDriverKind.make("codex"), createdAt: new Date().toISOString(), threadId: ThreadId.make("thread-1"), @@ -544,7 +560,7 @@ describe("CheckpointReactor", () => { it("captures pre-turn and completion checkpoints for claude runtime events", async () => { const harness = await createHarness({ seedFilesystemCheckpoints: false, - providerName: "claudeAgent", + providerName: ProviderDriverKind.make("claudeAgent"), }); const createdAt = new Date().toISOString(); @@ -569,7 +585,7 @@ describe("CheckpointReactor", () => { harness.provider.emit({ type: "turn.started", eventId: EventId.make("evt-turn-started-claude-1"), - provider: "claudeAgent", + provider: ProviderDriverKind.make("claudeAgent"), createdAt: new Date().toISOString(), threadId: ThreadId.make("thread-1"), turnId: asTurnId("turn-claude-1"), @@ -583,7 +599,7 @@ describe("CheckpointReactor", () => { harness.provider.emit({ type: "turn.completed", eventId: EventId.make("evt-turn-completed-claude-1"), - provider: "claudeAgent", + provider: ProviderDriverKind.make("claudeAgent"), createdAt: new Date().toISOString(), threadId: ThreadId.make("thread-1"), turnId: asTurnId("turn-claude-1"), @@ -627,7 +643,7 @@ describe("CheckpointReactor", () => { harness.provider.emit({ type: "turn.completed", eventId: EventId.make("evt-turn-completed-missing-baseline"), - provider: "codex", + provider: ProviderDriverKind.make("codex"), createdAt: new Date().toISOString(), threadId: ThreadId.make("thread-1"), @@ -716,7 +732,7 @@ describe("CheckpointReactor", () => { harness.provider.emit({ type: "turn.completed", eventId: EventId.make("evt-turn-completed-missing-provider-cwd"), - provider: "codex", + provider: ProviderDriverKind.make("codex"), createdAt: new Date().toISOString(), threadId: ThreadId.make("thread-1"), @@ -762,7 +778,7 @@ describe("CheckpointReactor", () => { harness.provider.emit({ type: "checkpoint.captured", eventId: EventId.make("evt-checkpoint-captured-3"), - provider: "codex", + provider: ProviderDriverKind.make("codex"), createdAt: new Date().toISOString(), threadId: ThreadId.make("thread-1"), @@ -812,7 +828,7 @@ describe("CheckpointReactor", () => { harness.provider.emit({ type: "turn.completed", eventId: EventId.make("evt-runtime-capture-failure"), - provider: "codex", + provider: ProviderDriverKind.make("codex"), createdAt: new Date().toISOString(), threadId: ThreadId.make("thread-1"), @@ -823,7 +839,7 @@ describe("CheckpointReactor", () => { harness.provider.emit({ type: "turn.started", eventId: EventId.make("evt-turn-started-after-runtime-failure"), - provider: "codex", + provider: ProviderDriverKind.make("codex"), createdAt: new Date().toISOString(), threadId: ThreadId.make("thread-1"), @@ -918,7 +934,7 @@ describe("CheckpointReactor", () => { }); it("executes provider revert and emits thread.reverted for claude sessions", async () => { - const harness = await createHarness({ providerName: "claudeAgent" }); + const harness = await createHarness({ providerName: ProviderDriverKind.make("claudeAgent") }); const createdAt = new Date().toISOString(); await Effect.runPromise( diff --git a/apps/server/src/orchestration/Layers/OrchestrationEngine.test.ts b/apps/server/src/orchestration/Layers/OrchestrationEngine.test.ts index b61664f161..0af5b099a6 100644 --- a/apps/server/src/orchestration/Layers/OrchestrationEngine.test.ts +++ b/apps/server/src/orchestration/Layers/OrchestrationEngine.test.ts @@ -7,6 +7,7 @@ import { ThreadId, TurnId, type OrchestrationEvent, + ProviderInstanceId, } from "@t3tools/contracts"; import { Effect, Layer, ManagedRuntime, Metric, Option, Queue, Stream } from "effect"; import { describe, expect, it } from "vitest"; @@ -104,7 +105,7 @@ describe("OrchestrationEngine", () => { title: "Bootstrap Project", workspaceRoot: "/tmp/project-bootstrap", defaultModelSelection: { - provider: "codex" as const, + instanceId: ProviderInstanceId.make("codex"), model: "gpt-5-codex", }, scripts: [], @@ -119,7 +120,7 @@ describe("OrchestrationEngine", () => { projectId: asProjectId("project-bootstrap"), title: "Bootstrap Thread", modelSelection: { - provider: "codex" as const, + instanceId: ProviderInstanceId.make("codex"), model: "gpt-5-codex", }, interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE, @@ -198,7 +199,7 @@ describe("OrchestrationEngine", () => { title: "Project 1", workspaceRoot: "/tmp/project-1", defaultModelSelection: { - provider: "codex", + instanceId: ProviderInstanceId.make("codex"), model: "gpt-5-codex", }, createdAt, @@ -212,7 +213,7 @@ describe("OrchestrationEngine", () => { projectId: asProjectId("project-1"), title: "Thread", modelSelection: { - provider: "codex", + instanceId: ProviderInstanceId.make("codex"), model: "gpt-5-codex", }, interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE, @@ -258,7 +259,7 @@ describe("OrchestrationEngine", () => { title: "Project Archive", workspaceRoot: "/tmp/project-archive", defaultModelSelection: { - provider: "codex", + instanceId: ProviderInstanceId.make("codex"), model: "gpt-5-codex", }, createdAt, @@ -272,7 +273,7 @@ describe("OrchestrationEngine", () => { projectId: asProjectId("project-archive"), title: "Archive me", modelSelection: { - provider: "codex", + instanceId: ProviderInstanceId.make("codex"), model: "gpt-5-codex", }, interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE, @@ -325,7 +326,7 @@ describe("OrchestrationEngine", () => { title: "Replay Project", workspaceRoot: "/tmp/project-replay", defaultModelSelection: { - provider: "codex", + instanceId: ProviderInstanceId.make("codex"), model: "gpt-5-codex", }, createdAt, @@ -339,7 +340,7 @@ describe("OrchestrationEngine", () => { projectId: asProjectId("project-replay"), title: "replay", modelSelection: { - provider: "codex", + instanceId: ProviderInstanceId.make("codex"), model: "gpt-5-codex", }, interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE, @@ -383,7 +384,7 @@ describe("OrchestrationEngine", () => { title: "Stream Project", workspaceRoot: "/tmp/project-stream", defaultModelSelection: { - provider: "codex", + instanceId: ProviderInstanceId.make("codex"), model: "gpt-5-codex", }, createdAt, @@ -407,7 +408,7 @@ describe("OrchestrationEngine", () => { projectId: asProjectId("project-stream"), title: "domain-stream", modelSelection: { - provider: "codex", + instanceId: ProviderInstanceId.make("codex"), model: "gpt-5-codex", }, interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE, @@ -444,7 +445,7 @@ describe("OrchestrationEngine", () => { title: "Ack Project", workspaceRoot: "/tmp/project-ack", defaultModelSelection: { - provider: "codex", + instanceId: ProviderInstanceId.make("codex"), model: "gpt-5-codex", }, createdAt, @@ -459,7 +460,7 @@ describe("OrchestrationEngine", () => { projectId: asProjectId("project-ack"), title: "Ack Thread", modelSelection: { - provider: "codex", + instanceId: ProviderInstanceId.make("codex"), model: "gpt-5-codex", }, interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE, @@ -496,7 +497,7 @@ describe("OrchestrationEngine", () => { projectId: asProjectId("project-missing"), title: "Missing Project Thread", modelSelection: { - provider: "codex", + instanceId: ProviderInstanceId.make("codex"), model: "gpt-5-codex", }, interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE, @@ -533,7 +534,7 @@ describe("OrchestrationEngine", () => { title: "Turn Diff Project", workspaceRoot: "/tmp/project-turn-diff", defaultModelSelection: { - provider: "codex", + instanceId: ProviderInstanceId.make("codex"), model: "gpt-5-codex", }, createdAt, @@ -547,7 +548,7 @@ describe("OrchestrationEngine", () => { projectId: asProjectId("project-turn-diff"), title: "Turn diff thread", modelSelection: { - provider: "codex", + instanceId: ProviderInstanceId.make("codex"), model: "gpt-5-codex", }, interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE, @@ -652,7 +653,7 @@ describe("OrchestrationEngine", () => { title: "Flaky Project", workspaceRoot: "/tmp/project-flaky", defaultModelSelection: { - provider: "codex", + instanceId: ProviderInstanceId.make("codex"), model: "gpt-5-codex", }, createdAt, @@ -668,7 +669,7 @@ describe("OrchestrationEngine", () => { projectId: asProjectId("project-flaky"), title: "flaky-fail", modelSelection: { - provider: "codex", + instanceId: ProviderInstanceId.make("codex"), model: "gpt-5-codex", }, interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE, @@ -688,7 +689,7 @@ describe("OrchestrationEngine", () => { projectId: asProjectId("project-flaky"), title: "flaky-ok", modelSelection: { - provider: "codex", + instanceId: ProviderInstanceId.make("codex"), model: "gpt-5-codex", }, interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE, @@ -747,7 +748,7 @@ describe("OrchestrationEngine", () => { title: "Atomic Project", workspaceRoot: "/tmp/project-atomic", defaultModelSelection: { - provider: "codex", + instanceId: ProviderInstanceId.make("codex"), model: "gpt-5-codex", }, createdAt, @@ -761,7 +762,7 @@ describe("OrchestrationEngine", () => { projectId: asProjectId("project-atomic"), title: "atomic", modelSelection: { - provider: "codex", + instanceId: ProviderInstanceId.make("codex"), model: "gpt-5-codex", }, interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE, @@ -890,7 +891,7 @@ describe("OrchestrationEngine", () => { title: "Sync Project", workspaceRoot: "/tmp/project-sync", defaultModelSelection: { - provider: "codex", + instanceId: ProviderInstanceId.make("codex"), model: "gpt-5-codex", }, createdAt, @@ -904,7 +905,7 @@ describe("OrchestrationEngine", () => { projectId: asProjectId("project-sync"), title: "sync-before", modelSelection: { - provider: "codex", + instanceId: ProviderInstanceId.make("codex"), model: "gpt-5-codex", }, interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE, @@ -975,7 +976,7 @@ describe("OrchestrationEngine", () => { title: "Duplicate Project", workspaceRoot: "/tmp/project-duplicate", defaultModelSelection: { - provider: "codex", + instanceId: ProviderInstanceId.make("codex"), model: "gpt-5-codex", }, createdAt, @@ -990,7 +991,7 @@ describe("OrchestrationEngine", () => { projectId: asProjectId("project-duplicate"), title: "duplicate", modelSelection: { - provider: "codex", + instanceId: ProviderInstanceId.make("codex"), model: "gpt-5-codex", }, interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE, @@ -1010,7 +1011,7 @@ describe("OrchestrationEngine", () => { projectId: asProjectId("project-duplicate"), title: "duplicate", modelSelection: { - provider: "codex", + instanceId: ProviderInstanceId.make("codex"), model: "gpt-5-codex", }, interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE, diff --git a/apps/server/src/orchestration/Layers/ProjectionPipeline.test.ts b/apps/server/src/orchestration/Layers/ProjectionPipeline.test.ts index 7a08765647..7f364c717a 100644 --- a/apps/server/src/orchestration/Layers/ProjectionPipeline.test.ts +++ b/apps/server/src/orchestration/Layers/ProjectionPipeline.test.ts @@ -7,6 +7,7 @@ import { ProjectId, ThreadId, TurnId, + ProviderInstanceId, } from "@t3tools/contracts"; import * as NodeServices from "@effect/platform-node/NodeServices"; import { assert, it } from "@effect/vitest"; @@ -92,7 +93,7 @@ it.layer(BaseTestLayer)("OrchestrationProjectionPipeline", (it) => { projectId: ProjectId.make("project-1"), title: "Thread 1", modelSelection: { - provider: "codex", + instanceId: ProviderInstanceId.make("codex"), model: "gpt-5-codex", }, runtimeMode: "full-access", @@ -364,7 +365,7 @@ it.layer(BaseTestLayer)("OrchestrationProjectionPipeline", (it) => { projectId: ProjectId.make("project-clear-attachments"), title: "Thread Clear Attachments", modelSelection: { - provider: "codex", + instanceId: ProviderInstanceId.make("codex"), model: "gpt-5-codex", }, runtimeMode: "full-access", @@ -492,7 +493,7 @@ it.layer( projectId: ProjectId.make("project-overwrite"), title: "Thread Overwrite", modelSelection: { - provider: "codex", + instanceId: ProviderInstanceId.make("codex"), model: "gpt-5-codex", }, runtimeMode: "full-access", @@ -640,7 +641,7 @@ it.layer( projectId: ProjectId.make("project-rollback"), title: "Thread Rollback", modelSelection: { - provider: "codex", + instanceId: ProviderInstanceId.make("codex"), model: "gpt-5-codex", }, runtimeMode: "full-access", @@ -769,7 +770,7 @@ it.layer( projectId: ProjectId.make("project-revert-files"), title: "Thread Revert Files", modelSelection: { - provider: "codex", + instanceId: ProviderInstanceId.make("codex"), model: "gpt-5-codex", }, runtimeMode: "full-access", @@ -977,7 +978,7 @@ it.layer(Layer.fresh(makeProjectionPipelinePrefixedTestLayer("t3-projection-atta projectId: ProjectId.make("project-delete-files"), title: "Thread Delete Files", modelSelection: { - provider: "codex", + instanceId: ProviderInstanceId.make("codex"), model: "gpt-5-codex", }, runtimeMode: "full-access", @@ -1140,7 +1141,7 @@ it.layer(BaseTestLayer)("OrchestrationProjectionPipeline", (it) => { projectId: ProjectId.make("project-a"), title: "Thread A", modelSelection: { - provider: "codex", + instanceId: ProviderInstanceId.make("codex"), model: "gpt-5-codex", }, runtimeMode: "full-access", @@ -1267,7 +1268,7 @@ it.layer(BaseTestLayer)("OrchestrationProjectionPipeline", (it) => { projectId: ProjectId.make("project-empty"), title: "Thread Empty", modelSelection: { - provider: "codex", + instanceId: ProviderInstanceId.make("codex"), model: "gpt-5-codex", }, runtimeMode: "full-access", @@ -1407,7 +1408,7 @@ it.layer(BaseTestLayer)("OrchestrationProjectionPipeline", (it) => { projectId: ProjectId.make("project-conflict"), title: "Thread Conflict", modelSelection: { - provider: "codex", + instanceId: ProviderInstanceId.make("codex"), model: "gpt-5-codex", }, runtimeMode: "full-access", @@ -1551,7 +1552,7 @@ it.layer(BaseTestLayer)("OrchestrationProjectionPipeline", (it) => { projectId: ProjectId.make("project-stale-approval"), title: "Thread Stale Approval", modelSelection: { - provider: "codex", + instanceId: ProviderInstanceId.make("codex"), model: "gpt-5-codex", }, runtimeMode: "approval-required", @@ -1694,7 +1695,7 @@ it.layer(BaseTestLayer)("OrchestrationProjectionPipeline", (it) => { projectId: ProjectId.make("project-nonstale-approval"), title: "Thread Non-Stale Approval", modelSelection: { - provider: "codex", + instanceId: ProviderInstanceId.make("codex"), model: "gpt-5-codex", }, runtimeMode: "approval-required", @@ -1874,7 +1875,7 @@ it.layer(BaseTestLayer)("OrchestrationProjectionPipeline", (it) => { projectId: ProjectId.make("project-revert"), title: "Thread Revert", modelSelection: { - provider: "codex", + instanceId: ProviderInstanceId.make("codex"), model: "gpt-5-codex", }, runtimeMode: "full-access", @@ -2195,7 +2196,7 @@ engineLayer("OrchestrationProjectionPipeline via engine dispatch", (it) => { title: "Live Project", workspaceRoot: "/tmp/project-live", defaultModelSelection: { - provider: "codex", + instanceId: ProviderInstanceId.make("codex"), model: "gpt-5-codex", }, createdAt, @@ -2233,7 +2234,7 @@ engineLayer("OrchestrationProjectionPipeline via engine dispatch", (it) => { title: "Scripts Project", workspaceRoot: "/tmp/project-scripts", defaultModelSelection: { - provider: "codex", + instanceId: ProviderInstanceId.make("codex"), model: "gpt-5-codex", }, createdAt, @@ -2253,7 +2254,7 @@ engineLayer("OrchestrationProjectionPipeline via engine dispatch", (it) => { }, ], defaultModelSelection: { - provider: "codex", + instanceId: ProviderInstanceId.make("codex"), model: "gpt-5", }, }); @@ -2272,7 +2273,7 @@ engineLayer("OrchestrationProjectionPipeline via engine dispatch", (it) => { { scriptsJson: '[{"id":"script-1","name":"Build","command":"bun run build","icon":"build","runOnWorktreeCreate":false}]', - defaultModelSelection: '{"provider":"codex","model":"gpt-5"}', + defaultModelSelection: '{"instanceId":"codex","model":"gpt-5"}', }, ]); }), diff --git a/apps/server/src/orchestration/Layers/ProjectionPipeline.ts b/apps/server/src/orchestration/Layers/ProjectionPipeline.ts index d981ae0da6..28a0208e75 100644 --- a/apps/server/src/orchestration/Layers/ProjectionPipeline.ts +++ b/apps/server/src/orchestration/Layers/ProjectionPipeline.ts @@ -945,6 +945,7 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti threadId: event.payload.threadId, status: event.payload.session.status, providerName: event.payload.session.providerName, + providerInstanceId: event.payload.session.providerInstanceId ?? null, runtimeMode: event.payload.session.runtimeMode, activeTurnId: event.payload.session.activeTurnId, lastError: event.payload.session.lastError, diff --git a/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.test.ts b/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.test.ts index 9f0d63545f..cba5ce7e83 100644 --- a/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.test.ts +++ b/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.test.ts @@ -1,4 +1,12 @@ -import { CheckpointRef, EventId, MessageId, ProjectId, ThreadId, TurnId } from "@t3tools/contracts"; +import { + CheckpointRef, + EventId, + MessageId, + ProjectId, + ThreadId, + TurnId, + ProviderInstanceId, +} from "@t3tools/contracts"; import { assert, it } from "@effect/vitest"; import { Effect, Layer } from "effect"; import * as SqlClient from "effect/unstable/sql/SqlClient"; @@ -252,7 +260,7 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => { workspaceRoot: "/tmp/project-1", repositoryIdentity: null, defaultModelSelection: { - provider: "codex", + instanceId: ProviderInstanceId.make("codex"), model: "gpt-5-codex", }, scripts: [ @@ -275,7 +283,7 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => { projectId: asProjectId("project-1"), title: "Thread 1", modelSelection: { - provider: "codex", + instanceId: ProviderInstanceId.make("codex"), model: "gpt-5-codex", }, interactionMode: "default", @@ -363,7 +371,7 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => { workspaceRoot: "/tmp/project-1", repositoryIdentity: null, defaultModelSelection: { - provider: "codex", + instanceId: ProviderInstanceId.make("codex"), model: "gpt-5-codex", }, scripts: [ @@ -385,7 +393,7 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => { projectId: asProjectId("project-1"), title: "Thread 1", modelSelection: { - provider: "codex", + instanceId: ProviderInstanceId.make("codex"), model: "gpt-5-codex", }, interactionMode: "default", diff --git a/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.ts b/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.ts index 07645571ba..59a396c926 100644 --- a/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.ts +++ b/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.ts @@ -195,6 +195,7 @@ function mapSessionRow( threadId: row.threadId, status: row.status, providerName: row.providerName, + ...(row.providerInstanceId !== null ? { providerInstanceId: row.providerInstanceId } : {}), runtimeMode: row.runtimeMode, activeTurnId: row.activeTurnId, lastError: row.lastError, @@ -350,6 +351,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () { thread_id AS "threadId", status, provider_name AS "providerName", + provider_instance_id AS "providerInstanceId", provider_session_id AS "providerSessionId", provider_thread_id AS "providerThreadId", runtime_mode AS "runtimeMode", @@ -608,6 +610,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () { thread_id AS "threadId", status, provider_name AS "providerName", + provider_instance_id AS "providerInstanceId", runtime_mode AS "runtimeMode", active_turn_id AS "activeTurnId", last_error AS "lastError", @@ -879,6 +882,9 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () { threadId: row.threadId, status: row.status, providerName: row.providerName, + ...(row.providerInstanceId !== null + ? { providerInstanceId: row.providerInstanceId } + : {}), runtimeMode: row.runtimeMode, activeTurnId: row.activeTurnId, lastError: row.lastError, diff --git a/apps/server/src/orchestration/Layers/ProviderCommandReactor.test.ts b/apps/server/src/orchestration/Layers/ProviderCommandReactor.test.ts index 80f571285d..c44f291504 100644 --- a/apps/server/src/orchestration/Layers/ProviderCommandReactor.test.ts +++ b/apps/server/src/orchestration/Layers/ProviderCommandReactor.test.ts @@ -2,7 +2,13 @@ import fs from "node:fs"; import os from "node:os"; import path from "node:path"; -import type { ModelSelection, ProviderRuntimeEvent, ProviderSession } from "@t3tools/contracts"; +import { + ModelSelection, + ProviderRuntimeEvent, + ProviderSession, + ProviderDriverKind, + ProviderInstanceId, +} from "@t3tools/contracts"; import { createModelSelection } from "@t3tools/shared/model"; import { ApprovalRequestId, @@ -37,7 +43,11 @@ import { RepositoryIdentityResolverLive } from "../../project/Layers/RepositoryI import { OrchestrationEngineLive } from "./OrchestrationEngine.ts"; import { OrchestrationProjectionPipelineLive } from "./ProjectionPipeline.ts"; import { OrchestrationProjectionSnapshotQueryLive } from "./ProjectionSnapshotQuery.ts"; -import { ProviderCommandReactorLive } from "./ProviderCommandReactor.ts"; +import { + providerErrorLabel, + providerErrorLabelFromInstanceHint, + ProviderCommandReactorLive, +} from "./ProviderCommandReactor.ts"; import { OrchestrationEngineService } from "../Services/OrchestrationEngine.ts"; import { ProviderCommandReactor } from "../Services/ProviderCommandReactor.ts"; import * as NodeServices from "@effect/platform-node/NodeServices"; @@ -98,6 +108,30 @@ describe("ProviderCommandReactor", () => { createdBaseDirs.clear(); }); + describe("provider error attribution", () => { + it("uses the current provider instance slug when current instance lookup fails", () => { + expect( + providerErrorLabelFromInstanceHint({ + instanceId: "codex_personal", + modelSelectionInstanceId: "codex", + sessionProvider: "codex", + }), + ).toBe("codex_personal"); + }); + + it("uses the desired provider instance slug when desired instance lookup fails", () => { + expect( + providerErrorLabelFromInstanceHint({ + instanceId: "claude_openrouter", + }), + ).toBe("claude_openrouter"); + }); + + it("uses the unknown driver kind when the resolved driver is not registered locally", () => { + expect(providerErrorLabel("third_party_driver")).toBe("third_party_driver"); + }); + }); + async function createHarness(input?: { readonly baseDir?: string; readonly threadModelSelection?: ModelSelection; @@ -112,7 +146,7 @@ describe("ProviderCommandReactor", () => { let nextSessionIndex = 1; const runtimeSessions: Array = []; const modelSelection = input?.threadModelSelection ?? { - provider: "codex", + instanceId: ProviderInstanceId.make("codex"), model: "gpt-5-codex", }; const startSession = vi.fn((_: unknown, input: unknown) => { @@ -128,8 +162,24 @@ describe("ProviderCommandReactor", () => { typeof input.threadId === "string" ? ThreadId.make(input.threadId) : ThreadId.make(`thread-${sessionIndex}`); + const inputModelSelection = + typeof input === "object" && input !== null && "modelSelection" in input + ? (input.modelSelection as ModelSelection | undefined) + : undefined; + const providerInstanceId = + typeof input === "object" && input !== null && "providerInstanceId" in input + ? (input.providerInstanceId as ProviderInstanceId | undefined) + : inputModelSelection?.instanceId; + const provider = + typeof input === "object" && + input !== null && + "provider" in input && + typeof input.provider === "string" + ? (input.provider as ProviderSession["provider"]) + : ProviderDriverKind.make(inputModelSelection?.instanceId ?? modelSelection.instanceId); const session: ProviderSession = { - provider: modelSelection.provider, + provider, + ...(providerInstanceId ? { providerInstanceId } : {}), status: "ready" as const, runtimeMode: typeof input === "object" && @@ -144,7 +194,9 @@ describe("ProviderCommandReactor", () => { typeof input.cwd === "string" ? { cwd: input.cwd } : {}), - ...(modelSelection.model !== undefined ? { model: modelSelection.model } : {}), + ...((inputModelSelection?.model ?? modelSelection.model) + ? { model: inputModelSelection?.model ?? modelSelection.model } + : {}), threadId, resumeCursor: resumeCursor ?? { opaque: `resume-${sessionIndex}` }, createdAt: now, @@ -236,6 +288,25 @@ describe("ProviderCommandReactor", () => { Effect.succeed({ sessionModelSwitch: input?.sessionModelSwitch ?? "in-session", }), + getInstanceInfo: (instanceId) => { + const raw = String(instanceId); + const driverKind = ProviderDriverKind.make( + raw.startsWith("claude") ? "claudeAgent" : raw.startsWith("codex") ? "codex" : raw, + ); + return Effect.succeed({ + instanceId, + driverKind, + displayName: undefined, + enabled: true, + continuationIdentity: { + driverKind, + continuationKey: + driverKind === ProviderDriverKind.make("codex") + ? "codex:home:/shared-codex" + : `${driverKind}:instance:${instanceId}`, + }, + }); + }, rollbackConversation: () => unsupported(), get streamEvents() { return Stream.fromPubSub(runtimeEventPubSub); @@ -320,6 +391,7 @@ describe("ProviderCommandReactor", () => { refreshStatus, generateBranchName, generateThreadTitle, + runtimeSessions, stateDir, drain, }; @@ -352,7 +424,7 @@ describe("ProviderCommandReactor", () => { expect(harness.startSession.mock.calls[0]?.[1]).toMatchObject({ cwd: "/tmp/provider-project", modelSelection: { - provider: "codex", + instanceId: ProviderInstanceId.make("codex"), model: "gpt-5-codex", }, runtimeMode: "approval-required", @@ -574,7 +646,7 @@ describe("ProviderCommandReactor", () => { text: "hello fast mode", attachments: [], }, - modelSelection: createModelSelection("codex", "gpt-5.3-codex", [ + modelSelection: createModelSelection(ProviderInstanceId.make("codex"), "gpt-5.3-codex", [ { id: "reasoningEffort", value: "high" }, { id: "fastMode", value: true }, ]), @@ -587,14 +659,14 @@ describe("ProviderCommandReactor", () => { await waitFor(() => harness.startSession.mock.calls.length === 1); await waitFor(() => harness.sendTurn.mock.calls.length === 1); expect(harness.startSession.mock.calls[0]?.[1]).toMatchObject({ - modelSelection: createModelSelection("codex", "gpt-5.3-codex", [ + modelSelection: createModelSelection(ProviderInstanceId.make("codex"), "gpt-5.3-codex", [ { id: "reasoningEffort", value: "high" }, { id: "fastMode", value: true }, ]), }); expect(harness.sendTurn.mock.calls[0]?.[0]).toMatchObject({ threadId: ThreadId.make("thread-1"), - modelSelection: createModelSelection("codex", "gpt-5.3-codex", [ + modelSelection: createModelSelection(ProviderInstanceId.make("codex"), "gpt-5.3-codex", [ { id: "reasoningEffort", value: "high" }, { id: "fastMode", value: true }, ]), @@ -603,7 +675,10 @@ describe("ProviderCommandReactor", () => { it("forwards claude effort options through session start and turn send", async () => { const harness = await createHarness({ - threadModelSelection: { provider: "claudeAgent", model: "claude-sonnet-4-6" }, + threadModelSelection: { + instanceId: ProviderInstanceId.make("claudeAgent"), + model: "claude-sonnet-4-6", + }, }); const now = new Date().toISOString(); @@ -618,9 +693,11 @@ describe("ProviderCommandReactor", () => { text: "hello with effort", attachments: [], }, - modelSelection: createModelSelection("claudeAgent", "claude-sonnet-4-6", [ - { id: "effort", value: "max" }, - ]), + modelSelection: createModelSelection( + ProviderInstanceId.make("claudeAgent"), + "claude-sonnet-4-6", + [{ id: "effort", value: "max" }], + ), interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE, runtimeMode: "approval-required", createdAt: now, @@ -630,21 +707,28 @@ describe("ProviderCommandReactor", () => { await waitFor(() => harness.startSession.mock.calls.length === 1); await waitFor(() => harness.sendTurn.mock.calls.length === 1); expect(harness.startSession.mock.calls[0]?.[1]).toMatchObject({ - modelSelection: createModelSelection("claudeAgent", "claude-sonnet-4-6", [ - { id: "effort", value: "max" }, - ]), + modelSelection: createModelSelection( + ProviderInstanceId.make("claudeAgent"), + "claude-sonnet-4-6", + [{ id: "effort", value: "max" }], + ), }); expect(harness.sendTurn.mock.calls[0]?.[0]).toMatchObject({ threadId: ThreadId.make("thread-1"), - modelSelection: createModelSelection("claudeAgent", "claude-sonnet-4-6", [ - { id: "effort", value: "max" }, - ]), + modelSelection: createModelSelection( + ProviderInstanceId.make("claudeAgent"), + "claude-sonnet-4-6", + [{ id: "effort", value: "max" }], + ), }); }); it("forwards claude fast mode options through session start and turn send", async () => { const harness = await createHarness({ - threadModelSelection: { provider: "claudeAgent", model: "claude-opus-4-6" }, + threadModelSelection: { + instanceId: ProviderInstanceId.make("claudeAgent"), + model: "claude-opus-4-6", + }, }); const now = new Date().toISOString(); @@ -659,9 +743,11 @@ describe("ProviderCommandReactor", () => { text: "hello with fast mode", attachments: [], }, - modelSelection: createModelSelection("claudeAgent", "claude-opus-4-6", [ - { id: "fastMode", value: true }, - ]), + modelSelection: createModelSelection( + ProviderInstanceId.make("claudeAgent"), + "claude-opus-4-6", + [{ id: "fastMode", value: true }], + ), interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE, runtimeMode: "approval-required", createdAt: now, @@ -671,15 +757,19 @@ describe("ProviderCommandReactor", () => { await waitFor(() => harness.startSession.mock.calls.length === 1); await waitFor(() => harness.sendTurn.mock.calls.length === 1); expect(harness.startSession.mock.calls[0]?.[1]).toMatchObject({ - modelSelection: createModelSelection("claudeAgent", "claude-opus-4-6", [ - { id: "fastMode", value: true }, - ]), + modelSelection: createModelSelection( + ProviderInstanceId.make("claudeAgent"), + "claude-opus-4-6", + [{ id: "fastMode", value: true }], + ), }); expect(harness.sendTurn.mock.calls[0]?.[0]).toMatchObject({ threadId: ThreadId.make("thread-1"), - modelSelection: createModelSelection("claudeAgent", "claude-opus-4-6", [ - { id: "fastMode", value: true }, - ]), + modelSelection: createModelSelection( + ProviderInstanceId.make("claudeAgent"), + "claude-opus-4-6", + [{ id: "fastMode", value: true }], + ), }); }); @@ -766,15 +856,15 @@ describe("ProviderCommandReactor", () => { expect(harness.sendTurn.mock.calls[1]?.[0]).toMatchObject({ threadId: ThreadId.make("thread-1"), modelSelection: { - provider: "codex", + instanceId: ProviderInstanceId.make("codex"), model: "gpt-5-codex", }, }); }); - it("rejects a first turn when requested provider conflicts with the thread model", async () => { + it("starts a first turn on the requested provider instance even when it differs from the thread model", async () => { const harness = await createHarness({ - threadModelSelection: { provider: "codex", model: "gpt-5-codex" }, + threadModelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5-codex" }, }); const now = new Date().toISOString(); @@ -790,7 +880,7 @@ describe("ProviderCommandReactor", () => { attachments: [], }, modelSelection: { - provider: "claudeAgent", + instanceId: ProviderInstanceId.make("claudeAgent"), model: "claude-opus-4-6", }, interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE, @@ -799,29 +889,25 @@ describe("ProviderCommandReactor", () => { }), ); - await waitFor(async () => { - const readModel = await Effect.runPromise(harness.engine.getReadModel()); - const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1")); - return ( - thread?.activities.some((activity) => activity.kind === "provider.turn.start.failed") ?? - false - ); - }); + await waitFor(() => harness.sendTurn.mock.calls.length === 1); - expect(harness.startSession).not.toHaveBeenCalled(); - expect(harness.sendTurn).not.toHaveBeenCalled(); + expect(harness.startSession).toHaveBeenCalledTimes(1); + expect(harness.startSession.mock.calls[0]?.[1]).toMatchObject({ + provider: ProviderDriverKind.make("claudeAgent"), + providerInstanceId: ProviderInstanceId.make("claudeAgent"), + modelSelection: { + instanceId: ProviderInstanceId.make("claudeAgent"), + model: "claude-opus-4-6", + }, + }); const readModel = await Effect.runPromise(harness.engine.getReadModel()); const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1")); - expect(thread?.session).toBeNull(); + expect(thread?.session?.providerName).toBe("claudeAgent"); + expect(thread?.session?.providerInstanceId).toBe(ProviderInstanceId.make("claudeAgent")); expect( thread?.activities.find((activity) => activity.kind === "provider.turn.start.failed"), - ).toMatchObject({ - summary: "Provider turn start failed", - payload: { - detail: expect.stringContaining("cannot switch to 'claudeAgent'"), - }, - }); + ).toBeUndefined(); }); it("reuses the same provider session when runtime mode is unchanged", async () => { @@ -870,9 +956,74 @@ describe("ProviderCommandReactor", () => { expect(harness.stopSession.mock.calls.length).toBe(0); }); + it("restarts an existing Codex thread on a compatible requested instance", async () => { + const harness = await createHarness(); + const now = new Date().toISOString(); + + await Effect.runPromise( + harness.engine.dispatch({ + type: "thread.turn.start", + commandId: CommandId.make("cmd-turn-start-compatible-codex-1"), + threadId: ThreadId.make("thread-1"), + message: { + messageId: asMessageId("user-message-compatible-codex-1"), + role: "user", + text: "first", + attachments: [], + }, + modelSelection: { + instanceId: ProviderInstanceId.make("codex"), + model: "gpt-5-codex", + }, + interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE, + runtimeMode: "approval-required", + createdAt: now, + }), + ); + + await waitFor(() => harness.sendTurn.mock.calls.length === 1); + + await Effect.runPromise( + harness.engine.dispatch({ + type: "thread.turn.start", + commandId: CommandId.make("cmd-turn-start-compatible-codex-2"), + threadId: ThreadId.make("thread-1"), + message: { + messageId: asMessageId("user-message-compatible-codex-2"), + role: "user", + text: "second", + attachments: [], + }, + modelSelection: { + instanceId: ProviderInstanceId.make("codex_work"), + model: "gpt-5-codex", + }, + interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE, + runtimeMode: "approval-required", + createdAt: new Date().toISOString(), + }), + ); + + await waitFor(() => harness.sendTurn.mock.calls.length === 2); + + expect(harness.startSession).toHaveBeenCalledTimes(2); + expect(harness.startSession.mock.calls[1]?.[1]).toMatchObject({ + provider: ProviderDriverKind.make("codex"), + providerInstanceId: ProviderInstanceId.make("codex_work"), + resumeCursor: { opaque: "resume-1" }, + }); + + const readModel = await Effect.runPromise(harness.engine.getReadModel()); + const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1")); + expect(thread?.session?.providerInstanceId).toBe(ProviderInstanceId.make("codex_work")); + }); + it("restarts the provider session when the thread workspace changes", async () => { const harness = await createHarness({ - threadModelSelection: { provider: "claudeAgent", model: "claude-sonnet-4-6" }, + threadModelSelection: { + instanceId: ProviderInstanceId.make("claudeAgent"), + model: "claude-sonnet-4-6", + }, }); const now = new Date().toISOString(); @@ -933,7 +1084,7 @@ describe("ProviderCommandReactor", () => { cwd: "/tmp/provider-project-worktree", resumeCursor: { opaque: "resume-1" }, modelSelection: { - provider: "claudeAgent", + instanceId: ProviderInstanceId.make("claudeAgent"), model: "claude-sonnet-4-6", }, runtimeMode: "approval-required", @@ -942,7 +1093,10 @@ describe("ProviderCommandReactor", () => { it("restarts claude sessions when claude effort changes", async () => { const harness = await createHarness({ - threadModelSelection: { provider: "claudeAgent", model: "claude-sonnet-4-6" }, + threadModelSelection: { + instanceId: ProviderInstanceId.make("claudeAgent"), + model: "claude-sonnet-4-6", + }, }); const now = new Date().toISOString(); @@ -957,9 +1111,11 @@ describe("ProviderCommandReactor", () => { text: "first claude turn", attachments: [], }, - modelSelection: createModelSelection("claudeAgent", "claude-sonnet-4-6", [ - { id: "effort", value: "medium" }, - ]), + modelSelection: createModelSelection( + ProviderInstanceId.make("claudeAgent"), + "claude-sonnet-4-6", + [{ id: "effort", value: "medium" }], + ), interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE, runtimeMode: "approval-required", createdAt: now, @@ -980,9 +1136,11 @@ describe("ProviderCommandReactor", () => { text: "second claude turn", attachments: [], }, - modelSelection: createModelSelection("claudeAgent", "claude-sonnet-4-6", [ - { id: "effort", value: "max" }, - ]), + modelSelection: createModelSelection( + ProviderInstanceId.make("claudeAgent"), + "claude-sonnet-4-6", + [{ id: "effort", value: "max" }], + ), interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE, runtimeMode: "approval-required", createdAt: now, @@ -993,9 +1151,11 @@ describe("ProviderCommandReactor", () => { await waitFor(() => harness.sendTurn.mock.calls.length === 2); expect(harness.startSession.mock.calls[1]?.[1]).toMatchObject({ resumeCursor: { opaque: "resume-1" }, - modelSelection: createModelSelection("claudeAgent", "claude-sonnet-4-6", [ - { id: "effort", value: "max" }, - ]), + modelSelection: createModelSelection( + ProviderInstanceId.make("claudeAgent"), + "claude-sonnet-4-6", + [{ id: "effort", value: "max" }], + ), }); }); @@ -1086,7 +1246,10 @@ describe("ProviderCommandReactor", () => { it("does not inject derived model options when restarting claude on runtime mode changes", async () => { const harness = await createHarness({ - threadModelSelection: { provider: "claudeAgent", model: "claude-opus-4-6" }, + threadModelSelection: { + instanceId: ProviderInstanceId.make("claudeAgent"), + model: "claude-opus-4-6", + }, }); const now = new Date().toISOString(); @@ -1122,7 +1285,7 @@ describe("ProviderCommandReactor", () => { expect(harness.startSession.mock.calls[0]?.[1]).toMatchObject({ modelSelection: { - provider: "claudeAgent", + instanceId: ProviderInstanceId.make("claudeAgent"), model: "claude-opus-4-6", }, runtimeMode: "approval-required", @@ -1230,7 +1393,7 @@ describe("ProviderCommandReactor", () => { attachments: [], }, modelSelection: { - provider: "claudeAgent", + instanceId: ProviderInstanceId.make("claudeAgent"), model: "claude-opus-4-6", }, interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE, @@ -1266,6 +1429,72 @@ describe("ProviderCommandReactor", () => { }); }); + it("rejects cross-driver provider changes after the existing thread session has stopped", async () => { + const harness = await createHarness(); + const now = new Date().toISOString(); + + await Effect.runPromise( + harness.engine.dispatch({ + type: "thread.session.set", + commandId: CommandId.make("cmd-session-set-stopped-provider-switch"), + threadId: ThreadId.make("thread-1"), + session: { + threadId: ThreadId.make("thread-1"), + status: "stopped", + providerName: "codex", + providerInstanceId: ProviderInstanceId.make("codex"), + runtimeMode: "approval-required", + activeTurnId: null, + lastError: null, + updatedAt: now, + }, + createdAt: now, + }), + ); + + await Effect.runPromise( + harness.engine.dispatch({ + type: "thread.turn.start", + commandId: CommandId.make("cmd-turn-start-stopped-provider-switch"), + threadId: ThreadId.make("thread-1"), + message: { + messageId: asMessageId("user-message-stopped-provider-switch"), + role: "user", + text: "continue with claude", + attachments: [], + }, + modelSelection: { + instanceId: ProviderInstanceId.make("claudeAgent"), + model: "claude-opus-4-6", + }, + interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE, + runtimeMode: "approval-required", + createdAt: now, + }), + ); + + await waitFor(async () => { + const readModel = await Effect.runPromise(harness.engine.getReadModel()); + const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1")); + return ( + thread?.activities.some((activity) => activity.kind === "provider.turn.start.failed") ?? + false + ); + }); + + expect(harness.startSession.mock.calls.length).toBe(0); + expect(harness.sendTurn.mock.calls.length).toBe(0); + const readModel = await Effect.runPromise(harness.engine.getReadModel()); + const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1")); + expect( + thread?.activities.find((activity) => activity.kind === "provider.turn.start.failed"), + ).toMatchObject({ + payload: { + detail: expect.stringContaining("cannot switch to 'claudeAgent'"), + }, + }); + }); + it("reacts to thread.turn.interrupt-requested by calling provider interrupt", async () => { const harness = await createHarness(); const now = new Date().toISOString(); @@ -1349,7 +1578,7 @@ describe("ProviderCommandReactor", () => { expect(harness.startSession.mock.calls[0]?.[1]).toMatchObject({ threadId: ThreadId.make("thread-1"), modelSelection: { - provider: "codex", + instanceId: ProviderInstanceId.make("codex"), model: "gpt-5-codex", }, runtimeMode: "approval-required", @@ -1359,6 +1588,77 @@ describe("ProviderCommandReactor", () => { }); }); + it("rejects active runtime sessions that are missing provider instance ids", async () => { + const harness = await createHarness(); + const now = new Date().toISOString(); + + await Effect.runPromise( + harness.engine.dispatch({ + type: "thread.session.set", + commandId: CommandId.make("cmd-session-set-missing-instance"), + threadId: ThreadId.make("thread-1"), + session: { + threadId: ThreadId.make("thread-1"), + status: "ready", + providerName: "codex", + runtimeMode: "approval-required", + activeTurnId: null, + lastError: null, + updatedAt: now, + }, + createdAt: now, + }), + ); + harness.runtimeSessions.push({ + provider: ProviderDriverKind.make("codex"), + status: "ready", + runtimeMode: "approval-required", + threadId: ThreadId.make("thread-1"), + cwd: "/tmp/provider-project", + resumeCursor: { opaque: "resume-without-instance" }, + createdAt: now, + updatedAt: now, + }); + + await Effect.runPromise( + harness.engine.dispatch({ + type: "thread.turn.start", + commandId: CommandId.make("cmd-turn-start-missing-instance"), + threadId: ThreadId.make("thread-1"), + message: { + messageId: asMessageId("user-message-missing-instance"), + role: "user", + text: "resume codex", + attachments: [], + }, + interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE, + runtimeMode: "approval-required", + createdAt: now, + }), + ); + + await waitFor(async () => { + const readModel = await Effect.runPromise(harness.engine.getReadModel()); + const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1")); + return ( + thread?.activities.some((activity) => activity.kind === "provider.turn.start.failed") ?? + false + ); + }); + + expect(harness.startSession.mock.calls.length).toBe(0); + expect(harness.sendTurn.mock.calls.length).toBe(0); + const readModel = await Effect.runPromise(harness.engine.getReadModel()); + const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1")); + expect( + thread?.activities.find((activity) => activity.kind === "provider.turn.start.failed"), + ).toMatchObject({ + payload: { + detail: expect.stringContaining("without a provider instance id"), + }, + }); + }); + it("reacts to thread.approval.respond by forwarding provider approval response", async () => { const harness = await createHarness(); const now = new Date().toISOString(); @@ -1451,7 +1751,7 @@ describe("ProviderCommandReactor", () => { harness.respondToRequest.mockImplementation(() => Effect.fail( new ProviderAdapterRequestError({ - provider: "codex", + provider: ProviderDriverKind.make("codex"), method: "session/request_permission", detail: "Unknown pending permission request: approval-request-1", }), @@ -1546,7 +1846,7 @@ describe("ProviderCommandReactor", () => { harness.respondToUserInput.mockImplementation(() => Effect.fail( new ProviderAdapterRequestError({ - provider: "claudeAgent", + provider: ProviderDriverKind.make("claudeAgent"), method: "item/tool/respondToUserInput", detail: "Unknown pending user-input request: user-input-request-1", }), @@ -1662,6 +1962,7 @@ describe("ProviderCommandReactor", () => { threadId: ThreadId.make("thread-1"), status: "ready", providerName: "codex", + providerInstanceId: ProviderInstanceId.make("codex_work"), runtimeMode: "approval-required", activeTurnId: null, lastError: null, @@ -1686,6 +1987,7 @@ describe("ProviderCommandReactor", () => { expect(thread?.session).not.toBeNull(); expect(thread?.session?.status).toBe("stopped"); expect(thread?.session?.threadId).toBe("thread-1"); + expect(thread?.session?.providerInstanceId).toBe(ProviderInstanceId.make("codex_work")); expect(thread?.session?.activeTurnId).toBeNull(); }); }); diff --git a/apps/server/src/orchestration/Layers/ProviderCommandReactor.ts b/apps/server/src/orchestration/Layers/ProviderCommandReactor.ts index f7ae38b2d2..9a9f3d71b0 100644 --- a/apps/server/src/orchestration/Layers/ProviderCommandReactor.ts +++ b/apps/server/src/orchestration/Layers/ProviderCommandReactor.ts @@ -4,7 +4,7 @@ import { EventId, type ModelSelection, type OrchestrationEvent, - ProviderKind, + ProviderDriverKind, type OrchestrationSession, ThreadId, type ProviderSession, @@ -77,6 +77,21 @@ const HANDLED_TURN_START_KEY_TTL = Duration.minutes(30); const DEFAULT_RUNTIME_MODE: RuntimeMode = "full-access"; const DEFAULT_THREAD_TITLE = "New thread"; +export function providerErrorLabel(value: string | undefined): string { + const normalized = value?.trim(); + return normalized && normalized.length > 0 ? normalized : "unknown"; +} + +export function providerErrorLabelFromInstanceHint(input: { + readonly instanceId?: string | undefined; + readonly modelSelectionInstanceId?: string | undefined; + readonly sessionProvider?: string | undefined; +}): string { + return providerErrorLabel( + input.instanceId ?? input.modelSelectionInstanceId ?? input.sessionProvider, + ); +} + function canReplaceThreadTitle(currentTitle: string, titleSeed?: string): boolean { const trimmedCurrentTitle = currentTitle.trim(); if (trimmedCurrentTitle === DEFAULT_THREAD_TITLE) { @@ -271,42 +286,108 @@ const make = Effect.gen(function* () { } const desiredRuntimeMode = thread.runtimeMode; - const currentProvider: ProviderKind | undefined = Schema.is(ProviderKind)( - thread.session?.providerName, - ) - ? thread.session.providerName - : undefined; const requestedModelSelection = options?.modelSelection; - const threadProvider: ProviderKind = currentProvider ?? thread.modelSelection.provider; - if ( - requestedModelSelection !== undefined && - requestedModelSelection.provider !== threadProvider - ) { - return yield* new ProviderAdapterRequestError({ - provider: threadProvider, - method: "thread.turn.start", - detail: `Thread '${threadId}' is bound to provider '${threadProvider}' and cannot switch to '${requestedModelSelection.provider}'.`, - }); - } - const preferredProvider: ProviderKind = threadProvider; - const desiredModelSelection = requestedModelSelection ?? thread.modelSelection; - const effectiveCwd = resolveThreadWorkspaceCwd({ - thread, - projects: readModel.projects, - }); - const resolveActiveSession = (threadId: ThreadId) => providerService .listSessions() .pipe(Effect.map((sessions) => sessions.find((session) => session.threadId === threadId))); + const activeSession = yield* resolveActiveSession(threadId); + const activeThreadSession = + thread.session !== null && thread.session.status !== "stopped" && activeSession + ? thread.session + : null; + if ( + activeThreadSession !== null && + activeSession !== undefined && + (activeThreadSession.providerInstanceId === undefined || + activeSession.providerInstanceId === undefined) + ) { + return yield* new ProviderAdapterRequestError({ + provider: providerErrorLabel(activeThreadSession.providerName ?? undefined), + method: "thread.turn.start", + detail: `Thread '${threadId}' has an active provider session without a provider instance id.`, + }); + } + const currentInstanceId = + activeThreadSession !== null && + activeSession !== undefined && + activeSession.providerInstanceId !== undefined + ? activeSession.providerInstanceId + : thread.modelSelection.instanceId; + const desiredModelSelection = requestedModelSelection ?? thread.modelSelection; + const desiredInstanceId = desiredModelSelection.instanceId; + const currentInfo = yield* providerService.getInstanceInfo(currentInstanceId).pipe( + Effect.mapError( + () => + new ProviderAdapterRequestError({ + provider: providerErrorLabelFromInstanceHint({ + instanceId: String(currentInstanceId), + modelSelectionInstanceId: String(thread.modelSelection.instanceId), + sessionProvider: thread.session?.providerName ?? undefined, + }), + method: "thread.turn.start", + detail: `Thread '${threadId}' references unknown provider instance '${currentInstanceId}'. The instance is not configured in this build.`, + }), + ), + ); + const desiredInfo = yield* providerService.getInstanceInfo(desiredInstanceId).pipe( + Effect.mapError( + () => + new ProviderAdapterRequestError({ + provider: providerErrorLabelFromInstanceHint({ + instanceId: String(desiredModelSelection.instanceId), + }), + method: "thread.turn.start", + detail: `Requested provider instance '${desiredInstanceId}' is not configured in this build.`, + }), + ), + ); + const desiredDriverKind = desiredInfo.driverKind; + if (!Schema.is(ProviderDriverKind)(desiredDriverKind)) { + return yield* new ProviderAdapterRequestError({ + provider: providerErrorLabel(String(desiredDriverKind)), + method: "thread.turn.start", + detail: `Requested provider instance '${desiredInstanceId}' uses unknown provider driver '${desiredDriverKind}'. The driver is not installed in this build.`, + }); + } + const preferredProvider: ProviderDriverKind = desiredDriverKind; + if ( + thread.session !== null && + requestedModelSelection !== undefined && + requestedModelSelection.instanceId !== currentInstanceId + ) { + if (currentInfo.driverKind !== desiredInfo.driverKind) { + return yield* new ProviderAdapterRequestError({ + provider: preferredProvider, + method: "thread.turn.start", + detail: `Thread '${threadId}' is bound to driver '${currentInfo.driverKind}' and cannot switch to '${desiredInfo.driverKind}'.`, + }); + } + if ( + currentInfo.continuationIdentity.continuationKey !== + desiredInfo.continuationIdentity.continuationKey + ) { + return yield* new ProviderAdapterRequestError({ + provider: preferredProvider, + method: "thread.turn.start", + detail: `Thread '${threadId}' cannot switch from instance '${currentInstanceId}' to '${desiredInstanceId}' because their provider resume state is incompatible.`, + }); + } + } + const effectiveCwd = resolveThreadWorkspaceCwd({ + thread, + projects: readModel.projects, + }); + const startProviderSession = (input?: { readonly resumeCursor?: unknown; - readonly provider?: ProviderKind; + readonly provider?: ProviderDriverKind; }) => providerService.startSession(threadId, { threadId, ...(preferredProvider ? { provider: preferredProvider } : {}), + providerInstanceId: desiredInstanceId, ...(effectiveCwd ? { cwd: effectiveCwd } : {}), modelSelection: desiredModelSelection, ...(input?.resumeCursor !== undefined ? { resumeCursor: input.resumeCursor } : {}), @@ -314,44 +395,55 @@ const make = Effect.gen(function* () { }); const bindSessionToThread = (session: ProviderSession) => - setThreadSession({ - threadId, - session: { + Effect.gen(function* () { + if (session.providerInstanceId === undefined) { + return yield* new ProviderAdapterRequestError({ + provider: providerErrorLabel(session.provider), + method: "thread.turn.start", + detail: `Provider session '${session.threadId}' started without a provider instance id.`, + }); + } + yield* setThreadSession({ threadId, - status: mapProviderSessionStatusToOrchestrationStatus(session.status), - providerName: session.provider, - runtimeMode: desiredRuntimeMode, - // Provider turn ids are not orchestration turn ids. - activeTurnId: null, - lastError: session.lastError ?? null, - updatedAt: session.updatedAt, - }, - createdAt, + session: { + threadId, + status: mapProviderSessionStatusToOrchestrationStatus(session.status), + providerName: session.provider, + providerInstanceId: session.providerInstanceId, + runtimeMode: desiredRuntimeMode, + // Provider turn ids are not orchestration turn ids. + activeTurnId: null, + lastError: session.lastError ?? null, + updatedAt: session.updatedAt, + }, + createdAt, + }); }); - const activeSession = yield* resolveActiveSession(threadId); const existingSessionThreadId = thread.session && thread.session.status !== "stopped" && activeSession ? thread.id : null; if (existingSessionThreadId) { const runtimeModeChanged = thread.runtimeMode !== thread.session?.runtimeMode; const cwdChanged = effectiveCwd !== activeSession?.cwd; - const sessionModelSwitch = - currentProvider === undefined - ? "in-session" - : (yield* providerService.getCapabilities(currentProvider)).sessionModelSwitch; + const sessionModelSwitch = (yield* providerService.getCapabilities(desiredInstanceId)) + .sessionModelSwitch; const modelChanged = requestedModelSelection !== undefined && requestedModelSelection.model !== activeSession?.model; + const instanceChanged = + requestedModelSelection !== undefined && + activeSession?.providerInstanceId !== requestedModelSelection.instanceId; const shouldRestartForModelChange = modelChanged && sessionModelSwitch === "unsupported"; const previousModelSelection = threadModelSelections.get(threadId); const shouldRestartForModelSelectionChange = - currentProvider === "claudeAgent" && + preferredProvider === "claudeAgent" && requestedModelSelection !== undefined && !Equal.equals(previousModelSelection, requestedModelSelection); if ( !runtimeModeChanged && !cwdChanged && + !instanceChanged && !shouldRestartForModelChange && !shouldRestartForModelSelectionChange ) { @@ -364,8 +456,10 @@ const make = Effect.gen(function* () { yield* Effect.logInfo("provider command reactor restarting provider session", { threadId, existingSessionThreadId, - currentProvider, - desiredProvider: desiredModelSelection.provider, + currentProvider: activeSession?.provider, + currentInstanceId, + desiredInstanceId, + desiredProvider: desiredModelSelection.instanceId, currentRuntimeMode: thread.session?.runtimeMode, desiredRuntimeMode: thread.runtimeMode, runtimeModeChanged, @@ -373,6 +467,7 @@ const make = Effect.gen(function* () { desiredCwd: effectiveCwd, cwdChanged, modelChanged, + instanceChanged, shouldRestartForModelChange, shouldRestartForModelSelectionChange, hasResumeCursor: resumeCursor !== undefined, @@ -429,7 +524,14 @@ const make = Effect.gen(function* () { const sessionModelSwitch = activeSession === undefined ? "in-session" - : (yield* providerService.getCapabilities(activeSession.provider)).sessionModelSwitch; + : activeSession.providerInstanceId === undefined + ? yield* new ProviderAdapterRequestError({ + provider: providerErrorLabel(activeSession.provider), + method: "thread.turn.start", + detail: `Active provider session '${activeSession.threadId}' is missing a provider instance id.`, + }) + : (yield* providerService.getCapabilities(activeSession.providerInstanceId)) + .sessionModelSwitch; const requestedModelSelection = input.modelSelection ?? threadModelSelections.get(input.threadId) ?? thread.modelSelection; const modelForTurn = @@ -800,6 +902,9 @@ const make = Effect.gen(function* () { threadId: thread.id, status: "stopped", providerName: thread.session?.providerName ?? null, + ...(thread.session?.providerInstanceId !== undefined + ? { providerInstanceId: thread.session.providerInstanceId } + : {}), runtimeMode: thread.session?.runtimeMode ?? DEFAULT_RUNTIME_MODE, activeTurnId: null, lastError: thread.session?.lastError ?? null, diff --git a/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.test.ts b/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.test.ts index 577c5050ea..487d1a3aac 100644 --- a/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.test.ts +++ b/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.test.ts @@ -2,10 +2,12 @@ import fs from "node:fs"; import os from "node:os"; import path from "node:path"; -import type { +import { OrchestrationReadModel, + ProviderDriverKind, ProviderRuntimeEvent, ProviderSession, + ProviderInstanceId, } from "@t3tools/contracts"; import { ApprovalRequestId, @@ -98,6 +100,19 @@ function createProviderServiceHarness() { stopSession: () => unsupported(), listSessions: () => Effect.succeed([...runtimeSessions]), getCapabilities: () => Effect.succeed({ sessionModelSwitch: "in-session" }), + getInstanceInfo: (instanceId) => { + const driverKind = ProviderDriverKind.make(String(instanceId)); + return Effect.succeed({ + instanceId, + driverKind, + displayName: undefined, + enabled: true, + continuationIdentity: { + driverKind, + continuationKey: `${driverKind}:instance:${instanceId}`, + }, + }); + }, rollbackConversation: () => unsupported(), get streamEvents() { return Stream.fromPubSub(runtimeEventPubSub); @@ -232,7 +247,7 @@ describe("ProviderRuntimeIngestion", () => { title: "Provider Project", workspaceRoot, defaultModelSelection: { - provider: "codex", + instanceId: ProviderInstanceId.make("codex"), model: "gpt-5-codex", }, createdAt, @@ -246,7 +261,7 @@ describe("ProviderRuntimeIngestion", () => { projectId: asProjectId("project-1"), title: "Thread", modelSelection: { - provider: "codex", + instanceId: ProviderInstanceId.make("codex"), model: "gpt-5-codex", }, interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE, @@ -274,7 +289,7 @@ describe("ProviderRuntimeIngestion", () => { }), ); provider.setSession({ - provider: "codex", + provider: ProviderDriverKind.make("codex"), status: "ready", runtimeMode: "approval-required", threadId: ThreadId.make("thread-1"), @@ -297,7 +312,7 @@ describe("ProviderRuntimeIngestion", () => { harness.emit({ type: "turn.started", eventId: asEventId("evt-turn-started"), - provider: "codex", + provider: ProviderDriverKind.make("codex"), threadId: asThreadId("thread-1"), createdAt: now, turnId: asTurnId("turn-1"), @@ -311,7 +326,7 @@ describe("ProviderRuntimeIngestion", () => { harness.emit({ type: "turn.completed", eventId: asEventId("evt-turn-completed"), - provider: "codex", + provider: ProviderDriverKind.make("codex"), threadId: asThreadId("thread-1"), createdAt: new Date().toISOString(), turnId: asTurnId("turn-1"), @@ -339,7 +354,7 @@ describe("ProviderRuntimeIngestion", () => { harness.emit({ type: "session.state.changed", eventId: asEventId("evt-session-state-waiting"), - provider: "codex", + provider: ProviderDriverKind.make("codex"), threadId: asThreadId("thread-1"), createdAt: waitingAt, payload: { @@ -358,7 +373,7 @@ describe("ProviderRuntimeIngestion", () => { harness.emit({ type: "session.state.changed", eventId: asEventId("evt-session-state-error"), - provider: "codex", + provider: ProviderDriverKind.make("codex"), threadId: asThreadId("thread-1"), createdAt: new Date().toISOString(), payload: { @@ -380,7 +395,7 @@ describe("ProviderRuntimeIngestion", () => { harness.emit({ type: "session.state.changed", eventId: asEventId("evt-session-state-stopped"), - provider: "codex", + provider: ProviderDriverKind.make("codex"), threadId: asThreadId("thread-1"), createdAt: new Date().toISOString(), payload: { @@ -401,7 +416,7 @@ describe("ProviderRuntimeIngestion", () => { harness.emit({ type: "session.state.changed", eventId: asEventId("evt-session-state-ready"), - provider: "codex", + provider: ProviderDriverKind.make("codex"), threadId: asThreadId("thread-1"), createdAt: new Date().toISOString(), payload: { @@ -427,7 +442,7 @@ describe("ProviderRuntimeIngestion", () => { harness.emit({ type: "turn.started", eventId: asEventId("evt-turn-started-midturn-lifecycle"), - provider: "codex", + provider: ProviderDriverKind.make("codex"), createdAt: now, threadId: asThreadId("thread-1"), turnId: asTurnId("turn-midturn-lifecycle"), @@ -443,14 +458,14 @@ describe("ProviderRuntimeIngestion", () => { harness.emit({ type: "thread.started", eventId: asEventId("evt-thread-started-midturn-lifecycle"), - provider: "codex", + provider: ProviderDriverKind.make("codex"), createdAt: new Date().toISOString(), threadId: asThreadId("thread-1"), }); harness.emit({ type: "session.started", eventId: asEventId("evt-session-started-midturn-lifecycle"), - provider: "codex", + provider: ProviderDriverKind.make("codex"), createdAt: new Date().toISOString(), threadId: asThreadId("thread-1"), }); @@ -464,7 +479,7 @@ describe("ProviderRuntimeIngestion", () => { harness.emit({ type: "turn.completed", eventId: asEventId("evt-turn-completed-midturn-lifecycle"), - provider: "codex", + provider: ProviderDriverKind.make("codex"), createdAt: new Date().toISOString(), threadId: asThreadId("thread-1"), turnId: asTurnId("turn-midturn-lifecycle"), @@ -502,7 +517,7 @@ describe("ProviderRuntimeIngestion", () => { harness.emit({ type: "turn.started", eventId: asEventId("evt-turn-started-claude-placeholder"), - provider: "claudeAgent", + provider: ProviderDriverKind.make("claudeAgent"), createdAt: new Date().toISOString(), threadId: asThreadId("thread-1"), turnId: asTurnId("turn-claude-placeholder"), @@ -518,7 +533,7 @@ describe("ProviderRuntimeIngestion", () => { harness.emit({ type: "turn.completed", eventId: asEventId("evt-turn-completed-claude-placeholder"), - provider: "claudeAgent", + provider: ProviderDriverKind.make("claudeAgent"), createdAt: new Date().toISOString(), threadId: asThreadId("thread-1"), turnId: asTurnId("turn-claude-placeholder"), @@ -538,7 +553,7 @@ describe("ProviderRuntimeIngestion", () => { harness.emit({ type: "turn.started", eventId: asEventId("evt-turn-started-primary"), - provider: "codex", + provider: ProviderDriverKind.make("codex"), createdAt: now, threadId: asThreadId("thread-1"), turnId: asTurnId("turn-primary"), @@ -553,7 +568,7 @@ describe("ProviderRuntimeIngestion", () => { harness.emit({ type: "turn.completed", eventId: asEventId("evt-turn-completed-aux"), - provider: "codex", + provider: ProviderDriverKind.make("codex"), createdAt: new Date().toISOString(), threadId: asThreadId("thread-1"), turnId: asTurnId("turn-aux"), @@ -569,7 +584,7 @@ describe("ProviderRuntimeIngestion", () => { harness.emit({ type: "turn.completed", eventId: asEventId("evt-turn-completed-primary"), - provider: "codex", + provider: ProviderDriverKind.make("codex"), createdAt: new Date().toISOString(), threadId: asThreadId("thread-1"), turnId: asTurnId("turn-primary"), @@ -589,7 +604,7 @@ describe("ProviderRuntimeIngestion", () => { harness.emit({ type: "turn.started", eventId: asEventId("evt-turn-started-guarded"), - provider: "codex", + provider: ProviderDriverKind.make("codex"), createdAt: now, threadId: asThreadId("thread-1"), turnId: asTurnId("turn-guarded-main"), @@ -605,7 +620,7 @@ describe("ProviderRuntimeIngestion", () => { harness.emit({ type: "turn.completed", eventId: asEventId("evt-turn-completed-guarded-other"), - provider: "codex", + provider: ProviderDriverKind.make("codex"), createdAt: new Date().toISOString(), threadId: asThreadId("thread-1"), turnId: asTurnId("turn-guarded-other"), @@ -621,7 +636,7 @@ describe("ProviderRuntimeIngestion", () => { harness.emit({ type: "turn.completed", eventId: asEventId("evt-turn-completed-guarded-main"), - provider: "codex", + provider: ProviderDriverKind.make("codex"), createdAt: new Date().toISOString(), threadId: asThreadId("thread-1"), turnId: asTurnId("turn-guarded-main"), @@ -641,7 +656,7 @@ describe("ProviderRuntimeIngestion", () => { harness.emit({ type: "content.delta", eventId: asEventId("evt-message-delta-1"), - provider: "codex", + provider: ProviderDriverKind.make("codex"), createdAt: now, threadId: asThreadId("thread-1"), turnId: asTurnId("turn-2"), @@ -654,7 +669,7 @@ describe("ProviderRuntimeIngestion", () => { harness.emit({ type: "content.delta", eventId: asEventId("evt-message-delta-2"), - provider: "codex", + provider: ProviderDriverKind.make("codex"), createdAt: now, threadId: asThreadId("thread-1"), turnId: asTurnId("turn-2"), @@ -667,7 +682,7 @@ describe("ProviderRuntimeIngestion", () => { harness.emit({ type: "item.completed", eventId: asEventId("evt-message-completed"), - provider: "codex", + provider: ProviderDriverKind.make("codex"), createdAt: now, threadId: asThreadId("thread-1"), turnId: asTurnId("turn-2"), @@ -698,7 +713,7 @@ describe("ProviderRuntimeIngestion", () => { harness.emit({ type: "item.completed", eventId: asEventId("evt-assistant-item-completed-no-delta"), - provider: "codex", + provider: ProviderDriverKind.make("codex"), createdAt: now, threadId: asThreadId("thread-1"), turnId: asTurnId("turn-no-delta"), @@ -730,7 +745,7 @@ describe("ProviderRuntimeIngestion", () => { harness.emit({ type: "item.completed", eventId: asEventId("evt-tool-completed-with-data"), - provider: "cursor", + provider: ProviderDriverKind.make("cursor"), createdAt: now, threadId: asThreadId("thread-1"), turnId: asTurnId("turn-tool-completed"), @@ -786,7 +801,7 @@ describe("ProviderRuntimeIngestion", () => { harness.emit({ type: "item.completed", eventId: asEventId("evt-command-completed"), - provider: "cursor", + provider: ProviderDriverKind.make("cursor"), createdAt: now, threadId: asThreadId("thread-1"), turnId: asTurnId("turn-command-completed"), @@ -828,7 +843,7 @@ describe("ProviderRuntimeIngestion", () => { harness.emit({ type: "item.completed", eventId: asEventId("evt-read-path-completed"), - provider: "cursor", + provider: ProviderDriverKind.make("cursor"), createdAt: now, threadId: asThreadId("thread-1"), turnId: asTurnId("turn-read-path"), @@ -870,7 +885,7 @@ describe("ProviderRuntimeIngestion", () => { harness.emit({ type: "turn.proposed.completed", eventId: asEventId("evt-plan-item-completed"), - provider: "codex", + provider: ProviderDriverKind.make("codex"), createdAt: now, threadId: asThreadId("thread-1"), turnId: asTurnId("turn-plan-final"), @@ -909,7 +924,7 @@ describe("ProviderRuntimeIngestion", () => { projectId: asProjectId("project-1"), title: "Plan Source", modelSelection: { - provider: "codex", + instanceId: ProviderInstanceId.make("codex"), model: "gpt-5-codex", }, interactionMode: "plan", @@ -944,7 +959,7 @@ describe("ProviderRuntimeIngestion", () => { projectId: asProjectId("project-1"), title: "Plan Target", modelSelection: { - provider: "codex", + instanceId: ProviderInstanceId.make("codex"), model: "gpt-5-codex", }, interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE, @@ -972,7 +987,7 @@ describe("ProviderRuntimeIngestion", () => { }), ); harness.setProviderSession({ - provider: "codex", + provider: ProviderDriverKind.make("codex"), status: "ready", runtimeMode: "approval-required", threadId: targetThreadId, @@ -984,7 +999,7 @@ describe("ProviderRuntimeIngestion", () => { harness.emit({ type: "turn.proposed.completed", eventId: asEventId("evt-plan-source-completed"), - provider: "codex", + provider: ProviderDriverKind.make("codex"), createdAt, threadId: sourceThreadId, turnId: sourceTurnId, @@ -1054,7 +1069,7 @@ describe("ProviderRuntimeIngestion", () => { harness.emit({ type: "turn.started", eventId: asEventId("evt-plan-target-started"), - provider: "codex", + provider: ProviderDriverKind.make("codex"), createdAt: new Date().toISOString(), threadId: targetThreadId, turnId: targetTurnId, @@ -1096,7 +1111,7 @@ describe("ProviderRuntimeIngestion", () => { projectId: asProjectId("project-1"), title: "Plan Source", modelSelection: { - provider: "codex", + instanceId: ProviderInstanceId.make("codex"), model: "gpt-5-codex", }, interactionMode: "plan", @@ -1124,7 +1139,7 @@ describe("ProviderRuntimeIngestion", () => { }), ); harness.setProviderSession({ - provider: "codex", + provider: ProviderDriverKind.make("codex"), status: "running", runtimeMode: "approval-required", threadId: targetThreadId, @@ -1136,7 +1151,7 @@ describe("ProviderRuntimeIngestion", () => { harness.emit({ type: "turn.started", eventId: asEventId("evt-turn-started-already-running"), - provider: "codex", + provider: ProviderDriverKind.make("codex"), createdAt, threadId: targetThreadId, turnId: activeTurnId, @@ -1153,7 +1168,7 @@ describe("ProviderRuntimeIngestion", () => { harness.emit({ type: "turn.proposed.completed", eventId: asEventId("evt-plan-source-completed-guarded"), - provider: "codex", + provider: ProviderDriverKind.make("codex"), createdAt, threadId: sourceThreadId, turnId: sourceTurnId, @@ -1206,7 +1221,7 @@ describe("ProviderRuntimeIngestion", () => { harness.emit({ type: "turn.started", eventId: asEventId("evt-turn-started-stale-plan-implementation"), - provider: "codex", + provider: ProviderDriverKind.make("codex"), createdAt: new Date().toISOString(), threadId: targetThreadId, turnId: staleTurnId, @@ -1249,7 +1264,7 @@ describe("ProviderRuntimeIngestion", () => { projectId: asProjectId("project-1"), title: "Plan Source", modelSelection: { - provider: "codex", + instanceId: ProviderInstanceId.make("codex"), model: "gpt-5-codex", }, interactionMode: "plan", @@ -1284,7 +1299,7 @@ describe("ProviderRuntimeIngestion", () => { projectId: asProjectId("project-1"), title: "Plan Target", modelSelection: { - provider: "codex", + instanceId: ProviderInstanceId.make("codex"), model: "gpt-5-codex", }, interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE, @@ -1315,7 +1330,7 @@ describe("ProviderRuntimeIngestion", () => { harness.emit({ type: "turn.proposed.completed", eventId: asEventId("evt-plan-source-completed-unrelated"), - provider: "codex", + provider: ProviderDriverKind.make("codex"), createdAt, threadId: sourceThreadId, turnId: sourceTurnId, @@ -1366,7 +1381,7 @@ describe("ProviderRuntimeIngestion", () => { ); harness.setProviderSession({ - provider: "codex", + provider: ProviderDriverKind.make("codex"), status: "running", runtimeMode: "approval-required", threadId: targetThreadId, @@ -1378,7 +1393,7 @@ describe("ProviderRuntimeIngestion", () => { harness.emit({ type: "turn.started", eventId: asEventId("evt-turn-started-unrelated-plan-implementation"), - provider: "codex", + provider: ProviderDriverKind.make("codex"), createdAt: new Date().toISOString(), threadId: targetThreadId, turnId: replayedTurnId, @@ -1405,7 +1420,7 @@ describe("ProviderRuntimeIngestion", () => { harness.emit({ type: "turn.started", eventId: asEventId("evt-turn-started-plan-buffer"), - provider: "codex", + provider: ProviderDriverKind.make("codex"), createdAt: now, threadId: asThreadId("thread-1"), turnId: asTurnId("turn-plan-buffer"), @@ -1420,7 +1435,7 @@ describe("ProviderRuntimeIngestion", () => { harness.emit({ type: "turn.proposed.delta", eventId: asEventId("evt-plan-delta-1"), - provider: "codex", + provider: ProviderDriverKind.make("codex"), createdAt: now, threadId: asThreadId("thread-1"), turnId: asTurnId("turn-plan-buffer"), @@ -1431,7 +1446,7 @@ describe("ProviderRuntimeIngestion", () => { harness.emit({ type: "turn.proposed.delta", eventId: asEventId("evt-plan-delta-2"), - provider: "codex", + provider: ProviderDriverKind.make("codex"), createdAt: now, threadId: asThreadId("thread-1"), turnId: asTurnId("turn-plan-buffer"), @@ -1442,7 +1457,7 @@ describe("ProviderRuntimeIngestion", () => { harness.emit({ type: "turn.completed", eventId: asEventId("evt-turn-completed-plan-buffer"), - provider: "codex", + provider: ProviderDriverKind.make("codex"), createdAt: now, threadId: asThreadId("thread-1"), turnId: asTurnId("turn-plan-buffer"), @@ -1471,7 +1486,7 @@ describe("ProviderRuntimeIngestion", () => { harness.emit({ type: "turn.started", eventId: asEventId("evt-turn-started-buffered"), - provider: "codex", + provider: ProviderDriverKind.make("codex"), createdAt: now, threadId: asThreadId("thread-1"), turnId: asTurnId("turn-buffered"), @@ -1485,7 +1500,7 @@ describe("ProviderRuntimeIngestion", () => { harness.emit({ type: "content.delta", eventId: asEventId("evt-message-delta-buffered"), - provider: "codex", + provider: ProviderDriverKind.make("codex"), createdAt: now, threadId: asThreadId("thread-1"), turnId: asTurnId("turn-buffered"), @@ -1508,7 +1523,7 @@ describe("ProviderRuntimeIngestion", () => { harness.emit({ type: "item.completed", eventId: asEventId("evt-message-completed-buffered"), - provider: "codex", + provider: ProviderDriverKind.make("codex"), createdAt: now, threadId: asThreadId("thread-1"), turnId: asTurnId("turn-buffered"), @@ -1539,7 +1554,7 @@ describe("ProviderRuntimeIngestion", () => { harness.emit({ type: "turn.started", eventId: asEventId("evt-turn-started-buffered-request-flush"), - provider: "codex", + provider: ProviderDriverKind.make("codex"), createdAt: now, threadId: asThreadId("thread-1"), turnId: asTurnId("turn-buffered-request-flush"), @@ -1554,7 +1569,7 @@ describe("ProviderRuntimeIngestion", () => { harness.emit({ type: "content.delta", eventId: asEventId("evt-message-delta-buffered-request-flush"), - provider: "codex", + provider: ProviderDriverKind.make("codex"), createdAt: now, threadId: asThreadId("thread-1"), turnId: asTurnId("turn-buffered-request-flush"), @@ -1567,7 +1582,7 @@ describe("ProviderRuntimeIngestion", () => { harness.emit({ type: "request.opened", eventId: asEventId("evt-request-opened-buffered-request-flush"), - provider: "codex", + provider: ProviderDriverKind.make("codex"), createdAt: now, threadId: asThreadId("thread-1"), turnId: asTurnId("turn-buffered-request-flush"), @@ -1599,7 +1614,7 @@ describe("ProviderRuntimeIngestion", () => { harness.emit({ type: "turn.started", eventId: asEventId("evt-turn-started-buffered-user-input-flush"), - provider: "codex", + provider: ProviderDriverKind.make("codex"), createdAt: now, threadId: asThreadId("thread-1"), turnId: asTurnId("turn-buffered-user-input-flush"), @@ -1614,7 +1629,7 @@ describe("ProviderRuntimeIngestion", () => { harness.emit({ type: "content.delta", eventId: asEventId("evt-message-delta-buffered-user-input-flush"), - provider: "codex", + provider: ProviderDriverKind.make("codex"), createdAt: now, threadId: asThreadId("thread-1"), turnId: asTurnId("turn-buffered-user-input-flush"), @@ -1627,7 +1642,7 @@ describe("ProviderRuntimeIngestion", () => { harness.emit({ type: "user-input.requested", eventId: asEventId("evt-user-input-requested-buffered-user-input-flush"), - provider: "codex", + provider: ProviderDriverKind.make("codex"), createdAt: now, threadId: asThreadId("thread-1"), turnId: asTurnId("turn-buffered-user-input-flush"), @@ -1667,7 +1682,7 @@ describe("ProviderRuntimeIngestion", () => { harness.emit({ type: "turn.started", eventId: asEventId("evt-turn-started-buffered-whitespace-request"), - provider: "codex", + provider: ProviderDriverKind.make("codex"), createdAt: startedAt, threadId: asThreadId("thread-1"), turnId: asTurnId("turn-buffered-whitespace-request"), @@ -1682,7 +1697,7 @@ describe("ProviderRuntimeIngestion", () => { harness.emit({ type: "content.delta", eventId: asEventId("evt-message-delta-buffered-whitespace-request"), - provider: "codex", + provider: ProviderDriverKind.make("codex"), createdAt: startedAt, threadId: asThreadId("thread-1"), turnId: asTurnId("turn-buffered-whitespace-request"), @@ -1695,7 +1710,7 @@ describe("ProviderRuntimeIngestion", () => { harness.emit({ type: "request.opened", eventId: asEventId("evt-request-opened-buffered-whitespace-request"), - provider: "codex", + provider: ProviderDriverKind.make("codex"), createdAt: pausedAt, threadId: asThreadId("thread-1"), turnId: asTurnId("turn-buffered-whitespace-request"), @@ -1729,7 +1744,7 @@ describe("ProviderRuntimeIngestion", () => { harness.emit({ type: "turn.started", eventId: asEventId("evt-turn-started-buffered-request-append"), - provider: "codex", + provider: ProviderDriverKind.make("codex"), createdAt: startedAt, threadId: asThreadId("thread-1"), turnId: asTurnId("turn-buffered-request-append"), @@ -1744,7 +1759,7 @@ describe("ProviderRuntimeIngestion", () => { harness.emit({ type: "content.delta", eventId: asEventId("evt-message-delta-buffered-request-append-initial"), - provider: "codex", + provider: ProviderDriverKind.make("codex"), createdAt: startedAt, threadId: asThreadId("thread-1"), turnId: asTurnId("turn-buffered-request-append"), @@ -1757,7 +1772,7 @@ describe("ProviderRuntimeIngestion", () => { harness.emit({ type: "request.opened", eventId: asEventId("evt-request-opened-buffered-request-append"), - provider: "codex", + provider: ProviderDriverKind.make("codex"), createdAt: pausedAt, threadId: asThreadId("thread-1"), turnId: asTurnId("turn-buffered-request-append"), @@ -1780,7 +1795,7 @@ describe("ProviderRuntimeIngestion", () => { harness.emit({ type: "content.delta", eventId: asEventId("evt-message-delta-buffered-request-append-followup"), - provider: "codex", + provider: ProviderDriverKind.make("codex"), createdAt: resumedAt, threadId: asThreadId("thread-1"), turnId: asTurnId("turn-buffered-request-append"), @@ -1793,7 +1808,7 @@ describe("ProviderRuntimeIngestion", () => { harness.emit({ type: "item.completed", eventId: asEventId("evt-message-completed-buffered-request-append"), - provider: "codex", + provider: ProviderDriverKind.make("codex"), createdAt: completedAt, threadId: asThreadId("thread-1"), turnId: asTurnId("turn-buffered-request-append"), @@ -1861,7 +1876,7 @@ describe("ProviderRuntimeIngestion", () => { harness.emit({ type: "turn.started", eventId: asEventId("evt-turn-started-streaming-request-segment"), - provider: "codex", + provider: ProviderDriverKind.make("codex"), createdAt: startedAt, threadId: asThreadId("thread-1"), turnId: asTurnId("turn-streaming-request-segment"), @@ -1876,7 +1891,7 @@ describe("ProviderRuntimeIngestion", () => { harness.emit({ type: "content.delta", eventId: asEventId("evt-message-delta-streaming-request-segment-initial"), - provider: "codex", + provider: ProviderDriverKind.make("codex"), createdAt: startedAt, threadId: asThreadId("thread-1"), turnId: asTurnId("turn-streaming-request-segment"), @@ -1889,7 +1904,7 @@ describe("ProviderRuntimeIngestion", () => { harness.emit({ type: "request.opened", eventId: asEventId("evt-request-opened-streaming-request-segment"), - provider: "codex", + provider: ProviderDriverKind.make("codex"), createdAt: pausedAt, threadId: asThreadId("thread-1"), turnId: asTurnId("turn-streaming-request-segment"), @@ -1912,7 +1927,7 @@ describe("ProviderRuntimeIngestion", () => { harness.emit({ type: "content.delta", eventId: asEventId("evt-message-delta-streaming-request-segment-followup"), - provider: "codex", + provider: ProviderDriverKind.make("codex"), createdAt: resumedAt, threadId: asThreadId("thread-1"), turnId: asTurnId("turn-streaming-request-segment"), @@ -1925,7 +1940,7 @@ describe("ProviderRuntimeIngestion", () => { harness.emit({ type: "item.completed", eventId: asEventId("evt-message-completed-streaming-request-segment"), - provider: "codex", + provider: ProviderDriverKind.make("codex"), createdAt: completedAt, threadId: asThreadId("thread-1"), turnId: asTurnId("turn-streaming-request-segment"), @@ -1983,7 +1998,7 @@ describe("ProviderRuntimeIngestion", () => { harness.emit({ type: "turn.started", eventId: asEventId("evt-turn-started-streaming-mode"), - provider: "codex", + provider: ProviderDriverKind.make("codex"), createdAt: now, threadId: asThreadId("thread-1"), turnId: asTurnId("turn-streaming-mode"), @@ -1998,7 +2013,7 @@ describe("ProviderRuntimeIngestion", () => { harness.emit({ type: "content.delta", eventId: asEventId("evt-message-delta-streaming-mode"), - provider: "codex", + provider: ProviderDriverKind.make("codex"), createdAt: now, threadId: asThreadId("thread-1"), turnId: asTurnId("turn-streaming-mode"), @@ -2025,7 +2040,7 @@ describe("ProviderRuntimeIngestion", () => { harness.emit({ type: "item.completed", eventId: asEventId("evt-message-completed-streaming-mode"), - provider: "codex", + provider: ProviderDriverKind.make("codex"), createdAt: now, threadId: asThreadId("thread-1"), turnId: asTurnId("turn-streaming-mode"), @@ -2058,7 +2073,7 @@ describe("ProviderRuntimeIngestion", () => { harness.emit({ type: "turn.started", eventId: asEventId("evt-turn-started-buffer-spill"), - provider: "codex", + provider: ProviderDriverKind.make("codex"), createdAt: now, threadId: asThreadId("thread-1"), turnId: asTurnId("turn-buffer-spill"), @@ -2073,7 +2088,7 @@ describe("ProviderRuntimeIngestion", () => { harness.emit({ type: "content.delta", eventId: asEventId("evt-message-delta-buffer-spill"), - provider: "codex", + provider: ProviderDriverKind.make("codex"), createdAt: now, threadId: asThreadId("thread-1"), turnId: asTurnId("turn-buffer-spill"), @@ -2086,7 +2101,7 @@ describe("ProviderRuntimeIngestion", () => { harness.emit({ type: "item.completed", eventId: asEventId("evt-message-completed-buffer-spill"), - provider: "codex", + provider: ProviderDriverKind.make("codex"), createdAt: now, threadId: asThreadId("thread-1"), turnId: asTurnId("turn-buffer-spill"), @@ -2118,7 +2133,7 @@ describe("ProviderRuntimeIngestion", () => { harness.emit({ type: "turn.started", eventId: asEventId("evt-turn-started-for-complete-dedup"), - provider: "codex", + provider: ProviderDriverKind.make("codex"), createdAt: now, threadId: asThreadId("thread-1"), turnId: asTurnId("turn-complete-dedup"), @@ -2134,7 +2149,7 @@ describe("ProviderRuntimeIngestion", () => { harness.emit({ type: "content.delta", eventId: asEventId("evt-message-delta-for-complete-dedup"), - provider: "codex", + provider: ProviderDriverKind.make("codex"), createdAt: now, threadId: asThreadId("thread-1"), turnId: asTurnId("turn-complete-dedup"), @@ -2147,7 +2162,7 @@ describe("ProviderRuntimeIngestion", () => { harness.emit({ type: "item.completed", eventId: asEventId("evt-message-completed-for-complete-dedup"), - provider: "codex", + provider: ProviderDriverKind.make("codex"), createdAt: now, threadId: asThreadId("thread-1"), turnId: asTurnId("turn-complete-dedup"), @@ -2160,7 +2175,7 @@ describe("ProviderRuntimeIngestion", () => { harness.emit({ type: "turn.completed", eventId: asEventId("evt-turn-completed-for-complete-dedup"), - provider: "codex", + provider: ProviderDriverKind.make("codex"), createdAt: now, threadId: asThreadId("thread-1"), turnId: asTurnId("turn-complete-dedup"), @@ -2204,7 +2219,7 @@ describe("ProviderRuntimeIngestion", () => { harness.emit({ type: "request.opened", eventId: asEventId("evt-request-opened"), - provider: "codex", + provider: ProviderDriverKind.make("codex"), createdAt: now, threadId: asThreadId("thread-1"), requestId: ApprovalRequestId.make("req-open"), @@ -2217,7 +2232,7 @@ describe("ProviderRuntimeIngestion", () => { harness.emit({ type: "request.resolved", eventId: asEventId("evt-request-resolved"), - provider: "codex", + provider: ProviderDriverKind.make("codex"), createdAt: now, threadId: asThreadId("thread-1"), requestId: ApprovalRequestId.make("req-open"), @@ -2270,7 +2285,7 @@ describe("ProviderRuntimeIngestion", () => { harness.emit({ type: "runtime.error", eventId: asEventId("evt-runtime-error"), - provider: "codex", + provider: ProviderDriverKind.make("codex"), createdAt: now, threadId: asThreadId("thread-1"), turnId: asTurnId("turn-3"), @@ -2297,7 +2312,7 @@ describe("ProviderRuntimeIngestion", () => { harness.emit({ type: "runtime.error", eventId: asEventId("evt-runtime-error-activity"), - provider: "codex", + provider: ProviderDriverKind.make("codex"), createdAt: now, threadId: asThreadId("thread-1"), turnId: asTurnId("turn-runtime-error-activity"), @@ -2328,7 +2343,7 @@ describe("ProviderRuntimeIngestion", () => { harness.emit({ type: "turn.started", eventId: asEventId("evt-warning-turn-started"), - provider: "codex", + provider: ProviderDriverKind.make("codex"), createdAt: now, threadId: asThreadId("thread-1"), turnId: asTurnId("turn-warning"), @@ -2338,7 +2353,7 @@ describe("ProviderRuntimeIngestion", () => { harness.emit({ type: "runtime.warning", eventId: asEventId("evt-warning-runtime"), - provider: "codex", + provider: ProviderDriverKind.make("codex"), createdAt: now, threadId: asThreadId("thread-1"), turnId: asTurnId("turn-warning"), @@ -2372,7 +2387,7 @@ describe("ProviderRuntimeIngestion", () => { harness.emit({ type: "session.started", eventId: asEventId("evt-session-started"), - provider: "codex", + provider: ProviderDriverKind.make("codex"), createdAt: now, threadId: asThreadId("thread-1"), message: "session started", @@ -2380,14 +2395,14 @@ describe("ProviderRuntimeIngestion", () => { harness.emit({ type: "thread.started", eventId: asEventId("evt-thread-started"), - provider: "codex", + provider: ProviderDriverKind.make("codex"), createdAt: now, threadId: asThreadId("thread-1"), }); harness.emit({ type: "item.started", eventId: asEventId("evt-tool-started"), - provider: "codex", + provider: ProviderDriverKind.make("codex"), createdAt: now, threadId: asThreadId("thread-1"), turnId: asTurnId("turn-9"), @@ -2424,7 +2439,7 @@ describe("ProviderRuntimeIngestion", () => { harness.emit({ type: "thread.metadata.updated", eventId: asEventId("evt-thread-metadata-updated"), - provider: "codex", + provider: ProviderDriverKind.make("codex"), createdAt: now, threadId: asThreadId("thread-1"), payload: { @@ -2436,7 +2451,7 @@ describe("ProviderRuntimeIngestion", () => { harness.emit({ type: "turn.plan.updated", eventId: asEventId("evt-turn-plan-updated"), - provider: "codex", + provider: ProviderDriverKind.make("codex"), createdAt: now, threadId: asThreadId("thread-1"), turnId: asTurnId("turn-p1"), @@ -2452,7 +2467,7 @@ describe("ProviderRuntimeIngestion", () => { harness.emit({ type: "item.updated", eventId: asEventId("evt-item-updated"), - provider: "codex", + provider: ProviderDriverKind.make("codex"), createdAt: now, threadId: asThreadId("thread-1"), turnId: asTurnId("turn-p1"), @@ -2469,7 +2484,7 @@ describe("ProviderRuntimeIngestion", () => { harness.emit({ type: "runtime.warning", eventId: asEventId("evt-runtime-warning"), - provider: "codex", + provider: ProviderDriverKind.make("codex"), createdAt: now, threadId: asThreadId("thread-1"), turnId: asTurnId("turn-p1"), @@ -2482,7 +2497,7 @@ describe("ProviderRuntimeIngestion", () => { harness.emit({ type: "turn.diff.updated", eventId: asEventId("evt-turn-diff-updated"), - provider: "codex", + provider: ProviderDriverKind.make("codex"), createdAt: now, threadId: asThreadId("thread-1"), turnId: asTurnId("turn-p1"), @@ -2558,7 +2573,7 @@ describe("ProviderRuntimeIngestion", () => { harness.emit({ type: "thread.token-usage.updated", eventId: asEventId("evt-thread-token-usage-updated"), - provider: "codex", + provider: ProviderDriverKind.make("codex"), createdAt: now, threadId: asThreadId("thread-1"), payload: { @@ -2610,7 +2625,7 @@ describe("ProviderRuntimeIngestion", () => { harness.emit({ type: "thread.token-usage.updated", eventId: asEventId("evt-thread-token-usage-updated-camel"), - provider: "codex", + provider: ProviderDriverKind.make("codex"), createdAt: now, threadId: asThreadId("thread-1"), payload: { @@ -2663,7 +2678,7 @@ describe("ProviderRuntimeIngestion", () => { harness.emit({ type: "thread.token-usage.updated", eventId: asEventId("evt-thread-token-usage-updated-claude-window"), - provider: "claudeAgent", + provider: ProviderDriverKind.make("claudeAgent"), createdAt: now, threadId: asThreadId("thread-1"), payload: { @@ -2707,7 +2722,7 @@ describe("ProviderRuntimeIngestion", () => { harness.emit({ type: "thread.state.changed", eventId: asEventId("evt-thread-compacted"), - provider: "codex", + provider: ProviderDriverKind.make("codex"), createdAt: now, threadId: asThreadId("thread-1"), turnId: asTurnId("turn-1"), @@ -2737,7 +2752,7 @@ describe("ProviderRuntimeIngestion", () => { harness.emit({ type: "task.started", eventId: asEventId("evt-task-started"), - provider: "codex", + provider: ProviderDriverKind.make("codex"), createdAt: now, threadId: asThreadId("thread-1"), turnId: asTurnId("turn-task-1"), @@ -2750,7 +2765,7 @@ describe("ProviderRuntimeIngestion", () => { harness.emit({ type: "task.progress", eventId: asEventId("evt-task-progress"), - provider: "codex", + provider: ProviderDriverKind.make("codex"), createdAt: now, threadId: asThreadId("thread-1"), turnId: asTurnId("turn-task-1"), @@ -2764,7 +2779,7 @@ describe("ProviderRuntimeIngestion", () => { harness.emit({ type: "task.completed", eventId: asEventId("evt-task-completed"), - provider: "codex", + provider: ProviderDriverKind.make("codex"), createdAt: now, threadId: asThreadId("thread-1"), turnId: asTurnId("turn-task-1"), @@ -2777,7 +2792,7 @@ describe("ProviderRuntimeIngestion", () => { harness.emit({ type: "turn.proposed.completed", eventId: asEventId("evt-task-proposed-plan-completed"), - provider: "codex", + provider: ProviderDriverKind.make("codex"), createdAt: now, threadId: asThreadId("thread-1"), turnId: asTurnId("turn-task-1"), @@ -2840,7 +2855,7 @@ describe("ProviderRuntimeIngestion", () => { harness.emit({ type: "user-input.requested", eventId: asEventId("evt-user-input-requested"), - provider: "codex", + provider: ProviderDriverKind.make("codex"), createdAt: now, threadId: asThreadId("thread-1"), turnId: asTurnId("turn-user-input"), @@ -2865,7 +2880,7 @@ describe("ProviderRuntimeIngestion", () => { harness.emit({ type: "user-input.resolved", eventId: asEventId("evt-user-input-resolved"), - provider: "codex", + provider: ProviderDriverKind.make("codex"), createdAt: new Date().toISOString(), threadId: asThreadId("thread-1"), turnId: asTurnId("turn-user-input"), @@ -2913,7 +2928,7 @@ describe("ProviderRuntimeIngestion", () => { harness.emit({ type: "content.delta", eventId: asEventId("evt-invalid-delta"), - provider: "codex", + provider: ProviderDriverKind.make("codex"), createdAt: now, threadId: asThreadId("thread-1"), turnId: asTurnId("turn-invalid"), @@ -2927,7 +2942,7 @@ describe("ProviderRuntimeIngestion", () => { harness.emit({ type: "runtime.error", eventId: asEventId("evt-runtime-error-after-failure"), - provider: "codex", + provider: ProviderDriverKind.make("codex"), createdAt: new Date().toISOString(), threadId: asThreadId("thread-1"), turnId: asTurnId("turn-after-failure"), diff --git a/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts b/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts index 7eeeed2d51..b7a4c195a5 100644 --- a/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts +++ b/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts @@ -1211,6 +1211,9 @@ const make = Effect.gen(function* () { threadId: thread.id, status, providerName: event.provider, + ...(event.providerInstanceId !== undefined + ? { providerInstanceId: event.providerInstanceId } + : {}), runtimeMode: thread.session?.runtimeMode ?? "full-access", activeTurnId: nextActiveTurnId, lastError, @@ -1456,6 +1459,9 @@ const make = Effect.gen(function* () { threadId: thread.id, status: "error", providerName: event.provider, + ...(event.providerInstanceId !== undefined + ? { providerInstanceId: event.providerInstanceId } + : {}), runtimeMode: thread.session?.runtimeMode ?? "full-access", activeTurnId: eventTurnId ?? null, lastError: runtimeErrorMessage, diff --git a/apps/server/src/orchestration/commandInvariants.test.ts b/apps/server/src/orchestration/commandInvariants.test.ts index a678bcea16..1e33a355d0 100644 --- a/apps/server/src/orchestration/commandInvariants.test.ts +++ b/apps/server/src/orchestration/commandInvariants.test.ts @@ -7,6 +7,7 @@ import { ThreadId, type OrchestrationCommand, type OrchestrationReadModel, + ProviderInstanceId, } from "@t3tools/contracts"; import { Effect } from "effect"; @@ -29,7 +30,7 @@ const readModel: OrchestrationReadModel = { title: "Project A", workspaceRoot: "/tmp/project-a", defaultModelSelection: { - provider: "codex", + instanceId: ProviderInstanceId.make("codex"), model: "gpt-5-codex", }, scripts: [], @@ -42,7 +43,7 @@ const readModel: OrchestrationReadModel = { title: "Project B", workspaceRoot: "/tmp/project-b", defaultModelSelection: { - provider: "codex", + instanceId: ProviderInstanceId.make("codex"), model: "gpt-5-codex", }, scripts: [], @@ -57,7 +58,7 @@ const readModel: OrchestrationReadModel = { projectId: ProjectId.make("project-a"), title: "Thread A", modelSelection: { - provider: "codex", + instanceId: ProviderInstanceId.make("codex"), model: "gpt-5-codex", }, interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE, @@ -80,7 +81,7 @@ const readModel: OrchestrationReadModel = { projectId: ProjectId.make("project-b"), title: "Thread B", modelSelection: { - provider: "codex", + instanceId: ProviderInstanceId.make("codex"), model: "gpt-5-codex", }, interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE, @@ -157,7 +158,7 @@ describe("commandInvariants", () => { projectId: ProjectId.make("project-a"), title: "new", modelSelection: { - provider: "codex", + instanceId: ProviderInstanceId.make("codex"), model: "gpt-5-codex", }, interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE, @@ -181,7 +182,7 @@ describe("commandInvariants", () => { projectId: ProjectId.make("project-a"), title: "dup", modelSelection: { - provider: "codex", + instanceId: ProviderInstanceId.make("codex"), model: "gpt-5-codex", }, interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE, diff --git a/apps/server/src/orchestration/decider.delete.test.ts b/apps/server/src/orchestration/decider.delete.test.ts index 2b32371493..548fcc0b68 100644 --- a/apps/server/src/orchestration/decider.delete.test.ts +++ b/apps/server/src/orchestration/decider.delete.test.ts @@ -7,6 +7,7 @@ import { type OrchestrationCommand, type OrchestrationEvent, type OrchestrationReadModel, + ProviderInstanceId, } from "@t3tools/contracts"; import { Effect } from "effect"; import { describe, expect, it } from "vitest"; @@ -63,7 +64,7 @@ async function seedReadModel(): Promise { projectId: asProjectId("project-delete"), title: "Thread Delete 1", modelSelection: { - provider: "codex", + instanceId: ProviderInstanceId.make("codex"), model: "gpt-5-codex", }, interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE, @@ -93,7 +94,7 @@ async function seedReadModel(): Promise { projectId: asProjectId("project-delete"), title: "Thread Delete 2", modelSelection: { - provider: "codex", + instanceId: ProviderInstanceId.make("codex"), model: "gpt-5-codex", }, interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE, diff --git a/apps/server/src/orchestration/decider.projectScripts.test.ts b/apps/server/src/orchestration/decider.projectScripts.test.ts index 1feabb0ed8..2356609919 100644 --- a/apps/server/src/orchestration/decider.projectScripts.test.ts +++ b/apps/server/src/orchestration/decider.projectScripts.test.ts @@ -5,6 +5,7 @@ import { MessageId, ProjectId, ThreadId, + ProviderInstanceId, } from "@t3tools/contracts"; import { createModelSelection } from "@t3tools/shared/model"; import { describe, expect, it } from "vitest"; @@ -138,7 +139,7 @@ describe("decider project scripts", () => { projectId: asProjectId("project-1"), title: "Thread", modelSelection: { - provider: "codex", + instanceId: ProviderInstanceId.make("codex"), model: "gpt-5-codex", }, interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE, @@ -163,7 +164,7 @@ describe("decider project scripts", () => { text: "hello", attachments: [], }, - modelSelection: createModelSelection("codex", "gpt-5.3-codex", [ + modelSelection: createModelSelection(ProviderInstanceId.make("codex"), "gpt-5.3-codex", [ { id: "reasoningEffort", value: "high" }, { id: "fastMode", value: true }, ]), @@ -188,7 +189,7 @@ describe("decider project scripts", () => { expect(turnStartEvent.payload).toMatchObject({ threadId: ThreadId.make("thread-1"), messageId: asMessageId("message-user-1"), - modelSelection: createModelSelection("codex", "gpt-5.3-codex", [ + modelSelection: createModelSelection(ProviderInstanceId.make("codex"), "gpt-5.3-codex", [ { id: "reasoningEffort", value: "high" }, { id: "fastMode", value: true }, ]), @@ -239,7 +240,7 @@ describe("decider project scripts", () => { projectId: asProjectId("project-1"), title: "Thread", modelSelection: { - provider: "codex", + instanceId: ProviderInstanceId.make("codex"), model: "gpt-5-codex", }, interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE, @@ -321,7 +322,7 @@ describe("decider project scripts", () => { projectId: asProjectId("project-1"), title: "Thread", modelSelection: { - provider: "codex", + instanceId: ProviderInstanceId.make("codex"), model: "gpt-5-codex", }, interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE, diff --git a/apps/server/src/orchestration/projector.test.ts b/apps/server/src/orchestration/projector.test.ts index a61153bb52..b50bc2da59 100644 --- a/apps/server/src/orchestration/projector.test.ts +++ b/apps/server/src/orchestration/projector.test.ts @@ -2,6 +2,7 @@ import { CommandId, EventId, ProjectId, + ProviderDriverKind, ThreadId, type OrchestrationEvent, } from "@t3tools/contracts"; @@ -57,7 +58,7 @@ describe("orchestration projector", () => { projectId: "project-1", title: "demo", modelSelection: { - provider: "codex", + provider: ProviderDriverKind.make("codex"), model: "gpt-5-codex", }, runtimeMode: "full-access", @@ -77,7 +78,7 @@ describe("orchestration projector", () => { projectId: "project-1", title: "demo", modelSelection: { - provider: "codex", + instanceId: "codex", model: "gpt-5-codex", }, runtimeMode: "full-access", @@ -118,7 +119,7 @@ describe("orchestration projector", () => { projectId: "project-1", title: "demo", modelSelection: { - provider: "codex", + provider: ProviderDriverKind.make("codex"), model: "gpt-5-codex", }, branch: null, @@ -150,7 +151,7 @@ describe("orchestration projector", () => { projectId: "project-1", title: "demo", modelSelection: { - provider: "codex", + provider: ProviderDriverKind.make("codex"), model: "gpt-5-codex", }, runtimeMode: "full-access", @@ -253,7 +254,7 @@ describe("orchestration projector", () => { projectId: "project-1", title: "demo", modelSelection: { - provider: "codex", + provider: ProviderDriverKind.make("codex"), model: "gpt-5.3-codex", }, runtimeMode: "full-access", @@ -319,7 +320,7 @@ describe("orchestration projector", () => { projectId: "project-1", title: "demo", modelSelection: { - provider: "codex", + provider: ProviderDriverKind.make("codex"), model: "gpt-5.3-codex", }, runtimeMode: "full-access", @@ -376,7 +377,7 @@ describe("orchestration projector", () => { projectId: "project-1", title: "demo", modelSelection: { - provider: "codex", + provider: ProviderDriverKind.make("codex"), model: "gpt-5.3-codex", }, runtimeMode: "full-access", @@ -463,7 +464,7 @@ describe("orchestration projector", () => { projectId: "project-1", title: "demo", modelSelection: { - provider: "codex", + provider: ProviderDriverKind.make("codex"), model: "gpt-5.3-codex", }, runtimeMode: "full-access", @@ -678,7 +679,7 @@ describe("orchestration projector", () => { projectId: "project-1", title: "demo", modelSelection: { - provider: "codex", + provider: ProviderDriverKind.make("codex"), model: "gpt-5.3-codex", }, runtimeMode: "full-access", @@ -831,7 +832,7 @@ describe("orchestration projector", () => { projectId: "project-1", title: "capped", modelSelection: { - provider: "codex", + provider: ProviderDriverKind.make("codex"), model: "gpt-5-codex", }, runtimeMode: "full-access", diff --git a/apps/server/src/persistence/Layers/ProjectionRepositories.test.ts b/apps/server/src/persistence/Layers/ProjectionRepositories.test.ts index d42be69945..fc5f7a5c15 100644 --- a/apps/server/src/persistence/Layers/ProjectionRepositories.test.ts +++ b/apps/server/src/persistence/Layers/ProjectionRepositories.test.ts @@ -1,4 +1,4 @@ -import { ProjectId, ThreadId } from "@t3tools/contracts"; +import { ProjectId, ThreadId, ProviderInstanceId } from "@t3tools/contracts"; import { assert, it } from "@effect/vitest"; import { Effect, Layer, Option } from "effect"; import * as SqlClient from "effect/unstable/sql/SqlClient"; @@ -28,7 +28,7 @@ projectionRepositoriesLayer("Projection repositories", (it) => { title: "Null options project", workspaceRoot: "/tmp/project-null-options", defaultModelSelection: { - provider: "codex", + instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4", }, scripts: [], @@ -52,7 +52,7 @@ projectionRepositoriesLayer("Projection repositories", (it) => { assert.strictEqual( row.defaultModelSelection, JSON.stringify({ - provider: "codex", + instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4", }), ); @@ -61,7 +61,7 @@ projectionRepositoriesLayer("Projection repositories", (it) => { projectId: ProjectId.make("project-null-options"), }); assert.deepStrictEqual(Option.getOrNull(persisted)?.defaultModelSelection, { - provider: "codex", + instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4", }); }), @@ -77,7 +77,7 @@ projectionRepositoriesLayer("Projection repositories", (it) => { projectId: ProjectId.make("project-null-options"), title: "Null options thread", modelSelection: { - provider: "claudeAgent", + instanceId: ProviderInstanceId.make("claudeAgent"), model: "claude-opus-4-6", }, runtimeMode: "full-access", @@ -110,7 +110,7 @@ projectionRepositoriesLayer("Projection repositories", (it) => { assert.strictEqual( row.modelSelection, JSON.stringify({ - provider: "claudeAgent", + instanceId: ProviderInstanceId.make("claudeAgent"), model: "claude-opus-4-6", }), ); @@ -119,7 +119,7 @@ projectionRepositoriesLayer("Projection repositories", (it) => { threadId: ThreadId.make("thread-null-options"), }); assert.deepStrictEqual(Option.getOrNull(persisted)?.modelSelection, { - provider: "claudeAgent", + instanceId: ProviderInstanceId.make("claudeAgent"), model: "claude-opus-4-6", }); }), diff --git a/apps/server/src/persistence/Layers/ProjectionThreadSessions.ts b/apps/server/src/persistence/Layers/ProjectionThreadSessions.ts index 2499eba196..80d241436f 100644 --- a/apps/server/src/persistence/Layers/ProjectionThreadSessions.ts +++ b/apps/server/src/persistence/Layers/ProjectionThreadSessions.ts @@ -23,6 +23,7 @@ const makeProjectionThreadSessionRepository = Effect.gen(function* () { thread_id, status, provider_name, + provider_instance_id, runtime_mode, active_turn_id, last_error, @@ -32,6 +33,7 @@ const makeProjectionThreadSessionRepository = Effect.gen(function* () { ${row.threadId}, ${row.status}, ${row.providerName}, + ${row.providerInstanceId}, ${row.runtimeMode}, ${row.activeTurnId}, ${row.lastError}, @@ -41,6 +43,7 @@ const makeProjectionThreadSessionRepository = Effect.gen(function* () { DO UPDATE SET status = excluded.status, provider_name = excluded.provider_name, + provider_instance_id = excluded.provider_instance_id, runtime_mode = excluded.runtime_mode, active_turn_id = excluded.active_turn_id, last_error = excluded.last_error, @@ -57,6 +60,7 @@ const makeProjectionThreadSessionRepository = Effect.gen(function* () { thread_id AS "threadId", status, provider_name AS "providerName", + provider_instance_id AS "providerInstanceId", runtime_mode AS "runtimeMode", active_turn_id AS "activeTurnId", last_error AS "lastError", diff --git a/apps/server/src/persistence/Layers/ProviderSessionRuntime.ts b/apps/server/src/persistence/Layers/ProviderSessionRuntime.ts index da3e8bce90..778e0c6d2e 100644 --- a/apps/server/src/persistence/Layers/ProviderSessionRuntime.ts +++ b/apps/server/src/persistence/Layers/ProviderSessionRuntime.ts @@ -46,6 +46,7 @@ const makeProviderSessionRuntimeRepository = Effect.gen(function* () { INSERT INTO provider_session_runtime ( thread_id, provider_name, + provider_instance_id, adapter_key, runtime_mode, status, @@ -56,6 +57,7 @@ const makeProviderSessionRuntimeRepository = Effect.gen(function* () { VALUES ( ${runtime.threadId}, ${runtime.providerName}, + ${runtime.providerInstanceId}, ${runtime.adapterKey}, ${runtime.runtimeMode}, ${runtime.status}, @@ -66,6 +68,7 @@ const makeProviderSessionRuntimeRepository = Effect.gen(function* () { ON CONFLICT (thread_id) DO UPDATE SET provider_name = excluded.provider_name, + provider_instance_id = excluded.provider_instance_id, adapter_key = excluded.adapter_key, runtime_mode = excluded.runtime_mode, status = excluded.status, @@ -83,6 +86,7 @@ const makeProviderSessionRuntimeRepository = Effect.gen(function* () { SELECT thread_id AS "threadId", provider_name AS "providerName", + provider_instance_id AS "providerInstanceId", adapter_key AS "adapterKey", runtime_mode AS "runtimeMode", status, @@ -102,6 +106,7 @@ const makeProviderSessionRuntimeRepository = Effect.gen(function* () { SELECT thread_id AS "threadId", provider_name AS "providerName", + provider_instance_id AS "providerInstanceId", adapter_key AS "adapterKey", runtime_mode AS "runtimeMode", status, diff --git a/apps/server/src/persistence/Migrations.ts b/apps/server/src/persistence/Migrations.ts index c8d4647fb7..025e9e4831 100644 --- a/apps/server/src/persistence/Migrations.ts +++ b/apps/server/src/persistence/Migrations.ts @@ -39,6 +39,8 @@ import Migration0023 from "./Migrations/023_ProjectionThreadShellSummary.ts"; import Migration0024 from "./Migrations/024_BackfillProjectionThreadShellSummary.ts"; import Migration0025 from "./Migrations/025_CleanupInvalidProjectionPendingApprovals.ts"; import Migration0026 from "./Migrations/026_CanonicalizeModelSelectionOptions.ts"; +import Migration0027 from "./Migrations/027_ProviderSessionRuntimeInstanceId.ts"; +import Migration0028 from "./Migrations/028_ProjectionThreadSessionInstanceId.ts"; /** * Migration loader with all migrations defined inline. @@ -77,6 +79,8 @@ export const migrationEntries = [ [24, "BackfillProjectionThreadShellSummary", Migration0024], [25, "CleanupInvalidProjectionPendingApprovals", Migration0025], [26, "CanonicalizeModelSelectionOptions", Migration0026], + [27, "ProviderSessionRuntimeInstanceId", Migration0027], + [28, "ProjectionThreadSessionInstanceId", Migration0028], ] as const; export const makeMigrationLoader = (throughId?: number) => diff --git a/apps/server/src/persistence/Migrations/027_028_ProviderInstanceIdColumns.test.ts b/apps/server/src/persistence/Migrations/027_028_ProviderInstanceIdColumns.test.ts new file mode 100644 index 0000000000..3233f5043a --- /dev/null +++ b/apps/server/src/persistence/Migrations/027_028_ProviderInstanceIdColumns.test.ts @@ -0,0 +1,74 @@ +import { assert, it } from "@effect/vitest"; +import { Effect, Layer } from "effect"; +import * as SqlClient from "effect/unstable/sql/SqlClient"; + +import { runMigrations } from "../Migrations.ts"; +import * as NodeSqliteClient from "../NodeSqliteClient.ts"; + +const layer = it.layer(Layer.mergeAll(NodeSqliteClient.layerMemory())); + +layer("027_028_ProviderInstanceIdColumns", (it) => { + it.effect("continues when provider_session_runtime was partially migrated", () => + Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + + yield* runMigrations({ toMigrationInclusive: 26 }); + yield* sql` + ALTER TABLE provider_session_runtime + ADD COLUMN provider_instance_id TEXT + `; + + yield* runMigrations({ toMigrationInclusive: 28 }); + + const migrations = yield* sql<{ + readonly migration_id: number; + readonly name: string; + }>` + SELECT migration_id, name + FROM effect_sql_migrations + WHERE migration_id IN (27, 28) + ORDER BY migration_id + `; + assert.deepStrictEqual(migrations, [ + { + migration_id: 27, + name: "ProviderSessionRuntimeInstanceId", + }, + { + migration_id: 28, + name: "ProjectionThreadSessionInstanceId", + }, + ]); + + const providerSessionColumns = yield* sql<{ readonly name: string }>` + PRAGMA table_info(provider_session_runtime) + `; + assert.ok(providerSessionColumns.some((column) => column.name === "provider_instance_id")); + + const projectionThreadSessionColumns = yield* sql<{ readonly name: string }>` + PRAGMA table_info(projection_thread_sessions) + `; + assert.ok( + projectionThreadSessionColumns.some((column) => column.name === "provider_instance_id"), + ); + + const providerSessionIndexes = yield* sql<{ readonly name: string }>` + PRAGMA index_list(provider_session_runtime) + `; + assert.ok( + providerSessionIndexes.some( + (index) => index.name === "idx_provider_session_runtime_instance", + ), + ); + + const projectionThreadSessionIndexes = yield* sql<{ readonly name: string }>` + PRAGMA index_list(projection_thread_sessions) + `; + assert.ok( + projectionThreadSessionIndexes.some( + (index) => index.name === "idx_projection_thread_sessions_instance", + ), + ); + }), + ); +}); diff --git a/apps/server/src/persistence/Migrations/027_ProviderSessionRuntimeInstanceId.ts b/apps/server/src/persistence/Migrations/027_ProviderSessionRuntimeInstanceId.ts new file mode 100644 index 0000000000..7ae0e55b13 --- /dev/null +++ b/apps/server/src/persistence/Migrations/027_ProviderSessionRuntimeInstanceId.ts @@ -0,0 +1,38 @@ +/** + * Adds the nullable `provider_instance_id` routing column to + * `provider_session_runtime`. + * + * Slice D of the provider-array refactor splits "driver kind" from + * "configured instance". Existing rows have only the driver name in + * `provider_name`; new rows additionally carry the user-defined instance + * routing key. The column remains nullable so legacy rows can still decode; + * the persistence boundary is responsible for materializing a concrete + * instance id before any hot routing path sees the binding. + * + * The column is nullable on purpose — backfilling it during the migration + * would require knowing which configured instance "owned" each historical + * session, and that mapping is ambiguous when the user later configures + * multiple instances of the same driver. Keeping that compatibility at the + * persistence boundary keeps the fallback out of active routing code. + */ +import * as SqlClient from "effect/unstable/sql/SqlClient"; +import * as Effect from "effect/Effect"; + +export default Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + + const columns = yield* sql<{ readonly name: string }>` + PRAGMA table_info(provider_session_runtime) + `; + if (!columns.some((column) => column.name === "provider_instance_id")) { + yield* sql` + ALTER TABLE provider_session_runtime + ADD COLUMN provider_instance_id TEXT + `; + } + + yield* sql` + CREATE INDEX IF NOT EXISTS idx_provider_session_runtime_instance + ON provider_session_runtime(provider_instance_id) + `; +}); diff --git a/apps/server/src/persistence/Migrations/028_ProjectionThreadSessionInstanceId.ts b/apps/server/src/persistence/Migrations/028_ProjectionThreadSessionInstanceId.ts new file mode 100644 index 0000000000..bc4ba98044 --- /dev/null +++ b/apps/server/src/persistence/Migrations/028_ProjectionThreadSessionInstanceId.ts @@ -0,0 +1,21 @@ +import * as SqlClient from "effect/unstable/sql/SqlClient"; +import * as Effect from "effect/Effect"; + +export default Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + + const columns = yield* sql<{ readonly name: string }>` + PRAGMA table_info(projection_thread_sessions) + `; + if (!columns.some((column) => column.name === "provider_instance_id")) { + yield* sql` + ALTER TABLE projection_thread_sessions + ADD COLUMN provider_instance_id TEXT + `; + } + + yield* sql` + CREATE INDEX IF NOT EXISTS idx_projection_thread_sessions_instance + ON projection_thread_sessions(provider_instance_id) + `; +}); diff --git a/apps/server/src/persistence/Services/ProjectionThreadSessions.ts b/apps/server/src/persistence/Services/ProjectionThreadSessions.ts index fcd13f068d..5d2c3c87d1 100644 --- a/apps/server/src/persistence/Services/ProjectionThreadSessions.ts +++ b/apps/server/src/persistence/Services/ProjectionThreadSessions.ts @@ -10,6 +10,7 @@ import { RuntimeMode, IsoDateTime, OrchestrationSessionStatus, + ProviderInstanceId, ThreadId, TurnId, } from "@t3tools/contracts"; @@ -22,6 +23,7 @@ export const ProjectionThreadSession = Schema.Struct({ threadId: ThreadId, status: OrchestrationSessionStatus, providerName: Schema.NullOr(Schema.String), + providerInstanceId: Schema.NullOr(ProviderInstanceId), runtimeMode: RuntimeMode, activeTurnId: Schema.NullOr(TurnId), lastError: Schema.NullOr(Schema.String), diff --git a/apps/server/src/persistence/Services/ProviderSessionRuntime.ts b/apps/server/src/persistence/Services/ProviderSessionRuntime.ts index bf8e658e8a..6ba15b32d9 100644 --- a/apps/server/src/persistence/Services/ProviderSessionRuntime.ts +++ b/apps/server/src/persistence/Services/ProviderSessionRuntime.ts @@ -7,6 +7,7 @@ */ import { IsoDateTime, + ProviderInstanceId, ProviderSessionRuntimeStatus, RuntimeMode, ThreadId, @@ -19,6 +20,14 @@ import type { ProviderSessionRuntimeRepositoryError } from "../Errors.ts"; export const ProviderSessionRuntime = Schema.Struct({ threadId: ThreadId, providerName: Schema.String, + /** + * User-defined routing key for the configured provider instance that + * owns this session. Nullable only at the storage/migration boundary: + * rows persisted before the driver/instance split carry only + * `providerName`. Repository consumers must materialize a concrete + * instance id before routing. + */ + providerInstanceId: Schema.NullOr(ProviderInstanceId), adapterKey: Schema.String, runtimeMode: RuntimeMode, status: ProviderSessionRuntimeStatus, diff --git a/apps/server/src/provider/Drivers/ClaudeDriver.ts b/apps/server/src/provider/Drivers/ClaudeDriver.ts new file mode 100644 index 0000000000..feddd3b86b --- /dev/null +++ b/apps/server/src/provider/Drivers/ClaudeDriver.ts @@ -0,0 +1,157 @@ +/** + * ClaudeDriver — `ProviderDriver` for the Claude Agent SDK runtime. + * + * Mirrors `CodexDriver`: a plain value whose `create()` returns one + * `ProviderInstance` bundling `snapshot` / `adapter` / `textGeneration` + * closures captured over the per-instance `ClaudeSettings`. + * + * Unlike Codex, the Claude snapshot probe may invoke a secondary probe + * (`probeClaudeCapabilities`) to read Anthropic account + slash-command + * metadata. That probe is per-instance and keyed by binary + resolved HOME so + * two concurrent Claude instances don't cross-contaminate account metadata. + * + * @module provider/Drivers/ClaudeDriver + */ +import { ClaudeSettings, ProviderDriverKind, type ServerProvider } from "@t3tools/contracts"; +import { Cache, Duration, Effect, FileSystem, Path, Schema, Stream } from "effect"; +import { ChildProcessSpawner } from "effect/unstable/process"; + +import { makeClaudeTextGeneration } from "../../git/Layers/ClaudeTextGeneration.ts"; +import { ServerConfig } from "../../config.ts"; +import { ProviderDriverError } from "../Errors.ts"; +import { makeClaudeAdapter } from "../Layers/ClaudeAdapter.ts"; +import { + checkClaudeProviderStatus, + makePendingClaudeProvider, + probeClaudeCapabilities, +} from "../Layers/ClaudeProvider.ts"; +import { ProviderEventLoggers } from "../Layers/ProviderEventLoggers.ts"; +import { makeManagedServerProvider } from "../makeManagedServerProvider.ts"; +import { + defaultProviderContinuationIdentity, + type ProviderDriver, + type ProviderInstance, +} from "../ProviderDriver.ts"; +import type { ServerProviderDraft } from "../providerSnapshot.ts"; +import { mergeProviderInstanceEnvironment } from "../ProviderInstanceEnvironment.ts"; +import { makeClaudeCapabilitiesCacheKey, makeClaudeContinuationGroupKey } from "./ClaudeHome.ts"; + +const DRIVER_KIND = ProviderDriverKind.make("claudeAgent"); +const SNAPSHOT_REFRESH_INTERVAL = Duration.minutes(5); +const CAPABILITIES_PROBE_TTL = Duration.minutes(5); + +export type ClaudeDriverEnv = + | ChildProcessSpawner.ChildProcessSpawner + | FileSystem.FileSystem + | Path.Path + | ProviderEventLoggers + | ServerConfig; + +const withInstanceIdentity = + (input: { + readonly instanceId: ProviderInstance["instanceId"]; + readonly displayName: string | undefined; + readonly accentColor: string | undefined; + readonly continuationGroupKey: string; + }) => + (snapshot: ServerProviderDraft): ServerProvider => ({ + ...snapshot, + instanceId: input.instanceId, + driver: DRIVER_KIND, + ...(input.displayName ? { displayName: input.displayName } : {}), + ...(input.accentColor ? { accentColor: input.accentColor } : {}), + continuation: { groupKey: input.continuationGroupKey }, + }); + +export const ClaudeDriver: ProviderDriver = { + driverKind: DRIVER_KIND, + metadata: { + displayName: "Claude", + supportsMultipleInstances: true, + }, + configSchema: ClaudeSettings, + defaultConfig: (): ClaudeSettings => Schema.decodeSync(ClaudeSettings)({}), + create: ({ instanceId, displayName, accentColor, environment, enabled, config }) => + Effect.gen(function* () { + const spawner = yield* ChildProcessSpawner.ChildProcessSpawner; + const path = yield* Path.Path; + const eventLoggers = yield* ProviderEventLoggers; + const processEnv = mergeProviderInstanceEnvironment(environment); + const fallbackContinuationIdentity = defaultProviderContinuationIdentity({ + driverKind: DRIVER_KIND, + instanceId, + }); + const effectiveConfig = { ...config, enabled } satisfies ClaudeSettings; + const continuationGroupKey = yield* makeClaudeContinuationGroupKey(effectiveConfig); + const stampIdentity = withInstanceIdentity({ + instanceId, + displayName, + accentColor, + continuationGroupKey, + }); + + const adapterOptions = { + instanceId, + environment: processEnv, + ...(eventLoggers.native ? { nativeEventLogger: eventLoggers.native } : {}), + }; + const adapter = yield* makeClaudeAdapter(effectiveConfig, adapterOptions); + const textGeneration = yield* makeClaudeTextGeneration(effectiveConfig, processEnv); + + // Per-instance capabilities cache: keyed on binary + resolved HOME so + // account-specific probes never share auth metadata across instances. + const capabilitiesProbeCache = yield* Cache.make({ + capacity: 1, + timeToLive: CAPABILITIES_PROBE_TTL, + lookup: () => + probeClaudeCapabilities(effectiveConfig, processEnv).pipe( + Effect.provideService(Path.Path, path), + ), + }); + const capabilitiesCacheKey = yield* makeClaudeCapabilitiesCacheKey(effectiveConfig); + + const checkProvider = checkClaudeProviderStatus( + effectiveConfig, + () => Cache.get(capabilitiesProbeCache, capabilitiesCacheKey), + processEnv, + ).pipe( + Effect.map(stampIdentity), + Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner), + Effect.provideService(Path.Path, path), + ); + + const snapshot = yield* makeManagedServerProvider({ + getSettings: Effect.succeed(effectiveConfig), + streamSettings: Stream.never, + haveSettingsChanged: () => false, + initialSnapshot: (settings) => stampIdentity(makePendingClaudeProvider(settings)), + checkProvider, + refreshInterval: SNAPSHOT_REFRESH_INTERVAL, + }).pipe( + Effect.mapError( + (cause) => + new ProviderDriverError({ + driver: DRIVER_KIND, + instanceId, + detail: `Failed to build Claude snapshot: ${cause.message ?? String(cause)}`, + cause, + }), + ), + ); + + return { + instanceId, + driverKind: DRIVER_KIND, + continuationIdentity: { + ...fallbackContinuationIdentity, + continuationKey: continuationGroupKey, + }, + displayName, + accentColor, + enabled, + snapshot, + adapter, + textGeneration, + } satisfies ProviderInstance; + }), +}; diff --git a/apps/server/src/provider/Drivers/ClaudeHome.test.ts b/apps/server/src/provider/Drivers/ClaudeHome.test.ts new file mode 100644 index 0000000000..84c9c331cc --- /dev/null +++ b/apps/server/src/provider/Drivers/ClaudeHome.test.ts @@ -0,0 +1,52 @@ +import * as NodeOS from "node:os"; + +import * as NodeServices from "@effect/platform-node/NodeServices"; +import { describe, expect, it } from "@effect/vitest"; +import { Effect, Path } from "effect"; + +import { + makeClaudeCapabilitiesCacheKey, + makeClaudeContinuationGroupKey, + makeClaudeEnvironment, + resolveClaudeHomePath, +} from "./ClaudeHome.ts"; + +it.layer(NodeServices.layer)("ClaudeHome", (it) => { + describe("Claude home resolution", () => { + it.effect("uses the process home when no Claude home override is configured", () => + Effect.gen(function* () { + const path = yield* Path.Path; + const resolved = path.resolve(NodeOS.homedir()); + + expect(yield* resolveClaudeHomePath({ homePath: "" })).toBe(resolved); + expect(yield* makeClaudeEnvironment({ homePath: "" })).toBe(process.env); + }), + ); + + it.effect("resolves configured Claude HOME and stamps continuation/cache keys with it", () => + Effect.gen(function* () { + const path = yield* Path.Path; + const homePath = "~/.claude-work"; + const resolved = path.resolve(NodeOS.homedir(), ".claude-work"); + + expect(yield* resolveClaudeHomePath({ homePath })).toBe(resolved); + expect((yield* makeClaudeEnvironment({ homePath })).HOME).toBe(resolved); + expect(yield* makeClaudeContinuationGroupKey({ homePath })).toBe(`claude:home:${resolved}`); + expect(yield* makeClaudeCapabilitiesCacheKey({ binaryPath: "claude", homePath })).toBe( + `claude\0${resolved}`, + ); + }), + ); + + it.effect("keeps continuation compatible across instances with the same Claude HOME", () => + Effect.gen(function* () { + const path = yield* Path.Path; + const resolved = path.resolve(NodeOS.homedir()); + + expect(yield* makeClaudeContinuationGroupKey({ homePath: "" })).toBe( + `claude:home:${resolved}`, + ); + }), + ); + }); +}); diff --git a/apps/server/src/provider/Drivers/ClaudeHome.ts b/apps/server/src/provider/Drivers/ClaudeHome.ts new file mode 100644 index 0000000000..c959096677 --- /dev/null +++ b/apps/server/src/provider/Drivers/ClaudeHome.ts @@ -0,0 +1,43 @@ +import * as NodeOS from "node:os"; + +import type { ClaudeSettings } from "@t3tools/contracts"; +import { Effect, Path } from "effect"; + +import { expandHomePath } from "../../pathExpansion.ts"; + +export const resolveClaudeHomePath = Effect.fn("resolveClaudeHomePath")(function* ( + config: Pick, +): Effect.fn.Return { + const path = yield* Path.Path; + const homePath = config.homePath.trim(); + return path.resolve(homePath.length > 0 ? expandHomePath(homePath) : NodeOS.homedir()); +}); + +export const makeClaudeEnvironment = Effect.fn("makeClaudeEnvironment")(function* ( + config: Pick, + baseEnv: NodeJS.ProcessEnv = process.env, +): Effect.fn.Return { + const homePath = config.homePath.trim(); + if (homePath.length === 0) return baseEnv; + const resolvedHomePath = yield* resolveClaudeHomePath(config); + return { + ...baseEnv, + HOME: resolvedHomePath, + }; +}); + +export const makeClaudeContinuationGroupKey = Effect.fn("makeClaudeContinuationGroupKey")( + function* (config: Pick): Effect.fn.Return { + const resolvedHomePath = yield* resolveClaudeHomePath(config); + return `claude:home:${resolvedHomePath}`; + }, +); + +export const makeClaudeCapabilitiesCacheKey = Effect.fn("makeClaudeCapabilitiesCacheKey")( + function* ( + config: Pick, + ): Effect.fn.Return { + const resolvedHomePath = yield* resolveClaudeHomePath(config); + return `${config.binaryPath}\0${resolvedHomePath}`; + }, +); diff --git a/apps/server/src/provider/Drivers/CodexDriver.ts b/apps/server/src/provider/Drivers/CodexDriver.ts new file mode 100644 index 0000000000..13598ab5f6 --- /dev/null +++ b/apps/server/src/provider/Drivers/CodexDriver.ts @@ -0,0 +1,171 @@ +/** + * CodexDriver — first concrete `ProviderDriver` in the new per-instance model. + * + * A driver is a plain value (not a Context.Service) whose `create()` returns + * one `ProviderInstance` bundling: + * - `snapshot` — the live `ServerProviderShape` for this instance; + * - `adapter` — the Codex session/turn/approval runtime; + * - `textGeneration` — commit/PR/branch/title generation via `codex exec`. + * + * Each call to `create()` captures the `codexConfig` argument in closures + * owned by the returned instance. Two instances created with different + * `homePath`s (e.g. `codex_personal` + `codex_work`) therefore run with + * fully independent Codex app-server processes and `CODEX_HOME` + * environments — no shared mutable state. + * + * Resource lifecycle: `create()` runs in a scope handed in by the registry. + * Closing that scope releases the adapter's child processes, the managed + * snapshot's refresh fibre, and the text-generation binaries' transient + * scratch files. The registry uses this to tear down an instance when its + * `providerInstances` entry disappears or its config changes. + * + * @module provider/Drivers/CodexDriver + */ +import { CodexSettings, ProviderDriverKind, type ServerProvider } from "@t3tools/contracts"; +import { Duration, Effect, FileSystem, Path, Schema, Stream } from "effect"; +import { ChildProcessSpawner } from "effect/unstable/process"; + +import { makeCodexTextGeneration } from "../../git/Layers/CodexTextGeneration.ts"; +import { ServerConfig } from "../../config.ts"; +import { ProviderDriverError } from "../Errors.ts"; +import { makeCodexAdapter } from "../Layers/CodexAdapter.ts"; +import { checkCodexProviderStatus, makePendingCodexProvider } from "../Layers/CodexProvider.ts"; +import { ProviderEventLoggers } from "../Layers/ProviderEventLoggers.ts"; +import { makeManagedServerProvider } from "../makeManagedServerProvider.ts"; +import type { ProviderDriver, ProviderInstance } from "../ProviderDriver.ts"; +import type { ServerProviderDraft } from "../providerSnapshot.ts"; +import { mergeProviderInstanceEnvironment } from "../ProviderInstanceEnvironment.ts"; +import { + codexContinuationIdentity, + materializeCodexShadowHome, + resolveCodexHomeLayout, +} from "./CodexHomeLayout.ts"; + +const DRIVER_KIND = ProviderDriverKind.make("codex"); +const SNAPSHOT_REFRESH_INTERVAL = Duration.minutes(5); + +/** + * Services the driver needs to materialize an instance. Surfaced as the + * driver's `R` so the registry layer aggregates these across every + * registered driver and the runtime satisfies them once. + */ +export type CodexDriverEnv = + | ChildProcessSpawner.ChildProcessSpawner + | FileSystem.FileSystem + | Path.Path + | ProviderEventLoggers + | ServerConfig; + +/** + * Stamp instance identity onto a `ServerProvider` snapshot produced by the + * driver-kind-only codex helpers. Once `buildServerProvider` in + * `providerSnapshot.ts` is widened to accept `instanceId`/`driver`, this + * wrapper disappears. + */ +const withInstanceIdentity = + (input: { + readonly instanceId: ProviderInstance["instanceId"]; + readonly displayName: string | undefined; + readonly accentColor: string | undefined; + readonly continuationGroupKey: string; + }) => + (snapshot: ServerProviderDraft): ServerProvider => ({ + ...snapshot, + instanceId: input.instanceId, + driver: DRIVER_KIND, + ...(input.displayName ? { displayName: input.displayName } : {}), + ...(input.accentColor ? { accentColor: input.accentColor } : {}), + continuation: { groupKey: input.continuationGroupKey }, + }); + +export const CodexDriver: ProviderDriver = { + driverKind: DRIVER_KIND, + metadata: { + displayName: "Codex", + supportsMultipleInstances: true, + }, + configSchema: CodexSettings, + defaultConfig: (): CodexSettings => Schema.decodeSync(CodexSettings)({}), + create: ({ instanceId, displayName, accentColor, environment, enabled, config }) => + Effect.gen(function* () { + const spawner = yield* ChildProcessSpawner.ChildProcessSpawner; + const eventLoggers = yield* ProviderEventLoggers; + const processEnv = mergeProviderInstanceEnvironment(environment); + const homeLayout = yield* resolveCodexHomeLayout(config); + const continuationIdentity = codexContinuationIdentity(homeLayout); + const stampIdentity = withInstanceIdentity({ + instanceId, + displayName, + accentColor, + continuationGroupKey: continuationIdentity.continuationKey, + }); + yield* materializeCodexShadowHome(homeLayout).pipe( + Effect.mapError( + (cause) => + new ProviderDriverError({ + driver: DRIVER_KIND, + instanceId, + detail: cause.message, + cause, + }), + ), + ); + const effectiveConfig = { + ...config, + enabled, + homePath: homeLayout.effectiveHomePath ?? "", + } satisfies CodexSettings; + + // `makeCodexAdapter` and `makeCodexTextGeneration` have `never` error + // channels at construction time — their failure modes are all on the + // per-operation closures they return. No `mapError` wrapper is needed + // here; the registry only has to worry about snapshot-build and + // spawner-availability failures surfaced from `checkCodexProviderStatus` + // below. + const adapter = yield* makeCodexAdapter(effectiveConfig, { + instanceId, + environment: processEnv, + ...(eventLoggers.native ? { nativeEventLogger: eventLoggers.native } : {}), + }); + const textGeneration = yield* makeCodexTextGeneration(effectiveConfig, processEnv); + + // Build a managed snapshot whose settings never change — mutations come + // in as instance rebuilds from the registry rather than in-place + // updates. Pre-provide `ChildProcessSpawner` so the check fits + // `makeManagedServerProvider.checkProvider`'s `R = never`. + const checkProvider = checkCodexProviderStatus(effectiveConfig, undefined, processEnv).pipe( + Effect.map(stampIdentity), + Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner), + ); + const snapshot = yield* makeManagedServerProvider({ + getSettings: Effect.succeed(effectiveConfig), + streamSettings: Stream.never, + haveSettingsChanged: () => false, + initialSnapshot: (settings) => stampIdentity(makePendingCodexProvider(settings)), + checkProvider, + refreshInterval: SNAPSHOT_REFRESH_INTERVAL, + }).pipe( + Effect.mapError( + (cause) => + new ProviderDriverError({ + driver: DRIVER_KIND, + instanceId, + detail: `Failed to build Codex snapshot: ${cause.message ?? String(cause)}`, + cause, + }), + ), + ); + + return { + instanceId, + driverKind: DRIVER_KIND, + continuationIdentity, + displayName, + accentColor, + enabled, + snapshot, + adapter, + textGeneration, + } satisfies ProviderInstance; + }), +}; diff --git a/apps/server/src/provider/Drivers/CodexHomeLayout.test.ts b/apps/server/src/provider/Drivers/CodexHomeLayout.test.ts new file mode 100644 index 0000000000..b84a43c403 --- /dev/null +++ b/apps/server/src/provider/Drivers/CodexHomeLayout.test.ts @@ -0,0 +1,209 @@ +import * as NodeServices from "@effect/platform-node/NodeServices"; +import { describe, expect, it } from "@effect/vitest"; +import { Effect, FileSystem, Path, Schema } from "effect"; + +import { CodexSettings } from "@t3tools/contracts"; +import { + CodexShadowHomeError, + materializeCodexShadowHome, + resolveCodexHomeLayout, +} from "./CodexHomeLayout.ts"; + +const decodeCodexSettings = (input: { + readonly enabled?: boolean; + readonly homePath?: string; + readonly shadowHomePath?: string; + readonly customModels?: readonly string[]; + readonly binaryPath?: string; +}): CodexSettings => Schema.decodeSync(CodexSettings)(input); + +const makeTempDir = Effect.fn("CodexHomeLayout.test.makeTempDir")(function* (prefix: string) { + const fileSystem = yield* FileSystem.FileSystem; + return yield* fileSystem.makeTempDirectoryScoped({ prefix }); +}); + +const writeTextFile = Effect.fn("CodexHomeLayout.test.writeTextFile")(function* ( + filePath: string, + contents: string, +) { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + yield* fileSystem.makeDirectory(path.dirname(filePath), { recursive: true }); + yield* fileSystem.writeFileString(filePath, contents); +}); + +it.layer(NodeServices.layer)("CodexHomeLayout", (it) => { + describe("resolveCodexHomeLayout", () => { + it.effect("uses direct CODEX_HOME when no shadow home is configured", () => + Effect.gen(function* () { + const homePath = yield* makeTempDir("t3code-codex-home-"); + + const layout = yield* resolveCodexHomeLayout( + decodeCodexSettings({ + homePath, + }), + ); + + expect(layout).toMatchObject({ + mode: "direct", + sharedHomePath: homePath, + effectiveHomePath: homePath, + continuationKey: `codex:home:${homePath}`, + }); + }), + ); + + it.effect("uses the shared home for continuation and the shadow home for runtime", () => + Effect.gen(function* () { + const path = yield* Path.Path; + const sharedHome = yield* makeTempDir("t3code-codex-shared-"); + const shadowRoot = yield* makeTempDir("t3code-codex-shadow-root-"); + const shadowHome = path.join(shadowRoot, "shadow"); + + const layout = yield* resolveCodexHomeLayout( + decodeCodexSettings({ + homePath: sharedHome, + shadowHomePath: shadowHome, + }), + ); + + expect(layout).toMatchObject({ + mode: "authOverlay", + sharedHomePath: sharedHome, + effectiveHomePath: shadowHome, + continuationKey: `codex:home:${sharedHome}`, + }); + }), + ); + }); + + describe("materializeCodexShadowHome", () => { + it.effect("materializes a shadow home with shared state links and private auth", () => + Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const sharedHome = yield* makeTempDir("t3code-codex-shared-"); + const shadowRoot = yield* makeTempDir("t3code-codex-shadow-root-"); + const shadowHome = path.join(shadowRoot, "shadow"); + + yield* fileSystem.makeDirectory(path.join(sharedHome, "sessions")); + yield* writeTextFile(path.join(sharedHome, "config.toml"), 'model = "gpt-5-codex"\n'); + yield* writeTextFile(path.join(sharedHome, "models_cache.json"), '{"models":["shared"]}\n'); + yield* writeTextFile(path.join(sharedHome, "auth.json"), '{"shared":true}\n'); + yield* fileSystem.makeDirectory(shadowHome, { recursive: true }); + yield* writeTextFile(path.join(shadowHome, "auth.json"), '{"shadow":true}\n'); + yield* fileSystem.symlink( + path.join(sharedHome, "models_cache.json"), + path.join(shadowHome, "models_cache.json"), + ); + + const layout = yield* resolveCodexHomeLayout( + decodeCodexSettings({ + homePath: sharedHome, + shadowHomePath: shadowHome, + }), + ); + + yield* materializeCodexShadowHome(layout); + + const sessionsTarget = yield* fileSystem.readLink(path.join(shadowHome, "sessions")); + const configTarget = yield* fileSystem.readLink(path.join(shadowHome, "config.toml")); + const modelsCacheExists = yield* fileSystem.exists( + path.join(shadowHome, "models_cache.json"), + ); + const authLinkResult = yield* fileSystem + .readLink(path.join(shadowHome, "auth.json")) + .pipe(Effect.result); + const authContents = yield* fileSystem.readFileString(path.join(shadowHome, "auth.json")); + + expect(sessionsTarget).toBe(path.join(sharedHome, "sessions")); + expect(configTarget).toBe(path.join(sharedHome, "config.toml")); + expect(modelsCacheExists).toBe(false); + expect(authLinkResult._tag).toBe("Failure"); + expect(authContents).toContain("shadow"); + }), + ); + + it.effect("accepts Codex-created shadow-local runtime directories", () => + Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const sharedHome = yield* makeTempDir("t3code-codex-shared-"); + const shadowRoot = yield* makeTempDir("t3code-codex-shadow-root-"); + const shadowHome = path.join(shadowRoot, "shadow"); + + yield* fileSystem.makeDirectory(path.join(sharedHome, "log")); + yield* fileSystem.makeDirectory(path.join(sharedHome, "memories")); + yield* fileSystem.makeDirectory(path.join(sharedHome, "tmp")); + yield* writeTextFile(path.join(sharedHome, "config.toml"), 'model = "gpt-5-codex"\n'); + yield* writeTextFile(path.join(shadowHome, "auth.json"), '{"shadow":true}\n'); + yield* fileSystem.makeDirectory(path.join(shadowHome, "log"), { recursive: true }); + yield* fileSystem.makeDirectory(path.join(shadowHome, "memories"), { recursive: true }); + yield* fileSystem.makeDirectory(path.join(shadowHome, "tmp"), { recursive: true }); + + const layout = yield* resolveCodexHomeLayout( + decodeCodexSettings({ + homePath: sharedHome, + shadowHomePath: shadowHome, + }), + ); + + yield* materializeCodexShadowHome(layout); + + const configTarget = yield* fileSystem.readLink(path.join(shadowHome, "config.toml")); + const logLinkResult = yield* fileSystem + .readLink(path.join(shadowHome, "log")) + .pipe(Effect.result); + const memoriesLinkResult = yield* fileSystem + .readLink(path.join(shadowHome, "memories")) + .pipe(Effect.result); + const tmpLinkResult = yield* fileSystem + .readLink(path.join(shadowHome, "tmp")) + .pipe(Effect.result); + + expect(configTarget).toBe(path.join(sharedHome, "config.toml")); + expect(logLinkResult._tag).toBe("Failure"); + expect(memoriesLinkResult._tag).toBe("Failure"); + expect(tmpLinkResult._tag).toBe("Failure"); + }), + ); + + it.effect("rejects shadow homes that point at the shared home", () => + Effect.gen(function* () { + const sharedHome = yield* makeTempDir("t3code-codex-shared-"); + const layout = yield* resolveCodexHomeLayout( + decodeCodexSettings({ + homePath: sharedHome, + shadowHomePath: sharedHome, + }), + ); + + const error = yield* materializeCodexShadowHome(layout).pipe(Effect.flip); + + expect(error).toBeInstanceOf(CodexShadowHomeError); + }), + ); + + it.effect("rejects shared entries that already exist in the shadow home as real files", () => + Effect.gen(function* () { + const path = yield* Path.Path; + const sharedHome = yield* makeTempDir("t3code-codex-shared-"); + const shadowRoot = yield* makeTempDir("t3code-codex-shadow-root-"); + const shadowHome = path.join(shadowRoot, "shadow"); + yield* writeTextFile(path.join(sharedHome, "config.toml"), 'model = "gpt-5-codex"\n'); + yield* writeTextFile(path.join(shadowHome, "config.toml"), 'model = "local"\n'); + + const layout = yield* resolveCodexHomeLayout( + decodeCodexSettings({ + homePath: sharedHome, + shadowHomePath: shadowHome, + }), + ); + + const error = yield* materializeCodexShadowHome(layout).pipe(Effect.flip); + + expect(error.detail).toContain("already exists and is not a symlink"); + }), + ); + }); +}); diff --git a/apps/server/src/provider/Drivers/CodexHomeLayout.ts b/apps/server/src/provider/Drivers/CodexHomeLayout.ts new file mode 100644 index 0000000000..0b6cd6b891 --- /dev/null +++ b/apps/server/src/provider/Drivers/CodexHomeLayout.ts @@ -0,0 +1,263 @@ +import * as NodeOS from "node:os"; + +import { ProviderDriverKind, type CodexSettings } from "@t3tools/contracts"; +import { Effect, FileSystem, Path, Schema } from "effect"; +import * as PlatformError from "effect/PlatformError"; + +import { expandHomePath } from "../../pathExpansion.ts"; + +export interface CodexHomeLayout { + readonly mode: "direct" | "authOverlay"; + readonly sharedHomePath: string; + readonly effectiveHomePath: string | undefined; + readonly continuationKey: string; +} + +const KNOWN_SHARED_DIRECTORIES = [ + "sessions", + "archived_sessions", + "sqlite", + "shell_snapshots", + "worktrees", + "skills", + "plugins", + "cache", + "logs", +] as const; + +const PRIVATE_ENTRY_NAMES = new Set(["auth.json", "models_cache.json"]); +const SHADOW_LOCAL_ENTRY_NAMES = new Set(["log", "memories", "tmp"]); + +function resolveHomePath(path: Path.Path, value: string | undefined): string { + const expanded = + value && value.trim().length > 0 + ? expandHomePath(value) + : path.join(NodeOS.homedir(), ".codex"); + return path.resolve(expanded); +} + +export const resolveCodexHomeLayout = Effect.fn("resolveCodexHomeLayout")(function* ( + config: CodexSettings, +): Effect.fn.Return { + const path = yield* Path.Path; + const sharedHomePath = resolveHomePath(path, config.homePath); + const shadowHomePath = config.shadowHomePath.trim(); + if (shadowHomePath.length === 0) { + return { + mode: "direct", + sharedHomePath, + effectiveHomePath: config.homePath.trim().length > 0 ? sharedHomePath : undefined, + continuationKey: `codex:home:${sharedHomePath}`, + }; + } + + const effectiveHomePath = path.resolve(expandHomePath(shadowHomePath)); + return { + mode: "authOverlay", + sharedHomePath, + effectiveHomePath, + continuationKey: `codex:home:${sharedHomePath}`, + }; +}); + +export class CodexShadowHomeError extends Schema.TaggedErrorClass()( + "CodexShadowHomeError", + { + detail: Schema.String, + cause: Schema.optional(Schema.Unknown), + }, +) { + override get message(): string { + return this.detail; + } +} + +type LinkState = + | { + readonly _tag: "Missing"; + } + | { + readonly _tag: "NotSymlink"; + } + | { + readonly _tag: "Symlink"; + readonly target: string; + }; + +function toShadowHomeError(cause: unknown): CodexShadowHomeError { + return Schema.is(CodexShadowHomeError)(cause) + ? cause + : new CodexShadowHomeError({ + detail: "Failed to materialize Codex shadow home.", + cause, + }); +} + +function normalizeShadowHomeError( + effect: Effect.Effect, +): Effect.Effect { + return effect.pipe(Effect.mapError(toShadowHomeError)); +} + +function isNotSymlinkError(error: PlatformError.PlatformError): boolean { + const cause = error.reason.cause; + return ( + error.reason._tag === "Unknown" && + typeof cause === "object" && + cause !== null && + "code" in cause && + cause.code === "EINVAL" + ); +} + +const readLinkState = Effect.fn("CodexHomeLayout.readLinkState")(function* ( + fileSystem: FileSystem.FileSystem, + linkPath: string, +): Effect.fn.Return { + return yield* fileSystem.readLink(linkPath).pipe( + Effect.map((target): LinkState => ({ _tag: "Symlink", target })), + Effect.catch((error) => { + if (error.reason._tag === "NotFound") { + return Effect.succeed({ _tag: "Missing" }); + } + if (isNotSymlinkError(error)) { + return Effect.succeed({ _tag: "NotSymlink" }); + } + return Effect.fail(toShadowHomeError(error)); + }), + ); +}); + +const removePrivateSymlink = Effect.fn("CodexHomeLayout.removePrivateSymlink")(function* (input: { + readonly fileSystem: FileSystem.FileSystem; + readonly shadowPath: string; + readonly entryName: string; +}): Effect.fn.Return { + const path = yield* Path.Path; + const privatePath = path.join(input.shadowPath, input.entryName); + const state = yield* readLinkState(input.fileSystem, privatePath); + if (state._tag === "Symlink") { + yield* normalizeShadowHomeError(input.fileSystem.remove(privatePath)); + } +}); + +const ensureSymlink = Effect.fn("CodexHomeLayout.ensureSymlink")(function* (input: { + readonly fileSystem: FileSystem.FileSystem; + readonly shadowPath: string; + readonly sharedPath: string; + readonly entryName: string; +}): Effect.fn.Return { + const path = yield* Path.Path; + const target = path.join(input.sharedPath, input.entryName); + const link = path.join(input.shadowPath, input.entryName); + const state = yield* readLinkState(input.fileSystem, link); + + if (state._tag === "NotSymlink") { + return yield* new CodexShadowHomeError({ + detail: `Cannot create Codex shadow home because '${link}' already exists and is not a symlink.`, + }); + } + + if (state._tag === "Missing") { + return yield* normalizeShadowHomeError(input.fileSystem.symlink(target, link)); + } + + const resolvedExisting = path.resolve(path.dirname(link), state.target); + if (resolvedExisting !== target) { + yield* normalizeShadowHomeError(input.fileSystem.remove(link)); + yield* normalizeShadowHomeError(input.fileSystem.symlink(target, link)); + } +}); + +const ensureShadowAuthIsPrivate = Effect.fn("CodexHomeLayout.ensureShadowAuthIsPrivate")(function* ( + fileSystem: FileSystem.FileSystem, + shadowPath: string, +): Effect.fn.Return { + const path = yield* Path.Path; + const authPath = path.join(shadowPath, "auth.json"); + const state = yield* readLinkState(fileSystem, authPath); + if (state._tag === "Symlink") { + return yield* new CodexShadowHomeError({ + detail: `Codex shadow auth file '${authPath}' must be a real file, not a symlink.`, + }); + } +}); + +export const materializeCodexShadowHome = Effect.fn("materializeCodexShadowHome")(function* ( + layout: CodexHomeLayout, +) { + if (layout.mode !== "authOverlay") return; + const effectiveHomePath = layout.effectiveHomePath; + if (!effectiveHomePath) return; + if (layout.sharedHomePath === effectiveHomePath) { + return yield* new CodexShadowHomeError({ + detail: "Codex shadow home path must be different from the shared home path.", + }); + } + + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + + yield* normalizeShadowHomeError( + Effect.all( + [ + fileSystem.makeDirectory(layout.sharedHomePath, { recursive: true }), + fileSystem.makeDirectory(effectiveHomePath, { recursive: true }), + ...KNOWN_SHARED_DIRECTORIES.map((directory) => + fileSystem.makeDirectory(path.join(layout.sharedHomePath, directory), { + recursive: true, + }), + ), + ], + { concurrency: "unbounded" }, + ), + ); + + const sharedEntryNames = yield* normalizeShadowHomeError( + fileSystem.readDirectory(layout.sharedHomePath), + ); + const entries = new Set(KNOWN_SHARED_DIRECTORIES); + for (const entryName of sharedEntryNames) { + if (!PRIVATE_ENTRY_NAMES.has(entryName) && !SHADOW_LOCAL_ENTRY_NAMES.has(entryName)) { + entries.add(entryName); + } + } + + yield* Effect.forEach( + PRIVATE_ENTRY_NAMES, + (entryName) => + entryName === "auth.json" + ? Effect.void + : removePrivateSymlink({ + fileSystem, + shadowPath: effectiveHomePath, + entryName, + }), + { discard: true }, + ); + + yield* Effect.forEach( + entries, + (entryName) => { + if (PRIVATE_ENTRY_NAMES.has(entryName)) { + return Effect.void; + } + return ensureSymlink({ + fileSystem, + shadowPath: effectiveHomePath, + sharedPath: layout.sharedHomePath, + entryName, + }); + }, + { discard: true }, + ); + + yield* ensureShadowAuthIsPrivate(fileSystem, effectiveHomePath); +}); + +export function codexContinuationIdentity(layout: CodexHomeLayout) { + return { + driverKind: ProviderDriverKind.make("codex"), + continuationKey: layout.continuationKey, + }; +} diff --git a/apps/server/src/provider/Drivers/CursorDriver.ts b/apps/server/src/provider/Drivers/CursorDriver.ts new file mode 100644 index 0000000000..b7eda591bc --- /dev/null +++ b/apps/server/src/provider/Drivers/CursorDriver.ts @@ -0,0 +1,148 @@ +/** + * CursorDriver — `ProviderDriver` for the Cursor Agent (`agent`) runtime. + * + * Cursor exposes an ACP-based CLI. The driver is still a plain value, but + * its snapshot uses `makeManagedServerProvider`'s optional `enrichSnapshot` + * hook to run the slow ACP model-capability probe in the background without + * blocking the initial `ready`-state publish. + * + * Text generation is supported via the ACP runtime — `makeCursorTextGeneration` + * drives `runtime.prompt` with a structured-output schema and collects the + * agent's `agent_message_chunk` stream into a single JSON blob. + * + * @module provider/Drivers/CursorDriver + */ +import { CursorSettings, ProviderDriverKind, type ServerProvider } from "@t3tools/contracts"; +import { Duration, Effect, FileSystem, Path, Schema, Stream } from "effect"; +import { ChildProcessSpawner } from "effect/unstable/process"; + +import { ServerConfig } from "../../config.ts"; +import { makeCursorTextGeneration } from "../../git/Layers/CursorTextGeneration.ts"; +import { ProviderDriverError } from "../Errors.ts"; +import { makeCursorAdapter } from "../Layers/CursorAdapter.ts"; +import { + buildInitialCursorProviderSnapshot, + checkCursorProviderStatus, + enrichCursorSnapshot, +} from "../Layers/CursorProvider.ts"; +import { ProviderEventLoggers } from "../Layers/ProviderEventLoggers.ts"; +import { makeManagedServerProvider } from "../makeManagedServerProvider.ts"; +import { + defaultProviderContinuationIdentity, + type ProviderDriver, + type ProviderInstance, +} from "../ProviderDriver.ts"; +import type { ServerProviderDraft } from "../providerSnapshot.ts"; +import { mergeProviderInstanceEnvironment } from "../ProviderInstanceEnvironment.ts"; + +const DRIVER_KIND = ProviderDriverKind.make("cursor"); +const SNAPSHOT_REFRESH_INTERVAL = Duration.minutes(5); + +export type CursorDriverEnv = + | ChildProcessSpawner.ChildProcessSpawner + | FileSystem.FileSystem + | Path.Path + | ProviderEventLoggers + | ServerConfig; + +const withInstanceIdentity = + (input: { + readonly instanceId: ProviderInstance["instanceId"]; + readonly displayName: string | undefined; + readonly accentColor: string | undefined; + readonly continuationGroupKey: string; + }) => + (snapshot: ServerProviderDraft): ServerProvider => ({ + ...snapshot, + instanceId: input.instanceId, + driver: DRIVER_KIND, + ...(input.displayName ? { displayName: input.displayName } : {}), + ...(input.accentColor ? { accentColor: input.accentColor } : {}), + continuation: { groupKey: input.continuationGroupKey }, + }); + +export const CursorDriver: ProviderDriver = { + driverKind: DRIVER_KIND, + metadata: { + displayName: "Cursor", + supportsMultipleInstances: true, + }, + configSchema: CursorSettings, + defaultConfig: (): CursorSettings => Schema.decodeSync(CursorSettings)({}), + create: ({ instanceId, displayName, accentColor, environment, enabled, config }) => + Effect.gen(function* () { + const spawner = yield* ChildProcessSpawner.ChildProcessSpawner; + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const eventLoggers = yield* ProviderEventLoggers; + const processEnv = mergeProviderInstanceEnvironment(environment); + const continuationIdentity = defaultProviderContinuationIdentity({ + driverKind: DRIVER_KIND, + instanceId, + }); + const stampIdentity = withInstanceIdentity({ + instanceId, + displayName, + accentColor, + continuationGroupKey: continuationIdentity.continuationKey, + }); + const effectiveConfig = { ...config, enabled } satisfies CursorSettings; + + const adapter = yield* makeCursorAdapter(effectiveConfig, { + environment: processEnv, + ...(eventLoggers.native ? { nativeEventLogger: eventLoggers.native } : {}), + instanceId, + }); + const textGeneration = yield* makeCursorTextGeneration(effectiveConfig, processEnv); + + const checkProvider = checkCursorProviderStatus(effectiveConfig, processEnv).pipe( + Effect.map(stampIdentity), + Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner), + Effect.provideService(FileSystem.FileSystem, fileSystem), + Effect.provideService(Path.Path, path), + ); + + const snapshot = yield* makeManagedServerProvider({ + getSettings: Effect.succeed(effectiveConfig), + streamSettings: Stream.never, + haveSettingsChanged: () => false, + initialSnapshot: (settings) => stampIdentity(buildInitialCursorProviderSnapshot(settings)), + checkProvider, + // Preserve the background ACP model-capability probe that used to + // live on `CursorProviderLive`. Only fires when the snapshot reports + // an authenticated, enabled provider with at least one non-custom + // model whose capabilities haven't been captured yet. + enrichSnapshot: ({ settings, snapshot: currentSnapshot, publishSnapshot }) => + enrichCursorSnapshot({ + settings, + environment: processEnv, + snapshot: currentSnapshot, + publishSnapshot, + stampIdentity, + }).pipe(Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner)), + refreshInterval: SNAPSHOT_REFRESH_INTERVAL, + }).pipe( + Effect.mapError( + (cause) => + new ProviderDriverError({ + driver: DRIVER_KIND, + instanceId, + detail: `Failed to build Cursor snapshot: ${cause.message ?? String(cause)}`, + cause, + }), + ), + ); + + return { + instanceId, + driverKind: DRIVER_KIND, + continuationIdentity, + displayName, + accentColor, + enabled, + snapshot, + adapter, + textGeneration, + } satisfies ProviderInstance; + }), +}; diff --git a/apps/server/src/provider/Drivers/OpenCodeDriver.ts b/apps/server/src/provider/Drivers/OpenCodeDriver.ts new file mode 100644 index 0000000000..29f74ead02 --- /dev/null +++ b/apps/server/src/provider/Drivers/OpenCodeDriver.ts @@ -0,0 +1,135 @@ +/** + * OpenCodeDriver — `ProviderDriver` for the OpenCode runtime. + * + * Mirrors the Codex / Claude drivers: a plain value whose `create()` + * bundles `snapshot` / `adapter` / `textGeneration` closures over the + * per-instance `OpenCodeSettings`. + * + * Two instances with different `serverUrl`s therefore talk to independent + * OpenCode servers; when no `serverUrl` is set, the adapter + text-generation + * shares spin up their own scoped child processes, and those child + * processes are released when the registry scope closes. + * + * @module provider/Drivers/OpenCodeDriver + */ +import { OpenCodeSettings, ProviderDriverKind, type ServerProvider } from "@t3tools/contracts"; +import { Duration, Effect, FileSystem, Path, Schema, Stream } from "effect"; +import { ChildProcessSpawner } from "effect/unstable/process"; + +import { makeOpenCodeTextGeneration } from "../../git/Layers/OpenCodeTextGeneration.ts"; +import { ServerConfig } from "../../config.ts"; +import { ProviderDriverError } from "../Errors.ts"; +import { makeOpenCodeAdapter } from "../Layers/OpenCodeAdapter.ts"; +import { + checkOpenCodeProviderStatus, + makePendingOpenCodeProvider, +} from "../Layers/OpenCodeProvider.ts"; +import { ProviderEventLoggers } from "../Layers/ProviderEventLoggers.ts"; +import { makeManagedServerProvider } from "../makeManagedServerProvider.ts"; +import { OpenCodeRuntime } from "../opencodeRuntime.ts"; +import { + defaultProviderContinuationIdentity, + type ProviderDriver, + type ProviderInstance, +} from "../ProviderDriver.ts"; +import type { ServerProviderDraft } from "../providerSnapshot.ts"; +import { mergeProviderInstanceEnvironment } from "../ProviderInstanceEnvironment.ts"; + +const DRIVER_KIND = ProviderDriverKind.make("opencode"); +const SNAPSHOT_REFRESH_INTERVAL = Duration.minutes(5); + +export type OpenCodeDriverEnv = + | ChildProcessSpawner.ChildProcessSpawner + | FileSystem.FileSystem + | OpenCodeRuntime + | Path.Path + | ProviderEventLoggers + | ServerConfig; + +const withInstanceIdentity = + (input: { + readonly instanceId: ProviderInstance["instanceId"]; + readonly displayName: string | undefined; + readonly accentColor: string | undefined; + readonly continuationGroupKey: string; + }) => + (snapshot: ServerProviderDraft): ServerProvider => ({ + ...snapshot, + instanceId: input.instanceId, + driver: DRIVER_KIND, + ...(input.displayName ? { displayName: input.displayName } : {}), + ...(input.accentColor ? { accentColor: input.accentColor } : {}), + continuation: { groupKey: input.continuationGroupKey }, + }); + +export const OpenCodeDriver: ProviderDriver = { + driverKind: DRIVER_KIND, + metadata: { + displayName: "OpenCode", + supportsMultipleInstances: true, + }, + configSchema: OpenCodeSettings, + defaultConfig: (): OpenCodeSettings => Schema.decodeSync(OpenCodeSettings)({}), + create: ({ instanceId, displayName, accentColor, environment, enabled, config }) => + Effect.gen(function* () { + const openCodeRuntime = yield* OpenCodeRuntime; + const serverConfig = yield* ServerConfig; + const eventLoggers = yield* ProviderEventLoggers; + const processEnv = mergeProviderInstanceEnvironment(environment); + const continuationIdentity = defaultProviderContinuationIdentity({ + driverKind: DRIVER_KIND, + instanceId, + }); + const stampIdentity = withInstanceIdentity({ + instanceId, + displayName, + accentColor, + continuationGroupKey: continuationIdentity.continuationKey, + }); + const effectiveConfig = { ...config, enabled } satisfies OpenCodeSettings; + + const adapter = yield* makeOpenCodeAdapter(effectiveConfig, { + instanceId, + environment: processEnv, + ...(eventLoggers.native ? { nativeEventLogger: eventLoggers.native } : {}), + }); + const textGeneration = yield* makeOpenCodeTextGeneration(effectiveConfig, processEnv); + + const checkProvider = checkOpenCodeProviderStatus( + effectiveConfig, + serverConfig.cwd, + processEnv, + ).pipe(Effect.map(stampIdentity), Effect.provideService(OpenCodeRuntime, openCodeRuntime)); + + const snapshot = yield* makeManagedServerProvider({ + getSettings: Effect.succeed(effectiveConfig), + streamSettings: Stream.never, + haveSettingsChanged: () => false, + initialSnapshot: (settings) => stampIdentity(makePendingOpenCodeProvider(settings)), + checkProvider, + refreshInterval: SNAPSHOT_REFRESH_INTERVAL, + }).pipe( + Effect.mapError( + (cause) => + new ProviderDriverError({ + driver: DRIVER_KIND, + instanceId, + detail: `Failed to build OpenCode snapshot: ${cause.message ?? String(cause)}`, + cause, + }), + ), + ); + + return { + instanceId, + driverKind: DRIVER_KIND, + continuationIdentity, + displayName, + accentColor, + enabled, + snapshot, + adapter, + textGeneration, + } satisfies ProviderInstance; + }), +}; diff --git a/apps/server/src/provider/Errors.ts b/apps/server/src/provider/Errors.ts index e4e46d3748..2bd926512e 100644 --- a/apps/server/src/provider/Errors.ts +++ b/apps/server/src/provider/Errors.ts @@ -116,6 +116,46 @@ export class ProviderUnsupportedError extends Schema.TaggedErrorClass()( + "ProviderInstanceNotFoundError", + { + instanceId: Schema.String, + cause: Schema.optional(Schema.Defect), + }, +) { + override get message(): string { + return `No provider instance bound to id '${this.instanceId}'`; + } +} + +/** + * ProviderDriverError - A driver `create` call failed before producing an + * instance. Surfaced to the registry, which marks the offending entry as + * an "unavailable" shadow snapshot rather than crashing the server. + */ +export class ProviderDriverError extends Schema.TaggedErrorClass()( + "ProviderDriverError", + { + driver: Schema.String, + instanceId: Schema.String, + detail: Schema.String, + cause: Schema.optional(Schema.Defect), + }, +) { + override get message(): string { + return `Provider driver '${this.driver}' failed to create instance '${this.instanceId}': ${this.detail}`; + } +} + /** * ProviderSessionNotFoundError - Provider-facing session not found. */ @@ -157,6 +197,7 @@ export type ProviderAdapterError = export type ProviderServiceError = | ProviderValidationError | ProviderUnsupportedError + | ProviderInstanceNotFoundError | ProviderSessionNotFoundError | ProviderSessionDirectoryPersistenceError | ProviderAdapterError diff --git a/apps/server/src/provider/Layers/ClaudeAdapter.test.ts b/apps/server/src/provider/Layers/ClaudeAdapter.test.ts index 9c83bce858..14cca34b20 100644 --- a/apps/server/src/provider/Layers/ClaudeAdapter.test.ts +++ b/apps/server/src/provider/Layers/ClaudeAdapter.test.ts @@ -12,21 +12,29 @@ import type { } from "@anthropic-ai/claude-agent-sdk"; import { ApprovalRequestId, + ClaudeSettings, + ProviderDriverKind, ProviderItemId, ProviderRuntimeEvent, type RuntimeMode, ThreadId, + ProviderInstanceId, } from "@t3tools/contracts"; import { createModelSelection } from "@t3tools/shared/model"; import { assert, describe, it } from "@effect/vitest"; -import { Effect, Fiber, Layer, Random, Stream } from "effect"; +import { Context, Effect, Fiber, Layer, Random, Schema, Stream } from "effect"; import { attachmentRelativePath } from "../../attachmentStore.ts"; import { ServerConfig } from "../../config.ts"; import { ServerSettingsService } from "../../serverSettings.ts"; import { ProviderAdapterValidationError } from "../Errors.ts"; -import { ClaudeAdapter } from "../Services/ClaudeAdapter.ts"; -import { makeClaudeAdapterLive, type ClaudeAdapterLiveOptions } from "./ClaudeAdapter.ts"; +import type { ClaudeAdapterShape } from "../Services/ClaudeAdapter.ts"; +import { makeClaudeAdapter, type ClaudeAdapterLiveOptions } from "./ClaudeAdapter.ts"; + +// Test-local service tag so the rest of the file can keep using `yield* ClaudeAdapter`. +class ClaudeAdapter extends Context.Service()( + "test/ClaudeAdapter", +) {} class FakeClaudeQuery implements AsyncIterable { private readonly queue: Array = []; @@ -137,6 +145,8 @@ function makeHarness(config?: { readonly nativeEventLogger?: ClaudeAdapterLiveOptions["nativeEventLogger"]; readonly cwd?: string; readonly baseDir?: string; + readonly claudeConfig?: Partial; + readonly instanceId?: ProviderInstanceId; }) { const query = new FakeClaudeQuery(); let createInput: @@ -147,6 +157,7 @@ function makeHarness(config?: { | undefined; const adapterOptions: ClaudeAdapterLiveOptions = { + ...(config?.instanceId ? { instanceId: config.instanceId } : {}), createQuery: (input) => { createInput = input; return query; @@ -164,7 +175,13 @@ function makeHarness(config?: { }; return { - layer: makeClaudeAdapterLive(adapterOptions).pipe( + layer: Layer.effect( + ClaudeAdapter, + Effect.gen(function* () { + const claudeConfig = Schema.decodeSync(ClaudeSettings)(config?.claudeConfig ?? {}); + return yield* makeClaudeAdapter(claudeConfig, adapterOptions); + }), + ).pipe( Layer.provideMerge( ServerConfig.layerTest( config?.cwd ?? "/tmp/claude-adapter-test", @@ -247,7 +264,11 @@ describe("ClaudeAdapterLive", () => { return Effect.gen(function* () { const adapter = yield* ClaudeAdapter; const result = yield* adapter - .startSession({ threadId: THREAD_ID, provider: "codex", runtimeMode: "full-access" }) + .startSession({ + threadId: THREAD_ID, + provider: ProviderDriverKind.make("codex"), + runtimeMode: "full-access", + }) .pipe(Effect.result); assert.equal(result._tag, "Failure"); @@ -257,7 +278,7 @@ describe("ClaudeAdapterLive", () => { assert.deepEqual( result.failure, new ProviderAdapterValidationError({ - provider: "claudeAgent", + provider: ProviderDriverKind.make("claudeAgent"), operation: "startSession", issue: "Expected provider 'claudeAgent' but received 'codex'.", }), @@ -274,7 +295,7 @@ describe("ClaudeAdapterLive", () => { const adapter = yield* ClaudeAdapter; yield* adapter.startSession({ threadId: THREAD_ID, - provider: "claudeAgent", + provider: ProviderDriverKind.make("claudeAgent"), runtimeMode: "full-access", }); @@ -294,7 +315,7 @@ describe("ClaudeAdapterLive", () => { const adapter = yield* ClaudeAdapter; yield* adapter.startSession({ threadId: THREAD_ID, - provider: "claudeAgent", + provider: ProviderDriverKind.make("claudeAgent"), runtimeMode: "approval-required", }); @@ -314,7 +335,7 @@ describe("ClaudeAdapterLive", () => { const adapter = yield* ClaudeAdapter; yield* adapter.startSession({ threadId: THREAD_ID, - provider: "claudeAgent", + provider: ProviderDriverKind.make("claudeAgent"), runtimeMode: "full-access", }); @@ -333,10 +354,12 @@ describe("ClaudeAdapterLive", () => { const adapter = yield* ClaudeAdapter; yield* adapter.startSession({ threadId: THREAD_ID, - provider: "claudeAgent", - modelSelection: createModelSelection("claudeAgent", "claude-opus-4-6", [ - { id: "effort", value: "max" }, - ]), + provider: ProviderDriverKind.make("claudeAgent"), + modelSelection: createModelSelection( + ProviderInstanceId.make("claudeAgent"), + "claude-opus-4-6", + [{ id: "effort", value: "max" }], + ), runtimeMode: "full-access", }); @@ -348,15 +371,37 @@ describe("ClaudeAdapterLive", () => { ); }); + it.effect("runs Claude SDK sessions with the configured Claude HOME", () => { + const harness = makeHarness({ claudeConfig: { homePath: "~/.claude-work" } }); + return Effect.gen(function* () { + const adapter = yield* ClaudeAdapter; + yield* adapter.startSession({ + threadId: THREAD_ID, + provider: ProviderDriverKind.make("claudeAgent"), + modelSelection: createModelSelection( + ProviderInstanceId.make("claudeAgent"), + "claude-opus-4-6", + ), + runtimeMode: "full-access", + }); + + const createInput = harness.getLastCreateQueryInput(); + assert.equal(createInput?.options.env?.HOME, path.join(os.homedir(), ".claude-work")); + }).pipe( + Effect.provideService(Random.Random, makeDeterministicRandomService()), + Effect.provide(harness.layer), + ); + }); + it.effect("maps the Claude Opus 4.7 default effort to the SDK-supported max value", () => { const harness = makeHarness(); return Effect.gen(function* () { const adapter = yield* ClaudeAdapter; yield* adapter.startSession({ threadId: THREAD_ID, - provider: "claudeAgent", + provider: ProviderDriverKind.make("claudeAgent"), modelSelection: { - provider: "claudeAgent", + instanceId: ProviderInstanceId.make("claudeAgent"), model: "claude-opus-4-7", }, runtimeMode: "full-access", @@ -376,10 +421,12 @@ describe("ClaudeAdapterLive", () => { const adapter = yield* ClaudeAdapter; yield* adapter.startSession({ threadId: THREAD_ID, - provider: "claudeAgent", - modelSelection: createModelSelection("claudeAgent", "claude-opus-4-7", [ - { id: "effort", value: "xhigh" }, - ]), + provider: ProviderDriverKind.make("claudeAgent"), + modelSelection: createModelSelection( + ProviderInstanceId.make("claudeAgent"), + "claude-opus-4-7", + [{ id: "effort", value: "xhigh" }], + ), runtimeMode: "full-access", }); @@ -397,10 +444,12 @@ describe("ClaudeAdapterLive", () => { const adapter = yield* ClaudeAdapter; yield* adapter.startSession({ threadId: THREAD_ID, - provider: "claudeAgent", - modelSelection: createModelSelection("claudeAgent", "claude-sonnet-4-6", [ - { id: "effort", value: "max" }, - ]), + provider: ProviderDriverKind.make("claudeAgent"), + modelSelection: createModelSelection( + ProviderInstanceId.make("claudeAgent"), + "claude-sonnet-4-6", + [{ id: "effort", value: "max" }], + ), runtimeMode: "full-access", }); @@ -418,10 +467,12 @@ describe("ClaudeAdapterLive", () => { const adapter = yield* ClaudeAdapter; yield* adapter.startSession({ threadId: THREAD_ID, - provider: "claudeAgent", - modelSelection: createModelSelection("claudeAgent", "claude-haiku-4-5", [ - { id: "effort", value: "high" }, - ]), + provider: ProviderDriverKind.make("claudeAgent"), + modelSelection: createModelSelection( + ProviderInstanceId.make("claudeAgent"), + "claude-haiku-4-5", + [{ id: "effort", value: "high" }], + ), runtimeMode: "full-access", }); @@ -439,10 +490,12 @@ describe("ClaudeAdapterLive", () => { const adapter = yield* ClaudeAdapter; yield* adapter.startSession({ threadId: THREAD_ID, - provider: "claudeAgent", - modelSelection: createModelSelection("claudeAgent", "claude-haiku-4-5", [ - { id: "thinking", value: false }, - ]), + provider: ProviderDriverKind.make("claudeAgent"), + modelSelection: createModelSelection( + ProviderInstanceId.make("claudeAgent"), + "claude-haiku-4-5", + [{ id: "thinking", value: false }], + ), runtimeMode: "full-access", }); @@ -462,10 +515,12 @@ describe("ClaudeAdapterLive", () => { const adapter = yield* ClaudeAdapter; yield* adapter.startSession({ threadId: THREAD_ID, - provider: "claudeAgent", - modelSelection: createModelSelection("claudeAgent", "claude-sonnet-4-6", [ - { id: "thinking", value: false }, - ]), + provider: ProviderDriverKind.make("claudeAgent"), + modelSelection: createModelSelection( + ProviderInstanceId.make("claudeAgent"), + "claude-sonnet-4-6", + [{ id: "thinking", value: false }], + ), runtimeMode: "full-access", }); @@ -483,10 +538,12 @@ describe("ClaudeAdapterLive", () => { const adapter = yield* ClaudeAdapter; yield* adapter.startSession({ threadId: THREAD_ID, - provider: "claudeAgent", - modelSelection: createModelSelection("claudeAgent", "claude-opus-4-6", [ - { id: "fastMode", value: true }, - ]), + provider: ProviderDriverKind.make("claudeAgent"), + modelSelection: createModelSelection( + ProviderInstanceId.make("claudeAgent"), + "claude-opus-4-6", + [{ id: "fastMode", value: true }], + ), runtimeMode: "full-access", }); @@ -506,10 +563,12 @@ describe("ClaudeAdapterLive", () => { const adapter = yield* ClaudeAdapter; yield* adapter.startSession({ threadId: THREAD_ID, - provider: "claudeAgent", - modelSelection: createModelSelection("claudeAgent", "claude-sonnet-4-6", [ - { id: "fastMode", value: true }, - ]), + provider: ProviderDriverKind.make("claudeAgent"), + modelSelection: createModelSelection( + ProviderInstanceId.make("claudeAgent"), + "claude-sonnet-4-6", + [{ id: "fastMode", value: true }], + ), runtimeMode: "full-access", }); @@ -527,10 +586,12 @@ describe("ClaudeAdapterLive", () => { const adapter = yield* ClaudeAdapter; const session = yield* adapter.startSession({ threadId: THREAD_ID, - provider: "claudeAgent", - modelSelection: createModelSelection("claudeAgent", "claude-sonnet-4-6", [ - { id: "effort", value: "ultrathink" }, - ]), + provider: ProviderDriverKind.make("claudeAgent"), + modelSelection: createModelSelection( + ProviderInstanceId.make("claudeAgent"), + "claude-sonnet-4-6", + [{ id: "effort", value: "ultrathink" }], + ), runtimeMode: "full-access", }); @@ -538,9 +599,11 @@ describe("ClaudeAdapterLive", () => { threadId: session.threadId, input: "Investigate the edge cases", attachments: [], - modelSelection: createModelSelection("claudeAgent", "claude-sonnet-4-6", [ - { id: "effort", value: "ultrathink" }, - ]), + modelSelection: createModelSelection( + ProviderInstanceId.make("claudeAgent"), + "claude-sonnet-4-6", + [{ id: "effort", value: "ultrathink" }], + ), }); const createInput = harness.getLastCreateQueryInput(); @@ -585,7 +648,7 @@ describe("ClaudeAdapterLive", () => { const session = yield* adapter.startSession({ threadId: THREAD_ID, - provider: "claudeAgent", + provider: ProviderDriverKind.make("claudeAgent"), runtimeMode: "full-access", }); @@ -630,9 +693,9 @@ describe("ClaudeAdapterLive", () => { const session = yield* adapter.startSession({ threadId: THREAD_ID, - provider: "claudeAgent", + provider: ProviderDriverKind.make("claudeAgent"), modelSelection: { - provider: "claudeAgent", + instanceId: ProviderInstanceId.make("claudeAgent"), model: "claude-sonnet-4-5", }, runtimeMode: "full-access", @@ -807,7 +870,7 @@ describe("ClaudeAdapterLive", () => { const session = yield* adapter.startSession({ threadId: THREAD_ID, - provider: "claudeAgent", + provider: ProviderDriverKind.make("claudeAgent"), runtimeMode: "full-access", }); @@ -986,7 +1049,7 @@ describe("ClaudeAdapterLive", () => { const session = yield* adapter.startSession({ threadId: THREAD_ID, - provider: "claudeAgent", + provider: ProviderDriverKind.make("claudeAgent"), runtimeMode: "full-access", }); @@ -1077,7 +1140,7 @@ describe("ClaudeAdapterLive", () => { const session = yield* adapter.startSession({ threadId: THREAD_ID, - provider: "claudeAgent", + provider: ProviderDriverKind.make("claudeAgent"), runtimeMode: "full-access", }); @@ -1153,7 +1216,7 @@ describe("ClaudeAdapterLive", () => { const session = yield* adapter.startSession({ threadId: THREAD_ID, - provider: "claudeAgent", + provider: ProviderDriverKind.make("claudeAgent"), runtimeMode: "full-access", }); @@ -1219,7 +1282,7 @@ describe("ClaudeAdapterLive", () => { yield* adapter.startSession({ threadId: THREAD_ID, - provider: "claudeAgent", + provider: ProviderDriverKind.make("claudeAgent"), runtimeMode: "full-access", }); @@ -1270,13 +1333,19 @@ describe("ClaudeAdapterLive", () => { it.effect("closes the previous session before replacing an existing thread session", () => { const queries: FakeClaudeQuery[] = []; - const layer = makeClaudeAdapterLive({ - createQuery: () => { - const query = new FakeClaudeQuery(); - queries.push(query); - return query; - }, - }).pipe( + const layer = Layer.effect( + ClaudeAdapter, + Effect.gen(function* () { + const claudeConfig = Schema.decodeSync(ClaudeSettings)({}); + return yield* makeClaudeAdapter(claudeConfig, { + createQuery: () => { + const query = new FakeClaudeQuery(); + queries.push(query); + return query; + }, + }); + }), + ).pipe( Layer.provideMerge(ServerConfig.layerTest("/tmp/claude-adapter-test", "/tmp")), Layer.provideMerge(ServerSettingsService.layerTest()), Layer.provideMerge(NodeServices.layer), @@ -1292,13 +1361,13 @@ describe("ClaudeAdapterLive", () => { const firstSession = yield* adapter.startSession({ threadId: THREAD_ID, - provider: "claudeAgent", + provider: ProviderDriverKind.make("claudeAgent"), runtimeMode: "full-access", }); const secondSession = yield* adapter.startSession({ threadId: THREAD_ID, - provider: "claudeAgent", + provider: ProviderDriverKind.make("claudeAgent"), runtimeMode: "full-access", resumeCursor: firstSession.resumeCursor, }); @@ -1347,21 +1416,27 @@ describe("ClaudeAdapterLive", () => { let promptConsumerError: unknown = undefined; - const layer = makeClaudeAdapterLive({ - createQuery: (input) => { - // Simulate the SDK consuming the prompt iterable - (async () => { - try { - for await (const _message of input.prompt) { - /* SDK processes user messages */ - } - } catch (error) { - promptConsumerError = error; - } - })(); - return query; - }, - }).pipe( + const layer = Layer.effect( + ClaudeAdapter, + Effect.gen(function* () { + const claudeConfig = Schema.decodeSync(ClaudeSettings)({}); + return yield* makeClaudeAdapter(claudeConfig, { + createQuery: (input) => { + // Simulate the SDK consuming the prompt iterable + (async () => { + try { + for await (const _message of input.prompt) { + /* SDK processes user messages */ + } + } catch (error) { + promptConsumerError = error; + } + })(); + return query; + }, + }); + }), + ).pipe( Layer.provideMerge(ServerConfig.layerTest("/tmp/claude-adapter-test", "/tmp")), Layer.provideMerge(ServerSettingsService.layerTest()), Layer.provideMerge(NodeServices.layer), @@ -1379,7 +1454,7 @@ describe("ClaudeAdapterLive", () => { yield* adapter.startSession({ threadId: THREAD_ID, - provider: "claudeAgent", + provider: ProviderDriverKind.make("claudeAgent"), runtimeMode: "full-access", }); @@ -1416,7 +1491,7 @@ describe("ClaudeAdapterLive", () => { yield* adapter.startSession({ threadId: THREAD_ID, - provider: "claudeAgent", + provider: ProviderDriverKind.make("claudeAgent"), runtimeMode: "full-access", }); @@ -1463,7 +1538,7 @@ describe("ClaudeAdapterLive", () => { yield* adapter.startSession({ threadId: THREAD_ID, - provider: "claudeAgent", + provider: ProviderDriverKind.make("claudeAgent"), runtimeMode: "full-access", }); @@ -1517,7 +1592,7 @@ describe("ClaudeAdapterLive", () => { yield* adapter.startSession({ threadId: THREAD_ID, - provider: "claudeAgent", + provider: ProviderDriverKind.make("claudeAgent"), runtimeMode: "full-access", }); @@ -1584,7 +1659,7 @@ describe("ClaudeAdapterLive", () => { yield* adapter.startSession({ threadId: THREAD_ID, - provider: "claudeAgent", + provider: ProviderDriverKind.make("claudeAgent"), runtimeMode: "full-access", }); @@ -1649,7 +1724,7 @@ describe("ClaudeAdapterLive", () => { yield* adapter.startSession({ threadId: THREAD_ID, - provider: "claudeAgent", + provider: ProviderDriverKind.make("claudeAgent"), runtimeMode: "full-access", }); @@ -1730,7 +1805,7 @@ describe("ClaudeAdapterLive", () => { const session = yield* adapter.startSession({ threadId: THREAD_ID, - provider: "claudeAgent", + provider: ProviderDriverKind.make("claudeAgent"), runtimeMode: "full-access", }); @@ -1821,7 +1896,7 @@ describe("ClaudeAdapterLive", () => { const session = yield* adapter.startSession({ threadId: THREAD_ID, - provider: "claudeAgent", + provider: ProviderDriverKind.make("claudeAgent"), runtimeMode: "full-access", }); @@ -1987,7 +2062,7 @@ describe("ClaudeAdapterLive", () => { const session = yield* adapter.startSession({ threadId: THREAD_ID, - provider: "claudeAgent", + provider: ProviderDriverKind.make("claudeAgent"), runtimeMode: "full-access", }); @@ -2056,7 +2131,7 @@ describe("ClaudeAdapterLive", () => { const session = yield* adapter.startSession({ threadId: THREAD_ID, - provider: "claudeAgent", + provider: ProviderDriverKind.make("claudeAgent"), runtimeMode: "full-access", }); @@ -2278,7 +2353,7 @@ describe("ClaudeAdapterLive", () => { const session = yield* adapter.startSession({ threadId: THREAD_ID, - provider: "claudeAgent", + provider: ProviderDriverKind.make("claudeAgent"), runtimeMode: "full-access", }); assert.equal(session.threadId, THREAD_ID); @@ -2351,7 +2426,7 @@ describe("ClaudeAdapterLive", () => { const session = yield* adapter.startSession({ threadId: THREAD_ID, - provider: "claudeAgent", + provider: ProviderDriverKind.make("claudeAgent"), runtimeMode: "approval-required", }); @@ -2460,7 +2535,7 @@ describe("ClaudeAdapterLive", () => { const session = yield* adapter.startSession({ threadId: THREAD_ID, - provider: "claudeAgent", + provider: ProviderDriverKind.make("claudeAgent"), runtimeMode: "approval-required", }); @@ -2533,7 +2608,7 @@ describe("ClaudeAdapterLive", () => { const session = yield* adapter.startSession({ threadId: RESUME_THREAD_ID, - provider: "claudeAgent", + provider: ProviderDriverKind.make("claudeAgent"), resumeCursor: { threadId: "resume-thread-1", resume: "550e8400-e29b-41d4-a716-446655440000", @@ -2575,7 +2650,7 @@ describe("ClaudeAdapterLive", () => { yield* adapter.startSession({ threadId: RESUME_THREAD_ID, - provider: "claudeAgent", + provider: ProviderDriverKind.make("claudeAgent"), resumeCursor: { threadId: RESUME_THREAD_ID, resume: durableSessionId, @@ -2658,7 +2733,7 @@ describe("ClaudeAdapterLive", () => { const session = yield* adapter.startSession({ threadId: THREAD_ID, - provider: "claudeAgent", + provider: ProviderDriverKind.make("claudeAgent"), runtimeMode: "full-access", }); @@ -2692,7 +2767,7 @@ describe("ClaudeAdapterLive", () => { const session = yield* adapter.startSession({ threadId: THREAD_ID, - provider: "claudeAgent", + provider: ProviderDriverKind.make("claudeAgent"), runtimeMode: "full-access", }); @@ -2772,14 +2847,14 @@ describe("ClaudeAdapterLive", () => { const session = yield* adapter.startSession({ threadId: THREAD_ID, - provider: "claudeAgent", + provider: ProviderDriverKind.make("claudeAgent"), runtimeMode: "full-access", }); yield* adapter.sendTurn({ threadId: session.threadId, input: "hello", modelSelection: { - provider: "claudeAgent", + instanceId: ProviderInstanceId.make("claudeAgent"), model: "claude-opus-4-6", }, attachments: [], @@ -2792,6 +2867,34 @@ describe("ClaudeAdapterLive", () => { ); }); + it.effect("updates model on sendTurn for the adapter's bound custom instance id", () => { + const customInstanceId = ProviderInstanceId.make("claude_openrouter"); + const harness = makeHarness({ instanceId: customInstanceId }); + return Effect.gen(function* () { + const adapter = yield* ClaudeAdapter; + + const session = yield* adapter.startSession({ + threadId: THREAD_ID, + provider: ProviderDriverKind.make("claudeAgent"), + runtimeMode: "full-access", + }); + yield* adapter.sendTurn({ + threadId: session.threadId, + input: "hello", + modelSelection: { + instanceId: customInstanceId, + model: "openai/gpt-5.5", + }, + attachments: [], + }); + + assert.deepEqual(harness.query.setModelCalls, ["openai/gpt-5.5"]); + }).pipe( + Effect.provideService(Random.Random, makeDeterministicRandomService()), + Effect.provide(harness.layer), + ); + }); + it.effect( "does not re-set the Claude model when the session already uses the same effective API model", () => { @@ -2799,13 +2902,13 @@ describe("ClaudeAdapterLive", () => { return Effect.gen(function* () { const adapter = yield* ClaudeAdapter; const modelSelection = { - provider: "claudeAgent" as const, + instanceId: ProviderInstanceId.make("claudeAgent"), model: "claude-opus-4-6", }; const session = yield* adapter.startSession({ threadId: THREAD_ID, - provider: "claudeAgent", + provider: ProviderDriverKind.make("claudeAgent"), modelSelection, runtimeMode: "full-access", }); @@ -2838,23 +2941,25 @@ describe("ClaudeAdapterLive", () => { const session = yield* adapter.startSession({ threadId: THREAD_ID, - provider: "claudeAgent", + provider: ProviderDriverKind.make("claudeAgent"), runtimeMode: "full-access", }); yield* adapter.sendTurn({ threadId: session.threadId, input: "hello", - modelSelection: createModelSelection("claudeAgent", "claude-opus-4-6", [ - { id: "contextWindow", value: "1m" }, - ]), + modelSelection: createModelSelection( + ProviderInstanceId.make("claudeAgent"), + "claude-opus-4-6", + [{ id: "contextWindow", value: "1m" }], + ), attachments: [], }); yield* adapter.sendTurn({ threadId: session.threadId, input: "hello again", modelSelection: { - provider: "claudeAgent", + instanceId: ProviderInstanceId.make("claudeAgent"), model: "claude-opus-4-6", }, attachments: [], @@ -2874,7 +2979,7 @@ describe("ClaudeAdapterLive", () => { const session = yield* adapter.startSession({ threadId: THREAD_ID, - provider: "claudeAgent", + provider: ProviderDriverKind.make("claudeAgent"), runtimeMode: "full-access", }); yield* adapter.sendTurn({ @@ -2904,7 +3009,7 @@ describe("ClaudeAdapterLive", () => { const session = yield* adapter.startSession({ threadId: THREAD_ID, - provider: "claudeAgent", + provider: ProviderDriverKind.make("claudeAgent"), runtimeMode, }); @@ -2956,7 +3061,7 @@ describe("ClaudeAdapterLive", () => { const session = yield* adapter.startSession({ threadId: THREAD_ID, - provider: "claudeAgent", + provider: ProviderDriverKind.make("claudeAgent"), runtimeMode: "full-access", }); yield* adapter.sendTurn({ @@ -2979,7 +3084,7 @@ describe("ClaudeAdapterLive", () => { const session = yield* adapter.startSession({ threadId: THREAD_ID, - provider: "claudeAgent", + provider: ProviderDriverKind.make("claudeAgent"), runtimeMode: "full-access", }); @@ -3045,7 +3150,7 @@ describe("ClaudeAdapterLive", () => { const session = yield* adapter.startSession({ threadId: THREAD_ID, - provider: "claudeAgent", + provider: ProviderDriverKind.make("claudeAgent"), runtimeMode: "full-access", }); @@ -3117,7 +3222,7 @@ describe("ClaudeAdapterLive", () => { // Start session in approval-required mode so canUseTool fires. const session = yield* adapter.startSession({ threadId: THREAD_ID, - provider: "claudeAgent", + provider: ProviderDriverKind.make("claudeAgent"), runtimeMode: "approval-required", }); @@ -3240,7 +3345,7 @@ describe("ClaudeAdapterLive", () => { // AskUserQuestion should still go through the user-input flow. const session = yield* adapter.startSession({ threadId: THREAD_ID, - provider: "claudeAgent", + provider: ProviderDriverKind.make("claudeAgent"), runtimeMode: "full-access", }); @@ -3306,7 +3411,7 @@ describe("ClaudeAdapterLive", () => { const session = yield* adapter.startSession({ threadId: THREAD_ID, - provider: "claudeAgent", + provider: ProviderDriverKind.make("claudeAgent"), runtimeMode: "approval-required", }); @@ -3393,7 +3498,7 @@ describe("ClaudeAdapterLive", () => { const session = yield* adapter.startSession({ threadId: THREAD_ID, - provider: "claudeAgent", + provider: ProviderDriverKind.make("claudeAgent"), runtimeMode: "full-access", }); const turn = yield* adapter.sendTurn({ diff --git a/apps/server/src/provider/Layers/ClaudeAdapter.ts b/apps/server/src/provider/Layers/ClaudeAdapter.ts index 35f326af07..c4cffbb16e 100644 --- a/apps/server/src/provider/Layers/ClaudeAdapter.ts +++ b/apps/server/src/provider/Layers/ClaudeAdapter.ts @@ -24,8 +24,11 @@ import { ApprovalRequestId, type CanonicalItemType, type CanonicalRequestType, + type ClaudeSettings, EventId, type ProviderApprovalDecision, + ProviderDriverKind, + ProviderInstanceId, ProviderItemId, type ProviderRuntimeEvent, type ProviderRuntimeTurnStatus, @@ -56,7 +59,7 @@ import { Exit, FileSystem, Fiber, - Layer, + Path, Queue, Random, Ref, @@ -65,7 +68,7 @@ import { import { resolveAttachmentPath } from "../../attachmentStore.ts"; import { ServerConfig } from "../../config.ts"; -import { ServerSettingsService } from "../../serverSettings.ts"; +import { makeClaudeEnvironment } from "../Drivers/ClaudeHome.ts"; import { getClaudeModelCapabilities, normalizeClaudeCliEffort, @@ -80,10 +83,10 @@ import { ProviderAdapterValidationError, type ProviderAdapterError, } from "../Errors.ts"; -import { ClaudeAdapter, type ClaudeAdapterShape } from "../Services/ClaudeAdapter.ts"; +import { type ClaudeAdapterShape } from "../Services/ClaudeAdapter.ts"; import { type EventNdjsonLogger, makeEventNdjsonLogger } from "./EventNdjsonLogger.ts"; -const PROVIDER = "claudeAgent" as const; +const PROVIDER = ProviderDriverKind.make("claudeAgent"); type ClaudeTextStreamKind = Extract; type ClaudeToolResultStreamKind = Extract< RuntimeContentStreamKind, @@ -182,6 +185,8 @@ interface ClaudeQueryRuntime extends AsyncIterable { } export interface ClaudeAdapterLiveOptions { + readonly instanceId?: ProviderInstanceId; + readonly environment?: NodeJS.ProcessEnv; readonly createQuery?: (input: { readonly prompt: AsyncIterable; readonly options: ClaudeQueryOptions; @@ -565,13 +570,16 @@ const CLAUDE_SETTING_SOURCES = [ "local", ] as const satisfies ReadonlyArray; -function buildPromptText(input: ProviderSendTurnInput): string { +function buildPromptText( + input: ProviderSendTurnInput, + boundInstanceId: ProviderInstanceId, +): string { const rawEffort = - input.modelSelection?.provider === "claudeAgent" + input.modelSelection?.instanceId === boundInstanceId ? getModelSelectionStringOptionValue(input.modelSelection, "effort") : null; const claudeModel = - input.modelSelection?.provider === "claudeAgent" ? input.modelSelection.model : undefined; + input.modelSelection?.instanceId === boundInstanceId ? input.modelSelection.model : undefined; const caps = getClaudeModelCapabilities(claudeModel); const promptEffort = resolvePromptInjectedEffort(caps, rawEffort); @@ -611,9 +619,10 @@ const buildUserMessageEffect = Effect.fn("buildUserMessageEffect")(function* ( dependencies: { readonly fileSystem: FileSystem.FileSystem; readonly attachmentsDir: string; + readonly boundInstanceId: ProviderInstanceId; }, ) { - const text = buildPromptText(input); + const text = buildPromptText(input, dependencies.boundInstanceId); const sdkContent: Array> = []; if (text.length > 0) { @@ -963,11 +972,17 @@ function sdkNativeItemId(message: SDKMessage): string | undefined { return undefined; } -const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* ( +export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* ( + claudeSettings: ClaudeSettings, options?: ClaudeAdapterLiveOptions, ) { + const boundInstanceId = options?.instanceId ?? ProviderInstanceId.make("claudeAgent"); const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; const serverConfig = yield* ServerConfig; + const claudeEnvironment = yield* makeClaudeEnvironment(claudeSettings, options?.environment).pipe( + Effect.provideService(Path.Path, path), + ); const nativeEventLogger = options?.nativeEventLogger ?? (options?.nativeEventLogPath !== undefined @@ -989,7 +1004,6 @@ const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* ( const sessions = new Map(); const runtimeEventQueue = yield* Queue.unbounded(); - const serverSettingsService = yield* ServerSettingsService; const nowIso = Effect.map(DateTime.now, DateTime.formatIso); const nextEventId = Effect.map(Random.nextUUIDv4, (id) => EventId.make(id)); @@ -2820,22 +2834,10 @@ const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* ( const canUseTool: CanUseTool = (toolName, toolInput, callbackOptions) => runPromise(canUseToolEffect(toolName, toolInput, callbackOptions)); - const claudeSettings = yield* serverSettingsService.getSettings.pipe( - Effect.map((settings) => settings.providers.claudeAgent), - Effect.mapError( - (error) => - new ProviderAdapterProcessError({ - provider: PROVIDER, - threadId: input.threadId, - detail: error.message, - cause: error, - }), - ), - ); const claudeBinaryPath = claudeSettings.binaryPath; const extraArgs = parseCliArgs(claudeSettings.launchArgs).flags; const modelSelection = - input.modelSelection?.provider === "claudeAgent" ? input.modelSelection : undefined; + input.modelSelection?.instanceId === boundInstanceId ? input.modelSelection : undefined; const caps = getClaudeModelCapabilities(modelSelection?.model); const descriptors = getProviderOptionDescriptors({ caps }); const apiModelId = modelSelection ? resolveClaudeApiModelId(modelSelection) : undefined; @@ -2863,7 +2865,6 @@ const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* ( ...(typeof thinking === "boolean" ? { alwaysThinkingEnabled: thinking } : {}), ...(fastMode ? { fastMode: true } : {}), }; - const queryOptions: ClaudeQueryOptions = { ...(input.cwd ? { cwd: input.cwd } : {}), ...(apiModelId ? { model: apiModelId } : {}), @@ -2885,7 +2886,7 @@ const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* ( ...(newSessionId ? { sessionId: newSessionId } : {}), includePartialMessages: true, canUseTool, - env: process.env, + env: claudeEnvironment, ...(input.cwd ? { additionalDirectories: [input.cwd] } : {}), ...(Object.keys(extraArgs).length > 0 ? { extraArgs } : {}), }; @@ -2933,6 +2934,7 @@ const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* ( const session: ProviderSession = { threadId, provider: PROVIDER, + providerInstanceId: boundInstanceId, status: "ready", runtimeMode: input.runtimeMode, ...(input.cwd ? { cwd: input.cwd } : {}), @@ -3044,7 +3046,9 @@ const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* ( const sendTurn: ClaudeAdapterShape["sendTurn"] = Effect.fn("sendTurn")(function* (input) { const context = yield* requireSession(input.threadId); const modelSelection = - input.modelSelection?.provider === "claudeAgent" ? input.modelSelection : undefined; + input.modelSelection !== undefined && input.modelSelection.instanceId === boundInstanceId + ? input.modelSelection + : undefined; if (context.turnState) { // Auto-close a stale synthetic turn (from background agent responses @@ -3118,6 +3122,7 @@ const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* ( const message = yield* buildUserMessageEffect(input, { fileSystem, attachmentsDir: serverConfig.attachmentsDir, + boundInstanceId, }); yield* Queue.offer(context.promptQueue, { @@ -3255,9 +3260,3 @@ const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* ( }, } satisfies ClaudeAdapterShape; }); - -export const ClaudeAdapterLive = Layer.effect(ClaudeAdapter, makeClaudeAdapter()); - -export function makeClaudeAdapterLive(options?: ClaudeAdapterLiveOptions) { - return Layer.effect(ClaudeAdapter, makeClaudeAdapter(options)); -} diff --git a/apps/server/src/provider/Layers/ClaudeProvider.ts b/apps/server/src/provider/Layers/ClaudeProvider.ts index f41082bbba..4350596700 100644 --- a/apps/server/src/provider/Layers/ClaudeProvider.ts +++ b/apps/server/src/provider/Layers/ClaudeProvider.ts @@ -1,16 +1,13 @@ -import type { - ClaudeSettings, - ClaudeModelSelection, - ModelCapabilities, - ServerProvider, - ServerProviderModel, - ServerProviderAuth, - ServerProviderSlashCommand, - ServerProviderState, +import { + type ClaudeSettings, + type ModelCapabilities, + type ModelSelection, + ProviderDriverKind, + type ServerProviderModel, + type ServerProviderSlashCommand, } from "@t3tools/contracts"; -import { Cache, Duration, Effect, Equal, Layer, Option, Result, Schema, Stream } from "effect"; +import { Effect, Option, Path, Result } from "effect"; import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process"; -import { decodeJsonResult } from "@t3tools/shared/schemaJson"; import { createModelCapabilities, getModelSelectionStringOptionValue, @@ -27,27 +24,22 @@ import { buildBooleanOptionDescriptor, buildSelectOptionDescriptor, buildServerProvider, - AUTH_PROBE_TIMEOUT_MS, DEFAULT_TIMEOUT_MS, detailFromResult, - extractAuthBoolean, isCommandMissingCause, parseGenericCliVersion, providerModelsFromSettings, spawnAndCollect, - type CommandResult, + type ServerProviderDraft, } from "../providerSnapshot.ts"; import { compareCliVersions } from "../cliVersion.ts"; -import { makeManagedServerProvider } from "../makeManagedServerProvider.ts"; -import { ClaudeProvider } from "../Services/ClaudeProvider.ts"; -import { ServerSettingsService } from "../../serverSettings.ts"; -import { ServerSettingsError } from "@t3tools/contracts"; +import { makeClaudeEnvironment } from "../Drivers/ClaudeHome.ts"; const DEFAULT_CLAUDE_MODEL_CAPABILITIES: ModelCapabilities = createModelCapabilities({ optionDescriptors: [], }); -const PROVIDER = "claudeAgent" as const; +const PROVIDER = ProviderDriverKind.make("claudeAgent"); const CLAUDE_PRESENTATION = { displayName: "Claude", showInteractionModeToggle: true, @@ -242,7 +234,7 @@ export function normalizeClaudeCliEffort(effort: string | null | undefined): str return effort; } -export function resolveClaudeApiModelId(modelSelection: ClaudeModelSelection): string { +export function resolveClaudeApiModelId(modelSelection: ModelSelection): string { switch (getModelSelectionStringOptionValue(modelSelection, "contextWindow")) { case "1m": return `${modelSelection.model}[1m]`; @@ -250,181 +242,6 @@ export function resolveClaudeApiModelId(modelSelection: ClaudeModelSelection): s return modelSelection.model; } } -export function parseClaudeAuthStatusFromOutput(result: CommandResult): { - readonly status: Exclude; - readonly auth: Pick; - readonly message?: string; -} { - const lowerOutput = `${result.stdout}\n${result.stderr}`.toLowerCase(); - - if ( - lowerOutput.includes("unknown command") || - lowerOutput.includes("unrecognized command") || - lowerOutput.includes("unexpected argument") - ) { - return { - status: "warning", - auth: { status: "unknown" }, - message: - "Claude Agent authentication status command is unavailable in this version of Claude.", - }; - } - - if ( - lowerOutput.includes("not logged in") || - lowerOutput.includes("login required") || - lowerOutput.includes("authentication required") || - lowerOutput.includes("run `claude login`") || - lowerOutput.includes("run claude login") - ) { - return { - status: "error", - auth: { status: "unauthenticated" }, - message: "Claude is not authenticated. Run `claude auth login` and try again.", - }; - } - - const parsedAuth = (() => { - const trimmed = result.stdout.trim(); - if (!trimmed || (!trimmed.startsWith("{") && !trimmed.startsWith("["))) { - return { attemptedJsonParse: false as const, auth: undefined as boolean | undefined }; - } - try { - return { - attemptedJsonParse: true as const, - auth: extractAuthBoolean(JSON.parse(trimmed)), - }; - } catch { - return { attemptedJsonParse: false as const, auth: undefined as boolean | undefined }; - } - })(); - - if (parsedAuth.auth === true) { - return { status: "ready", auth: { status: "authenticated" } }; - } - if (parsedAuth.auth === false) { - return { - status: "error", - auth: { status: "unauthenticated" }, - message: "Claude is not authenticated. Run `claude auth login` and try again.", - }; - } - if (parsedAuth.attemptedJsonParse) { - return { - status: "warning", - auth: { status: "unknown" }, - message: - "Could not verify Claude authentication status from JSON output (missing auth marker).", - }; - } - if (result.code === 0) { - return { status: "ready", auth: { status: "authenticated" } }; - } - - const detail = detailFromResult(result); - return { - status: "warning", - auth: { status: "unknown" }, - message: detail - ? `Could not verify Claude authentication status. ${detail}` - : "Could not verify Claude authentication status.", - }; -} - -// ── Subscription type detection ───────────────────────────────────── -// -// The SDK probe returns typed `AccountInfo.subscriptionType` directly. -// This walker is a best-effort fallback for the `claude auth status` -// JSON output whose shape is not guaranteed. - -/** Keys that directly hold a subscription/plan identifier. */ -const SUBSCRIPTION_TYPE_KEYS = [ - "subscriptionType", - "subscription_type", - "plan", - "tier", - "planType", - "plan_type", -] as const; - -/** Keys whose value may be a nested object containing subscription info. */ -const SUBSCRIPTION_CONTAINER_KEYS = ["account", "subscription", "user", "billing"] as const; -const AUTH_METHOD_KEYS = ["authMethod", "auth_method"] as const; -const AUTH_METHOD_CONTAINER_KEYS = ["auth", "account", "session"] as const; - -/** Lift an unknown value into `Option` if it is a non-empty string. */ -const asNonEmptyString = (v: unknown): Option.Option => - typeof v === "string" && v.length > 0 ? Option.some(v) : Option.none(); - -/** Lift an unknown value into `Option` if it is a plain object. */ -const asRecord = (v: unknown): Option.Option> => - typeof v === "object" && v !== null && !globalThis.Array.isArray(v) - ? Option.some(v as Record) - : Option.none(); - -/** - * Walk an unknown parsed JSON value looking for a subscription/plan - * identifier, returning the first match as an `Option`. - */ -function findSubscriptionType(value: unknown): Option.Option { - if (globalThis.Array.isArray(value)) { - return Option.firstSomeOf(value.map(findSubscriptionType)); - } - - return asRecord(value).pipe( - Option.flatMap((record) => { - const direct = Option.firstSomeOf( - SUBSCRIPTION_TYPE_KEYS.map((key) => asNonEmptyString(record[key])), - ); - if (Option.isSome(direct)) return direct; - - return Option.firstSomeOf( - SUBSCRIPTION_CONTAINER_KEYS.map((key) => - asRecord(record[key]).pipe(Option.flatMap(findSubscriptionType)), - ), - ); - }), - ); -} - -function findAuthMethod(value: unknown): Option.Option { - if (globalThis.Array.isArray(value)) { - return Option.firstSomeOf(value.map(findAuthMethod)); - } - - return asRecord(value).pipe( - Option.flatMap((record) => { - const direct = Option.firstSomeOf( - AUTH_METHOD_KEYS.map((key) => asNonEmptyString(record[key])), - ); - if (Option.isSome(direct)) return direct; - - return Option.firstSomeOf( - AUTH_METHOD_CONTAINER_KEYS.map((key) => - asRecord(record[key]).pipe(Option.flatMap(findAuthMethod)), - ), - ); - }), - ); -} - -/** - * Try to extract a subscription type from the `claude auth status` JSON - * output. This is a zero-cost operation on data we already have. - */ -const decodeUnknownJson = decodeJsonResult(Schema.Unknown); - -function extractSubscriptionTypeFromOutput(result: CommandResult): string | undefined { - const parsed = decodeUnknownJson(result.stdout.trim()); - if (Result.isFailure(parsed)) return undefined; - return Option.getOrUndefined(findSubscriptionType(parsed.success)); -} - -function extractClaudeAuthMethodFromOutput(result: CommandResult): string | undefined { - const parsed = decodeUnknownJson(result.stdout.trim()); - if (Result.isFailure(parsed)) return undefined; - return Option.getOrUndefined(findAuthMethod(parsed.success)); -} function toTitleCaseWords(value: string): string { return value @@ -439,11 +256,27 @@ function claudeSubscriptionLabel(subscriptionType: string | undefined): string | if (!normalized) return undefined; switch (normalized) { + case "claudemaxsubscription": + return "Max"; + case "claudemax5xsubscription": + return "Max 5x"; + case "claudemax20xsubscription": + return "Max 20x"; + case "claudeenterprisesubscription": + return "Enterprise"; + case "claudeteamsubscription": + return "Team"; + case "claudeprosubscription": + return "Pro"; + case "claudefreesubscription": + return "Free"; case "max": case "maxplan": - case "max5": - case "max20": return "Max"; + case "max5": + return "Max 5x"; + case "max20": + return "Max 20x"; case "enterprise": return "Enterprise"; case "team": @@ -460,10 +293,33 @@ function claudeSubscriptionLabel(subscriptionType: string | undefined): string | function normalizeClaudeAuthMethod(authMethod: string | undefined): string | undefined { const normalized = authMethod?.toLowerCase().replace(/[\s_-]+/g, ""); if (!normalized) return undefined; - if (normalized === "apikey") return "apiKey"; + if ( + normalized === "apikey" || + normalized === "anthropicapikey" || + normalized === "anthropicauthtoken" + ) { + return "apiKey"; + } return undefined; } +function formatClaudeSubscriptionAuthLabel(subscriptionType: string): string { + const subscriptionLabel = + claudeSubscriptionLabel(subscriptionType) ?? toTitleCaseWords(subscriptionType); + const normalized = subscriptionLabel.toLowerCase().replace(/[\s_-]+/g, ""); + + if (normalized.startsWith("claude") && normalized.endsWith("subscription")) { + return subscriptionLabel; + } + if (normalized.startsWith("claude")) { + return `${subscriptionLabel} Subscription`; + } + if (normalized.endsWith("subscription")) { + return `Claude ${subscriptionLabel}`; + } + return `Claude ${subscriptionLabel} Subscription`; +} + function claudeAuthMetadata(input: { readonly subscriptionType: string | undefined; readonly authMethod: string | undefined; @@ -476,10 +332,9 @@ function claudeAuthMetadata(input: { } if (input.subscriptionType) { - const subscriptionLabel = claudeSubscriptionLabel(input.subscriptionType); return { type: input.subscriptionType, - label: `Claude ${subscriptionLabel ?? toTitleCaseWords(input.subscriptionType)} Subscription`, + label: formatClaudeSubscriptionAuthLabel(input.subscriptionType), }; } @@ -495,6 +350,13 @@ function nonEmptyProbeString(value: string): string | undefined { return candidate ? candidate : undefined; } +type ClaudeCapabilitiesProbe = { + readonly email: string | undefined; + readonly subscriptionType: string | undefined; + readonly tokenSource: string | undefined; + readonly slashCommands: ReadonlyArray; +}; + function parseClaudeInitializationCommands( commands: ReadonlyArray | undefined, ): ReadonlyArray { @@ -580,30 +442,46 @@ function waitForAbortSignal(signal: AbortSignal): Promise { * This is used as a fallback when `claude auth status` does not include * subscription type information. */ -const probeClaudeCapabilities = (binaryPath: string) => { +const probeClaudeCapabilities = ( + claudeSettings: ClaudeSettings, + environment: NodeJS.ProcessEnv = process.env, +) => { const abort = new AbortController(); - return Effect.tryPromise(async () => { - const q = claudeQuery({ - // Never yield — we only need initialization data, not a conversation. - // This prevents any prompt from reaching the Anthropic API. - // oxlint-disable-next-line require-yield - prompt: (async function* (): AsyncGenerator { - await waitForAbortSignal(abort.signal); - })(), - options: { - persistSession: false, - pathToClaudeCodeExecutable: binaryPath, - abortController: abort, - settingSources: ["user", "project", "local"], - allowedTools: [], - stderr: () => {}, - }, + return Effect.gen(function* () { + const claudeEnvironment = yield* makeClaudeEnvironment(claudeSettings, environment); + return yield* Effect.tryPromise(async () => { + const q = claudeQuery({ + // Never yield — we only need initialization data, not a conversation. + // This prevents any prompt from reaching the Anthropic API. + // oxlint-disable-next-line require-yield + prompt: (async function* (): AsyncGenerator { + await waitForAbortSignal(abort.signal); + })(), + options: { + persistSession: false, + pathToClaudeCodeExecutable: claudeSettings.binaryPath, + abortController: abort, + settingSources: ["user", "project", "local"], + allowedTools: [], + env: claudeEnvironment, + stderr: () => {}, + }, + }); + const init = await q.initializationResult(); + const account = init.account as + | { + readonly email?: string; + readonly subscriptionType?: string; + readonly tokenSource?: string; + } + | undefined; + return { + email: account?.email, + subscriptionType: account?.subscriptionType, + tokenSource: account?.tokenSource, + slashCommands: parseClaudeInitializationCommands(init.commands), + } satisfies ClaudeCapabilitiesProbe; }); - const init = await q.initializationResult(); - return { - subscriptionType: init.account?.subscriptionType, - slashCommands: parseClaudeInitializationCommands(init.commands), - }; }).pipe( Effect.ensuring( Effect.sync(() => { @@ -619,31 +497,30 @@ const probeClaudeCapabilities = (binaryPath: string) => { ); }; -const runClaudeCommand = Effect.fn("runClaudeCommand")(function* (args: ReadonlyArray) { - const claudeSettings = yield* Effect.service(ServerSettingsService).pipe( - Effect.flatMap((service) => service.getSettings), - Effect.map((settings) => settings.providers.claudeAgent), - ); +const runClaudeCommand = Effect.fn("runClaudeCommand")(function* ( + claudeSettings: ClaudeSettings, + args: ReadonlyArray, + environment: NodeJS.ProcessEnv = process.env, +) { + const claudeEnvironment = yield* makeClaudeEnvironment(claudeSettings, environment); const command = ChildProcess.make(claudeSettings.binaryPath, [...args], { + env: claudeEnvironment, shell: process.platform === "win32", }); return yield* spawnAndCollect(claudeSettings.binaryPath, command); }); export const checkClaudeProviderStatus = Effect.fn("checkClaudeProviderStatus")(function* ( - resolveSubscriptionType?: (binaryPath: string) => Effect.Effect, - resolveSlashCommands?: ( - binaryPath: string, - ) => Effect.Effect | undefined>, + claudeSettings: ClaudeSettings, + resolveCapabilities?: ( + claudeSettings: ClaudeSettings, + ) => Effect.Effect, + environment: NodeJS.ProcessEnv = process.env, ): Effect.fn.Return< - ServerProvider, - ServerSettingsError, - ChildProcessSpawner.ChildProcessSpawner | ServerSettingsService + ServerProviderDraft, + never, + ChildProcessSpawner.ChildProcessSpawner | Path.Path > { - const claudeSettings = yield* Effect.service(ServerSettingsService).pipe( - Effect.flatMap((service) => service.getSettings), - Effect.map((settings) => settings.providers.claudeAgent), - ); const checkedAt = new Date().toISOString(); const allModels = providerModelsFromSettings( BUILT_IN_MODELS, @@ -654,7 +531,6 @@ export const checkClaudeProviderStatus = Effect.fn("checkClaudeProviderStatus")( if (!claudeSettings.enabled) { return buildServerProvider({ - provider: PROVIDER, presentation: CLAUDE_PRESENTATION, enabled: false, checkedAt, @@ -669,7 +545,7 @@ export const checkClaudeProviderStatus = Effect.fn("checkClaudeProviderStatus")( }); } - const versionProbe = yield* runClaudeCommand(["--version"]).pipe( + const versionProbe = yield* runClaudeCommand(claudeSettings, ["--version"], environment).pipe( Effect.timeoutOption(DEFAULT_TIMEOUT_MS), Effect.result, ); @@ -677,7 +553,6 @@ export const checkClaudeProviderStatus = Effect.fn("checkClaudeProviderStatus")( if (Result.isFailure(versionProbe)) { const error = versionProbe.failure; return buildServerProvider({ - provider: PROVIDER, presentation: CLAUDE_PRESENTATION, enabled: claudeSettings.enabled, checkedAt, @@ -696,7 +571,6 @@ export const checkClaudeProviderStatus = Effect.fn("checkClaudeProviderStatus")( if (Option.isNone(versionProbe.success)) { return buildServerProvider({ - provider: PROVIDER, presentation: CLAUDE_PRESENTATION, enabled: claudeSettings.enabled, checkedAt, @@ -717,7 +591,6 @@ export const checkClaudeProviderStatus = Effect.fn("checkClaudeProviderStatus")( if (version.code !== 0) { const detail = detailFromResult(version); return buildServerProvider({ - provider: PROVIDER, presentation: CLAUDE_PRESENTATION, enabled: claudeSettings.enabled, checkedAt, @@ -744,45 +617,14 @@ export const checkClaudeProviderStatus = Effect.fn("checkClaudeProviderStatus")( ? undefined : formatClaudeOpus47UpgradeMessage(parsedVersion); - const slashCommands = - (resolveSlashCommands - ? yield* resolveSlashCommands(claudeSettings.binaryPath).pipe( - Effect.orElseSucceed(() => undefined), - ) - : undefined) ?? []; + const capabilities = resolveCapabilities + ? yield* resolveCapabilities(claudeSettings).pipe(Effect.orElseSucceed(() => undefined)) + : undefined; + const slashCommands = capabilities?.slashCommands ?? []; const dedupedSlashCommands = dedupeSlashCommands(slashCommands); - // ── Auth check + subscription detection ──────────────────────────── - - const authProbe = yield* runClaudeCommand(["auth", "status"]).pipe( - Effect.timeoutOption(AUTH_PROBE_TIMEOUT_MS), - Effect.result, - ); - - // Determine subscription type from multiple sources (cheapest first): - // 1. `claude auth status` JSON output (may or may not contain it) - // 2. Cached SDK probe (spawns a Claude process on miss, reads - // `initializationResult()` for account metadata, then aborts - // immediately — no API tokens are consumed) - - let subscriptionType: string | undefined; - let authMethod: string | undefined; - - if (Result.isSuccess(authProbe) && Option.isSome(authProbe.success)) { - subscriptionType = extractSubscriptionTypeFromOutput(authProbe.success.value); - authMethod = extractClaudeAuthMethodFromOutput(authProbe.success.value); - } - - if (!subscriptionType && resolveSubscriptionType) { - subscriptionType = yield* resolveSubscriptionType(claudeSettings.binaryPath); - } - - // ── Handle auth results (same logic as before, adjusted models) ── - - if (Result.isFailure(authProbe)) { - const error = authProbe.failure; + if (!capabilities) { return buildServerProvider({ - provider: PROVIDER, presentation: CLAUDE_PRESENTATION, enabled: claudeSettings.enabled, checkedAt, @@ -793,36 +635,16 @@ export const checkClaudeProviderStatus = Effect.fn("checkClaudeProviderStatus")( version: parsedVersion, status: "warning", auth: { status: "unknown" }, - message: - error instanceof Error - ? `Could not verify Claude authentication status: ${error.message}.` - : "Could not verify Claude authentication status.", + message: "Could not verify Claude authentication status from initialization result.", }, }); } - if (Option.isNone(authProbe.success)) { - return buildServerProvider({ - provider: PROVIDER, - presentation: CLAUDE_PRESENTATION, - enabled: claudeSettings.enabled, - checkedAt, - models, - slashCommands: dedupedSlashCommands, - probe: { - installed: true, - version: parsedVersion, - status: "warning", - auth: { status: "unknown" }, - message: "Could not verify Claude authentication status. Timed out while running command.", - }, - }); - } - - const parsed = parseClaudeAuthStatusFromOutput(authProbe.success.value); - const authMetadata = claudeAuthMetadata({ subscriptionType, authMethod }); + const authMetadata = claudeAuthMetadata({ + subscriptionType: capabilities.subscriptionType, + authMethod: capabilities.tokenSource, + }); return buildServerProvider({ - provider: PROVIDER, presentation: CLAUDE_PRESENTATION, enabled: claudeSettings.enabled, checkedAt, @@ -831,21 +653,18 @@ export const checkClaudeProviderStatus = Effect.fn("checkClaudeProviderStatus")( probe: { installed: true, version: parsedVersion, - status: parsed.status, + status: "ready", auth: { - ...parsed.auth, + status: "authenticated", + ...(capabilities.email ? { email: capabilities.email } : {}), ...(authMetadata ? authMetadata : {}), }, - ...(parsed.message - ? { message: parsed.message } - : opus47UpgradeMessage - ? { message: opus47UpgradeMessage } - : {}), + ...(opus47UpgradeMessage ? { message: opus47UpgradeMessage } : {}), }, }); }); -const makePendingClaudeProvider = (claudeSettings: ClaudeSettings): ServerProvider => { +export const makePendingClaudeProvider = (claudeSettings: ClaudeSettings): ServerProviderDraft => { const checkedAt = new Date().toISOString(); const models = providerModelsFromSettings( BUILT_IN_MODELS, @@ -856,7 +675,6 @@ const makePendingClaudeProvider = (claudeSettings: ClaudeSettings): ServerProvid if (!claudeSettings.enabled) { return buildServerProvider({ - provider: PROVIDER, presentation: CLAUDE_PRESENTATION, enabled: false, checkedAt, @@ -872,7 +690,6 @@ const makePendingClaudeProvider = (claudeSettings: ClaudeSettings): ServerProvid } return buildServerProvider({ - provider: PROVIDER, presentation: CLAUDE_PRESENTATION, enabled: true, checkedAt, @@ -887,43 +704,4 @@ const makePendingClaudeProvider = (claudeSettings: ClaudeSettings): ServerProvid }); }; -export const ClaudeProviderLive = Layer.effect( - ClaudeProvider, - Effect.gen(function* () { - const serverSettings = yield* ServerSettingsService; - const spawner = yield* ChildProcessSpawner.ChildProcessSpawner; - - const subscriptionProbeCache = yield* Cache.make({ - capacity: 1, - timeToLive: Duration.minutes(5), - lookup: (binaryPath: string) => probeClaudeCapabilities(binaryPath), - }); - - const checkProvider = checkClaudeProviderStatus( - (binaryPath) => - Cache.get(subscriptionProbeCache, binaryPath).pipe( - Effect.map((probe) => probe?.subscriptionType), - ), - (binaryPath) => - Cache.get(subscriptionProbeCache, binaryPath).pipe( - Effect.map((probe) => probe?.slashCommands), - ), - ).pipe( - Effect.provideService(ServerSettingsService, serverSettings), - Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner), - ); - - return yield* makeManagedServerProvider({ - getSettings: serverSettings.getSettings.pipe( - Effect.map((settings) => settings.providers.claudeAgent), - Effect.orDie, - ), - streamSettings: serverSettings.streamChanges.pipe( - Stream.map((settings) => settings.providers.claudeAgent), - ), - haveSettingsChanged: (previous, next) => !Equal.equals(previous, next), - initialSnapshot: makePendingClaudeProvider, - checkProvider, - }); - }), -); +export { probeClaudeCapabilities }; diff --git a/apps/server/src/provider/Layers/CodexAdapter.test.ts b/apps/server/src/provider/Layers/CodexAdapter.test.ts index ad6fddab1c..4df4fb5d32 100644 --- a/apps/server/src/provider/Layers/CodexAdapter.test.ts +++ b/apps/server/src/provider/Layers/CodexAdapter.test.ts @@ -4,7 +4,10 @@ import os from "node:os"; import path from "node:path"; import { ApprovalRequestId, + CodexSettings, EventId, + ProviderDriverKind, + ProviderInstanceId, ProviderItemId, type ProviderApprovalDecision, type ProviderEvent, @@ -18,13 +21,13 @@ import { createModelSelection } from "@t3tools/shared/model"; import * as NodeServices from "@effect/platform-node/NodeServices"; import { it, vi } from "@effect/vitest"; -import { Effect, Exit, Fiber, Layer, Option, Queue, Scope, Stream } from "effect"; +import { Context, Effect, Exit, Fiber, Layer, Option, Queue, Schema, Scope, Stream } from "effect"; import * as CodexErrors from "effect-codex-app-server/errors"; import { ServerConfig } from "../../config.ts"; import { ServerSettingsService } from "../../serverSettings.ts"; import { ProviderAdapterValidationError } from "../Errors.ts"; -import { CodexAdapter } from "../Services/CodexAdapter.ts"; +import type { CodexAdapterShape } from "../Services/CodexAdapter.ts"; import { ProviderSessionDirectory } from "../Services/ProviderSessionDirectory.ts"; import { type CodexSessionRuntimeOptions, @@ -32,7 +35,12 @@ import { type CodexSessionRuntimeShape, type CodexThreadSnapshot, } from "./CodexSessionRuntime.ts"; -import { makeCodexAdapterLive } from "./CodexAdapter.ts"; +import { makeCodexAdapter } from "./CodexAdapter.ts"; + +// Test-local service tag so the rest of the file can keep using `yield* CodexAdapter`. +class CodexAdapter extends Context.Service()( + "test/CodexAdapter", +) {} const asThreadId = (value: string): ThreadId => ThreadId.make(value); const asTurnId = (value: string): TurnId => TurnId.make(value); @@ -45,7 +53,7 @@ class FakeCodexRuntime implements CodexSessionRuntimeShape { public readonly startImpl = vi.fn(() => Promise.resolve({ - provider: "codex" as const, + provider: ProviderDriverKind.make("codex"), status: "ready" as const, runtimeMode: this.options.runtimeMode, threadId: this.options.threadId, @@ -203,7 +211,15 @@ const providerSessionDirectoryTestLayer = Layer.succeed(ProviderSessionDirectory const validationRuntimeFactory = makeRuntimeFactory(); const validationLayer = it.layer( - makeCodexAdapterLive({ makeRuntime: validationRuntimeFactory.factory }).pipe( + Layer.effect( + CodexAdapter, + Effect.gen(function* () { + const codexConfig = Schema.decodeSync(CodexSettings)({}); + return yield* makeCodexAdapter(codexConfig, { + makeRuntime: validationRuntimeFactory.factory, + }); + }), + ).pipe( Layer.provideMerge(ServerConfig.layerTest(process.cwd(), process.cwd())), Layer.provideMerge(ServerSettingsService.layerTest()), Layer.provideMerge(providerSessionDirectoryTestLayer), @@ -217,7 +233,7 @@ validationLayer("CodexAdapterLive validation", (it) => { const adapter = yield* CodexAdapter; const result = yield* adapter .startSession({ - provider: "claudeAgent", + provider: ProviderDriverKind.make("claudeAgent"), threadId: asThreadId("thread-1"), runtimeMode: "full-access", }) @@ -227,7 +243,7 @@ validationLayer("CodexAdapterLive validation", (it) => { assert.deepStrictEqual( result.failure, new ProviderAdapterValidationError({ - provider: "codex", + provider: ProviderDriverKind.make("codex"), operation: "startSession", issue: "Expected provider 'codex' but received 'claudeAgent'.", }), @@ -241,9 +257,9 @@ validationLayer("CodexAdapterLive validation", (it) => { const adapter = yield* CodexAdapter; yield* adapter.startSession({ - provider: "codex", + provider: ProviderDriverKind.make("codex"), threadId: asThreadId("thread-1"), - modelSelection: createModelSelection("codex", "gpt-5.3-codex", [ + modelSelection: createModelSelection(ProviderInstanceId.make("codex"), "gpt-5.3-codex", [ { id: "fastMode", value: true }, ]), runtimeMode: "full-access", @@ -253,6 +269,7 @@ validationLayer("CodexAdapterLive validation", (it) => { binaryPath: "codex", cwd: process.cwd(), model: "gpt-5.3-codex", + providerInstanceId: ProviderInstanceId.make("codex"), serviceTier: "fast", threadId: asThreadId("thread-1"), runtimeMode: "full-access", @@ -263,7 +280,15 @@ validationLayer("CodexAdapterLive validation", (it) => { const sessionRuntimeFactory = makeRuntimeFactory(); const sessionErrorLayer = it.layer( - makeCodexAdapterLive({ makeRuntime: sessionRuntimeFactory.factory }).pipe( + Layer.effect( + CodexAdapter, + Effect.gen(function* () { + const codexConfig = Schema.decodeSync(CodexSettings)({}); + return yield* makeCodexAdapter(codexConfig, { + makeRuntime: sessionRuntimeFactory.factory, + }); + }), + ).pipe( Layer.provideMerge(ServerConfig.layerTest(process.cwd(), process.cwd())), Layer.provideMerge(ServerSettingsService.layerTest()), Layer.provideMerge(providerSessionDirectoryTestLayer), @@ -294,7 +319,7 @@ sessionErrorLayer("CodexAdapterLive session errors", (it) => { Effect.gen(function* () { const adapter = yield* CodexAdapter; yield* adapter.startSession({ - provider: "codex", + provider: ProviderDriverKind.make("codex"), threadId: asThreadId("sess-missing"), runtimeMode: "full-access", }); @@ -306,7 +331,7 @@ sessionErrorLayer("CodexAdapterLive session errors", (it) => { adapter.sendTurn({ threadId: asThreadId("sess-missing"), input: "hello", - modelSelection: createModelSelection("codex", "gpt-5.3-codex", [ + modelSelection: createModelSelection(ProviderInstanceId.make("codex"), "gpt-5.3-codex", [ { id: "reasoningEffort", value: "high" }, { id: "fastMode", value: true }, ]), @@ -322,11 +347,74 @@ sessionErrorLayer("CodexAdapterLive session errors", (it) => { }); }), ); + + it.effect("maps codex model options for the adapter's bound custom instance id", () => { + const customInstanceId = ProviderInstanceId.make("codex_personal"); + const customRuntimeFactory = makeRuntimeFactory(); + const customLayer = Layer.effect( + CodexAdapter, + Effect.gen(function* () { + const codexConfig = Schema.decodeSync(CodexSettings)({}); + return yield* makeCodexAdapter(codexConfig, { + instanceId: customInstanceId, + makeRuntime: customRuntimeFactory.factory, + }); + }), + ).pipe( + Layer.provideMerge(ServerConfig.layerTest(process.cwd(), process.cwd())), + Layer.provideMerge(ServerSettingsService.layerTest()), + Layer.provideMerge(providerSessionDirectoryTestLayer), + Layer.provideMerge(NodeServices.layer), + ); + + return Effect.gen(function* () { + const adapter = yield* CodexAdapter; + yield* adapter.startSession({ + provider: ProviderDriverKind.make("codex"), + threadId: asThreadId("sess-custom-instance"), + runtimeMode: "full-access", + }); + const runtime = customRuntimeFactory.lastRuntime; + assert.ok(runtime); + runtime.sendTurnImpl.mockClear(); + + yield* Effect.ignore( + adapter.sendTurn({ + threadId: asThreadId("sess-custom-instance"), + input: "hello", + modelSelection: createModelSelection( + ProviderInstanceId.make("codex_personal"), + "gpt-5.3-codex", + [ + { id: "reasoningEffort", value: "high" }, + { id: "fastMode", value: true }, + ], + ), + attachments: [], + }), + ); + + assert.deepStrictEqual(runtime.sendTurnImpl.mock.calls[0]?.[0], { + input: "hello", + model: "gpt-5.3-codex", + effort: "high", + serviceTier: "fast", + }); + }).pipe(Effect.provide(customLayer)); + }); }); const lifecycleRuntimeFactory = makeRuntimeFactory(); const lifecycleLayer = it.layer( - makeCodexAdapterLive({ makeRuntime: lifecycleRuntimeFactory.factory }).pipe( + Layer.effect( + CodexAdapter, + Effect.gen(function* () { + const codexConfig = Schema.decodeSync(CodexSettings)({}); + return yield* makeCodexAdapter(codexConfig, { + makeRuntime: lifecycleRuntimeFactory.factory, + }); + }), + ).pipe( Layer.provideMerge(ServerConfig.layerTest(process.cwd(), process.cwd())), Layer.provideMerge(ServerSettingsService.layerTest()), Layer.provideMerge(providerSessionDirectoryTestLayer), @@ -338,7 +426,7 @@ function startLifecycleRuntime() { return Effect.gen(function* () { const adapter = yield* CodexAdapter; yield* adapter.startSession({ - provider: "codex", + provider: ProviderDriverKind.make("codex"), threadId: asThreadId("thread-1"), runtimeMode: "full-access", }); @@ -357,7 +445,7 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => { const event: ProviderEvent = { id: asEventId("evt-msg-complete"), kind: "notification", - provider: "codex", + provider: ProviderDriverKind.make("codex"), createdAt: new Date().toISOString(), method: "item/completed", threadId: asThreadId("thread-1"), @@ -399,7 +487,7 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => { const event: ProviderEvent = { id: asEventId("evt-plan-complete"), kind: "notification", - provider: "codex", + provider: ProviderDriverKind.make("codex"), createdAt: new Date().toISOString(), method: "item/completed", threadId: asThreadId("thread-1"), @@ -440,7 +528,7 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => { yield* runtime.emit({ id: asEventId("evt-plan-delta"), kind: "notification", - provider: "codex", + provider: ProviderDriverKind.make("codex"), createdAt: new Date().toISOString(), method: "item/plan/delta", threadId: asThreadId("thread-1"), @@ -477,7 +565,7 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => { const event: ProviderEvent = { id: asEventId("evt-session-closed"), kind: "session", - provider: "codex", + provider: ProviderDriverKind.make("codex"), threadId: asThreadId("thread-1"), createdAt: new Date().toISOString(), method: "session/closed", @@ -508,7 +596,7 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => { yield* runtime.emit({ id: asEventId("evt-retryable-error"), kind: "notification", - provider: "codex", + provider: ProviderDriverKind.make("codex"), threadId: asThreadId("thread-1"), createdAt: new Date().toISOString(), method: "error", @@ -546,7 +634,7 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => { yield* runtime.emit({ id: asEventId("evt-process-stderr"), kind: "notification", - provider: "codex", + provider: ProviderDriverKind.make("codex"), threadId: asThreadId("thread-1"), createdAt: new Date().toISOString(), method: "process/stderr", @@ -580,7 +668,7 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => { yield* runtime.emit({ id: asEventId("evt-process-stderr-websocket"), kind: "notification", - provider: "codex", + provider: ProviderDriverKind.make("codex"), threadId: asThreadId("thread-1"), createdAt: new Date().toISOString(), method: "process/stderr", @@ -616,7 +704,7 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => { const event: ProviderEvent = { id: asEventId("evt-request-resolved"), kind: "notification", - provider: "codex", + provider: ProviderDriverKind.make("codex"), threadId: asThreadId("thread-1"), createdAt: new Date().toISOString(), method: "serverRequest/resolved", @@ -651,7 +739,7 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => { const event: ProviderEvent = { id: asEventId("evt-file-read-request-resolved"), kind: "notification", - provider: "codex", + provider: ProviderDriverKind.make("codex"), threadId: asThreadId("thread-1"), createdAt: new Date().toISOString(), method: "serverRequest/resolved", @@ -686,7 +774,7 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => { const event: ProviderEvent = { id: asEventId("evt-user-input-empty"), kind: "notification", - provider: "codex", + provider: ProviderDriverKind.make("codex"), threadId: asThreadId("thread-1"), createdAt: new Date().toISOString(), method: "item/tool/requestUserInput/answered", @@ -726,7 +814,7 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => { const event: ProviderEvent = { id: asEventId("evt-windows-sandbox-failed"), kind: "notification", - provider: "codex", + provider: ProviderDriverKind.make("codex"), threadId: asThreadId("thread-1"), createdAt: new Date().toISOString(), method: "windowsSandbox/setupCompleted", @@ -771,7 +859,7 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => { yield* runtime.emit({ id: asEventId("evt-user-input-requested"), kind: "request", - provider: "codex", + provider: ProviderDriverKind.make("codex"), threadId: asThreadId("thread-1"), createdAt: new Date().toISOString(), method: "item/tool/requestUserInput", @@ -798,7 +886,7 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => { yield* runtime.emit({ id: asEventId("evt-user-input-resolved"), kind: "notification", - provider: "codex", + provider: ProviderDriverKind.make("codex"), threadId: asThreadId("thread-1"), createdAt: new Date().toISOString(), method: "item/tool/requestUserInput/answered", @@ -838,7 +926,7 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => { yield* runtime.emit({ id: asEventId("evt-codex-thread-token-usage-updated"), kind: "notification", - provider: "codex", + provider: ProviderDriverKind.make("codex"), threadId: asThreadId("thread-1"), turnId: asTurnId("turn-1"), createdAt: new Date().toISOString(), @@ -897,7 +985,15 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => { const scopedLifecycleRuntimeFactory = makeScopedRuntimeFactory(); const scopedLifecycleLayer = it.layer( - makeCodexAdapterLive({ makeRuntime: scopedLifecycleRuntimeFactory.factory }).pipe( + Layer.effect( + CodexAdapter, + Effect.gen(function* () { + const codexConfig = Schema.decodeSync(CodexSettings)({}); + return yield* makeCodexAdapter(codexConfig, { + makeRuntime: scopedLifecycleRuntimeFactory.factory, + }); + }), + ).pipe( Layer.provideMerge(ServerConfig.layerTest(process.cwd(), process.cwd())), Layer.provideMerge(ServerSettingsService.layerTest()), Layer.provideMerge(providerSessionDirectoryTestLayer), @@ -912,7 +1008,7 @@ scopedLifecycleLayer("CodexAdapterLive scoped lifecycle", (it) => { const adapter = yield* CodexAdapter; yield* adapter.startSession({ - provider: "codex", + provider: ProviderDriverKind.make("codex"), threadId: asThreadId("thread-stop"), runtimeMode: "full-access", }); @@ -933,7 +1029,15 @@ scopedLifecycleLayer("CodexAdapterLive scoped lifecycle", (it) => { const scopedFailureRuntimeFactory = makeScopedRuntimeFactory({ failConstruction: true }); const scopedFailureLayer = it.layer( - makeCodexAdapterLive({ makeRuntime: scopedFailureRuntimeFactory.factory }).pipe( + Layer.effect( + CodexAdapter, + Effect.gen(function* () { + const codexConfig = Schema.decodeSync(CodexSettings)({}); + return yield* makeCodexAdapter(codexConfig, { + makeRuntime: scopedFailureRuntimeFactory.factory, + }); + }), + ).pipe( Layer.provideMerge(ServerConfig.layerTest(process.cwd(), process.cwd())), Layer.provideMerge(ServerSettingsService.layerTest()), Layer.provideMerge(providerSessionDirectoryTestLayer), @@ -949,7 +1053,7 @@ scopedFailureLayer("CodexAdapterLive scoped startup failure", (it) => { const result = yield* adapter .startSession({ - provider: "codex", + provider: ProviderDriverKind.make("codex"), threadId: asThreadId("thread-fail"), runtimeMode: "full-access", }) @@ -974,10 +1078,16 @@ it.effect("flushes managed native logs when the adapter layer shuts down", () => let scopeClosed = false; try { - const layer = makeCodexAdapterLive({ - makeRuntime: runtimeFactory.factory, - nativeEventLogPath: basePath, - }).pipe( + const layer = Layer.effect( + CodexAdapter, + Effect.gen(function* () { + const codexConfig = Schema.decodeSync(CodexSettings)({}); + return yield* makeCodexAdapter(codexConfig, { + makeRuntime: runtimeFactory.factory, + nativeEventLogPath: basePath, + }); + }), + ).pipe( Layer.provideMerge(ServerConfig.layerTest(process.cwd(), process.cwd())), Layer.provideMerge(ServerSettingsService.layerTest()), Layer.provideMerge(providerSessionDirectoryTestLayer), @@ -987,7 +1097,7 @@ it.effect("flushes managed native logs when the adapter layer shuts down", () => const adapter = yield* Effect.service(CodexAdapter).pipe(Effect.provide(context)); yield* adapter.startSession({ - provider: "codex", + provider: ProviderDriverKind.make("codex"), threadId: asThreadId("thread-logger"), runtimeMode: "full-access", }); @@ -999,7 +1109,7 @@ it.effect("flushes managed native logs when the adapter layer shuts down", () => yield* runtime.emit({ id: asEventId("evt-native-log"), kind: "notification", - provider: "codex", + provider: ProviderDriverKind.make("codex"), threadId: asThreadId("thread-logger"), createdAt: new Date().toISOString(), method: "process/stderr", diff --git a/apps/server/src/provider/Layers/CodexAdapter.ts b/apps/server/src/provider/Layers/CodexAdapter.ts index 5c824dc730..5186dc2962 100644 --- a/apps/server/src/provider/Layers/CodexAdapter.ts +++ b/apps/server/src/provider/Layers/CodexAdapter.ts @@ -10,7 +10,10 @@ import { type CanonicalItemType, type CanonicalRequestType, + type CodexSettings, + ProviderDriverKind, type ProviderEvent, + ProviderInstanceId, type ProviderRuntimeEvent, type ProviderRequestKind, type ThreadTokenUsageSnapshot, @@ -21,7 +24,7 @@ import { ThreadId, ProviderSendTurnInput, } from "@t3tools/contracts"; -import { Effect, Exit, Fiber, FileSystem, Layer, Queue, Schema, Scope, Stream } from "effect"; +import { Effect, Exit, Fiber, FileSystem, Queue, Schema, Scope, Stream } from "effect"; import { ChildProcessSpawner } from "effect/unstable/process"; import * as CodexErrors from "effect-codex-app-server/errors"; import * as EffectCodexSchema from "effect-codex-app-server/schema"; @@ -39,10 +42,9 @@ import { ProviderAdapterValidationError, type ProviderAdapterError, } from "../Errors.ts"; -import { CodexAdapter, type CodexAdapterShape } from "../Services/CodexAdapter.ts"; +import { type CodexAdapterShape } from "../Services/CodexAdapter.ts"; import { resolveAttachmentPath } from "../../attachmentStore.ts"; import { ServerConfig } from "../../config.ts"; -import { ServerSettingsService } from "../../serverSettings.ts"; import { CodexResumeCursorSchema, CodexSessionRuntimeThreadIdMissingError, @@ -53,9 +55,11 @@ import { } from "./CodexSessionRuntime.ts"; import { type EventNdjsonLogger, makeEventNdjsonLogger } from "./EventNdjsonLogger.ts"; -const PROVIDER = "codex" as const; +const PROVIDER = ProviderDriverKind.make("codex"); export interface CodexAdapterLiveOptions { + readonly instanceId?: ProviderInstanceId; + readonly environment?: NodeJS.ProcessEnv; readonly makeRuntime?: ( options: CodexSessionRuntimeOptions, ) => Effect.Effect< @@ -1318,9 +1322,20 @@ function mapToRuntimeEvents( return []; } -const makeCodexAdapter = Effect.fn("makeCodexAdapter")(function* ( +/** + * Build a Codex provider adapter bound to a specific `CodexSettings` payload. + * + * The adapter is a captured closure over `codexConfig` — the `binaryPath` and + * `homePath` are read from that payload, not from `ServerSettingsService`. + * This is what makes multi-instance routing possible: each `ProviderInstance` + * in the registry owns its own closure with its own config, so two Codex + * instances with different `homePath`s cannot step on each other. + */ +export const makeCodexAdapter = Effect.fn("makeCodexAdapter")(function* ( + codexConfig: CodexSettings, options?: CodexAdapterLiveOptions, ) { + const boundInstanceId = options?.instanceId ?? ProviderInstanceId.make("codex"); const fileSystem = yield* FileSystem.FileSystem; const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; const serverConfig = yield* Effect.service(ServerConfig); @@ -1333,7 +1348,6 @@ const makeCodexAdapter = Effect.fn("makeCodexAdapter")(function* ( : undefined); const managedNativeEventLogger = options?.nativeEventLogger === undefined ? nativeEventLogger : undefined; - const serverSettingsService = yield* ServerSettingsService; const runtimeEventQueue = yield* Queue.unbounded(); const sessions = new Map(); @@ -1353,31 +1367,21 @@ const makeCodexAdapter = Effect.fn("makeCodexAdapter")(function* ( yield* Effect.suspend(() => stopSessionInternal(existing)); } - const codexSettings = yield* serverSettingsService.getSettings.pipe( - Effect.map((settings) => settings.providers.codex), - Effect.mapError( - (error) => - new ProviderAdapterProcessError({ - provider: PROVIDER, - threadId: input.threadId, - detail: error.message, - cause: error, - }), - ), - ); const runtimeInput: CodexSessionRuntimeOptions = { threadId: input.threadId, + providerInstanceId: boundInstanceId, cwd: input.cwd ?? process.cwd(), - binaryPath: codexSettings.binaryPath, - ...(codexSettings.homePath ? { homePath: codexSettings.homePath } : {}), + binaryPath: codexConfig.binaryPath, + ...(options?.environment ? { environment: options.environment } : {}), + ...(codexConfig.homePath ? { homePath: codexConfig.homePath } : {}), ...(Schema.is(CodexResumeCursorSchema)(input.resumeCursor) ? { resumeCursor: input.resumeCursor } : {}), runtimeMode: input.runtimeMode, - ...(input.modelSelection?.provider === "codex" + ...(input.modelSelection?.instanceId === boundInstanceId ? { model: input.modelSelection.model } : {}), - ...(input.modelSelection?.provider === "codex" && + ...(input.modelSelection?.instanceId === boundInstanceId && getModelSelectionBooleanOptionValue(input.modelSelection, "fastMode") === true ? { serviceTier: "fast" } : {}), @@ -1492,17 +1496,17 @@ const makeCodexAdapter = Effect.fn("makeCodexAdapter")(function* ( const session = yield* requireSession(input.threadId); const reasoningEffort = - input.modelSelection?.provider === "codex" + input.modelSelection?.instanceId === boundInstanceId ? getModelSelectionStringOptionValue(input.modelSelection, "reasoningEffort") : undefined; const fastMode = - input.modelSelection?.provider === "codex" + input.modelSelection?.instanceId === boundInstanceId ? getModelSelectionBooleanOptionValue(input.modelSelection, "fastMode") : undefined; return yield* session.runtime .sendTurn({ ...(input.input !== undefined ? { input: input.input } : {}), - ...(input.modelSelection?.provider === "codex" + ...(input.modelSelection?.instanceId === boundInstanceId ? { model: input.modelSelection.model } : {}), ...(reasoningEffort @@ -1676,8 +1680,9 @@ const makeCodexAdapter = Effect.fn("makeCodexAdapter")(function* ( } satisfies CodexAdapterShape; }); -export const CodexAdapterLive = Layer.effect(CodexAdapter, makeCodexAdapter()); - -export function makeCodexAdapterLive(options?: CodexAdapterLiveOptions) { - return Layer.effect(CodexAdapter, makeCodexAdapter(options)); -} +// NOTE: the old `CodexAdapterLive` / `makeCodexAdapterLive` singleton Layer +// exports have been removed as part of the per-instance-driver refactor. +// `makeCodexAdapter(codexConfig, options?)` is now invoked directly by +// `CodexDriver.create()` for each configured instance; downstream consumers +// (server bootstrap, integration harness, this module's tests) will be +// migrated to the registry in a follow-up pass. diff --git a/apps/server/src/provider/Layers/CodexProvider.ts b/apps/server/src/provider/Layers/CodexProvider.ts index 915609ca21..0917d842a6 100644 --- a/apps/server/src/provider/Layers/CodexProvider.ts +++ b/apps/server/src/provider/Layers/CodexProvider.ts @@ -1,15 +1,4 @@ -import { - DateTime, - Duration, - Effect, - Equal, - Layer, - Option, - Result, - Schema, - Stream, - Types, -} from "effect"; +import { DateTime, Duration, Effect, Layer, Option, Result, Schema, Types } from "effect"; import { ChildProcessSpawner } from "effect/unstable/process"; import * as CodexClient from "effect-codex-app-server/client"; import * as CodexSchema from "effect-codex-app-server/schema"; @@ -27,14 +16,11 @@ import { ServerSettingsError } from "@t3tools/contracts"; import { createModelCapabilities } from "@t3tools/shared/model"; -import { makeManagedServerProvider } from "../makeManagedServerProvider.ts"; -import { buildServerProvider } from "../providerSnapshot.ts"; -import { CodexProvider } from "../Services/CodexProvider.ts"; +import { buildServerProvider, type ServerProviderDraft } from "../providerSnapshot.ts"; import { expandHomePath } from "../../pathExpansion.ts"; -import { ServerSettingsService } from "../../serverSettings.ts"; +import { scopedSafeTeardown } from "./scopedSafeTeardown.ts"; import packageJson from "../../../package.json" with { type: "json" }; -const PROVIDER = "codex" as const; const PROVIDER_PROBE_TIMEOUT_MS = 8_000; const CODEX_PRESENTATION = { displayName: "Codex", @@ -90,6 +76,11 @@ function codexAccountAuthLabel(account: CodexSchema.V2GetAccountResponse["accoun } } +function codexAccountEmail(account: CodexSchema.V2GetAccountResponse["account"]) { + if (!account || account.type !== "chatgpt") return undefined; + return account.email; +} + function mapCodexModelCapabilities( model: CodexSchema.V2ModelListResponse__Model, ): ModelCapabilities { @@ -245,18 +236,33 @@ export function buildCodexInitializeParams(): CodexSchema.V1InitializeParams { }; } +// Wrapped with `scopedSafeTeardown("codex-probe")` rather than the usual +// `Effect.scoped` so that a defect from the `Layer.build` finalizer (e.g. +// `ChildProcess.kill` throwing because the `codex app-server` child exited +// early) cannot override a successful probe body. Without this guard the +// defect bubbles past `Effect.result` in `checkCodexProviderStatus`, dies +// `refreshOneSource`, and `providersRef` never receives the snapshot. const probeCodexAppServerProvider = Effect.fn("probeCodexAppServerProvider")(function* (input: { readonly binaryPath: string; readonly homePath?: string; readonly cwd: string; readonly customModels?: ReadonlyArray; + readonly environment?: NodeJS.ProcessEnv; }) { + // `~` is not shell-expanded when env vars are set via `child_process.spawn`, + // so `CODEX_HOME=~/.codex_work` would reach codex verbatim and trip + // "CODEX_HOME points to '~/.codex_work', but that path does not exist". + // Expand here for parity with `CodexTextGeneration`/`CodexSessionRuntime`. + const resolvedHomePath = input.homePath ? expandHomePath(input.homePath) : undefined; const clientContext = yield* Layer.build( CodexClient.layerCommand({ command: input.binaryPath, args: ["app-server"], cwd: input.cwd, - ...(input.homePath ? { env: { CODEX_HOME: expandHomePath(input.homePath) } } : {}), + env: { + ...(input.environment ?? process.env), + ...(resolvedHomePath ? { CODEX_HOME: resolvedHomePath } : {}), + }, }), ); const client = yield* Effect.service(CodexClient.CodexAppServerClient).pipe( @@ -305,7 +311,7 @@ const probeCodexAppServerProvider = Effect.fn("probeCodexAppServerProvider")(fun models: appendCustomCodexModels(models, input.customModels ?? []), skills: parseCodexSkillsListResponse(skillsResponse, input.cwd), } satisfies CodexAppServerProviderSnapshot; -}, Effect.scoped); +}, scopedSafeTeardown("codex-probe")); const emptyCodexModelsFromSettings = (codexSettings: CodexSettings): ServerProvider["models"] => codexSettings.customModels @@ -318,13 +324,12 @@ const emptyCodexModelsFromSettings = (codexSettings: CodexSettings): ServerProvi capabilities: null, })); -const makePendingCodexProvider = (codexSettings: CodexSettings): ServerProvider => { +const makePendingCodexProvider = (codexSettings: CodexSettings): ServerProviderDraft => { const checkedAt = new Date().toISOString(); const models = emptyCodexModelsFromSettings(codexSettings); if (!codexSettings.enabled) { return buildServerProvider({ - provider: PROVIDER, presentation: CODEX_PRESENTATION, enabled: false, checkedAt, @@ -341,7 +346,6 @@ const makePendingCodexProvider = (codexSettings: CodexSettings): ServerProvider } return buildServerProvider({ - provider: PROVIDER, presentation: CODEX_PRESENTATION, enabled: true, checkedAt, @@ -363,10 +367,12 @@ function accountProbeStatus(account: CodexAppServerProviderSnapshot["account"]): readonly message?: string; } { const authLabel = codexAccountAuthLabel(account.account); + const authEmail = codexAccountEmail(account.account); const auth = { status: account.account ? ("authenticated" as const) : ("unknown" as const), ...(account.account?.type ? { type: account.account?.type } : {}), ...(authLabel ? { label: authLabel } : {}), + ...(authEmail ? { email: authEmail } : {}), } satisfies ServerProvider["auth"]; if (account.account) { @@ -385,31 +391,29 @@ function accountProbeStatus(account: CodexAppServerProviderSnapshot["account"]): } export const checkCodexProviderStatus = Effect.fn("checkCodexProviderStatus")(function* ( + codexSettings: CodexSettings, probe: (input: { readonly binaryPath: string; readonly homePath?: string; readonly cwd: string; readonly customModels: ReadonlyArray; + readonly environment?: NodeJS.ProcessEnv; }) => Effect.Effect< CodexAppServerProviderSnapshot, CodexErrors.CodexAppServerError, ChildProcessSpawner.ChildProcessSpawner > = probeCodexAppServerProvider, + environment: NodeJS.ProcessEnv = process.env, ): Effect.fn.Return< - ServerProvider, + ServerProviderDraft, ServerSettingsError, - ServerSettingsService | ChildProcessSpawner.ChildProcessSpawner + ChildProcessSpawner.ChildProcessSpawner > { - const codexSettings = yield* Effect.service(ServerSettingsService).pipe( - Effect.flatMap((service) => service.getSettings), - Effect.map((settings) => settings.providers.codex), - ); const checkedAt = DateTime.formatIso(yield* DateTime.now); const emptyModels = emptyCodexModelsFromSettings(codexSettings); if (!codexSettings.enabled) { return buildServerProvider({ - provider: PROVIDER, presentation: CODEX_PRESENTATION, enabled: false, checkedAt, @@ -430,13 +434,13 @@ export const checkCodexProviderStatus = Effect.fn("checkCodexProviderStatus")(fu homePath: codexSettings.homePath, cwd: process.cwd(), customModels: codexSettings.customModels, + environment, }).pipe(Effect.timeoutOption(Duration.millis(PROVIDER_PROBE_TIMEOUT_MS)), Effect.result); if (Result.isFailure(probeResult)) { const error = probeResult.failure; const installed = !Schema.is(CodexErrors.CodexAppServerSpawnError)(error); return buildServerProvider({ - provider: PROVIDER, presentation: CODEX_PRESENTATION, enabled: codexSettings.enabled, checkedAt, @@ -456,7 +460,6 @@ export const checkCodexProviderStatus = Effect.fn("checkCodexProviderStatus")(fu if (Option.isNone(probeResult.success)) { return buildServerProvider({ - provider: PROVIDER, presentation: CODEX_PRESENTATION, enabled: codexSettings.enabled, checkedAt, @@ -476,7 +479,6 @@ export const checkCodexProviderStatus = Effect.fn("checkCodexProviderStatus")(fu const accountStatus = accountProbeStatus(snapshot.account); return buildServerProvider({ - provider: PROVIDER, presentation: CODEX_PRESENTATION, enabled: codexSettings.enabled, checkedAt, @@ -492,28 +494,11 @@ export const checkCodexProviderStatus = Effect.fn("checkCodexProviderStatus")(fu }); }); -export const CodexProviderLive = Layer.effect( - CodexProvider, - Effect.gen(function* () { - const serverSettings = yield* ServerSettingsService; - const spawner = yield* ChildProcessSpawner.ChildProcessSpawner; - const checkProvider = checkCodexProviderStatus().pipe( - Effect.provideService(ServerSettingsService, serverSettings), - Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner), - ); - - return yield* makeManagedServerProvider({ - getSettings: serverSettings.getSettings.pipe( - Effect.map((settings) => settings.providers.codex), - Effect.orDie, - ), - streamSettings: serverSettings.streamChanges.pipe( - Stream.map((settings) => settings.providers.codex), - ), - haveSettingsChanged: (previous, next) => !Equal.equals(previous, next), - initialSnapshot: makePendingCodexProvider, - checkProvider, - refreshInterval: Duration.minutes(5), - }); - }), -); +// NOTE: the singleton `CodexProviderLive` Layer has been removed as part of +// the per-instance-driver refactor. `CodexDriver.create()` builds a managed +// snapshot per instance (each with its own `CodexSettings`) and hands the +// resulting `ServerProviderShape` back as `ProviderInstance.snapshot`. +// +// The `makePendingCodexProvider` and `checkCodexProviderStatus` helpers are +// re-exported for use by `CodexDriver`. +export { makePendingCodexProvider }; diff --git a/apps/server/src/provider/Layers/CodexSessionRuntime.ts b/apps/server/src/provider/Layers/CodexSessionRuntime.ts index e45e1825ee..4f9011fba0 100644 --- a/apps/server/src/provider/Layers/CodexSessionRuntime.ts +++ b/apps/server/src/provider/Layers/CodexSessionRuntime.ts @@ -1,10 +1,10 @@ -import { randomUUID } from "node:crypto"; - import { ApprovalRequestId, - DEFAULT_MODEL_BY_PROVIDER, + DEFAULT_MODEL, EventId, + ProviderDriverKind, ProviderItemId, + type ProviderInstanceId, type ProviderApprovalDecision, type ProviderEvent, type ProviderInteractionMode, @@ -17,7 +17,7 @@ import { TurnId, } from "@t3tools/contracts"; import { normalizeModelSlug } from "@t3tools/shared/model"; -import { Deferred, Effect, Exit, Layer, Queue, Ref, Scope, Schema, Stream } from "effect"; +import { Deferred, Effect, Exit, Layer, Queue, Ref, Scope, Random, Schema, Stream } from "effect"; import * as SchemaIssue from "effect/SchemaIssue"; import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process"; import * as CodexClient from "effect-codex-app-server/client"; @@ -26,13 +26,13 @@ import * as CodexRpc from "effect-codex-app-server/rpc"; import * as EffectCodexSchema from "effect-codex-app-server/schema"; import { buildCodexInitializeParams } from "./CodexProvider.ts"; +import { expandHomePath } from "../../pathExpansion.ts"; import { CODEX_DEFAULT_MODE_DEVELOPER_INSTRUCTIONS, CODEX_PLAN_MODE_DEVELOPER_INSTRUCTIONS, } from "../CodexDeveloperInstructions.ts"; -import { expandHomePath } from "../../pathExpansion.ts"; -const PROVIDER = "codex" as const; +const PROVIDER = ProviderDriverKind.make("codex"); const ANSI_ESCAPE_CHAR = String.fromCharCode(27); const ANSI_ESCAPE_REGEX = new RegExp(`${ANSI_ESCAPE_CHAR}\\[[0-9;]*m`, "g"); @@ -76,8 +76,10 @@ type CodexThreadItem = export interface CodexSessionRuntimeOptions { readonly threadId: ThreadId; + readonly providerInstanceId?: ProviderInstanceId; readonly binaryPath: string; readonly homePath?: string; + readonly environment?: NodeJS.ProcessEnv; readonly cwd: string; readonly runtimeMode: RuntimeMode; readonly model?: string; @@ -87,7 +89,10 @@ export interface CodexSessionRuntimeOptions { export interface CodexSessionRuntimeSendTurnInput { readonly input?: string; - readonly attachments?: ReadonlyArray<{ readonly type: "image"; readonly url: string }>; + readonly attachments?: ReadonlyArray<{ + readonly type: "image"; + readonly url: string; + }>; readonly model?: string; readonly serviceTier?: EffectCodexSchema.V2TurnStartParams__ServiceTier | undefined; readonly effort?: EffectCodexSchema.V2TurnStartParams__ReasoningEffort | undefined; @@ -303,7 +308,7 @@ function buildCodexCollaborationMode(input: { if (input.interactionMode === undefined) { return undefined; } - const model = normalizeCodexModelSlug(input.model) ?? DEFAULT_MODEL_BY_PROVIDER.codex; + const model = normalizeCodexModelSlug(input.model) ?? DEFAULT_MODEL; return { mode: input.interactionMode, settings: { @@ -321,7 +326,10 @@ export function buildTurnStartParams(input: { readonly threadId: string; readonly runtimeMode: RuntimeMode; readonly prompt?: string; - readonly attachments?: ReadonlyArray<{ readonly type: "image"; readonly url: string }>; + readonly attachments?: ReadonlyArray<{ + readonly type: "image"; + readonly url: string; + }>; readonly model?: string; readonly serviceTier?: EffectCodexSchema.V2TurnStartParams__ServiceTier; readonly effort?: EffectCodexSchema.V2TurnStartParams__ReasoningEffort; @@ -680,13 +688,19 @@ export const makeCodexSessionRuntime = ( const collabReceiverTurnsRef = yield* Ref.make(new Map()); const closedRef = yield* Ref.make(false); + // `~` is not shell-expanded when env vars are set via + // `child_process.spawn`; `expandHomePath` lets a configured + // `CODEX_HOME=~/.codex_work` reach codex as an absolute path. + const resolvedHomePath = options.homePath ? expandHomePath(options.homePath) : undefined; + const env = { + ...(options.environment ?? process.env), + ...(resolvedHomePath ? { CODEX_HOME: resolvedHomePath } : {}), + }; const child = yield* spawner .spawn( ChildProcess.make(options.binaryPath, ["app-server"], { cwd: options.cwd, - ...(options.homePath - ? { env: { ...process.env, CODEX_HOME: expandHomePath(options.homePath) } } - : {}), + env, shell: process.platform === "win32", }), ) @@ -712,6 +726,7 @@ export const makeCodexSessionRuntime = ( const initialSession = { provider: PROVIDER, + ...(options.providerInstanceId ? { providerInstanceId: options.providerInstanceId } : {}), status: "connecting", runtimeMode: options.runtimeMode, cwd: options.cwd, @@ -725,13 +740,15 @@ export const makeCodexSessionRuntime = ( const offerEvent = (event: ProviderEvent) => Queue.offer(events, event).pipe(Effect.asVoid); const emitEvent = (event: Omit) => - offerEvent({ - id: EventId.make(randomUUID()), - provider: PROVIDER, - createdAt: new Date().toISOString(), - ...event, - }); - + Effect.flatMap(Random.nextUUIDv4, (id) => + offerEvent({ + id: EventId.make(id), + provider: PROVIDER, + ...(options.providerInstanceId ? { providerInstanceId: options.providerInstanceId } : {}), + createdAt: new Date().toISOString(), + ...event, + }), + ); const emitSessionEvent = (method: string, message: string) => emitEvent({ kind: "session", @@ -891,7 +908,7 @@ export const makeCodexSessionRuntime = ( yield* client.handleServerRequest("item/commandExecution/requestApproval", (payload) => Effect.gen(function* () { - const requestId = ApprovalRequestId.make(randomUUID()); + const requestId = ApprovalRequestId.make(yield* Random.nextUUIDv4); const turnId = TurnId.make(payload.turnId); const itemId = ProviderItemId.make(payload.itemId); const decision = yield* Deferred.make(); @@ -947,7 +964,7 @@ export const makeCodexSessionRuntime = ( yield* client.handleServerRequest("item/fileChange/requestApproval", (payload) => Effect.gen(function* () { - const requestId = ApprovalRequestId.make(randomUUID()); + const requestId = ApprovalRequestId.make(yield* Random.nextUUIDv4); const turnId = TurnId.make(payload.turnId); const itemId = ProviderItemId.make(payload.itemId); const decision = yield* Deferred.make(); @@ -1003,7 +1020,7 @@ export const makeCodexSessionRuntime = ( yield* client.handleServerRequest("item/tool/requestUserInput", (payload) => Effect.gen(function* () { - const requestId = ApprovalRequestId.make(randomUUID()); + const requestId = ApprovalRequestId.make(yield* Random.nextUUIDv4); const turnId = TurnId.make(payload.turnId); const itemId = ProviderItemId.make(payload.itemId); const answers = yield* Deferred.make(); diff --git a/apps/server/src/provider/Layers/CursorAdapter.test.ts b/apps/server/src/provider/Layers/CursorAdapter.test.ts index 1f619d49f1..375eec049a 100644 --- a/apps/server/src/provider/Layers/CursorAdapter.test.ts +++ b/apps/server/src/provider/Layers/CursorAdapter.test.ts @@ -5,15 +5,27 @@ import { fileURLToPath } from "node:url"; import * as NodeServices from "@effect/platform-node/NodeServices"; import { assert, it } from "@effect/vitest"; -import { Deferred, Effect, Fiber, Layer, Stream } from "effect"; +import { Context, Deferred, Effect, Fiber, Layer, Schema, Stream } from "effect"; import { createModelSelection } from "@t3tools/shared/model"; -import { ApprovalRequestId, type ProviderRuntimeEvent, ThreadId } from "@t3tools/contracts"; +import { + ApprovalRequestId, + CursorSettings, + ProviderDriverKind, + type ProviderRuntimeEvent, + ThreadId, + ProviderInstanceId, +} from "@t3tools/contracts"; import { ServerConfig } from "../../config.ts"; import { ServerSettingsService } from "../../serverSettings.ts"; -import { CursorAdapter } from "../Services/CursorAdapter.ts"; -import { makeCursorAdapterLive } from "./CursorAdapter.ts"; +import type { CursorAdapterShape } from "../Services/CursorAdapter.ts"; +import { makeCursorAdapter } from "./CursorAdapter.ts"; + +// Test-local service tag so the rest of the file can keep using `yield* CursorAdapter`. +class CursorAdapter extends Context.Service()( + "test/CursorAdapter", +) {} const __dirname = path.dirname(fileURLToPath(import.meta.url)); const mockAgentPath = path.join(__dirname, "../../../scripts/acp-mock-agent.ts"); @@ -91,8 +103,31 @@ async function waitForFileContent(filePath: string, attempts = 40) { throw new Error(`Timed out waiting for file content at ${filePath}`); } +// Tests mutate `ServerSettingsService` mid-flight (e.g. setting +// `providers.cursor.binaryPath` to a mock ACP wrapper). The adapter +// captures `cursorSettings` once at construction, so without a resolver +// the mutation is invisible — sessions would spawn the constructor's +// (empty) binary path. Wiring `resolveSettings` through +// `ServerSettingsService.getSettings` makes each session read the latest +// snapshot, matching the old "always read live" behavior that these +// tests assumed. +const makeResolveCursorSettings = Effect.gen(function* () { + const serverSettings = yield* ServerSettingsService; + return serverSettings.getSettings.pipe( + Effect.map((snapshot) => snapshot.providers.cursor), + Effect.orDie, + ); +}); + const cursorAdapterTestLayer = it.layer( - makeCursorAdapterLive().pipe( + Layer.effect( + CursorAdapter, + Effect.gen(function* () { + const cursorConfig = Schema.decodeSync(CursorSettings)({}); + const resolveSettings = yield* makeResolveCursorSettings; + return yield* makeCursorAdapter(cursorConfig, { resolveSettings }); + }), + ).pipe( Layer.provideMerge(ServerSettingsService.layerTest()), Layer.provideMerge( ServerConfig.layerTest(process.cwd(), { @@ -120,10 +155,10 @@ cursorAdapterTestLayer("CursorAdapterLive", (it) => { const session = yield* adapter.startSession({ threadId, - provider: "cursor", + provider: ProviderDriverKind.make("cursor"), cwd: process.cwd(), runtimeMode: "full-access", - modelSelection: { provider: "cursor", model: "default" }, + modelSelection: { instanceId: ProviderInstanceId.make("cursor"), model: "default" }, }); assert.equal(session.provider, "cursor"); @@ -205,10 +240,10 @@ cursorAdapterTestLayer("CursorAdapterLive", (it) => { yield* adapter.startSession({ threadId, - provider: "cursor", + provider: ProviderDriverKind.make("cursor"), cwd: process.cwd(), runtimeMode: "full-access", - modelSelection: { provider: "cursor", model: "default" }, + modelSelection: { instanceId: ProviderInstanceId.make("cursor"), model: "default" }, }); yield* adapter.stopSession(threadId); @@ -244,17 +279,17 @@ cursorAdapterTestLayer("CursorAdapterLive", (it) => { [ adapter.startSession({ threadId, - provider: "cursor", + provider: ProviderDriverKind.make("cursor"), cwd: process.cwd(), runtimeMode: "full-access", - modelSelection: { provider: "cursor", model: "default" }, + modelSelection: { instanceId: ProviderInstanceId.make("cursor"), model: "default" }, }), adapter.startSession({ threadId, - provider: "cursor", + provider: ProviderDriverKind.make("cursor"), cwd: process.cwd(), runtimeMode: "full-access", - modelSelection: { provider: "cursor", model: "default" }, + modelSelection: { instanceId: ProviderInstanceId.make("cursor"), model: "default" }, }), ], { concurrency: "unbounded" }, @@ -276,7 +311,7 @@ cursorAdapterTestLayer("CursorAdapterLive", (it) => { const result = yield* adapter .startSession({ threadId: ThreadId.make("bad-provider"), - provider: "codex", + provider: ProviderDriverKind.make("codex"), cwd: process.cwd(), runtimeMode: "full-access", }) @@ -302,10 +337,10 @@ cursorAdapterTestLayer("CursorAdapterLive", (it) => { yield* adapter.startSession({ threadId, - provider: "cursor", + provider: ProviderDriverKind.make("cursor"), cwd: process.cwd(), runtimeMode: "full-access", - modelSelection: { provider: "cursor", model: "composer-2" }, + modelSelection: { instanceId: ProviderInstanceId.make("cursor"), model: "composer-2" }, }); yield* adapter.sendTurn({ @@ -358,7 +393,7 @@ cursorAdapterTestLayer("CursorAdapterLive", (it) => { providers: { cursor: { binaryPath: wrapperPath } }, }); - const modelSelection = createModelSelection("cursor", "gpt-5.4", [ + const modelSelection = createModelSelection(ProviderInstanceId.make("cursor"), "gpt-5.4", [ { id: "reasoning", value: "xhigh" }, { id: "contextWindow", value: "1m" }, { id: "fastMode", value: true }, @@ -366,7 +401,7 @@ cursorAdapterTestLayer("CursorAdapterLive", (it) => { yield* adapter.startSession({ threadId, - provider: "cursor", + provider: ProviderDriverKind.make("cursor"), cwd: process.cwd(), runtimeMode: "full-access", modelSelection, @@ -460,10 +495,10 @@ cursorAdapterTestLayer("CursorAdapterLive", (it) => { const program = Effect.gen(function* () { yield* adapter.startSession({ threadId, - provider: "cursor", + provider: ProviderDriverKind.make("cursor"), cwd: process.cwd(), runtimeMode: "approval-required", - modelSelection: { provider: "cursor", model: "default" }, + modelSelection: { instanceId: ProviderInstanceId.make("cursor"), model: "default" }, }); const turn = yield* adapter.sendTurn({ @@ -560,7 +595,14 @@ cursorAdapterTestLayer("CursorAdapterLive", (it) => { ); }).pipe( Effect.provide( - makeCursorAdapterLive().pipe( + Layer.effect( + CursorAdapter, + Effect.gen(function* () { + const cursorConfig = Schema.decodeSync(CursorSettings)({}); + const resolveSettings = yield* makeResolveCursorSettings; + return yield* makeCursorAdapter(cursorConfig, { resolveSettings }); + }), + ).pipe( Layer.provideMerge(ServerSettingsService.layerTest()), Layer.provideMerge( ServerConfig.layerTest(process.cwd(), { @@ -615,10 +657,10 @@ cursorAdapterTestLayer("CursorAdapterLive", (it) => { yield* adapter.startSession({ threadId, - provider: "cursor", + provider: ProviderDriverKind.make("cursor"), cwd: process.cwd(), runtimeMode: "full-access", - modelSelection: { provider: "cursor", model: "default" }, + modelSelection: { instanceId: ProviderInstanceId.make("cursor"), model: "default" }, }); const turn = yield* adapter.sendTurn({ @@ -714,10 +756,10 @@ cursorAdapterTestLayer("CursorAdapterLive", (it) => { yield* adapter.startSession({ threadId, - provider: "cursor", + provider: ProviderDriverKind.make("cursor"), cwd: process.cwd(), runtimeMode: "full-access", - modelSelection: { provider: "cursor", model: "default" }, + modelSelection: { instanceId: ProviderInstanceId.make("cursor"), model: "default" }, }); const turn = yield* adapter.sendTurn({ @@ -836,10 +878,10 @@ cursorAdapterTestLayer("CursorAdapterLive", (it) => { yield* adapter.startSession({ threadId, - provider: "cursor", + provider: ProviderDriverKind.make("cursor"), cwd: process.cwd(), runtimeMode: "approval-required", - modelSelection: { provider: "cursor", model: "default" }, + modelSelection: { instanceId: ProviderInstanceId.make("cursor"), model: "default" }, }); const sendTurnFiber = yield* adapter @@ -906,10 +948,10 @@ cursorAdapterTestLayer("CursorAdapterLive", (it) => { yield* adapter.startSession({ threadId, - provider: "cursor", + provider: ProviderDriverKind.make("cursor"), cwd: process.cwd(), runtimeMode: "approval-required", - modelSelection: { provider: "cursor", model: "default" }, + modelSelection: { instanceId: ProviderInstanceId.make("cursor"), model: "default" }, }); const sendTurnFiber = yield* adapter @@ -949,10 +991,10 @@ cursorAdapterTestLayer("CursorAdapterLive", (it) => { yield* adapter.startSession({ threadId, - provider: "cursor", + provider: ProviderDriverKind.make("cursor"), cwd: process.cwd(), runtimeMode: "full-access", - modelSelection: { provider: "cursor", model: "default" }, + modelSelection: { instanceId: ProviderInstanceId.make("cursor"), model: "default" }, }); const sendTurnFiber = yield* adapter @@ -992,10 +1034,10 @@ cursorAdapterTestLayer("CursorAdapterLive", (it) => { yield* adapter.startSession({ threadId, - provider: "cursor", + provider: ProviderDriverKind.make("cursor"), cwd: process.cwd(), runtimeMode: "full-access", - modelSelection: { provider: "cursor", model: "default" }, + modelSelection: { instanceId: ProviderInstanceId.make("cursor"), model: "default" }, }); const sendTurnFiber = yield* adapter @@ -1035,10 +1077,10 @@ cursorAdapterTestLayer("CursorAdapterLive", (it) => { yield* adapter.startSession({ threadId, - provider: "cursor", + provider: ProviderDriverKind.make("cursor"), cwd: process.cwd(), runtimeMode: "full-access", - modelSelection: { provider: "cursor", model: "default" }, + modelSelection: { instanceId: ProviderInstanceId.make("cursor"), model: "default" }, }); const firstEvents = Array.from(yield* Fiber.join(firstConsumer)); @@ -1073,10 +1115,10 @@ cursorAdapterTestLayer("CursorAdapterLive", (it) => { yield* adapter.startSession({ threadId, - provider: "cursor", + provider: ProviderDriverKind.make("cursor"), cwd: process.cwd(), runtimeMode: "full-access", - modelSelection: { provider: "cursor", model: "composer-2" }, + modelSelection: { instanceId: ProviderInstanceId.make("cursor"), model: "composer-2" }, }); yield* adapter.sendTurn({ @@ -1089,7 +1131,7 @@ cursorAdapterTestLayer("CursorAdapterLive", (it) => { threadId, input: "second turn after switching model", attachments: [], - modelSelection: createModelSelection("cursor", "composer-2", [ + modelSelection: createModelSelection(ProviderInstanceId.make("cursor"), "composer-2", [ { id: "fastMode", value: true }, ]), }); @@ -1136,17 +1178,17 @@ cursorAdapterTestLayer("CursorAdapterLive", (it) => { yield* adapter.startSession({ threadId, - provider: "cursor", + provider: ProviderDriverKind.make("cursor"), cwd: process.cwd(), runtimeMode: "full-access", - modelSelection: { provider: "cursor", model: "composer-2" }, + modelSelection: { instanceId: ProviderInstanceId.make("cursor"), model: "composer-2" }, }); yield* adapter.sendTurn({ threadId, input: "first turn with fast mode", attachments: [], - modelSelection: createModelSelection("cursor", "composer-2", [ + modelSelection: createModelSelection(ProviderInstanceId.make("cursor"), "composer-2", [ { id: "fastMode", value: true }, ]), }); @@ -1155,7 +1197,7 @@ cursorAdapterTestLayer("CursorAdapterLive", (it) => { threadId, input: "second turn without fast mode", attachments: [], - modelSelection: createModelSelection("cursor", "composer-2", [ + modelSelection: createModelSelection(ProviderInstanceId.make("cursor"), "composer-2", [ { id: "fastMode", value: false }, ]), }); @@ -1174,4 +1216,91 @@ cursorAdapterTestLayer("CursorAdapterLive", (it) => { yield* adapter.stopSession(threadId); }), ); + + it.effect( + "applies fast mode on the first turn when modelSelection uses a non-default instance id", + () => { + const customInstanceId = ProviderInstanceId.make("cursor_secondary"); + // Custom-instance cases can't share the suite-level `CursorAdapter` + // layer because that one binds `instanceId: "cursor"`. We build a + // fresh layer graph — including a fresh `ServerSettingsService` — so + // mid-test `updateSettings` calls target the same service instance the + // adapter's `resolveSettings` reads from, and so the outer + // `yield* ServerSettingsService` sees the same snapshot as well. + const customAdapterLayer = Layer.effect( + CursorAdapter, + Effect.gen(function* () { + const cursorConfig = Schema.decodeSync(CursorSettings)({}); + const resolveSettings = yield* makeResolveCursorSettings; + return yield* makeCursorAdapter(cursorConfig, { + instanceId: customInstanceId, + resolveSettings, + }); + }), + ).pipe( + Layer.provideMerge(ServerSettingsService.layerTest()), + Layer.provideMerge( + ServerConfig.layerTest(process.cwd(), { + prefix: "t3code-cursor-adapter-custom-instance-", + }), + ), + Layer.provideMerge(NodeServices.layer), + ); + + return Effect.gen(function* () { + const adapter = yield* CursorAdapter; + const serverSettings = yield* ServerSettingsService; + const threadId = ThreadId.make("cursor-fast-mode-custom-instance"); + const tempDir = yield* Effect.promise(() => mkdtemp(path.join(os.tmpdir(), "cursor-acp-"))); + const requestLogPath = path.join(tempDir, "requests.ndjson"); + const argvLogPath = path.join(tempDir, "argv.txt"); + yield* Effect.promise(() => writeFile(requestLogPath, "", "utf8")); + const wrapperPath = yield* Effect.promise(() => + makeProbeWrapper(requestLogPath, argvLogPath), + ); + yield* serverSettings.updateSettings({ + providers: { cursor: { binaryPath: wrapperPath } }, + }); + + yield* adapter.startSession({ + threadId, + provider: ProviderDriverKind.make("cursor"), + cwd: process.cwd(), + runtimeMode: "full-access", + modelSelection: { + instanceId: customInstanceId, + model: "composer-2", + }, + }); + + yield* adapter.sendTurn({ + threadId, + input: "first turn with fast mode", + attachments: [], + modelSelection: { + ...createModelSelection(ProviderInstanceId.make("cursor"), "composer-2", [ + { id: "fastMode", value: true }, + ]), + instanceId: customInstanceId, + }, + }); + + const requests = yield* Effect.promise(() => readJsonLines(requestLogPath)); + const fastConfigRequests = requests.filter( + (entry) => + entry.method === "session/set_config_option" && + (entry.params as Record | undefined)?.configId === "fast", + ); + assert.isAbove( + fastConfigRequests.length, + 0, + "fast mode should apply when instance id matches the adapter binding", + ); + const lastFastConfig = fastConfigRequests[fastConfigRequests.length - 1]; + assert.equal((lastFastConfig?.params as Record)?.value, "true"); + + yield* adapter.stopSession(threadId); + }).pipe(Effect.provide(customAdapterLayer)); + }, + ); }); diff --git a/apps/server/src/provider/Layers/CursorAdapter.ts b/apps/server/src/provider/Layers/CursorAdapter.ts index 5e12bfbefe..34d1221b02 100644 --- a/apps/server/src/provider/Layers/CursorAdapter.ts +++ b/apps/server/src/provider/Layers/CursorAdapter.ts @@ -7,6 +7,7 @@ import * as nodePath from "node:path"; import { ApprovalRequestId, + type CursorSettings, type ProviderOptionSelection, EventId, type ProviderApprovalDecision, @@ -14,6 +15,8 @@ import { type ProviderRuntimeEvent, type ProviderSession, type ProviderUserInputAnswers, + ProviderDriverKind, + ProviderInstanceId, RuntimeRequestId, type RuntimeMode, type ThreadId, @@ -26,7 +29,6 @@ import { Exit, Fiber, FileSystem, - Layer, Option, PubSub, Random, @@ -40,7 +42,6 @@ import type * as EffectAcpSchema from "effect-acp/schema"; import { resolveAttachmentPath } from "../../attachmentStore.ts"; import { ServerConfig } from "../../config.ts"; -import { ServerSettingsService } from "../../serverSettings.ts"; import { ProviderAdapterProcessError, ProviderAdapterRequestError, @@ -72,19 +73,37 @@ import { extractPlanMarkdown, extractTodosAsPlan, } from "../acp/CursorAcpExtension.ts"; -import { CursorAdapter, type CursorAdapterShape } from "../Services/CursorAdapter.ts"; +import { type CursorAdapterShape } from "../Services/CursorAdapter.ts"; import { resolveCursorAcpBaseModelId } from "./CursorProvider.ts"; import { type EventNdjsonLogger, makeEventNdjsonLogger } from "./EventNdjsonLogger.ts"; -const PROVIDER = "cursor" as const; +const PROVIDER = ProviderDriverKind.make("cursor"); const CURSOR_RESUME_VERSION = 1 as const; const ACP_PLAN_MODE_ALIASES = ["plan", "architect"]; const ACP_IMPLEMENT_MODE_ALIASES = ["code", "agent", "default", "chat", "implement"]; const ACP_APPROVAL_MODE_ALIASES = ["ask"]; export interface CursorAdapterLiveOptions { + readonly environment?: NodeJS.ProcessEnv; readonly nativeEventLogPath?: string; readonly nativeEventLogger?: EventNdjsonLogger; + /** + * Selections are honored when `modelSelection.instanceId` matches this value. + * Defaults to the legacy built-in instance id (`cursor`). + */ + readonly instanceId?: typeof ProviderInstanceId.Type; + /** + * Optional per-session settings resolver. When provided the adapter yields + * this effect at the start of every session and uses the result instead of + * the `cursorSettings` captured at construction. + * + * Production instances bind settings to the instance scope (the hydration + * layer rebuilds the adapter on config change) and leave this undefined. + * Test suites that mutate `ServerSettingsService` mid-flight — e.g. to + * swap `binaryPath` to a mock ACP wrapper — pass a resolver that reads + * the latest snapshot so the closure isn't stale. + */ + readonly resolveSettings?: Effect.Effect; } interface PendingApproval { @@ -280,12 +299,15 @@ function selectAutoApprovedPermissionOption( return undefined; } -function makeCursorAdapter(options?: CursorAdapterLiveOptions) { +export function makeCursorAdapter( + cursorSettings: CursorSettings, + options?: CursorAdapterLiveOptions, +) { return Effect.gen(function* () { + const boundInstanceId = options?.instanceId ?? ProviderInstanceId.make("cursor"); const fileSystem = yield* FileSystem.FileSystem; const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; const serverConfig = yield* Effect.service(ServerConfig); - const serverSettingsService = yield* ServerSettingsService; const nativeEventLogger = options?.nativeEventLogger ?? (options?.nativeEventLogPath !== undefined @@ -440,25 +462,12 @@ function makeCursorAdapter(options?: CursorAdapterLiveOptions) { const cwd = nodePath.resolve(input.cwd.trim()); const cursorModelSelection = - input.modelSelection?.provider === "cursor" ? input.modelSelection : undefined; + input.modelSelection?.instanceId === boundInstanceId ? input.modelSelection : undefined; const existing = sessions.get(input.threadId); if (existing && !existing.stopped) { yield* stopSessionInternal(existing); } - const cursorSettings = yield* serverSettingsService.getSettings.pipe( - Effect.map((settings) => settings.providers.cursor), - Effect.mapError( - (error) => - new ProviderAdapterProcessError({ - provider: PROVIDER, - threadId: input.threadId, - detail: error.message, - cause: error, - }), - ), - ); - const pendingApprovals = new Map(); const pendingUserInputs = new Map(); const sessionScope = yield* Scope.make("sequential"); @@ -475,8 +484,21 @@ function makeCursorAdapter(options?: CursorAdapterLiveOptions) { threadId: input.threadId, }); + // Resolve the CursorSettings used to spawn the ACP child. Production + // leaves `options.resolveSettings` undefined so we use the value + // captured at adapter construction — per-instance isolation is + // enforced by the hydration layer rebuilding this adapter whenever + // its config changes. Tests set `resolveSettings` to pull the latest + // snapshot from `ServerSettingsService` so that mid-suite + // `updateSettings({ providers: { cursor: { binaryPath } } })` calls + // actually take effect when the next session spawns. + const effectiveCursorSettings = options?.resolveSettings + ? yield* options.resolveSettings + : cursorSettings; + const acp = yield* makeCursorAcpRuntime({ - cursorSettings, + cursorSettings: effectiveCursorSettings, + ...(options?.environment ? { environment: options.environment } : {}), childProcessSpawner, cwd, ...(resumeSessionId ? { resumeSessionId } : {}), @@ -666,6 +688,7 @@ function makeCursorAdapter(options?: CursorAdapterLiveOptions) { const now = yield* nowIso; const session: ProviderSession = { provider: PROVIDER, + providerInstanceId: boundInstanceId, status: "ready", runtimeMode: input.runtimeMode, cwd, @@ -815,7 +838,7 @@ function makeCursorAdapter(options?: CursorAdapterLiveOptions) { const ctx = yield* requireSession(input.threadId); const turnId = TurnId.make(crypto.randomUUID()); const turnModelSelection = - input.modelSelection?.provider === "cursor" ? input.modelSelection : undefined; + input.modelSelection?.instanceId === boundInstanceId ? input.modelSelection : undefined; const model = turnModelSelection?.model ?? ctx.session.model; const resolvedModel = resolveCursorAcpBaseModelId(model); yield* applyRequestedSessionConfiguration({ @@ -1049,9 +1072,3 @@ function makeCursorAdapter(options?: CursorAdapterLiveOptions) { } satisfies CursorAdapterShape; }); } - -export const CursorAdapterLive = Layer.effect(CursorAdapter, makeCursorAdapter()); - -export function makeCursorAdapterLive(opts?: CursorAdapterLiveOptions) { - return Layer.effect(CursorAdapter, makeCursorAdapter(opts)); -} diff --git a/apps/server/src/provider/Layers/CursorProvider.test.ts b/apps/server/src/provider/Layers/CursorProvider.test.ts index c0ac5d20b0..33ef20acf2 100644 --- a/apps/server/src/provider/Layers/CursorProvider.test.ts +++ b/apps/server/src/provider/Layers/CursorProvider.test.ts @@ -1,10 +1,7 @@ -import * as path from "node:path"; -import * as os from "node:os"; -import { chmod, mkdtemp, readFile, writeFile } from "node:fs/promises"; -import { fileURLToPath } from "node:url"; +import * as NodeOS from "node:os"; import * as NodeServices from "@effect/platform-node/NodeServices"; -import { Effect } from "effect"; +import { Effect, FileSystem, Path } from "effect"; import { describe, expect, it } from "vitest"; import type * as EffectAcpSchema from "effect-acp/schema"; import type { CursorSettings, ServerProviderModel } from "@t3tools/contracts"; @@ -14,6 +11,7 @@ import { buildCursorProviderSnapshot, buildCursorCapabilitiesFromConfigOptions, buildCursorDiscoveredModelsFromConfigOptions, + checkCursorProviderStatus, discoverCursorModelCapabilitiesViaAcp, discoverCursorModelsViaAcp, getCursorFallbackModels, @@ -25,8 +23,14 @@ import { resolveCursorAcpConfigUpdates, } from "./CursorProvider.ts"; -const __dirname = path.dirname(fileURLToPath(import.meta.url)); -const mockAgentPath = path.join(__dirname, "../../../scripts/acp-mock-agent.ts"); +const runNode = ( + effect: Effect.Effect, +): Promise => Effect.runPromise(effect.pipe(Effect.provide(NodeServices.layer))); + +const resolveMockAgentPath = Effect.fn("resolveMockAgentPath")(function* () { + const path = yield* Path.Path; + return yield* path.fromFileUrl(new URL("../../../scripts/acp-mock-agent.ts", import.meta.url)); +}); function selectDescriptor( id: string, @@ -53,8 +57,16 @@ function booleanDescriptor(id: string, label: string, currentValue?: boolean) { }; } -async function makeMockAgentWrapper(extraEnv?: Record) { - const dir = await mkdtemp(path.join(os.tmpdir(), "cursor-provider-mock-")); +const makeMockAgentWrapper = Effect.fn("makeMockAgentWrapper")(function* ( + extraEnv?: Record, +) { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const mockAgentPath = yield* resolveMockAgentPath(); + const dir = yield* fileSystem.makeTempDirectory({ + directory: NodeOS.tmpdir(), + prefix: "cursor-provider-mock-", + }); const wrapperPath = path.join(dir, "fake-agent.sh"); const envExports = Object.entries(extraEnv ?? {}) .map(([key, value]) => `export ${key}=${JSON.stringify(value)}`) @@ -63,23 +75,80 @@ async function makeMockAgentWrapper(extraEnv?: Record) { ${envExports} exec ${JSON.stringify("bun")} ${JSON.stringify(mockAgentPath)} "$@" `; - await writeFile(wrapperPath, script, "utf8"); - await chmod(wrapperPath, 0o755); + yield* fileSystem.writeFileString(wrapperPath, script); + yield* fileSystem.chmod(wrapperPath, 0o755); return wrapperPath; -} +}); -async function waitForFileContent(filePath: string, attempts = 40): Promise { +const makeMockAgentWithAboutWrapper = Effect.fn("makeMockAgentWithAboutWrapper")(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const mockAgentPath = yield* resolveMockAgentPath(); + const dir = yield* fileSystem.makeTempDirectory({ + directory: NodeOS.tmpdir(), + prefix: "cursor-provider-about-mock-", + }); + const wrapperPath = path.join(dir, "fake-agent.sh"); + const script = `#!/bin/sh +if [ "$1" = "about" ]; then + printf 'CLI Version 2026.04.09-f2b0fcd\\n' + printf 'User Email cursor@example.com\\n' + exit 0 +fi +exec ${JSON.stringify("bun")} ${JSON.stringify(mockAgentPath)} "$@" +`; + yield* fileSystem.writeFileString(wrapperPath, script); + yield* fileSystem.chmod(wrapperPath, 0o755); + return wrapperPath; +}); + +const waitForFileContent = Effect.fn("waitForFileContent")(function* ( + filePath: string, + attempts = 40, +) { + const fileSystem = yield* FileSystem.FileSystem; for (let attempt = 0; attempt < attempts; attempt += 1) { - try { - const content = await readFile(filePath, "utf8"); + const content = yield* fileSystem + .readFileString(filePath) + .pipe(Effect.catch(() => Effect.void)); + if (content !== undefined) { if (content.trim().length > 0) { return content; } - } catch {} - await new Promise((resolve) => setTimeout(resolve, 50)); + } + yield* Effect.sleep("50 millis"); } - throw new Error(`Timed out waiting for file content at ${filePath}`); -} + return yield* Effect.fail(new Error(`Timed out waiting for file content at ${filePath}`)); +}); + +const makeProviderStatusEnvFixture = Effect.fn("makeProviderStatusEnvFixture")(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const tempDir = yield* fileSystem.makeTempDirectory({ + directory: NodeOS.tmpdir(), + prefix: "cursor-provider-status-env-", + }); + return { + requestLogPath: path.join(tempDir, "requests.ndjson"), + wrapperPath: yield* makeMockAgentWithAboutWrapper(), + }; +}); + +const makeExitLogFixture = Effect.fn("makeExitLogFixture")(function* (prefix: string) { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const tempDir = yield* fileSystem.makeTempDirectory({ + directory: NodeOS.tmpdir(), + prefix, + }); + const exitLogPath = path.join(tempDir, "exit.log"); + return { + exitLogPath, + wrapperPath: yield* makeMockAgentWrapper({ + T3_ACP_EXIT_LOG_PATH: exitLogPath, + }), + }; +}); const parameterizedGpt54ConfigOptions = [ { @@ -428,9 +497,38 @@ describe("buildCursorDiscoveredModelsFromConfigOptions", () => { }); }); +describe("checkCursorProviderStatus", () => { + it("passes the injected environment to ACP model discovery", async () => { + const { requestLogPath, wrapperPath } = await runNode(makeProviderStatusEnvFixture()); + + const provider = await Effect.runPromise( + checkCursorProviderStatus( + { + enabled: true, + binaryPath: wrapperPath, + apiEndpoint: "", + customModels: [], + }, + { + ...process.env, + T3_ACP_REQUEST_LOG_PATH: requestLogPath, + }, + ).pipe(Effect.provide(NodeServices.layer)), + ); + + expect(provider.models.map((model) => model.slug)).toEqual([ + "default", + "composer-2", + "gpt-5.4", + "claude-opus-4-6", + ]); + await expect(runNode(waitForFileContent(requestLogPath))).resolves.toContain("initialize"); + }); +}); + describe("discoverCursorModelsViaAcp", () => { it("keeps the ACP probe runtime alive long enough to discover models", async () => { - const wrapperPath = await makeMockAgentWrapper(); + const wrapperPath = await runNode(makeMockAgentWrapper()); const models = await Effect.runPromise( discoverCursorModelsViaAcp({ @@ -450,11 +548,9 @@ describe("discoverCursorModelsViaAcp", () => { }); it("closes the ACP probe runtime after discovery completes", async () => { - const tempDir = await mkdtemp(path.join(os.tmpdir(), "cursor-provider-exit-log-")); - const exitLogPath = path.join(tempDir, "exit.log"); - const wrapperPath = await makeMockAgentWrapper({ - T3_ACP_EXIT_LOG_PATH: exitLogPath, - }); + const { exitLogPath, wrapperPath } = await runNode( + makeExitLogFixture("cursor-provider-exit-log-"), + ); await Effect.runPromise( discoverCursorModelsViaAcp({ @@ -465,18 +561,16 @@ describe("discoverCursorModelsViaAcp", () => { }).pipe(Effect.provide(NodeServices.layer)), ); - const exitLog = await waitForFileContent(exitLogPath); + const exitLog = await runNode(waitForFileContent(exitLogPath)); expect(exitLog).toContain("SIGTERM"); }); }); describe("discoverCursorModelCapabilitiesViaAcp", () => { it("closes all ACP probe runtimes after capability enrichment completes", async () => { - const tempDir = await mkdtemp(path.join(os.tmpdir(), "cursor-capabilities-exit-log-")); - const exitLogPath = path.join(tempDir, "exit.log"); - const wrapperPath = await makeMockAgentWrapper({ - T3_ACP_EXIT_LOG_PATH: exitLogPath, - }); + const { exitLogPath, wrapperPath } = await runNode( + makeExitLogFixture("cursor-capabilities-exit-log-"), + ); const existingModels: ReadonlyArray = [ { slug: "default", name: "Auto", isCustom: false, capabilities: emptyCapabilities }, { slug: "composer-2", name: "Composer 2", isCustom: false, capabilities: emptyCapabilities }, @@ -508,7 +602,7 @@ describe("discoverCursorModelCapabilitiesViaAcp", () => { "claude-opus-4-6", ]); - const exitLog = await waitForFileContent(exitLogPath); + const exitLog = await runNode(waitForFileContent(exitLogPath)); expect(exitLog.match(/SIGTERM/g)?.length ?? 0).toBe(4); }); }); @@ -530,6 +624,7 @@ describe("parseCursorAboutOutput", () => { status: "ready", auth: { status: "authenticated", + email: "jmarminge@gmail.com", type: "Team", label: "Cursor Team Subscription", }, diff --git a/apps/server/src/provider/Layers/CursorProvider.ts b/apps/server/src/provider/Layers/CursorProvider.ts index 4225023f7d..ad52f63fbb 100644 --- a/apps/server/src/provider/Layers/CursorProvider.ts +++ b/apps/server/src/provider/Layers/CursorProvider.ts @@ -1,6 +1,4 @@ -import * as nodeFs from "node:fs"; import * as nodeOs from "node:os"; -import * as nodePath from "node:path"; import type { CursorSettings, @@ -10,10 +8,10 @@ import type { ServerProviderAuth, ServerProviderModel, ServerProviderState, - ServerSettingsError, } from "@t3tools/contracts"; +import { ProviderDriverKind } from "@t3tools/contracts"; import type * as EffectAcpSchema from "effect-acp/schema"; -import { Cause, Effect, Equal, Exit, Layer, Option, Result, Stream } from "effect"; +import { Cause, Effect, Exit, FileSystem, Layer, Option, Path, Result } from "effect"; import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process"; import { createModelCapabilities, @@ -29,13 +27,11 @@ import { isCommandMissingCause, providerModelsFromSettings, type CommandResult, + type ServerProviderDraft, } from "../providerSnapshot.ts"; -import { makeManagedServerProvider } from "../makeManagedServerProvider.ts"; -import { CursorProvider } from "../Services/CursorProvider.ts"; import { AcpSessionRuntime } from "../acp/AcpSessionRuntime.ts"; -import { ServerSettingsService } from "../../serverSettings.ts"; -const PROVIDER = "cursor" as const; +const PROVIDER = ProviderDriverKind.make("cursor"); const CURSOR_PRESENTATION = { displayName: "Cursor", badgeLabel: "Early Access", @@ -48,7 +44,6 @@ const EMPTY_CAPABILITIES: ModelCapabilities = createModelCapabilities({ const CURSOR_ACP_MODEL_DISCOVERY_TIMEOUT_MS = 15_000; const CURSOR_ACP_MODEL_CAPABILITY_TIMEOUT = "4 seconds"; const CURSOR_ACP_MODEL_DISCOVERY_CONCURRENCY = 4; -const CURSOR_REFRESH_INTERVAL = "1 hour"; const CURSOR_PARAMETERIZED_MODEL_PICKER_MIN_VERSION_DATE = 2026_04_08; export const CURSOR_PARAMETERIZED_MODEL_PICKER_CAPABILITIES = { _meta: { @@ -56,13 +51,14 @@ export const CURSOR_PARAMETERIZED_MODEL_PICKER_CAPABILITIES = { }, } satisfies NonNullable; -function buildInitialCursorProviderSnapshot(cursorSettings: CursorSettings): ServerProvider { +export function buildInitialCursorProviderSnapshot( + cursorSettings: CursorSettings, +): ServerProviderDraft { const checkedAt = new Date().toISOString(); const models = getCursorFallbackModels(cursorSettings); if (!cursorSettings.enabled) { return buildServerProvider({ - provider: PROVIDER, presentation: CURSOR_PRESENTATION, enabled: false, checkedAt, @@ -78,7 +74,6 @@ function buildInitialCursorProviderSnapshot(cursorSettings: CursorSettings): Ser } return buildServerProvider({ - provider: PROVIDER, presentation: CURSOR_PRESENTATION, enabled: true, checkedAt, @@ -112,7 +107,12 @@ function flattenSessionConfigSelectOptions( } return configOption.options.flatMap((entry) => "value" in entry - ? [{ value: entry.value.trim(), name: entry.name.trim() } satisfies CursorSessionSelectOption] + ? [ + { + value: entry.value.trim(), + name: entry.name.trim(), + } satisfies CursorSessionSelectOption, + ] : entry.options.map( (option) => ({ @@ -392,7 +392,10 @@ export function buildCursorDiscoveredModelsFromConfigOptions( ); } -const makeCursorAcpProbeRuntime = (cursorSettings: CursorSettings) => +const makeCursorAcpProbeRuntime = ( + cursorSettings: CursorSettings, + environment: NodeJS.ProcessEnv = process.env, +) => Effect.gen(function* () { const spawner = yield* ChildProcessSpawner.ChildProcessSpawner; const acpContext = yield* Layer.build( @@ -404,6 +407,7 @@ const makeCursorAcpProbeRuntime = (cursorSettings: CursorSettings) => "acp", ], cwd: process.cwd(), + env: environment, }, cwd: process.cwd(), clientInfo: { name: "t3-code-provider-probe", version: "0.0.0" }, @@ -417,7 +421,12 @@ const makeCursorAcpProbeRuntime = (cursorSettings: CursorSettings) => const withCursorAcpProbeRuntime = ( cursorSettings: CursorSettings, useRuntime: (acp: AcpSessionRuntime["Service"]) => Effect.Effect, -) => makeCursorAcpProbeRuntime(cursorSettings).pipe(Effect.flatMap(useRuntime), Effect.scoped); + environment: NodeJS.ProcessEnv = process.env, +) => + makeCursorAcpProbeRuntime(cursorSettings, environment).pipe( + Effect.flatMap(useRuntime), + Effect.scoped, + ); function normalizeCursorConfigOptionToken(value: string | null | undefined): string { return ( @@ -460,12 +469,18 @@ export function resolveCursorAcpBaseModelId(model: string | null | undefined): s export function resolveCursorAcpConfigUpdates( configOptions: ReadonlyArray | null | undefined, selections: ReadonlyArray | null | undefined, -): ReadonlyArray<{ readonly configId: string; readonly value: string | boolean }> { +): ReadonlyArray<{ + readonly configId: string; + readonly value: string | boolean; +}> { if (!configOptions || configOptions.length === 0) { return []; } - const updates: Array<{ readonly configId: string; readonly value: string | boolean }> = []; + const updates: Array<{ + readonly configId: string; + readonly value: string | boolean; + }> = []; const reasoningOption = findCursorEffortConfigOption(configOptions); const requestedReasoning = normalizeCursorReasoningValue( @@ -525,43 +540,129 @@ export function resolveCursorAcpConfigUpdates( return updates; } -export const discoverCursorModelsViaAcp = (cursorSettings: CursorSettings) => - withCursorAcpProbeRuntime(cursorSettings, (acp) => - Effect.map(acp.start(), (started) => - buildCursorDiscoveredModelsFromConfigOptions(started.sessionSetupResult.configOptions ?? []), - ), +export const discoverCursorModelsViaAcp = ( + cursorSettings: CursorSettings, + environment: NodeJS.ProcessEnv = process.env, +) => + withCursorAcpProbeRuntime( + cursorSettings, + (acp) => + Effect.map(acp.start(), (started) => + buildCursorDiscoveredModelsFromConfigOptions( + started.sessionSetupResult.configOptions ?? [], + ), + ), + environment, ); export const discoverCursorModelCapabilitiesViaAcp = ( cursorSettings: CursorSettings, existingModels: ReadonlyArray, + environment: NodeJS.ProcessEnv = process.env, ) => - withCursorAcpProbeRuntime(cursorSettings, (acp) => - Effect.gen(function* () { - const started = yield* acp.start(); - const initialConfigOptions = started.sessionSetupResult.configOptions ?? []; - const modelOption = findCursorModelConfigOption(initialConfigOptions); - const modelChoices = flattenSessionConfigSelectOptions(modelOption); - if (!modelOption || modelChoices.length === 0) { - return []; - } + withCursorAcpProbeRuntime( + cursorSettings, + (acp) => + Effect.gen(function* () { + const started = yield* acp.start(); + const initialConfigOptions = started.sessionSetupResult.configOptions ?? []; + const modelOption = findCursorModelConfigOption(initialConfigOptions); + const modelChoices = flattenSessionConfigSelectOptions(modelOption); + if (!modelOption || modelChoices.length === 0) { + return []; + } - const currentModelValue = - modelOption.type === "select" ? modelOption.currentValue?.trim() || undefined : undefined; - const capabilitiesBySlug = new Map(); - if (currentModelValue) { - capabilitiesBySlug.set( - currentModelValue, - buildCursorCapabilitiesFromConfigOptions(initialConfigOptions), + const currentModelValue = + modelOption.type === "select" ? modelOption.currentValue?.trim() || undefined : undefined; + const capabilitiesBySlug = new Map(); + if (currentModelValue) { + capabilitiesBySlug.set( + currentModelValue, + buildCursorCapabilitiesFromConfigOptions(initialConfigOptions), + ); + } + + const targetModelSlugs = new Set( + existingModels + .filter((model) => !model.isCustom && !hasCursorModelCapabilities(model)) + .map((model) => model.slug), ); - } + if (targetModelSlugs.size === 0) { + return buildCursorDiscoveredModels( + modelChoices.map((modelChoice) => ({ + slug: modelChoice.value.trim(), + name: modelChoice.name.trim(), + capabilities: capabilitiesBySlug.get(modelChoice.value.trim()) ?? EMPTY_CAPABILITIES, + })), + ); + } + + const probedCapabilities = yield* Effect.forEach( + modelChoices, + (modelChoice) => { + const modelSlug = modelChoice.value.trim(); + if ( + !modelSlug || + !targetModelSlugs.has(modelSlug) || + capabilitiesBySlug.has(modelSlug) + ) { + return Effect.void.pipe( + Effect.as(undefined), + ); + } + + return withCursorAcpProbeRuntime( + cursorSettings, + (probeAcp) => + Effect.gen(function* () { + const probeStarted = yield* probeAcp.start(); + const probeConfigOptions = probeStarted.sessionSetupResult.configOptions ?? []; + const probeModelOption = findCursorModelConfigOption(probeConfigOptions); + const probeCurrentModelValue = + probeModelOption?.type === "select" + ? probeModelOption.currentValue?.trim() || undefined + : undefined; + yield* Effect.annotateCurrentSpan({ + "cursor.acp.model.value": modelSlug, + "cursor.acp.model.currentValue": probeCurrentModelValue, + "cursor.acp.config_option_id": probeModelOption?.id ?? modelOption.id, + }); + const nextConfigOptions = + probeCurrentModelValue === modelSlug + ? probeConfigOptions + : yield* probeAcp + .setConfigOption(probeModelOption?.id ?? modelOption.id, modelSlug) + .pipe( + Effect.map((response) => response.configOptions ?? probeConfigOptions), + ); + return [ + modelSlug, + buildCursorCapabilitiesFromConfigOptions(nextConfigOptions), + ] as const; + }), + environment, + ).pipe( + Effect.timeout(CURSOR_ACP_MODEL_CAPABILITY_TIMEOUT), + Effect.retry({ times: 3 }), + Effect.withSpan("cursor-acp-model-capability-probe"), + Effect.catchCause((cause) => + Effect.logWarning("Cursor ACP capability probe failed", { + modelSlug, + cause: Cause.pretty(cause), + }), + ), + ); + }, + { concurrency: CURSOR_ACP_MODEL_DISCOVERY_CONCURRENCY }, + ); + + for (const entry of probedCapabilities) { + if (!entry) { + continue; + } + capabilitiesBySlug.set(entry[0], entry[1]); + } - const targetModelSlugs = new Set( - existingModels - .filter((model) => !model.isCustom && !hasCursorModelCapabilities(model)) - .map((model) => model.slug), - ); - if (targetModelSlugs.size === 0) { return buildCursorDiscoveredModels( modelChoices.map((modelChoice) => ({ slug: modelChoice.value.trim(), @@ -569,73 +670,8 @@ export const discoverCursorModelCapabilitiesViaAcp = ( capabilities: capabilitiesBySlug.get(modelChoice.value.trim()) ?? EMPTY_CAPABILITIES, })), ); - } - - const probedCapabilities = yield* Effect.forEach( - modelChoices, - (modelChoice) => { - const modelSlug = modelChoice.value.trim(); - if (!modelSlug || !targetModelSlugs.has(modelSlug) || capabilitiesBySlug.has(modelSlug)) { - return Effect.void.pipe( - Effect.as(undefined), - ); - } - - return withCursorAcpProbeRuntime(cursorSettings, (probeAcp) => - Effect.gen(function* () { - const probeStarted = yield* probeAcp.start(); - const probeConfigOptions = probeStarted.sessionSetupResult.configOptions ?? []; - const probeModelOption = findCursorModelConfigOption(probeConfigOptions); - const probeCurrentModelValue = - probeModelOption?.type === "select" - ? probeModelOption.currentValue?.trim() || undefined - : undefined; - yield* Effect.annotateCurrentSpan({ - "cursor.acp.model.value": modelSlug, - "cursor.acp.model.currentValue": probeCurrentModelValue, - "cursor.acp.config_option_id": probeModelOption?.id ?? modelOption.id, - }); - const nextConfigOptions = - probeCurrentModelValue === modelSlug - ? probeConfigOptions - : yield* probeAcp - .setConfigOption(probeModelOption?.id ?? modelOption.id, modelSlug) - .pipe(Effect.map((response) => response.configOptions ?? probeConfigOptions)); - return [ - modelSlug, - buildCursorCapabilitiesFromConfigOptions(nextConfigOptions), - ] as const; - }), - ).pipe( - Effect.timeout(CURSOR_ACP_MODEL_CAPABILITY_TIMEOUT), - Effect.retry({ times: 3 }), - Effect.withSpan("cursor-acp-model-capability-probe"), - Effect.catchCause((cause) => - Effect.logWarning("Cursor ACP capability probe failed", { - modelSlug, - cause: Cause.pretty(cause), - }), - ), - ); - }, - { concurrency: CURSOR_ACP_MODEL_DISCOVERY_CONCURRENCY }, - ); - - for (const entry of probedCapabilities) { - if (!entry) { - continue; - } - capabilitiesBySlug.set(entry[0], entry[1]); - } - - return buildCursorDiscoveredModels( - modelChoices.map((modelChoice) => ({ - slug: modelChoice.value.trim(), - name: modelChoice.name.trim(), - capabilities: capabilitiesBySlug.get(modelChoice.value.trim()) ?? EMPTY_CAPABILITIES, - })), - ); - }).pipe(Effect.withSpan("cursor-acp-model-capability-discovery", {})), + }).pipe(Effect.withSpan("cursor-acp-model-capability-discovery", {})), + environment, ); export function getCursorFallbackModels( @@ -683,10 +719,9 @@ export function buildCursorProviderSnapshot(input: { readonly parsed: CursorAboutResult; readonly discoveredModels?: ReadonlyArray; readonly discoveryWarning?: string; -}): ServerProvider { +}): ServerProviderDraft { const message = joinProviderMessages(input.parsed.message, input.discoveryWarning); return buildServerProvider({ - provider: PROVIDER, presentation: CURSOR_PRESENTATION, enabled: input.cursorSettings.enabled, checkedAt: input.checkedAt, @@ -811,14 +846,13 @@ function isCursorAboutJsonFormatUnsupported(result: CommandResult): boolean { ); } -function readCursorCliConfigChannel(): string | undefined { - try { - const configPath = nodePath.join(nodeOs.homedir(), ".cursor", "cli-config.json"); - return parseCursorCliConfigChannel(nodeFs.readFileSync(configPath, "utf8")); - } catch { - return undefined; - } -} +const readCursorCliConfigChannel = Effect.fn("readCursorCliConfigChannel")(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const configPath = path.join(nodeOs.homedir(), ".cursor", "cli-config.json"); + const raw = yield* fileSystem.readFileString(configPath).pipe(Effect.orElseSucceed(() => "")); + return parseCursorCliConfigChannel(raw); +}); export function getCursorParameterizedModelPickerUnsupportedMessage(input: { readonly version: string | null | undefined; @@ -934,6 +968,7 @@ export function parseCursorAboutOutput(result: CommandResult): CursorAboutResult status: "ready", auth: { status: "authenticated", + email: userEmail, ...authMetadata, }, }; @@ -989,17 +1024,22 @@ export function parseCursorAboutOutput(result: CommandResult): CursorAboutResult } // Any non-empty email value means authenticated. - return { version, status: "ready", auth: { status: "authenticated" } }; + return { + version, + status: "ready", + auth: { status: "authenticated", email: userEmail }, + }; } -const runCursorCommand = (args: ReadonlyArray) => +const runCursorCommand = ( + cursorSettings: CursorSettings, + args: ReadonlyArray, + environment: NodeJS.ProcessEnv = process.env, +) => Effect.gen(function* () { const spawner = yield* ChildProcessSpawner.ChildProcessSpawner; - const cursorSettings = yield* Effect.service(ServerSettingsService).pipe( - Effect.flatMap((service) => service.getSettings), - Effect.map((settings) => settings.providers.cursor), - ); const command = ChildProcess.make(cursorSettings.binaryPath, [...args], { + env: environment, shell: process.platform === "win32", }); @@ -1016,203 +1056,202 @@ const runCursorCommand = (args: ReadonlyArray) => return { stdout, stderr, code: exitCode } satisfies CommandResult; }).pipe(Effect.scoped); -const runCursorAboutCommand = Effect.gen(function* () { - const jsonResult = yield* runCursorCommand(["about", "--format", "json"]); - if (!isCursorAboutJsonFormatUnsupported(jsonResult)) { - return jsonResult; +const runCursorAboutCommand = ( + cursorSettings: CursorSettings, + environment: NodeJS.ProcessEnv = process.env, +) => + Effect.gen(function* () { + const jsonResult = yield* runCursorCommand( + cursorSettings, + ["about", "--format", "json"], + environment, + ); + if (!isCursorAboutJsonFormatUnsupported(jsonResult)) { + return jsonResult; + } + return yield* runCursorCommand(cursorSettings, ["about"], environment); + }); + +export const checkCursorProviderStatus = Effect.fn("checkCursorProviderStatus")(function* ( + cursorSettings: CursorSettings, + environment: NodeJS.ProcessEnv = process.env, +): Effect.fn.Return< + ServerProviderDraft, + never, + ChildProcessSpawner.ChildProcessSpawner | FileSystem.FileSystem | Path.Path +> { + const checkedAt = new Date().toISOString(); + const fallbackModels = getCursorFallbackModels(cursorSettings); + + if (!cursorSettings.enabled) { + return buildServerProvider({ + presentation: CURSOR_PRESENTATION, + enabled: false, + checkedAt, + models: fallbackModels, + probe: { + installed: false, + version: null, + status: "warning", + auth: { status: "unknown" }, + message: "Cursor is disabled in T3 Code settings.", + }, + }); } - return yield* runCursorCommand(["about"]); + + // Single `agent about` probe: returns version + auth status in one call. + const aboutProbe = yield* runCursorAboutCommand(cursorSettings, environment).pipe( + Effect.timeoutOption(ABOUT_TIMEOUT_MS), + Effect.result, + ); + + if (Result.isFailure(aboutProbe)) { + const error = aboutProbe.failure; + return buildServerProvider({ + presentation: CURSOR_PRESENTATION, + enabled: cursorSettings.enabled, + checkedAt, + models: fallbackModels, + probe: { + installed: !isCommandMissingCause(error), + version: null, + status: "error", + auth: { status: "unknown" }, + message: isCommandMissingCause(error) + ? "Cursor Agent CLI (`agent`) is not installed or not on PATH." + : `Failed to execute Cursor Agent CLI health check: ${error instanceof Error ? error.message : String(error)}.`, + }, + }); + } + + if (Option.isNone(aboutProbe.success)) { + return buildServerProvider({ + presentation: CURSOR_PRESENTATION, + enabled: cursorSettings.enabled, + checkedAt, + models: fallbackModels, + probe: { + installed: true, + version: null, + status: "error", + auth: { status: "unknown" }, + message: "Cursor Agent CLI is installed but timed out while running `agent about`.", + }, + }); + } + + const parsed = parseCursorAboutOutput(aboutProbe.success.value); + const cursorCliConfigChannel = yield* readCursorCliConfigChannel(); + const parameterizedModelPickerUnsupportedMessage = + getCursorParameterizedModelPickerUnsupportedMessage({ + version: parsed.version, + channel: cursorCliConfigChannel, + }); + if (parameterizedModelPickerUnsupportedMessage) { + return buildServerProvider({ + presentation: CURSOR_PRESENTATION, + enabled: cursorSettings.enabled, + checkedAt, + models: fallbackModels, + probe: { + installed: true, + version: parsed.version, + status: "error", + auth: parsed.auth, + message: + parsed.auth.status === "unauthenticated" && parsed.message + ? `${parameterizedModelPickerUnsupportedMessage} ${parsed.message}` + : parameterizedModelPickerUnsupportedMessage, + }, + }); + } + let discoveredModels = Option.none>(); + let discoveryWarning: string | undefined; + if (parsed.auth.status !== "unauthenticated") { + const discoveryExit = yield* Effect.exit( + discoverCursorModelsViaAcp(cursorSettings, environment).pipe( + Effect.timeoutOption(CURSOR_ACP_MODEL_DISCOVERY_TIMEOUT_MS), + ), + ); + if (Exit.isFailure(discoveryExit)) { + yield* Effect.logWarning("Cursor ACP model discovery failed", { + cause: Cause.pretty(discoveryExit.cause), + }); + discoveryWarning = "Cursor ACP model discovery failed. Check server logs for details."; + } else if (Option.isNone(discoveryExit.value)) { + discoveryWarning = `Cursor ACP model discovery timed out after ${CURSOR_ACP_MODEL_DISCOVERY_TIMEOUT_MS}ms.`; + } else if (discoveryExit.value.value.length === 0) { + discoveryWarning = "Cursor ACP model discovery returned no built-in models."; + } else { + discoveredModels = discoveryExit.value; + } + } + return buildCursorProviderSnapshot({ + checkedAt, + cursorSettings, + parsed, + discoveredModels: Option.getOrElse( + Option.filter(discoveredModels, (models) => models.length > 0), + () => [] as const, + ), + ...(discoveryWarning ? { discoveryWarning } : {}), + }); }); -export const checkCursorProviderStatus = Effect.fn("checkCursorProviderStatus")( - function* (): Effect.fn.Return< - ServerProvider, - ServerSettingsError, - ChildProcessSpawner.ChildProcessSpawner | ServerSettingsService - > { - const cursorSettings = yield* Effect.service(ServerSettingsService).pipe( - Effect.flatMap((service) => service.getSettings), - Effect.map((settings) => settings.providers.cursor), - ); - const checkedAt = new Date().toISOString(); - const fallbackModels = getCursorFallbackModels(cursorSettings); +export function hasUncapturedCursorModels(snapshot: Pick): boolean { + return snapshot.models.some((model) => !model.isCustom && !hasCursorModelCapabilities(model)); +} - if (!cursorSettings.enabled) { - return buildServerProvider({ - provider: PROVIDER, - presentation: CURSOR_PRESENTATION, - enabled: false, - checkedAt, - models: fallbackModels, - probe: { - installed: false, - version: null, - status: "warning", - auth: { status: "unknown" }, - message: "Cursor is disabled in T3 Code settings.", - }, - }); - } +/** + * Background capability enrichment for a Cursor snapshot. + * + * Used by `CursorDriver` as the `makeManagedServerProvider.enrichSnapshot` + * hook: runs the slow ACP per-model capability probe, and republishes the + * snapshot through `publishSnapshot` when new capabilities arrive. Skips + * the probe when the provider is disabled, unauthenticated, or has no + * uncaptured models. Keeps `EMPTY_CAPABILITIES` and the `PROVIDER` literal + * private to this module. + */ +export const enrichCursorSnapshot = (input: { + readonly settings: CursorSettings; + readonly environment?: NodeJS.ProcessEnv; + readonly snapshot: ServerProvider; + readonly publishSnapshot: (snapshot: ServerProvider) => Effect.Effect; + readonly stampIdentity?: (snapshot: ServerProvider) => ServerProvider; +}): Effect.Effect => { + const { settings, snapshot, publishSnapshot } = input; + const stampIdentity = input.stampIdentity ?? ((value) => value); - // Single `agent about` probe: returns version + auth status in one call. - const aboutProbe = yield* runCursorAboutCommand.pipe( - Effect.timeoutOption(ABOUT_TIMEOUT_MS), - Effect.result, - ); + if ( + !settings.enabled || + snapshot.auth.status === "unauthenticated" || + !hasUncapturedCursorModels(snapshot) + ) { + return Effect.void; + } - if (Result.isFailure(aboutProbe)) { - const error = aboutProbe.failure; - return buildServerProvider({ - provider: PROVIDER, - presentation: CURSOR_PRESENTATION, - enabled: cursorSettings.enabled, - checkedAt, - models: fallbackModels, - probe: { - installed: !isCommandMissingCause(error), - version: null, - status: "error", - auth: { status: "unknown" }, - message: isCommandMissingCause(error) - ? "Cursor Agent CLI (`agent`) is not installed or not on PATH." - : `Failed to execute Cursor Agent CLI health check: ${error instanceof Error ? error.message : String(error)}.`, - }, - }); - } - - if (Option.isNone(aboutProbe.success)) { - return buildServerProvider({ - provider: PROVIDER, - presentation: CURSOR_PRESENTATION, - enabled: cursorSettings.enabled, - checkedAt, - models: fallbackModels, - probe: { - installed: true, - version: null, - status: "error", - auth: { status: "unknown" }, - message: "Cursor Agent CLI is installed but timed out while running `agent about`.", - }, - }); - } - - const parsed = parseCursorAboutOutput(aboutProbe.success.value); - const parameterizedModelPickerUnsupportedMessage = - getCursorParameterizedModelPickerUnsupportedMessage({ - version: parsed.version, - channel: readCursorCliConfigChannel(), - }); - if (parameterizedModelPickerUnsupportedMessage) { - return buildServerProvider({ - provider: PROVIDER, - presentation: CURSOR_PRESENTATION, - enabled: cursorSettings.enabled, - checkedAt, - models: fallbackModels, - probe: { - installed: true, - version: parsed.version, - status: "error", - auth: parsed.auth, - message: - parsed.auth.status === "unauthenticated" && parsed.message - ? `${parameterizedModelPickerUnsupportedMessage} ${parsed.message}` - : parameterizedModelPickerUnsupportedMessage, - }, - }); - } - let discoveredModels = Option.none>(); - let discoveryWarning: string | undefined; - if (parsed.auth.status !== "unauthenticated") { - const discoveryExit = yield* Effect.exit( - discoverCursorModelsViaAcp(cursorSettings).pipe( - Effect.timeoutOption(CURSOR_ACP_MODEL_DISCOVERY_TIMEOUT_MS), - ), - ); - if (Exit.isFailure(discoveryExit)) { - yield* Effect.logWarning("Cursor ACP model discovery failed", { - cause: Cause.pretty(discoveryExit.cause), - }); - discoveryWarning = "Cursor ACP model discovery failed. Check server logs for details."; - } else if (Option.isNone(discoveryExit.value)) { - discoveryWarning = `Cursor ACP model discovery timed out after ${CURSOR_ACP_MODEL_DISCOVERY_TIMEOUT_MS}ms.`; - } else if (discoveryExit.value.value.length === 0) { - discoveryWarning = "Cursor ACP model discovery returned no built-in models."; - } else { - discoveredModels = discoveryExit.value; + return discoverCursorModelCapabilitiesViaAcp(settings, snapshot.models, input.environment).pipe( + Effect.flatMap((discoveredModels) => { + if (discoveredModels.length === 0) { + return Effect.void; } - } - return buildCursorProviderSnapshot({ - checkedAt, - cursorSettings, - parsed, - discoveredModels: Option.getOrElse( - Option.filter(discoveredModels, (models) => models.length > 0), - () => [] as const, - ), - ...(discoveryWarning ? { discoveryWarning } : {}), - }); - }, -); - -export const CursorProviderLive = Layer.effect( - CursorProvider, - Effect.gen(function* () { - const serverSettings = yield* ServerSettingsService; - const spawner = yield* ChildProcessSpawner.ChildProcessSpawner; - - const checkProvider = checkCursorProviderStatus().pipe( - Effect.provideService(ServerSettingsService, serverSettings), - Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner), - ); - - return yield* makeManagedServerProvider({ - getSettings: serverSettings.getSettings.pipe( - Effect.map((settings) => settings.providers.cursor), - Effect.orDie, - ), - streamSettings: serverSettings.streamChanges.pipe( - Stream.map((settings) => settings.providers.cursor), - ), - haveSettingsChanged: (previous, next) => !Equal.equals(previous, next), - initialSnapshot: buildInitialCursorProviderSnapshot, - checkProvider, - enrichSnapshot: ({ settings, snapshot, publishSnapshot }) => { - if ( - !settings.enabled || - snapshot.auth.status === "unauthenticated" || - !snapshot.models.some((model) => !model.isCustom && !hasCursorModelCapabilities(model)) - ) { - return Effect.void; - } - - return discoverCursorModelCapabilitiesViaAcp(settings, snapshot.models).pipe( - Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner), - Effect.flatMap((discoveredModels) => { - if (discoveredModels.length === 0) { - return Effect.void; - } - - return publishSnapshot({ - ...snapshot, - models: providerModelsFromSettings( - discoveredModels, - PROVIDER, - settings.customModels, - EMPTY_CAPABILITIES, - ), - }); - }), - Effect.catchCause((cause) => - Effect.logWarning("Cursor ACP background capability enrichment failed", { - models: snapshot.models.map((model) => model.slug), - cause: Cause.pretty(cause), - }).pipe(Effect.asVoid), + return publishSnapshot( + stampIdentity({ + ...snapshot, + models: providerModelsFromSettings( + discoveredModels, + PROVIDER, + settings.customModels, + EMPTY_CAPABILITIES, ), - ); - }, - refreshInterval: CURSOR_REFRESH_INTERVAL, - }); - }), -); + }), + ); + }), + Effect.catchCause((cause) => + Effect.logWarning("Cursor ACP background capability enrichment failed", { + models: snapshot.models.map((model) => model.slug), + cause: Cause.pretty(cause), + }).pipe(Effect.asVoid), + ), + ); +}; diff --git a/apps/server/src/provider/Layers/OpenCodeAdapter.test.ts b/apps/server/src/provider/Layers/OpenCodeAdapter.test.ts index 9a391b5539..370e5c028f 100644 --- a/apps/server/src/provider/Layers/OpenCodeAdapter.test.ts +++ b/apps/server/src/provider/Layers/OpenCodeAdapter.test.ts @@ -2,14 +2,20 @@ import assert from "node:assert/strict"; import * as NodeServices from "@effect/platform-node/NodeServices"; import { it } from "@effect/vitest"; -import { Effect, Layer, Option } from "effect"; +import { Context, Effect, Exit, Fiber, Layer, Option, Schema, Scope, Stream } from "effect"; import { beforeEach } from "vitest"; -import { ThreadId } from "@t3tools/contracts"; +import { + OpenCodeSettings, + ProviderDriverKind, + ProviderInstanceId, + ThreadId, +} from "@t3tools/contracts"; +import { createModelSelection } from "@t3tools/shared/model"; import { ServerConfig } from "../../config.ts"; import { ServerSettingsService } from "../../serverSettings.ts"; import { ProviderSessionDirectory } from "../Services/ProviderSessionDirectory.ts"; -import { OpenCodeAdapter } from "../Services/OpenCodeAdapter.ts"; +import type { OpenCodeAdapterShape } from "../Services/OpenCodeAdapter.ts"; import { OpenCodeRuntime, OpenCodeRuntimeError, @@ -17,10 +23,15 @@ import { } from "../opencodeRuntime.ts"; import { appendOpenCodeAssistantTextDelta, - makeOpenCodeAdapterLive, + makeOpenCodeAdapter, mergeOpenCodeAssistantText, } from "./OpenCodeAdapter.ts"; +// Test-local service tag so the rest of the file can keep using `yield* OpenCodeAdapter`. +class OpenCodeAdapter extends Context.Service()( + "test/OpenCodeAdapter", +) {} + const asThreadId = (value: string): ThreadId => ThreadId.make(value); type MessageEntry = { @@ -39,6 +50,7 @@ const runtimeMock = { abortCalls: [] as string[], closeCalls: [] as string[], revertCalls: [] as Array<{ sessionID: string; messageID?: string }>, + promptCalls: [] as Array, promptAsyncError: null as Error | null, closeError: null as Error | null, messages: [] as MessageEntry[], @@ -51,6 +63,7 @@ const runtimeMock = { this.state.abortCalls.length = 0; this.state.closeCalls.length = 0; this.state.revertCalls.length = 0; + this.state.promptCalls.length = 0; this.state.promptAsyncError = null; this.state.closeError = null; this.state.messages = []; @@ -111,7 +124,8 @@ const OpenCodeRuntimeTestDouble: OpenCodeRuntimeShape = { abort: async ({ sessionID }: { sessionID: string }) => { runtimeMock.state.abortCalls.push(sessionID); }, - promptAsync: async () => { + promptAsync: async (input: unknown) => { + runtimeMock.state.promptCalls.push(input); if (runtimeMock.state.promptAsyncError) { throw runtimeMock.state.promptAsyncError; } @@ -165,7 +179,24 @@ const providerSessionDirectoryTestLayer = Layer.succeed(ProviderSessionDirectory listBindings: () => Effect.succeed([]), }); -const OpenCodeAdapterTestLayer = makeOpenCodeAdapterLive().pipe( +// The adapter now receives its settings as a plain argument (the old design +// read from `ServerSettingsService` internally). The test-only +// `ServerSettingsService` below is still kept because other dependencies in +// the layer graph reach for it — but the routing values the assertions +// probe (serverUrl, serverPassword) must be threaded directly through the +// decoded `OpenCodeSettings`. +const openCodeAdapterTestSettings = Schema.decodeSync(OpenCodeSettings)({ + binaryPath: "fake-opencode", + serverUrl: "http://127.0.0.1:9999", + serverPassword: "secret-password", +}); + +const OpenCodeAdapterTestLayer = Layer.effect( + OpenCodeAdapter, + Effect.gen(function* () { + return yield* makeOpenCodeAdapter(openCodeAdapterTestSettings); + }), +).pipe( Layer.provideMerge(Layer.succeed(OpenCodeRuntime, OpenCodeRuntimeTestDouble)), Layer.provideMerge(ServerConfig.layerTest(process.cwd(), process.cwd())), Layer.provideMerge( @@ -196,7 +227,7 @@ it.layer(OpenCodeAdapterTestLayer)("OpenCodeAdapterLive", (it) => { const adapter = yield* OpenCodeAdapter; const session = yield* adapter.startSession({ - provider: "opencode", + provider: ProviderDriverKind.make("opencode"), threadId: asThreadId("thread-opencode"), runtimeMode: "full-access", }); @@ -215,7 +246,7 @@ it.layer(OpenCodeAdapterTestLayer)("OpenCodeAdapterLive", (it) => { Effect.gen(function* () { const adapter = yield* OpenCodeAdapter; yield* adapter.startSession({ - provider: "opencode", + provider: ProviderDriverKind.make("opencode"), threadId: asThreadId("thread-opencode"), runtimeMode: "full-access", }); @@ -230,16 +261,42 @@ it.layer(OpenCodeAdapterTestLayer)("OpenCodeAdapterLive", (it) => { }), ); + it.effect("emits one session.exited event when stopping a session", () => + Effect.gen(function* () { + const adapter = yield* OpenCodeAdapter; + const threadId = asThreadId("thread-opencode-stop-event"); + const eventsFiber = yield* adapter.streamEvents.pipe( + Stream.filter((event) => event.threadId === threadId), + Stream.take(3), + Stream.runCollect, + Effect.forkChild, + ); + + yield* adapter.startSession({ + provider: ProviderDriverKind.make("opencode"), + threadId, + runtimeMode: "full-access", + }); + yield* adapter.stopSession(threadId); + + const events = Array.from(yield* Fiber.join(eventsFiber).pipe(Effect.timeout("1 second"))); + assert.deepEqual( + events.map((event) => event.type), + ["session.started", "thread.started", "session.exited"], + ); + }), + ); + it.effect("clears session state even when cleanup finalizers throw", () => Effect.gen(function* () { const adapter = yield* OpenCodeAdapter; yield* adapter.startSession({ - provider: "opencode", + provider: ProviderDriverKind.make("opencode"), threadId: asThreadId("thread-stop-all-a"), runtimeMode: "full-access", }); yield* adapter.startSession({ - provider: "opencode", + provider: ProviderDriverKind.make("opencode"), threadId: asThreadId("thread-stop-all-b"), runtimeMode: "full-access", }); @@ -261,11 +318,44 @@ it.layer(OpenCodeAdapterTestLayer)("OpenCodeAdapterLive", (it) => { }), ); + it.effect("completes streamEvents when the adapter scope closes", () => + Effect.gen(function* () { + const scope = yield* Scope.make("sequential"); + let scopeClosed = false; + + try { + const adapterLayer = Layer.effect( + OpenCodeAdapter, + makeOpenCodeAdapter(openCodeAdapterTestSettings), + ).pipe( + Layer.provideMerge(Layer.succeed(OpenCodeRuntime, OpenCodeRuntimeTestDouble)), + Layer.provideMerge(ServerConfig.layerTest(process.cwd(), process.cwd())), + Layer.provideMerge(ServerSettingsService.layerTest()), + Layer.provideMerge(providerSessionDirectoryTestLayer), + Layer.provideMerge(NodeServices.layer), + ); + const context = yield* Layer.buildWithScope(adapterLayer, scope); + const adapter = yield* Effect.service(OpenCodeAdapter).pipe(Effect.provide(context)); + const eventsFiber = yield* adapter.streamEvents.pipe(Stream.runCollect, Effect.forkChild); + + yield* Scope.close(scope, Exit.void); + scopeClosed = true; + + const exit = yield* Fiber.await(eventsFiber).pipe(Effect.timeout("1 second")); + assert.equal(Exit.hasInterrupts(exit), true); + } finally { + if (!scopeClosed) { + yield* Scope.close(scope, Exit.void).pipe(Effect.ignore); + } + } + }), + ); + it.effect("rolls back session state when sendTurn fails before OpenCode accepts the prompt", () => Effect.gen(function* () { const adapter = yield* OpenCodeAdapter; yield* adapter.startSession({ - provider: "opencode", + provider: ProviderDriverKind.make("opencode"), threadId: asThreadId("thread-send-turn-failure"), runtimeMode: "full-access", }); @@ -276,7 +366,7 @@ it.layer(OpenCodeAdapterTestLayer)("OpenCodeAdapterLive", (it) => { threadId: asThreadId("thread-send-turn-failure"), input: "Fix it", modelSelection: { - provider: "opencode", + instanceId: ProviderInstanceId.make("opencode"), model: "openai/gpt-5", }, }) @@ -299,12 +389,158 @@ it.layer(OpenCodeAdapterTestLayer)("OpenCodeAdapterLive", (it) => { }), ); + it.effect("passes agent and variant options for the adapter's bound custom instance id", () => { + const customInstanceId = ProviderInstanceId.make("opencode_zen"); + const adapterLayer = Layer.effect( + OpenCodeAdapter, + Effect.gen(function* () { + return yield* makeOpenCodeAdapter(openCodeAdapterTestSettings, { + instanceId: customInstanceId, + }); + }), + ).pipe( + Layer.provideMerge(Layer.succeed(OpenCodeRuntime, OpenCodeRuntimeTestDouble)), + Layer.provideMerge(ServerConfig.layerTest(process.cwd(), process.cwd())), + Layer.provideMerge(ServerSettingsService.layerTest()), + Layer.provideMerge(providerSessionDirectoryTestLayer), + Layer.provideMerge(NodeServices.layer), + ); + + return Effect.gen(function* () { + const adapter = yield* OpenCodeAdapter; + yield* adapter.startSession({ + provider: ProviderDriverKind.make("opencode"), + threadId: asThreadId("thread-custom-instance"), + runtimeMode: "full-access", + }); + + yield* adapter.sendTurn({ + threadId: asThreadId("thread-custom-instance"), + input: "Fix it", + modelSelection: createModelSelection( + ProviderInstanceId.make("opencode_zen"), + "anthropic/claude-sonnet-4-5", + [ + { id: "agent", value: "github-copilot" }, + { id: "variant", value: "high" }, + ], + ), + }); + + assert.deepEqual(runtimeMock.state.promptCalls.at(-1), { + sessionID: "http://127.0.0.1:9999/session", + model: { + providerID: "anthropic", + modelID: "claude-sonnet-4-5", + }, + agent: "github-copilot", + variant: "high", + parts: [{ type: "text", text: "Fix it" }], + }); + }).pipe(Effect.provide(adapterLayer)); + }); + + it.effect("uses the bound custom instance id for fallback sendTurn model selection", () => { + const customInstanceId = ProviderInstanceId.make("opencode_zen"); + const adapterLayer = Layer.effect( + OpenCodeAdapter, + Effect.gen(function* () { + return yield* makeOpenCodeAdapter(openCodeAdapterTestSettings, { + instanceId: customInstanceId, + }); + }), + ).pipe( + Layer.provideMerge(Layer.succeed(OpenCodeRuntime, OpenCodeRuntimeTestDouble)), + Layer.provideMerge(ServerConfig.layerTest(process.cwd(), process.cwd())), + Layer.provideMerge(ServerSettingsService.layerTest()), + Layer.provideMerge(providerSessionDirectoryTestLayer), + Layer.provideMerge(NodeServices.layer), + ); + + return Effect.gen(function* () { + const adapter = yield* OpenCodeAdapter; + const threadId = asThreadId("thread-custom-instance-fallback-model"); + yield* adapter.startSession({ + provider: ProviderDriverKind.make("opencode"), + threadId, + runtimeMode: "full-access", + modelSelection: createModelSelection( + ProviderInstanceId.make("opencode_zen"), + "anthropic/claude-sonnet-4-5", + ), + }); + + yield* adapter.sendTurn({ + threadId, + input: "Fix it", + }); + + assert.deepEqual(runtimeMock.state.promptCalls.at(-1), { + sessionID: "http://127.0.0.1:9999/session", + model: { + providerID: "anthropic", + modelID: "claude-sonnet-4-5", + }, + parts: [{ type: "text", text: "Fix it" }], + }); + }).pipe(Effect.provide(adapterLayer)); + }); + + it.effect("rejects sendTurn model selections for another instance id", () => { + const customInstanceId = ProviderInstanceId.make("opencode_zen"); + const adapterLayer = Layer.effect( + OpenCodeAdapter, + Effect.gen(function* () { + return yield* makeOpenCodeAdapter(openCodeAdapterTestSettings, { + instanceId: customInstanceId, + }); + }), + ).pipe( + Layer.provideMerge(Layer.succeed(OpenCodeRuntime, OpenCodeRuntimeTestDouble)), + Layer.provideMerge(ServerConfig.layerTest(process.cwd(), process.cwd())), + Layer.provideMerge(ServerSettingsService.layerTest()), + Layer.provideMerge(providerSessionDirectoryTestLayer), + Layer.provideMerge(NodeServices.layer), + ); + + return Effect.gen(function* () { + const adapter = yield* OpenCodeAdapter; + const threadId = asThreadId("thread-custom-instance-wrong-selection"); + yield* adapter.startSession({ + provider: ProviderDriverKind.make("opencode"), + threadId, + runtimeMode: "full-access", + }); + + const error = yield* adapter + .sendTurn({ + threadId, + input: "Fix it", + modelSelection: createModelSelection( + ProviderInstanceId.make("opencode"), + "anthropic/claude-sonnet-4-5", + ), + }) + .pipe(Effect.flip); + + assert.equal(error._tag, "ProviderAdapterValidationError"); + if (error._tag !== "ProviderAdapterValidationError") { + throw new Error("Unexpected error type"); + } + assert.equal( + error.issue, + "OpenCode model selection is bound to instance 'opencode', expected 'opencode_zen'.", + ); + assert.deepEqual(runtimeMock.state.promptCalls, []); + }).pipe(Effect.provide(adapterLayer)); + }); + it.effect("reverts the full thread when rollback removes every assistant turn", () => Effect.gen(function* () { const adapter = yield* OpenCodeAdapter; const threadId = asThreadId("thread-rollback-all"); yield* adapter.startSession({ - provider: "opencode", + provider: ProviderDriverKind.make("opencode"), threadId, runtimeMode: "full-access", }); @@ -396,9 +632,14 @@ it.layer(OpenCodeAdapterTestLayer)("OpenCodeAdapterLive", (it) => { close: () => Effect.void, }; - const adapterLayer = makeOpenCodeAdapterLive({ - nativeEventLogger, - }).pipe( + const adapterLayer = Layer.effect( + OpenCodeAdapter, + Effect.gen(function* () { + return yield* makeOpenCodeAdapter(openCodeAdapterTestSettings, { + nativeEventLogger, + }); + }), + ).pipe( Layer.provideMerge(Layer.succeed(OpenCodeRuntime, OpenCodeRuntimeTestDouble)), Layer.provideMerge(ServerConfig.layerTest(process.cwd(), process.cwd())), Layer.provideMerge( @@ -419,7 +660,7 @@ it.layer(OpenCodeAdapterTestLayer)("OpenCodeAdapterLive", (it) => { const session = yield* Effect.gen(function* () { const adapter = yield* OpenCodeAdapter; const started = yield* adapter.startSession({ - provider: "opencode", + provider: ProviderDriverKind.make("opencode"), threadId: asThreadId("thread-native-log"), runtimeMode: "full-access", }); @@ -475,9 +716,12 @@ it.layer(OpenCodeAdapterTestLayer)("OpenCodeAdapterLive", (it) => { close: () => Effect.void, }; - const adapterLayer = makeOpenCodeAdapterLive({ - nativeEventLogger, - }).pipe( + const adapterLayer = Layer.effect( + OpenCodeAdapter, + makeOpenCodeAdapter(openCodeAdapterTestSettings, { + nativeEventLogger, + }), + ).pipe( Layer.provideMerge(Layer.succeed(OpenCodeRuntime, OpenCodeRuntimeTestDouble)), Layer.provideMerge(ServerConfig.layerTest(process.cwd(), process.cwd())), Layer.provideMerge( @@ -504,7 +748,7 @@ it.layer(OpenCodeAdapterTestLayer)("OpenCodeAdapterLive", (it) => { const { sessions, closeCallsDuringRun } = yield* Effect.gen(function* () { const adapter = yield* OpenCodeAdapter; yield* adapter.startSession({ - provider: "opencode", + provider: ProviderDriverKind.make("opencode"), threadId: asThreadId("thread-native-log-failure"), runtimeMode: "full-access", }); diff --git a/apps/server/src/provider/Layers/OpenCodeAdapter.ts b/apps/server/src/provider/Layers/OpenCodeAdapter.ts index aa504d5b96..a7b179ab1c 100644 --- a/apps/server/src/provider/Layers/OpenCodeAdapter.ts +++ b/apps/server/src/provider/Layers/OpenCodeAdapter.ts @@ -1,7 +1,8 @@ -import { randomUUID } from "node:crypto"; - import { EventId, + type OpenCodeSettings, + ProviderDriverKind, + ProviderInstanceId, type ProviderRuntimeEvent, type ProviderSession, RuntimeItemId, @@ -11,13 +12,12 @@ import { TurnId, type UserInputQuestion, } from "@t3tools/contracts"; -import { Cause, Effect, Exit, Layer, Queue, Ref, Scope, Stream } from "effect"; +import { Cause, Effect, Exit, Queue, Random, Ref, Scope, Stream } from "effect"; import type { OpencodeClient, Part, PermissionRequest, QuestionRequest } from "@opencode-ai/sdk/v2"; import { getModelSelectionStringOptionValue } from "@t3tools/shared/model"; import { resolveAttachmentPath } from "../../attachmentStore.ts"; import { ServerConfig } from "../../config.ts"; -import { ServerSettingsService } from "../../serverSettings.ts"; import { type EventNdjsonLogger, makeEventNdjsonLogger } from "./EventNdjsonLogger.ts"; import { ProviderAdapterProcessError, @@ -26,7 +26,7 @@ import { ProviderAdapterSessionNotFoundError, ProviderAdapterValidationError, } from "../Errors.ts"; -import { OpenCodeAdapter, type OpenCodeAdapterShape } from "../Services/OpenCodeAdapter.ts"; +import { type OpenCodeAdapterShape } from "../Services/OpenCodeAdapter.ts"; import { buildOpenCodePermissionRules, OpenCodeRuntime, @@ -41,7 +41,7 @@ import { type OpenCodeServerConnection, } from "../opencodeRuntime.ts"; -const PROVIDER = "opencode" as const; +const PROVIDER = ProviderDriverKind.make("opencode"); interface OpenCodeTurnSnapshot { readonly id: TurnId; @@ -89,6 +89,8 @@ interface OpenCodeSessionContext { } export interface OpenCodeAdapterLiveOptions { + readonly instanceId?: ProviderInstanceId; + readonly environment?: NodeJS.ProcessEnv; readonly nativeEventLogPath?: string; readonly nativeEventLogger?: EventNdjsonLogger; } @@ -125,35 +127,38 @@ const toProcessError = (threadId: ThreadId, cause: unknown): ProviderAdapterProc cause, }); -function buildEventBase(input: { +const buildEventBase = (input: { readonly threadId: ThreadId; readonly turnId?: TurnId | undefined; readonly itemId?: string | undefined; readonly requestId?: string | undefined; readonly createdAt?: string | undefined; readonly raw?: unknown; -}): Pick< - ProviderRuntimeEvent, - "eventId" | "provider" | "threadId" | "createdAt" | "turnId" | "itemId" | "requestId" | "raw" -> { - return { - eventId: EventId.make(randomUUID()), - provider: PROVIDER, - threadId: input.threadId, - createdAt: input.createdAt ?? nowIso(), - ...(input.turnId ? { turnId: input.turnId } : {}), - ...(input.itemId ? { itemId: RuntimeItemId.make(input.itemId) } : {}), - ...(input.requestId ? { requestId: RuntimeRequestId.make(input.requestId) } : {}), - ...(input.raw !== undefined - ? { - raw: { - source: "opencode.sdk.event", - payload: input.raw, - }, - } - : {}), - }; -} +}): Effect.Effect< + Pick< + ProviderRuntimeEvent, + "eventId" | "provider" | "threadId" | "createdAt" | "turnId" | "itemId" | "requestId" | "raw" + > +> => + Random.nextUUIDv4.pipe( + Effect.map((uuid) => ({ + eventId: EventId.make(uuid), + provider: PROVIDER, + threadId: input.threadId, + createdAt: input.createdAt ?? nowIso(), + ...(input.turnId ? { turnId: input.turnId } : {}), + ...(input.itemId ? { itemId: RuntimeItemId.make(input.itemId) } : {}), + ...(input.requestId ? { requestId: RuntimeRequestId.make(input.requestId) } : {}), + ...(input.raw !== undefined + ? { + raw: { + source: "opencode.sdk.event", + payload: input.raw, + }, + } + : {}), + })), + ); function toToolLifecycleItemType(toolName: string): ToolLifecycleItemType { const normalized = toolName.toLowerCase(); @@ -245,13 +250,19 @@ function ensureSessionContext( ): OpenCodeSessionContext { const session = sessions.get(threadId); if (!session) { - throw new ProviderAdapterSessionNotFoundError({ provider: PROVIDER, threadId }); + throw new ProviderAdapterSessionNotFoundError({ + provider: PROVIDER, + threadId, + }); } // `ensureSessionContext` is a sync gate used from both sync helpers and // Effect bodies. `Ref.getUnsafe` is an atomic read of the backing cell — // no fiber suspension required, which keeps this callable everywhere. if (Ref.getUnsafe(session.stopped)) { - throw new ProviderAdapterSessionClosedError({ provider: PROVIDER, threadId }); + throw new ProviderAdapterSessionClosedError({ + provider: PROVIDER, + threadId, + }); } return session; } @@ -419,7 +430,7 @@ const stopOpenCodeContext = Effect.fn("stopOpenCodeContext")(function* ( ) { // Race-safe one-shot: first caller flips the flag, everyone else no-ops. if (yield* Ref.getAndSet(context.stopped, true)) { - return; + return false; } // Best-effort remote abort. The scope close below tears down the local @@ -433,957 +444,990 @@ const stopOpenCodeContext = Effect.fn("stopOpenCodeContext")(function* ( // runs each finalizer we registered — the `AbortController.abort()` call, // the child-process termination, etc. yield* Scope.close(context.sessionScope, Exit.void); + return true; }); -export function makeOpenCodeAdapterLive(options?: OpenCodeAdapterLiveOptions) { - return Layer.effect( - OpenCodeAdapter, - Effect.gen(function* () { - const serverConfig = yield* ServerConfig; - const serverSettings = yield* ServerSettingsService; - const openCodeRuntime = yield* OpenCodeRuntime; - const nativeEventLogger = - options?.nativeEventLogger ?? - (options?.nativeEventLogPath !== undefined - ? yield* makeEventNdjsonLogger(options.nativeEventLogPath, { - stream: "native", - }) - : undefined); - // Only close loggers we created. If the caller passed one in via - // `options.nativeEventLogger`, they own its lifecycle. - const managedNativeEventLogger = - options?.nativeEventLogger === undefined ? nativeEventLogger : undefined; - const runtimeEvents = yield* Queue.unbounded(); - const sessions = new Map(); +export function makeOpenCodeAdapter( + openCodeSettings: OpenCodeSettings, + options?: OpenCodeAdapterLiveOptions, +) { + return Effect.gen(function* () { + const boundInstanceId = options?.instanceId ?? ProviderInstanceId.make("opencode"); + const serverConfig = yield* ServerConfig; + const openCodeRuntime = yield* OpenCodeRuntime; + const nativeEventLogger = + options?.nativeEventLogger ?? + (options?.nativeEventLogPath !== undefined + ? yield* makeEventNdjsonLogger(options.nativeEventLogPath, { + stream: "native", + }) + : undefined); + // Only close loggers we created. If the caller passed one in via + // `options.nativeEventLogger`, they own its lifecycle. + const managedNativeEventLogger = + options?.nativeEventLogger === undefined ? nativeEventLogger : undefined; + const runtimeEvents = yield* Queue.unbounded(); + const sessions = new Map(); - // Layer-level finalizer: when the adapter layer shuts down, stop every - // session. Each session's `Scope.close` tears down its spawned OpenCode - // server (via the `ChildProcessSpawner` finalizer installed in - // `startOpenCodeServerProcess`) and interrupts the forked event/exit - // fibers. Consumers that can't reason about Effect scopes therefore - // cannot leak OpenCode child processes by forgetting to call `stopAll`. - yield* Effect.addFinalizer(() => - Effect.gen(function* () { - const contexts = [...sessions.values()]; - sessions.clear(); - // `ignoreCause` swallows both typed failures (none here) and defects - // from throwing scope finalizers so a sibling's death can't interrupt - // the remaining cleanups. - yield* Effect.forEach( - contexts, - (context) => Effect.ignoreCause(stopOpenCodeContext(context)), - { concurrency: "unbounded", discard: true }, - ); - // Close the logger AFTER session teardown so any final lifecycle - // events emitted during shutdown still get written. `close` flushes - // the `Logger.batched` window and closes each per-thread - // `RotatingFileSink` handle owned by the logger's internal scope. - if (managedNativeEventLogger !== undefined) { - yield* managedNativeEventLogger.close(); - } - }), - ); - - const emit = (event: ProviderRuntimeEvent) => - Queue.offer(runtimeEvents, event).pipe(Effect.asVoid); - const writeNativeEvent = ( - threadId: ThreadId, - event: { - readonly observedAt: string; - readonly event: Record; - }, - ) => (nativeEventLogger ? nativeEventLogger.write(event, threadId) : Effect.void); - const writeNativeEventBestEffort = ( - threadId: ThreadId, - event: { - readonly observedAt: string; - readonly event: Record; - }, - ) => writeNativeEvent(threadId, event).pipe(Effect.catchCause(() => Effect.void)); - - const emitUnexpectedExit = Effect.fn("emitUnexpectedExit")(function* ( - context: OpenCodeSessionContext, - message: string, - ) { - // Atomic one-shot: two fibers can race here (the event-pump on stream - // failure and the server-exit watcher). `getAndSet` flips the flag in - // a single step so the loser observes `true` and returns; a plain - // `Ref.get` would let both racers slip past and emit duplicates. - if (yield* Ref.getAndSet(context.stopped, true)) { - return; + // Layer-level finalizer: when the adapter layer shuts down, stop every + // session. Each session's `Scope.close` tears down its spawned OpenCode + // server (via the `ChildProcessSpawner` finalizer installed in + // `startOpenCodeServerProcess`) and interrupts the forked event/exit + // fibers. Consumers that can't reason about Effect scopes therefore + // cannot leak OpenCode child processes by forgetting to call `stopAll`. + yield* Effect.addFinalizer(() => + Effect.gen(function* () { + const contexts = [...sessions.values()]; + sessions.clear(); + // `ignoreCause` swallows both typed failures (none here) and defects + // from throwing scope finalizers so a sibling's death can't interrupt + // the remaining cleanups. + yield* Effect.forEach( + contexts, + (context) => Effect.ignoreCause(stopOpenCodeContext(context)), + { concurrency: "unbounded", discard: true }, + ); + // Close the logger AFTER session teardown so any final lifecycle + // events emitted during shutdown still get written. `close` flushes + // the `Logger.batched` window and closes each per-thread + // `RotatingFileSink` handle owned by the logger's internal scope. + if (managedNativeEventLogger !== undefined) { + yield* managedNativeEventLogger.close(); } - const turnId = context.activeTurnId; - sessions.delete(context.session.threadId); - // Emit lifecycle events BEFORE tearing down the scope. Both call sites - // run this inside a fiber forked via `Effect.forkIn(context.sessionScope)`; - // closing that scope triggers the fiber-interrupt finalizer, so any - // subsequent yield point would unwind and silently drop these emits. + }).pipe(Effect.ensuring(Queue.shutdown(runtimeEvents))), + ); + + const emit = (event: ProviderRuntimeEvent) => + Queue.offer(runtimeEvents, event).pipe(Effect.asVoid); + const writeNativeEvent = ( + threadId: ThreadId, + event: { + readonly observedAt: string; + readonly event: Record; + }, + ) => (nativeEventLogger ? nativeEventLogger.write(event, threadId) : Effect.void); + const writeNativeEventBestEffort = ( + threadId: ThreadId, + event: { + readonly observedAt: string; + readonly event: Record; + }, + ) => writeNativeEvent(threadId, event).pipe(Effect.catchCause(() => Effect.void)); + + const emitUnexpectedExit = Effect.fn("emitUnexpectedExit")(function* ( + context: OpenCodeSessionContext, + message: string, + ) { + // Atomic one-shot: two fibers can race here (the event-pump on stream + // failure and the server-exit watcher). `getAndSet` flips the flag in + // a single step so the loser observes `true` and returns; a plain + // `Ref.get` would let both racers slip past and emit duplicates. + if (yield* Ref.getAndSet(context.stopped, true)) { + return; + } + const turnId = context.activeTurnId; + sessions.delete(context.session.threadId); + // Emit lifecycle events BEFORE tearing down the scope. Both call sites + // run this inside a fiber forked via `Effect.forkIn(context.sessionScope)`; + // closing that scope triggers the fiber-interrupt finalizer, so any + // subsequent yield point would unwind and silently drop these emits. + yield* emit({ + ...(yield* buildEventBase({ + threadId: context.session.threadId, + turnId, + })), + type: "runtime.error", + payload: { + message, + class: "transport_error", + }, + }).pipe(Effect.ignore); + yield* emit({ + ...(yield* buildEventBase({ + threadId: context.session.threadId, + turnId, + })), + type: "session.exited", + payload: { + reason: message, + recoverable: false, + exitKind: "error", + }, + }).pipe(Effect.ignore); + // Inline the teardown that `stopOpenCodeContext` would do; we can't + // delegate to it because our `getAndSet` above already flipped the + // one-shot guard, so the call would no-op. + yield* runOpenCodeSdk("session.abort", () => + context.client.session.abort({ sessionID: context.openCodeSessionId }), + ).pipe(Effect.ignore({ log: true })); + yield* Scope.close(context.sessionScope, Exit.void); + }); + + /** Emit content.delta and item.completed events for an assistant text part. */ + const emitAssistantTextDelta = Effect.fn("emitAssistantTextDelta")(function* ( + context: OpenCodeSessionContext, + part: Part, + turnId: TurnId | undefined, + raw: unknown, + ) { + const text = textFromPart(part); + if (text === undefined) { + return; + } + const previousText = context.emittedTextByPartId.get(part.id); + const { latestText, deltaToEmit } = mergeOpenCodeAssistantText(previousText, text); + context.emittedTextByPartId.set(part.id, latestText); + if (latestText !== text) { + context.partById.set( + part.id, + (part.type === "text" || part.type === "reasoning" + ? { ...part, text: latestText } + : part) satisfies Part, + ); + } + if (deltaToEmit.length > 0) { yield* emit({ - ...buildEventBase({ threadId: context.session.threadId, turnId }), - type: "runtime.error", + ...(yield* buildEventBase({ + threadId: context.session.threadId, + turnId, + itemId: part.id, + createdAt: + part.type === "text" || part.type === "reasoning" + ? isoFromEpochMs(part.time?.start) + : undefined, + raw, + })), + type: "content.delta", payload: { - message, - class: "transport_error", + streamKind: resolveTextStreamKind(part), + delta: deltaToEmit, }, - }).pipe(Effect.ignore); + }); + } + + if ( + part.type === "text" && + part.time?.end !== undefined && + !context.completedAssistantPartIds.has(part.id) + ) { + context.completedAssistantPartIds.add(part.id); yield* emit({ - ...buildEventBase({ threadId: context.session.threadId, turnId }), - type: "session.exited", + ...(yield* buildEventBase({ + threadId: context.session.threadId, + turnId, + itemId: part.id, + createdAt: isoFromEpochMs(part.time.end), + raw, + })), + type: "item.completed", payload: { - reason: message, - recoverable: false, - exitKind: "error", + itemType: "assistant_message", + status: "completed", + title: "Assistant message", + ...(latestText.length > 0 ? { detail: latestText } : {}), }, - }).pipe(Effect.ignore); - // Inline the teardown that `stopOpenCodeContext` would do; we can't - // delegate to it because our `getAndSet` above already flipped the - // one-shot guard, so the call would no-op. - yield* runOpenCodeSdk("session.abort", () => - context.client.session.abort({ sessionID: context.openCodeSessionId }), - ).pipe(Effect.ignore({ log: true })); - yield* Scope.close(context.sessionScope, Exit.void); + }); + } + }); + + const handleSubscribedEvent = Effect.fn("handleSubscribedEvent")(function* ( + context: OpenCodeSessionContext, + event: OpenCodeSubscribedEvent, + ) { + const payloadSessionId = + "properties" in event ? (event.properties as { sessionID?: unknown }).sessionID : undefined; + if (payloadSessionId !== context.openCodeSessionId) { + return; + } + + const turnId = context.activeTurnId; + yield* writeNativeEventBestEffort(context.session.threadId, { + observedAt: nowIso(), + event: { + provider: PROVIDER, + threadId: context.session.threadId, + providerThreadId: context.openCodeSessionId, + type: event.type, + ...(turnId ? { turnId } : {}), + payload: event, + }, }); - /** Emit content.delta and item.completed events for an assistant text part. */ - const emitAssistantTextDelta = Effect.fn("emitAssistantTextDelta")(function* ( - context: OpenCodeSessionContext, - part: Part, - turnId: TurnId | undefined, - raw: unknown, - ) { - const text = textFromPart(part); - if (text === undefined) { - return; + switch (event.type) { + case "message.updated": { + context.messageRoleById.set(event.properties.info.id, event.properties.info.role); + if (event.properties.info.role === "assistant") { + for (const part of context.partById.values()) { + if (part.messageID !== event.properties.info.id) { + continue; + } + yield* emitAssistantTextDelta(context, part, turnId, event); + } + } + break; } - const previousText = context.emittedTextByPartId.get(part.id); - const { latestText, deltaToEmit } = mergeOpenCodeAssistantText(previousText, text); - context.emittedTextByPartId.set(part.id, latestText); - if (latestText !== text) { - context.partById.set( - part.id, - (part.type === "text" || part.type === "reasoning" - ? { ...part, text: latestText } - : part) satisfies Part, - ); + + case "message.removed": { + context.messageRoleById.delete(event.properties.messageID); + break; } - if (deltaToEmit.length > 0) { + + case "message.part.delta": { + const existingPart = context.partById.get(event.properties.partID); + if (!existingPart) { + break; + } + const role = messageRoleForPart(context, existingPart); + if (role !== "assistant") { + break; + } + const streamKind = resolveTextStreamKind(existingPart); + const delta = event.properties.delta; + if (delta.length === 0) { + break; + } + const previousText = + context.emittedTextByPartId.get(event.properties.partID) ?? + textFromPart(existingPart) ?? + ""; + const { nextText, deltaToEmit } = appendOpenCodeAssistantTextDelta(previousText, delta); + if (deltaToEmit.length === 0) { + break; + } + context.emittedTextByPartId.set(event.properties.partID, nextText); + if (existingPart.type === "text" || existingPart.type === "reasoning") { + context.partById.set(event.properties.partID, { + ...existingPart, + text: nextText, + }); + } yield* emit({ - ...buildEventBase({ + ...(yield* buildEventBase({ threadId: context.session.threadId, turnId, - itemId: part.id, - createdAt: - part.type === "text" || part.type === "reasoning" - ? isoFromEpochMs(part.time?.start) - : undefined, - raw, - }), + itemId: event.properties.partID, + raw: event, + })), type: "content.delta", payload: { - streamKind: resolveTextStreamKind(part), + streamKind, delta: deltaToEmit, }, }); + break; } - if ( - part.type === "text" && - part.time?.end !== undefined && - !context.completedAssistantPartIds.has(part.id) - ) { - context.completedAssistantPartIds.add(part.id); + case "message.part.updated": { + const part = event.properties.part; + context.partById.set(part.id, part); + const messageRole = messageRoleForPart(context, part); + + if (messageRole === "assistant") { + yield* emitAssistantTextDelta(context, part, turnId, event); + } + + if (part.type === "tool") { + const itemType = toToolLifecycleItemType(part.tool); + const title = + part.state.status === "running" ? (part.state.title ?? part.tool) : part.tool; + const detail = detailFromToolPart(part); + const payload = { + itemType, + ...(part.state.status === "error" + ? { status: "failed" as const } + : part.state.status === "completed" + ? { status: "completed" as const } + : { status: "inProgress" as const }), + ...(title ? { title } : {}), + ...(detail ? { detail } : {}), + data: { + tool: part.tool, + state: part.state, + }, + }; + const runtimeEvent: ProviderRuntimeEvent = { + ...(yield* buildEventBase({ + threadId: context.session.threadId, + turnId, + itemId: part.callID, + createdAt: toolStateCreatedAt(part), + raw: event, + })), + type: + part.state.status === "pending" + ? "item.started" + : part.state.status === "completed" || part.state.status === "error" + ? "item.completed" + : "item.updated", + payload, + }; + appendTurnItem(context, turnId, part); + yield* emit(runtimeEvent); + } + break; + } + + case "permission.asked": { + context.pendingPermissions.set(event.properties.id, event.properties); yield* emit({ - ...buildEventBase({ + ...(yield* buildEventBase({ threadId: context.session.threadId, turnId, - itemId: part.id, - createdAt: isoFromEpochMs(part.time.end), - raw, - }), - type: "item.completed", + requestId: event.properties.id, + raw: event, + })), + type: "request.opened", payload: { - itemType: "assistant_message", - status: "completed", - title: "Assistant message", - ...(latestText.length > 0 ? { detail: latestText } : {}), + requestType: mapPermissionToRequestType(event.properties.permission), + detail: + event.properties.patterns.length > 0 + ? event.properties.patterns.join("\n") + : event.properties.permission, + args: event.properties.metadata, }, }); - } - }); - - const handleSubscribedEvent = Effect.fn("handleSubscribedEvent")(function* ( - context: OpenCodeSessionContext, - event: OpenCodeSubscribedEvent, - ) { - const payloadSessionId = - "properties" in event - ? (event.properties as { sessionID?: unknown }).sessionID - : undefined; - if (payloadSessionId !== context.openCodeSessionId) { - return; + break; } - const turnId = context.activeTurnId; - yield* writeNativeEventBestEffort(context.session.threadId, { - observedAt: nowIso(), - event: { - provider: PROVIDER, - threadId: context.session.threadId, - providerThreadId: context.openCodeSessionId, - type: event.type, - ...(turnId ? { turnId } : {}), - payload: event, - }, - }); + case "permission.replied": { + context.pendingPermissions.delete(event.properties.requestID); + yield* emit({ + ...(yield* buildEventBase({ + threadId: context.session.threadId, + turnId, + requestId: event.properties.requestID, + raw: event, + })), + type: "request.resolved", + payload: { + requestType: "unknown", + decision: mapPermissionDecision(event.properties.reply), + }, + }); + break; + } - switch (event.type) { - case "message.updated": { - context.messageRoleById.set(event.properties.info.id, event.properties.info.role); - if (event.properties.info.role === "assistant") { - for (const part of context.partById.values()) { - if (part.messageID !== event.properties.info.id) { - continue; - } - yield* emitAssistantTextDelta(context, part, turnId, event); - } - } - break; + case "question.asked": { + context.pendingQuestions.set(event.properties.id, event.properties); + yield* emit({ + ...(yield* buildEventBase({ + threadId: context.session.threadId, + turnId, + requestId: event.properties.id, + raw: event, + })), + type: "user-input.requested", + payload: { + questions: normalizeQuestionRequest(event.properties), + }, + }); + break; + } + + case "question.replied": { + const request = context.pendingQuestions.get(event.properties.requestID); + context.pendingQuestions.delete(event.properties.requestID); + const answers = Object.fromEntries( + (request?.questions ?? []).map((question, index) => [ + openCodeQuestionId(index, question), + event.properties.answers[index]?.join(", ") ?? "", + ]), + ); + yield* emit({ + ...(yield* buildEventBase({ + threadId: context.session.threadId, + turnId, + requestId: event.properties.requestID, + raw: event, + })), + type: "user-input.resolved", + payload: { answers }, + }); + break; + } + + case "question.rejected": { + context.pendingQuestions.delete(event.properties.requestID); + yield* emit({ + ...(yield* buildEventBase({ + threadId: context.session.threadId, + turnId, + requestId: event.properties.requestID, + raw: event, + })), + type: "user-input.resolved", + payload: { answers: {} }, + }); + break; + } + + case "session.status": { + if (event.properties.status.type === "busy") { + updateProviderSession(context, { + status: "running", + activeTurnId: turnId, + }); } - case "message.removed": { - context.messageRoleById.delete(event.properties.messageID); - break; - } - - case "message.part.delta": { - const existingPart = context.partById.get(event.properties.partID); - if (!existingPart) { - break; - } - const role = messageRoleForPart(context, existingPart); - if (role !== "assistant") { - break; - } - const streamKind = resolveTextStreamKind(existingPart); - const delta = event.properties.delta; - if (delta.length === 0) { - break; - } - const previousText = - context.emittedTextByPartId.get(event.properties.partID) ?? - textFromPart(existingPart) ?? - ""; - const { nextText, deltaToEmit } = appendOpenCodeAssistantTextDelta(previousText, delta); - if (deltaToEmit.length === 0) { - break; - } - context.emittedTextByPartId.set(event.properties.partID, nextText); - if (existingPart.type === "text" || existingPart.type === "reasoning") { - context.partById.set(event.properties.partID, { - ...existingPart, - text: nextText, - }); - } + if (event.properties.status.type === "retry") { yield* emit({ - ...buildEventBase({ + ...(yield* buildEventBase({ threadId: context.session.threadId, turnId, - itemId: event.properties.partID, raw: event, - }), - type: "content.delta", + })), + type: "runtime.warning", payload: { - streamKind, - delta: deltaToEmit, + message: event.properties.status.message, + detail: event.properties.status, }, }); break; } - case "message.part.updated": { - const part = event.properties.part; - context.partById.set(part.id, part); - const messageRole = messageRoleForPart(context, part); - - if (messageRole === "assistant") { - yield* emitAssistantTextDelta(context, part, turnId, event); - } - - if (part.type === "tool") { - const itemType = toToolLifecycleItemType(part.tool); - const title = - part.state.status === "running" ? (part.state.title ?? part.tool) : part.tool; - const detail = detailFromToolPart(part); - const payload = { - itemType, - ...(part.state.status === "error" - ? { status: "failed" as const } - : part.state.status === "completed" - ? { status: "completed" as const } - : { status: "inProgress" as const }), - ...(title ? { title } : {}), - ...(detail ? { detail } : {}), - data: { - tool: part.tool, - state: part.state, - }, - }; - const runtimeEvent: ProviderRuntimeEvent = { - ...buildEventBase({ - threadId: context.session.threadId, - turnId, - itemId: part.callID, - createdAt: toolStateCreatedAt(part), - raw: event, - }), - type: - part.state.status === "pending" - ? "item.started" - : part.state.status === "completed" || part.state.status === "error" - ? "item.completed" - : "item.updated", - payload, - }; - appendTurnItem(context, turnId, part); - yield* emit(runtimeEvent); - } - break; - } - - case "permission.asked": { - context.pendingPermissions.set(event.properties.id, event.properties); - yield* emit({ - ...buildEventBase({ - threadId: context.session.threadId, - turnId, - requestId: event.properties.id, - raw: event, - }), - type: "request.opened", - payload: { - requestType: mapPermissionToRequestType(event.properties.permission), - detail: - event.properties.patterns.length > 0 - ? event.properties.patterns.join("\n") - : event.properties.permission, - args: event.properties.metadata, - }, - }); - break; - } - - case "permission.replied": { - context.pendingPermissions.delete(event.properties.requestID); - yield* emit({ - ...buildEventBase({ - threadId: context.session.threadId, - turnId, - requestId: event.properties.requestID, - raw: event, - }), - type: "request.resolved", - payload: { - requestType: "unknown", - decision: mapPermissionDecision(event.properties.reply), - }, - }); - break; - } - - case "question.asked": { - context.pendingQuestions.set(event.properties.id, event.properties); - yield* emit({ - ...buildEventBase({ - threadId: context.session.threadId, - turnId, - requestId: event.properties.id, - raw: event, - }), - type: "user-input.requested", - payload: { - questions: normalizeQuestionRequest(event.properties), - }, - }); - break; - } - - case "question.replied": { - const request = context.pendingQuestions.get(event.properties.requestID); - context.pendingQuestions.delete(event.properties.requestID); - const answers = Object.fromEntries( - (request?.questions ?? []).map((question, index) => [ - openCodeQuestionId(index, question), - event.properties.answers[index]?.join(", ") ?? "", - ]), - ); - yield* emit({ - ...buildEventBase({ - threadId: context.session.threadId, - turnId, - requestId: event.properties.requestID, - raw: event, - }), - type: "user-input.resolved", - payload: { answers }, - }); - break; - } - - case "question.rejected": { - context.pendingQuestions.delete(event.properties.requestID); - yield* emit({ - ...buildEventBase({ - threadId: context.session.threadId, - turnId, - requestId: event.properties.requestID, - raw: event, - }), - type: "user-input.resolved", - payload: { answers: {} }, - }); - break; - } - - case "session.status": { - if (event.properties.status.type === "busy") { - updateProviderSession(context, { status: "running", activeTurnId: turnId }); - } - - if (event.properties.status.type === "retry") { - yield* emit({ - ...buildEventBase({ threadId: context.session.threadId, turnId, raw: event }), - type: "runtime.warning", - payload: { - message: event.properties.status.message, - detail: event.properties.status, - }, - }); - break; - } - - if (event.properties.status.type === "idle" && turnId) { - context.activeTurnId = undefined; - updateProviderSession(context, { status: "ready" }, { clearActiveTurnId: true }); - yield* emit({ - ...buildEventBase({ threadId: context.session.threadId, turnId, raw: event }), - type: "turn.completed", - payload: { - state: "completed", - }, - }); - } - break; - } - - case "session.error": { - const message = sessionErrorMessage(event.properties.error); - const activeTurnId = context.activeTurnId; + if (event.properties.status.type === "idle" && turnId) { context.activeTurnId = undefined; - updateProviderSession( - context, - { - status: "error", - lastError: message, - }, - { clearActiveTurnId: true }, - ); - if (activeTurnId) { - yield* emit({ - ...buildEventBase({ - threadId: context.session.threadId, - turnId: activeTurnId, - raw: event, - }), - type: "turn.completed", - payload: { - state: "failed", - errorMessage: message, - }, - }); - } + updateProviderSession(context, { status: "ready" }, { clearActiveTurnId: true }); yield* emit({ - ...buildEventBase({ threadId: context.session.threadId, raw: event }), - type: "runtime.error", + ...(yield* buildEventBase({ + threadId: context.session.threadId, + turnId, + raw: event, + })), + type: "turn.completed", payload: { - message, - class: "provider_error", - detail: event.properties.error, + state: "completed", }, }); - break; } - - default: - break; + break; } - }); - const startEventPump = Effect.fn("startEventPump")(function* ( - context: OpenCodeSessionContext, - ) { - // One AbortController per session scope. The finalizer fires when - // the scope closes (explicit stop, unexpected exit, or layer - // shutdown) and cancels the in-flight `event.subscribe` fetch so - // the async iterable unwinds cleanly. - const eventsAbortController = new AbortController(); - yield* Scope.addFinalizer( - context.sessionScope, - Effect.sync(() => eventsAbortController.abort()), - ); + case "session.error": { + const message = sessionErrorMessage(event.properties.error); + const activeTurnId = context.activeTurnId; + context.activeTurnId = undefined; + updateProviderSession( + context, + { + status: "error", + lastError: message, + }, + { clearActiveTurnId: true }, + ); + if (activeTurnId) { + yield* emit({ + ...(yield* buildEventBase({ + threadId: context.session.threadId, + turnId: activeTurnId, + raw: event, + })), + type: "turn.completed", + payload: { + state: "failed", + errorMessage: message, + }, + }); + } + yield* emit({ + ...(yield* buildEventBase({ + threadId: context.session.threadId, + raw: event, + })), + type: "runtime.error", + payload: { + message, + class: "provider_error", + detail: event.properties.error, + }, + }); + break; + } - // Fibers forked into `context.sessionScope` are interrupted - // automatically when the scope closes — no bookkeeping required. - yield* Effect.flatMap( - runOpenCodeSdk("event.subscribe", () => - context.client.event.subscribe(undefined, { - signal: eventsAbortController.signal, - }), - ), - (subscription) => - Stream.fromAsyncIterable( - subscription.stream, - (cause) => - new OpenCodeRuntimeError({ - operation: "event.subscribe", - detail: openCodeRuntimeErrorDetail(cause), - cause, - }), - ).pipe(Stream.runForEach((event) => handleSubscribedEvent(context, event))), - ).pipe( - Effect.exit, - Effect.flatMap((exit) => + default: + break; + } + }); + + const startEventPump = Effect.fn("startEventPump")(function* (context: OpenCodeSessionContext) { + // One AbortController per session scope. The finalizer fires when + // the scope closes (explicit stop, unexpected exit, or layer + // shutdown) and cancels the in-flight `event.subscribe` fetch so + // the async iterable unwinds cleanly. + const eventsAbortController = new AbortController(); + yield* Scope.addFinalizer( + context.sessionScope, + Effect.sync(() => eventsAbortController.abort()), + ); + + // Fibers forked into `context.sessionScope` are interrupted + // automatically when the scope closes — no bookkeeping required. + yield* Effect.flatMap( + runOpenCodeSdk("event.subscribe", () => + context.client.event.subscribe(undefined, { + signal: eventsAbortController.signal, + }), + ), + (subscription) => + Stream.fromAsyncIterable( + subscription.stream, + (cause) => + new OpenCodeRuntimeError({ + operation: "event.subscribe", + detail: openCodeRuntimeErrorDetail(cause), + cause, + }), + ).pipe(Stream.runForEach((event) => handleSubscribedEvent(context, event))), + ).pipe( + Effect.exit, + Effect.flatMap((exit) => + Effect.gen(function* () { + // Expected paths: caller aborted the fetch or the session + // has already been marked stopped. Treat as a clean exit. + if (eventsAbortController.signal.aborted || (yield* Ref.get(context.stopped))) { + return; + } + if (Exit.isFailure(exit)) { + yield* emitUnexpectedExit( + context, + openCodeRuntimeErrorDetail(Cause.squash(exit.cause)), + ); + } + }), + ), + Effect.forkIn(context.sessionScope), + ); + + if (!context.server.external && context.server.exitCode !== null) { + yield* context.server.exitCode.pipe( + Effect.flatMap((code) => Effect.gen(function* () { - // Expected paths: caller aborted the fetch or the session - // has already been marked stopped. Treat as a clean exit. - if (eventsAbortController.signal.aborted || (yield* Ref.get(context.stopped))) { + if (yield* Ref.get(context.stopped)) { return; } - if (Exit.isFailure(exit)) { - yield* emitUnexpectedExit( - context, - openCodeRuntimeErrorDetail(Cause.squash(exit.cause)), - ); - } + yield* emitUnexpectedExit(context, `OpenCode server exited unexpectedly (${code}).`); }), ), Effect.forkIn(context.sessionScope), ); + } + }); - if (!context.server.external && context.server.exitCode !== null) { - yield* context.server.exitCode.pipe( - Effect.flatMap((code) => - Effect.gen(function* () { - if (yield* Ref.get(context.stopped)) { - return; - } - yield* emitUnexpectedExit( - context, - `OpenCode server exited unexpectedly (${code}).`, - ); - }), - ), - Effect.forkIn(context.sessionScope), - ); + const startSession: OpenCodeAdapterShape["startSession"] = Effect.fn("startSession")( + function* (input) { + const binaryPath = openCodeSettings.binaryPath; + const serverUrl = openCodeSettings.serverUrl; + const serverPassword = openCodeSettings.serverPassword; + const directory = input.cwd ?? serverConfig.cwd; + const existing = sessions.get(input.threadId); + if (existing) { + yield* stopOpenCodeContext(existing); + sessions.delete(input.threadId); } - }); - const startSession: OpenCodeAdapterShape["startSession"] = Effect.fn("startSession")( - function* (input) { - const settings = yield* serverSettings.getSettings.pipe( - Effect.mapError( - (cause) => - new ProviderAdapterProcessError({ - provider: PROVIDER, - threadId: input.threadId, - detail: "Failed to read OpenCode settings.", - cause, + const started = yield* Effect.gen(function* () { + const sessionScope = yield* Scope.make(); + const startedExit = yield* Effect.exit( + Effect.gen(function* () { + // The runtime binds the server's lifetime to the Scope.Scope + // we provide below — closing `sessionScope` kills the child + // process automatically. No manual `server.close()` needed. + const server = yield* openCodeRuntime.connectToOpenCodeServer({ + binaryPath, + serverUrl, + ...(options?.environment ? { environment: options.environment } : {}), + }); + const client = openCodeRuntime.createOpenCodeSdkClient({ + baseUrl: server.url, + directory, + ...(server.external && serverPassword ? { serverPassword } : {}), + }); + const openCodeSession = yield* runOpenCodeSdk("session.create", () => + client.session.create({ + title: `T3 Code ${input.threadId}`, + permission: buildOpenCodePermissionRules(input.runtimeMode), }), - ), + ); + if (!openCodeSession.data) { + return yield* new OpenCodeRuntimeError({ + operation: "session.create", + detail: "OpenCode session.create returned no session payload.", + }); + } + return { + sessionScope, + server, + client, + openCodeSession: openCodeSession.data, + }; + }).pipe(Effect.provideService(Scope.Scope, sessionScope)), ); - const binaryPath = settings.providers.opencode.binaryPath; - const serverUrl = settings.providers.opencode.serverUrl; - const serverPassword = settings.providers.opencode.serverPassword; - const directory = input.cwd ?? serverConfig.cwd; - const existing = sessions.get(input.threadId); - if (existing) { - yield* stopOpenCodeContext(existing); - sessions.delete(input.threadId); + if (Exit.isFailure(startedExit)) { + yield* Scope.close(sessionScope, Exit.void).pipe(Effect.ignore); + return yield* toProcessError(input.threadId, Cause.squash(startedExit.cause)); } - - const started = yield* Effect.gen(function* () { - const sessionScope = yield* Scope.make(); - const startedExit = yield* Effect.exit( - Effect.gen(function* () { - // The runtime binds the server's lifetime to the Scope.Scope - // we provide below — closing `sessionScope` kills the child - // process automatically. No manual `server.close()` needed. - const server = yield* openCodeRuntime.connectToOpenCodeServer({ - binaryPath, - serverUrl, - }); - const client = openCodeRuntime.createOpenCodeSdkClient({ - baseUrl: server.url, - directory, - ...(server.external && serverPassword ? { serverPassword } : {}), - }); - const openCodeSession = yield* runOpenCodeSdk("session.create", () => - client.session.create({ - title: `T3 Code ${input.threadId}`, - permission: buildOpenCodePermissionRules(input.runtimeMode), - }), - ); - if (!openCodeSession.data) { - return yield* new OpenCodeRuntimeError({ - operation: "session.create", - detail: "OpenCode session.create returned no session payload.", - }); - } - return { sessionScope, server, client, openCodeSession: openCodeSession.data }; - }).pipe(Effect.provideService(Scope.Scope, sessionScope)), - ); - if (Exit.isFailure(startedExit)) { - yield* Scope.close(sessionScope, Exit.void).pipe(Effect.ignore); - return yield* toProcessError(input.threadId, Cause.squash(startedExit.cause)); - } - return startedExit.value; - }); - - // Guard against a concurrent startSession call that may have raced - // and already inserted a session while we were awaiting async work. - const raceWinner = sessions.get(input.threadId); - if (raceWinner) { - // Another call won the race – clean up the session we just created - // (including the remote SDK session) and return the existing one. - yield* runOpenCodeSdk("session.abort", () => - started.client.session.abort({ sessionID: started.openCodeSession.id }), - ).pipe(Effect.ignore); - yield* Scope.close(started.sessionScope, Exit.void).pipe(Effect.ignore); - return raceWinner.session; - } - - const createdAt = nowIso(); - const session: ProviderSession = { - provider: PROVIDER, - status: "ready", - runtimeMode: input.runtimeMode, - cwd: directory, - ...(input.modelSelection ? { model: input.modelSelection.model } : {}), - threadId: input.threadId, - createdAt, - updatedAt: createdAt, - }; - - const context: OpenCodeSessionContext = { - session, - client: started.client, - server: started.server, - directory, - openCodeSessionId: started.openCodeSession.id, - pendingPermissions: new Map(), - pendingQuestions: new Map(), - partById: new Map(), - emittedTextByPartId: new Map(), - messageRoleById: new Map(), - completedAssistantPartIds: new Set(), - turns: [], - activeTurnId: undefined, - activeAgent: undefined, - activeVariant: undefined, - stopped: yield* Ref.make(false), - sessionScope: started.sessionScope, - }; - sessions.set(input.threadId, context); - yield* startEventPump(context); - - yield* emit({ - ...buildEventBase({ threadId: input.threadId }), - type: "session.started", - payload: { - message: "OpenCode session started", - }, - }); - yield* emit({ - ...buildEventBase({ threadId: input.threadId }), - type: "thread.started", - payload: { - providerThreadId: started.openCodeSession.id, - }, - }); - - return session; - }, - ); - - const sendTurn: OpenCodeAdapterShape["sendTurn"] = Effect.fn("sendTurn")(function* (input) { - const context = ensureSessionContext(sessions, input.threadId); - const turnId = TurnId.make(`opencode-turn-${randomUUID()}`); - const modelSelection = - input.modelSelection ?? - (context.session.model - ? { provider: PROVIDER, model: context.session.model } - : undefined); - const parsedModel = parseOpenCodeModelSlug(modelSelection?.model); - if (!parsedModel) { - return yield* new ProviderAdapterValidationError({ - provider: PROVIDER, - operation: "sendTurn", - issue: "OpenCode model selection must use the 'provider/model' format.", - }); - } - - const text = input.input?.trim(); - const fileParts = toOpenCodeFileParts({ - attachments: input.attachments, - resolveAttachmentPath: (attachment) => - resolveAttachmentPath({ attachmentsDir: serverConfig.attachmentsDir, attachment }), + return startedExit.value; }); - if ((!text || text.length === 0) && fileParts.length === 0) { - return yield* new ProviderAdapterValidationError({ - provider: PROVIDER, - operation: "sendTurn", - issue: "OpenCode turns require text input or at least one attachment.", - }); + + // Guard against a concurrent startSession call that may have raced + // and already inserted a session while we were awaiting async work. + const raceWinner = sessions.get(input.threadId); + if (raceWinner) { + // Another call won the race – clean up the session we just created + // (including the remote SDK session) and return the existing one. + yield* runOpenCodeSdk("session.abort", () => + started.client.session.abort({ + sessionID: started.openCodeSession.id, + }), + ).pipe(Effect.ignore); + yield* Scope.close(started.sessionScope, Exit.void).pipe(Effect.ignore); + return raceWinner.session; } - const agent = - input.modelSelection?.provider === PROVIDER - ? getModelSelectionStringOptionValue(input.modelSelection, "agent") - : undefined; - const variant = - input.modelSelection?.provider === PROVIDER - ? getModelSelectionStringOptionValue(input.modelSelection, "variant") - : undefined; + const createdAt = nowIso(); + const session: ProviderSession = { + provider: PROVIDER, + providerInstanceId: boundInstanceId, + status: "ready", + runtimeMode: input.runtimeMode, + cwd: directory, + ...(input.modelSelection ? { model: input.modelSelection.model } : {}), + threadId: input.threadId, + createdAt, + updatedAt: createdAt, + }; - context.activeTurnId = turnId; - context.activeAgent = agent ?? (input.interactionMode === "plan" ? "plan" : undefined); - context.activeVariant = variant; - updateProviderSession( - context, - { - status: "running", - activeTurnId: turnId, - model: modelSelection?.model ?? context.session.model, - }, - { clearLastError: true }, - ); + const context: OpenCodeSessionContext = { + session, + client: started.client, + server: started.server, + directory, + openCodeSessionId: started.openCodeSession.id, + pendingPermissions: new Map(), + pendingQuestions: new Map(), + partById: new Map(), + emittedTextByPartId: new Map(), + messageRoleById: new Map(), + completedAssistantPartIds: new Set(), + turns: [], + activeTurnId: undefined, + activeAgent: undefined, + activeVariant: undefined, + stopped: yield* Ref.make(false), + sessionScope: started.sessionScope, + }; + sessions.set(input.threadId, context); + yield* startEventPump(context); yield* emit({ - ...buildEventBase({ threadId: input.threadId, turnId }), - type: "turn.started", + ...(yield* buildEventBase({ threadId: input.threadId })), + type: "session.started", payload: { - model: modelSelection?.model ?? context.session.model, - ...(variant ? { effort: variant } : {}), + message: "OpenCode session started", + }, + }); + yield* emit({ + ...(yield* buildEventBase({ threadId: input.threadId })), + type: "thread.started", + payload: { + providerThreadId: started.openCodeSession.id, }, }); - yield* runOpenCodeSdk("session.promptAsync", () => - context.client.session.promptAsync({ - sessionID: context.openCodeSessionId, - model: parsedModel, - ...(context.activeAgent ? { agent: context.activeAgent } : {}), - ...(context.activeVariant ? { variant: context.activeVariant } : {}), - parts: [...(text ? [{ type: "text" as const, text }] : []), ...fileParts], - }), - ).pipe( - Effect.mapError(toRequestError), - // On failure: clear active-turn state, flip the session back to ready - // with lastError set, emit turn.aborted, then let the typed error - // propagate. We don't need to rebuild the error here — `toRequestError` - // already produced the right shape. - Effect.tapError((requestError) => - Effect.gen(function* () { - context.activeTurnId = undefined; - context.activeAgent = undefined; - context.activeVariant = undefined; - updateProviderSession( - context, - { - status: "ready", - model: modelSelection?.model ?? context.session.model, - lastError: requestError.detail, - }, - { clearActiveTurnId: true }, - ); - yield* emit({ - ...buildEventBase({ threadId: input.threadId, turnId }), - type: "turn.aborted", - payload: { - reason: requestError.detail, - }, - }); - }), - ), - ); + return session; + }, + ); - return { - threadId: input.threadId, - turnId, - }; + const sendTurn: OpenCodeAdapterShape["sendTurn"] = Effect.fn("sendTurn")(function* (input) { + const context = ensureSessionContext(sessions, input.threadId); + const turnId = TurnId.make(`opencode-turn-${yield* Random.nextUUIDv4}`); + const modelSelection = + input.modelSelection ?? + (context.session.model + ? { instanceId: boundInstanceId, model: context.session.model } + : undefined); + if (modelSelection !== undefined && modelSelection.instanceId !== boundInstanceId) { + return yield* new ProviderAdapterValidationError({ + provider: PROVIDER, + operation: "sendTurn", + issue: `OpenCode model selection is bound to instance '${modelSelection?.instanceId}', expected '${boundInstanceId}'.`, + }); + } + const parsedModel = parseOpenCodeModelSlug(modelSelection?.model); + if (!parsedModel) { + return yield* new ProviderAdapterValidationError({ + provider: PROVIDER, + operation: "sendTurn", + issue: "OpenCode model selection must use the 'provider/model' format.", + }); + } + + const text = input.input?.trim(); + const fileParts = toOpenCodeFileParts({ + attachments: input.attachments, + resolveAttachmentPath: (attachment) => + resolveAttachmentPath({ + attachmentsDir: serverConfig.attachmentsDir, + attachment, + }), + }); + if ((!text || text.length === 0) && fileParts.length === 0) { + return yield* new ProviderAdapterValidationError({ + provider: PROVIDER, + operation: "sendTurn", + issue: "OpenCode turns require text input or at least one attachment.", + }); + } + + const agent = getModelSelectionStringOptionValue(modelSelection, "agent"); + const variant = getModelSelectionStringOptionValue(modelSelection, "variant"); + + context.activeTurnId = turnId; + context.activeAgent = agent ?? (input.interactionMode === "plan" ? "plan" : undefined); + context.activeVariant = variant; + updateProviderSession( + context, + { + status: "running", + activeTurnId: turnId, + model: modelSelection?.model ?? context.session.model, + }, + { clearLastError: true }, + ); + + yield* emit({ + ...(yield* buildEventBase({ threadId: input.threadId, turnId })), + type: "turn.started", + payload: { + model: modelSelection?.model ?? context.session.model, + ...(variant ? { effort: variant } : {}), + }, }); - const interruptTurn: OpenCodeAdapterShape["interruptTurn"] = Effect.fn("interruptTurn")( - function* (threadId, turnId) { - const context = ensureSessionContext(sessions, threadId); - yield* runOpenCodeSdk("session.abort", () => - context.client.session.abort({ sessionID: context.openCodeSessionId }), - ).pipe(Effect.mapError(toRequestError)); - if (turnId ?? context.activeTurnId) { + yield* runOpenCodeSdk("session.promptAsync", () => + context.client.session.promptAsync({ + sessionID: context.openCodeSessionId, + model: parsedModel, + ...(context.activeAgent ? { agent: context.activeAgent } : {}), + ...(context.activeVariant ? { variant: context.activeVariant } : {}), + parts: [...(text ? [{ type: "text" as const, text }] : []), ...fileParts], + }), + ).pipe( + Effect.mapError(toRequestError), + // On failure: clear active-turn state, flip the session back to ready + // with lastError set, emit turn.aborted, then let the typed error + // propagate. We don't need to rebuild the error here — `toRequestError` + // already produced the right shape. + Effect.tapError((requestError) => + Effect.gen(function* () { + context.activeTurnId = undefined; + context.activeAgent = undefined; + context.activeVariant = undefined; + updateProviderSession( + context, + { + status: "ready", + model: modelSelection?.model ?? context.session.model, + lastError: requestError.detail, + }, + { clearActiveTurnId: true }, + ); yield* emit({ - ...buildEventBase({ threadId, turnId: turnId ?? context.activeTurnId }), + ...(yield* buildEventBase({ + threadId: input.threadId, + turnId, + })), type: "turn.aborted", payload: { - reason: "Interrupted by user.", + reason: requestError.detail, }, }); - } - }, - ); - - const respondToRequest: OpenCodeAdapterShape["respondToRequest"] = Effect.fn( - "respondToRequest", - )(function* (threadId, requestId, decision) { - const context = ensureSessionContext(sessions, threadId); - if (!context.pendingPermissions.has(requestId)) { - return yield* new ProviderAdapterRequestError({ - provider: PROVIDER, - method: "permission.reply", - detail: `Unknown pending permission request: ${requestId}`, - }); - } - - yield* runOpenCodeSdk("permission.reply", () => - context.client.permission.reply({ - requestID: requestId, - reply: toOpenCodePermissionReply(decision), }), - ).pipe(Effect.mapError(toRequestError)); - }); - - const respondToUserInput: OpenCodeAdapterShape["respondToUserInput"] = Effect.fn( - "respondToUserInput", - )(function* (threadId, requestId, answers) { - const context = ensureSessionContext(sessions, threadId); - const request = context.pendingQuestions.get(requestId); - if (!request) { - return yield* new ProviderAdapterRequestError({ - provider: PROVIDER, - method: "question.reply", - detail: `Unknown pending user-input request: ${requestId}`, - }); - } - - yield* runOpenCodeSdk("question.reply", () => - context.client.question.reply({ - requestID: requestId, - answers: toOpenCodeQuestionAnswers(request, answers), - }), - ).pipe(Effect.mapError(toRequestError)); - }); - - const stopSession: OpenCodeAdapterShape["stopSession"] = Effect.fn("stopSession")( - function* (threadId) { - const context = ensureSessionContext(sessions, threadId); - yield* stopOpenCodeContext(context); - sessions.delete(threadId); - yield* emit({ - ...buildEventBase({ threadId }), - type: "session.exited", - payload: { - reason: "Session stopped.", - recoverable: false, - exitKind: "graceful", - }, - }); - }, + ), ); - const listSessions: OpenCodeAdapterShape["listSessions"] = () => - Effect.sync(() => [...sessions.values()].map((context) => context.session)); - - const hasSession: OpenCodeAdapterShape["hasSession"] = (threadId) => - Effect.sync(() => sessions.has(threadId)); - - const readThread: OpenCodeAdapterShape["readThread"] = Effect.fn("readThread")( - function* (threadId) { - const context = ensureSessionContext(sessions, threadId); - const messages = yield* runOpenCodeSdk("session.messages", () => - context.client.session.messages({ sessionID: context.openCodeSessionId }), - ).pipe(Effect.mapError(toRequestError)); - - const turns = (messages.data ?? []) - .filter((entry) => entry.info.role === "assistant") - .map((entry) => ({ - id: TurnId.make(entry.info.id), - items: [entry.info, ...entry.parts], - })); - - return { - threadId, - turns, - }; - }, - ); - - const rollbackThread: OpenCodeAdapterShape["rollbackThread"] = Effect.fn("rollbackThread")( - function* (threadId, numTurns) { - const context = ensureSessionContext(sessions, threadId); - const messages = yield* runOpenCodeSdk("session.messages", () => - context.client.session.messages({ sessionID: context.openCodeSessionId }), - ).pipe(Effect.mapError(toRequestError)); - - const assistantMessages = (messages.data ?? []).filter( - (entry) => entry.info.role === "assistant", - ); - const targetIndex = assistantMessages.length - numTurns - 1; - const target = targetIndex >= 0 ? assistantMessages[targetIndex] : null; - yield* runOpenCodeSdk("session.revert", () => - context.client.session.revert({ - sessionID: context.openCodeSessionId, - ...(target ? { messageID: target.info.id } : {}), - }), - ).pipe(Effect.mapError(toRequestError)); - - return yield* readThread(threadId); - }, - ); - - const stopAll: OpenCodeAdapterShape["stopAll"] = () => - Effect.gen(function* () { - const contexts = [...sessions.values()]; - sessions.clear(); - // `stopOpenCodeContext` is typed as never-failing — SDK aborts are - // already `Effect.ignore`'d inside it. `ignoreCause` here also - // swallows defects from throwing finalizers so one bad close can't - // interrupt the sibling fibers. Same pattern as the layer finalizer. - yield* Effect.forEach( - contexts, - (context) => Effect.ignoreCause(stopOpenCodeContext(context)), - { concurrency: "unbounded", discard: true }, - ); - }); - return { - provider: PROVIDER, - capabilities: { - sessionModelSwitch: "in-session", - }, - startSession, - sendTurn, - interruptTurn, - respondToRequest, - respondToUserInput, - stopSession, - listSessions, - hasSession, - readThread, - rollbackThread, - stopAll, - get streamEvents() { - return Stream.fromQueue(runtimeEvents); - }, - } satisfies OpenCodeAdapterShape; - }), - ); -} + threadId: input.threadId, + turnId, + }; + }); -export const OpenCodeAdapterLive = makeOpenCodeAdapterLive(); + const interruptTurn: OpenCodeAdapterShape["interruptTurn"] = Effect.fn("interruptTurn")( + function* (threadId, turnId) { + const context = ensureSessionContext(sessions, threadId); + yield* runOpenCodeSdk("session.abort", () => + context.client.session.abort({ sessionID: context.openCodeSessionId }), + ).pipe(Effect.mapError(toRequestError)); + if (turnId ?? context.activeTurnId) { + yield* emit({ + ...(yield* buildEventBase({ + threadId, + turnId: turnId ?? context.activeTurnId, + })), + type: "turn.aborted", + payload: { + reason: "Interrupted by user.", + }, + }); + } + }, + ); + + const respondToRequest: OpenCodeAdapterShape["respondToRequest"] = Effect.fn( + "respondToRequest", + )(function* (threadId, requestId, decision) { + const context = ensureSessionContext(sessions, threadId); + if (!context.pendingPermissions.has(requestId)) { + return yield* new ProviderAdapterRequestError({ + provider: PROVIDER, + method: "permission.reply", + detail: `Unknown pending permission request: ${requestId}`, + }); + } + + yield* runOpenCodeSdk("permission.reply", () => + context.client.permission.reply({ + requestID: requestId, + reply: toOpenCodePermissionReply(decision), + }), + ).pipe(Effect.mapError(toRequestError)); + }); + + const respondToUserInput: OpenCodeAdapterShape["respondToUserInput"] = Effect.fn( + "respondToUserInput", + )(function* (threadId, requestId, answers) { + const context = ensureSessionContext(sessions, threadId); + const request = context.pendingQuestions.get(requestId); + if (!request) { + return yield* new ProviderAdapterRequestError({ + provider: PROVIDER, + method: "question.reply", + detail: `Unknown pending user-input request: ${requestId}`, + }); + } + + yield* runOpenCodeSdk("question.reply", () => + context.client.question.reply({ + requestID: requestId, + answers: toOpenCodeQuestionAnswers(request, answers), + }), + ).pipe(Effect.mapError(toRequestError)); + }); + + const stopSession: OpenCodeAdapterShape["stopSession"] = Effect.fn("stopSession")( + function* (threadId) { + const context = sessions.get(threadId); + if (!context) { + throw new ProviderAdapterSessionNotFoundError({ + provider: PROVIDER, + threadId, + }); + } + const stopped = yield* stopOpenCodeContext(context); + sessions.delete(threadId); + if (!stopped) { + return; + } + yield* emit({ + ...(yield* buildEventBase({ threadId })), + type: "session.exited", + payload: { + reason: "Session stopped.", + recoverable: false, + exitKind: "graceful", + }, + }); + }, + ); + + const listSessions: OpenCodeAdapterShape["listSessions"] = () => + Effect.sync(() => [...sessions.values()].map((context) => context.session)); + + const hasSession: OpenCodeAdapterShape["hasSession"] = (threadId) => + Effect.sync(() => sessions.has(threadId)); + + const readThread: OpenCodeAdapterShape["readThread"] = Effect.fn("readThread")( + function* (threadId) { + const context = ensureSessionContext(sessions, threadId); + const messages = yield* runOpenCodeSdk("session.messages", () => + context.client.session.messages({ + sessionID: context.openCodeSessionId, + }), + ).pipe(Effect.mapError(toRequestError)); + + const turns = (messages.data ?? []) + .filter((entry) => entry.info.role === "assistant") + .map((entry) => ({ + id: TurnId.make(entry.info.id), + items: [entry.info, ...entry.parts], + })); + + return { + threadId, + turns, + }; + }, + ); + + const rollbackThread: OpenCodeAdapterShape["rollbackThread"] = Effect.fn("rollbackThread")( + function* (threadId, numTurns) { + const context = ensureSessionContext(sessions, threadId); + const messages = yield* runOpenCodeSdk("session.messages", () => + context.client.session.messages({ + sessionID: context.openCodeSessionId, + }), + ).pipe(Effect.mapError(toRequestError)); + + const assistantMessages = (messages.data ?? []).filter( + (entry) => entry.info.role === "assistant", + ); + const targetIndex = assistantMessages.length - numTurns - 1; + const target = targetIndex >= 0 ? assistantMessages[targetIndex] : null; + yield* runOpenCodeSdk("session.revert", () => + context.client.session.revert({ + sessionID: context.openCodeSessionId, + ...(target ? { messageID: target.info.id } : {}), + }), + ).pipe(Effect.mapError(toRequestError)); + + return yield* readThread(threadId); + }, + ); + + const stopAll: OpenCodeAdapterShape["stopAll"] = () => + Effect.gen(function* () { + const contexts = [...sessions.values()]; + sessions.clear(); + // `stopOpenCodeContext` is typed as never-failing — SDK aborts are + // already `Effect.ignore`'d inside it. `ignoreCause` here also + // swallows defects from throwing finalizers so one bad close can't + // interrupt the sibling fibers. Same pattern as the layer finalizer. + yield* Effect.forEach( + contexts, + (context) => Effect.ignoreCause(stopOpenCodeContext(context)), + { concurrency: "unbounded", discard: true }, + ); + }); + + return { + provider: PROVIDER, + capabilities: { + sessionModelSwitch: "in-session", + }, + startSession, + sendTurn, + interruptTurn, + respondToRequest, + respondToUserInput, + stopSession, + listSessions, + hasSession, + readThread, + rollbackThread, + stopAll, + get streamEvents() { + return Stream.fromQueue(runtimeEvents); + }, + } satisfies OpenCodeAdapterShape; + }); +} diff --git a/apps/server/src/provider/Layers/OpenCodeProvider.test.ts b/apps/server/src/provider/Layers/OpenCodeProvider.test.ts index 75622281c5..7abe0be981 100644 --- a/apps/server/src/provider/Layers/OpenCodeProvider.test.ts +++ b/apps/server/src/provider/Layers/OpenCodeProvider.test.ts @@ -2,22 +2,30 @@ import assert from "node:assert/strict"; import * as NodeServices from "@effect/platform-node/NodeServices"; import { it } from "@effect/vitest"; -import { Effect, Layer } from "effect"; +import { Effect, Layer, Schema } from "effect"; import { beforeEach } from "vitest"; +import { OpenCodeSettings } from "@t3tools/contracts"; import { ServerConfig } from "../../config.ts"; -import { ServerSettingsService } from "../../serverSettings.ts"; -import { OpenCodeProvider } from "../Services/OpenCodeProvider.ts"; import { OpenCodeRuntime, OpenCodeRuntimeError, type OpenCodeRuntimeShape, } from "../opencodeRuntime.ts"; -import { OpenCodeProviderLive } from "./OpenCodeProvider.ts"; +import { checkOpenCodeProviderStatus } from "./OpenCodeProvider.ts"; import type { OpenCodeInventory } from "../opencodeRuntime.ts"; const DEFAULT_VERSION_STDOUT = "opencode 1.14.19\n"; +/** + * The legacy `OpenCodeProviderLive` Layer + `OpenCodeProvider` service tag + * are deleted. The snapshot-producing logic they wrapped now lives in the + * standalone `checkOpenCodeProviderStatus(settings, cwd)` Effect, which + * drivers call directly when building their per-instance snapshot + * `ServerProviderShape`. Tests mirror that shape: build a settings payload, + * invoke the check, assert on the returned snapshot. + */ + const runtimeMock = { state: { runVersionError: null as Error | null, @@ -90,20 +98,26 @@ beforeEach(() => { runtimeMock.reset(); }); -const makeTestLayer = (settingsOverrides?: Parameters[0]) => - OpenCodeProviderLive.pipe( - Layer.provideMerge(Layer.succeed(OpenCodeRuntime, OpenCodeRuntimeTestDouble)), - Layer.provideMerge(ServerConfig.layerTest(process.cwd(), process.cwd())), - Layer.provideMerge(ServerSettingsService.layerTest(settingsOverrides)), - Layer.provideMerge(NodeServices.layer), - ); +const testLayer = Layer.succeed(OpenCodeRuntime, OpenCodeRuntimeTestDouble).pipe( + Layer.provideMerge(ServerConfig.layerTest(process.cwd(), process.cwd())), + Layer.provideMerge(NodeServices.layer), +); -it.layer(makeTestLayer())("OpenCodeProviderLive", (it) => { +const makeOpenCodeSettings = (overrides?: Partial): OpenCodeSettings => + Schema.decodeSync(OpenCodeSettings)({ + enabled: true, + binaryPath: "opencode", + serverUrl: "", + serverPassword: "", + customModels: [], + ...overrides, + }); + +it.layer(testLayer)("checkOpenCodeProviderStatus", (it) => { it.effect("shows a codex-style missing binary message", () => Effect.gen(function* () { runtimeMock.state.runVersionError = new Error("spawn opencode ENOENT"); - const provider = yield* OpenCodeProvider; - const snapshot = yield* provider.refresh; + const snapshot = yield* checkOpenCodeProviderStatus(makeOpenCodeSettings(), process.cwd()); assert.equal(snapshot.status, "error"); assert.equal(snapshot.installed, false); @@ -114,8 +128,7 @@ it.layer(makeTestLayer())("OpenCodeProviderLive", (it) => { it.effect("hides generic Effect.tryPromise text for local CLI probe failures", () => Effect.gen(function* () { runtimeMock.state.runVersionError = new Error("An error occurred in Effect.tryPromise"); - const provider = yield* OpenCodeProvider; - const snapshot = yield* provider.refresh; + const snapshot = yield* checkOpenCodeProviderStatus(makeOpenCodeSettings(), process.cwd()); assert.equal(snapshot.status, "error"); assert.equal(snapshot.installed, true); @@ -123,33 +136,6 @@ it.layer(makeTestLayer())("OpenCodeProviderLive", (it) => { }), ); - it.effect("refuses to probe when opencode is older than the required minimum", () => - Effect.gen(function* () { - runtimeMock.state.versionStdout = "opencode 1.4.7\n"; - const provider = yield* OpenCodeProvider; - const snapshot = yield* provider.refresh; - - assert.equal(snapshot.status, "error"); - assert.equal(snapshot.installed, true); - assert.equal(snapshot.version, "1.4.7"); - assert.ok(snapshot.message?.includes("1.14.19")); - assert.ok(snapshot.message?.toLowerCase().includes("upgrade")); - }), - ); - - it.effect("refuses to probe when opencode --version output is unparseable", () => - Effect.gen(function* () { - runtimeMock.state.versionStdout = "garbled binary output\n"; - const provider = yield* OpenCodeProvider; - const snapshot = yield* provider.refresh; - - assert.equal(snapshot.status, "error"); - assert.equal(snapshot.installed, true); - assert.equal(snapshot.version, null); - assert.ok(snapshot.message?.includes("1.14.19")); - }), - ); - it.effect("emits OpenCode variant defaults so trait picker can resolve a visible selection", () => Effect.gen(function* () { runtimeMock.state.inventory = { @@ -182,8 +168,7 @@ it.layer(makeTestLayer())("OpenCodeProviderLive", (it) => { ], }; - const provider = yield* OpenCodeProvider; - const snapshot = yield* provider.refresh; + const snapshot = yield* checkOpenCodeProviderStatus(makeOpenCodeSettings(), process.cwd()); const model = snapshot.models.find((entry) => entry.slug === "openai/gpt-5.4"); assert.ok(model); @@ -191,40 +176,41 @@ it.layer(makeTestLayer())("OpenCodeProviderLive", (it) => { (descriptor) => descriptor.id === "variant" && descriptor.type === "select", ); assert.ok(variantDescriptor && variantDescriptor.type === "select"); - assert.equal(variantDescriptor.options.find((option) => option.isDefault)?.id, "medium"); + assert.equal( + variantDescriptor.options.find((option) => option.isDefault === true)?.id, + "medium", + ); const agentDescriptor = model.capabilities?.optionDescriptors?.find( (descriptor) => descriptor.id === "agent" && descriptor.type === "select", ); assert.ok(agentDescriptor && agentDescriptor.type === "select"); - assert.equal(agentDescriptor.options.find((option) => option.isDefault)?.id, "build"); + assert.equal( + agentDescriptor.options.find((option) => option.isDefault === true)?.id, + "build", + ); }), ); it.effect("closes the local OpenCode server scope after provider refresh", () => Effect.gen(function* () { - const provider = yield* OpenCodeProvider; - yield* provider.refresh; + yield* checkOpenCodeProviderStatus(makeOpenCodeSettings(), process.cwd()); assert.equal(runtimeMock.state.closeCalls, 1); }), ); }); -it.layer( - makeTestLayer({ - providers: { - opencode: { - serverUrl: "http://127.0.0.1:9999", - serverPassword: "secret-password", - }, - }, - }), -)("OpenCodeProviderLive with configured server URL", (it) => { +it.layer(testLayer)("checkOpenCodeProviderStatus with configured server URL", (it) => { it.effect("surfaces a friendly auth error for configured servers", () => Effect.gen(function* () { runtimeMock.state.inventoryError = new Error("401 Unauthorized"); - const provider = yield* OpenCodeProvider; - const snapshot = yield* provider.refresh; + const snapshot = yield* checkOpenCodeProviderStatus( + makeOpenCodeSettings({ + serverUrl: "http://127.0.0.1:9999", + serverPassword: "secret-password", + }), + process.cwd(), + ); assert.equal(snapshot.status, "error"); assert.equal(snapshot.installed, true); @@ -240,8 +226,13 @@ it.layer( runtimeMock.state.inventoryError = new Error( "fetch failed: connect ECONNREFUSED 127.0.0.1:9999", ); - const provider = yield* OpenCodeProvider; - const snapshot = yield* provider.refresh; + const snapshot = yield* checkOpenCodeProviderStatus( + makeOpenCodeSettings({ + serverUrl: "http://127.0.0.1:9999", + serverPassword: "secret-password", + }), + process.cwd(), + ); assert.equal(snapshot.status, "error"); assert.equal(snapshot.installed, true); diff --git a/apps/server/src/provider/Layers/OpenCodeProvider.ts b/apps/server/src/provider/Layers/OpenCodeProvider.ts index b94840015e..c7487d7d52 100644 --- a/apps/server/src/provider/Layers/OpenCodeProvider.ts +++ b/apps/server/src/provider/Layers/OpenCodeProvider.ts @@ -1,24 +1,21 @@ -import type { - ModelCapabilities, - OpenCodeSettings, - ServerProvider, - ServerProviderModel, +import { + ProviderDriverKind, + type ModelCapabilities, + type OpenCodeSettings, + type ServerProviderModel, } from "@t3tools/contracts"; -import { Cause, Data, Effect, Equal, Layer, Stream } from "effect"; +import { Cause, Data, Effect } from "effect"; import { createModelCapabilities } from "@t3tools/shared/model"; -import { ServerConfig } from "../../config.ts"; -import { ServerSettingsService } from "../../serverSettings.ts"; -import { makeManagedServerProvider } from "../makeManagedServerProvider.ts"; import { buildServerProvider, nonEmptyTrimmed, parseGenericCliVersion, providerModelsFromSettings, + type ServerProviderDraft, } from "../providerSnapshot.ts"; import { compareCliVersions } from "../cliVersion.ts"; -import { OpenCodeProvider } from "../Services/OpenCodeProvider.ts"; import { OpenCodeRuntime, openCodeRuntimeErrorDetail, @@ -26,7 +23,7 @@ import { } from "../opencodeRuntime.ts"; import type { Agent, ProviderListResponse } from "@opencode-ai/sdk/v2"; -const PROVIDER = "opencode" as const; +const PROVIDER = ProviderDriverKind.make("opencode"); const OPENCODE_PRESENTATION = { displayName: "OpenCode", showInteractionModeToggle: false, @@ -251,7 +248,9 @@ function flattenOpenCodeModels(input: OpenCodeInventory): ReadonlyArray left.name.localeCompare(right.name)); } -const makePendingOpenCodeProvider = (openCodeSettings: OpenCodeSettings): ServerProvider => { +export const makePendingOpenCodeProvider = ( + openCodeSettings: OpenCodeSettings, +): ServerProviderDraft => { const checkedAt = new Date().toISOString(); const models = providerModelsFromSettings( [], @@ -262,7 +261,6 @@ const makePendingOpenCodeProvider = (openCodeSettings: OpenCodeSettings): Server if (!openCodeSettings.enabled) { return buildServerProvider({ - provider: PROVIDER, presentation: OPENCODE_PRESENTATION, enabled: false, checkedAt, @@ -281,7 +279,6 @@ const makePendingOpenCodeProvider = (openCodeSettings: OpenCodeSettings): Server } return buildServerProvider({ - provider: PROVIDER, presentation: OPENCODE_PRESENTATION, enabled: true, checkedAt, @@ -296,210 +293,179 @@ const makePendingOpenCodeProvider = (openCodeSettings: OpenCodeSettings): Server }); }; -export const OpenCodeProviderLive = Layer.effect( - OpenCodeProvider, - Effect.gen(function* () { - const serverSettings = yield* ServerSettingsService; - const serverConfig = yield* ServerConfig; - const openCodeRuntime = yield* OpenCodeRuntime; +export const checkOpenCodeProviderStatus = Effect.fn("checkOpenCodeProviderStatus")(function* ( + openCodeSettings: OpenCodeSettings, + cwd: string, + environment: NodeJS.ProcessEnv = process.env, +): Effect.fn.Return { + const openCodeRuntime = yield* OpenCodeRuntime; + const checkedAt = new Date().toISOString(); + const customModels = openCodeSettings.customModels; + const isExternalServer = openCodeSettings.serverUrl.trim().length > 0; - const checkOpenCodeProviderStatus = Effect.fn("checkOpenCodeProviderStatus")(function* (input: { - readonly settings: OpenCodeSettings; - readonly cwd: string; - }): Effect.fn.Return { - const checkedAt = new Date().toISOString(); - const customModels = input.settings.customModels; - const isExternalServer = input.settings.serverUrl.trim().length > 0; - - const fallback = (cause: unknown, version: string | null = null) => { - const failure = formatOpenCodeProbeError({ - cause, - isExternalServer, - serverUrl: input.settings.serverUrl, - }); - return buildServerProvider({ - provider: PROVIDER, - presentation: OPENCODE_PRESENTATION, - enabled: input.settings.enabled, - checkedAt, - models: providerModelsFromSettings( - [], - PROVIDER, - customModels, - DEFAULT_OPENCODE_MODEL_CAPABILITIES, - ), - probe: { - installed: failure.installed, - version, - status: "error", - auth: { status: "unknown" }, - message: failure.message, - }, - }); - }; - - if (!input.settings.enabled) { - return buildServerProvider({ - provider: PROVIDER, - presentation: OPENCODE_PRESENTATION, - enabled: false, - checkedAt, - models: providerModelsFromSettings( - [], - PROVIDER, - customModels, - DEFAULT_OPENCODE_MODEL_CAPABILITIES, - ), - probe: { - installed: false, - version: null, - status: "warning", - auth: { status: "unknown" }, - message: isExternalServer - ? "OpenCode is disabled in T3 Code settings. A server URL is configured." - : "OpenCode is disabled in T3 Code settings.", - }, - }); - } - - let version: string | null = null; - if (!isExternalServer) { - const versionExit = yield* Effect.exit( - openCodeRuntime - .runOpenCodeCommand({ - binaryPath: input.settings.binaryPath, - args: ["--version"], - }) - .pipe( - Effect.mapError( - (cause) => - new OpenCodeProbeError({ cause, detail: openCodeRuntimeErrorDetail(cause) }), - ), - ), - ); - if (versionExit._tag === "Failure") { - return fallback(Cause.squash(versionExit.cause)); - } - version = parseGenericCliVersion(versionExit.value.stdout) ?? null; - - if (!version) { - return fallback( - new Error( - `Unable to determine OpenCode version from \`opencode --version\` output. T3 Code requires OpenCode v${MINIMUM_OPENCODE_VERSION} or newer.`, - ), - null, - ); - } - if (compareCliVersions(version, MINIMUM_OPENCODE_VERSION) < 0) { - return buildServerProvider({ - provider: PROVIDER, - presentation: OPENCODE_PRESENTATION, - enabled: input.settings.enabled, - checkedAt, - models: providerModelsFromSettings( - [], - PROVIDER, - customModels, - DEFAULT_OPENCODE_MODEL_CAPABILITIES, - ), - probe: { - installed: true, - version, - status: "error", - auth: { status: "unknown" }, - message: `OpenCode v${version} is too old. Upgrade to v${MINIMUM_OPENCODE_VERSION} or newer.`, - }, - }); - } - } - - const inventoryExit = yield* Effect.exit( - Effect.scoped( - Effect.gen(function* () { - const server = yield* openCodeRuntime - .connectToOpenCodeServer({ - binaryPath: input.settings.binaryPath, - serverUrl: input.settings.serverUrl, - }) - .pipe( - Effect.mapError( - (cause) => - new OpenCodeProbeError({ cause, detail: openCodeRuntimeErrorDetail(cause) }), - ), - ); - return yield* openCodeRuntime - .loadOpenCodeInventory( - openCodeRuntime.createOpenCodeSdkClient({ - baseUrl: server.url, - directory: input.cwd, - ...(isExternalServer && input.settings.serverPassword - ? { serverPassword: input.settings.serverPassword } - : {}), - }), - ) - .pipe( - Effect.mapError( - (cause) => - new OpenCodeProbeError({ cause, detail: openCodeRuntimeErrorDetail(cause) }), - ), - ); - }), - ), - ); - if (inventoryExit._tag === "Failure") { - return fallback(Cause.squash(inventoryExit.cause), version); - } - - const models = providerModelsFromSettings( - flattenOpenCodeModels(inventoryExit.value), + const fallback = (cause: unknown, version: string | null = null) => { + const failure = formatOpenCodeProbeError({ + cause, + isExternalServer, + serverUrl: openCodeSettings.serverUrl, + }); + return buildServerProvider({ + presentation: OPENCODE_PRESENTATION, + enabled: openCodeSettings.enabled, + checkedAt, + models: providerModelsFromSettings( + [], PROVIDER, customModels, DEFAULT_OPENCODE_MODEL_CAPABILITIES, + ), + probe: { + installed: failure.installed, + version, + status: "error", + auth: { status: "unknown" }, + message: failure.message, + }, + }); + }; + + if (!openCodeSettings.enabled) { + return buildServerProvider({ + presentation: OPENCODE_PRESENTATION, + enabled: false, + checkedAt, + models: providerModelsFromSettings( + [], + PROVIDER, + customModels, + DEFAULT_OPENCODE_MODEL_CAPABILITIES, + ), + probe: { + installed: false, + version: null, + status: "warning", + auth: { status: "unknown" }, + message: isExternalServer + ? "OpenCode is disabled in T3 Code settings. A server URL is configured." + : "OpenCode is disabled in T3 Code settings.", + }, + }); + } + + let version: string | null = null; + if (!isExternalServer) { + const versionExit = yield* Effect.exit( + openCodeRuntime + .runOpenCodeCommand({ + binaryPath: openCodeSettings.binaryPath, + args: ["--version"], + environment, + }) + .pipe( + Effect.mapError( + (cause) => new OpenCodeProbeError({ cause, detail: openCodeRuntimeErrorDetail(cause) }), + ), + ), + ); + if (versionExit._tag === "Failure") { + return fallback(Cause.squash(versionExit.cause)); + } + version = parseGenericCliVersion(versionExit.value.stdout) ?? null; + + if (!version) { + return fallback( + new Error( + `Unable to determine OpenCode version from \`opencode --version\` output. T3 Code requires OpenCode v${MINIMUM_OPENCODE_VERSION} or newer.`, + ), + null, ); - const connectedCount = inventoryExit.value.providerList.connected.length; + } + if (compareCliVersions(version, MINIMUM_OPENCODE_VERSION) < 0) { return buildServerProvider({ - provider: PROVIDER, presentation: OPENCODE_PRESENTATION, - enabled: true, + enabled: openCodeSettings.enabled, checkedAt, - models, + models: providerModelsFromSettings( + [], + PROVIDER, + customModels, + DEFAULT_OPENCODE_MODEL_CAPABILITIES, + ), probe: { installed: true, version, - status: connectedCount > 0 ? "ready" : "warning", - auth: { - status: connectedCount > 0 ? "authenticated" : "unknown", - type: "opencode", - }, - message: - connectedCount > 0 - ? `${connectedCount} upstream provider${connectedCount === 1 ? "" : "s"} connected through ${isExternalServer ? "the configured OpenCode server" : "OpenCode"}.` - : isExternalServer - ? "Connected to the configured OpenCode server, but it did not report any connected upstream providers." - : "OpenCode is available, but it did not report any connected upstream providers.", + status: "error", + auth: { status: "unknown" }, + message: `OpenCode v${version} is too old. Upgrade to v${MINIMUM_OPENCODE_VERSION} or newer.`, }, }); - }); + } + } - const getProviderSettings = serverSettings.getSettings.pipe( - Effect.map((settings) => settings.providers.opencode), - ); + const inventoryExit = yield* Effect.exit( + Effect.scoped( + Effect.gen(function* () { + const server = yield* openCodeRuntime + .connectToOpenCodeServer({ + binaryPath: openCodeSettings.binaryPath, + serverUrl: openCodeSettings.serverUrl, + environment, + }) + .pipe( + Effect.mapError( + (cause) => + new OpenCodeProbeError({ cause, detail: openCodeRuntimeErrorDetail(cause) }), + ), + ); + return yield* openCodeRuntime + .loadOpenCodeInventory( + openCodeRuntime.createOpenCodeSdkClient({ + baseUrl: server.url, + directory: cwd, + ...(isExternalServer && openCodeSettings.serverPassword + ? { serverPassword: openCodeSettings.serverPassword } + : {}), + }), + ) + .pipe( + Effect.mapError( + (cause) => + new OpenCodeProbeError({ cause, detail: openCodeRuntimeErrorDetail(cause) }), + ), + ); + }), + ), + ); + if (inventoryExit._tag === "Failure") { + return fallback(Cause.squash(inventoryExit.cause), version); + } - return yield* makeManagedServerProvider({ - getSettings: getProviderSettings.pipe(Effect.orDie), - streamSettings: serverSettings.streamChanges.pipe( - Stream.map((settings) => settings.providers.opencode), - ), - haveSettingsChanged: (previous, next) => !Equal.equals(previous, next), - initialSnapshot: makePendingOpenCodeProvider, - checkProvider: getProviderSettings.pipe( - Effect.flatMap((settings) => - checkOpenCodeProviderStatus({ - settings, - cwd: serverConfig.cwd, - }), - ), - ), - }); - }), -); + const models = providerModelsFromSettings( + flattenOpenCodeModels(inventoryExit.value), + PROVIDER, + customModels, + DEFAULT_OPENCODE_MODEL_CAPABILITIES, + ); + const connectedCount = inventoryExit.value.providerList.connected.length; + return buildServerProvider({ + presentation: OPENCODE_PRESENTATION, + enabled: true, + checkedAt, + models, + probe: { + installed: true, + version, + status: connectedCount > 0 ? "ready" : "warning", + auth: { + status: connectedCount > 0 ? "authenticated" : "unknown", + type: "opencode", + }, + message: + connectedCount > 0 + ? `${connectedCount} upstream provider${connectedCount === 1 ? "" : "s"} connected through ${isExternalServer ? "the configured OpenCode server" : "OpenCode"}.` + : isExternalServer + ? "Connected to the configured OpenCode server, but it did not report any connected upstream providers." + : "OpenCode is available, but it did not report any connected upstream providers.", + }, + }); +}); diff --git a/apps/server/src/provider/Layers/ProviderAdapterRegistry.test.ts b/apps/server/src/provider/Layers/ProviderAdapterRegistry.test.ts index e0a68f68b6..05735f3a50 100644 --- a/apps/server/src/provider/Layers/ProviderAdapterRegistry.test.ts +++ b/apps/server/src/provider/Layers/ProviderAdapterRegistry.test.ts @@ -1,24 +1,30 @@ -import type { ProviderKind } from "@t3tools/contracts"; +import { + defaultInstanceIdForDriver, + ProviderDriverKind, + type ServerProvider, +} from "@t3tools/contracts"; import { it, assert, vi } from "@effect/vitest"; -import { assertFailure } from "@effect/vitest/utils"; -import { Effect, Layer, Stream } from "effect"; +import { Effect, Layer, PubSub, Stream } from "effect"; -import { ClaudeAdapter } from "../Services/ClaudeAdapter.ts"; import type { ClaudeAdapterShape } from "../Services/ClaudeAdapter.ts"; -import { CodexAdapter } from "../Services/CodexAdapter.ts"; import type { CodexAdapterShape } from "../Services/CodexAdapter.ts"; -import { CursorAdapter } from "../Services/CursorAdapter.ts"; import type { CursorAdapterShape } from "../Services/CursorAdapter.ts"; -import { OpenCodeAdapter } from "../Services/OpenCodeAdapter.ts"; import type { OpenCodeAdapterShape } from "../Services/OpenCodeAdapter.ts"; import { ProviderAdapterRegistry } from "../Services/ProviderAdapterRegistry.ts"; +import { ProviderInstanceRegistry } from "../Services/ProviderInstanceRegistry.ts"; +import type { ProviderInstance } from "../ProviderDriver.ts"; +import type { TextGenerationShape } from "../../git/Services/TextGeneration.ts"; import { ProviderAdapterRegistryLive } from "./ProviderAdapterRegistry.ts"; -import { ProviderUnsupportedError } from "../Errors.ts"; import * as NodeServices from "@effect/platform-node/NodeServices"; +const CODEX_DRIVER = ProviderDriverKind.make("codex"); +const CLAUDE_AGENT_DRIVER = ProviderDriverKind.make("claudeAgent"); +const OPENCODE_DRIVER = ProviderDriverKind.make("opencode"); +const CURSOR_DRIVER = ProviderDriverKind.make("cursor"); + const fakeCodexAdapter: CodexAdapterShape = { - provider: "codex", + provider: CODEX_DRIVER, capabilities: { sessionModelSwitch: "in-session" }, startSession: vi.fn(), sendTurn: vi.fn(), @@ -35,7 +41,7 @@ const fakeCodexAdapter: CodexAdapterShape = { }; const fakeClaudeAdapter: ClaudeAdapterShape = { - provider: "claudeAgent", + provider: CLAUDE_AGENT_DRIVER, capabilities: { sessionModelSwitch: "in-session" }, startSession: vi.fn(), sendTurn: vi.fn(), @@ -52,7 +58,7 @@ const fakeClaudeAdapter: ClaudeAdapterShape = { }; const fakeOpenCodeAdapter: OpenCodeAdapterShape = { - provider: "opencode", + provider: OPENCODE_DRIVER, capabilities: { sessionModelSwitch: "in-session" }, startSession: vi.fn(), sendTurn: vi.fn(), @@ -69,7 +75,7 @@ const fakeOpenCodeAdapter: OpenCodeAdapterShape = { }; const fakeCursorAdapter: CursorAdapterShape = { - provider: "cursor", + provider: CURSOR_DRIVER, capabilities: { sessionModelSwitch: "in-session" }, startSession: vi.fn(), sendTurn: vi.fn(), @@ -85,44 +91,94 @@ const fakeCursorAdapter: CursorAdapterShape = { streamEvents: Stream.empty, }; -const layer = it.layer( - Layer.mergeAll( - Layer.provide( - ProviderAdapterRegistryLive, - Layer.mergeAll( - Layer.succeed(CodexAdapter, fakeCodexAdapter), - Layer.succeed(ClaudeAdapter, fakeClaudeAdapter), - Layer.succeed(OpenCodeAdapter, fakeOpenCodeAdapter), - Layer.succeed(CursorAdapter, fakeCursorAdapter), - ), - ), - NodeServices.layer, - ), +// ProviderAdapterRegistryLive is now a facade over ProviderInstanceRegistry — +// it walks `listInstances` once at boot and surfaces the default-instance +// adapter keyed by its driver kind. To test the facade we supply four fake +// instances whose `instanceId === defaultInstanceIdForDriver(driverKind)` so +// they pass the default-instance filter. +const makeFakeInstance = ( + driverKindString: "codex" | "claudeAgent" | "cursor" | "opencode", + adapter: ProviderInstance["adapter"], +): ProviderInstance => { + const driverKind = ProviderDriverKind.make(driverKindString); + return { + instanceId: defaultInstanceIdForDriver(driverKind), + driverKind, + continuationIdentity: { + driverKind, + continuationKey: `${driverKind}:instance:${defaultInstanceIdForDriver(driverKind)}`, + }, + displayName: undefined, + enabled: true, + snapshot: { + getSnapshot: Effect.succeed({} as unknown as ServerProvider), + refresh: Effect.succeed({} as unknown as ServerProvider), + streamChanges: Stream.empty, + }, + adapter, + textGeneration: {} as unknown as TextGenerationShape, + }; +}; + +const fakeInstances: ReadonlyArray = [ + makeFakeInstance("codex", fakeCodexAdapter), + makeFakeInstance("claudeAgent", fakeClaudeAdapter), + makeFakeInstance("opencode", fakeOpenCodeAdapter), + makeFakeInstance("cursor", fakeCursorAdapter), +]; + +const fakeInstanceRegistryLayer = Layer.succeed(ProviderInstanceRegistry, { + getInstance: (instanceId) => + Effect.succeed(fakeInstances.find((instance) => instance.instanceId === instanceId)), + listInstances: Effect.succeed(fakeInstances), + listUnavailable: Effect.succeed([]), + streamChanges: Stream.empty, + // Tests never drive changes through this fake; acquire a throwaway + // subscription on an unused PubSub so the shape is satisfied. + subscribeChanges: Effect.flatMap(PubSub.unbounded(), (pubsub) => PubSub.subscribe(pubsub)), +}); + +const layer = Layer.mergeAll( + Layer.provide(ProviderAdapterRegistryLive, fakeInstanceRegistryLayer), + NodeServices.layer, ); -layer("ProviderAdapterRegistryLive", (it) => { - it.effect("resolves a registered provider adapter", () => +it.layer(layer)("ProviderAdapterRegistryLive", (it) => { + it("resolves adapters and routing metadata from provider instances", () => Effect.gen(function* () { const registry = yield* ProviderAdapterRegistry; - const codex = yield* registry.getByProvider("codex"); - const claude = yield* registry.getByProvider("claudeAgent"); - const openCode = yield* registry.getByProvider("opencode"); - const cursor = yield* registry.getByProvider("cursor"); - assert.equal(codex, fakeCodexAdapter); - assert.equal(claude, fakeClaudeAdapter); - assert.equal(openCode, fakeOpenCodeAdapter); - assert.equal(cursor, fakeCursorAdapter); + const claudeInstanceId = defaultInstanceIdForDriver(CLAUDE_AGENT_DRIVER); + + const adapter = yield* registry.getByInstance(claudeInstanceId); + assert.strictEqual(adapter, fakeClaudeAdapter); + + const info = yield* registry.getInstanceInfo(claudeInstanceId); + assert.deepStrictEqual(info, { + instanceId: claudeInstanceId, + driverKind: CLAUDE_AGENT_DRIVER, + displayName: undefined, + accentColor: undefined, + enabled: true, + continuationIdentity: { + driverKind: CLAUDE_AGENT_DRIVER, + continuationKey: "claudeAgent:instance:claudeAgent", + }, + }); + + const instances = yield* registry.listInstances(); + assert.deepStrictEqual(instances, [ + defaultInstanceIdForDriver(CODEX_DRIVER), + claudeInstanceId, + defaultInstanceIdForDriver(OPENCODE_DRIVER), + defaultInstanceIdForDriver(CURSOR_DRIVER), + ]); const providers = yield* registry.listProviders(); - assert.deepEqual(providers, ["codex", "claudeAgent", "opencode", "cursor"]); - }), - ); - - it.effect("fails with ProviderUnsupportedError for unknown providers", () => - Effect.gen(function* () { - const registry = yield* ProviderAdapterRegistry; - const adapter = yield* registry.getByProvider("unknown" as ProviderKind).pipe(Effect.result); - assertFailure(adapter, new ProviderUnsupportedError({ provider: "unknown" })); - }), - ); + assert.deepStrictEqual(providers, [ + CODEX_DRIVER, + CLAUDE_AGENT_DRIVER, + OPENCODE_DRIVER, + CURSOR_DRIVER, + ]); + })); }); diff --git a/apps/server/src/provider/Layers/ProviderAdapterRegistry.ts b/apps/server/src/provider/Layers/ProviderAdapterRegistry.ts index dabe5b8581..f2eeaa1aae 100644 --- a/apps/server/src/provider/Layers/ProviderAdapterRegistry.ts +++ b/apps/server/src/provider/Layers/ProviderAdapterRegistry.ts @@ -1,59 +1,101 @@ /** - * ProviderAdapterRegistryLive - In-memory provider adapter lookup layer. + * ProviderAdapterRegistryLive — facade over `ProviderInstanceRegistry`. * - * Binds provider kinds (codex/claudeAgent/...) to concrete adapter services. - * This layer only performs adapter lookup; it does not route session-scoped - * calls or own provider lifecycle workflows. + * `ProviderAdapterRegistry` historically mapped one `ProviderDriverKind` to one + * adapter via the four `AdapterLive` singleton Layers. The per-instance + * refactor moved adapter construction inside each `ProviderDriver.create()`: + * adapters are now bundled on the `ProviderInstance` that the + * `ProviderInstanceRegistry` owns. + * + * This facade fulfills the `ProviderAdapterRegistryShape` contract by doing + * dynamic look-ups against `ProviderInstanceRegistry` on every call. That + * means settings-driven hot-reload shows up here automatically — adding a + * new instance via settings makes `getByInstance` resolve immediately + * without rebuilding the facade. * * @module ProviderAdapterRegistryLive */ +import { + defaultInstanceIdForDriver, + ProviderInstanceId, + type ProviderDriverKind, +} from "@t3tools/contracts"; import { Effect, Layer } from "effect"; -import { ProviderUnsupportedError, type ProviderAdapterError } from "../Errors.ts"; -import type { ProviderAdapterShape } from "../Services/ProviderAdapter.ts"; +import { ProviderUnsupportedError } from "../Errors.ts"; +import { ProviderInstanceRegistry } from "../Services/ProviderInstanceRegistry.ts"; import { ProviderAdapterRegistry, type ProviderAdapterRegistryShape, } from "../Services/ProviderAdapterRegistry.ts"; -import { ClaudeAdapter } from "../Services/ClaudeAdapter.ts"; -import { CodexAdapter } from "../Services/CodexAdapter.ts"; -import { CursorAdapter } from "../Services/CursorAdapter.ts"; -import { OpenCodeAdapter } from "../Services/OpenCodeAdapter.ts"; -import { createBuiltInAdapterList } from "../builtInProviderCatalog.ts"; -export interface ProviderAdapterRegistryLiveOptions { - readonly adapters?: ReadonlyArray>; -} +const makeProviderAdapterRegistry = Effect.fn("makeProviderAdapterRegistry")(function* () { + const registry = yield* ProviderInstanceRegistry; -const makeProviderAdapterRegistry = Effect.fn("makeProviderAdapterRegistry")(function* ( - options?: ProviderAdapterRegistryLiveOptions, -) { - const cursorAdapterOption = yield* Effect.serviceOption(CursorAdapter); - const adapters = - options?.adapters !== undefined - ? options.adapters - : createBuiltInAdapterList({ - codex: yield* CodexAdapter, - claudeAgent: yield* ClaudeAdapter, - opencode: yield* OpenCodeAdapter, - ...(cursorAdapterOption._tag === "Some" ? { cursor: cursorAdapterOption.value } : {}), - }); - const byProvider = new Map(adapters.map((adapter) => [adapter.provider, adapter])); + const getByInstance: ProviderAdapterRegistryShape["getByInstance"] = (instanceId) => + registry.getInstance(instanceId).pipe( + Effect.flatMap((instance) => + instance === undefined + ? Effect.fail( + new ProviderUnsupportedError({ + provider: instanceId, + }), + ) + : Effect.succeed(instance.adapter), + ), + ); - const getByProvider: ProviderAdapterRegistryShape["getByProvider"] = (provider) => { - const adapter = byProvider.get(provider); - if (!adapter) { - return Effect.fail(new ProviderUnsupportedError({ provider })); - } - return Effect.succeed(adapter); - }; + const getInstanceInfo: ProviderAdapterRegistryShape["getInstanceInfo"] = (instanceId) => + registry.getInstance(instanceId).pipe( + Effect.flatMap((instance) => + instance === undefined + ? Effect.fail( + new ProviderUnsupportedError({ + provider: instanceId, + }), + ) + : Effect.succeed({ + instanceId: instance.instanceId, + driverKind: instance.driverKind, + displayName: instance.displayName, + accentColor: instance.accentColor, + enabled: instance.enabled, + continuationIdentity: instance.continuationIdentity, + }), + ), + ); + + const listInstances: ProviderAdapterRegistryShape["listInstances"] = () => + registry.listInstances.pipe( + Effect.map((instances) => instances.map((instance) => instance.instanceId)), + ); const listProviders: ProviderAdapterRegistryShape["listProviders"] = () => - Effect.sync(() => Array.from(byProvider.keys())); + registry.listInstances.pipe( + Effect.map((instances) => { + const kinds = new Set(); + for (const instance of instances) { + const defaultId = defaultInstanceIdForDriver(instance.driverKind); + if (instance.instanceId === defaultId) { + // Only the default-instance rows show up through the legacy + // shim — custom instances like `codex_personal` have no + // `ProviderDriverKind` equivalent. + kinds.add(instance.driverKind); + } + } + return Array.from(kinds); + }), + ); return { - getByProvider, + getByInstance, + getInstanceInfo, + listInstances, listProviders, + // Proxy directly — the facade has no state of its own; the instance + // registry already coalesces adds/removes/rebuilds into one emission. + streamChanges: registry.streamChanges, + subscribeChanges: registry.subscribeChanges, } satisfies ProviderAdapterRegistryShape; }); @@ -61,3 +103,14 @@ export const ProviderAdapterRegistryLive = Layer.effect( ProviderAdapterRegistry, makeProviderAdapterRegistry(), ); + +// Exposed for tests that want to build a facade over a pre-assembled +// `ProviderInstanceRegistry` without pulling in the whole boot graph. +export { makeProviderAdapterRegistry }; + +// Re-export for consumers that need the accessor shape. The service tag +// itself lives in `Services/ProviderAdapterRegistry.ts`. +export { ProviderAdapterRegistry } from "../Services/ProviderAdapterRegistry.ts"; +// Re-export for consumers (including tests) that construct a +// `ProviderInstanceId` before calling `getByInstance`. +export { ProviderInstanceId }; diff --git a/apps/server/src/provider/Layers/ProviderEventLoggers.ts b/apps/server/src/provider/Layers/ProviderEventLoggers.ts new file mode 100644 index 0000000000..4a15fdd685 --- /dev/null +++ b/apps/server/src/provider/Layers/ProviderEventLoggers.ts @@ -0,0 +1,83 @@ +/** + * ProviderEventLoggers — single observability service that owns the two + * shared NDJSON streams the provider runtime writes: + * + * - `native` — provider-protocol events as the SDK emits them, written + * from inside each `Adapter` factory. + * - `canonical` — runtime events after `ProviderService` has normalized + * them onto `ProviderRuntimeEvent`. + * + * Why a service tag and not constructor options? + * + * - Adapters are now constructed *inside* drivers (`Driver.create()`), + * not at the boot Layer. There is no longer a single `makeAdapterLive(options)` + * call site where we can hand an `EventNdjsonLogger` in by hand. + * - Multiple driver instances per kind (`codex_personal`, `codex_work`) + * should share one underlying log writer per stream — opening N writers + * against the same rotating file would race the rotation logic. Owning + * the loggers on a single tag keeps that invariant intact. + * - Tests can swap one (or both) loggers with in-memory recorders by + * `Layer.succeed(ProviderEventLoggers, { native, canonical })` instead of + * juggling per-Layer option threading. + * + * Both fields are optional. `makeEventNdjsonLogger` returns `undefined` when + * the target directory cannot be created; we forward that as `undefined` + * rather than failing the boot Layer, matching the previous best-effort + * behavior of `server.ts`. + * + * @module provider/Layers/ProviderEventLoggers + */ +import { Context, Effect, Layer } from "effect"; + +import { ServerConfig } from "../../config.ts"; +import { type EventNdjsonLogger, makeEventNdjsonLogger } from "./EventNdjsonLogger.ts"; + +export interface ProviderEventLoggersShape { + readonly native: EventNdjsonLogger | undefined; + readonly canonical: EventNdjsonLogger | undefined; +} + +/** + * Shared logger pair for native + canonical provider event streams. + * + * Service value is intentionally a struct of two optional loggers rather + * than two parallel tags. Construction site is one place + * (`ProviderEventLoggersLive`); consumers (drivers, `ProviderService`) read + * one tag and pluck the field they need. + */ +export class ProviderEventLoggers extends Context.Service< + ProviderEventLoggers, + ProviderEventLoggersShape +>()("t3/provider/ProviderEventLoggers") {} + +/** + * Constant value used by tests / boot layers that want to opt out of native + * + canonical logging entirely. Keeps the tag non-optional in the type + * system while letting the runtime treat absence as a no-op. + */ +export const NoOpProviderEventLoggers: ProviderEventLoggersShape = { + native: undefined, + canonical: undefined, +}; + +/** + * Live Layer that builds both loggers from `ServerConfig.providerEventLogPath`. + * If the directory create fails for either stream, the corresponding field + * is `undefined` and writes from that stream become no-ops downstream. + */ +export const ProviderEventLoggersLive = Layer.effect( + ProviderEventLoggers, + Effect.gen(function* () { + const { providerEventLogPath } = yield* ServerConfig; + const native = yield* makeEventNdjsonLogger(providerEventLogPath, { + stream: "native", + }); + const canonical = yield* makeEventNdjsonLogger(providerEventLogPath, { + stream: "canonical", + }); + return { + native, + canonical, + } satisfies ProviderEventLoggersShape; + }), +); diff --git a/apps/server/src/provider/Layers/ProviderInstanceRegistryHydration.ts b/apps/server/src/provider/Layers/ProviderInstanceRegistryHydration.ts new file mode 100644 index 0000000000..b6c44306f9 --- /dev/null +++ b/apps/server/src/provider/Layers/ProviderInstanceRegistryHydration.ts @@ -0,0 +1,176 @@ +/** + * ProviderInstanceRegistryHydration — derive a `ProviderInstanceConfigMap` + * from `ServerSettings` and keep `ProviderInstanceRegistry` in sync with it. + * + * The server still reads two shapes: + * + * 1. `settings.providerInstances` — the new driver-agnostic map the + * registry expects. Keyed by `ProviderInstanceId`, values are + * `ProviderInstanceConfig` envelopes. + * 2. `settings.providers.` — the legacy single-instance-per-driver + * fields (`providers.codex`, `providers.claudeAgent`, …). These are + * the source of truth for every deployment that hasn't been migrated + * yet to an explicit `providerInstances` entry. + * + * This module bridges (2) into (1) and wires the resulting map into a + * mutable registry. For every built-in driver whose id is not already + * present in `providerInstances` (keyed on + * `defaultInstanceIdForDriver(driverKind)` — literally the driver kind as a + * routing slug), we synthesize an envelope from the legacy field. The + * registry decodes both flavours through the same `configSchema` and ends + * up with one uniform `ProviderInstance` per entry. + * + * Explicit `providerInstances` entries always win — users can already + * override the legacy `providers.` blob by authoring a + * `providerInstances.codex` entry with a matching driver, and we don't + * want the synthesized envelope to silently stomp their config. + * + * Hot-reload + * ---------- + * On layer build we: + * 1. Read the current `ServerSettings` once and use it to seed the + * registry's initial state via `ProviderInstanceRegistryMutableLayer`. + * 2. Fork a daemon fiber (lifetime tied to the layer's scope) that + * subscribes to `ServerSettingsService.streamChanges` and calls + * `ProviderInstanceRegistryMutator.reconcile` on every emission. + * + * Failures inside the watcher are logged and swallowed so a single bad + * settings emission cannot kill the registry. Unknown drivers and invalid + * configs already round-trip through the registry's own "unavailable" + * shadow bucket. + * + * @module provider/Layers/ProviderInstanceRegistryHydration + */ +import { + defaultInstanceIdForDriver, + type ProviderInstanceConfig, + type ProviderInstanceConfigMap, + ServerSettings, +} from "@t3tools/contracts"; +import { Effect, Layer, Stream } from "effect"; + +import { ServerSettingsService } from "../../serverSettings.ts"; +import { BUILT_IN_DRIVERS, type BuiltInDriversEnv } from "../builtInDrivers.ts"; +import { ProviderInstanceRegistry } from "../Services/ProviderInstanceRegistry.ts"; +import { ProviderInstanceRegistryMutator } from "../Services/ProviderInstanceRegistryMutator.ts"; +import { ProviderInstanceRegistryMutableLayer } from "./ProviderInstanceRegistryLive.ts"; + +/** + * Synthesize a `ProviderInstanceConfigMap` from a `ServerSettings` snapshot. + * + * Strategy: + * 1. Copy all explicit `settings.providerInstances` entries verbatim. + * 2. For each built-in driver whose `defaultInstanceIdForDriver(id)` key + * is *not* already in the explicit map, synthesize an entry from the + * matching legacy `settings.providers.` blob. + * + * The returned map is the input the registry consumes; pure & exported + * separately so the hydration logic can be exercised by unit tests + * without layering. + */ +export const deriveProviderInstanceConfigMap = ( + settings: ServerSettings, +): ProviderInstanceConfigMap => { + const merged: Record = { ...settings.providerInstances }; + + for (const driver of BUILT_IN_DRIVERS) { + const instanceId = defaultInstanceIdForDriver(driver.driverKind); + if (instanceId in merged) { + // Explicit `providerInstances` entry for this slot — user-authored + // config always wins over the legacy mirror. + continue; + } + + // Only built-in drivers have a legacy mirror; the registry's + // `providers` struct is keyed on the same literal slug as + // `driverKind`. Access is dynamic (the driver kind is a branded string), + // but it's constrained to `keyof settings.providers` by the union of + // built-in driver kinds. + const legacyKey = driver.driverKind as keyof ServerSettings["providers"]; + const legacyConfig = settings.providers[legacyKey]; + if (legacyConfig === undefined) { + continue; + } + + merged[instanceId] = { + driver: driver.driverKind, + config: legacyConfig, + }; + } + + return merged as ProviderInstanceConfigMap; +}; + +/** + * Layer that consumes `ProviderInstanceRegistryMutator` and forks a + * settings-watcher fiber. The fiber's lifetime is tied to the enclosing + * layer scope (process lifetime in production), so it is interrupted on + * shutdown without leaking. + * + * Errors inside the watcher are logged and swallowed — the registry's own + * "unavailable" bucket already absorbs unknown drivers and invalid + * configs, so the only way the watcher could fail is a settings stream + * tear-down, which logs and exits cleanly. + */ +const SettingsWatcherLive: Layer.Layer< + never, + never, + ProviderInstanceRegistryMutator | ServerSettingsService +> = Layer.effectDiscard( + Effect.gen(function* () { + const mutator = yield* ProviderInstanceRegistryMutator; + const serverSettings = yield* ServerSettingsService; + yield* serverSettings.streamChanges.pipe( + Stream.runForEach((next) => + mutator + .reconcile(deriveProviderInstanceConfigMap(next)) + .pipe( + Effect.catchCause((cause) => + Effect.logError("ProviderInstanceRegistry reconcile failed", cause), + ), + ), + ), + Effect.forkScoped, + ); + }), +); + +/** + * Hydrate `ProviderInstanceRegistry` from `ServerSettings` and keep it in + * sync with subsequent `streamChanges` emissions. + * + * The Layer's two halves: + * - `ProviderInstanceRegistryMutableLayer` produces the registry + + * mutator from the initial config map. Its scope owns every + * per-instance child scope created during reconcile. + * - `SettingsWatcherLive` consumes the mutator and runs a daemon fiber + * in the same scope. + * + * Composing via `Layer.provideMerge` makes the watcher's deps available + * from the mutable layer while still surfacing the registry as an output. + * The mutator tag is technically also exposed; only this module imports + * it, so the visibility leak is harmless in practice. + */ +export const ProviderInstanceRegistryHydrationLive: Layer.Layer< + ProviderInstanceRegistry, + never, + BuiltInDriversEnv | ServerSettingsService +> = Layer.unwrap( + Effect.gen(function* () { + const serverSettings = yield* ServerSettingsService; + const initialSettings: ServerSettings | undefined = yield* serverSettings.getSettings.pipe( + Effect.orElseSucceed(() => undefined), + ); + const initialConfigMap = + initialSettings === undefined + ? ({} as ProviderInstanceConfigMap) + : deriveProviderInstanceConfigMap(initialSettings); + + const mutableLayer = ProviderInstanceRegistryMutableLayer({ + drivers: BUILT_IN_DRIVERS, + configMap: initialConfigMap, + }); + + return SettingsWatcherLive.pipe(Layer.provideMerge(mutableLayer)); + }), +) as Layer.Layer; diff --git a/apps/server/src/provider/Layers/ProviderInstanceRegistryLive.test.ts b/apps/server/src/provider/Layers/ProviderInstanceRegistryLive.test.ts new file mode 100644 index 0000000000..2246a2ae47 --- /dev/null +++ b/apps/server/src/provider/Layers/ProviderInstanceRegistryLive.test.ts @@ -0,0 +1,357 @@ +/** + * Multi-instance validation slices for `ProviderInstanceRegistryLive`. + * + * Two axes of the driver/registry refactor are exercised here: + * + * 1. **Same driver, many instances** — the "multi-instance codex slice" + * describe block below configures two independent `codex` instances and + * asserts each gets its own closures and identity. This is the + * multi-codex capability the refactor exists to unlock. + * + * 2. **Many drivers, one registry** — the "all drivers slice" describe + * block below configures one instance of every shipped driver + * (`codex`, `claudeAgent`, `cursor`, `opencode`) in a single + * `ProviderInstanceConfigMap` and asserts the registry boots them all + * without cross-contamination. This proves the driver SPI is uniform + * across every provider — any driver plugs into the registry through + * the same `ProviderDriver` value contract. + * + * Every instance in these tests is configured with `enabled: false` so the + * provider-status checks short-circuit to pending/disabled snapshots + * without trying to spawn real `codex` / `claude` / `agent` / `opencode` + * binaries. That keeps the assertions focused on registry routing + * behaviour rather than the runtime details of each provider. + */ +import { describe, expect, it } from "@effect/vitest"; +import * as NodeServices from "@effect/platform-node/NodeServices"; +import { + type ClaudeSettings, + type CodexSettings, + type CursorSettings, + type OpenCodeSettings, + ProviderDriverKind, + type ProviderInstanceConfigMap, + ProviderInstanceId, +} from "@t3tools/contracts"; +import { Effect, Layer } from "effect"; + +import { ServerConfig } from "../../config.ts"; +import { ClaudeDriver } from "../Drivers/ClaudeDriver.ts"; +import { CodexDriver } from "../Drivers/CodexDriver.ts"; +import { CursorDriver } from "../Drivers/CursorDriver.ts"; +import { OpenCodeDriver } from "../Drivers/OpenCodeDriver.ts"; +import { OpenCodeRuntimeLive } from "../opencodeRuntime.ts"; +import { NoOpProviderEventLoggers, ProviderEventLoggers } from "./ProviderEventLoggers.ts"; +import { makeProviderInstanceRegistry } from "./ProviderInstanceRegistryLive.ts"; + +const makeCodexConfig = (overrides: Partial): CodexSettings => ({ + enabled: false, + binaryPath: "codex", + homePath: "", + shadowHomePath: "", + customModels: [], + ...overrides, +}); + +const makeClaudeConfig = (overrides: Partial): ClaudeSettings => ({ + enabled: false, + binaryPath: "claude", + homePath: "", + customModels: [], + launchArgs: "", + ...overrides, +}); + +const makeCursorConfig = (overrides: Partial): CursorSettings => ({ + enabled: false, + binaryPath: "agent", + apiEndpoint: "", + customModels: [], + ...overrides, +}); + +const makeOpenCodeConfig = (overrides: Partial): OpenCodeSettings => ({ + enabled: false, + binaryPath: "opencode", + serverUrl: "", + serverPassword: "", + customModels: [], + ...overrides, +}); + +describe("ProviderInstanceRegistryLive — multi-instance codex slice", () => { + // `ServerConfig.layerTest` needs `FileSystem` to materialize its scratch + // directory. `Layer.merge` just unions requirements, so we have to push + // `NodeServices.layer` through `Layer.provideMerge` to satisfy that + // dependency while still surfacing NodeServices to the test body (the + // codex driver's `create` yields `ChildProcessSpawner` directly). + const testLayer = ServerConfig.layerTest(process.cwd(), { + prefix: "provider-instance-registry-test", + }).pipe( + Layer.provideMerge(NodeServices.layer), + Layer.provideMerge(Layer.succeed(ProviderEventLoggers, NoOpProviderEventLoggers)), + ); + + it.live("boots two independent codex instances from a ProviderInstanceConfigMap", () => + Effect.gen(function* () { + const personalId = ProviderInstanceId.make("codex_personal"); + const workId = ProviderInstanceId.make("codex_work"); + const codexDriverKind = ProviderDriverKind.make("codex"); + + const configMap: ProviderInstanceConfigMap = { + [personalId]: { + driver: codexDriverKind, + displayName: "Codex (personal)", + enabled: false, + config: makeCodexConfig({ + binaryPath: "/opt/codex-personal/bin/codex", + homePath: "/home/julius/.codex_personal", + customModels: ["personal-preview"], + }), + }, + [workId]: { + driver: codexDriverKind, + displayName: "Codex (work)", + enabled: false, + config: makeCodexConfig({ + binaryPath: "/opt/codex-work/bin/codex", + homePath: "/home/julius/.codex", + customModels: ["work-preview"], + }), + }, + }; + + const { registry } = yield* makeProviderInstanceRegistry({ + drivers: [CodexDriver], + configMap, + }); + + const instances = yield* registry.listInstances; + expect(instances.map((instance) => instance.instanceId).toSorted()).toEqual( + [personalId, workId].toSorted(), + ); + expect(instances.every((instance) => instance.driverKind === codexDriverKind)).toBe(true); + expect(instances.map((instance) => instance.displayName).toSorted()).toEqual( + ["Codex (personal)", "Codex (work)"].toSorted(), + ); + + // Each instance must be retrievable by id and carry its *own* closures. + const personal = yield* registry.getInstance(personalId); + const work = yield* registry.getInstance(workId); + expect(personal).toBeDefined(); + expect(work).toBeDefined(); + expect(personal!.adapter).not.toBe(work!.adapter); + expect(personal!.textGeneration).not.toBe(work!.textGeneration); + expect(personal!.snapshot).not.toBe(work!.snapshot); + + // Snapshots identify themselves by instanceId + driver — this is + // what makes per-instance routing distinguishable downstream. + const personalSnapshot = yield* personal!.snapshot.getSnapshot; + expect(personalSnapshot.instanceId).toBe(personalId); + expect(personalSnapshot.driver).toBe(codexDriverKind); + expect(personalSnapshot.enabled).toBe(false); + expect(personalSnapshot.continuation?.groupKey).toBe( + "codex:home:/home/julius/.codex_personal", + ); + + const workSnapshot = yield* work!.snapshot.getSnapshot; + expect(workSnapshot.instanceId).toBe(workId); + expect(workSnapshot.driver).toBe(codexDriverKind); + expect(workSnapshot.enabled).toBe(false); + expect(workSnapshot.continuation?.groupKey).toBe("codex:home:/home/julius/.codex"); + + // Nothing goes to the unavailable bucket — both drivers are registered. + const unavailable = yield* registry.listUnavailable; + expect(unavailable).toEqual([]); + }).pipe(Effect.provide(testLayer)), + ); + + it.live( + "shadows instances whose driver is not registered in this build without failing boot", + () => + Effect.gen(function* () { + const codexId = ProviderInstanceId.make("codex_main"); + const ghostId = ProviderInstanceId.make("ghost_main"); + + const configMap: ProviderInstanceConfigMap = { + [codexId]: { + driver: ProviderDriverKind.make("codex"), + enabled: false, + config: makeCodexConfig({}), + }, + [ghostId]: { + driver: ProviderDriverKind.make("ghostDriver"), + displayName: "A fork-only driver we don't ship", + enabled: false, + config: { arbitrary: "payload", preserved: true }, + }, + }; + + const { registry } = yield* makeProviderInstanceRegistry({ + drivers: [CodexDriver], + configMap, + }); + + const instances = yield* registry.listInstances; + expect(instances).toHaveLength(1); + expect(instances[0]!.instanceId).toBe(codexId); + + const unavailable = yield* registry.listUnavailable; + expect(unavailable).toHaveLength(1); + const ghost = unavailable[0]!; + expect(ghost.instanceId).toBe(ghostId); + expect(ghost.driver).toBe("ghostDriver"); + expect(ghost.availability).toBe("unavailable"); + expect(ghost.unavailableReason).toMatch(/ghostDriver/); + }).pipe(Effect.provide(testLayer)), + ); +}); + +describe("ProviderInstanceRegistryLive — all drivers slice", () => { + // All four drivers need `NodeServices` (ChildProcessSpawner + FileSystem + + // Path). `OpenCodeDriver.create` additionally yields `OpenCodeRuntime` + // at construction time, so we wire `OpenCodeRuntimeLive` into the stack. + // `OpenCodeRuntimeLive` bundles its own `NetService.layer` via + // `Layer.provide`, so the only external requirement it still exposes is + // `ChildProcessSpawner` — resolved here by piping it through + // `provideMerge(NodeServices.layer)`. + // + // The nested `provideMerge`s read bottom-up: `NodeServices.layer` + // provides `OpenCodeRuntimeLive`'s deps while keeping its own outputs + // surfaced; that merged layer then provides `ServerConfig.layerTest`'s + // `FileSystem` dep while keeping everything else surfaced to the test. + const infraLayer = OpenCodeRuntimeLive.pipe(Layer.provideMerge(NodeServices.layer)); + const testLayer = ServerConfig.layerTest(process.cwd(), { + prefix: "provider-instance-registry-all-drivers-test", + }).pipe( + Layer.provideMerge(infraLayer), + Layer.provideMerge(Layer.succeed(ProviderEventLoggers, NoOpProviderEventLoggers)), + ); + + it.live("boots one instance of every shipped driver from a single config map", () => + Effect.gen(function* () { + const codexId = ProviderInstanceId.make("codex_default"); + const claudeId = ProviderInstanceId.make("claude_default"); + const cursorId = ProviderInstanceId.make("cursor_default"); + const openCodeId = ProviderInstanceId.make("opencode_default"); + + const codexDriverKind = ProviderDriverKind.make("codex"); + const claudeDriverKind = ProviderDriverKind.make("claudeAgent"); + const cursorDriverKind = ProviderDriverKind.make("cursor"); + const openCodeDriverKind = ProviderDriverKind.make("opencode"); + + const configMap: ProviderInstanceConfigMap = { + [codexId]: { + driver: codexDriverKind, + displayName: "Codex", + enabled: false, + config: makeCodexConfig({ homePath: "/home/julius/.codex" }), + }, + [claudeId]: { + driver: claudeDriverKind, + displayName: "Claude", + enabled: false, + config: makeClaudeConfig({ + homePath: "/home/julius/.claude-work", + launchArgs: "--verbose", + }), + }, + [cursorId]: { + driver: cursorDriverKind, + displayName: "Cursor", + enabled: false, + config: makeCursorConfig({}), + }, + [openCodeId]: { + driver: openCodeDriverKind, + displayName: "OpenCode", + enabled: false, + config: makeOpenCodeConfig({}), + }, + }; + + const { registry } = yield* makeProviderInstanceRegistry({ + drivers: [CodexDriver, ClaudeDriver, CursorDriver, OpenCodeDriver], + configMap, + }); + + // Every configured instance must materialize — none downgraded to a + // shadow snapshot, because every driver in the map is registered. + const unavailable = yield* registry.listUnavailable; + expect(unavailable).toEqual([]); + + const instances = yield* registry.listInstances; + expect(instances).toHaveLength(4); + expect(instances.map((instance) => instance.instanceId).toSorted()).toEqual( + [codexId, claudeId, cursorId, openCodeId].toSorted(), + ); + + // Instance lookup by id resolves each instance to its own bundle — + // this is how rest-of-server routes turn/session calls in the new + // model. Each driver's bundle carries its advertised `driverKind`. + const codex = yield* registry.getInstance(codexId); + const claude = yield* registry.getInstance(claudeId); + const cursor = yield* registry.getInstance(cursorId); + const openCode = yield* registry.getInstance(openCodeId); + expect(codex?.driverKind).toBe(codexDriverKind); + expect(claude?.driverKind).toBe(claudeDriverKind); + expect(cursor?.driverKind).toBe(cursorDriverKind); + expect(openCode?.driverKind).toBe(openCodeDriverKind); + expect(codex?.displayName).toBe("Codex"); + expect(claude?.displayName).toBe("Claude"); + expect(cursor?.displayName).toBe("Cursor"); + expect(openCode?.displayName).toBe("OpenCode"); + + // Every instance owns its own set of closures — no sharing across + // drivers. `adapter` / `textGeneration` / `snapshot` are all + // distinct references even when two instances happen to share a + // trait (e.g. Cursor + others all use a stub-or-real + // `textGeneration`; they must still be different object values). + const adapters = [codex!.adapter, claude!.adapter, cursor!.adapter, openCode!.adapter]; + expect(new Set(adapters).size).toBe(adapters.length); + const textGenerations = [ + codex!.textGeneration, + claude!.textGeneration, + cursor!.textGeneration, + openCode!.textGeneration, + ]; + expect(new Set(textGenerations).size).toBe(textGenerations.length); + const snapshots = [codex!.snapshot, claude!.snapshot, cursor!.snapshot, openCode!.snapshot]; + expect(new Set(snapshots).size).toBe(snapshots.length); + + // Snapshots identify themselves by `instanceId` + `driver` so + // downstream aggregation in `ProviderRegistry` can tell instances + // apart even when two share a driver. With `enabled: false`, the + // check short-circuits and we get a disabled/pending snapshot back + // — that's enough signal to validate the stamping wrapper without + // spawning real binaries. + const codexSnapshot = yield* codex!.snapshot.getSnapshot; + expect(codexSnapshot.instanceId).toBe(codexId); + expect(codexSnapshot.driver).toBe(codexDriverKind); + expect(codexSnapshot.enabled).toBe(false); + expect(codexSnapshot.continuation?.groupKey).toBe("codex:home:/home/julius/.codex"); + + const claudeSnapshot = yield* claude!.snapshot.getSnapshot; + expect(claudeSnapshot.instanceId).toBe(claudeId); + expect(claudeSnapshot.driver).toBe(claudeDriverKind); + expect(claudeSnapshot.enabled).toBe(false); + expect(claudeSnapshot.continuation?.groupKey).toBe("claude:home:/home/julius/.claude-work"); + + const cursorSnapshot = yield* cursor!.snapshot.getSnapshot; + expect(cursorSnapshot.instanceId).toBe(cursorId); + expect(cursorSnapshot.driver).toBe(cursorDriverKind); + expect(cursorSnapshot.enabled).toBe(false); + expect(cursorSnapshot.continuation?.groupKey).toBe( + `${cursorDriverKind}:instance:${cursorId}`, + ); + + const openCodeSnapshot = yield* openCode!.snapshot.getSnapshot; + expect(openCodeSnapshot.instanceId).toBe(openCodeId); + expect(openCodeSnapshot.driver).toBe(openCodeDriverKind); + expect(openCodeSnapshot.enabled).toBe(false); + expect(openCodeSnapshot.continuation?.groupKey).toBe( + `${openCodeDriverKind}:instance:${openCodeId}`, + ); + }).pipe(Effect.provide(testLayer)), + ); +}); diff --git a/apps/server/src/provider/Layers/ProviderInstanceRegistryLive.ts b/apps/server/src/provider/Layers/ProviderInstanceRegistryLive.ts new file mode 100644 index 0000000000..63f687f55b --- /dev/null +++ b/apps/server/src/provider/Layers/ProviderInstanceRegistryLive.ts @@ -0,0 +1,434 @@ +/** + * ProviderInstanceRegistryLive — runtime implementation of + * `ProviderInstanceRegistry` plus its sibling mutator. + * + * Materializes every entry in a `ProviderInstanceConfigMap`: + * + * - When the entry's `driver` matches a registered driver, the registry + * decodes the opaque `config` envelope through `driver.configSchema` + * and calls `driver.create()` inside a fresh child scope. The + * resulting `ProviderInstance` is stored keyed by instance id, + * alongside its scope so the entry can be torn down independently. + * - When the entry's `driver` is unknown to this build (fork, rollback, + * in-flight PR branch), the registry emits an `"unavailable"` shadow + * `ServerProvider` snapshot instead of failing. This is what makes + * downgrades and fork-hopping safe per the + * `forward/backward compatibility invariant` in + * `packages/contracts/src/providerInstance.ts`. + * - When the entry's config fails schema decode, the registry logs and + * emits a shadow snapshot with the schema detail — same bucket as an + * unknown driver. + * + * Unlike the pre-Slice-D layer, the registry now holds mutable state + * (`Ref`s + `PubSub`) and exposes an internal mutator + * (`ProviderInstanceRegistryMutator`) whose `reconcile` method diffs a + * fresh config map against the live state, tearing down removed instances + * and building new ones without disturbing unaffected instances. + * + * Every live instance runs inside its own child `Scope`. The registry's + * own scope owns all child scopes via finalizers, so closing the registry + * tears every instance down in reverse order; closing a single instance + * (via `reconcile` removing it) leaves the rest untouched. + * + * @module provider/Layers/ProviderInstanceRegistryLive + */ +import { + defaultInstanceIdForDriver, + ProviderInstanceId, + type ProviderInstanceConfig, + type ProviderInstanceConfigMap, + type ProviderDriverKind, + type ServerProvider, +} from "@t3tools/contracts"; +import { Context, Effect, Equal, Exit, Layer, PubSub, Ref, Schema, Scope, Stream } from "effect"; + +import { buildUnavailableProviderSnapshot } from "../unavailableProviderSnapshot.ts"; +import { + ProviderInstanceRegistry, + type ProviderInstanceRegistryShape, +} from "../Services/ProviderInstanceRegistry.ts"; +import { + ProviderInstanceRegistryMutator, + type ProviderInstanceRegistryMutatorShape, +} from "../Services/ProviderInstanceRegistryMutator.ts"; +import type { AnyProviderDriver, ProviderInstance } from "../ProviderDriver.ts"; + +/** + * Live registry entry: the materialized `ProviderInstance` + the fresh + * child scope its `create` effect ran in + the original `entry` envelope + * so `reconcile` can cheaply detect "no-op" updates. + */ +interface LiveEntry { + readonly instance: ProviderInstance; + readonly scope: Scope.Closeable; + readonly entry: ProviderInstanceConfig; +} + +/** + * Internal state shared between the public registry service and the + * mutator service. Both services are thin shells around these refs. + */ +interface RegistryState { + readonly entries: Ref.Ref>; + readonly unavailable: Ref.Ref>; + readonly changes: PubSub.PubSub; +} + +/** + * Structural equality on `ProviderInstanceConfig` envelopes. Used by + * `reconcile` to skip rebuilds when settings arrive unchanged. Config + * payloads are opaque `unknown` at the envelope layer; `Equal.equals` + * falls back to structural equality for plain records, which matches how + * the schema decode output is constructed. + */ +const entryEqual = (a: ProviderInstanceConfig, b: ProviderInstanceConfig): boolean => + Equal.equals(a, b); + +const decodedConfigEnabled = (config: unknown): boolean | undefined => { + if (!config || typeof config !== "object" || globalThis.Array.isArray(config)) { + return undefined; + } + const enabled = (config as { readonly enabled?: unknown }).enabled; + return typeof enabled === "boolean" ? enabled : undefined; +}; + +/** + * Build one live entry from a raw config envelope. Returns either a + * `LiveEntry` plus undefined unavailable shadow, or a shadow snapshot and + * undefined entry — callers dispatch to the appropriate Ref bucket. + */ +const buildEntry = (input: { + readonly driversById: ReadonlyMap>; + readonly parentScope: Scope.Scope; + readonly instanceId: ProviderInstanceId; + readonly rawInstanceId: string; + readonly entry: ProviderInstanceConfig; +}): Effect.Effect< + | { readonly kind: "live"; readonly live: LiveEntry } + | { readonly kind: "unavailable"; readonly snapshot: ServerProvider }, + never, + R +> => + Effect.gen(function* () { + const { driversById, parentScope, instanceId, rawInstanceId, entry } = input; + const driver = driversById.get(entry.driver); + if (!driver) { + return { + kind: "unavailable" as const, + snapshot: buildUnavailableProviderSnapshot({ + driverKind: entry.driver, + instanceId, + displayName: entry.displayName, + accentColor: entry.accentColor, + reason: `Driver '${entry.driver}' is not registered in this build.`, + }), + }; + } + + const decoder = Schema.decodeUnknownEffect(driver.configSchema); + const decodeResult = yield* decoder(entry.config ?? driver.defaultConfig()).pipe(Effect.result); + if (decodeResult._tag === "Failure") { + const issue = decodeResult.failure; + const detail = issue.message ?? String(issue); + yield* Effect.logError("Failed to decode provider instance config", { + instanceId: rawInstanceId, + driver: entry.driver, + detail, + }); + return { + kind: "unavailable" as const, + snapshot: buildUnavailableProviderSnapshot({ + driverKind: entry.driver, + instanceId, + displayName: entry.displayName, + accentColor: entry.accentColor, + reason: `Invalid config for instance '${rawInstanceId}': ${detail}`, + }), + }; + } + + const typedConfig = decodeResult.success; + const childScope = yield* Scope.make(); + // Attach the child scope to the registry's parent scope: if the + // registry scope closes, each surviving instance's child scope is + // closed through this finalizer. `reconcile` manually closes the + // child scope on remove/replace; subsequent close via the parent's + // finalizer is a no-op because `Scope.close` is idempotent. + yield* Scope.addFinalizer(parentScope, Scope.close(childScope, Exit.void).pipe(Effect.ignore)); + + const createResult = yield* driver + .create({ + instanceId, + displayName: entry.displayName, + accentColor: entry.accentColor, + environment: entry.environment ?? [], + enabled: entry.enabled ?? decodedConfigEnabled(typedConfig) ?? true, + config: typedConfig, + }) + .pipe(Effect.provideService(Scope.Scope, childScope), Effect.result); + if (createResult._tag === "Failure") { + yield* Effect.logError("Failed to create provider instance", { + instanceId: rawInstanceId, + driver: entry.driver, + detail: createResult.failure.detail, + }); + yield* Scope.close(childScope, Exit.void).pipe(Effect.ignore); + return { + kind: "unavailable" as const, + snapshot: buildUnavailableProviderSnapshot({ + driverKind: entry.driver, + instanceId, + displayName: entry.displayName, + accentColor: entry.accentColor, + reason: `Driver '${entry.driver}' failed to create instance: ${createResult.failure.detail}`, + }), + }; + } + + return { + kind: "live" as const, + live: { + instance: createResult.success, + scope: childScope, + entry, + }, + }; + }); + +/** + * Reconcile-only implementation of the mutator. Exposed to the hydration + * layer; never called directly by the rest of the server. + */ +const makeReconcile = (input: { + readonly state: RegistryState; + readonly driversById: ReadonlyMap>; + readonly parentScope: Scope.Scope; +}): ((configMap: ProviderInstanceConfigMap) => Effect.Effect) => { + const { state, driversById, parentScope } = input; + return (configMap: ProviderInstanceConfigMap) => + Effect.gen(function* () { + const previousEntries = yield* Ref.get(state.entries); + const previousUnavailable = yield* Ref.get(state.unavailable); + const nextRaw = Object.entries(configMap); + const nextKeys = new Set( + nextRaw.map(([raw]) => ProviderInstanceId.make(raw)), + ); + + // 1. Close scopes for instances that disappeared or whose config + // changed. Do this BEFORE creating replacements so ids map 1-to-1 + // to live scopes at all times. + const removedIds: Array = []; + const replacedIds = new Set(); + for (const [instanceId, live] of previousEntries) { + if (!nextKeys.has(instanceId)) { + removedIds.push(instanceId); + continue; + } + const nextEntry = configMap[instanceId]; + if (nextEntry !== undefined && !entryEqual(live.entry, nextEntry)) { + replacedIds.add(instanceId); + } + } + for (const id of [...removedIds, ...replacedIds]) { + const live = previousEntries.get(id); + if (live) { + yield* Scope.close(live.scope, Exit.void).pipe(Effect.ignore); + } + } + + // 2. Build additions and replacements. Walk `nextRaw` so the final + // entry order follows settings-author order. + const builtEntries = new Map(); + const builtUnavailable = new Map(); + let orderChanged = false; + const previousOrder = [...previousEntries.keys()]; + const nextOrder: Array = []; + + for (const [rawInstanceId, entry] of nextRaw) { + const instanceId = ProviderInstanceId.make(rawInstanceId); + nextOrder.push(instanceId); + + const existing = previousEntries.get(instanceId); + if (existing !== undefined && !replacedIds.has(instanceId)) { + // No-op update: keep the existing live entry and scope. + builtEntries.set(instanceId, existing); + continue; + } + + const result = yield* buildEntry({ + driversById, + parentScope, + instanceId, + rawInstanceId, + entry, + }); + if (result.kind === "live") { + builtEntries.set(instanceId, result.live); + } else { + builtUnavailable.set(instanceId, result.snapshot); + } + } + + if (previousOrder.length === nextOrder.length) { + for (let i = 0; i < previousOrder.length; i++) { + if (previousOrder[i] !== nextOrder[i]) { + orderChanged = true; + break; + } + } + } else { + orderChanged = true; + } + + const entriesChanged = + orderChanged || + removedIds.length > 0 || + replacedIds.size > 0 || + builtEntries.size !== previousEntries.size; + const unavailableChanged = + builtUnavailable.size !== previousUnavailable.size || + [...builtUnavailable].some(([id, snapshot]) => { + const prev = previousUnavailable.get(id); + return prev === undefined || !Equal.equals(prev, snapshot); + }) || + [...previousUnavailable].some(([id]) => !builtUnavailable.has(id)); + + yield* Ref.set(state.entries, builtEntries); + yield* Ref.set(state.unavailable, builtUnavailable); + + if (entriesChanged || unavailableChanged) { + yield* PubSub.publish(state.changes, undefined); + } + }); +}; + +/** + * Build the registry's runtime state from a concrete configMap. Returns a + * record containing: + * + * - `registry`: the read-only `ProviderInstanceRegistryShape` to expose + * under `ProviderInstanceRegistry`. + * - `mutator`: the `ProviderInstanceRegistryMutatorShape` to expose + * under `ProviderInstanceRegistryMutator`. + * - `reconcile`: the raw reconcile function, provided for convenience so + * boot-time layers can hydrate an initial map before publishing the + * services. + * + * The scope that this effect runs in owns every per-instance child scope + * created during `reconcile`. Closing that scope closes every live + * instance. + */ +export const makeProviderInstanceRegistry = (input: { + readonly drivers: ReadonlyArray>; + readonly configMap: ProviderInstanceConfigMap; +}): Effect.Effect< + { + readonly registry: ProviderInstanceRegistryShape; + readonly mutator: ProviderInstanceRegistryMutatorShape; + }, + never, + R | Scope.Scope +> => + Effect.gen(function* () { + const driversById = new Map>( + input.drivers.map((driver) => [driver.driverKind, driver]), + ); + + // Capture the enclosing scope so per-instance child scopes can be + // attached to it at `reconcile` time. Without this, `reconcile` + // called later (e.g. from the hydration layer) would attach child + // scopes to the *caller's* scope instead of the registry's. + const parentScope = yield* Scope.Scope; + + // Capture the driver R context at construction time so `reconcile` + // can be invoked later without re-providing driver dependencies. + // The service tag's declared `reconcile: Effect` hides R from + // consumers — we materialize that here. + const driverContext = yield* Effect.context(); + + const entries = yield* Ref.make>(new Map()); + const unavailable = yield* Ref.make>(new Map()); + const changes = yield* PubSub.unbounded(); + yield* Effect.addFinalizer(() => PubSub.shutdown(changes)); + + const state: RegistryState = { entries, unavailable, changes }; + const reconcileWithR = makeReconcile({ state, driversById, parentScope }); + const reconcile: ProviderInstanceRegistryMutatorShape["reconcile"] = (configMap) => + reconcileWithR(configMap).pipe(Effect.provideContext(driverContext)); + + // Hydrate the initial configMap synchronously so callers can read + // `listInstances` immediately after this effect completes. + yield* reconcile(input.configMap); + + const registry: ProviderInstanceRegistryShape = { + getInstance: (id) => Ref.get(entries).pipe(Effect.map((map) => map.get(id)?.instance)), + listInstances: Ref.get(entries).pipe( + Effect.map( + (map) => + Array.from(map.values(), (live) => live.instance) as ReadonlyArray, + ), + ), + listUnavailable: Ref.get(unavailable).pipe( + Effect.map((map) => Array.from(map.values()) as ReadonlyArray), + ), + // Getters: each read constructs a fresh Stream / Effect descriptor + // so multiple consumers don't share a single already-started + // Channel or subscription. Matches the pattern `ProviderRegistry` + // uses for its own `streamChanges`. + get streamChanges() { + return Stream.fromPubSub(changes); + }, + // Synchronous subscribe — callers that need to consume changes + // from a forked fibre must acquire the subscription in their own + // fibre first (via `yield* registry.subscribeChanges`) and only + // then fork a consumer loop on `Stream.fromSubscription(...)` / + // `PubSub.take(...)`. See the shape docs for the race this avoids. + get subscribeChanges() { + return PubSub.subscribe(changes); + }, + }; + + const mutator: ProviderInstanceRegistryMutatorShape = { reconcile }; + + return { registry, mutator }; + }); + +/** + * Assemble a `ProviderInstanceRegistry` Layer bound to a fixed set of + * drivers and a pre-resolved `ProviderInstanceConfigMap`. Used by tests + * that want explicit control over the registry's source-of-truth without + * wiring up the settings watcher. + * + * Only exposes the public registry tag — hot-reload consumers should use + * `ProviderInstanceRegistryMutableLayer` (below) or the hydration layer. + */ +export const ProviderInstanceRegistryLayer = (input: { + readonly drivers: ReadonlyArray>; + readonly configMap: ProviderInstanceConfigMap; +}): Layer.Layer => + Layer.effect( + ProviderInstanceRegistry, + makeProviderInstanceRegistry(input).pipe(Effect.map((built) => built.registry)), + ) as Layer.Layer; + +/** + * Layer variant that also exposes the mutator tag. Consumed by + * `ProviderInstanceRegistryHydrationLive` to reconcile on settings + * changes. Tests that exercise the mutator directly can pair this Layer + * with a test-local `ServerSettingsService`. + */ +export const ProviderInstanceRegistryMutableLayer = (input: { + readonly drivers: ReadonlyArray>; + readonly configMap: ProviderInstanceConfigMap; +}): Layer.Layer => + Layer.effectContext( + makeProviderInstanceRegistry(input).pipe( + Effect.map(({ registry, mutator }) => + Context.make(ProviderInstanceRegistry, registry).pipe( + Context.add(ProviderInstanceRegistryMutator, mutator), + ), + ), + ), + ) as Layer.Layer; + +export { defaultInstanceIdForDriver }; diff --git a/apps/server/src/provider/Layers/ProviderRegistry.test.ts b/apps/server/src/provider/Layers/ProviderRegistry.test.ts index 1df9da6774..75f9c42936 100644 --- a/apps/server/src/provider/Layers/ProviderRegistry.test.ts +++ b/apps/server/src/provider/Layers/ProviderRegistry.test.ts @@ -1,11 +1,16 @@ import * as NodeServices from "@effect/platform-node/NodeServices"; -import { describe, it, assert } from "@effect/vitest"; +import { describe, it, assert, live } from "@effect/vitest"; import { Effect, Exit, Layer, PubSub, Ref, Schema, Scope, Sink, Stream } from "effect"; import * as CodexErrors from "effect-codex-app-server/errors"; import { + ClaudeSettings, + CodexSettings, DEFAULT_SERVER_SETTINGS, + ProviderDriverKind, + ProviderInstanceId, ServerSettings, type ServerProvider, + type ServerProviderSlashCommand, type ServerSettings as ContractServerSettings, } from "@t3tools/contracts"; import * as PlatformError from "effect/PlatformError"; @@ -14,7 +19,10 @@ import { deepMerge } from "@t3tools/shared/Struct"; import { createModelCapabilities } from "@t3tools/shared/model"; import { checkCodexProviderStatus, type CodexAppServerProviderSnapshot } from "./CodexProvider.ts"; -import { checkClaudeProviderStatus, parseClaudeAuthStatusFromOutput } from "./ClaudeProvider.ts"; +import { checkClaudeProviderStatus } from "./ClaudeProvider.ts"; +import { OpenCodeRuntimeLive } from "../opencodeRuntime.ts"; +import { NoOpProviderEventLoggers, ProviderEventLoggers } from "./ProviderEventLoggers.ts"; +import { ProviderInstanceRegistryHydrationLive } from "./ProviderInstanceRegistryHydration.ts"; import { haveProvidersChanged, mergeProviderSnapshot, @@ -22,8 +30,16 @@ import { } from "./ProviderRegistry.ts"; import { ServerConfig } from "../../config.ts"; import { ServerSettingsService, type ServerSettingsShape } from "../../serverSettings.ts"; +import type { ProviderInstance } from "../ProviderDriver.ts"; +import { ProviderInstanceRegistry } from "../Services/ProviderInstanceRegistry.ts"; import { ProviderRegistry } from "../Services/ProviderRegistry.ts"; +const defaultClaudeSettings: ClaudeSettings = Schema.decodeSync(ClaudeSettings)({}); +const defaultCodexSettings: CodexSettings = Schema.decodeSync(CodexSettings)({}); +const disabledCodexSettings: CodexSettings = Schema.decodeSync(CodexSettings)({ + enabled: false, +}); + process.env.T3CODE_CURSOR_ENABLED = "1"; // ── Test helpers ──────────────────────────────────────────────────── @@ -54,6 +70,27 @@ function booleanDescriptor(id: string, label: string) { }; } +type TestClaudeCapabilities = { + readonly email: string | undefined; + readonly subscriptionType: string | undefined; + readonly tokenSource: string | undefined; + readonly slashCommands: ReadonlyArray; +}; + +function claudeCapabilities(overrides: Partial = {}) { + return () => + Effect.succeed({ + email: undefined, + subscriptionType: undefined, + tokenSource: undefined, + slashCommands: [], + ...overrides, + }); +} + +const noClaudeCapabilities = () => + Effect.sync(() => undefined as TestClaudeCapabilities | undefined); + function mockHandle(result: { stdout: string; stderr: string; code: number }) { return ChildProcessSpawner.makeHandle({ pid: ChildProcessSpawner.ProcessId(1), @@ -71,7 +108,11 @@ function mockHandle(result: { stdout: string; stderr: string; code: number }) { } function mockSpawnerLayer( - handler: (args: ReadonlyArray) => { stdout: string; stderr: string; code: number }, + handler: (args: ReadonlyArray) => { + stdout: string; + stderr: string; + code: number; + }, ) { return Layer.succeed( ChildProcessSpawner.ChildProcessSpawner, @@ -82,6 +123,33 @@ function mockSpawnerLayer( ); } +function recordingMockSpawnerLayer( + handler: (args: ReadonlyArray) => { + stdout: string; + stderr: string; + code: number; + }, +) { + const commands: Array<{ + readonly args: ReadonlyArray; + readonly env: NodeJS.ProcessEnv | undefined; + }> = []; + const layer = Layer.succeed( + ChildProcessSpawner.ChildProcessSpawner, + ChildProcessSpawner.make((command) => { + const cmd = command as unknown as { + args: ReadonlyArray; + options?: { + readonly env?: NodeJS.ProcessEnv; + }; + }; + commands.push({ args: cmd.args, env: cmd.options?.env }); + return Effect.succeed(mockHandle(handler(cmd.args))); + }), + ); + return { layer, commands }; +} + function mockCommandSpawnerLayer( handler: ( command: string, @@ -91,7 +159,10 @@ function mockCommandSpawnerLayer( return Layer.succeed( ChildProcessSpawner.ChildProcessSpawner, ChildProcessSpawner.make((command) => { - const cmd = command as unknown as { command: string; args: ReadonlyArray }; + const cmd = command as unknown as { + command: string; + args: ReadonlyArray; + }; return Effect.succeed(mockHandle(handler(cmd.command, cmd.args))); }), ); @@ -181,7 +252,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))( describe("checkCodexProviderStatus", () => { it.effect("uses the app-server account and model list for provider status", () => Effect.gen(function* () { - const status = yield* checkCodexProviderStatus(() => + const status = yield* checkCodexProviderStatus(defaultCodexSettings, () => Effect.succeed( makeCodexProbeSnapshot({ skills: [ @@ -196,14 +267,13 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))( }), ), ); - - assert.strictEqual(status.provider, "codex"); assert.strictEqual(status.status, "ready"); assert.strictEqual(status.installed, true); assert.strictEqual(status.version, "1.0.0"); assert.strictEqual(status.auth.status, "authenticated"); assert.strictEqual(status.auth.type, "chatgpt"); assert.strictEqual(status.auth.label, "ChatGPT Pro 20x Subscription"); + assert.strictEqual(status.auth.email, "test@example.com"); assert.deepStrictEqual(status.models, [ { slug: "gpt-live-codex", @@ -226,7 +296,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))( it.effect("returns unauthenticated when app-server requires OpenAI auth", () => Effect.gen(function* () { - const status = yield* checkCodexProviderStatus(() => + const status = yield* checkCodexProviderStatus(defaultCodexSettings, () => Effect.succeed( makeCodexProbeSnapshot({ account: { @@ -250,7 +320,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))( "returns ready with unknown auth when app-server does not require OpenAI auth", () => Effect.gen(function* () { - const status = yield* checkCodexProviderStatus(() => + const status = yield* checkCodexProviderStatus(defaultCodexSettings, () => Effect.succeed( makeCodexProbeSnapshot({ account: { @@ -268,7 +338,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))( it.effect("returns an api key label for codex api key auth", () => Effect.gen(function* () { - const status = yield* checkCodexProviderStatus(() => + const status = yield* checkCodexProviderStatus(defaultCodexSettings, () => Effect.succeed( makeCodexProbeSnapshot({ account: { @@ -288,7 +358,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))( it.effect("returns unavailable when codex is missing", () => Effect.gen(function* () { - const status = yield* checkCodexProviderStatus(() => + const status = yield* checkCodexProviderStatus(defaultCodexSettings, () => Effect.fail( new CodexErrors.CodexAppServerSpawnError({ command: "codex app-server", @@ -296,7 +366,6 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))( }), ), ); - assert.strictEqual(status.provider, "codex"); assert.strictEqual(status.status, "error"); assert.strictEqual(status.installed, false); assert.strictEqual(status.auth.status, "unknown"); @@ -312,7 +381,8 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))( it("treats equal provider snapshots as unchanged", () => { const providers = [ { - provider: "codex", + instanceId: ProviderInstanceId.make("codex"), + driver: ProviderDriverKind.make("codex"), status: "ready", enabled: true, installed: true, @@ -324,7 +394,8 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))( skills: [], }, { - provider: "claudeAgent", + instanceId: ProviderInstanceId.make("claudeAgent"), + driver: ProviderDriverKind.make("claudeAgent"), status: "warning", enabled: true, installed: true, @@ -342,7 +413,8 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))( it("preserves previously discovered provider models when a refresh returns none", () => { const previousProvider = { - provider: "cursor", + instanceId: ProviderInstanceId.make("cursor"), + driver: ProviderDriverKind.make("cursor"), status: "ready", enabled: true, installed: true, @@ -381,7 +453,8 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))( it("fills missing capabilities from the previous provider snapshot", () => { const previousProvider = { - provider: "cursor", + instanceId: ProviderInstanceId.make("cursor"), + driver: ProviderDriverKind.make("cursor"), status: "ready", enabled: true, installed: true, @@ -427,41 +500,261 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))( ]); }); - it.effect("probes enabled providers in the background during registry startup", () => + it.effect("returns the cached provider list when a manual refresh fails", () => Effect.gen(function* () { - let spawnCount = 0; + const codexDriver = ProviderDriverKind.make("codex"); + const codexInstanceId = ProviderInstanceId.make("codex"); + const cachedProvider = { + instanceId: codexInstanceId, + driver: codexDriver, + status: "ready", + enabled: true, + installed: true, + auth: { status: "authenticated" }, + checkedAt: "2026-04-29T10:00:00.000Z", + version: "1.0.0", + models: [], + slashCommands: [], + skills: [], + } as const satisfies ServerProvider; + const instance = { + instanceId: codexInstanceId, + driverKind: codexDriver, + continuationIdentity: { + driverKind: codexDriver, + continuationKey: "codex:instance:codex", + }, + displayName: undefined, + enabled: true, + snapshot: { + getSnapshot: Effect.succeed(cachedProvider), + refresh: Effect.die(new Error("simulated refresh failure")), + streamChanges: Stream.empty, + }, + adapter: {} as ProviderInstance["adapter"], + textGeneration: {} as ProviderInstance["textGeneration"], + } satisfies ProviderInstance; + const instanceRegistryLayer = Layer.succeed(ProviderInstanceRegistry, { + getInstance: (instanceId) => + Effect.succeed(instanceId === codexInstanceId ? instance : undefined), + listInstances: Effect.succeed([instance]), + listUnavailable: Effect.succeed([]), + streamChanges: Stream.empty, + subscribeChanges: Effect.flatMap(PubSub.unbounded(), (pubsub) => + PubSub.subscribe(pubsub), + ), + }); + const scope = yield* Scope.make(); + yield* Effect.addFinalizer(() => Scope.close(scope, Exit.void)); + const runtimeServices = yield* Layer.build( + ProviderRegistryLive.pipe( + Layer.provideMerge(instanceRegistryLayer), + Layer.provideMerge( + ServerConfig.layerTest(process.cwd(), { + prefix: "t3-provider-registry-refresh-failure-", + }), + ), + Layer.provideMerge(NodeServices.layer), + ), + ).pipe(Scope.provide(scope)); + + yield* Effect.gen(function* () { + const registry = yield* ProviderRegistry; + + assert.deepStrictEqual(yield* registry.getProviders, [cachedProvider]); + assert.deepStrictEqual(yield* registry.refresh(codexDriver), [cachedProvider]); + assert.deepStrictEqual(yield* registry.refreshInstance(codexInstanceId), [ + cachedProvider, + ]); + }).pipe(Effect.provide(runtimeServices)); + }), + ); + + it.effect("keeps consuming registry changes after one sync fails", () => + Effect.gen(function* () { + const codexDriver = ProviderDriverKind.make("codex"); + const codexInstanceId = ProviderInstanceId.make("codex"); + const claudeDriver = ProviderDriverKind.make("claudeAgent"); + const claudeInstanceId = ProviderInstanceId.make("claudeAgent"); + const codexProvider = { + instanceId: codexInstanceId, + driver: codexDriver, + status: "ready", + enabled: true, + installed: true, + auth: { status: "authenticated" }, + checkedAt: "2026-04-29T10:00:00.000Z", + version: "1.0.0", + models: [], + slashCommands: [], + skills: [], + } as const satisfies ServerProvider; + const claudeProvider = { + instanceId: claudeInstanceId, + driver: claudeDriver, + status: "ready", + enabled: true, + installed: true, + auth: { status: "authenticated" }, + checkedAt: "2026-04-29T10:01:00.000Z", + version: "1.0.0", + models: [], + slashCommands: [], + skills: [], + } as const satisfies ServerProvider; + const makeInstance = (provider: ServerProvider): ProviderInstance => ({ + instanceId: provider.instanceId, + driverKind: provider.driver, + continuationIdentity: { + driverKind: provider.driver, + continuationKey: `${provider.driver}:instance:${provider.instanceId}`, + }, + displayName: undefined, + enabled: true, + snapshot: { + getSnapshot: Effect.succeed(provider), + refresh: Effect.succeed(provider), + streamChanges: Stream.empty, + }, + adapter: {} as ProviderInstance["adapter"], + textGeneration: {} as ProviderInstance["textGeneration"], + }); + const codexInstance = makeInstance(codexProvider); + const claudeInstance = makeInstance(claudeProvider); + const changes = yield* PubSub.unbounded(); + const instancesRef = yield* Ref.make>([codexInstance]); + const failNextList = yield* Ref.make(false); + const wait = (millis: number) => + Effect.promise(() => new Promise((resolve) => setTimeout(resolve, millis))); + const instanceRegistryLayer = Layer.succeed(ProviderInstanceRegistry, { + getInstance: (instanceId) => + Ref.get(instancesRef).pipe( + Effect.map((instances) => + instances.find((instance) => instance.instanceId === instanceId), + ), + ), + listInstances: Effect.gen(function* () { + const shouldFail = yield* Ref.get(failNextList); + if (shouldFail) { + yield* Ref.set(failNextList, false); + return yield* Effect.die(new Error("simulated registry list failure")); + } + return yield* Ref.get(instancesRef); + }), + listUnavailable: Effect.succeed([]), + streamChanges: Stream.fromPubSub(changes), + subscribeChanges: PubSub.subscribe(changes), + }); + const scope = yield* Scope.make(); + yield* Effect.addFinalizer(() => Scope.close(scope, Exit.void)); + const runtimeServices = yield* Layer.build( + ProviderRegistryLive.pipe( + Layer.provideMerge(instanceRegistryLayer), + Layer.provideMerge( + ServerConfig.layerTest(process.cwd(), { + prefix: "t3-provider-registry-sync-failure-", + }), + ), + Layer.provideMerge(NodeServices.layer), + ), + ).pipe(Scope.provide(scope)); + + yield* Effect.gen(function* () { + const registry = yield* ProviderRegistry; + assert.deepStrictEqual(yield* registry.getProviders, [codexProvider]); + + yield* Ref.set(failNextList, true); + yield* PubSub.publish(changes, undefined); + + yield* Ref.set(instancesRef, [codexInstance, claudeInstance]); + yield* PubSub.publish(changes, undefined); + + let providers = yield* registry.getProviders; + for ( + let attempt = 0; + attempt < 50 && + !providers.some((provider) => provider.instanceId === claudeInstanceId); + attempt += 1 + ) { + yield* wait(10); + providers = yield* registry.getProviders; + } + + assert.deepStrictEqual( + providers.map((provider) => provider.instanceId).toSorted(), + [codexInstanceId, claudeInstanceId].toSorted(), + ); + }).pipe(Effect.provide(runtimeServices)); + }), + ); + + // This test intentionally avoids `mockCommandSpawnerLayer` so the real + // `probeCodexAppServerProvider` path runs — including the full + // `codex app-server` RPC handshake via `CodexClient.layerCommand`. + // We point `binaryPath` at a name that cannot exist on any machine so + // the real `ChildProcessSpawner` deterministically returns ENOENT; the + // probe wraps that as `CodexAppServerSpawnError` and + // `checkCodexProviderStatus` turns it into the user-visible "not + // installed" error snapshot. If the aggregator's `syncLiveSources` + // breaks — the `codex_personal`-never-probes bug we are guarding + // against — that snapshot never lands in `getProviders` and the + // assertions below fail. + it.effect("propagates real Codex probe failures to the aggregator at boot", () => + Effect.gen(function* () { + const missingBinary = `t3code_codex_missing_${process.pid}_${Date.now()}`; const serverSettings = yield* makeMutableServerSettingsService( Schema.decodeSync(ServerSettings)( deepMerge(DEFAULT_SERVER_SETTINGS, { providers: { + // Disable every built-in probe that would otherwise spawn + // on the CI host. `enabled: false` short-circuits each + // driver's probe *before* it touches the spawner, so the + // test environment stays isolated from the dev + // machine's PATH. codex: { enabled: false }, + claudeAgent: { enabled: false }, cursor: { enabled: false }, + opencode: { enabled: false }, }, + // `providerInstances` keys are branded `ProviderInstanceId`; + // the branded index signature rejects plain string literals + // at the TS level even though the runtime schema happily + // accepts + decodes them. Cast the patch to `unknown` so + // the `Schema.decodeSync` below does the real validation. + providerInstances: { + // Matches the shape the user had in `.t3/dev/settings.json` + // when the bug was reported: a custom enabled Codex instance + // pointing at a binary the server has to actually spawn. + codex_personal: { + driver: "codex", + displayName: "Codex Personal", + enabled: true, + config: { + binaryPath: missingBinary, + homePath: `/tmp/${missingBinary}_home`, + }, + }, + } as unknown as ContractServerSettings["providerInstances"], }), ), ); const scope = yield* Scope.make(); yield* Effect.addFinalizer(() => Scope.close(scope, Exit.void)); const providerRegistryLayer = ProviderRegistryLive.pipe( + Layer.provideMerge(ProviderInstanceRegistryHydrationLive), Layer.provideMerge(Layer.succeed(ServerSettingsService, serverSettings)), Layer.provideMerge( ServerConfig.layerTest(process.cwd(), { prefix: "t3-provider-registry-", }), ), - Layer.provideMerge( - mockCommandSpawnerLayer((command, args) => { - spawnCount += 1; - const joined = args.join(" "); - if (joined === "--version") { - return { stdout: "claude 1.0.0\n", stderr: "", code: 0 }; - } - if (joined === "auth status") { - return { stdout: '{"authenticated":true}\n', stderr: "", code: 0 }; - } - throw new Error(`Unexpected args: ${command} ${joined}`); - }), - ), + Layer.provideMerge(Layer.succeed(ProviderEventLoggers, NoOpProviderEventLoggers)), + Layer.provideMerge(OpenCodeRuntimeLive), + // NO spawner mock — `ChildProcessSpawner` is supplied by the + // outer `NodeServices.layer` on `it.layer(...)` and will + // genuinely spawn a subprocess. The missing-binary ENOENT is + // what exercises the same failure mode as a misconfigured + // production `binaryPath`. ); const runtimeServices = yield* Layer.build(providerRegistryLayer).pipe( Scope.provide(scope), @@ -469,24 +762,197 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))( yield* Effect.gen(function* () { const registry = yield* ProviderRegistry; - assert.strictEqual(spawnCount > 0, true); + const providers = yield* registry.getProviders; + const codexPersonal = providers.find( + (provider) => provider.instanceId === "codex_personal", + ); + assert.notStrictEqual( + codexPersonal, + undefined, + `Expected the aggregator to know about codex_personal; instead saw: ${providers + .map((provider) => provider.instanceId) + .join(", ")}`, + ); + assert.strictEqual( + codexPersonal?.status, + "error", + "Real Codex probe against a missing binary should surface as 'error' in the aggregator", + ); + assert.strictEqual(codexPersonal?.installed, false); + assert.strictEqual( + codexPersonal?.message, + "Codex CLI (`codex`) is not installed or not on PATH.", + ); + }).pipe(Effect.provide(runtimeServices)); + }), + ); + + // Guards the second half of the reported bug: changing + // `providers.codex.binaryPath` in settings must tear down the live + // instance and rebuild it so a fresh probe runs with the new binary. + // This test drives the real settings stream → registry reconcile → + // aggregator sync pipeline and asserts that `getProviders` reflects + // the new probe's outcome. If `syncLiveSources` stops awaiting the + // rebuilt instance's refresh (previous bug mode), the aggregator + // keeps the old snapshot and this test fails. + // + // `live` (imported from `@effect/vitest`) is used instead of + // `it.effect` so real timers coordinate the fibres that drive the + // settings → reconcile → sync pipeline. Under `it.effect`'s + // TestClock, `Effect.sleep` blocks until `TestClock.adjust`, which + // would require this test to reach into the internals of the + // reconcile pipeline to advance it step by step. + // + // The nested `it` handed to `it.layer(…, (it) => …)` is the + // `MethodsNonLive` variant and therefore lacks `.live`; the + // top-level `live` export from `@effect/vitest` is the equivalent. + live("re-probes when settings change the codex binaryPath", () => + Effect.gen(function* () { + const firstMissing = `t3code_codex_first_${process.pid}_${Date.now()}`; + const secondMissing = `t3code_codex_second_${process.pid}_${Date.now()}`; + const serverSettings = yield* makeMutableServerSettingsService( + Schema.decodeSync(ServerSettings)( + deepMerge(DEFAULT_SERVER_SETTINGS, { + providers: { + codex: { enabled: true, binaryPath: firstMissing }, + claudeAgent: { enabled: false }, + cursor: { enabled: false }, + opencode: { enabled: false }, + }, + }), + ), + ); + const scope = yield* Scope.make(); + yield* Effect.addFinalizer(() => Scope.close(scope, Exit.void)); + const providerRegistryLayer = ProviderRegistryLive.pipe( + Layer.provideMerge(ProviderInstanceRegistryHydrationLive), + Layer.provideMerge(Layer.succeed(ServerSettingsService, serverSettings)), + Layer.provideMerge( + ServerConfig.layerTest(process.cwd(), { + prefix: "t3-provider-registry-", + }), + ), + Layer.provideMerge(Layer.succeed(ProviderEventLoggers, NoOpProviderEventLoggers)), + Layer.provideMerge(OpenCodeRuntimeLive), + // `it.live` does not inherit layers from the outer `it.layer` + // wrapper, so provide `NodeServices.layer` inline. This is the + // same real `ChildProcessSpawner` + `FileSystem` + `Path` + // services that production uses. + Layer.provideMerge(NodeServices.layer), + ); + const runtimeServices = yield* Layer.build(providerRegistryLayer).pipe( + Scope.provide(scope), + ); + + yield* Effect.gen(function* () { + const registry = yield* ProviderRegistry; + // Boot-time probe: the default codex instance is enabled with + // `firstMissing`, so the real spawner yields ENOENT and the + // snapshot should be `status: "error"`. What *distinguishes* + // the two probe runs is `checkedAt` — each probe stamps a + // fresh DateTime, so we capture it and assert it advances + // after the settings mutation. + const initialProviders = yield* registry.getProviders; + const initialCodex = initialProviders.find( + (provider) => provider.instanceId === "codex", + ); + assert.strictEqual(initialCodex?.status, "error"); + assert.strictEqual(initialCodex?.installed, false); + const initialCheckedAt = initialCodex?.checkedAt; + assert.notStrictEqual(initialCheckedAt, undefined); + + // Drive a settings change. The Hydration layer's + // `SettingsWatcherLive` consumes this via `streamChanges`, + // calls `reconcile`, which rebuilds the codex instance (the + // envelope changed because `binaryPath` differs → `entryEqual` + // is false). The registry's `Stream.runForEach( + // instanceRegistry.streamChanges, () => syncLiveSources)` + // fires `syncLiveSources`, which subscribes + awaits a fresh + // refresh on the rebuilt instance. + yield* serverSettings.updateSettings({ + providers: { + codex: { enabled: true, binaryPath: secondMissing }, + }, + }); + + // Poll with real timers (via `it.live`) until `checkedAt` + // advances or we hit a generous 3-second ceiling. Anything + // slower than that is a regression — the real probe fails + // fast on ENOENT, and the reconcile + sync pipeline is + // purely in-process. const refreshed = yield* Effect.gen(function* () { - for (let remainingAttempts = 50; remainingAttempts > 0; remainingAttempts -= 1) { + for (let attempts = 0; attempts < 60; attempts += 1) { const providers = yield* registry.getProviders; - const claudeProvider = providers.find( - (provider) => provider.provider === "claudeAgent", - ); - if (claudeProvider?.status === "ready") { + const codex = providers.find((provider) => provider.instanceId === "codex"); + if (codex !== undefined && codex.checkedAt !== initialCheckedAt) { return providers; } - yield* Effect.sleep("10 millis"); + yield* Effect.sleep("50 millis"); } return yield* registry.getProviders; }); - assert.strictEqual( - refreshed.find((provider) => provider.provider === "claudeAgent")?.status, - "ready", + + const reprobedCodex = refreshed.find((provider) => provider.instanceId === "codex"); + assert.notStrictEqual( + reprobedCodex?.checkedAt, + initialCheckedAt, + "Expected a fresh probe after settings change, got the stale snapshot", ); + assert.strictEqual(reprobedCodex?.status, "error"); + assert.strictEqual(reprobedCodex?.installed, false); + }).pipe(Effect.provide(runtimeServices)); + }), + ); + + it.effect("includes unavailable instance snapshots in getProviders", () => + Effect.gen(function* () { + const serverSettings = yield* makeMutableServerSettingsService( + Schema.decodeSync(ServerSettings)( + deepMerge(DEFAULT_SERVER_SETTINGS, { + providers: { + codex: { enabled: false }, + claudeAgent: { enabled: false }, + cursor: { enabled: false }, + opencode: { enabled: false }, + }, + providerInstances: { + ghost_main: { + driver: "ghostDriver", + displayName: "A fork-only driver we don't ship", + enabled: false, + config: { arbitrary: "payload" }, + }, + } as unknown as ContractServerSettings["providerInstances"], + }), + ), + ); + const scope = yield* Scope.make(); + yield* Effect.addFinalizer(() => Scope.close(scope, Exit.void)); + const providerRegistryLayer = ProviderRegistryLive.pipe( + Layer.provideMerge(ProviderInstanceRegistryHydrationLive), + Layer.provideMerge(Layer.succeed(ServerSettingsService, serverSettings)), + Layer.provideMerge( + ServerConfig.layerTest(process.cwd(), { + prefix: "t3-provider-registry-", + }), + ), + Layer.provideMerge(Layer.succeed(ProviderEventLoggers, NoOpProviderEventLoggers)), + Layer.provideMerge(OpenCodeRuntimeLive), + Layer.provideMerge(NodeServices.layer), + ); + const runtimeServices = yield* Layer.build(providerRegistryLayer).pipe( + Scope.provide(scope), + ); + + yield* Effect.gen(function* () { + const registry = yield* ProviderRegistry; + const providers = yield* registry.getProviders; + const ghost = providers.find((provider) => provider.instanceId === "ghost_main"); + + assert.notStrictEqual(ghost, undefined); + assert.strictEqual(ghost?.driver, "ghostDriver"); + assert.strictEqual(ghost?.availability, "unavailable"); + assert.match(ghost?.unavailableReason ?? "", /ghostDriver/); }).pipe(Effect.provide(runtimeServices)); }), ); @@ -513,12 +979,15 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))( const scope = yield* Scope.make(); yield* Effect.addFinalizer(() => Scope.close(scope, Exit.void)); const providerRegistryLayer = ProviderRegistryLive.pipe( + Layer.provideMerge(ProviderInstanceRegistryHydrationLive), Layer.provideMerge(Layer.succeed(ServerSettingsService, serverSettings)), Layer.provideMerge( ServerConfig.layerTest(process.cwd(), { prefix: "t3-provider-registry-", }), ), + Layer.provideMerge(Layer.succeed(ProviderEventLoggers, NoOpProviderEventLoggers)), + Layer.provideMerge(OpenCodeRuntimeLive), Layer.provideMerge( mockCommandSpawnerLayer((command, args) => { if (command === "agent") { @@ -526,10 +995,18 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))( } const joined = args.join(" "); if (joined === "--version") { - return { stdout: `${command} 1.0.0\n`, stderr: "", code: 0 }; + return { + stdout: `${command} 1.0.0\n`, + stderr: "", + code: 0, + }; } if (joined === "auth status") { - return { stdout: '{"authenticated":true}\n', stderr: "", code: 0 }; + return { + stdout: '{"authenticated":true}\n', + stderr: "", + code: 0, + }; } throw new Error(`Unexpected args: ${command} ${joined}`); }), @@ -545,12 +1022,16 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))( yield* Effect.gen(function* () { const registry = yield* ProviderRegistry; const providers = yield* registry.getProviders; - const cursorProvider = providers.find((provider) => provider.provider === "cursor"); - - assert.deepStrictEqual( - providers.map((provider) => provider.provider), - ["codex", "claudeAgent", "opencode", "cursor"], + const cursorProvider = providers.find( + (provider) => provider.instanceId === ProviderInstanceId.make("cursor"), ); + + assert.deepStrictEqual(providers.map((provider) => provider.instanceId).toSorted(), [ + "claudeAgent", + "codex", + "cursor", + "opencode", + ]); assert.strictEqual(cursorProvider?.enabled, false); assert.strictEqual(cursorProvider?.status, "disabled"); assert.strictEqual( @@ -564,20 +1045,9 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))( it.effect("skips codex probes entirely when the provider is disabled", () => Effect.gen(function* () { - const serverSettingsLayer = ServerSettingsService.layerTest({ - providers: { - codex: { - enabled: false, - }, - }, - }); - - const status = yield* checkCodexProviderStatus().pipe( - Effect.provide( - Layer.mergeAll(serverSettingsLayer, failingSpawnerLayer("spawn codex ENOENT")), - ), + const status = yield* checkCodexProviderStatus(disabledCodexSettings).pipe( + Effect.provide(failingSpawnerLayer("spawn codex ENOENT")), ); - assert.strictEqual(status.provider, "codex"); assert.strictEqual(status.enabled, false); assert.strictEqual(status.status, "disabled"); assert.strictEqual(status.installed, false); @@ -591,8 +1061,10 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))( describe("checkClaudeProviderStatus", () => { it.effect("returns ready when claude is installed and authenticated", () => Effect.gen(function* () { - const status = yield* checkClaudeProviderStatus(); - assert.strictEqual(status.provider, "claudeAgent"); + const status = yield* checkClaudeProviderStatus( + defaultClaudeSettings, + claudeCapabilities(), + ); assert.strictEqual(status.status, "ready"); assert.strictEqual(status.installed, true); assert.strictEqual(status.auth.status, "authenticated"); @@ -617,7 +1089,10 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))( "includes Claude Opus 4.7 with xhigh as the default effort on supported versions", () => Effect.gen(function* () { - const status = yield* checkClaudeProviderStatus(); + const status = yield* checkClaudeProviderStatus( + defaultClaudeSettings, + claudeCapabilities(), + ); const opus47 = status.models.find((model) => model.slug === "claude-opus-4-7"); if (!opus47) { assert.fail("Expected Claude Opus 4.7 to be present for Claude Code v2.1.111."); @@ -655,7 +1130,10 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))( it.effect("hides Claude Opus 4.7 on older Claude Code versions", () => Effect.gen(function* () { - const status = yield* checkClaudeProviderStatus(); + const status = yield* checkClaudeProviderStatus( + defaultClaudeSettings, + claudeCapabilities(), + ); assert.strictEqual( status.models.some((model) => model.slug === "claude-opus-4-7"), false, @@ -683,8 +1161,10 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))( it.effect("returns a display label for claude subscription types", () => Effect.gen(function* () { - const status = yield* checkClaudeProviderStatus(() => Effect.succeed("maxplan")); - assert.strictEqual(status.provider, "claudeAgent"); + const status = yield* checkClaudeProviderStatus( + defaultClaudeSettings, + claudeCapabilities({ subscriptionType: "maxplan" }), + ); assert.strictEqual(status.status, "ready"); assert.strictEqual(status.auth.status, "authenticated"); assert.strictEqual(status.auth.type, "maxplan"); @@ -706,18 +1186,120 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))( ), ); + it.effect("does not duplicate Claude in full subscription labels", () => + Effect.gen(function* () { + const status = yield* checkClaudeProviderStatus( + defaultClaudeSettings, + claudeCapabilities({ + subscriptionType: "Claude Max Subscription", + }), + ); + assert.strictEqual(status.auth.status, "authenticated"); + assert.strictEqual(status.auth.type, "Claude Max Subscription"); + assert.strictEqual(status.auth.label, "Claude Max Subscription"); + }).pipe( + Effect.provide( + mockSpawnerLayer((args) => { + const joined = args.join(" "); + if (joined === "--version") return { stdout: "1.0.0\n", stderr: "", code: 0 }; + throw new Error(`Unexpected args: ${joined}`); + }), + ), + ), + ); + + it.effect("does not duplicate Claude in provider-prefixed subscription names", () => + Effect.gen(function* () { + const status = yield* checkClaudeProviderStatus( + defaultClaudeSettings, + claudeCapabilities({ + subscriptionType: "Claude Max", + }), + ); + assert.strictEqual(status.auth.status, "authenticated"); + assert.strictEqual(status.auth.type, "Claude Max"); + assert.strictEqual(status.auth.label, "Claude Max Subscription"); + }).pipe( + Effect.provide( + mockSpawnerLayer((args) => { + const joined = args.join(" "); + if (joined === "--version") return { stdout: "1.0.0\n", stderr: "", code: 0 }; + throw new Error(`Unexpected args: ${joined}`); + }), + ), + ), + ); + + it.effect("returns claude auth email from initialization result", () => + Effect.gen(function* () { + const status = yield* checkClaudeProviderStatus( + defaultClaudeSettings, + claudeCapabilities({ email: "claude@example.com" }), + ); + assert.strictEqual(status.auth.status, "authenticated"); + assert.strictEqual(status.auth.email, "claude@example.com"); + }).pipe( + Effect.provide( + mockSpawnerLayer((args) => { + const joined = args.join(" "); + if (joined === "--version") return { stdout: "1.0.0\n", stderr: "", code: 0 }; + if (joined === "auth status") + return { + stdout: + '{"loggedIn":true,"authMethod":"claude.ai","account":{"email":"claude@example.com"}}\n', + stderr: "", + code: 0, + }; + throw new Error(`Unexpected args: ${joined}`); + }), + ), + ), + ); + + it.effect("runs Claude status probes with the configured Claude HOME", () => { + const claudeHome = "/tmp/t3code-claude-home"; + const recorded = recordingMockSpawnerLayer((args) => { + const joined = args.join(" "); + if (joined === "--version") return { stdout: "1.0.0\n", stderr: "", code: 0 }; + if (joined === "auth status") + return { + stdout: '{"loggedIn":true,"authMethod":"claude.ai"}\n', + stderr: "", + code: 0, + }; + throw new Error(`Unexpected args: ${joined}`); + }); + + return Effect.gen(function* () { + const status = yield* checkClaudeProviderStatus( + { + ...defaultClaudeSettings, + homePath: claudeHome, + }, + claudeCapabilities(), + ); + assert.strictEqual(status.status, "ready"); + assert.deepStrictEqual( + recorded.commands.map((command) => command.env?.HOME), + [claudeHome], + ); + }).pipe(Effect.provide(recorded.layer)); + }); + it.effect("includes probed claude slash commands in the provider snapshot", () => Effect.gen(function* () { const status = yield* checkClaudeProviderStatus( - () => Effect.succeed("maxplan"), - () => - Effect.succeed([ + defaultClaudeSettings, + claudeCapabilities({ + subscriptionType: "maxplan", + slashCommands: [ { name: "review", description: "Review a pull request", input: { hint: "pr-or-branch" }, }, - ]), + ], + }), ); assert.deepStrictEqual(status.slashCommands, [ @@ -747,9 +1329,10 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))( it.effect("deduplicates probed claude slash commands by name", () => Effect.gen(function* () { const status = yield* checkClaudeProviderStatus( - () => Effect.succeed("maxplan"), - () => - Effect.succeed([ + defaultClaudeSettings, + claudeCapabilities({ + subscriptionType: "maxplan", + slashCommands: [ { name: "ui", description: "Explore and refine UI", @@ -758,7 +1341,8 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))( name: "ui", input: { hint: "component-or-screen" }, }, - ]), + ], + }), ); assert.deepStrictEqual(status.slashCommands, [ @@ -787,8 +1371,10 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))( it.effect("returns an api key label for claude api key auth", () => Effect.gen(function* () { - const status = yield* checkClaudeProviderStatus(); - assert.strictEqual(status.provider, "claudeAgent"); + const status = yield* checkClaudeProviderStatus( + defaultClaudeSettings, + claudeCapabilities({ tokenSource: "ANTHROPIC_AUTH_TOKEN" }), + ); assert.strictEqual(status.status, "ready"); assert.strictEqual(status.auth.status, "authenticated"); assert.strictEqual(status.auth.type, "apiKey"); @@ -812,8 +1398,10 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))( it.effect("returns unavailable when claude is missing", () => Effect.gen(function* () { - const status = yield* checkClaudeProviderStatus(); - assert.strictEqual(status.provider, "claudeAgent"); + const status = yield* checkClaudeProviderStatus( + defaultClaudeSettings, + claudeCapabilities(), + ); assert.strictEqual(status.status, "error"); assert.strictEqual(status.installed, false); assert.strictEqual(status.auth.status, "unknown"); @@ -826,8 +1414,10 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))( it.effect("returns error when version check fails with non-zero exit code", () => Effect.gen(function* () { - const status = yield* checkClaudeProviderStatus(); - assert.strictEqual(status.provider, "claudeAgent"); + const status = yield* checkClaudeProviderStatus( + defaultClaudeSettings, + claudeCapabilities(), + ); assert.strictEqual(status.status, "error"); assert.strictEqual(status.installed, true); }).pipe( @@ -835,23 +1425,29 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))( mockSpawnerLayer((args) => { const joined = args.join(" "); if (joined === "--version") - return { stdout: "", stderr: "Something went wrong", code: 1 }; + return { + stdout: "", + stderr: "Something went wrong", + code: 1, + }; throw new Error(`Unexpected args: ${joined}`); }), ), ), ); - it.effect("returns unauthenticated when auth status reports not logged in", () => + it.effect("returns warning when the Claude initialization result is unavailable", () => Effect.gen(function* () { - const status = yield* checkClaudeProviderStatus(); - assert.strictEqual(status.provider, "claudeAgent"); - assert.strictEqual(status.status, "error"); + const status = yield* checkClaudeProviderStatus( + defaultClaudeSettings, + noClaudeCapabilities, + ); + assert.strictEqual(status.status, "warning"); assert.strictEqual(status.installed, true); - assert.strictEqual(status.auth.status, "unauthenticated"); + assert.strictEqual(status.auth.status, "unknown"); assert.strictEqual( status.message, - "Claude is not authenticated. Run `claude auth login` and try again.", + "Could not verify Claude authentication status from initialization result.", ); }).pipe( Effect.provide( @@ -869,90 +1465,6 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))( ), ), ); - - it.effect("returns unauthenticated when output includes 'not logged in'", () => - Effect.gen(function* () { - const status = yield* checkClaudeProviderStatus(); - assert.strictEqual(status.provider, "claudeAgent"); - assert.strictEqual(status.status, "error"); - assert.strictEqual(status.installed, true); - assert.strictEqual(status.auth.status, "unauthenticated"); - }).pipe( - Effect.provide( - mockSpawnerLayer((args) => { - const joined = args.join(" "); - if (joined === "--version") return { stdout: "1.0.0\n", stderr: "", code: 0 }; - if (joined === "auth status") - return { stdout: "Not logged in\n", stderr: "", code: 1 }; - throw new Error(`Unexpected args: ${joined}`); - }), - ), - ), - ); - - it.effect("returns warning when auth status command is unsupported", () => - Effect.gen(function* () { - const status = yield* checkClaudeProviderStatus(); - assert.strictEqual(status.provider, "claudeAgent"); - assert.strictEqual(status.status, "warning"); - assert.strictEqual(status.installed, true); - assert.strictEqual(status.auth.status, "unknown"); - assert.strictEqual( - status.message, - "Claude Agent authentication status command is unavailable in this version of Claude.", - ); - }).pipe( - Effect.provide( - mockSpawnerLayer((args) => { - const joined = args.join(" "); - if (joined === "--version") return { stdout: "1.0.0\n", stderr: "", code: 0 }; - if (joined === "auth status") - return { stdout: "", stderr: "error: unknown command 'auth'", code: 2 }; - throw new Error(`Unexpected args: ${joined}`); - }), - ), - ), - ); - }); - - // ── parseClaudeAuthStatusFromOutput pure tests ──────────────────── - - describe("parseClaudeAuthStatusFromOutput", () => { - it("exit code 0 with no auth markers is ready", () => { - const parsed = parseClaudeAuthStatusFromOutput({ stdout: "OK\n", stderr: "", code: 0 }); - assert.strictEqual(parsed.status, "ready"); - assert.strictEqual(parsed.auth.status, "authenticated"); - }); - - it("JSON with loggedIn=true is authenticated", () => { - const parsed = parseClaudeAuthStatusFromOutput({ - stdout: '{"loggedIn":true,"authMethod":"claude.ai"}\n', - stderr: "", - code: 0, - }); - assert.strictEqual(parsed.status, "ready"); - assert.strictEqual(parsed.auth.status, "authenticated"); - }); - - it("JSON with loggedIn=false is unauthenticated", () => { - const parsed = parseClaudeAuthStatusFromOutput({ - stdout: '{"loggedIn":false}\n', - stderr: "", - code: 0, - }); - assert.strictEqual(parsed.status, "error"); - assert.strictEqual(parsed.auth.status, "unauthenticated"); - }); - - it("JSON without auth marker is warning", () => { - const parsed = parseClaudeAuthStatusFromOutput({ - stdout: '{"ok":true}\n', - stderr: "", - code: 0, - }); - assert.strictEqual(parsed.status, "warning"); - assert.strictEqual(parsed.auth.status, "unknown"); - }); }); }, ); diff --git a/apps/server/src/provider/Layers/ProviderRegistry.ts b/apps/server/src/provider/Layers/ProviderRegistry.ts index ddd1701a94..4f586d881e 100644 --- a/apps/server/src/provider/Layers/ProviderRegistry.ts +++ b/apps/server/src/provider/Layers/ProviderRegistry.ts @@ -1,39 +1,63 @@ /** - * ProviderRegistryLive - Aggregates provider-specific snapshot services. + * ProviderRegistryLive — aggregates per-instance snapshot streams into a + * single materialized list. + * + * Historically this Layer composed four per-kind Live Layers + * (`CodexProviderLive`, `ClaudeProviderLive`, …) that each exposed a + * `ServerProviderShape`. Those Lives were deleted during the driver / + * instance refactor — every driver now carries its `snapshot: ServerProviderShape` + * bundled onto the `ProviderInstance` the registry produces. + * + * Each configured instance (including multi-instance setups like + * `codex_personal` + `codex_work`) contributes one `ProviderSnapshotSource`, + * keyed by `instanceId`. Instances whose driver is unavailable or whose + * config failed to decode are merged from `instanceRegistry.listUnavailable` + * as shadow snapshots so the UI can render their exact unavailable reason. + * + * Cache paths on disk are now keyed by `instanceId`. Because + * `defaultInstanceIdForDriver(kind) === kind` for built-in kinds, existing + * `.json` files remain the on-disk location for that driver's default + * instance. Identity-less legacy cache contents are ignored and replaced by + * the first live refresh. * * @module ProviderRegistryLive */ -import type { ProviderKind, ServerProvider } from "@t3tools/contracts"; -import { Effect, Equal, FileSystem, Layer, Path, PubSub, Ref, Stream } from "effect"; +import { + defaultInstanceIdForDriver, + ProviderDriverKind, + type ProviderInstanceId, + type ServerProvider, +} from "@t3tools/contracts"; +import { Cause, Effect, Equal, FileSystem, Layer, Path, PubSub, Ref, Stream } from "effect"; +import * as Semaphore from "effect/Semaphore"; import { ServerConfig } from "../../config.ts"; -import { ClaudeProviderLive } from "./ClaudeProvider.ts"; -import { CodexProviderLive } from "./CodexProvider.ts"; -import { CursorProviderLive } from "./CursorProvider.ts"; -import { OpenCodeProviderLive } from "./OpenCodeProvider.ts"; -import { ClaudeProvider } from "../Services/ClaudeProvider.ts"; -import { CodexProvider } from "../Services/CodexProvider.ts"; -import { CursorProvider } from "../Services/CursorProvider.ts"; -import { OpenCodeProvider } from "../Services/OpenCodeProvider.ts"; +import { ProviderInstanceRegistry } from "../Services/ProviderInstanceRegistry.ts"; import { ProviderRegistry, type ProviderRegistryShape } from "../Services/ProviderRegistry.ts"; -import { OpenCodeRuntimeLive } from "../opencodeRuntime.ts"; import { hydrateCachedProvider, - PROVIDER_CACHE_IDS, + isCachedProviderCorrelated, orderProviderSnapshots, readProviderStatusCache, resolveProviderStatusCachePath, writeProviderStatusCache, } from "../providerStatusCache.ts"; -import { createBuiltInProviderSources } from "../builtInProviderCatalog.ts"; +import type { ProviderInstance } from "../ProviderDriver.ts"; import type { ProviderSnapshotSource } from "../builtInProviderCatalog.ts"; const loadProviders = ( providerSources: ReadonlyArray, ): Effect.Effect> => - Effect.forEach(providerSources, (providerSource) => providerSource.getSnapshot, { - concurrency: "unbounded", - }); + Effect.forEach( + providerSources, + (providerSource) => + providerSource.getSnapshot.pipe( + Effect.flatMap((snapshot) => correlateSnapshotWithSource(providerSource, snapshot)), + ), + { + concurrency: "unbounded", + }, + ); const hasModelCapabilities = (model: ServerProvider["models"][number]): boolean => (model.capabilities?.optionDescriptors?.length ?? 0) > 0; @@ -77,63 +101,123 @@ export const haveProvidersChanged = ( nextProviders: ReadonlyArray, ): boolean => !Equal.equals(previousProviders, nextProviders); -const ProviderRegistryLiveBase = Layer.effect( +const correlateSnapshotWithSource = ( + source: ProviderSnapshotSource, + snapshot: ServerProvider, +): Effect.Effect => { + if (snapshot.instanceId !== source.instanceId) { + return Effect.die( + new Error( + `Provider snapshot instance mismatch: source '${source.instanceId}' emitted '${snapshot.instanceId}'.`, + ), + ); + } + if (snapshot.driver !== source.driverKind) { + return Effect.die( + new Error( + `Provider snapshot driver mismatch for instance '${source.instanceId}': source '${source.driverKind}' emitted '${snapshot.driver}'.`, + ), + ); + } + return Effect.succeed(snapshot); +}; + +/** + * Key a snapshot for aggregation and persistence. Snapshot sources + * must be correlated by instance id before reaching this map; missing + * identities are defects, not runtime routing fallbacks. + */ +const snapshotInstanceKey = (provider: ServerProvider): ProviderInstanceId => { + return provider.instanceId; +}; + +// Project a live `ProviderInstance` into the aggregator's consumption +// shape. Each call re-captures the instance's `snapshot` closures, so +// after `ProviderInstanceRegistry` rebuilds an instance (e.g. because +// its settings changed), a fresh source rides the new PubSub instead +// of a closed one. +const buildSnapshotSource = (instance: ProviderInstance): ProviderSnapshotSource => ({ + instanceId: instance.instanceId, + driverKind: instance.driverKind, + getSnapshot: instance.snapshot.getSnapshot, + refresh: instance.snapshot.refresh, + streamChanges: instance.snapshot.streamChanges, +}); + +export const ProviderRegistryLive = Layer.effect( ProviderRegistry, Effect.gen(function* () { - const codexProvider = yield* CodexProvider; - const claudeProvider = yield* ClaudeProvider; - const openCodeProvider = yield* OpenCodeProvider; + const instanceRegistry = yield* ProviderInstanceRegistry; const config = yield* ServerConfig; const fileSystem = yield* FileSystem.FileSystem; const path = yield* Path.Path; - const cursorProvider = yield* CursorProvider; - - const providerSources = createBuiltInProviderSources({ - codex: codexProvider, - claudeAgent: claudeProvider, - opencode: openCodeProvider, - cursor: cursorProvider, - }) satisfies ReadonlyArray; - const activeProviders = PROVIDER_CACHE_IDS; + // Aggregator PubSub — consumers (WS gateway, etc.) subscribe here for + // coalesced updates across every instance. const changesPubSub = yield* Effect.acquireRelease( PubSub.unbounded>(), PubSub.shutdown, ); - const fallbackProviders = yield* loadProviders(providerSources); - const cachePathByProvider = new Map( - activeProviders.map( - (provider) => - [ - provider, - resolveProviderStatusCachePath({ - cacheDir: config.providerStatusCacheDir, - provider, - }), - ] as const, - ), - ); - const fallbackByProvider = new Map( - fallbackProviders.map((provider) => [provider.provider, provider] as const), - ); + + // Boot-only: hydrate `providersRef` from the on-disk per-instance + // cache so the UI has something to render during the first refresh. + // Instances added post-boot skip this path; their first entry in + // `providersRef` comes from the reactive `syncLiveSources` pass + // below. + const bootInstances = yield* instanceRegistry.listInstances; + const bootSources = bootInstances.map(buildSnapshotSource); + const fallbackProviders = yield* loadProviders(bootSources); + const fallbackByInstance = new Map(); + for (let index = 0; index < fallbackProviders.length; index++) { + const provider = fallbackProviders[index]; + const source = bootSources[index]; + if (provider === undefined || source === undefined) { + continue; + } + fallbackByInstance.set(source.instanceId, provider); + } const cachedProviders = yield* Effect.forEach( - activeProviders, - (provider) => { - const filePath = cachePathByProvider.get(provider)!; - const fallbackProvider = fallbackByProvider.get(provider)!; - return readProviderStatusCache(filePath).pipe( - Effect.provideService(FileSystem.FileSystem, fileSystem), - Effect.map((cachedProvider) => - cachedProvider === undefined - ? undefined - : hydrateCachedProvider({ - cachedProvider, - fallbackProvider, - }), - ), - ); - }, + bootSources, + (source) => + Effect.gen(function* () { + // One cache file per configured instance. For the default + // instance of a built-in kind the path equals `.json` — + // identical to the legacy filename. We still require the cache + // payload to carry matching instance id + driver kind; old + // identity-less payloads are discarded and the awaited refresh + // below repopulates the cache. + const filePath = yield* resolveProviderStatusCachePath({ + cacheDir: config.providerStatusCacheDir, + instanceId: source.instanceId, + }).pipe(Effect.provideService(Path.Path, path)); + const fallbackProvider = fallbackByInstance.get(source.instanceId); + if (fallbackProvider === undefined) { + return undefined; + } + return yield* readProviderStatusCache(filePath).pipe( + Effect.provideService(FileSystem.FileSystem, fileSystem), + Effect.flatMap((cachedProvider) => { + if (cachedProvider === undefined) { + return Effect.void.pipe(Effect.as(undefined as ServerProvider | undefined)); + } + const correlation = { + cachedProvider, + fallbackProvider, + } as const; + if (!isCachedProviderCorrelated(correlation)) { + return Effect.logWarning("provider status cache identity mismatch, ignoring", { + path: filePath, + instanceId: source.instanceId, + cachedInstanceId: cachedProvider.instanceId ?? null, + driver: source.driverKind, + cachedDriver: cachedProvider.driver ?? null, + }).pipe(Effect.as(undefined as ServerProvider | undefined)); + } + return Effect.succeed(hydrateCachedProvider(correlation)); + }), + ); + }), { concurrency: "unbounded" }, ).pipe( Effect.map((providers) => @@ -144,34 +228,64 @@ const ProviderRegistryLiveBase = Layer.effect( ); const providersRef = yield* Ref.make>(cachedProviders); + // Live-source registry — the dynamic counterpart to the boot-time + // `bootSources`. Keyed by `instanceId`; the stored `ProviderInstance` + // reference is used for identity equality so "no-op" reconciles + // (settings unchanged) skip re-subscribing + re-probing. + const liveSubsRef = yield* Ref.make>( + new Map(), + ); + // Serialize `syncLiveSources` so a rapid burst of reconciles doesn't + // interleave two passes clobbering each other's fiber bookkeeping. + const syncSemaphore = yield* Semaphore.make(1); + + const getLiveSources: Effect.Effect> = Ref.get( + liveSubsRef, + ).pipe(Effect.map((map) => Array.from(map.values(), buildSnapshotSource))); + const persistProvider = (provider: ServerProvider) => - writeProviderStatusCache({ - filePath: cachePathByProvider.get(provider.provider)!, - provider, - }).pipe( - Effect.provideService(FileSystem.FileSystem, fileSystem), - Effect.provideService(Path.Path, path), - Effect.tapError(Effect.logError), - Effect.ignore, - ); + Effect.gen(function* () { + // Persist every instance — the file name is the instance id, so + // multi-instance setups (e.g. `codex_personal`, `codex_work`) each + // get their own cache. We resolve the path fresh so snapshots + // produced by newly-added instances post-boot still land on disk + // without the aggregator holding a stale `cachePathByInstance` + // entry. + const key = snapshotInstanceKey(provider); + const filePath = yield* resolveProviderStatusCachePath({ + cacheDir: config.providerStatusCacheDir, + instanceId: key, + }).pipe(Effect.provideService(Path.Path, path)); + yield* writeProviderStatusCache({ filePath, provider }).pipe( + Effect.provideService(FileSystem.FileSystem, fileSystem), + Effect.provideService(Path.Path, path), + Effect.tapError(Effect.logError), + Effect.ignore, + ); + }); const upsertProviders = Effect.fn("upsertProviders")(function* ( nextProviders: ReadonlyArray, options?: { readonly publish?: boolean; + readonly persist?: boolean; + readonly replace?: boolean; }, ) { const [previousProviders, providers] = yield* Ref.modify( providersRef, (previousProviders) => { const mergedProviders = new Map( - previousProviders.map((provider) => [provider.provider, provider] as const), + previousProviders.map((provider) => [snapshotInstanceKey(provider), provider] as const), ); for (const provider of nextProviders) { + const key = snapshotInstanceKey(provider); mergedProviders.set( - provider.provider, - mergeProviderSnapshot(mergedProviders.get(provider.provider), provider), + key, + options?.replace === true + ? provider + : mergeProviderSnapshot(mergedProviders.get(key), provider), ); } @@ -181,10 +295,12 @@ const ProviderRegistryLiveBase = Layer.effect( ); if (haveProvidersChanged(previousProviders, providers)) { - yield* Effect.forEach(nextProviders, persistProvider, { - concurrency: "unbounded", - discard: true, - }); + if (options?.persist !== false) { + yield* Effect.forEach(nextProviders, persistProvider, { + concurrency: "unbounded", + discard: true, + }); + } if (options?.publish !== false) { yield* PubSub.publish(changesPubSub, providers); } @@ -202,64 +318,246 @@ const ProviderRegistryLiveBase = Layer.effect( return yield* upsertProviders([provider], options); }); - const refresh = Effect.fn("refresh")(function* (provider?: ProviderKind) { - if (provider) { - const providerSource = providerSources.find((candidate) => candidate.provider === provider); - if (!providerSource) { - return yield* Ref.get(providersRef); - } - return yield* providerSource.refresh.pipe( - Effect.flatMap((nextProvider) => syncProvider(nextProvider)), - ); - } - - return yield* Effect.forEach( - providerSources, - (providerSource) => providerSource.refresh.pipe(Effect.flatMap(syncProvider)), - { - concurrency: "unbounded", - discard: true, - }, - ).pipe(Effect.andThen(Ref.get(providersRef))); + const refreshOneSource = Effect.fn("refreshOneSource")(function* ( + providerSource: ProviderSnapshotSource, + ) { + return yield* providerSource.refresh.pipe( + Effect.flatMap((nextProvider) => + correlateSnapshotWithSource(providerSource, nextProvider).pipe( + Effect.flatMap(syncProvider), + ), + ), + ); }); - yield* Effect.forEach( - providerSources, - (providerSource) => - Stream.runForEach(providerSource.streamChanges, (provider) => syncProvider(provider)).pipe( - Effect.forkScoped, - ), - { + const refreshAll = Effect.fn("refreshAll")(function* () { + const sources = yield* getLiveSources; + return yield* Effect.forEach(sources, (source) => refreshOneSource(source), { concurrency: "unbounded", discard: true, - }, + }).pipe(Effect.andThen(Ref.get(providersRef))); + }); + + const refresh = Effect.fn("refresh")(function* (provider?: ProviderDriverKind) { + if (provider === undefined) { + return yield* refreshAll(); + } + // Kind-scoped refreshes target the default instance for that driver. + const defaultInstanceId = defaultInstanceIdForDriver(provider); + const sources = yield* getLiveSources; + const providerSource = sources.find( + (candidate) => candidate.instanceId === defaultInstanceId, + ); + if (!providerSource) { + return yield* Ref.get(providersRef); + } + return yield* refreshOneSource(providerSource); + }); + + const refreshInstance = Effect.fn("refreshInstance")(function* ( + instanceId: ProviderInstanceId, + ) { + const sources = yield* getLiveSources; + const providerSource = sources.find((candidate) => candidate.instanceId === instanceId); + if (!providerSource) { + return yield* Ref.get(providersRef); + } + return yield* refreshOneSource(providerSource); + }); + + /** + * Diff the aggregator's live-source set against the current + * `ProviderInstanceRegistry` and: + * - subscribe to each newly-added or rebuilt instance's + * `streamChanges` (so periodic + enrichment refreshes land in + * `providersRef`); + * - force-refresh each newly-added/rebuilt instance and feed the + * result directly into `providersRef`, bypassing the PubSub + * attachment race that otherwise drops the initial probe; + * - prune `providersRef` of instances that no longer exist. + * + * Initial refreshes are awaited in parallel rather than forked, so + * callers (layer build; `streamChanges` watcher) see fully-probed + * state on return. This matters for layer build in particular: + * consumers reading `getProviders` immediately after layer build + * expect the probe to have already landed. + * + * Per-instance subscription fibers are not tracked explicitly. When + * a rebuilt instance's old child scope closes, its PubSub shuts + * down and our `Stream.runForEach` fiber exits naturally. + */ + const syncLiveSources = syncSemaphore.withPermits(1)( + Effect.gen(function* () { + const instances = yield* instanceRegistry.listInstances; + const unavailableProviders = yield* instanceRegistry.listUnavailable; + const nextByInstance = new Map( + instances.map((instance) => [instance.instanceId, instance] as const), + ); + const knownInstanceIds = new Set(nextByInstance.keys()); + for (const provider of unavailableProviders) { + knownInstanceIds.add(snapshotInstanceKey(provider)); + } + const previousSubs = yield* Ref.get(liveSubsRef); + + // Carry over subscriptions for instances whose identity is + // unchanged (reconcile treated them as no-op). Instances that + // disappeared, or were rebuilt with a different reference, + // fall through to the "newly-added" branch below. + const carriedOver = new Map(); + for (const [instanceId, previousInstance] of previousSubs) { + const nextInstance = nextByInstance.get(instanceId); + if (nextInstance !== undefined && nextInstance === previousInstance) { + carriedOver.set(instanceId, previousInstance); + } + } + + // Collect new/rebuilt instances in `nextByInstance` insertion + // order (which preserves settings-author order). + const newlyAdded: Array = []; + for (const [instanceId, instance] of nextByInstance) { + if (carriedOver.has(instanceId)) { + continue; + } + newlyAdded.push([instanceId, instance] as const); + } + + // Fork long-lived subscriptions to each new/rebuilt instance's + // change stream BEFORE kicking off refreshes — if the driver's + // own initial probe (line 140 in `makeManagedServerProvider`) + // wins the refreshSemaphore race, its PubSub publish must land + // in an active subscriber or the result is dropped. + for (const [, instance] of newlyAdded) { + const source = buildSnapshotSource(instance); + yield* Stream.runForEach(source.streamChanges, (provider) => + correlateSnapshotWithSource(source, provider).pipe(Effect.flatMap(syncProvider)), + ).pipe(Effect.forkScoped); + } + + // Force-refresh every new/rebuilt instance in parallel and wait + // for them all to complete. The refresh's result is piped + // directly into `syncProvider`, so `providersRef` is populated + // deterministically by the time this block returns — regardless + // of PubSub subscription timing. Failures are logged and + // swallowed so one bad driver can't wedge the whole registry. + yield* Effect.forEach( + newlyAdded, + ([, instance]) => + refreshOneSource(buildSnapshotSource(instance)).pipe(Effect.ignoreCause({ log: true })), + { concurrency: "unbounded", discard: true }, + ); + yield* upsertProviders(unavailableProviders, { + persist: false, + replace: true, + }); + + const nextSubs = new Map(carriedOver); + for (const [instanceId, instance] of newlyAdded) { + nextSubs.set(instanceId, instance); + } + yield* Ref.set(liveSubsRef, nextSubs); + + // Drop aggregator state for instances that have disappeared — + // otherwise the UI would keep rendering ghosts. + const [previousProviders, providers] = yield* Ref.modify( + providersRef, + (previousProviders) => { + const providers = orderProviderSnapshots( + previousProviders.filter((provider) => + knownInstanceIds.has(snapshotInstanceKey(provider)), + ), + ); + return [[previousProviders, providers] as const, providers]; + }, + ); + if (haveProvidersChanged(previousProviders, providers)) { + yield* PubSub.publish(changesPubSub, providers); + } + }), ); - yield* loadProviders(providerSources).pipe( - Effect.flatMap((providers) => upsertProviders(providers, { publish: false })), + const syncLiveSourcesAndContinue = syncLiveSources.pipe( + Effect.catchCause((cause) => { + if (Cause.hasInterruptsOnly(cause)) { + return Effect.interrupt; + } + return Effect.logError( + "provider registry instance sync failed; keeping subscription alive", + { + cause: Cause.pretty(cause), + }, + ); + }), ); + // Seed `providersRef` with the boot-time fallback snapshots so + // consumers calling `getProviders` immediately after layer build see + // a populated list — even before the first `syncLiveSources` refresh + // resolves. Cached snapshots (already in `providersRef`) merge with + // these via `upsertProviders` so on-disk state wins where present + // and pending fallbacks fill the gaps. + yield* upsertProviders(fallbackProviders, { publish: false }); + // Subscribe to registry mutations BEFORE running the initial sync. + // `subscribeChanges` acquires the dequeue synchronously in this + // fibre; the subscription is active the instant this `yield*` + // returns. Forking the consumer loop later cannot lose a publish + // because no publish can reach a not-yet-subscribed dequeue. + // + // (Contrast with the pre-fix code that did + // `Stream.runForEach(instanceRegistry.streamChanges, …).pipe(Effect.forkScoped)`. + // `Stream.fromPubSub` defers `PubSub.subscribe` to stream start, + // and `forkScoped` only schedules the fibre — so a reconcile that + // published between "fibre scheduled" and "fibre starts running" + // was dropped, which made any settings change that replaced an + // instance never propagate to the aggregator's `providersRef`.) + // Subscribe to registry mutations BEFORE running the initial sync. + // `subscribeChanges` acquires the `PubSub.Subscription` synchronously + // in this fibre; the subscription is registered with the PubSub the + // instant this `yield*` returns, so any subsequent publish is + // buffered in the subscription regardless of when the consumer + // fibre below actually starts running. + // + // (Contrast with the pre-fix code that did + // `Stream.runForEach(instanceRegistry.streamChanges, …).pipe(Effect.forkScoped)`. + // `instanceRegistry.streamChanges` is `Stream.fromPubSub(changes)`, + // which defers `PubSub.subscribe` to stream start. `forkScoped` only + // schedules the consumer fibre — so a reconcile that published + // between "fibre scheduled" and "fibre starts running + subscribes" + // was dropped, which made any settings change that replaced an + // instance never propagate to the aggregator's `providersRef`.) + const instanceChanges = yield* instanceRegistry.subscribeChanges; + // Initial sync: subscribe + kick off refreshes for every instance + // present at boot. Run synchronously so consumers pulling immediately + // after the layer build see the correct aggregator state. + yield* syncLiveSources; + // React to registry mutations — instance added / removed / rebuilt. + // `Stream.fromSubscription` builds a stream over the pre-acquired + // subscription rather than subscribing on stream start, which is + // what closes the race. + yield* Stream.runForEach( + Stream.fromSubscription(instanceChanges), + () => syncLiveSourcesAndContinue, + ).pipe(Effect.forkScoped); + + const recoverRefreshFailure = Effect.fn("recoverRefreshFailure")(function* ( + cause: Cause.Cause, + ) { + if (Cause.hasInterruptsOnly(cause)) { + return yield* Effect.interrupt; + } + yield* Effect.logError("provider registry refresh failed; preserving cached providers", { + cause: Cause.pretty(cause), + }); + return yield* Ref.get(providersRef); + }); + return { getProviders: Ref.get(providersRef), - refresh: (provider?: ProviderKind) => - refresh(provider).pipe( - Effect.tapError(Effect.logError), - Effect.orElseSucceed(() => [] as ReadonlyArray), - ), + refresh: (provider?: ProviderDriverKind) => + refresh(provider).pipe(Effect.catchCause(recoverRefreshFailure)), + refreshInstance: (instanceId: ProviderInstanceId) => + refreshInstance(instanceId).pipe(Effect.catchCause(recoverRefreshFailure)), get streamChanges() { return Stream.fromPubSub(changesPubSub); }, } satisfies ProviderRegistryShape; }), ); - -export const ProviderRegistryLive = Layer.unwrap( - Effect.sync(() => - ProviderRegistryLiveBase.pipe( - Layer.provideMerge(CursorProviderLive), - Layer.provideMerge(CodexProviderLive), - Layer.provideMerge(ClaudeProviderLive), - Layer.provideMerge(OpenCodeProviderLive), - Layer.provideMerge(OpenCodeRuntimeLive), - ), - ), -); diff --git a/apps/server/src/provider/Layers/ProviderService.test.ts b/apps/server/src/provider/Layers/ProviderService.test.ts index 09606ba35a..7e77125143 100644 --- a/apps/server/src/provider/Layers/ProviderService.test.ts +++ b/apps/server/src/provider/Layers/ProviderService.test.ts @@ -12,7 +12,8 @@ import type { import { ApprovalRequestId, EventId, - type ProviderKind, + ProviderDriverKind, + ProviderInstanceId, ProviderSessionStartInput, ThreadId, TurnId, @@ -20,20 +21,25 @@ import { import { createModelSelection } from "@t3tools/shared/model"; import { it, assert, vi } from "@effect/vitest"; -import { Effect, Fiber, Layer, Metric, Option, PubSub, Ref, Stream } from "effect"; +import { Effect, Exit, Fiber, Layer, Metric, Option, PubSub, Ref, Scope, Stream } from "effect"; import * as SqlClient from "effect/unstable/sql/SqlClient"; import { + ProviderAdapterRequestError, ProviderAdapterSessionNotFoundError, ProviderUnsupportedError, ProviderValidationError, type ProviderAdapterError, } from "../Errors.ts"; import type { ProviderAdapterShape } from "../Services/ProviderAdapter.ts"; -import { ProviderAdapterRegistry } from "../Services/ProviderAdapterRegistry.ts"; +import { + ProviderAdapterRegistry, + type ProviderAdapterRegistryShape, +} from "../Services/ProviderAdapterRegistry.ts"; import { ProviderService } from "../Services/ProviderService.ts"; import { ProviderSessionDirectory } from "../Services/ProviderSessionDirectory.ts"; import { makeProviderServiceLive } from "./ProviderService.ts"; +import { NoOpProviderEventLoggers, ProviderEventLoggers } from "./ProviderEventLoggers.ts"; import { ProviderSessionDirectoryLive } from "./ProviderSessionDirectory.ts"; import * as NodeServices from "@effect/platform-node/NodeServices"; import { ProviderSessionRuntimeRepositoryLive } from "../../persistence/Layers/ProviderSessionRuntime.ts"; @@ -44,6 +50,7 @@ import { } from "../../persistence/Layers/Sqlite.ts"; import { ServerSettingsService } from "../../serverSettings.ts"; import { AnalyticsService } from "../../telemetry/Services/AnalyticsService.ts"; +import { makeAdapterRegistryMock } from "../testUtils/providerAdapterRegistryMock.ts"; const defaultServerSettingsLayer = ServerSettingsService.layerTest(); @@ -51,11 +58,16 @@ const asRequestId = (value: string): ApprovalRequestId => ApprovalRequestId.make const asEventId = (value: string): EventId => EventId.make(value); const asThreadId = (value: string): ThreadId => ThreadId.make(value); const asTurnId = (value: string): TurnId => TurnId.make(value); +const codexInstanceId = ProviderInstanceId.make("codex"); +const claudeAgentInstanceId = ProviderInstanceId.make("claudeAgent"); +const CODEX_DRIVER = ProviderDriverKind.make("codex"); +const CLAUDE_AGENT_DRIVER = ProviderDriverKind.make("claudeAgent"); +const CURSOR_DRIVER = ProviderDriverKind.make("cursor"); type LegacyProviderRuntimeEvent = { readonly type: string; readonly eventId: EventId; - readonly provider: ProviderKind; + readonly provider: ProviderDriverKind; readonly createdAt: string; readonly threadId: ThreadId; readonly turnId?: string | undefined; @@ -65,7 +77,7 @@ type LegacyProviderRuntimeEvent = { readonly [key: string]: unknown; }; -function makeFakeCodexAdapter(provider: ProviderKind = "codex") { +function makeFakeCodexAdapter(provider: ProviderDriverKind = CODEX_DRIVER) { const sessions = new Map(); const runtimeEventPubSub = Effect.runSync(PubSub.unbounded()); @@ -74,10 +86,15 @@ function makeFakeCodexAdapter(provider: ProviderKind = "codex") { const now = new Date().toISOString(); const session: ProviderSession = { provider, + ...(input.providerInstanceId !== undefined + ? { providerInstanceId: input.providerInstanceId } + : {}), status: "ready", runtimeMode: input.runtimeMode, threadId: input.threadId, - resumeCursor: input.resumeCursor ?? { opaque: `resume-${String(input.threadId)}` }, + resumeCursor: input.resumeCursor ?? { + opaque: `resume-${String(input.threadId)}`, + }, cwd: input.cwd ?? process.cwd(), createdAt: now, updatedAt: now, @@ -245,19 +262,13 @@ const hasMetricSnapshot = ( function makeProviderServiceLayer() { const codex = makeFakeCodexAdapter(); - const claude = makeFakeCodexAdapter("claudeAgent"); - const cursor = makeFakeCodexAdapter("cursor"); - const registry: typeof ProviderAdapterRegistry.Service = { - getByProvider: (provider) => - provider === "codex" - ? Effect.succeed(codex.adapter) - : provider === "claudeAgent" - ? Effect.succeed(claude.adapter) - : provider === "cursor" - ? Effect.succeed(cursor.adapter) - : Effect.fail(new ProviderUnsupportedError({ provider })), - listProviders: () => Effect.succeed(["codex", "claudeAgent", "cursor"]), - }; + const claude = makeFakeCodexAdapter(CLAUDE_AGENT_DRIVER); + const cursor = makeFakeCodexAdapter(CURSOR_DRIVER); + const registry = makeAdapterRegistryMock({ + [ProviderDriverKind.make("codex")]: codex.adapter, + [ProviderDriverKind.make("claudeAgent")]: claude.adapter, + [ProviderDriverKind.make("cursor")]: cursor.adapter, + }); const providerAdapterLayer = Layer.succeed(ProviderAdapterRegistry, registry); const runtimeRepositoryLayer = ProviderSessionRuntimeRepositoryLive.pipe( @@ -272,6 +283,7 @@ function makeProviderServiceLayer() { Layer.provide(directoryLayer), Layer.provide(defaultServerSettingsLayer), Layer.provideMerge(AnalyticsService.layerTest), + Layer.provide(Layer.succeed(ProviderEventLoggers, NoOpProviderEventLoggers)), ), directoryLayer, @@ -288,27 +300,76 @@ function makeProviderServiceLayer() { }; } +it.effect("ProviderServiceLive catches stopAll failures during shutdown", () => + Effect.gen(function* () { + const codex = makeFakeCodexAdapter(); + codex.stopAll.mockImplementation(() => + Effect.fail( + new ProviderAdapterRequestError({ + provider: String(CODEX_DRIVER), + method: "stopAll", + detail: "simulated stopAll failure", + }), + ), + ); + const registry = makeAdapterRegistryMock({ + [CODEX_DRIVER]: codex.adapter, + }); + const providerAdapterLayer = Layer.succeed(ProviderAdapterRegistry, registry); + const runtimeRepositoryLayer = ProviderSessionRuntimeRepositoryLive.pipe( + Layer.provide(SqlitePersistenceMemory), + ); + const directoryLayer = ProviderSessionDirectoryLive.pipe(Layer.provide(runtimeRepositoryLayer)); + const providerLayer = Layer.mergeAll( + makeProviderServiceLive().pipe( + Layer.provide(providerAdapterLayer), + Layer.provide(directoryLayer), + Layer.provide(defaultServerSettingsLayer), + Layer.provideMerge(AnalyticsService.layerTest), + Layer.provide(Layer.succeed(ProviderEventLoggers, NoOpProviderEventLoggers)), + ), + directoryLayer, + runtimeRepositoryLayer, + NodeServices.layer, + ); + const scope = yield* Scope.make(); + const runtimeServices = yield* Layer.build(providerLayer).pipe(Scope.provide(scope)); + + yield* Effect.gen(function* () { + yield* ProviderService; + }).pipe(Effect.provide(runtimeServices)); + const closeExit = yield* Scope.close(scope, Exit.void).pipe(Effect.exit); + + assert.equal(Exit.isSuccess(closeExit), true); + assert.equal(codex.stopAll.mock.calls.length, 1); + }), +); + it.effect("ProviderServiceLive rejects new sessions for disabled providers", () => Effect.gen(function* () { const codex = makeFakeCodexAdapter(); - const claude = makeFakeCodexAdapter("claudeAgent"); - const registry: typeof ProviderAdapterRegistry.Service = { - getByProvider: (provider) => - provider === "codex" - ? Effect.succeed(codex.adapter) - : provider === "claudeAgent" - ? Effect.succeed(claude.adapter) - : Effect.fail(new ProviderUnsupportedError({ provider })), - listProviders: () => Effect.succeed(["codex", "claudeAgent"]), + const claude = makeFakeCodexAdapter(CLAUDE_AGENT_DRIVER); + const registryBase = makeAdapterRegistryMock({ + [CODEX_DRIVER]: codex.adapter, + [CLAUDE_AGENT_DRIVER]: claude.adapter, + }); + const registry: ProviderAdapterRegistryShape = { + ...registryBase, + getInstanceInfo: (instanceId) => + instanceId === claudeAgentInstanceId + ? Effect.succeed({ + instanceId, + driverKind: CLAUDE_AGENT_DRIVER, + displayName: undefined, + enabled: false, + continuationIdentity: { + driverKind: CLAUDE_AGENT_DRIVER, + continuationKey: "claudeAgent:instance:claudeAgent", + }, + }) + : registryBase.getInstanceInfo(instanceId), }; const providerAdapterLayer = Layer.succeed(ProviderAdapterRegistry, registry); - const serverSettingsLayer = ServerSettingsService.layerTest({ - providers: { - claudeAgent: { - enabled: false, - }, - }, - }); const runtimeRepositoryLayer = ProviderSessionRuntimeRepositoryLive.pipe( Layer.provide(SqlitePersistenceMemory), ); @@ -316,15 +377,17 @@ it.effect("ProviderServiceLive rejects new sessions for disabled providers", () const providerLayer = makeProviderServiceLive().pipe( Layer.provide(providerAdapterLayer), Layer.provide(directoryLayer), - Layer.provide(serverSettingsLayer), + Layer.provide(defaultServerSettingsLayer), Layer.provide(AnalyticsService.layerTest), + Layer.provide(Layer.succeed(ProviderEventLoggers, NoOpProviderEventLoggers)), ); const failure = yield* Effect.flip( Effect.gen(function* () { const provider = yield* ProviderService; return yield* provider.startSession(asThreadId("thread-disabled"), { - provider: "claudeAgent", + provider: ProviderDriverKind.make("claudeAgent"), + providerInstanceId: claudeAgentInstanceId, threadId: asThreadId("thread-disabled"), runtimeMode: "full-access", }); @@ -332,11 +395,149 @@ it.effect("ProviderServiceLive rejects new sessions for disabled providers", () ); assert.instanceOf(failure, ProviderValidationError); - assert.include(failure.issue, "Provider 'claudeAgent' is disabled in T3 Code settings."); + assert.include(failure.issue, "Provider instance 'claudeAgent' is disabled"); assert.equal(claude.startSession.mock.calls.length, 0); }).pipe(Effect.provide(NodeServices.layer)), ); +it.effect( + "ProviderServiceLive allows enabled custom instances when legacy driver is disabled", + () => + Effect.gen(function* () { + const instanceId = ProviderInstanceId.make("codex_personal"); + const driverKind = CODEX_DRIVER; + const codex = makeFakeCodexAdapter(); + const unsupported = () => + new ProviderUnsupportedError({ + provider: driverKind, + }); + const registry: ProviderAdapterRegistryShape = { + getByInstance: (requestedInstanceId) => + requestedInstanceId === instanceId + ? Effect.succeed(codex.adapter) + : Effect.fail(unsupported()), + getInstanceInfo: (requestedInstanceId) => + requestedInstanceId === instanceId + ? Effect.succeed({ + instanceId, + driverKind, + displayName: "Codex Personal", + enabled: true, + continuationIdentity: { + driverKind, + continuationKey: "codex:/Users/example/.codex", + }, + }) + : Effect.fail(unsupported()), + listInstances: () => Effect.succeed([instanceId]), + listProviders: () => Effect.succeed([driverKind] as const), + streamChanges: Stream.empty, + subscribeChanges: Effect.flatMap(PubSub.unbounded(), (pubsub) => + PubSub.subscribe(pubsub), + ), + }; + const providerAdapterLayer = Layer.succeed(ProviderAdapterRegistry, registry); + const serverSettingsLayer = ServerSettingsService.layerTest({ + providers: { + codex: { + enabled: false, + }, + }, + }); + const runtimeRepositoryLayer = ProviderSessionRuntimeRepositoryLive.pipe( + Layer.provide(SqlitePersistenceMemory), + ); + const directoryLayer = ProviderSessionDirectoryLive.pipe( + Layer.provide(runtimeRepositoryLayer), + ); + const providerLayer = makeProviderServiceLive().pipe( + Layer.provide(providerAdapterLayer), + Layer.provide(directoryLayer), + Layer.provide(serverSettingsLayer), + Layer.provide(AnalyticsService.layerTest), + Layer.provide(Layer.succeed(ProviderEventLoggers, NoOpProviderEventLoggers)), + ); + + const session = yield* Effect.gen(function* () { + const provider = yield* ProviderService; + return yield* provider.startSession(asThreadId("thread-enabled-custom"), { + provider: driverKind, + providerInstanceId: instanceId, + threadId: asThreadId("thread-enabled-custom"), + runtimeMode: "full-access", + }); + }).pipe(Effect.provide(providerLayer)); + + assert.equal(session.providerInstanceId, instanceId); + assert.equal(codex.startSession.mock.calls.length, 1); + }).pipe(Effect.provide(NodeServices.layer)), +); + +it.effect("ProviderServiceLive rejects new sessions for disabled custom instances", () => + Effect.gen(function* () { + const instanceId = ProviderInstanceId.make("codex_personal"); + const driverKind = ProviderDriverKind.make("codex"); + const codex = makeFakeCodexAdapter(); + const unsupported = () => + new ProviderUnsupportedError({ + provider: ProviderDriverKind.make("codex"), + }); + const registry: ProviderAdapterRegistryShape = { + getByInstance: (requestedInstanceId) => + requestedInstanceId === instanceId + ? Effect.succeed(codex.adapter) + : Effect.fail(unsupported()), + getInstanceInfo: (requestedInstanceId) => + requestedInstanceId === instanceId + ? Effect.succeed({ + instanceId, + driverKind, + displayName: "Codex Personal", + enabled: false, + continuationIdentity: { + driverKind, + continuationKey: "codex:/Users/example/.codex", + }, + }) + : Effect.fail(unsupported()), + listInstances: () => Effect.succeed([instanceId]), + listProviders: () => Effect.succeed([CODEX_DRIVER] as const), + streamChanges: Stream.empty, + subscribeChanges: Effect.flatMap(PubSub.unbounded(), (pubsub) => + PubSub.subscribe(pubsub), + ), + }; + const providerAdapterLayer = Layer.succeed(ProviderAdapterRegistry, registry); + const runtimeRepositoryLayer = ProviderSessionRuntimeRepositoryLive.pipe( + Layer.provide(SqlitePersistenceMemory), + ); + const directoryLayer = ProviderSessionDirectoryLive.pipe(Layer.provide(runtimeRepositoryLayer)); + const providerLayer = makeProviderServiceLive().pipe( + Layer.provide(providerAdapterLayer), + Layer.provide(directoryLayer), + Layer.provide(defaultServerSettingsLayer), + Layer.provide(AnalyticsService.layerTest), + Layer.provide(Layer.succeed(ProviderEventLoggers, NoOpProviderEventLoggers)), + ); + + const failure = yield* Effect.flip( + Effect.gen(function* () { + const provider = yield* ProviderService; + return yield* provider.startSession(asThreadId("thread-disabled-instance"), { + provider: ProviderDriverKind.make("codex"), + providerInstanceId: instanceId, + threadId: asThreadId("thread-disabled-instance"), + runtimeMode: "full-access", + }); + }).pipe(Effect.provide(providerLayer)), + ); + + assert.instanceOf(failure, ProviderValidationError); + assert.include(failure.issue, "Provider instance 'codex_personal' is disabled"); + assert.equal(codex.startSession.mock.calls.length, 0); + }).pipe(Effect.provide(NodeServices.layer)), +); + const routing = makeProviderServiceLayer(); it.effect("ProviderServiceLive writes canonical events to the emitting thread segment", () => @@ -344,13 +545,9 @@ it.effect("ProviderServiceLive writes canonical events to the emitting thread se const codex = makeFakeCodexAdapter(); const canonicalEvents: ProviderRuntimeEvent[] = []; const canonicalThreadIds: Array = []; - const registry: typeof ProviderAdapterRegistry.Service = { - getByProvider: (provider) => - provider === "codex" - ? Effect.succeed(codex.adapter) - : Effect.fail(new ProviderUnsupportedError({ provider })), - listProviders: () => Effect.succeed(["codex"]), - }; + const registry = makeAdapterRegistryMock({ + [ProviderDriverKind.make("codex")]: codex.adapter, + }); const runtimeRepositoryLayer = ProviderSessionRuntimeRepositoryLive.pipe( Layer.provide(SqlitePersistenceMemory), ); @@ -370,6 +567,7 @@ it.effect("ProviderServiceLive writes canonical events to the emitting thread se Layer.provide(directoryLayer), Layer.provide(defaultServerSettingsLayer), Layer.provide(AnalyticsService.layerTest), + Layer.provide(Layer.succeed(ProviderEventLoggers, NoOpProviderEventLoggers)), ); yield* Effect.gen(function* () { @@ -377,7 +575,7 @@ it.effect("ProviderServiceLive writes canonical events to the emitting thread se yield* sleep(10); codex.emit({ eventId: asEventId("evt-canonical-thread-segment"), - provider: "codex", + provider: ProviderDriverKind.make("codex"), threadId: asThreadId("thread-canonical-thread-segment"), createdAt: new Date().toISOString(), type: "turn.completed", @@ -400,13 +598,9 @@ it.effect("ProviderServiceLive keeps persisted resumable sessions on startup", ( const dbPath = path.join(tempDir, "orchestration.sqlite"); const codex = makeFakeCodexAdapter(); - const registry: typeof ProviderAdapterRegistry.Service = { - getByProvider: (provider) => - provider === "codex" - ? Effect.succeed(codex.adapter) - : Effect.fail(new ProviderUnsupportedError({ provider })), - listProviders: () => Effect.succeed(["codex"]), - }; + const registry = makeAdapterRegistryMock({ + [ProviderDriverKind.make("codex")]: codex.adapter, + }); const persistenceLayer = makeSqlitePersistenceLive(dbPath); const runtimeRepositoryLayer = ProviderSessionRuntimeRepositoryLive.pipe( @@ -417,7 +611,8 @@ it.effect("ProviderServiceLive keeps persisted resumable sessions on startup", ( yield* Effect.gen(function* () { const directory = yield* ProviderSessionDirectory; yield* directory.upsert({ - provider: "codex", + provider: ProviderDriverKind.make("codex"), + providerInstanceId: codexInstanceId, threadId: ThreadId.make("thread-stale"), }); }).pipe(Effect.provide(directoryLayer)); @@ -427,6 +622,7 @@ it.effect("ProviderServiceLive keeps persisted resumable sessions on startup", ( Layer.provide(directoryLayer), Layer.provide(defaultServerSettingsLayer), Layer.provide(AnalyticsService.layerTest), + Layer.provide(Layer.succeed(ProviderEventLoggers, NoOpProviderEventLoggers)), ); yield* Effect.gen(function* () { @@ -441,7 +637,9 @@ it.effect("ProviderServiceLive keeps persisted resumable sessions on startup", ( const runtime = yield* Effect.gen(function* () { const repository = yield* ProviderSessionRuntimeRepository; - return yield* repository.getByThreadId({ threadId: asThreadId("thread-stale") }); + return yield* repository.getByThreadId({ + threadId: asThreadId("thread-stale"), + }); }).pipe(Effect.provide(runtimeRepositoryLayer)); assert.equal(Option.isSome(runtime), true); @@ -471,13 +669,9 @@ it.effect( ); const firstCodex = makeFakeCodexAdapter(); - const firstRegistry: typeof ProviderAdapterRegistry.Service = { - getByProvider: (provider) => - provider === "codex" - ? Effect.succeed(firstCodex.adapter) - : Effect.fail(new ProviderUnsupportedError({ provider })), - listProviders: () => Effect.succeed(["codex"]), - }; + const firstRegistry = makeAdapterRegistryMock({ + [ProviderDriverKind.make("codex")]: firstCodex.adapter, + }); const firstDirectoryLayer = ProviderSessionDirectoryLive.pipe( Layer.provide(runtimeRepositoryLayer), @@ -487,6 +681,7 @@ it.effect( Layer.provide(firstDirectoryLayer), Layer.provide(defaultServerSettingsLayer), Layer.provide(AnalyticsService.layerTest), + Layer.provide(Layer.succeed(ProviderEventLoggers, NoOpProviderEventLoggers)), ); const updatedResumeCursor = { threadId: asThreadId("thread-1"), @@ -499,7 +694,8 @@ it.effect( const provider = yield* ProviderService; const threadId = asThreadId("thread-1"); const session = yield* provider.startSession(threadId, { - provider: "codex", + provider: ProviderDriverKind.make("codex"), + providerInstanceId: codexInstanceId, cwd: "/tmp/project", runtimeMode: "full-access", threadId, @@ -515,7 +711,9 @@ it.effect( const persistedAfterStopAll = yield* Effect.gen(function* () { const repository = yield* ProviderSessionRuntimeRepository; - return yield* repository.getByThreadId({ threadId: startedSession.threadId }); + return yield* repository.getByThreadId({ + threadId: startedSession.threadId, + }); }).pipe(Effect.provide(runtimeRepositoryLayer)); assert.equal(Option.isSome(persistedAfterStopAll), true); if (Option.isSome(persistedAfterStopAll)) { @@ -524,13 +722,9 @@ it.effect( } const secondCodex = makeFakeCodexAdapter(); - const secondRegistry: typeof ProviderAdapterRegistry.Service = { - getByProvider: (provider) => - provider === "codex" - ? Effect.succeed(secondCodex.adapter) - : Effect.fail(new ProviderUnsupportedError({ provider })), - listProviders: () => Effect.succeed(["codex"]), - }; + const secondRegistry = makeAdapterRegistryMock({ + [ProviderDriverKind.make("codex")]: secondCodex.adapter, + }); const secondDirectoryLayer = ProviderSessionDirectoryLive.pipe( Layer.provide(runtimeRepositoryLayer), ); @@ -539,6 +733,7 @@ it.effect( Layer.provide(secondDirectoryLayer), Layer.provide(defaultServerSettingsLayer), Layer.provide(AnalyticsService.layerTest), + Layer.provide(Layer.succeed(ProviderEventLoggers, NoOpProviderEventLoggers)), ); secondCodex.startSession.mockClear(); @@ -582,7 +777,8 @@ routing.layer("ProviderServiceLive routing", (it) => { const provider = yield* ProviderService; const session = yield* provider.startSession(asThreadId("thread-1"), { - provider: "codex", + provider: ProviderDriverKind.make("codex"), + providerInstanceId: codexInstanceId, threadId: asThreadId("thread-1"), cwd: "/tmp/project", runtimeMode: "full-access", @@ -667,7 +863,8 @@ routing.layer("ProviderServiceLive routing", (it) => { const provider = yield* ProviderService; const initial = yield* provider.startSession(asThreadId("thread-1"), { - provider: "codex", + provider: ProviderDriverKind.make("codex"), + providerInstanceId: codexInstanceId, threadId: asThreadId("thread-1"), cwd: "/tmp/project", runtimeMode: "full-access", @@ -708,7 +905,8 @@ routing.layer("ProviderServiceLive routing", (it) => { const runtimeRepository = yield* ProviderSessionRuntimeRepository; const initial = yield* provider.startSession(asThreadId("thread-reap-preserve"), { - provider: "codex", + provider: ProviderDriverKind.make("codex"), + providerInstanceId: codexInstanceId, threadId: asThreadId("thread-reap-preserve"), cwd: "/tmp/project-reap-preserve", runtimeMode: "full-access", @@ -758,7 +956,8 @@ routing.layer("ProviderServiceLive routing", (it) => { const provider = yield* ProviderService; const session = yield* provider.startSession(asThreadId("thread-claude"), { - provider: "claudeAgent", + provider: ProviderDriverKind.make("claudeAgent"), + providerInstanceId: claudeAgentInstanceId, threadId: asThreadId("thread-claude"), cwd: "/tmp/project-claude", runtimeMode: "full-access", @@ -769,20 +968,57 @@ routing.layer("ProviderServiceLive routing", (it) => { const startInput = routing.claude.startSession.mock.calls[0]?.[0]; assert.equal(typeof startInput === "object" && startInput !== null, true); if (startInput && typeof startInput === "object") { - const startPayload = startInput as { provider?: string; cwd?: string }; + const startPayload = startInput as { + provider?: string; + providerInstanceId?: ProviderInstanceId; + cwd?: string; + }; assert.equal(startPayload.provider, "claudeAgent"); + assert.equal(startPayload.providerInstanceId, claudeAgentInstanceId); assert.equal(startPayload.cwd, "/tmp/project-claude"); } }), ); + it.effect("dies when an active session conflicts with its persisted binding", () => + Effect.gen(function* () { + const provider = yield* ProviderService; + const directory = yield* ProviderSessionDirectory; + const threadId = asThreadId("thread-binding-mismatch"); + + yield* provider.startSession(threadId, { + provider: ProviderDriverKind.make("codex"), + providerInstanceId: codexInstanceId, + threadId, + cwd: "/tmp/project-binding-mismatch", + runtimeMode: "full-access", + }); + yield* directory.upsert({ + threadId, + provider: ProviderDriverKind.make("claudeAgent"), + providerInstanceId: claudeAgentInstanceId, + runtimeMode: "full-access", + }); + + const exit = yield* Effect.exit(provider.listSessions()); + assert.equal(Exit.hasDies(exit), true); + yield* directory.upsert({ + threadId, + provider: ProviderDriverKind.make("codex"), + providerInstanceId: codexInstanceId, + runtimeMode: "full-access", + }); + }), + ); + it.effect("stops stale sessions in other providers after a successful replacement start", () => Effect.gen(function* () { const provider = yield* ProviderService; const threadId = asThreadId("thread-provider-replacement"); const codexSession = yield* provider.startSession(threadId, { - provider: "codex", + provider: ProviderDriverKind.make("codex"), + providerInstanceId: codexInstanceId, threadId, cwd: "/tmp/project-provider-replacement", runtimeMode: "full-access", @@ -792,7 +1028,8 @@ routing.layer("ProviderServiceLive routing", (it) => { routing.claude.stopSession.mockClear(); const claudeSession = yield* provider.startSession(threadId, { - provider: "claudeAgent", + provider: ProviderDriverKind.make("claudeAgent"), + providerInstanceId: claudeAgentInstanceId, threadId, cwd: "/tmp/project-provider-replacement", runtimeMode: "full-access", @@ -818,7 +1055,8 @@ routing.layer("ProviderServiceLive routing", (it) => { const provider = yield* ProviderService; const initial = yield* provider.startSession(asThreadId("thread-1"), { - provider: "codex", + provider: ProviderDriverKind.make("codex"), + providerInstanceId: codexInstanceId, threadId: asThreadId("thread-1"), cwd: "/tmp/project-send-turn", runtimeMode: "full-access", @@ -858,12 +1096,15 @@ routing.layer("ProviderServiceLive routing", (it) => { const provider = yield* ProviderService; const initial = yield* provider.startSession(asThreadId("thread-claude-send-turn"), { - provider: "claudeAgent", + provider: ProviderDriverKind.make("claudeAgent"), + providerInstanceId: claudeAgentInstanceId, threadId: asThreadId("thread-claude-send-turn"), cwd: "/tmp/project-claude-send-turn", - modelSelection: createModelSelection("claudeAgent", "claude-opus-4-6", [ - { id: "effort", value: "max" }, - ]), + modelSelection: createModelSelection( + ProviderInstanceId.make("claudeAgent"), + "claude-opus-4-6", + [{ id: "effort", value: "max" }], + ), runtimeMode: "full-access", }); @@ -892,7 +1133,9 @@ routing.layer("ProviderServiceLive routing", (it) => { assert.equal(startPayload.cwd, "/tmp/project-claude-send-turn"); assert.deepEqual( startPayload.modelSelection, - createModelSelection("claudeAgent", "claude-opus-4-6", [{ id: "effort", value: "max" }]), + createModelSelection(ProviderInstanceId.make("claudeAgent"), "claude-opus-4-6", [ + { id: "effort", value: "max" }, + ]), ); assert.deepEqual(startPayload.resumeCursor, initial.resumeCursor); assert.equal(startPayload.threadId, initial.threadId); @@ -906,12 +1149,14 @@ routing.layer("ProviderServiceLive routing", (it) => { const provider = yield* ProviderService; yield* provider.startSession(asThreadId("thread-1"), { - provider: "codex", + provider: ProviderDriverKind.make("codex"), + providerInstanceId: codexInstanceId, threadId: asThreadId("thread-1"), runtimeMode: "full-access", }); yield* provider.startSession(asThreadId("thread-2"), { - provider: "codex", + provider: ProviderDriverKind.make("codex"), + providerInstanceId: codexInstanceId, threadId: asThreadId("thread-2"), runtimeMode: "full-access", }); @@ -931,7 +1176,8 @@ routing.layer("ProviderServiceLive routing", (it) => { const threadId = asThreadId("thread-runtime-status"); const session = yield* provider.startSession(threadId, { - provider: "codex", + provider: ProviderDriverKind.make("codex"), + providerInstanceId: codexInstanceId, threadId, runtimeMode: "full-access", }); @@ -977,14 +1223,10 @@ routing.layer("ProviderServiceLive routing", (it) => { Layer.provide(persistenceLayer), ); - const firstClaude = makeFakeCodexAdapter("claudeAgent"); - const firstRegistry: typeof ProviderAdapterRegistry.Service = { - getByProvider: (provider) => - provider === "claudeAgent" - ? Effect.succeed(firstClaude.adapter) - : Effect.fail(new ProviderUnsupportedError({ provider })), - listProviders: () => Effect.succeed(["claudeAgent"]), - }; + const firstClaude = makeFakeCodexAdapter(CLAUDE_AGENT_DRIVER); + const firstRegistry = makeAdapterRegistryMock({ + [ProviderDriverKind.make("claudeAgent")]: firstClaude.adapter, + }); const firstDirectoryLayer = ProviderSessionDirectoryLive.pipe( Layer.provide(runtimeRepositoryLayer), ); @@ -993,12 +1235,14 @@ routing.layer("ProviderServiceLive routing", (it) => { Layer.provide(firstDirectoryLayer), Layer.provide(defaultServerSettingsLayer), Layer.provide(AnalyticsService.layerTest), + Layer.provide(Layer.succeed(ProviderEventLoggers, NoOpProviderEventLoggers)), ); const initial = yield* Effect.gen(function* () { const provider = yield* ProviderService; return yield* provider.startSession(asThreadId("thread-claude-start"), { - provider: "claudeAgent", + provider: ProviderDriverKind.make("claudeAgent"), + providerInstanceId: claudeAgentInstanceId, threadId: asThreadId("thread-claude-start"), cwd: "/tmp/project-claude-start", runtimeMode: "full-access", @@ -1010,14 +1254,10 @@ routing.layer("ProviderServiceLive routing", (it) => { yield* provider.listSessions(); }).pipe(Effect.provide(firstProviderLayer)); - const secondClaude = makeFakeCodexAdapter("claudeAgent"); - const secondRegistry: typeof ProviderAdapterRegistry.Service = { - getByProvider: (provider) => - provider === "claudeAgent" - ? Effect.succeed(secondClaude.adapter) - : Effect.fail(new ProviderUnsupportedError({ provider })), - listProviders: () => Effect.succeed(["claudeAgent"]), - }; + const secondClaude = makeFakeCodexAdapter(CLAUDE_AGENT_DRIVER); + const secondRegistry = makeAdapterRegistryMock({ + [ProviderDriverKind.make("claudeAgent")]: secondClaude.adapter, + }); const secondDirectoryLayer = ProviderSessionDirectoryLive.pipe( Layer.provide(runtimeRepositoryLayer), ); @@ -1026,6 +1266,7 @@ routing.layer("ProviderServiceLive routing", (it) => { Layer.provide(secondDirectoryLayer), Layer.provide(defaultServerSettingsLayer), Layer.provide(AnalyticsService.layerTest), + Layer.provide(Layer.succeed(ProviderEventLoggers, NoOpProviderEventLoggers)), ); secondClaude.startSession.mockClear(); @@ -1033,7 +1274,8 @@ routing.layer("ProviderServiceLive routing", (it) => { yield* Effect.gen(function* () { const provider = yield* ProviderService; yield* provider.startSession(initial.threadId, { - provider: "claudeAgent", + provider: ProviderDriverKind.make("claudeAgent"), + providerInstanceId: claudeAgentInstanceId, threadId: initial.threadId, cwd: "/tmp/project-claude-start", runtimeMode: "full-access", @@ -1071,14 +1313,10 @@ routing.layer("ProviderServiceLive routing", (it) => { Layer.provide(persistenceLayer), ); - const firstClaude = makeFakeCodexAdapter("claudeAgent"); - const firstRegistry: typeof ProviderAdapterRegistry.Service = { - getByProvider: (provider) => - provider === "claudeAgent" - ? Effect.succeed(firstClaude.adapter) - : Effect.fail(new ProviderUnsupportedError({ provider })), - listProviders: () => Effect.succeed(["claudeAgent"]), - }; + const firstClaude = makeFakeCodexAdapter(CLAUDE_AGENT_DRIVER); + const firstRegistry = makeAdapterRegistryMock({ + [ProviderDriverKind.make("claudeAgent")]: firstClaude.adapter, + }); const firstDirectoryLayer = ProviderSessionDirectoryLive.pipe( Layer.provide(runtimeRepositoryLayer), ); @@ -1087,26 +1325,24 @@ routing.layer("ProviderServiceLive routing", (it) => { Layer.provide(firstDirectoryLayer), Layer.provide(defaultServerSettingsLayer), Layer.provide(AnalyticsService.layerTest), + Layer.provide(Layer.succeed(ProviderEventLoggers, NoOpProviderEventLoggers)), ); const initial = yield* Effect.gen(function* () { const provider = yield* ProviderService; return yield* provider.startSession(asThreadId("thread-claude-cwd"), { - provider: "claudeAgent", + provider: ProviderDriverKind.make("claudeAgent"), + providerInstanceId: claudeAgentInstanceId, threadId: asThreadId("thread-claude-cwd"), cwd: "/tmp/project-claude-cwd", runtimeMode: "full-access", }); }).pipe(Effect.provide(firstProviderLayer)); - const secondClaude = makeFakeCodexAdapter("claudeAgent"); - const secondRegistry: typeof ProviderAdapterRegistry.Service = { - getByProvider: (provider) => - provider === "claudeAgent" - ? Effect.succeed(secondClaude.adapter) - : Effect.fail(new ProviderUnsupportedError({ provider })), - listProviders: () => Effect.succeed(["claudeAgent"]), - }; + const secondClaude = makeFakeCodexAdapter(CLAUDE_AGENT_DRIVER); + const secondRegistry = makeAdapterRegistryMock({ + [ProviderDriverKind.make("claudeAgent")]: secondClaude.adapter, + }); const secondDirectoryLayer = ProviderSessionDirectoryLive.pipe( Layer.provide(runtimeRepositoryLayer), ); @@ -1115,6 +1351,7 @@ routing.layer("ProviderServiceLive routing", (it) => { Layer.provide(secondDirectoryLayer), Layer.provide(defaultServerSettingsLayer), Layer.provide(AnalyticsService.layerTest), + Layer.provide(Layer.succeed(ProviderEventLoggers, NoOpProviderEventLoggers)), ); secondClaude.startSession.mockClear(); @@ -1122,7 +1359,8 @@ routing.layer("ProviderServiceLive routing", (it) => { yield* Effect.gen(function* () { const provider = yield* ProviderService; yield* provider.startSession(initial.threadId, { - provider: "claudeAgent", + provider: ProviderDriverKind.make("claudeAgent"), + providerInstanceId: claudeAgentInstanceId, threadId: initial.threadId, runtimeMode: "full-access", }); @@ -1155,7 +1393,8 @@ fanout.layer("ProviderServiceLive fanout", (it) => { Effect.gen(function* () { const provider = yield* ProviderService; const session = yield* provider.startSession(asThreadId("thread-1"), { - provider: "codex", + provider: ProviderDriverKind.make("codex"), + providerInstanceId: codexInstanceId, threadId: asThreadId("thread-1"), runtimeMode: "full-access", }); @@ -1169,7 +1408,7 @@ fanout.layer("ProviderServiceLive fanout", (it) => { const completedEvent: LegacyProviderRuntimeEvent = { type: "turn.completed", eventId: asEventId("evt-1"), - provider: "codex", + provider: ProviderDriverKind.make("codex"), createdAt: new Date().toISOString(), threadId: session.threadId, turnId: asTurnId("turn-1"), @@ -1186,6 +1425,13 @@ fanout.layer("ProviderServiceLive fanout", (it) => { events.some((entry) => entry.type === "turn.completed"), true, ); + assert.equal( + events.some( + (entry) => + entry.type === "turn.completed" && entry.providerInstanceId === codexInstanceId, + ), + true, + ); }), ); @@ -1193,7 +1439,8 @@ fanout.layer("ProviderServiceLive fanout", (it) => { Effect.gen(function* () { const provider = yield* ProviderService; const session = yield* provider.startSession(asThreadId("thread-seq"), { - provider: "codex", + provider: ProviderDriverKind.make("codex"), + providerInstanceId: codexInstanceId, threadId: asThreadId("thread-seq"), runtimeMode: "full-access", }); @@ -1208,7 +1455,7 @@ fanout.layer("ProviderServiceLive fanout", (it) => { fanout.codex.emit({ type: "tool.started", eventId: asEventId("evt-seq-1"), - provider: "codex", + provider: ProviderDriverKind.make("codex"), createdAt: new Date().toISOString(), threadId: session.threadId, turnId: asTurnId("turn-1"), @@ -1218,7 +1465,7 @@ fanout.layer("ProviderServiceLive fanout", (it) => { fanout.codex.emit({ type: "tool.completed", eventId: asEventId("evt-seq-2"), - provider: "codex", + provider: ProviderDriverKind.make("codex"), createdAt: new Date().toISOString(), threadId: session.threadId, turnId: asTurnId("turn-1"), @@ -1228,7 +1475,7 @@ fanout.layer("ProviderServiceLive fanout", (it) => { fanout.codex.emit({ type: "turn.completed", eventId: asEventId("evt-seq-3"), - provider: "codex", + provider: ProviderDriverKind.make("codex"), createdAt: new Date().toISOString(), threadId: session.threadId, turnId: asTurnId("turn-1"), @@ -1248,7 +1495,8 @@ fanout.layer("ProviderServiceLive fanout", (it) => { Effect.gen(function* () { const provider = yield* ProviderService; const session = yield* provider.startSession(asThreadId("thread-1"), { - provider: "codex", + provider: ProviderDriverKind.make("codex"), + providerInstanceId: codexInstanceId, threadId: asThreadId("thread-1"), runtimeMode: "full-access", }); @@ -1273,7 +1521,7 @@ fanout.layer("ProviderServiceLive fanout", (it) => { { type: "tool.completed", eventId: asEventId("evt-ordered-1"), - provider: "codex", + provider: ProviderDriverKind.make("codex"), createdAt: new Date().toISOString(), threadId: session.threadId, turnId: asTurnId("turn-1"), @@ -1284,7 +1532,7 @@ fanout.layer("ProviderServiceLive fanout", (it) => { { type: "message.delta", eventId: asEventId("evt-ordered-2"), - provider: "codex", + provider: ProviderDriverKind.make("codex"), createdAt: new Date().toISOString(), threadId: session.threadId, turnId: asTurnId("turn-1"), @@ -1293,7 +1541,7 @@ fanout.layer("ProviderServiceLive fanout", (it) => { { type: "turn.completed", eventId: asEventId("evt-ordered-3"), - provider: "codex", + provider: ProviderDriverKind.make("codex"), createdAt: new Date().toISOString(), threadId: session.threadId, turnId: asTurnId("turn-1"), @@ -1320,7 +1568,8 @@ fanout.layer("ProviderServiceLive fanout", (it) => { const provider = yield* ProviderService; const session = yield* provider.startSession(asThreadId("thread-metrics"), { - provider: "claudeAgent", + provider: ProviderDriverKind.make("claudeAgent"), + providerInstanceId: claudeAgentInstanceId, threadId: asThreadId("thread-metrics"), cwd: "/tmp/project", runtimeMode: "full-access", @@ -1349,7 +1598,7 @@ fanout.layer("ProviderServiceLive fanout", (it) => { assert.equal( hasMetricSnapshot(snapshots, "t3_provider_turns_total", { - provider: "claudeAgent", + provider: ProviderDriverKind.make("claudeAgent"), operation: "interrupt", outcome: "success", }), @@ -1357,7 +1606,7 @@ fanout.layer("ProviderServiceLive fanout", (it) => { ); assert.equal( hasMetricSnapshot(snapshots, "t3_provider_turns_total", { - provider: "claudeAgent", + provider: ProviderDriverKind.make("claudeAgent"), operation: "approval-response", outcome: "success", }), @@ -1365,7 +1614,7 @@ fanout.layer("ProviderServiceLive fanout", (it) => { ); assert.equal( hasMetricSnapshot(snapshots, "t3_provider_turns_total", { - provider: "claudeAgent", + provider: ProviderDriverKind.make("claudeAgent"), operation: "user-input-response", outcome: "success", }), @@ -1373,7 +1622,7 @@ fanout.layer("ProviderServiceLive fanout", (it) => { ); assert.equal( hasMetricSnapshot(snapshots, "t3_provider_turns_total", { - provider: "claudeAgent", + provider: ProviderDriverKind.make("claudeAgent"), operation: "rollback", outcome: "success", }), @@ -1381,7 +1630,7 @@ fanout.layer("ProviderServiceLive fanout", (it) => { ); assert.equal( hasMetricSnapshot(snapshots, "t3_provider_sessions_total", { - provider: "claudeAgent", + provider: ProviderDriverKind.make("claudeAgent"), operation: "stop", outcome: "success", }), @@ -1397,7 +1646,8 @@ fanout.layer("ProviderServiceLive fanout", (it) => { const provider = yield* ProviderService; const session = yield* provider.startSession(asThreadId("thread-send-metrics"), { - provider: "claudeAgent", + provider: ProviderDriverKind.make("claudeAgent"), + providerInstanceId: claudeAgentInstanceId, threadId: asThreadId("thread-send-metrics"), cwd: "/tmp/project-send-metrics", runtimeMode: "full-access", @@ -1413,7 +1663,7 @@ fanout.layer("ProviderServiceLive fanout", (it) => { assert.equal( hasMetricSnapshot(snapshots, "t3_provider_turns_total", { - provider: "claudeAgent", + provider: ProviderDriverKind.make("claudeAgent"), operation: "send", outcome: "success", }), @@ -1421,7 +1671,7 @@ fanout.layer("ProviderServiceLive fanout", (it) => { ); assert.equal( hasMetricSnapshot(snapshots, "t3_provider_turn_duration", { - provider: "claudeAgent", + provider: ProviderDriverKind.make("claudeAgent"), operation: "send", }), true, @@ -1432,6 +1682,50 @@ fanout.layer("ProviderServiceLive fanout", (it) => { const validation = makeProviderServiceLayer(); validation.layer("ProviderServiceLive validation", (it) => { + it.effect("rejects session starts without an explicit provider instance id", () => + Effect.gen(function* () { + const provider = yield* ProviderService; + + validation.codex.startSession.mockClear(); + const failure = yield* Effect.flip( + provider.startSession(asThreadId("thread-missing-instance-id"), { + provider: ProviderDriverKind.make("codex"), + threadId: asThreadId("thread-missing-instance-id"), + runtimeMode: "full-access", + }), + ); + + assert.instanceOf(failure, ProviderValidationError); + assert.include(failure.issue, "Provider instance id is required for provider 'codex'."); + assert.equal(validation.codex.startSession.mock.calls.length, 0); + }), + ); + + it.effect("rejects mismatched provider kind and provider instance id", () => + Effect.gen(function* () { + const provider = yield* ProviderService; + + validation.codex.startSession.mockClear(); + validation.claude.startSession.mockClear(); + const failure = yield* Effect.flip( + provider.startSession(asThreadId("thread-instance-mismatch"), { + provider: ProviderDriverKind.make("codex"), + providerInstanceId: claudeAgentInstanceId, + threadId: asThreadId("thread-instance-mismatch"), + runtimeMode: "full-access", + }), + ); + + assert.instanceOf(failure, ProviderValidationError); + assert.include( + failure.issue, + "Provider instance 'claudeAgent' belongs to driver 'claudeAgent', not 'codex'.", + ); + assert.equal(validation.codex.startSession.mock.calls.length, 0); + assert.equal(validation.claude.startSession.mock.calls.length, 0); + }), + ); + it.effect("returns ProviderValidationError for invalid input payloads", () => Effect.gen(function* () { const provider = yield* ProviderService; @@ -1466,7 +1760,7 @@ validation.layer("ProviderServiceLive validation", (it) => { Effect.sync(() => { const now = new Date().toISOString(); return { - provider: "codex", + provider: ProviderDriverKind.make("codex"), status: "ready", threadId: input.threadId, runtimeMode: input.runtimeMode, @@ -1478,7 +1772,8 @@ validation.layer("ProviderServiceLive validation", (it) => { ); const session = yield* provider.startSession(asThreadId("thread-missing"), { - provider: "codex", + provider: ProviderDriverKind.make("codex"), + providerInstanceId: codexInstanceId, threadId: asThreadId("thread-missing"), cwd: "/tmp/project", runtimeMode: "full-access", diff --git a/apps/server/src/provider/Layers/ProviderService.ts b/apps/server/src/provider/Layers/ProviderService.ts index 94630d3bca..05b4e72ec1 100644 --- a/apps/server/src/provider/Layers/ProviderService.ts +++ b/apps/server/src/provider/Layers/ProviderService.ts @@ -19,10 +19,12 @@ import { ProviderSendTurnInput, ProviderSessionStartInput, ProviderStopSessionInput, + type ProviderInstanceId, + type ProviderDriverKind, type ProviderRuntimeEvent, type ProviderSession, } from "@t3tools/contracts"; -import { Effect, Layer, Option, PubSub, Schema, SchemaIssue, Stream } from "effect"; +import { Cause, Effect, Layer, Option, PubSub, Ref, Schema, SchemaIssue, Stream } from "effect"; import { increment, @@ -34,19 +36,24 @@ import { providerTurnMetricAttributes, withMetrics, } from "../../observability/Metrics.ts"; -import { ProviderValidationError } from "../Errors.ts"; +import { type ProviderAdapterError, ProviderValidationError } from "../Errors.ts"; +import type { ProviderAdapterShape } from "../Services/ProviderAdapter.ts"; import { ProviderAdapterRegistry } from "../Services/ProviderAdapterRegistry.ts"; import { ProviderService, type ProviderServiceShape } from "../Services/ProviderService.ts"; import { ProviderSessionDirectory, type ProviderRuntimeBinding, } from "../Services/ProviderSessionDirectory.ts"; -import { type EventNdjsonLogger, makeEventNdjsonLogger } from "./EventNdjsonLogger.ts"; +import { type EventNdjsonLogger } from "./EventNdjsonLogger.ts"; +import { ProviderEventLoggers } from "./ProviderEventLoggers.ts"; import { AnalyticsService } from "../../telemetry/Services/AnalyticsService.ts"; -import { ServerSettingsService } from "../../serverSettings.ts"; +/** + * Hook for tests that want to override the canonical event logger pulled + * from `ProviderEventLoggers`. Production wiring leaves this undefined and + * reads the logger off the tag. + */ export interface ProviderServiceLiveOptions { - readonly canonicalEventLogPath?: string; readonly canonicalEventLogger?: EventNdjsonLogger; } @@ -141,18 +148,53 @@ function readPersistedCwd( return trimmed.length > 0 ? trimmed : undefined; } +const dieOnMissingBindingInstanceId = ( + operation: string, + payload: { + readonly providerInstanceId?: ProviderInstanceId | undefined; + readonly provider?: ProviderDriverKind | undefined; + }, +): ProviderInstanceId => { + if (payload.providerInstanceId !== undefined) { + return payload.providerInstanceId; + } + throw new Error( + payload.provider + ? `${operation}: provider instance id is required for provider '${payload.provider}'.` + : `${operation}: provider instance id is required.`, + ); +}; + +const correlateRuntimeEventWithInstance = ( + source: { + readonly instanceId: ProviderInstanceId; + readonly provider: ProviderDriverKind; + }, + event: ProviderRuntimeEvent, +): ProviderRuntimeEvent => { + if (event.provider !== source.provider) { + throw new Error( + `ProviderService.streamEvents: provider instance '${source.instanceId}' is backed by driver '${source.provider}' but emitted driver '${event.provider}'.`, + ); + } + if (event.providerInstanceId !== undefined && event.providerInstanceId !== source.instanceId) { + throw new Error( + `ProviderService.streamEvents: provider instance '${source.instanceId}' emitted event for instance '${event.providerInstanceId}'.`, + ); + } + return { ...event, providerInstanceId: source.instanceId }; +}; + const makeProviderService = Effect.fn("makeProviderService")(function* ( options?: ProviderServiceLiveOptions, ) { const analytics = yield* Effect.service(AnalyticsService); - const serverSettings = yield* ServerSettingsService; - const canonicalEventLogger = - options?.canonicalEventLogger ?? - (options?.canonicalEventLogPath !== undefined - ? yield* makeEventNdjsonLogger(options.canonicalEventLogPath, { - stream: "canonical", - }) - : undefined); + const eventLoggers = yield* ProviderEventLoggers; + // Options-provided logger wins (test overrides); otherwise we take whatever + // the `ProviderEventLoggers` tag exposes — `undefined` means "no canonical + // log writer is attached", which downstream code already handles as a + // no-op. + const canonicalEventLogger = options?.canonicalEventLogger ?? eventLoggers.canonical; const registry = yield* ProviderAdapterRegistry; const directory = yield* ProviderSessionDirectory; @@ -169,6 +211,24 @@ const makeProviderService = Effect.fn("makeProviderService")(function* ( Effect.asVoid, ); + const requireBindingInstanceId = ( + operation: string, + payload: { + readonly providerInstanceId?: ProviderInstanceId | undefined; + readonly provider?: ProviderDriverKind | undefined; + }, + ): Effect.Effect => + payload.providerInstanceId !== undefined + ? Effect.succeed(payload.providerInstanceId) + : Effect.fail( + toValidationError( + operation, + payload.provider + ? `Provider instance id is required for provider '${payload.provider}'.` + : "Provider instance id is required.", + ), + ); + const upsertSessionBinding = ( session: ProviderSession, threadId: ThreadId, @@ -178,38 +238,106 @@ const makeProviderService = Effect.fn("makeProviderService")(function* ( readonly lastRuntimeEventAt?: string; }, ) => - directory.upsert({ - threadId, - provider: session.provider, - runtimeMode: session.runtimeMode, - status: toRuntimeStatus(session), - ...(session.resumeCursor !== undefined ? { resumeCursor: session.resumeCursor } : {}), - runtimePayload: toRuntimePayloadFromSession(session, extra), + Effect.gen(function* () { + const providerInstanceId = yield* requireBindingInstanceId( + "ProviderService.upsertSessionBinding", + session, + ); + yield* directory.upsert({ + threadId, + provider: session.provider, + providerInstanceId, + runtimeMode: session.runtimeMode, + status: toRuntimeStatus(session), + ...(session.resumeCursor !== undefined ? { resumeCursor: session.resumeCursor } : {}), + runtimePayload: toRuntimePayloadFromSession(session, extra), + }); }); - const providers = yield* registry.listProviders(); - const adapters = yield* Effect.forEach(providers, (provider) => registry.getByProvider(provider)); - const processRuntimeEvent = (event: ProviderRuntimeEvent): Effect.Effect => - increment(providerRuntimeEventsTotal, { - provider: event.provider, - eventType: event.type, - }).pipe(Effect.andThen(publishRuntimeEvent(event))); + const processRuntimeEvent = ( + source: { + readonly instanceId: ProviderInstanceId; + readonly provider: ProviderDriverKind; + }, + event: ProviderRuntimeEvent, + ): Effect.Effect => + Effect.sync(() => correlateRuntimeEventWithInstance(source, event)).pipe( + Effect.flatMap((canonicalEvent) => + increment(providerRuntimeEventsTotal, { + provider: canonicalEvent.provider, + eventType: canonicalEvent.type, + }).pipe(Effect.andThen(publishRuntimeEvent(canonicalEvent))), + ), + ); - yield* Effect.forEach(adapters, (adapter) => - Stream.runForEach(adapter.streamEvents, processRuntimeEvent).pipe(Effect.forkScoped), - ).pipe(Effect.asVoid); + // `subscribedAdapters` is our source-of-truth for "which instance adapters + // are currently wired into the runtime event bus". It both tracks the set + // of live subscriptions (so `reconcileInstanceSubscriptions` can diff and + // fork only the *new* or *rebuilt* ones) and serves as the dynamic adapter + // list consumed by `stopStaleSessionsForThread`, `listSessions`, and + // `runStopAll` — replacing the pre-Slice-D startup snapshot so hot-added + // instances become visible to those call sites as soon as settings edits + // land. + const subscribedAdapters = yield* Ref.make( + new Map>(), + ); + + const getAdapterEntries = Ref.get(subscribedAdapters).pipe( + Effect.map((map) => Array.from(map.entries())), + ); + + // Rebuild the map of id → adapter from the registry and fork a new event + // subscription for every instance that is either brand new or whose adapter + // identity changed (indicating the underlying `ProviderInstance` was torn + // down and rebuilt by `ProviderInstanceRegistry.reconcile`). Orphaned + // fibers for removed/replaced instances exit on their own because their + // adapter's `streamEvents` source terminates when the old scope closes. + const reconcileInstanceSubscriptions = Effect.gen(function* () { + const previous = yield* Ref.get(subscribedAdapters); + const currentIds = yield* registry.listInstances(); + const next = new Map>(); + for (const id of currentIds) { + const adapterOption = yield* registry + .getByInstance(id) + .pipe(Effect.tapError(Effect.logWarning), Effect.option); + if (Option.isNone(adapterOption)) continue; + const adapter = adapterOption.value; + next.set(id, adapter); + if (previous.get(id) !== adapter) { + yield* Stream.runForEach(adapter.streamEvents, (event) => + processRuntimeEvent( + { + instanceId: id, + provider: adapter.provider, + }, + event, + ), + ).pipe(Effect.forkScoped); + } + } + yield* Ref.set(subscribedAdapters, next); + }); + + const instanceChanges = yield* registry.subscribeChanges; + yield* reconcileInstanceSubscriptions; + yield* Stream.runForEach( + Stream.fromSubscription(instanceChanges), + () => reconcileInstanceSubscriptions, + ).pipe(Effect.forkScoped); const recoverSessionForThread = Effect.fn("recoverSessionForThread")(function* (input: { readonly binding: ProviderRuntimeBinding; readonly operation: string; }) { + const bindingInstanceId = yield* requireBindingInstanceId(input.operation, input.binding); yield* Effect.annotateCurrentSpan({ "provider.operation": "recover-session", "provider.kind": input.binding.provider, + "provider.instance_id": bindingInstanceId, "provider.thread_id": input.binding.threadId, }); return yield* Effect.gen(function* () { - const adapter = yield* registry.getByProvider(input.binding.provider); + const adapter = yield* registry.getByInstance(bindingInstanceId); const hasResumeCursor = input.binding.resumeCursor !== null && input.binding.resumeCursor !== undefined; const hasActiveSession = yield* adapter.hasSession(input.binding.threadId); @@ -219,7 +347,10 @@ const makeProviderService = Effect.fn("makeProviderService")(function* ( (session) => session.threadId === input.binding.threadId, ); if (existing) { - yield* upsertSessionBinding(existing, input.binding.threadId); + yield* upsertSessionBinding( + { ...existing, providerInstanceId: bindingInstanceId }, + input.binding.threadId, + ); yield* analytics.record("provider.session.recovered", { provider: existing.provider, strategy: "adopt-existing", @@ -242,6 +373,7 @@ const makeProviderService = Effect.fn("makeProviderService")(function* ( const resumed = yield* adapter.startSession({ threadId: input.binding.threadId, provider: input.binding.provider, + providerInstanceId: bindingInstanceId, ...(persistedCwd ? { cwd: persistedCwd } : {}), ...(persistedModelSelection ? { modelSelection: persistedModelSelection } : {}), ...(hasResumeCursor ? { resumeCursor: input.binding.resumeCursor } : {}), @@ -254,7 +386,10 @@ const makeProviderService = Effect.fn("makeProviderService")(function* ( ); } - yield* upsertSessionBinding(resumed, input.binding.threadId); + yield* upsertSessionBinding( + { ...resumed, providerInstanceId: bindingInstanceId }, + input.binding.threadId, + ); yield* analytics.record("provider.session.recovered", { provider: resumed.provider, strategy: "resume-thread", @@ -284,29 +419,49 @@ const makeProviderService = Effect.fn("makeProviderService")(function* ( `Cannot route thread '${input.threadId}' because no persisted provider binding exists.`, ); } - const adapter = yield* registry.getByProvider(binding.provider); + const instanceId = yield* requireBindingInstanceId(input.operation, binding); + const adapter = yield* registry.getByInstance(instanceId); const hasRequestedSession = yield* adapter.hasSession(input.threadId); if (hasRequestedSession) { - return { adapter, threadId: input.threadId, isActive: true } as const; + return { + adapter, + instanceId, + threadId: input.threadId, + isActive: true, + } as const; } if (!input.allowRecovery) { - return { adapter, threadId: input.threadId, isActive: false } as const; + return { + adapter, + instanceId, + threadId: input.threadId, + isActive: false, + } as const; } - const recovered = yield* recoverSessionForThread({ binding, operation: input.operation }); - return { adapter: recovered.adapter, threadId: input.threadId, isActive: true } as const; + const recovered = yield* recoverSessionForThread({ + binding, + operation: input.operation, + }); + return { + adapter: recovered.adapter, + instanceId, + threadId: input.threadId, + isActive: true, + } as const; }); const stopStaleSessionsForThread = Effect.fn("stopStaleSessionsForThread")(function* (input: { readonly threadId: ThreadId; - readonly currentProvider: ProviderSession["provider"]; + readonly currentInstanceId: ProviderInstanceId; }) { + const currentAdapters = yield* getAdapterEntries; yield* Effect.forEach( - adapters, - (adapter) => - adapter.provider === input.currentProvider + currentAdapters, + ([instanceId, adapter]) => + instanceId === input.currentInstanceId ? Effect.void : Effect.gen(function* () { const hasSession = yield* adapter.hasSession(input.threadId); @@ -341,63 +496,72 @@ const makeProviderService = Effect.fn("makeProviderService")(function* ( payload: rawInput, }); - const input = { - ...parsed, - threadId, - provider: parsed.provider ?? "codex", - }; + const resolvedInstanceId = yield* requireBindingInstanceId( + "ProviderService.startSession", + parsed, + ); + let metricProvider = parsed.provider ?? String(resolvedInstanceId); yield* Effect.annotateCurrentSpan({ "provider.operation": "start-session", - "provider.kind": input.provider, + "provider.instance_id": resolvedInstanceId, "provider.thread_id": threadId, - "provider.runtime_mode": input.runtimeMode, + "provider.runtime_mode": parsed.runtimeMode, }); return yield* Effect.gen(function* () { - const settings = yield* serverSettings.getSettings.pipe( - Effect.mapError((error) => - toValidationError( - "ProviderService.startSession", - `Failed to load provider settings: ${error.message}`, - error, - ), - ), - ); - if (!settings.providers[input.provider].enabled) { + const instanceInfo = yield* registry.getInstanceInfo(resolvedInstanceId); + const resolvedProvider = instanceInfo.driverKind; + metricProvider = resolvedProvider; + if (parsed.provider !== undefined && parsed.provider !== resolvedProvider) { return yield* toValidationError( "ProviderService.startSession", - `Provider '${input.provider}' is disabled in T3 Code settings.`, + `Provider instance '${resolvedInstanceId}' belongs to driver '${resolvedProvider}', not '${parsed.provider}'.`, + ); + } + const input = { + ...parsed, + threadId, + provider: resolvedProvider, + }; + if (!instanceInfo.enabled) { + return yield* toValidationError( + "ProviderService.startSession", + `Provider instance '${resolvedInstanceId}' is disabled in T3 Code settings.`, ); } const persistedBinding = Option.getOrUndefined(yield* directory.getBinding(threadId)); const effectiveResumeCursor = input.resumeCursor ?? - (persistedBinding?.provider === input.provider + (persistedBinding?.providerInstanceId === resolvedInstanceId ? persistedBinding.resumeCursor : undefined); const effectiveCwd = input.cwd ?? - (persistedBinding?.provider === input.provider + (persistedBinding?.providerInstanceId === resolvedInstanceId ? readPersistedCwd(persistedBinding.runtimePayload) : undefined); yield* Effect.annotateCurrentSpan({ + "provider.kind": resolvedProvider, "provider.resume_cursor.source": input.resumeCursor !== undefined ? "request" - : effectiveResumeCursor !== undefined && persistedBinding?.provider === input.provider + : effectiveResumeCursor !== undefined && + persistedBinding?.providerInstanceId === resolvedInstanceId ? "persisted" : "none", "provider.resume_cursor.present": effectiveResumeCursor !== undefined, "provider.cwd.source": input.cwd !== undefined ? "request" - : effectiveCwd !== undefined && persistedBinding?.provider === input.provider + : effectiveCwd !== undefined && + persistedBinding?.providerInstanceId === resolvedInstanceId ? "persisted" : "none", "provider.cwd.effective": effectiveCwd ?? "", }); - const adapter = yield* registry.getByProvider(input.provider); + const adapter = yield* registry.getByInstance(resolvedInstanceId); const session = yield* adapter.startSession({ ...input, + providerInstanceId: resolvedInstanceId, ...(effectiveCwd !== undefined ? { cwd: effectiveCwd } : {}), ...(effectiveResumeCursor !== undefined ? { resumeCursor: effectiveResumeCursor } : {}), }); @@ -408,31 +572,36 @@ const makeProviderService = Effect.fn("makeProviderService")(function* ( `Adapter/provider mismatch: requested '${adapter.provider}', received '${session.provider}'.`, ); } + const sessionWithInstance = { + ...session, + providerInstanceId: resolvedInstanceId, + }; yield* stopStaleSessionsForThread({ threadId, - currentProvider: adapter.provider, + currentInstanceId: resolvedInstanceId, }); - yield* upsertSessionBinding(session, threadId, { + yield* upsertSessionBinding(sessionWithInstance, threadId, { modelSelection: input.modelSelection, }); yield* analytics.record("provider.session.started", { - provider: session.provider, + provider: sessionWithInstance.provider, runtimeMode: input.runtimeMode, - hasResumeCursor: session.resumeCursor !== undefined, + hasResumeCursor: sessionWithInstance.resumeCursor !== undefined, hasCwd: typeof effectiveCwd === "string" && effectiveCwd.trim().length > 0, hasModel: typeof input.modelSelection?.model === "string" && input.modelSelection.model.trim().length > 0, }); - return session; + return sessionWithInstance; }).pipe( withMetrics({ counter: providerSessionsTotal, - attributes: providerMetricAttributes(input.provider, { - operation: "start", - }), + attributes: () => + providerMetricAttributes(metricProvider, { + operation: "start", + }), }), ); }, @@ -479,6 +648,7 @@ const makeProviderService = Effect.fn("makeProviderService")(function* ( yield* directory.upsert({ threadId: input.threadId, provider: routed.adapter.provider, + providerInstanceId: routed.instanceId, status: "running", ...(turn.resumeCursor !== undefined ? { resumeCursor: turn.resumeCursor } : {}), runtimePayload: { @@ -647,6 +817,7 @@ const makeProviderService = Effect.fn("makeProviderService")(function* ( yield* directory.upsert({ threadId: input.threadId, provider: routed.adapter.provider, + providerInstanceId: routed.instanceId, status: "stopped", runtimePayload: { activeTurnId: null, @@ -669,8 +840,16 @@ const makeProviderService = Effect.fn("makeProviderService")(function* ( const listSessions: ProviderServiceShape["listSessions"] = Effect.fn("listSessions")( function* () { - const sessionsByProvider = yield* Effect.forEach(adapters, (adapter) => - adapter.listSessions(), + const currentAdapters = yield* getAdapterEntries; + const sessionsByProvider = yield* Effect.forEach(currentAdapters, ([instanceId, adapter]) => + adapter.listSessions().pipe( + Effect.map((sessions) => + sessions.map((session) => ({ + ...session, + providerInstanceId: instanceId, + })), + ), + ), ); const activeSessions = sessionsByProvider.flatMap((sessions) => sessions); const persistedBindings = yield* directory.listThreadIds().pipe( @@ -694,29 +873,54 @@ const makeProviderService = Effect.fn("makeProviderService")(function* ( } } - return activeSessions.map((session) => { + const sessions: ProviderSession[] = []; + for (const session of activeSessions) { const binding = bindingsByThreadId.get(session.threadId); if (!binding) { - return session; + sessions.push(session); + continue; } const overrides: { resumeCursor?: ProviderSession["resumeCursor"]; runtimeMode?: ProviderSession["runtimeMode"]; + providerInstanceId?: ProviderSession["providerInstanceId"]; } = {}; + overrides.providerInstanceId = dieOnMissingBindingInstanceId( + "ProviderService.listSessions", + binding, + ); + if (binding.provider !== session.provider) { + return yield* Effect.die( + new Error( + `ProviderService.listSessions: thread '${session.threadId}' is active on provider '${session.provider}' but persisted binding names provider '${binding.provider}'.`, + ), + ); + } + if (overrides.providerInstanceId !== session.providerInstanceId) { + return yield* Effect.die( + new Error( + `ProviderService.listSessions: thread '${session.threadId}' is active on provider instance '${session.providerInstanceId}' but persisted binding names '${overrides.providerInstanceId}'.`, + ), + ); + } if (session.resumeCursor === undefined && binding.resumeCursor !== undefined) { overrides.resumeCursor = binding.resumeCursor; } if (binding.runtimeMode !== undefined) { overrides.runtimeMode = binding.runtimeMode; } - return Object.assign({}, session, overrides); - }); + sessions.push(Object.assign({}, session, overrides)); + } + return sessions; }, ); - const getCapabilities: ProviderServiceShape["getCapabilities"] = (provider) => - registry.getByProvider(provider).pipe(Effect.map((adapter) => adapter.capabilities)); + const getCapabilities: ProviderServiceShape["getCapabilities"] = (instanceId) => + registry.getByInstance(instanceId).pipe(Effect.map((adapter) => adapter.capabilities)); + + const getInstanceInfo: ProviderServiceShape["getInstanceInfo"] = (instanceId) => + registry.getInstanceInfo(instanceId); const rollbackConversation: ProviderServiceShape["rollbackConversation"] = Effect.fn( "rollbackConversation", @@ -761,8 +965,16 @@ const makeProviderService = Effect.fn("makeProviderService")(function* ( const runStopAll = Effect.fn("runStopAll")(function* () { const threadIds = yield* directory.listThreadIds(); - const activeSessions = yield* Effect.forEach(adapters, (adapter) => - adapter.listSessions(), + const currentAdapters = yield* getAdapterEntries; + const activeSessions = yield* Effect.forEach(currentAdapters, ([instanceId, adapter]) => + adapter.listSessions().pipe( + Effect.map((sessions) => + sessions.map((session) => ({ + ...session, + providerInstanceId: instanceId, + })), + ), + ), ).pipe(Effect.map((sessionsByAdapter) => sessionsByAdapter.flatMap((sessions) => sessions))); yield* Effect.forEach(activeSessions, (session) => upsertSessionBinding(session, session.threadId, { @@ -770,23 +982,22 @@ const makeProviderService = Effect.fn("makeProviderService")(function* ( lastRuntimeEventAt: new Date().toISOString(), }), ).pipe(Effect.asVoid); - yield* Effect.forEach(adapters, (adapter) => adapter.stopAll()).pipe(Effect.asVoid); - yield* Effect.forEach(threadIds, (threadId) => - directory.getProvider(threadId).pipe( - Effect.flatMap((provider) => - directory.upsert({ - threadId, - provider, - status: "stopped", - runtimePayload: { - activeTurnId: null, - lastRuntimeEvent: "provider.stopAll", - lastRuntimeEventAt: new Date().toISOString(), - }, - }), - ), - ), - ).pipe(Effect.asVoid); + yield* Effect.forEach(currentAdapters, ([, adapter]) => adapter.stopAll()).pipe(Effect.asVoid); + const bindings = yield* directory.listBindings().pipe(Effect.orElseSucceed(() => [])); + yield* Effect.forEach(bindings, (binding) => { + const providerInstanceId = dieOnMissingBindingInstanceId("ProviderService.stopAll", binding); + return directory.upsert({ + threadId: binding.threadId, + provider: binding.provider, + providerInstanceId, + status: "stopped", + runtimePayload: { + activeTurnId: null, + lastRuntimeEvent: "provider.stopAll", + lastRuntimeEventAt: new Date().toISOString(), + }, + }); + }).pipe(Effect.asVoid); yield* analytics.record("provider.sessions.stopped_all", { sessionCount: threadIds.length, }); @@ -794,8 +1005,10 @@ const makeProviderService = Effect.fn("makeProviderService")(function* ( }); yield* Effect.addFinalizer(() => - Effect.catch(runStopAll(), (cause) => - Effect.logWarning("failed to stop provider service", { cause }), + runStopAll().pipe( + Effect.catchCause((cause) => + Effect.logWarning("failed to stop provider service", { cause: Cause.pretty(cause) }), + ), ), ); @@ -808,6 +1021,7 @@ const makeProviderService = Effect.fn("makeProviderService")(function* ( stopSession, listSessions, getCapabilities, + getInstanceInfo, rollbackConversation, // Each access creates a fresh PubSub subscription so that multiple // consumers (ProviderRuntimeIngestion, CheckpointReactor, etc.) each diff --git a/apps/server/src/provider/Layers/ProviderSessionDirectory.test.ts b/apps/server/src/provider/Layers/ProviderSessionDirectory.test.ts index 35bdec1e37..28a168c43a 100644 --- a/apps/server/src/provider/Layers/ProviderSessionDirectory.test.ts +++ b/apps/server/src/provider/Layers/ProviderSessionDirectory.test.ts @@ -3,7 +3,7 @@ import os from "node:os"; import path from "node:path"; import * as NodeServices from "@effect/platform-node/NodeServices"; -import { ThreadId } from "@t3tools/contracts"; +import { ProviderDriverKind, ThreadId } from "@t3tools/contracts"; import { it, assert } from "@effect/vitest"; import { assertSome } from "@effect/vitest/utils"; import { Effect, Layer, Option } from "effect"; @@ -38,7 +38,7 @@ it.layer(makeDirectoryLayer(SqlitePersistenceMemory))("ProviderSessionDirectoryL const initialThreadId = ThreadId.make("thread-1"); yield* directory.upsert({ - provider: "codex", + provider: ProviderDriverKind.make("codex"), threadId: initialThreadId, }); @@ -47,7 +47,7 @@ it.layer(makeDirectoryLayer(SqlitePersistenceMemory))("ProviderSessionDirectoryL const resolvedBinding = yield* directory.getBinding(initialThreadId); assertSome(resolvedBinding, { threadId: initialThreadId, - provider: "codex", + provider: ProviderDriverKind.make("codex"), }); if (Option.isSome(resolvedBinding)) { assert.equal(resolvedBinding.value.threadId, initialThreadId); @@ -56,7 +56,7 @@ it.layer(makeDirectoryLayer(SqlitePersistenceMemory))("ProviderSessionDirectoryL const nextThreadId = ThreadId.make("thread-2"); yield* directory.upsert({ - provider: "codex", + provider: ProviderDriverKind.make("codex"), threadId: nextThreadId, }); const updatedBinding = yield* directory.getBinding(nextThreadId); @@ -85,7 +85,7 @@ it.layer(makeDirectoryLayer(SqlitePersistenceMemory))("ProviderSessionDirectoryL const threadId = ThreadId.make("thread-runtime"); yield* directory.upsert({ - provider: "codex", + provider: ProviderDriverKind.make("codex"), threadId, status: "starting", resumeCursor: { @@ -98,7 +98,7 @@ it.layer(makeDirectoryLayer(SqlitePersistenceMemory))("ProviderSessionDirectoryL }); yield* directory.upsert({ - provider: "codex", + provider: ProviderDriverKind.make("codex"), threadId, status: "running", runtimePayload: { @@ -133,6 +133,7 @@ it.layer(makeDirectoryLayer(SqlitePersistenceMemory))("ProviderSessionDirectoryL yield* runtimeRepository.upsert({ threadId: newerThreadId, providerName: "codex", + providerInstanceId: null, adapterKey: "codex", runtimeMode: "full-access", status: "running", @@ -148,6 +149,7 @@ it.layer(makeDirectoryLayer(SqlitePersistenceMemory))("ProviderSessionDirectoryL yield* runtimeRepository.upsert({ threadId: olderThreadId, providerName: "claudeAgent", + providerInstanceId: null, adapterKey: "claudeAgent", runtimeMode: "approval-required", status: "starting", @@ -165,7 +167,7 @@ it.layer(makeDirectoryLayer(SqlitePersistenceMemory))("ProviderSessionDirectoryL assert.deepEqual(bindings, [ { threadId: olderThreadId, - provider: "claudeAgent", + provider: ProviderDriverKind.make("claudeAgent"), adapterKey: "claudeAgent", runtimeMode: "approval-required", status: "starting", @@ -179,7 +181,7 @@ it.layer(makeDirectoryLayer(SqlitePersistenceMemory))("ProviderSessionDirectoryL }, { threadId: newerThreadId, - provider: "codex", + provider: ProviderDriverKind.make("codex"), adapterKey: "codex", runtimeMode: "full-access", status: "running", @@ -203,6 +205,7 @@ it.layer(makeDirectoryLayer(SqlitePersistenceMemory))("ProviderSessionDirectoryL yield* runtimeRepository.upsert({ threadId, providerName: "claudeAgent", + providerInstanceId: null, adapterKey: "claudeAgent", runtimeMode: "full-access", status: "running", @@ -212,7 +215,7 @@ it.layer(makeDirectoryLayer(SqlitePersistenceMemory))("ProviderSessionDirectoryL }); yield* directory.upsert({ - provider: "codex", + provider: ProviderDriverKind.make("codex"), threadId, }); @@ -235,7 +238,7 @@ it.layer(makeDirectoryLayer(SqlitePersistenceMemory))("ProviderSessionDirectoryL yield* Effect.gen(function* () { const directory = yield* ProviderSessionDirectory; yield* directory.upsert({ - provider: "codex", + provider: ProviderDriverKind.make("codex"), threadId, }); }).pipe(Effect.provide(directoryLayer)); @@ -249,7 +252,7 @@ it.layer(makeDirectoryLayer(SqlitePersistenceMemory))("ProviderSessionDirectoryL const resolvedBinding = yield* directory.getBinding(threadId); assertSome(resolvedBinding, { threadId, - provider: "codex", + provider: ProviderDriverKind.make("codex"), }); if (Option.isSome(resolvedBinding)) { assert.equal(resolvedBinding.value.threadId, threadId); diff --git a/apps/server/src/provider/Layers/ProviderSessionDirectory.ts b/apps/server/src/provider/Layers/ProviderSessionDirectory.ts index 4cb7147180..e1479082f2 100644 --- a/apps/server/src/provider/Layers/ProviderSessionDirectory.ts +++ b/apps/server/src/provider/Layers/ProviderSessionDirectory.ts @@ -1,4 +1,4 @@ -import { ProviderKind, type ThreadId } from "@t3tools/contracts"; +import { defaultInstanceIdForDriver, ProviderDriverKind, type ThreadId } from "@t3tools/contracts"; import { Effect, Layer, Option, Schema } from "effect"; import type { ProviderSessionRuntime } from "../../persistence/Services/ProviderSessionRuntime.ts"; @@ -20,11 +20,11 @@ function toPersistenceError(operation: string) { }); } -function decodeProviderKind( +function decodeProviderDriverKind( providerName: string, operation: string, -): Effect.Effect { - return Schema.decodeUnknownEffect(ProviderKind)(providerName).pipe( +): Effect.Effect { + return Schema.decodeUnknownEffect(ProviderDriverKind)(providerName).pipe( Effect.mapError( (cause) => new ProviderSessionDirectoryPersistenceError({ @@ -57,12 +57,17 @@ function toRuntimeBinding( runtime: ProviderSessionRuntime, operation: string, ): Effect.Effect { - return decodeProviderKind(runtime.providerName, operation).pipe( + return decodeProviderDriverKind(runtime.providerName, operation).pipe( Effect.map( (provider) => ({ threadId: runtime.threadId, provider, + // Migration boundary only: rows written before the instance split + // have a null provider_instance_id. Promote them as they leave + // persistence so hot routing code never has to infer an instance + // from a driver kind. + providerInstanceId: runtime.providerInstanceId ?? defaultInstanceIdForDriver(provider), adapterKey: runtime.adapterKey, runtimeMode: runtime.runtimeMode, status: runtime.status, @@ -108,10 +113,19 @@ const makeProviderSessionDirectory = Effect.gen(function* () { const now = new Date().toISOString(); const providerChanged = existingRuntime !== undefined && existingRuntime.providerName !== binding.provider; + const providerInstanceId = + binding.providerInstanceId ?? (!providerChanged ? existingRuntime?.providerInstanceId : null); + if (providerInstanceId === null || providerInstanceId === undefined) { + return yield* new ProviderValidationError({ + operation: "ProviderSessionDirectory.upsert", + issue: "providerInstanceId is required for provider session runtime bindings.", + }); + } yield* repository .upsert({ threadId: resolvedThreadId, providerName: binding.provider, + providerInstanceId, adapterKey: binding.adapterKey ?? (providerChanged ? binding.provider : (existingRuntime?.adapterKey ?? binding.provider)), diff --git a/apps/server/src/provider/Layers/ProviderSessionReaper.test.ts b/apps/server/src/provider/Layers/ProviderSessionReaper.test.ts index 45199a02b2..91e1a9aef9 100644 --- a/apps/server/src/provider/Layers/ProviderSessionReaper.test.ts +++ b/apps/server/src/provider/Layers/ProviderSessionReaper.test.ts @@ -1,5 +1,11 @@ import * as NodeServices from "@effect/platform-node/NodeServices"; -import { ProjectId, ThreadId, TurnId } from "@t3tools/contracts"; +import { + ProjectId, + ThreadId, + TurnId, + ProviderDriverKind, + ProviderInstanceId, +} from "@t3tools/contracts"; import { Effect, Exit, Layer, ManagedRuntime, Option, Scope, Stream } from "effect"; import { afterEach, describe, expect, it, vi } from "vitest"; @@ -17,7 +23,7 @@ import { ProviderSessionDirectoryLive } from "./ProviderSessionDirectory.ts"; import { makeProviderSessionReaperLive } from "./ProviderSessionReaper.ts"; const defaultModelSelection = { - provider: "codex", + instanceId: ProviderInstanceId.make("codex"), model: "gpt-5-codex", } as const; @@ -140,6 +146,19 @@ describe("ProviderSessionReaper", () => { stopSession, listSessions: () => Effect.succeed([]), getCapabilities: () => Effect.succeed({ sessionModelSwitch: "in-session" }), + getInstanceInfo: (instanceId) => { + const driverKind = ProviderDriverKind.make(String(instanceId)); + return Effect.succeed({ + instanceId, + driverKind, + displayName: undefined, + enabled: true, + continuationIdentity: { + driverKind, + continuationKey: `${driverKind}:instance:${instanceId}`, + }, + }); + }, rollbackConversation: () => unsupported(), streamEvents: Stream.empty, }; @@ -197,6 +216,7 @@ describe("ProviderSessionReaper", () => { repository.upsert({ threadId, providerName: "claudeAgent", + providerInstanceId: null, adapterKey: "claudeAgent", runtimeMode: "full-access", status: "running", @@ -244,6 +264,7 @@ describe("ProviderSessionReaper", () => { repository.upsert({ threadId, providerName: "claudeAgent", + providerInstanceId: null, adapterKey: "claudeAgent", runtimeMode: "full-access", status: "running", @@ -290,6 +311,7 @@ describe("ProviderSessionReaper", () => { repository.upsert({ threadId, providerName: "claudeAgent", + providerInstanceId: null, adapterKey: "claudeAgent", runtimeMode: "full-access", status: "running", @@ -336,6 +358,7 @@ describe("ProviderSessionReaper", () => { repository.upsert({ threadId, providerName: "claudeAgent", + providerInstanceId: null, adapterKey: "claudeAgent", runtimeMode: "full-access", status: "stopped", @@ -404,6 +427,7 @@ describe("ProviderSessionReaper", () => { repository.upsert({ threadId: failedThreadId, providerName: "claudeAgent", + providerInstanceId: null, adapterKey: "claudeAgent", runtimeMode: "full-access", status: "running", @@ -418,6 +442,7 @@ describe("ProviderSessionReaper", () => { repository.upsert({ threadId: reapedThreadId, providerName: "codex", + providerInstanceId: null, adapterKey: "codex", runtimeMode: "full-access", status: "running", @@ -483,6 +508,7 @@ describe("ProviderSessionReaper", () => { repository.upsert({ threadId: defectThreadId, providerName: "claudeAgent", + providerInstanceId: null, adapterKey: "claudeAgent", runtimeMode: "full-access", status: "running", @@ -497,6 +523,7 @@ describe("ProviderSessionReaper", () => { repository.upsert({ threadId: reapedThreadId, providerName: "codex", + providerInstanceId: null, adapterKey: "codex", runtimeMode: "full-access", status: "running", diff --git a/apps/server/src/provider/Layers/scopedSafeTeardown.test.ts b/apps/server/src/provider/Layers/scopedSafeTeardown.test.ts new file mode 100644 index 0000000000..ebbc379b7d --- /dev/null +++ b/apps/server/src/provider/Layers/scopedSafeTeardown.test.ts @@ -0,0 +1,94 @@ +import { it } from "@effect/vitest"; +import { Cause, Effect, Exit } from "effect"; +import { describe, expect } from "vitest"; + +import { scopedSafeTeardown } from "./scopedSafeTeardown.ts"; + +describe("scopedSafeTeardown", () => { + it.effect("returns the body's value when teardown is clean", () => + Effect.gen(function* () { + const finalizers: string[] = []; + const wrapped = Effect.gen(function* () { + yield* Effect.addFinalizer(() => + Effect.sync(() => { + finalizers.push("clean"); + }), + ); + return "body-ok"; + }).pipe(scopedSafeTeardown("test")); + + const value = yield* wrapped; + expect(value).toBe("body-ok"); + expect(finalizers).toEqual(["clean"]); + }), + ); + + it.effect("preserves body success when a finalizer dies", () => + // The production failure mode: `Layer.build(...)` registers a finalizer + // that kills a subprocess; if the kill fails, the defect would otherwise + // override a successful probe body. + Effect.gen(function* () { + const finalizers: string[] = []; + const wrapped = Effect.gen(function* () { + yield* Effect.addFinalizer(() => + Effect.sync(() => { + finalizers.push("ran-before-die"); + }), + ); + yield* Effect.addFinalizer(() => + Effect.die(new Error("simulated subprocess kill failure")), + ); + return "body-ok"; + }).pipe(scopedSafeTeardown("test")); + + const value = yield* wrapped; + expect(value).toBe("body-ok"); + // The clean finalizer still ran; teardown defect was logged + swallowed. + expect(finalizers).toEqual(["ran-before-die"]); + }), + ); + + it.effect("preserves typed body failures even when teardown is clean", () => + Effect.gen(function* () { + class BodyError { + readonly _tag = "BodyError" as const; + } + const wrapped = Effect.gen(function* () { + yield* Effect.addFinalizer(() => Effect.void); + return yield* Effect.fail(new BodyError()); + }).pipe(scopedSafeTeardown("test")); + + const exit = yield* Effect.exit(wrapped); + expect(Exit.isFailure(exit)).toBe(true); + if (Exit.isFailure(exit)) { + // Body's typed failure should surface, not a defect. + const squashed = Cause.squash(exit.cause); + expect(squashed).toBeInstanceOf(BodyError); + } + }), + ); + + it.effect("prefers the body's typed failure over a teardown defect", () => + // Even when both the body fails AND teardown defects, the body's typed + // failure is what callers see. This matters because `Effect.result` / + // `.pipe(Effect.exit)` in callers expects a typed Failure, not a Die. + Effect.gen(function* () { + class BodyError { + readonly _tag = "BodyError" as const; + } + const wrapped = Effect.gen(function* () { + yield* Effect.addFinalizer(() => + Effect.die(new Error("simulated subprocess kill failure")), + ); + return yield* Effect.fail(new BodyError()); + }).pipe(scopedSafeTeardown("test")); + + const exit = yield* Effect.exit(wrapped); + expect(Exit.isFailure(exit)).toBe(true); + if (Exit.isFailure(exit)) { + const squashed = Cause.squash(exit.cause); + expect(squashed).toBeInstanceOf(BodyError); + } + }), + ); +}); diff --git a/apps/server/src/provider/Layers/scopedSafeTeardown.ts b/apps/server/src/provider/Layers/scopedSafeTeardown.ts new file mode 100644 index 0000000000..688374590e --- /dev/null +++ b/apps/server/src/provider/Layers/scopedSafeTeardown.ts @@ -0,0 +1,61 @@ +/** + * scopedSafeTeardown — run a scope-requiring effect so that finalizer + * failures during scope close cannot override the body's Exit. + * + * Motivation + * ---------- + * The obvious pattern is `body.pipe(Effect.scoped)`: provide a fresh + * Scope, run the body, close the scope with the body's Exit. If a + * finalizer (e.g. `ChildProcess.kill` from an effect-codex-app-server + * spawn) dies during that close, the combined Exit becomes the + * finalizer's defect — even when the body already succeeded. + * + * Concretely this bit us in the Codex provider probe: a successful + * `initialize` → `account/read` → `skills/list` → `model/list` + * round-trip produced a `CodexAppServerProviderSnapshot`, but the + * `Layer.build(CodexClient.layerCommand(...))` finalizer then failed to + * kill the `codex app-server` subprocess with a `PlatformError`. The + * defect bubbled past `Effect.result` in `checkCodexProviderStatus`, + * died `refreshOneSource`, and `providersRef` never saw the snapshot. + * + * Strategy + * -------- + * 1. Make a fresh scope manually. + * 2. Run the body against that scope, capturing its Exit via + * `Effect.exit`. + * 3. Close the scope, catching any cause (typed failure *or* defect) + * with a log. + * 4. Replay the captured Exit so typed body failures still surface and + * successes still return their value. + * + * The helper deliberately logs teardown causes at `Warning` level — + * silently swallowing them is dangerous because they usually indicate a + * real bug in a downstream Layer's finalizer. + * + * @module provider/Layers/scopedSafeTeardown + */ +import { Effect, Exit, Scope } from "effect"; + +/** + * Run `effect` with a freshly made `Scope.Scope`, guaranteeing that + * teardown failures cannot override the body's Exit. + * + * Shape matches `Effect.scoped`: takes an effect whose env includes + * `Scope.Scope`, returns one whose env excludes it. + * + * @param label Short label for the warning log emitted when teardown + * fails. Use something like `"codex-probe"`. + */ +export const scopedSafeTeardown = + (label: string) => + (effect: Effect.Effect): Effect.Effect> => + Effect.gen(function* () { + const scope = yield* Scope.make(); + const bodyExit = yield* effect.pipe(Effect.provideService(Scope.Scope, scope), Effect.exit); + yield* Scope.close(scope, Exit.void).pipe( + Effect.catchCause((cause) => + Effect.logWarning(`${label} teardown errored; preserving body result`, cause), + ), + ); + return yield* bodyExit; + }) as Effect.Effect>; diff --git a/apps/server/src/provider/ProviderDriver.ts b/apps/server/src/provider/ProviderDriver.ts new file mode 100644 index 0000000000..bedfd61194 --- /dev/null +++ b/apps/server/src/provider/ProviderDriver.ts @@ -0,0 +1,167 @@ +/** + * ProviderDriver / ProviderInstance — driver SPI as plain values. + * + * `ProviderDriver` is a record, not a Context.Service. The thing it produces + * (`ProviderInstance`) is also a record — three captured closures + * (`snapshot`, `adapter`, `textGeneration`), an id, and a driver kind. There + * are intentionally no per-driver Context tags because tags are + * singleton-per-runtime and we need many instances of the same driver. + * + * The only Effect service involved is `ProviderInstanceRegistry`, which + * owns the live `Map` and is itself a + * singleton. + * + * Driver factories are functions of `(typed config, env)` where: + * - `typed config` is decoded once by the registry via `configSchema`, + * so drivers never deal with raw `unknown`. + * - `env` flows through Effect's R channel. Each driver declares the + * subset of infrastructure services it needs (FileSystem, + * ChildProcessSpawner, …) on its `create` return type; the registry + * layer's R is the union of those, and the runtime layer satisfies it. + * + * @module provider/ProviderDriver + */ +import type { + ProviderDriverKind, + ProviderInstanceEnvironment, + ProviderInstanceId, +} from "@t3tools/contracts"; +import type { Effect, Schema, Scope } from "effect"; + +import type { TextGenerationShape } from "../git/Services/TextGeneration.ts"; +import type { ProviderAdapterError, ProviderDriverError } from "./Errors.ts"; +import type { ProviderAdapterShape } from "./Services/ProviderAdapter.ts"; +import type { ServerProviderShape } from "./Services/ServerProvider.ts"; + +/** + * Static metadata advertised by a driver. Used for default presentation + * and (later) settings UI. Doesn't need to be Effect-typed because nothing + * about it is dynamic — drivers are registered at startup. + */ +export interface ProviderDriverMetadata { + /** Human-readable name for the driver itself (e.g. "Codex"). */ + readonly displayName: string; + /** + * Whether the driver may be instantiated more than once concurrently. + * Defaults to `true`. Set to `false` for drivers that wrap a global + * resource (e.g. a single desktop app socket) — the registry then + * rejects multi-instance configurations with a clear error. + */ + readonly supportsMultipleInstances?: boolean; +} + +/** + * One materialized provider instance. Held by the registry, looked up by + * `instanceId`, torn down by closing the scope it was created in. + * + * The three "shape" fields are captured closures owned by this instance — + * stopping one instance cannot affect another, and starting a second + * instance of the same driver does not reach into the first instance's + * state. + */ +export interface ProviderInstance { + readonly instanceId: ProviderInstanceId; + readonly driverKind: ProviderDriverKind; + readonly continuationIdentity: ProviderContinuationIdentity; + readonly displayName: string | undefined; + readonly accentColor?: string | undefined; + readonly enabled: boolean; + readonly snapshot: ServerProviderShape; + readonly adapter: ProviderAdapterShape; + readonly textGeneration: TextGenerationShape; +} + +export interface ProviderContinuationIdentity { + readonly driverKind: ProviderDriverKind; + readonly continuationKey: string; +} + +export function defaultProviderContinuationIdentity(input: { + readonly driverKind: ProviderDriverKind; + readonly instanceId: ProviderInstanceId; +}): ProviderContinuationIdentity { + return { + driverKind: input.driverKind, + continuationKey: `${input.driverKind}:instance:${input.instanceId}`, + }; +} + +/** + * Inputs the registry passes to a driver's `create` function. + * + * `config` is the typed payload — already decoded by the registry through + * `driver.configSchema`. Drivers never decode their own raw envelope. + */ +export interface ProviderDriverCreateInput { + readonly instanceId: ProviderInstanceId; + readonly displayName: string | undefined; + readonly accentColor?: string | undefined; + readonly environment: ProviderInstanceEnvironment; + readonly enabled: boolean; + readonly config: Config; +} + +/** + * Driver SPI — registered as a plain value, not a Layer. + * + * `Config` is whatever the driver decoded from + * `ProviderInstanceConfig.config`. `R` is the union of infrastructure + * services the driver depends on; the registry layer aggregates `R` across + * all registered drivers and the runtime supplies them. + * + * `create` is responsible for *all* per-instance state — process handles, + * pubsub topics, refs, file watchers — and must release them when its + * scope closes. Two calls to `create` with different `instanceId` / + * `config` MUST yield instances with no shared mutable state. + */ +export interface ProviderDriver { + readonly driverKind: ProviderDriverKind; + readonly metadata: ProviderDriverMetadata; + /** + * Decoder for the opaque `ProviderInstanceConfig.config` envelope. The + * registry runs this exactly once per (re)load of an instance; a decode + * failure is surfaced as `ProviderDriverError` and downgraded to an + * unavailable shadow snapshot. + * + * The `Encoded` parameter is intentionally left as `unknown` (not + * `Config`) so schemas with `withDecodingDefault` / transformations — where + * the encoded shape differs from the decoded shape — satisfy the SPI + * without casts. The registry only ever decodes `unknown` envelopes here, + * so the precise encoded type is irrelevant at this boundary. + * + * Using `Codec` rather than `Schema` pins `DecodingServices = never` — if + * we used `Schema`, the erased `any` in `AnyProviderDriver` would + * widen `DecodingServices` to `unknown` and poison the R channel of every + * caller of `decodeUnknownEffect`. + */ + readonly configSchema: Schema.Codec; + /** + * Default config payload used when the legacy + * `ServerSettings.providers.` entry is empty or when the driver + * is auto-bootstrapped without user configuration. Returning a typed + * default keeps the migration path simple — no special-casing needed + * to construct a "blank" instance. + */ + readonly defaultConfig: () => Config; + /** + * Materialize one instance. The returned effect runs in a scope owned + * by the registry; closing that scope releases every resource the + * driver opened. Failures become unavailable shadow snapshots — the + * driver MUST NOT throw defects. + */ + readonly create: ( + input: ProviderDriverCreateInput, + ) => Effect.Effect; +} + +/** + * Heterogeneous-array convenience: the registry stores drivers as + * `ReadonlyArray>` where `R` is the union of all + * registered drivers' env requirements. + */ +// `any` here intentionally erases the per-driver Config; the registry +// already decoded it before invoking `create`, so downstream code never +// needs the original `Config` type. Using `unknown` instead would force +// `create` callers into casts since `unknown` is not assignable to a +// concrete `Config` from inside the driver body. +export type AnyProviderDriver = ProviderDriver; diff --git a/apps/server/src/provider/ProviderInstanceEnvironment.test.ts b/apps/server/src/provider/ProviderInstanceEnvironment.test.ts new file mode 100644 index 0000000000..f37b328b15 --- /dev/null +++ b/apps/server/src/provider/ProviderInstanceEnvironment.test.ts @@ -0,0 +1,21 @@ +import { describe, expect, it } from "vitest"; + +import { mergeProviderInstanceEnvironment } from "./ProviderInstanceEnvironment.ts"; + +describe("mergeProviderInstanceEnvironment", () => { + it("overrides inherited environment values and preserves empty strings", () => { + expect( + mergeProviderInstanceEnvironment( + [ + { name: "OPENROUTER_API_KEY", value: "sk-or-test", sensitive: true }, + { name: "ANTHROPIC_API_KEY", value: "", sensitive: false }, + ], + { ANTHROPIC_API_KEY: "inherited", PATH: "/bin" }, + ), + ).toMatchObject({ + OPENROUTER_API_KEY: "sk-or-test", + ANTHROPIC_API_KEY: "", + PATH: "/bin", + }); + }); +}); diff --git a/apps/server/src/provider/ProviderInstanceEnvironment.ts b/apps/server/src/provider/ProviderInstanceEnvironment.ts new file mode 100644 index 0000000000..e469253604 --- /dev/null +++ b/apps/server/src/provider/ProviderInstanceEnvironment.ts @@ -0,0 +1,16 @@ +import type { ProviderInstanceEnvironment } from "@t3tools/contracts"; + +export function mergeProviderInstanceEnvironment( + environment: ProviderInstanceEnvironment | undefined, + baseEnv: NodeJS.ProcessEnv = process.env, +): NodeJS.ProcessEnv { + if (!environment || environment.length === 0) { + return baseEnv; + } + + const next: NodeJS.ProcessEnv = { ...baseEnv }; + for (const variable of environment) { + next[variable.name] = variable.value; + } + return next; +} diff --git a/apps/server/src/provider/Services/ClaudeAdapter.ts b/apps/server/src/provider/Services/ClaudeAdapter.ts index e8c33bd8e4..ed9bd7081b 100644 --- a/apps/server/src/provider/Services/ClaudeAdapter.ts +++ b/apps/server/src/provider/Services/ClaudeAdapter.ts @@ -1,30 +1,19 @@ /** - * ClaudeAdapter - Claude Agent implementation of the generic provider adapter contract. + * ClaudeAdapter — shape type for the Claude provider adapter. * - * This service owns Claude runtime/session semantics and emits canonical - * provider runtime events. It does not perform cross-provider routing, shared - * event fan-out, or checkpoint orchestration. - * - * Uses Effect `Context.Service` for dependency injection and returns the - * shared provider-adapter error channel with `provider: "claudeAgent"` context. + * Historically this module exposed a `Context.Service` tag so consumers + * could inject the adapter through the Effect layer graph. The driver + * model ({@link ../Drivers/ClaudeDriver}) bundles one adapter per + * instance as a captured closure instead, so the tag is gone — we only + * retain the shape interface as a naming anchor for the driver bundle. * * @module ClaudeAdapter */ -import { Context } from "effect"; - import type { ProviderAdapterError } from "../Errors.ts"; import type { ProviderAdapterShape } from "./ProviderAdapter.ts"; /** - * ClaudeAdapterShape - Service API for the Claude Agent provider adapter. + * ClaudeAdapterShape — per-instance Claude adapter contract. Carries + * a branded driver kind as the nominal discriminant. */ -export interface ClaudeAdapterShape extends ProviderAdapterShape { - readonly provider: "claudeAgent"; -} - -/** - * ClaudeAdapter - Service tag for Claude Agent provider adapter operations. - */ -export class ClaudeAdapter extends Context.Service()( - "t3/provider/Services/ClaudeAdapter", -) {} +export interface ClaudeAdapterShape extends ProviderAdapterShape {} diff --git a/apps/server/src/provider/Services/ClaudeProvider.ts b/apps/server/src/provider/Services/ClaudeProvider.ts deleted file mode 100644 index 7e21ac56d9..0000000000 --- a/apps/server/src/provider/Services/ClaudeProvider.ts +++ /dev/null @@ -1,9 +0,0 @@ -import { Context } from "effect"; - -import type { ServerProviderShape } from "./ServerProvider.ts"; - -export interface ClaudeProviderShape extends ServerProviderShape {} - -export class ClaudeProvider extends Context.Service()( - "t3/provider/Services/ClaudeProvider", -) {} diff --git a/apps/server/src/provider/Services/CodexAdapter.ts b/apps/server/src/provider/Services/CodexAdapter.ts index e7a5508c9c..33fe0fa12b 100644 --- a/apps/server/src/provider/Services/CodexAdapter.ts +++ b/apps/server/src/provider/Services/CodexAdapter.ts @@ -1,30 +1,19 @@ /** - * CodexAdapter - Codex implementation of the generic provider adapter contract. + * CodexAdapter — shape type for the Codex provider adapter. * - * This service owns Codex app-server process / JSON-RPC semantics and emits - * Codex provider events. It does not perform cross-provider routing, shared - * event fan-out, or checkpoint orchestration. - * - * Uses Effect `Context.Service` for dependency injection and returns the - * shared provider-adapter error channel with `provider: "codex"` context. + * Historically this module exposed a `Context.Service` tag so consumers + * could inject the adapter through the Effect layer graph. The driver + * model ({@link ../Drivers/CodexDriver}) bundles one adapter per + * instance as a captured closure instead, so the tag is gone — we only + * retain the shape interface as a naming anchor for the driver bundle. * * @module CodexAdapter */ -import { Context } from "effect"; - import type { ProviderAdapterError } from "../Errors.ts"; import type { ProviderAdapterShape } from "./ProviderAdapter.ts"; /** - * CodexAdapterShape - Service API for the Codex provider adapter. + * CodexAdapterShape — per-instance Codex adapter contract. Carries + * a branded driver kind as the nominal discriminant. */ -export interface CodexAdapterShape extends ProviderAdapterShape { - readonly provider: "codex"; -} - -/** - * CodexAdapter - Service tag for Codex provider adapter operations. - */ -export class CodexAdapter extends Context.Service()( - "t3/provider/Services/CodexAdapter", -) {} +export interface CodexAdapterShape extends ProviderAdapterShape {} diff --git a/apps/server/src/provider/Services/CodexProvider.ts b/apps/server/src/provider/Services/CodexProvider.ts deleted file mode 100644 index e116f1a761..0000000000 --- a/apps/server/src/provider/Services/CodexProvider.ts +++ /dev/null @@ -1,9 +0,0 @@ -import { Context } from "effect"; - -import type { ServerProviderShape } from "./ServerProvider.ts"; - -export interface CodexProviderShape extends ServerProviderShape {} - -export class CodexProvider extends Context.Service()( - "t3/provider/Services/CodexProvider", -) {} diff --git a/apps/server/src/provider/Services/CursorAdapter.ts b/apps/server/src/provider/Services/CursorAdapter.ts index f1edb31619..83581f0a45 100644 --- a/apps/server/src/provider/Services/CursorAdapter.ts +++ b/apps/server/src/provider/Services/CursorAdapter.ts @@ -1,12 +1,19 @@ -import { Context } from "effect"; - +/** + * CursorAdapter — shape type for the Cursor provider adapter. + * + * Historically this module exposed a `Context.Service` tag so consumers + * could inject the adapter through the Effect layer graph. The driver + * model ({@link ../Drivers/CursorDriver}) bundles one adapter per + * instance as a captured closure instead, so the tag is gone — we only + * retain the shape interface as a naming anchor for the driver bundle. + * + * @module CursorAdapter + */ import type { ProviderAdapterError } from "../Errors.ts"; import type { ProviderAdapterShape } from "./ProviderAdapter.ts"; -export interface CursorAdapterShape extends ProviderAdapterShape { - readonly provider: "cursor"; -} - -export class CursorAdapter extends Context.Service()( - "t3/provider/Services/CursorAdapter", -) {} +/** + * CursorAdapterShape — per-instance Cursor adapter contract. Carries + * a branded driver kind as the nominal discriminant. + */ +export interface CursorAdapterShape extends ProviderAdapterShape {} diff --git a/apps/server/src/provider/Services/CursorProvider.ts b/apps/server/src/provider/Services/CursorProvider.ts deleted file mode 100644 index aa70994f5e..0000000000 --- a/apps/server/src/provider/Services/CursorProvider.ts +++ /dev/null @@ -1,9 +0,0 @@ -import { Context } from "effect"; - -import type { ServerProviderShape } from "./ServerProvider.ts"; - -export interface CursorProviderShape extends ServerProviderShape {} - -export class CursorProvider extends Context.Service()( - "t3/provider/Services/CursorProvider", -) {} diff --git a/apps/server/src/provider/Services/OpenCodeAdapter.ts b/apps/server/src/provider/Services/OpenCodeAdapter.ts index ad5660022b..e3ad97904d 100644 --- a/apps/server/src/provider/Services/OpenCodeAdapter.ts +++ b/apps/server/src/provider/Services/OpenCodeAdapter.ts @@ -1,12 +1,19 @@ -import { Context } from "effect"; - +/** + * OpenCodeAdapter — shape type for the OpenCode provider adapter. + * + * Historically this module exposed a `Context.Service` tag so consumers + * could inject the adapter through the Effect layer graph. The driver + * model ({@link ../Drivers/OpenCodeDriver}) bundles one adapter per + * instance as a captured closure instead, so the tag is gone — we only + * retain the shape interface as a naming anchor for the driver bundle. + * + * @module OpenCodeAdapter + */ import type { ProviderAdapterError } from "../Errors.ts"; import type { ProviderAdapterShape } from "./ProviderAdapter.ts"; -export interface OpenCodeAdapterShape extends ProviderAdapterShape { - readonly provider: "opencode"; -} - -export class OpenCodeAdapter extends Context.Service()( - "t3/provider/Services/OpenCodeAdapter", -) {} +/** + * OpenCodeAdapterShape — per-instance OpenCode adapter contract. Carries + * a branded driver kind as the nominal discriminant. + */ +export interface OpenCodeAdapterShape extends ProviderAdapterShape {} diff --git a/apps/server/src/provider/Services/OpenCodeProvider.ts b/apps/server/src/provider/Services/OpenCodeProvider.ts deleted file mode 100644 index a799830eec..0000000000 --- a/apps/server/src/provider/Services/OpenCodeProvider.ts +++ /dev/null @@ -1,9 +0,0 @@ -import { Context } from "effect"; - -import type { ServerProviderShape } from "./ServerProvider.ts"; - -export interface OpenCodeProviderShape extends ServerProviderShape {} - -export class OpenCodeProvider extends Context.Service()( - "t3/provider/Services/OpenCodeProvider", -) {} diff --git a/apps/server/src/provider/Services/ProviderAdapter.ts b/apps/server/src/provider/Services/ProviderAdapter.ts index 91155764f1..dd1be73872 100644 --- a/apps/server/src/provider/Services/ProviderAdapter.ts +++ b/apps/server/src/provider/Services/ProviderAdapter.ts @@ -10,7 +10,7 @@ import type { ApprovalRequestId, ProviderApprovalDecision, - ProviderKind, + ProviderDriverKind, ProviderUserInputAnswers, ProviderRuntimeEvent, ProviderSendTurnInput, @@ -46,7 +46,7 @@ export interface ProviderAdapterShape { /** * Provider kind implemented by this adapter. */ - readonly provider: ProviderKind; + readonly provider: ProviderDriverKind; readonly capabilities: ProviderAdapterCapabilities; /** diff --git a/apps/server/src/provider/Services/ProviderAdapterRegistry.ts b/apps/server/src/provider/Services/ProviderAdapterRegistry.ts index b8e9d4b21c..1161487d5a 100644 --- a/apps/server/src/provider/Services/ProviderAdapterRegistry.ts +++ b/apps/server/src/provider/Services/ProviderAdapterRegistry.ts @@ -1,34 +1,91 @@ /** * ProviderAdapterRegistry - Lookup boundary for provider adapter implementations. * - * Maps a provider kind to the concrete adapter service (Codex, Claude, etc). - * It does not own session lifecycle or routing rules; `ProviderService` uses - * this registry together with `ProviderSessionDirectory`. + * Maps a `ProviderInstanceId` (the new per-instance routing key) or a + * `ProviderDriverKind` (legacy single-instance-per-driver key) to the concrete + * adapter service (Codex, Claude, etc). It does not own session lifecycle + * or routing rules; `ProviderService` uses this registry together with + * `ProviderSessionDirectory`. + * + * During the driver/instance migration this tag exposes both flavours: + * + * - `getByInstance` / `listInstances` — new per-instance routing. Callers + * that already know an `instanceId` (threads, sessions, events) + * should prefer these. + * (`defaultInstanceIdForDriver(kind) === kind`), matching the pre-Slice-D + * behaviour. New code should not grow additional callers of the kind-keyed + * methods; they exist so the settings UI, WS refresh RPC, and a handful + * of legacy persisted rows can still be routed during the rollout. * * @module ProviderAdapterRegistry */ -import type { ProviderKind } from "@t3tools/contracts"; +import type { ProviderDriverKind, ProviderInstanceId } from "@t3tools/contracts"; import { Context } from "effect"; -import type { Effect } from "effect"; +import type { Effect, PubSub, Scope, Stream } from "effect"; import type { ProviderAdapterError, ProviderUnsupportedError } from "../Errors.ts"; import type { ProviderAdapterShape } from "./ProviderAdapter.ts"; +import type { ProviderContinuationIdentity } from "../ProviderDriver.ts"; + +export interface ProviderInstanceRoutingInfo { + readonly instanceId: ProviderInstanceId; + readonly driverKind: ProviderDriverKind; + readonly displayName: string | undefined; + readonly accentColor?: string | undefined; + readonly enabled: boolean; + readonly continuationIdentity: ProviderContinuationIdentity; +} /** - * ProviderAdapterRegistryShape - Service API for adapter lookup by provider kind. + * ProviderAdapterRegistryShape - Service API for adapter lookup. */ export interface ProviderAdapterRegistryShape { /** - * Resolve the adapter for a provider kind. + * Resolve the adapter for a specific instance id. Returns + * `ProviderUnsupportedError` if no such instance is currently registered + * (which covers "never configured" *and* "configured but the driver is + * unavailable in this build" — both surface the same failure to callers + * that expect a working adapter). */ - readonly getByProvider: ( - provider: ProviderKind, + readonly getByInstance: ( + instanceId: ProviderInstanceId, ) => Effect.Effect, ProviderUnsupportedError>; + readonly getInstanceInfo: ( + instanceId: ProviderInstanceId, + ) => Effect.Effect; + /** - * List provider kinds currently registered. + * List all live instance ids. Excludes unavailable/shadow instances — + * callers of this method want something they can pass to `getByInstance`. */ - readonly listProviders: () => Effect.Effect>; + readonly listInstances: () => Effect.Effect>; + + /** + * Legacy: list provider kinds whose default instance is currently + * registered. + * + * @deprecated Prefer `listInstances`. Retained for migration-era call + * sites that iterate providers to build UI/metrics. + */ + readonly listProviders: () => Effect.Effect>; + + /** + * Change notification stream mirroring `ProviderInstanceRegistry.streamChanges`. + * Emits one `void` tick whenever the set of live instances changes + * (instance added, removed, or rebuilt after a settings edit). Consumers + * that fan out `adapter.streamEvents` per instance — e.g. `ProviderService`'s + * runtime event bus — re-pull `listInstances` on each tick and fork new + * subscriptions for instances they haven't seen yet. + */ + readonly streamChanges: Stream.Stream; + + /** + * Acquire a change subscription synchronously in the caller's current fiber. + * Consumers that must avoid missing a publish between initial reconciliation + * and watcher startup should use this, then fork `Stream.fromSubscription`. + */ + readonly subscribeChanges: Effect.Effect, never, Scope.Scope>; } /** @@ -38,5 +95,3 @@ export class ProviderAdapterRegistry extends Context.Service< ProviderAdapterRegistry, ProviderAdapterRegistryShape >()("t3/provider/Services/ProviderAdapterRegistry") {} - -// Dummy comment for workflow testing. diff --git a/apps/server/src/provider/Services/ProviderInstanceRegistry.ts b/apps/server/src/provider/Services/ProviderInstanceRegistry.ts new file mode 100644 index 0000000000..f642475a24 --- /dev/null +++ b/apps/server/src/provider/Services/ProviderInstanceRegistry.ts @@ -0,0 +1,84 @@ +/** + * ProviderInstanceRegistry — the single Effect service in the new model. + * + * Owns a `Map` produced by running + * registered driver factories against `ServerSettings.providerInstances`. + * The registry watches settings; when an instance's config changes (or + * the entry disappears), the registry tears down the affected instance's + * scope and rebuilds — that's the entire hot-reload story. + * + * What rest-of-server reads from here: + * - `getInstance(instanceId)` — for routing turn/session calls. + * - `listInstances` — for snapshot aggregation in `ProviderRegistry`. + * - `listUnavailable` — `ServerProvider` shadows for instances whose + * driver is not registered in this build (rollback / fork tolerance). + * - `streamChanges` — coalesced "registry mutated" pings so consumers + * can re-pull lists or re-broadcast. + * + * @module provider/Services/ProviderInstanceRegistry + */ +import type { ProviderInstanceId, ServerProvider } from "@t3tools/contracts"; +import { Context } from "effect"; +import type { Effect, PubSub, Scope, Stream } from "effect"; + +import type { ProviderInstance } from "../ProviderDriver.ts"; + +export interface ProviderInstanceRegistryShape { + /** + * Look up one instance by id. Returns `undefined` (not Option) when the + * id is unknown — callers branch on falsy and emit + * `ProviderInstanceNotFoundError`. + */ + readonly getInstance: ( + instanceId: ProviderInstanceId, + ) => Effect.Effect; + /** + * Every available (driver-registered, successfully created) instance, + * in stable settings-author order. + */ + readonly listInstances: Effect.Effect>; + /** + * Wire-shape shadow snapshots for instances whose driver is unknown to + * this build (or whose config failed to decode). Suitable for merging + * directly into `ProviderRegistry` output. + */ + readonly listUnavailable: Effect.Effect>; + /** + * Push notification stream emitted whenever the registry's contents + * change — instance added, removed, or rebuilt. The payload is `void` + * because consumers always want to re-pull `listInstances` / + * `listUnavailable` together. + * + * NOTE: because `Stream.fromPubSub` defers `PubSub.subscribe` until the + * stream starts running, forking a consumer via + * `Stream.runForEach(...).pipe(Effect.forkScoped)` races the next + * publish — the forked fiber may not have subscribed yet when the + * publish lands. Hot-reload consumers that must not miss a publish + * should use `subscribeChanges` below instead, which acquires the + * subscription synchronously in the caller's fiber before the consumer + * loop is forked. + */ + readonly streamChanges: Stream.Stream; + /** + * Acquire a subscription to the registry's change channel synchronously + * in the caller's fiber. Returns a `PubSub.Subscription` whose + * lifetime is scoped to the provided `Scope` (the subscription is + * released when the scope closes). Consumers typically `yield*` this + * in the same fiber that forks their consumer loop, then drain with + * `PubSub.take(subscription)` inside `Effect.forever`. Because the + * subscription is registered with the PubSub before this `yield*` + * returns, no subsequent publish can land in a gap. + * + * This exists because the `ProviderInstanceRegistry` publishes on a + * PubSub and `Stream.fromPubSub` defers subscription until the stream + * starts executing — a consumer that `forkScoped`s the stream + * consumption can miss a publish that lands in the narrow window + * between "fiber scheduled" and "fiber starts running". + */ + readonly subscribeChanges: Effect.Effect, never, Scope.Scope>; +} + +export class ProviderInstanceRegistry extends Context.Service< + ProviderInstanceRegistry, + ProviderInstanceRegistryShape +>()("t3/provider/Services/ProviderInstanceRegistry") {} diff --git a/apps/server/src/provider/Services/ProviderInstanceRegistryMutator.ts b/apps/server/src/provider/Services/ProviderInstanceRegistryMutator.ts new file mode 100644 index 0000000000..ff861f961c --- /dev/null +++ b/apps/server/src/provider/Services/ProviderInstanceRegistryMutator.ts @@ -0,0 +1,52 @@ +/** + * ProviderInstanceRegistryMutator — internal handle used by the hydration + * layer to reconcile the live registry with a fresh + * `ProviderInstanceConfigMap`. + * + * Kept separate from the public `ProviderInstanceRegistry` service tag so + * downstream consumers (drivers, reactors, `ProviderService`) can only read + * from the registry. Only the hydration layer — which watches + * `ServerSettingsService.streamChanges` and applies diffs — imports this + * tag. + * + * The mutator exposes a single entry point, `reconcile(configMap)`, which: + * + * 1. Diffs the incoming map against the live one keyed by instance id. + * 2. Closes the per-instance `Scope` of every removed or replaced entry + * (tearing down adapter processes, refresh fibres, temp files) BEFORE + * creating the replacement — `reconcile` guarantees "at most one live + * instance per id" at all times. + * 3. Opens a fresh child `Scope` for every added or replaced entry, runs + * the driver's `create`, and stores the resulting `ProviderInstance` + * plus its scope. + * 4. Publishes one `void` tick on the registry's `streamChanges` PubSub at + * the end of the batch — consumers re-pull `listInstances` / + * `listUnavailable`. + * + * `reconcile` is idempotent: calling it with an unchanged config map is a + * no-op (no scope churn, no pubsub emission). + * + * @module provider/Services/ProviderInstanceRegistryMutator + */ +import type { ProviderInstanceConfigMap } from "@t3tools/contracts"; +import { Context } from "effect"; +import type { Effect } from "effect"; + +export interface ProviderInstanceRegistryMutatorShape { + /** + * Bring the live registry in line with the supplied config map. See + * module docs for the add / remove / replace semantics. + * + * The effect never fails: individual driver `create` failures are + * captured as "unavailable" shadow snapshots inside the registry, the + * same way boot-time failures are handled by + * `makeProviderInstanceRegistry`. This keeps settings-watcher loops from + * erroring out on a single bad entry. + */ + readonly reconcile: (configMap: ProviderInstanceConfigMap) => Effect.Effect; +} + +export class ProviderInstanceRegistryMutator extends Context.Service< + ProviderInstanceRegistryMutator, + ProviderInstanceRegistryMutatorShape +>()("t3/provider/Services/ProviderInstanceRegistryMutator") {} diff --git a/apps/server/src/provider/Services/ProviderRegistry.ts b/apps/server/src/provider/Services/ProviderRegistry.ts index 2e04fa253b..13a87bd873 100644 --- a/apps/server/src/provider/Services/ProviderRegistry.ts +++ b/apps/server/src/provider/Services/ProviderRegistry.ts @@ -6,23 +6,42 @@ * * @module ProviderRegistry */ -import type { ProviderKind, ServerProvider } from "@t3tools/contracts"; +import type { ProviderInstanceId, ProviderDriverKind, ServerProvider } from "@t3tools/contracts"; import { Context } from "effect"; import type { Effect, Stream } from "effect"; export interface ProviderRegistryShape { /** - * Read the latest provider snapshots. + * Read the latest provider snapshots for every configured instance. + * Multiple snapshots may share the same `provider` kind (multiple + * instances of the same driver) and disambiguate via `instanceId`. */ readonly getProviders: Effect.Effect>; /** - * Refresh all providers, or a single provider when specified. + * Refresh all providers, or the default instance of the specified + * kind when supplied. + * + * Retained for back-compat with legacy call sites (WS refresh RPC, + * orchestration metrics). New code should prefer `refreshInstance`. + * + * @deprecated prefer `refreshInstance` for new call sites. */ - readonly refresh: (provider?: ProviderKind) => Effect.Effect>; + readonly refresh: (provider?: ProviderDriverKind) => Effect.Effect>; /** - * Stream of provider snapshot updates. + * Refresh the specific configured instance. Returns the updated snapshot + * list. When the instance id is unknown the call resolves with the + * currently cached list (no error) — matching the legacy `refresh` shim + * behaviour so transport layers don't have to special-case unknowns. + */ + readonly refreshInstance: ( + instanceId: ProviderInstanceId, + ) => Effect.Effect>; + + /** + * Stream of provider snapshot updates — one emission per aggregated + * change. The array contains the full current state. */ readonly streamChanges: Stream.Stream>; } diff --git a/apps/server/src/provider/Services/ProviderService.ts b/apps/server/src/provider/Services/ProviderService.ts index 1e461fcd1c..17a64689b4 100644 --- a/apps/server/src/provider/Services/ProviderService.ts +++ b/apps/server/src/provider/Services/ProviderService.ts @@ -13,7 +13,7 @@ */ import type { ProviderInterruptTurnInput, - ProviderKind, + ProviderInstanceId, ProviderRespondToRequestInput, ProviderRespondToUserInputInput, ProviderRuntimeEvent, @@ -29,6 +29,7 @@ import type { Effect, Stream } from "effect"; import type { ProviderServiceError } from "../Errors.ts"; import type { ProviderAdapterCapabilities } from "./ProviderAdapter.ts"; +import type { ProviderInstanceRoutingInfo } from "./ProviderAdapterRegistry.ts"; /** * ProviderServiceShape - Service API for provider session and turn orchestration. @@ -85,12 +86,16 @@ export interface ProviderServiceShape { readonly listSessions: () => Effect.Effect>; /** - * Read static capabilities for a provider adapter. + * Read capabilities for the adapter bound to a configured provider instance. */ readonly getCapabilities: ( - provider: ProviderKind, + instanceId: ProviderInstanceId, ) => Effect.Effect; + readonly getInstanceInfo: ( + instanceId: ProviderInstanceId, + ) => Effect.Effect; + /** * Roll back provider conversation state by a number of turns. */ diff --git a/apps/server/src/provider/Services/ProviderSessionDirectory.ts b/apps/server/src/provider/Services/ProviderSessionDirectory.ts index bee7a1b373..99ffb800f9 100644 --- a/apps/server/src/provider/Services/ProviderSessionDirectory.ts +++ b/apps/server/src/provider/Services/ProviderSessionDirectory.ts @@ -1,5 +1,6 @@ import type { - ProviderKind, + ProviderInstanceId, + ProviderDriverKind, ProviderSessionRuntimeStatus, RuntimeMode, ThreadId, @@ -14,7 +15,13 @@ import type { export interface ProviderRuntimeBinding { readonly threadId: ThreadId; - readonly provider: ProviderKind; + readonly provider: ProviderDriverKind; + /** + * Routing key for the configured provider instance that owns this + * session. The persistence layer promotes legacy null rows before + * exposing bindings; runtime callers must not infer this from `provider`. + */ + readonly providerInstanceId?: ProviderInstanceId; readonly adapterKey?: string; readonly status?: ProviderSessionRuntimeStatus; readonly resumeCursor?: unknown | null; @@ -39,7 +46,7 @@ export interface ProviderSessionDirectoryShape { readonly getProvider: ( threadId: ThreadId, - ) => Effect.Effect; + ) => Effect.Effect; readonly getBinding: ( threadId: ThreadId, diff --git a/apps/server/src/provider/acp/AcpAdapterSupport.test.ts b/apps/server/src/provider/acp/AcpAdapterSupport.test.ts index 7457713e0a..a7fcdc4c82 100644 --- a/apps/server/src/provider/acp/AcpAdapterSupport.test.ts +++ b/apps/server/src/provider/acp/AcpAdapterSupport.test.ts @@ -1,5 +1,6 @@ import { describe, expect, it } from "vitest"; import * as EffectAcpErrors from "effect-acp/errors"; +import { ProviderDriverKind } from "@t3tools/contracts"; import { acpPermissionOutcome, mapAcpToAdapterError } from "./AcpAdapterSupport.ts"; @@ -12,7 +13,7 @@ describe("AcpAdapterSupport", () => { it("maps ACP request errors to provider adapter request errors", () => { const error = mapAcpToAdapterError( - "cursor", + ProviderDriverKind.make("cursor"), "thread-1" as never, "session/prompt", new EffectAcpErrors.AcpRequestError({ diff --git a/apps/server/src/provider/acp/AcpAdapterSupport.ts b/apps/server/src/provider/acp/AcpAdapterSupport.ts index 914bb7e8c3..499ebd2e70 100644 --- a/apps/server/src/provider/acp/AcpAdapterSupport.ts +++ b/apps/server/src/provider/acp/AcpAdapterSupport.ts @@ -1,6 +1,6 @@ import { type ProviderApprovalDecision, - type ProviderKind, + type ProviderDriverKind, type ThreadId, } from "@t3tools/contracts"; import { Schema } from "effect"; @@ -13,7 +13,7 @@ import { } from "../Errors.ts"; export function mapAcpToAdapterError( - provider: ProviderKind, + provider: ProviderDriverKind, threadId: ThreadId, method: string, error: EffectAcpErrors.AcpError, diff --git a/apps/server/src/provider/acp/AcpCoreRuntimeEvents.test.ts b/apps/server/src/provider/acp/AcpCoreRuntimeEvents.test.ts index 79b51f585b..713d066892 100644 --- a/apps/server/src/provider/acp/AcpCoreRuntimeEvents.test.ts +++ b/apps/server/src/provider/acp/AcpCoreRuntimeEvents.test.ts @@ -1,4 +1,4 @@ -import { RuntimeRequestId, TurnId } from "@t3tools/contracts"; +import { ProviderDriverKind, RuntimeRequestId, TurnId } from "@t3tools/contracts"; import { describe, expect, it } from "vitest"; import { @@ -30,7 +30,7 @@ describe("AcpCoreRuntimeEvents", () => { expect( makeAcpRequestOpenedEvent({ stamp, - provider: "cursor", + provider: ProviderDriverKind.make("cursor"), threadId: "thread-1" as never, turnId, requestId: RuntimeRequestId.make("request-1"), @@ -52,7 +52,7 @@ describe("AcpCoreRuntimeEvents", () => { expect( makeAcpRequestResolvedEvent({ stamp, - provider: "cursor", + provider: ProviderDriverKind.make("cursor"), threadId: "thread-1" as never, turnId, requestId: RuntimeRequestId.make("request-1"), @@ -75,7 +75,7 @@ describe("AcpCoreRuntimeEvents", () => { expect( makeAcpPlanUpdatedEvent({ stamp, - provider: "cursor", + provider: ProviderDriverKind.make("cursor"), threadId: "thread-1" as never, turnId, payload: { @@ -95,7 +95,7 @@ describe("AcpCoreRuntimeEvents", () => { expect( makeAcpToolCallEvent({ stamp, - provider: "cursor", + provider: ProviderDriverKind.make("cursor"), threadId: "thread-1" as never, turnId, toolCall: { @@ -119,7 +119,7 @@ describe("AcpCoreRuntimeEvents", () => { expect( makeAcpContentDeltaEvent({ stamp, - provider: "cursor", + provider: ProviderDriverKind.make("cursor"), threadId: "thread-1" as never, turnId, itemId: "assistant:session-1:segment:0", @@ -137,7 +137,7 @@ describe("AcpCoreRuntimeEvents", () => { expect( makeAcpAssistantItemEvent({ stamp, - provider: "cursor", + provider: ProviderDriverKind.make("cursor"), threadId: "thread-1" as never, turnId, itemId: "assistant:session-1:segment:0", diff --git a/apps/server/src/provider/acp/AcpCoreRuntimeEvents.ts b/apps/server/src/provider/acp/AcpCoreRuntimeEvents.ts index 0c0f06cc62..c93e61dc37 100644 --- a/apps/server/src/provider/acp/AcpCoreRuntimeEvents.ts +++ b/apps/server/src/provider/acp/AcpCoreRuntimeEvents.ts @@ -4,7 +4,7 @@ import { type CanonicalRequestType, type EventId, type ProviderApprovalDecision, - type ProviderKind, + type ProviderDriverKind, type ProviderRuntimeEvent, type RuntimeRequestId, type ThreadId, @@ -78,7 +78,7 @@ function runtimeItemStatusFromAcpToolStatus( export function makeAcpRequestOpenedEvent(input: { readonly stamp: AcpEventStamp; - readonly provider: ProviderKind; + readonly provider: ProviderDriverKind; readonly threadId: ThreadId; readonly turnId: TurnId | undefined; readonly requestId: RuntimeRequestId; @@ -111,7 +111,7 @@ export function makeAcpRequestOpenedEvent(input: { export function makeAcpRequestResolvedEvent(input: { readonly stamp: AcpEventStamp; - readonly provider: ProviderKind; + readonly provider: ProviderDriverKind; readonly threadId: ThreadId; readonly turnId: TurnId | undefined; readonly requestId: RuntimeRequestId; @@ -134,7 +134,7 @@ export function makeAcpRequestResolvedEvent(input: { export function makeAcpPlanUpdatedEvent(input: { readonly stamp: AcpEventStamp; - readonly provider: ProviderKind; + readonly provider: ProviderDriverKind; readonly threadId: ThreadId; readonly turnId: TurnId | undefined; readonly payload: AcpPlanUpdate; @@ -159,7 +159,7 @@ export function makeAcpPlanUpdatedEvent(input: { export function makeAcpToolCallEvent(input: { readonly stamp: AcpEventStamp; - readonly provider: ProviderKind; + readonly provider: ProviderDriverKind; readonly threadId: ThreadId; readonly turnId: TurnId | undefined; readonly toolCall: AcpToolCallState; @@ -193,7 +193,7 @@ export function makeAcpToolCallEvent(input: { export function makeAcpAssistantItemEvent(input: { readonly stamp: AcpEventStamp; - readonly provider: ProviderKind; + readonly provider: ProviderDriverKind; readonly threadId: ThreadId; readonly turnId: TurnId | undefined; readonly itemId: string; @@ -215,7 +215,7 @@ export function makeAcpAssistantItemEvent(input: { export function makeAcpContentDeltaEvent(input: { readonly stamp: AcpEventStamp; - readonly provider: ProviderKind; + readonly provider: ProviderDriverKind; readonly threadId: ThreadId; readonly turnId: TurnId | undefined; readonly itemId?: string; diff --git a/apps/server/src/provider/acp/AcpNativeLogging.ts b/apps/server/src/provider/acp/AcpNativeLogging.ts index 2fb3f4e833..3d44aac0a4 100644 --- a/apps/server/src/provider/acp/AcpNativeLogging.ts +++ b/apps/server/src/provider/acp/AcpNativeLogging.ts @@ -1,4 +1,4 @@ -import type { ProviderKind, ThreadId } from "@t3tools/contracts"; +import type { ProviderDriverKind, ThreadId } from "@t3tools/contracts"; import { Cause, Effect } from "effect"; import type * as EffectAcpProtocol from "effect-acp/protocol"; @@ -7,7 +7,7 @@ import type { AcpSessionRequestLogEvent, AcpSessionRuntimeOptions } from "./AcpS function writeNativeAcpLog(input: { readonly nativeEventLogger: EventNdjsonLogger | undefined; - readonly provider: ProviderKind; + readonly provider: ProviderDriverKind; readonly threadId: ThreadId; readonly kind: "request" | "protocol"; readonly payload: unknown; @@ -44,7 +44,7 @@ function formatRequestLogPayload(event: AcpSessionRequestLogEvent) { export function makeAcpNativeLoggers(input: { readonly nativeEventLogger: EventNdjsonLogger | undefined; - readonly provider: ProviderKind; + readonly provider: ProviderDriverKind; readonly threadId: ThreadId; }): Pick { return { diff --git a/apps/server/src/provider/acp/AcpSessionRuntime.ts b/apps/server/src/provider/acp/AcpSessionRuntime.ts index d32e70cb4c..b4cf665608 100644 --- a/apps/server/src/provider/acp/AcpSessionRuntime.ts +++ b/apps/server/src/provider/acp/AcpSessionRuntime.ts @@ -21,7 +21,7 @@ export interface AcpSpawnInput { readonly command: string; readonly args: ReadonlyArray; readonly cwd?: string; - readonly env?: Readonly>; + readonly env?: NodeJS.ProcessEnv; } export interface AcpSessionRuntimeOptions { diff --git a/apps/server/src/provider/acp/CursorAcpSupport.ts b/apps/server/src/provider/acp/CursorAcpSupport.ts index 25e342f0d0..3e405dd7ff 100644 --- a/apps/server/src/provider/acp/CursorAcpSupport.ts +++ b/apps/server/src/provider/acp/CursorAcpSupport.ts @@ -23,6 +23,7 @@ export interface CursorAcpRuntimeInput extends Omit< > { readonly childProcessSpawner: ChildProcessSpawner.ChildProcessSpawner["Service"]; readonly cursorSettings: CursorAcpRuntimeCursorSettings | null | undefined; + readonly environment?: NodeJS.ProcessEnv; } export interface CursorAcpModelSelectionErrorContext { @@ -34,6 +35,7 @@ export interface CursorAcpModelSelectionErrorContext { export function buildCursorAcpSpawnInput( cursorSettings: CursorAcpRuntimeCursorSettings | null | undefined, cwd: string, + environment?: NodeJS.ProcessEnv, ): AcpSpawnInput { return { command: cursorSettings?.binaryPath || "agent", @@ -42,6 +44,7 @@ export function buildCursorAcpSpawnInput( "acp", ], cwd, + ...(environment ? { env: environment } : {}), }; } @@ -52,7 +55,7 @@ export const makeCursorAcpRuntime = ( const acpContext = yield* Layer.build( AcpSessionRuntime.layer({ ...input, - spawn: buildCursorAcpSpawnInput(input.cursorSettings, input.cwd), + spawn: buildCursorAcpSpawnInput(input.cursorSettings, input.cwd, input.environment), authMethodId: "cursor_login", clientCapabilities: CURSOR_PARAMETERIZED_MODEL_PICKER_CAPABILITIES, }).pipe( diff --git a/apps/server/src/provider/builtInDrivers.ts b/apps/server/src/provider/builtInDrivers.ts new file mode 100644 index 0000000000..5af56dc6b0 --- /dev/null +++ b/apps/server/src/provider/builtInDrivers.ts @@ -0,0 +1,50 @@ +/** + * BUILT_IN_DRIVERS — the static set of `ProviderDriver`s this build ships + * with. + * + * Every driver that the server knows how to instantiate from settings is + * listed here. The `ProviderInstanceRegistry` iterates this array when + * resolving `providerInstances` entries; anything not in the array surfaces + * as an `"unavailable"` shadow snapshot at runtime (see + * `buildUnavailableProviderSnapshot`). + * + * Adding a new first-party driver means: + * 1. implement `ProviderDriver` in a sibling `Drivers/Driver.ts`, + * 2. add it to this array, + * 3. ensure the runtime layer satisfies its declared `R`. + * + * The aggregated `BuiltInDriversEnv` type is the union of every driver's + * env requirement — the registry layer's `R` is this type, and the runtime + * layer (ChildProcessSpawner, FileSystem, Path, ServerConfig, + * OpenCodeRuntime, …) must satisfy it. + * + * @module provider/builtInDrivers + */ +import { ClaudeDriver, type ClaudeDriverEnv } from "./Drivers/ClaudeDriver.ts"; +import { CodexDriver, type CodexDriverEnv } from "./Drivers/CodexDriver.ts"; +import { CursorDriver, type CursorDriverEnv } from "./Drivers/CursorDriver.ts"; +import { OpenCodeDriver, type OpenCodeDriverEnv } from "./Drivers/OpenCodeDriver.ts"; +import type { AnyProviderDriver } from "./ProviderDriver.ts"; + +/** + * Union of infrastructure services required to construct any built-in + * driver. The registry layer declares `R = BuiltInDriversEnv`; the runtime + * layer must provide every service in this union. + */ +export type BuiltInDriversEnv = + | ClaudeDriverEnv + | CodexDriverEnv + | CursorDriverEnv + | OpenCodeDriverEnv; + +/** + * Ordered list of built-in drivers. Order matters only for tie-breaking in + * UI presentation — the registry itself is keyed by `driverKind`, so + * iteration order has no functional effect on instance lookup. + */ +export const BUILT_IN_DRIVERS: ReadonlyArray> = [ + CodexDriver, + ClaudeDriver, + CursorDriver, + OpenCodeDriver, +]; diff --git a/apps/server/src/provider/builtInProviderCatalog.ts b/apps/server/src/provider/builtInProviderCatalog.ts index 1fd10a85d9..ee25b6d018 100644 --- a/apps/server/src/provider/builtInProviderCatalog.ts +++ b/apps/server/src/provider/builtInProviderCatalog.ts @@ -1,49 +1,17 @@ -import type { ProviderKind, ServerProvider } from "@t3tools/contracts"; +import type { ProviderDriverKind, ProviderInstanceId, ServerProvider } from "@t3tools/contracts"; import type { Stream } from "effect"; -import type { ProviderAdapterError } from "./Errors.ts"; -import type { ProviderAdapterShape } from "./Services/ProviderAdapter.ts"; import type { ServerProviderShape } from "./Services/ServerProvider.ts"; export type ProviderSnapshotSource = { - readonly provider: ProviderKind; + /** + * Routing key — uniquely identifies this instance in the aggregated + * snapshot list. Two different snapshot sources may share the same + * driver kind (multiple instances of the same driver). + */ + readonly instanceId: ProviderInstanceId; + /** Driver implementation kind. */ + readonly driverKind: ProviderDriverKind; readonly getSnapshot: ServerProviderShape["getSnapshot"]; readonly refresh: ServerProviderShape["refresh"]; readonly streamChanges: Stream.Stream; }; - -type BuiltInProviderServiceMap = Record; -type BuiltInAdapterMap = { - readonly codex: ProviderAdapterShape; - readonly claudeAgent: ProviderAdapterShape; - readonly opencode: ProviderAdapterShape; - readonly cursor?: ProviderAdapterShape; -}; - -export const BUILT_IN_PROVIDER_ORDER = [ - "codex", - "claudeAgent", - "opencode", - "cursor", -] as const satisfies ReadonlyArray; - -export function createBuiltInProviderSources( - services: BuiltInProviderServiceMap, -): ReadonlyArray { - return BUILT_IN_PROVIDER_ORDER.map((provider) => ({ - provider, - getSnapshot: services[provider].getSnapshot, - refresh: services[provider].refresh, - streamChanges: services[provider].streamChanges, - })); -} - -export function createBuiltInAdapterList( - adapters: BuiltInAdapterMap, -): ReadonlyArray> { - return [ - adapters.codex, - adapters.claudeAgent, - adapters.opencode, - ...(adapters.cursor ? [adapters.cursor] : []), - ]; -} diff --git a/apps/server/src/provider/makeManagedServerProvider.test.ts b/apps/server/src/provider/makeManagedServerProvider.test.ts index 5d50d12e37..ff66476380 100644 --- a/apps/server/src/provider/makeManagedServerProvider.test.ts +++ b/apps/server/src/provider/makeManagedServerProvider.test.ts @@ -1,5 +1,5 @@ import { describe, it, assert } from "@effect/vitest"; -import type { ServerProvider } from "@t3tools/contracts"; +import { ProviderDriverKind, ProviderInstanceId, type ServerProvider } from "@t3tools/contracts"; import { createModelCapabilities } from "@t3tools/shared/model"; import { Deferred, Effect, Fiber, PubSub, Ref, Stream } from "effect"; @@ -21,7 +21,8 @@ interface TestSettings { } const initialSnapshot: ServerProvider = { - provider: "codex", + instanceId: ProviderInstanceId.make("codex"), + driver: ProviderDriverKind.make("codex"), enabled: true, installed: true, version: null, @@ -35,7 +36,8 @@ const initialSnapshot: ServerProvider = { }; const refreshedSnapshot: ServerProvider = { - provider: "codex", + instanceId: ProviderInstanceId.make("codex"), + driver: ProviderDriverKind.make("codex"), enabled: true, installed: true, version: "1.0.0", diff --git a/apps/server/src/provider/opencodeRuntime.ts b/apps/server/src/provider/opencodeRuntime.ts index 086584893c..3269c712a9 100644 --- a/apps/server/src/provider/opencodeRuntime.ts +++ b/apps/server/src/provider/opencodeRuntime.ts @@ -109,6 +109,7 @@ export interface OpenCodeRuntimeShape { */ readonly startOpenCodeServerProcess: (input: { readonly binaryPath: string; + readonly environment?: NodeJS.ProcessEnv; readonly port?: number; readonly hostname?: string; readonly timeoutMs?: number; @@ -121,6 +122,7 @@ export interface OpenCodeRuntimeShape { readonly connectToOpenCodeServer: (input: { readonly binaryPath: string; readonly serverUrl?: string | null; + readonly environment?: NodeJS.ProcessEnv; readonly port?: number; readonly hostname?: string; readonly timeoutMs?: number; @@ -128,6 +130,7 @@ export interface OpenCodeRuntimeShape { readonly runOpenCodeCommand: (input: { readonly binaryPath: string; readonly args: ReadonlyArray; + readonly environment?: NodeJS.ProcessEnv; }) => Effect.Effect; readonly createOpenCodeSdkClient: (input: { readonly baseUrl: string; @@ -274,7 +277,7 @@ const makeOpenCodeRuntime = Effect.gen(function* () { const child = yield* spawner.spawn( ChildProcess.make(input.binaryPath, [...input.args], { shell: process.platform === "win32", - env: process.env, + env: input.environment ?? process.env, }), ); const [stdout, stderr, code] = yield* Effect.all( @@ -332,7 +335,7 @@ const makeOpenCodeRuntime = Effect.gen(function* () { ChildProcess.make(input.binaryPath, args, { detached: process.platform !== "win32", env: { - ...process.env, + ...(input.environment ?? process.env), OPENCODE_CONFIG_CONTENT: JSON.stringify({}), }, }), @@ -472,6 +475,7 @@ const makeOpenCodeRuntime = Effect.gen(function* () { return startOpenCodeServerProcess({ binaryPath: input.binaryPath, + ...(input.environment !== undefined ? { environment: input.environment } : {}), ...(input.port !== undefined ? { port: input.port } : {}), ...(input.hostname !== undefined ? { hostname: input.hostname } : {}), ...(input.timeoutMs !== undefined ? { timeoutMs: input.timeoutMs } : {}), diff --git a/apps/server/src/provider/providerSnapshot.test.ts b/apps/server/src/provider/providerSnapshot.test.ts index f990afb2d6..449dca8fc5 100644 --- a/apps/server/src/provider/providerSnapshot.test.ts +++ b/apps/server/src/provider/providerSnapshot.test.ts @@ -1,5 +1,5 @@ import { describe, expect, it } from "vitest"; -import type { ModelCapabilities } from "@t3tools/contracts"; +import { ProviderDriverKind, type ModelCapabilities } from "@t3tools/contracts"; import { createModelCapabilities } from "@t3tools/shared/model"; import { providerModelsFromSettings } from "./providerSnapshot.ts"; @@ -27,7 +27,7 @@ describe("providerModelsFromSettings", () => { it("applies the provided capabilities to custom models", () => { const models = providerModelsFromSettings( [], - "opencode", + ProviderDriverKind.make("opencode"), ["openai/gpt-5"], OPENCODE_CUSTOM_MODEL_CAPABILITIES, ); diff --git a/apps/server/src/provider/providerSnapshot.ts b/apps/server/src/provider/providerSnapshot.ts index f1f0307485..af0c91274c 100644 --- a/apps/server/src/provider/providerSnapshot.ts +++ b/apps/server/src/provider/providerSnapshot.ts @@ -1,4 +1,5 @@ import type { + ProviderDriverKind, ModelCapabilities, ServerProvider, ServerProviderAuth, @@ -36,6 +37,8 @@ export interface ServerProviderPresentation { readonly showInteractionModeToggle?: boolean; } +export type ServerProviderDraft = Omit; + export function nonEmptyTrimmed(value: string | undefined): string | undefined { if (!value) return undefined; const trimmed = value.trim(); @@ -110,7 +113,7 @@ export function parseGenericCliVersion(output: string): string | null { export function providerModelsFromSettings( builtInModels: ReadonlyArray, - provider: ServerProvider["provider"], + provider: ProviderDriverKind, customModels: ReadonlyArray, customModelCapabilities: ModelCapabilities, ): ReadonlyArray { @@ -179,7 +182,6 @@ export function buildBooleanOptionDescriptor(input: { } export function buildServerProvider(input: { - provider: ServerProvider["provider"]; presentation: ServerProviderPresentation; enabled: boolean; checkedAt: string; @@ -187,9 +189,8 @@ export function buildServerProvider(input: { slashCommands?: ReadonlyArray; skills?: ReadonlyArray; probe: ProviderProbeResult; -}): ServerProvider { +}): ServerProviderDraft { return { - provider: input.provider, displayName: input.presentation.displayName, ...(input.presentation.badgeLabel ? { badgeLabel: input.presentation.badgeLabel } : {}), ...(typeof input.presentation.showInteractionModeToggle === "boolean" diff --git a/apps/server/src/provider/providerStatusCache.test.ts b/apps/server/src/provider/providerStatusCache.test.ts index 5a81341f6d..8986ba48f2 100644 --- a/apps/server/src/provider/providerStatusCache.test.ts +++ b/apps/server/src/provider/providerStatusCache.test.ts @@ -1,23 +1,33 @@ import * as NodeServices from "@effect/platform-node/NodeServices"; -import type { ServerProvider } from "@t3tools/contracts"; +import { + defaultInstanceIdForDriver, + ProviderDriverKind, + ProviderInstanceId, + type ServerProvider, +} from "@t3tools/contracts"; import { createModelCapabilities } from "@t3tools/shared/model"; import { assert, it } from "@effect/vitest"; import { Effect, FileSystem } from "effect"; import { hydrateCachedProvider, + isCachedProviderCorrelated, readProviderStatusCache, resolveProviderStatusCachePath, writeProviderStatusCache, } from "./providerStatusCache.ts"; const emptyCapabilities = createModelCapabilities({ optionDescriptors: [] }); +const CODEX_DRIVER = ProviderDriverKind.make("codex"); +const CLAUDE_AGENT_DRIVER = ProviderDriverKind.make("claudeAgent"); +const OPENCODE_DRIVER = ProviderDriverKind.make("opencode"); const makeProvider = ( - provider: ServerProvider["provider"], + provider: ProviderDriverKind, overrides?: Partial, ): ServerProvider => ({ - provider, + instanceId: defaultInstanceIdForDriver(provider), + driver: provider, enabled: true, installed: true, version: "1.0.0", @@ -35,26 +45,26 @@ it.layer(NodeServices.layer)("providerStatusCache", (it) => { Effect.gen(function* () { const fs = yield* FileSystem.FileSystem; const tempDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-provider-cache-" }); - const codexProvider = makeProvider("codex"); - const claudeProvider = makeProvider("claudeAgent", { + const codexProvider = makeProvider(CODEX_DRIVER); + const claudeProvider = makeProvider(CLAUDE_AGENT_DRIVER, { status: "warning", auth: { status: "unknown" }, }); - const openCodeProvider = makeProvider("opencode", { + const openCodeProvider = makeProvider(OPENCODE_DRIVER, { status: "warning", auth: { status: "unknown", type: "opencode" }, }); - const codexPath = resolveProviderStatusCachePath({ + const codexPath = yield* resolveProviderStatusCachePath({ cacheDir: tempDir, - provider: "codex", + instanceId: defaultInstanceIdForDriver(ProviderDriverKind.make("codex")), }); - const claudePath = resolveProviderStatusCachePath({ + const claudePath = yield* resolveProviderStatusCachePath({ cacheDir: tempDir, - provider: "claudeAgent", + instanceId: defaultInstanceIdForDriver(ProviderDriverKind.make("claudeAgent")), }); - const openCodePath = resolveProviderStatusCachePath({ + const openCodePath = yield* resolveProviderStatusCachePath({ cacheDir: tempDir, - provider: "opencode", + instanceId: defaultInstanceIdForDriver(ProviderDriverKind.make("opencode")), }); yield* writeProviderStatusCache({ @@ -77,7 +87,7 @@ it.layer(NodeServices.layer)("providerStatusCache", (it) => { ); it("hydrates cached provider status while preserving current settings-derived models", () => { - const cachedCodex = makeProvider("codex", { + const cachedCodex = makeProvider(CODEX_DRIVER, { checkedAt: "2026-04-10T12:00:00.000Z", models: [ { @@ -97,7 +107,7 @@ it.layer(NodeServices.layer)("providerStatusCache", (it) => { }, ], }); - const fallbackCodex = makeProvider("codex", { + const fallbackCodex = makeProvider(CODEX_DRIVER, { models: [ { slug: "gpt-5.4", @@ -138,11 +148,11 @@ it.layer(NodeServices.layer)("providerStatusCache", (it) => { }); it("ignores stale cached enabled state when the provider is now disabled", () => { - const cachedCodex = makeProvider("codex", { + const cachedCodex = makeProvider(CODEX_DRIVER, { checkedAt: "2026-04-10T12:00:00.000Z", message: "Cached ready status", }); - const disabledFallback = makeProvider("codex", { + const disabledFallback = makeProvider(CODEX_DRIVER, { enabled: false, installed: false, version: null, @@ -159,4 +169,68 @@ it.layer(NodeServices.layer)("providerStatusCache", (it) => { disabledFallback, ); }); + + it("rejects cached snapshots that are not correlated to the fallback instance", () => { + const fallbackCodex = makeProvider(CODEX_DRIVER, { + models: [ + { + slug: "gpt-5.4", + name: "GPT-5.4", + isCustom: false, + capabilities: emptyCapabilities, + }, + ], + }); + const legacyCachedCodex = { + provider: ProviderDriverKind.make("codex"), + enabled: true, + installed: true, + version: "1.0.0", + status: "ready", + auth: { status: "authenticated" }, + checkedAt: "2026-04-10T12:00:00.000Z", + models: [ + { + slug: "cached-legacy-model", + name: "Cached Legacy Model", + isCustom: false, + capabilities: emptyCapabilities, + }, + ], + slashCommands: [], + skills: [], + } as unknown as ServerProvider; + const mismatchedCachedCodex = makeProvider(CODEX_DRIVER, { + instanceId: ProviderInstanceId.make("codex_personal"), + }); + + assert.strictEqual( + isCachedProviderCorrelated({ + cachedProvider: legacyCachedCodex, + fallbackProvider: fallbackCodex, + }), + false, + ); + assert.deepStrictEqual( + hydrateCachedProvider({ + cachedProvider: legacyCachedCodex, + fallbackProvider: fallbackCodex, + }), + fallbackCodex, + ); + assert.strictEqual( + isCachedProviderCorrelated({ + cachedProvider: mismatchedCachedCodex, + fallbackProvider: fallbackCodex, + }), + false, + ); + assert.deepStrictEqual( + hydrateCachedProvider({ + cachedProvider: mismatchedCachedCodex, + fallbackProvider: fallbackCodex, + }), + fallbackCodex, + ); + }); }); diff --git a/apps/server/src/provider/providerStatusCache.ts b/apps/server/src/provider/providerStatusCache.ts index fdb31eecbe..d6c051fd56 100644 --- a/apps/server/src/provider/providerStatusCache.ts +++ b/apps/server/src/provider/providerStatusCache.ts @@ -1,25 +1,17 @@ -import * as nodePath from "node:path"; -import { type ServerProvider, ServerProvider as ServerProviderSchema } from "@t3tools/contracts"; -import { Cause, Effect, FileSystem, Schema } from "effect"; +import { + type ProviderDriverKind, + type ProviderInstanceId, + type ServerProvider, + ServerProvider as ServerProviderSchema, +} from "@t3tools/contracts"; +import { Cause, Effect, FileSystem, Path, Schema } from "effect"; import { writeFileStringAtomically } from "../atomicWrite.ts"; -export const PROVIDER_CACHE_IDS = [ - "codex", - "claudeAgent", - "opencode", - "cursor", -] as const satisfies ReadonlyArray; - const decodeProviderStatusCache = Schema.decodeUnknownEffect( Schema.fromJsonString(ServerProviderSchema), ); -const providerOrderRank = (provider: ServerProvider["provider"]): number => { - const rank = PROVIDER_CACHE_IDS.indexOf(provider); - return rank === -1 ? Number.MAX_SAFE_INTEGER : rank; -}; - const mergeProviderModels = ( fallbackModels: ReadonlyArray, cachedModels: ReadonlyArray, @@ -32,13 +24,27 @@ export const orderProviderSnapshots = ( providers: ReadonlyArray, ): ReadonlyArray => [...providers].toSorted( - (left, right) => providerOrderRank(left.provider) - providerOrderRank(right.provider), + (left, right) => + (left.displayName ?? "").localeCompare(right.displayName ?? "") || + left.driver.localeCompare(right.driver) || + left.instanceId.localeCompare(right.instanceId), ); +export const isCachedProviderCorrelated = (input: { + readonly cachedProvider: ServerProvider; + readonly fallbackProvider: ServerProvider; +}): boolean => + input.cachedProvider.instanceId === input.fallbackProvider.instanceId && + input.cachedProvider.driver === input.fallbackProvider.driver; + export const hydrateCachedProvider = (input: { readonly cachedProvider: ServerProvider; readonly fallbackProvider: ServerProvider; }): ServerProvider => { + if (!isCachedProviderCorrelated(input)) { + return input.fallbackProvider; + } + if ( !input.fallbackProvider.enabled || input.cachedProvider.enabled !== input.fallbackProvider.enabled @@ -64,10 +70,46 @@ export const hydrateCachedProvider = (input: { : hydratedProvider; }; -export const resolveProviderStatusCachePath = (input: { +/** + * Resolve the on-disk cache path for a provider instance snapshot. + * + * File naming: `/.json`. For the default instance of + * a built-in kind this equals the legacy `.json` path (because + * `defaultInstanceIdForDriver(kind).toString() === kind`), so existing + * cached snapshots remain readable without any rename step. + * + * Non-default instances (e.g. `codex_personal`) land in their own files and + * never collide with other instances. + * + * Cache contents must still carry matching `instanceId` + `driver` identity + * before hydration. The filename alone is not trusted as a routing key. + */ +export const resolveProviderStatusCachePath = Effect.fn("resolveProviderStatusCachePath")( + function* (input: { + readonly cacheDir: string; + readonly instanceId: ProviderInstanceId; + }): Effect.fn.Return { + const path = yield* Path.Path; + return path.join(input.cacheDir, `${input.instanceId}.json`); + }, +); + +/** + * Legacy kind-keyed path resolver retained for callers that still think in + * terms of `ProviderDriverKind`. Prefer `resolveProviderStatusCachePath` with an + * `instanceId`; new code should route through the instance registry. + * + * @deprecated use `resolveProviderStatusCachePath` with an instance id. + */ +export const resolveLegacyProviderStatusCachePath = Effect.fn( + "resolveLegacyProviderStatusCachePath", +)(function* (input: { readonly cacheDir: string; - readonly provider: ServerProvider["provider"]; -}) => nodePath.join(input.cacheDir, `${input.provider}.json`); + readonly provider: ProviderDriverKind; +}): Effect.fn.Return { + const path = yield* Path.Path; + return path.join(input.cacheDir, `${input.provider}.json`); +}); export const readProviderStatusCache = (filePath: string) => Effect.gen(function* () { diff --git a/apps/server/src/provider/testUtils/providerAdapterRegistryMock.ts b/apps/server/src/provider/testUtils/providerAdapterRegistryMock.ts new file mode 100644 index 0000000000..9a4f107db8 --- /dev/null +++ b/apps/server/src/provider/testUtils/providerAdapterRegistryMock.ts @@ -0,0 +1,95 @@ +/** + * Test helpers for constructing a `ProviderAdapterRegistryShape` mock from a + * kind-keyed adapter map. + * + * Tests historically assembled a `registry` object with only `getByProvider` + * + `listProviders` populated. Slice D grew the shape with `getByInstance` + * and `listInstances`; this helper fills both in from a single kind-keyed + * input so individual fixtures can stay concise. + * + * Non-default instance ids (e.g. `codex_personal`) are not addressable via + * the shim returned here — the legacy test fixtures only ever had + * single-instance-per-driver data anyway. + * + * @module provider/testUtils/providerAdapterRegistryMock + */ +import { + defaultInstanceIdForDriver, + ProviderDriverKind, + type ProviderInstanceId, +} from "@t3tools/contracts"; +import { Effect, PubSub, Record, Result, Stream } from "effect"; + +import { ProviderUnsupportedError, type ProviderAdapterError } from "../Errors.ts"; +import type { ProviderAdapterShape } from "../Services/ProviderAdapter.ts"; +import type { ProviderAdapterRegistryShape } from "../Services/ProviderAdapterRegistry.ts"; + +export type KindAdapterMap = Partial< + Record> +>; + +/** + * Build a `ProviderAdapterRegistryShape` from a kind-keyed adapter map. + * Every adapter present in the map is addressable via both the legacy + * `getByProvider(kind)` path and the new `getByInstance(id)` path (where + * `id = defaultInstanceIdForDriver(kind)`). + */ +export const makeAdapterRegistryMock = (adapters: KindAdapterMap): ProviderAdapterRegistryShape => { + const byInstanceId = new Map>(); + for (const [kind, adapter] of Object.entries(adapters)) { + if (!adapter) continue; + const driverKind = ProviderDriverKind.make(kind); + byInstanceId.set(defaultInstanceIdForDriver(driverKind), adapter); + } + + const getByInstance: ProviderAdapterRegistryShape["getByInstance"] = (instanceId) => { + const adapter = byInstanceId.get(instanceId); + return adapter + ? Effect.succeed(adapter) + : Effect.fail( + new ProviderUnsupportedError({ + provider: ProviderDriverKind.make(instanceId), + }), + ); + }; + + return { + getByInstance, + getInstanceInfo: (instanceId) => { + const adapter = byInstanceId.get(instanceId); + if (!adapter) { + return Effect.fail( + new ProviderUnsupportedError({ + provider: ProviderDriverKind.make(instanceId), + }), + ); + } + return Effect.succeed({ + instanceId, + driverKind: ProviderDriverKind.make(adapter.provider), + displayName: undefined, + enabled: true, + continuationIdentity: { + driverKind: ProviderDriverKind.make(adapter.provider), + continuationKey: `${adapter.provider}:instance:${instanceId}`, + }, + }); + }, + listInstances: () => Effect.succeed(Array.from(byInstanceId.keys())), + listProviders: () => + Effect.succeed( + Record.keys( + Record.filterMap(adapters, (adapter, kind) => + adapter !== undefined ? Result.succeed(kind) : Result.failVoid, + ), + ), + ), + // Static test fixtures don't reload; an empty stream is enough to + // satisfy the shape. Tests exercising hot-reload build their own + // stream via the real `ProviderInstanceRegistry`. + streamChanges: Stream.empty, + subscribeChanges: Effect.flatMap(PubSub.unbounded(), (pubsub) => + PubSub.subscribe(pubsub), + ), + }; +}; diff --git a/apps/server/src/provider/unavailableProviderSnapshot.ts b/apps/server/src/provider/unavailableProviderSnapshot.ts new file mode 100644 index 0000000000..97a532a9d9 --- /dev/null +++ b/apps/server/src/provider/unavailableProviderSnapshot.ts @@ -0,0 +1,72 @@ +/** + * Helpers for synthesizing "unavailable" `ServerProvider` snapshots. + * + * When `ServerSettings.providerInstances` (or persisted thread/session + * state) references a driver this build does not ship — typical after a + * downgrade from a fork or a feature-branch test session — the runtime + * needs to surface the entry to the UI without crashing. This module + * produces shadow snapshots that satisfy `ServerProvider`'s wire shape + * while signalling unavailability. + * + * @module unavailableProviderSnapshot + */ +import { + ProviderDriverKind, + type ProviderInstanceId, + type ServerProvider, +} from "@t3tools/contracts"; + +import { buildServerProvider } from "./providerSnapshot.ts"; + +export interface UnavailableProviderSnapshotInput { + readonly driverKind: ProviderDriverKind | string; + readonly instanceId: ProviderInstanceId; + readonly displayName?: string | undefined; + readonly accentColor?: string | undefined; + readonly reason: string; + /** + * Optional override for `checkedAt`. Defaulted to `new Date()` so callers + * (notably tests) don't have to pass it. + */ + readonly checkedAt?: string; +} + +/** + * Produce a `ServerProvider` snapshot representing a configured instance + * whose driver the running build does not implement. The result is safe + * to broadcast over the wire and is structured so the web UI can render + * a "missing driver" affordance without special-casing. + */ +export function buildUnavailableProviderSnapshot( + input: UnavailableProviderSnapshotInput, +): ServerProvider { + const checkedAt = input.checkedAt ?? new Date().toISOString(); + const displayName = input.displayName?.trim() || (input.driverKind as string); + + const base = buildServerProvider({ + presentation: { displayName }, + enabled: false, + checkedAt, + models: [], + skills: [], + probe: { + installed: false, + version: null, + status: "error", + auth: { status: "unknown" }, + message: input.reason, + }, + }); + + return { + ...base, + instanceId: input.instanceId, + ...(input.accentColor ? { accentColor: input.accentColor } : {}), + driver: + typeof input.driverKind === "string" + ? ProviderDriverKind.make(input.driverKind) + : input.driverKind, + availability: "unavailable", + unavailableReason: input.reason, + }; +} diff --git a/apps/server/src/server.test.ts b/apps/server/src/server.test.ts index 47e159d303..e699ad8339 100644 --- a/apps/server/src/server.test.ts +++ b/apps/server/src/server.test.ts @@ -17,6 +17,8 @@ import { type OrchestrationEvent, ORCHESTRATION_WS_METHODS, ProjectId, + ProviderDriverKind, + ProviderInstanceId, ResolvedKeybindingRule, ThreadId, WS_METHODS, @@ -110,7 +112,7 @@ const defaultProjectId = ProjectId.make("project-default"); const defaultThreadId = ThreadId.make("thread-default"); const defaultDesktopBootstrapToken = "test-desktop-bootstrap-token"; const defaultModelSelection = { - provider: "codex", + instanceId: ProviderInstanceId.make("codex"), model: "gpt-5-codex", } as const; const testEnvironmentDescriptor = { @@ -1845,7 +1847,8 @@ it.layer(NodeServices.layer)("server router seam", (it) => { Effect.gen(function* () { const providers = [ { - provider: "codex" as const, + instanceId: ProviderInstanceId.make("codex"), + driver: ProviderDriverKind.make("codex"), enabled: true, installed: true, version: "1.0.0", @@ -1915,7 +1918,8 @@ it.layer(NodeServices.layer)("server router seam", (it) => { Effect.gen(function* () { const nextProviders = [ { - provider: "codex" as const, + instanceId: ProviderInstanceId.make("codex"), + driver: ProviderDriverKind.make("codex"), enabled: true, installed: true, version: "1.0.0", @@ -2164,7 +2168,7 @@ it.layer(NodeServices.layer)("server router seam", (it) => { workspaceRoot: missingWorkspaceRoot, createWorkspaceRootIfMissing: true, defaultModelSelection: { - provider: "codex", + instanceId: ProviderInstanceId.make("codex"), model: "gpt-5-codex", }, createdAt: new Date().toISOString(), diff --git a/apps/server/src/server.ts b/apps/server/src/server.ts index f94bbb34b5..85f2d84ad2 100644 --- a/apps/server/src/server.ts +++ b/apps/server/src/server.ts @@ -16,22 +16,20 @@ import { OpenLive } from "./open.ts"; import { layerConfig as SqlitePersistenceLayerLive } from "./persistence/Layers/Sqlite.ts"; import { ServerLifecycleEventsLive } from "./serverLifecycleEvents.ts"; import { AnalyticsServiceLayerLive } from "./telemetry/Layers/AnalyticsService.ts"; -import { makeEventNdjsonLogger } from "./provider/Layers/EventNdjsonLogger.ts"; import { ProviderSessionDirectoryLive } from "./provider/Layers/ProviderSessionDirectory.ts"; import { ProviderSessionRuntimeRepositoryLive } from "./persistence/Layers/ProviderSessionRuntime.ts"; -import { makeCodexAdapterLive } from "./provider/Layers/CodexAdapter.ts"; -import { makeClaudeAdapterLive } from "./provider/Layers/ClaudeAdapter.ts"; -import { makeCursorAdapterLive } from "./provider/Layers/CursorAdapter.ts"; -import { makeOpenCodeAdapterLive } from "./provider/Layers/OpenCodeAdapter.ts"; import { ProviderAdapterRegistryLive } from "./provider/Layers/ProviderAdapterRegistry.ts"; -import { makeProviderServiceLive } from "./provider/Layers/ProviderService.ts"; +import { ProviderEventLoggersLive } from "./provider/Layers/ProviderEventLoggers.ts"; +import { ProviderServiceLive } from "./provider/Layers/ProviderService.ts"; import { ProviderSessionReaperLive } from "./provider/Layers/ProviderSessionReaper.ts"; +import { OpenCodeRuntimeLive } from "./provider/opencodeRuntime.ts"; import { CheckpointDiffQueryLive } from "./checkpointing/Layers/CheckpointDiffQuery.ts"; import { CheckpointStoreLive } from "./checkpointing/Layers/CheckpointStore.ts"; import { GitCoreLive } from "./git/Layers/GitCore.ts"; import { GitHubCliLive } from "./git/Layers/GitHubCli.ts"; import { GitStatusBroadcasterLive } from "./git/Layers/GitStatusBroadcaster.ts"; -import { RoutingTextGenerationLive } from "./git/Layers/RoutingTextGeneration.ts"; +import { TextGenerationLive } from "./git/Layers/TextGenerationLive.ts"; +import { ProviderInstanceRegistryHydrationLive } from "./provider/Layers/ProviderInstanceRegistryHydration.ts"; import { TerminalManagerLive } from "./terminal/Layers/Manager.ts"; import { GitManagerLive } from "./git/Layers/GitManager.ts"; import { KeybindingsLive } from "./keybindings.ts"; @@ -144,41 +142,15 @@ const ProviderSessionDirectoryLayerLive = ProviderSessionDirectoryLive.pipe( Layer.provide(ProviderSessionRuntimeRepositoryLive), ); -const ProviderLayerLive = Layer.unwrap( - Effect.gen(function* () { - const { providerEventLogPath } = yield* ServerConfig; - const nativeEventLogger = yield* makeEventNdjsonLogger(providerEventLogPath, { - stream: "native", - }); - const canonicalEventLogger = yield* makeEventNdjsonLogger(providerEventLogPath, { - stream: "canonical", - }); - const codexAdapterLayer = makeCodexAdapterLive( - nativeEventLogger ? { nativeEventLogger } : undefined, - ); - const claudeAdapterLayer = makeClaudeAdapterLive( - nativeEventLogger ? { nativeEventLogger } : undefined, - ); - const openCodeAdapterLayer = makeOpenCodeAdapterLive( - nativeEventLogger ? { nativeEventLogger } : undefined, - ); - const cursorAdapterLayer = makeCursorAdapterLive( - nativeEventLogger ? { nativeEventLogger } : undefined, - ); - const adapterRegistryLayer = ProviderAdapterRegistryLive.pipe( - Layer.provide(codexAdapterLayer), - Layer.provide(claudeAdapterLayer), - Layer.provide(openCodeAdapterLayer), - Layer.provide(cursorAdapterLayer), - Layer.provideMerge(ProviderSessionDirectoryLayerLive), - ); - return makeProviderServiceLive( - canonicalEventLogger ? { canonicalEventLogger } : undefined, - ).pipe( - Layer.provide(adapterRegistryLayer), - Layer.provideMerge(ProviderSessionDirectoryLayerLive), - ); - }), +// `ProviderAdapterRegistryLive` is now a facade that resolves kind → adapter +// by looking up the default `ProviderInstance` per driver in the instance +// registry. Adapter construction itself moved inside each driver's +// `create()`; `ProviderEventLoggersLive` owns the shared native/canonical +// NDJSON writers and is provided at the outer runtime layer so both +// `ProviderService` and the per-instance drivers read the same logger pair. +const ProviderLayerLive = ProviderServiceLive.pipe( + Layer.provide(ProviderAdapterRegistryLive), + Layer.provideMerge(ProviderSessionDirectoryLayerLive), ); const PersistenceLayerLive = Layer.empty.pipe(Layer.provideMerge(SqlitePersistenceLayerLive)); @@ -187,7 +159,7 @@ const GitManagerLayerLive = GitManagerLive.pipe( Layer.provideMerge(ProjectSetupScriptRunnerLive), Layer.provideMerge(GitCoreLive), Layer.provideMerge(GitHubCliLive), - Layer.provideMerge(RoutingTextGenerationLive), + Layer.provideMerge(TextGenerationLive), ); const GitLayerLive = Layer.empty.pipe( @@ -233,6 +205,24 @@ const RuntimeDependenciesLive = ReactorLayerLive.pipe( Layer.provideMerge(PersistenceLayerLive), Layer.provideMerge(KeybindingsLive), Layer.provideMerge(ProviderRegistryLive), + // The instance registry is the new routing keystone — text generation, + // adapter lookup, and runtime ingestion all resolve `ProviderInstanceId` + // through this layer. Built-in drivers come from `BUILT_IN_DRIVERS`; + // `providerInstances` hydration merges `settings.providers.` + // with explicit `providerInstances` entries on boot. + Layer.provideMerge(ProviderInstanceRegistryHydrationLive), + // Shared native/canonical NDJSON writers used by both the per-instance + // drivers (native stream, written from inside each `Adapter`) and + // `ProviderService` (canonical stream, written after event normalization). + // Provided once at the runtime level so every consumer sees the same + // logger instances. + Layer.provideMerge(ProviderEventLoggersLive), + // `OpenCodeDriver.create()` yields `OpenCodeRuntime`; previously the old + // `ProviderRegistryLive` pulled `OpenCodeRuntimeLive` in for itself, but + // the rewritten registry reads snapshots off the instance registry and + // no longer transitively provides it. Exposing it at the runtime level + // keeps a single Live for all opencode consumers. + Layer.provideMerge(OpenCodeRuntimeLive), Layer.provideMerge(ServerSettingsLive), Layer.provideMerge(WorkspaceLayerLive), Layer.provideMerge(ProjectFaviconResolverLive), diff --git a/apps/server/src/serverRuntimeStartup.test.ts b/apps/server/src/serverRuntimeStartup.test.ts index 836b71c7eb..91b4b215c1 100644 --- a/apps/server/src/serverRuntimeStartup.test.ts +++ b/apps/server/src/serverRuntimeStartup.test.ts @@ -1,5 +1,5 @@ import * as NodeServices from "@effect/platform-node/NodeServices"; -import { DEFAULT_MODEL_BY_PROVIDER, ProjectId, ThreadId } from "@t3tools/contracts"; +import { DEFAULT_MODEL, ProjectId, ProviderInstanceId, ThreadId } from "@t3tools/contracts"; import { assert, it } from "@effect/vitest"; import { Deferred, Effect, Fiber, Option, Ref, Stream } from "effect"; @@ -21,8 +21,8 @@ import { it("uses the canonical Codex default for auto-bootstrapped model selection", () => { assert.deepStrictEqual(getAutoBootstrapDefaultModelSelection(), { - provider: "codex", - model: DEFAULT_MODEL_BY_PROVIDER.codex, + instanceId: ProviderInstanceId.make("codex"), + model: DEFAULT_MODEL, }); }); diff --git a/apps/server/src/serverRuntimeStartup.ts b/apps/server/src/serverRuntimeStartup.ts index 99728f681f..1f164860a6 100644 --- a/apps/server/src/serverRuntimeStartup.ts +++ b/apps/server/src/serverRuntimeStartup.ts @@ -1,9 +1,10 @@ import { CommandId, - DEFAULT_MODEL_BY_PROVIDER, + DEFAULT_MODEL, DEFAULT_PROVIDER_INTERACTION_MODE, type ModelSelection, ProjectId, + ProviderInstanceId, ThreadId, } from "@t3tools/contracts"; import { @@ -154,8 +155,8 @@ export const launchStartupHeartbeat = recordStartupHeartbeat.pipe( ); export const getAutoBootstrapDefaultModelSelection = (): ModelSelection => ({ - provider: "codex", - model: DEFAULT_MODEL_BY_PROVIDER.codex, + instanceId: ProviderInstanceId.make("codex"), + model: DEFAULT_MODEL, }); export const resolveWelcomeBase = Effect.gen(function* () { diff --git a/apps/server/src/serverSettings.test.ts b/apps/server/src/serverSettings.test.ts index 55f598054b..f11c5bf451 100644 --- a/apps/server/src/serverSettings.test.ts +++ b/apps/server/src/serverSettings.test.ts @@ -1,5 +1,11 @@ import * as NodeServices from "@effect/platform-node/NodeServices"; -import { DEFAULT_SERVER_SETTINGS, ServerSettings, ServerSettingsPatch } from "@t3tools/contracts"; +import { + DEFAULT_SERVER_SETTINGS, + ProviderDriverKind, + ProviderInstanceId, + ServerSettings, + ServerSettingsPatch, +} from "@t3tools/contracts"; import { createModelSelection } from "@t3tools/shared/model"; import { assert, it } from "@effect/vitest"; import { Effect, FileSystem, Layer, Schema } from "effect"; @@ -49,14 +55,14 @@ it.layer(NodeServices.layer)("server settings", (it) => { const decoded = decode({ textGenerationModelSelection: { - provider: "codex", + provider: ProviderDriverKind.make("codex"), model: "gpt-5.4-mini", options: { reasoningEffort: "low" }, }, }); assert.deepEqual(decoded.textGenerationModelSelection, { - provider: "codex", + instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4-mini", options: [{ id: "reasoningEffort", value: "low" }], }); @@ -79,10 +85,10 @@ it.layer(NodeServices.layer)("server settings", (it) => { }, }, textGenerationModelSelection: { - provider: "codex", + instanceId: ProviderInstanceId.make("codex"), model: DEFAULT_SERVER_SETTINGS.textGenerationModelSelection.model, options: createModelSelection( - "codex", + ProviderInstanceId.make("codex"), DEFAULT_SERVER_SETTINGS.textGenerationModelSelection.model, [ { id: "reasoningEffort", value: "high" }, @@ -107,20 +113,26 @@ it.layer(NodeServices.layer)("server settings", (it) => { enabled: true, binaryPath: "/opt/homebrew/bin/codex", homePath: "/Users/julius/.codex", + shadowHomePath: "", customModels: [], }); assert.deepEqual(next.providers.claudeAgent, { enabled: true, binaryPath: "/usr/local/bin/claude", + homePath: "", customModels: ["claude-custom"], launchArgs: "", }); assert.deepEqual( next.textGenerationModelSelection, - createModelSelection("codex", DEFAULT_SERVER_SETTINGS.textGenerationModelSelection.model, [ - { id: "reasoningEffort", value: "high" }, - { id: "fastMode", value: false }, - ]), + createModelSelection( + ProviderInstanceId.make("codex"), + DEFAULT_SERVER_SETTINGS.textGenerationModelSelection.model, + [ + { id: "reasoningEffort", value: "high" }, + { id: "fastMode", value: false }, + ], + ), ); }).pipe(Effect.provide(makeServerSettingsLayer())), ); @@ -132,11 +144,13 @@ it.layer(NodeServices.layer)("server settings", (it) => { // Start with Claude text generation selection yield* serverSettings.updateSettings({ textGenerationModelSelection: { - provider: "claudeAgent", + instanceId: ProviderInstanceId.make("claudeAgent"), model: "claude-sonnet-4-6", - options: createModelSelection("claudeAgent", "claude-sonnet-4-6", [ - { id: "effort", value: "high" }, - ]).options!, + options: createModelSelection( + ProviderInstanceId.make("claudeAgent"), + "claude-sonnet-4-6", + [{ id: "effort", value: "high" }], + ).options!, }, }); @@ -144,9 +158,9 @@ it.layer(NodeServices.layer)("server settings", (it) => { // cause the update to lose the selected model. const next = yield* serverSettings.updateSettings({ textGenerationModelSelection: { - provider: "codex", + instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4", - options: createModelSelection("codex", "gpt-5.4", [ + options: createModelSelection(ProviderInstanceId.make("codex"), "gpt-5.4", [ { id: "reasoningEffort", value: "high" }, ]).options!, }, @@ -154,21 +168,107 @@ it.layer(NodeServices.layer)("server settings", (it) => { assert.deepEqual( next.textGenerationModelSelection, - createModelSelection("codex", "gpt-5.4", [{ id: "reasoningEffort", value: "high" }]), + createModelSelection(ProviderInstanceId.make("codex"), "gpt-5.4", [ + { id: "reasoningEffort", value: "high" }, + ]), ); }).pipe(Effect.provide(makeServerSettingsLayer())), ); + it.effect("preserves custom provider instance text generation selections", () => + Effect.gen(function* () { + const serverSettings = yield* ServerSettingsService; + + const next = yield* serverSettings.updateSettings({ + providerInstances: { + [ProviderInstanceId.make("claude_openrouter")]: { + driver: ProviderDriverKind.make("claudeAgent"), + enabled: true, + config: { customModels: ["openai/gpt-5.5"] }, + }, + }, + textGenerationModelSelection: { + instanceId: ProviderInstanceId.make("claude_openrouter"), + model: "openai/gpt-5.5", + }, + }); + + assert.deepEqual(next.textGenerationModelSelection, { + instanceId: ProviderInstanceId.make("claude_openrouter"), + model: "openai/gpt-5.5", + }); + }).pipe(Effect.provide(makeServerSettingsLayer())), + ); + + it.effect( + "uses explicit provider instance enabled state over legacy provider enabled state", + () => + Effect.gen(function* () { + const serverSettings = yield* ServerSettingsService; + const instanceId = ProviderInstanceId.make("claude_openrouter"); + + const next = yield* serverSettings.updateSettings({ + providers: { + claudeAgent: { + enabled: false, + }, + }, + providerInstances: { + [instanceId]: { + driver: ProviderDriverKind.make("claudeAgent"), + enabled: true, + config: { customModels: ["openai/gpt-5.5"] }, + }, + }, + textGenerationModelSelection: { + instanceId, + model: "openai/gpt-5.5", + }, + }); + + assert.deepEqual(next.textGenerationModelSelection, { + instanceId, + model: "openai/gpt-5.5", + }); + }).pipe(Effect.provide(makeServerSettingsLayer())), + ); + + it.effect("preserves enabled text generation selections for non-built-in drivers", () => + Effect.gen(function* () { + const serverSettings = yield* ServerSettingsService; + const instanceId = ProviderInstanceId.make("openrouter_text"); + + const next = yield* serverSettings.updateSettings({ + providerInstances: { + [instanceId]: { + driver: ProviderDriverKind.make("openrouter"), + enabled: true, + config: { customModels: ["openai/gpt-5.5"] }, + }, + }, + textGenerationModelSelection: { + instanceId, + model: "openai/gpt-5.5", + }, + }); + + assert.deepEqual(next.textGenerationModelSelection, { + instanceId, + model: "openai/gpt-5.5", + }); + }).pipe(Effect.provide(makeServerSettingsLayer())), + ); + it.effect("drops stale text generation options when resetting model selection", () => Effect.gen(function* () { const serverSettings = yield* ServerSettingsService; yield* serverSettings.updateSettings({ textGenerationModelSelection: { - provider: "codex", + instanceId: ProviderInstanceId.make("codex"), model: DEFAULT_SERVER_SETTINGS.textGenerationModelSelection.model, options: createModelSelection( - "codex", + ProviderInstanceId.make("codex"), DEFAULT_SERVER_SETTINGS.textGenerationModelSelection.model, [ { id: "reasoningEffort", value: "high" }, @@ -180,18 +280,55 @@ it.layer(NodeServices.layer)("server settings", (it) => { const next = yield* serverSettings.updateSettings({ textGenerationModelSelection: { - provider: DEFAULT_SERVER_SETTINGS.textGenerationModelSelection.provider, + instanceId: DEFAULT_SERVER_SETTINGS.textGenerationModelSelection.instanceId, model: DEFAULT_SERVER_SETTINGS.textGenerationModelSelection.model, }, }); assert.deepEqual(next.textGenerationModelSelection, { - provider: DEFAULT_SERVER_SETTINGS.textGenerationModelSelection.provider, + instanceId: DEFAULT_SERVER_SETTINGS.textGenerationModelSelection.instanceId, model: DEFAULT_SERVER_SETTINGS.textGenerationModelSelection.model, }); }).pipe(Effect.provide(makeServerSettingsLayer())), ); + it.effect("replaces provider instance maps when clearing optional fields", () => + Effect.gen(function* () { + const serverSettings = yield* ServerSettingsService; + const codexId = ProviderInstanceId.make("codex"); + + yield* serverSettings.updateSettings({ + providerInstances: { + [codexId]: { + driver: ProviderDriverKind.make("codex"), + displayName: "Codex Work", + accentColor: "#7c3aed", + enabled: true, + config: { homePath: "~/.codex" }, + }, + }, + }); + + const next = yield* serverSettings.updateSettings({ + providerInstances: { + [codexId]: { + driver: ProviderDriverKind.make("codex"), + displayName: "Codex Work", + enabled: true, + config: { homePath: "~/.codex" }, + }, + }, + }); + + assert.deepEqual(next.providerInstances[codexId], { + driver: ProviderDriverKind.make("codex"), + displayName: "Codex Work", + enabled: true, + config: { homePath: "~/.codex" }, + }); + }).pipe(Effect.provide(makeServerSettingsLayer())), + ); + it.effect("trims provider path settings when updates are applied", () => Effect.gen(function* () { const serverSettings = yield* ServerSettingsService; @@ -217,11 +354,13 @@ it.layer(NodeServices.layer)("server settings", (it) => { enabled: true, binaryPath: "/opt/homebrew/bin/codex", homePath: "", + shadowHomePath: "", customModels: [], }); assert.deepEqual(next.providers.claudeAgent, { enabled: true, binaryPath: "/opt/homebrew/bin/claude", + homePath: "", customModels: [], launchArgs: "", }); @@ -318,4 +457,67 @@ it.layer(NodeServices.layer)("server settings", (it) => { }); }).pipe(Effect.provide(makeServerSettingsLayer())), ); + + it.effect("stores sensitive provider instance environment values outside settings.json", () => + Effect.gen(function* () { + const serverSettings = yield* ServerSettingsService; + const serverConfig = yield* ServerConfig; + const fileSystem = yield* FileSystem.FileSystem; + const instanceId = ProviderInstanceId.make("codex_personal"); + + const next = yield* serverSettings.updateSettings({ + providerInstances: { + [instanceId]: { + driver: ProviderDriverKind.make("codex"), + environment: [ + { name: "OPENROUTER_API_KEY", value: "sk-or-secret", sensitive: true }, + { name: "ANTHROPIC_BASE_URL", value: "https://openrouter.ai/api", sensitive: false }, + ], + config: {}, + }, + }, + }); + + assert.deepEqual(next.providerInstances[instanceId]?.environment, [ + { + name: "OPENROUTER_API_KEY", + value: "sk-or-secret", + sensitive: true, + valueRedacted: true, + }, + { name: "ANTHROPIC_BASE_URL", value: "https://openrouter.ai/api", sensitive: false }, + ]); + + const raw = yield* fileSystem.readFileString(serverConfig.settingsPath); + assert.notInclude(raw, "sk-or-secret"); + assert.deepEqual(JSON.parse(raw).providerInstances.codex_personal.environment, [ + { + name: "OPENROUTER_API_KEY", + value: "", + sensitive: true, + valueRedacted: true, + }, + { name: "ANTHROPIC_BASE_URL", value: "https://openrouter.ai/api", sensitive: false }, + ]); + + const roundTripped = yield* serverSettings.updateSettings({ + providerInstances: { + [instanceId]: { + driver: ProviderDriverKind.make("codex"), + displayName: "Codex Personal", + environment: [ + { name: "OPENROUTER_API_KEY", value: "", sensitive: true, valueRedacted: true }, + { name: "ANTHROPIC_BASE_URL", value: "https://openrouter.ai/api", sensitive: false }, + ], + config: {}, + }, + }, + }); + + assert.equal( + roundTripped.providerInstances[instanceId]?.environment?.[0]?.value, + "sk-or-secret", + ); + }).pipe(Effect.provide(makeServerSettingsLayer())), + ); }); diff --git a/apps/server/src/serverSettings.ts b/apps/server/src/serverSettings.ts index c2147a0f45..2b9d8a5295 100644 --- a/apps/server/src/serverSettings.ts +++ b/apps/server/src/serverSettings.ts @@ -11,10 +11,15 @@ * @module ServerSettings */ import { + DEFAULT_GIT_TEXT_GENERATION_MODEL, DEFAULT_GIT_TEXT_GENERATION_MODEL_BY_PROVIDER, DEFAULT_SERVER_SETTINGS, + isProviderDriverKind, type ModelSelection, - type ProviderKind, + type ProviderInstanceConfig, + type ProviderInstanceEnvironmentVariable, + ProviderDriverKind, + ProviderInstanceId, ServerSettings, ServerSettingsError, type ServerSettingsPatch, @@ -44,6 +49,47 @@ import { ServerConfig } from "./config.ts"; import { type DeepPartial, deepMerge } from "@t3tools/shared/Struct"; import { fromLenientJson } from "@t3tools/shared/schemaJson"; import { applyServerSettingsPatch } from "@t3tools/shared/serverSettings"; +import { ServerSecretStoreLive } from "./auth/Layers/ServerSecretStore.ts"; +import { ServerSecretStore } from "./auth/Services/ServerSecretStore.ts"; + +const textEncoder = new TextEncoder(); +const textDecoder = new TextDecoder(); + +function providerEnvironmentSecretName(input: { + readonly instanceId: string; + readonly name: string; +}): string { + return `provider-env-${Buffer.from(input.instanceId, "utf8").toString("base64url")}-${Buffer.from(input.name, "utf8").toString("base64url")}`; +} + +function redactProviderEnvironmentVariable( + variable: ProviderInstanceEnvironmentVariable, +): ProviderInstanceEnvironmentVariable { + if (!variable.sensitive) { + const { valueRedacted: _omit, ...rest } = variable; + return rest; + } + return { + ...variable, + value: "", + ...(variable.value.length > 0 || variable.valueRedacted ? { valueRedacted: true } : {}), + }; +} + +export function redactServerSettingsForClient(settings: ServerSettings): ServerSettings { + const providerInstances = Object.fromEntries( + Object.entries(settings.providerInstances).map(([instanceId, instance]) => [ + instanceId, + instance.environment + ? { + ...instance, + environment: instance.environment.map(redactProviderEnvironmentVariable), + } + : instance, + ]), + ); + return { ...settings, providerInstances }; +} export interface ServerSettingsShape { /** Start the settings runtime and attach file watching. */ @@ -106,7 +152,13 @@ export class ServerSettingsService extends Context.Service< const ServerSettingsJson = fromLenientJson(ServerSettings); -const PROVIDER_ORDER: readonly ProviderKind[] = ["codex", "claudeAgent", "opencode", "cursor"]; +type LegacyProviderSettings = ServerSettings["providers"][keyof ServerSettings["providers"]]; + +const getLegacyProviderSettings = ( + settings: ServerSettings, + provider: ProviderDriverKind, +): LegacyProviderSettings | undefined => + (settings.providers as Record)[provider]; /** * Ensure the `textGenerationModelSelection` points to an enabled provider. @@ -116,22 +168,36 @@ const PROVIDER_ORDER: readonly ProviderKind[] = ["codex", "claudeAgent", "openco */ function resolveTextGenerationProvider(settings: ServerSettings): ServerSettings { const selection = settings.textGenerationModelSelection; - if (settings.providers[selection.provider].enabled) { + const instanceConfig = settings.providerInstances[selection.instanceId]; + if (instanceConfig !== undefined) { + return (instanceConfig.enabled ?? true) ? settings : fallbackTextGenerationProvider(settings); + } + + if ( + isProviderDriverKind(selection.instanceId) && + getLegacyProviderSettings(settings, selection.instanceId)?.enabled + ) { return settings; } - const fallback = PROVIDER_ORDER.find((p) => settings.providers[p].enabled); + return fallbackTextGenerationProvider(settings); +} + +function fallbackTextGenerationProvider(settings: ServerSettings): ServerSettings { + const fallbackEntry = Object.entries(settings.providers).find(([, provider]) => provider.enabled); + const fallback = fallbackEntry ? ProviderDriverKind.make(fallbackEntry[0]) : undefined; if (!fallback) { - // No providers enabled — return as-is; callers will report the error. return settings; } return { ...settings, textGenerationModelSelection: { - provider: fallback, - model: DEFAULT_GIT_TEXT_GENERATION_MODEL_BY_PROVIDER[fallback], - } as ModelSelection, + instanceId: ProviderInstanceId.make(fallback), + model: + DEFAULT_GIT_TEXT_GENERATION_MODEL_BY_PROVIDER[fallback] ?? + DEFAULT_GIT_TEXT_GENERATION_MODEL, + } satisfies ModelSelection, }; } @@ -176,6 +242,7 @@ const makeServerSettings = Effect.gen(function* () { const { settingsPath } = yield* ServerConfig; const fs = yield* FileSystem.FileSystem; const pathService = yield* Path.Path; + const secretStore = yield* ServerSecretStore; const writeSemaphore = yield* Semaphore.make(1); const cacheKey = "settings" as const; const changesPubSub = yield* PubSub.unbounded(); @@ -233,6 +300,138 @@ const makeServerSettings = Effect.gen(function* () { const getSettingsFromCache = Cache.get(settingsCache, cacheKey); + const toSettingsError = (detail: string, cause: unknown) => + new ServerSettingsError({ + settingsPath, + detail, + cause, + }); + + const materializeProviderEnvironmentSecrets = ( + settings: ServerSettings, + ): Effect.Effect => + Effect.gen(function* () { + const providerInstances: Record = { + ...settings.providerInstances, + }; + for (const [instanceId, instance] of Object.entries(settings.providerInstances)) { + if (!instance.environment) continue; + const environment: ProviderInstanceEnvironmentVariable[] = []; + for (const variable of instance.environment) { + if (!variable.sensitive || !variable.valueRedacted) { + environment.push(variable); + continue; + } + const secret = yield* secretStore + .get(providerEnvironmentSecretName({ instanceId, name: variable.name })) + .pipe( + Effect.mapError((cause) => + toSettingsError( + `failed to read sensitive environment variable ${variable.name}`, + cause, + ), + ), + ); + environment.push({ + ...variable, + value: secret ? textDecoder.decode(secret) : "", + }); + } + providerInstances[instanceId] = { + ...instance, + environment, + } satisfies ProviderInstanceConfig; + } + return { + ...settings, + providerInstances: providerInstances as ServerSettings["providerInstances"], + }; + }); + + const persistProviderEnvironmentSecrets = ( + current: ServerSettings, + next: ServerSettings, + ): Effect.Effect => + Effect.gen(function* () { + const providerInstances: Record = { + ...next.providerInstances, + }; + + const nextSecretKeys = new Set(); + for (const [instanceId, instance] of Object.entries(next.providerInstances)) { + if (!instance.environment) continue; + const environment: ProviderInstanceEnvironmentVariable[] = []; + for (const variable of instance.environment) { + const secretName = providerEnvironmentSecretName({ instanceId, name: variable.name }); + if (!variable.sensitive) { + yield* secretStore + .remove(secretName) + .pipe( + Effect.mapError((cause) => + toSettingsError(`failed to remove environment secret ${variable.name}`, cause), + ), + ); + environment.push(redactProviderEnvironmentVariable(variable)); + continue; + } + + nextSecretKeys.add(secretName); + if (!variable.valueRedacted) { + if (variable.value.length > 0) { + yield* secretStore + .set(secretName, textEncoder.encode(variable.value)) + .pipe( + Effect.mapError((cause) => + toSettingsError(`failed to persist environment secret ${variable.name}`, cause), + ), + ); + environment.push({ ...variable, value: "", valueRedacted: true }); + } else { + yield* secretStore + .remove(secretName) + .pipe( + Effect.mapError((cause) => + toSettingsError(`failed to remove environment secret ${variable.name}`, cause), + ), + ); + const { valueRedacted: _omit, ...rest } = variable; + environment.push(rest); + } + continue; + } + + environment.push(redactProviderEnvironmentVariable(variable)); + } + providerInstances[instanceId] = { + ...instance, + environment, + } satisfies ProviderInstanceConfig; + } + + for (const [instanceId, instance] of Object.entries(current.providerInstances)) { + for (const variable of instance.environment ?? []) { + if (!variable.sensitive) continue; + const secretName = providerEnvironmentSecretName({ instanceId, name: variable.name }); + if (nextSecretKeys.has(secretName)) continue; + yield* secretStore + .remove(secretName) + .pipe( + Effect.mapError((cause) => + toSettingsError( + `failed to remove stale environment secret ${variable.name}`, + cause, + ), + ), + ); + } + } + + return { + ...next, + providerInstances: providerInstances as ServerSettings["providerInstances"], + }; + }); + const writeSettingsAtomically = (settings: ServerSettings) => { const sparseSettings = stripDefaultServerSettings(settings, DEFAULT_SERVER_SETTINGS) ?? {}; @@ -324,14 +523,19 @@ const makeServerSettings = Effect.gen(function* () { return { start, ready: Deferred.await(startedDeferred), - getSettings: getSettingsFromCache.pipe(Effect.map(resolveTextGenerationProvider)), + getSettings: getSettingsFromCache.pipe( + Effect.flatMap(materializeProviderEnvironmentSecrets), + Effect.map(resolveTextGenerationProvider), + ), updateSettings: (patch) => writeSemaphore.withPermits(1)( Effect.gen(function* () { const current = yield* getSettingsFromCache; - const next = yield* Schema.decodeEffect(ServerSettings)( + const nextPersisted = yield* persistProviderEnvironmentSecrets( + current, applyServerSettingsPatch(current, patch), - ).pipe( + ); + const next = yield* Schema.decodeEffect(ServerSettings)(nextPersisted).pipe( Effect.mapError( (cause) => new ServerSettingsError({ @@ -344,13 +548,27 @@ const makeServerSettings = Effect.gen(function* () { yield* writeSettingsAtomically(next); yield* Cache.set(settingsCache, cacheKey, next); yield* emitChange(next); - return resolveTextGenerationProvider(next); + const materialized = yield* materializeProviderEnvironmentSecrets(next); + return resolveTextGenerationProvider(materialized); }), ), get streamChanges() { - return Stream.fromPubSub(changesPubSub).pipe(Stream.map(resolveTextGenerationProvider)); + return Stream.fromPubSub(changesPubSub).pipe( + Stream.mapEffect((settings) => + materializeProviderEnvironmentSecrets(settings).pipe( + Effect.catch((error: ServerSettingsError) => + Effect.logWarning("failed to materialize provider environment secrets", { + detail: error.detail, + }).pipe(Effect.as(settings)), + ), + ), + ), + Stream.map(resolveTextGenerationProvider), + ); }, } satisfies ServerSettingsShape; }); -export const ServerSettingsLive = Layer.effect(ServerSettingsService, makeServerSettings); +export const ServerSettingsLive = Layer.effect(ServerSettingsService, makeServerSettings).pipe( + Layer.provide(ServerSecretStoreLive), +); diff --git a/apps/server/src/ws.ts b/apps/server/src/ws.ts index aac716cfeb..fd256b32df 100644 --- a/apps/server/src/ws.ts +++ b/apps/server/src/ws.ts @@ -45,7 +45,7 @@ import { import { ProviderRegistry } from "./provider/Services/ProviderRegistry.ts"; import { ServerLifecycleEvents } from "./serverLifecycleEvents.ts"; import { ServerRuntimeStartup } from "./serverRuntimeStartup.ts"; -import { ServerSettingsService } from "./serverSettings.ts"; +import { redactServerSettingsForClient, ServerSettingsService } from "./serverSettings.ts"; import { TerminalManager } from "./terminal/Services/Manager.ts"; import { WorkspaceEntries } from "./workspace/Services/WorkspaceEntries.ts"; import { WorkspaceFileSystem } from "./workspace/Services/WorkspaceFileSystem.ts"; @@ -512,7 +512,7 @@ const makeWsRpcLayer = (currentSessionId: AuthSessionId) => const loadServerConfig = Effect.gen(function* () { const keybindingsConfig = yield* keybindings.loadConfigState; const providers = yield* providerRegistry.getProviders; - const settings = yield* serverSettings.getSettings; + const settings = redactServerSettingsForClient(yield* serverSettings.getSettings); const environment = yield* serverEnvironment.getDescriptor; const auth = yield* serverAuth.getDescriptor(); @@ -749,10 +749,13 @@ const makeWsRpcLayer = (currentSessionId: AuthSessionId) => observeRpcEffect(WS_METHODS.serverGetConfig, loadServerConfig, { "rpc.aggregate": "server", }), - [WS_METHODS.serverRefreshProviders]: (_input) => + [WS_METHODS.serverRefreshProviders]: (input) => observeRpcEffect( WS_METHODS.serverRefreshProviders, - providerRegistry.refresh().pipe(Effect.map((providers) => ({ providers }))), + (input.instanceId !== undefined + ? providerRegistry.refreshInstance(input.instanceId) + : providerRegistry.refresh() + ).pipe(Effect.map((providers) => ({ providers }))), { "rpc.aggregate": "server" }, ), [WS_METHODS.serverUpsertKeybinding]: (rule) => @@ -765,13 +768,21 @@ const makeWsRpcLayer = (currentSessionId: AuthSessionId) => { "rpc.aggregate": "server" }, ), [WS_METHODS.serverGetSettings]: (_input) => - observeRpcEffect(WS_METHODS.serverGetSettings, serverSettings.getSettings, { - "rpc.aggregate": "server", - }), + observeRpcEffect( + WS_METHODS.serverGetSettings, + serverSettings.getSettings.pipe(Effect.map(redactServerSettingsForClient)), + { + "rpc.aggregate": "server", + }, + ), [WS_METHODS.serverUpdateSettings]: ({ patch }) => - observeRpcEffect(WS_METHODS.serverUpdateSettings, serverSettings.updateSettings(patch), { - "rpc.aggregate": "server", - }), + observeRpcEffect( + WS_METHODS.serverUpdateSettings, + serverSettings.updateSettings(patch).pipe(Effect.map(redactServerSettingsForClient)), + { + "rpc.aggregate": "server", + }, + ), [WS_METHODS.projectsSearchEntries]: (input) => observeRpcEffect( WS_METHODS.projectsSearchEntries, @@ -976,6 +987,7 @@ const makeWsRpcLayer = (currentSessionId: AuthSessionId) => Stream.debounce(Duration.millis(PROVIDER_STATUS_DEBOUNCE_MS)), ); const settingsUpdates = serverSettings.streamChanges.pipe( + Stream.map((settings) => redactServerSettingsForClient(settings)), Stream.map((settings) => ({ version: 1 as const, type: "settingsUpdated" as const, @@ -983,13 +995,9 @@ const makeWsRpcLayer = (currentSessionId: AuthSessionId) => })), ); - yield* Effect.all( - [providerRegistry.refresh("codex"), providerRegistry.refresh("claudeAgent")], - { - concurrency: "unbounded", - discard: true, - }, - ).pipe(Effect.ignoreCause({ log: true }), Effect.forkScoped); + yield* providerRegistry + .refresh() + .pipe(Effect.ignoreCause({ log: true }), Effect.forkScoped); const liveUpdates = Stream.merge( keybindingsUpdates, diff --git a/apps/web/src/components/ChatView.browser.tsx b/apps/web/src/components/ChatView.browser.tsx index f5cc79b88a..445fe19305 100644 --- a/apps/web/src/components/ChatView.browser.tsx +++ b/apps/web/src/components/ChatView.browser.tsx @@ -9,6 +9,8 @@ import { type MessageId, type OrchestrationReadModel, type ProjectId, + ProviderDriverKind, + ProviderInstanceId, type ServerConfig, type ServerLifecycleWelcomePayload, type ThreadId, @@ -167,7 +169,8 @@ function createBaseServerConfig(): ServerConfig { issues: [], providers: [ { - provider: "codex", + driver: ProviderDriverKind.make("codex"), + instanceId: ProviderInstanceId.make("codex"), enabled: true, installed: true, version: "0.116.0", @@ -323,7 +326,7 @@ function createSnapshotForTargetUser(options: { title: "Project", workspaceRoot: "/repo/project", defaultModelSelection: { - provider: "codex", + instanceId: ProviderInstanceId.make("codex"), model: "gpt-5", }, scripts: [], @@ -338,7 +341,7 @@ function createSnapshotForTargetUser(options: { projectId: PROJECT_ID, title: THREAD_TITLE, modelSelection: { - provider: "codex", + instanceId: ProviderInstanceId.make("codex"), model: "gpt-5", }, interactionMode: "default", @@ -403,7 +406,7 @@ function addThreadToSnapshot( projectId: PROJECT_ID, title: "New thread", modelSelection: { - provider: "codex", + instanceId: ProviderInstanceId.make("codex"), model: "gpt-5", }, interactionMode: "default", @@ -740,7 +743,7 @@ function createSnapshotWithSecondaryProject(options?: { id: "thread-secondary-project" as ThreadId, projectId: SECOND_PROJECT_ID, title: "Release checklist", - modelSelection: { provider: "codex", model: "gpt-5" }, + modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5" }, interactionMode: "default", runtimeMode: "full-access", branch: "release/docs-portal", @@ -772,7 +775,7 @@ function createSnapshotWithSecondaryProject(options?: { id: ARCHIVED_SECONDARY_THREAD_ID, projectId: SECOND_PROJECT_ID, title: "Archived Docs Notes", - modelSelection: { provider: "codex", model: "gpt-5" }, + modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5" }, interactionMode: "default", runtimeMode: "full-access", branch: "release/docs-archive", @@ -807,7 +810,7 @@ function createSnapshotWithSecondaryProject(options?: { id: SECOND_PROJECT_ID, title: "Docs Portal", workspaceRoot: "/repo/clients/docs-portal", - defaultModelSelection: { provider: "codex", model: "gpt-5" }, + defaultModelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5" }, scripts: [], createdAt: NOW_ISO, updatedAt: NOW_ISO, @@ -884,7 +887,7 @@ function createSnapshotWithPendingUserInput(): OrchestrationReadModel { } function createSnapshotWithPlanFollowUpPrompt(options?: { - modelSelection?: { provider: "codex"; model: string }; + modelSelection?: { instanceId: ProviderInstanceId; model: string }; planMarkdown?: string; }): OrchestrationReadModel { const snapshot = createSnapshotForTargetUser({ @@ -892,7 +895,7 @@ function createSnapshotWithPlanFollowUpPrompt(options?: { targetText: "plan follow-up thread", }); const modelSelection = options?.modelSelection ?? { - provider: "codex" as const, + instanceId: ProviderInstanceId.make("codex"), model: "gpt-5", }; const planMarkdown = @@ -2438,6 +2441,126 @@ describe("ChatView timeline estimator parity (full app)", () => { } }); + it("keeps custom provider instance ids when bootstrapping a local draft thread", async () => { + setDraftThreadWithoutWorktree(); + const openRouterInstanceId = ProviderInstanceId.make("claude_openrouter"); + const openRouterSelection = createModelSelection(openRouterInstanceId, "openai/gpt-5.5"); + useComposerDraftStore.getState().setModelSelection(THREAD_REF, openRouterSelection); + + const mounted = await mountChatView({ + viewport: DEFAULT_VIEWPORT, + snapshot: createDraftOnlySnapshot(), + configureFixture: (nextFixture) => { + nextFixture.serverConfig = { + ...nextFixture.serverConfig, + providers: [ + ...nextFixture.serverConfig.providers, + { + driver: ProviderDriverKind.make("claudeAgent"), + instanceId: ProviderInstanceId.make("claudeAgent"), + enabled: true, + installed: true, + version: "2.1.117", + status: "ready", + auth: { status: "authenticated" }, + checkedAt: NOW_ISO, + models: [ + { + slug: "claude-opus-4-7", + name: "Claude Opus 4.7", + isCustom: false, + capabilities: createModelCapabilities({ optionDescriptors: [] }), + }, + ], + slashCommands: [], + skills: [], + }, + { + driver: ProviderDriverKind.make("claudeAgent"), + instanceId: openRouterInstanceId, + displayName: "Claude OpenRouter", + enabled: true, + installed: true, + version: "2.1.117", + status: "ready", + auth: { status: "authenticated" }, + checkedAt: NOW_ISO, + models: [ + { + slug: "claude-opus-4-7", + name: "Claude Opus 4.7", + isCustom: false, + capabilities: createModelCapabilities({ optionDescriptors: [] }), + }, + ], + slashCommands: [], + skills: [], + }, + ], + settings: { + ...nextFixture.serverConfig.settings, + providerInstances: { + ...nextFixture.serverConfig.settings.providerInstances, + [openRouterInstanceId]: { + driver: ProviderDriverKind.make("claudeAgent"), + displayName: "Claude OpenRouter", + config: { customModels: ["openai/gpt-5.5"] }, + }, + }, + }, + }; + }, + resolveRpc: (body) => { + if (body._tag === ORCHESTRATION_WS_METHODS.dispatchCommand) { + return { + sequence: fixture.snapshot.snapshotSequence + 1, + }; + } + return undefined; + }, + }); + + try { + useComposerDraftStore.getState().setPrompt(THREAD_REF, "Hello there"); + await waitForLayout(); + + const sendButton = await waitForSendButton(); + expect(sendButton.disabled).toBe(false); + sendButton.click(); + + await vi.waitFor( + () => { + const turnStartRequest = wsRequests.find( + (request) => + request._tag === ORCHESTRATION_WS_METHODS.dispatchCommand && + request.type === "thread.turn.start", + ) as + | { + modelSelection?: { instanceId?: string; model?: string }; + bootstrap?: { + createThread?: { + modelSelection?: { instanceId?: string; model?: string }; + }; + }; + } + | undefined; + + expect(turnStartRequest?.modelSelection).toMatchObject({ + instanceId: openRouterInstanceId, + model: "openai/gpt-5.5", + }); + expect(turnStartRequest?.bootstrap?.createThread?.modelSelection).toMatchObject({ + instanceId: openRouterInstanceId, + model: "openai/gpt-5.5", + }); + }, + { timeout: 8_000, interval: 16 }, + ); + } finally { + await mounted.cleanup(); + } + }); + it("keeps new-worktree mode on empty server threads and bootstraps the first send", async () => { const snapshot = addThreadToSnapshot(createDraftOnlySnapshot(), THREAD_ID); const mounted = await mountChatView({ @@ -3778,12 +3901,16 @@ describe("ChatView timeline estimator parity (full app)", () => { it("snapshots sticky codex settings into a new draft thread", async () => { useComposerDraftStore.setState({ stickyModelSelectionByProvider: { - codex: createModelSelection("codex", "gpt-5.3-codex", [ - { id: "reasoningEffort", value: "medium" }, - { id: "fastMode", value: true }, - ]), + [ProviderInstanceId.make("codex")]: createModelSelection( + ProviderInstanceId.make("codex"), + "gpt-5.3-codex", + [ + { id: "reasoningEffort", value: "medium" }, + { id: "fastMode", value: true }, + ], + ), }, - stickyActiveProvider: "codex", + stickyActiveProvider: ProviderInstanceId.make("codex"), }); const mounted = await mountChatView({ @@ -3814,7 +3941,7 @@ describe("ChatView timeline estimator parity (full app)", () => { expect(composerDraftFor(newDraftId)).toMatchObject({ modelSelectionByProvider: { codex: { - provider: "codex", + instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.3-codex", options: expect.arrayContaining([{ id: "fastMode", value: true }]), }, @@ -3829,12 +3956,16 @@ describe("ChatView timeline estimator parity (full app)", () => { it("hydrates the provider alongside a sticky claude model", async () => { useComposerDraftStore.setState({ stickyModelSelectionByProvider: { - claudeAgent: createModelSelection("claudeAgent", "claude-opus-4-6", [ - { id: "effort", value: "max" }, - { id: "fastMode", value: true }, - ]), + [ProviderInstanceId.make("claudeAgent")]: createModelSelection( + ProviderInstanceId.make("claudeAgent"), + "claude-opus-4-6", + [ + { id: "effort", value: "max" }, + { id: "fastMode", value: true }, + ], + ), }, - stickyActiveProvider: "claudeAgent", + stickyActiveProvider: ProviderInstanceId.make("claudeAgent"), }); const mounted = await mountChatView({ @@ -3860,10 +3991,14 @@ describe("ChatView timeline estimator parity (full app)", () => { expect(composerDraftFor(newDraftId)).toMatchObject({ modelSelectionByProvider: { - claudeAgent: createModelSelection("claudeAgent", "claude-opus-4-6", [ - { id: "effort", value: "max" }, - { id: "fastMode", value: true }, - ]), + claudeAgent: createModelSelection( + ProviderInstanceId.make("claudeAgent"), + "claude-opus-4-6", + [ + { id: "effort", value: "max" }, + { id: "fastMode", value: true }, + ], + ), }, activeProvider: "claudeAgent", }); @@ -3903,12 +4038,16 @@ describe("ChatView timeline estimator parity (full app)", () => { it("prefers draft state over sticky composer settings and defaults", async () => { useComposerDraftStore.setState({ stickyModelSelectionByProvider: { - codex: createModelSelection("codex", "gpt-5.3-codex", [ - { id: "reasoningEffort", value: "medium" }, - { id: "fastMode", value: true }, - ]), + [ProviderInstanceId.make("codex")]: createModelSelection( + ProviderInstanceId.make("codex"), + "gpt-5.3-codex", + [ + { id: "reasoningEffort", value: "medium" }, + { id: "fastMode", value: true }, + ], + ), }, - stickyActiveProvider: "codex", + stickyActiveProvider: ProviderInstanceId.make("codex"), }); const mounted = await mountChatView({ @@ -3938,7 +4077,7 @@ describe("ChatView timeline estimator parity (full app)", () => { expect(composerDraftFor(draftId)).toMatchObject({ modelSelectionByProvider: { codex: { - provider: "codex", + instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.3-codex", options: expect.arrayContaining([{ id: "fastMode", value: true }]), }, @@ -3948,7 +4087,7 @@ describe("ChatView timeline estimator parity (full app)", () => { useComposerDraftStore.getState().setModelSelection( draftId, - createModelSelection("codex", "gpt-5.4", [ + createModelSelection(ProviderInstanceId.make("codex"), "gpt-5.4", [ { id: "reasoningEffort", value: "low" }, { id: "fastMode", value: true }, ]), @@ -3963,7 +4102,7 @@ describe("ChatView timeline estimator parity (full app)", () => { ); expect(composerDraftFor(draftId)).toMatchObject({ modelSelectionByProvider: { - codex: createModelSelection("codex", "gpt-5.4", [ + codex: createModelSelection(ProviderInstanceId.make("codex"), "gpt-5.4", [ { id: "reasoningEffort", value: "low" }, { id: "fastMode", value: true }, ]), @@ -5435,7 +5574,10 @@ describe("ChatView timeline estimator parity (full app)", () => { const mounted = await mountChatView({ viewport: WIDE_FOOTER_VIEWPORT, snapshot: createSnapshotWithPlanFollowUpPrompt({ - modelSelection: { provider: "codex", model: "gpt-5.3-codex-spark" }, + modelSelection: { + instanceId: ProviderInstanceId.make("codex"), + model: "gpt-5.3-codex-spark", + }, planMarkdown: "# Imaginary Long-Range Plan: T3 Code Adaptive Orchestration and Safe-Delay Execution Initiative", }), @@ -5465,7 +5607,10 @@ describe("ChatView timeline estimator parity (full app)", () => { const mounted = await mountChatView({ viewport: WIDE_FOOTER_VIEWPORT, snapshot: createSnapshotWithPlanFollowUpPrompt({ - modelSelection: { provider: "codex", model: "gpt-5.3-codex-spark" }, + modelSelection: { + instanceId: ProviderInstanceId.make("codex"), + model: "gpt-5.3-codex-spark", + }, planMarkdown: "# Imaginary Long-Range Plan: T3 Code Adaptive Orchestration and Safe-Delay Execution Initiative", }), @@ -5589,14 +5734,17 @@ describe("ChatView timeline estimator parity (full app)", () => { projects: snapshot.projects.map((project) => project.id === PROJECT_ID ? Object.assign({}, project, { - defaultModelSelection: { provider: "codex", model: "gpt-5.4" }, + defaultModelSelection: { + instanceId: ProviderInstanceId.make("codex"), + model: "gpt-5.4", + }, }) : project, ), threads: snapshot.threads.map((thread) => thread.id === THREAD_ID ? Object.assign({}, thread, { - modelSelection: { provider: "codex", model: "gpt-5.4" }, + modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" }, }) : thread, ), @@ -5647,7 +5795,6 @@ describe("ChatView timeline estimator parity (full app)", () => { providers: [ { ...nextFixture.serverConfig.providers[0]!, - provider: "codex", models: [ { slug: "gpt-5.1-codex-max", diff --git a/apps/web/src/components/ChatView.logic.test.ts b/apps/web/src/components/ChatView.logic.test.ts index ba0a0eddf3..83c90edadd 100644 --- a/apps/web/src/components/ChatView.logic.test.ts +++ b/apps/web/src/components/ChatView.logic.test.ts @@ -1,5 +1,12 @@ import { scopeThreadRef } from "@t3tools/client-runtime"; -import { EnvironmentId, ProjectId, ThreadId, TurnId } from "@t3tools/contracts"; +import { + EnvironmentId, + ProjectId, + ProviderDriverKind, + ProviderInstanceId, + ThreadId, + TurnId, +} from "@t3tools/contracts"; import { afterEach, describe, expect, it, vi } from "vitest"; import { type EnvironmentState, useStore } from "../store"; import { type Thread } from "../types"; @@ -220,7 +227,7 @@ const makeThread = (input?: { codexThreadId: null, projectId: ProjectId.make("project-1"), title: "Thread", - modelSelection: { provider: "codex" as const, model: "gpt-5.4" }, + modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" }, runtimeMode: "full-access" as const, interactionMode: "default" as const, session: null, @@ -253,7 +260,7 @@ function setStoreThreads(threads: ReadonlyArray>) name: "Project", cwd: "/tmp/project", defaultModelSelection: { - provider: "codex", + instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4", }, createdAt: "2026-03-29T00:00:00.000Z", @@ -452,7 +459,7 @@ describe("hasServerAcknowledgedLocalDispatch", () => { }; const previousSession = { - provider: "codex" as const, + provider: ProviderDriverKind.make("codex"), status: "ready" as const, createdAt: "2026-03-29T00:00:00.000Z", updatedAt: "2026-03-29T00:00:10.000Z", @@ -466,7 +473,7 @@ describe("hasServerAcknowledgedLocalDispatch", () => { codexThreadId: null, projectId, title: "Thread", - modelSelection: { provider: "codex", model: "gpt-5.4" }, + modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" }, runtimeMode: "full-access", interactionMode: "default", session: previousSession, @@ -503,7 +510,7 @@ describe("hasServerAcknowledgedLocalDispatch", () => { codexThreadId: null, projectId, title: "Thread", - modelSelection: { provider: "codex", model: "gpt-5.4" }, + modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" }, runtimeMode: "full-access", interactionMode: "default", session: previousSession, @@ -549,7 +556,7 @@ describe("hasServerAcknowledgedLocalDispatch", () => { codexThreadId: null, projectId, title: "Thread", - modelSelection: { provider: "codex", model: "gpt-5.4" }, + modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" }, runtimeMode: "full-access", interactionMode: "default", session: previousSession, @@ -592,7 +599,7 @@ describe("hasServerAcknowledgedLocalDispatch", () => { codexThreadId: null, projectId, title: "Thread", - modelSelection: { provider: "codex", model: "gpt-5.4" }, + modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" }, runtimeMode: "full-access", interactionMode: "default", session: previousSession, @@ -635,7 +642,7 @@ describe("hasServerAcknowledgedLocalDispatch", () => { codexThreadId: null, projectId, title: "Thread", - modelSelection: { provider: "codex", model: "gpt-5.4" }, + modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" }, runtimeMode: "full-access", interactionMode: "default", session: previousSession, @@ -685,7 +692,7 @@ describe("hasServerAcknowledgedLocalDispatch", () => { codexThreadId: null, projectId, title: "Thread", - modelSelection: { provider: "codex", model: "gpt-5.4" }, + modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" }, runtimeMode: "full-access", interactionMode: "default", session: previousSession, diff --git a/apps/web/src/components/ChatView.logic.ts b/apps/web/src/components/ChatView.logic.ts index b77cc7b176..417313ef2c 100644 --- a/apps/web/src/components/ChatView.logic.ts +++ b/apps/web/src/components/ChatView.logic.ts @@ -1,8 +1,9 @@ import { type EnvironmentId, + isProviderDriverKind, ProjectId, type ModelSelection, - type ProviderKind, + type ProviderDriverKind, type ScopedThreadRef, type ThreadId, type TurnId, @@ -226,15 +227,39 @@ export function threadHasStarted(thread: Thread | null | undefined): boolean { ); } +// `threadProvider` is the open branded driver kind carried by the session. +// Unknown driver kinds degrade to `null` (i.e. "unlocked"), which is the safe +// rollback / fork behavior — the routing layer is the right place to surface +// "driver not installed" errors, not the lock state. +// +// `selectedProvider` takes the same open-string shape because the composer +// now tracks the picker selection as a `ProviderInstanceId` (e.g. +// `codex_personal`). Custom instance ids that don't directly match a +// registered driver resolve to `null` here, which matches the existing +// "unknown driver -> unlocked" semantics. Callers that want the lock to track +// a custom instance's underlying driver kind should resolve the instance id +// upstream and pass the correlated kind. export function deriveLockedProvider(input: { thread: Thread | null | undefined; - selectedProvider: ProviderKind | null; - threadProvider: ProviderKind | null; -}): ProviderKind | null { + selectedProvider: string | null; + threadProvider: string | null; +}): ProviderDriverKind | null { if (!threadHasStarted(input.thread)) { return null; } - return input.thread?.session?.provider ?? input.threadProvider ?? input.selectedProvider ?? null; + const sessionProvider = input.thread?.session?.provider ?? null; + if (sessionProvider) { + return sessionProvider; + } + const narrowedThreadProvider = + input.threadProvider && isProviderDriverKind(input.threadProvider) + ? input.threadProvider + : null; + const narrowedSelectedProvider = + input.selectedProvider && isProviderDriverKind(input.selectedProvider) + ? input.selectedProvider + : null; + return narrowedThreadProvider ?? narrowedSelectedProvider ?? null; } export async function waitForStartedServerThread( diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsx index c27afda975..765a2d5f9a 100644 --- a/apps/web/src/components/ChatView.tsx +++ b/apps/web/src/components/ChatView.tsx @@ -1,13 +1,14 @@ import { type ApprovalRequestId, - DEFAULT_MODEL_BY_PROVIDER, + DEFAULT_MODEL, + defaultInstanceIdForDriver, type EnvironmentId, type MessageId, type ModelSelection, type ProjectScript, - type ProviderKind, type ProjectId, type ProviderApprovalDecision, + ProviderInstanceId, type ServerProvider, type ResolvedKeybindingsConfig, type ScopedThreadRef, @@ -16,6 +17,7 @@ import { type KeybindingCommand, OrchestrationThreadActivity, ProviderInteractionMode, + ProviderDriverKind, RuntimeMode, TerminalOpenInput, } from "@t3tools/contracts"; @@ -115,7 +117,7 @@ import { import { newCommandId, newDraftId, newMessageId, newThreadId } from "~/lib/utils"; import { getProviderModelCapabilities, resolveSelectableProvider } from "../providerModels"; import { useSettings } from "../hooks/useSettings"; -import { resolveAppModelSelection } from "../modelSelection"; +import { resolveAppModelSelectionForInstance } from "../modelSelection"; import { isTerminalFocused } from "../lib/terminalFocus"; import { deriveLogicalProjectKeyFromSettings } from "../logicalProject"; import { @@ -302,7 +304,7 @@ function useThreadPlanCatalog(threadIds: readonly ThreadId[]): ThreadPlanCatalog } function formatOutgoingPrompt(params: { - provider: ProviderKind; + provider: ProviderDriverKind; model: string | null; models: ReadonlyArray; effort: string | null; @@ -777,8 +779,8 @@ export default function ChatView(props: ChatViewProps) { threadId, draftThread, fallbackDraftProject?.defaultModelSelection ?? { - provider: "codex", - model: DEFAULT_MODEL_BY_PROVIDER.codex, + instanceId: ProviderInstanceId.make("codex"), + model: DEFAULT_MODEL, }, localDraftError, ) @@ -1031,7 +1033,9 @@ export default function ChatView(props: ChatViewProps) { const selectedProviderByThreadId = composerActiveProvider ?? null; const threadProvider = - activeThread?.modelSelection.provider ?? activeProject?.defaultModelSelection?.provider ?? null; + activeThread?.modelSelection.instanceId ?? + activeProject?.defaultModelSelection?.instanceId ?? + null; const lockedProvider = deriveLockedProvider({ thread: activeThread, selectedProvider: selectedProviderByThreadId, @@ -1051,9 +1055,9 @@ export default function ChatView(props: ChatViewProps) { const providerStatuses = serverConfig?.providers ?? EMPTY_PROVIDERS; const unlockedSelectedProvider = resolveSelectableProvider( providerStatuses, - selectedProviderByThreadId ?? threadProvider ?? "codex", + selectedProviderByThreadId ?? threadProvider ?? ProviderDriverKind.make("codex"), ); - const selectedProvider: ProviderKind = lockedProvider ?? unlockedSelectedProvider; + const selectedProvider: ProviderDriverKind = lockedProvider ?? unlockedSelectedProvider; const phase = derivePhase(activeThread?.session ?? null); const threadActivities = activeThread?.activities ?? EMPTY_ACTIVITIES; const workLogEntries = useMemo( @@ -1425,10 +1429,24 @@ export default function ChatView(props: ChatViewProps) { const gitStatusQuery = useGitStatus({ environmentId, cwd: gitCwd }); const keybindings = useServerKeybindings(); const availableEditors = useServerAvailableEditors(); - const activeProviderStatus = useMemo( - () => providerStatuses.find((status) => status.provider === selectedProvider) ?? null, - [selectedProvider, providerStatuses], - ); + // Prefer an instance-id match so a custom Codex instance (e.g. + // `codex_personal`) surfaces its own status/message in the banner rather + // than the default Codex's. Falls back to first-match-by-kind when no + // saved instance id is available or the instance no longer exists. + const activeProviderInstanceId = + activeThread?.session?.providerInstanceId ?? + activeThread?.modelSelection.instanceId ?? + activeProject?.defaultModelSelection?.instanceId ?? + null; + const activeProviderStatus = useMemo(() => { + if (activeProviderInstanceId) { + return ( + providerStatuses.find((status) => status.instanceId === activeProviderInstanceId) ?? null + ); + } + const defaultInstanceId = defaultInstanceIdForDriver(selectedProvider); + return providerStatuses.find((status) => status.instanceId === defaultInstanceId) ?? null; + }, [activeProviderInstanceId, providerStatuses, selectedProvider]); const activeProjectCwd = activeProject?.cwd ?? null; const activeThreadWorktreePath = activeThread?.worktreePath ?? null; const activeWorkspaceRoot = activeThreadWorktreePath ?? activeProjectCwd ?? undefined; @@ -1945,7 +1963,7 @@ export default function ChatView(props: ChatViewProps) { if ( input.modelSelection !== undefined && (input.modelSelection.model !== serverThread.modelSelection.model || - input.modelSelection.provider !== serverThread.modelSelection.provider || + input.modelSelection.instanceId !== serverThread.modelSelection.instanceId || JSON.stringify(input.modelSelection.options ?? null) !== JSON.stringify(serverThread.modelSelection.options ?? null)) ) { @@ -2559,10 +2577,8 @@ export default function ChatView(props: ChatViewProps) { } const title = truncate(titleSeed); const threadCreateModelSelection = createModelSelection( - ctxSelectedProvider, - ctxSelectedModel || - activeProject.defaultModelSelection?.model || - DEFAULT_MODEL_BY_PROVIDER.codex, + ctxSelectedModelSelection.instanceId, + ctxSelectedModel || activeProject.defaultModelSelection?.model || DEFAULT_MODEL, ctxSelectedModelSelection.options, ); @@ -3128,21 +3144,46 @@ export default function ChatView(props: ChatViewProps) { ]); const onProviderModelSelect = useCallback( - (provider: ProviderKind, model: string) => { + (instanceId: ProviderInstanceId, model: string) => { if (!activeThread) return; - if (lockedProvider !== null && provider !== lockedProvider) { + // Look up the configured instance so model normalization and custom + // model lookup stay scoped to that exact instance. Unknown instance ids + // are rejected by returning early; the server remains authoritative too. + const entry = providerStatuses.find((snapshot) => snapshot.instanceId === instanceId); + const resolvedDriverKind = entry?.driver ?? null; + if ( + lockedProvider !== null && + resolvedDriverKind !== null && + resolvedDriverKind !== lockedProvider + ) { scheduleComposerFocus(); return; } - const resolvedProvider = resolveSelectableProvider(providerStatuses, provider); - const resolvedModel = resolveAppModelSelection( - resolvedProvider, + if (lockedProvider !== null && activeThread.session?.providerInstanceId) { + const currentEntry = providerStatuses.find( + (snapshot) => snapshot.instanceId === activeThread.session?.providerInstanceId, + ); + if ( + currentEntry?.continuation?.groupKey && + entry?.continuation?.groupKey && + currentEntry.continuation.groupKey !== entry.continuation.groupKey + ) { + scheduleComposerFocus(); + return; + } + } + const resolvedModel = resolveAppModelSelectionForInstance( + instanceId, settings, providerStatuses, model, ); + if (!resolvedModel) { + scheduleComposerFocus(); + return; + } const nextModelSelection: ModelSelection = { - provider: resolvedProvider, + instanceId, model: resolvedModel, }; setComposerDraftModelSelection( diff --git a/apps/web/src/components/CommandPalette.logic.test.ts b/apps/web/src/components/CommandPalette.logic.test.ts index a49dadc851..38b44f3f6a 100644 --- a/apps/web/src/components/CommandPalette.logic.test.ts +++ b/apps/web/src/components/CommandPalette.logic.test.ts @@ -1,5 +1,5 @@ import { describe, expect, it, vi } from "vitest"; -import { EnvironmentId, ProjectId, ThreadId } from "@t3tools/contracts"; +import { EnvironmentId, ProjectId, ProviderInstanceId, ThreadId } from "@t3tools/contracts"; import type { Thread } from "../types"; import { buildThreadActionItems, @@ -17,7 +17,7 @@ function makeThread(overrides: Partial = {}): Thread { codexThreadId: null, projectId: PROJECT_ID, title: "Thread", - modelSelection: { provider: "codex", model: "gpt-5" }, + modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5" }, runtimeMode: "full-access", interactionMode: "default", session: null, diff --git a/apps/web/src/components/CommandPalette.tsx b/apps/web/src/components/CommandPalette.tsx index 2b587afc51..050337e438 100644 --- a/apps/web/src/components/CommandPalette.tsx +++ b/apps/web/src/components/CommandPalette.tsx @@ -2,10 +2,11 @@ import { scopeProjectRef, scopeThreadRef } from "@t3tools/client-runtime"; import { - DEFAULT_MODEL_BY_PROVIDER, + DEFAULT_MODEL, type EnvironmentId, type FilesystemBrowseResult, type ProjectId, + ProviderInstanceId, } from "@t3tools/contracts"; import { useQuery, useQueryClient } from "@tanstack/react-query"; import { useNavigate, useParams } from "@tanstack/react-router"; @@ -786,8 +787,8 @@ function OpenCommandPaletteDialog() { workspaceRoot: cwd, createWorkspaceRootIfMissing: true, defaultModelSelection: { - provider: "codex", - model: DEFAULT_MODEL_BY_PROVIDER.codex, + instanceId: ProviderInstanceId.make("codex"), + model: DEFAULT_MODEL, }, createdAt: new Date().toISOString(), }); diff --git a/apps/web/src/components/Icons.tsx b/apps/web/src/components/Icons.tsx index 98bc509a6f..7df7975fb1 100644 --- a/apps/web/src/components/Icons.tsx +++ b/apps/web/src/components/Icons.tsx @@ -588,3 +588,26 @@ export const GithubCopilotIcon: Icon = ({ className, ...props }) => ( ); + +export const ACPRegistryIcon: Icon = ({ className, ...props }) => ( + + + +); + +export const PiAgentIcon: Icon = ({ className, ...props }) => ( + + + + + +); diff --git a/apps/web/src/components/KeybindingsToast.browser.tsx b/apps/web/src/components/KeybindingsToast.browser.tsx index 7eadd4e41b..df1c6ba542 100644 --- a/apps/web/src/components/KeybindingsToast.browser.tsx +++ b/apps/web/src/components/KeybindingsToast.browser.tsx @@ -7,6 +7,8 @@ import { type MessageId, type OrchestrationReadModel, type ProjectId, + ProviderDriverKind, + ProviderInstanceId, type ServerConfig, type ServerLifecycleWelcomePayload, type ThreadId, @@ -72,7 +74,8 @@ function createBaseServerConfig(): ServerConfig { issues: [], providers: [ { - provider: "codex", + driver: ProviderDriverKind.make("codex"), + instanceId: ProviderInstanceId.make("codex"), enabled: true, installed: true, version: "0.116.0", @@ -95,10 +98,25 @@ function createBaseServerConfig(): ServerConfig { ...DEFAULT_SERVER_SETTINGS, enableAssistantStreaming: false, defaultThreadEnvMode: "local" as const, - textGenerationModelSelection: { provider: "codex" as const, model: "gpt-5.4-mini" }, + textGenerationModelSelection: { + instanceId: ProviderInstanceId.make("codex"), + model: "gpt-5.4-mini", + }, providers: { - codex: { enabled: true, binaryPath: "", homePath: "", customModels: [] }, - claudeAgent: { enabled: true, binaryPath: "", customModels: [], launchArgs: "" }, + codex: { + enabled: true, + binaryPath: "", + homePath: "", + shadowHomePath: "", + customModels: [], + }, + claudeAgent: { + enabled: true, + binaryPath: "", + homePath: "", + customModels: [], + launchArgs: "", + }, cursor: { enabled: true, binaryPath: "", apiEndpoint: "", customModels: [] }, opencode: { enabled: true, @@ -121,7 +139,7 @@ function createMinimalSnapshot(): OrchestrationReadModel { title: "Project", workspaceRoot: "/repo/project", defaultModelSelection: { - provider: "codex", + instanceId: ProviderInstanceId.make("codex"), model: "gpt-5", }, scripts: [], @@ -136,7 +154,7 @@ function createMinimalSnapshot(): OrchestrationReadModel { projectId: PROJECT_ID, title: "Test thread", modelSelection: { - provider: "codex", + instanceId: ProviderInstanceId.make("codex"), model: "gpt-5", }, interactionMode: "default", diff --git a/apps/web/src/components/Sidebar.logic.test.ts b/apps/web/src/components/Sidebar.logic.test.ts index f92f2f628c..926c117c1c 100644 --- a/apps/web/src/components/Sidebar.logic.test.ts +++ b/apps/web/src/components/Sidebar.logic.test.ts @@ -1,4 +1,5 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { ProviderDriverKind } from "@t3tools/contracts"; import { createThreadJumpHintVisibilityController, @@ -20,7 +21,13 @@ import { sortProjectsForSidebar, THREAD_JUMP_HINT_SHOW_DELAY_MS, } from "./Sidebar.logic"; -import { EnvironmentId, OrchestrationLatestTurn, ProjectId, ThreadId } from "@t3tools/contracts"; +import { + EnvironmentId, + OrchestrationLatestTurn, + ProjectId, + ProviderInstanceId, + ThreadId, +} from "@t3tools/contracts"; import { DEFAULT_INTERACTION_MODE, DEFAULT_RUNTIME_MODE, @@ -474,7 +481,7 @@ describe("resolveThreadStatusPill", () => { latestTurn: null, lastVisitedAt: undefined, session: { - provider: "codex" as const, + provider: ProviderDriverKind.make("codex"), status: "running" as const, createdAt: "2026-03-09T10:00:00.000Z", updatedAt: "2026-03-09T10:00:00.000Z", @@ -698,7 +705,7 @@ function makeProject(overrides: Partial = {}): Project { name: "Project", cwd: "/tmp/project", defaultModelSelection: { - provider: "codex", + instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4", ...defaultModelSelection, }, @@ -717,7 +724,7 @@ function makeThread(overrides: Partial = {}): Thread { projectId: ProjectId.make("project-1"), title: "Thread", modelSelection: { - provider: "codex", + instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4", ...overrides?.modelSelection, }, diff --git a/apps/web/src/components/chat/ChatComposer.tsx b/apps/web/src/components/chat/ChatComposer.tsx index 3b47b2067c..2b7f62e8af 100644 --- a/apps/web/src/components/chat/ChatComposer.tsx +++ b/apps/web/src/components/chat/ChatComposer.tsx @@ -5,7 +5,6 @@ import type { ProjectEntry, ProviderApprovalDecision, ProviderInteractionMode, - ProviderKind, ResolvedKeybindingsConfig, RuntimeMode, ScopedThreadRef, @@ -14,6 +13,8 @@ import type { TurnId, } from "@t3tools/contracts"; import { + ProviderDriverKind, + ProviderInstanceId, PROVIDER_SEND_TURN_MAX_ATTACHMENTS, PROVIDER_SEND_TURN_MAX_IMAGE_BYTES, } from "@t3tools/contracts"; @@ -95,11 +96,14 @@ import { XIcon, } from "lucide-react"; import { proposedPlanTitle } from "../../proposedPlan"; +import { getProviderInteractionModeToggle } from "../../providerModels"; import { - getProviderInteractionModeToggle, - getProviderModels, - resolveSelectableProvider, -} from "../../providerModels"; + deriveProviderInstanceEntries, + resolveProviderDriverKindForInstanceSelection, + sortProviderInstanceEntries, + type ProviderInstanceEntry, +} from "../../providerInstances"; +import { type AppModelOption, getAppModelOptionsForInstance } from "../../modelSelection"; import type { UnifiedSettings } from "@t3tools/contracts/settings"; import type { SessionPhase, Thread } from "../../types"; import type { PendingUserInputDraftAnswer } from "../../pendingUserInput"; @@ -346,7 +350,7 @@ export interface ChatComposerHandle { selectedPromptEffort: string | null; selectedModelOptionsForDispatch: unknown; selectedModelSelection: ModelSelection; - selectedProvider: ProviderKind; + selectedProvider: ProviderDriverKind; selectedModel: string; selectedProviderModels: ReadonlyArray; }; @@ -406,7 +410,7 @@ export interface ChatComposerProps { interactionMode: ProviderInteractionMode; // Provider / model - lockedProvider: ProviderKind | null; + lockedProvider: ProviderDriverKind | null; providerStatuses: ServerProvider[]; activeProjectDefaultModelSelection: ModelSelection | null | undefined; activeThreadModelSelection: ModelSelection | null | undefined; @@ -449,7 +453,7 @@ export interface ChatComposerProps { cursorAdjacentToMention: boolean, ) => void; - onProviderModelSelect: (provider: ProviderKind, model: string) => void; + onProviderModelSelect: (instanceId: ProviderInstanceId, model: string) => void; toggleInteractionMode: () => void; handleRuntimeModeChange: (mode: RuntimeMode) => void; handleInteractionModeChange: (mode: ProviderInteractionMode) => void; @@ -566,29 +570,134 @@ export const ChatComposer = memo( // ------------------------------------------------------------------ // Model state // ------------------------------------------------------------------ + // Instance-aware projection of the wire provider list. One entry per + // configured instance (default built-in + any custom `providerInstances.*`), + // sorted default-first per driver kind for a stable picker order. + const providerInstanceEntries = useMemo>( + () => sortProviderInstanceEntries(deriveProviderInstanceEntries(providerStatuses)), + [providerStatuses], + ); const selectedProviderByThreadId = composerDraft.activeProvider ?? null; const threadProvider = - activeThreadModelSelection?.provider ?? activeProjectDefaultModelSelection?.provider ?? null; + activeThread?.session?.providerInstanceId ?? + activeThreadModelSelection?.instanceId ?? + activeProjectDefaultModelSelection?.instanceId ?? + null; + const explicitSelectedInstanceId = selectedProviderByThreadId ?? threadProvider; - const unlockedSelectedProvider = resolveSelectableProvider( - providerStatuses, - selectedProviderByThreadId ?? threadProvider ?? "codex", - ); - const selectedProvider: ProviderKind = lockedProvider ?? unlockedSelectedProvider; + const unlockedSelectedProvider = + resolveProviderDriverKindForInstanceSelection( + providerInstanceEntries, + providerStatuses, + explicitSelectedInstanceId, + ) ?? ProviderDriverKind.make("codex"); + const selectedProvider: ProviderDriverKind = lockedProvider ?? unlockedSelectedProvider; + const lockedContinuationGroupKey = useMemo((): string | null => { + if (!lockedProvider || !activeThread) return null; + const lockedInstanceId = + activeThread.session?.providerInstanceId ?? activeThreadModelSelection?.instanceId; + if (!lockedInstanceId) return null; + return ( + providerInstanceEntries.find((entry) => entry.instanceId === lockedInstanceId) + ?.continuationGroupKey ?? null + ); + }, [ + activeThread, + activeThreadModelSelection?.instanceId, + lockedProvider, + providerInstanceEntries, + ]); + + // Resolve which configured instance the composer is currently targeting. + // Priority: + // 1. The composer draft's `activeProvider` — the user's unsaved pick + // from the model picker (must win, otherwise the UI appears to + // ignore picker selections). + // 2. Thread's persisted instance id (server-side saved selection). + // 3. Project default's instance id. + // 4. First enabled entry matching the current driver kind. + // 5. First enabled entry overall / default instance for the kind. + // + const selectedInstanceId = useMemo(() => { + const candidates: Array = [ + composerDraft.activeProvider, + activeThread?.session?.providerInstanceId, + activeThreadModelSelection?.instanceId, + activeProjectDefaultModelSelection?.instanceId, + ]; + for (const candidate of candidates) { + if (!candidate) continue; + const match = providerInstanceEntries.find( + (entry) => entry.instanceId === candidate && entry.enabled, + ); + if (match) { + // When locked to a specific driver kind, ignore persisted instance + // ids from a different kind or continuation group. + if (lockedProvider && match.driverKind !== lockedProvider) continue; + if ( + lockedContinuationGroupKey && + match.continuationGroupKey !== lockedContinuationGroupKey + ) { + continue; + } + return match.instanceId; + } + } + if (explicitSelectedInstanceId) { + return ProviderInstanceId.make(explicitSelectedInstanceId); + } + const byKind = providerInstanceEntries.find( + (entry) => + entry.enabled && + entry.driverKind === selectedProvider && + (!lockedContinuationGroupKey || + entry.continuationGroupKey === lockedContinuationGroupKey), + ); + if (byKind) return byKind.instanceId; + const anyEnabled = providerInstanceEntries.find((entry) => entry.enabled); + return ( + anyEnabled?.instanceId ?? + providerInstanceEntries[0]?.instanceId ?? + activeThreadModelSelection?.instanceId ?? + activeProjectDefaultModelSelection?.instanceId ?? + ProviderInstanceId.make("codex") + ); + }, [ + activeProjectDefaultModelSelection?.instanceId, + activeThread?.session?.providerInstanceId, + activeThreadModelSelection?.instanceId, + composerDraft.activeProvider, + explicitSelectedInstanceId, + lockedContinuationGroupKey, + lockedProvider, + providerInstanceEntries, + selectedProvider, + ]); const { modelOptions: composerModelOptions, selectedModel } = useEffectiveComposerModelState({ threadRef: composerDraftTarget, providers: providerStatuses, selectedProvider, + selectedInstanceId, threadModelSelection: activeThreadModelSelection, projectModelSelection: activeProjectDefaultModelSelection, settings, }); - const selectedProviderModels = getProviderModels(providerStatuses, selectedProvider); + // Resolve the active instance's snapshot by `instanceId` so a custom + // instance gets its own slash commands, skills, and model list — not + // the first snapshot for the same driver kind. + const selectedProviderEntry = useMemo( + () => providerInstanceEntries.find((entry) => entry.instanceId === selectedInstanceId), + [providerInstanceEntries, selectedInstanceId], + ); const selectedProviderStatus = useMemo( - () => providerStatuses.find((provider) => provider.provider === selectedProvider), - [providerStatuses, selectedProvider], + () => selectedProviderEntry?.snapshot ?? null, + [selectedProviderEntry], + ); + const selectedProviderModels = useMemo>( + () => selectedProviderEntry?.models ?? [], + [selectedProviderEntry], ); const composerProviderState = useMemo( @@ -615,29 +724,30 @@ export const ChatComposer = memo( [providerStatuses, selectedProvider], ); const selectedModelSelection = useMemo( - () => createModelSelection(selectedProvider, selectedModel, selectedModelOptionsForDispatch), - [selectedModel, selectedModelOptionsForDispatch, selectedProvider], + () => + createModelSelection(selectedInstanceId, selectedModel, selectedModelOptionsForDispatch), + [selectedInstanceId, selectedModel, selectedModelOptionsForDispatch], ); const selectedModelForPicker = selectedModel; - const modelOptionsByProvider = useMemo< - Record> - >( - () => ({ - codex: providerStatuses.find((provider) => provider.provider === "codex")?.models ?? [], - claudeAgent: - providerStatuses.find((provider) => provider.provider === "claudeAgent")?.models ?? [], - opencode: - providerStatuses.find((provider) => provider.provider === "opencode")?.models ?? [], - cursor: providerStatuses.find((provider) => provider.provider === "cursor")?.models ?? [], - }), - [providerStatuses], - ); + // Instance-keyed option list so the picker can show each configured + // instance (built-in + custom) as a first-class sidebar entry. The + // options are server-reported models plus that exact instance's + // configured custom models; selected slugs are not injected into lists. + const modelOptionsByInstance = useMemo< + ReadonlyMap> + >(() => { + const out = new Map>(); + for (const entry of providerInstanceEntries) { + out.set(entry.instanceId, getAppModelOptionsForInstance(settings, entry)); + } + return out; + }, [providerInstanceEntries, settings]); const selectedModelForPickerWithCustomFallback = useMemo(() => { - const currentOptions = modelOptionsByProvider[selectedProvider]; + const currentOptions = modelOptionsByInstance.get(selectedInstanceId) ?? []; return currentOptions.some((option) => option.slug === selectedModelForPicker) ? selectedModelForPicker : (normalizeModelSlug(selectedModelForPicker, selectedProvider) ?? selectedModelForPicker); - }, [modelOptionsByProvider, selectedModelForPicker, selectedProvider]); + }, [modelOptionsByInstance, selectedInstanceId, selectedModelForPicker, selectedProvider]); // ------------------------------------------------------------------ // Context window @@ -1889,12 +1999,13 @@ export const ChatComposer = memo(
{ setIsComposerModelPickerOpen(open); }} - onProviderModelChange={onProviderModelSelect} + onInstanceModelChange={onProviderModelSelect} /> {isComposerFooterCompact ? ( diff --git a/apps/web/src/components/chat/CompactComposerControlsMenu.browser.tsx b/apps/web/src/components/chat/CompactComposerControlsMenu.browser.tsx index 1808b94033..49eb5fbb94 100644 --- a/apps/web/src/components/chat/CompactComposerControlsMenu.browser.tsx +++ b/apps/web/src/components/chat/CompactComposerControlsMenu.browser.tsx @@ -1,7 +1,10 @@ import { + DEFAULT_MODEL, DEFAULT_MODEL_BY_PROVIDER, EnvironmentId, ModelSelection, + ProviderInstanceId, + ProviderDriverKind, ThreadId, } from "@t3tools/contracts"; import { scopedThreadKey, scopeThreadRef } from "@t3tools/client-runtime"; @@ -50,8 +53,10 @@ async function mountMenu(props?: { modelSelection?: ModelSelection; prompt?: str const threadId = ThreadId.make("thread-compact-menu"); const threadRef = scopeThreadRef(LOCAL_ENVIRONMENT_ID, threadId); const threadKey = scopedThreadKey(threadRef); - const provider = props?.modelSelection?.provider ?? "claudeAgent"; - const model = props?.modelSelection?.model ?? DEFAULT_MODEL_BY_PROVIDER[provider]; + const provider = ProviderDriverKind.make("claudeAgent"); + const instanceId = ProviderInstanceId.make(props?.modelSelection?.instanceId ?? provider); + const model = + props?.modelSelection?.model ?? DEFAULT_MODEL_BY_PROVIDER[provider] ?? DEFAULT_MODEL; useComposerDraftStore.setState({ draftsByThreadKey: { @@ -62,9 +67,9 @@ async function mountMenu(props?: { modelSelection?: ModelSelection; prompt?: str persistedAttachments: [], terminalContexts: [], modelSelectionByProvider: { - [provider]: createModelSelection(provider, model, props?.modelSelection?.options), + [instanceId]: createModelSelection(instanceId, model, props?.modelSelection?.options), }, - activeProvider: provider, + activeProvider: instanceId, runtimeMode: null, interactionMode: null, }, @@ -178,7 +183,10 @@ describe("CompactComposerControlsMenu", () => { it("shows fast mode controls for Opus", async () => { await using _ = await mountMenu({ - modelSelection: createModelSelection("claudeAgent", "claude-opus-4-6"), + modelSelection: createModelSelection( + ProviderInstanceId.make("claudeAgent"), + "claude-opus-4-6", + ), }); await page.getByLabelText("More composer controls").click(); @@ -193,7 +201,10 @@ describe("CompactComposerControlsMenu", () => { it("hides fast mode controls for non-Opus Claude models", async () => { await using _ = await mountMenu({ - modelSelection: createModelSelection("claudeAgent", "claude-sonnet-4-6"), + modelSelection: createModelSelection( + ProviderInstanceId.make("claudeAgent"), + "claude-sonnet-4-6", + ), }); await page.getByLabelText("More composer controls").click(); @@ -205,7 +216,10 @@ describe("CompactComposerControlsMenu", () => { it("shows only the provided effort options", async () => { await using _ = await mountMenu({ - modelSelection: createModelSelection("claudeAgent", "claude-sonnet-4-6"), + modelSelection: createModelSelection( + ProviderInstanceId.make("claudeAgent"), + "claude-sonnet-4-6", + ), }); await page.getByLabelText("More composer controls").click(); @@ -222,9 +236,11 @@ describe("CompactComposerControlsMenu", () => { it("shows a Claude thinking on/off section for Haiku", async () => { await using _ = await mountMenu({ - modelSelection: createModelSelection("claudeAgent", "claude-haiku-4-5", [ - { id: "thinking", value: true }, - ]), + modelSelection: createModelSelection( + ProviderInstanceId.make("claudeAgent"), + "claude-haiku-4-5", + [{ id: "thinking", value: true }], + ), }); await page.getByLabelText("More composer controls").click(); @@ -239,9 +255,11 @@ describe("CompactComposerControlsMenu", () => { it("shows prompt-controlled Ultrathink state with selectable effort controls", async () => { await using _ = await mountMenu({ - modelSelection: createModelSelection("claudeAgent", "claude-opus-4-6", [ - { id: "effort", value: "high" }, - ]), + modelSelection: createModelSelection( + ProviderInstanceId.make("claudeAgent"), + "claude-opus-4-6", + [{ id: "effort", value: "high" }], + ), prompt: "Ultrathink:\nInvestigate this", }); @@ -256,9 +274,11 @@ describe("CompactComposerControlsMenu", () => { it("warns when ultrathink appears in prompt body text", async () => { await using _ = await mountMenu({ - modelSelection: createModelSelection("claudeAgent", "claude-opus-4-6", [ - { id: "effort", value: "high" }, - ]), + modelSelection: createModelSelection( + ProviderInstanceId.make("claudeAgent"), + "claude-opus-4-6", + [{ id: "effort", value: "high" }], + ), prompt: "Ultrathink:\nplease ultrathink about this problem", }); diff --git a/apps/web/src/components/chat/ComposerCommandMenu.tsx b/apps/web/src/components/chat/ComposerCommandMenu.tsx index 5d13e6593b..f687ec7ba2 100644 --- a/apps/web/src/components/chat/ComposerCommandMenu.tsx +++ b/apps/web/src/components/chat/ComposerCommandMenu.tsx @@ -1,6 +1,6 @@ import { type ProjectEntry, - type ProviderKind, + type ProviderDriverKind, type ServerProviderSkill, type ServerProviderSlashCommand, } from "@t3tools/contracts"; @@ -39,7 +39,7 @@ export type ComposerCommandItem = | { id: string; type: "provider-slash-command"; - provider: ProviderKind; + provider: ProviderDriverKind; command: ServerProviderSlashCommand; label: string; description: string; @@ -47,7 +47,7 @@ export type ComposerCommandItem = | { id: string; type: "skill"; - provider: ProviderKind; + provider: ProviderDriverKind; skill: ServerProviderSkill; label: string; description: string; diff --git a/apps/web/src/components/chat/ModelListRow.tsx b/apps/web/src/components/chat/ModelListRow.tsx index 6cd097ad1f..064df338e4 100644 --- a/apps/web/src/components/chat/ModelListRow.tsx +++ b/apps/web/src/components/chat/ModelListRow.tsx @@ -1,9 +1,8 @@ -import { type ProviderKind } from "@t3tools/contracts"; +import { type ProviderDriverKind, type ProviderInstanceId } from "@t3tools/contracts"; import { memo } from "react"; import { StarIcon } from "lucide-react"; import { getDisplayModelName, - getProviderLabel, getTriggerDisplayModelLabel, type ModelEsque, PROVIDER_ICON_BY_PROVIDER, @@ -16,7 +15,17 @@ import { cn } from "~/lib/utils"; export const ModelListRow = memo(function ModelListRow(props: { index: number; model: ModelEsque; - provider: ProviderKind; + /** Instance the model belongs to — the routing key used in combobox values. */ + instanceId: ProviderInstanceId; + /** Driver kind of the instance — used for the provider icon glyph. */ + driverKind: ProviderDriverKind; + /** + * Display name to show in the secondary line (provider footer). Usually + * the instance's configured `displayName` so custom instances like + * "Codex Personal" render with their user-authored label. + */ + providerDisplayName: string; + providerAccentColor?: string | undefined; isFavorite: boolean; showProvider: boolean; preferShortName?: boolean; @@ -25,13 +34,16 @@ export const ModelListRow = memo(function ModelListRow(props: { jumpLabel?: string | null; onToggleFavorite: () => void; }) { - const ProviderIcon = PROVIDER_ICON_BY_PROVIDER[props.provider]; + const ProviderIcon = PROVIDER_ICON_BY_PROVIDER[props.driverKind] ?? null; + const providerLabel = props.model.subProvider + ? `${props.providerDisplayName} · ${props.model.subProvider}` + : props.providerDisplayName; return ( {props.showProvider && (
- + {ProviderIcon ? : null} + {props.providerAccentColor ? ( + + ) : null} - {getProviderLabel(props.provider, props.model)} + {providerLabel}
)} diff --git a/apps/web/src/components/chat/ModelPickerContent.tsx b/apps/web/src/components/chat/ModelPickerContent.tsx index 82720425ef..c3468ef8c6 100644 --- a/apps/web/src/components/chat/ModelPickerContent.tsx +++ b/apps/web/src/components/chat/ModelPickerContent.tsx @@ -1,8 +1,7 @@ import { - type ProviderKind, - PROVIDER_DISPLAY_NAMES, + type ProviderInstanceId, + type ProviderDriverKind, type ResolvedKeybindingsConfig, - type ServerProvider, } from "@t3tools/contracts"; import { resolveSelectableModel } from "@t3tools/shared/model"; import { memo, useMemo, useState, useCallback, useEffect, useLayoutEffect, useRef } from "react"; @@ -22,40 +21,89 @@ import { import { useSettings, useUpdateSettings } from "~/hooks/useSettings"; import { cn } from "~/lib/utils"; import { TooltipProvider } from "../ui/tooltip"; +import type { ProviderInstanceEntry } from "../../providerInstances"; +import { providerModelKey, sortProviderModelItems } from "../../modelOrdering"; type ModelPickerItem = { slug: string; name: string; shortName?: string; subProvider?: string; - provider: ProviderKind; + instanceId: ProviderInstanceId; + driverKind: ProviderDriverKind; + instanceDisplayName: string; + instanceAccentColor?: string | undefined; + continuationGroupKey?: string | undefined; }; const EMPTY_MODEL_JUMP_LABELS = new Map(); +// Split a `${instanceId}:${slug}` combobox key back into its pieces. Slugs +// can contain colons (e.g. some vendor model ids), so we only split on the +// first colon — anything after that is the slug. +function splitInstanceModelKey(key: string): { instanceId: ProviderInstanceId; slug: string } { + const colonIndex = key.indexOf(":"); + if (colonIndex === -1) { + return { instanceId: key as ProviderInstanceId, slug: "" }; + } + return { + instanceId: key.slice(0, colonIndex) as ProviderInstanceId, + slug: key.slice(colonIndex + 1), + }; +} + export const ModelPickerContent = memo(function ModelPickerContent(props: { - provider: ProviderKind; + /** The instance currently selected in the composer (combobox "value"). */ + activeInstanceId: ProviderInstanceId; model: string; - lockedProvider: ProviderKind | null; - providers?: ReadonlyArray; + /** + * When set, the picker is locked to the given driver kind — typically + * because the user is editing a previously-sent message and can't change + * which driver served the turn. Multiple instances of the same kind + * remain selectable (e.g. locked to `codex` still lets the user switch + * between the default Codex and a custom Codex Personal). + */ + lockedProvider: ProviderDriverKind | null; + lockedContinuationGroupKey?: string | null; + /** + * All configured provider instances in display order. Used to render + * the sidebar (one button per instance) and to resolve display names + * for the locked-mode header. + */ + instanceEntries: ReadonlyArray; keybindings?: ResolvedKeybindingsConfig; - modelOptionsByProvider: Record>; + /** + * Model options per instance. Keyed by `ProviderInstanceId` so the + * default Codex instance and any custom Codex instances each have their + * own list (custom instances typically start with the same built-in + * model set but are free to diverge via customModels). + */ + modelOptionsByInstance: ReadonlyMap>; terminalOpen: boolean; onRequestClose?: () => void; - onProviderModelChange: (provider: ProviderKind, model: string) => void; + onInstanceModelChange: (instanceId: ProviderInstanceId, model: string) => void; }) { - const { keybindings: providedKeybindings, modelOptionsByProvider, onProviderModelChange } = props; + const { + keybindings: providedKeybindings, + modelOptionsByInstance, + instanceEntries, + onInstanceModelChange, + } = props; const [searchQuery, setSearchQuery] = useState(""); const searchInputRef = useRef(null); const listRegionRef = useRef(null); const highlightedModelKeyRef = useRef(null); const favorites = useSettings((s) => s.favorites ?? []); - const [selectedProvider, setSelectedProvider] = useState(() => { - if (props.lockedProvider !== null) { - return props.lockedProvider; - } - return favorites.length > 0 ? "favorites" : props.provider; - }); + const [selectedInstanceId, setSelectedInstanceId] = useState( + () => { + if (props.lockedProvider !== null) { + // When locked, prime the sidebar to the currently-active instance + // so jumping into the picker keeps the focused instance visible. + return props.activeInstanceId; + } + return favorites.length > 0 ? "favorites" : props.activeInstanceId; + }, + ); const keybindings = useMemo( () => providedKeybindings ?? [], [providedKeybindings], @@ -66,9 +114,9 @@ export const ModelPickerContent = memo(function ModelPickerContent(props: { searchInputRef.current?.focus({ preventScroll: true }); }, []); - const handleSelectProvider = useCallback( - (provider: ProviderKind | "favorites") => { - setSelectedProvider(provider); + const handleSelectInstance = useCallback( + (instanceId: ProviderInstanceId | "favorites") => { + setSelectedInstanceId(instanceId); window.requestAnimationFrame(() => { focusSearchInput(); }); @@ -90,44 +138,97 @@ export const ModelPickerContent = memo(function ModelPickerContent(props: { }; }, [focusSearchInput]); - // Create a Set for efficient lookup + // Create a Set for efficient lookup. Favorites are keyed by + // `${instanceId}:${slug}`; the storage schema widened from ProviderDriverKind + // to ProviderInstanceId so pre-migration favorites keyed by driver slugs + // (e.g. `"codex:gpt-5"`) still resolve — the default instance id equals + // the driver slug. const favoritesSet = useMemo(() => { - return new Set(favorites.map((fav) => `${fav.provider}:${fav.model}`)); - }, [favorites]); - const favoriteOrder = useMemo(() => { - return new Map( - favorites.map((favorite, index) => [`${favorite.provider}:${favorite.model}`, index]), - ); + return new Set(favorites.map((fav) => providerModelKey(fav.provider, fav.model))); }, [favorites]); - const readyProviderSet = useMemo(() => { - if (!props.providers || props.providers.length === 0) { - return null; - } - return new Set( - props.providers - .filter((provider) => provider.status === "ready") - .map((provider) => provider.provider), - ); - }, [props.providers]); + /** + * Lookup table keyed by `instanceId`. Used for display name + driver + * kind enrichment and for `ready`/enabled filtering before flattening + * models into the search list. + */ + const entryByInstanceId = useMemo( + () => new Map(instanceEntries.map((entry) => [entry.instanceId, entry])), + [instanceEntries], + ); + const matchesLockedProvider = useCallback( + (entry: Pick): boolean => { + if (props.lockedProvider === null) return true; + if (entry.driverKind !== props.lockedProvider) return false; + if (!props.lockedContinuationGroupKey) return true; + return entry.continuationGroupKey === props.lockedContinuationGroupKey; + }, + [props.lockedContinuationGroupKey, props.lockedProvider], + ); - // Flatten models into a searchable array - const flatModels = useMemo(() => { - return Object.entries(props.modelOptionsByProvider).flatMap(([providerKind, models]) => { - if (readyProviderSet && !readyProviderSet.has(providerKind as ProviderKind)) { - return []; + const readyInstanceSet = useMemo(() => { + const ready = new Set(); + for (const entry of instanceEntries) { + if (entry.status === "ready") { + ready.add(entry.instanceId); } - return models.map((m) => ({ - slug: m.slug, - name: m.name, - ...(m.shortName ? { shortName: m.shortName } : {}), - ...(m.subProvider ? { subProvider: m.subProvider } : {}), - provider: providerKind as ProviderKind, - })) satisfies Array; - }); - }, [props.modelOptionsByProvider, readyProviderSet]); + } + return ready; + }, [instanceEntries]); - // Filter models based on search query and selected provider + // Flatten models into a searchable array. One pass over the + // instance-keyed map; each model carries its instance id + driver kind + // so the list row can render the right icon and display name without + // another lookup. + const flatModels = useMemo(() => { + const out: ModelPickerItem[] = []; + for (const [instanceId, models] of modelOptionsByInstance) { + const entry = entryByInstanceId.get(instanceId); + if (!entry) { + // Instance disappeared between renders (configuration change). Skip + // its models — stale options shouldn't appear in the picker. + continue; + } + if (!readyInstanceSet.has(instanceId)) { + continue; + } + for (const model of models) { + out.push({ + slug: model.slug, + name: model.name, + ...(model.shortName ? { shortName: model.shortName } : {}), + ...(model.subProvider ? { subProvider: model.subProvider } : {}), + instanceId, + driverKind: entry.driverKind, + instanceDisplayName: entry.displayName, + ...(entry.accentColor ? { instanceAccentColor: entry.accentColor } : {}), + ...(entry.continuationGroupKey + ? { continuationGroupKey: entry.continuationGroupKey } + : {}), + }); + } + } + return out; + }, [modelOptionsByInstance, entryByInstanceId, readyInstanceSet]); + + const isLocked = props.lockedProvider !== null; + const isSearching = searchQuery.trim().length > 0; + const lockedInstanceEntries = useMemo( + () => + props.lockedProvider ? instanceEntries.filter((entry) => matchesLockedProvider(entry)) : [], + [instanceEntries, matchesLockedProvider, props.lockedProvider], + ); + const showLockedInstanceSidebar = isLocked && lockedInstanceEntries.length > 1; + const showSidebar = !isSearching && (!isLocked || showLockedInstanceSidebar); + const sidebarInstanceEntries = showLockedInstanceSidebar + ? lockedInstanceEntries + : instanceEntries; + const instanceOrder = useMemo( + () => instanceEntries.map((entry) => entry.instanceId), + [instanceEntries], + ); + + // Filter models based on search query and selected instance const filteredModels = useMemo(() => { let result = flatModels; @@ -138,13 +239,23 @@ export const ModelPickerContent = memo(function ModelPickerContent(props: { model, score: scoreModelPickerSearch( { - ...model, - isFavorite: favoritesSet.has(`${model.provider}:${model.slug}`), + name: model.name, + ...(model.shortName ? { shortName: model.shortName } : {}), + ...(model.subProvider ? { subProvider: model.subProvider } : {}), + driverKind: model.driverKind, + providerDisplayName: model.instanceDisplayName, + isFavorite: favoritesSet.has(providerModelKey(model.instanceId, model.slug)), }, searchQuery, ), - isFavorite: favoritesSet.has(`${model.provider}:${model.slug}`), - tieBreaker: buildModelPickerSearchText(model), + isFavorite: favoritesSet.has(providerModelKey(model.instanceId, model.slug)), + tieBreaker: buildModelPickerSearchText({ + name: model.name, + ...(model.shortName ? { shortName: model.shortName } : {}), + ...(model.subProvider ? { subProvider: model.subProvider } : {}), + driverKind: model.driverKind, + providerDisplayName: model.instanceDisplayName, + }), })) .filter( ( @@ -157,10 +268,12 @@ export const ModelPickerContent = memo(function ModelPickerContent(props: { } => rankedModel.score !== null, ); - // When searching, we only respect locked provider, ignoring sidebar selection + // When searching, we only respect locked provider (by driver kind), + // ignoring sidebar selection so account-scoped searches can find a + // model before the user chooses a specific instance rail item. if (props.lockedProvider !== null) { return rankedMatches - .filter((rankedModel) => rankedModel.model.provider === props.lockedProvider) + .filter((rankedModel) => matchesLockedProvider(rankedModel.model)) .toSorted((a, b) => { const scoreDelta = a.score - b.score; if (scoreDelta !== 0) { @@ -188,72 +301,87 @@ export const ModelPickerContent = memo(function ModelPickerContent(props: { .map((rankedModel) => rankedModel.model); } - // Locked provider mode always shows that provider's models, with favorites first. if (props.lockedProvider !== null) { - result = result.filter((m) => m.provider === props.lockedProvider); - } else if (selectedProvider === "favorites") { - result = result.filter((m) => favoritesSet.has(`${m.provider}:${m.slug}`)); + result = result.filter((m) => matchesLockedProvider(m)); + if (showLockedInstanceSidebar) { + result = result.filter((m) => m.instanceId === selectedInstanceId); + } + } else if (selectedInstanceId === "favorites") { + result = result.filter((m) => favoritesSet.has(providerModelKey(m.instanceId, m.slug))); } else { - result = result.filter((m) => m.provider === selectedProvider); + result = result.filter((m) => m.instanceId === selectedInstanceId); } - return result.toSorted((a, b) => { - const aOrder = favoriteOrder.get(`${a.provider}:${a.slug}`); - const bOrder = favoriteOrder.get(`${b.provider}:${b.slug}`); - - if (aOrder !== undefined && bOrder !== undefined) { - return aOrder - bOrder; - } - if (aOrder !== undefined) { - return -1; - } - if (bOrder !== undefined) { - return 1; - } - return 0; + return sortProviderModelItems(result, { + favoriteModelKeys: favoritesSet, + groupFavorites: selectedInstanceId !== "favorites", + instanceOrder: selectedInstanceId === "favorites" ? instanceOrder : [], }); }, [ - favoriteOrder, favoritesSet, flatModels, + instanceOrder, + matchesLockedProvider, props.lockedProvider, searchQuery, - selectedProvider, + showLockedInstanceSidebar, + selectedInstanceId, ]); const handleModelSelect = useCallback( - (modelSlug: string, provider: ProviderKind) => { - const resolvedModel = resolveSelectableModel( - provider, - modelSlug, - modelOptionsByProvider[provider], - ); + (modelSlug: string, instanceId: ProviderInstanceId) => { + const options = modelOptionsByInstance.get(instanceId); + if (!options) { + return; + } + const entry = entryByInstanceId.get(instanceId); + if (!entry) { + return; + } + // `resolveSelectableModel` uses the driver kind for normalization + // (slug casing etc.). Custom instances share their driver's + // normalization rules, so pass the driver kind here. + const resolvedModel = resolveSelectableModel(entry.driverKind, modelSlug, options); if (resolvedModel) { - onProviderModelChange(provider, resolvedModel); + onInstanceModelChange(instanceId, resolvedModel); } }, - [modelOptionsByProvider, onProviderModelChange], + [entryByInstanceId, modelOptionsByInstance, onInstanceModelChange], ); const toggleFavorite = useCallback( - (provider: ProviderKind, model: string) => { + (instanceId: ProviderInstanceId, model: string) => { const newFavorites = [...favorites]; - const index = newFavorites.findIndex((f) => f.provider === provider && f.model === model); + const index = newFavorites.findIndex((f) => f.provider === instanceId && f.model === model); if (index >= 0) { newFavorites.splice(index, 1); } else { - newFavorites.push({ provider, model }); + newFavorites.push({ provider: instanceId, model }); } updateSettings({ favorites: newFavorites }); }, [favorites, updateSettings], ); - const isLocked = props.lockedProvider !== null; - const isSearching = searchQuery.trim().length > 0; - const showSidebar = !isLocked && !isSearching; const LockedProviderIcon = isLocked && props.lockedProvider ? PROVIDER_ICON_BY_PROVIDER[props.lockedProvider] : null; + // Header label for locked mode. Use the active instance's displayName + // when the lock narrows to exactly one instance (so "Codex Personal" + // shows instead of the generic driver label); fall back to the first + // matching entry otherwise. + const lockedHeaderLabel = useMemo(() => { + if (!isLocked || !props.lockedProvider) return null; + const matches = instanceEntries.filter((entry) => matchesLockedProvider(entry)); + if (matches.length === 0) return null; + const active = matches.find((entry) => entry.instanceId === props.activeInstanceId); + return (active ?? matches[0])?.displayName ?? null; + }, [ + isLocked, + matchesLockedProvider, + props.lockedProvider, + props.activeInstanceId, + instanceEntries, + ]); const modelJumpCommandByKey = useMemo(() => { const mapping = new Map< string, @@ -264,7 +392,7 @@ export const ModelPickerContent = memo(function ModelPickerContent(props: { if (!jumpCommand) { return mapping; } - mapping.set(`${model.provider}:${model.slug}`, jumpCommand); + mapping.set(`${model.instanceId}:${model.slug}`, jumpCommand); } return mapping; }, [filteredModels]); @@ -273,16 +401,16 @@ export const ModelPickerContent = memo(function ModelPickerContent(props: { [modelJumpCommandByKey], ); const allModelKeys = useMemo( - (): string[] => flatModels.map((model) => `${model.provider}:${model.slug}`), + (): string[] => flatModels.map((model) => `${model.instanceId}:${model.slug}`), [flatModels], ); const filteredModelKeys = useMemo( - (): string[] => filteredModels.map((model) => `${model.provider}:${model.slug}`), + (): string[] => filteredModels.map((model) => `${model.instanceId}:${model.slug}`), [filteredModels], ); const filteredModelByKey = useMemo( (): ReadonlyMap => - new Map(filteredModels.map((model) => [`${model.provider}:${model.slug}`, model] as const)), + new Map(filteredModels.map((model) => [`${model.instanceId}:${model.slug}`, model] as const)), [filteredModels], ); const modelJumpShortcutContext = useMemo( @@ -331,10 +459,10 @@ export const ModelPickerContent = memo(function ModelPickerContent(props: { if (!targetModelKey) { return; } - const [provider, slug] = targetModelKey.split(":") as [ProviderKind, string]; + const { instanceId, slug } = splitInstanceModelKey(targetModelKey); event.preventDefault(); event.stopPropagation(); - handleModelSelect(slug, provider); + handleModelSelect(slug, instanceId); }; window.addEventListener("keydown", onWindowKeyDown, true); @@ -392,25 +520,25 @@ export const ModelPickerContent = memo(function ModelPickerContent(props: {
{/* Locked provider header (only shown in locked mode) */} - {isLocked && LockedProviderIcon && props.lockedProvider && ( + {isLocked && !showLockedInstanceSidebar && LockedProviderIcon && lockedHeaderLabel && (
- - {PROVIDER_DISPLAY_NAMES[props.lockedProvider]} - + {lockedHeaderLabel}
)} {/* Sidebar (only in unlocked mode) */} {showSidebar && ( )} @@ -422,7 +550,7 @@ export const ModelPickerContent = memo(function ModelPickerContent(props: { filter={null} autoHighlight open - value={`${props.provider}:${props.model}`} + value={`${props.activeInstanceId}:${props.model}`} onItemHighlighted={(modelKey) => { highlightedModelKeyRef.current = typeof modelKey === "string" ? modelKey : null; }} @@ -430,14 +558,14 @@ export const ModelPickerContent = memo(function ModelPickerContent(props: { if (typeof modelKey !== "string") { return; } - const [provider, slug] = modelKey.split(":") as [ProviderKind, string]; - handleModelSelect(slug, provider); + const { instanceId, slug } = splitInstanceModelKey(modelKey); + handleModelSelect(slug, instanceId); }} >
{/* Search bar */} @@ -464,11 +592,10 @@ export const ModelPickerContent = memo(function ModelPickerContent(props: { ).preventBaseUIHandler?.(); e.preventDefault(); e.stopPropagation(); - const [provider, slug] = highlightedModelKeyRef.current.split(":") as [ - ProviderKind, - string, - ]; - handleModelSelect(slug, provider); + const { instanceId, slug } = splitInstanceModelKey( + highlightedModelKeyRef.current, + ); + handleModelSelect(slug, instanceId); return; } e.stopPropagation(); @@ -495,14 +622,17 @@ export const ModelPickerContent = memo(function ModelPickerContent(props: { key={modelKey} index={index} model={model} - provider={model.provider} + instanceId={model.instanceId} + driverKind={model.driverKind} + providerDisplayName={model.instanceDisplayName} + providerAccentColor={model.instanceAccentColor} isFavorite={favoritesSet.has(modelKey)} - showProvider={!isLocked} + showProvider={!isLocked || showLockedInstanceSidebar} preferShortName={!isLocked} - useTriggerLabel={isLocked} - showNewBadge={isModelPickerNewModel(model.provider, model.slug)} + useTriggerLabel={isLocked && !showLockedInstanceSidebar} + showNewBadge={isModelPickerNewModel(model.driverKind, model.slug)} jumpLabel={modelJumpLabelByKey.get(modelKey) ?? null} - onToggleFavorite={() => toggleFavorite(model.provider, model.slug)} + onToggleFavorite={() => toggleFavorite(model.instanceId, model.slug)} /> ); })} diff --git a/apps/web/src/components/chat/ModelPickerSidebar.tsx b/apps/web/src/components/chat/ModelPickerSidebar.tsx index b4f23cacdd..121b5267a3 100644 --- a/apps/web/src/components/chat/ModelPickerSidebar.tsx +++ b/apps/web/src/components/chat/ModelPickerSidebar.tsx @@ -1,28 +1,32 @@ -import { type ProviderKind, type ServerProvider } from "@t3tools/contracts"; -import { memo } from "react"; +import { type ProviderInstanceId } from "@t3tools/contracts"; +import { memo, useMemo } from "react"; import { Clock3Icon, SparklesIcon, StarIcon } from "lucide-react"; import { Gemini, GithubCopilotIcon } from "../Icons"; -import { AVAILABLE_PROVIDER_OPTIONS, PROVIDER_ICON_BY_PROVIDER } from "./providerIconUtils"; +import { ProviderInstanceIcon } from "./ProviderInstanceIcon"; +import { ScrollArea } from "../ui/scroll-area"; import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip"; import { cn } from "~/lib/utils"; -import { getProviderSnapshot } from "../../providerModels"; +import type { ProviderInstanceEntry } from "../../providerInstances"; -function describeUnavailableProvider(label: string, live: ServerProvider | undefined): string { - if (!live) { - return `${label} — waiting for provider status…`; - } - if (live.status === "ready") { +/** + * Build the hover tooltip for an instance button. Mirrors the old + * kind-based copy but uses the entry's configured `displayName` so custom + * instances get their user-authored name (e.g. "Codex Personal — Unavailable."). + */ +function describeUnavailableInstance(entry: ProviderInstanceEntry): string { + const label = entry.displayName; + if (entry.status === "ready") { return label; } const kind = - live.status === "error" + entry.status === "error" ? "Unavailable" - : live.status === "warning" + : entry.status === "warning" ? "Limited" - : live.status === "disabled" + : entry.status === "disabled" ? "Disabled in settings" : "Not ready"; - const msg = live.message?.trim(); + const msg = entry.snapshot.message?.trim(); return msg ? `${label} — ${kind}. ${msg}` : `${label} — ${kind}.`; } @@ -39,172 +43,221 @@ const PICKER_TOOLTIP_SIDE = "left" as const; const PICKER_TOOLTIP_CLASS = "max-w-64 text-balance font-normal leading-snug"; export const ModelPickerSidebar = memo(function ModelPickerSidebar(props: { - selectedProvider: ProviderKind | "favorites"; - onSelectProvider: (provider: ProviderKind | "favorites") => void; - providers?: ReadonlyArray; + selectedInstanceId: ProviderInstanceId | "favorites"; + onSelectInstance: (instanceId: ProviderInstanceId | "favorites") => void; + /** + * Instance entries to render as rail buttons. Each entry becomes one icon + * keyed by `instanceId`, so the default built-in Codex and a user-authored + * `codex_personal` appear as two distinct rail items, each routing to + * their own model list. + */ + instanceEntries: ReadonlyArray; + /** Render the favorites rail entry. Hidden for locked-provider instance switching. */ + showFavorites?: boolean; + /** Render non-configured coming-soon provider entries. Hidden in scoped rails. */ + showComingSoon?: boolean; + /** + * Instance id values that should render the "new" sparkle badge. Callers + * pass the subset of default built-in ids they want flagged (custom + * instances are never flagged — the user just made them). + */ + newBadgeInstanceIds?: ReadonlySet; }) { - const handleProviderClick = (provider: ProviderKind | "favorites") => { - props.onSelectProvider(provider); + const handleSelect = (instanceId: ProviderInstanceId | "favorites") => { + props.onSelectInstance(instanceId); }; + const showFavorites = props.showFavorites ?? true; + const showComingSoon = props.showComingSoon ?? true; + const duplicateDriverCounts = useMemo(() => { + const counts = new Map(); + for (const entry of props.instanceEntries) { + counts.set(entry.driverKind, (counts.get(entry.driverKind) ?? 0) + 1); + } + return counts; + }, [props.instanceEntries]); return ( -
- {/* Favorites section */} -
-
- {props.selectedProvider === "favorites" &&
} - - handleProviderClick("favorites")} - type="button" - data-model-picker-provider="favorites" - aria-label="Favorites" + +
+ {/* Favorites section */} + {showFavorites ? ( +
+
+ {props.selectedInstanceId === "favorites" && ( +
+ )} + + handleSelect("favorites")} + type="button" + data-model-picker-provider="favorites" + aria-label="Favorites" + > + + + } + /> + - - + Favorites + + +
+
+ ) : null} + + {/* Instance buttons (one per configured instance — built-in + custom) */} + {props.instanceEntries.map((entry) => { + const isDisabled = !entry.isAvailable || entry.status !== "ready"; + const isSelected = props.selectedInstanceId === entry.instanceId; + const showNewBadge = props.newBadgeInstanceIds?.has(entry.instanceId) ?? false; + const showInstanceBadge = + Boolean(entry.accentColor) || (duplicateDriverCounts.get(entry.driverKind) ?? 0) > 1; + + const tooltip = isDisabled + ? describeUnavailableInstance(entry) + : showNewBadge + ? `${entry.displayName} — New` + : entry.displayName; + + const button = ( +
-
+ + {showNewBadge ? ( + + + + ) : null} + + ); - {/* Provider buttons */} - {AVAILABLE_PROVIDER_OPTIONS.map((option) => { - const OptionIcon = PROVIDER_ICON_BY_PROVIDER[option.value]; - const liveProvider = props.providers - ? getProviderSnapshot(props.providers, option.value) - : undefined; + const trigger = isDisabled ? ( + {button} + ) : ( + button + ); - const isDisabled = !liveProvider || liveProvider.status !== "ready"; - const isSelected = props.selectedProvider === option.value; - const badge = option.pickerSidebarBadge; + return ( +
+ {isSelected &&
} + + + + {tooltip} + + +
+ ); + })} - const providerTooltip = isDisabled - ? describeUnavailableProvider(option.label, liveProvider) - : badge === "new" - ? `${option.label} — New` - : option.label; - - const button = ( - - ); - - const trigger = isDisabled ? ( - {button} - ) : ( - button - ); - - return ( -
- {isSelected &&
} + {showComingSoon ? ( + <> + {/* Gemini button (coming soon) */} - + + + + } + /> - {providerTooltip} + Gemini — Coming soon -
- ); - })} - - {/* Gemini button (coming soon) */} - - - + + } + /> + - - - - - - - } - /> - - Gemini — Coming soon - - - {/* Github Copilot button (coming soon) */} - - - - - } - /> - - Github Copilot — Coming soon - - -
+ Github Copilot — Coming soon + + + + ) : null} +
+
); }); diff --git a/apps/web/src/components/chat/ProviderInstanceIcon.tsx b/apps/web/src/components/chat/ProviderInstanceIcon.tsx new file mode 100644 index 0000000000..154cada19a --- /dev/null +++ b/apps/web/src/components/chat/ProviderInstanceIcon.tsx @@ -0,0 +1,73 @@ +import { type CSSProperties, memo } from "react"; +import { type ProviderDriverKind } from "@t3tools/contracts"; + +import { PROVIDER_ICON_BY_PROVIDER } from "./providerIconUtils"; +import { cn } from "~/lib/utils"; + +export function providerInstanceInitials(label: string): string { + const words = label.replace(/[_-]+/g, " ").split(/\s+/u).filter(Boolean); + if (words.length === 0) return ""; + if (words.length === 1) return words[0]!.slice(0, 2).toUpperCase(); + return words + .slice(0, 2) + .map((word) => word[0]?.toUpperCase() ?? "") + .join(""); +} + +export const ProviderInstanceIcon = memo(function ProviderInstanceIcon(props: { + driverKind: ProviderDriverKind; + displayName: string; + accentColor?: string | undefined; + showBadge?: boolean; + className?: string; + iconClassName?: string; + badgeClassName?: string; + statusDotClassName?: string; +}) { + const Icon = PROVIDER_ICON_BY_PROVIDER[props.driverKind] ?? null; + const accentStyle = props.accentColor + ? ({ "--provider-accent": props.accentColor } as CSSProperties) + : undefined; + + return ( + + {Icon ? ( + + ) : ( + + {providerInstanceInitials(props.displayName)} + + )} + {props.statusDotClassName ? ( + + ) : null} + {props.showBadge ? ( + + {providerInstanceInitials(props.displayName)} + + ) : null} + + ); +}); diff --git a/apps/web/src/components/chat/ProviderModelPicker.browser.tsx b/apps/web/src/components/chat/ProviderModelPicker.browser.tsx index a5f539ae5a..d3b168876a 100644 --- a/apps/web/src/components/chat/ProviderModelPicker.browser.tsx +++ b/apps/web/src/components/chat/ProviderModelPicker.browser.tsx @@ -1,4 +1,4 @@ -import { type ProviderKind, type ServerProvider } from "@t3tools/contracts"; +import { ProviderDriverKind, ProviderInstanceId, type ServerProvider } from "@t3tools/contracts"; import { EnvironmentId } from "@t3tools/contracts"; import { createModelCapabilities } from "@t3tools/shared/model"; import { page, userEvent } from "vitest/browser"; @@ -6,8 +6,17 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import { render } from "vitest-browser-react"; import { ProviderModelPicker } from "./ProviderModelPicker"; -import { getCustomModelOptionsByProvider } from "../../modelSelection"; -import { DEFAULT_CLIENT_SETTINGS, DEFAULT_UNIFIED_SETTINGS } from "@t3tools/contracts/settings"; +import { getCustomModelOptionsByInstance } from "../../modelSelection"; +import { + deriveProviderInstanceEntries, + sortProviderInstanceEntries, +} from "../../providerInstances"; +import type { ModelEsque } from "./providerIconUtils"; +import { + DEFAULT_CLIENT_SETTINGS, + DEFAULT_UNIFIED_SETTINGS, + type UnifiedSettings, +} from "@t3tools/contracts/settings"; import { __resetLocalApiForTests } from "../../localApi"; // Mock the environments/runtime module to provide a mock primary environment connection @@ -93,7 +102,8 @@ function booleanDescriptor(id: string, label: string) { const TEST_PROVIDERS: ReadonlyArray = [ { - provider: "codex", + driver: ProviderDriverKind.make("codex"), + instanceId: ProviderInstanceId.make("codex"), displayName: "Codex", enabled: true, installed: true, @@ -137,7 +147,8 @@ const TEST_PROVIDERS: ReadonlyArray = [ ], }, { - provider: "claudeAgent", + driver: ProviderDriverKind.make("claudeAgent"), + instanceId: ProviderInstanceId.make("claudeAgent"), displayName: "Claude", enabled: true, installed: true, @@ -199,9 +210,14 @@ const TEST_PROVIDERS: ReadonlyArray = [ }, ]; +const CODEX_INSTANCE_ID = ProviderInstanceId.make("codex"); +const CLAUDE_INSTANCE_ID = ProviderInstanceId.make("claudeAgent"); +const OPENCODE_INSTANCE_ID = ProviderInstanceId.make("opencode"); + function buildCodexProvider(models: ServerProvider["models"]): ServerProvider { return { - provider: "codex", + driver: ProviderDriverKind.make("codex"), + instanceId: ProviderInstanceId.make("codex"), displayName: "Codex", enabled: true, installed: true, @@ -217,7 +233,8 @@ function buildCodexProvider(models: ServerProvider["models"]): ServerProvider { function buildOpenCodeProvider(models: ServerProvider["models"]): ServerProvider { return { - provider: "opencode", + driver: ProviderDriverKind.make("opencode"), + instanceId: ProviderInstanceId.make("opencode"), enabled: true, installed: true, version: "1.0.0", @@ -231,37 +248,47 @@ function buildOpenCodeProvider(models: ServerProvider["models"]): ServerProvider } async function mountPicker(props: { - provider: ProviderKind; + activeInstanceId?: ProviderInstanceId; model: string; - lockedProvider: ProviderKind | null; + lockedProvider: ProviderDriverKind | null; + lockedContinuationGroupKey?: string | null; providers?: ReadonlyArray; + settings?: UnifiedSettings; triggerVariant?: "ghost" | "outline"; }) { const host = document.createElement("div"); document.body.append(host); - const onProviderModelChange = vi.fn(); + const onInstanceModelChange = vi.fn(); const providers = props.providers ?? TEST_PROVIDERS; - const modelOptionsByProvider = getCustomModelOptionsByProvider( - DEFAULT_UNIFIED_SETTINGS, + const instanceEntries = sortProviderInstanceEntries(deriveProviderInstanceEntries(providers)); + const activeInstanceId = props.activeInstanceId ?? CODEX_INSTANCE_ID; + const modelOptionsByInstance = getCustomModelOptionsByInstance( + props.settings ?? DEFAULT_UNIFIED_SETTINGS, providers, - props.provider, + activeInstanceId, props.model, ); const screen = await render( , { container: host }, ); return { - onProviderModelChange, + onInstanceModelChange, + // Back-compat alias used by callers that still assert on the old callback + // name. Delegates to the instance-aware mock so existing expectations work. + get onProviderModelChange() { + return onInstanceModelChange; + }, cleanup: async () => { await screen.unmount(); host.remove(); @@ -304,7 +331,7 @@ describe("ProviderModelPicker", () => { it("shows provider sidebar in unlocked mode", async () => { const mounted = await mountPicker({ - provider: "claudeAgent", + activeInstanceId: CLAUDE_INSTANCE_ID, model: "claude-opus-4-6", lockedProvider: null, }); @@ -325,7 +352,7 @@ describe("ProviderModelPicker", () => { it("shows favorites first in the provider sidebar", async () => { const mounted = await mountPicker({ - provider: "claudeAgent", + activeInstanceId: CLAUDE_INSTANCE_ID, model: "claude-opus-4-6", lockedProvider: null, }); @@ -347,7 +374,7 @@ describe("ProviderModelPicker", () => { it("filters models by selected provider in sidebar", async () => { const mounted = await mountPicker({ - provider: "claudeAgent", + activeInstanceId: CLAUDE_INSTANCE_ID, model: "claude-opus-4-6", lockedProvider: null, }); @@ -379,9 +406,37 @@ describe("ProviderModelPicker", () => { } }); + it("uses client model visibility and ordering preferences", async () => { + const mounted = await mountPicker({ + activeInstanceId: CLAUDE_INSTANCE_ID, + model: "claude-opus-4-6", + lockedProvider: null, + settings: { + ...DEFAULT_UNIFIED_SETTINGS, + providerModelPreferences: { + [CLAUDE_INSTANCE_ID]: { + hiddenModels: ["claude-opus-4-6"], + modelOrder: ["claude-haiku-4-5", "claude-sonnet-4-6"], + }, + }, + }, + }); + + try { + await page.getByRole("button").click(); + + await vi.waitFor(() => { + expect(getVisibleModelNames()).toEqual(["Claude Haiku 4.5", "Claude Sonnet 4.6"]); + expect(getModelPickerListText()).not.toContain("Claude Opus 4.6"); + }); + } finally { + await mounted.cleanup(); + } + }); + it("focuses the search input after selecting a sidebar provider", async () => { const mounted = await mountPicker({ - provider: "claudeAgent", + activeInstanceId: CLAUDE_INSTANCE_ID, model: "claude-opus-4-6", lockedProvider: null, }); @@ -419,9 +474,9 @@ describe("ProviderModelPicker", () => { ); const mounted = await mountPicker({ - provider: "claudeAgent", + activeInstanceId: CLAUDE_INSTANCE_ID, model: "claude-opus-4-6", - lockedProvider: "claudeAgent", + lockedProvider: ProviderDriverKind.make("claudeAgent"), }); try { @@ -443,27 +498,115 @@ describe("ProviderModelPicker", () => { } }); + it("keeps an instance sidebar in locked mode when that provider has multiple instances", async () => { + const defaultCodexModels: ServerProvider["models"] = [ + { + slug: "gpt-work", + name: "GPT Work", + isCustom: false, + capabilities: createModelCapabilities({ optionDescriptors: [] }), + }, + ]; + const personalCodexModels: ServerProvider["models"] = [ + { + slug: "gpt-personal", + name: "GPT Personal", + isCustom: false, + capabilities: createModelCapabilities({ optionDescriptors: [] }), + }, + ]; + const isolatedCodexModels: ServerProvider["models"] = [ + { + slug: "gpt-isolated", + name: "GPT Isolated", + isCustom: false, + capabilities: createModelCapabilities({ optionDescriptors: [] }), + }, + ]; + const providers: ReadonlyArray = [ + { + ...buildCodexProvider(defaultCodexModels), + instanceId: "codex" as ProviderInstanceId, + displayName: "Codex Work", + accentColor: "#2563eb", + continuation: { groupKey: "codex:home:/Users/julius/.codex" }, + }, + { + ...buildCodexProvider(personalCodexModels), + instanceId: "codex_personal" as ProviderInstanceId, + displayName: "Codex Personal", + accentColor: "#dc2626", + continuation: { groupKey: "codex:home:/Users/julius/.codex" }, + }, + { + ...buildCodexProvider(isolatedCodexModels), + instanceId: "codex_isolated" as ProviderInstanceId, + displayName: "Codex Isolated", + accentColor: "#16a34a", + continuation: { groupKey: "codex:home:/Users/julius/.codex_isolated" }, + }, + TEST_PROVIDERS[1]!, + ]; + const mounted = await mountPicker({ + activeInstanceId: "codex" as ProviderInstanceId, + model: "gpt-work", + lockedProvider: ProviderDriverKind.make("codex"), + lockedContinuationGroupKey: "codex:home:/Users/julius/.codex", + providers, + }); + + try { + await page.getByRole("button").click(); + + await vi.waitFor(() => { + expect(getSidebarProviderOrder()).toEqual(["codex", "codex_personal"]); + expect(getModelPickerListText()).not.toContain("Codex Isolated"); + expect( + document.querySelector('[data-model-picker-provider="codex_personal"]') + ?.dataset.providerAccentColor, + ).toBe("#dc2626"); + expect(getModelPickerListText()).toContain("Codex Work"); + expect(getVisibleModelNames()).toEqual(["GPT Work"]); + }); + + await page.getByRole("button", { name: "Codex Personal" }).click(); + + await vi.waitFor(() => { + expect(getModelPickerListText()).toContain("Codex Personal"); + expect(getVisibleModelNames()).toEqual(["GPT Personal"]); + }); + } finally { + await mounted.cleanup(); + } + }); + it("falls back to the active provider's first model when props.model belongs to another provider (#1982)", async () => { const host = document.createElement("div"); document.body.append(host); - const onProviderModelChange = vi.fn(); - const modelOptionsByProvider = { - claudeAgent: [ - { slug: "claude-opus-4-6", name: "Claude Opus 4.6" }, - { slug: "claude-sonnet-4-6", name: "Claude Sonnet 4.6" }, + const onInstanceModelChange = vi.fn(); + const modelOptionsByInstance = new Map>([ + [ + "claudeAgent" as ProviderInstanceId, + [ + { slug: "claude-opus-4-6", name: "Claude Opus 4.6" }, + { slug: "claude-sonnet-4-6", name: "Claude Sonnet 4.6" }, + ], ], - codex: [{ slug: "gpt-5-codex", name: "GPT-5 Codex" }], - cursor: [], - opencode: [], - } as const; + ["codex" as ProviderInstanceId, [{ slug: "gpt-5-codex", name: "GPT-5 Codex" }]], + ["cursor" as ProviderInstanceId, []], + ["opencode" as ProviderInstanceId, []], + ]); + const instanceEntries = sortProviderInstanceEntries( + deriveProviderInstanceEntries(TEST_PROVIDERS), + ); const screen = await render( , { container: host }, ); @@ -504,9 +647,9 @@ describe("ProviderModelPicker", () => { ]), ]; const mounted = await mountPicker({ - provider: "opencode", + activeInstanceId: OPENCODE_INSTANCE_ID, model: "github-copilot/claude-opus-4.5", - lockedProvider: "opencode", + lockedProvider: ProviderDriverKind.make("opencode"), providers, }); @@ -531,7 +674,7 @@ describe("ProviderModelPicker", () => { it("searches models by name in flat list", async () => { const mounted = await mountPicker({ - provider: "claudeAgent", + activeInstanceId: CLAUDE_INSTANCE_ID, model: "claude-opus-4-6", lockedProvider: null, }); @@ -561,9 +704,9 @@ describe("ProviderModelPicker", () => { it("supports arrow-key navigation in the model picker", async () => { const mounted = await mountPicker({ - provider: "claudeAgent", + activeInstanceId: CLAUDE_INSTANCE_ID, model: "claude-opus-4-6", - lockedProvider: "claudeAgent", + lockedProvider: ProviderDriverKind.make("claudeAgent"), }); try { @@ -600,7 +743,7 @@ describe("ProviderModelPicker", () => { it("hides the provider sidebar while searching", async () => { const mounted = await mountPicker({ - provider: "claudeAgent", + activeInstanceId: CLAUDE_INSTANCE_ID, model: "claude-opus-4-6", lockedProvider: null, }); @@ -624,7 +767,7 @@ describe("ProviderModelPicker", () => { it("closes the picker when escape is pressed in search", async () => { const mounted = await mountPicker({ - provider: "claudeAgent", + activeInstanceId: CLAUDE_INSTANCE_ID, model: "claude-opus-4-6", lockedProvider: null, }); @@ -652,7 +795,7 @@ describe("ProviderModelPicker", () => { it("searches models by provider name", async () => { const mounted = await mountPicker({ - provider: "claudeAgent", + activeInstanceId: CLAUDE_INSTANCE_ID, model: "claude-opus-4-6", lockedProvider: null, }); @@ -718,7 +861,7 @@ describe("ProviderModelPicker", () => { ]), ]; const mounted = await mountPicker({ - provider: "opencode", + activeInstanceId: OPENCODE_INSTANCE_ID, model: "github-copilot/claude-opus-4.7", lockedProvider: null, providers, @@ -780,7 +923,7 @@ describe("ProviderModelPicker", () => { }, ]; const mounted = await mountPicker({ - provider: "opencode", + activeInstanceId: OPENCODE_INSTANCE_ID, model: "github-copilot/claude-opus-4.7", lockedProvider: null, providers, @@ -805,7 +948,7 @@ describe("ProviderModelPicker", () => { localStorage.removeItem("t3code:client-settings:v1"); const mounted = await mountPicker({ - provider: "claudeAgent", + activeInstanceId: CLAUDE_INSTANCE_ID, model: "claude-opus-4-6", lockedProvider: null, }); @@ -850,7 +993,7 @@ describe("ProviderModelPicker", () => { localStorage.removeItem("t3code:client-settings:v1"); const mounted = await mountPicker({ - provider: "claudeAgent", + activeInstanceId: CLAUDE_INSTANCE_ID, model: "claude-opus-4-6", lockedProvider: null, }); @@ -890,7 +1033,6 @@ describe("ProviderModelPicker", () => { ); const mounted = await mountPicker({ - provider: "codex", model: "gpt-5-codex", lockedProvider: null, }); @@ -910,9 +1052,9 @@ describe("ProviderModelPicker", () => { it("dispatches callback with correct provider and model when selected", async () => { const mounted = await mountPicker({ - provider: "claudeAgent", + activeInstanceId: CLAUDE_INSTANCE_ID, model: "claude-opus-4-6", - lockedProvider: "claudeAgent", + lockedProvider: ProviderDriverKind.make("claudeAgent"), }); try { @@ -995,7 +1137,6 @@ describe("ProviderModelPicker", () => { ]; const hidden = await mountPicker({ - provider: "codex", model: "gpt-5.3-codex", lockedProvider: null, providers: providersWithoutSpark, @@ -1014,7 +1155,6 @@ describe("ProviderModelPicker", () => { } const visible = await mountPicker({ - provider: "codex", model: "gpt-5.3-codex", lockedProvider: null, providers: providersWithSpark, @@ -1034,7 +1174,7 @@ describe("ProviderModelPicker", () => { it("shows disabled providers grayed out in sidebar", async () => { const disabledProviders = TEST_PROVIDERS.slice(); const claudeIndex = disabledProviders.findIndex( - (provider) => provider.provider === "claudeAgent", + (provider) => provider.instanceId === ProviderInstanceId.make("claudeAgent"), ); if (claudeIndex >= 0) { const claudeProvider = disabledProviders[claudeIndex]!; @@ -1046,7 +1186,6 @@ describe("ProviderModelPicker", () => { } const mounted = await mountPicker({ - provider: "codex", model: "gpt-5-codex", lockedProvider: null, providers: disabledProviders, @@ -1068,7 +1207,6 @@ describe("ProviderModelPicker", () => { it("accepts outline trigger styling", async () => { const mounted = await mountPicker({ - provider: "codex", model: "gpt-5-codex", lockedProvider: null, triggerVariant: "outline", diff --git a/apps/web/src/components/chat/ProviderModelPicker.tsx b/apps/web/src/components/chat/ProviderModelPicker.tsx index 4f4140f834..4a2860ee46 100644 --- a/apps/web/src/components/chat/ProviderModelPicker.tsx +++ b/apps/web/src/components/chat/ProviderModelPicker.tsx @@ -1,9 +1,9 @@ import { - type ProviderKind, + type ProviderInstanceId, + type ProviderDriverKind, type ResolvedKeybindingsConfig, - type ServerProvider, } from "@t3tools/contracts"; -import { memo, useEffect, useState } from "react"; +import { memo, useEffect, useMemo, useState } from "react"; import type { VariantProps } from "class-variance-authority"; import { ChevronDownIcon } from "lucide-react"; import { Button, buttonVariants } from "../ui/button"; @@ -11,21 +11,28 @@ import { Popover, PopoverPopup, PopoverTrigger } from "../ui/popover"; import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip"; import { cn } from "~/lib/utils"; import { ModelPickerContent } from "./ModelPickerContent"; +import { ProviderInstanceIcon } from "./ProviderInstanceIcon"; import { ModelEsque, - PROVIDER_ICON_BY_PROVIDER, getTriggerDisplayModelLabel, getTriggerDisplayModelName, } from "./providerIconUtils"; import { setModelPickerOpen } from "../../modelPickerOpenState"; +import type { ProviderInstanceEntry } from "../../providerInstances"; export const ProviderModelPicker = memo(function ProviderModelPicker(props: { - provider: ProviderKind; + /** + * The instance currently selected in the composer. Drives the trigger + * icon, label and the default-highlighted combobox row. + */ + activeInstanceId: ProviderInstanceId; model: string; - lockedProvider: ProviderKind | null; - providers?: ReadonlyArray; + lockedProvider: ProviderDriverKind | null; + lockedContinuationGroupKey?: string | null; + /** Instance entries rendered in the sidebar + used to resolve display name. */ + instanceEntries: ReadonlyArray; keybindings?: ResolvedKeybindingsConfig; - modelOptionsByProvider: Record>; + modelOptionsByInstance: ReadonlyMap>; activeProviderIconClassName?: string; compact?: boolean; disabled?: boolean; @@ -34,22 +41,36 @@ export const ProviderModelPicker = memo(function ProviderModelPicker(props: { triggerVariant?: VariantProps["variant"]; triggerClassName?: string; onOpenChange?: (open: boolean) => void; - onProviderModelChange: (provider: ProviderKind, model: string) => void; + onInstanceModelChange: (instanceId: ProviderInstanceId, model: string) => void; }) { const [uncontrolledIsMenuOpen, setUncontrolledIsMenuOpen] = useState(false); - const activeProvider = props.lockedProvider ?? props.provider; const isMenuOpen = props.open ?? uncontrolledIsMenuOpen; - const selectedProviderOptions = props.modelOptionsByProvider[activeProvider]; - // If the current slug belongs to a different provider (for example after a provider - // switch or disable), prefer the active provider's first option so the trigger icon - // and label stay in sync instead of showing a stale foreign slug. + + // Resolve the active instance entry by exact routing key. The composer + // resolves fallbacks before rendering this component; if the selected + // instance disappears, do not infer a replacement from its driver kind. + const activeEntry = useMemo(() => { + return ( + props.instanceEntries.find((entry) => entry.instanceId === props.activeInstanceId) ?? null + ); + }, [props.activeInstanceId, props.instanceEntries]); + + const activeInstanceId = props.activeInstanceId; + const selectedInstanceOptions = props.modelOptionsByInstance.get(activeInstanceId) ?? []; + // If the current slug belongs to a different instance (for example after + // a provider switch or disable), prefer the active instance's first + // option so the trigger icon and label stay in sync instead of showing + // a stale foreign slug. const selectedModel = - selectedProviderOptions.find((option) => option.slug === props.model) ?? - selectedProviderOptions[0]; - const ProviderIcon = PROVIDER_ICON_BY_PROVIDER[activeProvider]; + selectedInstanceOptions.find((option) => option.slug === props.model) ?? + selectedInstanceOptions[0]; const triggerTitle = selectedModel ? getTriggerDisplayModelName(selectedModel) : props.model; const triggerSubtitle = selectedModel?.subProvider; const triggerLabel = selectedModel ? getTriggerDisplayModelLabel(selectedModel) : props.model; + const duplicateDriverCount = props.instanceEntries.filter( + (entry) => activeEntry !== null && entry.driverKind === activeEntry.driverKind, + ).length; + const showInstanceBadge = Boolean(activeEntry?.accentColor) || duplicateDriverCount > 1; const setIsMenuOpen = (open: boolean) => { props.onOpenChange?.(open); @@ -65,9 +86,9 @@ export const ProviderModelPicker = memo(function ProviderModelPicker(props: { }; }, [isMenuOpen]); - const handleProviderModelChange = (provider: ProviderKind, model: string) => { + const handleInstanceModelChange = (instanceId: ProviderInstanceId, model: string) => { if (props.disabled) return; - props.onProviderModelChange(provider, model); + props.onInstanceModelChange(instanceId, model); setIsMenuOpen(false); }; @@ -103,10 +124,17 @@ export const ProviderModelPicker = memo(function ProviderModelPicker(props: { props.compact ? "max-w-36 sm:pl-1" : undefined, )} > -