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/29] 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/29] 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/29] 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/29] =?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/29] 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/29] 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/29] `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/29] 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/29] 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/29] 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/29] 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/29] 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/29] 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/29] 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/29] 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/29] 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/29] 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/29] 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/29] 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/29] 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/29] 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/29] 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/29] 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/29] 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/29] 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/29] 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/29] 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/29] 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/29] 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 {