authorgravatar for julius0216@outlook.comJulius Marminge <julius0216@outlook.com> 2026-04-19 21:46:40-07:00
committergravatar for noreply@github.comGitHub <noreply@github.com> 2026-04-19 21:46:40-07:00
log3b98fe3548831c536cf8c22d4b8a63e03e0a7d58
tree8daf7fb9cdcf8f22aa781454bd381b021556217a
parent66c326b8c424ca1e3702232a4fe5a06f6ba2a525
signature Signed by PGP key B5690EEEBB952194

`effect-codex-app-server` (#1942)

Co-authored-by: codex <codex@users.noreply.github.com>

35 files changed, 38106 insertions(+), 5381 deletions(-)

apps/server/package.json+1
...@@ -44,6 +44,7 @@...@@ -44,6 +44,7 @@
44 "@types/bun": "catalog:",44 "@types/bun": "catalog:",
45 "@types/node": "catalog:",45 "@types/node": "catalog:",
46 "effect-acp": "workspace:*",46 "effect-acp": "workspace:*",
47 "effect-codex-app-server": "workspace:*",
47 "tsdown": "catalog:",48 "tsdown": "catalog:",
48 "typescript": "catalog:",49 "typescript": "catalog:",
49 "vitest": "catalog:"50 "vitest": "catalog:"
apps/server/src/codexAppServerManager.test.ts deleted-1218
...@@ -1,1218 +0,0 @@
1import { describe, expect, it, vi } from "vitest";
2import { randomUUID } from "node:crypto";
3import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
4import os from "node:os";
5import path from "node:path";
6import { ApprovalRequestId, ThreadId } from "@t3tools/contracts";
7
8import {
9 buildCodexInitializeParams,
10 CODEX_DEFAULT_MODE_DEVELOPER_INSTRUCTIONS,
11 CODEX_PLAN_MODE_DEVELOPER_INSTRUCTIONS,
12 CodexAppServerManager,
13 classifyCodexStderrLine,
14 isRecoverableThreadResumeError,
15 normalizeCodexModelSlug,
16 readCodexAccountSnapshot,
17 resolveCodexModelForAccount,
18} from "./codexAppServerManager.ts";
19
20const asThreadId = (value: string): ThreadId => ThreadId.make(value);
21
22function createSendTurnHarness() {
23 const manager = new CodexAppServerManager();
24 const context = {
25 session: {
26 provider: "codex",
27 status: "ready",
28 threadId: "thread_1",
29 runtimeMode: "full-access",
30 model: "gpt-5.3-codex",
31 resumeCursor: { threadId: "thread_1" },
32 createdAt: "2026-02-10T00:00:00.000Z",
33 updatedAt: "2026-02-10T00:00:00.000Z",
34 },
35 account: {
36 type: "unknown",
37 planType: null,
38 sparkEnabled: true,
39 },
40 collabReceiverTurns: new Map(),
41 };
42
43 const requireSession = vi
44 .spyOn(
45 manager as unknown as { requireSession: (sessionId: string) => unknown },
46 "requireSession",
47 )
48 .mockReturnValue(context);
49 const sendRequest = vi
50 .spyOn(
51 manager as unknown as { sendRequest: (...args: unknown[]) => Promise<unknown> },
52 "sendRequest",
53 )
54 .mockResolvedValue({
55 turn: {
56 id: "turn_1",
57 },
58 });
59 const updateSession = vi
60 .spyOn(manager as unknown as { updateSession: (...args: unknown[]) => void }, "updateSession")
61 .mockImplementation(() => {});
62
63 return { manager, context, requireSession, sendRequest, updateSession };
64}
65
66function createThreadControlHarness() {
67 const manager = new CodexAppServerManager();
68 const context = {
69 session: {
70 provider: "codex",
71 status: "ready",
72 threadId: "thread_1",
73 runtimeMode: "full-access",
74 model: "gpt-5.3-codex",
75 resumeCursor: { threadId: "thread_1" },
76 createdAt: "2026-02-10T00:00:00.000Z",
77 updatedAt: "2026-02-10T00:00:00.000Z",
78 },
79 collabReceiverTurns: new Map(),
80 };
81
82 const requireSession = vi
83 .spyOn(
84 manager as unknown as { requireSession: (sessionId: string) => unknown },
85 "requireSession",
86 )
87 .mockReturnValue(context);
88 const sendRequest = vi.spyOn(
89 manager as unknown as { sendRequest: (...args: unknown[]) => Promise<unknown> },
90 "sendRequest",
91 );
92 const updateSession = vi
93 .spyOn(manager as unknown as { updateSession: (...args: unknown[]) => void }, "updateSession")
94 .mockImplementation(() => {});
95
96 return { manager, context, requireSession, sendRequest, updateSession };
97}
98
99function createPendingUserInputHarness() {
100 const manager = new CodexAppServerManager();
101 const context = {
102 session: {
103 provider: "codex",
104 status: "ready",
105 threadId: "thread_1",
106 runtimeMode: "full-access",
107 model: "gpt-5.3-codex",
108 resumeCursor: { threadId: "thread_1" },
109 createdAt: "2026-02-10T00:00:00.000Z",
110 updatedAt: "2026-02-10T00:00:00.000Z",
111 },
112 pendingUserInputs: new Map([
113 [
114 ApprovalRequestId.make("req-user-input-1"),
115 {
116 requestId: ApprovalRequestId.make("req-user-input-1"),
117 jsonRpcId: 42,
118 threadId: asThreadId("thread_1"),
119 },
120 ],
121 ]),
122 collabReceiverTurns: new Map(),
123 };
124
125 const requireSession = vi
126 .spyOn(
127 manager as unknown as { requireSession: (sessionId: string) => unknown },
128 "requireSession",
129 )
130 .mockReturnValue(context);
131 const writeMessage = vi
132 .spyOn(manager as unknown as { writeMessage: (...args: unknown[]) => void }, "writeMessage")
133 .mockImplementation(() => {});
134 const emitEvent = vi
135 .spyOn(manager as unknown as { emitEvent: (...args: unknown[]) => void }, "emitEvent")
136 .mockImplementation(() => {});
137
138 return { manager, context, requireSession, writeMessage, emitEvent };
139}
140
141function createCollabNotificationHarness() {
142 const manager = new CodexAppServerManager();
143 const context = {
144 session: {
145 provider: "codex",
146 status: "running",
147 threadId: asThreadId("thread_1"),
148 runtimeMode: "full-access",
149 model: "gpt-5.3-codex",
150 activeTurnId: "turn_parent",
151 resumeCursor: { threadId: "provider_parent" },
152 createdAt: "2026-02-10T00:00:00.000Z",
153 updatedAt: "2026-02-10T00:00:00.000Z",
154 },
155 account: {
156 type: "unknown",
157 planType: null,
158 sparkEnabled: true,
159 },
160 pending: new Map(),
161 pendingApprovals: new Map(),
162 pendingUserInputs: new Map(),
163 collabReceiverTurns: new Map<string, string>(),
164 nextRequestId: 1,
165 stopping: false,
166 };
167
168 const emitEvent = vi
169 .spyOn(manager as unknown as { emitEvent: (...args: unknown[]) => void }, "emitEvent")
170 .mockImplementation(() => {});
171 const updateSession = vi
172 .spyOn(manager as unknown as { updateSession: (...args: unknown[]) => void }, "updateSession")
173 .mockImplementation(() => {});
174
175 return { manager, context, emitEvent, updateSession };
176}
177
178describe("classifyCodexStderrLine", () => {
179 it("ignores empty lines", () => {
180 expect(classifyCodexStderrLine(" ")).toBeNull();
181 });
182
183 it("ignores non-error structured codex logs", () => {
184 const line =
185 "2026-02-08T04:24:19.241256Z WARN codex_core::features: unknown feature key in config: skills";
186 expect(classifyCodexStderrLine(line)).toBeNull();
187 });
188
189 it("ignores known benign rollout path errors", () => {
190 const line =
191 "\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";
192 expect(classifyCodexStderrLine(line)).toBeNull();
193 });
194
195 it("keeps unknown structured errors", () => {
196 const line = "2026-02-08T04:24:20.085687Z ERROR codex_core::runtime: unrecoverable failure";
197 expect(classifyCodexStderrLine(line)).toEqual({
198 message: line,
199 });
200 });
201
202 it("keeps plain stderr messages", () => {
203 const line = "fatal: permission denied";
204 expect(classifyCodexStderrLine(line)).toEqual({
205 message: line,
206 });
207 });
208});
209
210describe("process stderr events", () => {
211 it("emits classified stderr lines as notifications", () => {
212 const manager = new CodexAppServerManager();
213 const emitEvent = vi
214 .spyOn(manager as unknown as { emitEvent: (...args: unknown[]) => void }, "emitEvent")
215 .mockImplementation(() => {});
216
217 (
218 manager as unknown as {
219 emitNotificationEvent: (
220 context: { session: { threadId: ThreadId } },
221 method: string,
222 message: string,
223 ) => void;
224 }
225 ).emitNotificationEvent(
226 {
227 session: {
228 threadId: asThreadId("thread-1"),
229 },
230 },
231 "process/stderr",
232 "fatal: permission denied",
233 );
234
235 expect(emitEvent).toHaveBeenCalledWith(
236 expect.objectContaining({
237 kind: "notification",
238 method: "process/stderr",
239 threadId: "thread-1",
240 message: "fatal: permission denied",
241 }),
242 );
243 });
244});
245
246describe("normalizeCodexModelSlug", () => {
247 it("maps 5.3 aliases to gpt-5.3-codex", () => {
248 expect(normalizeCodexModelSlug("5.3")).toBe("gpt-5.3-codex");
249 expect(normalizeCodexModelSlug("gpt-5.3")).toBe("gpt-5.3-codex");
250 });
251
252 it("prefers codex id when model differs", () => {
253 expect(normalizeCodexModelSlug("gpt-5.3", "gpt-5.3-codex")).toBe("gpt-5.3-codex");
254 });
255
256 it("keeps non-aliased models as-is", () => {
257 expect(normalizeCodexModelSlug("gpt-5.2-codex")).toBe("gpt-5.2-codex");
258 expect(normalizeCodexModelSlug("gpt-5.2")).toBe("gpt-5.2");
259 });
260});
261
262describe("isRecoverableThreadResumeError", () => {
263 it("matches not-found resume errors", () => {
264 expect(
265 isRecoverableThreadResumeError(new Error("thread/resume failed: thread not found")),
266 ).toBe(true);
267 });
268
269 it("ignores non-resume errors", () => {
270 expect(
271 isRecoverableThreadResumeError(new Error("thread/start failed: permission denied")),
272 ).toBe(false);
273 });
274
275 it("ignores non-recoverable resume errors", () => {
276 expect(
277 isRecoverableThreadResumeError(
278 new Error("thread/resume failed: timed out waiting for server"),
279 ),
280 ).toBe(false);
281 });
282});
283
284describe("readCodexAccountSnapshot", () => {
285 it("disables spark for chatgpt plus accounts", () => {
286 expect(
287 readCodexAccountSnapshot({
288 type: "chatgpt",
289 email: "plus@example.com",
290 planType: "plus",
291 }),
292 ).toEqual({
293 type: "chatgpt",
294 planType: "plus",
295 sparkEnabled: false,
296 });
297 });
298
299 it("keeps spark enabled for chatgpt pro accounts", () => {
300 expect(
301 readCodexAccountSnapshot({
302 type: "chatgpt",
303 email: "pro@example.com",
304 planType: "pro",
305 }),
306 ).toEqual({
307 type: "chatgpt",
308 planType: "pro",
309 sparkEnabled: true,
310 });
311 });
312
313 it("disables spark for api key accounts", () => {
314 expect(
315 readCodexAccountSnapshot({
316 type: "apiKey",
317 }),
318 ).toEqual({
319 type: "apiKey",
320 planType: null,
321 sparkEnabled: false,
322 });
323 });
324
325 it("disables spark for unknown chatgpt plans", () => {
326 expect(
327 readCodexAccountSnapshot({
328 type: "chatgpt",
329 email: "unknown@example.com",
330 }),
331 ).toEqual({
332 type: "chatgpt",
333 planType: "unknown",
334 sparkEnabled: false,
335 });
336 });
337});
338
339describe("resolveCodexModelForAccount", () => {
340 it("falls back from spark to default for unsupported chatgpt plans", () => {
341 expect(
342 resolveCodexModelForAccount("gpt-5.3-codex-spark", {
343 type: "chatgpt",
344 planType: "plus",
345 sparkEnabled: false,
346 }),
347 ).toBe("gpt-5.3-codex");
348 });
349
350 it("keeps spark for supported plans", () => {
351 expect(
352 resolveCodexModelForAccount("gpt-5.3-codex-spark", {
353 type: "chatgpt",
354 planType: "pro",
355 sparkEnabled: true,
356 }),
357 ).toBe("gpt-5.3-codex-spark");
358 });
359
360 it("falls back from spark to default for api key auth", () => {
361 expect(
362 resolveCodexModelForAccount("gpt-5.3-codex-spark", {
363 type: "apiKey",
364 planType: null,
365 sparkEnabled: false,
366 }),
367 ).toBe("gpt-5.3-codex");
368 });
369});
370
371describe("startSession", () => {
372 it("enables Codex experimental api capabilities during initialize", () => {
373 expect(buildCodexInitializeParams()).toEqual({
374 clientInfo: {
375 name: "t3code_desktop",
376 title: "T3 Code Desktop",
377 version: "0.1.0",
378 },
379 capabilities: {
380 experimentalApi: true,
381 },
382 });
383 });
384
385 it("emits session/startFailed when resolving cwd throws before process launch", async () => {
386 const manager = new CodexAppServerManager();
387 const events: Array<{ method: string; kind: string; message?: string }> = [];
388 manager.on("event", (event) => {
389 events.push({
390 method: event.method,
391 kind: event.kind,
392 ...(event.message ? { message: event.message } : {}),
393 });
394 });
395
396 const processCwd = vi.spyOn(process, "cwd").mockImplementation(() => {
397 throw new Error("cwd missing");
398 });
399 try {
400 await expect(
401 manager.startSession({
402 threadId: asThreadId("thread-1"),
403 provider: "codex",
404 binaryPath: "codex",
405 runtimeMode: "full-access",
406 }),
407 ).rejects.toThrow("cwd missing");
408 expect(events).toHaveLength(1);
409 expect(events[0]).toEqual({
410 method: "session/startFailed",
411 kind: "error",
412 message: "cwd missing",
413 });
414 } finally {
415 processCwd.mockRestore();
416 manager.stopAll();
417 }
418 });
419
420 it("fails fast with an upgrade message when codex is below the minimum supported version", async () => {
421 const manager = new CodexAppServerManager();
422 const events: Array<{ method: string; kind: string; message?: string }> = [];
423 manager.on("event", (event) => {
424 events.push({
425 method: event.method,
426 kind: event.kind,
427 ...(event.message ? { message: event.message } : {}),
428 });
429 });
430
431 const versionCheck = vi
432 .spyOn(
433 manager as unknown as {
434 assertSupportedCodexCliVersion: (input: {
435 binaryPath: string;
436 cwd: string;
437 homePath?: string;
438 }) => void;
439 },
440 "assertSupportedCodexCliVersion",
441 )
442 .mockImplementation(() => {
443 throw new Error(
444 "Codex CLI v0.36.0 is too old for T3 Code. Upgrade to v0.37.0 or newer and restart T3 Code.",
445 );
446 });
447
448 try {
449 await expect(
450 manager.startSession({
451 threadId: asThreadId("thread-1"),
452 provider: "codex",
453 binaryPath: "codex",
454 runtimeMode: "full-access",
455 }),
456 ).rejects.toThrow(
457 "Codex CLI v0.36.0 is too old for T3 Code. Upgrade to v0.37.0 or newer and restart T3 Code.",
458 );
459 expect(versionCheck).toHaveBeenCalledTimes(1);
460 expect(events).toEqual([
461 {
462 method: "session/startFailed",
463 kind: "error",
464 message:
465 "Codex CLI v0.36.0 is too old for T3 Code. Upgrade to v0.37.0 or newer and restart T3 Code.",
466 },
467 ]);
468 } finally {
469 versionCheck.mockRestore();
470 manager.stopAll();
471 }
472 });
473
474 it("disposes an existing session before starting a replacement for the same thread", async () => {
475 const manager = new CodexAppServerManager();
476 const existingContext = {
477 session: {
478 provider: "codex",
479 status: "ready",
480 threadId: asThreadId("thread-1"),
481 runtimeMode: "full-access",
482 createdAt: "2026-02-10T00:00:00.000Z",
483 updatedAt: "2026-02-10T00:00:00.000Z",
484 },
485 };
486
487 (
488 manager as unknown as {
489 sessions: Map<ThreadId, typeof existingContext>;
490 }
491 ).sessions.set(asThreadId("thread-1"), existingContext);
492
493 const disposeSession = vi
494 .spyOn(
495 manager as unknown as {
496 disposeSession: (
497 context: typeof existingContext,
498 options?: { readonly emitLifecycleEvent?: boolean },
499 ) => void;
500 },
501 "disposeSession",
502 )
503 .mockImplementation(() => {});
504 const assertSupportedCodexCliVersion = vi
505 .spyOn(
506 manager as unknown as {
507 assertSupportedCodexCliVersion: (input: {
508 binaryPath: string;
509 cwd: string;
510 homePath?: string;
511 }) => void;
512 },
513 "assertSupportedCodexCliVersion",
514 )
515 .mockImplementation(() => {});
516 const processCwd = vi.spyOn(process, "cwd").mockImplementation(() => {
517 throw new Error("cwd missing");
518 });
519
520 try {
521 await expect(
522 manager.startSession({
523 threadId: asThreadId("thread-1"),
524 provider: "codex",
525 binaryPath: "codex",
526 runtimeMode: "full-access",
527 }),
528 ).rejects.toThrow("cwd missing");
529
530 expect(disposeSession).toHaveBeenCalledWith(existingContext, {
531 emitLifecycleEvent: false,
532 });
533 expect(assertSupportedCodexCliVersion).not.toHaveBeenCalled();
534 } finally {
535 disposeSession.mockRestore();
536 assertSupportedCodexCliVersion.mockRestore();
537 processCwd.mockRestore();
538 (
539 manager as unknown as {
540 sessions: Map<ThreadId, typeof existingContext>;
541 }
542 ).sessions.clear();
543 manager.stopAll();
544 }
545 });
546
547 it("continues replacement start when existing session disposal fails", async () => {
548 const manager = new CodexAppServerManager();
549 const existingContext = {
550 session: {
551 provider: "codex",
552 status: "ready",
553 threadId: asThreadId("thread-1"),
554 runtimeMode: "full-access",
555 createdAt: "2026-02-10T00:00:00.000Z",
556 updatedAt: "2026-02-10T00:00:00.000Z",
557 },
558 };
559
560 (
561 manager as unknown as {
562 sessions: Map<ThreadId, typeof existingContext>;
563 }
564 ).sessions.set(asThreadId("thread-1"), existingContext);
565
566 const disposeSession = vi
567 .spyOn(
568 manager as unknown as {
569 disposeSession: (
570 context: typeof existingContext,
571 options?: { readonly emitLifecycleEvent?: boolean },
572 ) => void;
573 },
574 "disposeSession",
575 )
576 .mockImplementation(() => {
577 throw new Error("dispose failed");
578 });
579 const assertSupportedCodexCliVersion = vi
580 .spyOn(
581 manager as unknown as {
582 assertSupportedCodexCliVersion: (input: {
583 binaryPath: string;
584 cwd: string;
585 homePath?: string;
586 }) => void;
587 },
588 "assertSupportedCodexCliVersion",
589 )
590 .mockImplementation(() => {});
591 const processCwd = vi.spyOn(process, "cwd").mockImplementation(() => {
592 throw new Error("cwd missing");
593 });
594
595 try {
596 await expect(
597 manager.startSession({
598 threadId: asThreadId("thread-1"),
599 provider: "codex",
600 binaryPath: "codex",
601 runtimeMode: "full-access",
602 }),
603 ).rejects.toThrow("cwd missing");
604
605 expect(disposeSession).toHaveBeenCalledWith(existingContext, {
606 emitLifecycleEvent: false,
607 });
608 expect(assertSupportedCodexCliVersion).not.toHaveBeenCalled();
609 } finally {
610 disposeSession.mockRestore();
611 assertSupportedCodexCliVersion.mockRestore();
612 processCwd.mockRestore();
613 (
614 manager as unknown as {
615 sessions: Map<ThreadId, typeof existingContext>;
616 }
617 ).sessions.clear();
618 manager.stopAll();
619 }
620 });
621});
622
623describe("sendTurn", () => {
624 it("sends text and image user input items to turn/start", async () => {
625 const { manager, context, requireSession, sendRequest, updateSession } =
626 createSendTurnHarness();
627
628 const result = await manager.sendTurn({
629 threadId: asThreadId("thread_1"),
630 input: "Inspect this image",
631 attachments: [
632 {
633 type: "image",
634 url: "data:image/png;base64,AAAA",
635 },
636 ],
637 model: "gpt-5.3",
638 serviceTier: "fast",
639 effort: "high",
640 });
641
642 expect(result).toEqual({
643 threadId: "thread_1",
644 turnId: "turn_1",
645 resumeCursor: { threadId: "thread_1" },
646 });
647 expect(requireSession).toHaveBeenCalledWith("thread_1");
648 expect(sendRequest).toHaveBeenCalledWith(context, "turn/start", {
649 threadId: "thread_1",
650 input: [
651 {
652 type: "text",
653 text: "Inspect this image",
654 text_elements: [],
655 },
656 {
657 type: "image",
658 url: "data:image/png;base64,AAAA",
659 },
660 ],
661 model: "gpt-5.3-codex",
662 serviceTier: "fast",
663 effort: "high",
664 });
665 expect(updateSession).toHaveBeenCalledWith(context, {
666 status: "running",
667 activeTurnId: "turn_1",
668 resumeCursor: { threadId: "thread_1" },
669 });
670 });
671
672 it("supports image-only turns", async () => {
673 const { manager, context, sendRequest } = createSendTurnHarness();
674
675 await manager.sendTurn({
676 threadId: asThreadId("thread_1"),
677 attachments: [
678 {
679 type: "image",
680 url: "data:image/png;base64,BBBB",
681 },
682 ],
683 });
684
685 expect(sendRequest).toHaveBeenCalledWith(context, "turn/start", {
686 threadId: "thread_1",
687 input: [
688 {
689 type: "image",
690 url: "data:image/png;base64,BBBB",
691 },
692 ],
693 model: "gpt-5.3-codex",
694 });
695 });
696
697 it("passes Codex plan mode as a collaboration preset on turn/start", async () => {
698 const { manager, context, sendRequest } = createSendTurnHarness();
699
700 await manager.sendTurn({
701 threadId: asThreadId("thread_1"),
702 input: "Plan the work",
703 interactionMode: "plan",
704 });
705
706 expect(sendRequest).toHaveBeenCalledWith(context, "turn/start", {
707 threadId: "thread_1",
708 input: [
709 {
710 type: "text",
711 text: "Plan the work",
712 text_elements: [],
713 },
714 ],
715 model: "gpt-5.3-codex",
716 collaborationMode: {
717 mode: "plan",
718 settings: {
719 model: "gpt-5.3-codex",
720 reasoning_effort: "medium",
721 developer_instructions: CODEX_PLAN_MODE_DEVELOPER_INSTRUCTIONS,
722 },
723 },
724 });
725 });
726
727 it("passes Codex default mode as a collaboration preset on turn/start", async () => {
728 const { manager, context, sendRequest } = createSendTurnHarness();
729
730 await manager.sendTurn({
731 threadId: asThreadId("thread_1"),
732 input: "PLEASE IMPLEMENT THIS PLAN:\n- step 1",
733 interactionMode: "default",
734 });
735
736 expect(sendRequest).toHaveBeenCalledWith(context, "turn/start", {
737 threadId: "thread_1",
738 input: [
739 {
740 type: "text",
741 text: "PLEASE IMPLEMENT THIS PLAN:\n- step 1",
742 text_elements: [],
743 },
744 ],
745 model: "gpt-5.3-codex",
746 collaborationMode: {
747 mode: "default",
748 settings: {
749 model: "gpt-5.3-codex",
750 reasoning_effort: "medium",
751 developer_instructions: CODEX_DEFAULT_MODE_DEVELOPER_INSTRUCTIONS,
752 },
753 },
754 });
755 });
756
757 it("keeps the session model when interaction mode is set without an explicit model", async () => {
758 const { manager, context, sendRequest } = createSendTurnHarness();
759 context.session.model = "gpt-5.2-codex";
760
761 await manager.sendTurn({
762 threadId: asThreadId("thread_1"),
763 input: "Plan this with my current session model",
764 interactionMode: "plan",
765 });
766
767 expect(sendRequest).toHaveBeenCalledWith(context, "turn/start", {
768 threadId: "thread_1",
769 input: [
770 {
771 type: "text",
772 text: "Plan this with my current session model",
773 text_elements: [],
774 },
775 ],
776 model: "gpt-5.2-codex",
777 collaborationMode: {
778 mode: "plan",
779 settings: {
780 model: "gpt-5.2-codex",
781 reasoning_effort: "medium",
782 developer_instructions: CODEX_PLAN_MODE_DEVELOPER_INSTRUCTIONS,
783 },
784 },
785 });
786 });
787
788 it("rejects empty turn input", async () => {
789 const { manager } = createSendTurnHarness();
790
791 await expect(
792 manager.sendTurn({
793 threadId: asThreadId("thread_1"),
794 }),
795 ).rejects.toThrow("Turn input must include text or attachments.");
796 });
797});
798
799describe("thread checkpoint control", () => {
800 it("reads thread turns from thread/read", async () => {
801 const { manager, context, requireSession, sendRequest } = createThreadControlHarness();
802 sendRequest.mockResolvedValue({
803 thread: {
804 id: "thread_1",
805 turns: [
806 {
807 id: "turn_1",
808 items: [{ type: "userMessage", content: [{ type: "text", text: "hello" }] }],
809 },
810 ],
811 },
812 });
813
814 const result = await manager.readThread(asThreadId("thread_1"));
815
816 expect(requireSession).toHaveBeenCalledWith("thread_1");
817 expect(sendRequest).toHaveBeenCalledWith(context, "thread/read", {
818 threadId: "thread_1",
819 includeTurns: true,
820 });
821 expect(result).toEqual({
822 threadId: "thread_1",
823 turns: [
824 {
825 id: "turn_1",
826 items: [{ type: "userMessage", content: [{ type: "text", text: "hello" }] }],
827 },
828 ],
829 });
830 });
831
832 it("reads thread turns from flat thread/read responses", async () => {
833 const { manager, context, sendRequest } = createThreadControlHarness();
834 sendRequest.mockResolvedValue({
835 threadId: "thread_1",
836 turns: [
837 {
838 id: "turn_1",
839 items: [{ type: "userMessage", content: [{ type: "text", text: "hello" }] }],
840 },
841 ],
842 });
843
844 const result = await manager.readThread(asThreadId("thread_1"));
845
846 expect(sendRequest).toHaveBeenCalledWith(context, "thread/read", {
847 threadId: "thread_1",
848 includeTurns: true,
849 });
850 expect(result).toEqual({
851 threadId: "thread_1",
852 turns: [
853 {
854 id: "turn_1",
855 items: [{ type: "userMessage", content: [{ type: "text", text: "hello" }] }],
856 },
857 ],
858 });
859 });
860
861 it("rolls back turns via thread/rollback and resets session running state", async () => {
862 const { manager, context, sendRequest, updateSession } = createThreadControlHarness();
863 sendRequest.mockResolvedValue({
864 thread: {
865 id: "thread_1",
866 turns: [],
867 },
868 });
869
870 const result = await manager.rollbackThread(asThreadId("thread_1"), 2);
871
872 expect(sendRequest).toHaveBeenCalledWith(context, "thread/rollback", {
873 threadId: "thread_1",
874 numTurns: 2,
875 });
876 expect(updateSession).toHaveBeenCalledWith(context, {
877 status: "ready",
878 activeTurnId: undefined,
879 });
880 expect(result).toEqual({
881 threadId: "thread_1",
882 turns: [],
883 });
884 });
885});
886
887describe("respondToUserInput", () => {
888 it("serializes canonical answers to Codex native answer objects", async () => {
889 const { manager, context, requireSession, writeMessage, emitEvent } =
890 createPendingUserInputHarness();
891
892 await manager.respondToUserInput(
893 asThreadId("thread_1"),
894 ApprovalRequestId.make("req-user-input-1"),
895 {
896 scope: "All request methods",
897 compat: "Keep current envelope",
898 },
899 );
900
901 expect(requireSession).toHaveBeenCalledWith("thread_1");
902 expect(writeMessage).toHaveBeenCalledWith(context, {
903 id: 42,
904 result: {
905 answers: {
906 scope: { answers: ["All request methods"] },
907 compat: { answers: ["Keep current envelope"] },
908 },
909 },
910 });
911 expect(emitEvent).toHaveBeenCalledWith(
912 expect.objectContaining({
913 method: "item/tool/requestUserInput/answered",
914 payload: {
915 requestId: "req-user-input-1",
916 answers: {
917 scope: { answers: ["All request methods"] },
918 compat: { answers: ["Keep current envelope"] },
919 },
920 },
921 }),
922 );
923 });
924
925 it("preserves explicit empty multi-select answers", async () => {
926 const { manager, context, requireSession, writeMessage, emitEvent } =
927 createPendingUserInputHarness();
928
929 await manager.respondToUserInput(
930 asThreadId("thread_1"),
931 ApprovalRequestId.make("req-user-input-1"),
932 {
933 scope: [],
934 },
935 );
936
937 expect(requireSession).toHaveBeenCalledWith("thread_1");
938 expect(writeMessage).toHaveBeenCalledWith(context, {
939 id: 42,
940 result: {
941 answers: {
942 scope: { answers: [] },
943 },
944 },
945 });
946 expect(emitEvent).toHaveBeenCalledWith(
947 expect.objectContaining({
948 method: "item/tool/requestUserInput/answered",
949 payload: {
950 requestId: "req-user-input-1",
951 answers: {
952 scope: { answers: [] },
953 },
954 },
955 }),
956 );
957 });
958
959 it("tracks file-read approval requests with the correct method", () => {
960 const manager = new CodexAppServerManager();
961 const context = {
962 session: {
963 sessionId: "sess_1",
964 provider: "codex",
965 status: "ready",
966 threadId: asThreadId("thread_1"),
967 resumeCursor: { threadId: "thread_1" },
968 createdAt: "2026-02-10T00:00:00.000Z",
969 updatedAt: "2026-02-10T00:00:00.000Z",
970 },
971 pendingApprovals: new Map(),
972 pendingUserInputs: new Map(),
973 collabReceiverTurns: new Map(),
974 };
975 type ApprovalRequestContext = {
976 session: typeof context.session;
977 pendingApprovals: typeof context.pendingApprovals;
978 pendingUserInputs: typeof context.pendingUserInputs;
979 };
980
981 (
982 manager as unknown as {
983 handleServerRequest: (
984 context: ApprovalRequestContext,
985 request: Record<string, unknown>,
986 ) => void;
987 }
988 ).handleServerRequest(context, {
989 jsonrpc: "2.0",
990 id: 42,
991 method: "item/fileRead/requestApproval",
992 params: {},
993 });
994
995 const request = Array.from(context.pendingApprovals.values())[0];
996 expect(request?.requestKind).toBe("file-read");
997 expect(request?.method).toBe("item/fileRead/requestApproval");
998 });
999});
1000
1001describe("collab child conversation routing", () => {
1002 it("rewrites child notification turn ids onto the parent turn", () => {
1003 const { manager, context, emitEvent } = createCollabNotificationHarness();
1004
1005 (
1006 manager as unknown as {
1007 handleServerNotification: (context: unknown, notification: Record<string, unknown>) => void;
1008 }
1009 ).handleServerNotification(context, {
1010 method: "item/completed",
1011 params: {
1012 item: {
1013 type: "collabAgentToolCall",
1014 id: "call_collab_1",
1015 receiverThreadIds: ["child_provider_1"],
1016 },
1017 threadId: "provider_parent",
1018 turnId: "turn_parent",
1019 },
1020 });
1021
1022 (
1023 manager as unknown as {
1024 handleServerNotification: (context: unknown, notification: Record<string, unknown>) => void;
1025 }
1026 ).handleServerNotification(context, {
1027 method: "item/agentMessage/delta",
1028 params: {
1029 threadId: "child_provider_1",
1030 turnId: "turn_child_1",
1031 itemId: "msg_child_1",
1032 delta: "working",
1033 },
1034 });
1035
1036 expect(emitEvent).toHaveBeenLastCalledWith(
1037 expect.objectContaining({
1038 method: "item/agentMessage/delta",
1039 turnId: "turn_parent",
1040 itemId: "msg_child_1",
1041 }),
1042 );
1043 });
1044
1045 it("suppresses child lifecycle notifications so they cannot replace the parent turn", () => {
1046 const { manager, context, emitEvent, updateSession } = createCollabNotificationHarness();
1047
1048 (
1049 manager as unknown as {
1050 handleServerNotification: (context: unknown, notification: Record<string, unknown>) => void;
1051 }
1052 ).handleServerNotification(context, {
1053 method: "item/completed",
1054 params: {
1055 item: {
1056 type: "collabAgentToolCall",
1057 id: "call_collab_1",
1058 receiverThreadIds: ["child_provider_1"],
1059 },
1060 threadId: "provider_parent",
1061 turnId: "turn_parent",
1062 },
1063 });
1064 emitEvent.mockClear();
1065 updateSession.mockClear();
1066
1067 (
1068 manager as unknown as {
1069 handleServerNotification: (context: unknown, notification: Record<string, unknown>) => void;
1070 }
1071 ).handleServerNotification(context, {
1072 method: "turn/started",
1073 params: {
1074 threadId: "child_provider_1",
1075 turn: { id: "turn_child_1" },
1076 },
1077 });
1078
1079 (
1080 manager as unknown as {
1081 handleServerNotification: (context: unknown, notification: Record<string, unknown>) => void;
1082 }
1083 ).handleServerNotification(context, {
1084 method: "turn/completed",
1085 params: {
1086 threadId: "child_provider_1",
1087 turn: { id: "turn_child_1", status: "completed" },
1088 },
1089 });
1090
1091 expect(emitEvent).not.toHaveBeenCalled();
1092 expect(updateSession).not.toHaveBeenCalled();
1093 });
1094
1095 it("rewrites child approval requests onto the parent turn", () => {
1096 const { manager, context, emitEvent } = createCollabNotificationHarness();
1097
1098 (
1099 manager as unknown as {
1100 handleServerNotification: (context: unknown, notification: Record<string, unknown>) => void;
1101 }
1102 ).handleServerNotification(context, {
1103 method: "item/completed",
1104 params: {
1105 item: {
1106 type: "collabAgentToolCall",
1107 id: "call_collab_1",
1108 receiverThreadIds: ["child_provider_1"],
1109 },
1110 threadId: "provider_parent",
1111 turnId: "turn_parent",
1112 },
1113 });
1114 emitEvent.mockClear();
1115
1116 (
1117 manager as unknown as {
1118 handleServerRequest: (context: unknown, request: Record<string, unknown>) => void;
1119 }
1120 ).handleServerRequest(context, {
1121 id: 42,
1122 method: "item/commandExecution/requestApproval",
1123 params: {
1124 threadId: "child_provider_1",
1125 turnId: "turn_child_1",
1126 itemId: "call_child_1",
1127 command: "bun install",
1128 },
1129 });
1130
1131 expect(Array.from(context.pendingApprovals.values())[0]).toEqual(
1132 expect.objectContaining({
1133 turnId: "turn_parent",
1134 itemId: "call_child_1",
1135 }),
1136 );
1137 expect(emitEvent).toHaveBeenCalledWith(
1138 expect.objectContaining({
1139 method: "item/commandExecution/requestApproval",
1140 turnId: "turn_parent",
1141 itemId: "call_child_1",
1142 }),
1143 );
1144 });
1145});
1146
1147describe.skipIf(!process.env.CODEX_BINARY_PATH)("startSession live Codex resume", () => {
1148 it("keeps prior thread history when resuming with a changed runtime mode", async () => {
1149 const workspaceDir = mkdtempSync(path.join(os.tmpdir(), "codex-live-resume-"));
1150 writeFileSync(path.join(workspaceDir, "README.md"), "hello\n", "utf8");
1151
1152 const manager = new CodexAppServerManager();
1153
1154 try {
1155 const firstSession = await manager.startSession({
1156 threadId: asThreadId("thread-live"),
1157 provider: "codex",
1158 cwd: workspaceDir,
1159 runtimeMode: "full-access",
1160 binaryPath: process.env.CODEX_BINARY_PATH!,
1161 ...(process.env.CODEX_HOME_PATH ? { homePath: process.env.CODEX_HOME_PATH } : {}),
1162 });
1163
1164 const firstTurn = await manager.sendTurn({
1165 threadId: firstSession.threadId,
1166 input: `Reply with exactly the word ALPHA ${randomUUID()}`,
1167 });
1168
1169 expect(firstTurn.threadId).toBe(firstSession.threadId);
1170
1171 await vi.waitFor(
1172 async () => {
1173 const snapshot = await manager.readThread(firstSession.threadId);
1174 expect(snapshot.turns.length).toBeGreaterThan(0);
1175 },
1176 { timeout: 120_000, interval: 1_000 },
1177 );
1178
1179 const firstSnapshot = await manager.readThread(firstSession.threadId);
1180 const originalThreadId = firstSnapshot.threadId;
1181 const originalTurnCount = firstSnapshot.turns.length;
1182
1183 manager.stopSession(firstSession.threadId);
1184
1185 const resumedSession = await manager.startSession({
1186 threadId: firstSession.threadId,
1187 provider: "codex",
1188 cwd: workspaceDir,
1189 runtimeMode: "approval-required",
1190 resumeCursor: firstSession.resumeCursor,
1191 binaryPath: process.env.CODEX_BINARY_PATH!,
1192 ...(process.env.CODEX_HOME_PATH ? { homePath: process.env.CODEX_HOME_PATH } : {}),
1193 });
1194
1195 expect(resumedSession.threadId).toBe(originalThreadId);
1196
1197 const resumedSnapshotBeforeTurn = await manager.readThread(resumedSession.threadId);
1198 expect(resumedSnapshotBeforeTurn.threadId).toBe(originalThreadId);
1199 expect(resumedSnapshotBeforeTurn.turns.length).toBeGreaterThanOrEqual(originalTurnCount);
1200
1201 await manager.sendTurn({
1202 threadId: resumedSession.threadId,
1203 input: `Reply with exactly the word BETA ${randomUUID()}`,
1204 });
1205
1206 await vi.waitFor(
1207 async () => {
1208 const snapshot = await manager.readThread(resumedSession.threadId);
1209 expect(snapshot.turns.length).toBeGreaterThan(originalTurnCount);
1210 },
1211 { timeout: 120_000, interval: 1_000 },
1212 );
1213 } finally {
1214 manager.stopAll();
1215 rmSync(workspaceDir, { recursive: true, force: true });
1216 }
1217 }, 180_000);
1218});
apps/server/src/codexAppServerManager.ts deleted-1633
...@@ -1,1633 +0,0 @@
1import { type ChildProcessWithoutNullStreams, spawn, spawnSync } from "node:child_process";
2import { randomUUID } from "node:crypto";
3import { EventEmitter } from "node:events";
4import readline from "node:readline";
5
6import {
7 ApprovalRequestId,
8 EventId,
9 ProviderItemId,
10 ProviderRequestKind,
11 type ProviderUserInputAnswers,
12 ThreadId,
13 TurnId,
14 type ProviderApprovalDecision,
15 type ProviderEvent,
16 type ProviderSession,
17 type ProviderTurnStartResult,
18 RuntimeMode,
19 ProviderInteractionMode,
20} from "@t3tools/contracts";
21import { normalizeModelSlug } from "@t3tools/shared/model";
22import { Effect, Context } from "effect";
23
24import {
25 formatCodexCliUpgradeMessage,
26 isCodexCliVersionSupported,
27 parseCodexCliVersion,
28} from "./provider/codexCliVersion.ts";
29import {
30 readCodexAccountSnapshot,
31 resolveCodexModelForAccount,
32 type CodexAccountSnapshot,
33} from "./provider/codexAccount.ts";
34import { buildCodexInitializeParams, killCodexChildProcess } from "./provider/codexAppServer.ts";
35import { expandHomePath } from "./pathExpansion.ts";
36
37export { buildCodexInitializeParams } from "./provider/codexAppServer.ts";
38export { readCodexAccountSnapshot, resolveCodexModelForAccount } from "./provider/codexAccount.ts";
39
40type PendingRequestKey = string;
41
42interface PendingRequest {
43 method: string;
44 timeout: ReturnType<typeof setTimeout>;
45 resolve: (value: unknown) => void;
46 reject: (error: Error) => void;
47}
48
49interface PendingApprovalRequest {
50 requestId: ApprovalRequestId;
51 jsonRpcId: string | number;
52 method:
53 | "item/commandExecution/requestApproval"
54 | "item/fileChange/requestApproval"
55 | "item/fileRead/requestApproval";
56 requestKind: ProviderRequestKind;
57 threadId: ThreadId;
58 turnId?: TurnId;
59 itemId?: ProviderItemId;
60}
61
62interface PendingUserInputRequest {
63 requestId: ApprovalRequestId;
64 jsonRpcId: string | number;
65 threadId: ThreadId;
66 turnId?: TurnId;
67 itemId?: ProviderItemId;
68}
69
70interface CodexUserInputAnswer {
71 answers: string[];
72}
73
74interface CodexSessionContext {
75 session: ProviderSession;
76 account: CodexAccountSnapshot;
77 child: ChildProcessWithoutNullStreams;
78 output: readline.Interface;
79 pending: Map<PendingRequestKey, PendingRequest>;
80 pendingApprovals: Map<ApprovalRequestId, PendingApprovalRequest>;
81 pendingUserInputs: Map<ApprovalRequestId, PendingUserInputRequest>;
82 collabReceiverTurns: Map<string, TurnId>;
83 nextRequestId: number;
84 stopping: boolean;
85}
86
87interface JsonRpcError {
88 code?: number;
89 message?: string;
90}
91
92interface JsonRpcRequest {
93 id: string | number;
94 method: string;
95 params?: unknown;
96}
97
98interface JsonRpcResponse {
99 id: string | number;
100 result?: unknown;
101 error?: JsonRpcError;
102}
103
104interface JsonRpcNotification {
105 method: string;
106 params?: unknown;
107}
108
109export interface CodexAppServerSendTurnInput {
110 readonly threadId: ThreadId;
111 readonly input?: string;
112 readonly attachments?: ReadonlyArray<{ type: "image"; url: string }>;
113 readonly model?: string;
114 readonly serviceTier?: string | null;
115 readonly effort?: string;
116 readonly interactionMode?: ProviderInteractionMode;
117}
118
119export interface CodexAppServerStartSessionInput {
120 readonly threadId: ThreadId;
121 readonly provider?: "codex";
122 readonly cwd?: string;
123 readonly model?: string;
124 readonly serviceTier?: string;
125 readonly resumeCursor?: unknown;
126 readonly binaryPath: string;
127 readonly homePath?: string;
128 readonly runtimeMode: RuntimeMode;
129}
130
131export interface CodexThreadTurnSnapshot {
132 id: TurnId;
133 items: unknown[];
134}
135
136export interface CodexThreadSnapshot {
137 threadId: string;
138 turns: CodexThreadTurnSnapshot[];
139}
140
141const CODEX_VERSION_CHECK_TIMEOUT_MS = 4_000;
142
143const ANSI_ESCAPE_CHAR = String.fromCharCode(27);
144const ANSI_ESCAPE_REGEX = new RegExp(`${ANSI_ESCAPE_CHAR}\\[[0-9;]*m`, "g");
145const CODEX_STDERR_LOG_REGEX =
146 /^\d{4}-\d{2}-\d{2}T\S+\s+(TRACE|DEBUG|INFO|WARN|ERROR)\s+\S+:\s+(.*)$/;
147const BENIGN_ERROR_LOG_SNIPPETS = [
148 "state db missing rollout path for thread",
149 "state db record_discrepancy: find_thread_path_by_id_str_in_subdir, falling_back",
150];
151const RECOVERABLE_THREAD_RESUME_ERROR_SNIPPETS = [
152 "not found",
153 "missing thread",
154 "no such thread",
155 "unknown thread",
156 "does not exist",
157];
158export const CODEX_PLAN_MODE_DEVELOPER_INSTRUCTIONS = `<collaboration_mode># Plan Mode (Conversational)
159
160You 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.
161
162## Mode rules (strict)
163
164You are in **Plan Mode** until a developer message explicitly ends it.
165
166Plan 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.
167
168## Plan Mode vs update_plan tool
169
170Plan Mode is a collaboration mode that can involve requesting user input and eventually issuing a \`<proposed_plan>\` block.
171
172Separately, \`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.
173
174## Execution vs. mutation in Plan Mode
175
176You may explore and execute **non-mutating** actions that improve the plan. You must not perform **mutating** actions.
177
178### Allowed (non-mutating, plan-improving)
179
180Actions that gather truth, reduce ambiguity, or validate feasibility without changing repo-tracked state. Examples:
181
182* Reading or searching files, configs, schemas, types, manifests, and docs
183* Static analysis, inspection, and repo exploration
184* Dry-run style commands when they do not edit repo-tracked files
185* 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
186
187### Not allowed (mutating, plan-executing)
188
189Actions that implement the plan or change repo-tracked state. Examples:
190
191* Editing or writing files
192* Running formatters or linters that rewrite files
193* Applying patches, migrations, or codegen that updates repo-tracked files
194* Side-effectful commands whose purpose is to carry out the plan rather than refine it
195
196When in doubt: if the action would reasonably be described as "doing the work" rather than "planning the work," do not do it.
197
198## PHASE 1 - Ground in the environment (explore first, ask second)
199
200Begin 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.
201
202Before 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.
203
204Exception: 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.
205
206Do 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.
207
208## PHASE 2 - Intent chat (what they actually want)
209
210* Keep asking until you can clearly state: goal + success criteria, audience, in/out of scope, constraints, current state, and the key preferences/tradeoffs.
211* Bias toward questions over guessing: if any high-impact ambiguity remains, do NOT plan yet-ask.
212
213## PHASE 3 - Implementation chat (what/how we'll build)
214
215* 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.
216
217## Asking questions
218
219Critical rules:
220
221* Strongly prefer using the \`request_user_input\` tool to ask any questions.
222* Offer only meaningful multiple-choice options; don't include filler choices that are obviously wrong or irrelevant.
223* 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.
224
225You SHOULD ask many questions, but each question must:
226
227* materially change the spec/plan, OR
228* confirm/lock an assumption, OR
229* choose between meaningful tradeoffs.
230* not be answerable by non-mutating commands.
231
232Use 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.
233
234## Two kinds of unknowns (treat differently)
235
2361. **Discoverable facts** (repo/system truth): explore first.
237
238 * Before asking, run targeted searches and check likely sources of truth (configs/manifests/entrypoints/schemas/types/constants).
239 * Ask only if: multiple plausible candidates; nothing found but you need a missing identifier/context; or ambiguity is actually product intent.
240 * If asking, present concrete candidates (paths/service names) + recommend one.
241 * Never ask questions you can answer from your environment (e.g., "where is this struct").
242
2432. **Preferences/tradeoffs** (not discoverable): ask early.
244
245 * These are intent or implementation preferences that cannot be derived from exploration.
246 * Provide 2-4 mutually exclusive options + a recommended default.
247 * If unanswered, proceed with the recommended option and record it as an assumption in the final plan.
248
249## Finalization rule
250
251Only output the final plan when it is decision complete and leaves no decisions to the implementer.
252
253When you present the official plan, wrap it in a \`<proposed_plan>\` block so the client can render it specially:
254
2551) The opening tag must be on its own line.
2562) Start the plan content on the next line (no text on the same line as the tag).
2573) The closing tag must be on its own line.
2584) Use Markdown inside the block.
2595) Keep the tags exactly as \`<proposed_plan>\` and \`</proposed_plan>\` (do not translate or rename them), even if the plan content is in another language.
260
261Example:
262
263<proposed_plan>
264plan content
265</proposed_plan>
266
267plan content should be human and agent digestible. The final plan must be plan-only and include:
268
269* A clear title
270* A brief summary section
271* Important changes or additions to public APIs/interfaces/types
272* Test cases and scenarios
273* Explicit assumptions and defaults chosen where needed
274
275Do 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 \`<proposed_plan>\` block in your response. Alternatively, they can decide to stay in Plan mode and continue refining the plan.
276
277Only produce at most one \`<proposed_plan>\` block per turn, and only when you are presenting a complete spec.
278</collaboration_mode>`;
279
280export const CODEX_DEFAULT_MODE_DEVELOPER_INSTRUCTIONS = `<collaboration_mode># Collaboration Mode: Default
281
282You are now in Default mode. Any previous instructions for other modes (e.g. Plan mode) are no longer active.
283
284Your active mode changes only when new developer instructions with a different \`<collaboration_mode>...</collaboration_mode>\` change it; user requests or tool descriptions do not change mode by themselves. Known mode names are Default and Plan.
285
286## request_user_input availability
287
288The \`request_user_input\` tool is unavailable in Default mode. If you call it while in Default mode, it will return an error.
289
290In 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.
291</collaboration_mode>`;
292
293function mapCodexRuntimeMode(runtimeMode: RuntimeMode): {
294 readonly approvalPolicy: "untrusted" | "on-request" | "never";
295 readonly sandbox: "read-only" | "workspace-write" | "danger-full-access";
296} {
297 switch (runtimeMode) {
298 case "approval-required":
299 return {
300 approvalPolicy: "untrusted",
301 sandbox: "read-only",
302 };
303 case "auto-accept-edits":
304 return {
305 approvalPolicy: "on-request",
306 sandbox: "workspace-write",
307 };
308 case "full-access":
309 return {
310 approvalPolicy: "never",
311 sandbox: "danger-full-access",
312 };
313 }
314}
315
316/**
317 * On Windows with `shell: true`, `child.kill()` only terminates the `cmd.exe`
318 * wrapper, leaving the actual command running. Use `taskkill /T` to kill the
319 * entire process tree instead.
320 */
321function killChildTree(child: ChildProcessWithoutNullStreams): void {
322 killCodexChildProcess(child);
323}
324
325export function normalizeCodexModelSlug(
326 model: string | undefined | null,
327 preferredId?: string,
328): string | undefined {
329 const normalized = normalizeModelSlug(model);
330 if (!normalized) {
331 return undefined;
332 }
333
334 if (preferredId?.endsWith("-codex") && preferredId !== normalized) {
335 return preferredId;
336 }
337
338 return normalized;
339}
340
341function buildCodexCollaborationMode(input: {
342 readonly interactionMode?: "default" | "plan";
343 readonly model?: string;
344 readonly effort?: string;
345}):
346 | {
347 mode: "default" | "plan";
348 settings: {
349 model: string;
350 reasoning_effort: string;
351 developer_instructions: string;
352 };
353 }
354 | undefined {
355 if (input.interactionMode === undefined) {
356 return undefined;
357 }
358 const model = normalizeCodexModelSlug(input.model) ?? "gpt-5.3-codex";
359 return {
360 mode: input.interactionMode,
361 settings: {
362 model,
363 reasoning_effort: input.effort ?? "medium",
364 developer_instructions:
365 input.interactionMode === "plan"
366 ? CODEX_PLAN_MODE_DEVELOPER_INSTRUCTIONS
367 : CODEX_DEFAULT_MODE_DEVELOPER_INSTRUCTIONS,
368 },
369 };
370}
371
372function toCodexUserInputAnswer(value: unknown): CodexUserInputAnswer {
373 if (typeof value === "string") {
374 return { answers: [value] };
375 }
376
377 if (Array.isArray(value)) {
378 const answers = value.filter((entry): entry is string => typeof entry === "string");
379 return { answers };
380 }
381
382 if (value && typeof value === "object") {
383 const maybeAnswers = (value as { answers?: unknown }).answers;
384 if (Array.isArray(maybeAnswers)) {
385 const answers = maybeAnswers.filter((entry): entry is string => typeof entry === "string");
386 return { answers };
387 }
388 }
389
390 throw new Error("User input answers must be strings or arrays of strings.");
391}
392
393function toCodexUserInputAnswers(
394 answers: ProviderUserInputAnswers,
395): Record<string, CodexUserInputAnswer> {
396 return Object.fromEntries(
397 Object.entries(answers).map(([questionId, value]) => [
398 questionId,
399 toCodexUserInputAnswer(value),
400 ]),
401 );
402}
403
404export function classifyCodexStderrLine(rawLine: string): { message: string } | null {
405 const line = rawLine.replaceAll(ANSI_ESCAPE_REGEX, "").trim();
406 if (!line) {
407 return null;
408 }
409
410 const match = line.match(CODEX_STDERR_LOG_REGEX);
411 if (match) {
412 const level = match[1];
413 if (level && level !== "ERROR") {
414 return null;
415 }
416
417 const isBenignError = BENIGN_ERROR_LOG_SNIPPETS.some((snippet) => line.includes(snippet));
418 if (isBenignError) {
419 return null;
420 }
421 }
422
423 return { message: line };
424}
425
426export function isRecoverableThreadResumeError(error: unknown): boolean {
427 const message = (error instanceof Error ? error.message : String(error)).toLowerCase();
428 if (!message.includes("thread/resume")) {
429 return false;
430 }
431
432 return RECOVERABLE_THREAD_RESUME_ERROR_SNIPPETS.some((snippet) => message.includes(snippet));
433}
434
435export interface CodexAppServerManagerEvents {
436 event: [event: ProviderEvent];
437}
438
439export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEvents> {
440 private readonly sessions = new Map<ThreadId, CodexSessionContext>();
441
442 private runPromise: (effect: Effect.Effect<unknown, never>) => Promise<unknown>;
443 constructor(services?: Context.Context<never>) {
444 super();
445 this.runPromise = services ? Effect.runPromiseWith(services) : Effect.runPromise;
446 }
447
448 async startSession(input: CodexAppServerStartSessionInput): Promise<ProviderSession> {
449 const threadId = input.threadId;
450 const now = new Date().toISOString();
451 let context: CodexSessionContext | undefined;
452
453 try {
454 const existingContext = this.sessions.get(threadId);
455 if (existingContext) {
456 await Effect.logWarning("codex app-server replacing existing session", {
457 threadId,
458 existingStatus: existingContext.session.status,
459 }).pipe(this.runPromise);
460 try {
461 this.disposeSession(existingContext, {
462 emitLifecycleEvent: false,
463 });
464 } catch (error) {
465 await Effect.logWarning("codex app-server failed to dispose existing session", {
466 threadId,
467 existingStatus: existingContext.session.status,
468 cause: error instanceof Error ? error.message : String(error),
469 }).pipe(this.runPromise);
470 }
471 }
472
473 const resolvedCwd = input.cwd ?? process.cwd();
474
475 const session: ProviderSession = {
476 provider: "codex",
477 status: "connecting",
478 runtimeMode: input.runtimeMode,
479 model: normalizeCodexModelSlug(input.model),
480 cwd: resolvedCwd,
481 threadId,
482 createdAt: now,
483 updatedAt: now,
484 };
485
486 const codexBinaryPath = input.binaryPath;
487 const codexHomePath = input.homePath;
488 this.assertSupportedCodexCliVersion({
489 binaryPath: codexBinaryPath,
490 cwd: resolvedCwd,
491 ...(codexHomePath ? { homePath: codexHomePath } : {}),
492 });
493 const child = spawn(codexBinaryPath, ["app-server"], {
494 cwd: resolvedCwd,
495 env: {
496 ...process.env,
497 ...(codexHomePath ? { CODEX_HOME: expandHomePath(codexHomePath) } : {}),
498 },
499 stdio: ["pipe", "pipe", "pipe"],
500 shell: process.platform === "win32",
501 });
502 const output = readline.createInterface({ input: child.stdout });
503
504 context = {
505 session,
506 account: {
507 type: "unknown",
508 planType: null,
509 sparkEnabled: true,
510 },
511 child,
512 output,
513 pending: new Map(),
514 pendingApprovals: new Map(),
515 pendingUserInputs: new Map(),
516 collabReceiverTurns: new Map(),
517 nextRequestId: 1,
518 stopping: false,
519 };
520
521 this.sessions.set(threadId, context);
522 this.attachProcessListeners(context);
523
524 this.emitLifecycleEvent(context, "session/connecting", "Starting codex app-server");
525
526 await this.sendRequest(context, "initialize", buildCodexInitializeParams());
527
528 this.writeMessage(context, { method: "initialized" });
529 try {
530 const modelListResponse = await this.sendRequest(context, "model/list", {});
531 console.log("codex model/list response", modelListResponse);
532 } catch (error) {
533 console.log("codex model/list failed", error);
534 }
535 try {
536 const accountReadResponse = await this.sendRequest(context, "account/read", {});
537 console.log("codex account/read response", accountReadResponse);
538 context.account = readCodexAccountSnapshot(accountReadResponse);
539 console.log("codex subscription status", {
540 type: context.account.type,
541 planType: context.account.planType,
542 sparkEnabled: context.account.sparkEnabled,
543 });
544 } catch (error) {
545 console.log("codex account/read failed", error);
546 }
547
548 const normalizedModel = resolveCodexModelForAccount(
549 normalizeCodexModelSlug(input.model),
550 context.account,
551 );
552 const sessionOverrides = {
553 model: normalizedModel ?? null,
554 ...(input.serviceTier !== undefined ? { serviceTier: input.serviceTier } : {}),
555 cwd: input.cwd ?? null,
556 ...mapCodexRuntimeMode(input.runtimeMode ?? "full-access"),
557 };
558
559 const threadStartParams = {
560 ...sessionOverrides,
561 experimentalRawEvents: false,
562 };
563 const resumeThreadId = readResumeThreadId(input);
564 this.emitLifecycleEvent(
565 context,
566 "session/threadOpenRequested",
567 resumeThreadId
568 ? `Attempting to resume thread ${resumeThreadId}.`
569 : "Starting a new Codex thread.",
570 );
571 await Effect.logInfo("codex app-server opening thread", {
572 threadId,
573 requestedRuntimeMode: input.runtimeMode,
574 requestedModel: normalizedModel ?? null,
575 requestedCwd: resolvedCwd,
576 resumeThreadId: resumeThreadId ?? null,
577 }).pipe(this.runPromise);
578
579 let threadOpenMethod: "thread/start" | "thread/resume" = "thread/start";
580 let threadOpenResponse: unknown;
581 if (resumeThreadId) {
582 try {
583 threadOpenMethod = "thread/resume";
584 threadOpenResponse = await this.sendRequest(context, "thread/resume", {
585 ...sessionOverrides,
586 threadId: resumeThreadId,
587 });
588 } catch (error) {
589 if (!isRecoverableThreadResumeError(error)) {
590 this.emitErrorEvent(
591 context,
592 "session/threadResumeFailed",
593 error instanceof Error ? error.message : "Codex thread resume failed.",
594 );
595 await Effect.logWarning("codex app-server thread resume failed", {
596 threadId,
597 requestedRuntimeMode: input.runtimeMode,
598 resumeThreadId,
599 recoverable: false,
600 cause: error instanceof Error ? error.message : String(error),
601 }).pipe(this.runPromise);
602 throw error;
603 }
604
605 threadOpenMethod = "thread/start";
606 this.emitLifecycleEvent(
607 context,
608 "session/threadResumeFallback",
609 `Could not resume thread ${resumeThreadId}; started a new thread instead.`,
610 );
611 await Effect.logWarning("codex app-server thread resume fell back to fresh start", {
612 threadId,
613 requestedRuntimeMode: input.runtimeMode,
614 resumeThreadId,
615 recoverable: true,
616 cause: error instanceof Error ? error.message : String(error),
617 }).pipe(this.runPromise);
618 threadOpenResponse = await this.sendRequest(context, "thread/start", threadStartParams);
619 }
620 } else {
621 threadOpenMethod = "thread/start";
622 threadOpenResponse = await this.sendRequest(context, "thread/start", threadStartParams);
623 }
624
625 const threadOpenRecord = this.readObject(threadOpenResponse);
626 const threadIdRaw =
627 this.readString(this.readObject(threadOpenRecord, "thread"), "id") ??
628 this.readString(threadOpenRecord, "threadId");
629 if (!threadIdRaw) {
630 throw new Error(`${threadOpenMethod} response did not include a thread id.`);
631 }
632 const providerThreadId = threadIdRaw;
633
634 this.updateSession(context, {
635 status: "ready",
636 resumeCursor: { threadId: providerThreadId },
637 });
638 this.emitLifecycleEvent(
639 context,
640 "session/threadOpenResolved",
641 `Codex ${threadOpenMethod} resolved.`,
642 );
643 await Effect.logInfo("codex app-server thread open resolved", {
644 threadId,
645 threadOpenMethod,
646 requestedResumeThreadId: resumeThreadId ?? null,
647 resolvedThreadId: providerThreadId,
648 requestedRuntimeMode: input.runtimeMode,
649 }).pipe(this.runPromise);
650 this.emitLifecycleEvent(context, "session/ready", `Connected to thread ${providerThreadId}`);
651 return { ...context.session };
652 } catch (error) {
653 const message = error instanceof Error ? error.message : "Failed to start Codex session.";
654 if (context) {
655 this.updateSession(context, {
656 status: "error",
657 lastError: message,
658 });
659 this.emitErrorEvent(context, "session/startFailed", message);
660 this.stopSession(threadId);
661 } else {
662 this.emitEvent({
663 id: EventId.make(randomUUID()),
664 kind: "error",
665 provider: "codex",
666 threadId,
667 createdAt: new Date().toISOString(),
668 method: "session/startFailed",
669 message,
670 });
671 }
672 throw new Error(message, { cause: error });
673 }
674 }
675
676 async sendTurn(input: CodexAppServerSendTurnInput): Promise<ProviderTurnStartResult> {
677 const context = this.requireSession(input.threadId);
678 context.collabReceiverTurns.clear();
679
680 const turnInput: Array<
681 { type: "text"; text: string; text_elements: [] } | { type: "image"; url: string }
682 > = [];
683 if (input.input) {
684 turnInput.push({
685 type: "text",
686 text: input.input,
687 text_elements: [],
688 });
689 }
690 for (const attachment of input.attachments ?? []) {
691 if (attachment.type === "image") {
692 turnInput.push({
693 type: "image",
694 url: attachment.url,
695 });
696 }
697 }
698 if (turnInput.length === 0) {
699 throw new Error("Turn input must include text or attachments.");
700 }
701
702 const providerThreadId = readResumeThreadId({
703 threadId: context.session.threadId,
704 runtimeMode: context.session.runtimeMode,
705 resumeCursor: context.session.resumeCursor,
706 });
707 if (!providerThreadId) {
708 throw new Error("Session is missing provider resume thread id.");
709 }
710 const turnStartParams: {
711 threadId: string;
712 input: Array<
713 { type: "text"; text: string; text_elements: [] } | { type: "image"; url: string }
714 >;
715 model?: string;
716 serviceTier?: string | null;
717 effort?: string;
718 collaborationMode?: {
719 mode: "default" | "plan";
720 settings: {
721 model: string;
722 reasoning_effort: string;
723 developer_instructions: string;
724 };
725 };
726 } = {
727 threadId: providerThreadId,
728 input: turnInput,
729 };
730 const normalizedModel = resolveCodexModelForAccount(
731 normalizeCodexModelSlug(input.model ?? context.session.model),
732 context.account,
733 );
734 if (normalizedModel) {
735 turnStartParams.model = normalizedModel;
736 }
737 if (input.serviceTier !== undefined) {
738 turnStartParams.serviceTier = input.serviceTier;
739 }
740 if (input.effort) {
741 turnStartParams.effort = input.effort;
742 }
743 const collaborationMode = buildCodexCollaborationMode({
744 ...(input.interactionMode !== undefined ? { interactionMode: input.interactionMode } : {}),
745 ...(normalizedModel !== undefined ? { model: normalizedModel } : {}),
746 ...(input.effort !== undefined ? { effort: input.effort } : {}),
747 });
748 if (collaborationMode) {
749 if (!turnStartParams.model) {
750 turnStartParams.model = collaborationMode.settings.model;
751 }
752 turnStartParams.collaborationMode = collaborationMode;
753 }
754
755 const response = await this.sendRequest(context, "turn/start", turnStartParams);
756
757 const turn = this.readObject(this.readObject(response), "turn");
758 const turnIdRaw = this.readString(turn, "id");
759 if (!turnIdRaw) {
760 throw new Error("turn/start response did not include a turn id.");
761 }
762 const turnId = TurnId.make(turnIdRaw);
763
764 this.updateSession(context, {
765 status: "running",
766 activeTurnId: turnId,
767 ...(context.session.resumeCursor !== undefined
768 ? { resumeCursor: context.session.resumeCursor }
769 : {}),
770 });
771
772 return {
773 threadId: context.session.threadId,
774 turnId,
775 ...(context.session.resumeCursor !== undefined
776 ? { resumeCursor: context.session.resumeCursor }
777 : {}),
778 };
779 }
780
781 async interruptTurn(threadId: ThreadId, turnId?: TurnId): Promise<void> {
782 const context = this.requireSession(threadId);
783 const effectiveTurnId = turnId ?? context.session.activeTurnId;
784
785 const providerThreadId = readResumeThreadId({
786 threadId: context.session.threadId,
787 runtimeMode: context.session.runtimeMode,
788 resumeCursor: context.session.resumeCursor,
789 });
790 if (!effectiveTurnId || !providerThreadId) {
791 return;
792 }
793
794 await this.sendRequest(context, "turn/interrupt", {
795 threadId: providerThreadId,
796 turnId: effectiveTurnId,
797 });
798 }
799
800 async readThread(threadId: ThreadId): Promise<CodexThreadSnapshot> {
801 const context = this.requireSession(threadId);
802 const providerThreadId = readResumeThreadId({
803 threadId: context.session.threadId,
804 runtimeMode: context.session.runtimeMode,
805 resumeCursor: context.session.resumeCursor,
806 });
807 if (!providerThreadId) {
808 throw new Error("Session is missing a provider resume thread id.");
809 }
810
811 const response = await this.sendRequest(context, "thread/read", {
812 threadId: providerThreadId,
813 includeTurns: true,
814 });
815 return this.parseThreadSnapshot("thread/read", response);
816 }
817
818 async rollbackThread(threadId: ThreadId, numTurns: number): Promise<CodexThreadSnapshot> {
819 const context = this.requireSession(threadId);
820 const providerThreadId = readResumeThreadId({
821 threadId: context.session.threadId,
822 runtimeMode: context.session.runtimeMode,
823 resumeCursor: context.session.resumeCursor,
824 });
825 if (!providerThreadId) {
826 throw new Error("Session is missing a provider resume thread id.");
827 }
828 if (!Number.isInteger(numTurns) || numTurns < 1) {
829 throw new Error("numTurns must be an integer >= 1.");
830 }
831
832 const response = await this.sendRequest(context, "thread/rollback", {
833 threadId: providerThreadId,
834 numTurns,
835 });
836 this.updateSession(context, {
837 status: "ready",
838 activeTurnId: undefined,
839 });
840 return this.parseThreadSnapshot("thread/rollback", response);
841 }
842
843 async respondToRequest(
844 threadId: ThreadId,
845 requestId: ApprovalRequestId,
846 decision: ProviderApprovalDecision,
847 ): Promise<void> {
848 const context = this.requireSession(threadId);
849 const pendingRequest = context.pendingApprovals.get(requestId);
850 if (!pendingRequest) {
851 throw new Error(`Unknown pending approval request: ${requestId}`);
852 }
853
854 context.pendingApprovals.delete(requestId);
855 this.writeMessage(context, {
856 id: pendingRequest.jsonRpcId,
857 result: {
858 decision,
859 },
860 });
861
862 this.emitEvent({
863 id: EventId.make(randomUUID()),
864 kind: "notification",
865 provider: "codex",
866 threadId: context.session.threadId,
867 createdAt: new Date().toISOString(),
868 method: "item/requestApproval/decision",
869 turnId: pendingRequest.turnId,
870 itemId: pendingRequest.itemId,
871 requestId: pendingRequest.requestId,
872 requestKind: pendingRequest.requestKind,
873 payload: {
874 requestId: pendingRequest.requestId,
875 requestKind: pendingRequest.requestKind,
876 decision,
877 },
878 });
879 }
880
881 async respondToUserInput(
882 threadId: ThreadId,
883 requestId: ApprovalRequestId,
884 answers: ProviderUserInputAnswers,
885 ): Promise<void> {
886 const context = this.requireSession(threadId);
887 const pendingRequest = context.pendingUserInputs.get(requestId);
888 if (!pendingRequest) {
889 throw new Error(`Unknown pending user input request: ${requestId}`);
890 }
891
892 context.pendingUserInputs.delete(requestId);
893 const codexAnswers = toCodexUserInputAnswers(answers);
894 this.writeMessage(context, {
895 id: pendingRequest.jsonRpcId,
896 result: {
897 answers: codexAnswers,
898 },
899 });
900
901 this.emitEvent({
902 id: EventId.make(randomUUID()),
903 kind: "notification",
904 provider: "codex",
905 threadId: context.session.threadId,
906 createdAt: new Date().toISOString(),
907 method: "item/tool/requestUserInput/answered",
908 turnId: pendingRequest.turnId,
909 itemId: pendingRequest.itemId,
910 requestId: pendingRequest.requestId,
911 payload: {
912 requestId: pendingRequest.requestId,
913 answers: codexAnswers,
914 },
915 });
916 }
917
918 stopSession(threadId: ThreadId): void {
919 const context = this.sessions.get(threadId);
920 if (!context) {
921 return;
922 }
923
924 this.disposeSession(context, {
925 emitLifecycleEvent: true,
926 });
927 }
928
929 private disposeSession(
930 context: CodexSessionContext,
931 options?: { readonly emitLifecycleEvent?: boolean },
932 ): void {
933 if (context.stopping) {
934 return;
935 }
936
937 context.stopping = true;
938
939 for (const pending of context.pending.values()) {
940 clearTimeout(pending.timeout);
941 pending.reject(new Error("Session stopped before request completed."));
942 }
943 context.pending.clear();
944 context.pendingApprovals.clear();
945 context.pendingUserInputs.clear();
946
947 context.output.close();
948
949 if (!context.child.killed) {
950 killChildTree(context.child);
951 }
952
953 this.updateSession(context, {
954 status: "closed",
955 activeTurnId: undefined,
956 });
957 if (options?.emitLifecycleEvent !== false) {
958 this.emitLifecycleEvent(context, "session/closed", "Session stopped");
959 }
960 this.sessions.delete(context.session.threadId);
961 }
962
963 listSessions(): ProviderSession[] {
964 return Array.from(this.sessions.values(), ({ session }) => ({
965 ...session,
966 }));
967 }
968
969 hasSession(threadId: ThreadId): boolean {
970 return this.sessions.has(threadId);
971 }
972
973 stopAll(): void {
974 for (const threadId of this.sessions.keys()) {
975 this.stopSession(threadId);
976 }
977 }
978
979 private requireSession(threadId: ThreadId): CodexSessionContext {
980 const context = this.sessions.get(threadId);
981 if (!context) {
982 throw new Error(`Unknown session for thread: ${threadId}`);
983 }
984
985 if (context.session.status === "closed") {
986 throw new Error(`Session is closed for thread: ${threadId}`);
987 }
988
989 return context;
990 }
991
992 private attachProcessListeners(context: CodexSessionContext): void {
993 context.output.on("line", (line) => {
994 this.handleStdoutLine(context, line);
995 });
996
997 context.child.stderr.on("data", (chunk: Buffer) => {
998 const raw = chunk.toString();
999 const lines = raw.split(/\r?\n/g);
1000 for (const rawLine of lines) {
1001 const classified = classifyCodexStderrLine(rawLine);
1002 if (!classified) {
1003 continue;
1004 }
1005
1006 this.emitNotificationEvent(context, "process/stderr", classified.message);
1007 }
1008 });
1009
1010 context.child.on("error", (error) => {
1011 const message = error.message || "codex app-server process errored.";
1012 this.updateSession(context, {
1013 status: "error",
1014 lastError: message,
1015 });
1016 this.emitErrorEvent(context, "process/error", message);
1017 });
1018
1019 context.child.on("exit", (code, signal) => {
1020 if (context.stopping) {
1021 return;
1022 }
1023
1024 const message = `codex app-server exited (code=${code ?? "null"}, signal=${signal ?? "null"}).`;
1025 this.updateSession(context, {
1026 status: "closed",
1027 activeTurnId: undefined,
1028 lastError: code === 0 ? context.session.lastError : message,
1029 });
1030 this.emitLifecycleEvent(context, "session/exited", message);
1031 this.sessions.delete(context.session.threadId);
1032 });
1033 }
1034
1035 private handleStdoutLine(context: CodexSessionContext, line: string): void {
1036 let parsed: unknown;
1037 try {
1038 parsed = JSON.parse(line);
1039 } catch {
1040 this.emitErrorEvent(
1041 context,
1042 "protocol/parseError",
1043 "Received invalid JSON from codex app-server.",
1044 );
1045 return;
1046 }
1047
1048 if (!parsed || typeof parsed !== "object") {
1049 this.emitErrorEvent(
1050 context,
1051 "protocol/invalidMessage",
1052 "Received non-object protocol message.",
1053 );
1054 return;
1055 }
1056
1057 if (this.isServerRequest(parsed)) {
1058 this.handleServerRequest(context, parsed);
1059 return;
1060 }
1061
1062 if (this.isServerNotification(parsed)) {
1063 this.handleServerNotification(context, parsed);
1064 return;
1065 }
1066
1067 if (this.isResponse(parsed)) {
1068 this.handleResponse(context, parsed);
1069 return;
1070 }
1071
1072 this.emitErrorEvent(
1073 context,
1074 "protocol/unrecognizedMessage",
1075 "Received protocol message in an unknown shape.",
1076 );
1077 }
1078
1079 private handleServerNotification(
1080 context: CodexSessionContext,
1081 notification: JsonRpcNotification,
1082 ): void {
1083 const rawRoute = this.readRouteFields(notification.params);
1084 this.rememberCollabReceiverTurns(context, notification.params, rawRoute.turnId);
1085 const childParentTurnId = this.readChildParentTurnId(context, notification.params);
1086 const isChildConversation = childParentTurnId !== undefined;
1087 if (
1088 isChildConversation &&
1089 this.shouldSuppressChildConversationNotification(notification.method)
1090 ) {
1091 return;
1092 }
1093 const textDelta =
1094 notification.method === "item/agentMessage/delta"
1095 ? this.readString(notification.params, "delta")
1096 : undefined;
1097
1098 this.emitEvent({
1099 id: EventId.make(randomUUID()),
1100 kind: "notification",
1101 provider: "codex",
1102 threadId: context.session.threadId,
1103 createdAt: new Date().toISOString(),
1104 method: notification.method,
1105 ...((childParentTurnId ?? rawRoute.turnId)
1106 ? { turnId: childParentTurnId ?? rawRoute.turnId }
1107 : {}),
1108 ...(rawRoute.itemId ? { itemId: rawRoute.itemId } : {}),
1109 textDelta,
1110 payload: notification.params,
1111 });
1112
1113 if (notification.method === "thread/started") {
1114 const providerThreadId = normalizeProviderThreadId(
1115 this.readString(this.readObject(notification.params)?.thread, "id"),
1116 );
1117 if (providerThreadId) {
1118 this.updateSession(context, { resumeCursor: { threadId: providerThreadId } });
1119 }
1120 return;
1121 }
1122
1123 if (notification.method === "turn/started") {
1124 if (isChildConversation) {
1125 return;
1126 }
1127 const turnId = toTurnId(this.readString(this.readObject(notification.params)?.turn, "id"));
1128 this.updateSession(context, {
1129 status: "running",
1130 activeTurnId: turnId,
1131 });
1132 return;
1133 }
1134
1135 if (notification.method === "turn/completed") {
1136 if (isChildConversation) {
1137 return;
1138 }
1139 context.collabReceiverTurns.clear();
1140 const turn = this.readObject(notification.params, "turn");
1141 const status = this.readString(turn, "status");
1142 const errorMessage = this.readString(this.readObject(turn, "error"), "message");
1143 this.updateSession(context, {
1144 status: status === "failed" ? "error" : "ready",
1145 activeTurnId: undefined,
1146 lastError: errorMessage ?? context.session.lastError,
1147 });
1148 return;
1149 }
1150
1151 if (notification.method === "error") {
1152 if (isChildConversation) {
1153 return;
1154 }
1155 const message = this.readString(this.readObject(notification.params)?.error, "message");
1156 const willRetry = this.readBoolean(notification.params, "willRetry");
1157
1158 this.updateSession(context, {
1159 status: willRetry ? "running" : "error",
1160 lastError: message ?? context.session.lastError,
1161 });
1162 }
1163 }
1164
1165 private handleServerRequest(context: CodexSessionContext, request: JsonRpcRequest): void {
1166 const rawRoute = this.readRouteFields(request.params);
1167 const childParentTurnId = this.readChildParentTurnId(context, request.params);
1168 const effectiveTurnId = childParentTurnId ?? rawRoute.turnId;
1169 const requestKind = this.requestKindForMethod(request.method);
1170 let requestId: ApprovalRequestId | undefined;
1171 if (requestKind) {
1172 requestId = ApprovalRequestId.make(randomUUID());
1173 const pendingRequest: PendingApprovalRequest = {
1174 requestId,
1175 jsonRpcId: request.id,
1176 method:
1177 requestKind === "command"
1178 ? "item/commandExecution/requestApproval"
1179 : requestKind === "file-read"
1180 ? "item/fileRead/requestApproval"
1181 : "item/fileChange/requestApproval",
1182 requestKind,
1183 threadId: context.session.threadId,
1184 ...(effectiveTurnId ? { turnId: effectiveTurnId } : {}),
1185 ...(rawRoute.itemId ? { itemId: rawRoute.itemId } : {}),
1186 };
1187 context.pendingApprovals.set(requestId, pendingRequest);
1188 }
1189
1190 if (request.method === "item/tool/requestUserInput") {
1191 requestId = ApprovalRequestId.make(randomUUID());
1192 context.pendingUserInputs.set(requestId, {
1193 requestId,
1194 jsonRpcId: request.id,
1195 threadId: context.session.threadId,
1196 ...(effectiveTurnId ? { turnId: effectiveTurnId } : {}),
1197 ...(rawRoute.itemId ? { itemId: rawRoute.itemId } : {}),
1198 });
1199 }
1200
1201 this.emitEvent({
1202 id: EventId.make(randomUUID()),
1203 kind: "request",
1204 provider: "codex",
1205 threadId: context.session.threadId,
1206 createdAt: new Date().toISOString(),
1207 method: request.method,
1208 ...(effectiveTurnId ? { turnId: effectiveTurnId } : {}),
1209 ...(rawRoute.itemId ? { itemId: rawRoute.itemId } : {}),
1210 requestId,
1211 requestKind,
1212 payload: request.params,
1213 });
1214
1215 if (requestKind) {
1216 return;
1217 }
1218
1219 if (request.method === "item/tool/requestUserInput") {
1220 return;
1221 }
1222
1223 this.writeMessage(context, {
1224 id: request.id,
1225 error: {
1226 code: -32601,
1227 message: `Unsupported server request: ${request.method}`,
1228 },
1229 });
1230 }
1231
1232 private handleResponse(context: CodexSessionContext, response: JsonRpcResponse): void {
1233 const key = String(response.id);
1234 const pending = context.pending.get(key);
1235 if (!pending) {
1236 return;
1237 }
1238
1239 clearTimeout(pending.timeout);
1240 context.pending.delete(key);
1241
1242 if (response.error?.message) {
1243 pending.reject(new Error(`${pending.method} failed: ${String(response.error.message)}`));
1244 return;
1245 }
1246
1247 pending.resolve(response.result);
1248 }
1249
1250 private async sendRequest<TResponse>(
1251 context: CodexSessionContext,
1252 method: string,
1253 params: unknown,
1254 timeoutMs = 20_000,
1255 ): Promise<TResponse> {
1256 const id = context.nextRequestId;
1257 context.nextRequestId += 1;
1258
1259 const result = await new Promise<unknown>((resolve, reject) => {
1260 const timeout = setTimeout(() => {
1261 context.pending.delete(String(id));
1262 reject(new Error(`Timed out waiting for ${method}.`));
1263 }, timeoutMs);
1264
1265 context.pending.set(String(id), {
1266 method,
1267 timeout,
1268 resolve,
1269 reject,
1270 });
1271 this.writeMessage(context, {
1272 method,
1273 id,
1274 params,
1275 });
1276 });
1277
1278 return result as TResponse;
1279 }
1280
1281 private writeMessage(context: CodexSessionContext, message: unknown): void {
1282 const encoded = JSON.stringify(message);
1283 if (!context.child.stdin.writable) {
1284 throw new Error("Cannot write to codex app-server stdin.");
1285 }
1286
1287 context.child.stdin.write(`${encoded}\n`);
1288 }
1289
1290 private emitLifecycleEvent(context: CodexSessionContext, method: string, message: string): void {
1291 this.emitEvent({
1292 id: EventId.make(randomUUID()),
1293 kind: "session",
1294 provider: "codex",
1295 threadId: context.session.threadId,
1296 createdAt: new Date().toISOString(),
1297 method,
1298 message,
1299 });
1300 }
1301
1302 private emitErrorEvent(context: CodexSessionContext, method: string, message: string): void {
1303 this.emitEvent({
1304 id: EventId.make(randomUUID()),
1305 kind: "error",
1306 provider: "codex",
1307 threadId: context.session.threadId,
1308 createdAt: new Date().toISOString(),
1309 method,
1310 message,
1311 });
1312 }
1313
1314 private emitNotificationEvent(
1315 context: CodexSessionContext,
1316 method: string,
1317 message: string,
1318 ): void {
1319 this.emitEvent({
1320 id: EventId.make(randomUUID()),
1321 kind: "notification",
1322 provider: "codex",
1323 threadId: context.session.threadId,
1324 createdAt: new Date().toISOString(),
1325 method,
1326 message,
1327 });
1328 }
1329
1330 private emitEvent(event: ProviderEvent): void {
1331 this.emit("event", event);
1332 }
1333
1334 private assertSupportedCodexCliVersion(input: {
1335 readonly binaryPath: string;
1336 readonly cwd: string;
1337 readonly homePath?: string;
1338 }): void {
1339 assertSupportedCodexCliVersion(input);
1340 }
1341
1342 private updateSession(context: CodexSessionContext, updates: Partial<ProviderSession>): void {
1343 context.session = {
1344 ...context.session,
1345 ...updates,
1346 updatedAt: new Date().toISOString(),
1347 };
1348 }
1349
1350 private requestKindForMethod(method: string): ProviderRequestKind | undefined {
1351 if (method === "item/commandExecution/requestApproval") {
1352 return "command";
1353 }
1354
1355 if (method === "item/fileRead/requestApproval") {
1356 return "file-read";
1357 }
1358
1359 if (method === "item/fileChange/requestApproval") {
1360 return "file-change";
1361 }
1362
1363 return undefined;
1364 }
1365
1366 private parseThreadSnapshot(method: string, response: unknown): CodexThreadSnapshot {
1367 const responseRecord = this.readObject(response);
1368 const thread = this.readObject(responseRecord, "thread");
1369 const threadIdRaw =
1370 this.readString(thread, "id") ?? this.readString(responseRecord, "threadId");
1371 if (!threadIdRaw) {
1372 throw new Error(`${method} response did not include a thread id.`);
1373 }
1374 const turnsRaw =
1375 this.readArray(thread, "turns") ?? this.readArray(responseRecord, "turns") ?? [];
1376 const turns = turnsRaw.map((turnValue, index) => {
1377 const turn = this.readObject(turnValue);
1378 const turnIdRaw = this.readString(turn, "id") ?? `${threadIdRaw}:turn:${index + 1}`;
1379 const turnId = TurnId.make(turnIdRaw);
1380 const items = this.readArray(turn, "items") ?? [];
1381 return {
1382 id: turnId,
1383 items,
1384 };
1385 });
1386
1387 return {
1388 threadId: threadIdRaw,
1389 turns,
1390 };
1391 }
1392
1393 private isServerRequest(value: unknown): value is JsonRpcRequest {
1394 if (!value || typeof value !== "object") {
1395 return false;
1396 }
1397
1398 const candidate = value as Record<string, unknown>;
1399 return (
1400 typeof candidate.method === "string" &&
1401 (typeof candidate.id === "string" || typeof candidate.id === "number")
1402 );
1403 }
1404
1405 private isServerNotification(value: unknown): value is JsonRpcNotification {
1406 if (!value || typeof value !== "object") {
1407 return false;
1408 }
1409
1410 const candidate = value as Record<string, unknown>;
1411 return typeof candidate.method === "string" && !("id" in candidate);
1412 }
1413
1414 private isResponse(value: unknown): value is JsonRpcResponse {
1415 if (!value || typeof value !== "object") {
1416 return false;
1417 }
1418
1419 const candidate = value as Record<string, unknown>;
1420 const hasId = typeof candidate.id === "string" || typeof candidate.id === "number";
1421 const hasMethod = typeof candidate.method === "string";
1422 return hasId && !hasMethod;
1423 }
1424
1425 private readRouteFields(params: unknown): {
1426 turnId?: TurnId;
1427 itemId?: ProviderItemId;
1428 } {
1429 const route: {
1430 turnId?: TurnId;
1431 itemId?: ProviderItemId;
1432 } = {};
1433
1434 const turnId = toTurnId(
1435 this.readString(params, "turnId") ?? this.readString(this.readObject(params, "turn"), "id"),
1436 );
1437 const itemId = toProviderItemId(
1438 this.readString(params, "itemId") ?? this.readString(this.readObject(params, "item"), "id"),
1439 );
1440
1441 if (turnId) {
1442 route.turnId = turnId;
1443 }
1444
1445 if (itemId) {
1446 route.itemId = itemId;
1447 }
1448
1449 return route;
1450 }
1451
1452 private readProviderConversationId(params: unknown): string | undefined {
1453 return (
1454 this.readString(params, "threadId") ??
1455 this.readString(this.readObject(params, "thread"), "id") ??
1456 this.readString(params, "conversationId")
1457 );
1458 }
1459
1460 private readChildParentTurnId(context: CodexSessionContext, params: unknown): TurnId | undefined {
1461 const providerConversationId = this.readProviderConversationId(params);
1462 if (!providerConversationId) {
1463 return undefined;
1464 }
1465 return context.collabReceiverTurns.get(providerConversationId);
1466 }
1467
1468 private rememberCollabReceiverTurns(
1469 context: CodexSessionContext,
1470 params: unknown,
1471 parentTurnId: TurnId | undefined,
1472 ): void {
1473 if (!parentTurnId) {
1474 return;
1475 }
1476 const payload = this.readObject(params);
1477 const item = this.readObject(payload, "item") ?? payload;
1478 const itemType = this.readString(item, "type") ?? this.readString(item, "kind");
1479 if (itemType !== "collabAgentToolCall") {
1480 return;
1481 }
1482
1483 const receiverThreadIds =
1484 this.readArray(item, "receiverThreadIds")
1485 ?.map((value) => (typeof value === "string" ? value : null))
1486 .filter((value): value is string => value !== null) ?? [];
1487 for (const receiverThreadId of receiverThreadIds) {
1488 context.collabReceiverTurns.set(receiverThreadId, parentTurnId);
1489 }
1490 }
1491
1492 private shouldSuppressChildConversationNotification(method: string): boolean {
1493 return (
1494 method === "thread/started" ||
1495 method === "thread/status/changed" ||
1496 method === "thread/archived" ||
1497 method === "thread/unarchived" ||
1498 method === "thread/closed" ||
1499 method === "thread/compacted" ||
1500 method === "thread/name/updated" ||
1501 method === "thread/tokenUsage/updated" ||
1502 method === "turn/started" ||
1503 method === "turn/completed" ||
1504 method === "turn/aborted" ||
1505 method === "turn/plan/updated" ||
1506 method === "item/plan/delta"
1507 );
1508 }
1509
1510 private readObject(value: unknown, key?: string): Record<string, unknown> | undefined {
1511 const target =
1512 key === undefined
1513 ? value
1514 : value && typeof value === "object"
1515 ? (value as Record<string, unknown>)[key]
1516 : undefined;
1517
1518 if (!target || typeof target !== "object") {
1519 return undefined;
1520 }
1521
1522 return target as Record<string, unknown>;
1523 }
1524
1525 private readArray(value: unknown, key?: string): unknown[] | undefined {
1526 const target =
1527 key === undefined
1528 ? value
1529 : value && typeof value === "object"
1530 ? (value as Record<string, unknown>)[key]
1531 : undefined;
1532 return Array.isArray(target) ? target : undefined;
1533 }
1534
1535 private readString(value: unknown, key: string): string | undefined {
1536 if (!value || typeof value !== "object") {
1537 return undefined;
1538 }
1539
1540 const candidate = (value as Record<string, unknown>)[key];
1541 return typeof candidate === "string" ? candidate : undefined;
1542 }
1543
1544 private readBoolean(value: unknown, key: string): boolean | undefined {
1545 if (!value || typeof value !== "object") {
1546 return undefined;
1547 }
1548
1549 const candidate = (value as Record<string, unknown>)[key];
1550 return typeof candidate === "boolean" ? candidate : undefined;
1551 }
1552}
1553
1554function brandIfNonEmpty<T extends string>(
1555 value: string | undefined,
1556 maker: (value: string) => T,
1557): T | undefined {
1558 const normalized = value?.trim();
1559 return normalized?.length ? maker(normalized) : undefined;
1560}
1561
1562function normalizeProviderThreadId(value: string | undefined): string | undefined {
1563 return brandIfNonEmpty(value, (normalized) => normalized);
1564}
1565
1566function assertSupportedCodexCliVersion(input: {
1567 readonly binaryPath: string;
1568 readonly cwd: string;
1569 readonly homePath?: string;
1570}): void {
1571 const result = spawnSync(input.binaryPath, ["--version"], {
1572 cwd: input.cwd,
1573 env: {
1574 ...process.env,
1575 ...(input.homePath ? { CODEX_HOME: expandHomePath(input.homePath) } : {}),
1576 },
1577 encoding: "utf8",
1578 shell: process.platform === "win32",
1579 stdio: ["ignore", "pipe", "pipe"],
1580 timeout: CODEX_VERSION_CHECK_TIMEOUT_MS,
1581 maxBuffer: 1024 * 1024,
1582 });
1583
1584 if (result.error) {
1585 const lower = result.error.message.toLowerCase();
1586 if (
1587 lower.includes("enoent") ||
1588 lower.includes("command not found") ||
1589 lower.includes("not found")
1590 ) {
1591 throw new Error(`Codex CLI (${input.binaryPath}) is not installed or not executable.`);
1592 }
1593 throw new Error(
1594 `Failed to execute Codex CLI version check: ${result.error.message || String(result.error)}`,
1595 );
1596 }
1597
1598 const stdout = result.stdout ?? "";
1599 const stderr = result.stderr ?? "";
1600 if (result.status !== 0) {
1601 const detail = stderr.trim() || stdout.trim() || `Command exited with code ${result.status}.`;
1602 throw new Error(`Codex CLI version check failed. ${detail}`);
1603 }
1604
1605 const parsedVersion = parseCodexCliVersion(`${stdout}\n${stderr}`);
1606 if (parsedVersion && !isCodexCliVersionSupported(parsedVersion)) {
1607 throw new Error(formatCodexCliUpgradeMessage(parsedVersion));
1608 }
1609}
1610
1611function readResumeCursorThreadId(resumeCursor: unknown): string | undefined {
1612 if (!resumeCursor || typeof resumeCursor !== "object" || Array.isArray(resumeCursor)) {
1613 return undefined;
1614 }
1615 const rawThreadId = (resumeCursor as Record<string, unknown>).threadId;
1616 return typeof rawThreadId === "string" ? normalizeProviderThreadId(rawThreadId) : undefined;
1617}
1618
1619function readResumeThreadId(input: {
1620 readonly resumeCursor?: unknown;
1621 readonly threadId?: ThreadId;
1622 readonly runtimeMode?: RuntimeMode;
1623}): string | undefined {
1624 return readResumeCursorThreadId(input.resumeCursor);
1625}
1626
1627function toTurnId(value: string | undefined): TurnId | undefined {
1628 return brandIfNonEmpty(value, TurnId.make);
1629}
1630
1631function toProviderItemId(value: string | undefined): ProviderItemId | undefined {
1632 return brandIfNonEmpty(value, ProviderItemId.make);
1633}
apps/server/src/git/Layers/CodexTextGeneration.ts+1-7
...@@ -29,9 +29,7 @@ import {...@@ -29,9 +29,7 @@ import {
29 sanitizeThreadTitle,29 sanitizeThreadTitle,
30 toJsonSchemaObject,30 toJsonSchemaObject,
31} from "../Utils.ts";31} from "../Utils.ts";
32import { getCodexModelCapabilities } from "../../provider/Layers/CodexProvider.ts";
33import { ServerSettingsService } from "../../serverSettings.ts";32import { ServerSettingsService } from "../../serverSettings.ts";
34import { normalizeCodexModelOptionsWithCapabilities } from "@t3tools/shared/model";
3533
36const CODEX_GIT_TEXT_GENERATION_REASONING_EFFORT = "low";34const CODEX_GIT_TEXT_GENERATION_REASONING_EFFORT = "low";
37const CODEX_TIMEOUT_MS = 180_000;35const CODEX_TIMEOUT_MS = 180_000;
...@@ -156,10 +154,6 @@ const makeCodexTextGeneration = Effect.gen(function* () {...@@ -156,10 +154,6 @@ const makeCodexTextGeneration = Effect.gen(function* () {
156 ).pipe(Effect.catch(() => Effect.undefined));154 ).pipe(Effect.catch(() => Effect.undefined));
157155
158 const runCodexCommand = Effect.fn("runCodexJson.runCodexCommand")(function* () {156 const runCodexCommand = Effect.fn("runCodexJson.runCodexCommand")(function* () {
159 const normalizedOptions = normalizeCodexModelOptionsWithCapabilities(
160 getCodexModelCapabilities(modelSelection.model),
161 modelSelection.options,
162 );
163 const reasoningEffort =157 const reasoningEffort =
164 modelSelection.options?.reasoningEffort ?? CODEX_GIT_TEXT_GENERATION_REASONING_EFFORT;158 modelSelection.options?.reasoningEffort ?? CODEX_GIT_TEXT_GENERATION_REASONING_EFFORT;
165 const command = ChildProcess.make(159 const command = ChildProcess.make(
...@@ -174,7 +168,7 @@ const makeCodexTextGeneration = Effect.gen(function* () {...@@ -174,7 +168,7 @@ const makeCodexTextGeneration = Effect.gen(function* () {
174 modelSelection.model,168 modelSelection.model,
175 "--config",169 "--config",
176 `model_reasoning_effort="${reasoningEffort}"`,170 `model_reasoning_effort="${reasoningEffort}"`,
177 ...(normalizedOptions?.fastMode ? ["--config", `service_tier="fast"`] : []),171 ...(modelSelection.options?.fastMode ? ["--config", `service_tier="fast"`] : []),
178 "--output-schema",172 "--output-schema",
179 schemaPath,173 schemaPath,
180 "--output-last-message",174 "--output-last-message",
apps/server/src/provider/CodexDeveloperInstructions.ts created+134
...@@ -0,0 +1,134 @@
1export const CODEX_PLAN_MODE_DEVELOPER_INSTRUCTIONS = `<collaboration_mode># Plan Mode (Conversational)
2
3You 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.
4
5## Mode rules (strict)
6
7You are in **Plan Mode** until a developer message explicitly ends it.
8
9Plan 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.
10
11## Plan Mode vs update_plan tool
12
13Plan Mode is a collaboration mode that can involve requesting user input and eventually issuing a \`<proposed_plan>\` block.
14
15Separately, \`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.
16
17## Execution vs. mutation in Plan Mode
18
19You may explore and execute **non-mutating** actions that improve the plan. You must not perform **mutating** actions.
20
21### Allowed (non-mutating, plan-improving)
22
23Actions that gather truth, reduce ambiguity, or validate feasibility without changing repo-tracked state. Examples:
24
25* Reading or searching files, configs, schemas, types, manifests, and docs
26* Static analysis, inspection, and repo exploration
27* Dry-run style commands when they do not edit repo-tracked files
28* 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
29
30### Not allowed (mutating, plan-executing)
31
32Actions that implement the plan or change repo-tracked state. Examples:
33
34* Editing or writing files
35* Running formatters or linters that rewrite files
36* Applying patches, migrations, or codegen that updates repo-tracked files
37* Side-effectful commands whose purpose is to carry out the plan rather than refine it
38
39When in doubt: if the action would reasonably be described as "doing the work" rather than "planning the work," do not do it.
40
41## PHASE 1 - Ground in the environment (explore first, ask second)
42
43Begin 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.
44
45Before 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.
46
47Exception: 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.
48
49Do 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.
50
51## PHASE 2 - Intent chat (what they actually want)
52
53* Keep asking until you can clearly state: goal + success criteria, audience, in/out of scope, constraints, current state, and the key preferences/tradeoffs.
54* Bias toward questions over guessing: if any high-impact ambiguity remains, do NOT plan yet-ask.
55
56## PHASE 3 - Implementation chat (what/how we'll build)
57
58* 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.
59
60## Asking questions
61
62Critical rules:
63
64* Strongly prefer using the \`request_user_input\` tool to ask any questions.
65* Offer only meaningful multiple-choice options; don't include filler choices that are obviously wrong or irrelevant.
66* 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.
67
68You SHOULD ask many questions, but each question must:
69
70* materially change the spec/plan, OR
71* confirm/lock an assumption, OR
72* choose between meaningful tradeoffs.
73* not be answerable by non-mutating commands.
74
75Use 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.
76
77## Two kinds of unknowns (treat differently)
78
791. **Discoverable facts** (repo/system truth): explore first.
80
81 * Before asking, run targeted searches and check likely sources of truth (configs/manifests/entrypoints/schemas/types/constants).
82 * Ask only if: multiple plausible candidates; nothing found but you need a missing identifier/context; or ambiguity is actually product intent.
83 * If asking, present concrete candidates (paths/service names) + recommend one.
84 * Never ask questions you can answer from your environment (e.g., "where is this struct").
85
862. **Preferences/tradeoffs** (not discoverable): ask early.
87
88 * These are intent or implementation preferences that cannot be derived from exploration.
89 * Provide 2-4 mutually exclusive options + a recommended default.
90 * If unanswered, proceed with the recommended option and record it as an assumption in the final plan.
91
92## Finalization rule
93
94Only output the final plan when it is decision complete and leaves no decisions to the implementer.
95
96When you present the official plan, wrap it in a \`<proposed_plan>\` block so the client can render it specially:
97
981) The opening tag must be on its own line.
992) Start the plan content on the next line (no text on the same line as the tag).
1003) The closing tag must be on its own line.
1014) Use Markdown inside the block.
1025) Keep the tags exactly as \`<proposed_plan>\` and \`</proposed_plan>\` (do not translate or rename them), even if the plan content is in another language.
103
104Example:
105
106<proposed_plan>
107plan content
108</proposed_plan>
109
110plan content should be human and agent digestible. The final plan must be plan-only and include:
111
112* A clear title
113* A brief summary section
114* Important changes or additions to public APIs/interfaces/types
115* Test cases and scenarios
116* Explicit assumptions and defaults chosen where needed
117
118Do 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 \`<proposed_plan>\` block in your response. Alternatively, they can decide to stay in Plan mode and continue refining the plan.
119
120Only produce at most one \`<proposed_plan>\` block per turn, and only when you are presenting a complete spec.
121</collaboration_mode>`;
122
123export const CODEX_DEFAULT_MODE_DEVELOPER_INSTRUCTIONS = `<collaboration_mode># Collaboration Mode: Default
124
125You are now in Default mode. Any previous instructions for other modes (e.g. Plan mode) are no longer active.
126
127Your active mode changes only when new developer instructions with a different \`<collaboration_mode>...</collaboration_mode>\` change it; user requests or tool descriptions do not change mode by themselves. Known mode names are Default and Plan.
128
129## request_user_input availability
130
131The \`request_user_input\` tool is unavailable in Default mode. If you call it while in Default mode, it will return an error.
132
133In 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.
134</collaboration_mode>`;
apps/server/src/provider/Layers/CodexAdapter.test.ts+348-302
...@@ -1,4 +1,7 @@...@@ -1,4 +1,7 @@
1import assert from "node:assert/strict";1import assert from "node:assert/strict";
2import fs from "node:fs";
3import os from "node:os";
4import path from "node:path";
2import {5import {
3 ApprovalRequestId,6 ApprovalRequestId,
4 EventId,7 EventId,
...@@ -12,20 +15,22 @@ import {...@@ -12,20 +15,22 @@ import {
12 TurnId,15 TurnId,
13} from "@t3tools/contracts";16} from "@t3tools/contracts";
14import * as NodeServices from "@effect/platform-node/NodeServices";17import * as NodeServices from "@effect/platform-node/NodeServices";
15import { afterAll, it, vi } from "@effect/vitest";18import { it, vi } from "@effect/vitest";
1619
17import { Effect, Fiber, Layer, Option, Stream } from "effect";20import { Effect, Exit, Fiber, Layer, Option, Queue, Scope, Stream } from "effect";
21import * as CodexErrors from "effect-codex-app-server/errors";
1822
19import {
20 CodexAppServerManager,
21 type CodexAppServerStartSessionInput,
22 type CodexAppServerSendTurnInput,
23} from "../../codexAppServerManager.ts";
24import { ServerConfig } from "../../config.ts";23import { ServerConfig } from "../../config.ts";
25import { ServerSettingsService } from "../../serverSettings.ts";24import { ServerSettingsService } from "../../serverSettings.ts";
26import { ProviderAdapterValidationError } from "../Errors.ts";25import { ProviderAdapterValidationError } from "../Errors.ts";
27import { CodexAdapter } from "../Services/CodexAdapter.ts";26import { CodexAdapter } from "../Services/CodexAdapter.ts";
28import { ProviderSessionDirectory } from "../Services/ProviderSessionDirectory.ts";27import { ProviderSessionDirectory } from "../Services/ProviderSessionDirectory.ts";
28import {
29 type CodexSessionRuntimeOptions,
30 type CodexSessionRuntimeSendTurnInput,
31 type CodexSessionRuntimeShape,
32 type CodexThreadSnapshot,
33} from "./CodexSessionRuntime.ts";
29import { makeCodexAdapterLive } from "./CodexAdapter.ts";34import { makeCodexAdapterLive } from "./CodexAdapter.ts";
3035
31const asThreadId = (value: string): ThreadId => ThreadId.make(value);36const asThreadId = (value: string): ThreadId => ThreadId.make(value);
...@@ -33,112 +38,159 @@ const asTurnId = (value: string): TurnId => TurnId.make(value);...@@ -33,112 +38,159 @@ const asTurnId = (value: string): TurnId => TurnId.make(value);
33const asEventId = (value: string): EventId => EventId.make(value);38const asEventId = (value: string): EventId => EventId.make(value);
34const asItemId = (value: string): ProviderItemId => ProviderItemId.make(value);39const asItemId = (value: string): ProviderItemId => ProviderItemId.make(value);
3540
36class FakeCodexManager extends CodexAppServerManager {41class FakeCodexRuntime implements CodexSessionRuntimeShape {
37 public startSessionImpl = vi.fn(42 private readonly eventQueue = Effect.runSync(Queue.unbounded<ProviderEvent>());
38 async (input: CodexAppServerStartSessionInput): Promise<ProviderSession> => {43 private readonly now = new Date().toISOString();
39 const now = new Date().toISOString();44
40 return {45 public readonly startImpl = vi.fn(() =>
41 provider: "codex",46 Promise.resolve({
42 status: "ready",47 provider: "codex" as const,
43 runtimeMode: input.runtimeMode,48 status: "ready" as const,
44 threadId: input.threadId,49 runtimeMode: this.options.runtimeMode,
45 cwd: input.cwd,50 threadId: this.options.threadId,
46 createdAt: now,51 cwd: this.options.cwd,
47 updatedAt: now,52 ...(this.options.model ? { model: this.options.model } : {}),
48 };53 createdAt: this.now,
49 },54 updatedAt: this.now,
55 } satisfies ProviderSession),
50 );56 );
5157
52 public sendTurnImpl = vi.fn(58 public readonly sendTurnImpl = vi.fn(
53 async (_input: CodexAppServerSendTurnInput): Promise<ProviderTurnStartResult> => ({59 (_input: CodexSessionRuntimeSendTurnInput): Promise<ProviderTurnStartResult> =>
54 threadId: asThreadId("thread-1"),60 Promise.resolve({
55 turnId: asTurnId("turn-1"),61 threadId: this.options.threadId,
56 }),62 turnId: asTurnId("turn-1"),
63 }),
57 );64 );
5865
59 public interruptTurnImpl = vi.fn(66 public readonly interruptTurnImpl = vi.fn(
60 async (_threadId: ThreadId, _turnId?: TurnId): Promise<void> => undefined,67 (_turnId?: TurnId): Promise<void> => Promise.resolve(undefined),
61 );68 );
6269
63 public readThreadImpl = vi.fn(async (_threadId: ThreadId) => ({70 public readonly readThreadImpl = vi.fn(
64 threadId: asThreadId("thread-1"),71 (): Promise<CodexThreadSnapshot> =>
65 turns: [],72 Promise.resolve({
66 }));73 threadId: "provider-thread-1",
6774 turns: [],
68 public rollbackThreadImpl = vi.fn(async (_threadId: ThreadId, _numTurns: number) => ({75 }),
69 threadId: asThreadId("thread-1"),
70 turns: [],
71 }));
72
73 public respondToRequestImpl = vi.fn(
74 async (
75 _threadId: ThreadId,
76 _requestId: ApprovalRequestId,
77 _decision: ProviderApprovalDecision,
78 ): Promise<void> => undefined,
79 );76 );
8077
81 public respondToUserInputImpl = vi.fn(78 public readonly rollbackThreadImpl = vi.fn(
82 async (79 (_numTurns: number): Promise<CodexThreadSnapshot> =>
83 _threadId: ThreadId,80 Promise.resolve({
84 _requestId: ApprovalRequestId,81 threadId: "provider-thread-1",
85 _answers: ProviderUserInputAnswers,82 turns: [],
86 ): Promise<void> => undefined,83 }),
87 );84 );
8885
89 public stopAllImpl = vi.fn(() => undefined);86 public readonly respondToRequestImpl = vi.fn(
87 (_requestId: ApprovalRequestId, _decision: ProviderApprovalDecision): Promise<void> =>
88 Promise.resolve(undefined),
89 );
9090
91 override startSession(input: CodexAppServerStartSessionInput): Promise<ProviderSession> {91 public readonly respondToUserInputImpl = vi.fn(
92 return this.startSessionImpl(input);92 (_requestId: ApprovalRequestId, _answers: ProviderUserInputAnswers): Promise<void> =>
93 }93 Promise.resolve(undefined),
94 );
9495
95 override sendTurn(input: CodexAppServerSendTurnInput): Promise<ProviderTurnStartResult> {96 public readonly closeImpl = vi.fn(() => Promise.resolve(undefined));
96 return this.sendTurnImpl(input);97
97 }98 readonly options: CodexSessionRuntimeOptions;
9899
99 override interruptTurn(threadId: ThreadId, turnId?: TurnId): Promise<void> {100 constructor(options: CodexSessionRuntimeOptions) {
100 return this.interruptTurnImpl(threadId, turnId);101 this.options = options;
101 }102 }
102103
103 override readThread(threadId: ThreadId) {104 start() {
104 return this.readThreadImpl(threadId);105 return Effect.promise(() => this.startImpl());
105 }106 }
106107
107 override rollbackThread(threadId: ThreadId, numTurns: number) {108 getSession = Effect.promise(() => this.startImpl());
108 return this.rollbackThreadImpl(threadId, numTurns);109
110 sendTurn(input: CodexSessionRuntimeSendTurnInput) {
111 return Effect.promise(() => this.sendTurnImpl(input));
109 }112 }
110113
111 override respondToRequest(114 interruptTurn(turnId?: TurnId) {
112 threadId: ThreadId,115 return Effect.promise(() => this.interruptTurnImpl(turnId));
113 requestId: ApprovalRequestId,
114 decision: ProviderApprovalDecision,
115 ): Promise<void> {
116 return this.respondToRequestImpl(threadId, requestId, decision);
117 }116 }
118117
119 override respondToUserInput(118 readThread = Effect.promise(() => this.readThreadImpl());
120 threadId: ThreadId,119
121 requestId: ApprovalRequestId,120 rollbackThread(numTurns: number) {
122 answers: ProviderUserInputAnswers,121 return Effect.promise(() => this.rollbackThreadImpl(numTurns));
123 ): Promise<void> {
124 return this.respondToUserInputImpl(threadId, requestId, answers);
125 }122 }
126123
127 override stopSession(_threadId: ThreadId): void {}124 respondToRequest(requestId: ApprovalRequestId, decision: ProviderApprovalDecision) {
125 return Effect.promise(() => this.respondToRequestImpl(requestId, decision));
126 }
128127
129 override listSessions(): ProviderSession[] {128 respondToUserInput(requestId: ApprovalRequestId, answers: ProviderUserInputAnswers) {
130 return [];129 return Effect.promise(() => this.respondToUserInputImpl(requestId, answers));
131 }130 }
132131
133 override hasSession(_threadId: ThreadId): boolean {132 get events() {
134 return false;133 return Stream.fromQueue(this.eventQueue);
135 }134 }
136135
137 override stopAll(): void {136 close = Effect.promise(() => this.closeImpl());
138 this.stopAllImpl();137
138 emit(event: ProviderEvent) {
139 return Queue.offer(this.eventQueue, event).pipe(Effect.asVoid);
139 }140 }
140}141}
141142
143function makeRuntimeFactory() {
144 const runtimes: Array<FakeCodexRuntime> = [];
145 const factory = vi.fn((options: CodexSessionRuntimeOptions) => {
146 const runtime = new FakeCodexRuntime(options);
147 runtimes.push(runtime);
148 return Effect.succeed(runtime);
149 });
150
151 return {
152 factory,
153 get lastRuntime(): FakeCodexRuntime | undefined {
154 return runtimes.at(-1);
155 },
156 };
157}
158
159function makeScopedRuntimeFactory(options?: { readonly failConstruction?: boolean }) {
160 const runtimes: Array<FakeCodexRuntime> = [];
161 const releasedThreadIds: Array<ThreadId> = [];
162
163 const factory = vi.fn((runtimeOptions: CodexSessionRuntimeOptions) =>
164 Effect.gen(function* () {
165 yield* Scope.Scope;
166 yield* Effect.addFinalizer(() =>
167 Effect.sync(() => {
168 releasedThreadIds.push(runtimeOptions.threadId);
169 }),
170 );
171
172 if (options?.failConstruction) {
173 return yield* new CodexErrors.CodexAppServerSpawnError({
174 command: `${runtimeOptions.binaryPath} app-server`,
175 cause: new Error("runtime construction failed"),
176 });
177 }
178
179 const runtime = new FakeCodexRuntime(runtimeOptions);
180 runtimes.push(runtime);
181 return runtime;
182 }),
183 );
184
185 return {
186 factory,
187 releasedThreadIds,
188 get lastRuntime(): FakeCodexRuntime | undefined {
189 return runtimes.at(-1);
190 },
191 };
192}
193
142const providerSessionDirectoryTestLayer = Layer.succeed(ProviderSessionDirectory, {194const providerSessionDirectoryTestLayer = Layer.succeed(ProviderSessionDirectory, {
143 upsert: () => Effect.void,195 upsert: () => Effect.void,
144 getProvider: () =>196 getProvider: () =>
...@@ -148,9 +200,9 @@ const providerSessionDirectoryTestLayer = Layer.succeed(ProviderSessionDirectory...@@ -148,9 +200,9 @@ const providerSessionDirectoryTestLayer = Layer.succeed(ProviderSessionDirectory
148 listBindings: () => Effect.succeed([]),200 listBindings: () => Effect.succeed([]),
149});201});
150202
151const validationManager = new FakeCodexManager();203const validationRuntimeFactory = makeRuntimeFactory();
152const validationLayer = it.layer(204const validationLayer = it.layer(
153 makeCodexAdapterLive({ manager: validationManager }).pipe(205 makeCodexAdapterLive({ makeRuntime: validationRuntimeFactory.factory }).pipe(
154 Layer.provideMerge(ServerConfig.layerTest(process.cwd(), process.cwd())),206 Layer.provideMerge(ServerConfig.layerTest(process.cwd(), process.cwd())),
155 Layer.provideMerge(ServerSettingsService.layerTest()),207 Layer.provideMerge(ServerSettingsService.layerTest()),
156 Layer.provideMerge(providerSessionDirectoryTestLayer),208 Layer.provideMerge(providerSessionDirectoryTestLayer),
...@@ -179,12 +231,12 @@ validationLayer("CodexAdapterLive validation", (it) => {...@@ -179,12 +231,12 @@ validationLayer("CodexAdapterLive validation", (it) => {
179 issue: "Expected provider 'codex' but received 'claudeAgent'.",231 issue: "Expected provider 'codex' but received 'claudeAgent'.",
180 }),232 }),
181 );233 );
182 assert.equal(validationManager.startSessionImpl.mock.calls.length, 0);234 assert.equal(validationRuntimeFactory.factory.mock.calls.length, 0);
183 }),235 }),
184 );236 );
185 it.effect("maps codex model options before starting a session", () =>237 it.effect("maps codex model options before starting a session", () =>
186 Effect.gen(function* () {238 Effect.gen(function* () {
187 validationManager.startSessionImpl.mockClear();239 validationRuntimeFactory.factory.mockClear();
188 const adapter = yield* CodexAdapter;240 const adapter = yield* CodexAdapter;
189241
190 yield* adapter.startSession({242 yield* adapter.startSession({
...@@ -200,24 +252,21 @@ validationLayer("CodexAdapterLive validation", (it) => {...@@ -200,24 +252,21 @@ validationLayer("CodexAdapterLive validation", (it) => {
200 runtimeMode: "full-access",252 runtimeMode: "full-access",
201 });253 });
202254
203 assert.deepStrictEqual(validationManager.startSessionImpl.mock.calls[0]?.[0], {255 assert.deepStrictEqual(validationRuntimeFactory.factory.mock.calls[0]?.[0], {
204 provider: "codex",
205 threadId: asThreadId("thread-1"),
206 binaryPath: "codex",256 binaryPath: "codex",
257 cwd: process.cwd(),
207 model: "gpt-5.3-codex",258 model: "gpt-5.3-codex",
208 serviceTier: "fast",259 serviceTier: "fast",
260 threadId: asThreadId("thread-1"),
209 runtimeMode: "full-access",261 runtimeMode: "full-access",
210 });262 });
211 }),263 }),
212 );264 );
213});265});
214266
215const sessionErrorManager = new FakeCodexManager();267const sessionRuntimeFactory = makeRuntimeFactory();
216sessionErrorManager.sendTurnImpl.mockImplementation(async () => {
217 throw new Error("Unknown session: sess-missing");
218});
219const sessionErrorLayer = it.layer(268const sessionErrorLayer = it.layer(
220 makeCodexAdapterLive({ manager: sessionErrorManager }).pipe(269 makeCodexAdapterLive({ makeRuntime: sessionRuntimeFactory.factory }).pipe(
221 Layer.provideMerge(ServerConfig.layerTest(process.cwd(), process.cwd())),270 Layer.provideMerge(ServerConfig.layerTest(process.cwd(), process.cwd())),
222 Layer.provideMerge(ServerSettingsService.layerTest()),271 Layer.provideMerge(ServerSettingsService.layerTest()),
223 Layer.provideMerge(providerSessionDirectoryTestLayer),272 Layer.provideMerge(providerSessionDirectoryTestLayer),
...@@ -226,7 +275,7 @@ const sessionErrorLayer = it.layer(...@@ -226,7 +275,7 @@ const sessionErrorLayer = it.layer(
226);275);
227276
228sessionErrorLayer("CodexAdapterLive session errors", (it) => {277sessionErrorLayer("CodexAdapterLive session errors", (it) => {
229 it.effect("maps unknown-session sendTurn errors to ProviderAdapterSessionNotFoundError", () =>278 it.effect("maps missing adapter sessions to ProviderAdapterSessionNotFoundError", () =>
230 Effect.gen(function* () {279 Effect.gen(function* () {
231 const adapter = yield* CodexAdapter;280 const adapter = yield* CodexAdapter;
232 const result = yield* adapter281 const result = yield* adapter
...@@ -241,14 +290,20 @@ sessionErrorLayer("CodexAdapterLive session errors", (it) => {...@@ -241,14 +290,20 @@ sessionErrorLayer("CodexAdapterLive session errors", (it) => {
241 assert.equal(result.failure._tag, "ProviderAdapterSessionNotFoundError");290 assert.equal(result.failure._tag, "ProviderAdapterSessionNotFoundError");
242 assert.equal(result.failure.provider, "codex");291 assert.equal(result.failure.provider, "codex");
243 assert.equal(result.failure.threadId, "sess-missing");292 assert.equal(result.failure.threadId, "sess-missing");
244 assert.equal(result.failure.cause instanceof Error, true);
245 }),293 }),
246 );294 );
247295
248 it.effect("maps codex model options before sending a turn", () =>296 it.effect("maps codex model options before sending a turn", () =>
249 Effect.gen(function* () {297 Effect.gen(function* () {
250 sessionErrorManager.sendTurnImpl.mockClear();
251 const adapter = yield* CodexAdapter;298 const adapter = yield* CodexAdapter;
299 yield* adapter.startSession({
300 provider: "codex",
301 threadId: asThreadId("sess-missing"),
302 runtimeMode: "full-access",
303 });
304 const runtime = sessionRuntimeFactory.lastRuntime;
305 assert.ok(runtime);
306 runtime.sendTurnImpl.mockClear();
252307
253 yield* Effect.ignore(308 yield* Effect.ignore(
254 adapter.sendTurn({309 adapter.sendTurn({
...@@ -266,8 +321,7 @@ sessionErrorLayer("CodexAdapterLive session errors", (it) => {...@@ -266,8 +321,7 @@ sessionErrorLayer("CodexAdapterLive session errors", (it) => {
266 }),321 }),
267 );322 );
268323
269 assert.deepStrictEqual(sessionErrorManager.sendTurnImpl.mock.calls[0]?.[0], {324 assert.deepStrictEqual(runtime.sendTurnImpl.mock.calls[0]?.[0], {
270 threadId: asThreadId("sess-missing"),
271 input: "hello",325 input: "hello",
272 model: "gpt-5.3-codex",326 model: "gpt-5.3-codex",
273 effort: "high",327 effort: "high",
...@@ -277,9 +331,9 @@ sessionErrorLayer("CodexAdapterLive session errors", (it) => {...@@ -277,9 +331,9 @@ sessionErrorLayer("CodexAdapterLive session errors", (it) => {
277 );331 );
278});332});
279333
280const lifecycleManager = new FakeCodexManager();334const lifecycleRuntimeFactory = makeRuntimeFactory();
281const lifecycleLayer = it.layer(335const lifecycleLayer = it.layer(
282 makeCodexAdapterLive({ manager: lifecycleManager }).pipe(336 makeCodexAdapterLive({ makeRuntime: lifecycleRuntimeFactory.factory }).pipe(
283 Layer.provideMerge(ServerConfig.layerTest(process.cwd(), process.cwd())),337 Layer.provideMerge(ServerConfig.layerTest(process.cwd(), process.cwd())),
284 Layer.provideMerge(ServerSettingsService.layerTest()),338 Layer.provideMerge(ServerSettingsService.layerTest()),
285 Layer.provideMerge(providerSessionDirectoryTestLayer),339 Layer.provideMerge(providerSessionDirectoryTestLayer),
...@@ -287,10 +341,24 @@ const lifecycleLayer = it.layer(...@@ -287,10 +341,24 @@ const lifecycleLayer = it.layer(
287 ),341 ),
288);342);
289343
344function startLifecycleRuntime() {
345 return Effect.gen(function* () {
346 const adapter = yield* CodexAdapter;
347 yield* adapter.startSession({
348 provider: "codex",
349 threadId: asThreadId("thread-1"),
350 runtimeMode: "full-access",
351 });
352 const runtime = lifecycleRuntimeFactory.lastRuntime;
353 assert.ok(runtime);
354 return { adapter, runtime };
355 });
356}
357
290lifecycleLayer("CodexAdapterLive lifecycle", (it) => {358lifecycleLayer("CodexAdapterLive lifecycle", (it) => {
291 it.effect("maps completed agent message items to canonical item.completed events", () =>359 it.effect("maps completed agent message items to canonical item.completed events", () =>
292 Effect.gen(function* () {360 Effect.gen(function* () {
293 const adapter = yield* CodexAdapter;361 const { adapter, runtime } = yield* startLifecycleRuntime();
294 const firstEventFiber = yield* Stream.runHead(adapter.streamEvents).pipe(Effect.forkChild);362 const firstEventFiber = yield* Stream.runHead(adapter.streamEvents).pipe(Effect.forkChild);
295363
296 const event: ProviderEvent = {364 const event: ProviderEvent = {
...@@ -303,14 +371,17 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => {...@@ -303,14 +371,17 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => {
303 turnId: asTurnId("turn-1"),371 turnId: asTurnId("turn-1"),
304 itemId: asItemId("msg_1"),372 itemId: asItemId("msg_1"),
305 payload: {373 payload: {
374 threadId: "thread-1",
375 turnId: "turn-1",
306 item: {376 item: {
307 type: "agentMessage",377 type: "agentMessage",
308 id: "msg_1",378 id: "msg_1",
379 text: "done",
309 },380 },
310 },381 },
311 };382 };
312383
313 lifecycleManager.emit("event", event);384 yield* runtime.emit(event);
314 const firstEvent = yield* Fiber.join(firstEventFiber);385 const firstEvent = yield* Fiber.join(firstEventFiber);
315386
316 assert.equal(firstEvent._tag, "Some");387 assert.equal(firstEvent._tag, "Some");
...@@ -329,7 +400,7 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => {...@@ -329,7 +400,7 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => {
329400
330 it.effect("maps completed plan items to canonical proposed-plan completion events", () =>401 it.effect("maps completed plan items to canonical proposed-plan completion events", () =>
331 Effect.gen(function* () {402 Effect.gen(function* () {
332 const adapter = yield* CodexAdapter;403 const { adapter, runtime } = yield* startLifecycleRuntime();
333 const firstEventFiber = yield* Stream.runHead(adapter.streamEvents).pipe(Effect.forkChild);404 const firstEventFiber = yield* Stream.runHead(adapter.streamEvents).pipe(Effect.forkChild);
334405
335 const event: ProviderEvent = {406 const event: ProviderEvent = {
...@@ -342,15 +413,17 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => {...@@ -342,15 +413,17 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => {
342 turnId: asTurnId("turn-1"),413 turnId: asTurnId("turn-1"),
343 itemId: asItemId("plan_1"),414 itemId: asItemId("plan_1"),
344 payload: {415 payload: {
416 threadId: "thread-1",
417 turnId: "turn-1",
345 item: {418 item: {
346 type: "Plan",419 type: "plan",
347 id: "plan_1",420 id: "plan_1",
348 text: "## Final plan\n\n- one\n- two",421 text: "## Final plan\n\n- one\n- two",
349 },422 },
350 },423 },
351 };424 };
352425
353 lifecycleManager.emit("event", event);426 yield* runtime.emit(event);
354 const firstEvent = yield* Fiber.join(firstEventFiber);427 const firstEvent = yield* Fiber.join(firstEventFiber);
355428
356 assert.equal(firstEvent._tag, "Some");429 assert.equal(firstEvent._tag, "Some");
...@@ -368,10 +441,10 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => {...@@ -368,10 +441,10 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => {
368441
369 it.effect("maps plan deltas to canonical proposed-plan delta events", () =>442 it.effect("maps plan deltas to canonical proposed-plan delta events", () =>
370 Effect.gen(function* () {443 Effect.gen(function* () {
371 const adapter = yield* CodexAdapter;444 const { adapter, runtime } = yield* startLifecycleRuntime();
372 const firstEventFiber = yield* Stream.runHead(adapter.streamEvents).pipe(Effect.forkChild);445 const firstEventFiber = yield* Stream.runHead(adapter.streamEvents).pipe(Effect.forkChild);
373446
374 lifecycleManager.emit("event", {447 yield* runtime.emit({
375 id: asEventId("evt-plan-delta"),448 id: asEventId("evt-plan-delta"),
376 kind: "notification",449 kind: "notification",
377 provider: "codex",450 provider: "codex",
...@@ -381,6 +454,9 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => {...@@ -381,6 +454,9 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => {
381 turnId: asTurnId("turn-1"),454 turnId: asTurnId("turn-1"),
382 itemId: asItemId("plan_1"),455 itemId: asItemId("plan_1"),
383 payload: {456 payload: {
457 threadId: "thread-1",
458 turnId: "turn-1",
459 itemId: "plan_1",
384 delta: "## Final plan",460 delta: "## Final plan",
385 },461 },
386 } satisfies ProviderEvent);462 } satisfies ProviderEvent);
...@@ -402,7 +478,7 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => {...@@ -402,7 +478,7 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => {
402478
403 it.effect("maps session/closed lifecycle events to canonical session.exited runtime events", () =>479 it.effect("maps session/closed lifecycle events to canonical session.exited runtime events", () =>
404 Effect.gen(function* () {480 Effect.gen(function* () {
405 const adapter = yield* CodexAdapter;481 const { adapter, runtime } = yield* startLifecycleRuntime();
406 const firstEventFiber = yield* Stream.runHead(adapter.streamEvents).pipe(Effect.forkChild);482 const firstEventFiber = yield* Stream.runHead(adapter.streamEvents).pipe(Effect.forkChild);
407483
408 const event: ProviderEvent = {484 const event: ProviderEvent = {
...@@ -415,7 +491,7 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => {...@@ -415,7 +491,7 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => {
415 message: "Session stopped",491 message: "Session stopped",
416 };492 };
417493
418 lifecycleManager.emit("event", event);494 yield* runtime.emit(event);
419 const firstEvent = yield* Fiber.join(firstEventFiber);495 const firstEvent = yield* Fiber.join(firstEventFiber);
420496
421 assert.equal(firstEvent._tag, "Some");497 assert.equal(firstEvent._tag, "Some");
...@@ -433,10 +509,10 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => {...@@ -433,10 +509,10 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => {
433509
434 it.effect("maps retryable Codex error notifications to runtime.warning", () =>510 it.effect("maps retryable Codex error notifications to runtime.warning", () =>
435 Effect.gen(function* () {511 Effect.gen(function* () {
436 const adapter = yield* CodexAdapter;512 const { adapter, runtime } = yield* startLifecycleRuntime();
437 const firstEventFiber = yield* Stream.runHead(adapter.streamEvents).pipe(Effect.forkChild);513 const firstEventFiber = yield* Stream.runHead(adapter.streamEvents).pipe(Effect.forkChild);
438514
439 lifecycleManager.emit("event", {515 yield* runtime.emit({
440 id: asEventId("evt-retryable-error"),516 id: asEventId("evt-retryable-error"),
441 kind: "notification",517 kind: "notification",
442 provider: "codex",518 provider: "codex",
...@@ -445,6 +521,8 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => {...@@ -445,6 +521,8 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => {
445 method: "error",521 method: "error",
446 turnId: asTurnId("turn-1"),522 turnId: asTurnId("turn-1"),
447 payload: {523 payload: {
524 threadId: "thread-1",
525 turnId: "turn-1",
448 error: {526 error: {
449 message: "Reconnecting... 2/5",527 message: "Reconnecting... 2/5",
450 },528 },
...@@ -469,10 +547,10 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => {...@@ -469,10 +547,10 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => {
469547
470 it.effect("maps process stderr notifications to runtime.warning", () =>548 it.effect("maps process stderr notifications to runtime.warning", () =>
471 Effect.gen(function* () {549 Effect.gen(function* () {
472 const adapter = yield* CodexAdapter;550 const { adapter, runtime } = yield* startLifecycleRuntime();
473 const firstEventFiber = yield* Stream.runHead(adapter.streamEvents).pipe(Effect.forkChild);551 const firstEventFiber = yield* Stream.runHead(adapter.streamEvents).pipe(Effect.forkChild);
474552
475 lifecycleManager.emit("event", {553 yield* runtime.emit({
476 id: asEventId("evt-process-stderr"),554 id: asEventId("evt-process-stderr"),
477 kind: "notification",555 kind: "notification",
478 provider: "codex",556 provider: "codex",
...@@ -503,10 +581,10 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => {...@@ -503,10 +581,10 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => {
503581
504 it.effect("maps fatal websocket stderr notifications to runtime.error", () =>582 it.effect("maps fatal websocket stderr notifications to runtime.error", () =>
505 Effect.gen(function* () {583 Effect.gen(function* () {
506 const adapter = yield* CodexAdapter;584 const { adapter, runtime } = yield* startLifecycleRuntime();
507 const firstEventFiber = yield* Stream.runHead(adapter.streamEvents).pipe(Effect.forkChild);585 const firstEventFiber = yield* Stream.runHead(adapter.streamEvents).pipe(Effect.forkChild);
508586
509 lifecycleManager.emit("event", {587 yield* runtime.emit({
510 id: asEventId("evt-process-stderr-websocket"),588 id: asEventId("evt-process-stderr-websocket"),
511 kind: "notification",589 kind: "notification",
512 provider: "codex",590 provider: "codex",
...@@ -539,7 +617,7 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => {...@@ -539,7 +617,7 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => {
539617
540 it.effect("preserves request type when mapping serverRequest/resolved", () =>618 it.effect("preserves request type when mapping serverRequest/resolved", () =>
541 Effect.gen(function* () {619 Effect.gen(function* () {
542 const adapter = yield* CodexAdapter;620 const { adapter, runtime } = yield* startLifecycleRuntime();
543 const firstEventFiber = yield* Stream.runHead(adapter.streamEvents).pipe(Effect.forkChild);621 const firstEventFiber = yield* Stream.runHead(adapter.streamEvents).pipe(Effect.forkChild);
544622
545 const event: ProviderEvent = {623 const event: ProviderEvent = {
...@@ -549,16 +627,15 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => {...@@ -549,16 +627,15 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => {
549 threadId: asThreadId("thread-1"),627 threadId: asThreadId("thread-1"),
550 createdAt: new Date().toISOString(),628 createdAt: new Date().toISOString(),
551 method: "serverRequest/resolved",629 method: "serverRequest/resolved",
630 requestKind: "command",
552 requestId: ApprovalRequestId.make("req-1"),631 requestId: ApprovalRequestId.make("req-1"),
553 payload: {632 payload: {
554 request: {633 threadId: "thread-1",
555 method: "item/commandExecution/requestApproval",634 requestId: "req-1",
556 },
557 decision: "accept",
558 },635 },
559 };636 };
560637
561 lifecycleManager.emit("event", event);638 yield* runtime.emit(event);
562 const firstEvent = yield* Fiber.join(firstEventFiber);639 const firstEvent = yield* Fiber.join(firstEventFiber);
563640
564 assert.equal(firstEvent._tag, "Some");641 assert.equal(firstEvent._tag, "Some");
...@@ -575,7 +652,7 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => {...@@ -575,7 +652,7 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => {
575652
576 it.effect("preserves file-read request type when mapping serverRequest/resolved", () =>653 it.effect("preserves file-read request type when mapping serverRequest/resolved", () =>
577 Effect.gen(function* () {654 Effect.gen(function* () {
578 const adapter = yield* CodexAdapter;655 const { adapter, runtime } = yield* startLifecycleRuntime();
579 const firstEventFiber = yield* Stream.runHead(adapter.streamEvents).pipe(Effect.forkChild);656 const firstEventFiber = yield* Stream.runHead(adapter.streamEvents).pipe(Effect.forkChild);
580657
581 const event: ProviderEvent = {658 const event: ProviderEvent = {
...@@ -585,16 +662,15 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => {...@@ -585,16 +662,15 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => {
585 threadId: asThreadId("thread-1"),662 threadId: asThreadId("thread-1"),
586 createdAt: new Date().toISOString(),663 createdAt: new Date().toISOString(),
587 method: "serverRequest/resolved",664 method: "serverRequest/resolved",
665 requestKind: "file-read",
588 requestId: ApprovalRequestId.make("req-file-read-1"),666 requestId: ApprovalRequestId.make("req-file-read-1"),
589 payload: {667 payload: {
590 request: {668 threadId: "thread-1",
591 method: "item/fileRead/requestApproval",669 requestId: "req-file-read-1",
592 },
593 decision: "accept",
594 },670 },
595 };671 };
596672
597 lifecycleManager.emit("event", event);673 yield* runtime.emit(event);
598 const firstEvent = yield* Fiber.join(firstEventFiber);674 const firstEvent = yield* Fiber.join(firstEventFiber);
599675
600 assert.equal(firstEvent._tag, "Some");676 assert.equal(firstEvent._tag, "Some");
...@@ -611,7 +687,7 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => {...@@ -611,7 +687,7 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => {
611687
612 it.effect("preserves explicit empty multi-select user-input answers", () =>688 it.effect("preserves explicit empty multi-select user-input answers", () =>
613 Effect.gen(function* () {689 Effect.gen(function* () {
614 const adapter = yield* CodexAdapter;690 const { adapter, runtime } = yield* startLifecycleRuntime();
615 const firstEventFiber = yield* Stream.runHead(adapter.streamEvents).pipe(Effect.forkChild);691 const firstEventFiber = yield* Stream.runHead(adapter.streamEvents).pipe(Effect.forkChild);
616692
617 const event: ProviderEvent = {693 const event: ProviderEvent = {
...@@ -623,12 +699,14 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => {...@@ -623,12 +699,14 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => {
623 method: "item/tool/requestUserInput/answered",699 method: "item/tool/requestUserInput/answered",
624 payload: {700 payload: {
625 answers: {701 answers: {
626 scope: [],702 scope: {
703 answers: [],
704 },
627 },705 },
628 },706 },
629 };707 };
630708
631 lifecycleManager.emit("event", event);709 yield* runtime.emit(event);
632 const firstEvent = yield* Fiber.join(firstEventFiber);710 const firstEvent = yield* Fiber.join(firstEventFiber);
633711
634 assert.equal(firstEvent._tag, "Some");712 assert.equal(firstEvent._tag, "Some");
...@@ -647,7 +725,7 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => {...@@ -647,7 +725,7 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => {
647725
648 it.effect("maps windowsSandbox/setupCompleted to session state and warning on failure", () =>726 it.effect("maps windowsSandbox/setupCompleted to session state and warning on failure", () =>
649 Effect.gen(function* () {727 Effect.gen(function* () {
650 const adapter = yield* CodexAdapter;728 const { adapter, runtime } = yield* startLifecycleRuntime();
651 const eventsFiber = yield* Stream.runCollect(Stream.take(adapter.streamEvents, 2)).pipe(729 const eventsFiber = yield* Stream.runCollect(Stream.take(adapter.streamEvents, 2)).pipe(
652 Effect.forkChild,730 Effect.forkChild,
653 );731 );
...@@ -661,12 +739,13 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => {...@@ -661,12 +739,13 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => {
661 method: "windowsSandbox/setupCompleted",739 method: "windowsSandbox/setupCompleted",
662 message: "Sandbox setup failed",740 message: "Sandbox setup failed",
663 payload: {741 payload: {
742 mode: "unelevated",
664 success: false,743 success: false,
665 detail: "unsupported environment",744 error: "unsupported environment",
666 },745 },
667 };746 };
668747
669 lifecycleManager.emit("event", event);748 yield* runtime.emit(event);
670 const events = Array.from(yield* Fiber.join(eventsFiber));749 const events = Array.from(yield* Fiber.join(eventsFiber));
671750
672 assert.equal(events.length, 2);751 assert.equal(events.length, 2);
...@@ -691,12 +770,12 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => {...@@ -691,12 +770,12 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => {
691 "maps requestUserInput requests and answered notifications to canonical user-input events",770 "maps requestUserInput requests and answered notifications to canonical user-input events",
692 () =>771 () =>
693 Effect.gen(function* () {772 Effect.gen(function* () {
694 const adapter = yield* CodexAdapter;773 const { adapter, runtime } = yield* startLifecycleRuntime();
695 const eventsFiber = yield* Stream.runCollect(Stream.take(adapter.streamEvents, 2)).pipe(774 const eventsFiber = yield* Stream.runCollect(Stream.take(adapter.streamEvents, 2)).pipe(
696 Effect.forkChild,775 Effect.forkChild,
697 );776 );
698777
699 lifecycleManager.emit("event", {778 yield* runtime.emit({
700 id: asEventId("evt-user-input-requested"),779 id: asEventId("evt-user-input-requested"),
701 kind: "request",780 kind: "request",
702 provider: "codex",781 provider: "codex",
...@@ -705,6 +784,9 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => {...@@ -705,6 +784,9 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => {
705 method: "item/tool/requestUserInput",784 method: "item/tool/requestUserInput",
706 requestId: ApprovalRequestId.make("req-user-input-1"),785 requestId: ApprovalRequestId.make("req-user-input-1"),
707 payload: {786 payload: {
787 itemId: "item-user-input-1",
788 threadId: "thread-1",
789 turnId: "turn-1",
708 questions: [790 questions: [
709 {791 {
710 id: "sandbox_mode",792 id: "sandbox_mode",
...@@ -716,12 +798,11 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => {...@@ -716,12 +798,11 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => {
716 description: "Allow workspace writes only",798 description: "Allow workspace writes only",
717 },799 },
718 ],800 ],
719 multiSelect: true,
720 },801 },
721 ],802 ],
722 },803 },
723 } satisfies ProviderEvent);804 } satisfies ProviderEvent);
724 lifecycleManager.emit("event", {805 yield* runtime.emit({
725 id: asEventId("evt-user-input-resolved"),806 id: asEventId("evt-user-input-resolved"),
726 kind: "notification",807 kind: "notification",
727 provider: "codex",808 provider: "codex",
...@@ -743,7 +824,7 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => {...@@ -743,7 +824,7 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => {
743 if (events[0]?.type === "user-input.requested") {824 if (events[0]?.type === "user-input.requested") {
744 assert.equal(events[0].requestId, "req-user-input-1");825 assert.equal(events[0].requestId, "req-user-input-1");
745 assert.equal(events[0].payload.questions[0]?.id, "sandbox_mode");826 assert.equal(events[0].payload.questions[0]?.id, "sandbox_mode");
746 assert.equal(events[0].payload.questions[0]?.multiSelect, true);827 assert.equal(events[0].payload.questions[0]?.multiSelect, false);
747 }828 }
748829
749 assert.equal(events[1]?.type, "user-input.resolved");830 assert.equal(events[1]?.type, "user-input.resolved");
...@@ -756,168 +837,12 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => {...@@ -756,168 +837,12 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => {
756 }),837 }),
757 );838 );
758839
759 it.effect("maps Codex task and reasoning event chunks into canonical runtime events", () =>
760 Effect.gen(function* () {
761 const adapter = yield* CodexAdapter;
762 const eventsFiber = yield* Stream.runCollect(Stream.take(adapter.streamEvents, 5)).pipe(
763 Effect.forkChild,
764 );
765
766 lifecycleManager.emit("event", {
767 id: asEventId("evt-codex-task-started"),
768 kind: "notification",
769 provider: "codex",
770 threadId: asThreadId("thread-1"),
771 createdAt: new Date().toISOString(),
772 method: "codex/event/task_started",
773 payload: {
774 id: "turn-structured-1",
775 msg: {
776 type: "task_started",
777 turn_id: "turn-structured-1",
778 collaboration_mode_kind: "plan",
779 },
780 },
781 } satisfies ProviderEvent);
782
783 lifecycleManager.emit("event", {
784 id: asEventId("evt-codex-agent-reasoning"),
785 kind: "notification",
786 provider: "codex",
787 threadId: asThreadId("thread-1"),
788 createdAt: new Date().toISOString(),
789 method: "codex/event/agent_reasoning",
790 payload: {
791 id: "turn-structured-1",
792 msg: {
793 type: "agent_reasoning",
794 text: "Need to compare both transport layers before finalizing the plan.",
795 },
796 },
797 } satisfies ProviderEvent);
798
799 lifecycleManager.emit("event", {
800 id: asEventId("evt-codex-reasoning-delta"),
801 kind: "notification",
802 provider: "codex",
803 threadId: asThreadId("thread-1"),
804 createdAt: new Date().toISOString(),
805 method: "codex/event/reasoning_content_delta",
806 payload: {
807 id: "turn-structured-1",
808 msg: {
809 type: "reasoning_content_delta",
810 turn_id: "turn-structured-1",
811 item_id: "rs_reasoning_1",
812 delta: "**Compare** transport boundaries",
813 summary_index: 0,
814 },
815 },
816 } satisfies ProviderEvent);
817
818 lifecycleManager.emit("event", {
819 id: asEventId("evt-codex-task-complete"),
820 kind: "notification",
821 provider: "codex",
822 threadId: asThreadId("thread-1"),
823 createdAt: new Date().toISOString(),
824 method: "codex/event/task_complete",
825 payload: {
826 id: "turn-structured-1",
827 msg: {
828 type: "task_complete",
829 turn_id: "turn-structured-1",
830 last_agent_message: "<proposed_plan>\n# Ship it\n</proposed_plan>",
831 },
832 },
833 } satisfies ProviderEvent);
834
835 const events = Array.from(yield* Fiber.join(eventsFiber));
836
837 assert.equal(events[0]?.type, "task.started");
838 if (events[0]?.type === "task.started") {
839 assert.equal(events[0].turnId, "turn-structured-1");
840 assert.equal(events[0].payload.taskId, "turn-structured-1");
841 assert.equal(events[0].payload.taskType, "plan");
842 }
843
844 assert.equal(events[1]?.type, "task.progress");
845 if (events[1]?.type === "task.progress") {
846 assert.equal(events[1].payload.taskId, "turn-structured-1");
847 assert.equal(
848 events[1].payload.description,
849 "Need to compare both transport layers before finalizing the plan.",
850 );
851 }
852
853 assert.equal(events[2]?.type, "content.delta");
854 if (events[2]?.type === "content.delta") {
855 assert.equal(events[2].turnId, "turn-structured-1");
856 assert.equal(events[2].itemId, "rs_reasoning_1");
857 assert.equal(events[2].payload.streamKind, "reasoning_summary_text");
858 assert.equal(events[2].payload.summaryIndex, 0);
859 }
860
861 assert.equal(events[3]?.type, "task.completed");
862 if (events[3]?.type === "task.completed") {
863 assert.equal(events[3].turnId, "turn-structured-1");
864 assert.equal(events[3].payload.taskId, "turn-structured-1");
865 assert.equal(events[3].payload.summary, "<proposed_plan>\n# Ship it\n</proposed_plan>");
866 }
867
868 assert.equal(events[4]?.type, "turn.proposed.completed");
869 if (events[4]?.type === "turn.proposed.completed") {
870 assert.equal(events[4].turnId, "turn-structured-1");
871 assert.equal(events[4].payload.planMarkdown, "# Ship it");
872 }
873 }),
874 );
875
876 it.effect("prefers manager-assigned turn ids for Codex task events", () =>
877 Effect.gen(function* () {
878 const adapter = yield* CodexAdapter;
879 const firstEventFiber = yield* Stream.runHead(adapter.streamEvents).pipe(Effect.forkChild);
880
881 lifecycleManager.emit("event", {
882 id: asEventId("evt-codex-task-started-parent-turn"),
883 kind: "notification",
884 provider: "codex",
885 threadId: asThreadId("thread-1"),
886 turnId: asTurnId("turn-parent"),
887 createdAt: new Date().toISOString(),
888 method: "codex/event/task_started",
889 payload: {
890 id: "turn-child",
891 msg: {
892 type: "task_started",
893 turn_id: "turn-child",
894 collaboration_mode_kind: "default",
895 },
896 conversationId: "child-provider-thread",
897 },
898 } satisfies ProviderEvent);
899
900 const firstEvent = yield* Fiber.join(firstEventFiber);
901 assert.equal(firstEvent._tag, "Some");
902 if (firstEvent._tag !== "Some") {
903 return;
904 }
905 assert.equal(firstEvent.value.type, "task.started");
906 if (firstEvent.value.type !== "task.started") {
907 return;
908 }
909 assert.equal(firstEvent.value.turnId, "turn-parent");
910 assert.equal(firstEvent.value.providerRefs?.providerTurnId, "turn-parent");
911 assert.equal(firstEvent.value.payload.taskId, "turn-child");
912 }),
913 );
914
915 it.effect("unwraps Codex token usage payloads for context window events", () =>840 it.effect("unwraps Codex token usage payloads for context window events", () =>
916 Effect.gen(function* () {841 Effect.gen(function* () {
917 const adapter = yield* CodexAdapter;842 const { adapter, runtime } = yield* startLifecycleRuntime();
918 const firstEventFiber = yield* Stream.runHead(adapter.streamEvents).pipe(Effect.forkChild);843 const firstEventFiber = yield* Stream.runHead(adapter.streamEvents).pipe(Effect.forkChild);
919844
920 lifecycleManager.emit("event", {845 yield* runtime.emit({
921 id: asEventId("evt-codex-thread-token-usage-updated"),846 id: asEventId("evt-codex-thread-token-usage-updated"),
922 kind: "notification",847 kind: "notification",
923 provider: "codex",848 provider: "codex",
...@@ -977,9 +902,130 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => {...@@ -977,9 +902,130 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => {
977 );902 );
978});903});
979904
980afterAll(() => {905const scopedLifecycleRuntimeFactory = makeScopedRuntimeFactory();
981 if (lifecycleManager.stopAllImpl.mock.calls.length === 0) {906const scopedLifecycleLayer = it.layer(
982 lifecycleManager.stopAll();907 makeCodexAdapterLive({ makeRuntime: scopedLifecycleRuntimeFactory.factory }).pipe(
983 }908 Layer.provideMerge(ServerConfig.layerTest(process.cwd(), process.cwd())),
984 assert.ok(lifecycleManager.stopAllImpl.mock.calls.length >= 1);909 Layer.provideMerge(ServerSettingsService.layerTest()),
910 Layer.provideMerge(providerSessionDirectoryTestLayer),
911 Layer.provideMerge(NodeServices.layer),
912 ),
913);
914
915scopedLifecycleLayer("CodexAdapterLive scoped lifecycle", (it) => {
916 it.effect("closes the externally owned session scope on stopSession", () =>
917 Effect.gen(function* () {
918 scopedLifecycleRuntimeFactory.releasedThreadIds.length = 0;
919 const adapter = yield* CodexAdapter;
920
921 yield* adapter.startSession({
922 provider: "codex",
923 threadId: asThreadId("thread-stop"),
924 runtimeMode: "full-access",
925 });
926
927 const runtime = scopedLifecycleRuntimeFactory.lastRuntime;
928 assert.ok(runtime);
929
930 yield* adapter.stopSession(asThreadId("thread-stop"));
931
932 assert.equal(runtime.closeImpl.mock.calls.length, 1);
933 assert.deepStrictEqual(scopedLifecycleRuntimeFactory.releasedThreadIds, [
934 asThreadId("thread-stop"),
935 ]);
936 assert.equal(yield* adapter.hasSession(asThreadId("thread-stop")), false);
937 }),
938 );
985});939});
940
941const scopedFailureRuntimeFactory = makeScopedRuntimeFactory({ failConstruction: true });
942const scopedFailureLayer = it.layer(
943 makeCodexAdapterLive({ makeRuntime: scopedFailureRuntimeFactory.factory }).pipe(
944 Layer.provideMerge(ServerConfig.layerTest(process.cwd(), process.cwd())),
945 Layer.provideMerge(ServerSettingsService.layerTest()),
946 Layer.provideMerge(providerSessionDirectoryTestLayer),
947 Layer.provideMerge(NodeServices.layer),
948 ),
949);
950
951scopedFailureLayer("CodexAdapterLive scoped startup failure", (it) => {
952 it.effect("closes the externally owned session scope when startSession fails", () =>
953 Effect.gen(function* () {
954 scopedFailureRuntimeFactory.releasedThreadIds.length = 0;
955 const adapter = yield* CodexAdapter;
956
957 const result = yield* adapter
958 .startSession({
959 provider: "codex",
960 threadId: asThreadId("thread-fail"),
961 runtimeMode: "full-access",
962 })
963 .pipe(Effect.result);
964
965 assert.equal(result._tag, "Failure");
966 assert.equal(result.failure._tag, "ProviderAdapterProcessError");
967 assert.deepStrictEqual(scopedFailureRuntimeFactory.releasedThreadIds, [
968 asThreadId("thread-fail"),
969 ]);
970 assert.equal(yield* adapter.hasSession(asThreadId("thread-fail")), false);
971 }),
972 );
973});
974
975it.effect("flushes managed native logs when the adapter layer shuts down", () =>
976 Effect.gen(function* () {
977 const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), "t3-codex-adapter-native-log-"));
978 const basePath = path.join(tempDir, "provider-native.ndjson");
979 const runtimeFactory = makeRuntimeFactory();
980 const scope = yield* Scope.make("sequential");
981 let scopeClosed = false;
982
983 try {
984 const layer = makeCodexAdapterLive({
985 makeRuntime: runtimeFactory.factory,
986 nativeEventLogPath: basePath,
987 }).pipe(
988 Layer.provideMerge(ServerConfig.layerTest(process.cwd(), process.cwd())),
989 Layer.provideMerge(ServerSettingsService.layerTest()),
990 Layer.provideMerge(providerSessionDirectoryTestLayer),
991 Layer.provideMerge(NodeServices.layer),
992 );
993 const context = yield* Layer.buildWithScope(layer, scope);
994 const adapter = yield* Effect.service(CodexAdapter).pipe(Effect.provide(context));
995
996 yield* adapter.startSession({
997 provider: "codex",
998 threadId: asThreadId("thread-logger"),
999 runtimeMode: "full-access",
1000 });
1001
1002 const runtime = runtimeFactory.lastRuntime;
1003 assert.ok(runtime);
1004
1005 const firstEventFiber = yield* Stream.runHead(adapter.streamEvents).pipe(Effect.forkChild);
1006 yield* runtime.emit({
1007 id: asEventId("evt-native-log"),
1008 kind: "notification",
1009 provider: "codex",
1010 threadId: asThreadId("thread-logger"),
1011 createdAt: new Date().toISOString(),
1012 method: "process/stderr",
1013 message: "native flush test",
1014 } satisfies ProviderEvent);
1015 yield* Fiber.join(firstEventFiber);
1016
1017 yield* Scope.close(scope, Exit.void);
1018 scopeClosed = true;
1019
1020 const threadLogPath = path.join(tempDir, "thread-logger.log");
1021 assert.equal(fs.existsSync(threadLogPath), true);
1022 const contents = fs.readFileSync(threadLogPath, "utf8");
1023 assert.match(contents, /NTIVE: .*"message":"native flush test"/);
1024 } finally {
1025 if (!scopeClosed) {
1026 yield* Scope.close(scope, Exit.void);
1027 }
1028 fs.rmSync(tempDir, { recursive: true, force: true });
1029 }
1030 }),
1031);
apps/server/src/provider/Layers/CodexAdapter.ts+628-597
...@@ -1,8 +1,9 @@...@@ -1,8 +1,9 @@
1/**1/**
2 * CodexAdapterLive - Scoped live implementation for the Codex provider adapter.2 * CodexAdapterLive - Scoped live implementation for the Codex provider adapter.
3 *3 *
4 * Wraps `CodexAppServerManager` behind the `CodexAdapter` service contract and4 * Wraps the typed Codex session runtime behind the `CodexAdapter` service
5 * maps manager failures into the shared `ProviderAdapterError` algebra.5 * contract and maps runtime failures into the shared `ProviderAdapterError`
6 * algebra.
6 *7 *
7 * @module CodexAdapterLive8 * @module CodexAdapterLive
8 */9 */
...@@ -11,98 +12,118 @@ import {...@@ -11,98 +12,118 @@ import {
11 type CanonicalRequestType,12 type CanonicalRequestType,
12 type ProviderEvent,13 type ProviderEvent,
13 type ProviderRuntimeEvent,14 type ProviderRuntimeEvent,
15 type ProviderRequestKind,
14 type ThreadTokenUsageSnapshot,16 type ThreadTokenUsageSnapshot,
15 type ProviderUserInputAnswers,17 type ProviderUserInputAnswers,
16 RuntimeItemId,18 RuntimeItemId,
17 RuntimeRequestId,19 RuntimeRequestId,
18 RuntimeTaskId,
19 ProviderApprovalDecision,20 ProviderApprovalDecision,
20 ProviderItemId,
21 ThreadId,21 ThreadId,
22 TurnId,
23 ProviderSendTurnInput,22 ProviderSendTurnInput,
24} from "@t3tools/contracts";23} from "@t3tools/contracts";
25import { Effect, FileSystem, Layer, Queue, Schema, Context, Stream } from "effect";24import { Effect, Exit, Fiber, FileSystem, Layer, Queue, Schema, Scope, Stream } from "effect";
25import { ChildProcessSpawner } from "effect/unstable/process";
26import * as CodexErrors from "effect-codex-app-server/errors";
27import * as EffectCodexSchema from "effect-codex-app-server/schema";
2628
27import {29import {
28 ProviderAdapterProcessError,
29 ProviderAdapterRequestError,30 ProviderAdapterRequestError,
31 ProviderAdapterProcessError,
30 ProviderAdapterSessionClosedError,32 ProviderAdapterSessionClosedError,
31 ProviderAdapterSessionNotFoundError,33 ProviderAdapterSessionNotFoundError,
32 ProviderAdapterValidationError,34 ProviderAdapterValidationError,
33 type ProviderAdapterError,35 type ProviderAdapterError,
34} from "../Errors.ts";36} from "../Errors.ts";
35import { CodexAdapter, type CodexAdapterShape } from "../Services/CodexAdapter.ts";37import { CodexAdapter, type CodexAdapterShape } from "../Services/CodexAdapter.ts";
36import {
37 CodexAppServerManager,
38 type CodexAppServerStartSessionInput,
39} from "../../codexAppServerManager.ts";
40import { resolveAttachmentPath } from "../../attachmentStore.ts";38import { resolveAttachmentPath } from "../../attachmentStore.ts";
41import { ServerConfig } from "../../config.ts";39import { ServerConfig } from "../../config.ts";
42import { ServerSettingsService } from "../../serverSettings.ts";40import { ServerSettingsService } from "../../serverSettings.ts";
41import {
42 CodexResumeCursorSchema,
43 CodexSessionRuntimeThreadIdMissingError,
44 makeCodexSessionRuntime,
45 type CodexSessionRuntimeError,
46 type CodexSessionRuntimeOptions,
47 type CodexSessionRuntimeShape,
48} from "./CodexSessionRuntime.ts";
43import { type EventNdjsonLogger, makeEventNdjsonLogger } from "./EventNdjsonLogger.ts";49import { type EventNdjsonLogger, makeEventNdjsonLogger } from "./EventNdjsonLogger.ts";
4450
45const PROVIDER = "codex" as const;51const PROVIDER = "codex" as const;
4652
47export interface CodexAdapterLiveOptions {53export interface CodexAdapterLiveOptions {
48 readonly manager?: CodexAppServerManager;54 readonly makeRuntime?: (
49 readonly makeManager?: (services?: Context.Context<never>) => CodexAppServerManager;55 options: CodexSessionRuntimeOptions,
56 ) => Effect.Effect<
57 CodexSessionRuntimeShape,
58 CodexSessionRuntimeError,
59 ChildProcessSpawner.ChildProcessSpawner | Scope.Scope
60 >;
50 readonly nativeEventLogPath?: string;61 readonly nativeEventLogPath?: string;
51 readonly nativeEventLogger?: EventNdjsonLogger;62 readonly nativeEventLogger?: EventNdjsonLogger;
52}63}
5364
54function toSessionError(65interface CodexAdapterSessionContext {
66 readonly threadId: ThreadId;
67 readonly scope: Scope.Closeable;
68 readonly runtime: CodexSessionRuntimeShape;
69 readonly eventFiber: Fiber.Fiber<void, never>;
70 stopped: boolean;
71}
72
73function mapCodexRuntimeError(
55 threadId: ThreadId,74 threadId: ThreadId,
56 cause: unknown,75 method: string,
57): ProviderAdapterSessionNotFoundError | ProviderAdapterSessionClosedError | undefined {76 error: CodexSessionRuntimeError,
58 const normalized = cause instanceof Error ? cause.message.toLowerCase() : "";77): ProviderAdapterError {
59 if (normalized.includes("unknown session") || normalized.includes("unknown provider session")) {78 if (
60 return new ProviderAdapterSessionNotFoundError({79 Schema.is(CodexErrors.CodexAppServerProcessExitedError)(error) ||
80 Schema.is(CodexErrors.CodexAppServerTransportError)(error)
81 ) {
82 return new ProviderAdapterSessionClosedError({
61 provider: PROVIDER,83 provider: PROVIDER,
62 threadId,84 threadId,
63 cause,85 cause: error,
64 });86 });
65 }87 }
66 if (normalized.includes("session is closed")) {88
67 return new ProviderAdapterSessionClosedError({89 if (Schema.is(CodexSessionRuntimeThreadIdMissingError)(error)) {
90 return new ProviderAdapterSessionNotFoundError({
68 provider: PROVIDER,91 provider: PROVIDER,
69 threadId,92 threadId,
70 cause,93 cause: error,
71 });94 });
72 }95 }
73 return undefined;
74}
7596
76function toRequestError(threadId: ThreadId, method: string, cause: unknown): ProviderAdapterError {
77 const sessionError = toSessionError(threadId, cause);
78 if (sessionError) {
79 return sessionError;
80 }
81 return new ProviderAdapterRequestError({97 return new ProviderAdapterRequestError({
82 provider: PROVIDER,98 provider: PROVIDER,
83 method,99 method,
84 detail: cause instanceof Error ? `${method} failed: ${cause.message}` : `${method} failed`,100 detail: error.message,
85 cause,101 cause: error,
86 });102 });
87}103}
88104
89function asObject(value: unknown): Record<string, unknown> | undefined {105type CodexLifecycleItem =
90 if (!value || typeof value !== "object") {106 | EffectCodexSchema.V2ItemStartedNotification["item"]
91 return undefined;107 | EffectCodexSchema.V2ItemCompletedNotification["item"];
92 }
93 return value as Record<string, unknown>;
94}
95108
96function asString(value: unknown): string | undefined {109type CodexToolUserInputQuestion =
97 return typeof value === "string" ? value : undefined;110 | EffectCodexSchema.ServerRequest__ToolRequestUserInputQuestion
98}111 | EffectCodexSchema.ToolRequestUserInputParams__ToolRequestUserInputQuestion;
99112
100function asArray(value: unknown): unknown[] | undefined {113const ApprovalDecisionPayload = Schema.Struct({
101 return Array.isArray(value) ? value : undefined;114 decision: ProviderApprovalDecision,
115});
116
117function readPayload<A>(
118 schema: Schema.Schema<A>,
119 payload: ProviderEvent["payload"],
120): A | undefined {
121 return Schema.is(schema)(payload) ? payload : undefined;
102}122}
103123
104function asNumber(value: unknown): number | undefined {124function trimText(value: string | undefined | null): string | undefined {
105 return typeof value === "number" && Number.isFinite(value) ? value : undefined;125 const trimmed = value?.trim();
126 return trimmed && trimmed.length > 0 ? trimmed : undefined;
106}127}
107128
108const FATAL_CODEX_STDERR_SNIPPETS = ["failed to connect to websocket"];129const FATAL_CODEX_STDERR_SNIPPETS = ["failed to connect to websocket"];
...@@ -112,26 +133,20 @@ function isFatalCodexProcessStderrMessage(message: string): boolean {...@@ -112,26 +133,20 @@ function isFatalCodexProcessStderrMessage(message: string): boolean {
112 return FATAL_CODEX_STDERR_SNIPPETS.some((snippet) => normalized.includes(snippet));133 return FATAL_CODEX_STDERR_SNIPPETS.some((snippet) => normalized.includes(snippet));
113}134}
114135
115function normalizeCodexTokenUsage(value: unknown): ThreadTokenUsageSnapshot | undefined {136function normalizeCodexTokenUsage(
116 const usage = asObject(value);137 usage: EffectCodexSchema.V2ThreadTokenUsageUpdatedNotification["tokenUsage"],
117 const totalUsage = asObject(usage?.total_token_usage ?? usage?.total);138): ThreadTokenUsageSnapshot | undefined {
118 const lastUsage = asObject(usage?.last_token_usage ?? usage?.last);139 const totalProcessedTokens = usage.total.totalTokens;
119140 const usedTokens = usage.last.totalTokens;
120 const totalProcessedTokens =
121 asNumber(totalUsage?.total_tokens) ?? asNumber(totalUsage?.totalTokens);
122 const usedTokens =
123 asNumber(lastUsage?.total_tokens) ?? asNumber(lastUsage?.totalTokens) ?? totalProcessedTokens;
124 if (usedTokens === undefined || usedTokens <= 0) {141 if (usedTokens === undefined || usedTokens <= 0) {
125 return undefined;142 return undefined;
126 }143 }
127144
128 const maxTokens = asNumber(usage?.model_context_window) ?? asNumber(usage?.modelContextWindow);145 const maxTokens = usage.modelContextWindow ?? undefined;
129 const inputTokens = asNumber(lastUsage?.input_tokens) ?? asNumber(lastUsage?.inputTokens);146 const inputTokens = usage.last.inputTokens;
130 const cachedInputTokens =147 const cachedInputTokens = usage.last.cachedInputTokens;
131 asNumber(lastUsage?.cached_input_tokens) ?? asNumber(lastUsage?.cachedInputTokens);148 const outputTokens = usage.last.outputTokens;
132 const outputTokens = asNumber(lastUsage?.output_tokens) ?? asNumber(lastUsage?.outputTokens);149 const reasoningOutputTokens = usage.last.reasoningOutputTokens;
133 const reasoningOutputTokens =
134 asNumber(lastUsage?.reasoning_output_tokens) ?? asNumber(lastUsage?.reasoningOutputTokens);
135150
136 return {151 return {
137 usedTokens,152 usedTokens,
...@@ -154,15 +169,9 @@ function normalizeCodexTokenUsage(value: unknown): ThreadTokenUsageSnapshot | un...@@ -154,15 +169,9 @@ function normalizeCodexTokenUsage(value: unknown): ThreadTokenUsageSnapshot | un
154 };169 };
155}170}
156171
157function toTurnId(value: string | undefined): TurnId | undefined {172function toTurnStatus(
158 return value?.trim() ? TurnId.make(value) : undefined;173 value: EffectCodexSchema.V2TurnCompletedNotification["turn"]["status"] | "cancelled",
159}174): "completed" | "failed" | "cancelled" | "interrupted" {
160
161function toProviderItemId(value: string | undefined): ProviderItemId | undefined {
162 return value?.trim() ? ProviderItemId.make(value) : undefined;
163}
164
165function toTurnStatus(value: unknown): "completed" | "failed" | "cancelled" | "interrupted" {
166 switch (value) {175 switch (value) {
167 case "completed":176 case "completed":
168 case "failed":177 case "failed":
...@@ -174,8 +183,8 @@ function toTurnStatus(value: unknown): "completed" | "failed" | "cancelled" | "i...@@ -174,8 +183,8 @@ function toTurnStatus(value: unknown): "completed" | "failed" | "cancelled" | "i
174 }183 }
175}184}
176185
177function normalizeItemType(raw: unknown): string {186function normalizeItemType(raw: string | undefined | null): string {
178 const type = asString(raw);187 const type = trimText(raw);
179 if (!type) return "item";188 if (!type) return "item";
180 return type189 return type
181 .replace(/([a-z0-9])([A-Z])/g, "$1 $2")190 .replace(/([a-z0-9])([A-Z])/g, "$1 $2")
...@@ -185,7 +194,7 @@ function normalizeItemType(raw: unknown): string {...@@ -185,7 +194,7 @@ function normalizeItemType(raw: unknown): string {
185 .toLowerCase();194 .toLowerCase();
186}195}
187196
188function toCanonicalItemType(raw: unknown): CanonicalItemType {197function toCanonicalItemType(raw: string | undefined | null): CanonicalItemType {
189 const type = normalizeItemType(raw);198 const type = normalizeItemType(raw);
190 if (type.includes("user")) return "user_message";199 if (type.includes("user")) return "user_message";
191 if (type.includes("agent message") || type.includes("assistant")) return "assistant_message";200 if (type.includes("agent message") || type.includes("assistant")) return "assistant_message";
...@@ -235,27 +244,18 @@ function itemTitle(itemType: CanonicalItemType): string | undefined {...@@ -235,27 +244,18 @@ function itemTitle(itemType: CanonicalItemType): string | undefined {
235 }244 }
236}245}
237246
238function itemDetail(247function itemDetail(item: CodexLifecycleItem): string | undefined {
239 item: Record<string, unknown>,
240 payload: Record<string, unknown>,
241): string | undefined {
242 const nestedResult = asObject(item.result);
243 const candidates = [248 const candidates = [
244 asString(item.command),249 "command" in item ? item.command : undefined,
245 asString(item.title),250 "title" in item ? item.title : undefined,
246 asString(item.summary),251 "summary" in item ? item.summary : undefined,
247 asString(item.text),252 "text" in item ? item.text : undefined,
248 asString(item.path),253 "path" in item ? item.path : undefined,
249 asString(item.prompt),254 "prompt" in item ? item.prompt : undefined,
250 asString(nestedResult?.command),
251 asString(payload.command),
252 asString(payload.message),
253 asString(payload.prompt),
254 ];255 ];
255 for (const candidate of candidates) {256 for (const candidate of candidates) {
256 if (!candidate) continue;257 const trimmed = typeof candidate === "string" ? trimText(candidate) : undefined;
257 const trimmed = candidate.trim();258 if (!trimmed) continue;
258 if (trimmed.length === 0) continue;
259 return trimmed;259 return trimmed;
260 }260 }
261 return undefined;261 return undefined;
...@@ -284,7 +284,7 @@ function toRequestTypeFromMethod(method: string): CanonicalRequestType {...@@ -284,7 +284,7 @@ function toRequestTypeFromMethod(method: string): CanonicalRequestType {
284 }284 }
285}285}
286286
287function toRequestTypeFromKind(kind: unknown): CanonicalRequestType {287function toRequestTypeFromKind(kind: ProviderRequestKind | undefined): CanonicalRequestType {
288 switch (kind) {288 switch (kind) {
289 case "command":289 case "command":
290 return "command_execution_approval";290 return "command_execution_approval";
...@@ -297,77 +297,36 @@ function toRequestTypeFromKind(kind: unknown): CanonicalRequestType {...@@ -297,77 +297,36 @@ function toRequestTypeFromKind(kind: unknown): CanonicalRequestType {
297 }297 }
298}298}
299299
300function toRequestTypeFromResolvedPayload(
301 payload: Record<string, unknown> | undefined,
302): CanonicalRequestType {
303 const request = asObject(payload?.request);
304 const method = asString(request?.method) ?? asString(payload?.method);
305 if (method) {
306 return toRequestTypeFromMethod(method);
307 }
308 const requestKind = asString(request?.kind) ?? asString(payload?.requestKind);
309 if (requestKind) {
310 return toRequestTypeFromKind(requestKind);
311 }
312 return "unknown";
313}
314
315function toCanonicalUserInputAnswers(300function toCanonicalUserInputAnswers(
316 answers: ProviderUserInputAnswers | undefined,301 answers: EffectCodexSchema.ToolRequestUserInputResponse["answers"],
317): ProviderUserInputAnswers {302): ProviderUserInputAnswers {
318 if (!answers) {
319 return {};
320 }
321
322 return Object.fromEntries(303 return Object.fromEntries(
323 Object.entries(answers).flatMap(([questionId, value]) => {304 Object.entries(answers).map(([questionId, value]) => {
324 if (typeof value === "string") {305 const normalizedAnswers = value.answers.length === 1 ? value.answers[0]! : [...value.answers];
325 return [[questionId, value] as const];306 return [questionId, normalizedAnswers] as const;
326 }
327
328 if (Array.isArray(value)) {
329 const normalized = value.filter((entry): entry is string => typeof entry === "string");
330 return [[questionId, normalized.length === 1 ? normalized[0] : normalized] as const];
331 }
332
333 const answerObject = asObject(value);
334 const answerList = asArray(answerObject?.answers)?.filter(
335 (entry): entry is string => typeof entry === "string",
336 );
337 if (!answerList) {
338 return [];
339 }
340 return [[questionId, answerList.length === 1 ? answerList[0] : answerList] as const];
341 }),307 }),
342 );308 );
343}309}
344310
345function toUserInputQuestions(payload: Record<string, unknown> | undefined) {311function toUserInputQuestions(questions: ReadonlyArray<CodexToolUserInputQuestion>) {
346 const questions = asArray(payload?.questions);
347 if (!questions) {
348 return undefined;
349 }
350
351 const parsedQuestions = questions312 const parsedQuestions = questions
352 .map((entry) => {313 .map((question) => {
353 const question = asObject(entry);314 const options =
354 if (!question) return undefined;315 question.options
355 const options = asArray(question.options)316 ?.map((option) => {
356 ?.map((option) => {317 const label = trimText(option.label);
357 const optionRecord = asObject(option);318 const description = trimText(option.description);
358 if (!optionRecord) return undefined;319 if (!label || !description) {
359 const label = asString(optionRecord.label)?.trim();320 return undefined;
360 const description = asString(optionRecord.description)?.trim();321 }
361 if (!label || !description) {322 return { label, description };
362 return undefined;323 })
363 }324 .filter((option) => option !== undefined) ?? [];
364 return { label, description };325
365 })326 const id = trimText(question.id);
366 .filter((option): option is { label: string; description: string } => option !== undefined);327 const header = trimText(question.header);
367 const id = asString(question.id)?.trim();328 const prompt = trimText(question.question);
368 const header = asString(question.header)?.trim();329 if (!id || !header || !prompt || options.length === 0) {
369 const prompt = asString(question.question)?.trim();
370 if (!id || !header || !prompt || !options || options.length === 0) {
371 return undefined;330 return undefined;
372 }331 }
373 return {332 return {
...@@ -375,38 +334,21 @@ function toUserInputQuestions(payload: Record<string, unknown> | undefined) {...@@ -375,38 +334,21 @@ function toUserInputQuestions(payload: Record<string, unknown> | undefined) {
375 header,334 header,
376 question: prompt,335 question: prompt,
377 options,336 options,
378 multiSelect: question.multiSelect === true,337 multiSelect: false,
379 };338 };
380 })339 })
381 .filter(340 .filter((question) => question !== undefined);
382 (
383 question,
384 ): question is {
385 id: string;
386 header: string;
387 question: string;
388 options: Array<{ label: string; description: string }>;
389 multiSelect: boolean;
390 } => question !== undefined,
391 );
392341
393 return parsedQuestions.length > 0 ? parsedQuestions : undefined;342 return parsedQuestions.length > 0 ? parsedQuestions : undefined;
394}343}
395344
396function toThreadState(345function toThreadState(
397 value: unknown,346 status: EffectCodexSchema.V2ThreadStatusChangedNotification["status"],
398): "active" | "idle" | "archived" | "closed" | "compacted" | "error" {347): "active" | "idle" | "archived" | "closed" | "compacted" | "error" {
399 switch (value) {348 switch (status.type) {
400 case "idle":349 case "idle":
401 return "idle";350 return "idle";
402 case "archived":351 case "systemError":
403 return "archived";
404 case "closed":
405 return "closed";
406 case "compacted":
407 return "compacted";
408 case "error":
409 case "failed":
410 return "error";352 return "error";
411 default:353 default:
412 return "active";354 return "active";
...@@ -438,15 +380,7 @@ function contentStreamKindFromMethod(...@@ -438,15 +380,7 @@ function contentStreamKindFromMethod(
438 }380 }
439}381}
440382
441const PROPOSED_PLAN_BLOCK_REGEX = /<proposed_plan>\s*([\s\S]*?)\s*<\/proposed_plan>/i;383function asRuntimeItemId(itemId: ProviderEvent["itemId"] & string): RuntimeItemId {
442
443function extractProposedPlanMarkdown(text: string | undefined): string | undefined {
444 const match = text ? PROPOSED_PLAN_BLOCK_REGEX.exec(text) : null;
445 const planMarkdown = match?.[1]?.trim();
446 return planMarkdown && planMarkdown.length > 0 ? planMarkdown : undefined;
447}
448
449function asRuntimeItemId(itemId: ProviderItemId): RuntimeItemId {
450 return RuntimeItemId.make(itemId);384 return RuntimeItemId.make(itemId);
451}385}
452386
...@@ -454,48 +388,6 @@ function asRuntimeRequestId(requestId: string): RuntimeRequestId {...@@ -454,48 +388,6 @@ function asRuntimeRequestId(requestId: string): RuntimeRequestId {
454 return RuntimeRequestId.make(requestId);388 return RuntimeRequestId.make(requestId);
455}389}
456390
457function asRuntimeTaskId(taskId: string): RuntimeTaskId {
458 return RuntimeTaskId.make(taskId);
459}
460
461function codexEventMessage(
462 payload: Record<string, unknown> | undefined,
463): Record<string, unknown> | undefined {
464 return asObject(payload?.msg);
465}
466
467function codexEventBase(
468 event: ProviderEvent,
469 canonicalThreadId: ThreadId,
470): Omit<ProviderRuntimeEvent, "type" | "payload"> {
471 const payload = asObject(event.payload);
472 const msg = codexEventMessage(payload);
473 const turnId = event.turnId ?? toTurnId(asString(msg?.turn_id) ?? asString(msg?.turnId));
474 const itemId = event.itemId ?? toProviderItemId(asString(msg?.item_id) ?? asString(msg?.itemId));
475 const requestId = asString(msg?.request_id) ?? asString(msg?.requestId);
476 const base = runtimeEventBase(event, canonicalThreadId);
477 const providerRefs = base.providerRefs
478 ? {
479 ...base.providerRefs,
480 ...(turnId ? { providerTurnId: turnId } : {}),
481 ...(itemId ? { providerItemId: itemId } : {}),
482 ...(requestId ? { providerRequestId: requestId } : {}),
483 }
484 : {
485 ...(turnId ? { providerTurnId: turnId } : {}),
486 ...(itemId ? { providerItemId: itemId } : {}),
487 ...(requestId ? { providerRequestId: requestId } : {}),
488 };
489
490 return {
491 ...base,
492 ...(turnId ? { turnId } : {}),
493 ...(itemId ? { itemId: asRuntimeItemId(itemId) } : {}),
494 ...(requestId ? { requestId: asRuntimeRequestId(requestId) } : {}),
495 ...(Object.keys(providerRefs).length > 0 ? { providerRefs } : {}),
496 };
497}
498
499function eventRawSource(event: ProviderEvent): NonNullable<ProviderRuntimeEvent["raw"]>["source"] {391function eventRawSource(event: ProviderEvent): NonNullable<ProviderRuntimeEvent["raw"]>["source"] {
500 return event.kind === "request" ? "codex.app-server.request" : "codex.app-server.notification";392 return event.kind === "request" ? "codex.app-server.request" : "codex.app-server.notification";
501}393}
...@@ -538,19 +430,19 @@ function mapItemLifecycle(...@@ -538,19 +430,19 @@ function mapItemLifecycle(
538 canonicalThreadId: ThreadId,430 canonicalThreadId: ThreadId,
539 lifecycle: "item.started" | "item.updated" | "item.completed",431 lifecycle: "item.started" | "item.updated" | "item.completed",
540): ProviderRuntimeEvent | undefined {432): ProviderRuntimeEvent | undefined {
541 const payload = asObject(event.payload);433 const payload =
542 const item = asObject(payload?.item);434 readPayload(EffectCodexSchema.V2ItemStartedNotification, event.payload) ??
543 const source = item ?? payload;435 readPayload(EffectCodexSchema.V2ItemCompletedNotification, event.payload);
544 if (!source) {436 const item = payload?.item;
437 if (!item) {
545 return undefined;438 return undefined;
546 }439 }
547440 const itemType = toCanonicalItemType(item.type);
548 const itemType = toCanonicalItemType(source.type ?? source.kind);
549 if (itemType === "unknown" && lifecycle !== "item.updated") {441 if (itemType === "unknown" && lifecycle !== "item.updated") {
550 return undefined;442 return undefined;
551 }443 }
552444
553 const detail = itemDetail(source, payload ?? {});445 const detail = itemDetail(item);
554 const status =446 const status =
555 lifecycle === "item.started"447 lifecycle === "item.started"
556 ? "inProgress"448 ? "inProgress"
...@@ -575,9 +467,6 @@ function mapToRuntimeEvents(...@@ -575,9 +467,6 @@ function mapToRuntimeEvents(
575 event: ProviderEvent,467 event: ProviderEvent,
576 canonicalThreadId: ThreadId,468 canonicalThreadId: ThreadId,
577): ReadonlyArray<ProviderRuntimeEvent> {469): ReadonlyArray<ProviderRuntimeEvent> {
578 const payload = asObject(event.payload);
579 const turn = asObject(payload?.turn);
580
581 if (event.kind === "error") {470 if (event.kind === "error") {
582 if (!event.message) {471 if (!event.message) {
583 return [];472 return [];
...@@ -597,7 +486,10 @@ function mapToRuntimeEvents(...@@ -597,7 +486,10 @@ function mapToRuntimeEvents(
597486
598 if (event.kind === "request") {487 if (event.kind === "request") {
599 if (event.method === "item/tool/requestUserInput") {488 if (event.method === "item/tool/requestUserInput") {
600 const questions = toUserInputQuestions(payload);489 const payload =
490 readPayload(EffectCodexSchema.ServerRequest__ToolRequestUserInputParams, event.payload) ??
491 readPayload(EffectCodexSchema.ToolRequestUserInputParams, event.payload);
492 const questions = payload ? toUserInputQuestions(payload.questions) : undefined;
601 if (!questions) {493 if (!questions) {
602 return [];494 return [];
603 }495 }
...@@ -612,8 +504,48 @@ function mapToRuntimeEvents(...@@ -612,8 +504,48 @@ function mapToRuntimeEvents(
612 ];504 ];
613 }505 }
614506
615 const detail =507 const detail = (() => {
616 asString(payload?.command) ?? asString(payload?.reason) ?? asString(payload?.prompt);508 switch (event.method) {
509 case "item/commandExecution/requestApproval": {
510 const payload = readPayload(
511 EffectCodexSchema.ServerRequest__CommandExecutionRequestApprovalParams,
512 event.payload,
513 );
514 return payload?.command ?? payload?.reason ?? undefined;
515 }
516 case "item/fileChange/requestApproval": {
517 const payload = readPayload(
518 EffectCodexSchema.ServerRequest__FileChangeRequestApprovalParams,
519 event.payload,
520 );
521 return payload?.reason ?? undefined;
522 }
523 case "applyPatchApproval": {
524 const payload = readPayload(
525 EffectCodexSchema.ServerRequest__ApplyPatchApprovalParams,
526 event.payload,
527 );
528 return payload?.reason ?? undefined;
529 }
530 case "execCommandApproval": {
531 const payload = readPayload(
532 EffectCodexSchema.ServerRequest__ExecCommandApprovalParams,
533 event.payload,
534 );
535 return payload?.reason ?? payload?.command.join(" ");
536 }
537 case "item/tool/call": {
538 const payload = readPayload(
539 EffectCodexSchema.ServerRequest__DynamicToolCallParams,
540 event.payload,
541 );
542 return payload?.tool ?? undefined;
543 }
544 default:
545 return undefined;
546 }
547 })();
548
617 return [549 return [
618 {550 {
619 ...runtimeEventBase(event, canonicalThreadId),551 ...runtimeEventBase(event, canonicalThreadId),
...@@ -628,7 +560,7 @@ function mapToRuntimeEvents(...@@ -628,7 +560,7 @@ function mapToRuntimeEvents(
628 }560 }
629561
630 if (event.method === "item/requestApproval/decision" && event.requestId) {562 if (event.method === "item/requestApproval/decision" && event.requestId) {
631 const decision = Schema.decodeUnknownSync(ProviderApprovalDecision)(payload?.decision);563 const payload = readPayload(ApprovalDecisionPayload, event.payload);
632 const requestType =564 const requestType =
633 event.requestKind !== undefined565 event.requestKind !== undefined
634 ? toRequestTypeFromKind(event.requestKind)566 ? toRequestTypeFromKind(event.requestKind)
...@@ -639,7 +571,7 @@ function mapToRuntimeEvents(...@@ -639,7 +571,7 @@ function mapToRuntimeEvents(
639 type: "request.resolved",571 type: "request.resolved",
640 payload: {572 payload: {
641 requestType,573 requestType,
642 ...(decision ? { decision } : {}),574 ...(payload ? { decision: payload.decision } : {}),
643 ...(event.payload !== undefined ? { resolution: event.payload } : {}),575 ...(event.payload !== undefined ? { resolution: event.payload } : {}),
644 },576 },
645 },577 },
...@@ -699,9 +631,8 @@ function mapToRuntimeEvents(...@@ -699,9 +631,8 @@ function mapToRuntimeEvents(
699 }631 }
700632
701 if (event.method === "thread/started") {633 if (event.method === "thread/started") {
702 const payloadThreadId = asString(asObject(payload?.thread)?.id);634 const payload = readPayload(EffectCodexSchema.V2ThreadStartedNotification, event.payload);
703 const providerThreadId = payloadThreadId ?? asString(payload?.threadId);635 if (!payload) {
704 if (!providerThreadId) {
705 return [];636 return [];
706 }637 }
707 return [638 return [
...@@ -709,7 +640,7 @@ function mapToRuntimeEvents(...@@ -709,7 +640,7 @@ function mapToRuntimeEvents(
709 ...runtimeEventBase(event, canonicalThreadId),640 ...runtimeEventBase(event, canonicalThreadId),
710 type: "thread.started",641 type: "thread.started",
711 payload: {642 payload: {
712 providerThreadId,643 providerThreadId: payload.thread.id,
713 },644 },
714 },645 },
715 ];646 ];
...@@ -722,6 +653,10 @@ function mapToRuntimeEvents(...@@ -722,6 +653,10 @@ function mapToRuntimeEvents(
722 event.method === "thread/closed" ||653 event.method === "thread/closed" ||
723 event.method === "thread/compacted"654 event.method === "thread/compacted"
724 ) {655 ) {
656 const payload =
657 event.method === "thread/status/changed"
658 ? readPayload(EffectCodexSchema.V2ThreadStatusChangedNotification, event.payload)
659 : undefined;
725 return [660 return [
726 {661 {
727 type: "thread.state.changed",662 type: "thread.state.changed",
...@@ -734,7 +669,9 @@ function mapToRuntimeEvents(...@@ -734,7 +669,9 @@ function mapToRuntimeEvents(
734 ? "closed"669 ? "closed"
735 : event.method === "thread/compacted"670 : event.method === "thread/compacted"
736 ? "compacted"671 ? "compacted"
737 : toThreadState(asObject(payload?.thread)?.state ?? payload?.state),672 : payload
673 ? toThreadState(payload.status)
674 : "active",
738 ...(event.payload !== undefined ? { detail: event.payload } : {}),675 ...(event.payload !== undefined ? { detail: event.payload } : {}),
739 },676 },
740 },677 },
...@@ -742,21 +679,34 @@ function mapToRuntimeEvents(...@@ -742,21 +679,34 @@ function mapToRuntimeEvents(
742 }679 }
743680
744 if (event.method === "thread/name/updated") {681 if (event.method === "thread/name/updated") {
682 const payload = readPayload(EffectCodexSchema.V2ThreadNameUpdatedNotification, event.payload);
745 return [683 return [
746 {684 {
747 type: "thread.metadata.updated",685 type: "thread.metadata.updated",
748 ...runtimeEventBase(event, canonicalThreadId),686 ...runtimeEventBase(event, canonicalThreadId),
749 payload: {687 payload: {
750 ...(asString(payload?.threadName) ? { name: asString(payload?.threadName) } : {}),688 ...(trimText(payload?.threadName) ? { name: trimText(payload?.threadName) } : {}),
751 ...(event.payload !== undefined ? { metadata: asObject(event.payload) } : {}),689 ...(payload
690 ? {
691 metadata: {
692 threadId: payload.threadId,
693 ...(payload.threadName !== undefined && payload.threadName !== null
694 ? { threadName: payload.threadName }
695 : {}),
696 },
697 }
698 : {}),
752 },699 },
753 },700 },
754 ];701 ];
755 }702 }
756703
757 if (event.method === "thread/tokenUsage/updated") {704 if (event.method === "thread/tokenUsage/updated") {
758 const tokenUsage = asObject(payload?.tokenUsage);705 const payload = readPayload(
759 const normalizedUsage = normalizeCodexTokenUsage(tokenUsage ?? event.payload);706 EffectCodexSchema.V2ThreadTokenUsageUpdatedNotification,
707 event.payload,
708 );
709 const normalizedUsage = payload ? normalizeCodexTokenUsage(payload.tokenUsage) : undefined;
760 if (!normalizedUsage) {710 if (!normalizedUsage) {
761 return [];711 return [];
762 }712 }
...@@ -781,28 +731,23 @@ function mapToRuntimeEvents(...@@ -781,28 +731,23 @@ function mapToRuntimeEvents(
781 ...runtimeEventBase(event, canonicalThreadId),731 ...runtimeEventBase(event, canonicalThreadId),
782 turnId,732 turnId,
783 type: "turn.started",733 type: "turn.started",
784 payload: {734 payload: {},
785 ...(asString(turn?.model) ? { model: asString(turn?.model) } : {}),
786 ...(asString(turn?.effort) ? { effort: asString(turn?.effort) } : {}),
787 },
788 },735 },
789 ];736 ];
790 }737 }
791738
792 if (event.method === "turn/completed") {739 if (event.method === "turn/completed") {
793 const errorMessage = asString(asObject(turn?.error)?.message);740 const payload = readPayload(EffectCodexSchema.V2TurnCompletedNotification, event.payload);
741 if (!payload) {
742 return [];
743 }
744 const errorMessage = trimText(payload.turn.error?.message);
794 return [745 return [
795 {746 {
796 ...runtimeEventBase(event, canonicalThreadId),747 ...runtimeEventBase(event, canonicalThreadId),
797 type: "turn.completed",748 type: "turn.completed",
798 payload: {749 payload: {
799 state: toTurnStatus(turn?.status),750 state: toTurnStatus(payload.turn.status),
800 ...(asString(turn?.stopReason) ? { stopReason: asString(turn?.stopReason) } : {}),
801 ...(turn?.usage !== undefined ? { usage: turn.usage } : {}),
802 ...(asObject(turn?.modelUsage) ? { modelUsage: asObject(turn?.modelUsage) } : {}),
803 ...(asNumber(turn?.totalCostUsd) !== undefined
804 ? { totalCostUsd: asNumber(turn?.totalCostUsd) }
805 : {}),
806 ...(errorMessage ? { errorMessage } : {}),751 ...(errorMessage ? { errorMessage } : {}),
807 },752 },
808 },753 },
...@@ -822,41 +767,37 @@ function mapToRuntimeEvents(...@@ -822,41 +767,37 @@ function mapToRuntimeEvents(
822 }767 }
823768
824 if (event.method === "turn/plan/updated") {769 if (event.method === "turn/plan/updated") {
825 const steps = Array.isArray(payload?.plan) ? payload.plan : [];770 const payload = readPayload(EffectCodexSchema.V2TurnPlanUpdatedNotification, event.payload);
771 if (!payload) {
772 return [];
773 }
826 return [774 return [
827 {775 {
828 ...runtimeEventBase(event, canonicalThreadId),776 ...runtimeEventBase(event, canonicalThreadId),
829 type: "turn.plan.updated",777 type: "turn.plan.updated",
830 payload: {778 payload: {
831 ...(asString(payload?.explanation)779 ...(trimText(payload.explanation) ? { explanation: trimText(payload.explanation) } : {}),
832 ? { explanation: asString(payload?.explanation) }780 plan: payload.plan.map((step) => ({
833 : {}),781 step: trimText(step.step) ?? "step",
834 plan: steps782 status:
835 .map((entry) => asObject(entry))783 step.status === "completed" || step.status === "inProgress" ? step.status : "pending",
836 .filter((entry): entry is Record<string, unknown> => entry !== undefined)784 })),
837 .map((entry) => ({
838 step: asString(entry.step) ?? "step",
839 status:
840 entry.status === "completed" || entry.status === "inProgress"
841 ? entry.status
842 : "pending",
843 })),
844 },785 },
845 },786 },
846 ];787 ];
847 }788 }
848789
849 if (event.method === "turn/diff/updated") {790 if (event.method === "turn/diff/updated") {
791 const payload = readPayload(EffectCodexSchema.V2TurnDiffUpdatedNotification, event.payload);
792 if (!payload) {
793 return [];
794 }
850 return [795 return [
851 {796 {
852 ...runtimeEventBase(event, canonicalThreadId),797 ...runtimeEventBase(event, canonicalThreadId),
853 type: "turn.diff.updated",798 type: "turn.diff.updated",
854 payload: {799 payload: {
855 unifiedDiff:800 unifiedDiff: payload.diff,
856 asString(payload?.unifiedDiff) ??
857 asString(payload?.diff) ??
858 asString(payload?.patch) ??
859 "",
860 },801 },
861 },802 },
862 ];803 ];
...@@ -868,15 +809,14 @@ function mapToRuntimeEvents(...@@ -868,15 +809,14 @@ function mapToRuntimeEvents(
868 }809 }
869810
870 if (event.method === "item/completed") {811 if (event.method === "item/completed") {
871 const payload = asObject(event.payload);812 const payload = readPayload(EffectCodexSchema.V2ItemCompletedNotification, event.payload);
872 const item = asObject(payload?.item);813 const item = payload?.item;
873 const source = item ?? payload;814 if (!item) {
874 if (!source) {
875 return [];815 return [];
876 }816 }
877 const itemType = source ? toCanonicalItemType(source.type ?? source.kind) : "unknown";817 const itemType = toCanonicalItemType(item.type);
878 if (itemType === "plan") {818 if (itemType === "plan") {
879 const detail = itemDetail(source, payload ?? {});819 const detail = itemDetail(item);
880 if (!detail) {820 if (!detail) {
881 return [];821 return [];
882 }822 }
...@@ -898,16 +838,22 @@ function mapToRuntimeEvents(...@@ -898,16 +838,22 @@ function mapToRuntimeEvents(
898 event.method === "item/reasoning/summaryPartAdded" ||838 event.method === "item/reasoning/summaryPartAdded" ||
899 event.method === "item/commandExecution/terminalInteraction"839 event.method === "item/commandExecution/terminalInteraction"
900 ) {840 ) {
901 const updated = mapItemLifecycle(event, canonicalThreadId, "item.updated");841 return [
902 return updated ? [updated] : [];842 {
843 ...runtimeEventBase(event, canonicalThreadId),
844 type: "item.updated",
845 payload: {
846 itemType:
847 event.method === "item/reasoning/summaryPartAdded" ? "reasoning" : "command_execution",
848 ...(event.payload !== undefined ? { data: event.payload } : {}),
849 },
850 },
851 ];
903 }852 }
904853
905 if (event.method === "item/plan/delta") {854 if (event.method === "item/plan/delta") {
906 const delta =855 const payload = readPayload(EffectCodexSchema.V2PlanDeltaNotification, event.payload);
907 event.textDelta ??856 const delta = event.textDelta ?? payload?.delta;
908 asString(payload?.delta) ??
909 asString(payload?.text) ??
910 asString(asObject(payload?.content)?.text);
911 if (!delta || delta.length === 0) {857 if (!delta || delta.length === 0) {
912 return [];858 return [];
913 }859 }
...@@ -922,18 +868,9 @@ function mapToRuntimeEvents(...@@ -922,18 +868,9 @@ function mapToRuntimeEvents(
922 ];868 ];
923 }869 }
924870
925 if (871 if (event.method === "item/agentMessage/delta") {
926 event.method === "item/agentMessage/delta" ||872 const payload = readPayload(EffectCodexSchema.V2AgentMessageDeltaNotification, event.payload);
927 event.method === "item/commandExecution/outputDelta" ||873 const delta = event.textDelta ?? payload?.delta;
928 event.method === "item/fileChange/outputDelta" ||
929 event.method === "item/reasoning/summaryTextDelta" ||
930 event.method === "item/reasoning/textDelta"
931 ) {
932 const delta =
933 event.textDelta ??
934 asString(payload?.delta) ??
935 asString(payload?.text) ??
936 asString(asObject(payload?.content)?.text);
937 if (!delta || delta.length === 0) {874 if (!delta || delta.length === 0) {
938 return [];875 return [];
939 }876 }
...@@ -944,216 +881,207 @@ function mapToRuntimeEvents(...@@ -944,216 +881,207 @@ function mapToRuntimeEvents(
944 payload: {881 payload: {
945 streamKind: contentStreamKindFromMethod(event.method),882 streamKind: contentStreamKindFromMethod(event.method),
946 delta,883 delta,
947 ...(typeof payload?.contentIndex === "number"
948 ? { contentIndex: payload.contentIndex }
949 : {}),
950 ...(typeof payload?.summaryIndex === "number"
951 ? { summaryIndex: payload.summaryIndex }
952 : {}),
953 },884 },
954 },885 },
955 ];886 ];
956 }887 }
957888
958 if (event.method === "item/mcpToolCall/progress") {889 if (event.method === "item/commandExecution/outputDelta") {
890 const payload = readPayload(
891 EffectCodexSchema.V2CommandExecutionOutputDeltaNotification,
892 event.payload,
893 );
894 const delta = event.textDelta ?? payload?.delta;
895 if (!delta || delta.length === 0) {
896 return [];
897 }
959 return [898 return [
960 {899 {
961 ...runtimeEventBase(event, canonicalThreadId),900 ...runtimeEventBase(event, canonicalThreadId),
962 type: "tool.progress",901 type: "content.delta",
963 payload: {902 payload: {
964 ...(asString(payload?.toolUseId) ? { toolUseId: asString(payload?.toolUseId) } : {}),903 streamKind: "command_output",
965 ...(asString(payload?.toolName) ? { toolName: asString(payload?.toolName) } : {}),904 delta,
966 ...(asString(payload?.summary) ? { summary: asString(payload?.summary) } : {}),
967 ...(asNumber(payload?.elapsedSeconds) !== undefined
968 ? { elapsedSeconds: asNumber(payload?.elapsedSeconds) }
969 : {}),
970 },905 },
971 },906 },
972 ];907 ];
973 }908 }
974909
975 if (event.method === "serverRequest/resolved") {910 if (event.method === "item/fileChange/outputDelta") {
976 const requestType =911 const payload = readPayload(
977 toRequestTypeFromResolvedPayload(payload) !== "unknown"912 EffectCodexSchema.V2FileChangeOutputDeltaNotification,
978 ? toRequestTypeFromResolvedPayload(payload)913 event.payload,
979 : event.requestId && event.requestKind !== undefined914 );
980 ? toRequestTypeFromKind(event.requestKind)915 const delta = event.textDelta ?? payload?.delta;
981 : "unknown";916 if (!delta || delta.length === 0) {
917 return [];
918 }
982 return [919 return [
983 {920 {
984 ...runtimeEventBase(event, canonicalThreadId),921 ...runtimeEventBase(event, canonicalThreadId),
985 type: "request.resolved",922 type: "content.delta",
986 payload: {923 payload: {
987 requestType,924 streamKind: "file_change_output",
988 ...(event.payload !== undefined ? { resolution: event.payload } : {}),925 delta,
989 },926 },
990 },927 },
991 ];928 ];
992 }929 }
993930
994 if (event.method === "item/tool/requestUserInput/answered") {931 if (event.method === "item/reasoning/summaryTextDelta") {
932 const payload = readPayload(
933 EffectCodexSchema.V2ReasoningSummaryTextDeltaNotification,
934 event.payload,
935 );
936 const delta = event.textDelta ?? payload?.delta;
937 if (!delta || delta.length === 0) {
938 return [];
939 }
995 return [940 return [
996 {941 {
997 ...runtimeEventBase(event, canonicalThreadId),942 ...runtimeEventBase(event, canonicalThreadId),
998 type: "user-input.resolved",943 type: "content.delta",
999 payload: {944 payload: {
1000 answers: toCanonicalUserInputAnswers(945 streamKind: "reasoning_summary_text",
1001 asObject(event.payload)?.answers as ProviderUserInputAnswers | undefined,946 delta,
1002 ),947 ...(payload ? { summaryIndex: payload.summaryIndex } : {}),
1003 },948 },
1004 },949 },
1005 ];950 ];
1006 }951 }
1007952
1008 if (event.method === "codex/event/task_started") {953 if (event.method === "item/reasoning/textDelta") {
1009 const msg = codexEventMessage(payload);954 const payload = readPayload(EffectCodexSchema.V2ReasoningTextDeltaNotification, event.payload);
1010 const taskId = asString(payload?.id) ?? asString(msg?.turn_id);955 const delta = event.textDelta ?? payload?.delta;
1011 if (!taskId) {956 if (!delta || delta.length === 0) {
1012 return [];957 return [];
1013 }958 }
1014 return [959 return [
1015 {960 {
1016 ...codexEventBase(event, canonicalThreadId),961 ...runtimeEventBase(event, canonicalThreadId),
1017 type: "task.started",962 type: "content.delta",
1018 payload: {963 payload: {
1019 taskId: asRuntimeTaskId(taskId),964 streamKind: "reasoning_text",
1020 ...(asString(msg?.collaboration_mode_kind)965 delta,
1021 ? { taskType: asString(msg?.collaboration_mode_kind) }966 ...(payload ? { contentIndex: payload.contentIndex } : {}),
1022 : {}),
1023 },967 },
1024 },968 },
1025 ];969 ];
1026 }970 }
1027971
1028 if (event.method === "codex/event/task_complete") {972 if (event.method === "item/mcpToolCall/progress") {
1029 const msg = codexEventMessage(payload);973 const payload = readPayload(EffectCodexSchema.V2McpToolCallProgressNotification, event.payload);
1030 const taskId = asString(payload?.id) ?? asString(msg?.turn_id);974 if (!payload) {
1031 const proposedPlanMarkdown = extractProposedPlanMarkdown(asString(msg?.last_agent_message));975 return [];
1032 if (!taskId) {
1033 if (!proposedPlanMarkdown) {
1034 return [];
1035 }
1036 return [
1037 {
1038 ...codexEventBase(event, canonicalThreadId),
1039 type: "turn.proposed.completed",
1040 payload: {
1041 planMarkdown: proposedPlanMarkdown,
1042 },
1043 },
1044 ];
1045 }976 }
1046 const events: ProviderRuntimeEvent[] = [977 return [
1047 {978 {
1048 ...codexEventBase(event, canonicalThreadId),979 ...runtimeEventBase(event, canonicalThreadId),
1049 type: "task.completed",980 type: "tool.progress",
1050 payload: {981 payload: {
1051 taskId: asRuntimeTaskId(taskId),982 summary: payload.message,
1052 status: "completed",
1053 ...(asString(msg?.last_agent_message)
1054 ? { summary: asString(msg?.last_agent_message) }
1055 : {}),
1056 },983 },
1057 },984 },
1058 ];985 ];
1059 if (proposedPlanMarkdown) {
1060 events.push({
1061 ...codexEventBase(event, canonicalThreadId),
1062 type: "turn.proposed.completed",
1063 payload: {
1064 planMarkdown: proposedPlanMarkdown,
1065 },
1066 });
1067 }
1068 return events;
1069 }986 }
1070987
1071 if (event.method === "codex/event/agent_reasoning") {988 if (event.method === "serverRequest/resolved") {
1072 const msg = codexEventMessage(payload);989 const payload = readPayload(
1073 const taskId = asString(payload?.id);990 EffectCodexSchema.V2ServerRequestResolvedNotification,
1074 const description = asString(msg?.text);991 event.payload,
1075 if (!taskId || !description) {992 );
993 if (!payload) {
1076 return [];994 return [];
1077 }995 }
996 const requestType = toRequestTypeFromKind(event.requestKind);
1078 return [997 return [
1079 {998 {
1080 ...codexEventBase(event, canonicalThreadId),999 ...runtimeEventBase(event, canonicalThreadId),
1081 type: "task.progress",1000 type: "request.resolved",
1082 payload: {1001 payload: {
1083 taskId: asRuntimeTaskId(taskId),1002 requestType,
1084 description,1003 ...(event.payload !== undefined ? { resolution: event.payload } : {}),
1085 },1004 },
1086 },1005 },
1087 ];1006 ];
1088 }1007 }
10891008
1090 if (event.method === "codex/event/reasoning_content_delta") {1009 if (event.method === "item/tool/requestUserInput/answered") {
1091 const msg = codexEventMessage(payload);1010 const payload = readPayload(EffectCodexSchema.ToolRequestUserInputResponse, event.payload);
1092 const delta = asString(msg?.delta);1011 if (!payload) {
1093 if (!delta) {
1094 return [];1012 return [];
1095 }1013 }
1096 return [1014 return [
1097 {1015 {
1098 ...codexEventBase(event, canonicalThreadId),1016 ...runtimeEventBase(event, canonicalThreadId),
1099 type: "content.delta",1017 type: "user-input.resolved",
1100 payload: {1018 payload: {
1101 streamKind:1019 answers: toCanonicalUserInputAnswers(payload.answers),
1102 asNumber(msg?.summary_index) !== undefined
1103 ? "reasoning_summary_text"
1104 : "reasoning_text",
1105 delta,
1106 ...(asNumber(msg?.summary_index) !== undefined
1107 ? { summaryIndex: asNumber(msg?.summary_index) }
1108 : {}),
1109 },1020 },
1110 },1021 },
1111 ];1022 ];
1112 }1023 }
11131024
1114 if (event.method === "model/rerouted") {1025 if (event.method === "model/rerouted") {
1026 const payload = readPayload(EffectCodexSchema.V2ModelReroutedNotification, event.payload);
1027 if (!payload) {
1028 return [];
1029 }
1115 return [1030 return [
1116 {1031 {
1117 type: "model.rerouted",1032 type: "model.rerouted",
1118 ...runtimeEventBase(event, canonicalThreadId),1033 ...runtimeEventBase(event, canonicalThreadId),
1119 payload: {1034 payload: {
1120 fromModel: asString(payload?.fromModel) ?? "unknown",1035 fromModel: payload.fromModel,
1121 toModel: asString(payload?.toModel) ?? "unknown",1036 toModel: payload.toModel,
1122 reason: asString(payload?.reason) ?? "unknown",1037 reason: payload.reason,
1123 },1038 },
1124 },1039 },
1125 ];1040 ];
1126 }1041 }
11271042
1128 if (event.method === "deprecationNotice") {1043 if (event.method === "deprecationNotice") {
1044 const payload = readPayload(EffectCodexSchema.V2DeprecationNoticeNotification, event.payload);
1045 if (!payload) {
1046 return [];
1047 }
1129 return [1048 return [
1130 {1049 {
1131 type: "deprecation.notice",1050 type: "deprecation.notice",
1132 ...runtimeEventBase(event, canonicalThreadId),1051 ...runtimeEventBase(event, canonicalThreadId),
1133 payload: {1052 payload: {
1134 summary: asString(payload?.summary) ?? "Deprecation notice",1053 summary: payload.summary,
1135 ...(asString(payload?.details) ? { details: asString(payload?.details) } : {}),1054 ...(trimText(payload.details) ? { details: trimText(payload.details) } : {}),
1136 },1055 },
1137 },1056 },
1138 ];1057 ];
1139 }1058 }
11401059
1141 if (event.method === "configWarning") {1060 if (event.method === "configWarning") {
1061 const payload = readPayload(EffectCodexSchema.V2ConfigWarningNotification, event.payload);
1062 if (!payload) {
1063 return [];
1064 }
1142 return [1065 return [
1143 {1066 {
1144 type: "config.warning",1067 type: "config.warning",
1145 ...runtimeEventBase(event, canonicalThreadId),1068 ...runtimeEventBase(event, canonicalThreadId),
1146 payload: {1069 payload: {
1147 summary: asString(payload?.summary) ?? "Configuration warning",1070 summary: payload.summary,
1148 ...(asString(payload?.details) ? { details: asString(payload?.details) } : {}),1071 ...(trimText(payload.details) ? { details: trimText(payload.details) } : {}),
1149 ...(asString(payload?.path) ? { path: asString(payload?.path) } : {}),1072 ...(trimText(payload.path) ? { path: trimText(payload.path) } : {}),
1150 ...(payload?.range !== undefined ? { range: payload.range } : {}),1073 ...(payload.range !== undefined && payload.range !== null
1074 ? { range: payload.range }
1075 : {}),
1151 },1076 },
1152 },1077 },
1153 ];1078 ];
1154 }1079 }
11551080
1156 if (event.method === "account/updated") {1081 if (event.method === "account/updated") {
1082 if (!readPayload(EffectCodexSchema.V2AccountUpdatedNotification, event.payload)) {
1083 return [];
1084 }
1157 return [1085 return [
1158 {1086 {
1159 type: "account.updated",1087 type: "account.updated",
...@@ -1166,6 +1094,9 @@ function mapToRuntimeEvents(...@@ -1166,6 +1094,9 @@ function mapToRuntimeEvents(
1166 }1094 }
11671095
1168 if (event.method === "account/rateLimits/updated") {1096 if (event.method === "account/rateLimits/updated") {
1097 if (!readPayload(EffectCodexSchema.V2AccountRateLimitsUpdatedNotification, event.payload)) {
1098 return [];
1099 }
1169 return [1100 return [
1170 {1101 {
1171 type: "account.rate-limits.updated",1102 type: "account.rate-limits.updated",
...@@ -1178,58 +1109,86 @@ function mapToRuntimeEvents(...@@ -1178,58 +1109,86 @@ function mapToRuntimeEvents(
1178 }1109 }
11791110
1180 if (event.method === "mcpServer/oauthLogin/completed") {1111 if (event.method === "mcpServer/oauthLogin/completed") {
1112 const payload = readPayload(
1113 EffectCodexSchema.V2McpServerOauthLoginCompletedNotification,
1114 event.payload,
1115 );
1116 if (!payload) {
1117 return [];
1118 }
1181 return [1119 return [
1182 {1120 {
1183 type: "mcp.oauth.completed",1121 type: "mcp.oauth.completed",
1184 ...runtimeEventBase(event, canonicalThreadId),1122 ...runtimeEventBase(event, canonicalThreadId),
1185 payload: {1123 payload: {
1186 success: payload?.success === true,1124 success: payload.success,
1187 ...(asString(payload?.name) ? { name: asString(payload?.name) } : {}),1125 name: payload.name,
1188 ...(asString(payload?.error) ? { error: asString(payload?.error) } : {}),1126 ...(trimText(payload.error) ? { error: trimText(payload.error) } : {}),
1189 },1127 },
1190 },1128 },
1191 ];1129 ];
1192 }1130 }
11931131
1194 if (event.method === "thread/realtime/started") {1132 if (event.method === "thread/realtime/started") {
1195 const realtimeSessionId = asString(payload?.realtimeSessionId);1133 const payload = readPayload(
1134 EffectCodexSchema.V2ThreadRealtimeStartedNotification,
1135 event.payload,
1136 );
1137 if (!payload) {
1138 return [];
1139 }
1196 return [1140 return [
1197 {1141 {
1198 type: "thread.realtime.started",1142 type: "thread.realtime.started",
1199 ...runtimeEventBase(event, canonicalThreadId),1143 ...runtimeEventBase(event, canonicalThreadId),
1200 payload: {1144 payload: {
1201 realtimeSessionId,1145 realtimeSessionId: payload.sessionId ?? undefined,
1202 },1146 },
1203 },1147 },
1204 ];1148 ];
1205 }1149 }
12061150
1207 if (event.method === "thread/realtime/itemAdded") {1151 if (event.method === "thread/realtime/itemAdded") {
1152 const payload = readPayload(
1153 EffectCodexSchema.V2ThreadRealtimeItemAddedNotification,
1154 event.payload,
1155 );
1156 if (!payload) {
1157 return [];
1158 }
1208 return [1159 return [
1209 {1160 {
1210 type: "thread.realtime.item-added",1161 type: "thread.realtime.item-added",
1211 ...runtimeEventBase(event, canonicalThreadId),1162 ...runtimeEventBase(event, canonicalThreadId),
1212 payload: {1163 payload: {
1213 item: event.payload ?? {},1164 item: payload.item,
1214 },1165 },
1215 },1166 },
1216 ];1167 ];
1217 }1168 }
12181169
1219 if (event.method === "thread/realtime/outputAudio/delta") {1170 if (event.method === "thread/realtime/outputAudio/delta") {
1171 const payload = readPayload(
1172 EffectCodexSchema.V2ThreadRealtimeOutputAudioDeltaNotification,
1173 event.payload,
1174 );
1175 if (!payload) {
1176 return [];
1177 }
1220 return [1178 return [
1221 {1179 {
1222 type: "thread.realtime.audio.delta",1180 type: "thread.realtime.audio.delta",
1223 ...runtimeEventBase(event, canonicalThreadId),1181 ...runtimeEventBase(event, canonicalThreadId),
1224 payload: {1182 payload: {
1225 audio: event.payload ?? {},1183 audio: payload.audio,
1226 },1184 },
1227 },1185 },
1228 ];1186 ];
1229 }1187 }
12301188
1231 if (event.method === "thread/realtime/error") {1189 if (event.method === "thread/realtime/error") {
1232 const message = asString(payload?.message) ?? event.message ?? "Realtime error";1190 const payload = readPayload(EffectCodexSchema.V2ThreadRealtimeErrorNotification, event.payload);
1191 const message = payload?.message ?? event.message ?? "Realtime error";
1233 return [1192 return [
1234 {1193 {
1235 type: "thread.realtime.error",1194 type: "thread.realtime.error",
...@@ -1242,20 +1201,24 @@ function mapToRuntimeEvents(...@@ -1242,20 +1201,24 @@ function mapToRuntimeEvents(
1242 }1201 }
12431202
1244 if (event.method === "thread/realtime/closed") {1203 if (event.method === "thread/realtime/closed") {
1204 const payload = readPayload(
1205 EffectCodexSchema.V2ThreadRealtimeClosedNotification,
1206 event.payload,
1207 );
1245 return [1208 return [
1246 {1209 {
1247 type: "thread.realtime.closed",1210 type: "thread.realtime.closed",
1248 ...runtimeEventBase(event, canonicalThreadId),1211 ...runtimeEventBase(event, canonicalThreadId),
1249 payload: {1212 payload: {
1250 reason: event.message,1213 reason: payload?.reason ?? event.message,
1251 },1214 },
1252 },1215 },
1253 ];1216 ];
1254 }1217 }
12551218
1256 if (event.method === "error") {1219 if (event.method === "error") {
1257 const message =1220 const payload = readPayload(EffectCodexSchema.V2ErrorNotification, event.payload);
1258 asString(asObject(payload?.error)?.message) ?? event.message ?? "Provider runtime error";1221 const message = payload?.error.message ?? event.message ?? "Provider runtime error";
1259 const willRetry = payload?.willRetry === true;1222 const willRetry = payload?.willRetry === true;
1260 return [1223 return [
1261 {1224 {
...@@ -1296,6 +1259,9 @@ function mapToRuntimeEvents(...@@ -1296,6 +1259,9 @@ function mapToRuntimeEvents(
1296 }1259 }
12971260
1298 if (event.method === "windows/worldWritableWarning") {1261 if (event.method === "windows/worldWritableWarning") {
1262 if (!readPayload(EffectCodexSchema.V2WindowsWorldWritableWarningNotification, event.payload)) {
1263 return [];
1264 }
1299 return [1265 return [
1300 {1266 {
1301 type: "runtime.warning",1267 type: "runtime.warning",
...@@ -1309,8 +1275,13 @@ function mapToRuntimeEvents(...@@ -1309,8 +1275,13 @@ function mapToRuntimeEvents(
1309 }1275 }
13101276
1311 if (event.method === "windowsSandbox/setupCompleted") {1277 if (event.method === "windowsSandbox/setupCompleted") {
1312 const payloadRecord = asObject(event.payload);1278 const payload = readPayload(
1313 const success = payloadRecord?.success;1279 EffectCodexSchema.V2WindowsSandboxSetupCompletedNotification,
1280 event.payload,
1281 );
1282 if (!payload) {
1283 return [];
1284 }
1314 const successMessage = event.message ?? "Windows sandbox setup completed";1285 const successMessage = event.message ?? "Windows sandbox setup completed";
1315 const failureMessage = event.message ?? "Windows sandbox setup failed";1286 const failureMessage = event.message ?? "Windows sandbox setup failed";
13161287
...@@ -1319,12 +1290,12 @@ function mapToRuntimeEvents(...@@ -1319,12 +1290,12 @@ function mapToRuntimeEvents(
1319 type: "session.state.changed",1290 type: "session.state.changed",
1320 ...runtimeEventBase(event, canonicalThreadId),1291 ...runtimeEventBase(event, canonicalThreadId),
1321 payload: {1292 payload: {
1322 state: success === false ? "error" : "ready",1293 state: payload.success === false ? "error" : "ready",
1323 reason: success === false ? failureMessage : successMessage,1294 reason: payload.success === false ? failureMessage : successMessage,
1324 ...(event.payload !== undefined ? { detail: event.payload } : {}),1295 ...(event.payload !== undefined ? { detail: event.payload } : {}),
1325 },1296 },
1326 },1297 },
1327 ...(success === false1298 ...(payload.success === false
1328 ? [1299 ? [
1329 {1300 {
1330 type: "runtime.warning" as const,1301 type: "runtime.warning" as const,
...@@ -1346,6 +1317,7 @@ const makeCodexAdapter = Effect.fn("makeCodexAdapter")(function* (...@@ -1346,6 +1317,7 @@ const makeCodexAdapter = Effect.fn("makeCodexAdapter")(function* (
1346 options?: CodexAdapterLiveOptions,1317 options?: CodexAdapterLiveOptions,
1347) {1318) {
1348 const fileSystem = yield* FileSystem.FileSystem;1319 const fileSystem = yield* FileSystem.FileSystem;
1320 const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
1349 const serverConfig = yield* Effect.service(ServerConfig);1321 const serverConfig = yield* Effect.service(ServerConfig);
1350 const nativeEventLogger =1322 const nativeEventLogger =
1351 options?.nativeEventLogger ??1323 options?.nativeEventLogger ??
...@@ -1354,78 +1326,124 @@ const makeCodexAdapter = Effect.fn("makeCodexAdapter")(function* (...@@ -1354,78 +1326,124 @@ const makeCodexAdapter = Effect.fn("makeCodexAdapter")(function* (
1354 stream: "native",1326 stream: "native",
1355 })1327 })
1356 : undefined);1328 : undefined);
13571329 const managedNativeEventLogger =
1358 const acquireManager = Effect.fn("acquireManager")(function* () {1330 options?.nativeEventLogger === undefined ? nativeEventLogger : undefined;
1359 if (options?.manager) {
1360 return options.manager;
1361 }
1362 const services = yield* Effect.context<never>();
1363 return options?.makeManager?.(services) ?? new CodexAppServerManager(services);
1364 });
1365
1366 const manager = yield* Effect.acquireRelease(acquireManager(), (manager) =>
1367 Effect.sync(() => {
1368 try {
1369 manager.stopAll();
1370 } catch {
1371 // Finalizers should never fail and block shutdown.
1372 }
1373 }),
1374 );
1375 const serverSettingsService = yield* ServerSettingsService;1331 const serverSettingsService = yield* ServerSettingsService;
1332 const runtimeEventQueue = yield* Queue.unbounded<ProviderRuntimeEvent>();
1333 const sessions = new Map<ThreadId, CodexAdapterSessionContext>();
13761334
1377 const startSession: CodexAdapterShape["startSession"] = Effect.fn("startSession")(1335 const startSession: CodexAdapterShape["startSession"] = (input) =>
1378 function* (input) {1336 Effect.scoped(
1379 if (input.provider !== undefined && input.provider !== PROVIDER) {1337 Effect.gen(function* () {
1380 return yield* new ProviderAdapterValidationError({1338 if (input.provider !== undefined && input.provider !== PROVIDER) {
1381 provider: PROVIDER,1339 return yield* new ProviderAdapterValidationError({
1382 operation: "startSession",
1383 issue: `Expected provider '${PROVIDER}' but received '${input.provider}'.`,
1384 });
1385 }
1386
1387 const codexSettings = yield* serverSettingsService.getSettings.pipe(
1388 Effect.map((settings) => settings.providers.codex),
1389 Effect.mapError(
1390 (error) =>
1391 new ProviderAdapterProcessError({
1392 provider: PROVIDER,
1393 threadId: input.threadId,
1394 detail: error.message,
1395 cause: error,
1396 }),
1397 ),
1398 );
1399 const binaryPath = codexSettings.binaryPath;
1400 const homePath = codexSettings.homePath;
1401 const managerInput: CodexAppServerStartSessionInput = {
1402 threadId: input.threadId,
1403 provider: "codex",
1404 ...(input.cwd !== undefined ? { cwd: input.cwd } : {}),
1405 ...(input.resumeCursor !== undefined ? { resumeCursor: input.resumeCursor } : {}),
1406 runtimeMode: input.runtimeMode,
1407 binaryPath,
1408 ...(homePath ? { homePath } : {}),
1409 ...(input.modelSelection?.provider === "codex"
1410 ? { model: input.modelSelection.model }
1411 : {}),
1412 ...(input.modelSelection?.provider === "codex" && input.modelSelection.options?.fastMode
1413 ? { serviceTier: "fast" }
1414 : {}),
1415 };
1416
1417 return yield* Effect.tryPromise({
1418 try: () => manager.startSession(managerInput),
1419 catch: (cause) =>
1420 new ProviderAdapterProcessError({
1421 provider: PROVIDER,1340 provider: PROVIDER,
1422 threadId: input.threadId,1341 operation: "startSession",
1423 detail: `Failed to start Codex adapter session: ${cause instanceof Error ? cause.message : String(cause)}.`,1342 issue: `Expected provider '${PROVIDER}' but received '${input.provider}'.`,
1424 cause,1343 });
1344 }
1345
1346 const existing = sessions.get(input.threadId);
1347 if (existing && !existing.stopped) {
1348 yield* Effect.suspend(() => stopSessionInternal(existing));
1349 }
1350
1351 const codexSettings = yield* serverSettingsService.getSettings.pipe(
1352 Effect.map((settings) => settings.providers.codex),
1353 Effect.mapError(
1354 (error) =>
1355 new ProviderAdapterProcessError({
1356 provider: PROVIDER,
1357 threadId: input.threadId,
1358 detail: error.message,
1359 cause: error,
1360 }),
1361 ),
1362 );
1363 const runtimeInput: CodexSessionRuntimeOptions = {
1364 threadId: input.threadId,
1365 cwd: input.cwd ?? process.cwd(),
1366 binaryPath: codexSettings.binaryPath,
1367 ...(codexSettings.homePath ? { homePath: codexSettings.homePath } : {}),
1368 ...(Schema.is(CodexResumeCursorSchema)(input.resumeCursor)
1369 ? { resumeCursor: input.resumeCursor }
1370 : {}),
1371 runtimeMode: input.runtimeMode,
1372 ...(input.modelSelection?.provider === "codex"
1373 ? { model: input.modelSelection.model }
1374 : {}),
1375 ...(input.modelSelection?.provider === "codex" && input.modelSelection.options?.fastMode
1376 ? { serviceTier: "fast" }
1377 : {}),
1378 };
1379 const sessionScope = yield* Scope.make("sequential");
1380 let sessionScopeTransferred = false;
1381 yield* Effect.addFinalizer(() =>
1382 sessionScopeTransferred ? Effect.void : Scope.close(sessionScope, Exit.void),
1383 );
1384 const createRuntime = options?.makeRuntime ?? makeCodexSessionRuntime;
1385 const runtime = yield* createRuntime(runtimeInput).pipe(
1386 Effect.provideService(Scope.Scope, sessionScope),
1387 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, childProcessSpawner),
1388 Effect.mapError(
1389 (cause) =>
1390 new ProviderAdapterProcessError({
1391 provider: PROVIDER,
1392 threadId: input.threadId,
1393 detail: cause.message,
1394 cause,
1395 }),
1396 ),
1397 );
1398
1399 const eventFiber = yield* Stream.runForEach(runtime.events, (event) =>
1400 Effect.gen(function* () {
1401 yield* writeNativeEvent(event);
1402 const runtimeEvents = mapToRuntimeEvents(event, event.threadId);
1403 if (runtimeEvents.length === 0) {
1404 yield* Effect.logDebug("ignoring unhandled Codex provider event", {
1405 method: event.method,
1406 threadId: event.threadId,
1407 turnId: event.turnId,
1408 itemId: event.itemId,
1409 });
1410 return;
1411 }
1412 yield* Queue.offerAll(runtimeEventQueue, runtimeEvents);
1425 }),1413 }),
1426 });1414 ).pipe(Effect.forkChild);
1427 },1415
1428 );1416 const started = yield* runtime.start().pipe(
1417 Effect.mapError(
1418 (cause) =>
1419 new ProviderAdapterProcessError({
1420 provider: PROVIDER,
1421 threadId: input.threadId,
1422 detail: cause.message,
1423 cause,
1424 }),
1425 ),
1426 Effect.onError(() =>
1427 runtime.close.pipe(
1428 Effect.andThen(Effect.ignore(Scope.close(sessionScope, Exit.void))),
1429 Effect.andThen(Fiber.interrupt(eventFiber)),
1430 Effect.ignore,
1431 ),
1432 ),
1433 );
1434
1435 sessions.set(input.threadId, {
1436 threadId: input.threadId,
1437 scope: sessionScope,
1438 runtime,
1439 eventFiber,
1440 stopped: false,
1441 });
1442 sessionScopeTransferred = true;
1443
1444 return started;
1445 }),
1446 );
14291447
1430 const resolveAttachment = Effect.fn("resolveAttachment")(function* (1448 const resolveAttachment = Effect.fn("resolveAttachment")(function* (
1431 input: ProviderSendTurnInput,1449 input: ProviderSendTurnInput,
...@@ -1436,11 +1454,11 @@ const makeCodexAdapter = Effect.fn("makeCodexAdapter")(function* (...@@ -1436,11 +1454,11 @@ const makeCodexAdapter = Effect.fn("makeCodexAdapter")(function* (
1436 attachment,1454 attachment,
1437 });1455 });
1438 if (!attachmentPath) {1456 if (!attachmentPath) {
1439 return yield* toRequestError(1457 return yield* new ProviderAdapterRequestError({
1440 input.threadId,1458 provider: PROVIDER,
1441 "turn/start",1459 method: "turn/start",
1442 new Error(`Invalid attachment id '${attachment.id}'.`),1460 detail: `Invalid attachment id '${attachment.id}'.`,
1443 );1461 });
1444 }1462 }
1445 const bytes = yield* fileSystem.readFile(attachmentPath).pipe(1463 const bytes = yield* fileSystem.readFile(attachmentPath).pipe(
1446 Effect.mapError(1464 Effect.mapError(
...@@ -1466,48 +1484,55 @@ const makeCodexAdapter = Effect.fn("makeCodexAdapter")(function* (...@@ -1466,48 +1484,55 @@ const makeCodexAdapter = Effect.fn("makeCodexAdapter")(function* (
1466 { concurrency: 1 },1484 { concurrency: 1 },
1467 );1485 );
14681486
1469 return yield* Effect.tryPromise({1487 const session = yield* requireSession(input.threadId);
1470 try: () => {1488 return yield* session.runtime
1471 const managerInput = {1489 .sendTurn({
1472 threadId: input.threadId,1490 ...(input.input !== undefined ? { input: input.input } : {}),
1473 ...(input.input !== undefined ? { input: input.input } : {}),1491 ...(input.modelSelection?.provider === "codex"
1474 ...(input.modelSelection?.provider === "codex"1492 ? { model: input.modelSelection.model }
1475 ? { model: input.modelSelection.model }1493 : {}),
1476 : {}),1494 ...(input.modelSelection?.provider === "codex" &&
1477 ...(input.modelSelection?.provider === "codex" &&1495 input.modelSelection.options?.reasoningEffort !== undefined
1478 input.modelSelection.options?.reasoningEffort !== undefined1496 ? { effort: input.modelSelection.options.reasoningEffort }
1479 ? { effort: input.modelSelection.options.reasoningEffort }1497 : {}),
1480 : {}),1498 ...(input.modelSelection?.provider === "codex" && input.modelSelection.options?.fastMode
1481 ...(input.modelSelection?.provider === "codex" && input.modelSelection.options?.fastMode1499 ? { serviceTier: "fast" }
1482 ? { serviceTier: "fast" }1500 : {}),
1483 : {}),1501 ...(input.interactionMode !== undefined ? { interactionMode: input.interactionMode } : {}),
1484 ...(input.interactionMode !== undefined1502 ...(codexAttachments.length > 0 ? { attachments: codexAttachments } : {}),
1485 ? { interactionMode: input.interactionMode }1503 })
1486 : {}),1504 .pipe(Effect.mapError((cause) => mapCodexRuntimeError(input.threadId, "turn/start", cause)));
1487 ...(codexAttachments.length > 0 ? { attachments: codexAttachments } : {}),1505 });
1488 };1506
1489 return manager.sendTurn(managerInput);1507 const requireSession = Effect.fn("requireSession")(function* (threadId: ThreadId) {
1490 },1508 const session = sessions.get(threadId);
1491 catch: (cause) => toRequestError(input.threadId, "turn/start", cause),1509 if (!session || session.stopped) {
1492 }).pipe(1510 return yield* new ProviderAdapterSessionNotFoundError({
1493 Effect.map((result) => ({1511 provider: PROVIDER,
1494 ...result,1512 threadId,
1495 threadId: input.threadId,1513 });
1496 })),1514 }
1497 );1515 return session;
1498 });1516 });
14991517
1500 const interruptTurn: CodexAdapterShape["interruptTurn"] = (threadId, turnId) =>1518 const interruptTurn: CodexAdapterShape["interruptTurn"] = (threadId, turnId) =>
1501 Effect.tryPromise({1519 requireSession(threadId).pipe(
1502 try: () => manager.interruptTurn(threadId, turnId),1520 Effect.flatMap((session) => session.runtime.interruptTurn(turnId)),
1503 catch: (cause) => toRequestError(threadId, "turn/interrupt", cause),1521 Effect.mapError((cause) =>
1504 });1522 cause._tag === "ProviderAdapterSessionNotFoundError"
1523 ? cause
1524 : mapCodexRuntimeError(threadId, "turn/interrupt", cause),
1525 ),
1526 );
15051527
1506 const readThread: CodexAdapterShape["readThread"] = (threadId) =>1528 const readThread: CodexAdapterShape["readThread"] = (threadId) =>
1507 Effect.tryPromise({1529 requireSession(threadId).pipe(
1508 try: () => manager.readThread(threadId),1530 Effect.flatMap((session) => session.runtime.readThread),
1509 catch: (cause) => toRequestError(threadId, "thread/read", cause),1531 Effect.mapError((cause) =>
1510 }).pipe(1532 cause._tag === "ProviderAdapterSessionNotFoundError"
1533 ? cause
1534 : mapCodexRuntimeError(threadId, "thread/read", cause),
1535 ),
1511 Effect.map((snapshot) => ({1536 Effect.map((snapshot) => ({
1512 threadId,1537 threadId,
1513 turns: snapshot.turns,1538 turns: snapshot.turns,
...@@ -1525,10 +1550,13 @@ const makeCodexAdapter = Effect.fn("makeCodexAdapter")(function* (...@@ -1525,10 +1550,13 @@ const makeCodexAdapter = Effect.fn("makeCodexAdapter")(function* (
1525 );1550 );
1526 }1551 }
15271552
1528 return Effect.tryPromise({1553 return requireSession(threadId).pipe(
1529 try: () => manager.rollbackThread(threadId, numTurns),1554 Effect.flatMap((session) => session.runtime.rollbackThread(numTurns)),
1530 catch: (cause) => toRequestError(threadId, "thread/rollback", cause),1555 Effect.mapError((cause) =>
1531 }).pipe(1556 cause._tag === "ProviderAdapterSessionNotFoundError"
1557 ? cause
1558 : mapCodexRuntimeError(threadId, "thread/rollback", cause),
1559 ),
1532 Effect.map((snapshot) => ({1560 Effect.map((snapshot) => ({
1533 threadId,1561 threadId,
1534 turns: snapshot.turns,1562 turns: snapshot.turns,
...@@ -1537,38 +1565,28 @@ const makeCodexAdapter = Effect.fn("makeCodexAdapter")(function* (...@@ -1537,38 +1565,28 @@ const makeCodexAdapter = Effect.fn("makeCodexAdapter")(function* (
1537 };1565 };
15381566
1539 const respondToRequest: CodexAdapterShape["respondToRequest"] = (threadId, requestId, decision) =>1567 const respondToRequest: CodexAdapterShape["respondToRequest"] = (threadId, requestId, decision) =>
1540 Effect.tryPromise({1568 requireSession(threadId).pipe(
1541 try: () => manager.respondToRequest(threadId, requestId, decision),1569 Effect.flatMap((session) => session.runtime.respondToRequest(requestId, decision)),
1542 catch: (cause) => toRequestError(threadId, "item/requestApproval/decision", cause),1570 Effect.mapError((cause) =>
1543 });1571 cause._tag === "ProviderAdapterSessionNotFoundError"
1572 ? cause
1573 : mapCodexRuntimeError(threadId, "item/requestApproval/decision", cause),
1574 ),
1575 );
15441576
1545 const respondToUserInput: CodexAdapterShape["respondToUserInput"] = (1577 const respondToUserInput: CodexAdapterShape["respondToUserInput"] = (
1546 threadId,1578 threadId,
1547 requestId,1579 requestId,
1548 answers,1580 answers,
1549 ) =>1581 ) =>
1550 Effect.tryPromise({1582 requireSession(threadId).pipe(
1551 try: () => manager.respondToUserInput(threadId, requestId, answers),1583 Effect.flatMap((session) => session.runtime.respondToUserInput(requestId, answers)),
1552 catch: (cause) => toRequestError(threadId, "item/tool/requestUserInput", cause),1584 Effect.mapError((cause) =>
1553 });1585 cause._tag === "ProviderAdapterSessionNotFoundError"
15541586 ? cause
1555 const stopSession: CodexAdapterShape["stopSession"] = (threadId) =>1587 : mapCodexRuntimeError(threadId, "item/tool/requestUserInput", cause),
1556 Effect.sync(() => {1588 ),
1557 manager.stopSession(threadId);1589 );
1558 });
1559
1560 const listSessions: CodexAdapterShape["listSessions"] = () =>
1561 Effect.sync(() => manager.listSessions());
1562
1563 const hasSession: CodexAdapterShape["hasSession"] = (threadId) =>
1564 Effect.sync(() => manager.hasSession(threadId));
1565
1566 const stopAll: CodexAdapterShape["stopAll"] = () =>
1567 Effect.sync(() => {
1568 manager.stopAll();
1569 });
1570
1571 const runtimeEventQueue = yield* Queue.unbounded<ProviderRuntimeEvent>();
15721590
1573 const writeNativeEvent = Effect.fn("writeNativeEvent")(function* (event: ProviderEvent) {1591 const writeNativeEvent = Effect.fn("writeNativeEvent")(function* (event: ProviderEvent) {
1574 if (!nativeEventLogger) {1592 if (!nativeEventLogger) {
...@@ -1577,38 +1595,51 @@ const makeCodexAdapter = Effect.fn("makeCodexAdapter")(function* (...@@ -1577,38 +1595,51 @@ const makeCodexAdapter = Effect.fn("makeCodexAdapter")(function* (
1577 yield* nativeEventLogger.write(event, event.threadId);1595 yield* nativeEventLogger.write(event, event.threadId);
1578 });1596 });
15791597
1580 const registerListener = Effect.fn("registerListener")(function* () {1598 const stopSessionInternal = Effect.fn("stopSessionInternal")(function* (
1581 const services = yield* Effect.context<never>();1599 session: CodexAdapterSessionContext,
1582 const listenerEffect = Effect.fn("listener")(function* (event: ProviderEvent) {1600 ) {
1583 yield* writeNativeEvent(event);1601 if (session.stopped) {
1584 const runtimeEvents = mapToRuntimeEvents(event, event.threadId);1602 return;
1585 if (runtimeEvents.length === 0) {1603 }
1586 yield* Effect.logDebug("ignoring unhandled Codex provider event", {1604 session.stopped = true;
1587 method: event.method,1605 sessions.delete(session.threadId);
1588 threadId: event.threadId,1606 yield* session.runtime.close.pipe(Effect.ignore);
1589 turnId: event.turnId,1607 yield* Effect.ignore(Scope.close(session.scope, Exit.void));
1590 itemId: event.itemId,1608 yield* Fiber.interrupt(session.eventFiber).pipe(Effect.ignore);
1591 });1609 });
1610
1611 const stopSession: CodexAdapterShape["stopSession"] = (threadId) =>
1612 Effect.gen(function* () {
1613 const session = sessions.get(threadId);
1614 if (!session) {
1592 return;1615 return;
1593 }1616 }
1594 yield* Queue.offerAll(runtimeEventQueue, runtimeEvents);1617 yield* stopSessionInternal(session);
1595 });1618 });
1596 const listener = (event: ProviderEvent) =>
1597 listenerEffect(event).pipe(Effect.runPromiseWith(services));
1598 manager.on("event", listener);
1599 return listener;
1600 });
16011619
1602 const unregisterListener = Effect.fn("unregisterListener")(function* (1620 const listSessions: CodexAdapterShape["listSessions"] = () =>
1603 listener: (event: ProviderEvent) => Promise<void>,1621 Effect.forEach(
1604 ) {1622 Array.from(sessions.values()).filter((session) => !session.stopped),
1605 yield* Effect.sync(() => {1623 (session) => session.runtime.getSession,
1606 manager.off("event", listener);1624 { concurrency: 1 },
1607 });1625 );
1608 yield* Queue.shutdown(runtimeEventQueue);
1609 });
16101626
1611 yield* Effect.acquireRelease(registerListener(), unregisterListener);1627 const hasSession: CodexAdapterShape["hasSession"] = (threadId) =>
1628 Effect.succeed(Boolean(sessions.get(threadId) && !sessions.get(threadId)?.stopped));
1629
1630 const stopAll: CodexAdapterShape["stopAll"] = () =>
1631 Effect.forEach(Array.from(sessions.values()), stopSessionInternal, {
1632 concurrency: 1,
1633 discard: true,
1634 }).pipe(Effect.asVoid);
1635
1636 yield* Effect.acquireRelease(Effect.void, () =>
1637 stopAll().pipe(
1638 Effect.andThen(Queue.shutdown(runtimeEventQueue)),
1639 Effect.andThen(managedNativeEventLogger?.close() ?? Effect.void),
1640 Effect.ignore,
1641 ),
1642 );
16121643
1613 return {1644 return {
1614 provider: PROVIDER,1645 provider: PROVIDER,
apps/server/src/provider/Layers/CodexProvider.ts+344-517
...@@ -1,366 +1,290 @@...@@ -1,366 +1,290 @@
1import * as OS from "node:os";
2import type {
3 ModelCapabilities,
4 CodexSettings,
5 ServerProvider,
6 ServerProviderModel,
7 ServerProviderAuth,
8 ServerProviderSkill,
9 ServerProviderState,
10} from "@t3tools/contracts";
11import {1import {
12 Cache,2 DateTime,
13 Duration,3 Duration,
14 Effect,4 Effect,
15 Equal,5 Equal,
16 FileSystem,
17 Layer,6 Layer,
18 Option,7 Option,
19 Path,
20 Result,8 Result,
9 Schema,
21 Stream,10 Stream,
11 Types,
22} from "effect";12} from "effect";
23import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";13import { ChildProcessSpawner } from "effect/unstable/process";
14import * as CodexClient from "effect-codex-app-server/client";
15import * as CodexSchema from "effect-codex-app-server/schema";
16import * as CodexErrors from "effect-codex-app-server/errors";
17
18import type {
19 CodexSettings,
20 ServerProvider,
21 ServerProviderState,
22 ModelCapabilities,
23 ServerProviderModel,
24 ServerProviderSkill,
25} from "@t3tools/contracts";
26import { ServerSettingsError } from "@t3tools/contracts";
2427
25import {
26 buildServerProvider,
27 DEFAULT_TIMEOUT_MS,
28 detailFromResult,
29 extractAuthBoolean,
30 isCommandMissingCause,
31 parseGenericCliVersion,
32 providerModelsFromSettings,
33 spawnAndCollect,
34 type CommandResult,
35} from "../providerSnapshot.ts";
36import { makeManagedServerProvider } from "../makeManagedServerProvider.ts";28import { makeManagedServerProvider } from "../makeManagedServerProvider.ts";
37import {29import { buildServerProvider } from "../providerSnapshot.ts";
38 formatCodexCliUpgradeMessage,
39 isCodexCliVersionSupported,
40 parseCodexCliVersion,
41} from "../codexCliVersion.ts";
42import {
43 adjustCodexModelsForAccount,
44 codexAuthSubLabel,
45 codexAuthSubType,
46 type CodexAccountSnapshot,
47} from "../codexAccount.ts";
48import { probeCodexDiscovery } from "../codexAppServer.ts";
49import { CodexProvider } from "../Services/CodexProvider.ts";30import { CodexProvider } from "../Services/CodexProvider.ts";
50import { expandHomePath } from "../../pathExpansion.ts";
51import { ServerSettingsService } from "../../serverSettings.ts";31import { ServerSettingsService } from "../../serverSettings.ts";
52import { ServerSettingsError } from "@t3tools/contracts";32import packageJson from "../../../package.json" with { type: "json" };
5333
54const DEFAULT_CODEX_MODEL_CAPABILITIES: ModelCapabilities = {34const PROVIDER = "codex" as const;
55 reasoningEffortLevels: [35const PROVIDER_PROBE_TIMEOUT_MS = 8_000;
56 { value: "xhigh", label: "Extra High" },36
57 { value: "high", label: "High", isDefault: true },37export interface CodexAppServerProviderSnapshot {
58 { value: "medium", label: "Medium" },38 readonly account: CodexSchema.V2GetAccountResponse;
59 { value: "low", label: "Low" },39 readonly version: string | undefined;
60 ],40 readonly models: ReadonlyArray<ServerProviderModel>;
61 supportsFastMode: true,41 readonly skills: ReadonlyArray<ServerProviderSkill>;
62 supportsThinkingToggle: false,42}
63 contextWindowOptions: [],43
64 promptInjectedEffortLevels: [],44const REASONING_EFFORT_LABELS: Record<CodexSchema.V2ModelListResponse__ReasoningEffort, string> = {
45 none: "None",
46 minimal: "Minimal",
47 low: "Low",
48 medium: "Medium",
49 high: "High",
50 xhigh: "Extra High",
65};51};
6652
67const PROVIDER = "codex" as const;53function codexAccountAuthLabel(account: CodexSchema.V2GetAccountResponse["account"]) {
68const OPENAI_AUTH_PROVIDERS = new Set(["openai"]);54 if (!account) return undefined;
69const BUILT_IN_MODELS: ReadonlyArray<ServerProviderModel> = [55 if (account.type === "apiKey") return "OpenAI API Key";
70 {56
71 slug: "gpt-5.4",57 switch (account.planType) {
72 name: "GPT-5.4",58 case "free":
73 isCustom: false,59 return "ChatGPT Free Subscription";
74 capabilities: {60 case "go":
75 reasoningEffortLevels: [61 return "ChatGPT Go Subscription";
76 { value: "xhigh", label: "Extra High" },62 case "plus":
77 { value: "high", label: "High", isDefault: true },63 return "ChatGPT Plus Subscription";
78 { value: "medium", label: "Medium" },64 case "pro":
79 { value: "low", label: "Low" },65 return "ChatGPT Pro Subscription";
80 ],66 case "team":
81 supportsFastMode: true,67 return "ChatGPT Team Subscription";
82 supportsThinkingToggle: false,68 case "self_serve_business_usage_based":
83 contextWindowOptions: [],69 case "business":
84 promptInjectedEffortLevels: [],70 return "ChatGPT Business Subscription";
85 },71 case "enterprise_cbp_usage_based":
86 },72 case "enterprise":
87 {73 return "ChatGPT Enterprise Subscription";
88 slug: "gpt-5.4-mini",74 case "edu":
89 name: "GPT-5.4 Mini",75 return "ChatGPT Edu Subscription";
90 isCustom: false,76 case "unknown":
91 capabilities: {77 return "ChatGPT Subscription";
92 reasoningEffortLevels: [78 default:
93 { value: "xhigh", label: "Extra High" },79 account.planType satisfies never;
94 { value: "high", label: "High", isDefault: true },80 return undefined;
95 { value: "medium", label: "Medium" },81 }
96 { value: "low", label: "Low" },82}
97 ],83
98 supportsFastMode: true,84function mapCodexModelCapabilities(
99 supportsThinkingToggle: false,85 model: CodexSchema.V2ModelListResponse__Model,
100 contextWindowOptions: [],86): ModelCapabilities {
101 promptInjectedEffortLevels: [],87 return {
102 },88 reasoningEffortLevels: model.supportedReasoningEfforts.map(({ reasoningEffort }) => ({
103 },89 value: reasoningEffort,
104 {90 label: REASONING_EFFORT_LABELS[reasoningEffort],
105 slug: "gpt-5.3-codex",91 ...(reasoningEffort === model.defaultReasoningEffort ? { isDefault: true } : {}),
106 name: "GPT-5.3 Codex",92 })),
107 isCustom: false,93 supportsFastMode: (model.additionalSpeedTiers ?? []).includes("fast"),
108 capabilities: {94 supportsThinkingToggle: false,
109 reasoningEffortLevels: [95 contextWindowOptions: [],
110 { value: "xhigh", label: "Extra High" },96 promptInjectedEffortLevels: [],
111 { value: "high", label: "High", isDefault: true },97 };
112 { value: "medium", label: "Medium" },98}
113 { value: "low", label: "Low" },99
114 ],100const toDisplayName = (model: CodexSchema.V2ModelListResponse__Model): string => {
115 supportsFastMode: true,101 // Capitalize 'gpt' to 'GPT-' and capitalize any letter following a dash
116 supportsThinkingToggle: false,102 return model.displayName
117 contextWindowOptions: [],103 .replace(/^gpt/i, "GPT") // Handle start with 'gpt' or 'GPT'
118 promptInjectedEffortLevels: [],104 .replace(/-([a-z])/g, (_, c) => "-" + c.toUpperCase());
119 },105};
120 },106
121 {107function parseCodexModelListResponse(
122 slug: "gpt-5.3-codex-spark",108 response: CodexSchema.V2ModelListResponse,
123 name: "GPT-5.3 Codex Spark",109): ReadonlyArray<ServerProviderModel> {
124 isCustom: false,110 return response.data.map((model) => ({
125 capabilities: {111 slug: model.model,
126 reasoningEffortLevels: [112 name: toDisplayName(model),
127 { value: "xhigh", label: "Extra High" },
128 { value: "high", label: "High", isDefault: true },
129 { value: "medium", label: "Medium" },
130 { value: "low", label: "Low" },
131 ],
132 supportsFastMode: true,
133 supportsThinkingToggle: false,
134 contextWindowOptions: [],
135 promptInjectedEffortLevels: [],
136 },
137 },
138 {
139 slug: "gpt-5.2-codex",
140 name: "GPT-5.2 Codex",
141 isCustom: false,
142 capabilities: {
143 reasoningEffortLevels: [
144 { value: "xhigh", label: "Extra High" },
145 { value: "high", label: "High", isDefault: true },
146 { value: "medium", label: "Medium" },
147 { value: "low", label: "Low" },
148 ],
149 supportsFastMode: true,
150 supportsThinkingToggle: false,
151 contextWindowOptions: [],
152 promptInjectedEffortLevels: [],
153 },
154 },
155 {
156 slug: "gpt-5.2",
157 name: "GPT-5.2",
158 isCustom: false,113 isCustom: false,
159 capabilities: {114 capabilities: mapCodexModelCapabilities(model),
160 reasoningEffortLevels: [115 }));
161 { value: "xhigh", label: "Extra High" },
162 { value: "high", label: "High", isDefault: true },
163 { value: "medium", label: "Medium" },
164 { value: "low", label: "Low" },
165 ],
166 supportsFastMode: true,
167 supportsThinkingToggle: false,
168 contextWindowOptions: [],
169 promptInjectedEffortLevels: [],
170 },
171 },
172];
173
174export function getCodexModelCapabilities(model: string | null | undefined): ModelCapabilities {
175 const slug = model?.trim();
176 return (
177 BUILT_IN_MODELS.find((candidate) => candidate.slug === slug)?.capabilities ??
178 DEFAULT_CODEX_MODEL_CAPABILITIES
179 );
180}116}
181117
182export function parseAuthStatusFromOutput(result: CommandResult): {118function appendCustomCodexModels(
183 readonly status: Exclude<ServerProviderState, "disabled">;119 models: ReadonlyArray<ServerProviderModel>,
184 readonly auth: Pick<ServerProviderAuth, "status">;120 customModels: ReadonlyArray<string>,
185 readonly message?: string;121): ReadonlyArray<ServerProviderModel> {
186} {122 if (customModels.length === 0) {
187 const lowerOutput = `${result.stdout}\n${result.stderr}`.toLowerCase();123 return models;
124 }
188125
189 if (126 const seen = new Set(models.map((model) => model.slug));
190 lowerOutput.includes("unknown command") ||127 const fallbackCapabilities = models.find((model) => model.capabilities)?.capabilities ?? null;
191 lowerOutput.includes("unrecognized command") ||128 const customEntries: ServerProviderModel[] = [];
192 lowerOutput.includes("unexpected argument")129 for (const rawModel of customModels) {
193 ) {130 const slug = rawModel.trim();
194 return {131 if (!slug || seen.has(slug)) {
195 status: "warning",132 continue;
196 auth: { status: "unknown" },133 }
197 message: "Codex CLI authentication status command is unavailable in this Codex version.",134 seen.add(slug);
198 };135 customEntries.push({
136 slug,
137 name: slug,
138 isCustom: true,
139 capabilities: fallbackCapabilities,
140 });
199 }141 }
142 return customEntries.length === 0 ? models : [...models, ...customEntries];
143}
200144
201 if (145function parseCodexSkillsListResponse(
202 lowerOutput.includes("not logged in") ||146 response: CodexSchema.V2SkillsListResponse,
203 lowerOutput.includes("login required") ||147 cwd: string,
204 lowerOutput.includes("authentication required") ||148): ReadonlyArray<ServerProviderSkill> {
205 lowerOutput.includes("run `codex login`") ||149 const matchingEntry = response.data.find((entry) => entry.cwd === cwd);
206 lowerOutput.includes("run codex login")150 const skills = matchingEntry
207 ) {151 ? matchingEntry.skills
208 return {152 : response.data.flatMap((entry) => entry.skills);
209 status: "error",153
210 auth: { status: "unauthenticated" },154 return skills.map((skill) => {
211 message: "Codex CLI is not authenticated. Run `codex login` and try again.",155 const shortDescription =
156 skill.shortDescription ?? skill.interface?.shortDescription ?? undefined;
157
158 const parsedSkill: Types.Mutable<ServerProviderSkill> = {
159 name: skill.name,
160 path: skill.path,
161 enabled: skill.enabled,
212 };162 };
213 }
214163
215 const parsedAuth = (() => {164 if (skill.description) {
216 const trimmed = result.stdout.trim();165 parsedSkill.description = skill.description;
217 if (!trimmed || (!trimmed.startsWith("{") && !trimmed.startsWith("["))) {
218 return { attemptedJsonParse: false as const, auth: undefined as boolean | undefined };
219 }166 }
220 try {167 if (skill.scope) {
221 return {168 parsedSkill.scope = skill.scope;
222 attemptedJsonParse: true as const,169 }
223 auth: extractAuthBoolean(JSON.parse(trimmed)),170 if (skill.interface?.displayName) {
224 };171 parsedSkill.displayName = skill.interface.displayName;
225 } catch {172 }
226 return { attemptedJsonParse: false as const, auth: undefined as boolean | undefined };173 if (shortDescription) {
174 parsedSkill.shortDescription = shortDescription;
227 }175 }
228 })();
229
230 if (parsedAuth.auth === true) {
231 return { status: "ready", auth: { status: "authenticated" } };
232 }
233 if (parsedAuth.auth === false) {
234 return {
235 status: "error",
236 auth: { status: "unauthenticated" },
237 message: "Codex CLI is not authenticated. Run `codex login` and try again.",
238 };
239 }
240 if (parsedAuth.attemptedJsonParse) {
241 return {
242 status: "warning",
243 auth: { status: "unknown" },
244 message:
245 "Could not verify Codex authentication status from JSON output (missing auth marker).",
246 };
247 }
248 if (result.code === 0) {
249 return { status: "ready", auth: { status: "authenticated" } };
250 }
251176
252 const detail = detailFromResult(result);177 return parsedSkill;
253 return {178 });
254 status: "warning",
255 auth: { status: "unknown" },
256 message: detail
257 ? `Could not verify Codex authentication status. ${detail}`
258 : "Could not verify Codex authentication status.",
259 };
260}179}
261180
262export const readCodexConfigModelProvider = Effect.fn("readCodexConfigModelProvider")(function* () {181const requestAllCodexModels = Effect.fn("requestAllCodexModels")(function* (
263 const fileSystem = yield* FileSystem.FileSystem;182 client: CodexClient.CodexAppServerClientShape,
264 const path = yield* Path.Path;183) {
265 const settingsService = yield* ServerSettingsService;184 const models: ServerProviderModel[] = [];
266 const codexHome = yield* settingsService.getSettings.pipe(185 let cursor: string | null | undefined = undefined;
267 Effect.map(
268 (settings) =>
269 settings.providers.codex.homePath ||
270 process.env.CODEX_HOME ||
271 path.join(OS.homedir(), ".codex"),
272 ),
273 );
274 const configPath = path.join(codexHome, "config.toml");
275186
276 const content = yield* fileSystem187 do {
277 .readFileString(configPath)188 const response: CodexSchema.V2ModelListResponse = yield* client.request(
278 .pipe(Effect.orElseSucceed(() => undefined));189 "model/list",
279 if (content === undefined) {190 cursor ? { cursor } : {},
280 return undefined;191 );
281 }192 models.push(...parseCodexModelListResponse(response));
282193 cursor = response.nextCursor;
283 let inTopLevel = true;194 } while (cursor);
284 for (const line of content.split("\n")) {
285 const trimmed = line.trim();
286 if (!trimmed || trimmed.startsWith("#")) continue;
287 if (trimmed.startsWith("[")) {
288 inTopLevel = false;
289 continue;
290 }
291 if (!inTopLevel) continue;
292195
293 const match = trimmed.match(/^model_provider\s*=\s*["']([^"']+)["']/);196 return models;
294 if (match) return match[1];
295 }
296 return undefined;
297});197});
298198
299export const hasCustomModelProvider = readCodexConfigModelProvider().pipe(199export function buildCodexInitializeParams(): CodexSchema.V1InitializeParams {
300 Effect.map((provider) => provider !== undefined && !OPENAI_AUTH_PROVIDERS.has(provider)),200 return {
301 Effect.orElseSucceed(() => false),201 clientInfo: {
302);202 name: "t3code_desktop",
303203 title: "T3 Code Desktop",
304const CAPABILITIES_PROBE_TIMEOUT_MS = 8_000;204 version: packageJson.version,
205 },
206 capabilities: {
207 experimentalApi: true,
208 },
209 };
210}
305211
306const probeCodexCapabilities = (input: {212const probeCodexAppServerProvider = Effect.fn("probeCodexAppServerProvider")(function* (input: {
307 readonly binaryPath: string;213 readonly binaryPath: string;
308 readonly homePath?: string;214 readonly homePath?: string;
309 readonly cwd: string;215 readonly cwd: string;
310}) =>216 readonly customModels?: ReadonlyArray<string>;
311 Effect.tryPromise((signal) => probeCodexDiscovery({ ...input, signal })).pipe(217}) {
312 Effect.timeoutOption(CAPABILITIES_PROBE_TIMEOUT_MS),218 const clientContext = yield* Layer.build(
313 Effect.result,219 CodexClient.layerCommand({
314 Effect.map((result) => {220 command: input.binaryPath,
315 if (Result.isFailure(result)) return undefined;221 args: ["app-server"],
316 return Option.isSome(result.success) ? result.success.value : undefined;222 cwd: input.cwd,
223 ...(input.homePath ? { env: { CODEX_HOME: input.homePath } } : {}),
317 }),224 }),
318 );225 );
319226 const client = yield* Effect.service(CodexClient.CodexAppServerClient).pipe(
320const runCodexCommand = Effect.fn("runCodexCommand")(function* (args: ReadonlyArray<string>) {227 Effect.provide(clientContext),
321 const settingsService = yield* ServerSettingsService;
322 const codexSettings = yield* settingsService.getSettings.pipe(
323 Effect.map((settings) => settings.providers.codex),
324 );228 );
325 const command = ChildProcess.make(codexSettings.binaryPath, [...args], {229
326 shell: process.platform === "win32",230 const initialize = yield* client.request("initialize", {
327 env: {231 clientInfo: {
328 ...process.env,232 name: "t3code_desktop",
329 ...(codexSettings.homePath ? { CODEX_HOME: expandHomePath(codexSettings.homePath) } : {}),233 title: "T3 Code Desktop",
234 version: "0.1.0",
235 },
236 capabilities: {
237 experimentalApi: true,
330 },238 },
331 });239 });
332 return yield* spawnAndCollect(codexSettings.binaryPath, command);240 yield* client.notify("initialized", undefined);
333});
334241
335export const checkCodexProviderStatus = Effect.fn("checkCodexProviderStatus")(function* (242 // Extract the version string after the first '/' in userAgent, up to the next space or the end
336 resolveAccount?: (input: {243 const versionMatch = initialize.userAgent.match(/\/([^\s]+)/);
337 readonly binaryPath: string;244 const version = versionMatch ? versionMatch[1] : undefined;
338 readonly homePath?: string;245
339 }) => Effect.Effect<CodexAccountSnapshot | undefined>,246 const accountResponse = yield* client.request("account/read", {});
340 resolveSkills?: (input: {247 if (!accountResponse.account && accountResponse.requiresOpenaiAuth) {
341 readonly binaryPath: string;248 return {
342 readonly homePath?: string;249 account: accountResponse,
343 readonly cwd: string;250 version,
344 }) => Effect.Effect<ReadonlyArray<ServerProviderSkill> | undefined>,251 models: appendCustomCodexModels([], input.customModels ?? []),
345): Effect.fn.Return<252 skills: [],
346 ServerProvider,253 } satisfies CodexAppServerProviderSnapshot;
347 ServerSettingsError,254 }
348 | ChildProcessSpawner.ChildProcessSpawner255
349 | FileSystem.FileSystem256 const [skillsResponse, models] = yield* Effect.all(
350 | Path.Path257 [
351 | ServerSettingsService258 client.request("skills/list", {
352> {259 cwds: [input.cwd],
353 const codexSettings = yield* Effect.service(ServerSettingsService).pipe(260 }),
354 Effect.flatMap((service) => service.getSettings),261 requestAllCodexModels(client),
355 Effect.map((settings) => settings.providers.codex),262 ],
263 { concurrency: "unbounded" },
356 );264 );
265
266 return {
267 account: accountResponse,
268 version,
269 models: appendCustomCodexModels(models, input.customModels ?? []),
270 skills: parseCodexSkillsListResponse(skillsResponse, input.cwd),
271 } satisfies CodexAppServerProviderSnapshot;
272}, Effect.scoped);
273
274const emptyCodexModelsFromSettings = (codexSettings: CodexSettings): ServerProvider["models"] =>
275 codexSettings.customModels
276 .map((model) => model.trim())
277 .filter((model, index, models) => model.length > 0 && models.indexOf(model) === index)
278 .map((model) => ({
279 slug: model,
280 name: model,
281 isCustom: true,
282 capabilities: null,
283 }));
284
285const makePendingCodexProvider = (codexSettings: CodexSettings): ServerProvider => {
357 const checkedAt = new Date().toISOString();286 const checkedAt = new Date().toISOString();
358 const models = providerModelsFromSettings(287 const models = emptyCodexModelsFromSettings(codexSettings);
359 BUILT_IN_MODELS,
360 PROVIDER,
361 codexSettings.customModels,
362 DEFAULT_CODEX_MODEL_CAPABILITIES,
363 );
364288
365 if (!codexSettings.enabled) {289 if (!codexSettings.enabled) {
366 return buildServerProvider({290 return buildServerProvider({
...@@ -368,6 +292,7 @@ export const checkCodexProviderStatus = Effect.fn("checkCodexProviderStatus")(fu...@@ -368,6 +292,7 @@ export const checkCodexProviderStatus = Effect.fn("checkCodexProviderStatus")(fu
368 enabled: false,292 enabled: false,
369 checkedAt,293 checkedAt,
370 models,294 models,
295 skills: [],
371 probe: {296 probe: {
372 installed: false,297 installed: false,
373 version: null,298 version: null,
...@@ -378,259 +303,160 @@ export const checkCodexProviderStatus = Effect.fn("checkCodexProviderStatus")(fu...@@ -378,259 +303,160 @@ export const checkCodexProviderStatus = Effect.fn("checkCodexProviderStatus")(fu
378 });303 });
379 }304 }
380305
381 const versionProbe = yield* runCodexCommand(["--version"]).pipe(306 return buildServerProvider({
382 Effect.timeoutOption(DEFAULT_TIMEOUT_MS),307 provider: PROVIDER,
383 Effect.result,308 enabled: true,
384 );309 checkedAt,
310 models,
311 skills: [],
312 probe: {
313 installed: false,
314 version: null,
315 status: "warning",
316 auth: { status: "unknown" },
317 message: "Codex provider status has not been checked in this session yet.",
318 },
319 });
320};
385321
386 if (Result.isFailure(versionProbe)) {322function accountProbeStatus(account: CodexAppServerProviderSnapshot["account"]): {
387 const error = versionProbe.failure;323 readonly status: Exclude<ServerProviderState, "disabled">;
388 return buildServerProvider({324 readonly auth: ServerProvider["auth"];
389 provider: PROVIDER,325 readonly message?: string;
390 enabled: codexSettings.enabled,326} {
391 checkedAt,327 const authLabel = codexAccountAuthLabel(account.account);
392 models,328 const auth = {
393 probe: {329 status: account.account ? ("authenticated" as const) : ("unknown" as const),
394 installed: !isCommandMissingCause(error),330 ...(account.account?.type ? { type: account.account?.type } : {}),
395 version: null,331 ...(authLabel ? { label: authLabel } : {}),
396 status: "error",332 } satisfies ServerProvider["auth"];
397 auth: { status: "unknown" },333
398 message: isCommandMissingCause(error)334 if (account.account) {
399 ? "Codex CLI (`codex`) is not installed or not on PATH."335 return { status: "ready", auth };
400 : `Failed to execute Codex CLI health check: ${error.message}.`,
401 },
402 });
403 }336 }
404337
405 if (Option.isNone(versionProbe.success)) {338 if (account.requiresOpenaiAuth) {
406 return buildServerProvider({339 return {
407 provider: PROVIDER,340 status: "error",
408 enabled: codexSettings.enabled,341 auth: { status: "unauthenticated" },
409 checkedAt,342 message: "Codex CLI is not authenticated. Run `codex login` and try again.",
410 models,343 };
411 probe: {
412 installed: true,
413 version: null,
414 status: "error",
415 auth: { status: "unknown" },
416 message: "Codex CLI is installed but failed to run. Timed out while running command.",
417 },
418 });
419 }344 }
420345
421 const version = versionProbe.success.value;346 return { status: "ready", auth };
422 const parsedVersion =347}
423 parseCodexCliVersion(`${version.stdout}\n${version.stderr}`) ??348
424 parseGenericCliVersion(`${version.stdout}\n${version.stderr}`);349export const checkCodexProviderStatus = Effect.fn("checkCodexProviderStatus")(function* (
425 if (version.code !== 0) {350 probe: (input: {
426 const detail = detailFromResult(version);351 readonly binaryPath: string;
427 return buildServerProvider({352 readonly homePath?: string;
428 provider: PROVIDER,353 readonly cwd: string;
429 enabled: codexSettings.enabled,354 readonly customModels: ReadonlyArray<string>;
430 checkedAt,355 }) => Effect.Effect<
431 models,356 CodexAppServerProviderSnapshot,
432 probe: {357 CodexErrors.CodexAppServerError,
433 installed: true,358 ChildProcessSpawner.ChildProcessSpawner
434 version: parsedVersion,359 > = probeCodexAppServerProvider,
435 status: "error",360): Effect.fn.Return<
436 auth: { status: "unknown" },361 ServerProvider,
437 message: detail362 ServerSettingsError,
438 ? `Codex CLI is installed but failed to run. ${detail}`363 ServerSettingsService | ChildProcessSpawner.ChildProcessSpawner
439 : "Codex CLI is installed but failed to run.",364> {
440 },365 const codexSettings = yield* Effect.service(ServerSettingsService).pipe(
441 });366 Effect.flatMap((service) => service.getSettings),
442 }367 Effect.map((settings) => settings.providers.codex),
368 );
369 const checkedAt = DateTime.formatIso(yield* DateTime.now);
370 const emptyModels = emptyCodexModelsFromSettings(codexSettings);
443371
444 if (parsedVersion && !isCodexCliVersionSupported(parsedVersion)) {372 if (!codexSettings.enabled) {
445 return buildServerProvider({373 return buildServerProvider({
446 provider: PROVIDER,374 provider: PROVIDER,
447 enabled: codexSettings.enabled,375 enabled: false,
448 checkedAt,376 checkedAt,
449 models,377 models: emptyModels,
378 skills: [],
450 probe: {379 probe: {
451 installed: true,380 installed: false,
452 version: parsedVersion,381 version: null,
453 status: "error",382 status: "warning",
454 auth: { status: "unknown" },383 auth: { status: "unknown" },
455 message: formatCodexCliUpgradeMessage(parsedVersion),384 message: "Codex is disabled in T3 Code settings.",
456 },385 },
457 });386 });
458 }387 }
459388
460 const skills =389 const probeResult = yield* probe({
461 (resolveSkills390 binaryPath: codexSettings.binaryPath,
462 ? yield* resolveSkills({391 homePath: codexSettings.homePath,
463 binaryPath: codexSettings.binaryPath,392 cwd: process.cwd(),
464 homePath: codexSettings.homePath,393 customModels: codexSettings.customModels,
465 cwd: process.cwd(),394 }).pipe(Effect.timeoutOption(Duration.millis(PROVIDER_PROBE_TIMEOUT_MS)), Effect.result);
466 }).pipe(Effect.orElseSucceed(() => undefined))
467 : undefined) ?? [];
468395
469 if (yield* hasCustomModelProvider) {396 if (Result.isFailure(probeResult)) {
397 const error = probeResult.failure;
398 const installed = !Schema.is(CodexErrors.CodexAppServerSpawnError)(error);
470 return buildServerProvider({399 return buildServerProvider({
471 provider: PROVIDER,400 provider: PROVIDER,
472 enabled: codexSettings.enabled,401 enabled: codexSettings.enabled,
473 checkedAt,402 checkedAt,
474 models,403 models: emptyModels,
475 skills,404 skills: [],
476 probe: {405 probe: {
477 installed: true,406 installed,
478 version: parsedVersion,407 version: null,
479 status: "ready",408 status: "error",
480 auth: { status: "unknown" },409 auth: { status: "unknown" },
481 message: "Using a custom Codex model provider; OpenAI login check skipped.",410 message: installed
411 ? `Codex app-server provider probe failed: ${error.message}.`
412 : "Codex CLI (`codex`) is not installed or not on PATH.",
482 },413 },
483 });414 });
484 }415 }
485416
486 const authProbe = yield* runCodexCommand(["login", "status"]).pipe(417 if (Option.isNone(probeResult.success)) {
487 Effect.timeoutOption(DEFAULT_TIMEOUT_MS),
488 Effect.result,
489 );
490 const account = resolveAccount
491 ? yield* resolveAccount({
492 binaryPath: codexSettings.binaryPath,
493 homePath: codexSettings.homePath,
494 })
495 : undefined;
496 const resolvedModels = adjustCodexModelsForAccount(models, account);
497
498 if (Result.isFailure(authProbe)) {
499 const error = authProbe.failure;
500 return buildServerProvider({418 return buildServerProvider({
501 provider: PROVIDER,419 provider: PROVIDER,
502 enabled: codexSettings.enabled,420 enabled: codexSettings.enabled,
503 checkedAt,421 checkedAt,
504 models: resolvedModels,422 models: emptyModels,
505 skills,423 skills: [],
506 probe: {424 probe: {
507 installed: true,425 installed: true,
508 version: parsedVersion,426 version: null,
509 status: "warning",427 status: "error",
510 auth: { status: "unknown" },428 auth: { status: "unknown" },
511 message: `Could not verify Codex authentication status: ${error.message}.`,429 message: "Timed out while checking Codex app-server provider status.",
512 },430 },
513 });431 });
514 }432 }
515433
516 if (Option.isNone(authProbe.success)) {434 const snapshot = probeResult.success.value;
517 return buildServerProvider({435 const accountStatus = accountProbeStatus(snapshot.account);
518 provider: PROVIDER,
519 enabled: codexSettings.enabled,
520 checkedAt,
521 models: resolvedModels,
522 skills,
523 probe: {
524 installed: true,
525 version: parsedVersion,
526 status: "warning",
527 auth: { status: "unknown" },
528 message: "Could not verify Codex authentication status. Timed out while running command.",
529 },
530 });
531 }
532436
533 const parsed = parseAuthStatusFromOutput(authProbe.success.value);
534 const authType = codexAuthSubType(account);
535 const authLabel = codexAuthSubLabel(account);
536 return buildServerProvider({437 return buildServerProvider({
537 provider: PROVIDER,438 provider: PROVIDER,
538 enabled: codexSettings.enabled,439 enabled: codexSettings.enabled,
539 checkedAt,440 checkedAt,
540 models: resolvedModels,441 models: snapshot.models,
541 skills,442 skills: snapshot.skills,
542 probe: {443 probe: {
543 installed: true,444 installed: true,
544 version: parsedVersion,445 version: snapshot.version ?? null,
545 status: parsed.status,446 status: accountStatus.status,
546 auth: {447 auth: accountStatus.auth,
547 ...parsed.auth,448 ...(accountStatus.message ? { message: accountStatus.message } : {}),
548 ...(authType ? { type: authType } : {}),
549 ...(authLabel ? { label: authLabel } : {}),
550 },
551 ...(parsed.message ? { message: parsed.message } : {}),
552 },449 },
553 });450 });
554});451});
555452
556const makePendingCodexProvider = (codexSettings: CodexSettings): ServerProvider => {
557 const checkedAt = new Date().toISOString();
558 const models = providerModelsFromSettings(
559 BUILT_IN_MODELS,
560 PROVIDER,
561 codexSettings.customModels,
562 DEFAULT_CODEX_MODEL_CAPABILITIES,
563 );
564
565 if (!codexSettings.enabled) {
566 return buildServerProvider({
567 provider: PROVIDER,
568 enabled: false,
569 checkedAt,
570 models,
571 probe: {
572 installed: false,
573 version: null,
574 status: "warning",
575 auth: { status: "unknown" },
576 message: "Codex is disabled in T3 Code settings.",
577 },
578 });
579 }
580
581 return buildServerProvider({
582 provider: PROVIDER,
583 enabled: true,
584 checkedAt,
585 models,
586 probe: {
587 installed: false,
588 version: null,
589 status: "warning",
590 auth: { status: "unknown" },
591 message: "Codex provider status has not been checked in this session yet.",
592 },
593 });
594};
595
596export const CodexProviderLive = Layer.effect(453export const CodexProviderLive = Layer.effect(
597 CodexProvider,454 CodexProvider,
598 Effect.gen(function* () {455 Effect.gen(function* () {
599 const serverSettings = yield* ServerSettingsService;456 const serverSettings = yield* ServerSettingsService;
600 const fileSystem = yield* FileSystem.FileSystem;
601 const path = yield* Path.Path;
602 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;457 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
603 const accountProbeCache = yield* Cache.make({458 const checkProvider = checkCodexProviderStatus().pipe(
604 capacity: 4,
605 timeToLive: Duration.minutes(5),
606 lookup: (key: string) => {
607 const [binaryPath, homePath, cwd] = JSON.parse(key) as [string, string | undefined, string];
608 return probeCodexCapabilities({
609 binaryPath,
610 cwd,
611 ...(homePath ? { homePath } : {}),
612 });
613 },
614 });
615
616 const getDiscovery = (input: {
617 readonly binaryPath: string;
618 readonly homePath?: string;
619 readonly cwd: string;
620 }) =>
621 Cache.get(accountProbeCache, JSON.stringify([input.binaryPath, input.homePath, input.cwd]));
622
623 const checkProvider = checkCodexProviderStatus(
624 (input) =>
625 getDiscovery({
626 ...input,
627 cwd: process.cwd(),
628 }).pipe(Effect.map((discovery) => discovery?.account)),
629 (input) => getDiscovery(input).pipe(Effect.map((discovery) => discovery?.skills)),
630 ).pipe(
631 Effect.provideService(ServerSettingsService, serverSettings),459 Effect.provideService(ServerSettingsService, serverSettings),
632 Effect.provideService(FileSystem.FileSystem, fileSystem),
633 Effect.provideService(Path.Path, path),
634 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),460 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
635 );461 );
636462
...@@ -645,6 +471,7 @@ export const CodexProviderLive = Layer.effect(...@@ -645,6 +471,7 @@ export const CodexProviderLive = Layer.effect(
645 haveSettingsChanged: (previous, next) => !Equal.equals(previous, next),471 haveSettingsChanged: (previous, next) => !Equal.equals(previous, next),
646 initialSnapshot: makePendingCodexProvider,472 initialSnapshot: makePendingCodexProvider,
647 checkProvider,473 checkProvider,
474 refreshInterval: Duration.minutes(5),
648 });475 });
649 }),476 }),
650);477);
apps/server/src/provider/Layers/CodexSessionRuntime.test.ts created+275
...@@ -0,0 +1,275 @@
1import assert from "node:assert/strict";
2
3import { Effect, Schema } from "effect";
4import { describe, it } from "vitest";
5import { ThreadId } from "@t3tools/contracts";
6import * as CodexErrors from "effect-codex-app-server/errors";
7import * as CodexRpc from "effect-codex-app-server/rpc";
8
9import {
10 CODEX_DEFAULT_MODE_DEVELOPER_INSTRUCTIONS,
11 CODEX_PLAN_MODE_DEVELOPER_INSTRUCTIONS,
12} from "../CodexDeveloperInstructions.ts";
13import {
14 buildTurnStartParams,
15 isRecoverableThreadResumeError,
16 openCodexThread,
17} from "./CodexSessionRuntime.ts";
18
19function makeThreadOpenResponse(
20 threadId: string,
21): CodexRpc.ClientRequestResponsesByMethod["thread/start"] {
22 return {
23 cwd: "/tmp/project",
24 model: "gpt-5.3-codex",
25 modelProvider: "openai",
26 approvalPolicy: "never",
27 approvalsReviewer: "user",
28 sandbox: { type: "danger-full-access" },
29 thread: {
30 id: threadId,
31 createdAt: "2026-04-18T00:00:00.000Z",
32 source: { session: "cli" },
33 turns: [],
34 status: {
35 state: "idle",
36 activeFlags: [],
37 },
38 },
39 } as unknown as CodexRpc.ClientRequestResponsesByMethod["thread/start"];
40}
41
42describe("buildTurnStartParams", () => {
43 it("includes plan collaboration mode when requested", () => {
44 const params = Effect.runSync(
45 buildTurnStartParams({
46 threadId: "provider-thread-1",
47 runtimeMode: "full-access",
48 prompt: "Make a plan",
49 model: "gpt-5.3-codex",
50 effort: "medium",
51 interactionMode: "plan",
52 }),
53 );
54
55 assert.deepStrictEqual(params, {
56 threadId: "provider-thread-1",
57 approvalPolicy: "never",
58 sandboxPolicy: {
59 type: "dangerFullAccess",
60 },
61 input: [
62 {
63 type: "text",
64 text: "Make a plan",
65 },
66 ],
67 model: "gpt-5.3-codex",
68 effort: "medium",
69 collaborationMode: {
70 mode: "plan",
71 settings: {
72 model: "gpt-5.3-codex",
73 reasoning_effort: "medium",
74 developer_instructions: CODEX_PLAN_MODE_DEVELOPER_INSTRUCTIONS,
75 },
76 },
77 });
78 });
79
80 it("includes default collaboration mode and image attachments", () => {
81 const params = Effect.runSync(
82 buildTurnStartParams({
83 threadId: "provider-thread-1",
84 runtimeMode: "auto-accept-edits",
85 prompt: "Implement it",
86 model: "gpt-5.3-codex",
87 interactionMode: "default",
88 attachments: [
89 {
90 type: "image",
91 url: "data:image/png;base64,abc",
92 },
93 ],
94 }),
95 );
96
97 assert.deepStrictEqual(params, {
98 threadId: "provider-thread-1",
99 approvalPolicy: "on-request",
100 sandboxPolicy: {
101 type: "workspaceWrite",
102 },
103 input: [
104 {
105 type: "text",
106 text: "Implement it",
107 },
108 {
109 type: "image",
110 url: "data:image/png;base64,abc",
111 },
112 ],
113 model: "gpt-5.3-codex",
114 collaborationMode: {
115 mode: "default",
116 settings: {
117 model: "gpt-5.3-codex",
118 reasoning_effort: "medium",
119 developer_instructions: CODEX_DEFAULT_MODE_DEVELOPER_INSTRUCTIONS,
120 },
121 },
122 });
123 });
124
125 it("omits collaboration mode when interaction mode is absent", () => {
126 const params = Effect.runSync(
127 buildTurnStartParams({
128 threadId: "provider-thread-1",
129 runtimeMode: "approval-required",
130 prompt: "Review",
131 }),
132 );
133
134 assert.deepStrictEqual(params, {
135 threadId: "provider-thread-1",
136 approvalPolicy: "untrusted",
137 sandboxPolicy: {
138 type: "readOnly",
139 },
140 input: [
141 {
142 type: "text",
143 text: "Review",
144 },
145 ],
146 });
147 });
148});
149
150describe("isRecoverableThreadResumeError", () => {
151 it("matches missing thread errors", () => {
152 assert.equal(
153 isRecoverableThreadResumeError(
154 new CodexErrors.CodexAppServerRequestError({
155 code: -32603,
156 errorMessage: "Thread does not exist",
157 }),
158 ),
159 true,
160 );
161 });
162
163 it("ignores non-recoverable resume errors", () => {
164 assert.equal(
165 isRecoverableThreadResumeError(
166 new CodexErrors.CodexAppServerRequestError({
167 code: -32603,
168 errorMessage: "Permission denied",
169 }),
170 ),
171 false,
172 );
173 });
174
175 it("ignores unrelated missing-resource errors that do not mention threads", () => {
176 assert.equal(
177 isRecoverableThreadResumeError(
178 new CodexErrors.CodexAppServerRequestError({
179 code: -32603,
180 errorMessage: "Config file not found",
181 }),
182 ),
183 false,
184 );
185 assert.equal(
186 isRecoverableThreadResumeError(
187 new CodexErrors.CodexAppServerRequestError({
188 code: -32603,
189 errorMessage: "Model does not exist",
190 }),
191 ),
192 false,
193 );
194 });
195});
196
197describe("openCodexThread", () => {
198 it("falls back to thread/start when resume fails recoverably", async () => {
199 const calls: Array<{ method: "thread/start" | "thread/resume"; payload: unknown }> = [];
200 const started = makeThreadOpenResponse("fresh-thread");
201 const client = {
202 request: <M extends "thread/start" | "thread/resume">(
203 method: M,
204 payload: CodexRpc.ClientRequestParamsByMethod[M],
205 ) => {
206 calls.push({ method, payload });
207 if (method === "thread/resume") {
208 return Effect.fail(
209 new CodexErrors.CodexAppServerRequestError({
210 code: -32603,
211 errorMessage: "thread not found",
212 }),
213 );
214 }
215 return Effect.succeed(started as CodexRpc.ClientRequestResponsesByMethod[M]);
216 },
217 };
218
219 const opened = await Effect.runPromise(
220 openCodexThread({
221 client,
222 threadId: ThreadId.make("thread-1"),
223 runtimeMode: "full-access",
224 cwd: "/tmp/project",
225 requestedModel: "gpt-5.3-codex",
226 serviceTier: undefined,
227 resumeThreadId: "stale-thread",
228 }),
229 );
230
231 assert.equal(opened.thread.id, "fresh-thread");
232 assert.deepStrictEqual(
233 calls.map((call) => call.method),
234 ["thread/resume", "thread/start"],
235 );
236 });
237
238 it("propagates non-recoverable resume failures", async () => {
239 const client = {
240 request: <M extends "thread/start" | "thread/resume">(
241 method: M,
242 _payload: CodexRpc.ClientRequestParamsByMethod[M],
243 ) => {
244 if (method === "thread/resume") {
245 return Effect.fail(
246 new CodexErrors.CodexAppServerRequestError({
247 code: -32603,
248 errorMessage: "timed out waiting for server",
249 }),
250 );
251 }
252 return Effect.succeed(
253 makeThreadOpenResponse("fresh-thread") as CodexRpc.ClientRequestResponsesByMethod[M],
254 );
255 },
256 };
257
258 await assert.rejects(
259 Effect.runPromise(
260 openCodexThread({
261 client,
262 threadId: ThreadId.make("thread-1"),
263 runtimeMode: "full-access",
264 cwd: "/tmp/project",
265 requestedModel: "gpt-5.3-codex",
266 serviceTier: undefined,
267 resumeThreadId: "stale-thread",
268 }),
269 ),
270 (error: unknown) =>
271 Schema.is(CodexErrors.CodexAppServerRequestError)(error) &&
272 error.errorMessage === "timed out waiting for server",
273 );
274 });
275});
apps/server/src/provider/Layers/CodexSessionRuntime.ts created+1325
...@@ -0,0 +1,1325 @@
1import { randomUUID } from "node:crypto";
2
3import {
4 ApprovalRequestId,
5 DEFAULT_MODEL_BY_PROVIDER,
6 EventId,
7 ProviderItemId,
8 type ProviderApprovalDecision,
9 type ProviderEvent,
10 type ProviderInteractionMode,
11 type ProviderRequestKind,
12 type ProviderSession,
13 type ProviderTurnStartResult,
14 type ProviderUserInputAnswers,
15 RuntimeMode,
16 ThreadId,
17 TurnId,
18} from "@t3tools/contracts";
19import { normalizeModelSlug } from "@t3tools/shared/model";
20import { Deferred, Effect, Exit, Layer, Queue, Ref, Scope, Schema, Stream } from "effect";
21import * as SchemaIssue from "effect/SchemaIssue";
22import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
23import * as CodexClient from "effect-codex-app-server/client";
24import * as CodexErrors from "effect-codex-app-server/errors";
25import * as CodexRpc from "effect-codex-app-server/rpc";
26import * as EffectCodexSchema from "effect-codex-app-server/schema";
27
28import { buildCodexInitializeParams } from "./CodexProvider.ts";
29import {
30 CODEX_DEFAULT_MODE_DEVELOPER_INSTRUCTIONS,
31 CODEX_PLAN_MODE_DEVELOPER_INSTRUCTIONS,
32} from "../CodexDeveloperInstructions.ts";
33
34const PROVIDER = "codex" as const;
35
36const ANSI_ESCAPE_CHAR = String.fromCharCode(27);
37const ANSI_ESCAPE_REGEX = new RegExp(`${ANSI_ESCAPE_CHAR}\\[[0-9;]*m`, "g");
38const CODEX_STDERR_LOG_REGEX =
39 /^\d{4}-\d{2}-\d{2}T\S+\s+(TRACE|DEBUG|INFO|WARN|ERROR)\s+\S+:\s+(.*)$/;
40const BENIGN_ERROR_LOG_SNIPPETS = [
41 "state db missing rollout path for thread",
42 "state db record_discrepancy: find_thread_path_by_id_str_in_subdir, falling_back",
43];
44const RECOVERABLE_THREAD_RESUME_ERROR_SNIPPETS = [
45 "not found",
46 "missing thread",
47 "no such thread",
48 "unknown thread",
49 "does not exist",
50];
51
52export const CodexResumeCursorSchema = Schema.Struct({
53 threadId: Schema.String,
54});
55const CodexUserInputAnswerObject = Schema.Struct({
56 answers: Schema.Array(Schema.String),
57});
58
59// TODO: Verify `packages/effect-codex-app-server/scripts/generate.ts` so the generated
60// `V2TurnStartParams` schema includes `collaborationMode` directly.
61const CodexTurnStartParamsWithCollaborationMode = EffectCodexSchema.V2TurnStartParams.pipe(
62 Schema.fieldsAssign({
63 collaborationMode: Schema.optionalKey(EffectCodexSchema.V2TurnStartParams__CollaborationMode),
64 }),
65);
66
67export type CodexTurnStartParamsWithCollaborationMode =
68 typeof CodexTurnStartParamsWithCollaborationMode.Type;
69const formatSchemaIssue = SchemaIssue.makeFormatterDefault();
70
71export type CodexResumeCursor = typeof CodexResumeCursorSchema.Type;
72type CodexThreadItem =
73 | EffectCodexSchema.V2ThreadReadResponse["thread"]["turns"][number]["items"][number]
74 | EffectCodexSchema.V2ThreadRollbackResponse["thread"]["turns"][number]["items"][number];
75
76export interface CodexSessionRuntimeOptions {
77 readonly threadId: ThreadId;
78 readonly binaryPath: string;
79 readonly homePath?: string;
80 readonly cwd: string;
81 readonly runtimeMode: RuntimeMode;
82 readonly model?: string;
83 readonly serviceTier?: EffectCodexSchema.V2ThreadStartParams__ServiceTier | undefined;
84 readonly resumeCursor?: CodexResumeCursor;
85}
86
87export interface CodexSessionRuntimeSendTurnInput {
88 readonly input?: string;
89 readonly attachments?: ReadonlyArray<{ readonly type: "image"; readonly url: string }>;
90 readonly model?: string;
91 readonly serviceTier?: EffectCodexSchema.V2TurnStartParams__ServiceTier | undefined;
92 readonly effort?: EffectCodexSchema.V2TurnStartParams__ReasoningEffort | undefined;
93 readonly interactionMode?: ProviderInteractionMode;
94}
95
96export interface CodexThreadTurnSnapshot {
97 readonly id: TurnId;
98 readonly items: ReadonlyArray<CodexThreadItem>;
99}
100
101export interface CodexThreadSnapshot {
102 readonly threadId: string;
103 readonly turns: ReadonlyArray<CodexThreadTurnSnapshot>;
104}
105
106export interface CodexSessionRuntimeShape {
107 readonly start: () => Effect.Effect<ProviderSession, CodexSessionRuntimeError>;
108 readonly getSession: Effect.Effect<ProviderSession>;
109 readonly sendTurn: (
110 input: CodexSessionRuntimeSendTurnInput,
111 ) => Effect.Effect<ProviderTurnStartResult, CodexSessionRuntimeError>;
112 readonly interruptTurn: (turnId?: TurnId) => Effect.Effect<void, CodexSessionRuntimeError>;
113 readonly readThread: Effect.Effect<CodexThreadSnapshot, CodexSessionRuntimeError>;
114 readonly rollbackThread: (
115 numTurns: number,
116 ) => Effect.Effect<CodexThreadSnapshot, CodexSessionRuntimeError>;
117 readonly respondToRequest: (
118 requestId: ApprovalRequestId,
119 decision: ProviderApprovalDecision,
120 ) => Effect.Effect<void, CodexSessionRuntimeError>;
121 readonly respondToUserInput: (
122 requestId: ApprovalRequestId,
123 answers: ProviderUserInputAnswers,
124 ) => Effect.Effect<void, CodexSessionRuntimeError>;
125 readonly events: Stream.Stream<ProviderEvent, never>;
126 readonly close: Effect.Effect<void>;
127}
128
129export type CodexSessionRuntimeError =
130 | CodexErrors.CodexAppServerError
131 | CodexSessionRuntimePendingApprovalNotFoundError
132 | CodexSessionRuntimePendingUserInputNotFoundError
133 | CodexSessionRuntimeInvalidUserInputAnswersError
134 | CodexSessionRuntimeThreadIdMissingError;
135
136export class CodexSessionRuntimePendingApprovalNotFoundError extends Schema.TaggedErrorClass<CodexSessionRuntimePendingApprovalNotFoundError>()(
137 "CodexSessionRuntimePendingApprovalNotFoundError",
138 {
139 requestId: Schema.String,
140 },
141) {
142 override get message(): string {
143 return `Unknown pending Codex approval request: ${this.requestId}`;
144 }
145}
146
147export class CodexSessionRuntimePendingUserInputNotFoundError extends Schema.TaggedErrorClass<CodexSessionRuntimePendingUserInputNotFoundError>()(
148 "CodexSessionRuntimePendingUserInputNotFoundError",
149 {
150 requestId: Schema.String,
151 },
152) {
153 override get message(): string {
154 return `Unknown pending Codex user input request: ${this.requestId}`;
155 }
156}
157
158export class CodexSessionRuntimeInvalidUserInputAnswersError extends Schema.TaggedErrorClass<CodexSessionRuntimeInvalidUserInputAnswersError>()(
159 "CodexSessionRuntimeInvalidUserInputAnswersError",
160 {
161 questionId: Schema.String,
162 },
163) {
164 override get message(): string {
165 return `Invalid Codex user input answers for question '${this.questionId}'`;
166 }
167}
168
169export class CodexSessionRuntimeThreadIdMissingError extends Schema.TaggedErrorClass<CodexSessionRuntimeThreadIdMissingError>()(
170 "CodexSessionRuntimeThreadIdMissingError",
171 {
172 threadId: Schema.String,
173 },
174) {
175 override get message(): string {
176 return `Codex session is missing a provider thread id for ${this.threadId}`;
177 }
178}
179
180interface PendingApproval {
181 readonly requestId: ApprovalRequestId;
182 readonly jsonRpcId: string;
183 readonly requestKind: ProviderRequestKind;
184 readonly turnId: TurnId | undefined;
185 readonly itemId: ProviderItemId | undefined;
186 readonly decision: Deferred.Deferred<ProviderApprovalDecision>;
187}
188
189interface ApprovalCorrelation {
190 readonly requestId: ApprovalRequestId;
191 readonly requestKind: ProviderRequestKind;
192 readonly turnId: TurnId | undefined;
193 readonly itemId: ProviderItemId | undefined;
194}
195
196interface PendingUserInput {
197 readonly requestId: ApprovalRequestId;
198 readonly turnId: TurnId | undefined;
199 readonly itemId: ProviderItemId | undefined;
200 readonly answers: Deferred.Deferred<ProviderUserInputAnswers>;
201}
202
203type CodexServerNotification = {
204 readonly [M in CodexRpc.ServerNotificationMethod]: {
205 readonly method: M;
206 readonly params: CodexRpc.ServerNotificationParamsByMethod[M];
207 };
208}[CodexRpc.ServerNotificationMethod];
209
210function makeCodexServerNotification<M extends CodexRpc.ServerNotificationMethod>(
211 method: M,
212 params: CodexRpc.ServerNotificationParamsByMethod[M],
213): CodexServerNotification {
214 return { method, params } as CodexServerNotification;
215}
216
217function normalizeCodexModelSlug(
218 model: string | undefined | null,
219 preferredId?: string,
220): string | undefined {
221 const normalized = normalizeModelSlug(model);
222 if (!normalized) {
223 return undefined;
224 }
225 if (preferredId?.endsWith("-codex") && preferredId !== normalized) {
226 return preferredId;
227 }
228 return normalized;
229}
230
231function readResumeCursorThreadId(
232 resumeCursor: ProviderSession["resumeCursor"],
233): string | undefined {
234 return Schema.is(CodexResumeCursorSchema)(resumeCursor) ? resumeCursor.threadId : undefined;
235}
236
237function runtimeModeToThreadConfig(input: RuntimeMode): {
238 readonly approvalPolicy: EffectCodexSchema.V2ThreadStartParams__AskForApproval;
239 readonly sandbox: EffectCodexSchema.V2ThreadStartParams__SandboxMode;
240} {
241 switch (input) {
242 case "approval-required":
243 return {
244 approvalPolicy: "untrusted",
245 sandbox: "read-only",
246 };
247 case "auto-accept-edits":
248 return {
249 approvalPolicy: "on-request",
250 sandbox: "workspace-write",
251 };
252 case "full-access":
253 default:
254 return {
255 approvalPolicy: "never",
256 sandbox: "danger-full-access",
257 };
258 }
259}
260
261function buildThreadStartParams(input: {
262 readonly cwd: string;
263 readonly runtimeMode: RuntimeMode;
264 readonly model: string | undefined;
265 readonly serviceTier: EffectCodexSchema.V2ThreadStartParams__ServiceTier | undefined;
266}): EffectCodexSchema.V2ThreadStartParams {
267 const config = runtimeModeToThreadConfig(input.runtimeMode);
268 return {
269 cwd: input.cwd,
270 approvalPolicy: config.approvalPolicy,
271 sandbox: config.sandbox,
272 ...(input.model ? { model: input.model } : {}),
273 ...(input.serviceTier ? { serviceTier: input.serviceTier } : {}),
274 };
275}
276
277function runtimeModeToTurnSandboxPolicy(
278 input: RuntimeMode,
279): EffectCodexSchema.V2TurnStartParams__SandboxPolicy {
280 switch (input) {
281 case "approval-required":
282 return {
283 type: "readOnly",
284 };
285 case "auto-accept-edits":
286 return {
287 type: "workspaceWrite",
288 };
289 case "full-access":
290 default:
291 return {
292 type: "dangerFullAccess",
293 };
294 }
295}
296
297function buildCodexCollaborationMode(input: {
298 readonly interactionMode?: ProviderInteractionMode;
299 readonly model?: string;
300 readonly effort?: EffectCodexSchema.V2TurnStartParams__ReasoningEffort;
301}): EffectCodexSchema.V2TurnStartParams__CollaborationMode | undefined {
302 if (input.interactionMode === undefined) {
303 return undefined;
304 }
305 const model = normalizeCodexModelSlug(input.model) ?? DEFAULT_MODEL_BY_PROVIDER.codex;
306 return {
307 mode: input.interactionMode,
308 settings: {
309 model,
310 reasoning_effort: input.effort ?? "medium",
311 developer_instructions:
312 input.interactionMode === "plan"
313 ? CODEX_PLAN_MODE_DEVELOPER_INSTRUCTIONS
314 : CODEX_DEFAULT_MODE_DEVELOPER_INSTRUCTIONS,
315 },
316 };
317}
318
319export function buildTurnStartParams(input: {
320 readonly threadId: string;
321 readonly runtimeMode: RuntimeMode;
322 readonly prompt?: string;
323 readonly attachments?: ReadonlyArray<{ readonly type: "image"; readonly url: string }>;
324 readonly model?: string;
325 readonly serviceTier?: EffectCodexSchema.V2TurnStartParams__ServiceTier;
326 readonly effort?: EffectCodexSchema.V2TurnStartParams__ReasoningEffort;
327 readonly interactionMode?: ProviderInteractionMode;
328}): Effect.Effect<
329 CodexTurnStartParamsWithCollaborationMode,
330 CodexErrors.CodexAppServerProtocolParseError
331> {
332 const turnInput: Array<EffectCodexSchema.V2TurnStartParams__UserInput> = [];
333 if (input.prompt) {
334 turnInput.push({
335 type: "text",
336 text: input.prompt,
337 });
338 }
339 for (const attachment of input.attachments ?? []) {
340 turnInput.push(attachment);
341 }
342
343 const config = runtimeModeToThreadConfig(input.runtimeMode);
344 const collaborationMode = buildCodexCollaborationMode({
345 ...(input.interactionMode ? { interactionMode: input.interactionMode } : {}),
346 ...(input.model ? { model: input.model } : {}),
347 ...(input.effort ? { effort: input.effort } : {}),
348 });
349
350 return Schema.decodeUnknownEffect(CodexTurnStartParamsWithCollaborationMode)({
351 threadId: input.threadId,
352 input: turnInput,
353 approvalPolicy: config.approvalPolicy,
354 sandboxPolicy: runtimeModeToTurnSandboxPolicy(input.runtimeMode),
355 ...(input.model ? { model: input.model } : {}),
356 ...(input.serviceTier ? { serviceTier: input.serviceTier } : {}),
357 ...(input.effort ? { effort: input.effort } : {}),
358 ...(collaborationMode ? { collaborationMode } : {}),
359 }).pipe(
360 Effect.mapError((error) => toProtocolParseError("Invalid turn/start request payload", error)),
361 );
362}
363
364function classifyCodexStderrLine(rawLine: string): { readonly message: string } | null {
365 const line = rawLine.replaceAll(ANSI_ESCAPE_REGEX, "").trim();
366 if (!line) {
367 return null;
368 }
369
370 const match = line.match(CODEX_STDERR_LOG_REGEX);
371 if (match) {
372 const level = match[1];
373 if (level && level !== "ERROR") {
374 return null;
375 }
376 if (BENIGN_ERROR_LOG_SNIPPETS.some((snippet) => line.includes(snippet))) {
377 return null;
378 }
379 }
380
381 return { message: line };
382}
383
384export function isRecoverableThreadResumeError(error: unknown): boolean {
385 const message = (error instanceof Error ? error.message : String(error)).toLowerCase();
386 if (!message.includes("thread")) {
387 return false;
388 }
389 return RECOVERABLE_THREAD_RESUME_ERROR_SNIPPETS.some((snippet) => message.includes(snippet));
390}
391
392type CodexThreadOpenResponse =
393 | CodexRpc.ClientRequestResponsesByMethod["thread/start"]
394 | CodexRpc.ClientRequestResponsesByMethod["thread/resume"];
395
396type CodexThreadOpenMethod = "thread/start" | "thread/resume";
397
398interface CodexThreadOpenClient {
399 readonly request: <M extends CodexThreadOpenMethod>(
400 method: M,
401 payload: CodexRpc.ClientRequestParamsByMethod[M],
402 ) => Effect.Effect<CodexRpc.ClientRequestResponsesByMethod[M], CodexErrors.CodexAppServerError>;
403}
404
405export const openCodexThread = (input: {
406 readonly client: CodexThreadOpenClient;
407 readonly threadId: ThreadId;
408 readonly runtimeMode: RuntimeMode;
409 readonly cwd: string;
410 readonly requestedModel: string | undefined;
411 readonly serviceTier: EffectCodexSchema.V2ThreadStartParams__ServiceTier | undefined;
412 readonly resumeThreadId: string | undefined;
413}): Effect.Effect<CodexThreadOpenResponse, CodexErrors.CodexAppServerError> => {
414 const resumeThreadId = input.resumeThreadId;
415 const startParams = buildThreadStartParams({
416 cwd: input.cwd,
417 runtimeMode: input.runtimeMode,
418 model: input.requestedModel,
419 serviceTier: input.serviceTier,
420 });
421
422 if (resumeThreadId === undefined) {
423 return input.client.request("thread/start", startParams);
424 }
425
426 return input.client
427 .request("thread/resume", {
428 threadId: resumeThreadId,
429 ...startParams,
430 })
431 .pipe(
432 Effect.catchIf(isRecoverableThreadResumeError, (error) =>
433 Effect.logWarning("codex app-server thread resume fell back to fresh start", {
434 threadId: input.threadId,
435 requestedRuntimeMode: input.runtimeMode,
436 resumeThreadId,
437 recoverable: true,
438 cause: error.message,
439 }).pipe(Effect.andThen(input.client.request("thread/start", startParams))),
440 ),
441 );
442};
443
444function readNotificationThreadId(notification: CodexServerNotification): string | undefined {
445 switch (notification.method) {
446 case "thread/started":
447 return notification.params.thread.id;
448 case "error":
449 case "thread/status/changed":
450 case "thread/archived":
451 case "thread/unarchived":
452 case "thread/closed":
453 case "thread/name/updated":
454 case "thread/tokenUsage/updated":
455 case "turn/started":
456 case "hook/started":
457 case "turn/completed":
458 case "hook/completed":
459 case "turn/diff/updated":
460 case "turn/plan/updated":
461 case "item/started":
462 case "item/autoApprovalReview/started":
463 case "item/autoApprovalReview/completed":
464 case "item/completed":
465 case "rawResponseItem/completed":
466 case "item/agentMessage/delta":
467 case "item/plan/delta":
468 case "item/commandExecution/outputDelta":
469 case "item/commandExecution/terminalInteraction":
470 case "item/fileChange/outputDelta":
471 case "serverRequest/resolved":
472 case "item/mcpToolCall/progress":
473 case "item/reasoning/summaryTextDelta":
474 case "item/reasoning/summaryPartAdded":
475 case "item/reasoning/textDelta":
476 case "thread/compacted":
477 case "thread/realtime/started":
478 case "thread/realtime/itemAdded":
479 case "thread/realtime/transcriptUpdated":
480 case "thread/realtime/outputAudio/delta":
481 case "thread/realtime/sdp":
482 case "thread/realtime/error":
483 case "thread/realtime/closed":
484 return notification.params.threadId;
485 default:
486 return undefined;
487 }
488}
489
490function readRouteFields(notification: CodexServerNotification): {
491 readonly turnId: TurnId | undefined;
492 readonly itemId: ProviderItemId | undefined;
493} {
494 switch (notification.method) {
495 case "thread/started":
496 return {
497 turnId: undefined,
498 itemId: undefined,
499 };
500 case "turn/started":
501 case "turn/completed":
502 return {
503 turnId: TurnId.make(notification.params.turn.id),
504 itemId: undefined,
505 };
506 case "error":
507 return {
508 turnId: TurnId.make(notification.params.turnId),
509 itemId: undefined,
510 };
511 case "turn/diff/updated":
512 case "turn/plan/updated":
513 return {
514 turnId: TurnId.make(notification.params.turnId),
515 itemId: undefined,
516 };
517 case "serverRequest/resolved":
518 return {
519 turnId: undefined,
520 itemId: undefined,
521 };
522 case "item/started":
523 case "item/completed":
524 return {
525 turnId: TurnId.make(notification.params.turnId),
526 itemId: ProviderItemId.make(notification.params.item.id),
527 };
528 case "item/agentMessage/delta":
529 case "item/plan/delta":
530 case "item/commandExecution/outputDelta":
531 case "item/commandExecution/terminalInteraction":
532 case "item/fileChange/outputDelta":
533 case "item/reasoning/summaryTextDelta":
534 case "item/reasoning/summaryPartAdded":
535 case "item/reasoning/textDelta":
536 return {
537 turnId: TurnId.make(notification.params.turnId),
538 itemId: ProviderItemId.make(notification.params.itemId),
539 };
540 default:
541 return {
542 turnId: undefined,
543 itemId: undefined,
544 };
545 }
546}
547
548function rememberCollabReceiverTurns(
549 collabReceiverTurns: Map<string, TurnId>,
550 notification: CodexServerNotification,
551 parentTurnId: TurnId | undefined,
552): void {
553 if (!parentTurnId) {
554 return;
555 }
556
557 if (notification.method !== "item/started" && notification.method !== "item/completed") {
558 return;
559 }
560
561 if (notification.params.item.type !== "collabAgentToolCall") {
562 return;
563 }
564
565 for (const receiverThreadId of notification.params.item.receiverThreadIds) {
566 collabReceiverTurns.set(receiverThreadId, parentTurnId);
567 }
568}
569
570function shouldSuppressChildConversationNotification(
571 method: CodexRpc.ServerNotificationMethod,
572): boolean {
573 return (
574 method === "thread/started" ||
575 method === "thread/status/changed" ||
576 method === "thread/archived" ||
577 method === "thread/unarchived" ||
578 method === "thread/closed" ||
579 method === "thread/compacted" ||
580 method === "thread/name/updated" ||
581 method === "thread/tokenUsage/updated" ||
582 method === "turn/started" ||
583 method === "turn/completed" ||
584 method === "turn/plan/updated" ||
585 method === "item/plan/delta"
586 );
587}
588
589function toCodexUserInputAnswer(
590 questionId: string,
591 value: ProviderUserInputAnswers[string],
592): Effect.Effect<
593 EffectCodexSchema.ToolRequestUserInputResponse__ToolRequestUserInputAnswer,
594 CodexSessionRuntimeInvalidUserInputAnswersError
595> {
596 if (typeof value === "string") {
597 return Effect.succeed({ answers: [value] });
598 }
599 if (Array.isArray(value)) {
600 const answers = value.filter((entry): entry is string => typeof entry === "string");
601 return Effect.succeed({ answers });
602 }
603 if (Schema.is(CodexUserInputAnswerObject)(value)) {
604 return Effect.succeed({ answers: value.answers });
605 }
606 return Effect.fail(new CodexSessionRuntimeInvalidUserInputAnswersError({ questionId }));
607}
608
609function toCodexUserInputAnswers(
610 answers: ProviderUserInputAnswers,
611): Effect.Effect<
612 EffectCodexSchema.ToolRequestUserInputResponse["answers"],
613 CodexSessionRuntimeInvalidUserInputAnswersError
614> {
615 return Effect.forEach(
616 Object.entries(answers),
617 ([questionId, value]) =>
618 toCodexUserInputAnswer(questionId, value).pipe(
619 Effect.map((answer) => [questionId, answer] as const),
620 ),
621 { concurrency: 1 },
622 ).pipe(Effect.map((entries) => Object.fromEntries(entries)));
623}
624
625function toProtocolParseError(
626 detail: string,
627 cause: Schema.SchemaError,
628): CodexErrors.CodexAppServerProtocolParseError {
629 return new CodexErrors.CodexAppServerProtocolParseError({
630 detail: `${detail}: ${formatSchemaIssue(cause.issue)}`,
631 cause,
632 });
633}
634
635function currentProviderThreadId(session: ProviderSession): string | undefined {
636 return readResumeCursorThreadId(session.resumeCursor);
637}
638
639function updateSession(
640 sessionRef: Ref.Ref<ProviderSession>,
641 updates: Partial<ProviderSession>,
642): Effect.Effect<void> {
643 return Ref.update(sessionRef, (session) => ({
644 ...session,
645 ...updates,
646 updatedAt: new Date().toISOString(),
647 }));
648}
649
650function parseThreadSnapshot(
651 response: EffectCodexSchema.V2ThreadReadResponse | EffectCodexSchema.V2ThreadRollbackResponse,
652): CodexThreadSnapshot {
653 return {
654 threadId: response.thread.id,
655 turns: response.thread.turns.map((turn) => ({
656 id: TurnId.make(turn.id),
657 items: turn.items,
658 })),
659 };
660}
661
662export const makeCodexSessionRuntime = (
663 options: CodexSessionRuntimeOptions,
664): Effect.Effect<
665 CodexSessionRuntimeShape,
666 CodexErrors.CodexAppServerError,
667 ChildProcessSpawner.ChildProcessSpawner | Scope.Scope
668> =>
669 Effect.gen(function* () {
670 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
671 const runtimeScope = yield* Scope.Scope;
672 const events = yield* Queue.unbounded<ProviderEvent>();
673 const pendingApprovalsRef = yield* Ref.make(new Map<ApprovalRequestId, PendingApproval>());
674 const approvalCorrelationsRef = yield* Ref.make(new Map<string, ApprovalCorrelation>());
675 const pendingUserInputsRef = yield* Ref.make(new Map<ApprovalRequestId, PendingUserInput>());
676 const collabReceiverTurnsRef = yield* Ref.make(new Map<string, TurnId>());
677 const closedRef = yield* Ref.make(false);
678
679 const child = yield* spawner
680 .spawn(
681 ChildProcess.make(options.binaryPath, ["app-server"], {
682 cwd: options.cwd,
683 ...(options.homePath ? { env: { ...process.env, CODEX_HOME: options.homePath } } : {}),
684 shell: process.platform === "win32",
685 }),
686 )
687 .pipe(
688 Effect.provideService(Scope.Scope, runtimeScope),
689 Effect.mapError(
690 (cause) =>
691 new CodexErrors.CodexAppServerSpawnError({
692 command: `${options.binaryPath} app-server`,
693 cause,
694 }),
695 ),
696 );
697
698 const clientContext = yield* CodexClient.layerChildProcess(child).pipe(
699 Layer.build,
700 Effect.provideService(Scope.Scope, runtimeScope),
701 );
702 const client = yield* Effect.service(CodexClient.CodexAppServerClient).pipe(
703 Effect.provide(clientContext),
704 );
705 const serverNotifications = yield* Queue.unbounded<CodexServerNotification>();
706
707 const initialSession = {
708 provider: PROVIDER,
709 status: "connecting",
710 runtimeMode: options.runtimeMode,
711 cwd: options.cwd,
712 ...(options.model ? { model: options.model } : {}),
713 threadId: options.threadId,
714 ...(options.resumeCursor !== undefined ? { resumeCursor: options.resumeCursor } : {}),
715 createdAt: new Date().toISOString(),
716 updatedAt: new Date().toISOString(),
717 } satisfies ProviderSession;
718 const sessionRef = yield* Ref.make<ProviderSession>(initialSession);
719 const offerEvent = (event: ProviderEvent) => Queue.offer(events, event).pipe(Effect.asVoid);
720
721 const emitEvent = (event: Omit<ProviderEvent, "id" | "provider" | "createdAt">) =>
722 offerEvent({
723 id: EventId.make(randomUUID()),
724 provider: PROVIDER,
725 createdAt: new Date().toISOString(),
726 ...event,
727 });
728
729 const emitSessionEvent = (method: string, message: string) =>
730 emitEvent({
731 kind: "session",
732 threadId: options.threadId,
733 method,
734 message,
735 });
736
737 const settlePendingApprovals = (decision: ProviderApprovalDecision) =>
738 Ref.get(pendingApprovalsRef).pipe(
739 Effect.flatMap((pendingApprovals) =>
740 Effect.forEach(
741 Array.from(pendingApprovals.values()),
742 (pendingApproval) =>
743 Deferred.succeed(pendingApproval.decision, decision).pipe(Effect.ignore),
744 { discard: true },
745 ),
746 ),
747 );
748
749 const settlePendingUserInputs = (answers: ProviderUserInputAnswers) =>
750 Ref.get(pendingUserInputsRef).pipe(
751 Effect.flatMap((pendingUserInputs) =>
752 Effect.forEach(
753 Array.from(pendingUserInputs.values()),
754 (pendingUserInput) =>
755 Deferred.succeed(pendingUserInput.answers, answers).pipe(Effect.ignore),
756 { discard: true },
757 ),
758 ),
759 );
760
761 const handleRawNotification = (notification: CodexServerNotification) =>
762 Effect.gen(function* () {
763 const payload = notification.params;
764 const route = readRouteFields(notification);
765 const collabReceiverTurns = yield* Ref.get(collabReceiverTurnsRef);
766 const childParentTurnId = (() => {
767 const providerConversationId = readNotificationThreadId(notification);
768 return providerConversationId
769 ? collabReceiverTurns.get(providerConversationId)
770 : undefined;
771 })();
772
773 rememberCollabReceiverTurns(collabReceiverTurns, notification, route.turnId);
774 if (childParentTurnId && shouldSuppressChildConversationNotification(notification.method)) {
775 yield* Ref.set(collabReceiverTurnsRef, collabReceiverTurns);
776 return;
777 }
778
779 let requestId: ApprovalRequestId | undefined;
780 let requestKind: ProviderRequestKind | undefined;
781 let turnId = childParentTurnId ?? route.turnId;
782 let itemId = route.itemId;
783
784 if (notification.method === "serverRequest/resolved") {
785 const rawRequestId =
786 typeof notification.params.requestId === "string"
787 ? notification.params.requestId
788 : String(notification.params.requestId);
789 const correlation = rawRequestId
790 ? (yield* Ref.get(approvalCorrelationsRef)).get(rawRequestId)
791 : undefined;
792 if (correlation) {
793 requestId = correlation.requestId;
794 requestKind = correlation.requestKind;
795 turnId = correlation.turnId ?? turnId;
796 itemId = correlation.itemId ?? itemId;
797 yield* Ref.update(approvalCorrelationsRef, (current) => {
798 const next = new Map(current);
799 next.delete(rawRequestId);
800 return next;
801 });
802 }
803 }
804
805 yield* Ref.set(collabReceiverTurnsRef, collabReceiverTurns);
806 yield* emitEvent({
807 kind: "notification",
808 threadId: options.threadId,
809 method: notification.method,
810 ...(turnId ? { turnId } : {}),
811 ...(itemId ? { itemId } : {}),
812 ...(requestId ? { requestId } : {}),
813 ...(requestKind ? { requestKind } : {}),
814 ...(notification.method === "item/agentMessage/delta"
815 ? { textDelta: notification.params.delta }
816 : {}),
817 ...(payload !== undefined ? { payload } : {}),
818 });
819 });
820
821 const currentSessionProviderThreadId = Effect.map(Ref.get(sessionRef), currentProviderThreadId);
822
823 yield* client.handleServerNotification("thread/started", (payload) =>
824 currentSessionProviderThreadId.pipe(
825 Effect.flatMap((providerThreadId) => {
826 if (providerThreadId && payload.thread.id !== providerThreadId) {
827 return Effect.void;
828 }
829 return updateSession(sessionRef, {
830 resumeCursor: { threadId: payload.thread.id },
831 });
832 }),
833 ),
834 );
835
836 yield* client.handleServerNotification("turn/started", (payload) =>
837 currentSessionProviderThreadId.pipe(
838 Effect.flatMap((providerThreadId) => {
839 if (providerThreadId && payload.threadId !== providerThreadId) {
840 return Effect.void;
841 }
842 return updateSession(sessionRef, {
843 status: "running",
844 activeTurnId: TurnId.make(payload.turn.id),
845 });
846 }),
847 ),
848 );
849
850 yield* client.handleServerNotification("turn/completed", (payload) =>
851 currentSessionProviderThreadId.pipe(
852 Effect.flatMap((providerThreadId) => {
853 if (providerThreadId && payload.threadId !== providerThreadId) {
854 return Effect.void;
855 }
856 const lastError =
857 payload.turn.status === "failed" && "error" in payload.turn && payload.turn.error
858 ? payload.turn.error.message
859 : undefined;
860 return updateSession(sessionRef, {
861 status: payload.turn.status === "failed" ? "error" : "ready",
862 activeTurnId: undefined,
863 ...(lastError ? { lastError } : {}),
864 });
865 }),
866 ),
867 );
868
869 yield* client.handleServerNotification("error", (payload) =>
870 currentSessionProviderThreadId.pipe(
871 Effect.flatMap((providerThreadId) => {
872 const payloadThreadId = payload.threadId;
873 if (providerThreadId && payloadThreadId && payloadThreadId !== providerThreadId) {
874 return Effect.void;
875 }
876 const errorMessage = payload.error.message;
877 const willRetry = payload.willRetry;
878 return updateSession(sessionRef, {
879 status: willRetry ? "running" : "error",
880 ...(errorMessage ? { lastError: errorMessage } : {}),
881 });
882 }),
883 ),
884 );
885
886 yield* client.handleServerRequest("item/commandExecution/requestApproval", (payload) =>
887 Effect.gen(function* () {
888 const requestId = ApprovalRequestId.make(randomUUID());
889 const turnId = TurnId.make(payload.turnId);
890 const itemId = ProviderItemId.make(payload.itemId);
891 const decision = yield* Deferred.make<ProviderApprovalDecision>();
892
893 yield* Ref.update(pendingApprovalsRef, (current) => {
894 const next = new Map(current);
895 next.set(requestId, {
896 requestId,
897 jsonRpcId: payload.approvalId ?? payload.itemId,
898 requestKind: "command",
899 turnId,
900 itemId,
901 decision,
902 });
903 return next;
904 });
905 yield* Ref.update(approvalCorrelationsRef, (current) => {
906 const next = new Map(current);
907 next.set(payload.approvalId ?? payload.itemId, {
908 requestId,
909 requestKind: "command",
910 turnId,
911 itemId,
912 });
913 return next;
914 });
915
916 yield* emitEvent({
917 kind: "request",
918 threadId: options.threadId,
919 method: "item/commandExecution/requestApproval",
920 requestId,
921 requestKind: "command",
922 ...(turnId ? { turnId } : {}),
923 ...(itemId ? { itemId } : {}),
924 payload,
925 });
926
927 const resolved = yield* Deferred.await(decision).pipe(
928 Effect.ensuring(
929 Ref.update(pendingApprovalsRef, (current) => {
930 const next = new Map(current);
931 next.delete(requestId);
932 return next;
933 }),
934 ),
935 );
936 return {
937 decision: resolved,
938 } satisfies EffectCodexSchema.CommandExecutionRequestApprovalResponse;
939 }),
940 );
941
942 yield* client.handleServerRequest("item/fileChange/requestApproval", (payload) =>
943 Effect.gen(function* () {
944 const requestId = ApprovalRequestId.make(randomUUID());
945 const turnId = TurnId.make(payload.turnId);
946 const itemId = ProviderItemId.make(payload.itemId);
947 const decision = yield* Deferred.make<ProviderApprovalDecision>();
948
949 yield* Ref.update(pendingApprovalsRef, (current) => {
950 const next = new Map(current);
951 next.set(requestId, {
952 requestId,
953 jsonRpcId: payload.itemId,
954 requestKind: "file-change",
955 turnId,
956 itemId,
957 decision,
958 });
959 return next;
960 });
961 yield* Ref.update(approvalCorrelationsRef, (current) => {
962 const next = new Map(current);
963 next.set(payload.itemId, {
964 requestId,
965 requestKind: "file-change",
966 turnId,
967 itemId,
968 });
969 return next;
970 });
971
972 yield* emitEvent({
973 kind: "request",
974 threadId: options.threadId,
975 method: "item/fileChange/requestApproval",
976 requestId,
977 requestKind: "file-change",
978 ...(turnId ? { turnId } : {}),
979 ...(itemId ? { itemId } : {}),
980 payload,
981 });
982
983 const resolved = yield* Deferred.await(decision).pipe(
984 Effect.ensuring(
985 Ref.update(pendingApprovalsRef, (current) => {
986 const next = new Map(current);
987 next.delete(requestId);
988 return next;
989 }),
990 ),
991 );
992 return {
993 decision: resolved,
994 } satisfies EffectCodexSchema.FileChangeRequestApprovalResponse;
995 }),
996 );
997
998 yield* client.handleServerRequest("item/tool/requestUserInput", (payload) =>
999 Effect.gen(function* () {
1000 const requestId = ApprovalRequestId.make(randomUUID());
1001 const turnId = TurnId.make(payload.turnId);
1002 const itemId = ProviderItemId.make(payload.itemId);
1003 const answers = yield* Deferred.make<ProviderUserInputAnswers>();
1004
1005 yield* Ref.update(pendingUserInputsRef, (current) => {
1006 const next = new Map(current);
1007 next.set(requestId, {
1008 requestId,
1009 turnId,
1010 itemId,
1011 answers,
1012 });
1013 return next;
1014 });
1015
1016 yield* emitEvent({
1017 kind: "request",
1018 threadId: options.threadId,
1019 method: "item/tool/requestUserInput",
1020 requestId,
1021 ...(turnId ? { turnId } : {}),
1022 ...(itemId ? { itemId } : {}),
1023 payload,
1024 });
1025
1026 const resolvedAnswers = yield* Deferred.await(answers).pipe(
1027 Effect.ensuring(
1028 Ref.update(pendingUserInputsRef, (current) => {
1029 const next = new Map(current);
1030 next.delete(requestId);
1031 return next;
1032 }),
1033 ),
1034 );
1035
1036 return {
1037 answers: yield* toCodexUserInputAnswers(resolvedAnswers).pipe(
1038 Effect.mapError((error) =>
1039 CodexErrors.CodexAppServerRequestError.invalidParams(error.message, {
1040 questionId: error.questionId,
1041 }),
1042 ),
1043 ),
1044 } satisfies EffectCodexSchema.ToolRequestUserInputResponse;
1045 }),
1046 );
1047
1048 yield* client.handleUnknownServerRequest((method) =>
1049 Effect.fail(CodexErrors.CodexAppServerRequestError.methodNotFound(method)),
1050 );
1051
1052 const registerServerNotification = <M extends CodexRpc.ServerNotificationMethod>(method: M) =>
1053 client.handleServerNotification(method, (params) =>
1054 Queue.offer(serverNotifications, makeCodexServerNotification(method, params)).pipe(
1055 Effect.asVoid,
1056 ),
1057 );
1058
1059 yield* Effect.forEach(
1060 Object.values(
1061 CodexRpc.SERVER_NOTIFICATION_METHODS,
1062 ) as ReadonlyArray<CodexRpc.ServerNotificationMethod>,
1063 registerServerNotification,
1064 { concurrency: 1, discard: true },
1065 );
1066
1067 yield* Stream.fromQueue(serverNotifications).pipe(
1068 Stream.runForEach(handleRawNotification),
1069 Effect.forkIn(runtimeScope),
1070 );
1071
1072 const stderrRemainderRef = yield* Ref.make("");
1073 yield* child.stderr.pipe(
1074 Stream.decodeText(),
1075 Stream.runForEach((chunk) =>
1076 Ref.modify(stderrRemainderRef, (current) => {
1077 const combined = current + chunk;
1078 const lines = combined.split("\n");
1079 const remainder = lines.pop() ?? "";
1080 return [lines.map((line) => line.replace(/\r$/, "")), remainder] as const;
1081 }).pipe(
1082 Effect.flatMap((lines) =>
1083 Effect.forEach(
1084 lines,
1085 (line) => {
1086 const classified = classifyCodexStderrLine(line);
1087 if (!classified) {
1088 return Effect.void;
1089 }
1090 return emitEvent({
1091 kind: "notification",
1092 threadId: options.threadId,
1093 method: "process/stderr",
1094 message: classified.message,
1095 });
1096 },
1097 { discard: true },
1098 ),
1099 ),
1100 ),
1101 ),
1102 Effect.forkIn(runtimeScope),
1103 );
1104
1105 yield* child.exitCode.pipe(
1106 Effect.flatMap((exitCode) =>
1107 Ref.get(closedRef).pipe(
1108 Effect.flatMap((closed) => {
1109 if (closed) {
1110 return Effect.void;
1111 }
1112 const nextStatus = exitCode === 0 ? "closed" : "error";
1113 return updateSession(sessionRef, {
1114 status: nextStatus,
1115 activeTurnId: undefined,
1116 }).pipe(
1117 Effect.andThen(
1118 emitSessionEvent(
1119 "session/exited",
1120 exitCode === 0
1121 ? "Codex App Server exited."
1122 : `Codex App Server exited with code ${exitCode}.`,
1123 ),
1124 ),
1125 );
1126 }),
1127 ),
1128 ),
1129 Effect.forkIn(runtimeScope),
1130 );
1131
1132 const start = Effect.fn("CodexSessionRuntime.start")(function* () {
1133 yield* emitSessionEvent("session/connecting", "Starting Codex App Server session.");
1134 yield* client.request("initialize", buildCodexInitializeParams());
1135 yield* client.notify("initialized", undefined);
1136
1137 const requestedModel = normalizeCodexModelSlug(options.model);
1138
1139 const opened = yield* openCodexThread({
1140 client,
1141 threadId: options.threadId,
1142 runtimeMode: options.runtimeMode,
1143 cwd: options.cwd,
1144 requestedModel,
1145 serviceTier: options.serviceTier,
1146 resumeThreadId: readResumeCursorThreadId(options.resumeCursor),
1147 });
1148
1149 const providerThreadId = opened.thread.id;
1150 const session = {
1151 ...(yield* Ref.get(sessionRef)),
1152 status: "ready",
1153 cwd: opened.cwd,
1154 model: opened.model,
1155 resumeCursor: { threadId: providerThreadId },
1156 updatedAt: new Date().toISOString(),
1157 } satisfies ProviderSession;
1158 yield* Ref.set(sessionRef, session);
1159 yield* emitSessionEvent("session/ready", "Codex App Server session ready.");
1160 return session;
1161 });
1162
1163 const readProviderThreadId = Effect.gen(function* () {
1164 const providerThreadId = currentProviderThreadId(yield* Ref.get(sessionRef));
1165 if (!providerThreadId) {
1166 return yield* new CodexSessionRuntimeThreadIdMissingError({
1167 threadId: options.threadId,
1168 });
1169 }
1170 return providerThreadId;
1171 });
1172
1173 const close = Effect.gen(function* () {
1174 const alreadyClosed = yield* Ref.getAndSet(closedRef, true);
1175 if (alreadyClosed) {
1176 return;
1177 }
1178 yield* settlePendingApprovals("cancel");
1179 yield* settlePendingUserInputs({});
1180 yield* updateSession(sessionRef, {
1181 status: "closed",
1182 activeTurnId: undefined,
1183 });
1184 yield* emitSessionEvent("session/closed", "Session stopped");
1185 yield* Scope.close(runtimeScope, Exit.void);
1186 yield* Queue.shutdown(serverNotifications);
1187 yield* Queue.shutdown(events);
1188 });
1189
1190 return {
1191 start,
1192 getSession: Ref.get(sessionRef),
1193 sendTurn: (input) =>
1194 Effect.gen(function* () {
1195 const providerThreadId = yield* readProviderThreadId;
1196 const normalizedModel = normalizeCodexModelSlug(
1197 input.model ?? (yield* Ref.get(sessionRef)).model,
1198 );
1199 const params = yield* buildTurnStartParams({
1200 threadId: providerThreadId,
1201 runtimeMode: options.runtimeMode,
1202 ...(input.input ? { prompt: input.input } : {}),
1203 ...(input.attachments ? { attachments: input.attachments } : {}),
1204 ...(normalizedModel ? { model: normalizedModel } : {}),
1205 ...(input.serviceTier ? { serviceTier: input.serviceTier } : {}),
1206 ...(input.effort ? { effort: input.effort } : {}),
1207 ...(input.interactionMode ? { interactionMode: input.interactionMode } : {}),
1208 });
1209 const rawResponse = yield* client.raw.request("turn/start", params);
1210 const response = yield* Schema.decodeUnknownEffect(EffectCodexSchema.V2TurnStartResponse)(
1211 rawResponse,
1212 ).pipe(
1213 Effect.mapError((error) =>
1214 toProtocolParseError("Invalid turn/start response payload", error),
1215 ),
1216 );
1217 const turnId = TurnId.make(response.turn.id);
1218 yield* updateSession(sessionRef, {
1219 status: "running",
1220 activeTurnId: turnId,
1221 ...(normalizedModel ? { model: normalizedModel } : {}),
1222 });
1223 const resumedProviderThreadId = currentProviderThreadId(yield* Ref.get(sessionRef));
1224 return {
1225 threadId: options.threadId,
1226 turnId,
1227 ...(resumedProviderThreadId
1228 ? { resumeCursor: { threadId: resumedProviderThreadId } }
1229 : {}),
1230 } satisfies ProviderTurnStartResult;
1231 }),
1232 interruptTurn: (turnId) =>
1233 Effect.gen(function* () {
1234 const providerThreadId = yield* readProviderThreadId;
1235 const session = yield* Ref.get(sessionRef);
1236 const effectiveTurnId = turnId ?? session.activeTurnId;
1237 if (!effectiveTurnId) {
1238 return;
1239 }
1240 yield* client.request("turn/interrupt", {
1241 threadId: providerThreadId,
1242 turnId: effectiveTurnId,
1243 });
1244 }),
1245 readThread: Effect.gen(function* () {
1246 const providerThreadId = yield* readProviderThreadId;
1247 const response = yield* client.request("thread/read", {
1248 threadId: providerThreadId,
1249 includeTurns: true,
1250 });
1251 return parseThreadSnapshot(response);
1252 }),
1253 rollbackThread: (numTurns) =>
1254 Effect.gen(function* () {
1255 const providerThreadId = yield* readProviderThreadId;
1256 const response = yield* client.request("thread/rollback", {
1257 threadId: providerThreadId,
1258 numTurns,
1259 });
1260 yield* updateSession(sessionRef, {
1261 status: "ready",
1262 activeTurnId: undefined,
1263 });
1264 return parseThreadSnapshot(response);
1265 }),
1266 respondToRequest: (requestId, decision) =>
1267 Effect.gen(function* () {
1268 const pending = (yield* Ref.get(pendingApprovalsRef)).get(requestId);
1269 if (!pending) {
1270 return yield* new CodexSessionRuntimePendingApprovalNotFoundError({
1271 requestId,
1272 });
1273 }
1274 yield* Ref.update(pendingApprovalsRef, (current) => {
1275 const next = new Map(current);
1276 next.delete(requestId);
1277 return next;
1278 });
1279 yield* Deferred.succeed(pending.decision, decision);
1280 yield* emitEvent({
1281 kind: "notification",
1282 threadId: options.threadId,
1283 method: "item/requestApproval/decision",
1284 requestId: pending.requestId,
1285 requestKind: pending.requestKind,
1286 ...(pending.turnId ? { turnId: pending.turnId } : {}),
1287 ...(pending.itemId ? { itemId: pending.itemId } : {}),
1288 payload: {
1289 requestId: pending.requestId,
1290 requestKind: pending.requestKind,
1291 decision,
1292 },
1293 });
1294 }),
1295 respondToUserInput: (requestId, answers) =>
1296 Effect.gen(function* () {
1297 const pending = (yield* Ref.get(pendingUserInputsRef)).get(requestId);
1298 if (!pending) {
1299 return yield* new CodexSessionRuntimePendingUserInputNotFoundError({
1300 requestId,
1301 });
1302 }
1303 const codexAnswers = yield* toCodexUserInputAnswers(answers);
1304 yield* Ref.update(pendingUserInputsRef, (current) => {
1305 const next = new Map(current);
1306 next.delete(requestId);
1307 return next;
1308 });
1309 yield* Deferred.succeed(pending.answers, answers);
1310 yield* emitEvent({
1311 kind: "notification",
1312 threadId: options.threadId,
1313 method: "item/tool/requestUserInput/answered",
1314 requestId: pending.requestId,
1315 ...(pending.turnId ? { turnId: pending.turnId } : {}),
1316 ...(pending.itemId ? { itemId: pending.itemId } : {}),
1317 payload: {
1318 answers: codexAnswers,
1319 },
1320 });
1321 }),
1322 events: Stream.fromQueue(events),
1323 close,
1324 } satisfies CodexSessionRuntimeShape;
1325 });
apps/server/src/provider/Layers/ProviderRegistry.test.ts+125-714
...@@ -1,18 +1,7 @@...@@ -1,18 +1,7 @@
1import * as NodeServices from "@effect/platform-node/NodeServices";1import * as NodeServices from "@effect/platform-node/NodeServices";
2import { describe, it, assert } from "@effect/vitest";2import { describe, it, assert } from "@effect/vitest";
3import {3import { Effect, Exit, Layer, PubSub, Ref, Schema, Scope, Sink, Stream } from "effect";
4 Effect,4import * as CodexErrors from "effect-codex-app-server/errors";
5 Exit,
6 FileSystem,
7 Layer,
8 Path,
9 PubSub,
10 Ref,
11 Schema,
12 Scope,
13 Sink,
14 Stream,
15} from "effect";
16import {5import {
17 DEFAULT_SERVER_SETTINGS,6 DEFAULT_SERVER_SETTINGS,
18 ServerSettings,7 ServerSettings,
...@@ -23,19 +12,13 @@ import * as PlatformError from "effect/PlatformError";...@@ -23,19 +12,13 @@ import * as PlatformError from "effect/PlatformError";
23import { ChildProcessSpawner } from "effect/unstable/process";12import { ChildProcessSpawner } from "effect/unstable/process";
24import { deepMerge } from "@t3tools/shared/Struct";13import { deepMerge } from "@t3tools/shared/Struct";
2514
26import {15import { checkCodexProviderStatus, type CodexAppServerProviderSnapshot } from "./CodexProvider.ts";
27 checkCodexProviderStatus,
28 hasCustomModelProvider,
29 parseAuthStatusFromOutput,
30 readCodexConfigModelProvider,
31} from "./CodexProvider.ts";
32import { checkClaudeProviderStatus, parseClaudeAuthStatusFromOutput } from "./ClaudeProvider.ts";16import { checkClaudeProviderStatus, parseClaudeAuthStatusFromOutput } from "./ClaudeProvider.ts";
33import {17import {
34 haveProvidersChanged,18 haveProvidersChanged,
35 mergeProviderSnapshot,19 mergeProviderSnapshot,
36 ProviderRegistryLive,20 ProviderRegistryLive,
37} from "./ProviderRegistry.ts";21} from "./ProviderRegistry.ts";
38import { OpenCodeProvider } from "../Services/OpenCodeProvider.ts";
39import { ServerConfig } from "../../config.ts";22import { ServerConfig } from "../../config.ts";
40import { ServerSettingsService, type ServerSettingsShape } from "../../serverSettings.ts";23import { ServerSettingsService, type ServerSettingsShape } from "../../serverSettings.ts";
41import { ProviderRegistry } from "../Services/ProviderRegistry.ts";24import { ProviderRegistry } from "../Services/ProviderRegistry.ts";
...@@ -45,19 +28,6 @@ process.env.T3CODE_CURSOR_ENABLED = "1";...@@ -45,19 +28,6 @@ process.env.T3CODE_CURSOR_ENABLED = "1";
45// ── Test helpers ────────────────────────────────────────────────────28// ── Test helpers ────────────────────────────────────────────────────
4629
47const encoder = new TextEncoder();30const encoder = new TextEncoder();
48const fakeOpenCodeSnapshot: ServerProvider = {
49 provider: "opencode",
50 status: "warning",
51 enabled: true,
52 installed: false,
53 auth: { status: "unknown" },
54 checkedAt: "2026-03-25T00:00:00.000Z",
55 version: null,
56 models: [],
57 slashCommands: [],
58 skills: [],
59 message: "OpenCode test stub",
60};
6131
62function mockHandle(result: { stdout: string; stderr: string; code: number }) {32function mockHandle(result: { stdout: string; stderr: string; code: number }) {
63 return ChildProcessSpawner.makeHandle({33 return ChildProcessSpawner.makeHandle({
...@@ -118,6 +88,43 @@ function failingSpawnerLayer(description: string) {...@@ -118,6 +88,43 @@ function failingSpawnerLayer(description: string) {
118 );88 );
119}89}
12090
91const codexModelCapabilities = {
92 reasoningEffortLevels: [
93 { value: "high", label: "High", isDefault: true },
94 { value: "low", label: "Low" },
95 ],
96 supportsFastMode: true,
97 supportsThinkingToggle: false,
98 contextWindowOptions: [],
99 promptInjectedEffortLevels: [],
100} satisfies NonNullable<ServerProvider["models"][number]["capabilities"]>;
101
102function makeCodexProbeSnapshot(
103 input: Partial<CodexAppServerProviderSnapshot> = {},
104): CodexAppServerProviderSnapshot {
105 return {
106 version: "1.0.0",
107 account: {
108 account: {
109 type: "chatgpt",
110 email: "test@example.com",
111 planType: "pro",
112 },
113 requiresOpenaiAuth: false,
114 },
115 models: [
116 {
117 slug: "gpt-live-codex",
118 name: "GPT Live Codex",
119 isCustom: false,
120 capabilities: codexModelCapabilities,
121 },
122 ],
123 skills: [],
124 ...input,
125 };
126}
127
121function makeMutableServerSettingsService(128function makeMutableServerSettingsService(
122 initial: ContractServerSettings = DEFAULT_SERVER_SETTINGS,129 initial: ContractServerSettings = DEFAULT_SERVER_SETTINGS,
123) {130) {
...@@ -144,126 +151,43 @@ function makeMutableServerSettingsService(...@@ -144,126 +151,43 @@ function makeMutableServerSettingsService(
144 });151 });
145}152}
146153
147/**
148 * Create a temporary CODEX_HOME scoped to the current Effect test.
149 * Cleanup is registered in the test scope rather than via Vitest hooks.
150 */
151function withTempCodexHome(configContent?: string) {
152 return Effect.gen(function* () {
153 const fileSystem = yield* FileSystem.FileSystem;
154 const path = yield* Path.Path;
155 const tmpDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-test-codex-" });
156
157 yield* Effect.acquireRelease(
158 Effect.sync(() => {
159 const originalCodexHome = process.env.CODEX_HOME;
160 process.env.CODEX_HOME = tmpDir;
161 return originalCodexHome;
162 }),
163 (originalCodexHome) =>
164 Effect.sync(() => {
165 if (originalCodexHome !== undefined) {
166 process.env.CODEX_HOME = originalCodexHome;
167 } else {
168 delete process.env.CODEX_HOME;
169 }
170 }),
171 );
172
173 if (configContent !== undefined) {
174 yield* fileSystem.writeFileString(path.join(tmpDir, "config.toml"), configContent);
175 }
176
177 return { tmpDir } as const;
178 });
179}
180
181it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(154it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(
182 "ProviderRegistry",155 "ProviderRegistry",
183 (it) => {156 (it) => {
184 // ── checkCodexProviderStatus tests ────────────────────────────────
185 //
186 // These tests control CODEX_HOME to ensure the custom-provider detection
187 // in hasCustomModelProvider() does not interfere with the auth-probe
188 // path being tested.
189
190 describe("checkCodexProviderStatus", () => {157 describe("checkCodexProviderStatus", () => {
191 it.effect("returns ready when codex is installed and authenticated", () =>158 it.effect("uses the app-server account and model list for provider status", () =>
192 Effect.gen(function* () {
193 // Point CODEX_HOME at an empty tmp dir (no config.toml) so the
194 // default code path (OpenAI provider, auth probe runs) is exercised.
195 yield* withTempCodexHome();
196 const status = yield* checkCodexProviderStatus();
197 assert.strictEqual(status.provider, "codex");
198 assert.strictEqual(status.status, "ready");
199 assert.strictEqual(status.installed, true);
200 assert.strictEqual(status.auth.status, "authenticated");
201 }).pipe(
202 Effect.provide(
203 mockSpawnerLayer((args) => {
204 const joined = args.join(" ");
205 if (joined === "--version") return { stdout: "codex 1.0.0\n", stderr: "", code: 0 };
206 if (joined === "login status") return { stdout: "Logged in\n", stderr: "", code: 0 };
207 throw new Error(`Unexpected args: ${joined}`);
208 }),
209 ),
210 ),
211 );
212
213 it.effect("returns the codex plan type in auth and keeps spark for supported plans", () =>
214 Effect.gen(function* () {159 Effect.gen(function* () {
215 yield* withTempCodexHome();
216 const status = yield* checkCodexProviderStatus(() =>160 const status = yield* checkCodexProviderStatus(() =>
217 Effect.succeed({161 Effect.succeed(
218 type: "chatgpt" as const,162 makeCodexProbeSnapshot({
219 planType: "pro" as const,163 skills: [
220 sparkEnabled: true,164 {
221 }),165 name: "github:gh-fix-ci",
166 path: "/Users/test/.codex/skills/gh-fix-ci/SKILL.md",
167 enabled: true,
168 displayName: "CI Debug",
169 shortDescription: "Debug failing GitHub Actions checks",
170 },
171 ],
172 }),
173 ),
222 );174 );
223175
224 assert.strictEqual(status.provider, "codex");176 assert.strictEqual(status.provider, "codex");
225 assert.strictEqual(status.status, "ready");177 assert.strictEqual(status.status, "ready");
178 assert.strictEqual(status.installed, true);
179 assert.strictEqual(status.version, "1.0.0");
226 assert.strictEqual(status.auth.status, "authenticated");180 assert.strictEqual(status.auth.status, "authenticated");
227 assert.strictEqual(status.auth.type, "pro");181 assert.strictEqual(status.auth.type, "chatgpt");
228 assert.strictEqual(status.auth.label, "ChatGPT Pro Subscription");182 assert.strictEqual(status.auth.label, "ChatGPT Pro Subscription");
229 assert.deepStrictEqual(183 assert.deepStrictEqual(status.models, [
230 status.models.some((model) => model.slug === "gpt-5.3-codex-spark"),184 {
231 true,185 slug: "gpt-live-codex",
232 );186 name: "GPT Live Codex",
233 }).pipe(187 isCustom: false,
234 Effect.provide(188 capabilities: codexModelCapabilities,
235 mockSpawnerLayer((args) => {189 },
236 const joined = args.join(" ");190 ]);
237 if (joined === "--version") return { stdout: "codex 1.0.0\n", stderr: "", code: 0 };
238 if (joined === "login status") return { stdout: "Logged in\n", stderr: "", code: 0 };
239 throw new Error(`Unexpected args: ${joined}`);
240 }),
241 ),
242 ),
243 );
244
245 it.effect("includes probed codex skills in the provider snapshot", () =>
246 Effect.gen(function* () {
247 yield* withTempCodexHome();
248 const status = yield* checkCodexProviderStatus(
249 () =>
250 Effect.succeed({
251 type: "chatgpt" as const,
252 planType: "pro" as const,
253 sparkEnabled: true,
254 }),
255 () =>
256 Effect.succeed([
257 {
258 name: "github:gh-fix-ci",
259 path: "/Users/test/.codex/skills/gh-fix-ci/SKILL.md",
260 enabled: true,
261 displayName: "CI Debug",
262 shortDescription: "Debug failing GitHub Actions checks",
263 },
264 ]),
265 );
266
267 assert.deepStrictEqual(status.skills, [191 assert.deepStrictEqual(status.skills, [
268 {192 {
269 name: "github:gh-fix-ci",193 name: "github:gh-fix-ci",
...@@ -273,172 +197,81 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(...@@ -273,172 +197,81 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(
273 shortDescription: "Debug failing GitHub Actions checks",197 shortDescription: "Debug failing GitHub Actions checks",
274 },198 },
275 ]);199 ]);
276 }).pipe(200 }),
277 Effect.provide(
278 mockSpawnerLayer((args) => {
279 const joined = args.join(" ");
280 if (joined === "--version") return { stdout: "codex 1.0.0\n", stderr: "", code: 0 };
281 if (joined === "login status") return { stdout: "Logged in\n", stderr: "", code: 0 };
282 throw new Error(`Unexpected args: ${joined}`);
283 }),
284 ),
285 ),
286 );201 );
287202
288 it.effect("hides spark from codex models for unsupported chatgpt plans", () =>203 it.effect("returns unauthenticated when app-server requires OpenAI auth", () =>
289 Effect.gen(function* () {204 Effect.gen(function* () {
290 yield* withTempCodexHome();
291 const status = yield* checkCodexProviderStatus(() =>205 const status = yield* checkCodexProviderStatus(() =>
292 Effect.succeed({206 Effect.succeed(
293 type: "chatgpt" as const,207 makeCodexProbeSnapshot({
294 planType: "plus" as const,208 account: {
295 sparkEnabled: false,209 account: null,
296 }),210 requiresOpenaiAuth: true,
211 },
212 }),
213 ),
297 );214 );
298215
299 assert.strictEqual(status.provider, "codex");216 assert.strictEqual(status.status, "error");
300 assert.strictEqual(status.status, "ready");217 assert.strictEqual(status.auth.status, "unauthenticated");
301 assert.strictEqual(status.auth.status, "authenticated");218 assert.strictEqual(
302 assert.strictEqual(status.auth.type, "plus");219 status.message,
303 assert.strictEqual(status.auth.label, "ChatGPT Plus Subscription");220 "Codex CLI is not authenticated. Run `codex login` and try again.",
304 assert.deepStrictEqual(
305 status.models.some((model) => model.slug === "gpt-5.3-codex-spark"),
306 false,
307 );221 );
308 }).pipe(222 }),
309 Effect.provide(
310 mockSpawnerLayer((args) => {
311 const joined = args.join(" ");
312 if (joined === "--version") return { stdout: "codex 1.0.0\n", stderr: "", code: 0 };
313 if (joined === "login status") return { stdout: "Logged in\n", stderr: "", code: 0 };
314 throw new Error(`Unexpected args: ${joined}`);
315 }),
316 ),
317 ),
318 );223 );
319224
320 it.effect("hides spark from codex models for non-pro chatgpt subscriptions", () =>225 it.effect(
321 Effect.gen(function* () {226 "returns ready with unknown auth when app-server does not require OpenAI auth",
322 yield* withTempCodexHome();227 () =>
323 const status = yield* checkCodexProviderStatus(() =>228 Effect.gen(function* () {
324 Effect.succeed({229 const status = yield* checkCodexProviderStatus(() =>
325 type: "chatgpt" as const,230 Effect.succeed(
326 planType: "team" as const,231 makeCodexProbeSnapshot({
327 sparkEnabled: false,232 account: {
328 }),233 account: null,
329 );234 requiresOpenaiAuth: false,
235 },
236 }),
237 ),
238 );
330239
331 assert.strictEqual(status.provider, "codex");240 assert.strictEqual(status.status, "ready");
332 assert.strictEqual(status.auth.type, "team");241 assert.strictEqual(status.auth.status, "unknown");
333 assert.strictEqual(status.auth.label, "ChatGPT Team Subscription");242 }),
334 assert.deepStrictEqual(
335 status.models.some((model) => model.slug === "gpt-5.3-codex-spark"),
336 false,
337 );
338 }).pipe(
339 Effect.provide(
340 mockSpawnerLayer((args) => {
341 const joined = args.join(" ");
342 if (joined === "--version") return { stdout: "codex 1.0.0\n", stderr: "", code: 0 };
343 if (joined === "login status") return { stdout: "Logged in\n", stderr: "", code: 0 };
344 throw new Error(`Unexpected args: ${joined}`);
345 }),
346 ),
347 ),
348 );243 );
349244
350 it.effect("returns an api key label for codex api key auth", () =>245 it.effect("returns an api key label for codex api key auth", () =>
351 Effect.gen(function* () {246 Effect.gen(function* () {
352 yield* withTempCodexHome();
353 const status = yield* checkCodexProviderStatus(() =>247 const status = yield* checkCodexProviderStatus(() =>
354 Effect.succeed({248 Effect.succeed(
355 type: "apiKey" as const,249 makeCodexProbeSnapshot({
356 planType: null,250 account: {
357 sparkEnabled: false,251 account: { type: "apiKey" },
358 }),252 requiresOpenaiAuth: false,
253 },
254 }),
255 ),
359 );256 );
360257
361 assert.strictEqual(status.provider, "codex");
362 assert.strictEqual(status.status, "ready");258 assert.strictEqual(status.status, "ready");
363 assert.strictEqual(status.auth.status, "authenticated");259 assert.strictEqual(status.auth.status, "authenticated");
364 assert.strictEqual(status.auth.type, "apiKey");260 assert.strictEqual(status.auth.type, "apiKey");
365 assert.strictEqual(status.auth.label, "OpenAI API Key");261 assert.strictEqual(status.auth.label, "OpenAI API Key");
366 assert.deepStrictEqual(262 }),
367 status.models.some((model) => model.slug === "gpt-5.3-codex-spark"),
368 false,
369 );
370 }).pipe(
371 Effect.provide(
372 mockSpawnerLayer((args) => {
373 const joined = args.join(" ");
374 if (joined === "--version") return { stdout: "codex 1.0.0\n", stderr: "", code: 0 };
375 if (joined === "login status") return { stdout: "Logged in\n", stderr: "", code: 0 };
376 throw new Error(`Unexpected args: ${joined}`);
377 }),
378 ),
379 ),
380 );
381
382 it.effect.skipIf(process.platform === "win32")(
383 "inherits PATH when launching the codex probe with a CODEX_HOME override",
384 () =>
385 Effect.gen(function* () {
386 const fileSystem = yield* FileSystem.FileSystem;
387 const path = yield* Path.Path;
388 const binDir = yield* fileSystem.makeTempDirectoryScoped({
389 prefix: "t3-test-codex-bin-",
390 });
391 const codexPath = path.join(binDir, "codex");
392 yield* fileSystem.writeFileString(
393 codexPath,
394 [
395 "#!/bin/sh",
396 'if [ "$1" = "--version" ]; then',
397 ' echo "codex-cli 1.0.0"',
398 " exit 0",
399 "fi",
400 'if [ "$1" = "login" ] && [ "$2" = "status" ]; then',
401 ' echo "Logged in using ChatGPT"',
402 " exit 0",
403 "fi",
404 'echo "unexpected args: $*" >&2',
405 "exit 1",
406 "",
407 ].join("\n"),
408 );
409 yield* fileSystem.chmod(codexPath, 0o755);
410 const customCodexHome = yield* fileSystem.makeTempDirectoryScoped({
411 prefix: "t3-test-codex-home-",
412 });
413 const previousPath = process.env.PATH;
414 process.env.PATH = binDir;
415
416 try {
417 const serverSettingsLayer = ServerSettingsService.layerTest({
418 providers: {
419 codex: {
420 homePath: customCodexHome,
421 },
422 },
423 });
424
425 const status = yield* checkCodexProviderStatus().pipe(
426 Effect.provide(serverSettingsLayer),
427 );
428 assert.strictEqual(status.provider, "codex");
429 assert.strictEqual(status.installed, true);
430 assert.strictEqual(status.status, "ready");
431 assert.strictEqual(status.auth.status, "authenticated");
432 } finally {
433 process.env.PATH = previousPath;
434 }
435 }),
436 );263 );
437264
438 it.effect("returns unavailable when codex is missing", () =>265 it.effect("returns unavailable when codex is missing", () =>
439 Effect.gen(function* () {266 Effect.gen(function* () {
440 yield* withTempCodexHome();267 const status = yield* checkCodexProviderStatus(() =>
441 const status = yield* checkCodexProviderStatus();268 Effect.fail(
269 new CodexErrors.CodexAppServerSpawnError({
270 command: "codex app-server",
271 cause: new Error("spawn codex ENOENT"),
272 }),
273 ),
274 );
442 assert.strictEqual(status.provider, "codex");275 assert.strictEqual(status.provider, "codex");
443 assert.strictEqual(status.status, "error");276 assert.strictEqual(status.status, "error");
444 assert.strictEqual(status.installed, false);277 assert.strictEqual(status.installed, false);
...@@ -447,107 +280,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(...@@ -447,107 +280,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(
447 status.message,280 status.message,
448 "Codex CLI (`codex`) is not installed or not on PATH.",281 "Codex CLI (`codex`) is not installed or not on PATH.",
449 );282 );
450 }).pipe(Effect.provide(failingSpawnerLayer("spawn codex ENOENT"))),283 }),
451 );
452
453 it.effect("returns unavailable when codex is below the minimum supported version", () =>
454 Effect.gen(function* () {
455 yield* withTempCodexHome();
456 const status = yield* checkCodexProviderStatus();
457 assert.strictEqual(status.provider, "codex");
458 assert.strictEqual(status.status, "error");
459 assert.strictEqual(status.installed, true);
460 assert.strictEqual(status.auth.status, "unknown");
461 assert.strictEqual(
462 status.message,
463 "Codex CLI v0.36.0 is too old for T3 Code. Upgrade to v0.37.0 or newer and restart T3 Code.",
464 );
465 }).pipe(
466 Effect.provide(
467 mockSpawnerLayer((args) => {
468 const joined = args.join(" ");
469 if (joined === "--version") return { stdout: "codex 0.36.0\n", stderr: "", code: 0 };
470 throw new Error(`Unexpected args: ${joined}`);
471 }),
472 ),
473 ),
474 );
475
476 it.effect("returns unauthenticated when auth probe reports login required", () =>
477 Effect.gen(function* () {
478 yield* withTempCodexHome();
479 const status = yield* checkCodexProviderStatus();
480 assert.strictEqual(status.provider, "codex");
481 assert.strictEqual(status.status, "error");
482 assert.strictEqual(status.installed, true);
483 assert.strictEqual(status.auth.status, "unauthenticated");
484 assert.strictEqual(
485 status.message,
486 "Codex CLI is not authenticated. Run `codex login` and try again.",
487 );
488 }).pipe(
489 Effect.provide(
490 mockSpawnerLayer((args) => {
491 const joined = args.join(" ");
492 if (joined === "--version") return { stdout: "codex 1.0.0\n", stderr: "", code: 0 };
493 if (joined === "login status") {
494 return { stdout: "", stderr: "Not logged in. Run codex login.", code: 1 };
495 }
496 throw new Error(`Unexpected args: ${joined}`);
497 }),
498 ),
499 ),
500 );
501
502 it.effect("returns unauthenticated when login status output includes 'not logged in'", () =>
503 Effect.gen(function* () {
504 yield* withTempCodexHome();
505 const status = yield* checkCodexProviderStatus();
506 assert.strictEqual(status.provider, "codex");
507 assert.strictEqual(status.status, "error");
508 assert.strictEqual(status.installed, true);
509 assert.strictEqual(status.auth.status, "unauthenticated");
510 assert.strictEqual(
511 status.message,
512 "Codex CLI is not authenticated. Run `codex login` and try again.",
513 );
514 }).pipe(
515 Effect.provide(
516 mockSpawnerLayer((args) => {
517 const joined = args.join(" ");
518 if (joined === "--version") return { stdout: "codex 1.0.0\n", stderr: "", code: 0 };
519 if (joined === "login status")
520 return { stdout: "Not logged in\n", stderr: "", code: 1 };
521 throw new Error(`Unexpected args: ${joined}`);
522 }),
523 ),
524 ),
525 );
526
527 it.effect("returns warning when login status command is unsupported", () =>
528 Effect.gen(function* () {
529 yield* withTempCodexHome();
530 const status = yield* checkCodexProviderStatus();
531 assert.strictEqual(status.provider, "codex");
532 assert.strictEqual(status.status, "warning");
533 assert.strictEqual(status.installed, true);
534 assert.strictEqual(status.auth.status, "unknown");
535 assert.strictEqual(
536 status.message,
537 "Codex CLI authentication status command is unavailable in this Codex version.",
538 );
539 }).pipe(
540 Effect.provide(
541 mockSpawnerLayer((args) => {
542 const joined = args.join(" ");
543 if (joined === "--version") return { stdout: "codex 1.0.0\n", stderr: "", code: 0 };
544 if (joined === "login status") {
545 return { stdout: "", stderr: "error: unknown command 'login'", code: 2 };
546 }
547 throw new Error(`Unexpected args: ${joined}`);
548 }),
549 ),
550 ),
551 );284 );
552 });285 });
553286
...@@ -677,7 +410,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(...@@ -677,7 +410,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(
677 Schema.decodeSync(ServerSettings)(410 Schema.decodeSync(ServerSettings)(
678 deepMerge(DEFAULT_SERVER_SETTINGS, {411 deepMerge(DEFAULT_SERVER_SETTINGS, {
679 providers: {412 providers: {
680 claudeAgent: { enabled: false },413 codex: { enabled: false },
681 cursor: { enabled: false },414 cursor: { enabled: false },
682 },415 },
683 }),416 }),
...@@ -697,14 +430,8 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(...@@ -697,14 +430,8 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(
697 spawnCount += 1;430 spawnCount += 1;
698 const joined = args.join(" ");431 const joined = args.join(" ");
699 if (joined === "--version") {432 if (joined === "--version") {
700 if (command === "codex") {
701 return { stdout: "codex 1.0.0\n", stderr: "", code: 0 };
702 }
703 return { stdout: "claude 1.0.0\n", stderr: "", code: 0 };433 return { stdout: "claude 1.0.0\n", stderr: "", code: 0 };
704 }434 }
705 if (joined === "login status") {
706 return { stdout: "Logged in\n", stderr: "", code: 0 };
707 }
708 if (joined === "auth status") {435 if (joined === "auth status") {
709 return { stdout: '{"authenticated":true}\n', stderr: "", code: 0 };436 return { stdout: '{"authenticated":true}\n', stderr: "", code: 0 };
710 }437 }
...@@ -722,8 +449,10 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(...@@ -722,8 +449,10 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(
722 const refreshed = yield* Effect.gen(function* () {449 const refreshed = yield* Effect.gen(function* () {
723 for (let remainingAttempts = 50; remainingAttempts > 0; remainingAttempts -= 1) {450 for (let remainingAttempts = 50; remainingAttempts > 0; remainingAttempts -= 1) {
724 const providers = yield* registry.getProviders;451 const providers = yield* registry.getProviders;
725 const codexProvider = providers.find((provider) => provider.provider === "codex");452 const claudeProvider = providers.find(
726 if (codexProvider?.status === "ready") {453 (provider) => provider.provider === "claudeAgent",
454 );
455 if (claudeProvider?.status === "ready") {
727 return providers;456 return providers;
728 }457 }
729 yield* Effect.sleep("10 millis");458 yield* Effect.sleep("10 millis");
...@@ -731,99 +460,13 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(...@@ -731,99 +460,13 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(
731 return yield* registry.getProviders;460 return yield* registry.getProviders;
732 });461 });
733 assert.strictEqual(462 assert.strictEqual(
734 refreshed.find((provider) => provider.provider === "codex")?.status,463 refreshed.find((provider) => provider.provider === "claudeAgent")?.status,
735 "ready",464 "ready",
736 );465 );
737 }).pipe(Effect.provide(runtimeServices));466 }).pipe(Effect.provide(runtimeServices));
738 }),467 }),
739 );468 );
740469
741 it.effect("reruns codex health when codex provider settings change", () =>
742 Effect.gen(function* () {
743 const serverSettings = yield* makeMutableServerSettingsService();
744 const scope = yield* Scope.make();
745 yield* Effect.addFinalizer(() => Scope.close(scope, Exit.void));
746 const providerRegistryLayer = ProviderRegistryLive.pipe(
747 Layer.provideMerge(Layer.succeed(ServerSettingsService, serverSettings)),
748 Layer.provideMerge(
749 ServerConfig.layerTest(process.cwd(), {
750 prefix: "t3-provider-registry-",
751 }),
752 ),
753 Layer.provideMerge(
754 Layer.succeed(OpenCodeProvider, {
755 getSnapshot: Effect.succeed(fakeOpenCodeSnapshot),
756 refresh: Effect.succeed(fakeOpenCodeSnapshot),
757 streamChanges: Stream.empty,
758 }),
759 ),
760 Layer.provideMerge(
761 mockCommandSpawnerLayer((command, args) => {
762 const joined = args.join(" ");
763 if (joined === "--version") {
764 if (command === "codex") {
765 return { stdout: "codex 1.0.0\n", stderr: "", code: 0 };
766 }
767 return { stdout: "", stderr: "spawn ENOENT", code: 1 };
768 }
769 if (joined === "about --format json") {
770 return {
771 stdout: JSON.stringify({
772 cliVersion: "2026.04.09-f2b0fcd",
773 userEmail: null,
774 }),
775 stderr: "",
776 code: 0,
777 };
778 }
779 if (joined === "about") {
780 return { stdout: "", stderr: "spawn ENOENT", code: 1 };
781 }
782 if (joined === "login status") {
783 return { stdout: "Logged in\n", stderr: "", code: 0 };
784 }
785 throw new Error(`Unexpected args: ${joined}`);
786 }),
787 ),
788 );
789 const runtimeServices = yield* Layer.build(providerRegistryLayer).pipe(
790 Scope.provide(scope),
791 );
792
793 yield* Effect.gen(function* () {
794 const registry = yield* ProviderRegistry;
795
796 const refreshed = yield* registry.refresh("codex");
797 assert.strictEqual(
798 refreshed.find((status) => status.provider === "codex")?.status,
799 "ready",
800 );
801
802 yield* serverSettings.updateSettings({
803 providers: {
804 codex: {
805 binaryPath: "/custom/codex",
806 },
807 },
808 });
809
810 for (let attempt = 0; attempt < 20; attempt += 1) {
811 const updated = yield* registry.getProviders;
812 if (updated.find((status) => status.provider === "codex")?.status === "error") {
813 return;
814 }
815 yield* Effect.promise(() => new Promise((resolve) => setTimeout(resolve, 0)));
816 }
817
818 const updated = yield* registry.getProviders;
819 assert.strictEqual(
820 updated.find((status) => status.provider === "codex")?.status,
821 "error",
822 );
823 }).pipe(Effect.provide(runtimeServices));
824 }),
825 );
826
827 it.effect(470 it.effect(
828 "keeps cursor disabled and skips probing when the provider setting is disabled",471 "keeps cursor disabled and skips probing when the provider setting is disabled",
829 () =>472 () =>
...@@ -832,6 +475,9 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(...@@ -832,6 +475,9 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(
832 Schema.decodeSync(ServerSettings)(475 Schema.decodeSync(ServerSettings)(
833 deepMerge(DEFAULT_SERVER_SETTINGS, {476 deepMerge(DEFAULT_SERVER_SETTINGS, {
834 providers: {477 providers: {
478 codex: {
479 enabled: false,
480 },
835 cursor: {481 cursor: {
836 enabled: false,482 enabled: false,
837 },483 },
...@@ -858,9 +504,6 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(...@@ -858,9 +504,6 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(
858 if (joined === "--version") {504 if (joined === "--version") {
859 return { stdout: `${command} 1.0.0\n`, stderr: "", code: 0 };505 return { stdout: `${command} 1.0.0\n`, stderr: "", code: 0 };
860 }506 }
861 if (joined === "login status") {
862 return { stdout: "Logged in\n", stderr: "", code: 0 };
863 }
864 if (joined === "auth status") {507 if (joined === "auth status") {
865 return { stdout: '{"authenticated":true}\n', stderr: "", code: 0 };508 return { stdout: '{"authenticated":true}\n', stderr: "", code: 0 };
866 }509 }
...@@ -919,238 +562,6 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(...@@ -919,238 +562,6 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(
919 );562 );
920 });563 });
921564
922 // ── Custom model provider: checkCodexProviderStatus integration ───
923
924 describe("checkCodexProviderStatus with custom model provider", () => {
925 it.effect(
926 "skips auth probe and returns ready when a custom model provider is configured",
927 () =>
928 Effect.gen(function* () {
929 yield* withTempCodexHome(
930 [
931 'model_provider = "portkey"',
932 "",
933 "[model_providers.portkey]",
934 'base_url = "https://api.portkey.ai/v1"',
935 'env_key = "PORTKEY_API_KEY"',
936 ].join("\n"),
937 );
938 const status = yield* checkCodexProviderStatus();
939 assert.strictEqual(status.provider, "codex");
940 assert.strictEqual(status.status, "ready");
941 assert.strictEqual(status.installed, true);
942 assert.strictEqual(status.auth.status, "unknown");
943 assert.strictEqual(
944 status.message,
945 "Using a custom Codex model provider; OpenAI login check skipped.",
946 );
947 }).pipe(
948 Effect.provide(
949 // The spawner only handles --version; if the test attempts
950 // "login status" the throw proves the auth probe was NOT skipped.
951 mockSpawnerLayer((args) => {
952 const joined = args.join(" ");
953 if (joined === "--version") return { stdout: "codex 1.0.0\n", stderr: "", code: 0 };
954 throw new Error(`Auth probe should have been skipped but got args: ${joined}`);
955 }),
956 ),
957 ),
958 );
959
960 it.effect("still reports error when codex CLI is missing even with custom provider", () =>
961 Effect.gen(function* () {
962 yield* withTempCodexHome(
963 [
964 'model_provider = "portkey"',
965 "",
966 "[model_providers.portkey]",
967 'base_url = "https://api.portkey.ai/v1"',
968 'env_key = "PORTKEY_API_KEY"',
969 ].join("\n"),
970 );
971 const status = yield* checkCodexProviderStatus();
972 assert.strictEqual(status.status, "error");
973 assert.strictEqual(status.installed, false);
974 }).pipe(Effect.provide(failingSpawnerLayer("spawn codex ENOENT"))),
975 );
976 });
977
978 describe("checkCodexProviderStatus with openai model provider", () => {
979 it.effect("still runs auth probe when model_provider is openai", () =>
980 Effect.gen(function* () {
981 yield* withTempCodexHome('model_provider = "openai"\n');
982 const status = yield* checkCodexProviderStatus();
983 // The auth probe runs and sees "not logged in" → error
984 assert.strictEqual(status.status, "error");
985 assert.strictEqual(status.auth.status, "unauthenticated");
986 }).pipe(
987 Effect.provide(
988 mockSpawnerLayer((args) => {
989 const joined = args.join(" ");
990 if (joined === "--version") return { stdout: "codex 1.0.0\n", stderr: "", code: 0 };
991 if (joined === "login status")
992 return { stdout: "Not logged in\n", stderr: "", code: 1 };
993 throw new Error(`Unexpected args: ${joined}`);
994 }),
995 ),
996 ),
997 );
998 });
999
1000 // ── parseAuthStatusFromOutput pure tests ──────────────────────────
1001
1002 describe("parseAuthStatusFromOutput", () => {
1003 it("exit code 0 with no auth markers is ready", () => {
1004 const parsed = parseAuthStatusFromOutput({ stdout: "OK\n", stderr: "", code: 0 });
1005 assert.strictEqual(parsed.status, "ready");
1006 assert.strictEqual(parsed.auth.status, "authenticated");
1007 });
1008
1009 it("JSON with authenticated=false is unauthenticated", () => {
1010 const parsed = parseAuthStatusFromOutput({
1011 stdout: '[{"authenticated":false}]\n',
1012 stderr: "",
1013 code: 0,
1014 });
1015 assert.strictEqual(parsed.status, "error");
1016 assert.strictEqual(parsed.auth.status, "unauthenticated");
1017 });
1018
1019 it("JSON without auth marker is warning", () => {
1020 const parsed = parseAuthStatusFromOutput({
1021 stdout: '[{"ok":true}]\n',
1022 stderr: "",
1023 code: 0,
1024 });
1025 assert.strictEqual(parsed.status, "warning");
1026 assert.strictEqual(parsed.auth.status, "unknown");
1027 });
1028 });
1029
1030 // ── readCodexConfigModelProvider tests ─────────────────────────────
1031
1032 describe("readCodexConfigModelProvider", () => {
1033 it.effect("returns undefined when config file does not exist", () =>
1034 Effect.gen(function* () {
1035 yield* withTempCodexHome();
1036 assert.strictEqual(yield* readCodexConfigModelProvider(), undefined);
1037 }),
1038 );
1039
1040 it.effect("returns undefined when config has no model_provider key", () =>
1041 Effect.gen(function* () {
1042 yield* withTempCodexHome('model = "gpt-5-codex"\n');
1043 assert.strictEqual(yield* readCodexConfigModelProvider(), undefined);
1044 }),
1045 );
1046
1047 it.effect("returns the provider when model_provider is set at top level", () =>
1048 Effect.gen(function* () {
1049 yield* withTempCodexHome('model = "gpt-5-codex"\nmodel_provider = "portkey"\n');
1050 assert.strictEqual(yield* readCodexConfigModelProvider(), "portkey");
1051 }),
1052 );
1053
1054 it.effect("returns openai when model_provider is openai", () =>
1055 Effect.gen(function* () {
1056 yield* withTempCodexHome('model_provider = "openai"\n');
1057 assert.strictEqual(yield* readCodexConfigModelProvider(), "openai");
1058 }),
1059 );
1060
1061 it.effect("ignores model_provider inside section headers", () =>
1062 Effect.gen(function* () {
1063 yield* withTempCodexHome(
1064 [
1065 'model = "gpt-5-codex"',
1066 "",
1067 "[model_providers.portkey]",
1068 'base_url = "https://api.portkey.ai/v1"',
1069 'model_provider = "should-be-ignored"',
1070 "",
1071 ].join("\n"),
1072 );
1073 assert.strictEqual(yield* readCodexConfigModelProvider(), undefined);
1074 }),
1075 );
1076
1077 it.effect("handles comments and whitespace", () =>
1078 Effect.gen(function* () {
1079 yield* withTempCodexHome(
1080 [
1081 "# This is a comment",
1082 "",
1083 ' model_provider = "azure" ',
1084 "",
1085 "[profiles.deep-review]",
1086 'model = "gpt-5-pro"',
1087 ].join("\n"),
1088 );
1089 assert.strictEqual(yield* readCodexConfigModelProvider(), "azure");
1090 }),
1091 );
1092
1093 it.effect("handles single-quoted values in TOML", () =>
1094 Effect.gen(function* () {
1095 yield* withTempCodexHome("model_provider = 'mistral'\n");
1096 assert.strictEqual(yield* readCodexConfigModelProvider(), "mistral");
1097 }),
1098 );
1099 });
1100
1101 // ── hasCustomModelProvider tests ───────────────────────────────────
1102
1103 describe("hasCustomModelProvider", () => {
1104 it.effect("returns false when no config file exists", () =>
1105 Effect.gen(function* () {
1106 yield* withTempCodexHome();
1107 assert.strictEqual(yield* hasCustomModelProvider, false);
1108 }),
1109 );
1110
1111 it.effect("returns false when model_provider is not set", () =>
1112 Effect.gen(function* () {
1113 yield* withTempCodexHome('model = "gpt-5-codex"\n');
1114 assert.strictEqual(yield* hasCustomModelProvider, false);
1115 }),
1116 );
1117
1118 it.effect("returns false when model_provider is openai", () =>
1119 Effect.gen(function* () {
1120 yield* withTempCodexHome('model_provider = "openai"\n');
1121 assert.strictEqual(yield* hasCustomModelProvider, false);
1122 }),
1123 );
1124
1125 it.effect("returns true when model_provider is portkey", () =>
1126 Effect.gen(function* () {
1127 yield* withTempCodexHome('model_provider = "portkey"\n');
1128 assert.strictEqual(yield* hasCustomModelProvider, true);
1129 }),
1130 );
1131
1132 it.effect("returns true when model_provider is azure", () =>
1133 Effect.gen(function* () {
1134 yield* withTempCodexHome('model_provider = "azure"\n');
1135 assert.strictEqual(yield* hasCustomModelProvider, true);
1136 }),
1137 );
1138
1139 it.effect("returns true when model_provider is ollama", () =>
1140 Effect.gen(function* () {
1141 yield* withTempCodexHome('model_provider = "ollama"\n');
1142 assert.strictEqual(yield* hasCustomModelProvider, true);
1143 }),
1144 );
1145
1146 it.effect("returns true when model_provider is a custom proxy", () =>
1147 Effect.gen(function* () {
1148 yield* withTempCodexHome('model_provider = "my-company-proxy"\n');
1149 assert.strictEqual(yield* hasCustomModelProvider, true);
1150 }),
1151 );
1152 });
1153
1154 // ── checkClaudeProviderStatus tests ──────────────────────────565 // ── checkClaudeProviderStatus tests ──────────────────────────
1155566
1156 describe("checkClaudeProviderStatus", () => {567 describe("checkClaudeProviderStatus", () => {
apps/server/src/provider/codexAccount.ts deleted-123
...@@ -1,123 +0,0 @@
1import type { ServerProviderModel } from "@t3tools/contracts";
2
3export type CodexPlanType =
4 | "free"
5 | "go"
6 | "plus"
7 | "pro"
8 | "team"
9 | "business"
10 | "enterprise"
11 | "edu"
12 | "unknown";
13
14export interface CodexAccountSnapshot {
15 readonly type: "apiKey" | "chatgpt" | "unknown";
16 readonly planType: CodexPlanType | null;
17 readonly sparkEnabled: boolean;
18}
19
20export const CODEX_DEFAULT_MODEL = "gpt-5.3-codex";
21export const CODEX_SPARK_MODEL = "gpt-5.3-codex-spark";
22const CODEX_SPARK_ENABLED_PLAN_TYPES = new Set<CodexPlanType>(["pro"]);
23
24function asObject(value: unknown): Record<string, unknown> | undefined {
25 if (!value || typeof value !== "object") {
26 return undefined;
27 }
28 return value as Record<string, unknown>;
29}
30
31function asString(value: unknown): string | undefined {
32 return typeof value === "string" ? value : undefined;
33}
34
35export function readCodexAccountSnapshot(response: unknown): CodexAccountSnapshot {
36 const record = asObject(response);
37 const account = asObject(record?.account) ?? record;
38 const accountType = asString(account?.type);
39
40 if (accountType === "apiKey") {
41 return {
42 type: "apiKey",
43 planType: null,
44 sparkEnabled: false,
45 };
46 }
47
48 if (accountType === "chatgpt") {
49 const planType = (account?.planType as CodexPlanType | null) ?? "unknown";
50 return {
51 type: "chatgpt",
52 planType,
53 sparkEnabled: CODEX_SPARK_ENABLED_PLAN_TYPES.has(planType),
54 };
55 }
56
57 return {
58 type: "unknown",
59 planType: null,
60 sparkEnabled: false,
61 };
62}
63
64export function codexAuthSubType(account: CodexAccountSnapshot | undefined): string | undefined {
65 if (account?.type === "apiKey") {
66 return "apiKey";
67 }
68
69 if (account?.type !== "chatgpt") {
70 return undefined;
71 }
72
73 return account.planType && account.planType !== "unknown" ? account.planType : "chatgpt";
74}
75
76export function codexAuthSubLabel(account: CodexAccountSnapshot | undefined): string | undefined {
77 switch (codexAuthSubType(account)) {
78 case "apiKey":
79 return "OpenAI API Key";
80 case "chatgpt":
81 return "ChatGPT Subscription";
82 case "free":
83 return "ChatGPT Free Subscription";
84 case "go":
85 return "ChatGPT Go Subscription";
86 case "plus":
87 return "ChatGPT Plus Subscription";
88 case "pro":
89 return "ChatGPT Pro Subscription";
90 case "team":
91 return "ChatGPT Team Subscription";
92 case "business":
93 return "ChatGPT Business Subscription";
94 case "enterprise":
95 return "ChatGPT Enterprise Subscription";
96 case "edu":
97 return "ChatGPT Edu Subscription";
98 default:
99 return undefined;
100 }
101}
102
103export function adjustCodexModelsForAccount(
104 baseModels: ReadonlyArray<ServerProviderModel>,
105 account: CodexAccountSnapshot | undefined,
106): ReadonlyArray<ServerProviderModel> {
107 if (account?.sparkEnabled !== false) {
108 return baseModels;
109 }
110
111 return baseModels.filter((model) => model.isCustom || model.slug !== CODEX_SPARK_MODEL);
112}
113
114export function resolveCodexModelForAccount(
115 model: string | undefined,
116 account: CodexAccountSnapshot,
117): string | undefined {
118 if (model !== CODEX_SPARK_MODEL || account.sparkEnabled) {
119 return model;
120 }
121
122 return CODEX_DEFAULT_MODEL;
123}
apps/server/src/provider/codexAppServer.ts deleted-242
...@@ -1,242 +0,0 @@
1import { spawn, spawnSync, type ChildProcessWithoutNullStreams } from "node:child_process";
2import readline from "node:readline";
3import type { ServerProviderSkill } from "@t3tools/contracts";
4import { readCodexAccountSnapshot, type CodexAccountSnapshot } from "./codexAccount.ts";
5import { expandHomePath } from "../pathExpansion.ts";
6
7interface JsonRpcProbeResponse {
8 readonly id?: unknown;
9 readonly result?: unknown;
10 readonly error?: {
11 readonly message?: unknown;
12 };
13}
14
15export interface CodexDiscoverySnapshot {
16 readonly account: CodexAccountSnapshot;
17 readonly skills: ReadonlyArray<ServerProviderSkill>;
18}
19
20function readErrorMessage(response: JsonRpcProbeResponse): string | undefined {
21 return typeof response.error?.message === "string" ? response.error.message : undefined;
22}
23
24function readObject(value: unknown): Record<string, unknown> | undefined {
25 return value && typeof value === "object" ? (value as Record<string, unknown>) : undefined;
26}
27
28function readArray(value: unknown): ReadonlyArray<unknown> | undefined {
29 return Array.isArray(value) ? value : undefined;
30}
31
32function readString(value: unknown): string | undefined {
33 return typeof value === "string" ? value : undefined;
34}
35
36function nonEmptyTrimmed(value: unknown): string | undefined {
37 const candidate = readString(value)?.trim();
38 return candidate ? candidate : undefined;
39}
40
41function parseCodexSkillsResult(result: unknown, cwd: string): ReadonlyArray<ServerProviderSkill> {
42 const resultRecord = readObject(result);
43 const dataBuckets = readArray(resultRecord?.data) ?? [];
44 const matchingBucket = dataBuckets.find(
45 (value) => nonEmptyTrimmed(readObject(value)?.cwd) === cwd,
46 );
47 const rawSkills =
48 readArray(readObject(matchingBucket)?.skills) ?? readArray(resultRecord?.skills) ?? [];
49
50 return rawSkills.flatMap((value) => {
51 const skill = readObject(value);
52 const display = readObject(skill?.interface);
53 const name = nonEmptyTrimmed(skill?.name);
54 const path = nonEmptyTrimmed(skill?.path);
55 if (!name || !path) {
56 return [];
57 }
58
59 return [
60 {
61 name,
62 path,
63 enabled: skill?.enabled !== false,
64 ...(nonEmptyTrimmed(skill?.description)
65 ? { description: nonEmptyTrimmed(skill?.description) }
66 : {}),
67 ...(nonEmptyTrimmed(skill?.scope) ? { scope: nonEmptyTrimmed(skill?.scope) } : {}),
68 ...(nonEmptyTrimmed(display?.displayName)
69 ? { displayName: nonEmptyTrimmed(display?.displayName) }
70 : {}),
71 ...(nonEmptyTrimmed(skill?.shortDescription) || nonEmptyTrimmed(display?.shortDescription)
72 ? {
73 shortDescription:
74 nonEmptyTrimmed(skill?.shortDescription) ??
75 nonEmptyTrimmed(display?.shortDescription),
76 }
77 : {}),
78 } satisfies ServerProviderSkill,
79 ];
80 });
81}
82
83export function buildCodexInitializeParams() {
84 return {
85 clientInfo: {
86 name: "t3code_desktop",
87 title: "T3 Code Desktop",
88 version: "0.1.0",
89 },
90 capabilities: {
91 experimentalApi: true,
92 },
93 } as const;
94}
95
96export function killCodexChildProcess(child: ChildProcessWithoutNullStreams): void {
97 if (process.platform === "win32" && child.pid !== undefined) {
98 try {
99 spawnSync("taskkill", ["/pid", String(child.pid), "/T", "/F"], { stdio: "ignore" });
100 return;
101 } catch {
102 // Fall through to direct kill when taskkill is unavailable.
103 }
104 }
105
106 child.kill();
107}
108
109export async function probeCodexDiscovery(input: {
110 readonly binaryPath: string;
111 readonly homePath?: string;
112 readonly cwd: string;
113 readonly signal?: AbortSignal;
114}): Promise<CodexDiscoverySnapshot> {
115 return await new Promise((resolve, reject) => {
116 const child = spawn(input.binaryPath, ["app-server"], {
117 env: {
118 ...process.env,
119 ...(input.homePath ? { CODEX_HOME: expandHomePath(input.homePath) } : {}),
120 },
121 stdio: ["pipe", "pipe", "pipe"],
122 shell: process.platform === "win32",
123 });
124 const output = readline.createInterface({ input: child.stdout });
125
126 let completed = false;
127 let account: CodexAccountSnapshot | undefined;
128 let skills: ReadonlyArray<ServerProviderSkill> | undefined;
129
130 const cleanup = () => {
131 output.removeAllListeners();
132 output.close();
133 child.removeAllListeners();
134 if (!child.killed) {
135 killCodexChildProcess(child);
136 }
137 };
138
139 const finish = (callback: () => void) => {
140 if (completed) return;
141 completed = true;
142 cleanup();
143 callback();
144 };
145
146 const fail = (error: unknown) =>
147 finish(() =>
148 reject(
149 error instanceof Error
150 ? error
151 : new Error(`Codex discovery probe failed: ${String(error)}.`),
152 ),
153 );
154
155 const maybeResolve = () => {
156 if (account && skills !== undefined) {
157 const resolvedAccount = account;
158 const resolvedSkills = skills;
159 finish(() => resolve({ account: resolvedAccount, skills: resolvedSkills }));
160 }
161 };
162
163 if (input.signal?.aborted) {
164 fail(new Error("Codex discovery probe aborted."));
165 return;
166 }
167 input.signal?.addEventListener("abort", () =>
168 fail(new Error("Codex discovery probe aborted.")),
169 );
170
171 const writeMessage = (message: unknown) => {
172 if (!child.stdin.writable) {
173 fail(new Error("Cannot write to codex app-server stdin."));
174 return;
175 }
176
177 child.stdin.write(`${JSON.stringify(message)}\n`);
178 };
179
180 output.on("line", (line) => {
181 let parsed: unknown;
182 try {
183 parsed = JSON.parse(line);
184 } catch {
185 fail(new Error("Received invalid JSON from codex app-server during discovery probe."));
186 return;
187 }
188
189 if (!parsed || typeof parsed !== "object") {
190 return;
191 }
192
193 const response = parsed as JsonRpcProbeResponse;
194 if (response.id === 1) {
195 const errorMessage = readErrorMessage(response);
196 if (errorMessage) {
197 fail(new Error(`initialize failed: ${errorMessage}`));
198 return;
199 }
200
201 writeMessage({ method: "initialized" });
202 writeMessage({ id: 2, method: "skills/list", params: { cwds: [input.cwd] } });
203 writeMessage({ id: 3, method: "account/read", params: {} });
204 return;
205 }
206
207 if (response.id === 2) {
208 const errorMessage = readErrorMessage(response);
209 skills = errorMessage ? [] : parseCodexSkillsResult(response.result, input.cwd);
210 maybeResolve();
211 return;
212 }
213
214 if (response.id === 3) {
215 const errorMessage = readErrorMessage(response);
216 if (errorMessage) {
217 fail(new Error(`account/read failed: ${errorMessage}`));
218 return;
219 }
220
221 account = readCodexAccountSnapshot(response.result);
222 maybeResolve();
223 }
224 });
225
226 child.once("error", fail);
227 child.once("exit", (code, signal) => {
228 if (completed) return;
229 fail(
230 new Error(
231 `codex app-server exited before probe completed (code=${code ?? "null"}, signal=${signal ?? "null"}).`,
232 ),
233 );
234 });
235
236 writeMessage({
237 id: 1,
238 method: "initialize",
239 params: buildCodexInitializeParams(),
240 });
241 });
242}
apps/server/src/provider/codexCliVersion.ts deleted-25
...@@ -1,25 +0,0 @@
1import { compareCliVersions, normalizeCliVersion } from "./cliVersion.ts";
2
3const CODEX_VERSION_PATTERN = /\bv?(\d+\.\d+(?:\.\d+)?(?:-[0-9A-Za-z.-]+)?)\b/;
4
5export const MINIMUM_CODEX_CLI_VERSION = "0.37.0";
6
7export const compareCodexCliVersions = compareCliVersions;
8
9export function parseCodexCliVersion(output: string): string | null {
10 const match = CODEX_VERSION_PATTERN.exec(output);
11 if (!match?.[1]) {
12 return null;
13 }
14
15 return normalizeCliVersion(match[1]);
16}
17
18export function isCodexCliVersionSupported(version: string): boolean {
19 return compareCodexCliVersions(version, MINIMUM_CODEX_CLI_VERSION) >= 0;
20}
21
22export function formatCodexCliUpgradeMessage(version: string | null): string {
23 const versionLabel = version ? `v${version}` : "the installed version";
24 return `Codex CLI ${versionLabel} is too old for T3 Code. Upgrade to v${MINIMUM_CODEX_CLI_VERSION} or newer and restart T3 Code.`;
25}
apps/web/src/session-logic.test.ts-1
...@@ -11,7 +11,6 @@ import {...@@ -11,7 +11,6 @@ import {
11 deriveCompletionDividerBeforeEntryId,11 deriveCompletionDividerBeforeEntryId,
12 deriveActiveWorkStartedAt,12 deriveActiveWorkStartedAt,
13 deriveActivePlanState,13 deriveActivePlanState,
14 PROVIDER_OPTIONS,
15 derivePendingApprovals,14 derivePendingApprovals,
16 derivePendingUserInputs,15 derivePendingUserInputs,
17 deriveTimelineEntries,16 deriveTimelineEntries,
bun.lock+18
...@@ -67,6 +67,7 @@...@@ -67,6 +67,7 @@
67 "@types/bun": "catalog:",67 "@types/bun": "catalog:",
68 "@types/node": "catalog:",68 "@types/node": "catalog:",
69 "effect-acp": "workspace:*",69 "effect-acp": "workspace:*",
70 "effect-codex-app-server": "workspace:*",
70 "tsdown": "catalog:",71 "tsdown": "catalog:",
71 "typescript": "catalog:",72 "typescript": "catalog:",
72 "vitest": "catalog:",73 "vitest": "catalog:",
...@@ -166,6 +167,21 @@...@@ -166,6 +167,21 @@
166 "vitest": "catalog:",167 "vitest": "catalog:",
167 },168 },
168 },169 },
170 "packages/effect-codex-app-server": {
171 "name": "effect-codex-app-server",
172 "dependencies": {
173 "effect": "catalog:",
174 },
175 "devDependencies": {
176 "@effect/language-service": "catalog:",
177 "@effect/openapi-generator": "catalog:",
178 "@effect/platform-node": "catalog:",
179 "@effect/vitest": "catalog:",
180 "tsdown": "catalog:",
181 "typescript": "catalog:",
182 "vitest": "catalog:",
183 },
184 },
169 "packages/shared": {185 "packages/shared": {
170 "name": "@t3tools/shared",186 "name": "@t3tools/shared",
171 "version": "0.0.0-alpha.1",187 "version": "0.0.0-alpha.1",
...@@ -1083,6 +1099,8 @@...@@ -1083,6 +1099,8 @@
10831099
1084 "effect-acp": ["effect-acp@workspace:packages/effect-acp"],1100 "effect-acp": ["effect-acp@workspace:packages/effect-acp"],
10851101
1102 "effect-codex-app-server": ["effect-codex-app-server@workspace:packages/effect-codex-app-server"],
1103
1086 "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=="],1104 "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=="],
10871105
1088 "electron-to-chromium": ["electron-to-chromium@1.5.313", "", {}, "sha512-QBMrTWEf00GXZmJyx2lbYD45jpI3TUFnNIzJ5BBc8piGUDwMPa1GV6HJWTZVvY/eiN3fSopl7NRbgGp9sZ9LTA=="],1106 "electron-to-chromium": ["electron-to-chromium@1.5.313", "", {}, "sha512-QBMrTWEf00GXZmJyx2lbYD45jpI3TUFnNIzJ5BBc8piGUDwMPa1GV6HJWTZVvY/eiN3fSopl7NRbgGp9sZ9LTA=="],
packages/effect-acp/src/_internal/stdio.ts+5-2
...@@ -9,7 +9,6 @@ import { ChildProcessSpawner } from "effect/unstable/process";...@@ -9,7 +9,6 @@ import { ChildProcessSpawner } from "effect/unstable/process";
9import * as AcpError from "../errors.ts";9import * as AcpError from "../errors.ts";
1010
11const encoder = new TextEncoder();11const encoder = new TextEncoder();
12const decoder = new TextDecoder();
1312
14export const makeChildStdio = (handle: ChildProcessSpawner.ChildProcessHandle) =>13export const makeChildStdio = (handle: ChildProcessSpawner.ChildProcessHandle) =>
15 Stdio.make({14 Stdio.make({
...@@ -25,6 +24,7 @@ export const makeChildStdio = (handle: ChildProcessSpawner.ChildProcessHandle) =...@@ -25,6 +24,7 @@ export const makeChildStdio = (handle: ChildProcessSpawner.ChildProcessHandle) =
25export const makeInMemoryStdio = Effect.fn("makeInMemoryStdio")(function* () {24export const makeInMemoryStdio = Effect.fn("makeInMemoryStdio")(function* () {
26 const input = yield* Queue.unbounded<Uint8Array, Cause.Done<void>>();25 const input = yield* Queue.unbounded<Uint8Array, Cause.Done<void>>();
27 const output = yield* Queue.unbounded<string>();26 const output = yield* Queue.unbounded<string>();
27 const decoder = new TextDecoder();
2828
29 return {29 return {
30 stdio: Stdio.make({30 stdio: Stdio.make({
...@@ -32,7 +32,10 @@ export const makeInMemoryStdio = Effect.fn("makeInMemoryStdio")(function* () {...@@ -32,7 +32,10 @@ export const makeInMemoryStdio = Effect.fn("makeInMemoryStdio")(function* () {
32 stdin: Stream.fromQueue(input),32 stdin: Stream.fromQueue(input),
33 stdout: () =>33 stdout: () =>
34 Sink.forEach((chunk: string | Uint8Array) =>34 Sink.forEach((chunk: string | Uint8Array) =>
35 Queue.offer(output, typeof chunk === "string" ? chunk : decoder.decode(chunk)),35 Queue.offer(
36 output,
37 typeof chunk === "string" ? chunk : decoder.decode(chunk, { stream: true }),
38 ),
36 ),39 ),
37 stderr: () => Sink.drain,40 stderr: () => Sink.drain,
38 }),41 }),
packages/effect-codex-app-server/package.json created+48
...@@ -0,0 +1,48 @@
1{
2 "name": "effect-codex-app-server",
3 "private": true,
4 "type": "module",
5 "exports": {
6 "./client": {
7 "types": "./src/client.ts",
8 "import": "./src/client.ts"
9 },
10 "./schema": {
11 "types": "./src/schema.ts",
12 "import": "./src/schema.ts"
13 },
14 "./rpc": {
15 "types": "./src/rpc.ts",
16 "import": "./src/rpc.ts"
17 },
18 "./protocol": {
19 "types": "./src/protocol.ts",
20 "import": "./src/protocol.ts"
21 },
22 "./errors": {
23 "types": "./src/errors.ts",
24 "import": "./src/errors.ts"
25 }
26 },
27 "scripts": {
28 "dev": "tsdown src/client.ts src/rpc.ts src/protocol.ts src/schema.ts --format esm,cjs --dts --watch --clean",
29 "build": "tsdown src/client.ts src/rpc.ts src/protocol.ts src/schema.ts --format esm,cjs --dts --clean",
30 "prepare": "effect-language-service patch",
31 "typecheck": "tsc --noEmit",
32 "test": "vitest run",
33 "generate": "bun run scripts/generate.ts",
34 "probe": "bun run test/examples/codex-app-server-probe.ts"
35 },
36 "dependencies": {
37 "effect": "catalog:"
38 },
39 "devDependencies": {
40 "@effect/language-service": "catalog:",
41 "@effect/openapi-generator": "catalog:",
42 "@effect/platform-node": "catalog:",
43 "@effect/vitest": "catalog:",
44 "tsdown": "catalog:",
45 "typescript": "catalog:",
46 "vitest": "catalog:"
47 }
48}
packages/effect-codex-app-server/scripts/generate.ts created+772
...@@ -0,0 +1,772 @@
1#!/usr/bin/env node
2
3import * as NodeRuntime from "@effect/platform-node/NodeRuntime";
4import * as NodeServices from "@effect/platform-node/NodeServices";
5import { make as makeJsonSchemaGenerator } from "@effect/openapi-generator/JsonSchemaGenerator";
6import { Effect, FileSystem, Layer, Logger, Path, Schema } from "effect";
7import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
8
9const UPSTREAM_REF = "dbfe855f4fd0f5dcdf079882652a8efe622b0595";
10const USER_AGENT = "effect-codex-app-server-generator";
11const GITHUB_API_BASE =
12 "https://api.github.com/repos/openai/codex/contents/codex-rs/app-server-protocol";
13
14const GithubContentEntries = Schema.Array(
15 Schema.Struct({
16 name: Schema.String,
17 path: Schema.String,
18 download_url: Schema.NullOr(Schema.String),
19 type: Schema.String,
20 }),
21);
22type GithubContentEntry = (typeof GithubContentEntries.Type)[number];
23
24interface GeneratedPaths {
25 readonly generatedDir: string;
26 readonly schemaOutputPath: string;
27 readonly metaOutputPath: string;
28 readonly namespacesOutputPath: string;
29}
30
31interface MethodEntry {
32 readonly method: string;
33 readonly paramsType?: string;
34}
35
36interface JsonSchemaFile {
37 readonly namespace?: string;
38 readonly exportName: string;
39 readonly fileName: string;
40 readonly downloadUrl: string;
41 readonly qualifiedName: string;
42}
43
44class GeneratorError extends Schema.TaggedErrorClass<GeneratorError>()("GeneratorError", {
45 detail: Schema.String,
46 cause: Schema.optional(Schema.Defect),
47}) {
48 override get message() {
49 return this.detail;
50 }
51}
52
53const ManualSchemas: Record<string, typeof Schema.Json.Type> = {
54 GetAuthStatusParams: {
55 type: "object",
56 title: "GetAuthStatusParams",
57 properties: {
58 includeToken: {
59 anyOf: [{ type: "boolean" }, { type: "null" }],
60 },
61 refreshToken: {
62 anyOf: [{ type: "boolean" }, { type: "null" }],
63 },
64 },
65 },
66 GetConversationSummaryParams: {
67 title: "GetConversationSummaryParams",
68 oneOf: [
69 {
70 type: "object",
71 properties: {
72 rolloutPath: { type: "string" },
73 },
74 required: ["rolloutPath"],
75 },
76 {
77 type: "object",
78 properties: {
79 conversationId: { type: "string" },
80 },
81 required: ["conversationId"],
82 },
83 ],
84 },
85 GetConversationSummaryResponse: {
86 type: "object",
87 title: "GetConversationSummaryResponse",
88 properties: {
89 summary: {},
90 },
91 required: ["summary"],
92 },
93 GitDiffToRemoteParams: {
94 type: "object",
95 title: "GitDiffToRemoteParams",
96 properties: {
97 cwd: { type: "string" },
98 },
99 required: ["cwd"],
100 },
101 GitDiffToRemoteResponse: {
102 type: "object",
103 title: "GitDiffToRemoteResponse",
104 properties: {
105 sha: { type: "string" },
106 diff: { type: "string" },
107 },
108 required: ["sha", "diff"],
109 },
110 GetAuthStatusResponse: {
111 type: "object",
112 title: "GetAuthStatusResponse",
113 properties: {
114 authMethod: {
115 anyOf: [{}, { type: "null" }],
116 },
117 authToken: {
118 anyOf: [{ type: "string" }, { type: "null" }],
119 },
120 requiresOpenaiAuth: {
121 anyOf: [{ type: "boolean" }, { type: "null" }],
122 },
123 },
124 required: ["authMethod", "authToken", "requiresOpenaiAuth"],
125 },
126};
127
128const getGeneratedPaths = Effect.fn("getGeneratedPaths")(function* () {
129 const path = yield* Path.Path;
130 const generatedDir = path.join(import.meta.dirname, "..", "src", "_generated");
131 return {
132 generatedDir,
133 schemaOutputPath: path.join(generatedDir, "schema.gen.ts"),
134 metaOutputPath: path.join(generatedDir, "meta.gen.ts"),
135 namespacesOutputPath: path.join(generatedDir, "namespaces.gen.ts"),
136 } satisfies GeneratedPaths;
137});
138
139const ensureGeneratedDir = Effect.fn("ensureGeneratedDir")(function* () {
140 const fs = yield* FileSystem.FileSystem;
141 const { generatedDir } = yield* getGeneratedPaths();
142 yield* fs.makeDirectory(generatedDir, { recursive: true });
143});
144
145const fetchText = Effect.fn("fetchText")(function* (url: string) {
146 const response = yield* Effect.tryPromise({
147 try: () =>
148 fetch(url, {
149 headers: {
150 "user-agent": USER_AGENT,
151 },
152 }),
153 catch: (cause) =>
154 new GeneratorError({
155 detail: `Failed to fetch ${url}`,
156 cause,
157 }),
158 });
159
160 if (!response.ok) {
161 const detail = yield* Effect.tryPromise({
162 try: () => response.text(),
163 catch: () => "",
164 });
165 return yield* Effect.fail(
166 new GeneratorError({
167 detail: `Failed to download ${url}: ${response.status} ${detail}`,
168 }),
169 );
170 }
171
172 return yield* Effect.tryPromise({
173 try: () => response.text(),
174 catch: (cause) =>
175 new GeneratorError({
176 detail: `Failed to read response body for ${url}`,
177 cause,
178 }),
179 });
180});
181
182const fetchDirectoryEntries = Effect.fn("fetchDirectoryEntries")(function* (path: string) {
183 const raw = yield* fetchText(`${GITHUB_API_BASE}/${path}?ref=${UPSTREAM_REF}`);
184 return yield* Schema.decodeEffect(Schema.fromJsonString(GithubContentEntries))(raw);
185});
186
187function collectSchemaEntries(
188 chunk: string,
189): ReadonlyArray<{ readonly name: string; readonly code: string }> {
190 const lines = chunk
191 .split("\n")
192 .map((line) => line.trim())
193 .filter((line) => line.length > 0 && !line.startsWith("//"));
194 const entries: Array<{ name: string; code: string }> = [];
195
196 for (let index = 0; index < lines.length; index += 1) {
197 const typeLine = lines[index];
198 if (!typeLine?.startsWith("export type ")) {
199 continue;
200 }
201
202 const constLine = lines[index + 1];
203 if (!constLine?.startsWith("export const ")) {
204 throw new Error(`Malformed generator output near: ${typeLine}`);
205 }
206
207 const match = /^export type ([A-Za-z0-9_]+)/.exec(typeLine);
208 if (!match?.[1]) {
209 throw new Error(`Could not extract schema name from: ${typeLine}`);
210 }
211
212 entries.push({
213 name: match[1],
214 code: `${typeLine}\n${constLine}`,
215 });
216 index += 1;
217 }
218
219 return entries;
220}
221
222function normalizeNullableTypes(value: typeof Schema.Json.Type): typeof Schema.Json.Type {
223 if (Array.isArray(value)) {
224 return value.map(normalizeNullableTypes);
225 }
226 if (value === null || typeof value !== "object") {
227 return value;
228 }
229
230 const normalizedEntries = Object.entries(value).map(([key, child]) => [
231 key,
232 normalizeNullableTypes(child),
233 ]);
234 const normalizedObject = Object.fromEntries(normalizedEntries) as Record<
235 string,
236 typeof Schema.Json.Type
237 >;
238 const typeValue = normalizedObject.type;
239
240 if (!Array.isArray(typeValue)) {
241 return normalizedObject;
242 }
243
244 const normalizedTypes = typeValue.filter((entry): entry is string => typeof entry === "string");
245 if (normalizedTypes.length !== typeValue.length || !normalizedTypes.includes("null")) {
246 return normalizedObject;
247 }
248
249 const nonNullTypes = normalizedTypes.filter((entry) => entry !== "null");
250 if (nonNullTypes.length !== 1) {
251 return normalizedObject;
252 }
253 const nonNullType = nonNullTypes[0]!;
254
255 const nextObject: Record<string, typeof Schema.Json.Type> = {};
256 for (const [key, child] of Object.entries(normalizedObject)) {
257 if (key !== "type") {
258 nextObject[key] = child;
259 }
260 }
261
262 return {
263 anyOf: [
264 {
265 ...nextObject,
266 type: nonNullType,
267 },
268 { type: "null" },
269 ],
270 };
271}
272
273function stripNullDefaults(value: typeof Schema.Json.Type): typeof Schema.Json.Type {
274 if (Array.isArray(value)) {
275 return value.map(stripNullDefaults);
276 }
277 if (value === null || typeof value !== "object") {
278 return value;
279 }
280
281 return Object.fromEntries(
282 Object.entries(value)
283 .filter(([key, child]) => !(key === "default" && child === null))
284 .map(([key, child]) => [key, stripNullDefaults(child)]),
285 ) as typeof Schema.Json.Type;
286}
287
288function toPascalCaseMethod(method: string) {
289 return method
290 .split("/")
291 .flatMap((segment) => segment.split(/(?=[A-Z])/))
292 .flatMap((segment) => segment.split(/[-_]/))
293 .filter(Boolean)
294 .map((segment) => segment[0]!.toUpperCase() + segment.slice(1))
295 .join("");
296}
297
298function parseRequestEntries(fileContents: string): ReadonlyArray<MethodEntry> {
299 const entryPattern = /\{\s*"method":\s*"([^"]+)",\s*id:\s*RequestId,\s*params:\s*([^,}]+)/g;
300 const entries: Array<MethodEntry> = [];
301 let match: RegExpExecArray | null;
302 while ((match = entryPattern.exec(fileContents)) !== null) {
303 entries.push({
304 method: match[1]!,
305 paramsType: match[2]!.trim(),
306 });
307 }
308 return entries;
309}
310
311function parseNotificationEntries(fileContents: string): ReadonlyArray<MethodEntry> {
312 const entryPattern = /\{\s*"method":\s*"([^"]+)"(?:,\s*"params":\s*([^ }]+))?\s*\}/g;
313 const entries: Array<MethodEntry> = [];
314 let match: RegExpExecArray | null;
315 while ((match = entryPattern.exec(fileContents)) !== null) {
316 entries.push({
317 method: match[1]!,
318 ...(match[2] ? { paramsType: match[2].trim() } : {}),
319 });
320 }
321 return entries;
322}
323
324function resolveSchemaTypeName(
325 rawTypeName: string,
326 generatedSchemaNames: ReadonlySet<string>,
327): string {
328 if (rawTypeName === "undefined") {
329 return "undefined";
330 }
331
332 const candidates = [
333 rawTypeName,
334 `V2${rawTypeName}`,
335 `V1${rawTypeName}`,
336 `SerdeJson${rawTypeName}`,
337 ];
338 for (const candidate of candidates) {
339 if (generatedSchemaNames.has(candidate)) {
340 return candidate;
341 }
342 }
343
344 throw new Error(`Unable to resolve schema type name: ${rawTypeName}`);
345}
346
347function resolveResponseTypeName(
348 method: string,
349 paramsType: string | undefined,
350 generatedSchemaNames: ReadonlySet<string>,
351): string {
352 const overrides: Record<string, string> = {
353 "account/logout": "LogoutAccountResponse",
354 "account/rateLimits/read": "GetAccountRateLimitsResponse",
355 "config/batchWrite": "ConfigWriteResponse",
356 "config/mcpServer/reload": "McpServerRefreshResponse",
357 "config/value/write": "ConfigWriteResponse",
358 "configRequirements/read": "ConfigRequirementsReadResponse",
359 };
360
361 const override = overrides[method];
362 if (override) {
363 return resolveSchemaTypeName(override, generatedSchemaNames);
364 }
365
366 if (paramsType && paramsType !== "undefined") {
367 const fromParams = paramsType.replace(/Params$/, "Response");
368 try {
369 return resolveSchemaTypeName(fromParams, generatedSchemaNames);
370 } catch {
371 // Fall through to method-based lookup.
372 }
373 }
374
375 return resolveSchemaTypeName(`${toPascalCaseMethod(method)}Response`, generatedSchemaNames);
376}
377
378function renderMethodConstants(constantName: string, entries: ReadonlyArray<MethodEntry>) {
379 return [
380 `export const ${constantName} = {`,
381 ...entries.map(
382 (entry) => ` ${JSON.stringify(entry.method)}: ${JSON.stringify(entry.method)},`,
383 ),
384 "} as const;",
385 "",
386 ].join("\n");
387}
388
389function renderTypeInterface(
390 interfaceName: string,
391 entries: ReadonlyArray<MethodEntry>,
392 typeName: (entry: MethodEntry) => string,
393) {
394 return [
395 `export interface ${interfaceName} {`,
396 ...entries.map((entry) => ` readonly ${JSON.stringify(entry.method)}: ${typeName(entry)};`),
397 "}",
398 "",
399 ].join("\n");
400}
401
402function renderSchemaMap(
403 constantName: string,
404 entries: ReadonlyArray<MethodEntry>,
405 typeName: (entry: MethodEntry) => string,
406) {
407 return [
408 `export const ${constantName} = {`,
409 ...entries.map((entry) => {
410 const schemaName = typeName(entry);
411 return ` ${JSON.stringify(entry.method)}: ${
412 schemaName === "undefined" ? "undefined" : `CodexSchema.${schemaName}`
413 },`;
414 }),
415 "} as const;",
416 "",
417 ].join("\n");
418}
419
420function renderSchemaTypeReference(schemaName: string) {
421 return schemaName === "undefined" ? "undefined" : `typeof CodexSchema.${schemaName}.Type`;
422}
423
424function exportNameForPath(filePath: string): string {
425 const relative = filePath.replace(/^schema\/json\//, "").replace(/\.json$/, "");
426 if (!relative.includes("/")) {
427 return relative;
428 }
429
430 const [namespace, name] = relative.split("/", 2) as [string, string];
431 const namespacePrefix = namespace
432 .split(/[^A-Za-z0-9]+/)
433 .filter(Boolean)
434 .map((segment) => segment[0]!.toUpperCase() + segment.slice(1))
435 .join("");
436 return `${namespacePrefix}${name}`;
437}
438
439function buildJsonSchemaFiles(
440 entries: ReadonlyArray<GithubContentEntry>,
441): ReadonlyArray<JsonSchemaFile> {
442 return entries
443 .filter(
444 (entry) =>
445 entry.type === "file" &&
446 entry.name.endsWith(".json") &&
447 entry.download_url !== null &&
448 !entry.name.startsWith("codex_app_server_protocol."),
449 )
450 .map((entry) => {
451 const relative = entry.path.replace(/^codex-rs\/app-server-protocol\/schema\/json\//, "");
452 const parts = relative.split("/");
453 if (parts.length > 1) {
454 return {
455 namespace: parts[0]!,
456 exportName: exportNameForPath(relative),
457 fileName: entry.name,
458 downloadUrl: entry.download_url!,
459 qualifiedName: relative.replace(/\.json$/, ""),
460 } satisfies JsonSchemaFile;
461 }
462 return {
463 exportName: exportNameForPath(relative),
464 fileName: entry.name,
465 downloadUrl: entry.download_url!,
466 qualifiedName: relative.replace(/\.json$/, ""),
467 } satisfies JsonSchemaFile;
468 });
469}
470
471function rewriteExternalRefs(
472 value: typeof Schema.Json.Type,
473 localDefinitionNames: ReadonlyMap<string, string>,
474 currentNamespace: string | undefined,
475 exportNameByQualifiedName: ReadonlyMap<string, string>,
476): typeof Schema.Json.Type {
477 if (Array.isArray(value)) {
478 return value.map((entry) =>
479 rewriteExternalRefs(entry, localDefinitionNames, currentNamespace, exportNameByQualifiedName),
480 );
481 }
482 if (value === null || typeof value !== "object") {
483 return value;
484 }
485
486 return Object.fromEntries(
487 Object.entries(value).map(([key, child]) => {
488 if (key === "$ref" && typeof child === "string" && child.startsWith("#/definitions/")) {
489 const definitionName = child.slice("#/definitions/".length);
490 const localRewrite = localDefinitionNames.get(definitionName);
491 if (localRewrite) {
492 return [key, `#/definitions/${localRewrite}`];
493 }
494
495 const candidates = [
496 ...(currentNamespace ? [`${currentNamespace}/${definitionName}`] : []),
497 definitionName,
498 definitionName.replace(/^v[12]\//, ""),
499 definitionName.replace(/^serde_json\//, ""),
500 `v2/${definitionName}`,
501 `v1/${definitionName}`,
502 `serde_json/${definitionName}`,
503 ];
504
505 const rewritten = candidates
506 .map((candidate) => exportNameByQualifiedName.get(candidate))
507 .find((candidate) => candidate !== undefined);
508
509 if (!rewritten) {
510 throw new Error(`Missing rewritten definition for ref: ${child}`);
511 }
512
513 return [key, `#/definitions/${rewritten}`];
514 }
515
516 return [
517 key,
518 rewriteExternalRefs(
519 child,
520 localDefinitionNames,
521 currentNamespace,
522 exportNameByQualifiedName,
523 ),
524 ];
525 }),
526 ) as typeof Schema.Json.Type;
527}
528
529const generateFiles = Effect.fn("generateFiles")(function* () {
530 yield* ensureGeneratedDir();
531
532 const [rootJsonEntries, v1JsonEntries, v2JsonEntries] = yield* Effect.all([
533 fetchDirectoryEntries("schema/json"),
534 fetchDirectoryEntries("schema/json/v1"),
535 fetchDirectoryEntries("schema/json/v2"),
536 ]);
537
538 const jsonSchemaFiles = [
539 ...buildJsonSchemaFiles(rootJsonEntries),
540 ...buildJsonSchemaFiles(v1JsonEntries),
541 ...buildJsonSchemaFiles(v2JsonEntries),
542 ].toSorted((left, right) => left.exportName.localeCompare(right.exportName));
543
544 const exportNameByQualifiedName = new Map(
545 jsonSchemaFiles.map((file) => [file.qualifiedName, file.exportName]),
546 );
547 const aggregateSchemas: Record<string, typeof Schema.Json.Type> = {};
548
549 for (const file of jsonSchemaFiles) {
550 const raw = yield* fetchText(file.downloadUrl);
551 const parsed = JSON.parse(raw) as {
552 readonly definitions?: Record<string, typeof Schema.Json.Type>;
553 } & Record<string, typeof Schema.Json.Type>;
554 const localDefinitionNames = new Map(
555 Object.keys(parsed.definitions ?? {}).map((definitionName) => [
556 definitionName,
557 `${file.exportName}__${definitionName.replace(/[^A-Za-z0-9]/g, "")}`,
558 ]),
559 );
560
561 for (const [definitionName, definitionSchema] of Object.entries(parsed.definitions ?? {})) {
562 aggregateSchemas[localDefinitionNames.get(definitionName)!] = stripNullDefaults(
563 normalizeNullableTypes(
564 rewriteExternalRefs(
565 definitionSchema,
566 localDefinitionNames,
567 file.namespace,
568 exportNameByQualifiedName,
569 ),
570 ),
571 );
572 }
573
574 const topLevelSchema: Record<string, typeof Schema.Json.Type> = {};
575 for (const [key, value] of Object.entries(parsed)) {
576 if (key !== "definitions") {
577 topLevelSchema[key] = value;
578 }
579 }
580
581 aggregateSchemas[file.exportName] = stripNullDefaults(
582 normalizeNullableTypes(
583 rewriteExternalRefs(
584 topLevelSchema,
585 localDefinitionNames,
586 file.namespace,
587 exportNameByQualifiedName,
588 ),
589 ),
590 );
591 }
592
593 for (const [name, schema] of Object.entries(ManualSchemas)) {
594 if (!(name in aggregateSchemas)) {
595 aggregateSchemas[name] = stripNullDefaults(normalizeNullableTypes(schema));
596 }
597 }
598
599 const generator = makeJsonSchemaGenerator();
600 for (const [name, schema] of Object.entries(aggregateSchemas).toSorted(([left], [right]) =>
601 left.localeCompare(right),
602 )) {
603 generator.addSchema(name, schema as never);
604 }
605
606 const generatedEntries = new Map<string, string>();
607 const output = generator.generate("openapi-3.1", aggregateSchemas as never, false).trim();
608 if (output.length > 0) {
609 for (const entry of collectSchemaEntries(output)) {
610 if (!generatedEntries.has(entry.name)) {
611 generatedEntries.set(entry.name, entry.code);
612 }
613 }
614 }
615
616 const generatedSchemaNames = new Set(generatedEntries.keys());
617 const clientRequestRaw = yield* fetchText(
618 `https://raw.githubusercontent.com/openai/codex/${UPSTREAM_REF}/codex-rs/app-server-protocol/schema/typescript/ClientRequest.ts`,
619 );
620 const clientNotificationRaw = yield* fetchText(
621 `https://raw.githubusercontent.com/openai/codex/${UPSTREAM_REF}/codex-rs/app-server-protocol/schema/typescript/ClientNotification.ts`,
622 );
623 const serverRequestRaw = yield* fetchText(
624 `https://raw.githubusercontent.com/openai/codex/${UPSTREAM_REF}/codex-rs/app-server-protocol/schema/typescript/ServerRequest.ts`,
625 );
626 const serverNotificationRaw = yield* fetchText(
627 `https://raw.githubusercontent.com/openai/codex/${UPSTREAM_REF}/codex-rs/app-server-protocol/schema/typescript/ServerNotification.ts`,
628 );
629
630 const clientRequestEntries = parseRequestEntries(clientRequestRaw);
631 const clientNotificationEntries = parseNotificationEntries(clientNotificationRaw);
632 const serverRequestEntries = parseRequestEntries(serverRequestRaw);
633 const serverNotificationEntries = parseNotificationEntries(serverNotificationRaw);
634
635 const prelude = [
636 "// This file is generated by the effect-codex-app-server package. Do not edit manually.",
637 `// Upstream protocol ref: ${UPSTREAM_REF}`,
638 "",
639 ];
640
641 const schemaOutput = [
642 ...prelude,
643 'import * as Schema from "effect/Schema";',
644 "",
645 [...generatedEntries.values()].join("\n\n"),
646 "",
647 ].join("\n");
648
649 const metaOutput = [
650 ...prelude,
651 'import * as CodexSchema from "./schema.gen.ts";',
652 "",
653 renderMethodConstants("CLIENT_REQUEST_METHODS", clientRequestEntries),
654 renderMethodConstants("CLIENT_NOTIFICATION_METHODS", clientNotificationEntries),
655 renderMethodConstants("SERVER_REQUEST_METHODS", serverRequestEntries),
656 renderMethodConstants("SERVER_NOTIFICATION_METHODS", serverNotificationEntries),
657 "export type ClientRequestMethod = keyof typeof CLIENT_REQUEST_METHODS;",
658 "export type ClientNotificationMethod = keyof typeof CLIENT_NOTIFICATION_METHODS;",
659 "export type ServerRequestMethod = keyof typeof SERVER_REQUEST_METHODS;",
660 "export type ServerNotificationMethod = keyof typeof SERVER_NOTIFICATION_METHODS;",
661 "",
662 renderTypeInterface("ClientRequestParamsByMethod", clientRequestEntries, (entry) =>
663 renderSchemaTypeReference(
664 resolveSchemaTypeName(entry.paramsType ?? "undefined", generatedSchemaNames),
665 ),
666 ),
667 renderTypeInterface("ClientRequestResponsesByMethod", clientRequestEntries, (entry) =>
668 renderSchemaTypeReference(
669 resolveResponseTypeName(entry.method, entry.paramsType, generatedSchemaNames),
670 ),
671 ),
672 renderTypeInterface("ClientNotificationParamsByMethod", clientNotificationEntries, (entry) =>
673 renderSchemaTypeReference(
674 resolveSchemaTypeName(entry.paramsType ?? "undefined", generatedSchemaNames),
675 ),
676 ),
677 renderTypeInterface("ServerRequestParamsByMethod", serverRequestEntries, (entry) =>
678 renderSchemaTypeReference(
679 resolveSchemaTypeName(entry.paramsType ?? "undefined", generatedSchemaNames),
680 ),
681 ),
682 renderTypeInterface("ServerRequestResponsesByMethod", serverRequestEntries, (entry) =>
683 renderSchemaTypeReference(
684 resolveResponseTypeName(entry.method, entry.paramsType, generatedSchemaNames),
685 ),
686 ),
687 renderTypeInterface("ServerNotificationParamsByMethod", serverNotificationEntries, (entry) =>
688 renderSchemaTypeReference(
689 resolveSchemaTypeName(entry.paramsType ?? "undefined", generatedSchemaNames),
690 ),
691 ),
692 renderSchemaMap("CLIENT_REQUEST_PARAMS", clientRequestEntries, (entry) =>
693 resolveSchemaTypeName(entry.paramsType ?? "undefined", generatedSchemaNames),
694 ),
695 renderSchemaMap("CLIENT_REQUEST_RESPONSES", clientRequestEntries, (entry) =>
696 resolveResponseTypeName(entry.method, entry.paramsType, generatedSchemaNames),
697 ),
698 renderSchemaMap("CLIENT_NOTIFICATION_PARAMS", clientNotificationEntries, (entry) =>
699 resolveSchemaTypeName(entry.paramsType ?? "undefined", generatedSchemaNames),
700 ),
701 renderSchemaMap("SERVER_REQUEST_PARAMS", serverRequestEntries, (entry) =>
702 resolveSchemaTypeName(entry.paramsType ?? "undefined", generatedSchemaNames),
703 ),
704 renderSchemaMap("SERVER_REQUEST_RESPONSES", serverRequestEntries, (entry) =>
705 resolveResponseTypeName(entry.method, entry.paramsType, generatedSchemaNames),
706 ),
707 renderSchemaMap("SERVER_NOTIFICATION_PARAMS", serverNotificationEntries, (entry) =>
708 resolveSchemaTypeName(entry.paramsType ?? "undefined", generatedSchemaNames),
709 ),
710 ].join("\n");
711
712 const namespaceGroups = new Map<string, Array<JsonSchemaFile>>();
713 for (const file of jsonSchemaFiles) {
714 if (!file.namespace) {
715 continue;
716 }
717 const current = namespaceGroups.get(file.namespace) ?? [];
718 current.push(file);
719 namespaceGroups.set(file.namespace, current);
720 }
721
722 const namespacesOutput = [
723 ...prelude,
724 'import * as CodexSchema from "./schema.gen.ts";',
725 "",
726 ...[...namespaceGroups.entries()]
727 .toSorted(([left], [right]) => left.localeCompare(right))
728 .map(([namespace, files]) => {
729 const constantName = namespace.replace(/[^A-Za-z0-9]/g, "");
730 return [
731 `export const ${constantName} = {`,
732 ...files
733 .toSorted((left, right) => left.fileName.localeCompare(right.fileName))
734 .map(
735 (file) =>
736 ` ${JSON.stringify(file.fileName.replace(/\.json$/, ""))}: CodexSchema.${file.exportName},`,
737 ),
738 "} as const;",
739 "",
740 ].join("\n");
741 }),
742 ].join("\n");
743
744 const fs = yield* FileSystem.FileSystem;
745 const { generatedDir, metaOutputPath, namespacesOutputPath, schemaOutputPath } =
746 yield* getGeneratedPaths();
747 yield* fs.writeFileString(schemaOutputPath, schemaOutput);
748 yield* fs.writeFileString(metaOutputPath, metaOutput);
749 yield* fs.writeFileString(namespacesOutputPath, namespacesOutput);
750
751 yield* Effect.log(`Generated Codex App Server schemas from ${UPSTREAM_REF}`);
752
753 yield* Effect.service(ChildProcessSpawner.ChildProcessSpawner).pipe(
754 Effect.flatMap((spawner) => spawner.spawn(ChildProcess.make("bun", ["oxfmt", generatedDir]))),
755 Effect.flatMap((child) => child.exitCode),
756 Effect.tap((code) =>
757 code === 0
758 ? Effect.void
759 : Effect.fail(
760 new GeneratorError({
761 detail: `oxfmt failed with exit code ${code}`,
762 }),
763 ),
764 ),
765 );
766});
767
768generateFiles().pipe(
769 Effect.scoped,
770 Effect.provide(Layer.mergeAll(Logger.layer([Logger.consolePretty()]), NodeServices.layer)),
771 NodeRuntime.runMain,
772);
packages/effect-codex-app-server/src/_generated/meta.gen.ts created+585
...@@ -0,0 +1,585 @@
1// This file is generated by the effect-codex-app-server package. Do not edit manually.
2// Upstream protocol ref: dbfe855f4fd0f5dcdf079882652a8efe622b0595
3
4import * as CodexSchema from "./schema.gen.ts";
5
6export const CLIENT_REQUEST_METHODS = {
7 initialize: "initialize",
8 "thread/start": "thread/start",
9 "thread/resume": "thread/resume",
10 "thread/fork": "thread/fork",
11 "thread/archive": "thread/archive",
12 "thread/unsubscribe": "thread/unsubscribe",
13 "thread/name/set": "thread/name/set",
14 "thread/metadata/update": "thread/metadata/update",
15 "thread/unarchive": "thread/unarchive",
16 "thread/compact/start": "thread/compact/start",
17 "thread/shellCommand": "thread/shellCommand",
18 "thread/rollback": "thread/rollback",
19 "thread/list": "thread/list",
20 "thread/loaded/list": "thread/loaded/list",
21 "thread/read": "thread/read",
22 "skills/list": "skills/list",
23 "plugin/list": "plugin/list",
24 "plugin/read": "plugin/read",
25 "app/list": "app/list",
26 "fs/readFile": "fs/readFile",
27 "fs/writeFile": "fs/writeFile",
28 "fs/createDirectory": "fs/createDirectory",
29 "fs/getMetadata": "fs/getMetadata",
30 "fs/readDirectory": "fs/readDirectory",
31 "fs/remove": "fs/remove",
32 "fs/copy": "fs/copy",
33 "fs/watch": "fs/watch",
34 "fs/unwatch": "fs/unwatch",
35 "skills/config/write": "skills/config/write",
36 "plugin/install": "plugin/install",
37 "plugin/uninstall": "plugin/uninstall",
38 "turn/start": "turn/start",
39 "turn/steer": "turn/steer",
40 "turn/interrupt": "turn/interrupt",
41 "review/start": "review/start",
42 "model/list": "model/list",
43 "experimentalFeature/list": "experimentalFeature/list",
44 "experimentalFeature/enablement/set": "experimentalFeature/enablement/set",
45 "mcpServer/oauth/login": "mcpServer/oauth/login",
46 "config/mcpServer/reload": "config/mcpServer/reload",
47 "mcpServerStatus/list": "mcpServerStatus/list",
48 "mcpServer/resource/read": "mcpServer/resource/read",
49 "mcpServer/tool/call": "mcpServer/tool/call",
50 "windowsSandbox/setupStart": "windowsSandbox/setupStart",
51 "account/login/start": "account/login/start",
52 "account/login/cancel": "account/login/cancel",
53 "account/logout": "account/logout",
54 "account/rateLimits/read": "account/rateLimits/read",
55 "feedback/upload": "feedback/upload",
56 "command/exec": "command/exec",
57 "command/exec/write": "command/exec/write",
58 "command/exec/terminate": "command/exec/terminate",
59 "command/exec/resize": "command/exec/resize",
60 "config/read": "config/read",
61 "externalAgentConfig/detect": "externalAgentConfig/detect",
62 "externalAgentConfig/import": "externalAgentConfig/import",
63 "config/value/write": "config/value/write",
64 "config/batchWrite": "config/batchWrite",
65 "configRequirements/read": "configRequirements/read",
66 "account/read": "account/read",
67 getConversationSummary: "getConversationSummary",
68 gitDiffToRemote: "gitDiffToRemote",
69 getAuthStatus: "getAuthStatus",
70 fuzzyFileSearch: "fuzzyFileSearch",
71} as const;
72
73export const CLIENT_NOTIFICATION_METHODS = {
74 initialized: "initialized",
75} as const;
76
77export const SERVER_REQUEST_METHODS = {
78 "item/commandExecution/requestApproval": "item/commandExecution/requestApproval",
79 "item/fileChange/requestApproval": "item/fileChange/requestApproval",
80 "item/tool/requestUserInput": "item/tool/requestUserInput",
81 "mcpServer/elicitation/request": "mcpServer/elicitation/request",
82 "item/permissions/requestApproval": "item/permissions/requestApproval",
83 "item/tool/call": "item/tool/call",
84 "account/chatgptAuthTokens/refresh": "account/chatgptAuthTokens/refresh",
85 applyPatchApproval: "applyPatchApproval",
86 execCommandApproval: "execCommandApproval",
87} as const;
88
89export const SERVER_NOTIFICATION_METHODS = {
90 error: "error",
91 "thread/started": "thread/started",
92 "thread/status/changed": "thread/status/changed",
93 "thread/archived": "thread/archived",
94 "thread/unarchived": "thread/unarchived",
95 "thread/closed": "thread/closed",
96 "skills/changed": "skills/changed",
97 "thread/name/updated": "thread/name/updated",
98 "thread/tokenUsage/updated": "thread/tokenUsage/updated",
99 "turn/started": "turn/started",
100 "hook/started": "hook/started",
101 "turn/completed": "turn/completed",
102 "hook/completed": "hook/completed",
103 "turn/diff/updated": "turn/diff/updated",
104 "turn/plan/updated": "turn/plan/updated",
105 "item/started": "item/started",
106 "item/autoApprovalReview/started": "item/autoApprovalReview/started",
107 "item/autoApprovalReview/completed": "item/autoApprovalReview/completed",
108 "item/completed": "item/completed",
109 "rawResponseItem/completed": "rawResponseItem/completed",
110 "item/agentMessage/delta": "item/agentMessage/delta",
111 "item/plan/delta": "item/plan/delta",
112 "command/exec/outputDelta": "command/exec/outputDelta",
113 "item/commandExecution/outputDelta": "item/commandExecution/outputDelta",
114 "item/commandExecution/terminalInteraction": "item/commandExecution/terminalInteraction",
115 "item/fileChange/outputDelta": "item/fileChange/outputDelta",
116 "serverRequest/resolved": "serverRequest/resolved",
117 "item/mcpToolCall/progress": "item/mcpToolCall/progress",
118 "mcpServer/oauthLogin/completed": "mcpServer/oauthLogin/completed",
119 "mcpServer/startupStatus/updated": "mcpServer/startupStatus/updated",
120 "account/updated": "account/updated",
121 "account/rateLimits/updated": "account/rateLimits/updated",
122 "app/list/updated": "app/list/updated",
123 "fs/changed": "fs/changed",
124 "item/reasoning/summaryTextDelta": "item/reasoning/summaryTextDelta",
125 "item/reasoning/summaryPartAdded": "item/reasoning/summaryPartAdded",
126 "item/reasoning/textDelta": "item/reasoning/textDelta",
127 "thread/compacted": "thread/compacted",
128 "model/rerouted": "model/rerouted",
129 deprecationNotice: "deprecationNotice",
130 configWarning: "configWarning",
131 "fuzzyFileSearch/sessionUpdated": "fuzzyFileSearch/sessionUpdated",
132 "fuzzyFileSearch/sessionCompleted": "fuzzyFileSearch/sessionCompleted",
133 "thread/realtime/started": "thread/realtime/started",
134 "thread/realtime/itemAdded": "thread/realtime/itemAdded",
135 "thread/realtime/transcriptUpdated": "thread/realtime/transcriptUpdated",
136 "thread/realtime/outputAudio/delta": "thread/realtime/outputAudio/delta",
137 "thread/realtime/sdp": "thread/realtime/sdp",
138 "thread/realtime/error": "thread/realtime/error",
139 "thread/realtime/closed": "thread/realtime/closed",
140 "windows/worldWritableWarning": "windows/worldWritableWarning",
141 "windowsSandbox/setupCompleted": "windowsSandbox/setupCompleted",
142 "account/login/completed": "account/login/completed",
143} as const;
144
145export type ClientRequestMethod = keyof typeof CLIENT_REQUEST_METHODS;
146export type ClientNotificationMethod = keyof typeof CLIENT_NOTIFICATION_METHODS;
147export type ServerRequestMethod = keyof typeof SERVER_REQUEST_METHODS;
148export type ServerNotificationMethod = keyof typeof SERVER_NOTIFICATION_METHODS;
149
150export interface ClientRequestParamsByMethod {
151 readonly initialize: typeof CodexSchema.V1InitializeParams.Type;
152 readonly "thread/start": typeof CodexSchema.V2ThreadStartParams.Type;
153 readonly "thread/resume": typeof CodexSchema.V2ThreadResumeParams.Type;
154 readonly "thread/fork": typeof CodexSchema.V2ThreadForkParams.Type;
155 readonly "thread/archive": typeof CodexSchema.V2ThreadArchiveParams.Type;
156 readonly "thread/unsubscribe": typeof CodexSchema.V2ThreadUnsubscribeParams.Type;
157 readonly "thread/name/set": typeof CodexSchema.V2ThreadSetNameParams.Type;
158 readonly "thread/metadata/update": typeof CodexSchema.V2ThreadMetadataUpdateParams.Type;
159 readonly "thread/unarchive": typeof CodexSchema.V2ThreadUnarchiveParams.Type;
160 readonly "thread/compact/start": typeof CodexSchema.V2ThreadCompactStartParams.Type;
161 readonly "thread/shellCommand": typeof CodexSchema.V2ThreadShellCommandParams.Type;
162 readonly "thread/rollback": typeof CodexSchema.V2ThreadRollbackParams.Type;
163 readonly "thread/list": typeof CodexSchema.V2ThreadListParams.Type;
164 readonly "thread/loaded/list": typeof CodexSchema.V2ThreadLoadedListParams.Type;
165 readonly "thread/read": typeof CodexSchema.V2ThreadReadParams.Type;
166 readonly "skills/list": typeof CodexSchema.V2SkillsListParams.Type;
167 readonly "plugin/list": typeof CodexSchema.V2PluginListParams.Type;
168 readonly "plugin/read": typeof CodexSchema.V2PluginReadParams.Type;
169 readonly "app/list": typeof CodexSchema.V2AppsListParams.Type;
170 readonly "fs/readFile": typeof CodexSchema.V2FsReadFileParams.Type;
171 readonly "fs/writeFile": typeof CodexSchema.V2FsWriteFileParams.Type;
172 readonly "fs/createDirectory": typeof CodexSchema.V2FsCreateDirectoryParams.Type;
173 readonly "fs/getMetadata": typeof CodexSchema.V2FsGetMetadataParams.Type;
174 readonly "fs/readDirectory": typeof CodexSchema.V2FsReadDirectoryParams.Type;
175 readonly "fs/remove": typeof CodexSchema.V2FsRemoveParams.Type;
176 readonly "fs/copy": typeof CodexSchema.V2FsCopyParams.Type;
177 readonly "fs/watch": typeof CodexSchema.V2FsWatchParams.Type;
178 readonly "fs/unwatch": typeof CodexSchema.V2FsUnwatchParams.Type;
179 readonly "skills/config/write": typeof CodexSchema.V2SkillsConfigWriteParams.Type;
180 readonly "plugin/install": typeof CodexSchema.V2PluginInstallParams.Type;
181 readonly "plugin/uninstall": typeof CodexSchema.V2PluginUninstallParams.Type;
182 readonly "turn/start": typeof CodexSchema.V2TurnStartParams.Type;
183 readonly "turn/steer": typeof CodexSchema.V2TurnSteerParams.Type;
184 readonly "turn/interrupt": typeof CodexSchema.V2TurnInterruptParams.Type;
185 readonly "review/start": typeof CodexSchema.V2ReviewStartParams.Type;
186 readonly "model/list": typeof CodexSchema.V2ModelListParams.Type;
187 readonly "experimentalFeature/list": typeof CodexSchema.V2ExperimentalFeatureListParams.Type;
188 readonly "experimentalFeature/enablement/set": typeof CodexSchema.V2ExperimentalFeatureEnablementSetParams.Type;
189 readonly "mcpServer/oauth/login": typeof CodexSchema.V2McpServerOauthLoginParams.Type;
190 readonly "config/mcpServer/reload": undefined;
191 readonly "mcpServerStatus/list": typeof CodexSchema.V2ListMcpServerStatusParams.Type;
192 readonly "mcpServer/resource/read": typeof CodexSchema.V2McpResourceReadParams.Type;
193 readonly "mcpServer/tool/call": typeof CodexSchema.V2McpServerToolCallParams.Type;
194 readonly "windowsSandbox/setupStart": typeof CodexSchema.V2WindowsSandboxSetupStartParams.Type;
195 readonly "account/login/start": typeof CodexSchema.V2LoginAccountParams.Type;
196 readonly "account/login/cancel": typeof CodexSchema.V2CancelLoginAccountParams.Type;
197 readonly "account/logout": undefined;
198 readonly "account/rateLimits/read": undefined;
199 readonly "feedback/upload": typeof CodexSchema.V2FeedbackUploadParams.Type;
200 readonly "command/exec": typeof CodexSchema.V2CommandExecParams.Type;
201 readonly "command/exec/write": typeof CodexSchema.V2CommandExecWriteParams.Type;
202 readonly "command/exec/terminate": typeof CodexSchema.V2CommandExecTerminateParams.Type;
203 readonly "command/exec/resize": typeof CodexSchema.V2CommandExecResizeParams.Type;
204 readonly "config/read": typeof CodexSchema.V2ConfigReadParams.Type;
205 readonly "externalAgentConfig/detect": typeof CodexSchema.V2ExternalAgentConfigDetectParams.Type;
206 readonly "externalAgentConfig/import": typeof CodexSchema.V2ExternalAgentConfigImportParams.Type;
207 readonly "config/value/write": typeof CodexSchema.V2ConfigValueWriteParams.Type;
208 readonly "config/batchWrite": typeof CodexSchema.V2ConfigBatchWriteParams.Type;
209 readonly "configRequirements/read": undefined;
210 readonly "account/read": typeof CodexSchema.V2GetAccountParams.Type;
211 readonly getConversationSummary: typeof CodexSchema.GetConversationSummaryParams.Type;
212 readonly gitDiffToRemote: typeof CodexSchema.GitDiffToRemoteParams.Type;
213 readonly getAuthStatus: typeof CodexSchema.GetAuthStatusParams.Type;
214 readonly fuzzyFileSearch: typeof CodexSchema.FuzzyFileSearchParams.Type;
215}
216
217export interface ClientRequestResponsesByMethod {
218 readonly initialize: typeof CodexSchema.V1InitializeResponse.Type;
219 readonly "thread/start": typeof CodexSchema.V2ThreadStartResponse.Type;
220 readonly "thread/resume": typeof CodexSchema.V2ThreadResumeResponse.Type;
221 readonly "thread/fork": typeof CodexSchema.V2ThreadForkResponse.Type;
222 readonly "thread/archive": typeof CodexSchema.V2ThreadArchiveResponse.Type;
223 readonly "thread/unsubscribe": typeof CodexSchema.V2ThreadUnsubscribeResponse.Type;
224 readonly "thread/name/set": typeof CodexSchema.V2ThreadSetNameResponse.Type;
225 readonly "thread/metadata/update": typeof CodexSchema.V2ThreadMetadataUpdateResponse.Type;
226 readonly "thread/unarchive": typeof CodexSchema.V2ThreadUnarchiveResponse.Type;
227 readonly "thread/compact/start": typeof CodexSchema.V2ThreadCompactStartResponse.Type;
228 readonly "thread/shellCommand": typeof CodexSchema.V2ThreadShellCommandResponse.Type;
229 readonly "thread/rollback": typeof CodexSchema.V2ThreadRollbackResponse.Type;
230 readonly "thread/list": typeof CodexSchema.V2ThreadListResponse.Type;
231 readonly "thread/loaded/list": typeof CodexSchema.V2ThreadLoadedListResponse.Type;
232 readonly "thread/read": typeof CodexSchema.V2ThreadReadResponse.Type;
233 readonly "skills/list": typeof CodexSchema.V2SkillsListResponse.Type;
234 readonly "plugin/list": typeof CodexSchema.V2PluginListResponse.Type;
235 readonly "plugin/read": typeof CodexSchema.V2PluginReadResponse.Type;
236 readonly "app/list": typeof CodexSchema.V2AppsListResponse.Type;
237 readonly "fs/readFile": typeof CodexSchema.V2FsReadFileResponse.Type;
238 readonly "fs/writeFile": typeof CodexSchema.V2FsWriteFileResponse.Type;
239 readonly "fs/createDirectory": typeof CodexSchema.V2FsCreateDirectoryResponse.Type;
240 readonly "fs/getMetadata": typeof CodexSchema.V2FsGetMetadataResponse.Type;
241 readonly "fs/readDirectory": typeof CodexSchema.V2FsReadDirectoryResponse.Type;
242 readonly "fs/remove": typeof CodexSchema.V2FsRemoveResponse.Type;
243 readonly "fs/copy": typeof CodexSchema.V2FsCopyResponse.Type;
244 readonly "fs/watch": typeof CodexSchema.V2FsWatchResponse.Type;
245 readonly "fs/unwatch": typeof CodexSchema.V2FsUnwatchResponse.Type;
246 readonly "skills/config/write": typeof CodexSchema.V2SkillsConfigWriteResponse.Type;
247 readonly "plugin/install": typeof CodexSchema.V2PluginInstallResponse.Type;
248 readonly "plugin/uninstall": typeof CodexSchema.V2PluginUninstallResponse.Type;
249 readonly "turn/start": typeof CodexSchema.V2TurnStartResponse.Type;
250 readonly "turn/steer": typeof CodexSchema.V2TurnSteerResponse.Type;
251 readonly "turn/interrupt": typeof CodexSchema.V2TurnInterruptResponse.Type;
252 readonly "review/start": typeof CodexSchema.V2ReviewStartResponse.Type;
253 readonly "model/list": typeof CodexSchema.V2ModelListResponse.Type;
254 readonly "experimentalFeature/list": typeof CodexSchema.V2ExperimentalFeatureListResponse.Type;
255 readonly "experimentalFeature/enablement/set": typeof CodexSchema.V2ExperimentalFeatureEnablementSetResponse.Type;
256 readonly "mcpServer/oauth/login": typeof CodexSchema.V2McpServerOauthLoginResponse.Type;
257 readonly "config/mcpServer/reload": typeof CodexSchema.V2McpServerRefreshResponse.Type;
258 readonly "mcpServerStatus/list": typeof CodexSchema.V2ListMcpServerStatusResponse.Type;
259 readonly "mcpServer/resource/read": typeof CodexSchema.V2McpResourceReadResponse.Type;
260 readonly "mcpServer/tool/call": typeof CodexSchema.V2McpServerToolCallResponse.Type;
261 readonly "windowsSandbox/setupStart": typeof CodexSchema.V2WindowsSandboxSetupStartResponse.Type;
262 readonly "account/login/start": typeof CodexSchema.V2LoginAccountResponse.Type;
263 readonly "account/login/cancel": typeof CodexSchema.V2CancelLoginAccountResponse.Type;
264 readonly "account/logout": typeof CodexSchema.V2LogoutAccountResponse.Type;
265 readonly "account/rateLimits/read": typeof CodexSchema.V2GetAccountRateLimitsResponse.Type;
266 readonly "feedback/upload": typeof CodexSchema.V2FeedbackUploadResponse.Type;
267 readonly "command/exec": typeof CodexSchema.V2CommandExecResponse.Type;
268 readonly "command/exec/write": typeof CodexSchema.V2CommandExecWriteResponse.Type;
269 readonly "command/exec/terminate": typeof CodexSchema.V2CommandExecTerminateResponse.Type;
270 readonly "command/exec/resize": typeof CodexSchema.V2CommandExecResizeResponse.Type;
271 readonly "config/read": typeof CodexSchema.V2ConfigReadResponse.Type;
272 readonly "externalAgentConfig/detect": typeof CodexSchema.V2ExternalAgentConfigDetectResponse.Type;
273 readonly "externalAgentConfig/import": typeof CodexSchema.V2ExternalAgentConfigImportResponse.Type;
274 readonly "config/value/write": typeof CodexSchema.V2ConfigWriteResponse.Type;
275 readonly "config/batchWrite": typeof CodexSchema.V2ConfigWriteResponse.Type;
276 readonly "configRequirements/read": typeof CodexSchema.V2ConfigRequirementsReadResponse.Type;
277 readonly "account/read": typeof CodexSchema.V2GetAccountResponse.Type;
278 readonly getConversationSummary: typeof CodexSchema.GetConversationSummaryResponse.Type;
279 readonly gitDiffToRemote: typeof CodexSchema.GitDiffToRemoteResponse.Type;
280 readonly getAuthStatus: typeof CodexSchema.GetAuthStatusResponse.Type;
281 readonly fuzzyFileSearch: typeof CodexSchema.FuzzyFileSearchResponse.Type;
282}
283
284export interface ClientNotificationParamsByMethod {
285 readonly initialized: undefined;
286}
287
288export interface ServerRequestParamsByMethod {
289 readonly "item/commandExecution/requestApproval": typeof CodexSchema.CommandExecutionRequestApprovalParams.Type;
290 readonly "item/fileChange/requestApproval": typeof CodexSchema.FileChangeRequestApprovalParams.Type;
291 readonly "item/tool/requestUserInput": typeof CodexSchema.ToolRequestUserInputParams.Type;
292 readonly "mcpServer/elicitation/request": typeof CodexSchema.McpServerElicitationRequestParams.Type;
293 readonly "item/permissions/requestApproval": typeof CodexSchema.PermissionsRequestApprovalParams.Type;
294 readonly "item/tool/call": typeof CodexSchema.DynamicToolCallParams.Type;
295 readonly "account/chatgptAuthTokens/refresh": typeof CodexSchema.ChatgptAuthTokensRefreshParams.Type;
296 readonly applyPatchApproval: typeof CodexSchema.ApplyPatchApprovalParams.Type;
297 readonly execCommandApproval: typeof CodexSchema.ExecCommandApprovalParams.Type;
298}
299
300export interface ServerRequestResponsesByMethod {
301 readonly "item/commandExecution/requestApproval": typeof CodexSchema.CommandExecutionRequestApprovalResponse.Type;
302 readonly "item/fileChange/requestApproval": typeof CodexSchema.FileChangeRequestApprovalResponse.Type;
303 readonly "item/tool/requestUserInput": typeof CodexSchema.ToolRequestUserInputResponse.Type;
304 readonly "mcpServer/elicitation/request": typeof CodexSchema.McpServerElicitationRequestResponse.Type;
305 readonly "item/permissions/requestApproval": typeof CodexSchema.PermissionsRequestApprovalResponse.Type;
306 readonly "item/tool/call": typeof CodexSchema.DynamicToolCallResponse.Type;
307 readonly "account/chatgptAuthTokens/refresh": typeof CodexSchema.ChatgptAuthTokensRefreshResponse.Type;
308 readonly applyPatchApproval: typeof CodexSchema.ApplyPatchApprovalResponse.Type;
309 readonly execCommandApproval: typeof CodexSchema.ExecCommandApprovalResponse.Type;
310}
311
312export interface ServerNotificationParamsByMethod {
313 readonly error: typeof CodexSchema.V2ErrorNotification.Type;
314 readonly "thread/started": typeof CodexSchema.V2ThreadStartedNotification.Type;
315 readonly "thread/status/changed": typeof CodexSchema.V2ThreadStatusChangedNotification.Type;
316 readonly "thread/archived": typeof CodexSchema.V2ThreadArchivedNotification.Type;
317 readonly "thread/unarchived": typeof CodexSchema.V2ThreadUnarchivedNotification.Type;
318 readonly "thread/closed": typeof CodexSchema.V2ThreadClosedNotification.Type;
319 readonly "skills/changed": typeof CodexSchema.V2SkillsChangedNotification.Type;
320 readonly "thread/name/updated": typeof CodexSchema.V2ThreadNameUpdatedNotification.Type;
321 readonly "thread/tokenUsage/updated": typeof CodexSchema.V2ThreadTokenUsageUpdatedNotification.Type;
322 readonly "turn/started": typeof CodexSchema.V2TurnStartedNotification.Type;
323 readonly "hook/started": typeof CodexSchema.V2HookStartedNotification.Type;
324 readonly "turn/completed": typeof CodexSchema.V2TurnCompletedNotification.Type;
325 readonly "hook/completed": typeof CodexSchema.V2HookCompletedNotification.Type;
326 readonly "turn/diff/updated": typeof CodexSchema.V2TurnDiffUpdatedNotification.Type;
327 readonly "turn/plan/updated": typeof CodexSchema.V2TurnPlanUpdatedNotification.Type;
328 readonly "item/started": typeof CodexSchema.V2ItemStartedNotification.Type;
329 readonly "item/autoApprovalReview/started": typeof CodexSchema.V2ItemGuardianApprovalReviewStartedNotification.Type;
330 readonly "item/autoApprovalReview/completed": typeof CodexSchema.V2ItemGuardianApprovalReviewCompletedNotification.Type;
331 readonly "item/completed": typeof CodexSchema.V2ItemCompletedNotification.Type;
332 readonly "rawResponseItem/completed": typeof CodexSchema.V2RawResponseItemCompletedNotification.Type;
333 readonly "item/agentMessage/delta": typeof CodexSchema.V2AgentMessageDeltaNotification.Type;
334 readonly "item/plan/delta": typeof CodexSchema.V2PlanDeltaNotification.Type;
335 readonly "command/exec/outputDelta": typeof CodexSchema.V2CommandExecOutputDeltaNotification.Type;
336 readonly "item/commandExecution/outputDelta": typeof CodexSchema.V2CommandExecutionOutputDeltaNotification.Type;
337 readonly "item/commandExecution/terminalInteraction": typeof CodexSchema.V2TerminalInteractionNotification.Type;
338 readonly "item/fileChange/outputDelta": typeof CodexSchema.V2FileChangeOutputDeltaNotification.Type;
339 readonly "serverRequest/resolved": typeof CodexSchema.V2ServerRequestResolvedNotification.Type;
340 readonly "item/mcpToolCall/progress": typeof CodexSchema.V2McpToolCallProgressNotification.Type;
341 readonly "mcpServer/oauthLogin/completed": typeof CodexSchema.V2McpServerOauthLoginCompletedNotification.Type;
342 readonly "mcpServer/startupStatus/updated": typeof CodexSchema.V2McpServerStatusUpdatedNotification.Type;
343 readonly "account/updated": typeof CodexSchema.V2AccountUpdatedNotification.Type;
344 readonly "account/rateLimits/updated": typeof CodexSchema.V2AccountRateLimitsUpdatedNotification.Type;
345 readonly "app/list/updated": typeof CodexSchema.V2AppListUpdatedNotification.Type;
346 readonly "fs/changed": typeof CodexSchema.V2FsChangedNotification.Type;
347 readonly "item/reasoning/summaryTextDelta": typeof CodexSchema.V2ReasoningSummaryTextDeltaNotification.Type;
348 readonly "item/reasoning/summaryPartAdded": typeof CodexSchema.V2ReasoningSummaryPartAddedNotification.Type;
349 readonly "item/reasoning/textDelta": typeof CodexSchema.V2ReasoningTextDeltaNotification.Type;
350 readonly "thread/compacted": typeof CodexSchema.V2ContextCompactedNotification.Type;
351 readonly "model/rerouted": typeof CodexSchema.V2ModelReroutedNotification.Type;
352 readonly deprecationNotice: typeof CodexSchema.V2DeprecationNoticeNotification.Type;
353 readonly configWarning: typeof CodexSchema.V2ConfigWarningNotification.Type;
354 readonly "fuzzyFileSearch/sessionUpdated": typeof CodexSchema.FuzzyFileSearchSessionUpdatedNotification.Type;
355 readonly "fuzzyFileSearch/sessionCompleted": typeof CodexSchema.FuzzyFileSearchSessionCompletedNotification.Type;
356 readonly "thread/realtime/started": typeof CodexSchema.V2ThreadRealtimeStartedNotification.Type;
357 readonly "thread/realtime/itemAdded": typeof CodexSchema.V2ThreadRealtimeItemAddedNotification.Type;
358 readonly "thread/realtime/transcriptUpdated": typeof CodexSchema.V2ThreadRealtimeTranscriptUpdatedNotification.Type;
359 readonly "thread/realtime/outputAudio/delta": typeof CodexSchema.V2ThreadRealtimeOutputAudioDeltaNotification.Type;
360 readonly "thread/realtime/sdp": typeof CodexSchema.V2ThreadRealtimeSdpNotification.Type;
361 readonly "thread/realtime/error": typeof CodexSchema.V2ThreadRealtimeErrorNotification.Type;
362 readonly "thread/realtime/closed": typeof CodexSchema.V2ThreadRealtimeClosedNotification.Type;
363 readonly "windows/worldWritableWarning": typeof CodexSchema.V2WindowsWorldWritableWarningNotification.Type;
364 readonly "windowsSandbox/setupCompleted": typeof CodexSchema.V2WindowsSandboxSetupCompletedNotification.Type;
365 readonly "account/login/completed": typeof CodexSchema.V2AccountLoginCompletedNotification.Type;
366}
367
368export const CLIENT_REQUEST_PARAMS = {
369 initialize: CodexSchema.V1InitializeParams,
370 "thread/start": CodexSchema.V2ThreadStartParams,
371 "thread/resume": CodexSchema.V2ThreadResumeParams,
372 "thread/fork": CodexSchema.V2ThreadForkParams,
373 "thread/archive": CodexSchema.V2ThreadArchiveParams,
374 "thread/unsubscribe": CodexSchema.V2ThreadUnsubscribeParams,
375 "thread/name/set": CodexSchema.V2ThreadSetNameParams,
376 "thread/metadata/update": CodexSchema.V2ThreadMetadataUpdateParams,
377 "thread/unarchive": CodexSchema.V2ThreadUnarchiveParams,
378 "thread/compact/start": CodexSchema.V2ThreadCompactStartParams,
379 "thread/shellCommand": CodexSchema.V2ThreadShellCommandParams,
380 "thread/rollback": CodexSchema.V2ThreadRollbackParams,
381 "thread/list": CodexSchema.V2ThreadListParams,
382 "thread/loaded/list": CodexSchema.V2ThreadLoadedListParams,
383 "thread/read": CodexSchema.V2ThreadReadParams,
384 "skills/list": CodexSchema.V2SkillsListParams,
385 "plugin/list": CodexSchema.V2PluginListParams,
386 "plugin/read": CodexSchema.V2PluginReadParams,
387 "app/list": CodexSchema.V2AppsListParams,
388 "fs/readFile": CodexSchema.V2FsReadFileParams,
389 "fs/writeFile": CodexSchema.V2FsWriteFileParams,
390 "fs/createDirectory": CodexSchema.V2FsCreateDirectoryParams,
391 "fs/getMetadata": CodexSchema.V2FsGetMetadataParams,
392 "fs/readDirectory": CodexSchema.V2FsReadDirectoryParams,
393 "fs/remove": CodexSchema.V2FsRemoveParams,
394 "fs/copy": CodexSchema.V2FsCopyParams,
395 "fs/watch": CodexSchema.V2FsWatchParams,
396 "fs/unwatch": CodexSchema.V2FsUnwatchParams,
397 "skills/config/write": CodexSchema.V2SkillsConfigWriteParams,
398 "plugin/install": CodexSchema.V2PluginInstallParams,
399 "plugin/uninstall": CodexSchema.V2PluginUninstallParams,
400 "turn/start": CodexSchema.V2TurnStartParams,
401 "turn/steer": CodexSchema.V2TurnSteerParams,
402 "turn/interrupt": CodexSchema.V2TurnInterruptParams,
403 "review/start": CodexSchema.V2ReviewStartParams,
404 "model/list": CodexSchema.V2ModelListParams,
405 "experimentalFeature/list": CodexSchema.V2ExperimentalFeatureListParams,
406 "experimentalFeature/enablement/set": CodexSchema.V2ExperimentalFeatureEnablementSetParams,
407 "mcpServer/oauth/login": CodexSchema.V2McpServerOauthLoginParams,
408 "config/mcpServer/reload": undefined,
409 "mcpServerStatus/list": CodexSchema.V2ListMcpServerStatusParams,
410 "mcpServer/resource/read": CodexSchema.V2McpResourceReadParams,
411 "mcpServer/tool/call": CodexSchema.V2McpServerToolCallParams,
412 "windowsSandbox/setupStart": CodexSchema.V2WindowsSandboxSetupStartParams,
413 "account/login/start": CodexSchema.V2LoginAccountParams,
414 "account/login/cancel": CodexSchema.V2CancelLoginAccountParams,
415 "account/logout": undefined,
416 "account/rateLimits/read": undefined,
417 "feedback/upload": CodexSchema.V2FeedbackUploadParams,
418 "command/exec": CodexSchema.V2CommandExecParams,
419 "command/exec/write": CodexSchema.V2CommandExecWriteParams,
420 "command/exec/terminate": CodexSchema.V2CommandExecTerminateParams,
421 "command/exec/resize": CodexSchema.V2CommandExecResizeParams,
422 "config/read": CodexSchema.V2ConfigReadParams,
423 "externalAgentConfig/detect": CodexSchema.V2ExternalAgentConfigDetectParams,
424 "externalAgentConfig/import": CodexSchema.V2ExternalAgentConfigImportParams,
425 "config/value/write": CodexSchema.V2ConfigValueWriteParams,
426 "config/batchWrite": CodexSchema.V2ConfigBatchWriteParams,
427 "configRequirements/read": undefined,
428 "account/read": CodexSchema.V2GetAccountParams,
429 getConversationSummary: CodexSchema.GetConversationSummaryParams,
430 gitDiffToRemote: CodexSchema.GitDiffToRemoteParams,
431 getAuthStatus: CodexSchema.GetAuthStatusParams,
432 fuzzyFileSearch: CodexSchema.FuzzyFileSearchParams,
433} as const;
434
435export const CLIENT_REQUEST_RESPONSES = {
436 initialize: CodexSchema.V1InitializeResponse,
437 "thread/start": CodexSchema.V2ThreadStartResponse,
438 "thread/resume": CodexSchema.V2ThreadResumeResponse,
439 "thread/fork": CodexSchema.V2ThreadForkResponse,
440 "thread/archive": CodexSchema.V2ThreadArchiveResponse,
441 "thread/unsubscribe": CodexSchema.V2ThreadUnsubscribeResponse,
442 "thread/name/set": CodexSchema.V2ThreadSetNameResponse,
443 "thread/metadata/update": CodexSchema.V2ThreadMetadataUpdateResponse,
444 "thread/unarchive": CodexSchema.V2ThreadUnarchiveResponse,
445 "thread/compact/start": CodexSchema.V2ThreadCompactStartResponse,
446 "thread/shellCommand": CodexSchema.V2ThreadShellCommandResponse,
447 "thread/rollback": CodexSchema.V2ThreadRollbackResponse,
448 "thread/list": CodexSchema.V2ThreadListResponse,
449 "thread/loaded/list": CodexSchema.V2ThreadLoadedListResponse,
450 "thread/read": CodexSchema.V2ThreadReadResponse,
451 "skills/list": CodexSchema.V2SkillsListResponse,
452 "plugin/list": CodexSchema.V2PluginListResponse,
453 "plugin/read": CodexSchema.V2PluginReadResponse,
454 "app/list": CodexSchema.V2AppsListResponse,
455 "fs/readFile": CodexSchema.V2FsReadFileResponse,
456 "fs/writeFile": CodexSchema.V2FsWriteFileResponse,
457 "fs/createDirectory": CodexSchema.V2FsCreateDirectoryResponse,
458 "fs/getMetadata": CodexSchema.V2FsGetMetadataResponse,
459 "fs/readDirectory": CodexSchema.V2FsReadDirectoryResponse,
460 "fs/remove": CodexSchema.V2FsRemoveResponse,
461 "fs/copy": CodexSchema.V2FsCopyResponse,
462 "fs/watch": CodexSchema.V2FsWatchResponse,
463 "fs/unwatch": CodexSchema.V2FsUnwatchResponse,
464 "skills/config/write": CodexSchema.V2SkillsConfigWriteResponse,
465 "plugin/install": CodexSchema.V2PluginInstallResponse,
466 "plugin/uninstall": CodexSchema.V2PluginUninstallResponse,
467 "turn/start": CodexSchema.V2TurnStartResponse,
468 "turn/steer": CodexSchema.V2TurnSteerResponse,
469 "turn/interrupt": CodexSchema.V2TurnInterruptResponse,
470 "review/start": CodexSchema.V2ReviewStartResponse,
471 "model/list": CodexSchema.V2ModelListResponse,
472 "experimentalFeature/list": CodexSchema.V2ExperimentalFeatureListResponse,
473 "experimentalFeature/enablement/set": CodexSchema.V2ExperimentalFeatureEnablementSetResponse,
474 "mcpServer/oauth/login": CodexSchema.V2McpServerOauthLoginResponse,
475 "config/mcpServer/reload": CodexSchema.V2McpServerRefreshResponse,
476 "mcpServerStatus/list": CodexSchema.V2ListMcpServerStatusResponse,
477 "mcpServer/resource/read": CodexSchema.V2McpResourceReadResponse,
478 "mcpServer/tool/call": CodexSchema.V2McpServerToolCallResponse,
479 "windowsSandbox/setupStart": CodexSchema.V2WindowsSandboxSetupStartResponse,
480 "account/login/start": CodexSchema.V2LoginAccountResponse,
481 "account/login/cancel": CodexSchema.V2CancelLoginAccountResponse,
482 "account/logout": CodexSchema.V2LogoutAccountResponse,
483 "account/rateLimits/read": CodexSchema.V2GetAccountRateLimitsResponse,
484 "feedback/upload": CodexSchema.V2FeedbackUploadResponse,
485 "command/exec": CodexSchema.V2CommandExecResponse,
486 "command/exec/write": CodexSchema.V2CommandExecWriteResponse,
487 "command/exec/terminate": CodexSchema.V2CommandExecTerminateResponse,
488 "command/exec/resize": CodexSchema.V2CommandExecResizeResponse,
489 "config/read": CodexSchema.V2ConfigReadResponse,
490 "externalAgentConfig/detect": CodexSchema.V2ExternalAgentConfigDetectResponse,
491 "externalAgentConfig/import": CodexSchema.V2ExternalAgentConfigImportResponse,
492 "config/value/write": CodexSchema.V2ConfigWriteResponse,
493 "config/batchWrite": CodexSchema.V2ConfigWriteResponse,
494 "configRequirements/read": CodexSchema.V2ConfigRequirementsReadResponse,
495 "account/read": CodexSchema.V2GetAccountResponse,
496 getConversationSummary: CodexSchema.GetConversationSummaryResponse,
497 gitDiffToRemote: CodexSchema.GitDiffToRemoteResponse,
498 getAuthStatus: CodexSchema.GetAuthStatusResponse,
499 fuzzyFileSearch: CodexSchema.FuzzyFileSearchResponse,
500} as const;
501
502export const CLIENT_NOTIFICATION_PARAMS = {
503 initialized: undefined,
504} as const;
505
506export const SERVER_REQUEST_PARAMS = {
507 "item/commandExecution/requestApproval": CodexSchema.CommandExecutionRequestApprovalParams,
508 "item/fileChange/requestApproval": CodexSchema.FileChangeRequestApprovalParams,
509 "item/tool/requestUserInput": CodexSchema.ToolRequestUserInputParams,
510 "mcpServer/elicitation/request": CodexSchema.McpServerElicitationRequestParams,
511 "item/permissions/requestApproval": CodexSchema.PermissionsRequestApprovalParams,
512 "item/tool/call": CodexSchema.DynamicToolCallParams,
513 "account/chatgptAuthTokens/refresh": CodexSchema.ChatgptAuthTokensRefreshParams,
514 applyPatchApproval: CodexSchema.ApplyPatchApprovalParams,
515 execCommandApproval: CodexSchema.ExecCommandApprovalParams,
516} as const;
517
518export const SERVER_REQUEST_RESPONSES = {
519 "item/commandExecution/requestApproval": CodexSchema.CommandExecutionRequestApprovalResponse,
520 "item/fileChange/requestApproval": CodexSchema.FileChangeRequestApprovalResponse,
521 "item/tool/requestUserInput": CodexSchema.ToolRequestUserInputResponse,
522 "mcpServer/elicitation/request": CodexSchema.McpServerElicitationRequestResponse,
523 "item/permissions/requestApproval": CodexSchema.PermissionsRequestApprovalResponse,
524 "item/tool/call": CodexSchema.DynamicToolCallResponse,
525 "account/chatgptAuthTokens/refresh": CodexSchema.ChatgptAuthTokensRefreshResponse,
526 applyPatchApproval: CodexSchema.ApplyPatchApprovalResponse,
527 execCommandApproval: CodexSchema.ExecCommandApprovalResponse,
528} as const;
529
530export const SERVER_NOTIFICATION_PARAMS = {
531 error: CodexSchema.V2ErrorNotification,
532 "thread/started": CodexSchema.V2ThreadStartedNotification,
533 "thread/status/changed": CodexSchema.V2ThreadStatusChangedNotification,
534 "thread/archived": CodexSchema.V2ThreadArchivedNotification,
535 "thread/unarchived": CodexSchema.V2ThreadUnarchivedNotification,
536 "thread/closed": CodexSchema.V2ThreadClosedNotification,
537 "skills/changed": CodexSchema.V2SkillsChangedNotification,
538 "thread/name/updated": CodexSchema.V2ThreadNameUpdatedNotification,
539 "thread/tokenUsage/updated": CodexSchema.V2ThreadTokenUsageUpdatedNotification,
540 "turn/started": CodexSchema.V2TurnStartedNotification,
541 "hook/started": CodexSchema.V2HookStartedNotification,
542 "turn/completed": CodexSchema.V2TurnCompletedNotification,
543 "hook/completed": CodexSchema.V2HookCompletedNotification,
544 "turn/diff/updated": CodexSchema.V2TurnDiffUpdatedNotification,
545 "turn/plan/updated": CodexSchema.V2TurnPlanUpdatedNotification,
546 "item/started": CodexSchema.V2ItemStartedNotification,
547 "item/autoApprovalReview/started": CodexSchema.V2ItemGuardianApprovalReviewStartedNotification,
548 "item/autoApprovalReview/completed":
549 CodexSchema.V2ItemGuardianApprovalReviewCompletedNotification,
550 "item/completed": CodexSchema.V2ItemCompletedNotification,
551 "rawResponseItem/completed": CodexSchema.V2RawResponseItemCompletedNotification,
552 "item/agentMessage/delta": CodexSchema.V2AgentMessageDeltaNotification,
553 "item/plan/delta": CodexSchema.V2PlanDeltaNotification,
554 "command/exec/outputDelta": CodexSchema.V2CommandExecOutputDeltaNotification,
555 "item/commandExecution/outputDelta": CodexSchema.V2CommandExecutionOutputDeltaNotification,
556 "item/commandExecution/terminalInteraction": CodexSchema.V2TerminalInteractionNotification,
557 "item/fileChange/outputDelta": CodexSchema.V2FileChangeOutputDeltaNotification,
558 "serverRequest/resolved": CodexSchema.V2ServerRequestResolvedNotification,
559 "item/mcpToolCall/progress": CodexSchema.V2McpToolCallProgressNotification,
560 "mcpServer/oauthLogin/completed": CodexSchema.V2McpServerOauthLoginCompletedNotification,
561 "mcpServer/startupStatus/updated": CodexSchema.V2McpServerStatusUpdatedNotification,
562 "account/updated": CodexSchema.V2AccountUpdatedNotification,
563 "account/rateLimits/updated": CodexSchema.V2AccountRateLimitsUpdatedNotification,
564 "app/list/updated": CodexSchema.V2AppListUpdatedNotification,
565 "fs/changed": CodexSchema.V2FsChangedNotification,
566 "item/reasoning/summaryTextDelta": CodexSchema.V2ReasoningSummaryTextDeltaNotification,
567 "item/reasoning/summaryPartAdded": CodexSchema.V2ReasoningSummaryPartAddedNotification,
568 "item/reasoning/textDelta": CodexSchema.V2ReasoningTextDeltaNotification,
569 "thread/compacted": CodexSchema.V2ContextCompactedNotification,
570 "model/rerouted": CodexSchema.V2ModelReroutedNotification,
571 deprecationNotice: CodexSchema.V2DeprecationNoticeNotification,
572 configWarning: CodexSchema.V2ConfigWarningNotification,
573 "fuzzyFileSearch/sessionUpdated": CodexSchema.FuzzyFileSearchSessionUpdatedNotification,
574 "fuzzyFileSearch/sessionCompleted": CodexSchema.FuzzyFileSearchSessionCompletedNotification,
575 "thread/realtime/started": CodexSchema.V2ThreadRealtimeStartedNotification,
576 "thread/realtime/itemAdded": CodexSchema.V2ThreadRealtimeItemAddedNotification,
577 "thread/realtime/transcriptUpdated": CodexSchema.V2ThreadRealtimeTranscriptUpdatedNotification,
578 "thread/realtime/outputAudio/delta": CodexSchema.V2ThreadRealtimeOutputAudioDeltaNotification,
579 "thread/realtime/sdp": CodexSchema.V2ThreadRealtimeSdpNotification,
580 "thread/realtime/error": CodexSchema.V2ThreadRealtimeErrorNotification,
581 "thread/realtime/closed": CodexSchema.V2ThreadRealtimeClosedNotification,
582 "windows/worldWritableWarning": CodexSchema.V2WindowsWorldWritableWarningNotification,
583 "windowsSandbox/setupCompleted": CodexSchema.V2WindowsSandboxSetupCompletedNotification,
584 "account/login/completed": CodexSchema.V2AccountLoginCompletedNotification,
585} as const;
packages/effect-codex-app-server/src/_generated/namespaces.gen.ts created+180
...@@ -0,0 +1,180 @@
1// This file is generated by the effect-codex-app-server package. Do not edit manually.
2// Upstream protocol ref: dbfe855f4fd0f5dcdf079882652a8efe622b0595
3
4import * as CodexSchema from "./schema.gen.ts";
5
6export const v1 = {
7 InitializeParams: CodexSchema.V1InitializeParams,
8 InitializeResponse: CodexSchema.V1InitializeResponse,
9} as const;
10
11export const v2 = {
12 AccountLoginCompletedNotification: CodexSchema.V2AccountLoginCompletedNotification,
13 AccountRateLimitsUpdatedNotification: CodexSchema.V2AccountRateLimitsUpdatedNotification,
14 AccountUpdatedNotification: CodexSchema.V2AccountUpdatedNotification,
15 AgentMessageDeltaNotification: CodexSchema.V2AgentMessageDeltaNotification,
16 AppListUpdatedNotification: CodexSchema.V2AppListUpdatedNotification,
17 AppsListParams: CodexSchema.V2AppsListParams,
18 AppsListResponse: CodexSchema.V2AppsListResponse,
19 CancelLoginAccountParams: CodexSchema.V2CancelLoginAccountParams,
20 CancelLoginAccountResponse: CodexSchema.V2CancelLoginAccountResponse,
21 CommandExecOutputDeltaNotification: CodexSchema.V2CommandExecOutputDeltaNotification,
22 CommandExecParams: CodexSchema.V2CommandExecParams,
23 CommandExecResizeParams: CodexSchema.V2CommandExecResizeParams,
24 CommandExecResizeResponse: CodexSchema.V2CommandExecResizeResponse,
25 CommandExecResponse: CodexSchema.V2CommandExecResponse,
26 CommandExecTerminateParams: CodexSchema.V2CommandExecTerminateParams,
27 CommandExecTerminateResponse: CodexSchema.V2CommandExecTerminateResponse,
28 CommandExecutionOutputDeltaNotification: CodexSchema.V2CommandExecutionOutputDeltaNotification,
29 CommandExecWriteParams: CodexSchema.V2CommandExecWriteParams,
30 CommandExecWriteResponse: CodexSchema.V2CommandExecWriteResponse,
31 ConfigBatchWriteParams: CodexSchema.V2ConfigBatchWriteParams,
32 ConfigReadParams: CodexSchema.V2ConfigReadParams,
33 ConfigReadResponse: CodexSchema.V2ConfigReadResponse,
34 ConfigRequirementsReadResponse: CodexSchema.V2ConfigRequirementsReadResponse,
35 ConfigValueWriteParams: CodexSchema.V2ConfigValueWriteParams,
36 ConfigWarningNotification: CodexSchema.V2ConfigWarningNotification,
37 ConfigWriteResponse: CodexSchema.V2ConfigWriteResponse,
38 ContextCompactedNotification: CodexSchema.V2ContextCompactedNotification,
39 DeprecationNoticeNotification: CodexSchema.V2DeprecationNoticeNotification,
40 ErrorNotification: CodexSchema.V2ErrorNotification,
41 ExperimentalFeatureEnablementSetParams: CodexSchema.V2ExperimentalFeatureEnablementSetParams,
42 ExperimentalFeatureEnablementSetResponse: CodexSchema.V2ExperimentalFeatureEnablementSetResponse,
43 ExperimentalFeatureListParams: CodexSchema.V2ExperimentalFeatureListParams,
44 ExperimentalFeatureListResponse: CodexSchema.V2ExperimentalFeatureListResponse,
45 ExternalAgentConfigDetectParams: CodexSchema.V2ExternalAgentConfigDetectParams,
46 ExternalAgentConfigDetectResponse: CodexSchema.V2ExternalAgentConfigDetectResponse,
47 ExternalAgentConfigImportParams: CodexSchema.V2ExternalAgentConfigImportParams,
48 ExternalAgentConfigImportResponse: CodexSchema.V2ExternalAgentConfigImportResponse,
49 FeedbackUploadParams: CodexSchema.V2FeedbackUploadParams,
50 FeedbackUploadResponse: CodexSchema.V2FeedbackUploadResponse,
51 FileChangeOutputDeltaNotification: CodexSchema.V2FileChangeOutputDeltaNotification,
52 FsChangedNotification: CodexSchema.V2FsChangedNotification,
53 FsCopyParams: CodexSchema.V2FsCopyParams,
54 FsCopyResponse: CodexSchema.V2FsCopyResponse,
55 FsCreateDirectoryParams: CodexSchema.V2FsCreateDirectoryParams,
56 FsCreateDirectoryResponse: CodexSchema.V2FsCreateDirectoryResponse,
57 FsGetMetadataParams: CodexSchema.V2FsGetMetadataParams,
58 FsGetMetadataResponse: CodexSchema.V2FsGetMetadataResponse,
59 FsReadDirectoryParams: CodexSchema.V2FsReadDirectoryParams,
60 FsReadDirectoryResponse: CodexSchema.V2FsReadDirectoryResponse,
61 FsReadFileParams: CodexSchema.V2FsReadFileParams,
62 FsReadFileResponse: CodexSchema.V2FsReadFileResponse,
63 FsRemoveParams: CodexSchema.V2FsRemoveParams,
64 FsRemoveResponse: CodexSchema.V2FsRemoveResponse,
65 FsUnwatchParams: CodexSchema.V2FsUnwatchParams,
66 FsUnwatchResponse: CodexSchema.V2FsUnwatchResponse,
67 FsWatchParams: CodexSchema.V2FsWatchParams,
68 FsWatchResponse: CodexSchema.V2FsWatchResponse,
69 FsWriteFileParams: CodexSchema.V2FsWriteFileParams,
70 FsWriteFileResponse: CodexSchema.V2FsWriteFileResponse,
71 GetAccountParams: CodexSchema.V2GetAccountParams,
72 GetAccountRateLimitsResponse: CodexSchema.V2GetAccountRateLimitsResponse,
73 GetAccountResponse: CodexSchema.V2GetAccountResponse,
74 HookCompletedNotification: CodexSchema.V2HookCompletedNotification,
75 HookStartedNotification: CodexSchema.V2HookStartedNotification,
76 ItemCompletedNotification: CodexSchema.V2ItemCompletedNotification,
77 ItemGuardianApprovalReviewCompletedNotification:
78 CodexSchema.V2ItemGuardianApprovalReviewCompletedNotification,
79 ItemGuardianApprovalReviewStartedNotification:
80 CodexSchema.V2ItemGuardianApprovalReviewStartedNotification,
81 ItemStartedNotification: CodexSchema.V2ItemStartedNotification,
82 ListMcpServerStatusParams: CodexSchema.V2ListMcpServerStatusParams,
83 ListMcpServerStatusResponse: CodexSchema.V2ListMcpServerStatusResponse,
84 LoginAccountParams: CodexSchema.V2LoginAccountParams,
85 LoginAccountResponse: CodexSchema.V2LoginAccountResponse,
86 LogoutAccountResponse: CodexSchema.V2LogoutAccountResponse,
87 McpResourceReadParams: CodexSchema.V2McpResourceReadParams,
88 McpResourceReadResponse: CodexSchema.V2McpResourceReadResponse,
89 McpServerOauthLoginCompletedNotification: CodexSchema.V2McpServerOauthLoginCompletedNotification,
90 McpServerOauthLoginParams: CodexSchema.V2McpServerOauthLoginParams,
91 McpServerOauthLoginResponse: CodexSchema.V2McpServerOauthLoginResponse,
92 McpServerRefreshResponse: CodexSchema.V2McpServerRefreshResponse,
93 McpServerStatusUpdatedNotification: CodexSchema.V2McpServerStatusUpdatedNotification,
94 McpServerToolCallParams: CodexSchema.V2McpServerToolCallParams,
95 McpServerToolCallResponse: CodexSchema.V2McpServerToolCallResponse,
96 McpToolCallProgressNotification: CodexSchema.V2McpToolCallProgressNotification,
97 ModelListParams: CodexSchema.V2ModelListParams,
98 ModelListResponse: CodexSchema.V2ModelListResponse,
99 ModelReroutedNotification: CodexSchema.V2ModelReroutedNotification,
100 PlanDeltaNotification: CodexSchema.V2PlanDeltaNotification,
101 PluginInstallParams: CodexSchema.V2PluginInstallParams,
102 PluginInstallResponse: CodexSchema.V2PluginInstallResponse,
103 PluginListParams: CodexSchema.V2PluginListParams,
104 PluginListResponse: CodexSchema.V2PluginListResponse,
105 PluginReadParams: CodexSchema.V2PluginReadParams,
106 PluginReadResponse: CodexSchema.V2PluginReadResponse,
107 PluginUninstallParams: CodexSchema.V2PluginUninstallParams,
108 PluginUninstallResponse: CodexSchema.V2PluginUninstallResponse,
109 RawResponseItemCompletedNotification: CodexSchema.V2RawResponseItemCompletedNotification,
110 ReasoningSummaryPartAddedNotification: CodexSchema.V2ReasoningSummaryPartAddedNotification,
111 ReasoningSummaryTextDeltaNotification: CodexSchema.V2ReasoningSummaryTextDeltaNotification,
112 ReasoningTextDeltaNotification: CodexSchema.V2ReasoningTextDeltaNotification,
113 ReviewStartParams: CodexSchema.V2ReviewStartParams,
114 ReviewStartResponse: CodexSchema.V2ReviewStartResponse,
115 ServerRequestResolvedNotification: CodexSchema.V2ServerRequestResolvedNotification,
116 SkillsChangedNotification: CodexSchema.V2SkillsChangedNotification,
117 SkillsConfigWriteParams: CodexSchema.V2SkillsConfigWriteParams,
118 SkillsConfigWriteResponse: CodexSchema.V2SkillsConfigWriteResponse,
119 SkillsListParams: CodexSchema.V2SkillsListParams,
120 SkillsListResponse: CodexSchema.V2SkillsListResponse,
121 TerminalInteractionNotification: CodexSchema.V2TerminalInteractionNotification,
122 ThreadArchivedNotification: CodexSchema.V2ThreadArchivedNotification,
123 ThreadArchiveParams: CodexSchema.V2ThreadArchiveParams,
124 ThreadArchiveResponse: CodexSchema.V2ThreadArchiveResponse,
125 ThreadClosedNotification: CodexSchema.V2ThreadClosedNotification,
126 ThreadCompactStartParams: CodexSchema.V2ThreadCompactStartParams,
127 ThreadCompactStartResponse: CodexSchema.V2ThreadCompactStartResponse,
128 ThreadForkParams: CodexSchema.V2ThreadForkParams,
129 ThreadForkResponse: CodexSchema.V2ThreadForkResponse,
130 ThreadListParams: CodexSchema.V2ThreadListParams,
131 ThreadListResponse: CodexSchema.V2ThreadListResponse,
132 ThreadLoadedListParams: CodexSchema.V2ThreadLoadedListParams,
133 ThreadLoadedListResponse: CodexSchema.V2ThreadLoadedListResponse,
134 ThreadMetadataUpdateParams: CodexSchema.V2ThreadMetadataUpdateParams,
135 ThreadMetadataUpdateResponse: CodexSchema.V2ThreadMetadataUpdateResponse,
136 ThreadNameUpdatedNotification: CodexSchema.V2ThreadNameUpdatedNotification,
137 ThreadReadParams: CodexSchema.V2ThreadReadParams,
138 ThreadReadResponse: CodexSchema.V2ThreadReadResponse,
139 ThreadRealtimeClosedNotification: CodexSchema.V2ThreadRealtimeClosedNotification,
140 ThreadRealtimeErrorNotification: CodexSchema.V2ThreadRealtimeErrorNotification,
141 ThreadRealtimeItemAddedNotification: CodexSchema.V2ThreadRealtimeItemAddedNotification,
142 ThreadRealtimeOutputAudioDeltaNotification:
143 CodexSchema.V2ThreadRealtimeOutputAudioDeltaNotification,
144 ThreadRealtimeSdpNotification: CodexSchema.V2ThreadRealtimeSdpNotification,
145 ThreadRealtimeStartedNotification: CodexSchema.V2ThreadRealtimeStartedNotification,
146 ThreadRealtimeTranscriptUpdatedNotification:
147 CodexSchema.V2ThreadRealtimeTranscriptUpdatedNotification,
148 ThreadResumeParams: CodexSchema.V2ThreadResumeParams,
149 ThreadResumeResponse: CodexSchema.V2ThreadResumeResponse,
150 ThreadRollbackParams: CodexSchema.V2ThreadRollbackParams,
151 ThreadRollbackResponse: CodexSchema.V2ThreadRollbackResponse,
152 ThreadSetNameParams: CodexSchema.V2ThreadSetNameParams,
153 ThreadSetNameResponse: CodexSchema.V2ThreadSetNameResponse,
154 ThreadShellCommandParams: CodexSchema.V2ThreadShellCommandParams,
155 ThreadShellCommandResponse: CodexSchema.V2ThreadShellCommandResponse,
156 ThreadStartedNotification: CodexSchema.V2ThreadStartedNotification,
157 ThreadStartParams: CodexSchema.V2ThreadStartParams,
158 ThreadStartResponse: CodexSchema.V2ThreadStartResponse,
159 ThreadStatusChangedNotification: CodexSchema.V2ThreadStatusChangedNotification,
160 ThreadTokenUsageUpdatedNotification: CodexSchema.V2ThreadTokenUsageUpdatedNotification,
161 ThreadUnarchivedNotification: CodexSchema.V2ThreadUnarchivedNotification,
162 ThreadUnarchiveParams: CodexSchema.V2ThreadUnarchiveParams,
163 ThreadUnarchiveResponse: CodexSchema.V2ThreadUnarchiveResponse,
164 ThreadUnsubscribeParams: CodexSchema.V2ThreadUnsubscribeParams,
165 ThreadUnsubscribeResponse: CodexSchema.V2ThreadUnsubscribeResponse,
166 TurnCompletedNotification: CodexSchema.V2TurnCompletedNotification,
167 TurnDiffUpdatedNotification: CodexSchema.V2TurnDiffUpdatedNotification,
168 TurnInterruptParams: CodexSchema.V2TurnInterruptParams,
169 TurnInterruptResponse: CodexSchema.V2TurnInterruptResponse,
170 TurnPlanUpdatedNotification: CodexSchema.V2TurnPlanUpdatedNotification,
171 TurnStartedNotification: CodexSchema.V2TurnStartedNotification,
172 TurnStartParams: CodexSchema.V2TurnStartParams,
173 TurnStartResponse: CodexSchema.V2TurnStartResponse,
174 TurnSteerParams: CodexSchema.V2TurnSteerParams,
175 TurnSteerResponse: CodexSchema.V2TurnSteerResponse,
176 WindowsSandboxSetupCompletedNotification: CodexSchema.V2WindowsSandboxSetupCompletedNotification,
177 WindowsSandboxSetupStartParams: CodexSchema.V2WindowsSandboxSetupStartParams,
178 WindowsSandboxSetupStartResponse: CodexSchema.V2WindowsSandboxSetupStartResponse,
179 WindowsWorldWritableWarningNotification: CodexSchema.V2WindowsWorldWritableWarningNotification,
180} as const;
packages/effect-codex-app-server/src/_generated/schema.gen.ts created+31734
...@@ -0,0 +1,31734 @@
1// This file is generated by the effect-codex-app-server package. Do not edit manually.
2// Upstream protocol ref: dbfe855f4fd0f5dcdf079882652a8efe622b0595
3
4import * as Schema from "effect/Schema";
5
6export type ApplyPatchApprovalParams__FileChange =
7 | { readonly content: string; readonly type: "add" }
8 | { readonly content: string; readonly type: "delete" }
9 | { readonly move_path?: string | null; readonly type: "update"; readonly unified_diff: string };
10export const ApplyPatchApprovalParams__FileChange = Schema.Union(
11 [
12 Schema.Struct({
13 content: Schema.String,
14 type: Schema.Literal("add").annotate({ title: "AddFileChangeType" }),
15 }).annotate({ title: "AddFileChange" }),
16 Schema.Struct({
17 content: Schema.String,
18 type: Schema.Literal("delete").annotate({ title: "DeleteFileChangeType" }),
19 }).annotate({ title: "DeleteFileChange" }),
20 Schema.Struct({
21 move_path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
22 type: Schema.Literal("update").annotate({ title: "UpdateFileChangeType" }),
23 unified_diff: Schema.String,
24 }).annotate({ title: "UpdateFileChange" }),
25 ],
26 { mode: "oneOf" },
27);
28
29export type ApplyPatchApprovalParams__ThreadId = string;
30export const ApplyPatchApprovalParams__ThreadId = Schema.String;
31
32export type ApplyPatchApprovalResponse__NetworkPolicyRuleAction = "allow" | "deny";
33export const ApplyPatchApprovalResponse__NetworkPolicyRuleAction = Schema.Literals([
34 "allow",
35 "deny",
36]);
37
38export type ChatgptAuthTokensRefreshParams__ChatgptAuthTokensRefreshReason = "unauthorized";
39export const ChatgptAuthTokensRefreshParams__ChatgptAuthTokensRefreshReason =
40 Schema.Literal("unauthorized");
41
42export type ClientRequest__AbsolutePathBuf = string;
43export const ClientRequest__AbsolutePathBuf = Schema.String.annotate({
44 description:
45 "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.",
46});
47
48export type ClientRequest__ApprovalsReviewer = "user" | "guardian_subagent";
49export const ClientRequest__ApprovalsReviewer = Schema.Literals([
50 "user",
51 "guardian_subagent",
52]).annotate({
53 description:
54 "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.",
55});
56
57export type ClientRequest__AppsListParams = {
58 readonly cursor?: string | null;
59 readonly forceRefetch?: boolean;
60 readonly limit?: number | null;
61 readonly threadId?: string | null;
62};
63export const ClientRequest__AppsListParams = Schema.Struct({
64 cursor: Schema.optionalKey(
65 Schema.Union([
66 Schema.String.annotate({
67 description: "Opaque pagination cursor returned by a previous call.",
68 }),
69 Schema.Null,
70 ]),
71 ),
72 forceRefetch: Schema.optionalKey(
73 Schema.Boolean.annotate({
74 description: "When true, bypass app caches and fetch the latest data from sources.",
75 }),
76 ),
77 limit: Schema.optionalKey(
78 Schema.Union([
79 Schema.Number.annotate({
80 description: "Optional page size; defaults to a reasonable server-side value.",
81 format: "uint32",
82 })
83 .check(Schema.isInt())
84 .check(Schema.isGreaterThanOrEqualTo(0)),
85 Schema.Null,
86 ]),
87 ),
88 threadId: Schema.optionalKey(
89 Schema.Union([
90 Schema.String.annotate({
91 description:
92 "Optional thread id used to evaluate app feature gating from that thread's config.",
93 }),
94 Schema.Null,
95 ]),
96 ),
97}).annotate({ description: "EXPERIMENTAL - list available apps/connectors." });
98
99export type ClientRequest__AskForApproval =
100 | "untrusted"
101 | "on-failure"
102 | "on-request"
103 | "never"
104 | {
105 readonly granular: {
106 readonly mcp_elicitations: boolean;
107 readonly request_permissions?: boolean;
108 readonly rules: boolean;
109 readonly sandbox_approval: boolean;
110 readonly skill_approval?: boolean;
111 };
112 };
113export const ClientRequest__AskForApproval = Schema.Union(
114 [
115 Schema.Literals(["untrusted", "on-failure", "on-request", "never"]),
116 Schema.Struct({
117 granular: Schema.Struct({
118 mcp_elicitations: Schema.Boolean,
119 request_permissions: Schema.optionalKey(Schema.Boolean.annotate({ default: false })),
120 rules: Schema.Boolean,
121 sandbox_approval: Schema.Boolean,
122 skill_approval: Schema.optionalKey(Schema.Boolean.annotate({ default: false })),
123 }),
124 }).annotate({ title: "GranularAskForApproval" }),
125 ],
126 { mode: "oneOf" },
127);
128
129export type ClientRequest__CancelLoginAccountParams = { readonly loginId: string };
130export const ClientRequest__CancelLoginAccountParams = Schema.Struct({ loginId: Schema.String });
131
132export type ClientRequest__ClientInfo = {
133 readonly name: string;
134 readonly title?: string | null;
135 readonly version: string;
136};
137export const ClientRequest__ClientInfo = Schema.Struct({
138 name: Schema.String,
139 title: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
140 version: Schema.String,
141});
142
143export type ClientRequest__CommandExecResizeParams = {
144 readonly processId: string;
145 readonly size: { readonly cols: number; readonly rows: number };
146};
147export const ClientRequest__CommandExecResizeParams = Schema.Struct({
148 processId: Schema.String.annotate({
149 description:
150 "Client-supplied, connection-scoped `processId` from the original `command/exec` request.",
151 }),
152 size: Schema.Struct({
153 cols: Schema.Number.annotate({
154 description: "Terminal width in character cells.",
155 format: "uint16",
156 })
157 .check(Schema.isInt())
158 .check(Schema.isGreaterThanOrEqualTo(0)),
159 rows: Schema.Number.annotate({
160 description: "Terminal height in character cells.",
161 format: "uint16",
162 })
163 .check(Schema.isInt())
164 .check(Schema.isGreaterThanOrEqualTo(0)),
165 }).annotate({ description: "PTY size in character cells for `command/exec` PTY sessions." }),
166}).annotate({ description: "Resize a running PTY-backed `command/exec` session." });
167
168export type ClientRequest__CommandExecTerminalSize = {
169 readonly cols: number;
170 readonly rows: number;
171};
172export const ClientRequest__CommandExecTerminalSize = Schema.Struct({
173 cols: Schema.Number.annotate({
174 description: "Terminal width in character cells.",
175 format: "uint16",
176 })
177 .check(Schema.isInt())
178 .check(Schema.isGreaterThanOrEqualTo(0)),
179 rows: Schema.Number.annotate({
180 description: "Terminal height in character cells.",
181 format: "uint16",
182 })
183 .check(Schema.isInt())
184 .check(Schema.isGreaterThanOrEqualTo(0)),
185}).annotate({ description: "PTY size in character cells for `command/exec` PTY sessions." });
186
187export type ClientRequest__CommandExecTerminateParams = { readonly processId: string };
188export const ClientRequest__CommandExecTerminateParams = Schema.Struct({
189 processId: Schema.String.annotate({
190 description:
191 "Client-supplied, connection-scoped `processId` from the original `command/exec` request.",
192 }),
193}).annotate({ description: "Terminate a running `command/exec` session." });
194
195export type ClientRequest__CommandExecWriteParams = {
196 readonly closeStdin?: boolean;
197 readonly deltaBase64?: string | null;
198 readonly processId: string;
199};
200export const ClientRequest__CommandExecWriteParams = Schema.Struct({
201 closeStdin: Schema.optionalKey(
202 Schema.Boolean.annotate({
203 description: "Close stdin after writing `deltaBase64`, if present.",
204 }),
205 ),
206 deltaBase64: Schema.optionalKey(
207 Schema.Union([
208 Schema.String.annotate({ description: "Optional base64-encoded stdin bytes to write." }),
209 Schema.Null,
210 ]),
211 ),
212 processId: Schema.String.annotate({
213 description:
214 "Client-supplied, connection-scoped `processId` from the original `command/exec` request.",
215 }),
216}).annotate({
217 description: "Write stdin bytes to a running `command/exec` session, close stdin, or both.",
218});
219
220export type ClientRequest__ConfigReadParams = {
221 readonly cwd?: string | null;
222 readonly includeLayers?: boolean;
223};
224export const ClientRequest__ConfigReadParams = Schema.Struct({
225 cwd: Schema.optionalKey(
226 Schema.Union([
227 Schema.String.annotate({
228 description:
229 "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).",
230 }),
231 Schema.Null,
232 ]),
233 ),
234 includeLayers: Schema.optionalKey(Schema.Boolean.annotate({ default: false })),
235});
236
237export type ClientRequest__ContentItem =
238 | { readonly text: string; readonly type: "input_text" }
239 | { readonly image_url: string; readonly type: "input_image" }
240 | { readonly text: string; readonly type: "output_text" };
241export const ClientRequest__ContentItem = Schema.Union(
242 [
243 Schema.Struct({
244 text: Schema.String,
245 type: Schema.Literal("input_text").annotate({ title: "InputTextContentItemType" }),
246 }).annotate({ title: "InputTextContentItem" }),
247 Schema.Struct({
248 image_url: Schema.String,
249 type: Schema.Literal("input_image").annotate({ title: "InputImageContentItemType" }),
250 }).annotate({ title: "InputImageContentItem" }),
251 Schema.Struct({
252 text: Schema.String,
253 type: Schema.Literal("output_text").annotate({ title: "OutputTextContentItemType" }),
254 }).annotate({ title: "OutputTextContentItem" }),
255 ],
256 { mode: "oneOf" },
257);
258
259export type ClientRequest__ExperimentalFeatureEnablementSetParams = {
260 readonly enablement: { readonly [x: string]: boolean };
261};
262export const ClientRequest__ExperimentalFeatureEnablementSetParams = Schema.Struct({
263 enablement: Schema.Record(Schema.String, Schema.Boolean).annotate({
264 description:
265 "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.",
266 }),
267});
268
269export type ClientRequest__ExperimentalFeatureListParams = {
270 readonly cursor?: string | null;
271 readonly limit?: number | null;
272};
273export const ClientRequest__ExperimentalFeatureListParams = Schema.Struct({
274 cursor: Schema.optionalKey(
275 Schema.Union([
276 Schema.String.annotate({
277 description: "Opaque pagination cursor returned by a previous call.",
278 }),
279 Schema.Null,
280 ]),
281 ),
282 limit: Schema.optionalKey(
283 Schema.Union([
284 Schema.Number.annotate({
285 description: "Optional page size; defaults to a reasonable server-side value.",
286 format: "uint32",
287 })
288 .check(Schema.isInt())
289 .check(Schema.isGreaterThanOrEqualTo(0)),
290 Schema.Null,
291 ]),
292 ),
293});
294
295export type ClientRequest__ExternalAgentConfigDetectParams = {
296 readonly cwds?: ReadonlyArray<string> | null;
297 readonly includeHome?: boolean;
298};
299export const ClientRequest__ExternalAgentConfigDetectParams = Schema.Struct({
300 cwds: Schema.optionalKey(
301 Schema.Union([
302 Schema.Array(Schema.String).annotate({
303 description: "Zero or more working directories to include for repo-scoped detection.",
304 }),
305 Schema.Null,
306 ]),
307 ),
308 includeHome: Schema.optionalKey(
309 Schema.Boolean.annotate({
310 description: "If true, include detection under the user's home (~/.claude, ~/.codex, etc.).",
311 }),
312 ),
313});
314
315export type ClientRequest__ExternalAgentConfigMigrationItemType =
316 | "AGENTS_MD"
317 | "CONFIG"
318 | "SKILLS"
319 | "MCP_SERVER_CONFIG";
320export const ClientRequest__ExternalAgentConfigMigrationItemType = Schema.Literals([
321 "AGENTS_MD",
322 "CONFIG",
323 "SKILLS",
324 "MCP_SERVER_CONFIG",
325]);
326
327export type ClientRequest__FeedbackUploadParams = {
328 readonly classification: string;
329 readonly extraLogFiles?: ReadonlyArray<string> | null;
330 readonly includeLogs: boolean;
331 readonly reason?: string | null;
332 readonly threadId?: string | null;
333};
334export const ClientRequest__FeedbackUploadParams = Schema.Struct({
335 classification: Schema.String,
336 extraLogFiles: Schema.optionalKey(Schema.Union([Schema.Array(Schema.String), Schema.Null])),
337 includeLogs: Schema.Boolean,
338 reason: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
339 threadId: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
340});
341
342export type ClientRequest__FsCopyParams = {
343 readonly destinationPath: string;
344 readonly recursive?: boolean;
345 readonly sourcePath: string;
346};
347export const ClientRequest__FsCopyParams = Schema.Struct({
348 destinationPath: Schema.String.annotate({
349 description:
350 "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.",
351 }),
352 recursive: Schema.optionalKey(
353 Schema.Boolean.annotate({
354 description: "Required for directory copies; ignored for file copies.",
355 }),
356 ),
357 sourcePath: Schema.String.annotate({
358 description:
359 "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.",
360 }),
361}).annotate({ description: "Copy a file or directory tree on the host filesystem." });
362
363export type ClientRequest__FsCreateDirectoryParams = {
364 readonly path: string;
365 readonly recursive?: boolean | null;
366};
367export const ClientRequest__FsCreateDirectoryParams = Schema.Struct({
368 path: Schema.String.annotate({
369 description:
370 "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.",
371 }),
372 recursive: Schema.optionalKey(
373 Schema.Union([
374 Schema.Boolean.annotate({
375 description: "Whether parent directories should also be created. Defaults to `true`.",
376 }),
377 Schema.Null,
378 ]),
379 ),
380}).annotate({ description: "Create a directory on the host filesystem." });
381
382export type ClientRequest__FsGetMetadataParams = { readonly path: string };
383export const ClientRequest__FsGetMetadataParams = Schema.Struct({
384 path: Schema.String.annotate({
385 description:
386 "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.",
387 }),
388}).annotate({ description: "Request metadata for an absolute path." });
389
390export type ClientRequest__FsReadDirectoryParams = { readonly path: string };
391export const ClientRequest__FsReadDirectoryParams = Schema.Struct({
392 path: Schema.String.annotate({
393 description:
394 "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.",
395 }),
396}).annotate({ description: "List direct child names for a directory." });
397
398export type ClientRequest__FsReadFileParams = { readonly path: string };
399export const ClientRequest__FsReadFileParams = Schema.Struct({
400 path: Schema.String.annotate({
401 description:
402 "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.",
403 }),
404}).annotate({ description: "Read a file from the host filesystem." });
405
406export type ClientRequest__FsRemoveParams = {
407 readonly force?: boolean | null;
408 readonly path: string;
409 readonly recursive?: boolean | null;
410};
411export const ClientRequest__FsRemoveParams = Schema.Struct({
412 force: Schema.optionalKey(
413 Schema.Union([
414 Schema.Boolean.annotate({
415 description: "Whether missing paths should be ignored. Defaults to `true`.",
416 }),
417 Schema.Null,
418 ]),
419 ),
420 path: Schema.String.annotate({
421 description:
422 "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.",
423 }),
424 recursive: Schema.optionalKey(
425 Schema.Union([
426 Schema.Boolean.annotate({
427 description: "Whether directory removal should recurse. Defaults to `true`.",
428 }),
429 Schema.Null,
430 ]),
431 ),
432}).annotate({ description: "Remove a file or directory tree from the host filesystem." });
433
434export type ClientRequest__FsUnwatchParams = { readonly watchId: string };
435export const ClientRequest__FsUnwatchParams = Schema.Struct({
436 watchId: Schema.String.annotate({
437 description: "Watch identifier previously provided to `fs/watch`.",
438 }),
439}).annotate({ description: "Stop filesystem watch notifications for a prior `fs/watch`." });
440
441export type ClientRequest__FsWatchParams = { readonly path: string; readonly watchId: string };
442export const ClientRequest__FsWatchParams = Schema.Struct({
443 path: Schema.String.annotate({
444 description:
445 "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.",
446 }),
447 watchId: Schema.String.annotate({
448 description: "Connection-scoped watch identifier used for `fs/unwatch` and `fs/changed`.",
449 }),
450}).annotate({ description: "Start filesystem watch notifications for an absolute path." });
451
452export type ClientRequest__FsWriteFileParams = {
453 readonly dataBase64: string;
454 readonly path: string;
455};
456export const ClientRequest__FsWriteFileParams = Schema.Struct({
457 dataBase64: Schema.String.annotate({ description: "File contents encoded as base64." }),
458 path: Schema.String.annotate({
459 description:
460 "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.",
461 }),
462}).annotate({ description: "Write a file on the host filesystem." });
463
464export type ClientRequest__FuzzyFileSearchParams = {
465 readonly cancellationToken?: string | null;
466 readonly query: string;
467 readonly roots: ReadonlyArray<string>;
468};
469export const ClientRequest__FuzzyFileSearchParams = Schema.Struct({
470 cancellationToken: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
471 query: Schema.String,
472 roots: Schema.Array(Schema.String),
473});
474
475export type ClientRequest__GetAccountParams = { readonly refreshToken?: boolean };
476export const ClientRequest__GetAccountParams = Schema.Struct({
477 refreshToken: Schema.optionalKey(
478 Schema.Boolean.annotate({
479 description:
480 "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`.",
481 default: false,
482 }),
483 ),
484});
485
486export type ClientRequest__GhostCommit = {
487 readonly id: string;
488 readonly parent?: string | null;
489 readonly preexisting_untracked_dirs: ReadonlyArray<string>;
490 readonly preexisting_untracked_files: ReadonlyArray<string>;
491};
492export const ClientRequest__GhostCommit = Schema.Struct({
493 id: Schema.String,
494 parent: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
495 preexisting_untracked_dirs: Schema.Array(Schema.String),
496 preexisting_untracked_files: Schema.Array(Schema.String),
497}).annotate({ description: "Details of a ghost commit created from a repository state." });
498
499export type ClientRequest__ImageDetail = "auto" | "low" | "high" | "original";
500export const ClientRequest__ImageDetail = Schema.Literals(["auto", "low", "high", "original"]);
501
502export type ClientRequest__InitializeCapabilities = {
503 readonly experimentalApi?: boolean;
504 readonly optOutNotificationMethods?: ReadonlyArray<string> | null;
505};
506export const ClientRequest__InitializeCapabilities = Schema.Struct({
507 experimentalApi: Schema.optionalKey(
508 Schema.Boolean.annotate({
509 description: "Opt into receiving experimental API methods and fields.",
510 default: false,
511 }),
512 ),
513 optOutNotificationMethods: Schema.optionalKey(
514 Schema.Union([
515 Schema.Array(Schema.String).annotate({
516 description:
517 "Exact notification method names that should be suppressed for this connection (for example `thread/started`).",
518 }),
519 Schema.Null,
520 ]),
521 ),
522}).annotate({ description: "Client-declared capabilities negotiated during initialize." });
523
524export type ClientRequest__LocalShellAction = {
525 readonly command: ReadonlyArray<string>;
526 readonly env?: { readonly [x: string]: string } | null;
527 readonly timeout_ms?: number | null;
528 readonly type: "exec";
529 readonly user?: string | null;
530 readonly working_directory?: string | null;
531};
532export const ClientRequest__LocalShellAction = Schema.Union(
533 [
534 Schema.Struct({
535 command: Schema.Array(Schema.String),
536 env: Schema.optionalKey(
537 Schema.Union([Schema.Record(Schema.String, Schema.String), Schema.Null]),
538 ),
539 timeout_ms: Schema.optionalKey(
540 Schema.Union([
541 Schema.Number.annotate({ format: "uint64" })
542 .check(Schema.isInt())
543 .check(Schema.isGreaterThanOrEqualTo(0)),
544 Schema.Null,
545 ]),
546 ),
547 type: Schema.Literal("exec").annotate({ title: "ExecLocalShellActionType" }),
548 user: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
549 working_directory: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
550 }).annotate({ title: "ExecLocalShellAction" }),
551 ],
552 { mode: "oneOf" },
553);
554
555export type ClientRequest__LocalShellStatus = "completed" | "in_progress" | "incomplete";
556export const ClientRequest__LocalShellStatus = Schema.Literals([
557 "completed",
558 "in_progress",
559 "incomplete",
560]);
561
562export type ClientRequest__LoginAccountParams =
563 | { readonly apiKey: string; readonly type: "apiKey" }
564 | { readonly type: "chatgpt" }
565 | { readonly type: "chatgptDeviceCode" }
566 | {
567 readonly accessToken: string;
568 readonly chatgptAccountId: string;
569 readonly chatgptPlanType?: string | null;
570 readonly type: "chatgptAuthTokens";
571 };
572export const ClientRequest__LoginAccountParams = Schema.Union(
573 [
574 Schema.Struct({
575 apiKey: Schema.String,
576 type: Schema.Literal("apiKey").annotate({ title: "ApiKeyLoginAccountParamsType" }),
577 }).annotate({ title: "ApiKeyLoginAccountParams" }),
578 Schema.Struct({
579 type: Schema.Literal("chatgpt").annotate({ title: "ChatgptLoginAccountParamsType" }),
580 }).annotate({ title: "ChatgptLoginAccountParams" }),
581 Schema.Struct({
582 type: Schema.Literal("chatgptDeviceCode").annotate({
583 title: "ChatgptDeviceCodeLoginAccountParamsType",
584 }),
585 }).annotate({ title: "ChatgptDeviceCodeLoginAccountParams" }),
586 Schema.Struct({
587 accessToken: Schema.String.annotate({
588 description:
589 "Access token (JWT) supplied by the client. This token is used for backend API requests and email extraction.",
590 }),
591 chatgptAccountId: Schema.String.annotate({
592 description: "Workspace/account identifier supplied by the client.",
593 }),
594 chatgptPlanType: Schema.optionalKey(
595 Schema.Union([
596 Schema.String.annotate({
597 description:
598 "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`.",
599 }),
600 Schema.Null,
601 ]),
602 ),
603 type: Schema.Literal("chatgptAuthTokens").annotate({
604 title: "ChatgptAuthTokensLoginAccountParamsType",
605 }),
606 }).annotate({
607 title: "ChatgptAuthTokensLoginAccountParams",
608 description:
609 "[UNSTABLE] FOR OPENAI INTERNAL USE ONLY - DO NOT USE. The access token must contain the same scopes that Codex-managed ChatGPT auth tokens have.",
610 }),
611 ],
612 { mode: "oneOf" },
613);
614
615export type ClientRequest__McpResourceReadParams = {
616 readonly server: string;
617 readonly threadId: string;
618 readonly uri: string;
619};
620export const ClientRequest__McpResourceReadParams = Schema.Struct({
621 server: Schema.String,
622 threadId: Schema.String,
623 uri: Schema.String,
624});
625
626export type ClientRequest__McpServerOauthLoginParams = {
627 readonly name: string;
628 readonly scopes?: ReadonlyArray<string> | null;
629 readonly timeoutSecs?: number | null;
630};
631export const ClientRequest__McpServerOauthLoginParams = Schema.Struct({
632 name: Schema.String,
633 scopes: Schema.optionalKey(Schema.Union([Schema.Array(Schema.String), Schema.Null])),
634 timeoutSecs: Schema.optionalKey(
635 Schema.Union([Schema.Number.annotate({ format: "int64" }).check(Schema.isInt()), Schema.Null]),
636 ),
637});
638
639export type ClientRequest__McpServerStatusDetail = "full" | "toolsAndAuthOnly";
640export const ClientRequest__McpServerStatusDetail = Schema.Literals(["full", "toolsAndAuthOnly"]);
641
642export type ClientRequest__McpServerToolCallParams = {
643 readonly _meta?: unknown;
644 readonly arguments?: unknown;
645 readonly server: string;
646 readonly threadId: string;
647 readonly tool: string;
648};
649export const ClientRequest__McpServerToolCallParams = Schema.Struct({
650 _meta: Schema.optionalKey(Schema.Unknown),
651 arguments: Schema.optionalKey(Schema.Unknown),
652 server: Schema.String,
653 threadId: Schema.String,
654 tool: Schema.String,
655});
656
657export type ClientRequest__MergeStrategy = "replace" | "upsert";
658export const ClientRequest__MergeStrategy = Schema.Literals(["replace", "upsert"]);
659
660export type ClientRequest__MessagePhase = "commentary" | "final_answer";
661export const ClientRequest__MessagePhase = Schema.Literals(["commentary", "final_answer"]).annotate(
662 {
663 description:
664 '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.',
665 },
666);
667
668export type ClientRequest__ModeKind = "plan" | "default";
669export const ClientRequest__ModeKind = Schema.Literals(["plan", "default"]).annotate({
670 description: "Initial collaboration mode to use when the TUI starts.",
671});
672
673export type ClientRequest__ModelListParams = {
674 readonly cursor?: string | null;
675 readonly includeHidden?: boolean | null;
676 readonly limit?: number | null;
677};
678export const ClientRequest__ModelListParams = Schema.Struct({
679 cursor: Schema.optionalKey(
680 Schema.Union([
681 Schema.String.annotate({
682 description: "Opaque pagination cursor returned by a previous call.",
683 }),
684 Schema.Null,
685 ]),
686 ),
687 includeHidden: Schema.optionalKey(
688 Schema.Union([
689 Schema.Boolean.annotate({
690 description: "When true, include models that are hidden from the default picker list.",
691 }),
692 Schema.Null,
693 ]),
694 ),
695 limit: Schema.optionalKey(
696 Schema.Union([
697 Schema.Number.annotate({
698 description: "Optional page size; defaults to a reasonable server-side value.",
699 format: "uint32",
700 })
701 .check(Schema.isInt())
702 .check(Schema.isGreaterThanOrEqualTo(0)),
703 Schema.Null,
704 ]),
705 ),
706});
707
708export type ClientRequest__Personality = "none" | "friendly" | "pragmatic";
709export const ClientRequest__Personality = Schema.Literals(["none", "friendly", "pragmatic"]);
710
711export type ClientRequest__PluginUninstallParams = {
712 readonly forceRemoteSync?: boolean;
713 readonly pluginId: string;
714};
715export const ClientRequest__PluginUninstallParams = Schema.Struct({
716 forceRemoteSync: Schema.optionalKey(
717 Schema.Boolean.annotate({
718 description: "When true, apply the remote plugin change before the local uninstall flow.",
719 }),
720 ),
721 pluginId: Schema.String,
722});
723
724export type ClientRequest__ReasoningEffort =
725 | "none"
726 | "minimal"
727 | "low"
728 | "medium"
729 | "high"
730 | "xhigh";
731export const ClientRequest__ReasoningEffort = Schema.Literals([
732 "none",
733 "minimal",
734 "low",
735 "medium",
736 "high",
737 "xhigh",
738]).annotate({
739 description:
740 "See https://platform.openai.com/docs/guides/reasoning?api-mode=responses#get-started-with-reasoning",
741});
742
743export type ClientRequest__ReasoningItemContent =
744 | { readonly text: string; readonly type: "reasoning_text" }
745 | { readonly text: string; readonly type: "text" };
746export const ClientRequest__ReasoningItemContent = Schema.Union(
747 [
748 Schema.Struct({
749 text: Schema.String,
750 type: Schema.Literal("reasoning_text").annotate({
751 title: "ReasoningTextReasoningItemContentType",
752 }),
753 }).annotate({ title: "ReasoningTextReasoningItemContent" }),
754 Schema.Struct({
755 text: Schema.String,
756 type: Schema.Literal("text").annotate({ title: "TextReasoningItemContentType" }),
757 }).annotate({ title: "TextReasoningItemContent" }),
758 ],
759 { mode: "oneOf" },
760);
761
762export type ClientRequest__ReasoningItemReasoningSummary = {
763 readonly text: string;
764 readonly type: "summary_text";
765};
766export const ClientRequest__ReasoningItemReasoningSummary = Schema.Union(
767 [
768 Schema.Struct({
769 text: Schema.String,
770 type: Schema.Literal("summary_text").annotate({
771 title: "SummaryTextReasoningItemReasoningSummaryType",
772 }),
773 }).annotate({ title: "SummaryTextReasoningItemReasoningSummary" }),
774 ],
775 { mode: "oneOf" },
776);
777
778export type ClientRequest__ReasoningSummary = "auto" | "concise" | "detailed" | "none";
779export const ClientRequest__ReasoningSummary = Schema.Union(
780 [
781 Schema.Literals(["auto", "concise", "detailed"]),
782 Schema.Literal("none").annotate({ description: "Option to disable reasoning summaries." }),
783 ],
784 { mode: "oneOf" },
785).annotate({
786 description:
787 "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",
788});
789
790export type ClientRequest__RequestId = string | number;
791export const ClientRequest__RequestId = Schema.Union([
792 Schema.String,
793 Schema.Number.annotate({ format: "int64" }).check(Schema.isInt()),
794]);
795
796export type ClientRequest__ResponsesApiWebSearchAction =
797 | {
798 readonly queries?: ReadonlyArray<string> | null;
799 readonly query?: string | null;
800 readonly type: "search";
801 }
802 | { readonly type: "open_page"; readonly url?: string | null }
803 | {
804 readonly pattern?: string | null;
805 readonly type: "find_in_page";
806 readonly url?: string | null;
807 }
808 | { readonly type: "other" };
809export const ClientRequest__ResponsesApiWebSearchAction = Schema.Union(
810 [
811 Schema.Struct({
812 queries: Schema.optionalKey(Schema.Union([Schema.Array(Schema.String), Schema.Null])),
813 query: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
814 type: Schema.Literal("search").annotate({ title: "SearchResponsesApiWebSearchActionType" }),
815 }).annotate({ title: "SearchResponsesApiWebSearchAction" }),
816 Schema.Struct({
817 type: Schema.Literal("open_page").annotate({
818 title: "OpenPageResponsesApiWebSearchActionType",
819 }),
820 url: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
821 }).annotate({ title: "OpenPageResponsesApiWebSearchAction" }),
822 Schema.Struct({
823 pattern: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
824 type: Schema.Literal("find_in_page").annotate({
825 title: "FindInPageResponsesApiWebSearchActionType",
826 }),
827 url: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
828 }).annotate({ title: "FindInPageResponsesApiWebSearchAction" }),
829 Schema.Struct({
830 type: Schema.Literal("other").annotate({ title: "OtherResponsesApiWebSearchActionType" }),
831 }).annotate({ title: "OtherResponsesApiWebSearchAction" }),
832 ],
833 { mode: "oneOf" },
834);
835
836export type ClientRequest__ReviewDelivery = "inline" | "detached";
837export const ClientRequest__ReviewDelivery = Schema.Literals(["inline", "detached"]);
838
839export type ClientRequest__ReviewTarget =
840 | { readonly type: "uncommittedChanges" }
841 | { readonly branch: string; readonly type: "baseBranch" }
842 | { readonly sha: string; readonly title?: string | null; readonly type: "commit" }
843 | { readonly instructions: string; readonly type: "custom" };
844export const ClientRequest__ReviewTarget = Schema.Union(
845 [
846 Schema.Struct({
847 type: Schema.Literal("uncommittedChanges").annotate({
848 title: "UncommittedChangesReviewTargetType",
849 }),
850 }).annotate({
851 title: "UncommittedChangesReviewTarget",
852 description: "Review the working tree: staged, unstaged, and untracked files.",
853 }),
854 Schema.Struct({
855 branch: Schema.String,
856 type: Schema.Literal("baseBranch").annotate({ title: "BaseBranchReviewTargetType" }),
857 }).annotate({
858 title: "BaseBranchReviewTarget",
859 description: "Review changes between the current branch and the given base branch.",
860 }),
861 Schema.Struct({
862 sha: Schema.String,
863 title: Schema.optionalKey(
864 Schema.Union([
865 Schema.String.annotate({
866 description: "Optional human-readable label (e.g., commit subject) for UIs.",
867 }),
868 Schema.Null,
869 ]),
870 ),
871 type: Schema.Literal("commit").annotate({ title: "CommitReviewTargetType" }),
872 }).annotate({
873 title: "CommitReviewTarget",
874 description: "Review the changes introduced by a specific commit.",
875 }),
876 Schema.Struct({
877 instructions: Schema.String,
878 type: Schema.Literal("custom").annotate({ title: "CustomReviewTargetType" }),
879 }).annotate({
880 title: "CustomReviewTarget",
881 description: "Arbitrary instructions, equivalent to the old free-form prompt.",
882 }),
883 ],
884 { mode: "oneOf" },
885);
886
887export type ClientRequest__SandboxMode = "read-only" | "workspace-write" | "danger-full-access";
888export const ClientRequest__SandboxMode = Schema.Literals([
889 "read-only",
890 "workspace-write",
891 "danger-full-access",
892]);
893
894export type ClientRequest__ServiceTier = "fast" | "flex";
895export const ClientRequest__ServiceTier = Schema.Literals(["fast", "flex"]);
896
897export type ClientRequest__SkillsListExtraRootsForCwd = {
898 readonly cwd: string;
899 readonly extraUserRoots: ReadonlyArray<string>;
900};
901export const ClientRequest__SkillsListExtraRootsForCwd = Schema.Struct({
902 cwd: Schema.String,
903 extraUserRoots: Schema.Array(Schema.String),
904});
905
906export type ClientRequest__TextElement = {
907 readonly byteRange: { readonly end: number; readonly start: number };
908 readonly placeholder?: string | null;
909};
910export const ClientRequest__TextElement = Schema.Struct({
911 byteRange: Schema.Struct({
912 end: Schema.Number.annotate({ format: "uint" })
913 .check(Schema.isInt())
914 .check(Schema.isGreaterThanOrEqualTo(0)),
915 start: Schema.Number.annotate({ format: "uint" })
916 .check(Schema.isInt())
917 .check(Schema.isGreaterThanOrEqualTo(0)),
918 }).annotate({
919 description: "Byte range in the parent `text` buffer that this element occupies.",
920 }),
921 placeholder: Schema.optionalKey(
922 Schema.Union([
923 Schema.String.annotate({
924 description: "Optional human-readable placeholder for the element, displayed in the UI.",
925 }),
926 Schema.Null,
927 ]),
928 ),
929});
930
931export type ClientRequest__ThreadArchiveParams = { readonly threadId: string };
932export const ClientRequest__ThreadArchiveParams = Schema.Struct({ threadId: Schema.String });
933
934export type ClientRequest__ThreadCompactStartParams = { readonly threadId: string };
935export const ClientRequest__ThreadCompactStartParams = Schema.Struct({ threadId: Schema.String });
936
937export type ClientRequest__ThreadLoadedListParams = {
938 readonly cursor?: string | null;
939 readonly limit?: number | null;
940};
941export const ClientRequest__ThreadLoadedListParams = Schema.Struct({
942 cursor: Schema.optionalKey(
943 Schema.Union([
944 Schema.String.annotate({
945 description: "Opaque pagination cursor returned by a previous call.",
946 }),
947 Schema.Null,
948 ]),
949 ),
950 limit: Schema.optionalKey(
951 Schema.Union([
952 Schema.Number.annotate({
953 description: "Optional page size; defaults to no limit.",
954 format: "uint32",
955 })
956 .check(Schema.isInt())
957 .check(Schema.isGreaterThanOrEqualTo(0)),
958 Schema.Null,
959 ]),
960 ),
961});
962
963export type ClientRequest__ThreadMetadataGitInfoUpdateParams = {
964 readonly branch?: string | null;
965 readonly originUrl?: string | null;
966 readonly sha?: string | null;
967};
968export const ClientRequest__ThreadMetadataGitInfoUpdateParams = Schema.Struct({
969 branch: Schema.optionalKey(
970 Schema.Union([
971 Schema.String.annotate({
972 description:
973 "Omit to leave the stored branch unchanged, set to `null` to clear it, or provide a non-empty string to replace it.",
974 }),
975 Schema.Null,
976 ]),
977 ),
978 originUrl: Schema.optionalKey(
979 Schema.Union([
980 Schema.String.annotate({
981 description:
982 "Omit to leave the stored origin URL unchanged, set to `null` to clear it, or provide a non-empty string to replace it.",
983 }),
984 Schema.Null,
985 ]),
986 ),
987 sha: Schema.optionalKey(
988 Schema.Union([
989 Schema.String.annotate({
990 description:
991 "Omit to leave the stored commit unchanged, set to `null` to clear it, or provide a non-empty string to replace it.",
992 }),
993 Schema.Null,
994 ]),
995 ),
996});
997
998export type ClientRequest__ThreadReadParams = {
999 readonly includeTurns?: boolean;
1000 readonly threadId: string;
1001};
1002export const ClientRequest__ThreadReadParams = Schema.Struct({
1003 includeTurns: Schema.optionalKey(
1004 Schema.Boolean.annotate({
1005 description: "When true, include turns and their items from rollout history.",
1006 default: false,
1007 }),
1008 ),
1009 threadId: Schema.String,
1010});
1011
1012export type ClientRequest__ThreadRollbackParams = {
1013 readonly numTurns: number;
1014 readonly threadId: string;
1015};
1016export const ClientRequest__ThreadRollbackParams = Schema.Struct({
1017 numTurns: Schema.Number.annotate({
1018 description:
1019 "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.",
1020 format: "uint32",
1021 })
1022 .check(Schema.isInt())
1023 .check(Schema.isGreaterThanOrEqualTo(0)),
1024 threadId: Schema.String,
1025});
1026
1027export type ClientRequest__ThreadSetNameParams = {
1028 readonly name: string;
1029 readonly threadId: string;
1030};
1031export const ClientRequest__ThreadSetNameParams = Schema.Struct({
1032 name: Schema.String,
1033 threadId: Schema.String,
1034});
1035
1036export type ClientRequest__ThreadShellCommandParams = {
1037 readonly command: string;
1038 readonly threadId: string;
1039};
1040export const ClientRequest__ThreadShellCommandParams = Schema.Struct({
1041 command: Schema.String.annotate({
1042 description:
1043 "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.",
1044 }),
1045 threadId: Schema.String,
1046});
1047
1048export type ClientRequest__ThreadSortKey = "created_at" | "updated_at";
1049export const ClientRequest__ThreadSortKey = Schema.Literals(["created_at", "updated_at"]);
1050
1051export type ClientRequest__ThreadSourceKind =
1052 | "cli"
1053 | "vscode"
1054 | "exec"
1055 | "appServer"
1056 | "subAgent"
1057 | "subAgentReview"
1058 | "subAgentCompact"
1059 | "subAgentThreadSpawn"
1060 | "subAgentOther"
1061 | "unknown";
1062export const ClientRequest__ThreadSourceKind = Schema.Literals([
1063 "cli",
1064 "vscode",
1065 "exec",
1066 "appServer",
1067 "subAgent",
1068 "subAgentReview",
1069 "subAgentCompact",
1070 "subAgentThreadSpawn",
1071 "subAgentOther",
1072 "unknown",
1073]);
1074
1075export type ClientRequest__ThreadStartSource = "startup" | "clear";
1076export const ClientRequest__ThreadStartSource = Schema.Literals(["startup", "clear"]);
1077
1078export type ClientRequest__ThreadUnarchiveParams = { readonly threadId: string };
1079export const ClientRequest__ThreadUnarchiveParams = Schema.Struct({ threadId: Schema.String });
1080
1081export type ClientRequest__ThreadUnsubscribeParams = { readonly threadId: string };
1082export const ClientRequest__ThreadUnsubscribeParams = Schema.Struct({ threadId: Schema.String });
1083
1084export type ClientRequest__TurnInterruptParams = {
1085 readonly threadId: string;
1086 readonly turnId: string;
1087};
1088export const ClientRequest__TurnInterruptParams = Schema.Struct({
1089 threadId: Schema.String,
1090 turnId: Schema.String,
1091});
1092
1093export type ClientRequest__WindowsSandboxSetupMode = "elevated" | "unelevated";
1094export const ClientRequest__WindowsSandboxSetupMode = Schema.Literals(["elevated", "unelevated"]);
1095
1096export type CommandExecutionRequestApprovalParams__AbsolutePathBuf = string;
1097export const CommandExecutionRequestApprovalParams__AbsolutePathBuf = Schema.String.annotate({
1098 description:
1099 "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.",
1100});
1101
1102export type CommandExecutionRequestApprovalParams__AdditionalNetworkPermissions = {
1103 readonly enabled?: boolean | null;
1104};
1105export const CommandExecutionRequestApprovalParams__AdditionalNetworkPermissions = Schema.Struct({
1106 enabled: Schema.optionalKey(Schema.Union([Schema.Boolean, Schema.Null])),
1107});
1108
1109export type CommandExecutionRequestApprovalParams__CommandAction =
1110 | {
1111 readonly command: string;
1112 readonly name: string;
1113 readonly path: string;
1114 readonly type: "read";
1115 }
1116 | { readonly command: string; readonly path?: string | null; readonly type: "listFiles" }
1117 | {
1118 readonly command: string;
1119 readonly path?: string | null;
1120 readonly query?: string | null;
1121 readonly type: "search";
1122 }
1123 | { readonly command: string; readonly type: "unknown" };
1124export const CommandExecutionRequestApprovalParams__CommandAction = Schema.Union(
1125 [
1126 Schema.Struct({
1127 command: Schema.String,
1128 name: Schema.String,
1129 path: Schema.String,
1130 type: Schema.Literal("read").annotate({ title: "ReadCommandActionType" }),
1131 }).annotate({ title: "ReadCommandAction" }),
1132 Schema.Struct({
1133 command: Schema.String,
1134 path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
1135 type: Schema.Literal("listFiles").annotate({ title: "ListFilesCommandActionType" }),
1136 }).annotate({ title: "ListFilesCommandAction" }),
1137 Schema.Struct({
1138 command: Schema.String,
1139 path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
1140 query: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
1141 type: Schema.Literal("search").annotate({ title: "SearchCommandActionType" }),
1142 }).annotate({ title: "SearchCommandAction" }),
1143 Schema.Struct({
1144 command: Schema.String,
1145 type: Schema.Literal("unknown").annotate({ title: "UnknownCommandActionType" }),
1146 }).annotate({ title: "UnknownCommandAction" }),
1147 ],
1148 { mode: "oneOf" },
1149);
1150
1151export type CommandExecutionRequestApprovalParams__NetworkApprovalProtocol =
1152 | "http"
1153 | "https"
1154 | "socks5Tcp"
1155 | "socks5Udp";
1156export const CommandExecutionRequestApprovalParams__NetworkApprovalProtocol = Schema.Literals([
1157 "http",
1158 "https",
1159 "socks5Tcp",
1160 "socks5Udp",
1161]);
1162
1163export type CommandExecutionRequestApprovalParams__NetworkPolicyRuleAction = "allow" | "deny";
1164export const CommandExecutionRequestApprovalParams__NetworkPolicyRuleAction = Schema.Literals([
1165 "allow",
1166 "deny",
1167]);
1168
1169export type CommandExecutionRequestApprovalResponse__NetworkPolicyRuleAction = "allow" | "deny";
1170export const CommandExecutionRequestApprovalResponse__NetworkPolicyRuleAction = Schema.Literals([
1171 "allow",
1172 "deny",
1173]);
1174
1175export type DynamicToolCallResponse__DynamicToolCallOutputContentItem =
1176 | { readonly text: string; readonly type: "inputText" }
1177 | { readonly imageUrl: string; readonly type: "inputImage" };
1178export const DynamicToolCallResponse__DynamicToolCallOutputContentItem = Schema.Union(
1179 [
1180 Schema.Struct({
1181 text: Schema.String,
1182 type: Schema.Literal("inputText").annotate({
1183 title: "InputTextDynamicToolCallOutputContentItemType",
1184 }),
1185 }).annotate({ title: "InputTextDynamicToolCallOutputContentItem" }),
1186 Schema.Struct({
1187 imageUrl: Schema.String,
1188 type: Schema.Literal("inputImage").annotate({
1189 title: "InputImageDynamicToolCallOutputContentItemType",
1190 }),
1191 }).annotate({ title: "InputImageDynamicToolCallOutputContentItem" }),
1192 ],
1193 { mode: "oneOf" },
1194);
1195
1196export type ExecCommandApprovalParams__ParsedCommand =
1197 | { readonly cmd: string; readonly name: string; readonly path: string; readonly type: "read" }
1198 | { readonly cmd: string; readonly path?: string | null; readonly type: "list_files" }
1199 | {
1200 readonly cmd: string;
1201 readonly path?: string | null;
1202 readonly query?: string | null;
1203 readonly type: "search";
1204 }
1205 | { readonly cmd: string; readonly type: "unknown" };
1206export const ExecCommandApprovalParams__ParsedCommand = Schema.Union(
1207 [
1208 Schema.Struct({
1209 cmd: Schema.String,
1210 name: Schema.String,
1211 path: Schema.String.annotate({
1212 description:
1213 "(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.",
1214 }),
1215 type: Schema.Literal("read").annotate({ title: "ReadParsedCommandType" }),
1216 }).annotate({ title: "ReadParsedCommand" }),
1217 Schema.Struct({
1218 cmd: Schema.String,
1219 path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
1220 type: Schema.Literal("list_files").annotate({ title: "ListFilesParsedCommandType" }),
1221 }).annotate({ title: "ListFilesParsedCommand" }),
1222 Schema.Struct({
1223 cmd: Schema.String,
1224 path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
1225 query: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
1226 type: Schema.Literal("search").annotate({ title: "SearchParsedCommandType" }),
1227 }).annotate({ title: "SearchParsedCommand" }),
1228 Schema.Struct({
1229 cmd: Schema.String,
1230 type: Schema.Literal("unknown").annotate({ title: "UnknownParsedCommandType" }),
1231 }).annotate({ title: "UnknownParsedCommand" }),
1232 ],
1233 { mode: "oneOf" },
1234);
1235
1236export type ExecCommandApprovalParams__ThreadId = string;
1237export const ExecCommandApprovalParams__ThreadId = Schema.String;
1238
1239export type ExecCommandApprovalResponse__NetworkPolicyRuleAction = "allow" | "deny";
1240export const ExecCommandApprovalResponse__NetworkPolicyRuleAction = Schema.Literals([
1241 "allow",
1242 "deny",
1243]);
1244
1245export type FileChangeRequestApprovalResponse__FileChangeApprovalDecision =
1246 | "accept"
1247 | "acceptForSession"
1248 | "decline"
1249 | "cancel";
1250export const FileChangeRequestApprovalResponse__FileChangeApprovalDecision = Schema.Literals([
1251 "accept",
1252 "acceptForSession",
1253 "decline",
1254 "cancel",
1255]);
1256
1257export type FuzzyFileSearchResponse__FuzzyFileSearchMatchType = "file" | "directory";
1258export const FuzzyFileSearchResponse__FuzzyFileSearchMatchType = Schema.Literals([
1259 "file",
1260 "directory",
1261]);
1262
1263export type FuzzyFileSearchSessionUpdatedNotification__FuzzyFileSearchMatchType =
1264 | "file"
1265 | "directory";
1266export const FuzzyFileSearchSessionUpdatedNotification__FuzzyFileSearchMatchType = Schema.Literals([
1267 "file",
1268 "directory",
1269]);
1270
1271export type JSONRPCError__JSONRPCErrorError = {
1272 readonly code: number;
1273 readonly data?: unknown;
1274 readonly message: string;
1275};
1276export const JSONRPCError__JSONRPCErrorError = Schema.Struct({
1277 code: Schema.Number.annotate({ format: "int64" }).check(Schema.isInt()),
1278 data: Schema.optionalKey(Schema.Unknown),
1279 message: Schema.String,
1280});
1281
1282export type JSONRPCError__RequestId = string | number;
1283export const JSONRPCError__RequestId = Schema.Union([
1284 Schema.String,
1285 Schema.Number.annotate({ format: "int64" }).check(Schema.isInt()),
1286]);
1287
1288export type JSONRPCMessage__JSONRPCErrorError = {
1289 readonly code: number;
1290 readonly data?: unknown;
1291 readonly message: string;
1292};
1293export const JSONRPCMessage__JSONRPCErrorError = Schema.Struct({
1294 code: Schema.Number.annotate({ format: "int64" }).check(Schema.isInt()),
1295 data: Schema.optionalKey(Schema.Unknown),
1296 message: Schema.String,
1297});
1298
1299export type JSONRPCMessage__JSONRPCNotification = {
1300 readonly method: string;
1301 readonly params?: unknown;
1302};
1303export const JSONRPCMessage__JSONRPCNotification = Schema.Struct({
1304 method: Schema.String,
1305 params: Schema.optionalKey(Schema.Unknown),
1306}).annotate({ description: "A notification which does not expect a response." });
1307
1308export type JSONRPCMessage__RequestId = string | number;
1309export const JSONRPCMessage__RequestId = Schema.Union([
1310 Schema.String,
1311 Schema.Number.annotate({ format: "int64" }).check(Schema.isInt()),
1312]);
1313
1314export type JSONRPCMessage__W3cTraceContext = {
1315 readonly traceparent?: string | null;
1316 readonly tracestate?: string | null;
1317};
1318export const JSONRPCMessage__W3cTraceContext = Schema.Struct({
1319 traceparent: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
1320 tracestate: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
1321});
1322
1323export type JSONRPCRequest__RequestId = string | number;
1324export const JSONRPCRequest__RequestId = Schema.Union([
1325 Schema.String,
1326 Schema.Number.annotate({ format: "int64" }).check(Schema.isInt()),
1327]);
1328
1329export type JSONRPCRequest__W3cTraceContext = {
1330 readonly traceparent?: string | null;
1331 readonly tracestate?: string | null;
1332};
1333export const JSONRPCRequest__W3cTraceContext = Schema.Struct({
1334 traceparent: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
1335 tracestate: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
1336});
1337
1338export type JSONRPCResponse__RequestId = string | number;
1339export const JSONRPCResponse__RequestId = Schema.Union([
1340 Schema.String,
1341 Schema.Number.annotate({ format: "int64" }).check(Schema.isInt()),
1342]);
1343
1344export type McpServerElicitationRequestParams__McpElicitationArrayType = "array";
1345export const McpServerElicitationRequestParams__McpElicitationArrayType = Schema.Literal("array");
1346
1347export type McpServerElicitationRequestParams__McpElicitationBooleanType = "boolean";
1348export const McpServerElicitationRequestParams__McpElicitationBooleanType =
1349 Schema.Literal("boolean");
1350
1351export type McpServerElicitationRequestParams__McpElicitationConstOption = {
1352 readonly const: string;
1353 readonly title: string;
1354};
1355export const McpServerElicitationRequestParams__McpElicitationConstOption = Schema.Struct({
1356 const: Schema.String,
1357 title: Schema.String,
1358});
1359
1360export type McpServerElicitationRequestParams__McpElicitationNumberType = "number" | "integer";
1361export const McpServerElicitationRequestParams__McpElicitationNumberType = Schema.Literals([
1362 "number",
1363 "integer",
1364]);
1365
1366export type McpServerElicitationRequestParams__McpElicitationObjectType = "object";
1367export const McpServerElicitationRequestParams__McpElicitationObjectType = Schema.Literal("object");
1368
1369export type McpServerElicitationRequestParams__McpElicitationStringFormat =
1370 | "email"
1371 | "uri"
1372 | "date"
1373 | "date-time";
1374export const McpServerElicitationRequestParams__McpElicitationStringFormat = Schema.Literals([
1375 "email",
1376 "uri",
1377 "date",
1378 "date-time",
1379]);
1380
1381export type McpServerElicitationRequestParams__McpElicitationStringType = "string";
1382export const McpServerElicitationRequestParams__McpElicitationStringType = Schema.Literal("string");
1383
1384export type McpServerElicitationRequestResponse__McpServerElicitationAction =
1385 | "accept"
1386 | "decline"
1387 | "cancel";
1388export const McpServerElicitationRequestResponse__McpServerElicitationAction = Schema.Literals([
1389 "accept",
1390 "decline",
1391 "cancel",
1392]);
1393
1394export type PermissionsRequestApprovalParams__AbsolutePathBuf = string;
1395export const PermissionsRequestApprovalParams__AbsolutePathBuf = Schema.String.annotate({
1396 description:
1397 "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.",
1398});
1399
1400export type PermissionsRequestApprovalParams__AdditionalNetworkPermissions = {
1401 readonly enabled?: boolean | null;
1402};
1403export const PermissionsRequestApprovalParams__AdditionalNetworkPermissions = Schema.Struct({
1404 enabled: Schema.optionalKey(Schema.Union([Schema.Boolean, Schema.Null])),
1405});
1406
1407export type PermissionsRequestApprovalResponse__AbsolutePathBuf = string;
1408export const PermissionsRequestApprovalResponse__AbsolutePathBuf = Schema.String.annotate({
1409 description:
1410 "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.",
1411});
1412
1413export type PermissionsRequestApprovalResponse__AdditionalNetworkPermissions = {
1414 readonly enabled?: boolean | null;
1415};
1416export const PermissionsRequestApprovalResponse__AdditionalNetworkPermissions = Schema.Struct({
1417 enabled: Schema.optionalKey(Schema.Union([Schema.Boolean, Schema.Null])),
1418});
1419
1420export type ServerNotification__AbsolutePathBuf = string;
1421export const ServerNotification__AbsolutePathBuf = Schema.String.annotate({
1422 description:
1423 "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.",
1424});
1425
1426export type ServerNotification__AccountLoginCompletedNotification = {
1427 readonly error?: string | null;
1428 readonly loginId?: string | null;
1429 readonly success: boolean;
1430};
1431export const ServerNotification__AccountLoginCompletedNotification = Schema.Struct({
1432 error: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
1433 loginId: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
1434 success: Schema.Boolean,
1435});
1436
1437export type ServerNotification__AgentMessageDeltaNotification = {
1438 readonly delta: string;
1439 readonly itemId: string;
1440 readonly threadId: string;
1441 readonly turnId: string;
1442};
1443export const ServerNotification__AgentMessageDeltaNotification = Schema.Struct({
1444 delta: Schema.String,
1445 itemId: Schema.String,
1446 threadId: Schema.String,
1447 turnId: Schema.String,
1448});
1449
1450export type ServerNotification__AgentPath = string;
1451export const ServerNotification__AgentPath = Schema.String;
1452
1453export type ServerNotification__AppBranding = {
1454 readonly category?: string | null;
1455 readonly developer?: string | null;
1456 readonly isDiscoverableApp: boolean;
1457 readonly privacyPolicy?: string | null;
1458 readonly termsOfService?: string | null;
1459 readonly website?: string | null;
1460};
1461export const ServerNotification__AppBranding = Schema.Struct({
1462 category: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
1463 developer: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
1464 isDiscoverableApp: Schema.Boolean,
1465 privacyPolicy: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
1466 termsOfService: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
1467 website: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
1468}).annotate({ description: "EXPERIMENTAL - app metadata returned by app-list APIs." });
1469
1470export type ServerNotification__AppReview = { readonly status: string };
1471export const ServerNotification__AppReview = Schema.Struct({ status: Schema.String });
1472
1473export type ServerNotification__AppScreenshot = {
1474 readonly fileId?: string | null;
1475 readonly url?: string | null;
1476 readonly userPrompt: string;
1477};
1478export const ServerNotification__AppScreenshot = Schema.Struct({
1479 fileId: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
1480 url: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
1481 userPrompt: Schema.String,
1482});
1483
1484export type ServerNotification__AuthMode = "apikey" | "chatgpt" | "chatgptAuthTokens";
1485export const ServerNotification__AuthMode = Schema.Literals([
1486 "apikey",
1487 "chatgpt",
1488 "chatgptAuthTokens",
1489]).annotate({ description: "Authentication mode for OpenAI-backed providers." });
1490
1491export type ServerNotification__AutoReviewDecisionSource = "agent";
1492export const ServerNotification__AutoReviewDecisionSource = Schema.Literal("agent").annotate({
1493 description: "[UNSTABLE] Source that produced a terminal guardian approval review decision.",
1494});
1495
1496export type ServerNotification__CollabAgentStatus =
1497 | "pendingInit"
1498 | "running"
1499 | "interrupted"
1500 | "completed"
1501 | "errored"
1502 | "shutdown"
1503 | "notFound";
1504export const ServerNotification__CollabAgentStatus = Schema.Literals([
1505 "pendingInit",
1506 "running",
1507 "interrupted",
1508 "completed",
1509 "errored",
1510 "shutdown",
1511 "notFound",
1512]);
1513
1514export type ServerNotification__CommandAction =
1515 | {
1516 readonly command: string;
1517 readonly name: string;
1518 readonly path: string;
1519 readonly type: "read";
1520 }
1521 | { readonly command: string; readonly path?: string | null; readonly type: "listFiles" }
1522 | {
1523 readonly command: string;
1524 readonly path?: string | null;
1525 readonly query?: string | null;
1526 readonly type: "search";
1527 }
1528 | { readonly command: string; readonly type: "unknown" };
1529export const ServerNotification__CommandAction = Schema.Union(
1530 [
1531 Schema.Struct({
1532 command: Schema.String,
1533 name: Schema.String,
1534 path: Schema.String,
1535 type: Schema.Literal("read").annotate({ title: "ReadCommandActionType" }),
1536 }).annotate({ title: "ReadCommandAction" }),
1537 Schema.Struct({
1538 command: Schema.String,
1539 path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
1540 type: Schema.Literal("listFiles").annotate({ title: "ListFilesCommandActionType" }),
1541 }).annotate({ title: "ListFilesCommandAction" }),
1542 Schema.Struct({
1543 command: Schema.String,
1544 path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
1545 query: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
1546 type: Schema.Literal("search").annotate({ title: "SearchCommandActionType" }),
1547 }).annotate({ title: "SearchCommandAction" }),
1548 Schema.Struct({
1549 command: Schema.String,
1550 type: Schema.Literal("unknown").annotate({ title: "UnknownCommandActionType" }),
1551 }).annotate({ title: "UnknownCommandAction" }),
1552 ],
1553 { mode: "oneOf" },
1554);
1555
1556export type ServerNotification__CommandExecOutputDeltaNotification = {
1557 readonly capReached: boolean;
1558 readonly deltaBase64: string;
1559 readonly processId: string;
1560 readonly stream: "stdout" | "stderr";
1561};
1562export const ServerNotification__CommandExecOutputDeltaNotification = Schema.Struct({
1563 capReached: Schema.Boolean.annotate({
1564 description:
1565 "`true` on the final streamed chunk for a stream when `outputBytesCap` truncated later output on that stream.",
1566 }),
1567 deltaBase64: Schema.String.annotate({ description: "Base64-encoded output bytes." }),
1568 processId: Schema.String.annotate({
1569 description:
1570 "Client-supplied, connection-scoped `processId` from the original `command/exec` request.",
1571 }),
1572 stream: Schema.Literals(["stdout", "stderr"]).annotate({
1573 description: "Stream label for `command/exec/outputDelta` notifications.",
1574 }),
1575}).annotate({
1576 description:
1577 "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.",
1578});
1579
1580export type ServerNotification__CommandExecutionOutputDeltaNotification = {
1581 readonly delta: string;
1582 readonly itemId: string;
1583 readonly threadId: string;
1584 readonly turnId: string;
1585};
1586export const ServerNotification__CommandExecutionOutputDeltaNotification = Schema.Struct({
1587 delta: Schema.String,
1588 itemId: Schema.String,
1589 threadId: Schema.String,
1590 turnId: Schema.String,
1591});
1592
1593export type ServerNotification__CommandExecutionStatus =
1594 | "inProgress"
1595 | "completed"
1596 | "failed"
1597 | "declined";
1598export const ServerNotification__CommandExecutionStatus = Schema.Literals([
1599 "inProgress",
1600 "completed",
1601 "failed",
1602 "declined",
1603]);
1604
1605export type ServerNotification__ContextCompactedNotification = {
1606 readonly threadId: string;
1607 readonly turnId: string;
1608};
1609export const ServerNotification__ContextCompactedNotification = Schema.Struct({
1610 threadId: Schema.String,
1611 turnId: Schema.String,
1612}).annotate({ description: "Deprecated: Use `ContextCompaction` item type instead." });
1613
1614export type ServerNotification__CreditsSnapshot = {
1615 readonly balance?: string | null;
1616 readonly hasCredits: boolean;
1617 readonly unlimited: boolean;
1618};
1619export const ServerNotification__CreditsSnapshot = Schema.Struct({
1620 balance: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
1621 hasCredits: Schema.Boolean,
1622 unlimited: Schema.Boolean,
1623});
1624
1625export type ServerNotification__DeprecationNoticeNotification = {
1626 readonly details?: string | null;
1627 readonly summary: string;
1628};
1629export const ServerNotification__DeprecationNoticeNotification = Schema.Struct({
1630 details: Schema.optionalKey(
1631 Schema.Union([
1632 Schema.String.annotate({
1633 description: "Optional extra guidance, such as migration steps or rationale.",
1634 }),
1635 Schema.Null,
1636 ]),
1637 ),
1638 summary: Schema.String.annotate({ description: "Concise summary of what is deprecated." }),
1639});
1640
1641export type ServerNotification__DynamicToolCallOutputContentItem =
1642 | { readonly text: string; readonly type: "inputText" }
1643 | { readonly imageUrl: string; readonly type: "inputImage" };
1644export const ServerNotification__DynamicToolCallOutputContentItem = Schema.Union(
1645 [
1646 Schema.Struct({
1647 text: Schema.String,
1648 type: Schema.Literal("inputText").annotate({
1649 title: "InputTextDynamicToolCallOutputContentItemType",
1650 }),
1651 }).annotate({ title: "InputTextDynamicToolCallOutputContentItem" }),
1652 Schema.Struct({
1653 imageUrl: Schema.String,
1654 type: Schema.Literal("inputImage").annotate({
1655 title: "InputImageDynamicToolCallOutputContentItemType",
1656 }),
1657 }).annotate({ title: "InputImageDynamicToolCallOutputContentItem" }),
1658 ],
1659 { mode: "oneOf" },
1660);
1661
1662export type ServerNotification__DynamicToolCallStatus = "inProgress" | "completed" | "failed";
1663export const ServerNotification__DynamicToolCallStatus = Schema.Literals([
1664 "inProgress",
1665 "completed",
1666 "failed",
1667]);
1668
1669export type ServerNotification__FileChangeOutputDeltaNotification = {
1670 readonly delta: string;
1671 readonly itemId: string;
1672 readonly threadId: string;
1673 readonly turnId: string;
1674};
1675export const ServerNotification__FileChangeOutputDeltaNotification = Schema.Struct({
1676 delta: Schema.String,
1677 itemId: Schema.String,
1678 threadId: Schema.String,
1679 turnId: Schema.String,
1680});
1681
1682export type ServerNotification__FuzzyFileSearchMatchType = "file" | "directory";
1683export const ServerNotification__FuzzyFileSearchMatchType = Schema.Literals(["file", "directory"]);
1684
1685export type ServerNotification__FuzzyFileSearchSessionCompletedNotification = {
1686 readonly sessionId: string;
1687};
1688export const ServerNotification__FuzzyFileSearchSessionCompletedNotification = Schema.Struct({
1689 sessionId: Schema.String,
1690});
1691
1692export type ServerNotification__GitInfo = {
1693 readonly branch?: string | null;
1694 readonly originUrl?: string | null;
1695 readonly sha?: string | null;
1696};
1697export const ServerNotification__GitInfo = Schema.Struct({
1698 branch: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
1699 originUrl: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
1700 sha: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
1701});
1702
1703export type ServerNotification__GuardianApprovalReviewStatus =
1704 | "inProgress"
1705 | "approved"
1706 | "denied"
1707 | "timedOut"
1708 | "aborted";
1709export const ServerNotification__GuardianApprovalReviewStatus = Schema.Literals([
1710 "inProgress",
1711 "approved",
1712 "denied",
1713 "timedOut",
1714 "aborted",
1715]).annotate({ description: "[UNSTABLE] Lifecycle state for a guardian approval review." });
1716
1717export type ServerNotification__GuardianCommandSource = "shell" | "unifiedExec";
1718export const ServerNotification__GuardianCommandSource = Schema.Literals(["shell", "unifiedExec"]);
1719
1720export type ServerNotification__GuardianRiskLevel = "low" | "medium" | "high" | "critical";
1721export const ServerNotification__GuardianRiskLevel = Schema.Literals([
1722 "low",
1723 "medium",
1724 "high",
1725 "critical",
1726]).annotate({ description: "[UNSTABLE] Risk level assigned by guardian approval review." });
1727
1728export type ServerNotification__GuardianUserAuthorization = "unknown" | "low" | "medium" | "high";
1729export const ServerNotification__GuardianUserAuthorization = Schema.Literals([
1730 "unknown",
1731 "low",
1732 "medium",
1733 "high",
1734]).annotate({
1735 description: "[UNSTABLE] Authorization level assigned by guardian approval review.",
1736});
1737
1738export type ServerNotification__HookEventName =
1739 | "preToolUse"
1740 | "postToolUse"
1741 | "sessionStart"
1742 | "userPromptSubmit"
1743 | "stop";
1744export const ServerNotification__HookEventName = Schema.Literals([
1745 "preToolUse",
1746 "postToolUse",
1747 "sessionStart",
1748 "userPromptSubmit",
1749 "stop",
1750]);
1751
1752export type ServerNotification__HookExecutionMode = "sync" | "async";
1753export const ServerNotification__HookExecutionMode = Schema.Literals(["sync", "async"]);
1754
1755export type ServerNotification__HookHandlerType = "command" | "prompt" | "agent";
1756export const ServerNotification__HookHandlerType = Schema.Literals(["command", "prompt", "agent"]);
1757
1758export type ServerNotification__HookOutputEntryKind =
1759 | "warning"
1760 | "stop"
1761 | "feedback"
1762 | "context"
1763 | "error";
1764export const ServerNotification__HookOutputEntryKind = Schema.Literals([
1765 "warning",
1766 "stop",
1767 "feedback",
1768 "context",
1769 "error",
1770]);
1771
1772export type ServerNotification__HookPromptFragment = {
1773 readonly hookRunId: string;
1774 readonly text: string;
1775};
1776export const ServerNotification__HookPromptFragment = Schema.Struct({
1777 hookRunId: Schema.String,
1778 text: Schema.String,
1779});
1780
1781export type ServerNotification__HookRunStatus =
1782 | "running"
1783 | "completed"
1784 | "failed"
1785 | "blocked"
1786 | "stopped";
1787export const ServerNotification__HookRunStatus = Schema.Literals([
1788 "running",
1789 "completed",
1790 "failed",
1791 "blocked",
1792 "stopped",
1793]);
1794
1795export type ServerNotification__HookScope = "thread" | "turn";
1796export const ServerNotification__HookScope = Schema.Literals(["thread", "turn"]);
1797
1798export type ServerNotification__McpServerOauthLoginCompletedNotification = {
1799 readonly error?: string | null;
1800 readonly name: string;
1801 readonly success: boolean;
1802};
1803export const ServerNotification__McpServerOauthLoginCompletedNotification = Schema.Struct({
1804 error: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
1805 name: Schema.String,
1806 success: Schema.Boolean,
1807});
1808
1809export type ServerNotification__McpServerStartupState =
1810 | "starting"
1811 | "ready"
1812 | "failed"
1813 | "cancelled";
1814export const ServerNotification__McpServerStartupState = Schema.Literals([
1815 "starting",
1816 "ready",
1817 "failed",
1818 "cancelled",
1819]);
1820
1821export type ServerNotification__McpToolCallError = { readonly message: string };
1822export const ServerNotification__McpToolCallError = Schema.Struct({ message: Schema.String });
1823
1824export type ServerNotification__McpToolCallProgressNotification = {
1825 readonly itemId: string;
1826 readonly message: string;
1827 readonly threadId: string;
1828 readonly turnId: string;
1829};
1830export const ServerNotification__McpToolCallProgressNotification = Schema.Struct({
1831 itemId: Schema.String,
1832 message: Schema.String,
1833 threadId: Schema.String,
1834 turnId: Schema.String,
1835});
1836
1837export type ServerNotification__McpToolCallResult = {
1838 readonly _meta?: unknown;
1839 readonly content: ReadonlyArray<unknown>;
1840 readonly structuredContent?: unknown;
1841};
1842export const ServerNotification__McpToolCallResult = Schema.Struct({
1843 _meta: Schema.optionalKey(Schema.Unknown),
1844 content: Schema.Array(Schema.Unknown),
1845 structuredContent: Schema.optionalKey(Schema.Unknown),
1846});
1847
1848export type ServerNotification__McpToolCallStatus = "inProgress" | "completed" | "failed";
1849export const ServerNotification__McpToolCallStatus = Schema.Literals([
1850 "inProgress",
1851 "completed",
1852 "failed",
1853]);
1854
1855export type ServerNotification__MemoryCitationEntry = {
1856 readonly lineEnd: number;
1857 readonly lineStart: number;
1858 readonly note: string;
1859 readonly path: string;
1860};
1861export const ServerNotification__MemoryCitationEntry = Schema.Struct({
1862 lineEnd: Schema.Number.annotate({ format: "uint32" })
1863 .check(Schema.isInt())
1864 .check(Schema.isGreaterThanOrEqualTo(0)),
1865 lineStart: Schema.Number.annotate({ format: "uint32" })
1866 .check(Schema.isInt())
1867 .check(Schema.isGreaterThanOrEqualTo(0)),
1868 note: Schema.String,
1869 path: Schema.String,
1870});
1871
1872export type ServerNotification__MessagePhase = "commentary" | "final_answer";
1873export const ServerNotification__MessagePhase = Schema.Literals([
1874 "commentary",
1875 "final_answer",
1876]).annotate({
1877 description:
1878 '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.',
1879});
1880
1881export type ServerNotification__ModelRerouteReason = "highRiskCyberActivity";
1882export const ServerNotification__ModelRerouteReason = Schema.Literal("highRiskCyberActivity");
1883
1884export type ServerNotification__NetworkApprovalProtocol =
1885 | "http"
1886 | "https"
1887 | "socks5Tcp"
1888 | "socks5Udp";
1889export const ServerNotification__NetworkApprovalProtocol = Schema.Literals([
1890 "http",
1891 "https",
1892 "socks5Tcp",
1893 "socks5Udp",
1894]);
1895
1896export type ServerNotification__NonSteerableTurnKind = "review" | "compact";
1897export const ServerNotification__NonSteerableTurnKind = Schema.Literals(["review", "compact"]);
1898
1899export type ServerNotification__PatchApplyStatus =
1900 | "inProgress"
1901 | "completed"
1902 | "failed"
1903 | "declined";
1904export const ServerNotification__PatchApplyStatus = Schema.Literals([
1905 "inProgress",
1906 "completed",
1907 "failed",
1908 "declined",
1909]);
1910
1911export type ServerNotification__PatchChangeKind =
1912 | { readonly type: "add" }
1913 | { readonly type: "delete" }
1914 | { readonly move_path?: string | null; readonly type: "update" };
1915export const ServerNotification__PatchChangeKind = Schema.Union(
1916 [
1917 Schema.Struct({
1918 type: Schema.Literal("add").annotate({ title: "AddPatchChangeKindType" }),
1919 }).annotate({ title: "AddPatchChangeKind" }),
1920 Schema.Struct({
1921 type: Schema.Literal("delete").annotate({ title: "DeletePatchChangeKindType" }),
1922 }).annotate({ title: "DeletePatchChangeKind" }),
1923 Schema.Struct({
1924 move_path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
1925 type: Schema.Literal("update").annotate({ title: "UpdatePatchChangeKindType" }),
1926 }).annotate({ title: "UpdatePatchChangeKind" }),
1927 ],
1928 { mode: "oneOf" },
1929);
1930
1931export type ServerNotification__PlanDeltaNotification = {
1932 readonly delta: string;
1933 readonly itemId: string;
1934 readonly threadId: string;
1935 readonly turnId: string;
1936};
1937export const ServerNotification__PlanDeltaNotification = Schema.Struct({
1938 delta: Schema.String,
1939 itemId: Schema.String,
1940 threadId: Schema.String,
1941 turnId: Schema.String,
1942}).annotate({
1943 description:
1944 "EXPERIMENTAL - proposed plan streaming deltas for plan items. Clients should not assume concatenated deltas match the completed plan item content.",
1945});
1946
1947export type ServerNotification__PlanType =
1948 | "free"
1949 | "go"
1950 | "plus"
1951 | "pro"
1952 | "team"
1953 | "self_serve_business_usage_based"
1954 | "business"
1955 | "enterprise_cbp_usage_based"
1956 | "enterprise"
1957 | "edu"
1958 | "unknown";
1959export const ServerNotification__PlanType = Schema.Literals([
1960 "free",
1961 "go",
1962 "plus",
1963 "pro",
1964 "team",
1965 "self_serve_business_usage_based",
1966 "business",
1967 "enterprise_cbp_usage_based",
1968 "enterprise",
1969 "edu",
1970 "unknown",
1971]);
1972
1973export type ServerNotification__RateLimitWindow = {
1974 readonly resetsAt?: number | null;
1975 readonly usedPercent: number;
1976 readonly windowDurationMins?: number | null;
1977};
1978export const ServerNotification__RateLimitWindow = Schema.Struct({
1979 resetsAt: Schema.optionalKey(
1980 Schema.Union([Schema.Number.annotate({ format: "int64" }).check(Schema.isInt()), Schema.Null]),
1981 ),
1982 usedPercent: Schema.Number.annotate({ format: "int32" }).check(Schema.isInt()),
1983 windowDurationMins: Schema.optionalKey(
1984 Schema.Union([Schema.Number.annotate({ format: "int64" }).check(Schema.isInt()), Schema.Null]),
1985 ),
1986});
1987
1988export type ServerNotification__RealtimeConversationVersion = "v1" | "v2";
1989export const ServerNotification__RealtimeConversationVersion = Schema.Literals(["v1", "v2"]);
1990
1991export type ServerNotification__ReasoningEffort =
1992 | "none"
1993 | "minimal"
1994 | "low"
1995 | "medium"
1996 | "high"
1997 | "xhigh";
1998export const ServerNotification__ReasoningEffort = Schema.Literals([
1999 "none",
2000 "minimal",
2001 "low",
2002 "medium",
2003 "high",
2004 "xhigh",
2005]).annotate({
2006 description:
2007 "See https://platform.openai.com/docs/guides/reasoning?api-mode=responses#get-started-with-reasoning",
2008});
2009
2010export type ServerNotification__ReasoningSummaryPartAddedNotification = {
2011 readonly itemId: string;
2012 readonly summaryIndex: number;
2013 readonly threadId: string;
2014 readonly turnId: string;
2015};
2016export const ServerNotification__ReasoningSummaryPartAddedNotification = Schema.Struct({
2017 itemId: Schema.String,
2018 summaryIndex: Schema.Number.annotate({ format: "int64" }).check(Schema.isInt()),
2019 threadId: Schema.String,
2020 turnId: Schema.String,
2021});
2022
2023export type ServerNotification__ReasoningSummaryTextDeltaNotification = {
2024 readonly delta: string;
2025 readonly itemId: string;
2026 readonly summaryIndex: number;
2027 readonly threadId: string;
2028 readonly turnId: string;
2029};
2030export const ServerNotification__ReasoningSummaryTextDeltaNotification = Schema.Struct({
2031 delta: Schema.String,
2032 itemId: Schema.String,
2033 summaryIndex: Schema.Number.annotate({ format: "int64" }).check(Schema.isInt()),
2034 threadId: Schema.String,
2035 turnId: Schema.String,
2036});
2037
2038export type ServerNotification__ReasoningTextDeltaNotification = {
2039 readonly contentIndex: number;
2040 readonly delta: string;
2041 readonly itemId: string;
2042 readonly threadId: string;
2043 readonly turnId: string;
2044};
2045export const ServerNotification__ReasoningTextDeltaNotification = Schema.Struct({
2046 contentIndex: Schema.Number.annotate({ format: "int64" }).check(Schema.isInt()),
2047 delta: Schema.String,
2048 itemId: Schema.String,
2049 threadId: Schema.String,
2050 turnId: Schema.String,
2051});
2052
2053export type ServerNotification__RequestId = string | number;
2054export const ServerNotification__RequestId = Schema.Union([
2055 Schema.String,
2056 Schema.Number.annotate({ format: "int64" }).check(Schema.isInt()),
2057]);
2058
2059export type ServerNotification__SkillsChangedNotification = {};
2060export const ServerNotification__SkillsChangedNotification = Schema.Struct({}).annotate({
2061 description:
2062 "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.",
2063});
2064
2065export type ServerNotification__TerminalInteractionNotification = {
2066 readonly itemId: string;
2067 readonly processId: string;
2068 readonly stdin: string;
2069 readonly threadId: string;
2070 readonly turnId: string;
2071};
2072export const ServerNotification__TerminalInteractionNotification = Schema.Struct({
2073 itemId: Schema.String,
2074 processId: Schema.String,
2075 stdin: Schema.String,
2076 threadId: Schema.String,
2077 turnId: Schema.String,
2078});
2079
2080export type ServerNotification__TextElement = {
2081 readonly byteRange: { readonly end: number; readonly start: number };
2082 readonly placeholder?: string | null;
2083};
2084export const ServerNotification__TextElement = Schema.Struct({
2085 byteRange: Schema.Struct({
2086 end: Schema.Number.annotate({ format: "uint" })
2087 .check(Schema.isInt())
2088 .check(Schema.isGreaterThanOrEqualTo(0)),
2089 start: Schema.Number.annotate({ format: "uint" })
2090 .check(Schema.isInt())
2091 .check(Schema.isGreaterThanOrEqualTo(0)),
2092 }).annotate({
2093 description: "Byte range in the parent `text` buffer that this element occupies.",
2094 }),
2095 placeholder: Schema.optionalKey(
2096 Schema.Union([
2097 Schema.String.annotate({
2098 description: "Optional human-readable placeholder for the element, displayed in the UI.",
2099 }),
2100 Schema.Null,
2101 ]),
2102 ),
2103});
2104
2105export type ServerNotification__TextPosition = { readonly column: number; readonly line: number };
2106export const ServerNotification__TextPosition = Schema.Struct({
2107 column: Schema.Number.annotate({
2108 description: "1-based column number (in Unicode scalar values).",
2109 format: "uint",
2110 })
2111 .check(Schema.isInt())
2112 .check(Schema.isGreaterThanOrEqualTo(0)),
2113 line: Schema.Number.annotate({ description: "1-based line number.", format: "uint" })
2114 .check(Schema.isInt())
2115 .check(Schema.isGreaterThanOrEqualTo(0)),
2116});
2117
2118export type ServerNotification__ThreadActiveFlag = "waitingOnApproval" | "waitingOnUserInput";
2119export const ServerNotification__ThreadActiveFlag = Schema.Literals([
2120 "waitingOnApproval",
2121 "waitingOnUserInput",
2122]);
2123
2124export type ServerNotification__ThreadArchivedNotification = { readonly threadId: string };
2125export const ServerNotification__ThreadArchivedNotification = Schema.Struct({
2126 threadId: Schema.String,
2127});
2128
2129export type ServerNotification__ThreadClosedNotification = { readonly threadId: string };
2130export const ServerNotification__ThreadClosedNotification = Schema.Struct({
2131 threadId: Schema.String,
2132});
2133
2134export type ServerNotification__ThreadId = string;
2135export const ServerNotification__ThreadId = Schema.String;
2136
2137export type ServerNotification__ThreadNameUpdatedNotification = {
2138 readonly threadId: string;
2139 readonly threadName?: string | null;
2140};
2141export const ServerNotification__ThreadNameUpdatedNotification = Schema.Struct({
2142 threadId: Schema.String,
2143 threadName: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
2144});
2145
2146export type ServerNotification__ThreadRealtimeAudioChunk = {
2147 readonly data: string;
2148 readonly itemId?: string | null;
2149 readonly numChannels: number;
2150 readonly sampleRate: number;
2151 readonly samplesPerChannel?: number | null;
2152};
2153export const ServerNotification__ThreadRealtimeAudioChunk = Schema.Struct({
2154 data: Schema.String,
2155 itemId: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
2156 numChannels: Schema.Number.annotate({ format: "uint16" })
2157 .check(Schema.isInt())
2158 .check(Schema.isGreaterThanOrEqualTo(0)),
2159 sampleRate: Schema.Number.annotate({ format: "uint32" })
2160 .check(Schema.isInt())
2161 .check(Schema.isGreaterThanOrEqualTo(0)),
2162 samplesPerChannel: Schema.optionalKey(
2163 Schema.Union([
2164 Schema.Number.annotate({ format: "uint32" })
2165 .check(Schema.isInt())
2166 .check(Schema.isGreaterThanOrEqualTo(0)),
2167 Schema.Null,
2168 ]),
2169 ),
2170}).annotate({ description: "EXPERIMENTAL - thread realtime audio chunk." });
2171
2172export type ServerNotification__ThreadRealtimeClosedNotification = {
2173 readonly reason?: string | null;
2174 readonly threadId: string;
2175};
2176export const ServerNotification__ThreadRealtimeClosedNotification = Schema.Struct({
2177 reason: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
2178 threadId: Schema.String,
2179}).annotate({ description: "EXPERIMENTAL - emitted when thread realtime transport closes." });
2180
2181export type ServerNotification__ThreadRealtimeErrorNotification = {
2182 readonly message: string;
2183 readonly threadId: string;
2184};
2185export const ServerNotification__ThreadRealtimeErrorNotification = Schema.Struct({
2186 message: Schema.String,
2187 threadId: Schema.String,
2188}).annotate({ description: "EXPERIMENTAL - emitted when thread realtime encounters an error." });
2189
2190export type ServerNotification__ThreadRealtimeItemAddedNotification = {
2191 readonly item: unknown;
2192 readonly threadId: string;
2193};
2194export const ServerNotification__ThreadRealtimeItemAddedNotification = Schema.Struct({
2195 item: Schema.Unknown,
2196 threadId: Schema.String,
2197}).annotate({
2198 description: "EXPERIMENTAL - raw non-audio thread realtime item emitted by the backend.",
2199});
2200
2201export type ServerNotification__ThreadRealtimeSdpNotification = {
2202 readonly sdp: string;
2203 readonly threadId: string;
2204};
2205export const ServerNotification__ThreadRealtimeSdpNotification = Schema.Struct({
2206 sdp: Schema.String,
2207 threadId: Schema.String,
2208}).annotate({
2209 description: "EXPERIMENTAL - emitted with the remote SDP for a WebRTC realtime session.",
2210});
2211
2212export type ServerNotification__ThreadRealtimeTranscriptUpdatedNotification = {
2213 readonly role: string;
2214 readonly text: string;
2215 readonly threadId: string;
2216};
2217export const ServerNotification__ThreadRealtimeTranscriptUpdatedNotification = Schema.Struct({
2218 role: Schema.String,
2219 text: Schema.String,
2220 threadId: Schema.String,
2221}).annotate({
2222 description:
2223 "EXPERIMENTAL - flat transcript delta emitted whenever realtime transcript text changes.",
2224});
2225
2226export type ServerNotification__ThreadUnarchivedNotification = { readonly threadId: string };
2227export const ServerNotification__ThreadUnarchivedNotification = Schema.Struct({
2228 threadId: Schema.String,
2229});
2230
2231export type ServerNotification__TokenUsageBreakdown = {
2232 readonly cachedInputTokens: number;
2233 readonly inputTokens: number;
2234 readonly outputTokens: number;
2235 readonly reasoningOutputTokens: number;
2236 readonly totalTokens: number;
2237};
2238export const ServerNotification__TokenUsageBreakdown = Schema.Struct({
2239 cachedInputTokens: Schema.Number.annotate({ format: "int64" }).check(Schema.isInt()),
2240 inputTokens: Schema.Number.annotate({ format: "int64" }).check(Schema.isInt()),
2241 outputTokens: Schema.Number.annotate({ format: "int64" }).check(Schema.isInt()),
2242 reasoningOutputTokens: Schema.Number.annotate({ format: "int64" }).check(Schema.isInt()),
2243 totalTokens: Schema.Number.annotate({ format: "int64" }).check(Schema.isInt()),
2244});
2245
2246export type ServerNotification__TurnDiffUpdatedNotification = {
2247 readonly diff: string;
2248 readonly threadId: string;
2249 readonly turnId: string;
2250};
2251export const ServerNotification__TurnDiffUpdatedNotification = Schema.Struct({
2252 diff: Schema.String,
2253 threadId: Schema.String,
2254 turnId: Schema.String,
2255}).annotate({
2256 description:
2257 "Notification that the turn-level unified diff has changed. Contains the latest aggregated diff across all file changes in the turn.",
2258});
2259
2260export type ServerNotification__TurnPlanStepStatus = "pending" | "inProgress" | "completed";
2261export const ServerNotification__TurnPlanStepStatus = Schema.Literals([
2262 "pending",
2263 "inProgress",
2264 "completed",
2265]);
2266
2267export type ServerNotification__TurnStatus = "completed" | "interrupted" | "failed" | "inProgress";
2268export const ServerNotification__TurnStatus = Schema.Literals([
2269 "completed",
2270 "interrupted",
2271 "failed",
2272 "inProgress",
2273]);
2274
2275export type ServerNotification__WebSearchAction =
2276 | {
2277 readonly queries?: ReadonlyArray<string> | null;
2278 readonly query?: string | null;
2279 readonly type: "search";
2280 }
2281 | { readonly type: "openPage"; readonly url?: string | null }
2282 | { readonly pattern?: string | null; readonly type: "findInPage"; readonly url?: string | null }
2283 | { readonly type: "other" };
2284export const ServerNotification__WebSearchAction = Schema.Union(
2285 [
2286 Schema.Struct({
2287 queries: Schema.optionalKey(Schema.Union([Schema.Array(Schema.String), Schema.Null])),
2288 query: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
2289 type: Schema.Literal("search").annotate({ title: "SearchWebSearchActionType" }),
2290 }).annotate({ title: "SearchWebSearchAction" }),
2291 Schema.Struct({
2292 type: Schema.Literal("openPage").annotate({ title: "OpenPageWebSearchActionType" }),
2293 url: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
2294 }).annotate({ title: "OpenPageWebSearchAction" }),
2295 Schema.Struct({
2296 pattern: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
2297 type: Schema.Literal("findInPage").annotate({ title: "FindInPageWebSearchActionType" }),
2298 url: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
2299 }).annotate({ title: "FindInPageWebSearchAction" }),
2300 Schema.Struct({
2301 type: Schema.Literal("other").annotate({ title: "OtherWebSearchActionType" }),
2302 }).annotate({ title: "OtherWebSearchAction" }),
2303 ],
2304 { mode: "oneOf" },
2305);
2306
2307export type ServerNotification__WindowsSandboxSetupMode = "elevated" | "unelevated";
2308export const ServerNotification__WindowsSandboxSetupMode = Schema.Literals([
2309 "elevated",
2310 "unelevated",
2311]);
2312
2313export type ServerNotification__WindowsWorldWritableWarningNotification = {
2314 readonly extraCount: number;
2315 readonly failedScan: boolean;
2316 readonly samplePaths: ReadonlyArray<string>;
2317};
2318export const ServerNotification__WindowsWorldWritableWarningNotification = Schema.Struct({
2319 extraCount: Schema.Number.annotate({ format: "uint" })
2320 .check(Schema.isInt())
2321 .check(Schema.isGreaterThanOrEqualTo(0)),
2322 failedScan: Schema.Boolean,
2323 samplePaths: Schema.Array(Schema.String),
2324});
2325
2326export type ServerRequest__AbsolutePathBuf = string;
2327export const ServerRequest__AbsolutePathBuf = Schema.String.annotate({
2328 description:
2329 "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.",
2330});
2331
2332export type ServerRequest__AdditionalNetworkPermissions = { readonly enabled?: boolean | null };
2333export const ServerRequest__AdditionalNetworkPermissions = Schema.Struct({
2334 enabled: Schema.optionalKey(Schema.Union([Schema.Boolean, Schema.Null])),
2335});
2336
2337export type ServerRequest__ChatgptAuthTokensRefreshReason = "unauthorized";
2338export const ServerRequest__ChatgptAuthTokensRefreshReason = Schema.Literal("unauthorized");
2339
2340export type ServerRequest__CommandAction =
2341 | {
2342 readonly command: string;
2343 readonly name: string;
2344 readonly path: string;
2345 readonly type: "read";
2346 }
2347 | { readonly command: string; readonly path?: string | null; readonly type: "listFiles" }
2348 | {
2349 readonly command: string;
2350 readonly path?: string | null;
2351 readonly query?: string | null;
2352 readonly type: "search";
2353 }
2354 | { readonly command: string; readonly type: "unknown" };
2355export const ServerRequest__CommandAction = Schema.Union(
2356 [
2357 Schema.Struct({
2358 command: Schema.String,
2359 name: Schema.String,
2360 path: Schema.String,
2361 type: Schema.Literal("read").annotate({ title: "ReadCommandActionType" }),
2362 }).annotate({ title: "ReadCommandAction" }),
2363 Schema.Struct({
2364 command: Schema.String,
2365 path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
2366 type: Schema.Literal("listFiles").annotate({ title: "ListFilesCommandActionType" }),
2367 }).annotate({ title: "ListFilesCommandAction" }),
2368 Schema.Struct({
2369 command: Schema.String,
2370 path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
2371 query: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
2372 type: Schema.Literal("search").annotate({ title: "SearchCommandActionType" }),
2373 }).annotate({ title: "SearchCommandAction" }),
2374 Schema.Struct({
2375 command: Schema.String,
2376 type: Schema.Literal("unknown").annotate({ title: "UnknownCommandActionType" }),
2377 }).annotate({ title: "UnknownCommandAction" }),
2378 ],
2379 { mode: "oneOf" },
2380);
2381
2382export type ServerRequest__DynamicToolCallParams = {
2383 readonly arguments: unknown;
2384 readonly callId: string;
2385 readonly threadId: string;
2386 readonly tool: string;
2387 readonly turnId: string;
2388};
2389export const ServerRequest__DynamicToolCallParams = Schema.Struct({
2390 arguments: Schema.Unknown,
2391 callId: Schema.String,
2392 threadId: Schema.String,
2393 tool: Schema.String,
2394 turnId: Schema.String,
2395});
2396
2397export type ServerRequest__FileChange =
2398 | { readonly content: string; readonly type: "add" }
2399 | { readonly content: string; readonly type: "delete" }
2400 | { readonly move_path?: string | null; readonly type: "update"; readonly unified_diff: string };
2401export const ServerRequest__FileChange = Schema.Union(
2402 [
2403 Schema.Struct({
2404 content: Schema.String,
2405 type: Schema.Literal("add").annotate({ title: "AddFileChangeType" }),
2406 }).annotate({ title: "AddFileChange" }),
2407 Schema.Struct({
2408 content: Schema.String,
2409 type: Schema.Literal("delete").annotate({ title: "DeleteFileChangeType" }),
2410 }).annotate({ title: "DeleteFileChange" }),
2411 Schema.Struct({
2412 move_path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
2413 type: Schema.Literal("update").annotate({ title: "UpdateFileChangeType" }),
2414 unified_diff: Schema.String,
2415 }).annotate({ title: "UpdateFileChange" }),
2416 ],
2417 { mode: "oneOf" },
2418);
2419
2420export type ServerRequest__FileChangeRequestApprovalParams = {
2421 readonly grantRoot?: string | null;
2422 readonly itemId: string;
2423 readonly reason?: string | null;
2424 readonly threadId: string;
2425 readonly turnId: string;
2426};
2427export const ServerRequest__FileChangeRequestApprovalParams = Schema.Struct({
2428 grantRoot: Schema.optionalKey(
2429 Schema.Union([
2430 Schema.String.annotate({
2431 description:
2432 "[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).",
2433 }),
2434 Schema.Null,
2435 ]),
2436 ),
2437 itemId: Schema.String,
2438 reason: Schema.optionalKey(
2439 Schema.Union([
2440 Schema.String.annotate({
2441 description: "Optional explanatory reason (e.g. request for extra write access).",
2442 }),
2443 Schema.Null,
2444 ]),
2445 ),
2446 threadId: Schema.String,
2447 turnId: Schema.String,
2448});
2449
2450export type ServerRequest__McpElicitationArrayType = "array";
2451export const ServerRequest__McpElicitationArrayType = Schema.Literal("array");
2452
2453export type ServerRequest__McpElicitationBooleanType = "boolean";
2454export const ServerRequest__McpElicitationBooleanType = Schema.Literal("boolean");
2455
2456export type ServerRequest__McpElicitationConstOption = {
2457 readonly const: string;
2458 readonly title: string;
2459};
2460export const ServerRequest__McpElicitationConstOption = Schema.Struct({
2461 const: Schema.String,
2462 title: Schema.String,
2463});
2464
2465export type ServerRequest__McpElicitationNumberType = "number" | "integer";
2466export const ServerRequest__McpElicitationNumberType = Schema.Literals(["number", "integer"]);
2467
2468export type ServerRequest__McpElicitationObjectType = "object";
2469export const ServerRequest__McpElicitationObjectType = Schema.Literal("object");
2470
2471export type ServerRequest__McpElicitationStringFormat = "email" | "uri" | "date" | "date-time";
2472export const ServerRequest__McpElicitationStringFormat = Schema.Literals([
2473 "email",
2474 "uri",
2475 "date",
2476 "date-time",
2477]);
2478
2479export type ServerRequest__McpElicitationStringType = "string";
2480export const ServerRequest__McpElicitationStringType = Schema.Literal("string");
2481
2482export type ServerRequest__NetworkApprovalProtocol = "http" | "https" | "socks5Tcp" | "socks5Udp";
2483export const ServerRequest__NetworkApprovalProtocol = Schema.Literals([
2484 "http",
2485 "https",
2486 "socks5Tcp",
2487 "socks5Udp",
2488]);
2489
2490export type ServerRequest__NetworkPolicyRuleAction = "allow" | "deny";
2491export const ServerRequest__NetworkPolicyRuleAction = Schema.Literals(["allow", "deny"]);
2492
2493export type ServerRequest__ParsedCommand =
2494 | { readonly cmd: string; readonly name: string; readonly path: string; readonly type: "read" }
2495 | { readonly cmd: string; readonly path?: string | null; readonly type: "list_files" }
2496 | {
2497 readonly cmd: string;
2498 readonly path?: string | null;
2499 readonly query?: string | null;
2500 readonly type: "search";
2501 }
2502 | { readonly cmd: string; readonly type: "unknown" };
2503export const ServerRequest__ParsedCommand = Schema.Union(
2504 [
2505 Schema.Struct({
2506 cmd: Schema.String,
2507 name: Schema.String,
2508 path: Schema.String.annotate({
2509 description:
2510 "(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.",
2511 }),
2512 type: Schema.Literal("read").annotate({ title: "ReadParsedCommandType" }),
2513 }).annotate({ title: "ReadParsedCommand" }),
2514 Schema.Struct({
2515 cmd: Schema.String,
2516 path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
2517 type: Schema.Literal("list_files").annotate({ title: "ListFilesParsedCommandType" }),
2518 }).annotate({ title: "ListFilesParsedCommand" }),
2519 Schema.Struct({
2520 cmd: Schema.String,
2521 path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
2522 query: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
2523 type: Schema.Literal("search").annotate({ title: "SearchParsedCommandType" }),
2524 }).annotate({ title: "SearchParsedCommand" }),
2525 Schema.Struct({
2526 cmd: Schema.String,
2527 type: Schema.Literal("unknown").annotate({ title: "UnknownParsedCommandType" }),
2528 }).annotate({ title: "UnknownParsedCommand" }),
2529 ],
2530 { mode: "oneOf" },
2531);
2532
2533export type ServerRequest__RequestId = string | number;
2534export const ServerRequest__RequestId = Schema.Union([
2535 Schema.String,
2536 Schema.Number.annotate({ format: "int64" }).check(Schema.isInt()),
2537]);
2538
2539export type ServerRequest__ThreadId = string;
2540export const ServerRequest__ThreadId = Schema.String;
2541
2542export type ServerRequest__ToolRequestUserInputOption = {
2543 readonly description: string;
2544 readonly label: string;
2545};
2546export const ServerRequest__ToolRequestUserInputOption = Schema.Struct({
2547 description: Schema.String,
2548 label: Schema.String,
2549}).annotate({
2550 description: "EXPERIMENTAL. Defines a single selectable option for request_user_input.",
2551});
2552
2553export type ToolRequestUserInputParams__ToolRequestUserInputOption = {
2554 readonly description: string;
2555 readonly label: string;
2556};
2557export const ToolRequestUserInputParams__ToolRequestUserInputOption = Schema.Struct({
2558 description: Schema.String,
2559 label: Schema.String,
2560}).annotate({
2561 description: "EXPERIMENTAL. Defines a single selectable option for request_user_input.",
2562});
2563
2564export type ToolRequestUserInputResponse__ToolRequestUserInputAnswer = {
2565 readonly answers: ReadonlyArray<string>;
2566};
2567export const ToolRequestUserInputResponse__ToolRequestUserInputAnswer = Schema.Struct({
2568 answers: Schema.Array(Schema.String),
2569}).annotate({
2570 description: "EXPERIMENTAL. Captures a user's answer to a request_user_input question.",
2571});
2572
2573export type V1InitializeParams__ClientInfo = {
2574 readonly name: string;
2575 readonly title?: string | null;
2576 readonly version: string;
2577};
2578export const V1InitializeParams__ClientInfo = Schema.Struct({
2579 name: Schema.String,
2580 title: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
2581 version: Schema.String,
2582});
2583
2584export type V1InitializeParams__InitializeCapabilities = {
2585 readonly experimentalApi?: boolean;
2586 readonly optOutNotificationMethods?: ReadonlyArray<string> | null;
2587};
2588export const V1InitializeParams__InitializeCapabilities = Schema.Struct({
2589 experimentalApi: Schema.optionalKey(
2590 Schema.Boolean.annotate({
2591 description: "Opt into receiving experimental API methods and fields.",
2592 default: false,
2593 }),
2594 ),
2595 optOutNotificationMethods: Schema.optionalKey(
2596 Schema.Union([
2597 Schema.Array(Schema.String).annotate({
2598 description:
2599 "Exact notification method names that should be suppressed for this connection (for example `thread/started`).",
2600 }),
2601 Schema.Null,
2602 ]),
2603 ),
2604}).annotate({ description: "Client-declared capabilities negotiated during initialize." });
2605
2606export type V2AccountRateLimitsUpdatedNotification__CreditsSnapshot = {
2607 readonly balance?: string | null;
2608 readonly hasCredits: boolean;
2609 readonly unlimited: boolean;
2610};
2611export const V2AccountRateLimitsUpdatedNotification__CreditsSnapshot = Schema.Struct({
2612 balance: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
2613 hasCredits: Schema.Boolean,
2614 unlimited: Schema.Boolean,
2615});
2616
2617export type V2AccountRateLimitsUpdatedNotification__PlanType =
2618 | "free"
2619 | "go"
2620 | "plus"
2621 | "pro"
2622 | "team"
2623 | "self_serve_business_usage_based"
2624 | "business"
2625 | "enterprise_cbp_usage_based"
2626 | "enterprise"
2627 | "edu"
2628 | "unknown";
2629export const V2AccountRateLimitsUpdatedNotification__PlanType = Schema.Literals([
2630 "free",
2631 "go",
2632 "plus",
2633 "pro",
2634 "team",
2635 "self_serve_business_usage_based",
2636 "business",
2637 "enterprise_cbp_usage_based",
2638 "enterprise",
2639 "edu",
2640 "unknown",
2641]);
2642
2643export type V2AccountRateLimitsUpdatedNotification__RateLimitWindow = {
2644 readonly resetsAt?: number | null;
2645 readonly usedPercent: number;
2646 readonly windowDurationMins?: number | null;
2647};
2648export const V2AccountRateLimitsUpdatedNotification__RateLimitWindow = Schema.Struct({
2649 resetsAt: Schema.optionalKey(
2650 Schema.Union([Schema.Number.annotate({ format: "int64" }).check(Schema.isInt()), Schema.Null]),
2651 ),
2652 usedPercent: Schema.Number.annotate({ format: "int32" }).check(Schema.isInt()),
2653 windowDurationMins: Schema.optionalKey(
2654 Schema.Union([Schema.Number.annotate({ format: "int64" }).check(Schema.isInt()), Schema.Null]),
2655 ),
2656});
2657
2658export type V2AccountUpdatedNotification__AuthMode = "apikey" | "chatgpt" | "chatgptAuthTokens";
2659export const V2AccountUpdatedNotification__AuthMode = Schema.Literals([
2660 "apikey",
2661 "chatgpt",
2662 "chatgptAuthTokens",
2663]).annotate({ description: "Authentication mode for OpenAI-backed providers." });
2664
2665export type V2AccountUpdatedNotification__PlanType =
2666 | "free"
2667 | "go"
2668 | "plus"
2669 | "pro"
2670 | "team"
2671 | "self_serve_business_usage_based"
2672 | "business"
2673 | "enterprise_cbp_usage_based"
2674 | "enterprise"
2675 | "edu"
2676 | "unknown";
2677export const V2AccountUpdatedNotification__PlanType = Schema.Literals([
2678 "free",
2679 "go",
2680 "plus",
2681 "pro",
2682 "team",
2683 "self_serve_business_usage_based",
2684 "business",
2685 "enterprise_cbp_usage_based",
2686 "enterprise",
2687 "edu",
2688 "unknown",
2689]);
2690
2691export type V2AppListUpdatedNotification__AppBranding = {
2692 readonly category?: string | null;
2693 readonly developer?: string | null;
2694 readonly isDiscoverableApp: boolean;
2695 readonly privacyPolicy?: string | null;
2696 readonly termsOfService?: string | null;
2697 readonly website?: string | null;
2698};
2699export const V2AppListUpdatedNotification__AppBranding = Schema.Struct({
2700 category: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
2701 developer: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
2702 isDiscoverableApp: Schema.Boolean,
2703 privacyPolicy: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
2704 termsOfService: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
2705 website: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
2706}).annotate({ description: "EXPERIMENTAL - app metadata returned by app-list APIs." });
2707
2708export type V2AppListUpdatedNotification__AppReview = { readonly status: string };
2709export const V2AppListUpdatedNotification__AppReview = Schema.Struct({ status: Schema.String });
2710
2711export type V2AppListUpdatedNotification__AppScreenshot = {
2712 readonly fileId?: string | null;
2713 readonly url?: string | null;
2714 readonly userPrompt: string;
2715};
2716export const V2AppListUpdatedNotification__AppScreenshot = Schema.Struct({
2717 fileId: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
2718 url: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
2719 userPrompt: Schema.String,
2720});
2721
2722export type V2AppsListResponse__AppBranding = {
2723 readonly category?: string | null;
2724 readonly developer?: string | null;
2725 readonly isDiscoverableApp: boolean;
2726 readonly privacyPolicy?: string | null;
2727 readonly termsOfService?: string | null;
2728 readonly website?: string | null;
2729};
2730export const V2AppsListResponse__AppBranding = Schema.Struct({
2731 category: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
2732 developer: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
2733 isDiscoverableApp: Schema.Boolean,
2734 privacyPolicy: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
2735 termsOfService: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
2736 website: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
2737}).annotate({ description: "EXPERIMENTAL - app metadata returned by app-list APIs." });
2738
2739export type V2AppsListResponse__AppReview = { readonly status: string };
2740export const V2AppsListResponse__AppReview = Schema.Struct({ status: Schema.String });
2741
2742export type V2AppsListResponse__AppScreenshot = {
2743 readonly fileId?: string | null;
2744 readonly url?: string | null;
2745 readonly userPrompt: string;
2746};
2747export const V2AppsListResponse__AppScreenshot = Schema.Struct({
2748 fileId: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
2749 url: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
2750 userPrompt: Schema.String,
2751});
2752
2753export type V2CancelLoginAccountResponse__CancelLoginAccountStatus = "canceled" | "notFound";
2754export const V2CancelLoginAccountResponse__CancelLoginAccountStatus = Schema.Literals([
2755 "canceled",
2756 "notFound",
2757]);
2758
2759export type V2CommandExecParams__AbsolutePathBuf = string;
2760export const V2CommandExecParams__AbsolutePathBuf = Schema.String.annotate({
2761 description:
2762 "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.",
2763});
2764
2765export type V2CommandExecParams__CommandExecTerminalSize = {
2766 readonly cols: number;
2767 readonly rows: number;
2768};
2769export const V2CommandExecParams__CommandExecTerminalSize = Schema.Struct({
2770 cols: Schema.Number.annotate({
2771 description: "Terminal width in character cells.",
2772 format: "uint16",
2773 })
2774 .check(Schema.isInt())
2775 .check(Schema.isGreaterThanOrEqualTo(0)),
2776 rows: Schema.Number.annotate({
2777 description: "Terminal height in character cells.",
2778 format: "uint16",
2779 })
2780 .check(Schema.isInt())
2781 .check(Schema.isGreaterThanOrEqualTo(0)),
2782}).annotate({ description: "PTY size in character cells for `command/exec` PTY sessions." });
2783
2784export type V2ConfigBatchWriteParams__MergeStrategy = "replace" | "upsert";
2785export const V2ConfigBatchWriteParams__MergeStrategy = Schema.Literals(["replace", "upsert"]);
2786
2787export type V2ConfigReadResponse__AbsolutePathBuf = string;
2788export const V2ConfigReadResponse__AbsolutePathBuf = Schema.String.annotate({
2789 description:
2790 "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.",
2791});
2792
2793export type V2ConfigReadResponse__AnalyticsConfig = {
2794 readonly enabled?: boolean | null;
2795 readonly [x: string]: unknown;
2796};
2797export const V2ConfigReadResponse__AnalyticsConfig = Schema.StructWithRest(
2798 Schema.Struct({ enabled: Schema.optionalKey(Schema.Union([Schema.Boolean, Schema.Null])) }),
2799 [Schema.Record(Schema.String, Schema.Unknown)],
2800);
2801
2802export type V2ConfigReadResponse__AppToolApproval = "auto" | "prompt" | "approve";
2803export const V2ConfigReadResponse__AppToolApproval = Schema.Literals(["auto", "prompt", "approve"]);
2804
2805export type V2ConfigReadResponse__AppToolsConfig = {};
2806export const V2ConfigReadResponse__AppToolsConfig = Schema.Struct({});
2807
2808export type V2ConfigReadResponse__ApprovalsReviewer = "user" | "guardian_subagent";
2809export const V2ConfigReadResponse__ApprovalsReviewer = Schema.Literals([
2810 "user",
2811 "guardian_subagent",
2812]).annotate({
2813 description:
2814 "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.",
2815});
2816
2817export type V2ConfigReadResponse__AppsDefaultConfig = {
2818 readonly destructive_enabled?: boolean;
2819 readonly enabled?: boolean;
2820 readonly open_world_enabled?: boolean;
2821};
2822export const V2ConfigReadResponse__AppsDefaultConfig = Schema.Struct({
2823 destructive_enabled: Schema.optionalKey(Schema.Boolean.annotate({ default: true })),
2824 enabled: Schema.optionalKey(Schema.Boolean.annotate({ default: true })),
2825 open_world_enabled: Schema.optionalKey(Schema.Boolean.annotate({ default: true })),
2826});
2827
2828export type V2ConfigReadResponse__AskForApproval =
2829 | "untrusted"
2830 | "on-failure"
2831 | "on-request"
2832 | "never"
2833 | {
2834 readonly granular: {
2835 readonly mcp_elicitations: boolean;
2836 readonly request_permissions?: boolean;
2837 readonly rules: boolean;
2838 readonly sandbox_approval: boolean;
2839 readonly skill_approval?: boolean;
2840 };
2841 };
2842export const V2ConfigReadResponse__AskForApproval = Schema.Union(
2843 [
2844 Schema.Literals(["untrusted", "on-failure", "on-request", "never"]),
2845 Schema.Struct({
2846 granular: Schema.Struct({
2847 mcp_elicitations: Schema.Boolean,
2848 request_permissions: Schema.optionalKey(Schema.Boolean.annotate({ default: false })),
2849 rules: Schema.Boolean,
2850 sandbox_approval: Schema.Boolean,
2851 skill_approval: Schema.optionalKey(Schema.Boolean.annotate({ default: false })),
2852 }),
2853 }).annotate({ title: "GranularAskForApproval" }),
2854 ],
2855 { mode: "oneOf" },
2856);
2857
2858export type V2ConfigReadResponse__ForcedLoginMethod = "chatgpt" | "api";
2859export const V2ConfigReadResponse__ForcedLoginMethod = Schema.Literals(["chatgpt", "api"]);
2860
2861export type V2ConfigReadResponse__ReasoningEffort =
2862 | "none"
2863 | "minimal"
2864 | "low"
2865 | "medium"
2866 | "high"
2867 | "xhigh";
2868export const V2ConfigReadResponse__ReasoningEffort = Schema.Literals([
2869 "none",
2870 "minimal",
2871 "low",
2872 "medium",
2873 "high",
2874 "xhigh",
2875]).annotate({
2876 description:
2877 "See https://platform.openai.com/docs/guides/reasoning?api-mode=responses#get-started-with-reasoning",
2878});
2879
2880export type V2ConfigReadResponse__ReasoningSummary = "auto" | "concise" | "detailed" | "none";
2881export const V2ConfigReadResponse__ReasoningSummary = Schema.Union(
2882 [
2883 Schema.Literals(["auto", "concise", "detailed"]),
2884 Schema.Literal("none").annotate({ description: "Option to disable reasoning summaries." }),
2885 ],
2886 { mode: "oneOf" },
2887).annotate({
2888 description:
2889 "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",
2890});
2891
2892export type V2ConfigReadResponse__SandboxMode =
2893 | "read-only"
2894 | "workspace-write"
2895 | "danger-full-access";
2896export const V2ConfigReadResponse__SandboxMode = Schema.Literals([
2897 "read-only",
2898 "workspace-write",
2899 "danger-full-access",
2900]);
2901
2902export type V2ConfigReadResponse__SandboxWorkspaceWrite = {
2903 readonly exclude_slash_tmp?: boolean;
2904 readonly exclude_tmpdir_env_var?: boolean;
2905 readonly network_access?: boolean;
2906 readonly writable_roots?: ReadonlyArray<string>;
2907};
2908export const V2ConfigReadResponse__SandboxWorkspaceWrite = Schema.Struct({
2909 exclude_slash_tmp: Schema.optionalKey(Schema.Boolean.annotate({ default: false })),
2910 exclude_tmpdir_env_var: Schema.optionalKey(Schema.Boolean.annotate({ default: false })),
2911 network_access: Schema.optionalKey(Schema.Boolean.annotate({ default: false })),
2912 writable_roots: Schema.optionalKey(Schema.Array(Schema.String).annotate({ default: [] })),
2913});
2914
2915export type V2ConfigReadResponse__ServiceTier = "fast" | "flex";
2916export const V2ConfigReadResponse__ServiceTier = Schema.Literals(["fast", "flex"]);
2917
2918export type V2ConfigReadResponse__Verbosity = "low" | "medium" | "high";
2919export const V2ConfigReadResponse__Verbosity = Schema.Literals(["low", "medium", "high"]).annotate({
2920 description:
2921 "Controls output length/detail on GPT-5 models via the Responses API. Serialized with lowercase values to match the OpenAI API.",
2922});
2923
2924export type V2ConfigReadResponse__WebSearchContextSize = "low" | "medium" | "high";
2925export const V2ConfigReadResponse__WebSearchContextSize = Schema.Literals([
2926 "low",
2927 "medium",
2928 "high",
2929]);
2930
2931export type V2ConfigReadResponse__WebSearchLocation = {
2932 readonly city?: string | null;
2933 readonly country?: string | null;
2934 readonly region?: string | null;
2935 readonly timezone?: string | null;
2936};
2937export const V2ConfigReadResponse__WebSearchLocation = Schema.Struct({
2938 city: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
2939 country: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
2940 region: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
2941 timezone: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
2942});
2943
2944export type V2ConfigReadResponse__WebSearchMode = "disabled" | "cached" | "live";
2945export const V2ConfigReadResponse__WebSearchMode = Schema.Literals(["disabled", "cached", "live"]);
2946
2947export type V2ConfigRequirementsReadResponse__AskForApproval =
2948 | "untrusted"
2949 | "on-failure"
2950 | "on-request"
2951 | "never"
2952 | {
2953 readonly granular: {
2954 readonly mcp_elicitations: boolean;
2955 readonly request_permissions?: boolean;
2956 readonly rules: boolean;
2957 readonly sandbox_approval: boolean;
2958 readonly skill_approval?: boolean;
2959 };
2960 };
2961export const V2ConfigRequirementsReadResponse__AskForApproval = Schema.Union(
2962 [
2963 Schema.Literals(["untrusted", "on-failure", "on-request", "never"]),
2964 Schema.Struct({
2965 granular: Schema.Struct({
2966 mcp_elicitations: Schema.Boolean,
2967 request_permissions: Schema.optionalKey(Schema.Boolean.annotate({ default: false })),
2968 rules: Schema.Boolean,
2969 sandbox_approval: Schema.Boolean,
2970 skill_approval: Schema.optionalKey(Schema.Boolean.annotate({ default: false })),
2971 }),
2972 }).annotate({ title: "GranularAskForApproval" }),
2973 ],
2974 { mode: "oneOf" },
2975);
2976
2977export type V2ConfigRequirementsReadResponse__NetworkDomainPermission = "allow" | "deny";
2978export const V2ConfigRequirementsReadResponse__NetworkDomainPermission = Schema.Literals([
2979 "allow",
2980 "deny",
2981]);
2982
2983export type V2ConfigRequirementsReadResponse__NetworkUnixSocketPermission = "allow" | "none";
2984export const V2ConfigRequirementsReadResponse__NetworkUnixSocketPermission = Schema.Literals([
2985 "allow",
2986 "none",
2987]);
2988
2989export type V2ConfigRequirementsReadResponse__ResidencyRequirement = "us";
2990export const V2ConfigRequirementsReadResponse__ResidencyRequirement = Schema.Literal("us");
2991
2992export type V2ConfigRequirementsReadResponse__SandboxMode =
2993 | "read-only"
2994 | "workspace-write"
2995 | "danger-full-access";
2996export const V2ConfigRequirementsReadResponse__SandboxMode = Schema.Literals([
2997 "read-only",
2998 "workspace-write",
2999 "danger-full-access",
3000]);
3001
3002export type V2ConfigRequirementsReadResponse__WebSearchMode = "disabled" | "cached" | "live";
3003export const V2ConfigRequirementsReadResponse__WebSearchMode = Schema.Literals([
3004 "disabled",
3005 "cached",
3006 "live",
3007]);
3008
3009export type V2ConfigValueWriteParams__MergeStrategy = "replace" | "upsert";
3010export const V2ConfigValueWriteParams__MergeStrategy = Schema.Literals(["replace", "upsert"]);
3011
3012export type V2ConfigWarningNotification__TextPosition = {
3013 readonly column: number;
3014 readonly line: number;
3015};
3016export const V2ConfigWarningNotification__TextPosition = Schema.Struct({
3017 column: Schema.Number.annotate({
3018 description: "1-based column number (in Unicode scalar values).",
3019 format: "uint",
3020 })
3021 .check(Schema.isInt())
3022 .check(Schema.isGreaterThanOrEqualTo(0)),
3023 line: Schema.Number.annotate({ description: "1-based line number.", format: "uint" })
3024 .check(Schema.isInt())
3025 .check(Schema.isGreaterThanOrEqualTo(0)),
3026});
3027
3028export type V2ConfigWriteResponse__AbsolutePathBuf = string;
3029export const V2ConfigWriteResponse__AbsolutePathBuf = Schema.String.annotate({
3030 description:
3031 "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.",
3032});
3033
3034export type V2ConfigWriteResponse__WriteStatus = "ok" | "okOverridden";
3035export const V2ConfigWriteResponse__WriteStatus = Schema.Literals(["ok", "okOverridden"]);
3036
3037export type V2ErrorNotification__NonSteerableTurnKind = "review" | "compact";
3038export const V2ErrorNotification__NonSteerableTurnKind = Schema.Literals(["review", "compact"]);
3039
3040export type V2ExperimentalFeatureListResponse__ExperimentalFeature = {
3041 readonly announcement?: string | null;
3042 readonly defaultEnabled: boolean;
3043 readonly description?: string | null;
3044 readonly displayName?: string | null;
3045 readonly enabled: boolean;
3046 readonly name: string;
3047 readonly stage: "beta" | "underDevelopment" | "stable" | "deprecated" | "removed";
3048};
3049export const V2ExperimentalFeatureListResponse__ExperimentalFeature = Schema.Struct({
3050 announcement: Schema.optionalKey(
3051 Schema.Union([
3052 Schema.String.annotate({
3053 description:
3054 "Announcement copy shown to users when the feature is introduced. Null when this feature is not in beta.",
3055 }),
3056 Schema.Null,
3057 ]),
3058 ),
3059 defaultEnabled: Schema.Boolean.annotate({
3060 description: "Whether this feature is enabled by default.",
3061 }),
3062 description: Schema.optionalKey(
3063 Schema.Union([
3064 Schema.String.annotate({
3065 description:
3066 "Short summary describing what the feature does. Null when this feature is not in beta.",
3067 }),
3068 Schema.Null,
3069 ]),
3070 ),
3071 displayName: Schema.optionalKey(
3072 Schema.Union([
3073 Schema.String.annotate({
3074 description:
3075 "User-facing display name shown in the experimental features UI. Null when this feature is not in beta.",
3076 }),
3077 Schema.Null,
3078 ]),
3079 ),
3080 enabled: Schema.Boolean.annotate({
3081 description: "Whether this feature is currently enabled in the loaded config.",
3082 }),
3083 name: Schema.String.annotate({
3084 description: "Stable key used in config.toml and CLI flag toggles.",
3085 }),
3086 stage: Schema.Literals(["beta", "underDevelopment", "stable", "deprecated", "removed"]).annotate({
3087 description: "Lifecycle stage of this feature flag.",
3088 }),
3089});
3090
3091export type V2ExternalAgentConfigDetectResponse__ExternalAgentConfigMigrationItemType =
3092 | "AGENTS_MD"
3093 | "CONFIG"
3094 | "SKILLS"
3095 | "MCP_SERVER_CONFIG";
3096export const V2ExternalAgentConfigDetectResponse__ExternalAgentConfigMigrationItemType =
3097 Schema.Literals(["AGENTS_MD", "CONFIG", "SKILLS", "MCP_SERVER_CONFIG"]);
3098
3099export type V2ExternalAgentConfigImportParams__ExternalAgentConfigMigrationItemType =
3100 | "AGENTS_MD"
3101 | "CONFIG"
3102 | "SKILLS"
3103 | "MCP_SERVER_CONFIG";
3104export const V2ExternalAgentConfigImportParams__ExternalAgentConfigMigrationItemType =
3105 Schema.Literals(["AGENTS_MD", "CONFIG", "SKILLS", "MCP_SERVER_CONFIG"]);
3106
3107export type V2FsChangedNotification__AbsolutePathBuf = string;
3108export const V2FsChangedNotification__AbsolutePathBuf = Schema.String.annotate({
3109 description:
3110 "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.",
3111});
3112
3113export type V2FsReadDirectoryResponse__FsReadDirectoryEntry = {
3114 readonly fileName: string;
3115 readonly isDirectory: boolean;
3116 readonly isFile: boolean;
3117};
3118export const V2FsReadDirectoryResponse__FsReadDirectoryEntry = Schema.Struct({
3119 fileName: Schema.String.annotate({
3120 description: "Direct child entry name only, not an absolute or relative path.",
3121 }),
3122 isDirectory: Schema.Boolean.annotate({
3123 description: "Whether this entry resolves to a directory.",
3124 }),
3125 isFile: Schema.Boolean.annotate({
3126 description: "Whether this entry resolves to a regular file.",
3127 }),
3128}).annotate({ description: "A directory entry returned by `fs/readDirectory`." });
3129
3130export type V2GetAccountRateLimitsResponse__CreditsSnapshot = {
3131 readonly balance?: string | null;
3132 readonly hasCredits: boolean;
3133 readonly unlimited: boolean;
3134};
3135export const V2GetAccountRateLimitsResponse__CreditsSnapshot = Schema.Struct({
3136 balance: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
3137 hasCredits: Schema.Boolean,
3138 unlimited: Schema.Boolean,
3139});
3140
3141export type V2GetAccountRateLimitsResponse__PlanType =
3142 | "free"
3143 | "go"
3144 | "plus"
3145 | "pro"
3146 | "team"
3147 | "self_serve_business_usage_based"
3148 | "business"
3149 | "enterprise_cbp_usage_based"
3150 | "enterprise"
3151 | "edu"
3152 | "unknown";
3153export const V2GetAccountRateLimitsResponse__PlanType = Schema.Literals([
3154 "free",
3155 "go",
3156 "plus",
3157 "pro",
3158 "team",
3159 "self_serve_business_usage_based",
3160 "business",
3161 "enterprise_cbp_usage_based",
3162 "enterprise",
3163 "edu",
3164 "unknown",
3165]);
3166
3167export type V2GetAccountRateLimitsResponse__RateLimitWindow = {
3168 readonly resetsAt?: number | null;
3169 readonly usedPercent: number;
3170 readonly windowDurationMins?: number | null;
3171};
3172export const V2GetAccountRateLimitsResponse__RateLimitWindow = Schema.Struct({
3173 resetsAt: Schema.optionalKey(
3174 Schema.Union([Schema.Number.annotate({ format: "int64" }).check(Schema.isInt()), Schema.Null]),
3175 ),
3176 usedPercent: Schema.Number.annotate({ format: "int32" }).check(Schema.isInt()),
3177 windowDurationMins: Schema.optionalKey(
3178 Schema.Union([Schema.Number.annotate({ format: "int64" }).check(Schema.isInt()), Schema.Null]),
3179 ),
3180});
3181
3182export type V2GetAccountResponse__PlanType =
3183 | "free"
3184 | "go"
3185 | "plus"
3186 | "pro"
3187 | "team"
3188 | "self_serve_business_usage_based"
3189 | "business"
3190 | "enterprise_cbp_usage_based"
3191 | "enterprise"
3192 | "edu"
3193 | "unknown";
3194export const V2GetAccountResponse__PlanType = Schema.Literals([
3195 "free",
3196 "go",
3197 "plus",
3198 "pro",
3199 "team",
3200 "self_serve_business_usage_based",
3201 "business",
3202 "enterprise_cbp_usage_based",
3203 "enterprise",
3204 "edu",
3205 "unknown",
3206]);
3207
3208export type V2HookCompletedNotification__HookEventName =
3209 | "preToolUse"
3210 | "postToolUse"
3211 | "sessionStart"
3212 | "userPromptSubmit"
3213 | "stop";
3214export const V2HookCompletedNotification__HookEventName = Schema.Literals([
3215 "preToolUse",
3216 "postToolUse",
3217 "sessionStart",
3218 "userPromptSubmit",
3219 "stop",
3220]);
3221
3222export type V2HookCompletedNotification__HookExecutionMode = "sync" | "async";
3223export const V2HookCompletedNotification__HookExecutionMode = Schema.Literals(["sync", "async"]);
3224
3225export type V2HookCompletedNotification__HookHandlerType = "command" | "prompt" | "agent";
3226export const V2HookCompletedNotification__HookHandlerType = Schema.Literals([
3227 "command",
3228 "prompt",
3229 "agent",
3230]);
3231
3232export type V2HookCompletedNotification__HookOutputEntryKind =
3233 | "warning"
3234 | "stop"
3235 | "feedback"
3236 | "context"
3237 | "error";
3238export const V2HookCompletedNotification__HookOutputEntryKind = Schema.Literals([
3239 "warning",
3240 "stop",
3241 "feedback",
3242 "context",
3243 "error",
3244]);
3245
3246export type V2HookCompletedNotification__HookRunStatus =
3247 | "running"
3248 | "completed"
3249 | "failed"
3250 | "blocked"
3251 | "stopped";
3252export const V2HookCompletedNotification__HookRunStatus = Schema.Literals([
3253 "running",
3254 "completed",
3255 "failed",
3256 "blocked",
3257 "stopped",
3258]);
3259
3260export type V2HookCompletedNotification__HookScope = "thread" | "turn";
3261export const V2HookCompletedNotification__HookScope = Schema.Literals(["thread", "turn"]);
3262
3263export type V2HookStartedNotification__HookEventName =
3264 | "preToolUse"
3265 | "postToolUse"
3266 | "sessionStart"
3267 | "userPromptSubmit"
3268 | "stop";
3269export const V2HookStartedNotification__HookEventName = Schema.Literals([
3270 "preToolUse",
3271 "postToolUse",
3272 "sessionStart",
3273 "userPromptSubmit",
3274 "stop",
3275]);
3276
3277export type V2HookStartedNotification__HookExecutionMode = "sync" | "async";
3278export const V2HookStartedNotification__HookExecutionMode = Schema.Literals(["sync", "async"]);
3279
3280export type V2HookStartedNotification__HookHandlerType = "command" | "prompt" | "agent";
3281export const V2HookStartedNotification__HookHandlerType = Schema.Literals([
3282 "command",
3283 "prompt",
3284 "agent",
3285]);
3286
3287export type V2HookStartedNotification__HookOutputEntryKind =
3288 | "warning"
3289 | "stop"
3290 | "feedback"
3291 | "context"
3292 | "error";
3293export const V2HookStartedNotification__HookOutputEntryKind = Schema.Literals([
3294 "warning",
3295 "stop",
3296 "feedback",
3297 "context",
3298 "error",
3299]);
3300
3301export type V2HookStartedNotification__HookRunStatus =
3302 | "running"
3303 | "completed"
3304 | "failed"
3305 | "blocked"
3306 | "stopped";
3307export const V2HookStartedNotification__HookRunStatus = Schema.Literals([
3308 "running",
3309 "completed",
3310 "failed",
3311 "blocked",
3312 "stopped",
3313]);
3314
3315export type V2HookStartedNotification__HookScope = "thread" | "turn";
3316export const V2HookStartedNotification__HookScope = Schema.Literals(["thread", "turn"]);
3317
3318export type V2ItemCompletedNotification__CollabAgentStatus =
3319 | "pendingInit"
3320 | "running"
3321 | "interrupted"
3322 | "completed"
3323 | "errored"
3324 | "shutdown"
3325 | "notFound";
3326export const V2ItemCompletedNotification__CollabAgentStatus = Schema.Literals([
3327 "pendingInit",
3328 "running",
3329 "interrupted",
3330 "completed",
3331 "errored",
3332 "shutdown",
3333 "notFound",
3334]);
3335
3336export type V2ItemCompletedNotification__CommandAction =
3337 | {
3338 readonly command: string;
3339 readonly name: string;
3340 readonly path: string;
3341 readonly type: "read";
3342 }
3343 | { readonly command: string; readonly path?: string | null; readonly type: "listFiles" }
3344 | {
3345 readonly command: string;
3346 readonly path?: string | null;
3347 readonly query?: string | null;
3348 readonly type: "search";
3349 }
3350 | { readonly command: string; readonly type: "unknown" };
3351export const V2ItemCompletedNotification__CommandAction = Schema.Union(
3352 [
3353 Schema.Struct({
3354 command: Schema.String,
3355 name: Schema.String,
3356 path: Schema.String,
3357 type: Schema.Literal("read").annotate({ title: "ReadCommandActionType" }),
3358 }).annotate({ title: "ReadCommandAction" }),
3359 Schema.Struct({
3360 command: Schema.String,
3361 path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
3362 type: Schema.Literal("listFiles").annotate({ title: "ListFilesCommandActionType" }),
3363 }).annotate({ title: "ListFilesCommandAction" }),
3364 Schema.Struct({
3365 command: Schema.String,
3366 path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
3367 query: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
3368 type: Schema.Literal("search").annotate({ title: "SearchCommandActionType" }),
3369 }).annotate({ title: "SearchCommandAction" }),
3370 Schema.Struct({
3371 command: Schema.String,
3372 type: Schema.Literal("unknown").annotate({ title: "UnknownCommandActionType" }),
3373 }).annotate({ title: "UnknownCommandAction" }),
3374 ],
3375 { mode: "oneOf" },
3376);
3377
3378export type V2ItemCompletedNotification__CommandExecutionStatus =
3379 | "inProgress"
3380 | "completed"
3381 | "failed"
3382 | "declined";
3383export const V2ItemCompletedNotification__CommandExecutionStatus = Schema.Literals([
3384 "inProgress",
3385 "completed",
3386 "failed",
3387 "declined",
3388]);
3389
3390export type V2ItemCompletedNotification__DynamicToolCallOutputContentItem =
3391 | { readonly text: string; readonly type: "inputText" }
3392 | { readonly imageUrl: string; readonly type: "inputImage" };
3393export const V2ItemCompletedNotification__DynamicToolCallOutputContentItem = Schema.Union(
3394 [
3395 Schema.Struct({
3396 text: Schema.String,
3397 type: Schema.Literal("inputText").annotate({
3398 title: "InputTextDynamicToolCallOutputContentItemType",
3399 }),
3400 }).annotate({ title: "InputTextDynamicToolCallOutputContentItem" }),
3401 Schema.Struct({
3402 imageUrl: Schema.String,
3403 type: Schema.Literal("inputImage").annotate({
3404 title: "InputImageDynamicToolCallOutputContentItemType",
3405 }),
3406 }).annotate({ title: "InputImageDynamicToolCallOutputContentItem" }),
3407 ],
3408 { mode: "oneOf" },
3409);
3410
3411export type V2ItemCompletedNotification__DynamicToolCallStatus =
3412 | "inProgress"
3413 | "completed"
3414 | "failed";
3415export const V2ItemCompletedNotification__DynamicToolCallStatus = Schema.Literals([
3416 "inProgress",
3417 "completed",
3418 "failed",
3419]);
3420
3421export type V2ItemCompletedNotification__HookPromptFragment = {
3422 readonly hookRunId: string;
3423 readonly text: string;
3424};
3425export const V2ItemCompletedNotification__HookPromptFragment = Schema.Struct({
3426 hookRunId: Schema.String,
3427 text: Schema.String,
3428});
3429
3430export type V2ItemCompletedNotification__McpToolCallError = { readonly message: string };
3431export const V2ItemCompletedNotification__McpToolCallError = Schema.Struct({
3432 message: Schema.String,
3433});
3434
3435export type V2ItemCompletedNotification__McpToolCallResult = {
3436 readonly _meta?: unknown;
3437 readonly content: ReadonlyArray<unknown>;
3438 readonly structuredContent?: unknown;
3439};
3440export const V2ItemCompletedNotification__McpToolCallResult = Schema.Struct({
3441 _meta: Schema.optionalKey(Schema.Unknown),
3442 content: Schema.Array(Schema.Unknown),
3443 structuredContent: Schema.optionalKey(Schema.Unknown),
3444});
3445
3446export type V2ItemCompletedNotification__McpToolCallStatus = "inProgress" | "completed" | "failed";
3447export const V2ItemCompletedNotification__McpToolCallStatus = Schema.Literals([
3448 "inProgress",
3449 "completed",
3450 "failed",
3451]);
3452
3453export type V2ItemCompletedNotification__MemoryCitationEntry = {
3454 readonly lineEnd: number;
3455 readonly lineStart: number;
3456 readonly note: string;
3457 readonly path: string;
3458};
3459export const V2ItemCompletedNotification__MemoryCitationEntry = Schema.Struct({
3460 lineEnd: Schema.Number.annotate({ format: "uint32" })
3461 .check(Schema.isInt())
3462 .check(Schema.isGreaterThanOrEqualTo(0)),
3463 lineStart: Schema.Number.annotate({ format: "uint32" })
3464 .check(Schema.isInt())
3465 .check(Schema.isGreaterThanOrEqualTo(0)),
3466 note: Schema.String,
3467 path: Schema.String,
3468});
3469
3470export type V2ItemCompletedNotification__MessagePhase = "commentary" | "final_answer";
3471export const V2ItemCompletedNotification__MessagePhase = Schema.Literals([
3472 "commentary",
3473 "final_answer",
3474]).annotate({
3475 description:
3476 '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.',
3477});
3478
3479export type V2ItemCompletedNotification__PatchApplyStatus =
3480 | "inProgress"
3481 | "completed"
3482 | "failed"
3483 | "declined";
3484export const V2ItemCompletedNotification__PatchApplyStatus = Schema.Literals([
3485 "inProgress",
3486 "completed",
3487 "failed",
3488 "declined",
3489]);
3490
3491export type V2ItemCompletedNotification__PatchChangeKind =
3492 | { readonly type: "add" }
3493 | { readonly type: "delete" }
3494 | { readonly move_path?: string | null; readonly type: "update" };
3495export const V2ItemCompletedNotification__PatchChangeKind = Schema.Union(
3496 [
3497 Schema.Struct({
3498 type: Schema.Literal("add").annotate({ title: "AddPatchChangeKindType" }),
3499 }).annotate({ title: "AddPatchChangeKind" }),
3500 Schema.Struct({
3501 type: Schema.Literal("delete").annotate({ title: "DeletePatchChangeKindType" }),
3502 }).annotate({ title: "DeletePatchChangeKind" }),
3503 Schema.Struct({
3504 move_path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
3505 type: Schema.Literal("update").annotate({ title: "UpdatePatchChangeKindType" }),
3506 }).annotate({ title: "UpdatePatchChangeKind" }),
3507 ],
3508 { mode: "oneOf" },
3509);
3510
3511export type V2ItemCompletedNotification__ReasoningEffort =
3512 | "none"
3513 | "minimal"
3514 | "low"
3515 | "medium"
3516 | "high"
3517 | "xhigh";
3518export const V2ItemCompletedNotification__ReasoningEffort = Schema.Literals([
3519 "none",
3520 "minimal",
3521 "low",
3522 "medium",
3523 "high",
3524 "xhigh",
3525]).annotate({
3526 description:
3527 "See https://platform.openai.com/docs/guides/reasoning?api-mode=responses#get-started-with-reasoning",
3528});
3529
3530export type V2ItemCompletedNotification__TextElement = {
3531 readonly byteRange: { readonly end: number; readonly start: number };
3532 readonly placeholder?: string | null;
3533};
3534export const V2ItemCompletedNotification__TextElement = Schema.Struct({
3535 byteRange: Schema.Struct({
3536 end: Schema.Number.annotate({ format: "uint" })
3537 .check(Schema.isInt())
3538 .check(Schema.isGreaterThanOrEqualTo(0)),
3539 start: Schema.Number.annotate({ format: "uint" })
3540 .check(Schema.isInt())
3541 .check(Schema.isGreaterThanOrEqualTo(0)),
3542 }).annotate({
3543 description: "Byte range in the parent `text` buffer that this element occupies.",
3544 }),
3545 placeholder: Schema.optionalKey(
3546 Schema.Union([
3547 Schema.String.annotate({
3548 description: "Optional human-readable placeholder for the element, displayed in the UI.",
3549 }),
3550 Schema.Null,
3551 ]),
3552 ),
3553});
3554
3555export type V2ItemCompletedNotification__WebSearchAction =
3556 | {
3557 readonly queries?: ReadonlyArray<string> | null;
3558 readonly query?: string | null;
3559 readonly type: "search";
3560 }
3561 | { readonly type: "openPage"; readonly url?: string | null }
3562 | { readonly pattern?: string | null; readonly type: "findInPage"; readonly url?: string | null }
3563 | { readonly type: "other" };
3564export const V2ItemCompletedNotification__WebSearchAction = Schema.Union(
3565 [
3566 Schema.Struct({
3567 queries: Schema.optionalKey(Schema.Union([Schema.Array(Schema.String), Schema.Null])),
3568 query: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
3569 type: Schema.Literal("search").annotate({ title: "SearchWebSearchActionType" }),
3570 }).annotate({ title: "SearchWebSearchAction" }),
3571 Schema.Struct({
3572 type: Schema.Literal("openPage").annotate({ title: "OpenPageWebSearchActionType" }),
3573 url: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
3574 }).annotate({ title: "OpenPageWebSearchAction" }),
3575 Schema.Struct({
3576 pattern: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
3577 type: Schema.Literal("findInPage").annotate({ title: "FindInPageWebSearchActionType" }),
3578 url: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
3579 }).annotate({ title: "FindInPageWebSearchAction" }),
3580 Schema.Struct({
3581 type: Schema.Literal("other").annotate({ title: "OtherWebSearchActionType" }),
3582 }).annotate({ title: "OtherWebSearchAction" }),
3583 ],
3584 { mode: "oneOf" },
3585);
3586
3587export type V2ItemGuardianApprovalReviewCompletedNotification__AutoReviewDecisionSource = "agent";
3588export const V2ItemGuardianApprovalReviewCompletedNotification__AutoReviewDecisionSource =
3589 Schema.Literal("agent").annotate({
3590 description: "[UNSTABLE] Source that produced a terminal guardian approval review decision.",
3591 });
3592
3593export type V2ItemGuardianApprovalReviewCompletedNotification__GuardianApprovalReviewStatus =
3594 | "inProgress"
3595 | "approved"
3596 | "denied"
3597 | "timedOut"
3598 | "aborted";
3599export const V2ItemGuardianApprovalReviewCompletedNotification__GuardianApprovalReviewStatus =
3600 Schema.Literals(["inProgress", "approved", "denied", "timedOut", "aborted"]).annotate({
3601 description: "[UNSTABLE] Lifecycle state for a guardian approval review.",
3602 });
3603
3604export type V2ItemGuardianApprovalReviewCompletedNotification__GuardianCommandSource =
3605 | "shell"
3606 | "unifiedExec";
3607export const V2ItemGuardianApprovalReviewCompletedNotification__GuardianCommandSource =
3608 Schema.Literals(["shell", "unifiedExec"]);
3609
3610export type V2ItemGuardianApprovalReviewCompletedNotification__GuardianRiskLevel =
3611 | "low"
3612 | "medium"
3613 | "high"
3614 | "critical";
3615export const V2ItemGuardianApprovalReviewCompletedNotification__GuardianRiskLevel = Schema.Literals(
3616 ["low", "medium", "high", "critical"],
3617).annotate({ description: "[UNSTABLE] Risk level assigned by guardian approval review." });
3618
3619export type V2ItemGuardianApprovalReviewCompletedNotification__GuardianUserAuthorization =
3620 | "unknown"
3621 | "low"
3622 | "medium"
3623 | "high";
3624export const V2ItemGuardianApprovalReviewCompletedNotification__GuardianUserAuthorization =
3625 Schema.Literals(["unknown", "low", "medium", "high"]).annotate({
3626 description: "[UNSTABLE] Authorization level assigned by guardian approval review.",
3627 });
3628
3629export type V2ItemGuardianApprovalReviewCompletedNotification__NetworkApprovalProtocol =
3630 | "http"
3631 | "https"
3632 | "socks5Tcp"
3633 | "socks5Udp";
3634export const V2ItemGuardianApprovalReviewCompletedNotification__NetworkApprovalProtocol =
3635 Schema.Literals(["http", "https", "socks5Tcp", "socks5Udp"]);
3636
3637export type V2ItemGuardianApprovalReviewStartedNotification__GuardianApprovalReviewStatus =
3638 | "inProgress"
3639 | "approved"
3640 | "denied"
3641 | "timedOut"
3642 | "aborted";
3643export const V2ItemGuardianApprovalReviewStartedNotification__GuardianApprovalReviewStatus =
3644 Schema.Literals(["inProgress", "approved", "denied", "timedOut", "aborted"]).annotate({
3645 description: "[UNSTABLE] Lifecycle state for a guardian approval review.",
3646 });
3647
3648export type V2ItemGuardianApprovalReviewStartedNotification__GuardianCommandSource =
3649 | "shell"
3650 | "unifiedExec";
3651export const V2ItemGuardianApprovalReviewStartedNotification__GuardianCommandSource =
3652 Schema.Literals(["shell", "unifiedExec"]);
3653
3654export type V2ItemGuardianApprovalReviewStartedNotification__GuardianRiskLevel =
3655 | "low"
3656 | "medium"
3657 | "high"
3658 | "critical";
3659export const V2ItemGuardianApprovalReviewStartedNotification__GuardianRiskLevel = Schema.Literals([
3660 "low",
3661 "medium",
3662 "high",
3663 "critical",
3664]).annotate({ description: "[UNSTABLE] Risk level assigned by guardian approval review." });
3665
3666export type V2ItemGuardianApprovalReviewStartedNotification__GuardianUserAuthorization =
3667 | "unknown"
3668 | "low"
3669 | "medium"
3670 | "high";
3671export const V2ItemGuardianApprovalReviewStartedNotification__GuardianUserAuthorization =
3672 Schema.Literals(["unknown", "low", "medium", "high"]).annotate({
3673 description: "[UNSTABLE] Authorization level assigned by guardian approval review.",
3674 });
3675
3676export type V2ItemGuardianApprovalReviewStartedNotification__NetworkApprovalProtocol =
3677 | "http"
3678 | "https"
3679 | "socks5Tcp"
3680 | "socks5Udp";
3681export const V2ItemGuardianApprovalReviewStartedNotification__NetworkApprovalProtocol =
3682 Schema.Literals(["http", "https", "socks5Tcp", "socks5Udp"]);
3683
3684export type V2ItemStartedNotification__CollabAgentStatus =
3685 | "pendingInit"
3686 | "running"
3687 | "interrupted"
3688 | "completed"
3689 | "errored"
3690 | "shutdown"
3691 | "notFound";
3692export const V2ItemStartedNotification__CollabAgentStatus = Schema.Literals([
3693 "pendingInit",
3694 "running",
3695 "interrupted",
3696 "completed",
3697 "errored",
3698 "shutdown",
3699 "notFound",
3700]);
3701
3702export type V2ItemStartedNotification__CommandAction =
3703 | {
3704 readonly command: string;
3705 readonly name: string;
3706 readonly path: string;
3707 readonly type: "read";
3708 }
3709 | { readonly command: string; readonly path?: string | null; readonly type: "listFiles" }
3710 | {
3711 readonly command: string;
3712 readonly path?: string | null;
3713 readonly query?: string | null;
3714 readonly type: "search";
3715 }
3716 | { readonly command: string; readonly type: "unknown" };
3717export const V2ItemStartedNotification__CommandAction = Schema.Union(
3718 [
3719 Schema.Struct({
3720 command: Schema.String,
3721 name: Schema.String,
3722 path: Schema.String,
3723 type: Schema.Literal("read").annotate({ title: "ReadCommandActionType" }),
3724 }).annotate({ title: "ReadCommandAction" }),
3725 Schema.Struct({
3726 command: Schema.String,
3727 path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
3728 type: Schema.Literal("listFiles").annotate({ title: "ListFilesCommandActionType" }),
3729 }).annotate({ title: "ListFilesCommandAction" }),
3730 Schema.Struct({
3731 command: Schema.String,
3732 path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
3733 query: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
3734 type: Schema.Literal("search").annotate({ title: "SearchCommandActionType" }),
3735 }).annotate({ title: "SearchCommandAction" }),
3736 Schema.Struct({
3737 command: Schema.String,
3738 type: Schema.Literal("unknown").annotate({ title: "UnknownCommandActionType" }),
3739 }).annotate({ title: "UnknownCommandAction" }),
3740 ],
3741 { mode: "oneOf" },
3742);
3743
3744export type V2ItemStartedNotification__CommandExecutionStatus =
3745 | "inProgress"
3746 | "completed"
3747 | "failed"
3748 | "declined";
3749export const V2ItemStartedNotification__CommandExecutionStatus = Schema.Literals([
3750 "inProgress",
3751 "completed",
3752 "failed",
3753 "declined",
3754]);
3755
3756export type V2ItemStartedNotification__DynamicToolCallOutputContentItem =
3757 | { readonly text: string; readonly type: "inputText" }
3758 | { readonly imageUrl: string; readonly type: "inputImage" };
3759export const V2ItemStartedNotification__DynamicToolCallOutputContentItem = Schema.Union(
3760 [
3761 Schema.Struct({
3762 text: Schema.String,
3763 type: Schema.Literal("inputText").annotate({
3764 title: "InputTextDynamicToolCallOutputContentItemType",
3765 }),
3766 }).annotate({ title: "InputTextDynamicToolCallOutputContentItem" }),
3767 Schema.Struct({
3768 imageUrl: Schema.String,
3769 type: Schema.Literal("inputImage").annotate({
3770 title: "InputImageDynamicToolCallOutputContentItemType",
3771 }),
3772 }).annotate({ title: "InputImageDynamicToolCallOutputContentItem" }),
3773 ],
3774 { mode: "oneOf" },
3775);
3776
3777export type V2ItemStartedNotification__DynamicToolCallStatus =
3778 | "inProgress"
3779 | "completed"
3780 | "failed";
3781export const V2ItemStartedNotification__DynamicToolCallStatus = Schema.Literals([
3782 "inProgress",
3783 "completed",
3784 "failed",
3785]);
3786
3787export type V2ItemStartedNotification__HookPromptFragment = {
3788 readonly hookRunId: string;
3789 readonly text: string;
3790};
3791export const V2ItemStartedNotification__HookPromptFragment = Schema.Struct({
3792 hookRunId: Schema.String,
3793 text: Schema.String,
3794});
3795
3796export type V2ItemStartedNotification__McpToolCallError = { readonly message: string };
3797export const V2ItemStartedNotification__McpToolCallError = Schema.Struct({
3798 message: Schema.String,
3799});
3800
3801export type V2ItemStartedNotification__McpToolCallResult = {
3802 readonly _meta?: unknown;
3803 readonly content: ReadonlyArray<unknown>;
3804 readonly structuredContent?: unknown;
3805};
3806export const V2ItemStartedNotification__McpToolCallResult = Schema.Struct({
3807 _meta: Schema.optionalKey(Schema.Unknown),
3808 content: Schema.Array(Schema.Unknown),
3809 structuredContent: Schema.optionalKey(Schema.Unknown),
3810});
3811
3812export type V2ItemStartedNotification__McpToolCallStatus = "inProgress" | "completed" | "failed";
3813export const V2ItemStartedNotification__McpToolCallStatus = Schema.Literals([
3814 "inProgress",
3815 "completed",
3816 "failed",
3817]);
3818
3819export type V2ItemStartedNotification__MemoryCitationEntry = {
3820 readonly lineEnd: number;
3821 readonly lineStart: number;
3822 readonly note: string;
3823 readonly path: string;
3824};
3825export const V2ItemStartedNotification__MemoryCitationEntry = Schema.Struct({
3826 lineEnd: Schema.Number.annotate({ format: "uint32" })
3827 .check(Schema.isInt())
3828 .check(Schema.isGreaterThanOrEqualTo(0)),
3829 lineStart: Schema.Number.annotate({ format: "uint32" })
3830 .check(Schema.isInt())
3831 .check(Schema.isGreaterThanOrEqualTo(0)),
3832 note: Schema.String,
3833 path: Schema.String,
3834});
3835
3836export type V2ItemStartedNotification__MessagePhase = "commentary" | "final_answer";
3837export const V2ItemStartedNotification__MessagePhase = Schema.Literals([
3838 "commentary",
3839 "final_answer",
3840]).annotate({
3841 description:
3842 '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.',
3843});
3844
3845export type V2ItemStartedNotification__PatchApplyStatus =
3846 | "inProgress"
3847 | "completed"
3848 | "failed"
3849 | "declined";
3850export const V2ItemStartedNotification__PatchApplyStatus = Schema.Literals([
3851 "inProgress",
3852 "completed",
3853 "failed",
3854 "declined",
3855]);
3856
3857export type V2ItemStartedNotification__PatchChangeKind =
3858 | { readonly type: "add" }
3859 | { readonly type: "delete" }
3860 | { readonly move_path?: string | null; readonly type: "update" };
3861export const V2ItemStartedNotification__PatchChangeKind = Schema.Union(
3862 [
3863 Schema.Struct({
3864 type: Schema.Literal("add").annotate({ title: "AddPatchChangeKindType" }),
3865 }).annotate({ title: "AddPatchChangeKind" }),
3866 Schema.Struct({
3867 type: Schema.Literal("delete").annotate({ title: "DeletePatchChangeKindType" }),
3868 }).annotate({ title: "DeletePatchChangeKind" }),
3869 Schema.Struct({
3870 move_path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
3871 type: Schema.Literal("update").annotate({ title: "UpdatePatchChangeKindType" }),
3872 }).annotate({ title: "UpdatePatchChangeKind" }),
3873 ],
3874 { mode: "oneOf" },
3875);
3876
3877export type V2ItemStartedNotification__ReasoningEffort =
3878 | "none"
3879 | "minimal"
3880 | "low"
3881 | "medium"
3882 | "high"
3883 | "xhigh";
3884export const V2ItemStartedNotification__ReasoningEffort = Schema.Literals([
3885 "none",
3886 "minimal",
3887 "low",
3888 "medium",
3889 "high",
3890 "xhigh",
3891]).annotate({
3892 description:
3893 "See https://platform.openai.com/docs/guides/reasoning?api-mode=responses#get-started-with-reasoning",
3894});
3895
3896export type V2ItemStartedNotification__TextElement = {
3897 readonly byteRange: { readonly end: number; readonly start: number };
3898 readonly placeholder?: string | null;
3899};
3900export const V2ItemStartedNotification__TextElement = Schema.Struct({
3901 byteRange: Schema.Struct({
3902 end: Schema.Number.annotate({ format: "uint" })
3903 .check(Schema.isInt())
3904 .check(Schema.isGreaterThanOrEqualTo(0)),
3905 start: Schema.Number.annotate({ format: "uint" })
3906 .check(Schema.isInt())
3907 .check(Schema.isGreaterThanOrEqualTo(0)),
3908 }).annotate({
3909 description: "Byte range in the parent `text` buffer that this element occupies.",
3910 }),
3911 placeholder: Schema.optionalKey(
3912 Schema.Union([
3913 Schema.String.annotate({
3914 description: "Optional human-readable placeholder for the element, displayed in the UI.",
3915 }),
3916 Schema.Null,
3917 ]),
3918 ),
3919});
3920
3921export type V2ItemStartedNotification__WebSearchAction =
3922 | {
3923 readonly queries?: ReadonlyArray<string> | null;
3924 readonly query?: string | null;
3925 readonly type: "search";
3926 }
3927 | { readonly type: "openPage"; readonly url?: string | null }
3928 | { readonly pattern?: string | null; readonly type: "findInPage"; readonly url?: string | null }
3929 | { readonly type: "other" };
3930export const V2ItemStartedNotification__WebSearchAction = Schema.Union(
3931 [
3932 Schema.Struct({
3933 queries: Schema.optionalKey(Schema.Union([Schema.Array(Schema.String), Schema.Null])),
3934 query: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
3935 type: Schema.Literal("search").annotate({ title: "SearchWebSearchActionType" }),
3936 }).annotate({ title: "SearchWebSearchAction" }),
3937 Schema.Struct({
3938 type: Schema.Literal("openPage").annotate({ title: "OpenPageWebSearchActionType" }),
3939 url: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
3940 }).annotate({ title: "OpenPageWebSearchAction" }),
3941 Schema.Struct({
3942 pattern: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
3943 type: Schema.Literal("findInPage").annotate({ title: "FindInPageWebSearchActionType" }),
3944 url: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
3945 }).annotate({ title: "FindInPageWebSearchAction" }),
3946 Schema.Struct({
3947 type: Schema.Literal("other").annotate({ title: "OtherWebSearchActionType" }),
3948 }).annotate({ title: "OtherWebSearchAction" }),
3949 ],
3950 { mode: "oneOf" },
3951);
3952
3953export type V2ListMcpServerStatusParams__McpServerStatusDetail = "full" | "toolsAndAuthOnly";
3954export const V2ListMcpServerStatusParams__McpServerStatusDetail = Schema.Literals([
3955 "full",
3956 "toolsAndAuthOnly",
3957]);
3958
3959export type V2ListMcpServerStatusResponse__McpAuthStatus =
3960 | "unsupported"
3961 | "notLoggedIn"
3962 | "bearerToken"
3963 | "oAuth";
3964export const V2ListMcpServerStatusResponse__McpAuthStatus = Schema.Literals([
3965 "unsupported",
3966 "notLoggedIn",
3967 "bearerToken",
3968 "oAuth",
3969]);
3970
3971export type V2ListMcpServerStatusResponse__Resource = {
3972 readonly _meta?: unknown;
3973 readonly annotations?: unknown;
3974 readonly description?: string | null;
3975 readonly icons?: ReadonlyArray<unknown> | null;
3976 readonly mimeType?: string | null;
3977 readonly name: string;
3978 readonly size?: number | null;
3979 readonly title?: string | null;
3980 readonly uri: string;
3981};
3982export const V2ListMcpServerStatusResponse__Resource = Schema.Struct({
3983 _meta: Schema.optionalKey(Schema.Unknown),
3984 annotations: Schema.optionalKey(Schema.Unknown),
3985 description: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
3986 icons: Schema.optionalKey(Schema.Union([Schema.Array(Schema.Unknown), Schema.Null])),
3987 mimeType: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
3988 name: Schema.String,
3989 size: Schema.optionalKey(
3990 Schema.Union([Schema.Number.annotate({ format: "int64" }).check(Schema.isInt()), Schema.Null]),
3991 ),
3992 title: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
3993 uri: Schema.String,
3994}).annotate({ description: "A known resource that the server is capable of reading." });
3995
3996export type V2ListMcpServerStatusResponse__ResourceTemplate = {
3997 readonly annotations?: unknown;
3998 readonly description?: string | null;
3999 readonly mimeType?: string | null;
4000 readonly name: string;
4001 readonly title?: string | null;
4002 readonly uriTemplate: string;
4003};
4004export const V2ListMcpServerStatusResponse__ResourceTemplate = Schema.Struct({
4005 annotations: Schema.optionalKey(Schema.Unknown),
4006 description: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
4007 mimeType: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
4008 name: Schema.String,
4009 title: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
4010 uriTemplate: Schema.String,
4011}).annotate({ description: "A template description for resources available on the server." });
4012
4013export type V2ListMcpServerStatusResponse__Tool = {
4014 readonly _meta?: unknown;
4015 readonly annotations?: unknown;
4016 readonly description?: string | null;
4017 readonly icons?: ReadonlyArray<unknown> | null;
4018 readonly inputSchema: unknown;
4019 readonly name: string;
4020 readonly outputSchema?: unknown;
4021 readonly title?: string | null;
4022};
4023export const V2ListMcpServerStatusResponse__Tool = Schema.Struct({
4024 _meta: Schema.optionalKey(Schema.Unknown),
4025 annotations: Schema.optionalKey(Schema.Unknown),
4026 description: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
4027 icons: Schema.optionalKey(Schema.Union([Schema.Array(Schema.Unknown), Schema.Null])),
4028 inputSchema: Schema.Unknown,
4029 name: Schema.String,
4030 outputSchema: Schema.optionalKey(Schema.Unknown),
4031 title: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
4032}).annotate({ description: "Definition for a tool the client can call." });
4033
4034export type V2McpResourceReadResponse__ResourceContent =
4035 | {
4036 readonly _meta?: unknown;
4037 readonly mimeType?: string | null;
4038 readonly text: string;
4039 readonly uri: string;
4040 }
4041 | {
4042 readonly _meta?: unknown;
4043 readonly blob: string;
4044 readonly mimeType?: string | null;
4045 readonly uri: string;
4046 };
4047export const V2McpResourceReadResponse__ResourceContent = Schema.Union([
4048 Schema.Struct({
4049 _meta: Schema.optionalKey(Schema.Unknown),
4050 mimeType: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
4051 text: Schema.String,
4052 uri: Schema.String.annotate({ description: "The URI of this resource." }),
4053 }),
4054 Schema.Struct({
4055 _meta: Schema.optionalKey(Schema.Unknown),
4056 blob: Schema.String,
4057 mimeType: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
4058 uri: Schema.String.annotate({ description: "The URI of this resource." }),
4059 }),
4060]).annotate({ description: "Contents returned when reading a resource from an MCP server." });
4061
4062export type V2McpServerStatusUpdatedNotification__McpServerStartupState =
4063 | "starting"
4064 | "ready"
4065 | "failed"
4066 | "cancelled";
4067export const V2McpServerStatusUpdatedNotification__McpServerStartupState = Schema.Literals([
4068 "starting",
4069 "ready",
4070 "failed",
4071 "cancelled",
4072]);
4073
4074export type V2ModelListResponse__InputModality = "text" | "image";
4075export const V2ModelListResponse__InputModality = Schema.Literals(["text", "image"]).annotate({
4076 description: "Canonical user-input modality tags advertised by a model.",
4077});
4078
4079export type V2ModelListResponse__ModelAvailabilityNux = { readonly message: string };
4080export const V2ModelListResponse__ModelAvailabilityNux = Schema.Struct({ message: Schema.String });
4081
4082export type V2ModelListResponse__ModelUpgradeInfo = {
4083 readonly migrationMarkdown?: string | null;
4084 readonly model: string;
4085 readonly modelLink?: string | null;
4086 readonly upgradeCopy?: string | null;
4087};
4088export const V2ModelListResponse__ModelUpgradeInfo = Schema.Struct({
4089 migrationMarkdown: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
4090 model: Schema.String,
4091 modelLink: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
4092 upgradeCopy: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
4093});
4094
4095export type V2ModelListResponse__ReasoningEffort =
4096 | "none"
4097 | "minimal"
4098 | "low"
4099 | "medium"
4100 | "high"
4101 | "xhigh";
4102export const V2ModelListResponse__ReasoningEffort = Schema.Literals([
4103 "none",
4104 "minimal",
4105 "low",
4106 "medium",
4107 "high",
4108 "xhigh",
4109]).annotate({
4110 description:
4111 "See https://platform.openai.com/docs/guides/reasoning?api-mode=responses#get-started-with-reasoning",
4112});
4113
4114export type V2ModelReroutedNotification__ModelRerouteReason = "highRiskCyberActivity";
4115export const V2ModelReroutedNotification__ModelRerouteReason =
4116 Schema.Literal("highRiskCyberActivity");
4117
4118export type V2PluginInstallParams__AbsolutePathBuf = string;
4119export const V2PluginInstallParams__AbsolutePathBuf = Schema.String.annotate({
4120 description:
4121 "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.",
4122});
4123
4124export type V2PluginInstallResponse__AppSummary = {
4125 readonly description?: string | null;
4126 readonly id: string;
4127 readonly installUrl?: string | null;
4128 readonly name: string;
4129 readonly needsAuth: boolean;
4130};
4131export const V2PluginInstallResponse__AppSummary = Schema.Struct({
4132 description: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
4133 id: Schema.String,
4134 installUrl: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
4135 name: Schema.String,
4136 needsAuth: Schema.Boolean,
4137}).annotate({ description: "EXPERIMENTAL - app metadata summary for plugin responses." });
4138
4139export type V2PluginInstallResponse__PluginAuthPolicy = "ON_INSTALL" | "ON_USE";
4140export const V2PluginInstallResponse__PluginAuthPolicy = Schema.Literals(["ON_INSTALL", "ON_USE"]);
4141
4142export type V2PluginListParams__AbsolutePathBuf = string;
4143export const V2PluginListParams__AbsolutePathBuf = Schema.String.annotate({
4144 description:
4145 "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.",
4146});
4147
4148export type V2PluginListResponse__AbsolutePathBuf = string;
4149export const V2PluginListResponse__AbsolutePathBuf = Schema.String.annotate({
4150 description:
4151 "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.",
4152});
4153
4154export type V2PluginListResponse__MarketplaceInterface = { readonly displayName?: string | null };
4155export const V2PluginListResponse__MarketplaceInterface = Schema.Struct({
4156 displayName: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
4157});
4158
4159export type V2PluginListResponse__PluginAuthPolicy = "ON_INSTALL" | "ON_USE";
4160export const V2PluginListResponse__PluginAuthPolicy = Schema.Literals(["ON_INSTALL", "ON_USE"]);
4161
4162export type V2PluginListResponse__PluginInstallPolicy =
4163 | "NOT_AVAILABLE"
4164 | "AVAILABLE"
4165 | "INSTALLED_BY_DEFAULT";
4166export const V2PluginListResponse__PluginInstallPolicy = Schema.Literals([
4167 "NOT_AVAILABLE",
4168 "AVAILABLE",
4169 "INSTALLED_BY_DEFAULT",
4170]);
4171
4172export type V2PluginReadParams__AbsolutePathBuf = string;
4173export const V2PluginReadParams__AbsolutePathBuf = Schema.String.annotate({
4174 description:
4175 "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.",
4176});
4177
4178export type V2PluginReadResponse__AbsolutePathBuf = string;
4179export const V2PluginReadResponse__AbsolutePathBuf = Schema.String.annotate({
4180 description:
4181 "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.",
4182});
4183
4184export type V2PluginReadResponse__AppSummary = {
4185 readonly description?: string | null;
4186 readonly id: string;
4187 readonly installUrl?: string | null;
4188 readonly name: string;
4189 readonly needsAuth: boolean;
4190};
4191export const V2PluginReadResponse__AppSummary = Schema.Struct({
4192 description: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
4193 id: Schema.String,
4194 installUrl: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
4195 name: Schema.String,
4196 needsAuth: Schema.Boolean,
4197}).annotate({ description: "EXPERIMENTAL - app metadata summary for plugin responses." });
4198
4199export type V2PluginReadResponse__PluginAuthPolicy = "ON_INSTALL" | "ON_USE";
4200export const V2PluginReadResponse__PluginAuthPolicy = Schema.Literals(["ON_INSTALL", "ON_USE"]);
4201
4202export type V2PluginReadResponse__PluginInstallPolicy =
4203 | "NOT_AVAILABLE"
4204 | "AVAILABLE"
4205 | "INSTALLED_BY_DEFAULT";
4206export const V2PluginReadResponse__PluginInstallPolicy = Schema.Literals([
4207 "NOT_AVAILABLE",
4208 "AVAILABLE",
4209 "INSTALLED_BY_DEFAULT",
4210]);
4211
4212export type V2PluginReadResponse__SkillInterface = {
4213 readonly brandColor?: string | null;
4214 readonly defaultPrompt?: string | null;
4215 readonly displayName?: string | null;
4216 readonly iconLarge?: string | null;
4217 readonly iconSmall?: string | null;
4218 readonly shortDescription?: string | null;
4219};
4220export const V2PluginReadResponse__SkillInterface = Schema.Struct({
4221 brandColor: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
4222 defaultPrompt: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
4223 displayName: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
4224 iconLarge: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
4225 iconSmall: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
4226 shortDescription: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
4227});
4228
4229export type V2RawResponseItemCompletedNotification__ContentItem =
4230 | { readonly text: string; readonly type: "input_text" }
4231 | { readonly image_url: string; readonly type: "input_image" }
4232 | { readonly text: string; readonly type: "output_text" };
4233export const V2RawResponseItemCompletedNotification__ContentItem = Schema.Union(
4234 [
4235 Schema.Struct({
4236 text: Schema.String,
4237 type: Schema.Literal("input_text").annotate({ title: "InputTextContentItemType" }),
4238 }).annotate({ title: "InputTextContentItem" }),
4239 Schema.Struct({
4240 image_url: Schema.String,
4241 type: Schema.Literal("input_image").annotate({ title: "InputImageContentItemType" }),
4242 }).annotate({ title: "InputImageContentItem" }),
4243 Schema.Struct({
4244 text: Schema.String,
4245 type: Schema.Literal("output_text").annotate({ title: "OutputTextContentItemType" }),
4246 }).annotate({ title: "OutputTextContentItem" }),
4247 ],
4248 { mode: "oneOf" },
4249);
4250
4251export type V2RawResponseItemCompletedNotification__GhostCommit = {
4252 readonly id: string;
4253 readonly parent?: string | null;
4254 readonly preexisting_untracked_dirs: ReadonlyArray<string>;
4255 readonly preexisting_untracked_files: ReadonlyArray<string>;
4256};
4257export const V2RawResponseItemCompletedNotification__GhostCommit = Schema.Struct({
4258 id: Schema.String,
4259 parent: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
4260 preexisting_untracked_dirs: Schema.Array(Schema.String),
4261 preexisting_untracked_files: Schema.Array(Schema.String),
4262}).annotate({ description: "Details of a ghost commit created from a repository state." });
4263
4264export type V2RawResponseItemCompletedNotification__ImageDetail =
4265 | "auto"
4266 | "low"
4267 | "high"
4268 | "original";
4269export const V2RawResponseItemCompletedNotification__ImageDetail = Schema.Literals([
4270 "auto",
4271 "low",
4272 "high",
4273 "original",
4274]);
4275
4276export type V2RawResponseItemCompletedNotification__LocalShellAction = {
4277 readonly command: ReadonlyArray<string>;
4278 readonly env?: { readonly [x: string]: string } | null;
4279 readonly timeout_ms?: number | null;
4280 readonly type: "exec";
4281 readonly user?: string | null;
4282 readonly working_directory?: string | null;
4283};
4284export const V2RawResponseItemCompletedNotification__LocalShellAction = Schema.Union(
4285 [
4286 Schema.Struct({
4287 command: Schema.Array(Schema.String),
4288 env: Schema.optionalKey(
4289 Schema.Union([Schema.Record(Schema.String, Schema.String), Schema.Null]),
4290 ),
4291 timeout_ms: Schema.optionalKey(
4292 Schema.Union([
4293 Schema.Number.annotate({ format: "uint64" })
4294 .check(Schema.isInt())
4295 .check(Schema.isGreaterThanOrEqualTo(0)),
4296 Schema.Null,
4297 ]),
4298 ),
4299 type: Schema.Literal("exec").annotate({ title: "ExecLocalShellActionType" }),
4300 user: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
4301 working_directory: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
4302 }).annotate({ title: "ExecLocalShellAction" }),
4303 ],
4304 { mode: "oneOf" },
4305);
4306
4307export type V2RawResponseItemCompletedNotification__LocalShellStatus =
4308 | "completed"
4309 | "in_progress"
4310 | "incomplete";
4311export const V2RawResponseItemCompletedNotification__LocalShellStatus = Schema.Literals([
4312 "completed",
4313 "in_progress",
4314 "incomplete",
4315]);
4316
4317export type V2RawResponseItemCompletedNotification__MessagePhase = "commentary" | "final_answer";
4318export const V2RawResponseItemCompletedNotification__MessagePhase = Schema.Literals([
4319 "commentary",
4320 "final_answer",
4321]).annotate({
4322 description:
4323 '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.',
4324});
4325
4326export type V2RawResponseItemCompletedNotification__ReasoningItemContent =
4327 | { readonly text: string; readonly type: "reasoning_text" }
4328 | { readonly text: string; readonly type: "text" };
4329export const V2RawResponseItemCompletedNotification__ReasoningItemContent = Schema.Union(
4330 [
4331 Schema.Struct({
4332 text: Schema.String,
4333 type: Schema.Literal("reasoning_text").annotate({
4334 title: "ReasoningTextReasoningItemContentType",
4335 }),
4336 }).annotate({ title: "ReasoningTextReasoningItemContent" }),
4337 Schema.Struct({
4338 text: Schema.String,
4339 type: Schema.Literal("text").annotate({ title: "TextReasoningItemContentType" }),
4340 }).annotate({ title: "TextReasoningItemContent" }),
4341 ],
4342 { mode: "oneOf" },
4343);
4344
4345export type V2RawResponseItemCompletedNotification__ReasoningItemReasoningSummary = {
4346 readonly text: string;
4347 readonly type: "summary_text";
4348};
4349export const V2RawResponseItemCompletedNotification__ReasoningItemReasoningSummary = Schema.Union(
4350 [
4351 Schema.Struct({
4352 text: Schema.String,
4353 type: Schema.Literal("summary_text").annotate({
4354 title: "SummaryTextReasoningItemReasoningSummaryType",
4355 }),
4356 }).annotate({ title: "SummaryTextReasoningItemReasoningSummary" }),
4357 ],
4358 { mode: "oneOf" },
4359);
4360
4361export type V2RawResponseItemCompletedNotification__ResponsesApiWebSearchAction =
4362 | {
4363 readonly queries?: ReadonlyArray<string> | null;
4364 readonly query?: string | null;
4365 readonly type: "search";
4366 }
4367 | { readonly type: "open_page"; readonly url?: string | null }
4368 | {
4369 readonly pattern?: string | null;
4370 readonly type: "find_in_page";
4371 readonly url?: string | null;
4372 }
4373 | { readonly type: "other" };
4374export const V2RawResponseItemCompletedNotification__ResponsesApiWebSearchAction = Schema.Union(
4375 [
4376 Schema.Struct({
4377 queries: Schema.optionalKey(Schema.Union([Schema.Array(Schema.String), Schema.Null])),
4378 query: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
4379 type: Schema.Literal("search").annotate({ title: "SearchResponsesApiWebSearchActionType" }),
4380 }).annotate({ title: "SearchResponsesApiWebSearchAction" }),
4381 Schema.Struct({
4382 type: Schema.Literal("open_page").annotate({
4383 title: "OpenPageResponsesApiWebSearchActionType",
4384 }),
4385 url: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
4386 }).annotate({ title: "OpenPageResponsesApiWebSearchAction" }),
4387 Schema.Struct({
4388 pattern: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
4389 type: Schema.Literal("find_in_page").annotate({
4390 title: "FindInPageResponsesApiWebSearchActionType",
4391 }),
4392 url: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
4393 }).annotate({ title: "FindInPageResponsesApiWebSearchAction" }),
4394 Schema.Struct({
4395 type: Schema.Literal("other").annotate({ title: "OtherResponsesApiWebSearchActionType" }),
4396 }).annotate({ title: "OtherResponsesApiWebSearchAction" }),
4397 ],
4398 { mode: "oneOf" },
4399);
4400
4401export type V2ReviewStartParams__ReviewDelivery = "inline" | "detached";
4402export const V2ReviewStartParams__ReviewDelivery = Schema.Literals(["inline", "detached"]);
4403
4404export type V2ReviewStartParams__ReviewTarget =
4405 | { readonly type: "uncommittedChanges" }
4406 | { readonly branch: string; readonly type: "baseBranch" }
4407 | { readonly sha: string; readonly title?: string | null; readonly type: "commit" }
4408 | { readonly instructions: string; readonly type: "custom" };
4409export const V2ReviewStartParams__ReviewTarget = Schema.Union(
4410 [
4411 Schema.Struct({
4412 type: Schema.Literal("uncommittedChanges").annotate({
4413 title: "UncommittedChangesReviewTargetType",
4414 }),
4415 }).annotate({
4416 title: "UncommittedChangesReviewTarget",
4417 description: "Review the working tree: staged, unstaged, and untracked files.",
4418 }),
4419 Schema.Struct({
4420 branch: Schema.String,
4421 type: Schema.Literal("baseBranch").annotate({ title: "BaseBranchReviewTargetType" }),
4422 }).annotate({
4423 title: "BaseBranchReviewTarget",
4424 description: "Review changes between the current branch and the given base branch.",
4425 }),
4426 Schema.Struct({
4427 sha: Schema.String,
4428 title: Schema.optionalKey(
4429 Schema.Union([
4430 Schema.String.annotate({
4431 description: "Optional human-readable label (e.g., commit subject) for UIs.",
4432 }),
4433 Schema.Null,
4434 ]),
4435 ),
4436 type: Schema.Literal("commit").annotate({ title: "CommitReviewTargetType" }),
4437 }).annotate({
4438 title: "CommitReviewTarget",
4439 description: "Review the changes introduced by a specific commit.",
4440 }),
4441 Schema.Struct({
4442 instructions: Schema.String,
4443 type: Schema.Literal("custom").annotate({ title: "CustomReviewTargetType" }),
4444 }).annotate({
4445 title: "CustomReviewTarget",
4446 description: "Arbitrary instructions, equivalent to the old free-form prompt.",
4447 }),
4448 ],
4449 { mode: "oneOf" },
4450);
4451
4452export type V2ReviewStartResponse__CollabAgentStatus =
4453 | "pendingInit"
4454 | "running"
4455 | "interrupted"
4456 | "completed"
4457 | "errored"
4458 | "shutdown"
4459 | "notFound";
4460export const V2ReviewStartResponse__CollabAgentStatus = Schema.Literals([
4461 "pendingInit",
4462 "running",
4463 "interrupted",
4464 "completed",
4465 "errored",
4466 "shutdown",
4467 "notFound",
4468]);
4469
4470export type V2ReviewStartResponse__CommandAction =
4471 | {
4472 readonly command: string;
4473 readonly name: string;
4474 readonly path: string;
4475 readonly type: "read";
4476 }
4477 | { readonly command: string; readonly path?: string | null; readonly type: "listFiles" }
4478 | {
4479 readonly command: string;
4480 readonly path?: string | null;
4481 readonly query?: string | null;
4482 readonly type: "search";
4483 }
4484 | { readonly command: string; readonly type: "unknown" };
4485export const V2ReviewStartResponse__CommandAction = Schema.Union(
4486 [
4487 Schema.Struct({
4488 command: Schema.String,
4489 name: Schema.String,
4490 path: Schema.String,
4491 type: Schema.Literal("read").annotate({ title: "ReadCommandActionType" }),
4492 }).annotate({ title: "ReadCommandAction" }),
4493 Schema.Struct({
4494 command: Schema.String,
4495 path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
4496 type: Schema.Literal("listFiles").annotate({ title: "ListFilesCommandActionType" }),
4497 }).annotate({ title: "ListFilesCommandAction" }),
4498 Schema.Struct({
4499 command: Schema.String,
4500 path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
4501 query: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
4502 type: Schema.Literal("search").annotate({ title: "SearchCommandActionType" }),
4503 }).annotate({ title: "SearchCommandAction" }),
4504 Schema.Struct({
4505 command: Schema.String,
4506 type: Schema.Literal("unknown").annotate({ title: "UnknownCommandActionType" }),
4507 }).annotate({ title: "UnknownCommandAction" }),
4508 ],
4509 { mode: "oneOf" },
4510);
4511
4512export type V2ReviewStartResponse__CommandExecutionStatus =
4513 | "inProgress"
4514 | "completed"
4515 | "failed"
4516 | "declined";
4517export const V2ReviewStartResponse__CommandExecutionStatus = Schema.Literals([
4518 "inProgress",
4519 "completed",
4520 "failed",
4521 "declined",
4522]);
4523
4524export type V2ReviewStartResponse__DynamicToolCallOutputContentItem =
4525 | { readonly text: string; readonly type: "inputText" }
4526 | { readonly imageUrl: string; readonly type: "inputImage" };
4527export const V2ReviewStartResponse__DynamicToolCallOutputContentItem = Schema.Union(
4528 [
4529 Schema.Struct({
4530 text: Schema.String,
4531 type: Schema.Literal("inputText").annotate({
4532 title: "InputTextDynamicToolCallOutputContentItemType",
4533 }),
4534 }).annotate({ title: "InputTextDynamicToolCallOutputContentItem" }),
4535 Schema.Struct({
4536 imageUrl: Schema.String,
4537 type: Schema.Literal("inputImage").annotate({
4538 title: "InputImageDynamicToolCallOutputContentItemType",
4539 }),
4540 }).annotate({ title: "InputImageDynamicToolCallOutputContentItem" }),
4541 ],
4542 { mode: "oneOf" },
4543);
4544
4545export type V2ReviewStartResponse__DynamicToolCallStatus = "inProgress" | "completed" | "failed";
4546export const V2ReviewStartResponse__DynamicToolCallStatus = Schema.Literals([
4547 "inProgress",
4548 "completed",
4549 "failed",
4550]);
4551
4552export type V2ReviewStartResponse__HookPromptFragment = {
4553 readonly hookRunId: string;
4554 readonly text: string;
4555};
4556export const V2ReviewStartResponse__HookPromptFragment = Schema.Struct({
4557 hookRunId: Schema.String,
4558 text: Schema.String,
4559});
4560
4561export type V2ReviewStartResponse__McpToolCallError = { readonly message: string };
4562export const V2ReviewStartResponse__McpToolCallError = Schema.Struct({ message: Schema.String });
4563
4564export type V2ReviewStartResponse__McpToolCallResult = {
4565 readonly _meta?: unknown;
4566 readonly content: ReadonlyArray<unknown>;
4567 readonly structuredContent?: unknown;
4568};
4569export const V2ReviewStartResponse__McpToolCallResult = Schema.Struct({
4570 _meta: Schema.optionalKey(Schema.Unknown),
4571 content: Schema.Array(Schema.Unknown),
4572 structuredContent: Schema.optionalKey(Schema.Unknown),
4573});
4574
4575export type V2ReviewStartResponse__McpToolCallStatus = "inProgress" | "completed" | "failed";
4576export const V2ReviewStartResponse__McpToolCallStatus = Schema.Literals([
4577 "inProgress",
4578 "completed",
4579 "failed",
4580]);
4581
4582export type V2ReviewStartResponse__MemoryCitationEntry = {
4583 readonly lineEnd: number;
4584 readonly lineStart: number;
4585 readonly note: string;
4586 readonly path: string;
4587};
4588export const V2ReviewStartResponse__MemoryCitationEntry = Schema.Struct({
4589 lineEnd: Schema.Number.annotate({ format: "uint32" })
4590 .check(Schema.isInt())
4591 .check(Schema.isGreaterThanOrEqualTo(0)),
4592 lineStart: Schema.Number.annotate({ format: "uint32" })
4593 .check(Schema.isInt())
4594 .check(Schema.isGreaterThanOrEqualTo(0)),
4595 note: Schema.String,
4596 path: Schema.String,
4597});
4598
4599export type V2ReviewStartResponse__MessagePhase = "commentary" | "final_answer";
4600export const V2ReviewStartResponse__MessagePhase = Schema.Literals([
4601 "commentary",
4602 "final_answer",
4603]).annotate({
4604 description:
4605 '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.',
4606});
4607
4608export type V2ReviewStartResponse__NonSteerableTurnKind = "review" | "compact";
4609export const V2ReviewStartResponse__NonSteerableTurnKind = Schema.Literals(["review", "compact"]);
4610
4611export type V2ReviewStartResponse__PatchApplyStatus =
4612 | "inProgress"
4613 | "completed"
4614 | "failed"
4615 | "declined";
4616export const V2ReviewStartResponse__PatchApplyStatus = Schema.Literals([
4617 "inProgress",
4618 "completed",
4619 "failed",
4620 "declined",
4621]);
4622
4623export type V2ReviewStartResponse__PatchChangeKind =
4624 | { readonly type: "add" }
4625 | { readonly type: "delete" }
4626 | { readonly move_path?: string | null; readonly type: "update" };
4627export const V2ReviewStartResponse__PatchChangeKind = Schema.Union(
4628 [
4629 Schema.Struct({
4630 type: Schema.Literal("add").annotate({ title: "AddPatchChangeKindType" }),
4631 }).annotate({ title: "AddPatchChangeKind" }),
4632 Schema.Struct({
4633 type: Schema.Literal("delete").annotate({ title: "DeletePatchChangeKindType" }),
4634 }).annotate({ title: "DeletePatchChangeKind" }),
4635 Schema.Struct({
4636 move_path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
4637 type: Schema.Literal("update").annotate({ title: "UpdatePatchChangeKindType" }),
4638 }).annotate({ title: "UpdatePatchChangeKind" }),
4639 ],
4640 { mode: "oneOf" },
4641);
4642
4643export type V2ReviewStartResponse__ReasoningEffort =
4644 | "none"
4645 | "minimal"
4646 | "low"
4647 | "medium"
4648 | "high"
4649 | "xhigh";
4650export const V2ReviewStartResponse__ReasoningEffort = Schema.Literals([
4651 "none",
4652 "minimal",
4653 "low",
4654 "medium",
4655 "high",
4656 "xhigh",
4657]).annotate({
4658 description:
4659 "See https://platform.openai.com/docs/guides/reasoning?api-mode=responses#get-started-with-reasoning",
4660});
4661
4662export type V2ReviewStartResponse__TextElement = {
4663 readonly byteRange: { readonly end: number; readonly start: number };
4664 readonly placeholder?: string | null;
4665};
4666export const V2ReviewStartResponse__TextElement = Schema.Struct({
4667 byteRange: Schema.Struct({
4668 end: Schema.Number.annotate({ format: "uint" })
4669 .check(Schema.isInt())
4670 .check(Schema.isGreaterThanOrEqualTo(0)),
4671 start: Schema.Number.annotate({ format: "uint" })
4672 .check(Schema.isInt())
4673 .check(Schema.isGreaterThanOrEqualTo(0)),
4674 }).annotate({
4675 description: "Byte range in the parent `text` buffer that this element occupies.",
4676 }),
4677 placeholder: Schema.optionalKey(
4678 Schema.Union([
4679 Schema.String.annotate({
4680 description: "Optional human-readable placeholder for the element, displayed in the UI.",
4681 }),
4682 Schema.Null,
4683 ]),
4684 ),
4685});
4686
4687export type V2ReviewStartResponse__TurnStatus =
4688 | "completed"
4689 | "interrupted"
4690 | "failed"
4691 | "inProgress";
4692export const V2ReviewStartResponse__TurnStatus = Schema.Literals([
4693 "completed",
4694 "interrupted",
4695 "failed",
4696 "inProgress",
4697]);
4698
4699export type V2ReviewStartResponse__WebSearchAction =
4700 | {
4701 readonly queries?: ReadonlyArray<string> | null;
4702 readonly query?: string | null;
4703 readonly type: "search";
4704 }
4705 | { readonly type: "openPage"; readonly url?: string | null }
4706 | { readonly pattern?: string | null; readonly type: "findInPage"; readonly url?: string | null }
4707 | { readonly type: "other" };
4708export const V2ReviewStartResponse__WebSearchAction = Schema.Union(
4709 [
4710 Schema.Struct({
4711 queries: Schema.optionalKey(Schema.Union([Schema.Array(Schema.String), Schema.Null])),
4712 query: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
4713 type: Schema.Literal("search").annotate({ title: "SearchWebSearchActionType" }),
4714 }).annotate({ title: "SearchWebSearchAction" }),
4715 Schema.Struct({
4716 type: Schema.Literal("openPage").annotate({ title: "OpenPageWebSearchActionType" }),
4717 url: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
4718 }).annotate({ title: "OpenPageWebSearchAction" }),
4719 Schema.Struct({
4720 pattern: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
4721 type: Schema.Literal("findInPage").annotate({ title: "FindInPageWebSearchActionType" }),
4722 url: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
4723 }).annotate({ title: "FindInPageWebSearchAction" }),
4724 Schema.Struct({
4725 type: Schema.Literal("other").annotate({ title: "OtherWebSearchActionType" }),
4726 }).annotate({ title: "OtherWebSearchAction" }),
4727 ],
4728 { mode: "oneOf" },
4729);
4730
4731export type V2ServerRequestResolvedNotification__RequestId = string | number;
4732export const V2ServerRequestResolvedNotification__RequestId = Schema.Union([
4733 Schema.String,
4734 Schema.Number.annotate({ format: "int64" }).check(Schema.isInt()),
4735]);
4736
4737export type V2SkillsConfigWriteParams__AbsolutePathBuf = string;
4738export const V2SkillsConfigWriteParams__AbsolutePathBuf = Schema.String.annotate({
4739 description:
4740 "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.",
4741});
4742
4743export type V2SkillsListParams__SkillsListExtraRootsForCwd = {
4744 readonly cwd: string;
4745 readonly extraUserRoots: ReadonlyArray<string>;
4746};
4747export const V2SkillsListParams__SkillsListExtraRootsForCwd = Schema.Struct({
4748 cwd: Schema.String,
4749 extraUserRoots: Schema.Array(Schema.String),
4750});
4751
4752export type V2SkillsListResponse__SkillErrorInfo = {
4753 readonly message: string;
4754 readonly path: string;
4755};
4756export const V2SkillsListResponse__SkillErrorInfo = Schema.Struct({
4757 message: Schema.String,
4758 path: Schema.String,
4759});
4760
4761export type V2SkillsListResponse__SkillInterface = {
4762 readonly brandColor?: string | null;
4763 readonly defaultPrompt?: string | null;
4764 readonly displayName?: string | null;
4765 readonly iconLarge?: string | null;
4766 readonly iconSmall?: string | null;
4767 readonly shortDescription?: string | null;
4768};
4769export const V2SkillsListResponse__SkillInterface = Schema.Struct({
4770 brandColor: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
4771 defaultPrompt: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
4772 displayName: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
4773 iconLarge: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
4774 iconSmall: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
4775 shortDescription: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
4776});
4777
4778export type V2SkillsListResponse__SkillScope = "user" | "repo" | "system" | "admin";
4779export const V2SkillsListResponse__SkillScope = Schema.Literals([
4780 "user",
4781 "repo",
4782 "system",
4783 "admin",
4784]);
4785
4786export type V2SkillsListResponse__SkillToolDependency = {
4787 readonly command?: string | null;
4788 readonly description?: string | null;
4789 readonly transport?: string | null;
4790 readonly type: string;
4791 readonly url?: string | null;
4792 readonly value: string;
4793};
4794export const V2SkillsListResponse__SkillToolDependency = Schema.Struct({
4795 command: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
4796 description: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
4797 transport: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
4798 type: Schema.String,
4799 url: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
4800 value: Schema.String,
4801});
4802
4803export type V2ThreadForkParams__ApprovalsReviewer = "user" | "guardian_subagent";
4804export const V2ThreadForkParams__ApprovalsReviewer = Schema.Literals([
4805 "user",
4806 "guardian_subagent",
4807]).annotate({
4808 description:
4809 "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.",
4810});
4811
4812export type V2ThreadForkParams__AskForApproval =
4813 | "untrusted"
4814 | "on-failure"
4815 | "on-request"
4816 | "never"
4817 | {
4818 readonly granular: {
4819 readonly mcp_elicitations: boolean;
4820 readonly request_permissions?: boolean;
4821 readonly rules: boolean;
4822 readonly sandbox_approval: boolean;
4823 readonly skill_approval?: boolean;
4824 };
4825 };
4826export const V2ThreadForkParams__AskForApproval = Schema.Union(
4827 [
4828 Schema.Literals(["untrusted", "on-failure", "on-request", "never"]),
4829 Schema.Struct({
4830 granular: Schema.Struct({
4831 mcp_elicitations: Schema.Boolean,
4832 request_permissions: Schema.optionalKey(Schema.Boolean.annotate({ default: false })),
4833 rules: Schema.Boolean,
4834 sandbox_approval: Schema.Boolean,
4835 skill_approval: Schema.optionalKey(Schema.Boolean.annotate({ default: false })),
4836 }),
4837 }).annotate({ title: "GranularAskForApproval" }),
4838 ],
4839 { mode: "oneOf" },
4840);
4841
4842export type V2ThreadForkParams__SandboxMode =
4843 | "read-only"
4844 | "workspace-write"
4845 | "danger-full-access";
4846export const V2ThreadForkParams__SandboxMode = Schema.Literals([
4847 "read-only",
4848 "workspace-write",
4849 "danger-full-access",
4850]);
4851
4852export type V2ThreadForkParams__ServiceTier = "fast" | "flex";
4853export const V2ThreadForkParams__ServiceTier = Schema.Literals(["fast", "flex"]);
4854
4855export type V2ThreadForkResponse__AbsolutePathBuf = string;
4856export const V2ThreadForkResponse__AbsolutePathBuf = Schema.String.annotate({
4857 description:
4858 "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.",
4859});
4860
4861export type V2ThreadForkResponse__AgentPath = string;
4862export const V2ThreadForkResponse__AgentPath = Schema.String;
4863
4864export type V2ThreadForkResponse__AskForApproval =
4865 | "untrusted"
4866 | "on-failure"
4867 | "on-request"
4868 | "never"
4869 | {
4870 readonly granular: {
4871 readonly mcp_elicitations: boolean;
4872 readonly request_permissions?: boolean;
4873 readonly rules: boolean;
4874 readonly sandbox_approval: boolean;
4875 readonly skill_approval?: boolean;
4876 };
4877 };
4878export const V2ThreadForkResponse__AskForApproval = Schema.Union(
4879 [
4880 Schema.Literals(["untrusted", "on-failure", "on-request", "never"]),
4881 Schema.Struct({
4882 granular: Schema.Struct({
4883 mcp_elicitations: Schema.Boolean,
4884 request_permissions: Schema.optionalKey(Schema.Boolean.annotate({ default: false })),
4885 rules: Schema.Boolean,
4886 sandbox_approval: Schema.Boolean,
4887 skill_approval: Schema.optionalKey(Schema.Boolean.annotate({ default: false })),
4888 }),
4889 }).annotate({ title: "GranularAskForApproval" }),
4890 ],
4891 { mode: "oneOf" },
4892);
4893
4894export type V2ThreadForkResponse__CollabAgentStatus =
4895 | "pendingInit"
4896 | "running"
4897 | "interrupted"
4898 | "completed"
4899 | "errored"
4900 | "shutdown"
4901 | "notFound";
4902export const V2ThreadForkResponse__CollabAgentStatus = Schema.Literals([
4903 "pendingInit",
4904 "running",
4905 "interrupted",
4906 "completed",
4907 "errored",
4908 "shutdown",
4909 "notFound",
4910]);
4911
4912export type V2ThreadForkResponse__CommandAction =
4913 | {
4914 readonly command: string;
4915 readonly name: string;
4916 readonly path: string;
4917 readonly type: "read";
4918 }
4919 | { readonly command: string; readonly path?: string | null; readonly type: "listFiles" }
4920 | {
4921 readonly command: string;
4922 readonly path?: string | null;
4923 readonly query?: string | null;
4924 readonly type: "search";
4925 }
4926 | { readonly command: string; readonly type: "unknown" };
4927export const V2ThreadForkResponse__CommandAction = Schema.Union(
4928 [
4929 Schema.Struct({
4930 command: Schema.String,
4931 name: Schema.String,
4932 path: Schema.String,
4933 type: Schema.Literal("read").annotate({ title: "ReadCommandActionType" }),
4934 }).annotate({ title: "ReadCommandAction" }),
4935 Schema.Struct({
4936 command: Schema.String,
4937 path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
4938 type: Schema.Literal("listFiles").annotate({ title: "ListFilesCommandActionType" }),
4939 }).annotate({ title: "ListFilesCommandAction" }),
4940 Schema.Struct({
4941 command: Schema.String,
4942 path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
4943 query: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
4944 type: Schema.Literal("search").annotate({ title: "SearchCommandActionType" }),
4945 }).annotate({ title: "SearchCommandAction" }),
4946 Schema.Struct({
4947 command: Schema.String,
4948 type: Schema.Literal("unknown").annotate({ title: "UnknownCommandActionType" }),
4949 }).annotate({ title: "UnknownCommandAction" }),
4950 ],
4951 { mode: "oneOf" },
4952);
4953
4954export type V2ThreadForkResponse__CommandExecutionStatus =
4955 | "inProgress"
4956 | "completed"
4957 | "failed"
4958 | "declined";
4959export const V2ThreadForkResponse__CommandExecutionStatus = Schema.Literals([
4960 "inProgress",
4961 "completed",
4962 "failed",
4963 "declined",
4964]);
4965
4966export type V2ThreadForkResponse__DynamicToolCallOutputContentItem =
4967 | { readonly text: string; readonly type: "inputText" }
4968 | { readonly imageUrl: string; readonly type: "inputImage" };
4969export const V2ThreadForkResponse__DynamicToolCallOutputContentItem = Schema.Union(
4970 [
4971 Schema.Struct({
4972 text: Schema.String,
4973 type: Schema.Literal("inputText").annotate({
4974 title: "InputTextDynamicToolCallOutputContentItemType",
4975 }),
4976 }).annotate({ title: "InputTextDynamicToolCallOutputContentItem" }),
4977 Schema.Struct({
4978 imageUrl: Schema.String,
4979 type: Schema.Literal("inputImage").annotate({
4980 title: "InputImageDynamicToolCallOutputContentItemType",
4981 }),
4982 }).annotate({ title: "InputImageDynamicToolCallOutputContentItem" }),
4983 ],
4984 { mode: "oneOf" },
4985);
4986
4987export type V2ThreadForkResponse__DynamicToolCallStatus = "inProgress" | "completed" | "failed";
4988export const V2ThreadForkResponse__DynamicToolCallStatus = Schema.Literals([
4989 "inProgress",
4990 "completed",
4991 "failed",
4992]);
4993
4994export type V2ThreadForkResponse__GitInfo = {
4995 readonly branch?: string | null;
4996 readonly originUrl?: string | null;
4997 readonly sha?: string | null;
4998};
4999export const V2ThreadForkResponse__GitInfo = Schema.Struct({
5000 branch: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
5001 originUrl: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
5002 sha: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
5003});
5004
5005export type V2ThreadForkResponse__HookPromptFragment = {
5006 readonly hookRunId: string;
5007 readonly text: string;
5008};
5009export const V2ThreadForkResponse__HookPromptFragment = Schema.Struct({
5010 hookRunId: Schema.String,
5011 text: Schema.String,
5012});
5013
5014export type V2ThreadForkResponse__McpToolCallError = { readonly message: string };
5015export const V2ThreadForkResponse__McpToolCallError = Schema.Struct({ message: Schema.String });
5016
5017export type V2ThreadForkResponse__McpToolCallResult = {
5018 readonly _meta?: unknown;
5019 readonly content: ReadonlyArray<unknown>;
5020 readonly structuredContent?: unknown;
5021};
5022export const V2ThreadForkResponse__McpToolCallResult = Schema.Struct({
5023 _meta: Schema.optionalKey(Schema.Unknown),
5024 content: Schema.Array(Schema.Unknown),
5025 structuredContent: Schema.optionalKey(Schema.Unknown),
5026});
5027
5028export type V2ThreadForkResponse__McpToolCallStatus = "inProgress" | "completed" | "failed";
5029export const V2ThreadForkResponse__McpToolCallStatus = Schema.Literals([
5030 "inProgress",
5031 "completed",
5032 "failed",
5033]);
5034
5035export type V2ThreadForkResponse__MemoryCitationEntry = {
5036 readonly lineEnd: number;
5037 readonly lineStart: number;
5038 readonly note: string;
5039 readonly path: string;
5040};
5041export const V2ThreadForkResponse__MemoryCitationEntry = Schema.Struct({
5042 lineEnd: Schema.Number.annotate({ format: "uint32" })
5043 .check(Schema.isInt())
5044 .check(Schema.isGreaterThanOrEqualTo(0)),
5045 lineStart: Schema.Number.annotate({ format: "uint32" })
5046 .check(Schema.isInt())
5047 .check(Schema.isGreaterThanOrEqualTo(0)),
5048 note: Schema.String,
5049 path: Schema.String,
5050});
5051
5052export type V2ThreadForkResponse__MessagePhase = "commentary" | "final_answer";
5053export const V2ThreadForkResponse__MessagePhase = Schema.Literals([
5054 "commentary",
5055 "final_answer",
5056]).annotate({
5057 description:
5058 '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.',
5059});
5060
5061export type V2ThreadForkResponse__NonSteerableTurnKind = "review" | "compact";
5062export const V2ThreadForkResponse__NonSteerableTurnKind = Schema.Literals(["review", "compact"]);
5063
5064export type V2ThreadForkResponse__PatchApplyStatus =
5065 | "inProgress"
5066 | "completed"
5067 | "failed"
5068 | "declined";
5069export const V2ThreadForkResponse__PatchApplyStatus = Schema.Literals([
5070 "inProgress",
5071 "completed",
5072 "failed",
5073 "declined",
5074]);
5075
5076export type V2ThreadForkResponse__PatchChangeKind =
5077 | { readonly type: "add" }
5078 | { readonly type: "delete" }
5079 | { readonly move_path?: string | null; readonly type: "update" };
5080export const V2ThreadForkResponse__PatchChangeKind = Schema.Union(
5081 [
5082 Schema.Struct({
5083 type: Schema.Literal("add").annotate({ title: "AddPatchChangeKindType" }),
5084 }).annotate({ title: "AddPatchChangeKind" }),
5085 Schema.Struct({
5086 type: Schema.Literal("delete").annotate({ title: "DeletePatchChangeKindType" }),
5087 }).annotate({ title: "DeletePatchChangeKind" }),
5088 Schema.Struct({
5089 move_path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
5090 type: Schema.Literal("update").annotate({ title: "UpdatePatchChangeKindType" }),
5091 }).annotate({ title: "UpdatePatchChangeKind" }),
5092 ],
5093 { mode: "oneOf" },
5094);
5095
5096export type V2ThreadForkResponse__ReasoningEffort =
5097 | "none"
5098 | "minimal"
5099 | "low"
5100 | "medium"
5101 | "high"
5102 | "xhigh";
5103export const V2ThreadForkResponse__ReasoningEffort = Schema.Literals([
5104 "none",
5105 "minimal",
5106 "low",
5107 "medium",
5108 "high",
5109 "xhigh",
5110]).annotate({
5111 description:
5112 "See https://platform.openai.com/docs/guides/reasoning?api-mode=responses#get-started-with-reasoning",
5113});
5114
5115export type V2ThreadForkResponse__ServiceTier = "fast" | "flex";
5116export const V2ThreadForkResponse__ServiceTier = Schema.Literals(["fast", "flex"]);
5117
5118export type V2ThreadForkResponse__TextElement = {
5119 readonly byteRange: { readonly end: number; readonly start: number };
5120 readonly placeholder?: string | null;
5121};
5122export const V2ThreadForkResponse__TextElement = Schema.Struct({
5123 byteRange: Schema.Struct({
5124 end: Schema.Number.annotate({ format: "uint" })
5125 .check(Schema.isInt())
5126 .check(Schema.isGreaterThanOrEqualTo(0)),
5127 start: Schema.Number.annotate({ format: "uint" })
5128 .check(Schema.isInt())
5129 .check(Schema.isGreaterThanOrEqualTo(0)),
5130 }).annotate({
5131 description: "Byte range in the parent `text` buffer that this element occupies.",
5132 }),
5133 placeholder: Schema.optionalKey(
5134 Schema.Union([
5135 Schema.String.annotate({
5136 description: "Optional human-readable placeholder for the element, displayed in the UI.",
5137 }),
5138 Schema.Null,
5139 ]),
5140 ),
5141});
5142
5143export type V2ThreadForkResponse__ThreadActiveFlag = "waitingOnApproval" | "waitingOnUserInput";
5144export const V2ThreadForkResponse__ThreadActiveFlag = Schema.Literals([
5145 "waitingOnApproval",
5146 "waitingOnUserInput",
5147]);
5148
5149export type V2ThreadForkResponse__ThreadId = string;
5150export const V2ThreadForkResponse__ThreadId = Schema.String;
5151
5152export type V2ThreadForkResponse__TurnStatus =
5153 | "completed"
5154 | "interrupted"
5155 | "failed"
5156 | "inProgress";
5157export const V2ThreadForkResponse__TurnStatus = Schema.Literals([
5158 "completed",
5159 "interrupted",
5160 "failed",
5161 "inProgress",
5162]);
5163
5164export type V2ThreadForkResponse__WebSearchAction =
5165 | {
5166 readonly queries?: ReadonlyArray<string> | null;
5167 readonly query?: string | null;
5168 readonly type: "search";
5169 }
5170 | { readonly type: "openPage"; readonly url?: string | null }
5171 | { readonly pattern?: string | null; readonly type: "findInPage"; readonly url?: string | null }
5172 | { readonly type: "other" };
5173export const V2ThreadForkResponse__WebSearchAction = Schema.Union(
5174 [
5175 Schema.Struct({
5176 queries: Schema.optionalKey(Schema.Union([Schema.Array(Schema.String), Schema.Null])),
5177 query: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
5178 type: Schema.Literal("search").annotate({ title: "SearchWebSearchActionType" }),
5179 }).annotate({ title: "SearchWebSearchAction" }),
5180 Schema.Struct({
5181 type: Schema.Literal("openPage").annotate({ title: "OpenPageWebSearchActionType" }),
5182 url: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
5183 }).annotate({ title: "OpenPageWebSearchAction" }),
5184 Schema.Struct({
5185 pattern: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
5186 type: Schema.Literal("findInPage").annotate({ title: "FindInPageWebSearchActionType" }),
5187 url: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
5188 }).annotate({ title: "FindInPageWebSearchAction" }),
5189 Schema.Struct({
5190 type: Schema.Literal("other").annotate({ title: "OtherWebSearchActionType" }),
5191 }).annotate({ title: "OtherWebSearchAction" }),
5192 ],
5193 { mode: "oneOf" },
5194);
5195
5196export type V2ThreadListParams__ThreadSortKey = "created_at" | "updated_at";
5197export const V2ThreadListParams__ThreadSortKey = Schema.Literals(["created_at", "updated_at"]);
5198
5199export type V2ThreadListParams__ThreadSourceKind =
5200 | "cli"
5201 | "vscode"
5202 | "exec"
5203 | "appServer"
5204 | "subAgent"
5205 | "subAgentReview"
5206 | "subAgentCompact"
5207 | "subAgentThreadSpawn"
5208 | "subAgentOther"
5209 | "unknown";
5210export const V2ThreadListParams__ThreadSourceKind = Schema.Literals([
5211 "cli",
5212 "vscode",
5213 "exec",
5214 "appServer",
5215 "subAgent",
5216 "subAgentReview",
5217 "subAgentCompact",
5218 "subAgentThreadSpawn",
5219 "subAgentOther",
5220 "unknown",
5221]);
5222
5223export type V2ThreadListResponse__AgentPath = string;
5224export const V2ThreadListResponse__AgentPath = Schema.String;
5225
5226export type V2ThreadListResponse__CollabAgentStatus =
5227 | "pendingInit"
5228 | "running"
5229 | "interrupted"
5230 | "completed"
5231 | "errored"
5232 | "shutdown"
5233 | "notFound";
5234export const V2ThreadListResponse__CollabAgentStatus = Schema.Literals([
5235 "pendingInit",
5236 "running",
5237 "interrupted",
5238 "completed",
5239 "errored",
5240 "shutdown",
5241 "notFound",
5242]);
5243
5244export type V2ThreadListResponse__CommandAction =
5245 | {
5246 readonly command: string;
5247 readonly name: string;
5248 readonly path: string;
5249 readonly type: "read";
5250 }
5251 | { readonly command: string; readonly path?: string | null; readonly type: "listFiles" }
5252 | {
5253 readonly command: string;
5254 readonly path?: string | null;
5255 readonly query?: string | null;
5256 readonly type: "search";
5257 }
5258 | { readonly command: string; readonly type: "unknown" };
5259export const V2ThreadListResponse__CommandAction = Schema.Union(
5260 [
5261 Schema.Struct({
5262 command: Schema.String,
5263 name: Schema.String,
5264 path: Schema.String,
5265 type: Schema.Literal("read").annotate({ title: "ReadCommandActionType" }),
5266 }).annotate({ title: "ReadCommandAction" }),
5267 Schema.Struct({
5268 command: Schema.String,
5269 path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
5270 type: Schema.Literal("listFiles").annotate({ title: "ListFilesCommandActionType" }),
5271 }).annotate({ title: "ListFilesCommandAction" }),
5272 Schema.Struct({
5273 command: Schema.String,
5274 path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
5275 query: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
5276 type: Schema.Literal("search").annotate({ title: "SearchCommandActionType" }),
5277 }).annotate({ title: "SearchCommandAction" }),
5278 Schema.Struct({
5279 command: Schema.String,
5280 type: Schema.Literal("unknown").annotate({ title: "UnknownCommandActionType" }),
5281 }).annotate({ title: "UnknownCommandAction" }),
5282 ],
5283 { mode: "oneOf" },
5284);
5285
5286export type V2ThreadListResponse__CommandExecutionStatus =
5287 | "inProgress"
5288 | "completed"
5289 | "failed"
5290 | "declined";
5291export const V2ThreadListResponse__CommandExecutionStatus = Schema.Literals([
5292 "inProgress",
5293 "completed",
5294 "failed",
5295 "declined",
5296]);
5297
5298export type V2ThreadListResponse__DynamicToolCallOutputContentItem =
5299 | { readonly text: string; readonly type: "inputText" }
5300 | { readonly imageUrl: string; readonly type: "inputImage" };
5301export const V2ThreadListResponse__DynamicToolCallOutputContentItem = Schema.Union(
5302 [
5303 Schema.Struct({
5304 text: Schema.String,
5305 type: Schema.Literal("inputText").annotate({
5306 title: "InputTextDynamicToolCallOutputContentItemType",
5307 }),
5308 }).annotate({ title: "InputTextDynamicToolCallOutputContentItem" }),
5309 Schema.Struct({
5310 imageUrl: Schema.String,
5311 type: Schema.Literal("inputImage").annotate({
5312 title: "InputImageDynamicToolCallOutputContentItemType",
5313 }),
5314 }).annotate({ title: "InputImageDynamicToolCallOutputContentItem" }),
5315 ],
5316 { mode: "oneOf" },
5317);
5318
5319export type V2ThreadListResponse__DynamicToolCallStatus = "inProgress" | "completed" | "failed";
5320export const V2ThreadListResponse__DynamicToolCallStatus = Schema.Literals([
5321 "inProgress",
5322 "completed",
5323 "failed",
5324]);
5325
5326export type V2ThreadListResponse__GitInfo = {
5327 readonly branch?: string | null;
5328 readonly originUrl?: string | null;
5329 readonly sha?: string | null;
5330};
5331export const V2ThreadListResponse__GitInfo = Schema.Struct({
5332 branch: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
5333 originUrl: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
5334 sha: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
5335});
5336
5337export type V2ThreadListResponse__HookPromptFragment = {
5338 readonly hookRunId: string;
5339 readonly text: string;
5340};
5341export const V2ThreadListResponse__HookPromptFragment = Schema.Struct({
5342 hookRunId: Schema.String,
5343 text: Schema.String,
5344});
5345
5346export type V2ThreadListResponse__McpToolCallError = { readonly message: string };
5347export const V2ThreadListResponse__McpToolCallError = Schema.Struct({ message: Schema.String });
5348
5349export type V2ThreadListResponse__McpToolCallResult = {
5350 readonly _meta?: unknown;
5351 readonly content: ReadonlyArray<unknown>;
5352 readonly structuredContent?: unknown;
5353};
5354export const V2ThreadListResponse__McpToolCallResult = Schema.Struct({
5355 _meta: Schema.optionalKey(Schema.Unknown),
5356 content: Schema.Array(Schema.Unknown),
5357 structuredContent: Schema.optionalKey(Schema.Unknown),
5358});
5359
5360export type V2ThreadListResponse__McpToolCallStatus = "inProgress" | "completed" | "failed";
5361export const V2ThreadListResponse__McpToolCallStatus = Schema.Literals([
5362 "inProgress",
5363 "completed",
5364 "failed",
5365]);
5366
5367export type V2ThreadListResponse__MemoryCitationEntry = {
5368 readonly lineEnd: number;
5369 readonly lineStart: number;
5370 readonly note: string;
5371 readonly path: string;
5372};
5373export const V2ThreadListResponse__MemoryCitationEntry = Schema.Struct({
5374 lineEnd: Schema.Number.annotate({ format: "uint32" })
5375 .check(Schema.isInt())
5376 .check(Schema.isGreaterThanOrEqualTo(0)),
5377 lineStart: Schema.Number.annotate({ format: "uint32" })
5378 .check(Schema.isInt())
5379 .check(Schema.isGreaterThanOrEqualTo(0)),
5380 note: Schema.String,
5381 path: Schema.String,
5382});
5383
5384export type V2ThreadListResponse__MessagePhase = "commentary" | "final_answer";
5385export const V2ThreadListResponse__MessagePhase = Schema.Literals([
5386 "commentary",
5387 "final_answer",
5388]).annotate({
5389 description:
5390 '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.',
5391});
5392
5393export type V2ThreadListResponse__NonSteerableTurnKind = "review" | "compact";
5394export const V2ThreadListResponse__NonSteerableTurnKind = Schema.Literals(["review", "compact"]);
5395
5396export type V2ThreadListResponse__PatchApplyStatus =
5397 | "inProgress"
5398 | "completed"
5399 | "failed"
5400 | "declined";
5401export const V2ThreadListResponse__PatchApplyStatus = Schema.Literals([
5402 "inProgress",
5403 "completed",
5404 "failed",
5405 "declined",
5406]);
5407
5408export type V2ThreadListResponse__PatchChangeKind =
5409 | { readonly type: "add" }
5410 | { readonly type: "delete" }
5411 | { readonly move_path?: string | null; readonly type: "update" };
5412export const V2ThreadListResponse__PatchChangeKind = Schema.Union(
5413 [
5414 Schema.Struct({
5415 type: Schema.Literal("add").annotate({ title: "AddPatchChangeKindType" }),
5416 }).annotate({ title: "AddPatchChangeKind" }),
5417 Schema.Struct({
5418 type: Schema.Literal("delete").annotate({ title: "DeletePatchChangeKindType" }),
5419 }).annotate({ title: "DeletePatchChangeKind" }),
5420 Schema.Struct({
5421 move_path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
5422 type: Schema.Literal("update").annotate({ title: "UpdatePatchChangeKindType" }),
5423 }).annotate({ title: "UpdatePatchChangeKind" }),
5424 ],
5425 { mode: "oneOf" },
5426);
5427
5428export type V2ThreadListResponse__ReasoningEffort =
5429 | "none"
5430 | "minimal"
5431 | "low"
5432 | "medium"
5433 | "high"
5434 | "xhigh";
5435export const V2ThreadListResponse__ReasoningEffort = Schema.Literals([
5436 "none",
5437 "minimal",
5438 "low",
5439 "medium",
5440 "high",
5441 "xhigh",
5442]).annotate({
5443 description:
5444 "See https://platform.openai.com/docs/guides/reasoning?api-mode=responses#get-started-with-reasoning",
5445});
5446
5447export type V2ThreadListResponse__TextElement = {
5448 readonly byteRange: { readonly end: number; readonly start: number };
5449 readonly placeholder?: string | null;
5450};
5451export const V2ThreadListResponse__TextElement = Schema.Struct({
5452 byteRange: Schema.Struct({
5453 end: Schema.Number.annotate({ format: "uint" })
5454 .check(Schema.isInt())
5455 .check(Schema.isGreaterThanOrEqualTo(0)),
5456 start: Schema.Number.annotate({ format: "uint" })
5457 .check(Schema.isInt())
5458 .check(Schema.isGreaterThanOrEqualTo(0)),
5459 }).annotate({
5460 description: "Byte range in the parent `text` buffer that this element occupies.",
5461 }),
5462 placeholder: Schema.optionalKey(
5463 Schema.Union([
5464 Schema.String.annotate({
5465 description: "Optional human-readable placeholder for the element, displayed in the UI.",
5466 }),
5467 Schema.Null,
5468 ]),
5469 ),
5470});
5471
5472export type V2ThreadListResponse__ThreadActiveFlag = "waitingOnApproval" | "waitingOnUserInput";
5473export const V2ThreadListResponse__ThreadActiveFlag = Schema.Literals([
5474 "waitingOnApproval",
5475 "waitingOnUserInput",
5476]);
5477
5478export type V2ThreadListResponse__ThreadId = string;
5479export const V2ThreadListResponse__ThreadId = Schema.String;
5480
5481export type V2ThreadListResponse__TurnStatus =
5482 | "completed"
5483 | "interrupted"
5484 | "failed"
5485 | "inProgress";
5486export const V2ThreadListResponse__TurnStatus = Schema.Literals([
5487 "completed",
5488 "interrupted",
5489 "failed",
5490 "inProgress",
5491]);
5492
5493export type V2ThreadListResponse__WebSearchAction =
5494 | {
5495 readonly queries?: ReadonlyArray<string> | null;
5496 readonly query?: string | null;
5497 readonly type: "search";
5498 }
5499 | { readonly type: "openPage"; readonly url?: string | null }
5500 | { readonly pattern?: string | null; readonly type: "findInPage"; readonly url?: string | null }
5501 | { readonly type: "other" };
5502export const V2ThreadListResponse__WebSearchAction = Schema.Union(
5503 [
5504 Schema.Struct({
5505 queries: Schema.optionalKey(Schema.Union([Schema.Array(Schema.String), Schema.Null])),
5506 query: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
5507 type: Schema.Literal("search").annotate({ title: "SearchWebSearchActionType" }),
5508 }).annotate({ title: "SearchWebSearchAction" }),
5509 Schema.Struct({
5510 type: Schema.Literal("openPage").annotate({ title: "OpenPageWebSearchActionType" }),
5511 url: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
5512 }).annotate({ title: "OpenPageWebSearchAction" }),
5513 Schema.Struct({
5514 pattern: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
5515 type: Schema.Literal("findInPage").annotate({ title: "FindInPageWebSearchActionType" }),
5516 url: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
5517 }).annotate({ title: "FindInPageWebSearchAction" }),
5518 Schema.Struct({
5519 type: Schema.Literal("other").annotate({ title: "OtherWebSearchActionType" }),
5520 }).annotate({ title: "OtherWebSearchAction" }),
5521 ],
5522 { mode: "oneOf" },
5523);
5524
5525export type V2ThreadMetadataUpdateParams__ThreadMetadataGitInfoUpdateParams = {
5526 readonly branch?: string | null;
5527 readonly originUrl?: string | null;
5528 readonly sha?: string | null;
5529};
5530export const V2ThreadMetadataUpdateParams__ThreadMetadataGitInfoUpdateParams = Schema.Struct({
5531 branch: Schema.optionalKey(
5532 Schema.Union([
5533 Schema.String.annotate({
5534 description:
5535 "Omit to leave the stored branch unchanged, set to `null` to clear it, or provide a non-empty string to replace it.",
5536 }),
5537 Schema.Null,
5538 ]),
5539 ),
5540 originUrl: Schema.optionalKey(
5541 Schema.Union([
5542 Schema.String.annotate({
5543 description:
5544 "Omit to leave the stored origin URL unchanged, set to `null` to clear it, or provide a non-empty string to replace it.",
5545 }),
5546 Schema.Null,
5547 ]),
5548 ),
5549 sha: Schema.optionalKey(
5550 Schema.Union([
5551 Schema.String.annotate({
5552 description:
5553 "Omit to leave the stored commit unchanged, set to `null` to clear it, or provide a non-empty string to replace it.",
5554 }),
5555 Schema.Null,
5556 ]),
5557 ),
5558});
5559
5560export type V2ThreadMetadataUpdateResponse__AgentPath = string;
5561export const V2ThreadMetadataUpdateResponse__AgentPath = Schema.String;
5562
5563export type V2ThreadMetadataUpdateResponse__CollabAgentStatus =
5564 | "pendingInit"
5565 | "running"
5566 | "interrupted"
5567 | "completed"
5568 | "errored"
5569 | "shutdown"
5570 | "notFound";
5571export const V2ThreadMetadataUpdateResponse__CollabAgentStatus = Schema.Literals([
5572 "pendingInit",
5573 "running",
5574 "interrupted",
5575 "completed",
5576 "errored",
5577 "shutdown",
5578 "notFound",
5579]);
5580
5581export type V2ThreadMetadataUpdateResponse__CommandAction =
5582 | {
5583 readonly command: string;
5584 readonly name: string;
5585 readonly path: string;
5586 readonly type: "read";
5587 }
5588 | { readonly command: string; readonly path?: string | null; readonly type: "listFiles" }
5589 | {
5590 readonly command: string;
5591 readonly path?: string | null;
5592 readonly query?: string | null;
5593 readonly type: "search";
5594 }
5595 | { readonly command: string; readonly type: "unknown" };
5596export const V2ThreadMetadataUpdateResponse__CommandAction = Schema.Union(
5597 [
5598 Schema.Struct({
5599 command: Schema.String,
5600 name: Schema.String,
5601 path: Schema.String,
5602 type: Schema.Literal("read").annotate({ title: "ReadCommandActionType" }),
5603 }).annotate({ title: "ReadCommandAction" }),
5604 Schema.Struct({
5605 command: Schema.String,
5606 path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
5607 type: Schema.Literal("listFiles").annotate({ title: "ListFilesCommandActionType" }),
5608 }).annotate({ title: "ListFilesCommandAction" }),
5609 Schema.Struct({
5610 command: Schema.String,
5611 path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
5612 query: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
5613 type: Schema.Literal("search").annotate({ title: "SearchCommandActionType" }),
5614 }).annotate({ title: "SearchCommandAction" }),
5615 Schema.Struct({
5616 command: Schema.String,
5617 type: Schema.Literal("unknown").annotate({ title: "UnknownCommandActionType" }),
5618 }).annotate({ title: "UnknownCommandAction" }),
5619 ],
5620 { mode: "oneOf" },
5621);
5622
5623export type V2ThreadMetadataUpdateResponse__CommandExecutionStatus =
5624 | "inProgress"
5625 | "completed"
5626 | "failed"
5627 | "declined";
5628export const V2ThreadMetadataUpdateResponse__CommandExecutionStatus = Schema.Literals([
5629 "inProgress",
5630 "completed",
5631 "failed",
5632 "declined",
5633]);
5634
5635export type V2ThreadMetadataUpdateResponse__DynamicToolCallOutputContentItem =
5636 | { readonly text: string; readonly type: "inputText" }
5637 | { readonly imageUrl: string; readonly type: "inputImage" };
5638export const V2ThreadMetadataUpdateResponse__DynamicToolCallOutputContentItem = Schema.Union(
5639 [
5640 Schema.Struct({
5641 text: Schema.String,
5642 type: Schema.Literal("inputText").annotate({
5643 title: "InputTextDynamicToolCallOutputContentItemType",
5644 }),
5645 }).annotate({ title: "InputTextDynamicToolCallOutputContentItem" }),
5646 Schema.Struct({
5647 imageUrl: Schema.String,
5648 type: Schema.Literal("inputImage").annotate({
5649 title: "InputImageDynamicToolCallOutputContentItemType",
5650 }),
5651 }).annotate({ title: "InputImageDynamicToolCallOutputContentItem" }),
5652 ],
5653 { mode: "oneOf" },
5654);
5655
5656export type V2ThreadMetadataUpdateResponse__DynamicToolCallStatus =
5657 | "inProgress"
5658 | "completed"
5659 | "failed";
5660export const V2ThreadMetadataUpdateResponse__DynamicToolCallStatus = Schema.Literals([
5661 "inProgress",
5662 "completed",
5663 "failed",
5664]);
5665
5666export type V2ThreadMetadataUpdateResponse__GitInfo = {
5667 readonly branch?: string | null;
5668 readonly originUrl?: string | null;
5669 readonly sha?: string | null;
5670};
5671export const V2ThreadMetadataUpdateResponse__GitInfo = Schema.Struct({
5672 branch: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
5673 originUrl: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
5674 sha: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
5675});
5676
5677export type V2ThreadMetadataUpdateResponse__HookPromptFragment = {
5678 readonly hookRunId: string;
5679 readonly text: string;
5680};
5681export const V2ThreadMetadataUpdateResponse__HookPromptFragment = Schema.Struct({
5682 hookRunId: Schema.String,
5683 text: Schema.String,
5684});
5685
5686export type V2ThreadMetadataUpdateResponse__McpToolCallError = { readonly message: string };
5687export const V2ThreadMetadataUpdateResponse__McpToolCallError = Schema.Struct({
5688 message: Schema.String,
5689});
5690
5691export type V2ThreadMetadataUpdateResponse__McpToolCallResult = {
5692 readonly _meta?: unknown;
5693 readonly content: ReadonlyArray<unknown>;
5694 readonly structuredContent?: unknown;
5695};
5696export const V2ThreadMetadataUpdateResponse__McpToolCallResult = Schema.Struct({
5697 _meta: Schema.optionalKey(Schema.Unknown),
5698 content: Schema.Array(Schema.Unknown),
5699 structuredContent: Schema.optionalKey(Schema.Unknown),
5700});
5701
5702export type V2ThreadMetadataUpdateResponse__McpToolCallStatus =
5703 | "inProgress"
5704 | "completed"
5705 | "failed";
5706export const V2ThreadMetadataUpdateResponse__McpToolCallStatus = Schema.Literals([
5707 "inProgress",
5708 "completed",
5709 "failed",
5710]);
5711
5712export type V2ThreadMetadataUpdateResponse__MemoryCitationEntry = {
5713 readonly lineEnd: number;
5714 readonly lineStart: number;
5715 readonly note: string;
5716 readonly path: string;
5717};
5718export const V2ThreadMetadataUpdateResponse__MemoryCitationEntry = Schema.Struct({
5719 lineEnd: Schema.Number.annotate({ format: "uint32" })
5720 .check(Schema.isInt())
5721 .check(Schema.isGreaterThanOrEqualTo(0)),
5722 lineStart: Schema.Number.annotate({ format: "uint32" })
5723 .check(Schema.isInt())
5724 .check(Schema.isGreaterThanOrEqualTo(0)),
5725 note: Schema.String,
5726 path: Schema.String,
5727});
5728
5729export type V2ThreadMetadataUpdateResponse__MessagePhase = "commentary" | "final_answer";
5730export const V2ThreadMetadataUpdateResponse__MessagePhase = Schema.Literals([
5731 "commentary",
5732 "final_answer",
5733]).annotate({
5734 description:
5735 '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.',
5736});
5737
5738export type V2ThreadMetadataUpdateResponse__NonSteerableTurnKind = "review" | "compact";
5739export const V2ThreadMetadataUpdateResponse__NonSteerableTurnKind = Schema.Literals([
5740 "review",
5741 "compact",
5742]);
5743
5744export type V2ThreadMetadataUpdateResponse__PatchApplyStatus =
5745 | "inProgress"
5746 | "completed"
5747 | "failed"
5748 | "declined";
5749export const V2ThreadMetadataUpdateResponse__PatchApplyStatus = Schema.Literals([
5750 "inProgress",
5751 "completed",
5752 "failed",
5753 "declined",
5754]);
5755
5756export type V2ThreadMetadataUpdateResponse__PatchChangeKind =
5757 | { readonly type: "add" }
5758 | { readonly type: "delete" }
5759 | { readonly move_path?: string | null; readonly type: "update" };
5760export const V2ThreadMetadataUpdateResponse__PatchChangeKind = Schema.Union(
5761 [
5762 Schema.Struct({
5763 type: Schema.Literal("add").annotate({ title: "AddPatchChangeKindType" }),
5764 }).annotate({ title: "AddPatchChangeKind" }),
5765 Schema.Struct({
5766 type: Schema.Literal("delete").annotate({ title: "DeletePatchChangeKindType" }),
5767 }).annotate({ title: "DeletePatchChangeKind" }),
5768 Schema.Struct({
5769 move_path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
5770 type: Schema.Literal("update").annotate({ title: "UpdatePatchChangeKindType" }),
5771 }).annotate({ title: "UpdatePatchChangeKind" }),
5772 ],
5773 { mode: "oneOf" },
5774);
5775
5776export type V2ThreadMetadataUpdateResponse__ReasoningEffort =
5777 | "none"
5778 | "minimal"
5779 | "low"
5780 | "medium"
5781 | "high"
5782 | "xhigh";
5783export const V2ThreadMetadataUpdateResponse__ReasoningEffort = Schema.Literals([
5784 "none",
5785 "minimal",
5786 "low",
5787 "medium",
5788 "high",
5789 "xhigh",
5790]).annotate({
5791 description:
5792 "See https://platform.openai.com/docs/guides/reasoning?api-mode=responses#get-started-with-reasoning",
5793});
5794
5795export type V2ThreadMetadataUpdateResponse__TextElement = {
5796 readonly byteRange: { readonly end: number; readonly start: number };
5797 readonly placeholder?: string | null;
5798};
5799export const V2ThreadMetadataUpdateResponse__TextElement = Schema.Struct({
5800 byteRange: Schema.Struct({
5801 end: Schema.Number.annotate({ format: "uint" })
5802 .check(Schema.isInt())
5803 .check(Schema.isGreaterThanOrEqualTo(0)),
5804 start: Schema.Number.annotate({ format: "uint" })
5805 .check(Schema.isInt())
5806 .check(Schema.isGreaterThanOrEqualTo(0)),
5807 }).annotate({
5808 description: "Byte range in the parent `text` buffer that this element occupies.",
5809 }),
5810 placeholder: Schema.optionalKey(
5811 Schema.Union([
5812 Schema.String.annotate({
5813 description: "Optional human-readable placeholder for the element, displayed in the UI.",
5814 }),
5815 Schema.Null,
5816 ]),
5817 ),
5818});
5819
5820export type V2ThreadMetadataUpdateResponse__ThreadActiveFlag =
5821 | "waitingOnApproval"
5822 | "waitingOnUserInput";
5823export const V2ThreadMetadataUpdateResponse__ThreadActiveFlag = Schema.Literals([
5824 "waitingOnApproval",
5825 "waitingOnUserInput",
5826]);
5827
5828export type V2ThreadMetadataUpdateResponse__ThreadId = string;
5829export const V2ThreadMetadataUpdateResponse__ThreadId = Schema.String;
5830
5831export type V2ThreadMetadataUpdateResponse__TurnStatus =
5832 | "completed"
5833 | "interrupted"
5834 | "failed"
5835 | "inProgress";
5836export const V2ThreadMetadataUpdateResponse__TurnStatus = Schema.Literals([
5837 "completed",
5838 "interrupted",
5839 "failed",
5840 "inProgress",
5841]);
5842
5843export type V2ThreadMetadataUpdateResponse__WebSearchAction =
5844 | {
5845 readonly queries?: ReadonlyArray<string> | null;
5846 readonly query?: string | null;
5847 readonly type: "search";
5848 }
5849 | { readonly type: "openPage"; readonly url?: string | null }
5850 | { readonly pattern?: string | null; readonly type: "findInPage"; readonly url?: string | null }
5851 | { readonly type: "other" };
5852export const V2ThreadMetadataUpdateResponse__WebSearchAction = Schema.Union(
5853 [
5854 Schema.Struct({
5855 queries: Schema.optionalKey(Schema.Union([Schema.Array(Schema.String), Schema.Null])),
5856 query: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
5857 type: Schema.Literal("search").annotate({ title: "SearchWebSearchActionType" }),
5858 }).annotate({ title: "SearchWebSearchAction" }),
5859 Schema.Struct({
5860 type: Schema.Literal("openPage").annotate({ title: "OpenPageWebSearchActionType" }),
5861 url: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
5862 }).annotate({ title: "OpenPageWebSearchAction" }),
5863 Schema.Struct({
5864 pattern: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
5865 type: Schema.Literal("findInPage").annotate({ title: "FindInPageWebSearchActionType" }),
5866 url: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
5867 }).annotate({ title: "FindInPageWebSearchAction" }),
5868 Schema.Struct({
5869 type: Schema.Literal("other").annotate({ title: "OtherWebSearchActionType" }),
5870 }).annotate({ title: "OtherWebSearchAction" }),
5871 ],
5872 { mode: "oneOf" },
5873);
5874
5875export type V2ThreadReadResponse__AgentPath = string;
5876export const V2ThreadReadResponse__AgentPath = Schema.String;
5877
5878export type V2ThreadReadResponse__CollabAgentStatus =
5879 | "pendingInit"
5880 | "running"
5881 | "interrupted"
5882 | "completed"
5883 | "errored"
5884 | "shutdown"
5885 | "notFound";
5886export const V2ThreadReadResponse__CollabAgentStatus = Schema.Literals([
5887 "pendingInit",
5888 "running",
5889 "interrupted",
5890 "completed",
5891 "errored",
5892 "shutdown",
5893 "notFound",
5894]);
5895
5896export type V2ThreadReadResponse__CommandAction =
5897 | {
5898 readonly command: string;
5899 readonly name: string;
5900 readonly path: string;
5901 readonly type: "read";
5902 }
5903 | { readonly command: string; readonly path?: string | null; readonly type: "listFiles" }
5904 | {
5905 readonly command: string;
5906 readonly path?: string | null;
5907 readonly query?: string | null;
5908 readonly type: "search";
5909 }
5910 | { readonly command: string; readonly type: "unknown" };
5911export const V2ThreadReadResponse__CommandAction = Schema.Union(
5912 [
5913 Schema.Struct({
5914 command: Schema.String,
5915 name: Schema.String,
5916 path: Schema.String,
5917 type: Schema.Literal("read").annotate({ title: "ReadCommandActionType" }),
5918 }).annotate({ title: "ReadCommandAction" }),
5919 Schema.Struct({
5920 command: Schema.String,
5921 path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
5922 type: Schema.Literal("listFiles").annotate({ title: "ListFilesCommandActionType" }),
5923 }).annotate({ title: "ListFilesCommandAction" }),
5924 Schema.Struct({
5925 command: Schema.String,
5926 path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
5927 query: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
5928 type: Schema.Literal("search").annotate({ title: "SearchCommandActionType" }),
5929 }).annotate({ title: "SearchCommandAction" }),
5930 Schema.Struct({
5931 command: Schema.String,
5932 type: Schema.Literal("unknown").annotate({ title: "UnknownCommandActionType" }),
5933 }).annotate({ title: "UnknownCommandAction" }),
5934 ],
5935 { mode: "oneOf" },
5936);
5937
5938export type V2ThreadReadResponse__CommandExecutionStatus =
5939 | "inProgress"
5940 | "completed"
5941 | "failed"
5942 | "declined";
5943export const V2ThreadReadResponse__CommandExecutionStatus = Schema.Literals([
5944 "inProgress",
5945 "completed",
5946 "failed",
5947 "declined",
5948]);
5949
5950export type V2ThreadReadResponse__DynamicToolCallOutputContentItem =
5951 | { readonly text: string; readonly type: "inputText" }
5952 | { readonly imageUrl: string; readonly type: "inputImage" };
5953export const V2ThreadReadResponse__DynamicToolCallOutputContentItem = Schema.Union(
5954 [
5955 Schema.Struct({
5956 text: Schema.String,
5957 type: Schema.Literal("inputText").annotate({
5958 title: "InputTextDynamicToolCallOutputContentItemType",
5959 }),
5960 }).annotate({ title: "InputTextDynamicToolCallOutputContentItem" }),
5961 Schema.Struct({
5962 imageUrl: Schema.String,
5963 type: Schema.Literal("inputImage").annotate({
5964 title: "InputImageDynamicToolCallOutputContentItemType",
5965 }),
5966 }).annotate({ title: "InputImageDynamicToolCallOutputContentItem" }),
5967 ],
5968 { mode: "oneOf" },
5969);
5970
5971export type V2ThreadReadResponse__DynamicToolCallStatus = "inProgress" | "completed" | "failed";
5972export const V2ThreadReadResponse__DynamicToolCallStatus = Schema.Literals([
5973 "inProgress",
5974 "completed",
5975 "failed",
5976]);
5977
5978export type V2ThreadReadResponse__GitInfo = {
5979 readonly branch?: string | null;
5980 readonly originUrl?: string | null;
5981 readonly sha?: string | null;
5982};
5983export const V2ThreadReadResponse__GitInfo = Schema.Struct({
5984 branch: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
5985 originUrl: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
5986 sha: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
5987});
5988
5989export type V2ThreadReadResponse__HookPromptFragment = {
5990 readonly hookRunId: string;
5991 readonly text: string;
5992};
5993export const V2ThreadReadResponse__HookPromptFragment = Schema.Struct({
5994 hookRunId: Schema.String,
5995 text: Schema.String,
5996});
5997
5998export type V2ThreadReadResponse__McpToolCallError = { readonly message: string };
5999export const V2ThreadReadResponse__McpToolCallError = Schema.Struct({ message: Schema.String });
6000
6001export type V2ThreadReadResponse__McpToolCallResult = {
6002 readonly _meta?: unknown;
6003 readonly content: ReadonlyArray<unknown>;
6004 readonly structuredContent?: unknown;
6005};
6006export const V2ThreadReadResponse__McpToolCallResult = Schema.Struct({
6007 _meta: Schema.optionalKey(Schema.Unknown),
6008 content: Schema.Array(Schema.Unknown),
6009 structuredContent: Schema.optionalKey(Schema.Unknown),
6010});
6011
6012export type V2ThreadReadResponse__McpToolCallStatus = "inProgress" | "completed" | "failed";
6013export const V2ThreadReadResponse__McpToolCallStatus = Schema.Literals([
6014 "inProgress",
6015 "completed",
6016 "failed",
6017]);
6018
6019export type V2ThreadReadResponse__MemoryCitationEntry = {
6020 readonly lineEnd: number;
6021 readonly lineStart: number;
6022 readonly note: string;
6023 readonly path: string;
6024};
6025export const V2ThreadReadResponse__MemoryCitationEntry = Schema.Struct({
6026 lineEnd: Schema.Number.annotate({ format: "uint32" })
6027 .check(Schema.isInt())
6028 .check(Schema.isGreaterThanOrEqualTo(0)),
6029 lineStart: Schema.Number.annotate({ format: "uint32" })
6030 .check(Schema.isInt())
6031 .check(Schema.isGreaterThanOrEqualTo(0)),
6032 note: Schema.String,
6033 path: Schema.String,
6034});
6035
6036export type V2ThreadReadResponse__MessagePhase = "commentary" | "final_answer";
6037export const V2ThreadReadResponse__MessagePhase = Schema.Literals([
6038 "commentary",
6039 "final_answer",
6040]).annotate({
6041 description:
6042 '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.',
6043});
6044
6045export type V2ThreadReadResponse__NonSteerableTurnKind = "review" | "compact";
6046export const V2ThreadReadResponse__NonSteerableTurnKind = Schema.Literals(["review", "compact"]);
6047
6048export type V2ThreadReadResponse__PatchApplyStatus =
6049 | "inProgress"
6050 | "completed"
6051 | "failed"
6052 | "declined";
6053export const V2ThreadReadResponse__PatchApplyStatus = Schema.Literals([
6054 "inProgress",
6055 "completed",
6056 "failed",
6057 "declined",
6058]);
6059
6060export type V2ThreadReadResponse__PatchChangeKind =
6061 | { readonly type: "add" }
6062 | { readonly type: "delete" }
6063 | { readonly move_path?: string | null; readonly type: "update" };
6064export const V2ThreadReadResponse__PatchChangeKind = Schema.Union(
6065 [
6066 Schema.Struct({
6067 type: Schema.Literal("add").annotate({ title: "AddPatchChangeKindType" }),
6068 }).annotate({ title: "AddPatchChangeKind" }),
6069 Schema.Struct({
6070 type: Schema.Literal("delete").annotate({ title: "DeletePatchChangeKindType" }),
6071 }).annotate({ title: "DeletePatchChangeKind" }),
6072 Schema.Struct({
6073 move_path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
6074 type: Schema.Literal("update").annotate({ title: "UpdatePatchChangeKindType" }),
6075 }).annotate({ title: "UpdatePatchChangeKind" }),
6076 ],
6077 { mode: "oneOf" },
6078);
6079
6080export type V2ThreadReadResponse__ReasoningEffort =
6081 | "none"
6082 | "minimal"
6083 | "low"
6084 | "medium"
6085 | "high"
6086 | "xhigh";
6087export const V2ThreadReadResponse__ReasoningEffort = Schema.Literals([
6088 "none",
6089 "minimal",
6090 "low",
6091 "medium",
6092 "high",
6093 "xhigh",
6094]).annotate({
6095 description:
6096 "See https://platform.openai.com/docs/guides/reasoning?api-mode=responses#get-started-with-reasoning",
6097});
6098
6099export type V2ThreadReadResponse__TextElement = {
6100 readonly byteRange: { readonly end: number; readonly start: number };
6101 readonly placeholder?: string | null;
6102};
6103export const V2ThreadReadResponse__TextElement = Schema.Struct({
6104 byteRange: Schema.Struct({
6105 end: Schema.Number.annotate({ format: "uint" })
6106 .check(Schema.isInt())
6107 .check(Schema.isGreaterThanOrEqualTo(0)),
6108 start: Schema.Number.annotate({ format: "uint" })
6109 .check(Schema.isInt())
6110 .check(Schema.isGreaterThanOrEqualTo(0)),
6111 }).annotate({
6112 description: "Byte range in the parent `text` buffer that this element occupies.",
6113 }),
6114 placeholder: Schema.optionalKey(
6115 Schema.Union([
6116 Schema.String.annotate({
6117 description: "Optional human-readable placeholder for the element, displayed in the UI.",
6118 }),
6119 Schema.Null,
6120 ]),
6121 ),
6122});
6123
6124export type V2ThreadReadResponse__ThreadActiveFlag = "waitingOnApproval" | "waitingOnUserInput";
6125export const V2ThreadReadResponse__ThreadActiveFlag = Schema.Literals([
6126 "waitingOnApproval",
6127 "waitingOnUserInput",
6128]);
6129
6130export type V2ThreadReadResponse__ThreadId = string;
6131export const V2ThreadReadResponse__ThreadId = Schema.String;
6132
6133export type V2ThreadReadResponse__TurnStatus =
6134 | "completed"
6135 | "interrupted"
6136 | "failed"
6137 | "inProgress";
6138export const V2ThreadReadResponse__TurnStatus = Schema.Literals([
6139 "completed",
6140 "interrupted",
6141 "failed",
6142 "inProgress",
6143]);
6144
6145export type V2ThreadReadResponse__WebSearchAction =
6146 | {
6147 readonly queries?: ReadonlyArray<string> | null;
6148 readonly query?: string | null;
6149 readonly type: "search";
6150 }
6151 | { readonly type: "openPage"; readonly url?: string | null }
6152 | { readonly pattern?: string | null; readonly type: "findInPage"; readonly url?: string | null }
6153 | { readonly type: "other" };
6154export const V2ThreadReadResponse__WebSearchAction = Schema.Union(
6155 [
6156 Schema.Struct({
6157 queries: Schema.optionalKey(Schema.Union([Schema.Array(Schema.String), Schema.Null])),
6158 query: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
6159 type: Schema.Literal("search").annotate({ title: "SearchWebSearchActionType" }),
6160 }).annotate({ title: "SearchWebSearchAction" }),
6161 Schema.Struct({
6162 type: Schema.Literal("openPage").annotate({ title: "OpenPageWebSearchActionType" }),
6163 url: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
6164 }).annotate({ title: "OpenPageWebSearchAction" }),
6165 Schema.Struct({
6166 pattern: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
6167 type: Schema.Literal("findInPage").annotate({ title: "FindInPageWebSearchActionType" }),
6168 url: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
6169 }).annotate({ title: "FindInPageWebSearchAction" }),
6170 Schema.Struct({
6171 type: Schema.Literal("other").annotate({ title: "OtherWebSearchActionType" }),
6172 }).annotate({ title: "OtherWebSearchAction" }),
6173 ],
6174 { mode: "oneOf" },
6175);
6176
6177export type V2ThreadRealtimeOutputAudioDeltaNotification__ThreadRealtimeAudioChunk = {
6178 readonly data: string;
6179 readonly itemId?: string | null;
6180 readonly numChannels: number;
6181 readonly sampleRate: number;
6182 readonly samplesPerChannel?: number | null;
6183};
6184export const V2ThreadRealtimeOutputAudioDeltaNotification__ThreadRealtimeAudioChunk = Schema.Struct(
6185 {
6186 data: Schema.String,
6187 itemId: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
6188 numChannels: Schema.Number.annotate({ format: "uint16" })
6189 .check(Schema.isInt())
6190 .check(Schema.isGreaterThanOrEqualTo(0)),
6191 sampleRate: Schema.Number.annotate({ format: "uint32" })
6192 .check(Schema.isInt())
6193 .check(Schema.isGreaterThanOrEqualTo(0)),
6194 samplesPerChannel: Schema.optionalKey(
6195 Schema.Union([
6196 Schema.Number.annotate({ format: "uint32" })
6197 .check(Schema.isInt())
6198 .check(Schema.isGreaterThanOrEqualTo(0)),
6199 Schema.Null,
6200 ]),
6201 ),
6202 },
6203).annotate({ description: "EXPERIMENTAL - thread realtime audio chunk." });
6204
6205export type V2ThreadRealtimeStartedNotification__RealtimeConversationVersion = "v1" | "v2";
6206export const V2ThreadRealtimeStartedNotification__RealtimeConversationVersion = Schema.Literals([
6207 "v1",
6208 "v2",
6209]);
6210
6211export type V2ThreadResumeParams__ApprovalsReviewer = "user" | "guardian_subagent";
6212export const V2ThreadResumeParams__ApprovalsReviewer = Schema.Literals([
6213 "user",
6214 "guardian_subagent",
6215]).annotate({
6216 description:
6217 "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.",
6218});
6219
6220export type V2ThreadResumeParams__AskForApproval =
6221 | "untrusted"
6222 | "on-failure"
6223 | "on-request"
6224 | "never"
6225 | {
6226 readonly granular: {
6227 readonly mcp_elicitations: boolean;
6228 readonly request_permissions?: boolean;
6229 readonly rules: boolean;
6230 readonly sandbox_approval: boolean;
6231 readonly skill_approval?: boolean;
6232 };
6233 };
6234export const V2ThreadResumeParams__AskForApproval = Schema.Union(
6235 [
6236 Schema.Literals(["untrusted", "on-failure", "on-request", "never"]),
6237 Schema.Struct({
6238 granular: Schema.Struct({
6239 mcp_elicitations: Schema.Boolean,
6240 request_permissions: Schema.optionalKey(Schema.Boolean.annotate({ default: false })),
6241 rules: Schema.Boolean,
6242 sandbox_approval: Schema.Boolean,
6243 skill_approval: Schema.optionalKey(Schema.Boolean.annotate({ default: false })),
6244 }),
6245 }).annotate({ title: "GranularAskForApproval" }),
6246 ],
6247 { mode: "oneOf" },
6248);
6249
6250export type V2ThreadResumeParams__ContentItem =
6251 | { readonly text: string; readonly type: "input_text" }
6252 | { readonly image_url: string; readonly type: "input_image" }
6253 | { readonly text: string; readonly type: "output_text" };
6254export const V2ThreadResumeParams__ContentItem = Schema.Union(
6255 [
6256 Schema.Struct({
6257 text: Schema.String,
6258 type: Schema.Literal("input_text").annotate({ title: "InputTextContentItemType" }),
6259 }).annotate({ title: "InputTextContentItem" }),
6260 Schema.Struct({
6261 image_url: Schema.String,
6262 type: Schema.Literal("input_image").annotate({ title: "InputImageContentItemType" }),
6263 }).annotate({ title: "InputImageContentItem" }),
6264 Schema.Struct({
6265 text: Schema.String,
6266 type: Schema.Literal("output_text").annotate({ title: "OutputTextContentItemType" }),
6267 }).annotate({ title: "OutputTextContentItem" }),
6268 ],
6269 { mode: "oneOf" },
6270);
6271
6272export type V2ThreadResumeParams__GhostCommit = {
6273 readonly id: string;
6274 readonly parent?: string | null;
6275 readonly preexisting_untracked_dirs: ReadonlyArray<string>;
6276 readonly preexisting_untracked_files: ReadonlyArray<string>;
6277};
6278export const V2ThreadResumeParams__GhostCommit = Schema.Struct({
6279 id: Schema.String,
6280 parent: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
6281 preexisting_untracked_dirs: Schema.Array(Schema.String),
6282 preexisting_untracked_files: Schema.Array(Schema.String),
6283}).annotate({ description: "Details of a ghost commit created from a repository state." });
6284
6285export type V2ThreadResumeParams__ImageDetail = "auto" | "low" | "high" | "original";
6286export const V2ThreadResumeParams__ImageDetail = Schema.Literals([
6287 "auto",
6288 "low",
6289 "high",
6290 "original",
6291]);
6292
6293export type V2ThreadResumeParams__LocalShellAction = {
6294 readonly command: ReadonlyArray<string>;
6295 readonly env?: { readonly [x: string]: string } | null;
6296 readonly timeout_ms?: number | null;
6297 readonly type: "exec";
6298 readonly user?: string | null;
6299 readonly working_directory?: string | null;
6300};
6301export const V2ThreadResumeParams__LocalShellAction = Schema.Union(
6302 [
6303 Schema.Struct({
6304 command: Schema.Array(Schema.String),
6305 env: Schema.optionalKey(
6306 Schema.Union([Schema.Record(Schema.String, Schema.String), Schema.Null]),
6307 ),
6308 timeout_ms: Schema.optionalKey(
6309 Schema.Union([
6310 Schema.Number.annotate({ format: "uint64" })
6311 .check(Schema.isInt())
6312 .check(Schema.isGreaterThanOrEqualTo(0)),
6313 Schema.Null,
6314 ]),
6315 ),
6316 type: Schema.Literal("exec").annotate({ title: "ExecLocalShellActionType" }),
6317 user: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
6318 working_directory: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
6319 }).annotate({ title: "ExecLocalShellAction" }),
6320 ],
6321 { mode: "oneOf" },
6322);
6323
6324export type V2ThreadResumeParams__LocalShellStatus = "completed" | "in_progress" | "incomplete";
6325export const V2ThreadResumeParams__LocalShellStatus = Schema.Literals([
6326 "completed",
6327 "in_progress",
6328 "incomplete",
6329]);
6330
6331export type V2ThreadResumeParams__MessagePhase = "commentary" | "final_answer";
6332export const V2ThreadResumeParams__MessagePhase = Schema.Literals([
6333 "commentary",
6334 "final_answer",
6335]).annotate({
6336 description:
6337 '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.',
6338});
6339
6340export type V2ThreadResumeParams__Personality = "none" | "friendly" | "pragmatic";
6341export const V2ThreadResumeParams__Personality = Schema.Literals(["none", "friendly", "pragmatic"]);
6342
6343export type V2ThreadResumeParams__ReasoningItemContent =
6344 | { readonly text: string; readonly type: "reasoning_text" }
6345 | { readonly text: string; readonly type: "text" };
6346export const V2ThreadResumeParams__ReasoningItemContent = Schema.Union(
6347 [
6348 Schema.Struct({
6349 text: Schema.String,
6350 type: Schema.Literal("reasoning_text").annotate({
6351 title: "ReasoningTextReasoningItemContentType",
6352 }),
6353 }).annotate({ title: "ReasoningTextReasoningItemContent" }),
6354 Schema.Struct({
6355 text: Schema.String,
6356 type: Schema.Literal("text").annotate({ title: "TextReasoningItemContentType" }),
6357 }).annotate({ title: "TextReasoningItemContent" }),
6358 ],
6359 { mode: "oneOf" },
6360);
6361
6362export type V2ThreadResumeParams__ReasoningItemReasoningSummary = {
6363 readonly text: string;
6364 readonly type: "summary_text";
6365};
6366export const V2ThreadResumeParams__ReasoningItemReasoningSummary = Schema.Union(
6367 [
6368 Schema.Struct({
6369 text: Schema.String,
6370 type: Schema.Literal("summary_text").annotate({
6371 title: "SummaryTextReasoningItemReasoningSummaryType",
6372 }),
6373 }).annotate({ title: "SummaryTextReasoningItemReasoningSummary" }),
6374 ],
6375 { mode: "oneOf" },
6376);
6377
6378export type V2ThreadResumeParams__ResponsesApiWebSearchAction =
6379 | {
6380 readonly queries?: ReadonlyArray<string> | null;
6381 readonly query?: string | null;
6382 readonly type: "search";
6383 }
6384 | { readonly type: "open_page"; readonly url?: string | null }
6385 | {
6386 readonly pattern?: string | null;
6387 readonly type: "find_in_page";
6388 readonly url?: string | null;
6389 }
6390 | { readonly type: "other" };
6391export const V2ThreadResumeParams__ResponsesApiWebSearchAction = Schema.Union(
6392 [
6393 Schema.Struct({
6394 queries: Schema.optionalKey(Schema.Union([Schema.Array(Schema.String), Schema.Null])),
6395 query: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
6396 type: Schema.Literal("search").annotate({ title: "SearchResponsesApiWebSearchActionType" }),
6397 }).annotate({ title: "SearchResponsesApiWebSearchAction" }),
6398 Schema.Struct({
6399 type: Schema.Literal("open_page").annotate({
6400 title: "OpenPageResponsesApiWebSearchActionType",
6401 }),
6402 url: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
6403 }).annotate({ title: "OpenPageResponsesApiWebSearchAction" }),
6404 Schema.Struct({
6405 pattern: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
6406 type: Schema.Literal("find_in_page").annotate({
6407 title: "FindInPageResponsesApiWebSearchActionType",
6408 }),
6409 url: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
6410 }).annotate({ title: "FindInPageResponsesApiWebSearchAction" }),
6411 Schema.Struct({
6412 type: Schema.Literal("other").annotate({ title: "OtherResponsesApiWebSearchActionType" }),
6413 }).annotate({ title: "OtherResponsesApiWebSearchAction" }),
6414 ],
6415 { mode: "oneOf" },
6416);
6417
6418export type V2ThreadResumeParams__SandboxMode =
6419 | "read-only"
6420 | "workspace-write"
6421 | "danger-full-access";
6422export const V2ThreadResumeParams__SandboxMode = Schema.Literals([
6423 "read-only",
6424 "workspace-write",
6425 "danger-full-access",
6426]);
6427
6428export type V2ThreadResumeParams__ServiceTier = "fast" | "flex";
6429export const V2ThreadResumeParams__ServiceTier = Schema.Literals(["fast", "flex"]);
6430
6431export type V2ThreadResumeResponse__AbsolutePathBuf = string;
6432export const V2ThreadResumeResponse__AbsolutePathBuf = Schema.String.annotate({
6433 description:
6434 "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.",
6435});
6436
6437export type V2ThreadResumeResponse__AgentPath = string;
6438export const V2ThreadResumeResponse__AgentPath = Schema.String;
6439
6440export type V2ThreadResumeResponse__AskForApproval =
6441 | "untrusted"
6442 | "on-failure"
6443 | "on-request"
6444 | "never"
6445 | {
6446 readonly granular: {
6447 readonly mcp_elicitations: boolean;
6448 readonly request_permissions?: boolean;
6449 readonly rules: boolean;
6450 readonly sandbox_approval: boolean;
6451 readonly skill_approval?: boolean;
6452 };
6453 };
6454export const V2ThreadResumeResponse__AskForApproval = Schema.Union(
6455 [
6456 Schema.Literals(["untrusted", "on-failure", "on-request", "never"]),
6457 Schema.Struct({
6458 granular: Schema.Struct({
6459 mcp_elicitations: Schema.Boolean,
6460 request_permissions: Schema.optionalKey(Schema.Boolean.annotate({ default: false })),
6461 rules: Schema.Boolean,
6462 sandbox_approval: Schema.Boolean,
6463 skill_approval: Schema.optionalKey(Schema.Boolean.annotate({ default: false })),
6464 }),
6465 }).annotate({ title: "GranularAskForApproval" }),
6466 ],
6467 { mode: "oneOf" },
6468);
6469
6470export type V2ThreadResumeResponse__CollabAgentStatus =
6471 | "pendingInit"
6472 | "running"
6473 | "interrupted"
6474 | "completed"
6475 | "errored"
6476 | "shutdown"
6477 | "notFound";
6478export const V2ThreadResumeResponse__CollabAgentStatus = Schema.Literals([
6479 "pendingInit",
6480 "running",
6481 "interrupted",
6482 "completed",
6483 "errored",
6484 "shutdown",
6485 "notFound",
6486]);
6487
6488export type V2ThreadResumeResponse__CommandAction =
6489 | {
6490 readonly command: string;
6491 readonly name: string;
6492 readonly path: string;
6493 readonly type: "read";
6494 }
6495 | { readonly command: string; readonly path?: string | null; readonly type: "listFiles" }
6496 | {
6497 readonly command: string;
6498 readonly path?: string | null;
6499 readonly query?: string | null;
6500 readonly type: "search";
6501 }
6502 | { readonly command: string; readonly type: "unknown" };
6503export const V2ThreadResumeResponse__CommandAction = Schema.Union(
6504 [
6505 Schema.Struct({
6506 command: Schema.String,
6507 name: Schema.String,
6508 path: Schema.String,
6509 type: Schema.Literal("read").annotate({ title: "ReadCommandActionType" }),
6510 }).annotate({ title: "ReadCommandAction" }),
6511 Schema.Struct({
6512 command: Schema.String,
6513 path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
6514 type: Schema.Literal("listFiles").annotate({ title: "ListFilesCommandActionType" }),
6515 }).annotate({ title: "ListFilesCommandAction" }),
6516 Schema.Struct({
6517 command: Schema.String,
6518 path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
6519 query: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
6520 type: Schema.Literal("search").annotate({ title: "SearchCommandActionType" }),
6521 }).annotate({ title: "SearchCommandAction" }),
6522 Schema.Struct({
6523 command: Schema.String,
6524 type: Schema.Literal("unknown").annotate({ title: "UnknownCommandActionType" }),
6525 }).annotate({ title: "UnknownCommandAction" }),
6526 ],
6527 { mode: "oneOf" },
6528);
6529
6530export type V2ThreadResumeResponse__CommandExecutionStatus =
6531 | "inProgress"
6532 | "completed"
6533 | "failed"
6534 | "declined";
6535export const V2ThreadResumeResponse__CommandExecutionStatus = Schema.Literals([
6536 "inProgress",
6537 "completed",
6538 "failed",
6539 "declined",
6540]);
6541
6542export type V2ThreadResumeResponse__DynamicToolCallOutputContentItem =
6543 | { readonly text: string; readonly type: "inputText" }
6544 | { readonly imageUrl: string; readonly type: "inputImage" };
6545export const V2ThreadResumeResponse__DynamicToolCallOutputContentItem = Schema.Union(
6546 [
6547 Schema.Struct({
6548 text: Schema.String,
6549 type: Schema.Literal("inputText").annotate({
6550 title: "InputTextDynamicToolCallOutputContentItemType",
6551 }),
6552 }).annotate({ title: "InputTextDynamicToolCallOutputContentItem" }),
6553 Schema.Struct({
6554 imageUrl: Schema.String,
6555 type: Schema.Literal("inputImage").annotate({
6556 title: "InputImageDynamicToolCallOutputContentItemType",
6557 }),
6558 }).annotate({ title: "InputImageDynamicToolCallOutputContentItem" }),
6559 ],
6560 { mode: "oneOf" },
6561);
6562
6563export type V2ThreadResumeResponse__DynamicToolCallStatus = "inProgress" | "completed" | "failed";
6564export const V2ThreadResumeResponse__DynamicToolCallStatus = Schema.Literals([
6565 "inProgress",
6566 "completed",
6567 "failed",
6568]);
6569
6570export type V2ThreadResumeResponse__GitInfo = {
6571 readonly branch?: string | null;
6572 readonly originUrl?: string | null;
6573 readonly sha?: string | null;
6574};
6575export const V2ThreadResumeResponse__GitInfo = Schema.Struct({
6576 branch: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
6577 originUrl: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
6578 sha: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
6579});
6580
6581export type V2ThreadResumeResponse__HookPromptFragment = {
6582 readonly hookRunId: string;
6583 readonly text: string;
6584};
6585export const V2ThreadResumeResponse__HookPromptFragment = Schema.Struct({
6586 hookRunId: Schema.String,
6587 text: Schema.String,
6588});
6589
6590export type V2ThreadResumeResponse__McpToolCallError = { readonly message: string };
6591export const V2ThreadResumeResponse__McpToolCallError = Schema.Struct({ message: Schema.String });
6592
6593export type V2ThreadResumeResponse__McpToolCallResult = {
6594 readonly _meta?: unknown;
6595 readonly content: ReadonlyArray<unknown>;
6596 readonly structuredContent?: unknown;
6597};
6598export const V2ThreadResumeResponse__McpToolCallResult = Schema.Struct({
6599 _meta: Schema.optionalKey(Schema.Unknown),
6600 content: Schema.Array(Schema.Unknown),
6601 structuredContent: Schema.optionalKey(Schema.Unknown),
6602});
6603
6604export type V2ThreadResumeResponse__McpToolCallStatus = "inProgress" | "completed" | "failed";
6605export const V2ThreadResumeResponse__McpToolCallStatus = Schema.Literals([
6606 "inProgress",
6607 "completed",
6608 "failed",
6609]);
6610
6611export type V2ThreadResumeResponse__MemoryCitationEntry = {
6612 readonly lineEnd: number;
6613 readonly lineStart: number;
6614 readonly note: string;
6615 readonly path: string;
6616};
6617export const V2ThreadResumeResponse__MemoryCitationEntry = Schema.Struct({
6618 lineEnd: Schema.Number.annotate({ format: "uint32" })
6619 .check(Schema.isInt())
6620 .check(Schema.isGreaterThanOrEqualTo(0)),
6621 lineStart: Schema.Number.annotate({ format: "uint32" })
6622 .check(Schema.isInt())
6623 .check(Schema.isGreaterThanOrEqualTo(0)),
6624 note: Schema.String,
6625 path: Schema.String,
6626});
6627
6628export type V2ThreadResumeResponse__MessagePhase = "commentary" | "final_answer";
6629export const V2ThreadResumeResponse__MessagePhase = Schema.Literals([
6630 "commentary",
6631 "final_answer",
6632]).annotate({
6633 description:
6634 '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.',
6635});
6636
6637export type V2ThreadResumeResponse__NonSteerableTurnKind = "review" | "compact";
6638export const V2ThreadResumeResponse__NonSteerableTurnKind = Schema.Literals(["review", "compact"]);
6639
6640export type V2ThreadResumeResponse__PatchApplyStatus =
6641 | "inProgress"
6642 | "completed"
6643 | "failed"
6644 | "declined";
6645export const V2ThreadResumeResponse__PatchApplyStatus = Schema.Literals([
6646 "inProgress",
6647 "completed",
6648 "failed",
6649 "declined",
6650]);
6651
6652export type V2ThreadResumeResponse__PatchChangeKind =
6653 | { readonly type: "add" }
6654 | { readonly type: "delete" }
6655 | { readonly move_path?: string | null; readonly type: "update" };
6656export const V2ThreadResumeResponse__PatchChangeKind = Schema.Union(
6657 [
6658 Schema.Struct({
6659 type: Schema.Literal("add").annotate({ title: "AddPatchChangeKindType" }),
6660 }).annotate({ title: "AddPatchChangeKind" }),
6661 Schema.Struct({
6662 type: Schema.Literal("delete").annotate({ title: "DeletePatchChangeKindType" }),
6663 }).annotate({ title: "DeletePatchChangeKind" }),
6664 Schema.Struct({
6665 move_path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
6666 type: Schema.Literal("update").annotate({ title: "UpdatePatchChangeKindType" }),
6667 }).annotate({ title: "UpdatePatchChangeKind" }),
6668 ],
6669 { mode: "oneOf" },
6670);
6671
6672export type V2ThreadResumeResponse__ReasoningEffort =
6673 | "none"
6674 | "minimal"
6675 | "low"
6676 | "medium"
6677 | "high"
6678 | "xhigh";
6679export const V2ThreadResumeResponse__ReasoningEffort = Schema.Literals([
6680 "none",
6681 "minimal",
6682 "low",
6683 "medium",
6684 "high",
6685 "xhigh",
6686]).annotate({
6687 description:
6688 "See https://platform.openai.com/docs/guides/reasoning?api-mode=responses#get-started-with-reasoning",
6689});
6690
6691export type V2ThreadResumeResponse__ServiceTier = "fast" | "flex";
6692export const V2ThreadResumeResponse__ServiceTier = Schema.Literals(["fast", "flex"]);
6693
6694export type V2ThreadResumeResponse__TextElement = {
6695 readonly byteRange: { readonly end: number; readonly start: number };
6696 readonly placeholder?: string | null;
6697};
6698export const V2ThreadResumeResponse__TextElement = Schema.Struct({
6699 byteRange: Schema.Struct({
6700 end: Schema.Number.annotate({ format: "uint" })
6701 .check(Schema.isInt())
6702 .check(Schema.isGreaterThanOrEqualTo(0)),
6703 start: Schema.Number.annotate({ format: "uint" })
6704 .check(Schema.isInt())
6705 .check(Schema.isGreaterThanOrEqualTo(0)),
6706 }).annotate({
6707 description: "Byte range in the parent `text` buffer that this element occupies.",
6708 }),
6709 placeholder: Schema.optionalKey(
6710 Schema.Union([
6711 Schema.String.annotate({
6712 description: "Optional human-readable placeholder for the element, displayed in the UI.",
6713 }),
6714 Schema.Null,
6715 ]),
6716 ),
6717});
6718
6719export type V2ThreadResumeResponse__ThreadActiveFlag = "waitingOnApproval" | "waitingOnUserInput";
6720export const V2ThreadResumeResponse__ThreadActiveFlag = Schema.Literals([
6721 "waitingOnApproval",
6722 "waitingOnUserInput",
6723]);
6724
6725export type V2ThreadResumeResponse__ThreadId = string;
6726export const V2ThreadResumeResponse__ThreadId = Schema.String;
6727
6728export type V2ThreadResumeResponse__TurnStatus =
6729 | "completed"
6730 | "interrupted"
6731 | "failed"
6732 | "inProgress";
6733export const V2ThreadResumeResponse__TurnStatus = Schema.Literals([
6734 "completed",
6735 "interrupted",
6736 "failed",
6737 "inProgress",
6738]);
6739
6740export type V2ThreadResumeResponse__WebSearchAction =
6741 | {
6742 readonly queries?: ReadonlyArray<string> | null;
6743 readonly query?: string | null;
6744 readonly type: "search";
6745 }
6746 | { readonly type: "openPage"; readonly url?: string | null }
6747 | { readonly pattern?: string | null; readonly type: "findInPage"; readonly url?: string | null }
6748 | { readonly type: "other" };
6749export const V2ThreadResumeResponse__WebSearchAction = Schema.Union(
6750 [
6751 Schema.Struct({
6752 queries: Schema.optionalKey(Schema.Union([Schema.Array(Schema.String), Schema.Null])),
6753 query: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
6754 type: Schema.Literal("search").annotate({ title: "SearchWebSearchActionType" }),
6755 }).annotate({ title: "SearchWebSearchAction" }),
6756 Schema.Struct({
6757 type: Schema.Literal("openPage").annotate({ title: "OpenPageWebSearchActionType" }),
6758 url: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
6759 }).annotate({ title: "OpenPageWebSearchAction" }),
6760 Schema.Struct({
6761 pattern: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
6762 type: Schema.Literal("findInPage").annotate({ title: "FindInPageWebSearchActionType" }),
6763 url: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
6764 }).annotate({ title: "FindInPageWebSearchAction" }),
6765 Schema.Struct({
6766 type: Schema.Literal("other").annotate({ title: "OtherWebSearchActionType" }),
6767 }).annotate({ title: "OtherWebSearchAction" }),
6768 ],
6769 { mode: "oneOf" },
6770);
6771
6772export type V2ThreadRollbackResponse__AgentPath = string;
6773export const V2ThreadRollbackResponse__AgentPath = Schema.String;
6774
6775export type V2ThreadRollbackResponse__CollabAgentStatus =
6776 | "pendingInit"
6777 | "running"
6778 | "interrupted"
6779 | "completed"
6780 | "errored"
6781 | "shutdown"
6782 | "notFound";
6783export const V2ThreadRollbackResponse__CollabAgentStatus = Schema.Literals([
6784 "pendingInit",
6785 "running",
6786 "interrupted",
6787 "completed",
6788 "errored",
6789 "shutdown",
6790 "notFound",
6791]);
6792
6793export type V2ThreadRollbackResponse__CommandAction =
6794 | {
6795 readonly command: string;
6796 readonly name: string;
6797 readonly path: string;
6798 readonly type: "read";
6799 }
6800 | { readonly command: string; readonly path?: string | null; readonly type: "listFiles" }
6801 | {
6802 readonly command: string;
6803 readonly path?: string | null;
6804 readonly query?: string | null;
6805 readonly type: "search";
6806 }
6807 | { readonly command: string; readonly type: "unknown" };
6808export const V2ThreadRollbackResponse__CommandAction = Schema.Union(
6809 [
6810 Schema.Struct({
6811 command: Schema.String,
6812 name: Schema.String,
6813 path: Schema.String,
6814 type: Schema.Literal("read").annotate({ title: "ReadCommandActionType" }),
6815 }).annotate({ title: "ReadCommandAction" }),
6816 Schema.Struct({
6817 command: Schema.String,
6818 path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
6819 type: Schema.Literal("listFiles").annotate({ title: "ListFilesCommandActionType" }),
6820 }).annotate({ title: "ListFilesCommandAction" }),
6821 Schema.Struct({
6822 command: Schema.String,
6823 path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
6824 query: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
6825 type: Schema.Literal("search").annotate({ title: "SearchCommandActionType" }),
6826 }).annotate({ title: "SearchCommandAction" }),
6827 Schema.Struct({
6828 command: Schema.String,
6829 type: Schema.Literal("unknown").annotate({ title: "UnknownCommandActionType" }),
6830 }).annotate({ title: "UnknownCommandAction" }),
6831 ],
6832 { mode: "oneOf" },
6833);
6834
6835export type V2ThreadRollbackResponse__CommandExecutionStatus =
6836 | "inProgress"
6837 | "completed"
6838 | "failed"
6839 | "declined";
6840export const V2ThreadRollbackResponse__CommandExecutionStatus = Schema.Literals([
6841 "inProgress",
6842 "completed",
6843 "failed",
6844 "declined",
6845]);
6846
6847export type V2ThreadRollbackResponse__DynamicToolCallOutputContentItem =
6848 | { readonly text: string; readonly type: "inputText" }
6849 | { readonly imageUrl: string; readonly type: "inputImage" };
6850export const V2ThreadRollbackResponse__DynamicToolCallOutputContentItem = Schema.Union(
6851 [
6852 Schema.Struct({
6853 text: Schema.String,
6854 type: Schema.Literal("inputText").annotate({
6855 title: "InputTextDynamicToolCallOutputContentItemType",
6856 }),
6857 }).annotate({ title: "InputTextDynamicToolCallOutputContentItem" }),
6858 Schema.Struct({
6859 imageUrl: Schema.String,
6860 type: Schema.Literal("inputImage").annotate({
6861 title: "InputImageDynamicToolCallOutputContentItemType",
6862 }),
6863 }).annotate({ title: "InputImageDynamicToolCallOutputContentItem" }),
6864 ],
6865 { mode: "oneOf" },
6866);
6867
6868export type V2ThreadRollbackResponse__DynamicToolCallStatus = "inProgress" | "completed" | "failed";
6869export const V2ThreadRollbackResponse__DynamicToolCallStatus = Schema.Literals([
6870 "inProgress",
6871 "completed",
6872 "failed",
6873]);
6874
6875export type V2ThreadRollbackResponse__GitInfo = {
6876 readonly branch?: string | null;
6877 readonly originUrl?: string | null;
6878 readonly sha?: string | null;
6879};
6880export const V2ThreadRollbackResponse__GitInfo = Schema.Struct({
6881 branch: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
6882 originUrl: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
6883 sha: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
6884});
6885
6886export type V2ThreadRollbackResponse__HookPromptFragment = {
6887 readonly hookRunId: string;
6888 readonly text: string;
6889};
6890export const V2ThreadRollbackResponse__HookPromptFragment = Schema.Struct({
6891 hookRunId: Schema.String,
6892 text: Schema.String,
6893});
6894
6895export type V2ThreadRollbackResponse__McpToolCallError = { readonly message: string };
6896export const V2ThreadRollbackResponse__McpToolCallError = Schema.Struct({ message: Schema.String });
6897
6898export type V2ThreadRollbackResponse__McpToolCallResult = {
6899 readonly _meta?: unknown;
6900 readonly content: ReadonlyArray<unknown>;
6901 readonly structuredContent?: unknown;
6902};
6903export const V2ThreadRollbackResponse__McpToolCallResult = Schema.Struct({
6904 _meta: Schema.optionalKey(Schema.Unknown),
6905 content: Schema.Array(Schema.Unknown),
6906 structuredContent: Schema.optionalKey(Schema.Unknown),
6907});
6908
6909export type V2ThreadRollbackResponse__McpToolCallStatus = "inProgress" | "completed" | "failed";
6910export const V2ThreadRollbackResponse__McpToolCallStatus = Schema.Literals([
6911 "inProgress",
6912 "completed",
6913 "failed",
6914]);
6915
6916export type V2ThreadRollbackResponse__MemoryCitationEntry = {
6917 readonly lineEnd: number;
6918 readonly lineStart: number;
6919 readonly note: string;
6920 readonly path: string;
6921};
6922export const V2ThreadRollbackResponse__MemoryCitationEntry = Schema.Struct({
6923 lineEnd: Schema.Number.annotate({ format: "uint32" })
6924 .check(Schema.isInt())
6925 .check(Schema.isGreaterThanOrEqualTo(0)),
6926 lineStart: Schema.Number.annotate({ format: "uint32" })
6927 .check(Schema.isInt())
6928 .check(Schema.isGreaterThanOrEqualTo(0)),
6929 note: Schema.String,
6930 path: Schema.String,
6931});
6932
6933export type V2ThreadRollbackResponse__MessagePhase = "commentary" | "final_answer";
6934export const V2ThreadRollbackResponse__MessagePhase = Schema.Literals([
6935 "commentary",
6936 "final_answer",
6937]).annotate({
6938 description:
6939 '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.',
6940});
6941
6942export type V2ThreadRollbackResponse__NonSteerableTurnKind = "review" | "compact";
6943export const V2ThreadRollbackResponse__NonSteerableTurnKind = Schema.Literals([
6944 "review",
6945 "compact",
6946]);
6947
6948export type V2ThreadRollbackResponse__PatchApplyStatus =
6949 | "inProgress"
6950 | "completed"
6951 | "failed"
6952 | "declined";
6953export const V2ThreadRollbackResponse__PatchApplyStatus = Schema.Literals([
6954 "inProgress",
6955 "completed",
6956 "failed",
6957 "declined",
6958]);
6959
6960export type V2ThreadRollbackResponse__PatchChangeKind =
6961 | { readonly type: "add" }
6962 | { readonly type: "delete" }
6963 | { readonly move_path?: string | null; readonly type: "update" };
6964export const V2ThreadRollbackResponse__PatchChangeKind = Schema.Union(
6965 [
6966 Schema.Struct({
6967 type: Schema.Literal("add").annotate({ title: "AddPatchChangeKindType" }),
6968 }).annotate({ title: "AddPatchChangeKind" }),
6969 Schema.Struct({
6970 type: Schema.Literal("delete").annotate({ title: "DeletePatchChangeKindType" }),
6971 }).annotate({ title: "DeletePatchChangeKind" }),
6972 Schema.Struct({
6973 move_path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
6974 type: Schema.Literal("update").annotate({ title: "UpdatePatchChangeKindType" }),
6975 }).annotate({ title: "UpdatePatchChangeKind" }),
6976 ],
6977 { mode: "oneOf" },
6978);
6979
6980export type V2ThreadRollbackResponse__ReasoningEffort =
6981 | "none"
6982 | "minimal"
6983 | "low"
6984 | "medium"
6985 | "high"
6986 | "xhigh";
6987export const V2ThreadRollbackResponse__ReasoningEffort = Schema.Literals([
6988 "none",
6989 "minimal",
6990 "low",
6991 "medium",
6992 "high",
6993 "xhigh",
6994]).annotate({
6995 description:
6996 "See https://platform.openai.com/docs/guides/reasoning?api-mode=responses#get-started-with-reasoning",
6997});
6998
6999export type V2ThreadRollbackResponse__TextElement = {
7000 readonly byteRange: { readonly end: number; readonly start: number };
7001 readonly placeholder?: string | null;
7002};
7003export const V2ThreadRollbackResponse__TextElement = Schema.Struct({
7004 byteRange: Schema.Struct({
7005 end: Schema.Number.annotate({ format: "uint" })
7006 .check(Schema.isInt())
7007 .check(Schema.isGreaterThanOrEqualTo(0)),
7008 start: Schema.Number.annotate({ format: "uint" })
7009 .check(Schema.isInt())
7010 .check(Schema.isGreaterThanOrEqualTo(0)),
7011 }).annotate({
7012 description: "Byte range in the parent `text` buffer that this element occupies.",
7013 }),
7014 placeholder: Schema.optionalKey(
7015 Schema.Union([
7016 Schema.String.annotate({
7017 description: "Optional human-readable placeholder for the element, displayed in the UI.",
7018 }),
7019 Schema.Null,
7020 ]),
7021 ),
7022});
7023
7024export type V2ThreadRollbackResponse__ThreadActiveFlag = "waitingOnApproval" | "waitingOnUserInput";
7025export const V2ThreadRollbackResponse__ThreadActiveFlag = Schema.Literals([
7026 "waitingOnApproval",
7027 "waitingOnUserInput",
7028]);
7029
7030export type V2ThreadRollbackResponse__ThreadId = string;
7031export const V2ThreadRollbackResponse__ThreadId = Schema.String;
7032
7033export type V2ThreadRollbackResponse__TurnStatus =
7034 | "completed"
7035 | "interrupted"
7036 | "failed"
7037 | "inProgress";
7038export const V2ThreadRollbackResponse__TurnStatus = Schema.Literals([
7039 "completed",
7040 "interrupted",
7041 "failed",
7042 "inProgress",
7043]);
7044
7045export type V2ThreadRollbackResponse__WebSearchAction =
7046 | {
7047 readonly queries?: ReadonlyArray<string> | null;
7048 readonly query?: string | null;
7049 readonly type: "search";
7050 }
7051 | { readonly type: "openPage"; readonly url?: string | null }
7052 | { readonly pattern?: string | null; readonly type: "findInPage"; readonly url?: string | null }
7053 | { readonly type: "other" };
7054export const V2ThreadRollbackResponse__WebSearchAction = Schema.Union(
7055 [
7056 Schema.Struct({
7057 queries: Schema.optionalKey(Schema.Union([Schema.Array(Schema.String), Schema.Null])),
7058 query: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
7059 type: Schema.Literal("search").annotate({ title: "SearchWebSearchActionType" }),
7060 }).annotate({ title: "SearchWebSearchAction" }),
7061 Schema.Struct({
7062 type: Schema.Literal("openPage").annotate({ title: "OpenPageWebSearchActionType" }),
7063 url: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
7064 }).annotate({ title: "OpenPageWebSearchAction" }),
7065 Schema.Struct({
7066 pattern: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
7067 type: Schema.Literal("findInPage").annotate({ title: "FindInPageWebSearchActionType" }),
7068 url: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
7069 }).annotate({ title: "FindInPageWebSearchAction" }),
7070 Schema.Struct({
7071 type: Schema.Literal("other").annotate({ title: "OtherWebSearchActionType" }),
7072 }).annotate({ title: "OtherWebSearchAction" }),
7073 ],
7074 { mode: "oneOf" },
7075);
7076
7077export type V2ThreadStartedNotification__AgentPath = string;
7078export const V2ThreadStartedNotification__AgentPath = Schema.String;
7079
7080export type V2ThreadStartedNotification__CollabAgentStatus =
7081 | "pendingInit"
7082 | "running"
7083 | "interrupted"
7084 | "completed"
7085 | "errored"
7086 | "shutdown"
7087 | "notFound";
7088export const V2ThreadStartedNotification__CollabAgentStatus = Schema.Literals([
7089 "pendingInit",
7090 "running",
7091 "interrupted",
7092 "completed",
7093 "errored",
7094 "shutdown",
7095 "notFound",
7096]);
7097
7098export type V2ThreadStartedNotification__CommandAction =
7099 | {
7100 readonly command: string;
7101 readonly name: string;
7102 readonly path: string;
7103 readonly type: "read";
7104 }
7105 | { readonly command: string; readonly path?: string | null; readonly type: "listFiles" }
7106 | {
7107 readonly command: string;
7108 readonly path?: string | null;
7109 readonly query?: string | null;
7110 readonly type: "search";
7111 }
7112 | { readonly command: string; readonly type: "unknown" };
7113export const V2ThreadStartedNotification__CommandAction = Schema.Union(
7114 [
7115 Schema.Struct({
7116 command: Schema.String,
7117 name: Schema.String,
7118 path: Schema.String,
7119 type: Schema.Literal("read").annotate({ title: "ReadCommandActionType" }),
7120 }).annotate({ title: "ReadCommandAction" }),
7121 Schema.Struct({
7122 command: Schema.String,
7123 path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
7124 type: Schema.Literal("listFiles").annotate({ title: "ListFilesCommandActionType" }),
7125 }).annotate({ title: "ListFilesCommandAction" }),
7126 Schema.Struct({
7127 command: Schema.String,
7128 path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
7129 query: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
7130 type: Schema.Literal("search").annotate({ title: "SearchCommandActionType" }),
7131 }).annotate({ title: "SearchCommandAction" }),
7132 Schema.Struct({
7133 command: Schema.String,
7134 type: Schema.Literal("unknown").annotate({ title: "UnknownCommandActionType" }),
7135 }).annotate({ title: "UnknownCommandAction" }),
7136 ],
7137 { mode: "oneOf" },
7138);
7139
7140export type V2ThreadStartedNotification__CommandExecutionStatus =
7141 | "inProgress"
7142 | "completed"
7143 | "failed"
7144 | "declined";
7145export const V2ThreadStartedNotification__CommandExecutionStatus = Schema.Literals([
7146 "inProgress",
7147 "completed",
7148 "failed",
7149 "declined",
7150]);
7151
7152export type V2ThreadStartedNotification__DynamicToolCallOutputContentItem =
7153 | { readonly text: string; readonly type: "inputText" }
7154 | { readonly imageUrl: string; readonly type: "inputImage" };
7155export const V2ThreadStartedNotification__DynamicToolCallOutputContentItem = Schema.Union(
7156 [
7157 Schema.Struct({
7158 text: Schema.String,
7159 type: Schema.Literal("inputText").annotate({
7160 title: "InputTextDynamicToolCallOutputContentItemType",
7161 }),
7162 }).annotate({ title: "InputTextDynamicToolCallOutputContentItem" }),
7163 Schema.Struct({
7164 imageUrl: Schema.String,
7165 type: Schema.Literal("inputImage").annotate({
7166 title: "InputImageDynamicToolCallOutputContentItemType",
7167 }),
7168 }).annotate({ title: "InputImageDynamicToolCallOutputContentItem" }),
7169 ],
7170 { mode: "oneOf" },
7171);
7172
7173export type V2ThreadStartedNotification__DynamicToolCallStatus =
7174 | "inProgress"
7175 | "completed"
7176 | "failed";
7177export const V2ThreadStartedNotification__DynamicToolCallStatus = Schema.Literals([
7178 "inProgress",
7179 "completed",
7180 "failed",
7181]);
7182
7183export type V2ThreadStartedNotification__GitInfo = {
7184 readonly branch?: string | null;
7185 readonly originUrl?: string | null;
7186 readonly sha?: string | null;
7187};
7188export const V2ThreadStartedNotification__GitInfo = Schema.Struct({
7189 branch: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
7190 originUrl: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
7191 sha: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
7192});
7193
7194export type V2ThreadStartedNotification__HookPromptFragment = {
7195 readonly hookRunId: string;
7196 readonly text: string;
7197};
7198export const V2ThreadStartedNotification__HookPromptFragment = Schema.Struct({
7199 hookRunId: Schema.String,
7200 text: Schema.String,
7201});
7202
7203export type V2ThreadStartedNotification__McpToolCallError = { readonly message: string };
7204export const V2ThreadStartedNotification__McpToolCallError = Schema.Struct({
7205 message: Schema.String,
7206});
7207
7208export type V2ThreadStartedNotification__McpToolCallResult = {
7209 readonly _meta?: unknown;
7210 readonly content: ReadonlyArray<unknown>;
7211 readonly structuredContent?: unknown;
7212};
7213export const V2ThreadStartedNotification__McpToolCallResult = Schema.Struct({
7214 _meta: Schema.optionalKey(Schema.Unknown),
7215 content: Schema.Array(Schema.Unknown),
7216 structuredContent: Schema.optionalKey(Schema.Unknown),
7217});
7218
7219export type V2ThreadStartedNotification__McpToolCallStatus = "inProgress" | "completed" | "failed";
7220export const V2ThreadStartedNotification__McpToolCallStatus = Schema.Literals([
7221 "inProgress",
7222 "completed",
7223 "failed",
7224]);
7225
7226export type V2ThreadStartedNotification__MemoryCitationEntry = {
7227 readonly lineEnd: number;
7228 readonly lineStart: number;
7229 readonly note: string;
7230 readonly path: string;
7231};
7232export const V2ThreadStartedNotification__MemoryCitationEntry = Schema.Struct({
7233 lineEnd: Schema.Number.annotate({ format: "uint32" })
7234 .check(Schema.isInt())
7235 .check(Schema.isGreaterThanOrEqualTo(0)),
7236 lineStart: Schema.Number.annotate({ format: "uint32" })
7237 .check(Schema.isInt())
7238 .check(Schema.isGreaterThanOrEqualTo(0)),
7239 note: Schema.String,
7240 path: Schema.String,
7241});
7242
7243export type V2ThreadStartedNotification__MessagePhase = "commentary" | "final_answer";
7244export const V2ThreadStartedNotification__MessagePhase = Schema.Literals([
7245 "commentary",
7246 "final_answer",
7247]).annotate({
7248 description:
7249 '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.',
7250});
7251
7252export type V2ThreadStartedNotification__NonSteerableTurnKind = "review" | "compact";
7253export const V2ThreadStartedNotification__NonSteerableTurnKind = Schema.Literals([
7254 "review",
7255 "compact",
7256]);
7257
7258export type V2ThreadStartedNotification__PatchApplyStatus =
7259 | "inProgress"
7260 | "completed"
7261 | "failed"
7262 | "declined";
7263export const V2ThreadStartedNotification__PatchApplyStatus = Schema.Literals([
7264 "inProgress",
7265 "completed",
7266 "failed",
7267 "declined",
7268]);
7269
7270export type V2ThreadStartedNotification__PatchChangeKind =
7271 | { readonly type: "add" }
7272 | { readonly type: "delete" }
7273 | { readonly move_path?: string | null; readonly type: "update" };
7274export const V2ThreadStartedNotification__PatchChangeKind = Schema.Union(
7275 [
7276 Schema.Struct({
7277 type: Schema.Literal("add").annotate({ title: "AddPatchChangeKindType" }),
7278 }).annotate({ title: "AddPatchChangeKind" }),
7279 Schema.Struct({
7280 type: Schema.Literal("delete").annotate({ title: "DeletePatchChangeKindType" }),
7281 }).annotate({ title: "DeletePatchChangeKind" }),
7282 Schema.Struct({
7283 move_path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
7284 type: Schema.Literal("update").annotate({ title: "UpdatePatchChangeKindType" }),
7285 }).annotate({ title: "UpdatePatchChangeKind" }),
7286 ],
7287 { mode: "oneOf" },
7288);
7289
7290export type V2ThreadStartedNotification__ReasoningEffort =
7291 | "none"
7292 | "minimal"
7293 | "low"
7294 | "medium"
7295 | "high"
7296 | "xhigh";
7297export const V2ThreadStartedNotification__ReasoningEffort = Schema.Literals([
7298 "none",
7299 "minimal",
7300 "low",
7301 "medium",
7302 "high",
7303 "xhigh",
7304]).annotate({
7305 description:
7306 "See https://platform.openai.com/docs/guides/reasoning?api-mode=responses#get-started-with-reasoning",
7307});
7308
7309export type V2ThreadStartedNotification__TextElement = {
7310 readonly byteRange: { readonly end: number; readonly start: number };
7311 readonly placeholder?: string | null;
7312};
7313export const V2ThreadStartedNotification__TextElement = Schema.Struct({
7314 byteRange: Schema.Struct({
7315 end: Schema.Number.annotate({ format: "uint" })
7316 .check(Schema.isInt())
7317 .check(Schema.isGreaterThanOrEqualTo(0)),
7318 start: Schema.Number.annotate({ format: "uint" })
7319 .check(Schema.isInt())
7320 .check(Schema.isGreaterThanOrEqualTo(0)),
7321 }).annotate({
7322 description: "Byte range in the parent `text` buffer that this element occupies.",
7323 }),
7324 placeholder: Schema.optionalKey(
7325 Schema.Union([
7326 Schema.String.annotate({
7327 description: "Optional human-readable placeholder for the element, displayed in the UI.",
7328 }),
7329 Schema.Null,
7330 ]),
7331 ),
7332});
7333
7334export type V2ThreadStartedNotification__ThreadActiveFlag =
7335 | "waitingOnApproval"
7336 | "waitingOnUserInput";
7337export const V2ThreadStartedNotification__ThreadActiveFlag = Schema.Literals([
7338 "waitingOnApproval",
7339 "waitingOnUserInput",
7340]);
7341
7342export type V2ThreadStartedNotification__ThreadId = string;
7343export const V2ThreadStartedNotification__ThreadId = Schema.String;
7344
7345export type V2ThreadStartedNotification__TurnStatus =
7346 | "completed"
7347 | "interrupted"
7348 | "failed"
7349 | "inProgress";
7350export const V2ThreadStartedNotification__TurnStatus = Schema.Literals([
7351 "completed",
7352 "interrupted",
7353 "failed",
7354 "inProgress",
7355]);
7356
7357export type V2ThreadStartedNotification__WebSearchAction =
7358 | {
7359 readonly queries?: ReadonlyArray<string> | null;
7360 readonly query?: string | null;
7361 readonly type: "search";
7362 }
7363 | { readonly type: "openPage"; readonly url?: string | null }
7364 | { readonly pattern?: string | null; readonly type: "findInPage"; readonly url?: string | null }
7365 | { readonly type: "other" };
7366export const V2ThreadStartedNotification__WebSearchAction = Schema.Union(
7367 [
7368 Schema.Struct({
7369 queries: Schema.optionalKey(Schema.Union([Schema.Array(Schema.String), Schema.Null])),
7370 query: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
7371 type: Schema.Literal("search").annotate({ title: "SearchWebSearchActionType" }),
7372 }).annotate({ title: "SearchWebSearchAction" }),
7373 Schema.Struct({
7374 type: Schema.Literal("openPage").annotate({ title: "OpenPageWebSearchActionType" }),
7375 url: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
7376 }).annotate({ title: "OpenPageWebSearchAction" }),
7377 Schema.Struct({
7378 pattern: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
7379 type: Schema.Literal("findInPage").annotate({ title: "FindInPageWebSearchActionType" }),
7380 url: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
7381 }).annotate({ title: "FindInPageWebSearchAction" }),
7382 Schema.Struct({
7383 type: Schema.Literal("other").annotate({ title: "OtherWebSearchActionType" }),
7384 }).annotate({ title: "OtherWebSearchAction" }),
7385 ],
7386 { mode: "oneOf" },
7387);
7388
7389export type V2ThreadStartParams__ApprovalsReviewer = "user" | "guardian_subagent";
7390export const V2ThreadStartParams__ApprovalsReviewer = Schema.Literals([
7391 "user",
7392 "guardian_subagent",
7393]).annotate({
7394 description:
7395 "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.",
7396});
7397
7398export type V2ThreadStartParams__AskForApproval =
7399 | "untrusted"
7400 | "on-failure"
7401 | "on-request"
7402 | "never"
7403 | {
7404 readonly granular: {
7405 readonly mcp_elicitations: boolean;
7406 readonly request_permissions?: boolean;
7407 readonly rules: boolean;
7408 readonly sandbox_approval: boolean;
7409 readonly skill_approval?: boolean;
7410 };
7411 };
7412export const V2ThreadStartParams__AskForApproval = Schema.Union(
7413 [
7414 Schema.Literals(["untrusted", "on-failure", "on-request", "never"]),
7415 Schema.Struct({
7416 granular: Schema.Struct({
7417 mcp_elicitations: Schema.Boolean,
7418 request_permissions: Schema.optionalKey(Schema.Boolean.annotate({ default: false })),
7419 rules: Schema.Boolean,
7420 sandbox_approval: Schema.Boolean,
7421 skill_approval: Schema.optionalKey(Schema.Boolean.annotate({ default: false })),
7422 }),
7423 }).annotate({ title: "GranularAskForApproval" }),
7424 ],
7425 { mode: "oneOf" },
7426);
7427
7428export type V2ThreadStartParams__Personality = "none" | "friendly" | "pragmatic";
7429export const V2ThreadStartParams__Personality = Schema.Literals(["none", "friendly", "pragmatic"]);
7430
7431export type V2ThreadStartParams__SandboxMode =
7432 | "read-only"
7433 | "workspace-write"
7434 | "danger-full-access";
7435export const V2ThreadStartParams__SandboxMode = Schema.Literals([
7436 "read-only",
7437 "workspace-write",
7438 "danger-full-access",
7439]);
7440
7441export type V2ThreadStartParams__ServiceTier = "fast" | "flex";
7442export const V2ThreadStartParams__ServiceTier = Schema.Literals(["fast", "flex"]);
7443
7444export type V2ThreadStartParams__ThreadStartSource = "startup" | "clear";
7445export const V2ThreadStartParams__ThreadStartSource = Schema.Literals(["startup", "clear"]);
7446
7447export type V2ThreadStartResponse__AbsolutePathBuf = string;
7448export const V2ThreadStartResponse__AbsolutePathBuf = Schema.String.annotate({
7449 description:
7450 "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.",
7451});
7452
7453export type V2ThreadStartResponse__AgentPath = string;
7454export const V2ThreadStartResponse__AgentPath = Schema.String;
7455
7456export type V2ThreadStartResponse__AskForApproval =
7457 | "untrusted"
7458 | "on-failure"
7459 | "on-request"
7460 | "never"
7461 | {
7462 readonly granular: {
7463 readonly mcp_elicitations: boolean;
7464 readonly request_permissions?: boolean;
7465 readonly rules: boolean;
7466 readonly sandbox_approval: boolean;
7467 readonly skill_approval?: boolean;
7468 };
7469 };
7470export const V2ThreadStartResponse__AskForApproval = Schema.Union(
7471 [
7472 Schema.Literals(["untrusted", "on-failure", "on-request", "never"]),
7473 Schema.Struct({
7474 granular: Schema.Struct({
7475 mcp_elicitations: Schema.Boolean,
7476 request_permissions: Schema.optionalKey(Schema.Boolean.annotate({ default: false })),
7477 rules: Schema.Boolean,
7478 sandbox_approval: Schema.Boolean,
7479 skill_approval: Schema.optionalKey(Schema.Boolean.annotate({ default: false })),
7480 }),
7481 }).annotate({ title: "GranularAskForApproval" }),
7482 ],
7483 { mode: "oneOf" },
7484);
7485
7486export type V2ThreadStartResponse__CollabAgentStatus =
7487 | "pendingInit"
7488 | "running"
7489 | "interrupted"
7490 | "completed"
7491 | "errored"
7492 | "shutdown"
7493 | "notFound";
7494export const V2ThreadStartResponse__CollabAgentStatus = Schema.Literals([
7495 "pendingInit",
7496 "running",
7497 "interrupted",
7498 "completed",
7499 "errored",
7500 "shutdown",
7501 "notFound",
7502]);
7503
7504export type V2ThreadStartResponse__CommandAction =
7505 | {
7506 readonly command: string;
7507 readonly name: string;
7508 readonly path: string;
7509 readonly type: "read";
7510 }
7511 | { readonly command: string; readonly path?: string | null; readonly type: "listFiles" }
7512 | {
7513 readonly command: string;
7514 readonly path?: string | null;
7515 readonly query?: string | null;
7516 readonly type: "search";
7517 }
7518 | { readonly command: string; readonly type: "unknown" };
7519export const V2ThreadStartResponse__CommandAction = Schema.Union(
7520 [
7521 Schema.Struct({
7522 command: Schema.String,
7523 name: Schema.String,
7524 path: Schema.String,
7525 type: Schema.Literal("read").annotate({ title: "ReadCommandActionType" }),
7526 }).annotate({ title: "ReadCommandAction" }),
7527 Schema.Struct({
7528 command: Schema.String,
7529 path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
7530 type: Schema.Literal("listFiles").annotate({ title: "ListFilesCommandActionType" }),
7531 }).annotate({ title: "ListFilesCommandAction" }),
7532 Schema.Struct({
7533 command: Schema.String,
7534 path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
7535 query: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
7536 type: Schema.Literal("search").annotate({ title: "SearchCommandActionType" }),
7537 }).annotate({ title: "SearchCommandAction" }),
7538 Schema.Struct({
7539 command: Schema.String,
7540 type: Schema.Literal("unknown").annotate({ title: "UnknownCommandActionType" }),
7541 }).annotate({ title: "UnknownCommandAction" }),
7542 ],
7543 { mode: "oneOf" },
7544);
7545
7546export type V2ThreadStartResponse__CommandExecutionStatus =
7547 | "inProgress"
7548 | "completed"
7549 | "failed"
7550 | "declined";
7551export const V2ThreadStartResponse__CommandExecutionStatus = Schema.Literals([
7552 "inProgress",
7553 "completed",
7554 "failed",
7555 "declined",
7556]);
7557
7558export type V2ThreadStartResponse__DynamicToolCallOutputContentItem =
7559 | { readonly text: string; readonly type: "inputText" }
7560 | { readonly imageUrl: string; readonly type: "inputImage" };
7561export const V2ThreadStartResponse__DynamicToolCallOutputContentItem = Schema.Union(
7562 [
7563 Schema.Struct({
7564 text: Schema.String,
7565 type: Schema.Literal("inputText").annotate({
7566 title: "InputTextDynamicToolCallOutputContentItemType",
7567 }),
7568 }).annotate({ title: "InputTextDynamicToolCallOutputContentItem" }),
7569 Schema.Struct({
7570 imageUrl: Schema.String,
7571 type: Schema.Literal("inputImage").annotate({
7572 title: "InputImageDynamicToolCallOutputContentItemType",
7573 }),
7574 }).annotate({ title: "InputImageDynamicToolCallOutputContentItem" }),
7575 ],
7576 { mode: "oneOf" },
7577);
7578
7579export type V2ThreadStartResponse__DynamicToolCallStatus = "inProgress" | "completed" | "failed";
7580export const V2ThreadStartResponse__DynamicToolCallStatus = Schema.Literals([
7581 "inProgress",
7582 "completed",
7583 "failed",
7584]);
7585
7586export type V2ThreadStartResponse__GitInfo = {
7587 readonly branch?: string | null;
7588 readonly originUrl?: string | null;
7589 readonly sha?: string | null;
7590};
7591export const V2ThreadStartResponse__GitInfo = Schema.Struct({
7592 branch: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
7593 originUrl: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
7594 sha: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
7595});
7596
7597export type V2ThreadStartResponse__HookPromptFragment = {
7598 readonly hookRunId: string;
7599 readonly text: string;
7600};
7601export const V2ThreadStartResponse__HookPromptFragment = Schema.Struct({
7602 hookRunId: Schema.String,
7603 text: Schema.String,
7604});
7605
7606export type V2ThreadStartResponse__McpToolCallError = { readonly message: string };
7607export const V2ThreadStartResponse__McpToolCallError = Schema.Struct({ message: Schema.String });
7608
7609export type V2ThreadStartResponse__McpToolCallResult = {
7610 readonly _meta?: unknown;
7611 readonly content: ReadonlyArray<unknown>;
7612 readonly structuredContent?: unknown;
7613};
7614export const V2ThreadStartResponse__McpToolCallResult = Schema.Struct({
7615 _meta: Schema.optionalKey(Schema.Unknown),
7616 content: Schema.Array(Schema.Unknown),
7617 structuredContent: Schema.optionalKey(Schema.Unknown),
7618});
7619
7620export type V2ThreadStartResponse__McpToolCallStatus = "inProgress" | "completed" | "failed";
7621export const V2ThreadStartResponse__McpToolCallStatus = Schema.Literals([
7622 "inProgress",
7623 "completed",
7624 "failed",
7625]);
7626
7627export type V2ThreadStartResponse__MemoryCitationEntry = {
7628 readonly lineEnd: number;
7629 readonly lineStart: number;
7630 readonly note: string;
7631 readonly path: string;
7632};
7633export const V2ThreadStartResponse__MemoryCitationEntry = Schema.Struct({
7634 lineEnd: Schema.Number.annotate({ format: "uint32" })
7635 .check(Schema.isInt())
7636 .check(Schema.isGreaterThanOrEqualTo(0)),
7637 lineStart: Schema.Number.annotate({ format: "uint32" })
7638 .check(Schema.isInt())
7639 .check(Schema.isGreaterThanOrEqualTo(0)),
7640 note: Schema.String,
7641 path: Schema.String,
7642});
7643
7644export type V2ThreadStartResponse__MessagePhase = "commentary" | "final_answer";
7645export const V2ThreadStartResponse__MessagePhase = Schema.Literals([
7646 "commentary",
7647 "final_answer",
7648]).annotate({
7649 description:
7650 '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.',
7651});
7652
7653export type V2ThreadStartResponse__NonSteerableTurnKind = "review" | "compact";
7654export const V2ThreadStartResponse__NonSteerableTurnKind = Schema.Literals(["review", "compact"]);
7655
7656export type V2ThreadStartResponse__PatchApplyStatus =
7657 | "inProgress"
7658 | "completed"
7659 | "failed"
7660 | "declined";
7661export const V2ThreadStartResponse__PatchApplyStatus = Schema.Literals([
7662 "inProgress",
7663 "completed",
7664 "failed",
7665 "declined",
7666]);
7667
7668export type V2ThreadStartResponse__PatchChangeKind =
7669 | { readonly type: "add" }
7670 | { readonly type: "delete" }
7671 | { readonly move_path?: string | null; readonly type: "update" };
7672export const V2ThreadStartResponse__PatchChangeKind = Schema.Union(
7673 [
7674 Schema.Struct({
7675 type: Schema.Literal("add").annotate({ title: "AddPatchChangeKindType" }),
7676 }).annotate({ title: "AddPatchChangeKind" }),
7677 Schema.Struct({
7678 type: Schema.Literal("delete").annotate({ title: "DeletePatchChangeKindType" }),
7679 }).annotate({ title: "DeletePatchChangeKind" }),
7680 Schema.Struct({
7681 move_path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
7682 type: Schema.Literal("update").annotate({ title: "UpdatePatchChangeKindType" }),
7683 }).annotate({ title: "UpdatePatchChangeKind" }),
7684 ],
7685 { mode: "oneOf" },
7686);
7687
7688export type V2ThreadStartResponse__ReasoningEffort =
7689 | "none"
7690 | "minimal"
7691 | "low"
7692 | "medium"
7693 | "high"
7694 | "xhigh";
7695export const V2ThreadStartResponse__ReasoningEffort = Schema.Literals([
7696 "none",
7697 "minimal",
7698 "low",
7699 "medium",
7700 "high",
7701 "xhigh",
7702]).annotate({
7703 description:
7704 "See https://platform.openai.com/docs/guides/reasoning?api-mode=responses#get-started-with-reasoning",
7705});
7706
7707export type V2ThreadStartResponse__ServiceTier = "fast" | "flex";
7708export const V2ThreadStartResponse__ServiceTier = Schema.Literals(["fast", "flex"]);
7709
7710export type V2ThreadStartResponse__TextElement = {
7711 readonly byteRange: { readonly end: number; readonly start: number };
7712 readonly placeholder?: string | null;
7713};
7714export const V2ThreadStartResponse__TextElement = Schema.Struct({
7715 byteRange: Schema.Struct({
7716 end: Schema.Number.annotate({ format: "uint" })
7717 .check(Schema.isInt())
7718 .check(Schema.isGreaterThanOrEqualTo(0)),
7719 start: Schema.Number.annotate({ format: "uint" })
7720 .check(Schema.isInt())
7721 .check(Schema.isGreaterThanOrEqualTo(0)),
7722 }).annotate({
7723 description: "Byte range in the parent `text` buffer that this element occupies.",
7724 }),
7725 placeholder: Schema.optionalKey(
7726 Schema.Union([
7727 Schema.String.annotate({
7728 description: "Optional human-readable placeholder for the element, displayed in the UI.",
7729 }),
7730 Schema.Null,
7731 ]),
7732 ),
7733});
7734
7735export type V2ThreadStartResponse__ThreadActiveFlag = "waitingOnApproval" | "waitingOnUserInput";
7736export const V2ThreadStartResponse__ThreadActiveFlag = Schema.Literals([
7737 "waitingOnApproval",
7738 "waitingOnUserInput",
7739]);
7740
7741export type V2ThreadStartResponse__ThreadId = string;
7742export const V2ThreadStartResponse__ThreadId = Schema.String;
7743
7744export type V2ThreadStartResponse__TurnStatus =
7745 | "completed"
7746 | "interrupted"
7747 | "failed"
7748 | "inProgress";
7749export const V2ThreadStartResponse__TurnStatus = Schema.Literals([
7750 "completed",
7751 "interrupted",
7752 "failed",
7753 "inProgress",
7754]);
7755
7756export type V2ThreadStartResponse__WebSearchAction =
7757 | {
7758 readonly queries?: ReadonlyArray<string> | null;
7759 readonly query?: string | null;
7760 readonly type: "search";
7761 }
7762 | { readonly type: "openPage"; readonly url?: string | null }
7763 | { readonly pattern?: string | null; readonly type: "findInPage"; readonly url?: string | null }
7764 | { readonly type: "other" };
7765export const V2ThreadStartResponse__WebSearchAction = Schema.Union(
7766 [
7767 Schema.Struct({
7768 queries: Schema.optionalKey(Schema.Union([Schema.Array(Schema.String), Schema.Null])),
7769 query: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
7770 type: Schema.Literal("search").annotate({ title: "SearchWebSearchActionType" }),
7771 }).annotate({ title: "SearchWebSearchAction" }),
7772 Schema.Struct({
7773 type: Schema.Literal("openPage").annotate({ title: "OpenPageWebSearchActionType" }),
7774 url: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
7775 }).annotate({ title: "OpenPageWebSearchAction" }),
7776 Schema.Struct({
7777 pattern: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
7778 type: Schema.Literal("findInPage").annotate({ title: "FindInPageWebSearchActionType" }),
7779 url: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
7780 }).annotate({ title: "FindInPageWebSearchAction" }),
7781 Schema.Struct({
7782 type: Schema.Literal("other").annotate({ title: "OtherWebSearchActionType" }),
7783 }).annotate({ title: "OtherWebSearchAction" }),
7784 ],
7785 { mode: "oneOf" },
7786);
7787
7788export type V2ThreadStatusChangedNotification__ThreadActiveFlag =
7789 | "waitingOnApproval"
7790 | "waitingOnUserInput";
7791export const V2ThreadStatusChangedNotification__ThreadActiveFlag = Schema.Literals([
7792 "waitingOnApproval",
7793 "waitingOnUserInput",
7794]);
7795
7796export type V2ThreadTokenUsageUpdatedNotification__TokenUsageBreakdown = {
7797 readonly cachedInputTokens: number;
7798 readonly inputTokens: number;
7799 readonly outputTokens: number;
7800 readonly reasoningOutputTokens: number;
7801 readonly totalTokens: number;
7802};
7803export const V2ThreadTokenUsageUpdatedNotification__TokenUsageBreakdown = Schema.Struct({
7804 cachedInputTokens: Schema.Number.annotate({ format: "int64" }).check(Schema.isInt()),
7805 inputTokens: Schema.Number.annotate({ format: "int64" }).check(Schema.isInt()),
7806 outputTokens: Schema.Number.annotate({ format: "int64" }).check(Schema.isInt()),
7807 reasoningOutputTokens: Schema.Number.annotate({ format: "int64" }).check(Schema.isInt()),
7808 totalTokens: Schema.Number.annotate({ format: "int64" }).check(Schema.isInt()),
7809});
7810
7811export type V2ThreadUnarchiveResponse__AgentPath = string;
7812export const V2ThreadUnarchiveResponse__AgentPath = Schema.String;
7813
7814export type V2ThreadUnarchiveResponse__CollabAgentStatus =
7815 | "pendingInit"
7816 | "running"
7817 | "interrupted"
7818 | "completed"
7819 | "errored"
7820 | "shutdown"
7821 | "notFound";
7822export const V2ThreadUnarchiveResponse__CollabAgentStatus = Schema.Literals([
7823 "pendingInit",
7824 "running",
7825 "interrupted",
7826 "completed",
7827 "errored",
7828 "shutdown",
7829 "notFound",
7830]);
7831
7832export type V2ThreadUnarchiveResponse__CommandAction =
7833 | {
7834 readonly command: string;
7835 readonly name: string;
7836 readonly path: string;
7837 readonly type: "read";
7838 }
7839 | { readonly command: string; readonly path?: string | null; readonly type: "listFiles" }
7840 | {
7841 readonly command: string;
7842 readonly path?: string | null;
7843 readonly query?: string | null;
7844 readonly type: "search";
7845 }
7846 | { readonly command: string; readonly type: "unknown" };
7847export const V2ThreadUnarchiveResponse__CommandAction = Schema.Union(
7848 [
7849 Schema.Struct({
7850 command: Schema.String,
7851 name: Schema.String,
7852 path: Schema.String,
7853 type: Schema.Literal("read").annotate({ title: "ReadCommandActionType" }),
7854 }).annotate({ title: "ReadCommandAction" }),
7855 Schema.Struct({
7856 command: Schema.String,
7857 path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
7858 type: Schema.Literal("listFiles").annotate({ title: "ListFilesCommandActionType" }),
7859 }).annotate({ title: "ListFilesCommandAction" }),
7860 Schema.Struct({
7861 command: Schema.String,
7862 path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
7863 query: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
7864 type: Schema.Literal("search").annotate({ title: "SearchCommandActionType" }),
7865 }).annotate({ title: "SearchCommandAction" }),
7866 Schema.Struct({
7867 command: Schema.String,
7868 type: Schema.Literal("unknown").annotate({ title: "UnknownCommandActionType" }),
7869 }).annotate({ title: "UnknownCommandAction" }),
7870 ],
7871 { mode: "oneOf" },
7872);
7873
7874export type V2ThreadUnarchiveResponse__CommandExecutionStatus =
7875 | "inProgress"
7876 | "completed"
7877 | "failed"
7878 | "declined";
7879export const V2ThreadUnarchiveResponse__CommandExecutionStatus = Schema.Literals([
7880 "inProgress",
7881 "completed",
7882 "failed",
7883 "declined",
7884]);
7885
7886export type V2ThreadUnarchiveResponse__DynamicToolCallOutputContentItem =
7887 | { readonly text: string; readonly type: "inputText" }
7888 | { readonly imageUrl: string; readonly type: "inputImage" };
7889export const V2ThreadUnarchiveResponse__DynamicToolCallOutputContentItem = Schema.Union(
7890 [
7891 Schema.Struct({
7892 text: Schema.String,
7893 type: Schema.Literal("inputText").annotate({
7894 title: "InputTextDynamicToolCallOutputContentItemType",
7895 }),
7896 }).annotate({ title: "InputTextDynamicToolCallOutputContentItem" }),
7897 Schema.Struct({
7898 imageUrl: Schema.String,
7899 type: Schema.Literal("inputImage").annotate({
7900 title: "InputImageDynamicToolCallOutputContentItemType",
7901 }),
7902 }).annotate({ title: "InputImageDynamicToolCallOutputContentItem" }),
7903 ],
7904 { mode: "oneOf" },
7905);
7906
7907export type V2ThreadUnarchiveResponse__DynamicToolCallStatus =
7908 | "inProgress"
7909 | "completed"
7910 | "failed";
7911export const V2ThreadUnarchiveResponse__DynamicToolCallStatus = Schema.Literals([
7912 "inProgress",
7913 "completed",
7914 "failed",
7915]);
7916
7917export type V2ThreadUnarchiveResponse__GitInfo = {
7918 readonly branch?: string | null;
7919 readonly originUrl?: string | null;
7920 readonly sha?: string | null;
7921};
7922export const V2ThreadUnarchiveResponse__GitInfo = Schema.Struct({
7923 branch: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
7924 originUrl: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
7925 sha: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
7926});
7927
7928export type V2ThreadUnarchiveResponse__HookPromptFragment = {
7929 readonly hookRunId: string;
7930 readonly text: string;
7931};
7932export const V2ThreadUnarchiveResponse__HookPromptFragment = Schema.Struct({
7933 hookRunId: Schema.String,
7934 text: Schema.String,
7935});
7936
7937export type V2ThreadUnarchiveResponse__McpToolCallError = { readonly message: string };
7938export const V2ThreadUnarchiveResponse__McpToolCallError = Schema.Struct({
7939 message: Schema.String,
7940});
7941
7942export type V2ThreadUnarchiveResponse__McpToolCallResult = {
7943 readonly _meta?: unknown;
7944 readonly content: ReadonlyArray<unknown>;
7945 readonly structuredContent?: unknown;
7946};
7947export const V2ThreadUnarchiveResponse__McpToolCallResult = Schema.Struct({
7948 _meta: Schema.optionalKey(Schema.Unknown),
7949 content: Schema.Array(Schema.Unknown),
7950 structuredContent: Schema.optionalKey(Schema.Unknown),
7951});
7952
7953export type V2ThreadUnarchiveResponse__McpToolCallStatus = "inProgress" | "completed" | "failed";
7954export const V2ThreadUnarchiveResponse__McpToolCallStatus = Schema.Literals([
7955 "inProgress",
7956 "completed",
7957 "failed",
7958]);
7959
7960export type V2ThreadUnarchiveResponse__MemoryCitationEntry = {
7961 readonly lineEnd: number;
7962 readonly lineStart: number;
7963 readonly note: string;
7964 readonly path: string;
7965};
7966export const V2ThreadUnarchiveResponse__MemoryCitationEntry = Schema.Struct({
7967 lineEnd: Schema.Number.annotate({ format: "uint32" })
7968 .check(Schema.isInt())
7969 .check(Schema.isGreaterThanOrEqualTo(0)),
7970 lineStart: Schema.Number.annotate({ format: "uint32" })
7971 .check(Schema.isInt())
7972 .check(Schema.isGreaterThanOrEqualTo(0)),
7973 note: Schema.String,
7974 path: Schema.String,
7975});
7976
7977export type V2ThreadUnarchiveResponse__MessagePhase = "commentary" | "final_answer";
7978export const V2ThreadUnarchiveResponse__MessagePhase = Schema.Literals([
7979 "commentary",
7980 "final_answer",
7981]).annotate({
7982 description:
7983 '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.',
7984});
7985
7986export type V2ThreadUnarchiveResponse__NonSteerableTurnKind = "review" | "compact";
7987export const V2ThreadUnarchiveResponse__NonSteerableTurnKind = Schema.Literals([
7988 "review",
7989 "compact",
7990]);
7991
7992export type V2ThreadUnarchiveResponse__PatchApplyStatus =
7993 | "inProgress"
7994 | "completed"
7995 | "failed"
7996 | "declined";
7997export const V2ThreadUnarchiveResponse__PatchApplyStatus = Schema.Literals([
7998 "inProgress",
7999 "completed",
8000 "failed",
8001 "declined",
8002]);
8003
8004export type V2ThreadUnarchiveResponse__PatchChangeKind =
8005 | { readonly type: "add" }
8006 | { readonly type: "delete" }
8007 | { readonly move_path?: string | null; readonly type: "update" };
8008export const V2ThreadUnarchiveResponse__PatchChangeKind = Schema.Union(
8009 [
8010 Schema.Struct({
8011 type: Schema.Literal("add").annotate({ title: "AddPatchChangeKindType" }),
8012 }).annotate({ title: "AddPatchChangeKind" }),
8013 Schema.Struct({
8014 type: Schema.Literal("delete").annotate({ title: "DeletePatchChangeKindType" }),
8015 }).annotate({ title: "DeletePatchChangeKind" }),
8016 Schema.Struct({
8017 move_path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
8018 type: Schema.Literal("update").annotate({ title: "UpdatePatchChangeKindType" }),
8019 }).annotate({ title: "UpdatePatchChangeKind" }),
8020 ],
8021 { mode: "oneOf" },
8022);
8023
8024export type V2ThreadUnarchiveResponse__ReasoningEffort =
8025 | "none"
8026 | "minimal"
8027 | "low"
8028 | "medium"
8029 | "high"
8030 | "xhigh";
8031export const V2ThreadUnarchiveResponse__ReasoningEffort = Schema.Literals([
8032 "none",
8033 "minimal",
8034 "low",
8035 "medium",
8036 "high",
8037 "xhigh",
8038]).annotate({
8039 description:
8040 "See https://platform.openai.com/docs/guides/reasoning?api-mode=responses#get-started-with-reasoning",
8041});
8042
8043export type V2ThreadUnarchiveResponse__TextElement = {
8044 readonly byteRange: { readonly end: number; readonly start: number };
8045 readonly placeholder?: string | null;
8046};
8047export const V2ThreadUnarchiveResponse__TextElement = Schema.Struct({
8048 byteRange: Schema.Struct({
8049 end: Schema.Number.annotate({ format: "uint" })
8050 .check(Schema.isInt())
8051 .check(Schema.isGreaterThanOrEqualTo(0)),
8052 start: Schema.Number.annotate({ format: "uint" })
8053 .check(Schema.isInt())
8054 .check(Schema.isGreaterThanOrEqualTo(0)),
8055 }).annotate({
8056 description: "Byte range in the parent `text` buffer that this element occupies.",
8057 }),
8058 placeholder: Schema.optionalKey(
8059 Schema.Union([
8060 Schema.String.annotate({
8061 description: "Optional human-readable placeholder for the element, displayed in the UI.",
8062 }),
8063 Schema.Null,
8064 ]),
8065 ),
8066});
8067
8068export type V2ThreadUnarchiveResponse__ThreadActiveFlag =
8069 | "waitingOnApproval"
8070 | "waitingOnUserInput";
8071export const V2ThreadUnarchiveResponse__ThreadActiveFlag = Schema.Literals([
8072 "waitingOnApproval",
8073 "waitingOnUserInput",
8074]);
8075
8076export type V2ThreadUnarchiveResponse__ThreadId = string;
8077export const V2ThreadUnarchiveResponse__ThreadId = Schema.String;
8078
8079export type V2ThreadUnarchiveResponse__TurnStatus =
8080 | "completed"
8081 | "interrupted"
8082 | "failed"
8083 | "inProgress";
8084export const V2ThreadUnarchiveResponse__TurnStatus = Schema.Literals([
8085 "completed",
8086 "interrupted",
8087 "failed",
8088 "inProgress",
8089]);
8090
8091export type V2ThreadUnarchiveResponse__WebSearchAction =
8092 | {
8093 readonly queries?: ReadonlyArray<string> | null;
8094 readonly query?: string | null;
8095 readonly type: "search";
8096 }
8097 | { readonly type: "openPage"; readonly url?: string | null }
8098 | { readonly pattern?: string | null; readonly type: "findInPage"; readonly url?: string | null }
8099 | { readonly type: "other" };
8100export const V2ThreadUnarchiveResponse__WebSearchAction = Schema.Union(
8101 [
8102 Schema.Struct({
8103 queries: Schema.optionalKey(Schema.Union([Schema.Array(Schema.String), Schema.Null])),
8104 query: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
8105 type: Schema.Literal("search").annotate({ title: "SearchWebSearchActionType" }),
8106 }).annotate({ title: "SearchWebSearchAction" }),
8107 Schema.Struct({
8108 type: Schema.Literal("openPage").annotate({ title: "OpenPageWebSearchActionType" }),
8109 url: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
8110 }).annotate({ title: "OpenPageWebSearchAction" }),
8111 Schema.Struct({
8112 pattern: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
8113 type: Schema.Literal("findInPage").annotate({ title: "FindInPageWebSearchActionType" }),
8114 url: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
8115 }).annotate({ title: "FindInPageWebSearchAction" }),
8116 Schema.Struct({
8117 type: Schema.Literal("other").annotate({ title: "OtherWebSearchActionType" }),
8118 }).annotate({ title: "OtherWebSearchAction" }),
8119 ],
8120 { mode: "oneOf" },
8121);
8122
8123export type V2ThreadUnsubscribeResponse__ThreadUnsubscribeStatus =
8124 | "notLoaded"
8125 | "notSubscribed"
8126 | "unsubscribed";
8127export const V2ThreadUnsubscribeResponse__ThreadUnsubscribeStatus = Schema.Literals([
8128 "notLoaded",
8129 "notSubscribed",
8130 "unsubscribed",
8131]);
8132
8133export type V2TurnCompletedNotification__CollabAgentStatus =
8134 | "pendingInit"
8135 | "running"
8136 | "interrupted"
8137 | "completed"
8138 | "errored"
8139 | "shutdown"
8140 | "notFound";
8141export const V2TurnCompletedNotification__CollabAgentStatus = Schema.Literals([
8142 "pendingInit",
8143 "running",
8144 "interrupted",
8145 "completed",
8146 "errored",
8147 "shutdown",
8148 "notFound",
8149]);
8150
8151export type V2TurnCompletedNotification__CommandAction =
8152 | {
8153 readonly command: string;
8154 readonly name: string;
8155 readonly path: string;
8156 readonly type: "read";
8157 }
8158 | { readonly command: string; readonly path?: string | null; readonly type: "listFiles" }
8159 | {
8160 readonly command: string;
8161 readonly path?: string | null;
8162 readonly query?: string | null;
8163 readonly type: "search";
8164 }
8165 | { readonly command: string; readonly type: "unknown" };
8166export const V2TurnCompletedNotification__CommandAction = Schema.Union(
8167 [
8168 Schema.Struct({
8169 command: Schema.String,
8170 name: Schema.String,
8171 path: Schema.String,
8172 type: Schema.Literal("read").annotate({ title: "ReadCommandActionType" }),
8173 }).annotate({ title: "ReadCommandAction" }),
8174 Schema.Struct({
8175 command: Schema.String,
8176 path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
8177 type: Schema.Literal("listFiles").annotate({ title: "ListFilesCommandActionType" }),
8178 }).annotate({ title: "ListFilesCommandAction" }),
8179 Schema.Struct({
8180 command: Schema.String,
8181 path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
8182 query: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
8183 type: Schema.Literal("search").annotate({ title: "SearchCommandActionType" }),
8184 }).annotate({ title: "SearchCommandAction" }),
8185 Schema.Struct({
8186 command: Schema.String,
8187 type: Schema.Literal("unknown").annotate({ title: "UnknownCommandActionType" }),
8188 }).annotate({ title: "UnknownCommandAction" }),
8189 ],
8190 { mode: "oneOf" },
8191);
8192
8193export type V2TurnCompletedNotification__CommandExecutionStatus =
8194 | "inProgress"
8195 | "completed"
8196 | "failed"
8197 | "declined";
8198export const V2TurnCompletedNotification__CommandExecutionStatus = Schema.Literals([
8199 "inProgress",
8200 "completed",
8201 "failed",
8202 "declined",
8203]);
8204
8205export type V2TurnCompletedNotification__DynamicToolCallOutputContentItem =
8206 | { readonly text: string; readonly type: "inputText" }
8207 | { readonly imageUrl: string; readonly type: "inputImage" };
8208export const V2TurnCompletedNotification__DynamicToolCallOutputContentItem = Schema.Union(
8209 [
8210 Schema.Struct({
8211 text: Schema.String,
8212 type: Schema.Literal("inputText").annotate({
8213 title: "InputTextDynamicToolCallOutputContentItemType",
8214 }),
8215 }).annotate({ title: "InputTextDynamicToolCallOutputContentItem" }),
8216 Schema.Struct({
8217 imageUrl: Schema.String,
8218 type: Schema.Literal("inputImage").annotate({
8219 title: "InputImageDynamicToolCallOutputContentItemType",
8220 }),
8221 }).annotate({ title: "InputImageDynamicToolCallOutputContentItem" }),
8222 ],
8223 { mode: "oneOf" },
8224);
8225
8226export type V2TurnCompletedNotification__DynamicToolCallStatus =
8227 | "inProgress"
8228 | "completed"
8229 | "failed";
8230export const V2TurnCompletedNotification__DynamicToolCallStatus = Schema.Literals([
8231 "inProgress",
8232 "completed",
8233 "failed",
8234]);
8235
8236export type V2TurnCompletedNotification__HookPromptFragment = {
8237 readonly hookRunId: string;
8238 readonly text: string;
8239};
8240export const V2TurnCompletedNotification__HookPromptFragment = Schema.Struct({
8241 hookRunId: Schema.String,
8242 text: Schema.String,
8243});
8244
8245export type V2TurnCompletedNotification__McpToolCallError = { readonly message: string };
8246export const V2TurnCompletedNotification__McpToolCallError = Schema.Struct({
8247 message: Schema.String,
8248});
8249
8250export type V2TurnCompletedNotification__McpToolCallResult = {
8251 readonly _meta?: unknown;
8252 readonly content: ReadonlyArray<unknown>;
8253 readonly structuredContent?: unknown;
8254};
8255export const V2TurnCompletedNotification__McpToolCallResult = Schema.Struct({
8256 _meta: Schema.optionalKey(Schema.Unknown),
8257 content: Schema.Array(Schema.Unknown),
8258 structuredContent: Schema.optionalKey(Schema.Unknown),
8259});
8260
8261export type V2TurnCompletedNotification__McpToolCallStatus = "inProgress" | "completed" | "failed";
8262export const V2TurnCompletedNotification__McpToolCallStatus = Schema.Literals([
8263 "inProgress",
8264 "completed",
8265 "failed",
8266]);
8267
8268export type V2TurnCompletedNotification__MemoryCitationEntry = {
8269 readonly lineEnd: number;
8270 readonly lineStart: number;
8271 readonly note: string;
8272 readonly path: string;
8273};
8274export const V2TurnCompletedNotification__MemoryCitationEntry = Schema.Struct({
8275 lineEnd: Schema.Number.annotate({ format: "uint32" })
8276 .check(Schema.isInt())
8277 .check(Schema.isGreaterThanOrEqualTo(0)),
8278 lineStart: Schema.Number.annotate({ format: "uint32" })
8279 .check(Schema.isInt())
8280 .check(Schema.isGreaterThanOrEqualTo(0)),
8281 note: Schema.String,
8282 path: Schema.String,
8283});
8284
8285export type V2TurnCompletedNotification__MessagePhase = "commentary" | "final_answer";
8286export const V2TurnCompletedNotification__MessagePhase = Schema.Literals([
8287 "commentary",
8288 "final_answer",
8289]).annotate({
8290 description:
8291 '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.',
8292});
8293
8294export type V2TurnCompletedNotification__NonSteerableTurnKind = "review" | "compact";
8295export const V2TurnCompletedNotification__NonSteerableTurnKind = Schema.Literals([
8296 "review",
8297 "compact",
8298]);
8299
8300export type V2TurnCompletedNotification__PatchApplyStatus =
8301 | "inProgress"
8302 | "completed"
8303 | "failed"
8304 | "declined";
8305export const V2TurnCompletedNotification__PatchApplyStatus = Schema.Literals([
8306 "inProgress",
8307 "completed",
8308 "failed",
8309 "declined",
8310]);
8311
8312export type V2TurnCompletedNotification__PatchChangeKind =
8313 | { readonly type: "add" }
8314 | { readonly type: "delete" }
8315 | { readonly move_path?: string | null; readonly type: "update" };
8316export const V2TurnCompletedNotification__PatchChangeKind = Schema.Union(
8317 [
8318 Schema.Struct({
8319 type: Schema.Literal("add").annotate({ title: "AddPatchChangeKindType" }),
8320 }).annotate({ title: "AddPatchChangeKind" }),
8321 Schema.Struct({
8322 type: Schema.Literal("delete").annotate({ title: "DeletePatchChangeKindType" }),
8323 }).annotate({ title: "DeletePatchChangeKind" }),
8324 Schema.Struct({
8325 move_path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
8326 type: Schema.Literal("update").annotate({ title: "UpdatePatchChangeKindType" }),
8327 }).annotate({ title: "UpdatePatchChangeKind" }),
8328 ],
8329 { mode: "oneOf" },
8330);
8331
8332export type V2TurnCompletedNotification__ReasoningEffort =
8333 | "none"
8334 | "minimal"
8335 | "low"
8336 | "medium"
8337 | "high"
8338 | "xhigh";
8339export const V2TurnCompletedNotification__ReasoningEffort = Schema.Literals([
8340 "none",
8341 "minimal",
8342 "low",
8343 "medium",
8344 "high",
8345 "xhigh",
8346]).annotate({
8347 description:
8348 "See https://platform.openai.com/docs/guides/reasoning?api-mode=responses#get-started-with-reasoning",
8349});
8350
8351export type V2TurnCompletedNotification__TextElement = {
8352 readonly byteRange: { readonly end: number; readonly start: number };
8353 readonly placeholder?: string | null;
8354};
8355export const V2TurnCompletedNotification__TextElement = Schema.Struct({
8356 byteRange: Schema.Struct({
8357 end: Schema.Number.annotate({ format: "uint" })
8358 .check(Schema.isInt())
8359 .check(Schema.isGreaterThanOrEqualTo(0)),
8360 start: Schema.Number.annotate({ format: "uint" })
8361 .check(Schema.isInt())
8362 .check(Schema.isGreaterThanOrEqualTo(0)),
8363 }).annotate({
8364 description: "Byte range in the parent `text` buffer that this element occupies.",
8365 }),
8366 placeholder: Schema.optionalKey(
8367 Schema.Union([
8368 Schema.String.annotate({
8369 description: "Optional human-readable placeholder for the element, displayed in the UI.",
8370 }),
8371 Schema.Null,
8372 ]),
8373 ),
8374});
8375
8376export type V2TurnCompletedNotification__TurnStatus =
8377 | "completed"
8378 | "interrupted"
8379 | "failed"
8380 | "inProgress";
8381export const V2TurnCompletedNotification__TurnStatus = Schema.Literals([
8382 "completed",
8383 "interrupted",
8384 "failed",
8385 "inProgress",
8386]);
8387
8388export type V2TurnCompletedNotification__WebSearchAction =
8389 | {
8390 readonly queries?: ReadonlyArray<string> | null;
8391 readonly query?: string | null;
8392 readonly type: "search";
8393 }
8394 | { readonly type: "openPage"; readonly url?: string | null }
8395 | { readonly pattern?: string | null; readonly type: "findInPage"; readonly url?: string | null }
8396 | { readonly type: "other" };
8397export const V2TurnCompletedNotification__WebSearchAction = Schema.Union(
8398 [
8399 Schema.Struct({
8400 queries: Schema.optionalKey(Schema.Union([Schema.Array(Schema.String), Schema.Null])),
8401 query: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
8402 type: Schema.Literal("search").annotate({ title: "SearchWebSearchActionType" }),
8403 }).annotate({ title: "SearchWebSearchAction" }),
8404 Schema.Struct({
8405 type: Schema.Literal("openPage").annotate({ title: "OpenPageWebSearchActionType" }),
8406 url: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
8407 }).annotate({ title: "OpenPageWebSearchAction" }),
8408 Schema.Struct({
8409 pattern: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
8410 type: Schema.Literal("findInPage").annotate({ title: "FindInPageWebSearchActionType" }),
8411 url: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
8412 }).annotate({ title: "FindInPageWebSearchAction" }),
8413 Schema.Struct({
8414 type: Schema.Literal("other").annotate({ title: "OtherWebSearchActionType" }),
8415 }).annotate({ title: "OtherWebSearchAction" }),
8416 ],
8417 { mode: "oneOf" },
8418);
8419
8420export type V2TurnPlanUpdatedNotification__TurnPlanStepStatus =
8421 | "pending"
8422 | "inProgress"
8423 | "completed";
8424export const V2TurnPlanUpdatedNotification__TurnPlanStepStatus = Schema.Literals([
8425 "pending",
8426 "inProgress",
8427 "completed",
8428]);
8429
8430export type V2TurnStartedNotification__CollabAgentStatus =
8431 | "pendingInit"
8432 | "running"
8433 | "interrupted"
8434 | "completed"
8435 | "errored"
8436 | "shutdown"
8437 | "notFound";
8438export const V2TurnStartedNotification__CollabAgentStatus = Schema.Literals([
8439 "pendingInit",
8440 "running",
8441 "interrupted",
8442 "completed",
8443 "errored",
8444 "shutdown",
8445 "notFound",
8446]);
8447
8448export type V2TurnStartedNotification__CommandAction =
8449 | {
8450 readonly command: string;
8451 readonly name: string;
8452 readonly path: string;
8453 readonly type: "read";
8454 }
8455 | { readonly command: string; readonly path?: string | null; readonly type: "listFiles" }
8456 | {
8457 readonly command: string;
8458 readonly path?: string | null;
8459 readonly query?: string | null;
8460 readonly type: "search";
8461 }
8462 | { readonly command: string; readonly type: "unknown" };
8463export const V2TurnStartedNotification__CommandAction = Schema.Union(
8464 [
8465 Schema.Struct({
8466 command: Schema.String,
8467 name: Schema.String,
8468 path: Schema.String,
8469 type: Schema.Literal("read").annotate({ title: "ReadCommandActionType" }),
8470 }).annotate({ title: "ReadCommandAction" }),
8471 Schema.Struct({
8472 command: Schema.String,
8473 path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
8474 type: Schema.Literal("listFiles").annotate({ title: "ListFilesCommandActionType" }),
8475 }).annotate({ title: "ListFilesCommandAction" }),
8476 Schema.Struct({
8477 command: Schema.String,
8478 path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
8479 query: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
8480 type: Schema.Literal("search").annotate({ title: "SearchCommandActionType" }),
8481 }).annotate({ title: "SearchCommandAction" }),
8482 Schema.Struct({
8483 command: Schema.String,
8484 type: Schema.Literal("unknown").annotate({ title: "UnknownCommandActionType" }),
8485 }).annotate({ title: "UnknownCommandAction" }),
8486 ],
8487 { mode: "oneOf" },
8488);
8489
8490export type V2TurnStartedNotification__CommandExecutionStatus =
8491 | "inProgress"
8492 | "completed"
8493 | "failed"
8494 | "declined";
8495export const V2TurnStartedNotification__CommandExecutionStatus = Schema.Literals([
8496 "inProgress",
8497 "completed",
8498 "failed",
8499 "declined",
8500]);
8501
8502export type V2TurnStartedNotification__DynamicToolCallOutputContentItem =
8503 | { readonly text: string; readonly type: "inputText" }
8504 | { readonly imageUrl: string; readonly type: "inputImage" };
8505export const V2TurnStartedNotification__DynamicToolCallOutputContentItem = Schema.Union(
8506 [
8507 Schema.Struct({
8508 text: Schema.String,
8509 type: Schema.Literal("inputText").annotate({
8510 title: "InputTextDynamicToolCallOutputContentItemType",
8511 }),
8512 }).annotate({ title: "InputTextDynamicToolCallOutputContentItem" }),
8513 Schema.Struct({
8514 imageUrl: Schema.String,
8515 type: Schema.Literal("inputImage").annotate({
8516 title: "InputImageDynamicToolCallOutputContentItemType",
8517 }),
8518 }).annotate({ title: "InputImageDynamicToolCallOutputContentItem" }),
8519 ],
8520 { mode: "oneOf" },
8521);
8522
8523export type V2TurnStartedNotification__DynamicToolCallStatus =
8524 | "inProgress"
8525 | "completed"
8526 | "failed";
8527export const V2TurnStartedNotification__DynamicToolCallStatus = Schema.Literals([
8528 "inProgress",
8529 "completed",
8530 "failed",
8531]);
8532
8533export type V2TurnStartedNotification__HookPromptFragment = {
8534 readonly hookRunId: string;
8535 readonly text: string;
8536};
8537export const V2TurnStartedNotification__HookPromptFragment = Schema.Struct({
8538 hookRunId: Schema.String,
8539 text: Schema.String,
8540});
8541
8542export type V2TurnStartedNotification__McpToolCallError = { readonly message: string };
8543export const V2TurnStartedNotification__McpToolCallError = Schema.Struct({
8544 message: Schema.String,
8545});
8546
8547export type V2TurnStartedNotification__McpToolCallResult = {
8548 readonly _meta?: unknown;
8549 readonly content: ReadonlyArray<unknown>;
8550 readonly structuredContent?: unknown;
8551};
8552export const V2TurnStartedNotification__McpToolCallResult = Schema.Struct({
8553 _meta: Schema.optionalKey(Schema.Unknown),
8554 content: Schema.Array(Schema.Unknown),
8555 structuredContent: Schema.optionalKey(Schema.Unknown),
8556});
8557
8558export type V2TurnStartedNotification__McpToolCallStatus = "inProgress" | "completed" | "failed";
8559export const V2TurnStartedNotification__McpToolCallStatus = Schema.Literals([
8560 "inProgress",
8561 "completed",
8562 "failed",
8563]);
8564
8565export type V2TurnStartedNotification__MemoryCitationEntry = {
8566 readonly lineEnd: number;
8567 readonly lineStart: number;
8568 readonly note: string;
8569 readonly path: string;
8570};
8571export const V2TurnStartedNotification__MemoryCitationEntry = Schema.Struct({
8572 lineEnd: Schema.Number.annotate({ format: "uint32" })
8573 .check(Schema.isInt())
8574 .check(Schema.isGreaterThanOrEqualTo(0)),
8575 lineStart: Schema.Number.annotate({ format: "uint32" })
8576 .check(Schema.isInt())
8577 .check(Schema.isGreaterThanOrEqualTo(0)),
8578 note: Schema.String,
8579 path: Schema.String,
8580});
8581
8582export type V2TurnStartedNotification__MessagePhase = "commentary" | "final_answer";
8583export const V2TurnStartedNotification__MessagePhase = Schema.Literals([
8584 "commentary",
8585 "final_answer",
8586]).annotate({
8587 description:
8588 '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.',
8589});
8590
8591export type V2TurnStartedNotification__NonSteerableTurnKind = "review" | "compact";
8592export const V2TurnStartedNotification__NonSteerableTurnKind = Schema.Literals([
8593 "review",
8594 "compact",
8595]);
8596
8597export type V2TurnStartedNotification__PatchApplyStatus =
8598 | "inProgress"
8599 | "completed"
8600 | "failed"
8601 | "declined";
8602export const V2TurnStartedNotification__PatchApplyStatus = Schema.Literals([
8603 "inProgress",
8604 "completed",
8605 "failed",
8606 "declined",
8607]);
8608
8609export type V2TurnStartedNotification__PatchChangeKind =
8610 | { readonly type: "add" }
8611 | { readonly type: "delete" }
8612 | { readonly move_path?: string | null; readonly type: "update" };
8613export const V2TurnStartedNotification__PatchChangeKind = Schema.Union(
8614 [
8615 Schema.Struct({
8616 type: Schema.Literal("add").annotate({ title: "AddPatchChangeKindType" }),
8617 }).annotate({ title: "AddPatchChangeKind" }),
8618 Schema.Struct({
8619 type: Schema.Literal("delete").annotate({ title: "DeletePatchChangeKindType" }),
8620 }).annotate({ title: "DeletePatchChangeKind" }),
8621 Schema.Struct({
8622 move_path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
8623 type: Schema.Literal("update").annotate({ title: "UpdatePatchChangeKindType" }),
8624 }).annotate({ title: "UpdatePatchChangeKind" }),
8625 ],
8626 { mode: "oneOf" },
8627);
8628
8629export type V2TurnStartedNotification__ReasoningEffort =
8630 | "none"
8631 | "minimal"
8632 | "low"
8633 | "medium"
8634 | "high"
8635 | "xhigh";
8636export const V2TurnStartedNotification__ReasoningEffort = Schema.Literals([
8637 "none",
8638 "minimal",
8639 "low",
8640 "medium",
8641 "high",
8642 "xhigh",
8643]).annotate({
8644 description:
8645 "See https://platform.openai.com/docs/guides/reasoning?api-mode=responses#get-started-with-reasoning",
8646});
8647
8648export type V2TurnStartedNotification__TextElement = {
8649 readonly byteRange: { readonly end: number; readonly start: number };
8650 readonly placeholder?: string | null;
8651};
8652export const V2TurnStartedNotification__TextElement = Schema.Struct({
8653 byteRange: Schema.Struct({
8654 end: Schema.Number.annotate({ format: "uint" })
8655 .check(Schema.isInt())
8656 .check(Schema.isGreaterThanOrEqualTo(0)),
8657 start: Schema.Number.annotate({ format: "uint" })
8658 .check(Schema.isInt())
8659 .check(Schema.isGreaterThanOrEqualTo(0)),
8660 }).annotate({
8661 description: "Byte range in the parent `text` buffer that this element occupies.",
8662 }),
8663 placeholder: Schema.optionalKey(
8664 Schema.Union([
8665 Schema.String.annotate({
8666 description: "Optional human-readable placeholder for the element, displayed in the UI.",
8667 }),
8668 Schema.Null,
8669 ]),
8670 ),
8671});
8672
8673export type V2TurnStartedNotification__TurnStatus =
8674 | "completed"
8675 | "interrupted"
8676 | "failed"
8677 | "inProgress";
8678export const V2TurnStartedNotification__TurnStatus = Schema.Literals([
8679 "completed",
8680 "interrupted",
8681 "failed",
8682 "inProgress",
8683]);
8684
8685export type V2TurnStartedNotification__WebSearchAction =
8686 | {
8687 readonly queries?: ReadonlyArray<string> | null;
8688 readonly query?: string | null;
8689 readonly type: "search";
8690 }
8691 | { readonly type: "openPage"; readonly url?: string | null }
8692 | { readonly pattern?: string | null; readonly type: "findInPage"; readonly url?: string | null }
8693 | { readonly type: "other" };
8694export const V2TurnStartedNotification__WebSearchAction = Schema.Union(
8695 [
8696 Schema.Struct({
8697 queries: Schema.optionalKey(Schema.Union([Schema.Array(Schema.String), Schema.Null])),
8698 query: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
8699 type: Schema.Literal("search").annotate({ title: "SearchWebSearchActionType" }),
8700 }).annotate({ title: "SearchWebSearchAction" }),
8701 Schema.Struct({
8702 type: Schema.Literal("openPage").annotate({ title: "OpenPageWebSearchActionType" }),
8703 url: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
8704 }).annotate({ title: "OpenPageWebSearchAction" }),
8705 Schema.Struct({
8706 pattern: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
8707 type: Schema.Literal("findInPage").annotate({ title: "FindInPageWebSearchActionType" }),
8708 url: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
8709 }).annotate({ title: "FindInPageWebSearchAction" }),
8710 Schema.Struct({
8711 type: Schema.Literal("other").annotate({ title: "OtherWebSearchActionType" }),
8712 }).annotate({ title: "OtherWebSearchAction" }),
8713 ],
8714 { mode: "oneOf" },
8715);
8716
8717export type V2TurnStartParams__AbsolutePathBuf = string;
8718export const V2TurnStartParams__AbsolutePathBuf = Schema.String.annotate({
8719 description:
8720 "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.",
8721});
8722
8723export type V2TurnStartParams__ApprovalsReviewer = "user" | "guardian_subagent";
8724export const V2TurnStartParams__ApprovalsReviewer = Schema.Literals([
8725 "user",
8726 "guardian_subagent",
8727]).annotate({
8728 description:
8729 "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.",
8730});
8731
8732export type V2TurnStartParams__AskForApproval =
8733 | "untrusted"
8734 | "on-failure"
8735 | "on-request"
8736 | "never"
8737 | {
8738 readonly granular: {
8739 readonly mcp_elicitations: boolean;
8740 readonly request_permissions?: boolean;
8741 readonly rules: boolean;
8742 readonly sandbox_approval: boolean;
8743 readonly skill_approval?: boolean;
8744 };
8745 };
8746export const V2TurnStartParams__AskForApproval = Schema.Union(
8747 [
8748 Schema.Literals(["untrusted", "on-failure", "on-request", "never"]),
8749 Schema.Struct({
8750 granular: Schema.Struct({
8751 mcp_elicitations: Schema.Boolean,
8752 request_permissions: Schema.optionalKey(Schema.Boolean.annotate({ default: false })),
8753 rules: Schema.Boolean,
8754 sandbox_approval: Schema.Boolean,
8755 skill_approval: Schema.optionalKey(Schema.Boolean.annotate({ default: false })),
8756 }),
8757 }).annotate({ title: "GranularAskForApproval" }),
8758 ],
8759 { mode: "oneOf" },
8760);
8761
8762export type V2TurnStartParams__ModeKind = "plan" | "default";
8763export const V2TurnStartParams__ModeKind = Schema.Literals(["plan", "default"]).annotate({
8764 description: "Initial collaboration mode to use when the TUI starts.",
8765});
8766
8767export type V2TurnStartParams__Personality = "none" | "friendly" | "pragmatic";
8768export const V2TurnStartParams__Personality = Schema.Literals(["none", "friendly", "pragmatic"]);
8769
8770export type V2TurnStartParams__ReasoningEffort =
8771 | "none"
8772 | "minimal"
8773 | "low"
8774 | "medium"
8775 | "high"
8776 | "xhigh";
8777export const V2TurnStartParams__ReasoningEffort = Schema.Literals([
8778 "none",
8779 "minimal",
8780 "low",
8781 "medium",
8782 "high",
8783 "xhigh",
8784]).annotate({
8785 description:
8786 "See https://platform.openai.com/docs/guides/reasoning?api-mode=responses#get-started-with-reasoning",
8787});
8788
8789export type V2TurnStartParams__ReasoningSummary = "auto" | "concise" | "detailed" | "none";
8790export const V2TurnStartParams__ReasoningSummary = Schema.Union(
8791 [
8792 Schema.Literals(["auto", "concise", "detailed"]),
8793 Schema.Literal("none").annotate({ description: "Option to disable reasoning summaries." }),
8794 ],
8795 { mode: "oneOf" },
8796).annotate({
8797 description:
8798 "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",
8799});
8800
8801export type V2TurnStartParams__ServiceTier = "fast" | "flex";
8802export const V2TurnStartParams__ServiceTier = Schema.Literals(["fast", "flex"]);
8803
8804export type V2TurnStartParams__TextElement = {
8805 readonly byteRange: { readonly end: number; readonly start: number };
8806 readonly placeholder?: string | null;
8807};
8808export const V2TurnStartParams__TextElement = Schema.Struct({
8809 byteRange: Schema.Struct({
8810 end: Schema.Number.annotate({ format: "uint" })
8811 .check(Schema.isInt())
8812 .check(Schema.isGreaterThanOrEqualTo(0)),
8813 start: Schema.Number.annotate({ format: "uint" })
8814 .check(Schema.isInt())
8815 .check(Schema.isGreaterThanOrEqualTo(0)),
8816 }).annotate({
8817 description: "Byte range in the parent `text` buffer that this element occupies.",
8818 }),
8819 placeholder: Schema.optionalKey(
8820 Schema.Union([
8821 Schema.String.annotate({
8822 description: "Optional human-readable placeholder for the element, displayed in the UI.",
8823 }),
8824 Schema.Null,
8825 ]),
8826 ),
8827});
8828
8829export type V2TurnStartResponse__CollabAgentStatus =
8830 | "pendingInit"
8831 | "running"
8832 | "interrupted"
8833 | "completed"
8834 | "errored"
8835 | "shutdown"
8836 | "notFound";
8837export const V2TurnStartResponse__CollabAgentStatus = Schema.Literals([
8838 "pendingInit",
8839 "running",
8840 "interrupted",
8841 "completed",
8842 "errored",
8843 "shutdown",
8844 "notFound",
8845]);
8846
8847export type V2TurnStartResponse__CommandAction =
8848 | {
8849 readonly command: string;
8850 readonly name: string;
8851 readonly path: string;
8852 readonly type: "read";
8853 }
8854 | { readonly command: string; readonly path?: string | null; readonly type: "listFiles" }
8855 | {
8856 readonly command: string;
8857 readonly path?: string | null;
8858 readonly query?: string | null;
8859 readonly type: "search";
8860 }
8861 | { readonly command: string; readonly type: "unknown" };
8862export const V2TurnStartResponse__CommandAction = Schema.Union(
8863 [
8864 Schema.Struct({
8865 command: Schema.String,
8866 name: Schema.String,
8867 path: Schema.String,
8868 type: Schema.Literal("read").annotate({ title: "ReadCommandActionType" }),
8869 }).annotate({ title: "ReadCommandAction" }),
8870 Schema.Struct({
8871 command: Schema.String,
8872 path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
8873 type: Schema.Literal("listFiles").annotate({ title: "ListFilesCommandActionType" }),
8874 }).annotate({ title: "ListFilesCommandAction" }),
8875 Schema.Struct({
8876 command: Schema.String,
8877 path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
8878 query: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
8879 type: Schema.Literal("search").annotate({ title: "SearchCommandActionType" }),
8880 }).annotate({ title: "SearchCommandAction" }),
8881 Schema.Struct({
8882 command: Schema.String,
8883 type: Schema.Literal("unknown").annotate({ title: "UnknownCommandActionType" }),
8884 }).annotate({ title: "UnknownCommandAction" }),
8885 ],
8886 { mode: "oneOf" },
8887);
8888
8889export type V2TurnStartResponse__CommandExecutionStatus =
8890 | "inProgress"
8891 | "completed"
8892 | "failed"
8893 | "declined";
8894export const V2TurnStartResponse__CommandExecutionStatus = Schema.Literals([
8895 "inProgress",
8896 "completed",
8897 "failed",
8898 "declined",
8899]);
8900
8901export type V2TurnStartResponse__DynamicToolCallOutputContentItem =
8902 | { readonly text: string; readonly type: "inputText" }
8903 | { readonly imageUrl: string; readonly type: "inputImage" };
8904export const V2TurnStartResponse__DynamicToolCallOutputContentItem = Schema.Union(
8905 [
8906 Schema.Struct({
8907 text: Schema.String,
8908 type: Schema.Literal("inputText").annotate({
8909 title: "InputTextDynamicToolCallOutputContentItemType",
8910 }),
8911 }).annotate({ title: "InputTextDynamicToolCallOutputContentItem" }),
8912 Schema.Struct({
8913 imageUrl: Schema.String,
8914 type: Schema.Literal("inputImage").annotate({
8915 title: "InputImageDynamicToolCallOutputContentItemType",
8916 }),
8917 }).annotate({ title: "InputImageDynamicToolCallOutputContentItem" }),
8918 ],
8919 { mode: "oneOf" },
8920);
8921
8922export type V2TurnStartResponse__DynamicToolCallStatus = "inProgress" | "completed" | "failed";
8923export const V2TurnStartResponse__DynamicToolCallStatus = Schema.Literals([
8924 "inProgress",
8925 "completed",
8926 "failed",
8927]);
8928
8929export type V2TurnStartResponse__HookPromptFragment = {
8930 readonly hookRunId: string;
8931 readonly text: string;
8932};
8933export const V2TurnStartResponse__HookPromptFragment = Schema.Struct({
8934 hookRunId: Schema.String,
8935 text: Schema.String,
8936});
8937
8938export type V2TurnStartResponse__McpToolCallError = { readonly message: string };
8939export const V2TurnStartResponse__McpToolCallError = Schema.Struct({ message: Schema.String });
8940
8941export type V2TurnStartResponse__McpToolCallResult = {
8942 readonly _meta?: unknown;
8943 readonly content: ReadonlyArray<unknown>;
8944 readonly structuredContent?: unknown;
8945};
8946export const V2TurnStartResponse__McpToolCallResult = Schema.Struct({
8947 _meta: Schema.optionalKey(Schema.Unknown),
8948 content: Schema.Array(Schema.Unknown),
8949 structuredContent: Schema.optionalKey(Schema.Unknown),
8950});
8951
8952export type V2TurnStartResponse__McpToolCallStatus = "inProgress" | "completed" | "failed";
8953export const V2TurnStartResponse__McpToolCallStatus = Schema.Literals([
8954 "inProgress",
8955 "completed",
8956 "failed",
8957]);
8958
8959export type V2TurnStartResponse__MemoryCitationEntry = {
8960 readonly lineEnd: number;
8961 readonly lineStart: number;
8962 readonly note: string;
8963 readonly path: string;
8964};
8965export const V2TurnStartResponse__MemoryCitationEntry = Schema.Struct({
8966 lineEnd: Schema.Number.annotate({ format: "uint32" })
8967 .check(Schema.isInt())
8968 .check(Schema.isGreaterThanOrEqualTo(0)),
8969 lineStart: Schema.Number.annotate({ format: "uint32" })
8970 .check(Schema.isInt())
8971 .check(Schema.isGreaterThanOrEqualTo(0)),
8972 note: Schema.String,
8973 path: Schema.String,
8974});
8975
8976export type V2TurnStartResponse__MessagePhase = "commentary" | "final_answer";
8977export const V2TurnStartResponse__MessagePhase = Schema.Literals([
8978 "commentary",
8979 "final_answer",
8980]).annotate({
8981 description:
8982 '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.',
8983});
8984
8985export type V2TurnStartResponse__NonSteerableTurnKind = "review" | "compact";
8986export const V2TurnStartResponse__NonSteerableTurnKind = Schema.Literals(["review", "compact"]);
8987
8988export type V2TurnStartResponse__PatchApplyStatus =
8989 | "inProgress"
8990 | "completed"
8991 | "failed"
8992 | "declined";
8993export const V2TurnStartResponse__PatchApplyStatus = Schema.Literals([
8994 "inProgress",
8995 "completed",
8996 "failed",
8997 "declined",
8998]);
8999
9000export type V2TurnStartResponse__PatchChangeKind =
9001 | { readonly type: "add" }
9002 | { readonly type: "delete" }
9003 | { readonly move_path?: string | null; readonly type: "update" };
9004export const V2TurnStartResponse__PatchChangeKind = Schema.Union(
9005 [
9006 Schema.Struct({
9007 type: Schema.Literal("add").annotate({ title: "AddPatchChangeKindType" }),
9008 }).annotate({ title: "AddPatchChangeKind" }),
9009 Schema.Struct({
9010 type: Schema.Literal("delete").annotate({ title: "DeletePatchChangeKindType" }),
9011 }).annotate({ title: "DeletePatchChangeKind" }),
9012 Schema.Struct({
9013 move_path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
9014 type: Schema.Literal("update").annotate({ title: "UpdatePatchChangeKindType" }),
9015 }).annotate({ title: "UpdatePatchChangeKind" }),
9016 ],
9017 { mode: "oneOf" },
9018);
9019
9020export type V2TurnStartResponse__ReasoningEffort =
9021 | "none"
9022 | "minimal"
9023 | "low"
9024 | "medium"
9025 | "high"
9026 | "xhigh";
9027export const V2TurnStartResponse__ReasoningEffort = Schema.Literals([
9028 "none",
9029 "minimal",
9030 "low",
9031 "medium",
9032 "high",
9033 "xhigh",
9034]).annotate({
9035 description:
9036 "See https://platform.openai.com/docs/guides/reasoning?api-mode=responses#get-started-with-reasoning",
9037});
9038
9039export type V2TurnStartResponse__TextElement = {
9040 readonly byteRange: { readonly end: number; readonly start: number };
9041 readonly placeholder?: string | null;
9042};
9043export const V2TurnStartResponse__TextElement = Schema.Struct({
9044 byteRange: Schema.Struct({
9045 end: Schema.Number.annotate({ format: "uint" })
9046 .check(Schema.isInt())
9047 .check(Schema.isGreaterThanOrEqualTo(0)),
9048 start: Schema.Number.annotate({ format: "uint" })
9049 .check(Schema.isInt())
9050 .check(Schema.isGreaterThanOrEqualTo(0)),
9051 }).annotate({
9052 description: "Byte range in the parent `text` buffer that this element occupies.",
9053 }),
9054 placeholder: Schema.optionalKey(
9055 Schema.Union([
9056 Schema.String.annotate({
9057 description: "Optional human-readable placeholder for the element, displayed in the UI.",
9058 }),
9059 Schema.Null,
9060 ]),
9061 ),
9062});
9063
9064export type V2TurnStartResponse__TurnStatus = "completed" | "interrupted" | "failed" | "inProgress";
9065export const V2TurnStartResponse__TurnStatus = Schema.Literals([
9066 "completed",
9067 "interrupted",
9068 "failed",
9069 "inProgress",
9070]);
9071
9072export type V2TurnStartResponse__WebSearchAction =
9073 | {
9074 readonly queries?: ReadonlyArray<string> | null;
9075 readonly query?: string | null;
9076 readonly type: "search";
9077 }
9078 | { readonly type: "openPage"; readonly url?: string | null }
9079 | { readonly pattern?: string | null; readonly type: "findInPage"; readonly url?: string | null }
9080 | { readonly type: "other" };
9081export const V2TurnStartResponse__WebSearchAction = Schema.Union(
9082 [
9083 Schema.Struct({
9084 queries: Schema.optionalKey(Schema.Union([Schema.Array(Schema.String), Schema.Null])),
9085 query: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
9086 type: Schema.Literal("search").annotate({ title: "SearchWebSearchActionType" }),
9087 }).annotate({ title: "SearchWebSearchAction" }),
9088 Schema.Struct({
9089 type: Schema.Literal("openPage").annotate({ title: "OpenPageWebSearchActionType" }),
9090 url: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
9091 }).annotate({ title: "OpenPageWebSearchAction" }),
9092 Schema.Struct({
9093 pattern: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
9094 type: Schema.Literal("findInPage").annotate({ title: "FindInPageWebSearchActionType" }),
9095 url: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
9096 }).annotate({ title: "FindInPageWebSearchAction" }),
9097 Schema.Struct({
9098 type: Schema.Literal("other").annotate({ title: "OtherWebSearchActionType" }),
9099 }).annotate({ title: "OtherWebSearchAction" }),
9100 ],
9101 { mode: "oneOf" },
9102);
9103
9104export type V2TurnSteerParams__TextElement = {
9105 readonly byteRange: { readonly end: number; readonly start: number };
9106 readonly placeholder?: string | null;
9107};
9108export const V2TurnSteerParams__TextElement = Schema.Struct({
9109 byteRange: Schema.Struct({
9110 end: Schema.Number.annotate({ format: "uint" })
9111 .check(Schema.isInt())
9112 .check(Schema.isGreaterThanOrEqualTo(0)),
9113 start: Schema.Number.annotate({ format: "uint" })
9114 .check(Schema.isInt())
9115 .check(Schema.isGreaterThanOrEqualTo(0)),
9116 }).annotate({
9117 description: "Byte range in the parent `text` buffer that this element occupies.",
9118 }),
9119 placeholder: Schema.optionalKey(
9120 Schema.Union([
9121 Schema.String.annotate({
9122 description: "Optional human-readable placeholder for the element, displayed in the UI.",
9123 }),
9124 Schema.Null,
9125 ]),
9126 ),
9127});
9128
9129export type V2WindowsSandboxSetupCompletedNotification__WindowsSandboxSetupMode =
9130 | "elevated"
9131 | "unelevated";
9132export const V2WindowsSandboxSetupCompletedNotification__WindowsSandboxSetupMode = Schema.Literals([
9133 "elevated",
9134 "unelevated",
9135]);
9136
9137export type V2WindowsSandboxSetupStartParams__AbsolutePathBuf = string;
9138export const V2WindowsSandboxSetupStartParams__AbsolutePathBuf = Schema.String.annotate({
9139 description:
9140 "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.",
9141});
9142
9143export type V2WindowsSandboxSetupStartParams__WindowsSandboxSetupMode = "elevated" | "unelevated";
9144export const V2WindowsSandboxSetupStartParams__WindowsSandboxSetupMode = Schema.Literals([
9145 "elevated",
9146 "unelevated",
9147]);
9148
9149export type ApplyPatchApprovalResponse__NetworkPolicyAmendment = {
9150 readonly action: ApplyPatchApprovalResponse__NetworkPolicyRuleAction;
9151 readonly host: string;
9152};
9153export const ApplyPatchApprovalResponse__NetworkPolicyAmendment = Schema.Struct({
9154 action: ApplyPatchApprovalResponse__NetworkPolicyRuleAction,
9155 host: Schema.String,
9156});
9157
9158export type ClientRequest__PluginInstallParams = {
9159 readonly forceRemoteSync?: boolean;
9160 readonly marketplacePath: ClientRequest__AbsolutePathBuf;
9161 readonly pluginName: string;
9162};
9163export const ClientRequest__PluginInstallParams = Schema.Struct({
9164 forceRemoteSync: Schema.optionalKey(
9165 Schema.Boolean.annotate({
9166 description: "When true, apply the remote plugin change before the local install flow.",
9167 }),
9168 ),
9169 marketplacePath: ClientRequest__AbsolutePathBuf,
9170 pluginName: Schema.String,
9171});
9172
9173export type ClientRequest__PluginListParams = {
9174 readonly cwds?: ReadonlyArray<ClientRequest__AbsolutePathBuf> | null;
9175 readonly forceRemoteSync?: boolean;
9176};
9177export const ClientRequest__PluginListParams = Schema.Struct({
9178 cwds: Schema.optionalKey(
9179 Schema.Union([
9180 Schema.Array(ClientRequest__AbsolutePathBuf).annotate({
9181 description:
9182 "Optional working directories used to discover repo marketplaces. When omitted, only home-scoped marketplaces and the official curated marketplace are considered.",
9183 }),
9184 Schema.Null,
9185 ]),
9186 ),
9187 forceRemoteSync: Schema.optionalKey(
9188 Schema.Boolean.annotate({
9189 description:
9190 "When true, reconcile the official curated marketplace against the remote plugin state before listing marketplaces.",
9191 }),
9192 ),
9193});
9194
9195export type ClientRequest__PluginReadParams = {
9196 readonly marketplacePath: ClientRequest__AbsolutePathBuf;
9197 readonly pluginName: string;
9198};
9199export const ClientRequest__PluginReadParams = Schema.Struct({
9200 marketplacePath: ClientRequest__AbsolutePathBuf,
9201 pluginName: Schema.String,
9202});
9203
9204export type ClientRequest__SandboxPolicy =
9205 | { readonly type: "dangerFullAccess" }
9206 | {
9207 readonly access?:
9208 | {
9209 readonly includePlatformDefaults?: boolean;
9210 readonly readableRoots?: ReadonlyArray<ClientRequest__AbsolutePathBuf>;
9211 readonly type: "restricted";
9212 }
9213 | { readonly type: "fullAccess" };
9214 readonly networkAccess?: boolean;
9215 readonly type: "readOnly";
9216 }
9217 | { readonly networkAccess?: "restricted" | "enabled"; readonly type: "externalSandbox" }
9218 | {
9219 readonly excludeSlashTmp?: boolean;
9220 readonly excludeTmpdirEnvVar?: boolean;
9221 readonly networkAccess?: boolean;
9222 readonly readOnlyAccess?:
9223 | {
9224 readonly includePlatformDefaults?: boolean;
9225 readonly readableRoots?: ReadonlyArray<ClientRequest__AbsolutePathBuf>;
9226 readonly type: "restricted";
9227 }
9228 | { readonly type: "fullAccess" };
9229 readonly type: "workspaceWrite";
9230 readonly writableRoots?: ReadonlyArray<ClientRequest__AbsolutePathBuf>;
9231 };
9232export const ClientRequest__SandboxPolicy = Schema.Union(
9233 [
9234 Schema.Struct({
9235 type: Schema.Literal("dangerFullAccess").annotate({
9236 title: "DangerFullAccessSandboxPolicyType",
9237 }),
9238 }).annotate({ title: "DangerFullAccessSandboxPolicy" }),
9239 Schema.Struct({
9240 access: Schema.optionalKey(
9241 Schema.Union(
9242 [
9243 Schema.Struct({
9244 includePlatformDefaults: Schema.optionalKey(
9245 Schema.Boolean.annotate({ default: true }),
9246 ),
9247 readableRoots: Schema.optionalKey(
9248 Schema.Array(ClientRequest__AbsolutePathBuf).annotate({ default: [] }),
9249 ),
9250 type: Schema.Literal("restricted").annotate({
9251 title: "RestrictedReadOnlyAccessType",
9252 }),
9253 }).annotate({ title: "RestrictedReadOnlyAccess" }),
9254 Schema.Struct({
9255 type: Schema.Literal("fullAccess").annotate({
9256 title: "FullAccessReadOnlyAccessType",
9257 }),
9258 }).annotate({ title: "FullAccessReadOnlyAccess" }),
9259 ],
9260 { mode: "oneOf" },
9261 ).annotate({ default: { type: "fullAccess" } }),
9262 ),
9263 networkAccess: Schema.optionalKey(Schema.Boolean.annotate({ default: false })),
9264 type: Schema.Literal("readOnly").annotate({ title: "ReadOnlySandboxPolicyType" }),
9265 }).annotate({ title: "ReadOnlySandboxPolicy" }),
9266 Schema.Struct({
9267 networkAccess: Schema.optionalKey(
9268 Schema.Literals(["restricted", "enabled"]).annotate({ default: "restricted" }),
9269 ),
9270 type: Schema.Literal("externalSandbox").annotate({
9271 title: "ExternalSandboxSandboxPolicyType",
9272 }),
9273 }).annotate({ title: "ExternalSandboxSandboxPolicy" }),
9274 Schema.Struct({
9275 excludeSlashTmp: Schema.optionalKey(Schema.Boolean.annotate({ default: false })),
9276 excludeTmpdirEnvVar: Schema.optionalKey(Schema.Boolean.annotate({ default: false })),
9277 networkAccess: Schema.optionalKey(Schema.Boolean.annotate({ default: false })),
9278 readOnlyAccess: Schema.optionalKey(
9279 Schema.Union(
9280 [
9281 Schema.Struct({
9282 includePlatformDefaults: Schema.optionalKey(
9283 Schema.Boolean.annotate({ default: true }),
9284 ),
9285 readableRoots: Schema.optionalKey(
9286 Schema.Array(ClientRequest__AbsolutePathBuf).annotate({ default: [] }),
9287 ),
9288 type: Schema.Literal("restricted").annotate({
9289 title: "RestrictedReadOnlyAccessType",
9290 }),
9291 }).annotate({ title: "RestrictedReadOnlyAccess" }),
9292 Schema.Struct({
9293 type: Schema.Literal("fullAccess").annotate({
9294 title: "FullAccessReadOnlyAccessType",
9295 }),
9296 }).annotate({ title: "FullAccessReadOnlyAccess" }),
9297 ],
9298 { mode: "oneOf" },
9299 ).annotate({ default: { type: "fullAccess" } }),
9300 ),
9301 type: Schema.Literal("workspaceWrite").annotate({ title: "WorkspaceWriteSandboxPolicyType" }),
9302 writableRoots: Schema.optionalKey(
9303 Schema.Array(ClientRequest__AbsolutePathBuf).annotate({ default: [] }),
9304 ),
9305 }).annotate({ title: "WorkspaceWriteSandboxPolicy" }),
9306 ],
9307 { mode: "oneOf" },
9308);
9309
9310export type ClientRequest__SkillsConfigWriteParams = {
9311 readonly enabled: boolean;
9312 readonly name?: string | null;
9313 readonly path?: ClientRequest__AbsolutePathBuf | null;
9314};
9315export const ClientRequest__SkillsConfigWriteParams = Schema.Struct({
9316 enabled: Schema.Boolean,
9317 name: Schema.optionalKey(
9318 Schema.Union([Schema.String.annotate({ description: "Name-based selector." }), Schema.Null]),
9319 ),
9320 path: Schema.optionalKey(
9321 Schema.Union([ClientRequest__AbsolutePathBuf, Schema.Null]).annotate({
9322 description: "Path-based selector.",
9323 }),
9324 ),
9325});
9326
9327export type ClientRequest__ExternalAgentConfigMigrationItem = {
9328 readonly cwd?: string | null;
9329 readonly description: string;
9330 readonly itemType: ClientRequest__ExternalAgentConfigMigrationItemType;
9331};
9332export const ClientRequest__ExternalAgentConfigMigrationItem = Schema.Struct({
9333 cwd: Schema.optionalKey(
9334 Schema.Union([
9335 Schema.String.annotate({
9336 description:
9337 "Null or empty means home-scoped migration; non-empty means repo-scoped migration.",
9338 }),
9339 Schema.Null,
9340 ]),
9341 ),
9342 description: Schema.String,
9343 itemType: ClientRequest__ExternalAgentConfigMigrationItemType,
9344});
9345
9346export type ClientRequest__FunctionCallOutputContentItem =
9347 | { readonly text: string; readonly type: "input_text" }
9348 | {
9349 readonly detail?: ClientRequest__ImageDetail | null;
9350 readonly image_url: string;
9351 readonly type: "input_image";
9352 };
9353export const ClientRequest__FunctionCallOutputContentItem = Schema.Union(
9354 [
9355 Schema.Struct({
9356 text: Schema.String,
9357 type: Schema.Literal("input_text").annotate({
9358 title: "InputTextFunctionCallOutputContentItemType",
9359 }),
9360 }).annotate({ title: "InputTextFunctionCallOutputContentItem" }),
9361 Schema.Struct({
9362 detail: Schema.optionalKey(Schema.Union([ClientRequest__ImageDetail, Schema.Null])),
9363 image_url: Schema.String,
9364 type: Schema.Literal("input_image").annotate({
9365 title: "InputImageFunctionCallOutputContentItemType",
9366 }),
9367 }).annotate({ title: "InputImageFunctionCallOutputContentItem" }),
9368 ],
9369 { mode: "oneOf" },
9370).annotate({
9371 description:
9372 "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.",
9373});
9374
9375export type ClientRequest__InitializeParams = {
9376 readonly capabilities?: ClientRequest__InitializeCapabilities | null;
9377 readonly clientInfo: ClientRequest__ClientInfo;
9378};
9379export const ClientRequest__InitializeParams = Schema.Struct({
9380 capabilities: Schema.optionalKey(
9381 Schema.Union([ClientRequest__InitializeCapabilities, Schema.Null]),
9382 ),
9383 clientInfo: ClientRequest__ClientInfo,
9384});
9385
9386export type ClientRequest__ListMcpServerStatusParams = {
9387 readonly cursor?: string | null;
9388 readonly detail?: ClientRequest__McpServerStatusDetail | null;
9389 readonly limit?: number | null;
9390};
9391export const ClientRequest__ListMcpServerStatusParams = Schema.Struct({
9392 cursor: Schema.optionalKey(
9393 Schema.Union([
9394 Schema.String.annotate({
9395 description: "Opaque pagination cursor returned by a previous call.",
9396 }),
9397 Schema.Null,
9398 ]),
9399 ),
9400 detail: Schema.optionalKey(
9401 Schema.Union([ClientRequest__McpServerStatusDetail, Schema.Null]).annotate({
9402 description:
9403 "Controls how much MCP inventory data to fetch for each server. Defaults to `Full` when omitted.",
9404 }),
9405 ),
9406 limit: Schema.optionalKey(
9407 Schema.Union([
9408 Schema.Number.annotate({
9409 description: "Optional page size; defaults to a server-defined value.",
9410 format: "uint32",
9411 })
9412 .check(Schema.isInt())
9413 .check(Schema.isGreaterThanOrEqualTo(0)),
9414 Schema.Null,
9415 ]),
9416 ),
9417});
9418
9419export type ClientRequest__ConfigEdit = {
9420 readonly keyPath: string;
9421 readonly mergeStrategy: ClientRequest__MergeStrategy;
9422 readonly value: unknown;
9423};
9424export const ClientRequest__ConfigEdit = Schema.Struct({
9425 keyPath: Schema.String,
9426 mergeStrategy: ClientRequest__MergeStrategy,
9427 value: Schema.Unknown,
9428});
9429
9430export type ClientRequest__ConfigValueWriteParams = {
9431 readonly expectedVersion?: string | null;
9432 readonly filePath?: string | null;
9433 readonly keyPath: string;
9434 readonly mergeStrategy: ClientRequest__MergeStrategy;
9435 readonly value: unknown;
9436};
9437export const ClientRequest__ConfigValueWriteParams = Schema.Struct({
9438 expectedVersion: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
9439 filePath: Schema.optionalKey(
9440 Schema.Union([
9441 Schema.String.annotate({
9442 description:
9443 "Path to the config file to write; defaults to the user's `config.toml` when omitted.",
9444 }),
9445 Schema.Null,
9446 ]),
9447 ),
9448 keyPath: Schema.String,
9449 mergeStrategy: ClientRequest__MergeStrategy,
9450 value: Schema.Unknown,
9451});
9452
9453export type ClientRequest__Settings = {
9454 readonly developer_instructions?: string | null;
9455 readonly model: string;
9456 readonly reasoning_effort?: ClientRequest__ReasoningEffort | null;
9457};
9458export const ClientRequest__Settings = Schema.Struct({
9459 developer_instructions: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
9460 model: Schema.String,
9461 reasoning_effort: Schema.optionalKey(Schema.Union([ClientRequest__ReasoningEffort, Schema.Null])),
9462}).annotate({ description: "Settings for a collaboration mode." });
9463
9464export type ClientRequest__ReviewStartParams = {
9465 readonly delivery?: ClientRequest__ReviewDelivery | null;
9466 readonly target: ClientRequest__ReviewTarget;
9467 readonly threadId: string;
9468};
9469export const ClientRequest__ReviewStartParams = Schema.Struct({
9470 delivery: Schema.optionalKey(
9471 Schema.Union([ClientRequest__ReviewDelivery, Schema.Null]).annotate({
9472 description:
9473 "Where to run the review: inline (default) on the current thread or detached on a new thread (returned in `reviewThreadId`).",
9474 }),
9475 ),
9476 target: ClientRequest__ReviewTarget,
9477 threadId: Schema.String,
9478});
9479
9480export type ClientRequest__ThreadForkParams = {
9481 readonly approvalPolicy?: ClientRequest__AskForApproval | null;
9482 readonly approvalsReviewer?: ClientRequest__ApprovalsReviewer | null;
9483 readonly baseInstructions?: string | null;
9484 readonly config?: { readonly [x: string]: unknown } | null;
9485 readonly cwd?: string | null;
9486 readonly developerInstructions?: string | null;
9487 readonly ephemeral?: boolean;
9488 readonly model?: string | null;
9489 readonly modelProvider?: string | null;
9490 readonly sandbox?: ClientRequest__SandboxMode | null;
9491 readonly serviceTier?: ClientRequest__ServiceTier | null | null;
9492 readonly threadId: string;
9493};
9494export const ClientRequest__ThreadForkParams = Schema.Struct({
9495 approvalPolicy: Schema.optionalKey(Schema.Union([ClientRequest__AskForApproval, Schema.Null])),
9496 approvalsReviewer: Schema.optionalKey(
9497 Schema.Union([ClientRequest__ApprovalsReviewer, Schema.Null]).annotate({
9498 description:
9499 "Override where approval requests are routed for review on this thread and subsequent turns.",
9500 }),
9501 ),
9502 baseInstructions: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
9503 config: Schema.optionalKey(
9504 Schema.Union([Schema.Record(Schema.String, Schema.Unknown), Schema.Null]),
9505 ),
9506 cwd: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
9507 developerInstructions: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
9508 ephemeral: Schema.optionalKey(Schema.Boolean),
9509 model: Schema.optionalKey(
9510 Schema.Union([
9511 Schema.String.annotate({
9512 description: "Configuration overrides for the forked thread, if any.",
9513 }),
9514 Schema.Null,
9515 ]),
9516 ),
9517 modelProvider: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
9518 sandbox: Schema.optionalKey(Schema.Union([ClientRequest__SandboxMode, Schema.Null])),
9519 serviceTier: Schema.optionalKey(
9520 Schema.Union([Schema.Union([ClientRequest__ServiceTier, Schema.Null]), Schema.Null]),
9521 ),
9522 threadId: Schema.String,
9523}).annotate({
9524 description:
9525 "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.",
9526});
9527
9528export type ClientRequest__ThreadResumeParams = {
9529 readonly approvalPolicy?: ClientRequest__AskForApproval | null;
9530 readonly approvalsReviewer?: ClientRequest__ApprovalsReviewer | null;
9531 readonly baseInstructions?: string | null;
9532 readonly config?: { readonly [x: string]: unknown } | null;
9533 readonly cwd?: string | null;
9534 readonly developerInstructions?: string | null;
9535 readonly model?: string | null;
9536 readonly modelProvider?: string | null;
9537 readonly personality?: ClientRequest__Personality | null;
9538 readonly sandbox?: ClientRequest__SandboxMode | null;
9539 readonly serviceTier?: ClientRequest__ServiceTier | null | null;
9540 readonly threadId: string;
9541};
9542export const ClientRequest__ThreadResumeParams = Schema.Struct({
9543 approvalPolicy: Schema.optionalKey(Schema.Union([ClientRequest__AskForApproval, Schema.Null])),
9544 approvalsReviewer: Schema.optionalKey(
9545 Schema.Union([ClientRequest__ApprovalsReviewer, Schema.Null]).annotate({
9546 description:
9547 "Override where approval requests are routed for review on this thread and subsequent turns.",
9548 }),
9549 ),
9550 baseInstructions: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
9551 config: Schema.optionalKey(
9552 Schema.Union([Schema.Record(Schema.String, Schema.Unknown), Schema.Null]),
9553 ),
9554 cwd: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
9555 developerInstructions: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
9556 model: Schema.optionalKey(
9557 Schema.Union([
9558 Schema.String.annotate({
9559 description: "Configuration overrides for the resumed thread, if any.",
9560 }),
9561 Schema.Null,
9562 ]),
9563 ),
9564 modelProvider: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
9565 personality: Schema.optionalKey(Schema.Union([ClientRequest__Personality, Schema.Null])),
9566 sandbox: Schema.optionalKey(Schema.Union([ClientRequest__SandboxMode, Schema.Null])),
9567 serviceTier: Schema.optionalKey(
9568 Schema.Union([Schema.Union([ClientRequest__ServiceTier, Schema.Null]), Schema.Null]),
9569 ),
9570 threadId: Schema.String,
9571}).annotate({
9572 description:
9573 "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.",
9574});
9575
9576export type ClientRequest__SkillsListParams = {
9577 readonly cwds?: ReadonlyArray<string>;
9578 readonly forceReload?: boolean;
9579 readonly perCwdExtraUserRoots?: ReadonlyArray<ClientRequest__SkillsListExtraRootsForCwd> | null;
9580};
9581export const ClientRequest__SkillsListParams = Schema.Struct({
9582 cwds: Schema.optionalKey(
9583 Schema.Array(Schema.String).annotate({
9584 description: "When empty, defaults to the current session working directory.",
9585 }),
9586 ),
9587 forceReload: Schema.optionalKey(
9588 Schema.Boolean.annotate({
9589 description: "When true, bypass the skills cache and re-scan skills from disk.",
9590 }),
9591 ),
9592 perCwdExtraUserRoots: Schema.optionalKey(
9593 Schema.Union([
9594 Schema.Array(ClientRequest__SkillsListExtraRootsForCwd).annotate({
9595 description: "Optional per-cwd extra roots to scan as user-scoped skills.",
9596 }),
9597 Schema.Null,
9598 ]),
9599 ),
9600});
9601
9602export type ClientRequest__UserInput =
9603 | {
9604 readonly text: string;
9605 readonly text_elements?: ReadonlyArray<ClientRequest__TextElement>;
9606 readonly type: "text";
9607 }
9608 | { readonly type: "image"; readonly url: string }
9609 | { readonly path: string; readonly type: "localImage" }
9610 | { readonly name: string; readonly path: string; readonly type: "skill" }
9611 | { readonly name: string; readonly path: string; readonly type: "mention" };
9612export const ClientRequest__UserInput = Schema.Union(
9613 [
9614 Schema.Struct({
9615 text: Schema.String,
9616 text_elements: Schema.optionalKey(
9617 Schema.Array(ClientRequest__TextElement).annotate({
9618 description: "UI-defined spans within `text` used to render or persist special elements.",
9619 default: [],
9620 }),
9621 ),
9622 type: Schema.Literal("text").annotate({ title: "TextUserInputType" }),
9623 }).annotate({ title: "TextUserInput" }),
9624 Schema.Struct({
9625 type: Schema.Literal("image").annotate({ title: "ImageUserInputType" }),
9626 url: Schema.String,
9627 }).annotate({ title: "ImageUserInput" }),
9628 Schema.Struct({
9629 path: Schema.String,
9630 type: Schema.Literal("localImage").annotate({ title: "LocalImageUserInputType" }),
9631 }).annotate({ title: "LocalImageUserInput" }),
9632 Schema.Struct({
9633 name: Schema.String,
9634 path: Schema.String,
9635 type: Schema.Literal("skill").annotate({ title: "SkillUserInputType" }),
9636 }).annotate({ title: "SkillUserInput" }),
9637 Schema.Struct({
9638 name: Schema.String,
9639 path: Schema.String,
9640 type: Schema.Literal("mention").annotate({ title: "MentionUserInputType" }),
9641 }).annotate({ title: "MentionUserInput" }),
9642 ],
9643 { mode: "oneOf" },
9644);
9645
9646export type ClientRequest__ThreadMetadataUpdateParams = {
9647 readonly gitInfo?: ClientRequest__ThreadMetadataGitInfoUpdateParams | null;
9648 readonly threadId: string;
9649};
9650export const ClientRequest__ThreadMetadataUpdateParams = Schema.Struct({
9651 gitInfo: Schema.optionalKey(
9652 Schema.Union([ClientRequest__ThreadMetadataGitInfoUpdateParams, Schema.Null]).annotate({
9653 description:
9654 "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.",
9655 }),
9656 ),
9657 threadId: Schema.String,
9658});
9659
9660export type ClientRequest__ThreadListParams = {
9661 readonly archived?: boolean | null;
9662 readonly cursor?: string | null;
9663 readonly cwd?: string | null;
9664 readonly limit?: number | null;
9665 readonly modelProviders?: ReadonlyArray<string> | null;
9666 readonly searchTerm?: string | null;
9667 readonly sortKey?: ClientRequest__ThreadSortKey | null;
9668 readonly sourceKinds?: ReadonlyArray<ClientRequest__ThreadSourceKind> | null;
9669};
9670export const ClientRequest__ThreadListParams = Schema.Struct({
9671 archived: Schema.optionalKey(
9672 Schema.Union([
9673 Schema.Boolean.annotate({
9674 description:
9675 "Optional archived filter; when set to true, only archived threads are returned. If false or null, only non-archived threads are returned.",
9676 }),
9677 Schema.Null,
9678 ]),
9679 ),
9680 cursor: Schema.optionalKey(
9681 Schema.Union([
9682 Schema.String.annotate({
9683 description: "Opaque pagination cursor returned by a previous call.",
9684 }),
9685 Schema.Null,
9686 ]),
9687 ),
9688 cwd: Schema.optionalKey(
9689 Schema.Union([
9690 Schema.String.annotate({
9691 description:
9692 "Optional cwd filter; when set, only threads whose session cwd exactly matches this path are returned.",
9693 }),
9694 Schema.Null,
9695 ]),
9696 ),
9697 limit: Schema.optionalKey(
9698 Schema.Union([
9699 Schema.Number.annotate({
9700 description: "Optional page size; defaults to a reasonable server-side value.",
9701 format: "uint32",
9702 })
9703 .check(Schema.isInt())
9704 .check(Schema.isGreaterThanOrEqualTo(0)),
9705 Schema.Null,
9706 ]),
9707 ),
9708 modelProviders: Schema.optionalKey(
9709 Schema.Union([
9710 Schema.Array(Schema.String).annotate({
9711 description:
9712 "Optional provider filter; when set, only sessions recorded under these providers are returned. When present but empty, includes all providers.",
9713 }),
9714 Schema.Null,
9715 ]),
9716 ),
9717 searchTerm: Schema.optionalKey(
9718 Schema.Union([
9719 Schema.String.annotate({
9720 description: "Optional substring filter for the extracted thread title.",
9721 }),
9722 Schema.Null,
9723 ]),
9724 ),
9725 sortKey: Schema.optionalKey(
9726 Schema.Union([ClientRequest__ThreadSortKey, Schema.Null]).annotate({
9727 description: "Optional sort key; defaults to created_at.",
9728 }),
9729 ),
9730 sourceKinds: Schema.optionalKey(
9731 Schema.Union([
9732 Schema.Array(ClientRequest__ThreadSourceKind).annotate({
9733 description:
9734 "Optional source filter; when set, only sessions from these source kinds are returned. When omitted or empty, defaults to interactive sources.",
9735 }),
9736 Schema.Null,
9737 ]),
9738 ),
9739});
9740
9741export type ClientRequest__ThreadStartParams = {
9742 readonly approvalPolicy?: ClientRequest__AskForApproval | null;
9743 readonly approvalsReviewer?: ClientRequest__ApprovalsReviewer | null;
9744 readonly baseInstructions?: string | null;
9745 readonly config?: { readonly [x: string]: unknown } | null;
9746 readonly cwd?: string | null;
9747 readonly developerInstructions?: string | null;
9748 readonly ephemeral?: boolean | null;
9749 readonly model?: string | null;
9750 readonly modelProvider?: string | null;
9751 readonly personality?: ClientRequest__Personality | null;
9752 readonly sandbox?: ClientRequest__SandboxMode | null;
9753 readonly serviceName?: string | null;
9754 readonly serviceTier?: ClientRequest__ServiceTier | null | null;
9755 readonly sessionStartSource?: ClientRequest__ThreadStartSource | null;
9756};
9757export const ClientRequest__ThreadStartParams = Schema.Struct({
9758 approvalPolicy: Schema.optionalKey(Schema.Union([ClientRequest__AskForApproval, Schema.Null])),
9759 approvalsReviewer: Schema.optionalKey(
9760 Schema.Union([ClientRequest__ApprovalsReviewer, Schema.Null]).annotate({
9761 description:
9762 "Override where approval requests are routed for review on this thread and subsequent turns.",
9763 }),
9764 ),
9765 baseInstructions: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
9766 config: Schema.optionalKey(
9767 Schema.Union([Schema.Record(Schema.String, Schema.Unknown), Schema.Null]),
9768 ),
9769 cwd: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
9770 developerInstructions: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
9771 ephemeral: Schema.optionalKey(Schema.Union([Schema.Boolean, Schema.Null])),
9772 model: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
9773 modelProvider: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
9774 personality: Schema.optionalKey(Schema.Union([ClientRequest__Personality, Schema.Null])),
9775 sandbox: Schema.optionalKey(Schema.Union([ClientRequest__SandboxMode, Schema.Null])),
9776 serviceName: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
9777 serviceTier: Schema.optionalKey(
9778 Schema.Union([Schema.Union([ClientRequest__ServiceTier, Schema.Null]), Schema.Null]),
9779 ),
9780 sessionStartSource: Schema.optionalKey(
9781 Schema.Union([ClientRequest__ThreadStartSource, Schema.Null]),
9782 ),
9783});
9784
9785export type ClientRequest__WindowsSandboxSetupStartParams = {
9786 readonly cwd?: ClientRequest__AbsolutePathBuf | null;
9787 readonly mode: ClientRequest__WindowsSandboxSetupMode;
9788};
9789export const ClientRequest__WindowsSandboxSetupStartParams = Schema.Struct({
9790 cwd: Schema.optionalKey(Schema.Union([ClientRequest__AbsolutePathBuf, Schema.Null])),
9791 mode: ClientRequest__WindowsSandboxSetupMode,
9792});
9793
9794export type CommandExecutionRequestApprovalParams__AdditionalFileSystemPermissions = {
9795 readonly read?: ReadonlyArray<CommandExecutionRequestApprovalParams__AbsolutePathBuf> | null;
9796 readonly write?: ReadonlyArray<CommandExecutionRequestApprovalParams__AbsolutePathBuf> | null;
9797};
9798export const CommandExecutionRequestApprovalParams__AdditionalFileSystemPermissions = Schema.Struct(
9799 {
9800 read: Schema.optionalKey(
9801 Schema.Union([
9802 Schema.Array(CommandExecutionRequestApprovalParams__AbsolutePathBuf),
9803 Schema.Null,
9804 ]),
9805 ),
9806 write: Schema.optionalKey(
9807 Schema.Union([
9808 Schema.Array(CommandExecutionRequestApprovalParams__AbsolutePathBuf),
9809 Schema.Null,
9810 ]),
9811 ),
9812 },
9813);
9814
9815export type CommandExecutionRequestApprovalParams__NetworkApprovalContext = {
9816 readonly host: string;
9817 readonly protocol: CommandExecutionRequestApprovalParams__NetworkApprovalProtocol;
9818};
9819export const CommandExecutionRequestApprovalParams__NetworkApprovalContext = Schema.Struct({
9820 host: Schema.String,
9821 protocol: CommandExecutionRequestApprovalParams__NetworkApprovalProtocol,
9822});
9823
9824export type CommandExecutionRequestApprovalParams__NetworkPolicyAmendment = {
9825 readonly action: CommandExecutionRequestApprovalParams__NetworkPolicyRuleAction;
9826 readonly host: string;
9827};
9828export const CommandExecutionRequestApprovalParams__NetworkPolicyAmendment = Schema.Struct({
9829 action: CommandExecutionRequestApprovalParams__NetworkPolicyRuleAction,
9830 host: Schema.String,
9831});
9832
9833export type CommandExecutionRequestApprovalResponse__NetworkPolicyAmendment = {
9834 readonly action: CommandExecutionRequestApprovalResponse__NetworkPolicyRuleAction;
9835 readonly host: string;
9836};
9837export const CommandExecutionRequestApprovalResponse__NetworkPolicyAmendment = Schema.Struct({
9838 action: CommandExecutionRequestApprovalResponse__NetworkPolicyRuleAction,
9839 host: Schema.String,
9840});
9841
9842export type ExecCommandApprovalResponse__NetworkPolicyAmendment = {
9843 readonly action: ExecCommandApprovalResponse__NetworkPolicyRuleAction;
9844 readonly host: string;
9845};
9846export const ExecCommandApprovalResponse__NetworkPolicyAmendment = Schema.Struct({
9847 action: ExecCommandApprovalResponse__NetworkPolicyRuleAction,
9848 host: Schema.String,
9849});
9850
9851export type FuzzyFileSearchResponse__FuzzyFileSearchResult = {
9852 readonly file_name: string;
9853 readonly indices?: ReadonlyArray<number> | null;
9854 readonly match_type: FuzzyFileSearchResponse__FuzzyFileSearchMatchType;
9855 readonly path: string;
9856 readonly root: string;
9857 readonly score: number;
9858};
9859export const FuzzyFileSearchResponse__FuzzyFileSearchResult = Schema.Struct({
9860 file_name: Schema.String,
9861 indices: Schema.optionalKey(
9862 Schema.Union([
9863 Schema.Array(
9864 Schema.Number.annotate({ format: "uint32" })
9865 .check(Schema.isInt())
9866 .check(Schema.isGreaterThanOrEqualTo(0)),
9867 ),
9868 Schema.Null,
9869 ]),
9870 ),
9871 match_type: FuzzyFileSearchResponse__FuzzyFileSearchMatchType,
9872 path: Schema.String,
9873 root: Schema.String,
9874 score: Schema.Number.annotate({ format: "uint32" })
9875 .check(Schema.isInt())
9876 .check(Schema.isGreaterThanOrEqualTo(0)),
9877}).annotate({ description: "Superset of [`codex_file_search::FileMatch`]" });
9878
9879export type FuzzyFileSearchSessionUpdatedNotification__FuzzyFileSearchResult = {
9880 readonly file_name: string;
9881 readonly indices?: ReadonlyArray<number> | null;
9882 readonly match_type: FuzzyFileSearchSessionUpdatedNotification__FuzzyFileSearchMatchType;
9883 readonly path: string;
9884 readonly root: string;
9885 readonly score: number;
9886};
9887export const FuzzyFileSearchSessionUpdatedNotification__FuzzyFileSearchResult = Schema.Struct({
9888 file_name: Schema.String,
9889 indices: Schema.optionalKey(
9890 Schema.Union([
9891 Schema.Array(
9892 Schema.Number.annotate({ format: "uint32" })
9893 .check(Schema.isInt())
9894 .check(Schema.isGreaterThanOrEqualTo(0)),
9895 ),
9896 Schema.Null,
9897 ]),
9898 ),
9899 match_type: FuzzyFileSearchSessionUpdatedNotification__FuzzyFileSearchMatchType,
9900 path: Schema.String,
9901 root: Schema.String,
9902 score: Schema.Number.annotate({ format: "uint32" })
9903 .check(Schema.isInt())
9904 .check(Schema.isGreaterThanOrEqualTo(0)),
9905}).annotate({ description: "Superset of [`codex_file_search::FileMatch`]" });
9906
9907export type JSONRPCMessage__JSONRPCError = {
9908 readonly error: JSONRPCMessage__JSONRPCErrorError;
9909 readonly id: JSONRPCMessage__RequestId;
9910};
9911export const JSONRPCMessage__JSONRPCError = Schema.Struct({
9912 error: JSONRPCMessage__JSONRPCErrorError,
9913 id: JSONRPCMessage__RequestId,
9914}).annotate({ description: "A response to a request that indicates an error occurred." });
9915
9916export type JSONRPCMessage__JSONRPCResponse = {
9917 readonly id: JSONRPCMessage__RequestId;
9918 readonly result: unknown;
9919};
9920export const JSONRPCMessage__JSONRPCResponse = Schema.Struct({
9921 id: JSONRPCMessage__RequestId,
9922 result: Schema.Unknown,
9923}).annotate({ description: "A successful (non-error) response to a request." });
9924
9925export type JSONRPCMessage__JSONRPCRequest = {
9926 readonly id: JSONRPCMessage__RequestId;
9927 readonly method: string;
9928 readonly params?: unknown;
9929 readonly trace?: JSONRPCMessage__W3cTraceContext | null;
9930};
9931export const JSONRPCMessage__JSONRPCRequest = Schema.Struct({
9932 id: JSONRPCMessage__RequestId,
9933 method: Schema.String,
9934 params: Schema.optionalKey(Schema.Unknown),
9935 trace: Schema.optionalKey(
9936 Schema.Union([JSONRPCMessage__W3cTraceContext, Schema.Null]).annotate({
9937 description: "Optional W3C Trace Context for distributed tracing.",
9938 }),
9939 ),
9940}).annotate({ description: "A request that expects a response." });
9941
9942export type McpServerElicitationRequestParams__McpElicitationBooleanSchema = {
9943 readonly default?: boolean | null;
9944 readonly description?: string | null;
9945 readonly title?: string | null;
9946 readonly type: McpServerElicitationRequestParams__McpElicitationBooleanType;
9947};
9948export const McpServerElicitationRequestParams__McpElicitationBooleanSchema = Schema.Struct({
9949 default: Schema.optionalKey(Schema.Union([Schema.Boolean, Schema.Null])),
9950 description: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
9951 title: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
9952 type: McpServerElicitationRequestParams__McpElicitationBooleanType,
9953});
9954
9955export type McpServerElicitationRequestParams__McpElicitationTitledEnumItems = {
9956 readonly anyOf: ReadonlyArray<McpServerElicitationRequestParams__McpElicitationConstOption>;
9957};
9958export const McpServerElicitationRequestParams__McpElicitationTitledEnumItems = Schema.Struct({
9959 anyOf: Schema.Array(McpServerElicitationRequestParams__McpElicitationConstOption),
9960});
9961
9962export type McpServerElicitationRequestParams__McpElicitationNumberSchema = {
9963 readonly default?: number | null;
9964 readonly description?: string | null;
9965 readonly maximum?: number | null;
9966 readonly minimum?: number | null;
9967 readonly title?: string | null;
9968 readonly type: McpServerElicitationRequestParams__McpElicitationNumberType;
9969};
9970export const McpServerElicitationRequestParams__McpElicitationNumberSchema = Schema.Struct({
9971 default: Schema.optionalKey(
9972 Schema.Union([
9973 Schema.Number.annotate({ format: "double" }).check(Schema.isFinite()),
9974 Schema.Null,
9975 ]),
9976 ),
9977 description: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
9978 maximum: Schema.optionalKey(
9979 Schema.Union([
9980 Schema.Number.annotate({ format: "double" }).check(Schema.isFinite()),
9981 Schema.Null,
9982 ]),
9983 ),
9984 minimum: Schema.optionalKey(
9985 Schema.Union([
9986 Schema.Number.annotate({ format: "double" }).check(Schema.isFinite()),
9987 Schema.Null,
9988 ]),
9989 ),
9990 title: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
9991 type: McpServerElicitationRequestParams__McpElicitationNumberType,
9992});
9993
9994export type McpServerElicitationRequestParams__McpElicitationLegacyTitledEnumSchema = {
9995 readonly default?: string | null;
9996 readonly description?: string | null;
9997 readonly enum: ReadonlyArray<string>;
9998 readonly enumNames?: ReadonlyArray<string> | null;
9999 readonly title?: string | null;
10000 readonly type: McpServerElicitationRequestParams__McpElicitationStringType;
10001};
10002export const McpServerElicitationRequestParams__McpElicitationLegacyTitledEnumSchema =
10003 Schema.Struct({
10004 default: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
10005 description: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
10006 enum: Schema.Array(Schema.String),
10007 enumNames: Schema.optionalKey(Schema.Union([Schema.Array(Schema.String), Schema.Null])),
10008 title: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
10009 type: McpServerElicitationRequestParams__McpElicitationStringType,
10010 });
10011
10012export type McpServerElicitationRequestParams__McpElicitationStringSchema = {
10013 readonly default?: string | null;
10014 readonly description?: string | null;
10015 readonly format?: McpServerElicitationRequestParams__McpElicitationStringFormat | null;
10016 readonly maxLength?: number | null;
10017 readonly minLength?: number | null;
10018 readonly title?: string | null;
10019 readonly type: McpServerElicitationRequestParams__McpElicitationStringType;
10020};
10021export const McpServerElicitationRequestParams__McpElicitationStringSchema = Schema.Struct({
10022 default: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
10023 description: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
10024 format: Schema.optionalKey(
10025 Schema.Union([McpServerElicitationRequestParams__McpElicitationStringFormat, Schema.Null]),
10026 ),
10027 maxLength: Schema.optionalKey(
10028 Schema.Union([
10029 Schema.Number.annotate({ format: "uint32" })
10030 .check(Schema.isInt())
10031 .check(Schema.isGreaterThanOrEqualTo(0)),
10032 Schema.Null,
10033 ]),
10034 ),
10035 minLength: Schema.optionalKey(
10036 Schema.Union([
10037 Schema.Number.annotate({ format: "uint32" })
10038 .check(Schema.isInt())
10039 .check(Schema.isGreaterThanOrEqualTo(0)),
10040 Schema.Null,
10041 ]),
10042 ),
10043 title: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
10044 type: McpServerElicitationRequestParams__McpElicitationStringType,
10045});
10046
10047export type McpServerElicitationRequestParams__McpElicitationTitledSingleSelectEnumSchema = {
10048 readonly default?: string | null;
10049 readonly description?: string | null;
10050 readonly oneOf: ReadonlyArray<McpServerElicitationRequestParams__McpElicitationConstOption>;
10051 readonly title?: string | null;
10052 readonly type: McpServerElicitationRequestParams__McpElicitationStringType;
10053};
10054export const McpServerElicitationRequestParams__McpElicitationTitledSingleSelectEnumSchema =
10055 Schema.Struct({
10056 default: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
10057 description: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
10058 oneOf: Schema.Array(McpServerElicitationRequestParams__McpElicitationConstOption),
10059 title: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
10060 type: McpServerElicitationRequestParams__McpElicitationStringType,
10061 });
10062
10063export type McpServerElicitationRequestParams__McpElicitationUntitledEnumItems = {
10064 readonly enum: ReadonlyArray<string>;
10065 readonly type: McpServerElicitationRequestParams__McpElicitationStringType;
10066};
10067export const McpServerElicitationRequestParams__McpElicitationUntitledEnumItems = Schema.Struct({
10068 enum: Schema.Array(Schema.String),
10069 type: McpServerElicitationRequestParams__McpElicitationStringType,
10070});
10071
10072export type McpServerElicitationRequestParams__McpElicitationUntitledSingleSelectEnumSchema = {
10073 readonly default?: string | null;
10074 readonly description?: string | null;
10075 readonly enum: ReadonlyArray<string>;
10076 readonly title?: string | null;
10077 readonly type: McpServerElicitationRequestParams__McpElicitationStringType;
10078};
10079export const McpServerElicitationRequestParams__McpElicitationUntitledSingleSelectEnumSchema =
10080 Schema.Struct({
10081 default: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
10082 description: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
10083 enum: Schema.Array(Schema.String),
10084 title: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
10085 type: McpServerElicitationRequestParams__McpElicitationStringType,
10086 });
10087
10088export type PermissionsRequestApprovalParams__AdditionalFileSystemPermissions = {
10089 readonly read?: ReadonlyArray<PermissionsRequestApprovalParams__AbsolutePathBuf> | null;
10090 readonly write?: ReadonlyArray<PermissionsRequestApprovalParams__AbsolutePathBuf> | null;
10091};
10092export const PermissionsRequestApprovalParams__AdditionalFileSystemPermissions = Schema.Struct({
10093 read: Schema.optionalKey(
10094 Schema.Union([Schema.Array(PermissionsRequestApprovalParams__AbsolutePathBuf), Schema.Null]),
10095 ),
10096 write: Schema.optionalKey(
10097 Schema.Union([Schema.Array(PermissionsRequestApprovalParams__AbsolutePathBuf), Schema.Null]),
10098 ),
10099});
10100
10101export type PermissionsRequestApprovalResponse__AdditionalFileSystemPermissions = {
10102 readonly read?: ReadonlyArray<PermissionsRequestApprovalResponse__AbsolutePathBuf> | null;
10103 readonly write?: ReadonlyArray<PermissionsRequestApprovalResponse__AbsolutePathBuf> | null;
10104};
10105export const PermissionsRequestApprovalResponse__AdditionalFileSystemPermissions = Schema.Struct({
10106 read: Schema.optionalKey(
10107 Schema.Union([Schema.Array(PermissionsRequestApprovalResponse__AbsolutePathBuf), Schema.Null]),
10108 ),
10109 write: Schema.optionalKey(
10110 Schema.Union([Schema.Array(PermissionsRequestApprovalResponse__AbsolutePathBuf), Schema.Null]),
10111 ),
10112});
10113
10114export type ServerNotification__FsChangedNotification = {
10115 readonly changedPaths: ReadonlyArray<ServerNotification__AbsolutePathBuf>;
10116 readonly watchId: string;
10117};
10118export const ServerNotification__FsChangedNotification = Schema.Struct({
10119 changedPaths: Schema.Array(ServerNotification__AbsolutePathBuf).annotate({
10120 description: "File or directory paths associated with this event.",
10121 }),
10122 watchId: Schema.String.annotate({
10123 description: "Watch identifier previously provided to `fs/watch`.",
10124 }),
10125}).annotate({ description: "Filesystem watch notification emitted for `fs/watch` subscribers." });
10126
10127export type ServerNotification__AppMetadata = {
10128 readonly categories?: ReadonlyArray<string> | null;
10129 readonly developer?: string | null;
10130 readonly firstPartyRequiresInstall?: boolean | null;
10131 readonly firstPartyType?: string | null;
10132 readonly review?: ServerNotification__AppReview | null;
10133 readonly screenshots?: ReadonlyArray<ServerNotification__AppScreenshot> | null;
10134 readonly seoDescription?: string | null;
10135 readonly showInComposerWhenUnlinked?: boolean | null;
10136 readonly subCategories?: ReadonlyArray<string> | null;
10137 readonly version?: string | null;
10138 readonly versionId?: string | null;
10139 readonly versionNotes?: string | null;
10140};
10141export const ServerNotification__AppMetadata = Schema.Struct({
10142 categories: Schema.optionalKey(Schema.Union([Schema.Array(Schema.String), Schema.Null])),
10143 developer: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
10144 firstPartyRequiresInstall: Schema.optionalKey(Schema.Union([Schema.Boolean, Schema.Null])),
10145 firstPartyType: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
10146 review: Schema.optionalKey(Schema.Union([ServerNotification__AppReview, Schema.Null])),
10147 screenshots: Schema.optionalKey(
10148 Schema.Union([Schema.Array(ServerNotification__AppScreenshot), Schema.Null]),
10149 ),
10150 seoDescription: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
10151 showInComposerWhenUnlinked: Schema.optionalKey(Schema.Union([Schema.Boolean, Schema.Null])),
10152 subCategories: Schema.optionalKey(Schema.Union([Schema.Array(Schema.String), Schema.Null])),
10153 version: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
10154 versionId: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
10155 versionNotes: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
10156});
10157
10158export type ServerNotification__CollabAgentState = {
10159 readonly message?: string | null;
10160 readonly status: ServerNotification__CollabAgentStatus;
10161};
10162export const ServerNotification__CollabAgentState = Schema.Struct({
10163 message: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
10164 status: ServerNotification__CollabAgentStatus,
10165});
10166
10167export type ServerNotification__FuzzyFileSearchResult = {
10168 readonly file_name: string;
10169 readonly indices?: ReadonlyArray<number> | null;
10170 readonly match_type: ServerNotification__FuzzyFileSearchMatchType;
10171 readonly path: string;
10172 readonly root: string;
10173 readonly score: number;
10174};
10175export const ServerNotification__FuzzyFileSearchResult = Schema.Struct({
10176 file_name: Schema.String,
10177 indices: Schema.optionalKey(
10178 Schema.Union([
10179 Schema.Array(
10180 Schema.Number.annotate({ format: "uint32" })
10181 .check(Schema.isInt())
10182 .check(Schema.isGreaterThanOrEqualTo(0)),
10183 ),
10184 Schema.Null,
10185 ]),
10186 ),
10187 match_type: ServerNotification__FuzzyFileSearchMatchType,
10188 path: Schema.String,
10189 root: Schema.String,
10190 score: Schema.Number.annotate({ format: "uint32" })
10191 .check(Schema.isInt())
10192 .check(Schema.isGreaterThanOrEqualTo(0)),
10193}).annotate({ description: "Superset of [`codex_file_search::FileMatch`]" });
10194
10195export type ServerNotification__GuardianApprovalReview = {
10196 readonly rationale?: string | null;
10197 readonly riskLevel?: ServerNotification__GuardianRiskLevel | null;
10198 readonly status: ServerNotification__GuardianApprovalReviewStatus;
10199 readonly userAuthorization?: ServerNotification__GuardianUserAuthorization | null;
10200};
10201export const ServerNotification__GuardianApprovalReview = Schema.Struct({
10202 rationale: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
10203 riskLevel: Schema.optionalKey(Schema.Union([ServerNotification__GuardianRiskLevel, Schema.Null])),
10204 status: ServerNotification__GuardianApprovalReviewStatus,
10205 userAuthorization: Schema.optionalKey(
10206 Schema.Union([ServerNotification__GuardianUserAuthorization, Schema.Null]),
10207 ),
10208}).annotate({
10209 description:
10210 "[UNSTABLE] Temporary guardian approval review payload used by `item/autoApprovalReview/*` notifications. This shape is expected to change soon.",
10211});
10212
10213export type ServerNotification__HookOutputEntry = {
10214 readonly kind: ServerNotification__HookOutputEntryKind;
10215 readonly text: string;
10216};
10217export const ServerNotification__HookOutputEntry = Schema.Struct({
10218 kind: ServerNotification__HookOutputEntryKind,
10219 text: Schema.String,
10220});
10221
10222export type ServerNotification__McpServerStatusUpdatedNotification = {
10223 readonly error?: string | null;
10224 readonly name: string;
10225 readonly status: ServerNotification__McpServerStartupState;
10226};
10227export const ServerNotification__McpServerStatusUpdatedNotification = Schema.Struct({
10228 error: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
10229 name: Schema.String,
10230 status: ServerNotification__McpServerStartupState,
10231});
10232
10233export type ServerNotification__MemoryCitation = {
10234 readonly entries: ReadonlyArray<ServerNotification__MemoryCitationEntry>;
10235 readonly threadIds: ReadonlyArray<string>;
10236};
10237export const ServerNotification__MemoryCitation = Schema.Struct({
10238 entries: Schema.Array(ServerNotification__MemoryCitationEntry),
10239 threadIds: Schema.Array(Schema.String),
10240});
10241
10242export type ServerNotification__ModelReroutedNotification = {
10243 readonly fromModel: string;
10244 readonly reason: ServerNotification__ModelRerouteReason;
10245 readonly threadId: string;
10246 readonly toModel: string;
10247 readonly turnId: string;
10248};
10249export const ServerNotification__ModelReroutedNotification = Schema.Struct({
10250 fromModel: Schema.String,
10251 reason: ServerNotification__ModelRerouteReason,
10252 threadId: Schema.String,
10253 toModel: Schema.String,
10254 turnId: Schema.String,
10255});
10256
10257export type ServerNotification__GuardianApprovalReviewAction =
10258 | {
10259 readonly command: string;
10260 readonly cwd: string;
10261 readonly source: ServerNotification__GuardianCommandSource;
10262 readonly type: "command";
10263 }
10264 | {
10265 readonly argv: ReadonlyArray<string>;
10266 readonly cwd: string;
10267 readonly program: string;
10268 readonly source: ServerNotification__GuardianCommandSource;
10269 readonly type: "execve";
10270 }
10271 | { readonly cwd: string; readonly files: ReadonlyArray<string>; readonly type: "applyPatch" }
10272 | {
10273 readonly host: string;
10274 readonly port: number;
10275 readonly protocol: ServerNotification__NetworkApprovalProtocol;
10276 readonly target: string;
10277 readonly type: "networkAccess";
10278 }
10279 | {
10280 readonly connectorId?: string | null;
10281 readonly connectorName?: string | null;
10282 readonly server: string;
10283 readonly toolName: string;
10284 readonly toolTitle?: string | null;
10285 readonly type: "mcpToolCall";
10286 };
10287export const ServerNotification__GuardianApprovalReviewAction = Schema.Union(
10288 [
10289 Schema.Struct({
10290 command: Schema.String,
10291 cwd: Schema.String,
10292 source: ServerNotification__GuardianCommandSource,
10293 type: Schema.Literal("command").annotate({
10294 title: "CommandGuardianApprovalReviewActionType",
10295 }),
10296 }).annotate({ title: "CommandGuardianApprovalReviewAction" }),
10297 Schema.Struct({
10298 argv: Schema.Array(Schema.String),
10299 cwd: Schema.String,
10300 program: Schema.String,
10301 source: ServerNotification__GuardianCommandSource,
10302 type: Schema.Literal("execve").annotate({ title: "ExecveGuardianApprovalReviewActionType" }),
10303 }).annotate({ title: "ExecveGuardianApprovalReviewAction" }),
10304 Schema.Struct({
10305 cwd: Schema.String,
10306 files: Schema.Array(Schema.String),
10307 type: Schema.Literal("applyPatch").annotate({
10308 title: "ApplyPatchGuardianApprovalReviewActionType",
10309 }),
10310 }).annotate({ title: "ApplyPatchGuardianApprovalReviewAction" }),
10311 Schema.Struct({
10312 host: Schema.String,
10313 port: Schema.Number.annotate({ format: "uint16" })
10314 .check(Schema.isInt())
10315 .check(Schema.isGreaterThanOrEqualTo(0)),
10316 protocol: ServerNotification__NetworkApprovalProtocol,
10317 target: Schema.String,
10318 type: Schema.Literal("networkAccess").annotate({
10319 title: "NetworkAccessGuardianApprovalReviewActionType",
10320 }),
10321 }).annotate({ title: "NetworkAccessGuardianApprovalReviewAction" }),
10322 Schema.Struct({
10323 connectorId: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
10324 connectorName: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
10325 server: Schema.String,
10326 toolName: Schema.String,
10327 toolTitle: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
10328 type: Schema.Literal("mcpToolCall").annotate({
10329 title: "McpToolCallGuardianApprovalReviewActionType",
10330 }),
10331 }).annotate({ title: "McpToolCallGuardianApprovalReviewAction" }),
10332 ],
10333 { mode: "oneOf" },
10334);
10335
10336export type ServerNotification__CodexErrorInfo =
10337 | "contextWindowExceeded"
10338 | "usageLimitExceeded"
10339 | "serverOverloaded"
10340 | "internalServerError"
10341 | "unauthorized"
10342 | "badRequest"
10343 | "threadRollbackFailed"
10344 | "sandboxError"
10345 | "other"
10346 | { readonly httpConnectionFailed: { readonly httpStatusCode?: number | null } }
10347 | { readonly responseStreamConnectionFailed: { readonly httpStatusCode?: number | null } }
10348 | { readonly responseStreamDisconnected: { readonly httpStatusCode?: number | null } }
10349 | { readonly responseTooManyFailedAttempts: { readonly httpStatusCode?: number | null } }
10350 | {
10351 readonly activeTurnNotSteerable: {
10352 readonly turnKind: ServerNotification__NonSteerableTurnKind;
10353 };
10354 };
10355export const ServerNotification__CodexErrorInfo = Schema.Union(
10356 [
10357 Schema.Literals([
10358 "contextWindowExceeded",
10359 "usageLimitExceeded",
10360 "serverOverloaded",
10361 "internalServerError",
10362 "unauthorized",
10363 "badRequest",
10364 "threadRollbackFailed",
10365 "sandboxError",
10366 "other",
10367 ]),
10368 Schema.Struct({
10369 httpConnectionFailed: Schema.Struct({
10370 httpStatusCode: Schema.optionalKey(
10371 Schema.Union([
10372 Schema.Number.annotate({ format: "uint16" })
10373 .check(Schema.isInt())
10374 .check(Schema.isGreaterThanOrEqualTo(0)),
10375 Schema.Null,
10376 ]),
10377 ),
10378 }),
10379 }).annotate({ title: "HttpConnectionFailedCodexErrorInfo" }),
10380 Schema.Struct({
10381 responseStreamConnectionFailed: Schema.Struct({
10382 httpStatusCode: Schema.optionalKey(
10383 Schema.Union([
10384 Schema.Number.annotate({ format: "uint16" })
10385 .check(Schema.isInt())
10386 .check(Schema.isGreaterThanOrEqualTo(0)),
10387 Schema.Null,
10388 ]),
10389 ),
10390 }),
10391 }).annotate({
10392 title: "ResponseStreamConnectionFailedCodexErrorInfo",
10393 description: "Failed to connect to the response SSE stream.",
10394 }),
10395 Schema.Struct({
10396 responseStreamDisconnected: Schema.Struct({
10397 httpStatusCode: Schema.optionalKey(
10398 Schema.Union([
10399 Schema.Number.annotate({ format: "uint16" })
10400 .check(Schema.isInt())
10401 .check(Schema.isGreaterThanOrEqualTo(0)),
10402 Schema.Null,
10403 ]),
10404 ),
10405 }),
10406 }).annotate({
10407 title: "ResponseStreamDisconnectedCodexErrorInfo",
10408 description:
10409 "The response SSE stream disconnected in the middle of a turn before completion.",
10410 }),
10411 Schema.Struct({
10412 responseTooManyFailedAttempts: Schema.Struct({
10413 httpStatusCode: Schema.optionalKey(
10414 Schema.Union([
10415 Schema.Number.annotate({ format: "uint16" })
10416 .check(Schema.isInt())
10417 .check(Schema.isGreaterThanOrEqualTo(0)),
10418 Schema.Null,
10419 ]),
10420 ),
10421 }),
10422 }).annotate({
10423 title: "ResponseTooManyFailedAttemptsCodexErrorInfo",
10424 description: "Reached the retry limit for responses.",
10425 }),
10426 Schema.Struct({
10427 activeTurnNotSteerable: Schema.Struct({ turnKind: ServerNotification__NonSteerableTurnKind }),
10428 }).annotate({
10429 title: "ActiveTurnNotSteerableCodexErrorInfo",
10430 description:
10431 "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`.",
10432 }),
10433 ],
10434 { mode: "oneOf" },
10435).annotate({
10436 description:
10437 "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.",
10438});
10439
10440export type ServerNotification__FileUpdateChange = {
10441 readonly diff: string;
10442 readonly kind: ServerNotification__PatchChangeKind;
10443 readonly path: string;
10444};
10445export const ServerNotification__FileUpdateChange = Schema.Struct({
10446 diff: Schema.String,
10447 kind: ServerNotification__PatchChangeKind,
10448 path: Schema.String,
10449});
10450
10451export type ServerNotification__AccountUpdatedNotification = {
10452 readonly authMode?: ServerNotification__AuthMode | null;
10453 readonly planType?: ServerNotification__PlanType | null;
10454};
10455export const ServerNotification__AccountUpdatedNotification = Schema.Struct({
10456 authMode: Schema.optionalKey(Schema.Union([ServerNotification__AuthMode, Schema.Null])),
10457 planType: Schema.optionalKey(Schema.Union([ServerNotification__PlanType, Schema.Null])),
10458});
10459
10460export type ServerNotification__RateLimitSnapshot = {
10461 readonly credits?: ServerNotification__CreditsSnapshot | null;
10462 readonly limitId?: string | null;
10463 readonly limitName?: string | null;
10464 readonly planType?: ServerNotification__PlanType | null;
10465 readonly primary?: ServerNotification__RateLimitWindow | null;
10466 readonly secondary?: ServerNotification__RateLimitWindow | null;
10467};
10468export const ServerNotification__RateLimitSnapshot = Schema.Struct({
10469 credits: Schema.optionalKey(Schema.Union([ServerNotification__CreditsSnapshot, Schema.Null])),
10470 limitId: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
10471 limitName: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
10472 planType: Schema.optionalKey(Schema.Union([ServerNotification__PlanType, Schema.Null])),
10473 primary: Schema.optionalKey(Schema.Union([ServerNotification__RateLimitWindow, Schema.Null])),
10474 secondary: Schema.optionalKey(Schema.Union([ServerNotification__RateLimitWindow, Schema.Null])),
10475});
10476
10477export type ServerNotification__ThreadRealtimeStartedNotification = {
10478 readonly sessionId?: string | null;
10479 readonly threadId: string;
10480 readonly version: ServerNotification__RealtimeConversationVersion;
10481};
10482export const ServerNotification__ThreadRealtimeStartedNotification = Schema.Struct({
10483 sessionId: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
10484 threadId: Schema.String,
10485 version: ServerNotification__RealtimeConversationVersion,
10486}).annotate({ description: "EXPERIMENTAL - emitted when thread realtime startup is accepted." });
10487
10488export type ServerNotification__ServerRequestResolvedNotification = {
10489 readonly requestId: ServerNotification__RequestId;
10490 readonly threadId: string;
10491};
10492export const ServerNotification__ServerRequestResolvedNotification = Schema.Struct({
10493 requestId: ServerNotification__RequestId,
10494 threadId: Schema.String,
10495});
10496
10497export type ServerNotification__UserInput =
10498 | {
10499 readonly text: string;
10500 readonly text_elements?: ReadonlyArray<ServerNotification__TextElement>;
10501 readonly type: "text";
10502 }
10503 | { readonly type: "image"; readonly url: string }
10504 | { readonly path: string; readonly type: "localImage" }
10505 | { readonly name: string; readonly path: string; readonly type: "skill" }
10506 | { readonly name: string; readonly path: string; readonly type: "mention" };
10507export const ServerNotification__UserInput = Schema.Union(
10508 [
10509 Schema.Struct({
10510 text: Schema.String,
10511 text_elements: Schema.optionalKey(
10512 Schema.Array(ServerNotification__TextElement).annotate({
10513 description: "UI-defined spans within `text` used to render or persist special elements.",
10514 default: [],
10515 }),
10516 ),
10517 type: Schema.Literal("text").annotate({ title: "TextUserInputType" }),
10518 }).annotate({ title: "TextUserInput" }),
10519 Schema.Struct({
10520 type: Schema.Literal("image").annotate({ title: "ImageUserInputType" }),
10521 url: Schema.String,
10522 }).annotate({ title: "ImageUserInput" }),
10523 Schema.Struct({
10524 path: Schema.String,
10525 type: Schema.Literal("localImage").annotate({ title: "LocalImageUserInputType" }),
10526 }).annotate({ title: "LocalImageUserInput" }),
10527 Schema.Struct({
10528 name: Schema.String,
10529 path: Schema.String,
10530 type: Schema.Literal("skill").annotate({ title: "SkillUserInputType" }),
10531 }).annotate({ title: "SkillUserInput" }),
10532 Schema.Struct({
10533 name: Schema.String,
10534 path: Schema.String,
10535 type: Schema.Literal("mention").annotate({ title: "MentionUserInputType" }),
10536 }).annotate({ title: "MentionUserInput" }),
10537 ],
10538 { mode: "oneOf" },
10539);
10540
10541export type ServerNotification__TextRange = {
10542 readonly end: ServerNotification__TextPosition;
10543 readonly start: ServerNotification__TextPosition;
10544};
10545export const ServerNotification__TextRange = Schema.Struct({
10546 end: ServerNotification__TextPosition,
10547 start: ServerNotification__TextPosition,
10548});
10549
10550export type ServerNotification__ThreadStatus =
10551 | { readonly type: "notLoaded" }
10552 | { readonly type: "idle" }
10553 | { readonly type: "systemError" }
10554 | {
10555 readonly activeFlags: ReadonlyArray<ServerNotification__ThreadActiveFlag>;
10556 readonly type: "active";
10557 };
10558export const ServerNotification__ThreadStatus = Schema.Union(
10559 [
10560 Schema.Struct({
10561 type: Schema.Literal("notLoaded").annotate({ title: "NotLoadedThreadStatusType" }),
10562 }).annotate({ title: "NotLoadedThreadStatus" }),
10563 Schema.Struct({
10564 type: Schema.Literal("idle").annotate({ title: "IdleThreadStatusType" }),
10565 }).annotate({ title: "IdleThreadStatus" }),
10566 Schema.Struct({
10567 type: Schema.Literal("systemError").annotate({ title: "SystemErrorThreadStatusType" }),
10568 }).annotate({ title: "SystemErrorThreadStatus" }),
10569 Schema.Struct({
10570 activeFlags: Schema.Array(ServerNotification__ThreadActiveFlag),
10571 type: Schema.Literal("active").annotate({ title: "ActiveThreadStatusType" }),
10572 }).annotate({ title: "ActiveThreadStatus" }),
10573 ],
10574 { mode: "oneOf" },
10575);
10576
10577export type ServerNotification__SubAgentSource =
10578 | "review"
10579 | "compact"
10580 | "memory_consolidation"
10581 | {
10582 readonly thread_spawn: {
10583 readonly agent_nickname?: string | null;
10584 readonly agent_path?: ServerNotification__AgentPath | null;
10585 readonly agent_role?: string | null;
10586 readonly depth: number;
10587 readonly parent_thread_id: ServerNotification__ThreadId;
10588 };
10589 }
10590 | { readonly other: string };
10591export const ServerNotification__SubAgentSource = Schema.Union(
10592 [
10593 Schema.Literals(["review", "compact", "memory_consolidation"]),
10594 Schema.Struct({
10595 thread_spawn: Schema.Struct({
10596 agent_nickname: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
10597 agent_path: Schema.optionalKey(Schema.Union([ServerNotification__AgentPath, Schema.Null])),
10598 agent_role: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
10599 depth: Schema.Number.annotate({ format: "int32" }).check(Schema.isInt()),
10600 parent_thread_id: ServerNotification__ThreadId,
10601 }),
10602 }).annotate({ title: "ThreadSpawnSubAgentSource" }),
10603 Schema.Struct({ other: Schema.String }).annotate({ title: "OtherSubAgentSource" }),
10604 ],
10605 { mode: "oneOf" },
10606);
10607
10608export type ServerNotification__ThreadRealtimeOutputAudioDeltaNotification = {
10609 readonly audio: ServerNotification__ThreadRealtimeAudioChunk;
10610 readonly threadId: string;
10611};
10612export const ServerNotification__ThreadRealtimeOutputAudioDeltaNotification = Schema.Struct({
10613 audio: ServerNotification__ThreadRealtimeAudioChunk,
10614 threadId: Schema.String,
10615}).annotate({ description: "EXPERIMENTAL - streamed output audio emitted by thread realtime." });
10616
10617export type ServerNotification__ThreadTokenUsage = {
10618 readonly last: ServerNotification__TokenUsageBreakdown;
10619 readonly modelContextWindow?: number | null;
10620 readonly total: ServerNotification__TokenUsageBreakdown;
10621};
10622export const ServerNotification__ThreadTokenUsage = Schema.Struct({
10623 last: ServerNotification__TokenUsageBreakdown,
10624 modelContextWindow: Schema.optionalKey(
10625 Schema.Union([Schema.Number.annotate({ format: "int64" }).check(Schema.isInt()), Schema.Null]),
10626 ),
10627 total: ServerNotification__TokenUsageBreakdown,
10628});
10629
10630export type ServerNotification__TurnPlanStep = {
10631 readonly status: ServerNotification__TurnPlanStepStatus;
10632 readonly step: string;
10633};
10634export const ServerNotification__TurnPlanStep = Schema.Struct({
10635 status: ServerNotification__TurnPlanStepStatus,
10636 step: Schema.String,
10637});
10638
10639export type ServerNotification__WindowsSandboxSetupCompletedNotification = {
10640 readonly error?: string | null;
10641 readonly mode: ServerNotification__WindowsSandboxSetupMode;
10642 readonly success: boolean;
10643};
10644export const ServerNotification__WindowsSandboxSetupCompletedNotification = Schema.Struct({
10645 error: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
10646 mode: ServerNotification__WindowsSandboxSetupMode,
10647 success: Schema.Boolean,
10648});
10649
10650export type ServerRequest__AdditionalFileSystemPermissions = {
10651 readonly read?: ReadonlyArray<ServerRequest__AbsolutePathBuf> | null;
10652 readonly write?: ReadonlyArray<ServerRequest__AbsolutePathBuf> | null;
10653};
10654export const ServerRequest__AdditionalFileSystemPermissions = Schema.Struct({
10655 read: Schema.optionalKey(
10656 Schema.Union([Schema.Array(ServerRequest__AbsolutePathBuf), Schema.Null]),
10657 ),
10658 write: Schema.optionalKey(
10659 Schema.Union([Schema.Array(ServerRequest__AbsolutePathBuf), Schema.Null]),
10660 ),
10661});
10662
10663export type ServerRequest__ChatgptAuthTokensRefreshParams = {
10664 readonly previousAccountId?: string | null;
10665 readonly reason: ServerRequest__ChatgptAuthTokensRefreshReason;
10666};
10667export const ServerRequest__ChatgptAuthTokensRefreshParams = Schema.Struct({
10668 previousAccountId: Schema.optionalKey(
10669 Schema.Union([
10670 Schema.String.annotate({
10671 description:
10672 "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`).",
10673 }),
10674 Schema.Null,
10675 ]),
10676 ),
10677 reason: ServerRequest__ChatgptAuthTokensRefreshReason,
10678});
10679
10680export type ServerRequest__McpElicitationBooleanSchema = {
10681 readonly default?: boolean | null;
10682 readonly description?: string | null;
10683 readonly title?: string | null;
10684 readonly type: ServerRequest__McpElicitationBooleanType;
10685};
10686export const ServerRequest__McpElicitationBooleanSchema = Schema.Struct({
10687 default: Schema.optionalKey(Schema.Union([Schema.Boolean, Schema.Null])),
10688 description: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
10689 title: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
10690 type: ServerRequest__McpElicitationBooleanType,
10691});
10692
10693export type ServerRequest__McpElicitationTitledEnumItems = {
10694 readonly anyOf: ReadonlyArray<ServerRequest__McpElicitationConstOption>;
10695};
10696export const ServerRequest__McpElicitationTitledEnumItems = Schema.Struct({
10697 anyOf: Schema.Array(ServerRequest__McpElicitationConstOption),
10698});
10699
10700export type ServerRequest__McpElicitationNumberSchema = {
10701 readonly default?: number | null;
10702 readonly description?: string | null;
10703 readonly maximum?: number | null;
10704 readonly minimum?: number | null;
10705 readonly title?: string | null;
10706 readonly type: ServerRequest__McpElicitationNumberType;
10707};
10708export const ServerRequest__McpElicitationNumberSchema = Schema.Struct({
10709 default: Schema.optionalKey(
10710 Schema.Union([
10711 Schema.Number.annotate({ format: "double" }).check(Schema.isFinite()),
10712 Schema.Null,
10713 ]),
10714 ),
10715 description: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
10716 maximum: Schema.optionalKey(
10717 Schema.Union([
10718 Schema.Number.annotate({ format: "double" }).check(Schema.isFinite()),
10719 Schema.Null,
10720 ]),
10721 ),
10722 minimum: Schema.optionalKey(
10723 Schema.Union([
10724 Schema.Number.annotate({ format: "double" }).check(Schema.isFinite()),
10725 Schema.Null,
10726 ]),
10727 ),
10728 title: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
10729 type: ServerRequest__McpElicitationNumberType,
10730});
10731
10732export type ServerRequest__McpElicitationLegacyTitledEnumSchema = {
10733 readonly default?: string | null;
10734 readonly description?: string | null;
10735 readonly enum: ReadonlyArray<string>;
10736 readonly enumNames?: ReadonlyArray<string> | null;
10737 readonly title?: string | null;
10738 readonly type: ServerRequest__McpElicitationStringType;
10739};
10740export const ServerRequest__McpElicitationLegacyTitledEnumSchema = Schema.Struct({
10741 default: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
10742 description: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
10743 enum: Schema.Array(Schema.String),
10744 enumNames: Schema.optionalKey(Schema.Union([Schema.Array(Schema.String), Schema.Null])),
10745 title: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
10746 type: ServerRequest__McpElicitationStringType,
10747});
10748
10749export type ServerRequest__McpElicitationStringSchema = {
10750 readonly default?: string | null;
10751 readonly description?: string | null;
10752 readonly format?: ServerRequest__McpElicitationStringFormat | null;
10753 readonly maxLength?: number | null;
10754 readonly minLength?: number | null;
10755 readonly title?: string | null;
10756 readonly type: ServerRequest__McpElicitationStringType;
10757};
10758export const ServerRequest__McpElicitationStringSchema = Schema.Struct({
10759 default: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
10760 description: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
10761 format: Schema.optionalKey(
10762 Schema.Union([ServerRequest__McpElicitationStringFormat, Schema.Null]),
10763 ),
10764 maxLength: Schema.optionalKey(
10765 Schema.Union([
10766 Schema.Number.annotate({ format: "uint32" })
10767 .check(Schema.isInt())
10768 .check(Schema.isGreaterThanOrEqualTo(0)),
10769 Schema.Null,
10770 ]),
10771 ),
10772 minLength: Schema.optionalKey(
10773 Schema.Union([
10774 Schema.Number.annotate({ format: "uint32" })
10775 .check(Schema.isInt())
10776 .check(Schema.isGreaterThanOrEqualTo(0)),
10777 Schema.Null,
10778 ]),
10779 ),
10780 title: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
10781 type: ServerRequest__McpElicitationStringType,
10782});
10783
10784export type ServerRequest__McpElicitationTitledSingleSelectEnumSchema = {
10785 readonly default?: string | null;
10786 readonly description?: string | null;
10787 readonly oneOf: ReadonlyArray<ServerRequest__McpElicitationConstOption>;
10788 readonly title?: string | null;
10789 readonly type: ServerRequest__McpElicitationStringType;
10790};
10791export const ServerRequest__McpElicitationTitledSingleSelectEnumSchema = Schema.Struct({
10792 default: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
10793 description: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
10794 oneOf: Schema.Array(ServerRequest__McpElicitationConstOption),
10795 title: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
10796 type: ServerRequest__McpElicitationStringType,
10797});
10798
10799export type ServerRequest__McpElicitationUntitledEnumItems = {
10800 readonly enum: ReadonlyArray<string>;
10801 readonly type: ServerRequest__McpElicitationStringType;
10802};
10803export const ServerRequest__McpElicitationUntitledEnumItems = Schema.Struct({
10804 enum: Schema.Array(Schema.String),
10805 type: ServerRequest__McpElicitationStringType,
10806});
10807
10808export type ServerRequest__McpElicitationUntitledSingleSelectEnumSchema = {
10809 readonly default?: string | null;
10810 readonly description?: string | null;
10811 readonly enum: ReadonlyArray<string>;
10812 readonly title?: string | null;
10813 readonly type: ServerRequest__McpElicitationStringType;
10814};
10815export const ServerRequest__McpElicitationUntitledSingleSelectEnumSchema = Schema.Struct({
10816 default: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
10817 description: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
10818 enum: Schema.Array(Schema.String),
10819 title: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
10820 type: ServerRequest__McpElicitationStringType,
10821});
10822
10823export type ServerRequest__NetworkApprovalContext = {
10824 readonly host: string;
10825 readonly protocol: ServerRequest__NetworkApprovalProtocol;
10826};
10827export const ServerRequest__NetworkApprovalContext = Schema.Struct({
10828 host: Schema.String,
10829 protocol: ServerRequest__NetworkApprovalProtocol,
10830});
10831
10832export type ServerRequest__NetworkPolicyAmendment = {
10833 readonly action: ServerRequest__NetworkPolicyRuleAction;
10834 readonly host: string;
10835};
10836export const ServerRequest__NetworkPolicyAmendment = Schema.Struct({
10837 action: ServerRequest__NetworkPolicyRuleAction,
10838 host: Schema.String,
10839});
10840
10841export type ServerRequest__ApplyPatchApprovalParams = {
10842 readonly callId: string;
10843 readonly conversationId: ServerRequest__ThreadId;
10844 readonly fileChanges: { readonly [x: string]: ServerRequest__FileChange };
10845 readonly grantRoot?: string | null;
10846 readonly reason?: string | null;
10847};
10848export const ServerRequest__ApplyPatchApprovalParams = Schema.Struct({
10849 callId: Schema.String.annotate({
10850 description:
10851 "Use to correlate this with [codex_protocol::protocol::PatchApplyBeginEvent] and [codex_protocol::protocol::PatchApplyEndEvent].",
10852 }),
10853 conversationId: ServerRequest__ThreadId,
10854 fileChanges: Schema.Record(Schema.String, ServerRequest__FileChange),
10855 grantRoot: Schema.optionalKey(
10856 Schema.Union([
10857 Schema.String.annotate({
10858 description:
10859 "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).",
10860 }),
10861 Schema.Null,
10862 ]),
10863 ),
10864 reason: Schema.optionalKey(
10865 Schema.Union([
10866 Schema.String.annotate({
10867 description: "Optional explanatory reason (e.g. request for extra write access).",
10868 }),
10869 Schema.Null,
10870 ]),
10871 ),
10872});
10873
10874export type ServerRequest__ExecCommandApprovalParams = {
10875 readonly approvalId?: string | null;
10876 readonly callId: string;
10877 readonly command: ReadonlyArray<string>;
10878 readonly conversationId: ServerRequest__ThreadId;
10879 readonly cwd: string;
10880 readonly parsedCmd: ReadonlyArray<ServerRequest__ParsedCommand>;
10881 readonly reason?: string | null;
10882};
10883export const ServerRequest__ExecCommandApprovalParams = Schema.Struct({
10884 approvalId: Schema.optionalKey(
10885 Schema.Union([
10886 Schema.String.annotate({ description: "Identifier for this specific approval callback." }),
10887 Schema.Null,
10888 ]),
10889 ),
10890 callId: Schema.String.annotate({
10891 description:
10892 "Use to correlate this with [codex_protocol::protocol::ExecCommandBeginEvent] and [codex_protocol::protocol::ExecCommandEndEvent].",
10893 }),
10894 command: Schema.Array(Schema.String),
10895 conversationId: ServerRequest__ThreadId,
10896 cwd: Schema.String,
10897 parsedCmd: Schema.Array(ServerRequest__ParsedCommand),
10898 reason: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
10899});
10900
10901export type ServerRequest__ToolRequestUserInputQuestion = {
10902 readonly header: string;
10903 readonly id: string;
10904 readonly isOther?: boolean;
10905 readonly isSecret?: boolean;
10906 readonly options?: ReadonlyArray<ServerRequest__ToolRequestUserInputOption> | null;
10907 readonly question: string;
10908};
10909export const ServerRequest__ToolRequestUserInputQuestion = Schema.Struct({
10910 header: Schema.String,
10911 id: Schema.String,
10912 isOther: Schema.optionalKey(Schema.Boolean.annotate({ default: false })),
10913 isSecret: Schema.optionalKey(Schema.Boolean.annotate({ default: false })),
10914 options: Schema.optionalKey(
10915 Schema.Union([Schema.Array(ServerRequest__ToolRequestUserInputOption), Schema.Null]),
10916 ),
10917 question: Schema.String,
10918}).annotate({
10919 description: "EXPERIMENTAL. Represents one request_user_input question and its required options.",
10920});
10921
10922export type ToolRequestUserInputParams__ToolRequestUserInputQuestion = {
10923 readonly header: string;
10924 readonly id: string;
10925 readonly isOther?: boolean;
10926 readonly isSecret?: boolean;
10927 readonly options?: ReadonlyArray<ToolRequestUserInputParams__ToolRequestUserInputOption> | null;
10928 readonly question: string;
10929};
10930export const ToolRequestUserInputParams__ToolRequestUserInputQuestion = Schema.Struct({
10931 header: Schema.String,
10932 id: Schema.String,
10933 isOther: Schema.optionalKey(Schema.Boolean.annotate({ default: false })),
10934 isSecret: Schema.optionalKey(Schema.Boolean.annotate({ default: false })),
10935 options: Schema.optionalKey(
10936 Schema.Union([
10937 Schema.Array(ToolRequestUserInputParams__ToolRequestUserInputOption),
10938 Schema.Null,
10939 ]),
10940 ),
10941 question: Schema.String,
10942}).annotate({
10943 description: "EXPERIMENTAL. Represents one request_user_input question and its required options.",
10944});
10945
10946export type V2AccountRateLimitsUpdatedNotification__RateLimitSnapshot = {
10947 readonly credits?: V2AccountRateLimitsUpdatedNotification__CreditsSnapshot | null;
10948 readonly limitId?: string | null;
10949 readonly limitName?: string | null;
10950 readonly planType?: V2AccountRateLimitsUpdatedNotification__PlanType | null;
10951 readonly primary?: V2AccountRateLimitsUpdatedNotification__RateLimitWindow | null;
10952 readonly secondary?: V2AccountRateLimitsUpdatedNotification__RateLimitWindow | null;
10953};
10954export const V2AccountRateLimitsUpdatedNotification__RateLimitSnapshot = Schema.Struct({
10955 credits: Schema.optionalKey(
10956 Schema.Union([V2AccountRateLimitsUpdatedNotification__CreditsSnapshot, Schema.Null]),
10957 ),
10958 limitId: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
10959 limitName: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
10960 planType: Schema.optionalKey(
10961 Schema.Union([V2AccountRateLimitsUpdatedNotification__PlanType, Schema.Null]),
10962 ),
10963 primary: Schema.optionalKey(
10964 Schema.Union([V2AccountRateLimitsUpdatedNotification__RateLimitWindow, Schema.Null]),
10965 ),
10966 secondary: Schema.optionalKey(
10967 Schema.Union([V2AccountRateLimitsUpdatedNotification__RateLimitWindow, Schema.Null]),
10968 ),
10969});
10970
10971export type V2AppListUpdatedNotification__AppMetadata = {
10972 readonly categories?: ReadonlyArray<string> | null;
10973 readonly developer?: string | null;
10974 readonly firstPartyRequiresInstall?: boolean | null;
10975 readonly firstPartyType?: string | null;
10976 readonly review?: V2AppListUpdatedNotification__AppReview | null;
10977 readonly screenshots?: ReadonlyArray<V2AppListUpdatedNotification__AppScreenshot> | null;
10978 readonly seoDescription?: string | null;
10979 readonly showInComposerWhenUnlinked?: boolean | null;
10980 readonly subCategories?: ReadonlyArray<string> | null;
10981 readonly version?: string | null;
10982 readonly versionId?: string | null;
10983 readonly versionNotes?: string | null;
10984};
10985export const V2AppListUpdatedNotification__AppMetadata = Schema.Struct({
10986 categories: Schema.optionalKey(Schema.Union([Schema.Array(Schema.String), Schema.Null])),
10987 developer: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
10988 firstPartyRequiresInstall: Schema.optionalKey(Schema.Union([Schema.Boolean, Schema.Null])),
10989 firstPartyType: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
10990 review: Schema.optionalKey(Schema.Union([V2AppListUpdatedNotification__AppReview, Schema.Null])),
10991 screenshots: Schema.optionalKey(
10992 Schema.Union([Schema.Array(V2AppListUpdatedNotification__AppScreenshot), Schema.Null]),
10993 ),
10994 seoDescription: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
10995 showInComposerWhenUnlinked: Schema.optionalKey(Schema.Union([Schema.Boolean, Schema.Null])),
10996 subCategories: Schema.optionalKey(Schema.Union([Schema.Array(Schema.String), Schema.Null])),
10997 version: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
10998 versionId: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
10999 versionNotes: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
11000});
11001
11002export type V2AppsListResponse__AppMetadata = {
11003 readonly categories?: ReadonlyArray<string> | null;
11004 readonly developer?: string | null;
11005 readonly firstPartyRequiresInstall?: boolean | null;
11006 readonly firstPartyType?: string | null;
11007 readonly review?: V2AppsListResponse__AppReview | null;
11008 readonly screenshots?: ReadonlyArray<V2AppsListResponse__AppScreenshot> | null;
11009 readonly seoDescription?: string | null;
11010 readonly showInComposerWhenUnlinked?: boolean | null;
11011 readonly subCategories?: ReadonlyArray<string> | null;
11012 readonly version?: string | null;
11013 readonly versionId?: string | null;
11014 readonly versionNotes?: string | null;
11015};
11016export const V2AppsListResponse__AppMetadata = Schema.Struct({
11017 categories: Schema.optionalKey(Schema.Union([Schema.Array(Schema.String), Schema.Null])),
11018 developer: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
11019 firstPartyRequiresInstall: Schema.optionalKey(Schema.Union([Schema.Boolean, Schema.Null])),
11020 firstPartyType: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
11021 review: Schema.optionalKey(Schema.Union([V2AppsListResponse__AppReview, Schema.Null])),
11022 screenshots: Schema.optionalKey(
11023 Schema.Union([Schema.Array(V2AppsListResponse__AppScreenshot), Schema.Null]),
11024 ),
11025 seoDescription: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
11026 showInComposerWhenUnlinked: Schema.optionalKey(Schema.Union([Schema.Boolean, Schema.Null])),
11027 subCategories: Schema.optionalKey(Schema.Union([Schema.Array(Schema.String), Schema.Null])),
11028 version: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
11029 versionId: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
11030 versionNotes: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
11031});
11032
11033export type V2CommandExecParams__SandboxPolicy =
11034 | { readonly type: "dangerFullAccess" }
11035 | {
11036 readonly access?:
11037 | {
11038 readonly includePlatformDefaults?: boolean;
11039 readonly readableRoots?: ReadonlyArray<V2CommandExecParams__AbsolutePathBuf>;
11040 readonly type: "restricted";
11041 }
11042 | { readonly type: "fullAccess" };
11043 readonly networkAccess?: boolean;
11044 readonly type: "readOnly";
11045 }
11046 | { readonly networkAccess?: "restricted" | "enabled"; readonly type: "externalSandbox" }
11047 | {
11048 readonly excludeSlashTmp?: boolean;
11049 readonly excludeTmpdirEnvVar?: boolean;
11050 readonly networkAccess?: boolean;
11051 readonly readOnlyAccess?:
11052 | {
11053 readonly includePlatformDefaults?: boolean;
11054 readonly readableRoots?: ReadonlyArray<V2CommandExecParams__AbsolutePathBuf>;
11055 readonly type: "restricted";
11056 }
11057 | { readonly type: "fullAccess" };
11058 readonly type: "workspaceWrite";
11059 readonly writableRoots?: ReadonlyArray<V2CommandExecParams__AbsolutePathBuf>;
11060 };
11061export const V2CommandExecParams__SandboxPolicy = Schema.Union(
11062 [
11063 Schema.Struct({
11064 type: Schema.Literal("dangerFullAccess").annotate({
11065 title: "DangerFullAccessSandboxPolicyType",
11066 }),
11067 }).annotate({ title: "DangerFullAccessSandboxPolicy" }),
11068 Schema.Struct({
11069 access: Schema.optionalKey(
11070 Schema.Union(
11071 [
11072 Schema.Struct({
11073 includePlatformDefaults: Schema.optionalKey(
11074 Schema.Boolean.annotate({ default: true }),
11075 ),
11076 readableRoots: Schema.optionalKey(
11077 Schema.Array(V2CommandExecParams__AbsolutePathBuf).annotate({ default: [] }),
11078 ),
11079 type: Schema.Literal("restricted").annotate({
11080 title: "RestrictedReadOnlyAccessType",
11081 }),
11082 }).annotate({ title: "RestrictedReadOnlyAccess" }),
11083 Schema.Struct({
11084 type: Schema.Literal("fullAccess").annotate({
11085 title: "FullAccessReadOnlyAccessType",
11086 }),
11087 }).annotate({ title: "FullAccessReadOnlyAccess" }),
11088 ],
11089 { mode: "oneOf" },
11090 ).annotate({ default: { type: "fullAccess" } }),
11091 ),
11092 networkAccess: Schema.optionalKey(Schema.Boolean.annotate({ default: false })),
11093 type: Schema.Literal("readOnly").annotate({ title: "ReadOnlySandboxPolicyType" }),
11094 }).annotate({ title: "ReadOnlySandboxPolicy" }),
11095 Schema.Struct({
11096 networkAccess: Schema.optionalKey(
11097 Schema.Literals(["restricted", "enabled"]).annotate({ default: "restricted" }),
11098 ),
11099 type: Schema.Literal("externalSandbox").annotate({
11100 title: "ExternalSandboxSandboxPolicyType",
11101 }),
11102 }).annotate({ title: "ExternalSandboxSandboxPolicy" }),
11103 Schema.Struct({
11104 excludeSlashTmp: Schema.optionalKey(Schema.Boolean.annotate({ default: false })),
11105 excludeTmpdirEnvVar: Schema.optionalKey(Schema.Boolean.annotate({ default: false })),
11106 networkAccess: Schema.optionalKey(Schema.Boolean.annotate({ default: false })),
11107 readOnlyAccess: Schema.optionalKey(
11108 Schema.Union(
11109 [
11110 Schema.Struct({
11111 includePlatformDefaults: Schema.optionalKey(
11112 Schema.Boolean.annotate({ default: true }),
11113 ),
11114 readableRoots: Schema.optionalKey(
11115 Schema.Array(V2CommandExecParams__AbsolutePathBuf).annotate({ default: [] }),
11116 ),
11117 type: Schema.Literal("restricted").annotate({
11118 title: "RestrictedReadOnlyAccessType",
11119 }),
11120 }).annotate({ title: "RestrictedReadOnlyAccess" }),
11121 Schema.Struct({
11122 type: Schema.Literal("fullAccess").annotate({
11123 title: "FullAccessReadOnlyAccessType",
11124 }),
11125 }).annotate({ title: "FullAccessReadOnlyAccess" }),
11126 ],
11127 { mode: "oneOf" },
11128 ).annotate({ default: { type: "fullAccess" } }),
11129 ),
11130 type: Schema.Literal("workspaceWrite").annotate({ title: "WorkspaceWriteSandboxPolicyType" }),
11131 writableRoots: Schema.optionalKey(
11132 Schema.Array(V2CommandExecParams__AbsolutePathBuf).annotate({ default: [] }),
11133 ),
11134 }).annotate({ title: "WorkspaceWriteSandboxPolicy" }),
11135 ],
11136 { mode: "oneOf" },
11137);
11138
11139export type V2ConfigBatchWriteParams__ConfigEdit = {
11140 readonly keyPath: string;
11141 readonly mergeStrategy: V2ConfigBatchWriteParams__MergeStrategy;
11142 readonly value: unknown;
11143};
11144export const V2ConfigBatchWriteParams__ConfigEdit = Schema.Struct({
11145 keyPath: Schema.String,
11146 mergeStrategy: V2ConfigBatchWriteParams__MergeStrategy,
11147 value: Schema.Unknown,
11148});
11149
11150export type V2ConfigReadResponse__ConfigLayerSource =
11151 | { readonly domain: string; readonly key: string; readonly type: "mdm" }
11152 | { readonly file: string; readonly type: "system" }
11153 | { readonly file: string; readonly type: "user" }
11154 | { readonly dotCodexFolder: V2ConfigReadResponse__AbsolutePathBuf; readonly type: "project" }
11155 | { readonly type: "sessionFlags" }
11156 | {
11157 readonly file: V2ConfigReadResponse__AbsolutePathBuf;
11158 readonly type: "legacyManagedConfigTomlFromFile";
11159 }
11160 | { readonly type: "legacyManagedConfigTomlFromMdm" };
11161export const V2ConfigReadResponse__ConfigLayerSource = Schema.Union(
11162 [
11163 Schema.Struct({
11164 domain: Schema.String,
11165 key: Schema.String,
11166 type: Schema.Literal("mdm").annotate({ title: "MdmConfigLayerSourceType" }),
11167 }).annotate({
11168 title: "MdmConfigLayerSource",
11169 description: "Managed preferences layer delivered by MDM (macOS only).",
11170 }),
11171 Schema.Struct({
11172 file: Schema.String.annotate({
11173 description:
11174 "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.",
11175 }),
11176 type: Schema.Literal("system").annotate({ title: "SystemConfigLayerSourceType" }),
11177 }).annotate({
11178 title: "SystemConfigLayerSource",
11179 description: "Managed config layer from a file (usually `managed_config.toml`).",
11180 }),
11181 Schema.Struct({
11182 file: Schema.String.annotate({
11183 description:
11184 "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.",
11185 }),
11186 type: Schema.Literal("user").annotate({ title: "UserConfigLayerSourceType" }),
11187 }).annotate({
11188 title: "UserConfigLayerSource",
11189 description:
11190 "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",
11191 }),
11192 Schema.Struct({
11193 dotCodexFolder: V2ConfigReadResponse__AbsolutePathBuf,
11194 type: Schema.Literal("project").annotate({ title: "ProjectConfigLayerSourceType" }),
11195 }).annotate({
11196 title: "ProjectConfigLayerSource",
11197 description:
11198 "Path to a .codex/ folder within a project. There could be multiple of these between `cwd` and the project/repo root.",
11199 }),
11200 Schema.Struct({
11201 type: Schema.Literal("sessionFlags").annotate({ title: "SessionFlagsConfigLayerSourceType" }),
11202 }).annotate({
11203 title: "SessionFlagsConfigLayerSource",
11204 description: "Session-layer overrides supplied via `-c`/`--config`.",
11205 }),
11206 Schema.Struct({
11207 file: V2ConfigReadResponse__AbsolutePathBuf,
11208 type: Schema.Literal("legacyManagedConfigTomlFromFile").annotate({
11209 title: "LegacyManagedConfigTomlFromFileConfigLayerSourceType",
11210 }),
11211 }).annotate({
11212 title: "LegacyManagedConfigTomlFromFileConfigLayerSource",
11213 description:
11214 '`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`.',
11215 }),
11216 Schema.Struct({
11217 type: Schema.Literal("legacyManagedConfigTomlFromMdm").annotate({
11218 title: "LegacyManagedConfigTomlFromMdmConfigLayerSourceType",
11219 }),
11220 }).annotate({ title: "LegacyManagedConfigTomlFromMdmConfigLayerSource" }),
11221 ],
11222 { mode: "oneOf" },
11223);
11224
11225export type V2ConfigReadResponse__WebSearchToolConfig = {
11226 readonly allowed_domains?: ReadonlyArray<string> | null;
11227 readonly context_size?: V2ConfigReadResponse__WebSearchContextSize | null;
11228 readonly location?: V2ConfigReadResponse__WebSearchLocation | null;
11229};
11230export const V2ConfigReadResponse__WebSearchToolConfig = Schema.Struct({
11231 allowed_domains: Schema.optionalKey(Schema.Union([Schema.Array(Schema.String), Schema.Null])),
11232 context_size: Schema.optionalKey(
11233 Schema.Union([V2ConfigReadResponse__WebSearchContextSize, Schema.Null]),
11234 ),
11235 location: Schema.optionalKey(
11236 Schema.Union([V2ConfigReadResponse__WebSearchLocation, Schema.Null]),
11237 ),
11238});
11239
11240export type V2ConfigRequirementsReadResponse__ConfigRequirements = {
11241 readonly allowedApprovalPolicies?: ReadonlyArray<V2ConfigRequirementsReadResponse__AskForApproval> | null;
11242 readonly allowedSandboxModes?: ReadonlyArray<V2ConfigRequirementsReadResponse__SandboxMode> | null;
11243 readonly allowedWebSearchModes?: ReadonlyArray<V2ConfigRequirementsReadResponse__WebSearchMode> | null;
11244 readonly enforceResidency?: V2ConfigRequirementsReadResponse__ResidencyRequirement | null;
11245 readonly featureRequirements?: { readonly [x: string]: boolean } | null;
11246};
11247export const V2ConfigRequirementsReadResponse__ConfigRequirements = Schema.Struct({
11248 allowedApprovalPolicies: Schema.optionalKey(
11249 Schema.Union([Schema.Array(V2ConfigRequirementsReadResponse__AskForApproval), Schema.Null]),
11250 ),
11251 allowedSandboxModes: Schema.optionalKey(
11252 Schema.Union([Schema.Array(V2ConfigRequirementsReadResponse__SandboxMode), Schema.Null]),
11253 ),
11254 allowedWebSearchModes: Schema.optionalKey(
11255 Schema.Union([Schema.Array(V2ConfigRequirementsReadResponse__WebSearchMode), Schema.Null]),
11256 ),
11257 enforceResidency: Schema.optionalKey(
11258 Schema.Union([V2ConfigRequirementsReadResponse__ResidencyRequirement, Schema.Null]),
11259 ),
11260 featureRequirements: Schema.optionalKey(
11261 Schema.Union([Schema.Record(Schema.String, Schema.Boolean), Schema.Null]),
11262 ),
11263});
11264
11265export type V2ConfigWarningNotification__TextRange = {
11266 readonly end: V2ConfigWarningNotification__TextPosition;
11267 readonly start: V2ConfigWarningNotification__TextPosition;
11268};
11269export const V2ConfigWarningNotification__TextRange = Schema.Struct({
11270 end: V2ConfigWarningNotification__TextPosition,
11271 start: V2ConfigWarningNotification__TextPosition,
11272});
11273
11274export type V2ConfigWriteResponse__ConfigLayerSource =
11275 | { readonly domain: string; readonly key: string; readonly type: "mdm" }
11276 | { readonly file: string; readonly type: "system" }
11277 | { readonly file: string; readonly type: "user" }
11278 | { readonly dotCodexFolder: V2ConfigWriteResponse__AbsolutePathBuf; readonly type: "project" }
11279 | { readonly type: "sessionFlags" }
11280 | {
11281 readonly file: V2ConfigWriteResponse__AbsolutePathBuf;
11282 readonly type: "legacyManagedConfigTomlFromFile";
11283 }
11284 | { readonly type: "legacyManagedConfigTomlFromMdm" };
11285export const V2ConfigWriteResponse__ConfigLayerSource = Schema.Union(
11286 [
11287 Schema.Struct({
11288 domain: Schema.String,
11289 key: Schema.String,
11290 type: Schema.Literal("mdm").annotate({ title: "MdmConfigLayerSourceType" }),
11291 }).annotate({
11292 title: "MdmConfigLayerSource",
11293 description: "Managed preferences layer delivered by MDM (macOS only).",
11294 }),
11295 Schema.Struct({
11296 file: Schema.String.annotate({
11297 description:
11298 "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.",
11299 }),
11300 type: Schema.Literal("system").annotate({ title: "SystemConfigLayerSourceType" }),
11301 }).annotate({
11302 title: "SystemConfigLayerSource",
11303 description: "Managed config layer from a file (usually `managed_config.toml`).",
11304 }),
11305 Schema.Struct({
11306 file: Schema.String.annotate({
11307 description:
11308 "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.",
11309 }),
11310 type: Schema.Literal("user").annotate({ title: "UserConfigLayerSourceType" }),
11311 }).annotate({
11312 title: "UserConfigLayerSource",
11313 description:
11314 "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",
11315 }),
11316 Schema.Struct({
11317 dotCodexFolder: V2ConfigWriteResponse__AbsolutePathBuf,
11318 type: Schema.Literal("project").annotate({ title: "ProjectConfigLayerSourceType" }),
11319 }).annotate({
11320 title: "ProjectConfigLayerSource",
11321 description:
11322 "Path to a .codex/ folder within a project. There could be multiple of these between `cwd` and the project/repo root.",
11323 }),
11324 Schema.Struct({
11325 type: Schema.Literal("sessionFlags").annotate({ title: "SessionFlagsConfigLayerSourceType" }),
11326 }).annotate({
11327 title: "SessionFlagsConfigLayerSource",
11328 description: "Session-layer overrides supplied via `-c`/`--config`.",
11329 }),
11330 Schema.Struct({
11331 file: V2ConfigWriteResponse__AbsolutePathBuf,
11332 type: Schema.Literal("legacyManagedConfigTomlFromFile").annotate({
11333 title: "LegacyManagedConfigTomlFromFileConfigLayerSourceType",
11334 }),
11335 }).annotate({
11336 title: "LegacyManagedConfigTomlFromFileConfigLayerSource",
11337 description:
11338 '`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`.',
11339 }),
11340 Schema.Struct({
11341 type: Schema.Literal("legacyManagedConfigTomlFromMdm").annotate({
11342 title: "LegacyManagedConfigTomlFromMdmConfigLayerSourceType",
11343 }),
11344 }).annotate({ title: "LegacyManagedConfigTomlFromMdmConfigLayerSource" }),
11345 ],
11346 { mode: "oneOf" },
11347);
11348
11349export type V2ErrorNotification__CodexErrorInfo =
11350 | "contextWindowExceeded"
11351 | "usageLimitExceeded"
11352 | "serverOverloaded"
11353 | "internalServerError"
11354 | "unauthorized"
11355 | "badRequest"
11356 | "threadRollbackFailed"
11357 | "sandboxError"
11358 | "other"
11359 | { readonly httpConnectionFailed: { readonly httpStatusCode?: number | null } }
11360 | { readonly responseStreamConnectionFailed: { readonly httpStatusCode?: number | null } }
11361 | { readonly responseStreamDisconnected: { readonly httpStatusCode?: number | null } }
11362 | { readonly responseTooManyFailedAttempts: { readonly httpStatusCode?: number | null } }
11363 | {
11364 readonly activeTurnNotSteerable: {
11365 readonly turnKind: V2ErrorNotification__NonSteerableTurnKind;
11366 };
11367 };
11368export const V2ErrorNotification__CodexErrorInfo = Schema.Union(
11369 [
11370 Schema.Literals([
11371 "contextWindowExceeded",
11372 "usageLimitExceeded",
11373 "serverOverloaded",
11374 "internalServerError",
11375 "unauthorized",
11376 "badRequest",
11377 "threadRollbackFailed",
11378 "sandboxError",
11379 "other",
11380 ]),
11381 Schema.Struct({
11382 httpConnectionFailed: Schema.Struct({
11383 httpStatusCode: Schema.optionalKey(
11384 Schema.Union([
11385 Schema.Number.annotate({ format: "uint16" })
11386 .check(Schema.isInt())
11387 .check(Schema.isGreaterThanOrEqualTo(0)),
11388 Schema.Null,
11389 ]),
11390 ),
11391 }),
11392 }).annotate({ title: "HttpConnectionFailedCodexErrorInfo" }),
11393 Schema.Struct({
11394 responseStreamConnectionFailed: Schema.Struct({
11395 httpStatusCode: Schema.optionalKey(
11396 Schema.Union([
11397 Schema.Number.annotate({ format: "uint16" })
11398 .check(Schema.isInt())
11399 .check(Schema.isGreaterThanOrEqualTo(0)),
11400 Schema.Null,
11401 ]),
11402 ),
11403 }),
11404 }).annotate({
11405 title: "ResponseStreamConnectionFailedCodexErrorInfo",
11406 description: "Failed to connect to the response SSE stream.",
11407 }),
11408 Schema.Struct({
11409 responseStreamDisconnected: Schema.Struct({
11410 httpStatusCode: Schema.optionalKey(
11411 Schema.Union([
11412 Schema.Number.annotate({ format: "uint16" })
11413 .check(Schema.isInt())
11414 .check(Schema.isGreaterThanOrEqualTo(0)),
11415 Schema.Null,
11416 ]),
11417 ),
11418 }),
11419 }).annotate({
11420 title: "ResponseStreamDisconnectedCodexErrorInfo",
11421 description:
11422 "The response SSE stream disconnected in the middle of a turn before completion.",
11423 }),
11424 Schema.Struct({
11425 responseTooManyFailedAttempts: Schema.Struct({
11426 httpStatusCode: Schema.optionalKey(
11427 Schema.Union([
11428 Schema.Number.annotate({ format: "uint16" })
11429 .check(Schema.isInt())
11430 .check(Schema.isGreaterThanOrEqualTo(0)),
11431 Schema.Null,
11432 ]),
11433 ),
11434 }),
11435 }).annotate({
11436 title: "ResponseTooManyFailedAttemptsCodexErrorInfo",
11437 description: "Reached the retry limit for responses.",
11438 }),
11439 Schema.Struct({
11440 activeTurnNotSteerable: Schema.Struct({
11441 turnKind: V2ErrorNotification__NonSteerableTurnKind,
11442 }),
11443 }).annotate({
11444 title: "ActiveTurnNotSteerableCodexErrorInfo",
11445 description:
11446 "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`.",
11447 }),
11448 ],
11449 { mode: "oneOf" },
11450).annotate({
11451 description:
11452 "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.",
11453});
11454
11455export type V2ExternalAgentConfigDetectResponse__ExternalAgentConfigMigrationItem = {
11456 readonly cwd?: string | null;
11457 readonly description: string;
11458 readonly itemType: V2ExternalAgentConfigDetectResponse__ExternalAgentConfigMigrationItemType;
11459};
11460export const V2ExternalAgentConfigDetectResponse__ExternalAgentConfigMigrationItem = Schema.Struct({
11461 cwd: Schema.optionalKey(
11462 Schema.Union([
11463 Schema.String.annotate({
11464 description:
11465 "Null or empty means home-scoped migration; non-empty means repo-scoped migration.",
11466 }),
11467 Schema.Null,
11468 ]),
11469 ),
11470 description: Schema.String,
11471 itemType: V2ExternalAgentConfigDetectResponse__ExternalAgentConfigMigrationItemType,
11472});
11473
11474export type V2ExternalAgentConfigImportParams__ExternalAgentConfigMigrationItem = {
11475 readonly cwd?: string | null;
11476 readonly description: string;
11477 readonly itemType: V2ExternalAgentConfigImportParams__ExternalAgentConfigMigrationItemType;
11478};
11479export const V2ExternalAgentConfigImportParams__ExternalAgentConfigMigrationItem = Schema.Struct({
11480 cwd: Schema.optionalKey(
11481 Schema.Union([
11482 Schema.String.annotate({
11483 description:
11484 "Null or empty means home-scoped migration; non-empty means repo-scoped migration.",
11485 }),
11486 Schema.Null,
11487 ]),
11488 ),
11489 description: Schema.String,
11490 itemType: V2ExternalAgentConfigImportParams__ExternalAgentConfigMigrationItemType,
11491});
11492
11493export type V2GetAccountRateLimitsResponse__RateLimitSnapshot = {
11494 readonly credits?: V2GetAccountRateLimitsResponse__CreditsSnapshot | null;
11495 readonly limitId?: string | null;
11496 readonly limitName?: string | null;
11497 readonly planType?: V2GetAccountRateLimitsResponse__PlanType | null;
11498 readonly primary?: V2GetAccountRateLimitsResponse__RateLimitWindow | null;
11499 readonly secondary?: V2GetAccountRateLimitsResponse__RateLimitWindow | null;
11500};
11501export const V2GetAccountRateLimitsResponse__RateLimitSnapshot = Schema.Struct({
11502 credits: Schema.optionalKey(
11503 Schema.Union([V2GetAccountRateLimitsResponse__CreditsSnapshot, Schema.Null]),
11504 ),
11505 limitId: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
11506 limitName: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
11507 planType: Schema.optionalKey(
11508 Schema.Union([V2GetAccountRateLimitsResponse__PlanType, Schema.Null]),
11509 ),
11510 primary: Schema.optionalKey(
11511 Schema.Union([V2GetAccountRateLimitsResponse__RateLimitWindow, Schema.Null]),
11512 ),
11513 secondary: Schema.optionalKey(
11514 Schema.Union([V2GetAccountRateLimitsResponse__RateLimitWindow, Schema.Null]),
11515 ),
11516});
11517
11518export type V2GetAccountResponse__Account =
11519 | { readonly type: "apiKey" }
11520 | {
11521 readonly email: string;
11522 readonly planType: V2GetAccountResponse__PlanType;
11523 readonly type: "chatgpt";
11524 };
11525export const V2GetAccountResponse__Account = Schema.Union(
11526 [
11527 Schema.Struct({
11528 type: Schema.Literal("apiKey").annotate({ title: "ApiKeyAccountType" }),
11529 }).annotate({ title: "ApiKeyAccount" }),
11530 Schema.Struct({
11531 email: Schema.String,
11532 planType: V2GetAccountResponse__PlanType,
11533 type: Schema.Literal("chatgpt").annotate({ title: "ChatgptAccountType" }),
11534 }).annotate({ title: "ChatgptAccount" }),
11535 ],
11536 { mode: "oneOf" },
11537);
11538
11539export type V2HookCompletedNotification__HookOutputEntry = {
11540 readonly kind: V2HookCompletedNotification__HookOutputEntryKind;
11541 readonly text: string;
11542};
11543export const V2HookCompletedNotification__HookOutputEntry = Schema.Struct({
11544 kind: V2HookCompletedNotification__HookOutputEntryKind,
11545 text: Schema.String,
11546});
11547
11548export type V2HookStartedNotification__HookOutputEntry = {
11549 readonly kind: V2HookStartedNotification__HookOutputEntryKind;
11550 readonly text: string;
11551};
11552export const V2HookStartedNotification__HookOutputEntry = Schema.Struct({
11553 kind: V2HookStartedNotification__HookOutputEntryKind,
11554 text: Schema.String,
11555});
11556
11557export type V2ItemCompletedNotification__CollabAgentState = {
11558 readonly message?: string | null;
11559 readonly status: V2ItemCompletedNotification__CollabAgentStatus;
11560};
11561export const V2ItemCompletedNotification__CollabAgentState = Schema.Struct({
11562 message: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
11563 status: V2ItemCompletedNotification__CollabAgentStatus,
11564});
11565
11566export type V2ItemCompletedNotification__MemoryCitation = {
11567 readonly entries: ReadonlyArray<V2ItemCompletedNotification__MemoryCitationEntry>;
11568 readonly threadIds: ReadonlyArray<string>;
11569};
11570export const V2ItemCompletedNotification__MemoryCitation = Schema.Struct({
11571 entries: Schema.Array(V2ItemCompletedNotification__MemoryCitationEntry),
11572 threadIds: Schema.Array(Schema.String),
11573});
11574
11575export type V2ItemCompletedNotification__FileUpdateChange = {
11576 readonly diff: string;
11577 readonly kind: V2ItemCompletedNotification__PatchChangeKind;
11578 readonly path: string;
11579};
11580export const V2ItemCompletedNotification__FileUpdateChange = Schema.Struct({
11581 diff: Schema.String,
11582 kind: V2ItemCompletedNotification__PatchChangeKind,
11583 path: Schema.String,
11584});
11585
11586export type V2ItemCompletedNotification__UserInput =
11587 | {
11588 readonly text: string;
11589 readonly text_elements?: ReadonlyArray<V2ItemCompletedNotification__TextElement>;
11590 readonly type: "text";
11591 }
11592 | { readonly type: "image"; readonly url: string }
11593 | { readonly path: string; readonly type: "localImage" }
11594 | { readonly name: string; readonly path: string; readonly type: "skill" }
11595 | { readonly name: string; readonly path: string; readonly type: "mention" };
11596export const V2ItemCompletedNotification__UserInput = Schema.Union(
11597 [
11598 Schema.Struct({
11599 text: Schema.String,
11600 text_elements: Schema.optionalKey(
11601 Schema.Array(V2ItemCompletedNotification__TextElement).annotate({
11602 description: "UI-defined spans within `text` used to render or persist special elements.",
11603 default: [],
11604 }),
11605 ),
11606 type: Schema.Literal("text").annotate({ title: "TextUserInputType" }),
11607 }).annotate({ title: "TextUserInput" }),
11608 Schema.Struct({
11609 type: Schema.Literal("image").annotate({ title: "ImageUserInputType" }),
11610 url: Schema.String,
11611 }).annotate({ title: "ImageUserInput" }),
11612 Schema.Struct({
11613 path: Schema.String,
11614 type: Schema.Literal("localImage").annotate({ title: "LocalImageUserInputType" }),
11615 }).annotate({ title: "LocalImageUserInput" }),
11616 Schema.Struct({
11617 name: Schema.String,
11618 path: Schema.String,
11619 type: Schema.Literal("skill").annotate({ title: "SkillUserInputType" }),
11620 }).annotate({ title: "SkillUserInput" }),
11621 Schema.Struct({
11622 name: Schema.String,
11623 path: Schema.String,
11624 type: Schema.Literal("mention").annotate({ title: "MentionUserInputType" }),
11625 }).annotate({ title: "MentionUserInput" }),
11626 ],
11627 { mode: "oneOf" },
11628);
11629
11630export type V2ItemGuardianApprovalReviewCompletedNotification__GuardianApprovalReview = {
11631 readonly rationale?: string | null;
11632 readonly riskLevel?: V2ItemGuardianApprovalReviewCompletedNotification__GuardianRiskLevel | null;
11633 readonly status: V2ItemGuardianApprovalReviewCompletedNotification__GuardianApprovalReviewStatus;
11634 readonly userAuthorization?: V2ItemGuardianApprovalReviewCompletedNotification__GuardianUserAuthorization | null;
11635};
11636export const V2ItemGuardianApprovalReviewCompletedNotification__GuardianApprovalReview =
11637 Schema.Struct({
11638 rationale: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
11639 riskLevel: Schema.optionalKey(
11640 Schema.Union([
11641 V2ItemGuardianApprovalReviewCompletedNotification__GuardianRiskLevel,
11642 Schema.Null,
11643 ]),
11644 ),
11645 status: V2ItemGuardianApprovalReviewCompletedNotification__GuardianApprovalReviewStatus,
11646 userAuthorization: Schema.optionalKey(
11647 Schema.Union([
11648 V2ItemGuardianApprovalReviewCompletedNotification__GuardianUserAuthorization,
11649 Schema.Null,
11650 ]),
11651 ),
11652 }).annotate({
11653 description:
11654 "[UNSTABLE] Temporary guardian approval review payload used by `item/autoApprovalReview/*` notifications. This shape is expected to change soon.",
11655 });
11656
11657export type V2ItemGuardianApprovalReviewCompletedNotification__GuardianApprovalReviewAction =
11658 | {
11659 readonly command: string;
11660 readonly cwd: string;
11661 readonly source: V2ItemGuardianApprovalReviewCompletedNotification__GuardianCommandSource;
11662 readonly type: "command";
11663 }
11664 | {
11665 readonly argv: ReadonlyArray<string>;
11666 readonly cwd: string;
11667 readonly program: string;
11668 readonly source: V2ItemGuardianApprovalReviewCompletedNotification__GuardianCommandSource;
11669 readonly type: "execve";
11670 }
11671 | { readonly cwd: string; readonly files: ReadonlyArray<string>; readonly type: "applyPatch" }
11672 | {
11673 readonly host: string;
11674 readonly port: number;
11675 readonly protocol: V2ItemGuardianApprovalReviewCompletedNotification__NetworkApprovalProtocol;
11676 readonly target: string;
11677 readonly type: "networkAccess";
11678 }
11679 | {
11680 readonly connectorId?: string | null;
11681 readonly connectorName?: string | null;
11682 readonly server: string;
11683 readonly toolName: string;
11684 readonly toolTitle?: string | null;
11685 readonly type: "mcpToolCall";
11686 };
11687export const V2ItemGuardianApprovalReviewCompletedNotification__GuardianApprovalReviewAction =
11688 Schema.Union(
11689 [
11690 Schema.Struct({
11691 command: Schema.String,
11692 cwd: Schema.String,
11693 source: V2ItemGuardianApprovalReviewCompletedNotification__GuardianCommandSource,
11694 type: Schema.Literal("command").annotate({
11695 title: "CommandGuardianApprovalReviewActionType",
11696 }),
11697 }).annotate({ title: "CommandGuardianApprovalReviewAction" }),
11698 Schema.Struct({
11699 argv: Schema.Array(Schema.String),
11700 cwd: Schema.String,
11701 program: Schema.String,
11702 source: V2ItemGuardianApprovalReviewCompletedNotification__GuardianCommandSource,
11703 type: Schema.Literal("execve").annotate({
11704 title: "ExecveGuardianApprovalReviewActionType",
11705 }),
11706 }).annotate({ title: "ExecveGuardianApprovalReviewAction" }),
11707 Schema.Struct({
11708 cwd: Schema.String,
11709 files: Schema.Array(Schema.String),
11710 type: Schema.Literal("applyPatch").annotate({
11711 title: "ApplyPatchGuardianApprovalReviewActionType",
11712 }),
11713 }).annotate({ title: "ApplyPatchGuardianApprovalReviewAction" }),
11714 Schema.Struct({
11715 host: Schema.String,
11716 port: Schema.Number.annotate({ format: "uint16" })
11717 .check(Schema.isInt())
11718 .check(Schema.isGreaterThanOrEqualTo(0)),
11719 protocol: V2ItemGuardianApprovalReviewCompletedNotification__NetworkApprovalProtocol,
11720 target: Schema.String,
11721 type: Schema.Literal("networkAccess").annotate({
11722 title: "NetworkAccessGuardianApprovalReviewActionType",
11723 }),
11724 }).annotate({ title: "NetworkAccessGuardianApprovalReviewAction" }),
11725 Schema.Struct({
11726 connectorId: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
11727 connectorName: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
11728 server: Schema.String,
11729 toolName: Schema.String,
11730 toolTitle: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
11731 type: Schema.Literal("mcpToolCall").annotate({
11732 title: "McpToolCallGuardianApprovalReviewActionType",
11733 }),
11734 }).annotate({ title: "McpToolCallGuardianApprovalReviewAction" }),
11735 ],
11736 { mode: "oneOf" },
11737 );
11738
11739export type V2ItemGuardianApprovalReviewStartedNotification__GuardianApprovalReview = {
11740 readonly rationale?: string | null;
11741 readonly riskLevel?: V2ItemGuardianApprovalReviewStartedNotification__GuardianRiskLevel | null;
11742 readonly status: V2ItemGuardianApprovalReviewStartedNotification__GuardianApprovalReviewStatus;
11743 readonly userAuthorization?: V2ItemGuardianApprovalReviewStartedNotification__GuardianUserAuthorization | null;
11744};
11745export const V2ItemGuardianApprovalReviewStartedNotification__GuardianApprovalReview =
11746 Schema.Struct({
11747 rationale: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
11748 riskLevel: Schema.optionalKey(
11749 Schema.Union([
11750 V2ItemGuardianApprovalReviewStartedNotification__GuardianRiskLevel,
11751 Schema.Null,
11752 ]),
11753 ),
11754 status: V2ItemGuardianApprovalReviewStartedNotification__GuardianApprovalReviewStatus,
11755 userAuthorization: Schema.optionalKey(
11756 Schema.Union([
11757 V2ItemGuardianApprovalReviewStartedNotification__GuardianUserAuthorization,
11758 Schema.Null,
11759 ]),
11760 ),
11761 }).annotate({
11762 description:
11763 "[UNSTABLE] Temporary guardian approval review payload used by `item/autoApprovalReview/*` notifications. This shape is expected to change soon.",
11764 });
11765
11766export type V2ItemGuardianApprovalReviewStartedNotification__GuardianApprovalReviewAction =
11767 | {
11768 readonly command: string;
11769 readonly cwd: string;
11770 readonly source: V2ItemGuardianApprovalReviewStartedNotification__GuardianCommandSource;
11771 readonly type: "command";
11772 }
11773 | {
11774 readonly argv: ReadonlyArray<string>;
11775 readonly cwd: string;
11776 readonly program: string;
11777 readonly source: V2ItemGuardianApprovalReviewStartedNotification__GuardianCommandSource;
11778 readonly type: "execve";
11779 }
11780 | { readonly cwd: string; readonly files: ReadonlyArray<string>; readonly type: "applyPatch" }
11781 | {
11782 readonly host: string;
11783 readonly port: number;
11784 readonly protocol: V2ItemGuardianApprovalReviewStartedNotification__NetworkApprovalProtocol;
11785 readonly target: string;
11786 readonly type: "networkAccess";
11787 }
11788 | {
11789 readonly connectorId?: string | null;
11790 readonly connectorName?: string | null;
11791 readonly server: string;
11792 readonly toolName: string;
11793 readonly toolTitle?: string | null;
11794 readonly type: "mcpToolCall";
11795 };
11796export const V2ItemGuardianApprovalReviewStartedNotification__GuardianApprovalReviewAction =
11797 Schema.Union(
11798 [
11799 Schema.Struct({
11800 command: Schema.String,
11801 cwd: Schema.String,
11802 source: V2ItemGuardianApprovalReviewStartedNotification__GuardianCommandSource,
11803 type: Schema.Literal("command").annotate({
11804 title: "CommandGuardianApprovalReviewActionType",
11805 }),
11806 }).annotate({ title: "CommandGuardianApprovalReviewAction" }),
11807 Schema.Struct({
11808 argv: Schema.Array(Schema.String),
11809 cwd: Schema.String,
11810 program: Schema.String,
11811 source: V2ItemGuardianApprovalReviewStartedNotification__GuardianCommandSource,
11812 type: Schema.Literal("execve").annotate({
11813 title: "ExecveGuardianApprovalReviewActionType",
11814 }),
11815 }).annotate({ title: "ExecveGuardianApprovalReviewAction" }),
11816 Schema.Struct({
11817 cwd: Schema.String,
11818 files: Schema.Array(Schema.String),
11819 type: Schema.Literal("applyPatch").annotate({
11820 title: "ApplyPatchGuardianApprovalReviewActionType",
11821 }),
11822 }).annotate({ title: "ApplyPatchGuardianApprovalReviewAction" }),
11823 Schema.Struct({
11824 host: Schema.String,
11825 port: Schema.Number.annotate({ format: "uint16" })
11826 .check(Schema.isInt())
11827 .check(Schema.isGreaterThanOrEqualTo(0)),
11828 protocol: V2ItemGuardianApprovalReviewStartedNotification__NetworkApprovalProtocol,
11829 target: Schema.String,
11830 type: Schema.Literal("networkAccess").annotate({
11831 title: "NetworkAccessGuardianApprovalReviewActionType",
11832 }),
11833 }).annotate({ title: "NetworkAccessGuardianApprovalReviewAction" }),
11834 Schema.Struct({
11835 connectorId: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
11836 connectorName: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
11837 server: Schema.String,
11838 toolName: Schema.String,
11839 toolTitle: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
11840 type: Schema.Literal("mcpToolCall").annotate({
11841 title: "McpToolCallGuardianApprovalReviewActionType",
11842 }),
11843 }).annotate({ title: "McpToolCallGuardianApprovalReviewAction" }),
11844 ],
11845 { mode: "oneOf" },
11846 );
11847
11848export type V2ItemStartedNotification__CollabAgentState = {
11849 readonly message?: string | null;
11850 readonly status: V2ItemStartedNotification__CollabAgentStatus;
11851};
11852export const V2ItemStartedNotification__CollabAgentState = Schema.Struct({
11853 message: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
11854 status: V2ItemStartedNotification__CollabAgentStatus,
11855});
11856
11857export type V2ItemStartedNotification__MemoryCitation = {
11858 readonly entries: ReadonlyArray<V2ItemStartedNotification__MemoryCitationEntry>;
11859 readonly threadIds: ReadonlyArray<string>;
11860};
11861export const V2ItemStartedNotification__MemoryCitation = Schema.Struct({
11862 entries: Schema.Array(V2ItemStartedNotification__MemoryCitationEntry),
11863 threadIds: Schema.Array(Schema.String),
11864});
11865
11866export type V2ItemStartedNotification__FileUpdateChange = {
11867 readonly diff: string;
11868 readonly kind: V2ItemStartedNotification__PatchChangeKind;
11869 readonly path: string;
11870};
11871export const V2ItemStartedNotification__FileUpdateChange = Schema.Struct({
11872 diff: Schema.String,
11873 kind: V2ItemStartedNotification__PatchChangeKind,
11874 path: Schema.String,
11875});
11876
11877export type V2ItemStartedNotification__UserInput =
11878 | {
11879 readonly text: string;
11880 readonly text_elements?: ReadonlyArray<V2ItemStartedNotification__TextElement>;
11881 readonly type: "text";
11882 }
11883 | { readonly type: "image"; readonly url: string }
11884 | { readonly path: string; readonly type: "localImage" }
11885 | { readonly name: string; readonly path: string; readonly type: "skill" }
11886 | { readonly name: string; readonly path: string; readonly type: "mention" };
11887export const V2ItemStartedNotification__UserInput = Schema.Union(
11888 [
11889 Schema.Struct({
11890 text: Schema.String,
11891 text_elements: Schema.optionalKey(
11892 Schema.Array(V2ItemStartedNotification__TextElement).annotate({
11893 description: "UI-defined spans within `text` used to render or persist special elements.",
11894 default: [],
11895 }),
11896 ),
11897 type: Schema.Literal("text").annotate({ title: "TextUserInputType" }),
11898 }).annotate({ title: "TextUserInput" }),
11899 Schema.Struct({
11900 type: Schema.Literal("image").annotate({ title: "ImageUserInputType" }),
11901 url: Schema.String,
11902 }).annotate({ title: "ImageUserInput" }),
11903 Schema.Struct({
11904 path: Schema.String,
11905 type: Schema.Literal("localImage").annotate({ title: "LocalImageUserInputType" }),
11906 }).annotate({ title: "LocalImageUserInput" }),
11907 Schema.Struct({
11908 name: Schema.String,
11909 path: Schema.String,
11910 type: Schema.Literal("skill").annotate({ title: "SkillUserInputType" }),
11911 }).annotate({ title: "SkillUserInput" }),
11912 Schema.Struct({
11913 name: Schema.String,
11914 path: Schema.String,
11915 type: Schema.Literal("mention").annotate({ title: "MentionUserInputType" }),
11916 }).annotate({ title: "MentionUserInput" }),
11917 ],
11918 { mode: "oneOf" },
11919);
11920
11921export type V2ListMcpServerStatusResponse__McpServerStatus = {
11922 readonly authStatus: V2ListMcpServerStatusResponse__McpAuthStatus;
11923 readonly name: string;
11924 readonly resourceTemplates: ReadonlyArray<V2ListMcpServerStatusResponse__ResourceTemplate>;
11925 readonly resources: ReadonlyArray<V2ListMcpServerStatusResponse__Resource>;
11926 readonly tools: { readonly [x: string]: V2ListMcpServerStatusResponse__Tool };
11927};
11928export const V2ListMcpServerStatusResponse__McpServerStatus = Schema.Struct({
11929 authStatus: V2ListMcpServerStatusResponse__McpAuthStatus,
11930 name: Schema.String,
11931 resourceTemplates: Schema.Array(V2ListMcpServerStatusResponse__ResourceTemplate),
11932 resources: Schema.Array(V2ListMcpServerStatusResponse__Resource),
11933 tools: Schema.Record(Schema.String, V2ListMcpServerStatusResponse__Tool),
11934});
11935
11936export type V2ModelListResponse__ReasoningEffortOption = {
11937 readonly description: string;
11938 readonly reasoningEffort: V2ModelListResponse__ReasoningEffort;
11939};
11940export const V2ModelListResponse__ReasoningEffortOption = Schema.Struct({
11941 description: Schema.String,
11942 reasoningEffort: V2ModelListResponse__ReasoningEffort,
11943});
11944
11945export type V2PluginListResponse__MarketplaceLoadErrorInfo = {
11946 readonly marketplacePath: V2PluginListResponse__AbsolutePathBuf;
11947 readonly message: string;
11948};
11949export const V2PluginListResponse__MarketplaceLoadErrorInfo = Schema.Struct({
11950 marketplacePath: V2PluginListResponse__AbsolutePathBuf,
11951 message: Schema.String,
11952});
11953
11954export type V2PluginListResponse__PluginInterface = {
11955 readonly brandColor?: string | null;
11956 readonly capabilities: ReadonlyArray<string>;
11957 readonly category?: string | null;
11958 readonly composerIcon?: V2PluginListResponse__AbsolutePathBuf | null;
11959 readonly defaultPrompt?: ReadonlyArray<string> | null;
11960 readonly developerName?: string | null;
11961 readonly displayName?: string | null;
11962 readonly logo?: V2PluginListResponse__AbsolutePathBuf | null;
11963 readonly longDescription?: string | null;
11964 readonly privacyPolicyUrl?: string | null;
11965 readonly screenshots: ReadonlyArray<V2PluginListResponse__AbsolutePathBuf>;
11966 readonly shortDescription?: string | null;
11967 readonly termsOfServiceUrl?: string | null;
11968 readonly websiteUrl?: string | null;
11969};
11970export const V2PluginListResponse__PluginInterface = Schema.Struct({
11971 brandColor: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
11972 capabilities: Schema.Array(Schema.String),
11973 category: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
11974 composerIcon: Schema.optionalKey(
11975 Schema.Union([V2PluginListResponse__AbsolutePathBuf, Schema.Null]),
11976 ),
11977 defaultPrompt: Schema.optionalKey(
11978 Schema.Union([
11979 Schema.Array(Schema.String).annotate({
11980 description:
11981 "Starter prompts for the plugin. Capped at 3 entries with a maximum of 128 characters per entry.",
11982 }),
11983 Schema.Null,
11984 ]),
11985 ),
11986 developerName: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
11987 displayName: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
11988 logo: Schema.optionalKey(Schema.Union([V2PluginListResponse__AbsolutePathBuf, Schema.Null])),
11989 longDescription: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
11990 privacyPolicyUrl: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
11991 screenshots: Schema.Array(V2PluginListResponse__AbsolutePathBuf),
11992 shortDescription: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
11993 termsOfServiceUrl: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
11994 websiteUrl: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
11995});
11996
11997export type V2PluginListResponse__PluginSource = {
11998 readonly path: V2PluginListResponse__AbsolutePathBuf;
11999 readonly type: "local";
12000};
12001export const V2PluginListResponse__PluginSource = Schema.Union(
12002 [
12003 Schema.Struct({
12004 path: V2PluginListResponse__AbsolutePathBuf,
12005 type: Schema.Literal("local").annotate({ title: "LocalPluginSourceType" }),
12006 }).annotate({ title: "LocalPluginSource" }),
12007 ],
12008 { mode: "oneOf" },
12009);
12010
12011export type V2PluginReadResponse__PluginInterface = {
12012 readonly brandColor?: string | null;
12013 readonly capabilities: ReadonlyArray<string>;
12014 readonly category?: string | null;
12015 readonly composerIcon?: V2PluginReadResponse__AbsolutePathBuf | null;
12016 readonly defaultPrompt?: ReadonlyArray<string> | null;
12017 readonly developerName?: string | null;
12018 readonly displayName?: string | null;
12019 readonly logo?: V2PluginReadResponse__AbsolutePathBuf | null;
12020 readonly longDescription?: string | null;
12021 readonly privacyPolicyUrl?: string | null;
12022 readonly screenshots: ReadonlyArray<V2PluginReadResponse__AbsolutePathBuf>;
12023 readonly shortDescription?: string | null;
12024 readonly termsOfServiceUrl?: string | null;
12025 readonly websiteUrl?: string | null;
12026};
12027export const V2PluginReadResponse__PluginInterface = Schema.Struct({
12028 brandColor: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
12029 capabilities: Schema.Array(Schema.String),
12030 category: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
12031 composerIcon: Schema.optionalKey(
12032 Schema.Union([V2PluginReadResponse__AbsolutePathBuf, Schema.Null]),
12033 ),
12034 defaultPrompt: Schema.optionalKey(
12035 Schema.Union([
12036 Schema.Array(Schema.String).annotate({
12037 description:
12038 "Starter prompts for the plugin. Capped at 3 entries with a maximum of 128 characters per entry.",
12039 }),
12040 Schema.Null,
12041 ]),
12042 ),
12043 developerName: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
12044 displayName: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
12045 logo: Schema.optionalKey(Schema.Union([V2PluginReadResponse__AbsolutePathBuf, Schema.Null])),
12046 longDescription: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
12047 privacyPolicyUrl: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
12048 screenshots: Schema.Array(V2PluginReadResponse__AbsolutePathBuf),
12049 shortDescription: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
12050 termsOfServiceUrl: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
12051 websiteUrl: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
12052});
12053
12054export type V2PluginReadResponse__PluginSource = {
12055 readonly path: V2PluginReadResponse__AbsolutePathBuf;
12056 readonly type: "local";
12057};
12058export const V2PluginReadResponse__PluginSource = Schema.Union(
12059 [
12060 Schema.Struct({
12061 path: V2PluginReadResponse__AbsolutePathBuf,
12062 type: Schema.Literal("local").annotate({ title: "LocalPluginSourceType" }),
12063 }).annotate({ title: "LocalPluginSource" }),
12064 ],
12065 { mode: "oneOf" },
12066);
12067
12068export type V2PluginReadResponse__SkillSummary = {
12069 readonly description: string;
12070 readonly enabled: boolean;
12071 readonly interface?: V2PluginReadResponse__SkillInterface | null;
12072 readonly name: string;
12073 readonly path: string;
12074 readonly shortDescription?: string | null;
12075};
12076export const V2PluginReadResponse__SkillSummary = Schema.Struct({
12077 description: Schema.String,
12078 enabled: Schema.Boolean,
12079 interface: Schema.optionalKey(Schema.Union([V2PluginReadResponse__SkillInterface, Schema.Null])),
12080 name: Schema.String,
12081 path: Schema.String,
12082 shortDescription: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
12083});
12084
12085export type V2RawResponseItemCompletedNotification__FunctionCallOutputContentItem =
12086 | { readonly text: string; readonly type: "input_text" }
12087 | {
12088 readonly detail?: V2RawResponseItemCompletedNotification__ImageDetail | null;
12089 readonly image_url: string;
12090 readonly type: "input_image";
12091 };
12092export const V2RawResponseItemCompletedNotification__FunctionCallOutputContentItem = Schema.Union(
12093 [
12094 Schema.Struct({
12095 text: Schema.String,
12096 type: Schema.Literal("input_text").annotate({
12097 title: "InputTextFunctionCallOutputContentItemType",
12098 }),
12099 }).annotate({ title: "InputTextFunctionCallOutputContentItem" }),
12100 Schema.Struct({
12101 detail: Schema.optionalKey(
12102 Schema.Union([V2RawResponseItemCompletedNotification__ImageDetail, Schema.Null]),
12103 ),
12104 image_url: Schema.String,
12105 type: Schema.Literal("input_image").annotate({
12106 title: "InputImageFunctionCallOutputContentItemType",
12107 }),
12108 }).annotate({ title: "InputImageFunctionCallOutputContentItem" }),
12109 ],
12110 { mode: "oneOf" },
12111).annotate({
12112 description:
12113 "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.",
12114});
12115
12116export type V2ReviewStartResponse__CollabAgentState = {
12117 readonly message?: string | null;
12118 readonly status: V2ReviewStartResponse__CollabAgentStatus;
12119};
12120export const V2ReviewStartResponse__CollabAgentState = Schema.Struct({
12121 message: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
12122 status: V2ReviewStartResponse__CollabAgentStatus,
12123});
12124
12125export type V2ReviewStartResponse__MemoryCitation = {
12126 readonly entries: ReadonlyArray<V2ReviewStartResponse__MemoryCitationEntry>;
12127 readonly threadIds: ReadonlyArray<string>;
12128};
12129export const V2ReviewStartResponse__MemoryCitation = Schema.Struct({
12130 entries: Schema.Array(V2ReviewStartResponse__MemoryCitationEntry),
12131 threadIds: Schema.Array(Schema.String),
12132});
12133
12134export type V2ReviewStartResponse__CodexErrorInfo =
12135 | "contextWindowExceeded"
12136 | "usageLimitExceeded"
12137 | "serverOverloaded"
12138 | "internalServerError"
12139 | "unauthorized"
12140 | "badRequest"
12141 | "threadRollbackFailed"
12142 | "sandboxError"
12143 | "other"
12144 | { readonly httpConnectionFailed: { readonly httpStatusCode?: number | null } }
12145 | { readonly responseStreamConnectionFailed: { readonly httpStatusCode?: number | null } }
12146 | { readonly responseStreamDisconnected: { readonly httpStatusCode?: number | null } }
12147 | { readonly responseTooManyFailedAttempts: { readonly httpStatusCode?: number | null } }
12148 | {
12149 readonly activeTurnNotSteerable: {
12150 readonly turnKind: V2ReviewStartResponse__NonSteerableTurnKind;
12151 };
12152 };
12153export const V2ReviewStartResponse__CodexErrorInfo = Schema.Union(
12154 [
12155 Schema.Literals([
12156 "contextWindowExceeded",
12157 "usageLimitExceeded",
12158 "serverOverloaded",
12159 "internalServerError",
12160 "unauthorized",
12161 "badRequest",
12162 "threadRollbackFailed",
12163 "sandboxError",
12164 "other",
12165 ]),
12166 Schema.Struct({
12167 httpConnectionFailed: Schema.Struct({
12168 httpStatusCode: Schema.optionalKey(
12169 Schema.Union([
12170 Schema.Number.annotate({ format: "uint16" })
12171 .check(Schema.isInt())
12172 .check(Schema.isGreaterThanOrEqualTo(0)),
12173 Schema.Null,
12174 ]),
12175 ),
12176 }),
12177 }).annotate({ title: "HttpConnectionFailedCodexErrorInfo" }),
12178 Schema.Struct({
12179 responseStreamConnectionFailed: Schema.Struct({
12180 httpStatusCode: Schema.optionalKey(
12181 Schema.Union([
12182 Schema.Number.annotate({ format: "uint16" })
12183 .check(Schema.isInt())
12184 .check(Schema.isGreaterThanOrEqualTo(0)),
12185 Schema.Null,
12186 ]),
12187 ),
12188 }),
12189 }).annotate({
12190 title: "ResponseStreamConnectionFailedCodexErrorInfo",
12191 description: "Failed to connect to the response SSE stream.",
12192 }),
12193 Schema.Struct({
12194 responseStreamDisconnected: Schema.Struct({
12195 httpStatusCode: Schema.optionalKey(
12196 Schema.Union([
12197 Schema.Number.annotate({ format: "uint16" })
12198 .check(Schema.isInt())
12199 .check(Schema.isGreaterThanOrEqualTo(0)),
12200 Schema.Null,
12201 ]),
12202 ),
12203 }),
12204 }).annotate({
12205 title: "ResponseStreamDisconnectedCodexErrorInfo",
12206 description:
12207 "The response SSE stream disconnected in the middle of a turn before completion.",
12208 }),
12209 Schema.Struct({
12210 responseTooManyFailedAttempts: Schema.Struct({
12211 httpStatusCode: Schema.optionalKey(
12212 Schema.Union([
12213 Schema.Number.annotate({ format: "uint16" })
12214 .check(Schema.isInt())
12215 .check(Schema.isGreaterThanOrEqualTo(0)),
12216 Schema.Null,
12217 ]),
12218 ),
12219 }),
12220 }).annotate({
12221 title: "ResponseTooManyFailedAttemptsCodexErrorInfo",
12222 description: "Reached the retry limit for responses.",
12223 }),
12224 Schema.Struct({
12225 activeTurnNotSteerable: Schema.Struct({
12226 turnKind: V2ReviewStartResponse__NonSteerableTurnKind,
12227 }),
12228 }).annotate({
12229 title: "ActiveTurnNotSteerableCodexErrorInfo",
12230 description:
12231 "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`.",
12232 }),
12233 ],
12234 { mode: "oneOf" },
12235).annotate({
12236 description:
12237 "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.",
12238});
12239
12240export type V2ReviewStartResponse__FileUpdateChange = {
12241 readonly diff: string;
12242 readonly kind: V2ReviewStartResponse__PatchChangeKind;
12243 readonly path: string;
12244};
12245export const V2ReviewStartResponse__FileUpdateChange = Schema.Struct({
12246 diff: Schema.String,
12247 kind: V2ReviewStartResponse__PatchChangeKind,
12248 path: Schema.String,
12249});
12250
12251export type V2ReviewStartResponse__UserInput =
12252 | {
12253 readonly text: string;
12254 readonly text_elements?: ReadonlyArray<V2ReviewStartResponse__TextElement>;
12255 readonly type: "text";
12256 }
12257 | { readonly type: "image"; readonly url: string }
12258 | { readonly path: string; readonly type: "localImage" }
12259 | { readonly name: string; readonly path: string; readonly type: "skill" }
12260 | { readonly name: string; readonly path: string; readonly type: "mention" };
12261export const V2ReviewStartResponse__UserInput = Schema.Union(
12262 [
12263 Schema.Struct({
12264 text: Schema.String,
12265 text_elements: Schema.optionalKey(
12266 Schema.Array(V2ReviewStartResponse__TextElement).annotate({
12267 description: "UI-defined spans within `text` used to render or persist special elements.",
12268 default: [],
12269 }),
12270 ),
12271 type: Schema.Literal("text").annotate({ title: "TextUserInputType" }),
12272 }).annotate({ title: "TextUserInput" }),
12273 Schema.Struct({
12274 type: Schema.Literal("image").annotate({ title: "ImageUserInputType" }),
12275 url: Schema.String,
12276 }).annotate({ title: "ImageUserInput" }),
12277 Schema.Struct({
12278 path: Schema.String,
12279 type: Schema.Literal("localImage").annotate({ title: "LocalImageUserInputType" }),
12280 }).annotate({ title: "LocalImageUserInput" }),
12281 Schema.Struct({
12282 name: Schema.String,
12283 path: Schema.String,
12284 type: Schema.Literal("skill").annotate({ title: "SkillUserInputType" }),
12285 }).annotate({ title: "SkillUserInput" }),
12286 Schema.Struct({
12287 name: Schema.String,
12288 path: Schema.String,
12289 type: Schema.Literal("mention").annotate({ title: "MentionUserInputType" }),
12290 }).annotate({ title: "MentionUserInput" }),
12291 ],
12292 { mode: "oneOf" },
12293);
12294
12295export type V2SkillsListResponse__SkillDependencies = {
12296 readonly tools: ReadonlyArray<V2SkillsListResponse__SkillToolDependency>;
12297};
12298export const V2SkillsListResponse__SkillDependencies = Schema.Struct({
12299 tools: Schema.Array(V2SkillsListResponse__SkillToolDependency),
12300});
12301
12302export type V2ThreadForkResponse__SandboxPolicy =
12303 | { readonly type: "dangerFullAccess" }
12304 | {
12305 readonly access?:
12306 | {
12307 readonly includePlatformDefaults?: boolean;
12308 readonly readableRoots?: ReadonlyArray<V2ThreadForkResponse__AbsolutePathBuf>;
12309 readonly type: "restricted";
12310 }
12311 | { readonly type: "fullAccess" };
12312 readonly networkAccess?: boolean;
12313 readonly type: "readOnly";
12314 }
12315 | { readonly networkAccess?: "restricted" | "enabled"; readonly type: "externalSandbox" }
12316 | {
12317 readonly excludeSlashTmp?: boolean;
12318 readonly excludeTmpdirEnvVar?: boolean;
12319 readonly networkAccess?: boolean;
12320 readonly readOnlyAccess?:
12321 | {
12322 readonly includePlatformDefaults?: boolean;
12323 readonly readableRoots?: ReadonlyArray<V2ThreadForkResponse__AbsolutePathBuf>;
12324 readonly type: "restricted";
12325 }
12326 | { readonly type: "fullAccess" };
12327 readonly type: "workspaceWrite";
12328 readonly writableRoots?: ReadonlyArray<V2ThreadForkResponse__AbsolutePathBuf>;
12329 };
12330export const V2ThreadForkResponse__SandboxPolicy = Schema.Union(
12331 [
12332 Schema.Struct({
12333 type: Schema.Literal("dangerFullAccess").annotate({
12334 title: "DangerFullAccessSandboxPolicyType",
12335 }),
12336 }).annotate({ title: "DangerFullAccessSandboxPolicy" }),
12337 Schema.Struct({
12338 access: Schema.optionalKey(
12339 Schema.Union(
12340 [
12341 Schema.Struct({
12342 includePlatformDefaults: Schema.optionalKey(
12343 Schema.Boolean.annotate({ default: true }),
12344 ),
12345 readableRoots: Schema.optionalKey(
12346 Schema.Array(V2ThreadForkResponse__AbsolutePathBuf).annotate({ default: [] }),
12347 ),
12348 type: Schema.Literal("restricted").annotate({
12349 title: "RestrictedReadOnlyAccessType",
12350 }),
12351 }).annotate({ title: "RestrictedReadOnlyAccess" }),
12352 Schema.Struct({
12353 type: Schema.Literal("fullAccess").annotate({
12354 title: "FullAccessReadOnlyAccessType",
12355 }),
12356 }).annotate({ title: "FullAccessReadOnlyAccess" }),
12357 ],
12358 { mode: "oneOf" },
12359 ).annotate({ default: { type: "fullAccess" } }),
12360 ),
12361 networkAccess: Schema.optionalKey(Schema.Boolean.annotate({ default: false })),
12362 type: Schema.Literal("readOnly").annotate({ title: "ReadOnlySandboxPolicyType" }),
12363 }).annotate({ title: "ReadOnlySandboxPolicy" }),
12364 Schema.Struct({
12365 networkAccess: Schema.optionalKey(
12366 Schema.Literals(["restricted", "enabled"]).annotate({ default: "restricted" }),
12367 ),
12368 type: Schema.Literal("externalSandbox").annotate({
12369 title: "ExternalSandboxSandboxPolicyType",
12370 }),
12371 }).annotate({ title: "ExternalSandboxSandboxPolicy" }),
12372 Schema.Struct({
12373 excludeSlashTmp: Schema.optionalKey(Schema.Boolean.annotate({ default: false })),
12374 excludeTmpdirEnvVar: Schema.optionalKey(Schema.Boolean.annotate({ default: false })),
12375 networkAccess: Schema.optionalKey(Schema.Boolean.annotate({ default: false })),
12376 readOnlyAccess: Schema.optionalKey(
12377 Schema.Union(
12378 [
12379 Schema.Struct({
12380 includePlatformDefaults: Schema.optionalKey(
12381 Schema.Boolean.annotate({ default: true }),
12382 ),
12383 readableRoots: Schema.optionalKey(
12384 Schema.Array(V2ThreadForkResponse__AbsolutePathBuf).annotate({ default: [] }),
12385 ),
12386 type: Schema.Literal("restricted").annotate({
12387 title: "RestrictedReadOnlyAccessType",
12388 }),
12389 }).annotate({ title: "RestrictedReadOnlyAccess" }),
12390 Schema.Struct({
12391 type: Schema.Literal("fullAccess").annotate({
12392 title: "FullAccessReadOnlyAccessType",
12393 }),
12394 }).annotate({ title: "FullAccessReadOnlyAccess" }),
12395 ],
12396 { mode: "oneOf" },
12397 ).annotate({ default: { type: "fullAccess" } }),
12398 ),
12399 type: Schema.Literal("workspaceWrite").annotate({ title: "WorkspaceWriteSandboxPolicyType" }),
12400 writableRoots: Schema.optionalKey(
12401 Schema.Array(V2ThreadForkResponse__AbsolutePathBuf).annotate({ default: [] }),
12402 ),
12403 }).annotate({ title: "WorkspaceWriteSandboxPolicy" }),
12404 ],
12405 { mode: "oneOf" },
12406);
12407
12408export type V2ThreadForkResponse__CollabAgentState = {
12409 readonly message?: string | null;
12410 readonly status: V2ThreadForkResponse__CollabAgentStatus;
12411};
12412export const V2ThreadForkResponse__CollabAgentState = Schema.Struct({
12413 message: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
12414 status: V2ThreadForkResponse__CollabAgentStatus,
12415});
12416
12417export type V2ThreadForkResponse__MemoryCitation = {
12418 readonly entries: ReadonlyArray<V2ThreadForkResponse__MemoryCitationEntry>;
12419 readonly threadIds: ReadonlyArray<string>;
12420};
12421export const V2ThreadForkResponse__MemoryCitation = Schema.Struct({
12422 entries: Schema.Array(V2ThreadForkResponse__MemoryCitationEntry),
12423 threadIds: Schema.Array(Schema.String),
12424});
12425
12426export type V2ThreadForkResponse__CodexErrorInfo =
12427 | "contextWindowExceeded"
12428 | "usageLimitExceeded"
12429 | "serverOverloaded"
12430 | "internalServerError"
12431 | "unauthorized"
12432 | "badRequest"
12433 | "threadRollbackFailed"
12434 | "sandboxError"
12435 | "other"
12436 | { readonly httpConnectionFailed: { readonly httpStatusCode?: number | null } }
12437 | { readonly responseStreamConnectionFailed: { readonly httpStatusCode?: number | null } }
12438 | { readonly responseStreamDisconnected: { readonly httpStatusCode?: number | null } }
12439 | { readonly responseTooManyFailedAttempts: { readonly httpStatusCode?: number | null } }
12440 | {
12441 readonly activeTurnNotSteerable: {
12442 readonly turnKind: V2ThreadForkResponse__NonSteerableTurnKind;
12443 };
12444 };
12445export const V2ThreadForkResponse__CodexErrorInfo = Schema.Union(
12446 [
12447 Schema.Literals([
12448 "contextWindowExceeded",
12449 "usageLimitExceeded",
12450 "serverOverloaded",
12451 "internalServerError",
12452 "unauthorized",
12453 "badRequest",
12454 "threadRollbackFailed",
12455 "sandboxError",
12456 "other",
12457 ]),
12458 Schema.Struct({
12459 httpConnectionFailed: Schema.Struct({
12460 httpStatusCode: Schema.optionalKey(
12461 Schema.Union([
12462 Schema.Number.annotate({ format: "uint16" })
12463 .check(Schema.isInt())
12464 .check(Schema.isGreaterThanOrEqualTo(0)),
12465 Schema.Null,
12466 ]),
12467 ),
12468 }),
12469 }).annotate({ title: "HttpConnectionFailedCodexErrorInfo" }),
12470 Schema.Struct({
12471 responseStreamConnectionFailed: Schema.Struct({
12472 httpStatusCode: Schema.optionalKey(
12473 Schema.Union([
12474 Schema.Number.annotate({ format: "uint16" })
12475 .check(Schema.isInt())
12476 .check(Schema.isGreaterThanOrEqualTo(0)),
12477 Schema.Null,
12478 ]),
12479 ),
12480 }),
12481 }).annotate({
12482 title: "ResponseStreamConnectionFailedCodexErrorInfo",
12483 description: "Failed to connect to the response SSE stream.",
12484 }),
12485 Schema.Struct({
12486 responseStreamDisconnected: Schema.Struct({
12487 httpStatusCode: Schema.optionalKey(
12488 Schema.Union([
12489 Schema.Number.annotate({ format: "uint16" })
12490 .check(Schema.isInt())
12491 .check(Schema.isGreaterThanOrEqualTo(0)),
12492 Schema.Null,
12493 ]),
12494 ),
12495 }),
12496 }).annotate({
12497 title: "ResponseStreamDisconnectedCodexErrorInfo",
12498 description:
12499 "The response SSE stream disconnected in the middle of a turn before completion.",
12500 }),
12501 Schema.Struct({
12502 responseTooManyFailedAttempts: Schema.Struct({
12503 httpStatusCode: Schema.optionalKey(
12504 Schema.Union([
12505 Schema.Number.annotate({ format: "uint16" })
12506 .check(Schema.isInt())
12507 .check(Schema.isGreaterThanOrEqualTo(0)),
12508 Schema.Null,
12509 ]),
12510 ),
12511 }),
12512 }).annotate({
12513 title: "ResponseTooManyFailedAttemptsCodexErrorInfo",
12514 description: "Reached the retry limit for responses.",
12515 }),
12516 Schema.Struct({
12517 activeTurnNotSteerable: Schema.Struct({
12518 turnKind: V2ThreadForkResponse__NonSteerableTurnKind,
12519 }),
12520 }).annotate({
12521 title: "ActiveTurnNotSteerableCodexErrorInfo",
12522 description:
12523 "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`.",
12524 }),
12525 ],
12526 { mode: "oneOf" },
12527).annotate({
12528 description:
12529 "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.",
12530});
12531
12532export type V2ThreadForkResponse__FileUpdateChange = {
12533 readonly diff: string;
12534 readonly kind: V2ThreadForkResponse__PatchChangeKind;
12535 readonly path: string;
12536};
12537export const V2ThreadForkResponse__FileUpdateChange = Schema.Struct({
12538 diff: Schema.String,
12539 kind: V2ThreadForkResponse__PatchChangeKind,
12540 path: Schema.String,
12541});
12542
12543export type V2ThreadForkResponse__UserInput =
12544 | {
12545 readonly text: string;
12546 readonly text_elements?: ReadonlyArray<V2ThreadForkResponse__TextElement>;
12547 readonly type: "text";
12548 }
12549 | { readonly type: "image"; readonly url: string }
12550 | { readonly path: string; readonly type: "localImage" }
12551 | { readonly name: string; readonly path: string; readonly type: "skill" }
12552 | { readonly name: string; readonly path: string; readonly type: "mention" };
12553export const V2ThreadForkResponse__UserInput = Schema.Union(
12554 [
12555 Schema.Struct({
12556 text: Schema.String,
12557 text_elements: Schema.optionalKey(
12558 Schema.Array(V2ThreadForkResponse__TextElement).annotate({
12559 description: "UI-defined spans within `text` used to render or persist special elements.",
12560 default: [],
12561 }),
12562 ),
12563 type: Schema.Literal("text").annotate({ title: "TextUserInputType" }),
12564 }).annotate({ title: "TextUserInput" }),
12565 Schema.Struct({
12566 type: Schema.Literal("image").annotate({ title: "ImageUserInputType" }),
12567 url: Schema.String,
12568 }).annotate({ title: "ImageUserInput" }),
12569 Schema.Struct({
12570 path: Schema.String,
12571 type: Schema.Literal("localImage").annotate({ title: "LocalImageUserInputType" }),
12572 }).annotate({ title: "LocalImageUserInput" }),
12573 Schema.Struct({
12574 name: Schema.String,
12575 path: Schema.String,
12576 type: Schema.Literal("skill").annotate({ title: "SkillUserInputType" }),
12577 }).annotate({ title: "SkillUserInput" }),
12578 Schema.Struct({
12579 name: Schema.String,
12580 path: Schema.String,
12581 type: Schema.Literal("mention").annotate({ title: "MentionUserInputType" }),
12582 }).annotate({ title: "MentionUserInput" }),
12583 ],
12584 { mode: "oneOf" },
12585);
12586
12587export type V2ThreadForkResponse__SubAgentSource =
12588 | "review"
12589 | "compact"
12590 | "memory_consolidation"
12591 | {
12592 readonly thread_spawn: {
12593 readonly agent_nickname?: string | null;
12594 readonly agent_path?: V2ThreadForkResponse__AgentPath | null;
12595 readonly agent_role?: string | null;
12596 readonly depth: number;
12597 readonly parent_thread_id: V2ThreadForkResponse__ThreadId;
12598 };
12599 }
12600 | { readonly other: string };
12601export const V2ThreadForkResponse__SubAgentSource = Schema.Union(
12602 [
12603 Schema.Literals(["review", "compact", "memory_consolidation"]),
12604 Schema.Struct({
12605 thread_spawn: Schema.Struct({
12606 agent_nickname: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
12607 agent_path: Schema.optionalKey(
12608 Schema.Union([V2ThreadForkResponse__AgentPath, Schema.Null]),
12609 ),
12610 agent_role: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
12611 depth: Schema.Number.annotate({ format: "int32" }).check(Schema.isInt()),
12612 parent_thread_id: V2ThreadForkResponse__ThreadId,
12613 }),
12614 }).annotate({ title: "ThreadSpawnSubAgentSource" }),
12615 Schema.Struct({ other: Schema.String }).annotate({ title: "OtherSubAgentSource" }),
12616 ],
12617 { mode: "oneOf" },
12618);
12619
12620export type V2ThreadListResponse__CollabAgentState = {
12621 readonly message?: string | null;
12622 readonly status: V2ThreadListResponse__CollabAgentStatus;
12623};
12624export const V2ThreadListResponse__CollabAgentState = Schema.Struct({
12625 message: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
12626 status: V2ThreadListResponse__CollabAgentStatus,
12627});
12628
12629export type V2ThreadListResponse__MemoryCitation = {
12630 readonly entries: ReadonlyArray<V2ThreadListResponse__MemoryCitationEntry>;
12631 readonly threadIds: ReadonlyArray<string>;
12632};
12633export const V2ThreadListResponse__MemoryCitation = Schema.Struct({
12634 entries: Schema.Array(V2ThreadListResponse__MemoryCitationEntry),
12635 threadIds: Schema.Array(Schema.String),
12636});
12637
12638export type V2ThreadListResponse__CodexErrorInfo =
12639 | "contextWindowExceeded"
12640 | "usageLimitExceeded"
12641 | "serverOverloaded"
12642 | "internalServerError"
12643 | "unauthorized"
12644 | "badRequest"
12645 | "threadRollbackFailed"
12646 | "sandboxError"
12647 | "other"
12648 | { readonly httpConnectionFailed: { readonly httpStatusCode?: number | null } }
12649 | { readonly responseStreamConnectionFailed: { readonly httpStatusCode?: number | null } }
12650 | { readonly responseStreamDisconnected: { readonly httpStatusCode?: number | null } }
12651 | { readonly responseTooManyFailedAttempts: { readonly httpStatusCode?: number | null } }
12652 | {
12653 readonly activeTurnNotSteerable: {
12654 readonly turnKind: V2ThreadListResponse__NonSteerableTurnKind;
12655 };
12656 };
12657export const V2ThreadListResponse__CodexErrorInfo = Schema.Union(
12658 [
12659 Schema.Literals([
12660 "contextWindowExceeded",
12661 "usageLimitExceeded",
12662 "serverOverloaded",
12663 "internalServerError",
12664 "unauthorized",
12665 "badRequest",
12666 "threadRollbackFailed",
12667 "sandboxError",
12668 "other",
12669 ]),
12670 Schema.Struct({
12671 httpConnectionFailed: Schema.Struct({
12672 httpStatusCode: Schema.optionalKey(
12673 Schema.Union([
12674 Schema.Number.annotate({ format: "uint16" })
12675 .check(Schema.isInt())
12676 .check(Schema.isGreaterThanOrEqualTo(0)),
12677 Schema.Null,
12678 ]),
12679 ),
12680 }),
12681 }).annotate({ title: "HttpConnectionFailedCodexErrorInfo" }),
12682 Schema.Struct({
12683 responseStreamConnectionFailed: Schema.Struct({
12684 httpStatusCode: Schema.optionalKey(
12685 Schema.Union([
12686 Schema.Number.annotate({ format: "uint16" })
12687 .check(Schema.isInt())
12688 .check(Schema.isGreaterThanOrEqualTo(0)),
12689 Schema.Null,
12690 ]),
12691 ),
12692 }),
12693 }).annotate({
12694 title: "ResponseStreamConnectionFailedCodexErrorInfo",
12695 description: "Failed to connect to the response SSE stream.",
12696 }),
12697 Schema.Struct({
12698 responseStreamDisconnected: Schema.Struct({
12699 httpStatusCode: Schema.optionalKey(
12700 Schema.Union([
12701 Schema.Number.annotate({ format: "uint16" })
12702 .check(Schema.isInt())
12703 .check(Schema.isGreaterThanOrEqualTo(0)),
12704 Schema.Null,
12705 ]),
12706 ),
12707 }),
12708 }).annotate({
12709 title: "ResponseStreamDisconnectedCodexErrorInfo",
12710 description:
12711 "The response SSE stream disconnected in the middle of a turn before completion.",
12712 }),
12713 Schema.Struct({
12714 responseTooManyFailedAttempts: Schema.Struct({
12715 httpStatusCode: Schema.optionalKey(
12716 Schema.Union([
12717 Schema.Number.annotate({ format: "uint16" })
12718 .check(Schema.isInt())
12719 .check(Schema.isGreaterThanOrEqualTo(0)),
12720 Schema.Null,
12721 ]),
12722 ),
12723 }),
12724 }).annotate({
12725 title: "ResponseTooManyFailedAttemptsCodexErrorInfo",
12726 description: "Reached the retry limit for responses.",
12727 }),
12728 Schema.Struct({
12729 activeTurnNotSteerable: Schema.Struct({
12730 turnKind: V2ThreadListResponse__NonSteerableTurnKind,
12731 }),
12732 }).annotate({
12733 title: "ActiveTurnNotSteerableCodexErrorInfo",
12734 description:
12735 "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`.",
12736 }),
12737 ],
12738 { mode: "oneOf" },
12739).annotate({
12740 description:
12741 "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.",
12742});
12743
12744export type V2ThreadListResponse__FileUpdateChange = {
12745 readonly diff: string;
12746 readonly kind: V2ThreadListResponse__PatchChangeKind;
12747 readonly path: string;
12748};
12749export const V2ThreadListResponse__FileUpdateChange = Schema.Struct({
12750 diff: Schema.String,
12751 kind: V2ThreadListResponse__PatchChangeKind,
12752 path: Schema.String,
12753});
12754
12755export type V2ThreadListResponse__UserInput =
12756 | {
12757 readonly text: string;
12758 readonly text_elements?: ReadonlyArray<V2ThreadListResponse__TextElement>;
12759 readonly type: "text";
12760 }
12761 | { readonly type: "image"; readonly url: string }
12762 | { readonly path: string; readonly type: "localImage" }
12763 | { readonly name: string; readonly path: string; readonly type: "skill" }
12764 | { readonly name: string; readonly path: string; readonly type: "mention" };
12765export const V2ThreadListResponse__UserInput = Schema.Union(
12766 [
12767 Schema.Struct({
12768 text: Schema.String,
12769 text_elements: Schema.optionalKey(
12770 Schema.Array(V2ThreadListResponse__TextElement).annotate({
12771 description: "UI-defined spans within `text` used to render or persist special elements.",
12772 default: [],
12773 }),
12774 ),
12775 type: Schema.Literal("text").annotate({ title: "TextUserInputType" }),
12776 }).annotate({ title: "TextUserInput" }),
12777 Schema.Struct({
12778 type: Schema.Literal("image").annotate({ title: "ImageUserInputType" }),
12779 url: Schema.String,
12780 }).annotate({ title: "ImageUserInput" }),
12781 Schema.Struct({
12782 path: Schema.String,
12783 type: Schema.Literal("localImage").annotate({ title: "LocalImageUserInputType" }),
12784 }).annotate({ title: "LocalImageUserInput" }),
12785 Schema.Struct({
12786 name: Schema.String,
12787 path: Schema.String,
12788 type: Schema.Literal("skill").annotate({ title: "SkillUserInputType" }),
12789 }).annotate({ title: "SkillUserInput" }),
12790 Schema.Struct({
12791 name: Schema.String,
12792 path: Schema.String,
12793 type: Schema.Literal("mention").annotate({ title: "MentionUserInputType" }),
12794 }).annotate({ title: "MentionUserInput" }),
12795 ],
12796 { mode: "oneOf" },
12797);
12798
12799export type V2ThreadListResponse__SubAgentSource =
12800 | "review"
12801 | "compact"
12802 | "memory_consolidation"
12803 | {
12804 readonly thread_spawn: {
12805 readonly agent_nickname?: string | null;
12806 readonly agent_path?: V2ThreadListResponse__AgentPath | null;
12807 readonly agent_role?: string | null;
12808 readonly depth: number;
12809 readonly parent_thread_id: V2ThreadListResponse__ThreadId;
12810 };
12811 }
12812 | { readonly other: string };
12813export const V2ThreadListResponse__SubAgentSource = Schema.Union(
12814 [
12815 Schema.Literals(["review", "compact", "memory_consolidation"]),
12816 Schema.Struct({
12817 thread_spawn: Schema.Struct({
12818 agent_nickname: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
12819 agent_path: Schema.optionalKey(
12820 Schema.Union([V2ThreadListResponse__AgentPath, Schema.Null]),
12821 ),
12822 agent_role: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
12823 depth: Schema.Number.annotate({ format: "int32" }).check(Schema.isInt()),
12824 parent_thread_id: V2ThreadListResponse__ThreadId,
12825 }),
12826 }).annotate({ title: "ThreadSpawnSubAgentSource" }),
12827 Schema.Struct({ other: Schema.String }).annotate({ title: "OtherSubAgentSource" }),
12828 ],
12829 { mode: "oneOf" },
12830);
12831
12832export type V2ThreadMetadataUpdateResponse__CollabAgentState = {
12833 readonly message?: string | null;
12834 readonly status: V2ThreadMetadataUpdateResponse__CollabAgentStatus;
12835};
12836export const V2ThreadMetadataUpdateResponse__CollabAgentState = Schema.Struct({
12837 message: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
12838 status: V2ThreadMetadataUpdateResponse__CollabAgentStatus,
12839});
12840
12841export type V2ThreadMetadataUpdateResponse__MemoryCitation = {
12842 readonly entries: ReadonlyArray<V2ThreadMetadataUpdateResponse__MemoryCitationEntry>;
12843 readonly threadIds: ReadonlyArray<string>;
12844};
12845export const V2ThreadMetadataUpdateResponse__MemoryCitation = Schema.Struct({
12846 entries: Schema.Array(V2ThreadMetadataUpdateResponse__MemoryCitationEntry),
12847 threadIds: Schema.Array(Schema.String),
12848});
12849
12850export type V2ThreadMetadataUpdateResponse__CodexErrorInfo =
12851 | "contextWindowExceeded"
12852 | "usageLimitExceeded"
12853 | "serverOverloaded"
12854 | "internalServerError"
12855 | "unauthorized"
12856 | "badRequest"
12857 | "threadRollbackFailed"
12858 | "sandboxError"
12859 | "other"
12860 | { readonly httpConnectionFailed: { readonly httpStatusCode?: number | null } }
12861 | { readonly responseStreamConnectionFailed: { readonly httpStatusCode?: number | null } }
12862 | { readonly responseStreamDisconnected: { readonly httpStatusCode?: number | null } }
12863 | { readonly responseTooManyFailedAttempts: { readonly httpStatusCode?: number | null } }
12864 | {
12865 readonly activeTurnNotSteerable: {
12866 readonly turnKind: V2ThreadMetadataUpdateResponse__NonSteerableTurnKind;
12867 };
12868 };
12869export const V2ThreadMetadataUpdateResponse__CodexErrorInfo = Schema.Union(
12870 [
12871 Schema.Literals([
12872 "contextWindowExceeded",
12873 "usageLimitExceeded",
12874 "serverOverloaded",
12875 "internalServerError",
12876 "unauthorized",
12877 "badRequest",
12878 "threadRollbackFailed",
12879 "sandboxError",
12880 "other",
12881 ]),
12882 Schema.Struct({
12883 httpConnectionFailed: Schema.Struct({
12884 httpStatusCode: Schema.optionalKey(
12885 Schema.Union([
12886 Schema.Number.annotate({ format: "uint16" })
12887 .check(Schema.isInt())
12888 .check(Schema.isGreaterThanOrEqualTo(0)),
12889 Schema.Null,
12890 ]),
12891 ),
12892 }),
12893 }).annotate({ title: "HttpConnectionFailedCodexErrorInfo" }),
12894 Schema.Struct({
12895 responseStreamConnectionFailed: Schema.Struct({
12896 httpStatusCode: Schema.optionalKey(
12897 Schema.Union([
12898 Schema.Number.annotate({ format: "uint16" })
12899 .check(Schema.isInt())
12900 .check(Schema.isGreaterThanOrEqualTo(0)),
12901 Schema.Null,
12902 ]),
12903 ),
12904 }),
12905 }).annotate({
12906 title: "ResponseStreamConnectionFailedCodexErrorInfo",
12907 description: "Failed to connect to the response SSE stream.",
12908 }),
12909 Schema.Struct({
12910 responseStreamDisconnected: Schema.Struct({
12911 httpStatusCode: Schema.optionalKey(
12912 Schema.Union([
12913 Schema.Number.annotate({ format: "uint16" })
12914 .check(Schema.isInt())
12915 .check(Schema.isGreaterThanOrEqualTo(0)),
12916 Schema.Null,
12917 ]),
12918 ),
12919 }),
12920 }).annotate({
12921 title: "ResponseStreamDisconnectedCodexErrorInfo",
12922 description:
12923 "The response SSE stream disconnected in the middle of a turn before completion.",
12924 }),
12925 Schema.Struct({
12926 responseTooManyFailedAttempts: Schema.Struct({
12927 httpStatusCode: Schema.optionalKey(
12928 Schema.Union([
12929 Schema.Number.annotate({ format: "uint16" })
12930 .check(Schema.isInt())
12931 .check(Schema.isGreaterThanOrEqualTo(0)),
12932 Schema.Null,
12933 ]),
12934 ),
12935 }),
12936 }).annotate({
12937 title: "ResponseTooManyFailedAttemptsCodexErrorInfo",
12938 description: "Reached the retry limit for responses.",
12939 }),
12940 Schema.Struct({
12941 activeTurnNotSteerable: Schema.Struct({
12942 turnKind: V2ThreadMetadataUpdateResponse__NonSteerableTurnKind,
12943 }),
12944 }).annotate({
12945 title: "ActiveTurnNotSteerableCodexErrorInfo",
12946 description:
12947 "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`.",
12948 }),
12949 ],
12950 { mode: "oneOf" },
12951).annotate({
12952 description:
12953 "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.",
12954});
12955
12956export type V2ThreadMetadataUpdateResponse__FileUpdateChange = {
12957 readonly diff: string;
12958 readonly kind: V2ThreadMetadataUpdateResponse__PatchChangeKind;
12959 readonly path: string;
12960};
12961export const V2ThreadMetadataUpdateResponse__FileUpdateChange = Schema.Struct({
12962 diff: Schema.String,
12963 kind: V2ThreadMetadataUpdateResponse__PatchChangeKind,
12964 path: Schema.String,
12965});
12966
12967export type V2ThreadMetadataUpdateResponse__UserInput =
12968 | {
12969 readonly text: string;
12970 readonly text_elements?: ReadonlyArray<V2ThreadMetadataUpdateResponse__TextElement>;
12971 readonly type: "text";
12972 }
12973 | { readonly type: "image"; readonly url: string }
12974 | { readonly path: string; readonly type: "localImage" }
12975 | { readonly name: string; readonly path: string; readonly type: "skill" }
12976 | { readonly name: string; readonly path: string; readonly type: "mention" };
12977export const V2ThreadMetadataUpdateResponse__UserInput = Schema.Union(
12978 [
12979 Schema.Struct({
12980 text: Schema.String,
12981 text_elements: Schema.optionalKey(
12982 Schema.Array(V2ThreadMetadataUpdateResponse__TextElement).annotate({
12983 description: "UI-defined spans within `text` used to render or persist special elements.",
12984 default: [],
12985 }),
12986 ),
12987 type: Schema.Literal("text").annotate({ title: "TextUserInputType" }),
12988 }).annotate({ title: "TextUserInput" }),
12989 Schema.Struct({
12990 type: Schema.Literal("image").annotate({ title: "ImageUserInputType" }),
12991 url: Schema.String,
12992 }).annotate({ title: "ImageUserInput" }),
12993 Schema.Struct({
12994 path: Schema.String,
12995 type: Schema.Literal("localImage").annotate({ title: "LocalImageUserInputType" }),
12996 }).annotate({ title: "LocalImageUserInput" }),
12997 Schema.Struct({
12998 name: Schema.String,
12999 path: Schema.String,
13000 type: Schema.Literal("skill").annotate({ title: "SkillUserInputType" }),
13001 }).annotate({ title: "SkillUserInput" }),
13002 Schema.Struct({
13003 name: Schema.String,
13004 path: Schema.String,
13005 type: Schema.Literal("mention").annotate({ title: "MentionUserInputType" }),
13006 }).annotate({ title: "MentionUserInput" }),
13007 ],
13008 { mode: "oneOf" },
13009);
13010
13011export type V2ThreadMetadataUpdateResponse__SubAgentSource =
13012 | "review"
13013 | "compact"
13014 | "memory_consolidation"
13015 | {
13016 readonly thread_spawn: {
13017 readonly agent_nickname?: string | null;
13018 readonly agent_path?: V2ThreadMetadataUpdateResponse__AgentPath | null;
13019 readonly agent_role?: string | null;
13020 readonly depth: number;
13021 readonly parent_thread_id: V2ThreadMetadataUpdateResponse__ThreadId;
13022 };
13023 }
13024 | { readonly other: string };
13025export const V2ThreadMetadataUpdateResponse__SubAgentSource = Schema.Union(
13026 [
13027 Schema.Literals(["review", "compact", "memory_consolidation"]),
13028 Schema.Struct({
13029 thread_spawn: Schema.Struct({
13030 agent_nickname: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
13031 agent_path: Schema.optionalKey(
13032 Schema.Union([V2ThreadMetadataUpdateResponse__AgentPath, Schema.Null]),
13033 ),
13034 agent_role: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
13035 depth: Schema.Number.annotate({ format: "int32" }).check(Schema.isInt()),
13036 parent_thread_id: V2ThreadMetadataUpdateResponse__ThreadId,
13037 }),
13038 }).annotate({ title: "ThreadSpawnSubAgentSource" }),
13039 Schema.Struct({ other: Schema.String }).annotate({ title: "OtherSubAgentSource" }),
13040 ],
13041 { mode: "oneOf" },
13042);
13043
13044export type V2ThreadReadResponse__CollabAgentState = {
13045 readonly message?: string | null;
13046 readonly status: V2ThreadReadResponse__CollabAgentStatus;
13047};
13048export const V2ThreadReadResponse__CollabAgentState = Schema.Struct({
13049 message: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
13050 status: V2ThreadReadResponse__CollabAgentStatus,
13051});
13052
13053export type V2ThreadReadResponse__MemoryCitation = {
13054 readonly entries: ReadonlyArray<V2ThreadReadResponse__MemoryCitationEntry>;
13055 readonly threadIds: ReadonlyArray<string>;
13056};
13057export const V2ThreadReadResponse__MemoryCitation = Schema.Struct({
13058 entries: Schema.Array(V2ThreadReadResponse__MemoryCitationEntry),
13059 threadIds: Schema.Array(Schema.String),
13060});
13061
13062export type V2ThreadReadResponse__CodexErrorInfo =
13063 | "contextWindowExceeded"
13064 | "usageLimitExceeded"
13065 | "serverOverloaded"
13066 | "internalServerError"
13067 | "unauthorized"
13068 | "badRequest"
13069 | "threadRollbackFailed"
13070 | "sandboxError"
13071 | "other"
13072 | { readonly httpConnectionFailed: { readonly httpStatusCode?: number | null } }
13073 | { readonly responseStreamConnectionFailed: { readonly httpStatusCode?: number | null } }
13074 | { readonly responseStreamDisconnected: { readonly httpStatusCode?: number | null } }
13075 | { readonly responseTooManyFailedAttempts: { readonly httpStatusCode?: number | null } }
13076 | {
13077 readonly activeTurnNotSteerable: {
13078 readonly turnKind: V2ThreadReadResponse__NonSteerableTurnKind;
13079 };
13080 };
13081export const V2ThreadReadResponse__CodexErrorInfo = Schema.Union(
13082 [
13083 Schema.Literals([
13084 "contextWindowExceeded",
13085 "usageLimitExceeded",
13086 "serverOverloaded",
13087 "internalServerError",
13088 "unauthorized",
13089 "badRequest",
13090 "threadRollbackFailed",
13091 "sandboxError",
13092 "other",
13093 ]),
13094 Schema.Struct({
13095 httpConnectionFailed: Schema.Struct({
13096 httpStatusCode: Schema.optionalKey(
13097 Schema.Union([
13098 Schema.Number.annotate({ format: "uint16" })
13099 .check(Schema.isInt())
13100 .check(Schema.isGreaterThanOrEqualTo(0)),
13101 Schema.Null,
13102 ]),
13103 ),
13104 }),
13105 }).annotate({ title: "HttpConnectionFailedCodexErrorInfo" }),
13106 Schema.Struct({
13107 responseStreamConnectionFailed: Schema.Struct({
13108 httpStatusCode: Schema.optionalKey(
13109 Schema.Union([
13110 Schema.Number.annotate({ format: "uint16" })
13111 .check(Schema.isInt())
13112 .check(Schema.isGreaterThanOrEqualTo(0)),
13113 Schema.Null,
13114 ]),
13115 ),
13116 }),
13117 }).annotate({
13118 title: "ResponseStreamConnectionFailedCodexErrorInfo",
13119 description: "Failed to connect to the response SSE stream.",
13120 }),
13121 Schema.Struct({
13122 responseStreamDisconnected: Schema.Struct({
13123 httpStatusCode: Schema.optionalKey(
13124 Schema.Union([
13125 Schema.Number.annotate({ format: "uint16" })
13126 .check(Schema.isInt())
13127 .check(Schema.isGreaterThanOrEqualTo(0)),
13128 Schema.Null,
13129 ]),
13130 ),
13131 }),
13132 }).annotate({
13133 title: "ResponseStreamDisconnectedCodexErrorInfo",
13134 description:
13135 "The response SSE stream disconnected in the middle of a turn before completion.",
13136 }),
13137 Schema.Struct({
13138 responseTooManyFailedAttempts: Schema.Struct({
13139 httpStatusCode: Schema.optionalKey(
13140 Schema.Union([
13141 Schema.Number.annotate({ format: "uint16" })
13142 .check(Schema.isInt())
13143 .check(Schema.isGreaterThanOrEqualTo(0)),
13144 Schema.Null,
13145 ]),
13146 ),
13147 }),
13148 }).annotate({
13149 title: "ResponseTooManyFailedAttemptsCodexErrorInfo",
13150 description: "Reached the retry limit for responses.",
13151 }),
13152 Schema.Struct({
13153 activeTurnNotSteerable: Schema.Struct({
13154 turnKind: V2ThreadReadResponse__NonSteerableTurnKind,
13155 }),
13156 }).annotate({
13157 title: "ActiveTurnNotSteerableCodexErrorInfo",
13158 description:
13159 "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`.",
13160 }),
13161 ],
13162 { mode: "oneOf" },
13163).annotate({
13164 description:
13165 "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.",
13166});
13167
13168export type V2ThreadReadResponse__FileUpdateChange = {
13169 readonly diff: string;
13170 readonly kind: V2ThreadReadResponse__PatchChangeKind;
13171 readonly path: string;
13172};
13173export const V2ThreadReadResponse__FileUpdateChange = Schema.Struct({
13174 diff: Schema.String,
13175 kind: V2ThreadReadResponse__PatchChangeKind,
13176 path: Schema.String,
13177});
13178
13179export type V2ThreadReadResponse__UserInput =
13180 | {
13181 readonly text: string;
13182 readonly text_elements?: ReadonlyArray<V2ThreadReadResponse__TextElement>;
13183 readonly type: "text";
13184 }
13185 | { readonly type: "image"; readonly url: string }
13186 | { readonly path: string; readonly type: "localImage" }
13187 | { readonly name: string; readonly path: string; readonly type: "skill" }
13188 | { readonly name: string; readonly path: string; readonly type: "mention" };
13189export const V2ThreadReadResponse__UserInput = Schema.Union(
13190 [
13191 Schema.Struct({
13192 text: Schema.String,
13193 text_elements: Schema.optionalKey(
13194 Schema.Array(V2ThreadReadResponse__TextElement).annotate({
13195 description: "UI-defined spans within `text` used to render or persist special elements.",
13196 default: [],
13197 }),
13198 ),
13199 type: Schema.Literal("text").annotate({ title: "TextUserInputType" }),
13200 }).annotate({ title: "TextUserInput" }),
13201 Schema.Struct({
13202 type: Schema.Literal("image").annotate({ title: "ImageUserInputType" }),
13203 url: Schema.String,
13204 }).annotate({ title: "ImageUserInput" }),
13205 Schema.Struct({
13206 path: Schema.String,
13207 type: Schema.Literal("localImage").annotate({ title: "LocalImageUserInputType" }),
13208 }).annotate({ title: "LocalImageUserInput" }),
13209 Schema.Struct({
13210 name: Schema.String,
13211 path: Schema.String,
13212 type: Schema.Literal("skill").annotate({ title: "SkillUserInputType" }),
13213 }).annotate({ title: "SkillUserInput" }),
13214 Schema.Struct({
13215 name: Schema.String,
13216 path: Schema.String,
13217 type: Schema.Literal("mention").annotate({ title: "MentionUserInputType" }),
13218 }).annotate({ title: "MentionUserInput" }),
13219 ],
13220 { mode: "oneOf" },
13221);
13222
13223export type V2ThreadReadResponse__SubAgentSource =
13224 | "review"
13225 | "compact"
13226 | "memory_consolidation"
13227 | {
13228 readonly thread_spawn: {
13229 readonly agent_nickname?: string | null;
13230 readonly agent_path?: V2ThreadReadResponse__AgentPath | null;
13231 readonly agent_role?: string | null;
13232 readonly depth: number;
13233 readonly parent_thread_id: V2ThreadReadResponse__ThreadId;
13234 };
13235 }
13236 | { readonly other: string };
13237export const V2ThreadReadResponse__SubAgentSource = Schema.Union(
13238 [
13239 Schema.Literals(["review", "compact", "memory_consolidation"]),
13240 Schema.Struct({
13241 thread_spawn: Schema.Struct({
13242 agent_nickname: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
13243 agent_path: Schema.optionalKey(
13244 Schema.Union([V2ThreadReadResponse__AgentPath, Schema.Null]),
13245 ),
13246 agent_role: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
13247 depth: Schema.Number.annotate({ format: "int32" }).check(Schema.isInt()),
13248 parent_thread_id: V2ThreadReadResponse__ThreadId,
13249 }),
13250 }).annotate({ title: "ThreadSpawnSubAgentSource" }),
13251 Schema.Struct({ other: Schema.String }).annotate({ title: "OtherSubAgentSource" }),
13252 ],
13253 { mode: "oneOf" },
13254);
13255
13256export type V2ThreadResumeParams__FunctionCallOutputContentItem =
13257 | { readonly text: string; readonly type: "input_text" }
13258 | {
13259 readonly detail?: V2ThreadResumeParams__ImageDetail | null;
13260 readonly image_url: string;
13261 readonly type: "input_image";
13262 };
13263export const V2ThreadResumeParams__FunctionCallOutputContentItem = Schema.Union(
13264 [
13265 Schema.Struct({
13266 text: Schema.String,
13267 type: Schema.Literal("input_text").annotate({
13268 title: "InputTextFunctionCallOutputContentItemType",
13269 }),
13270 }).annotate({ title: "InputTextFunctionCallOutputContentItem" }),
13271 Schema.Struct({
13272 detail: Schema.optionalKey(Schema.Union([V2ThreadResumeParams__ImageDetail, Schema.Null])),
13273 image_url: Schema.String,
13274 type: Schema.Literal("input_image").annotate({
13275 title: "InputImageFunctionCallOutputContentItemType",
13276 }),
13277 }).annotate({ title: "InputImageFunctionCallOutputContentItem" }),
13278 ],
13279 { mode: "oneOf" },
13280).annotate({
13281 description:
13282 "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.",
13283});
13284
13285export type V2ThreadResumeResponse__SandboxPolicy =
13286 | { readonly type: "dangerFullAccess" }
13287 | {
13288 readonly access?:
13289 | {
13290 readonly includePlatformDefaults?: boolean;
13291 readonly readableRoots?: ReadonlyArray<V2ThreadResumeResponse__AbsolutePathBuf>;
13292 readonly type: "restricted";
13293 }
13294 | { readonly type: "fullAccess" };
13295 readonly networkAccess?: boolean;
13296 readonly type: "readOnly";
13297 }
13298 | { readonly networkAccess?: "restricted" | "enabled"; readonly type: "externalSandbox" }
13299 | {
13300 readonly excludeSlashTmp?: boolean;
13301 readonly excludeTmpdirEnvVar?: boolean;
13302 readonly networkAccess?: boolean;
13303 readonly readOnlyAccess?:
13304 | {
13305 readonly includePlatformDefaults?: boolean;
13306 readonly readableRoots?: ReadonlyArray<V2ThreadResumeResponse__AbsolutePathBuf>;
13307 readonly type: "restricted";
13308 }
13309 | { readonly type: "fullAccess" };
13310 readonly type: "workspaceWrite";
13311 readonly writableRoots?: ReadonlyArray<V2ThreadResumeResponse__AbsolutePathBuf>;
13312 };
13313export const V2ThreadResumeResponse__SandboxPolicy = Schema.Union(
13314 [
13315 Schema.Struct({
13316 type: Schema.Literal("dangerFullAccess").annotate({
13317 title: "DangerFullAccessSandboxPolicyType",
13318 }),
13319 }).annotate({ title: "DangerFullAccessSandboxPolicy" }),
13320 Schema.Struct({
13321 access: Schema.optionalKey(
13322 Schema.Union(
13323 [
13324 Schema.Struct({
13325 includePlatformDefaults: Schema.optionalKey(
13326 Schema.Boolean.annotate({ default: true }),
13327 ),
13328 readableRoots: Schema.optionalKey(
13329 Schema.Array(V2ThreadResumeResponse__AbsolutePathBuf).annotate({ default: [] }),
13330 ),
13331 type: Schema.Literal("restricted").annotate({
13332 title: "RestrictedReadOnlyAccessType",
13333 }),
13334 }).annotate({ title: "RestrictedReadOnlyAccess" }),
13335 Schema.Struct({
13336 type: Schema.Literal("fullAccess").annotate({
13337 title: "FullAccessReadOnlyAccessType",
13338 }),
13339 }).annotate({ title: "FullAccessReadOnlyAccess" }),
13340 ],
13341 { mode: "oneOf" },
13342 ).annotate({ default: { type: "fullAccess" } }),
13343 ),
13344 networkAccess: Schema.optionalKey(Schema.Boolean.annotate({ default: false })),
13345 type: Schema.Literal("readOnly").annotate({ title: "ReadOnlySandboxPolicyType" }),
13346 }).annotate({ title: "ReadOnlySandboxPolicy" }),
13347 Schema.Struct({
13348 networkAccess: Schema.optionalKey(
13349 Schema.Literals(["restricted", "enabled"]).annotate({ default: "restricted" }),
13350 ),
13351 type: Schema.Literal("externalSandbox").annotate({
13352 title: "ExternalSandboxSandboxPolicyType",
13353 }),
13354 }).annotate({ title: "ExternalSandboxSandboxPolicy" }),
13355 Schema.Struct({
13356 excludeSlashTmp: Schema.optionalKey(Schema.Boolean.annotate({ default: false })),
13357 excludeTmpdirEnvVar: Schema.optionalKey(Schema.Boolean.annotate({ default: false })),
13358 networkAccess: Schema.optionalKey(Schema.Boolean.annotate({ default: false })),
13359 readOnlyAccess: Schema.optionalKey(
13360 Schema.Union(
13361 [
13362 Schema.Struct({
13363 includePlatformDefaults: Schema.optionalKey(
13364 Schema.Boolean.annotate({ default: true }),
13365 ),
13366 readableRoots: Schema.optionalKey(
13367 Schema.Array(V2ThreadResumeResponse__AbsolutePathBuf).annotate({ default: [] }),
13368 ),
13369 type: Schema.Literal("restricted").annotate({
13370 title: "RestrictedReadOnlyAccessType",
13371 }),
13372 }).annotate({ title: "RestrictedReadOnlyAccess" }),
13373 Schema.Struct({
13374 type: Schema.Literal("fullAccess").annotate({
13375 title: "FullAccessReadOnlyAccessType",
13376 }),
13377 }).annotate({ title: "FullAccessReadOnlyAccess" }),
13378 ],
13379 { mode: "oneOf" },
13380 ).annotate({ default: { type: "fullAccess" } }),
13381 ),
13382 type: Schema.Literal("workspaceWrite").annotate({ title: "WorkspaceWriteSandboxPolicyType" }),
13383 writableRoots: Schema.optionalKey(
13384 Schema.Array(V2ThreadResumeResponse__AbsolutePathBuf).annotate({ default: [] }),
13385 ),
13386 }).annotate({ title: "WorkspaceWriteSandboxPolicy" }),
13387 ],
13388 { mode: "oneOf" },
13389);
13390
13391export type V2ThreadResumeResponse__CollabAgentState = {
13392 readonly message?: string | null;
13393 readonly status: V2ThreadResumeResponse__CollabAgentStatus;
13394};
13395export const V2ThreadResumeResponse__CollabAgentState = Schema.Struct({
13396 message: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
13397 status: V2ThreadResumeResponse__CollabAgentStatus,
13398});
13399
13400export type V2ThreadResumeResponse__MemoryCitation = {
13401 readonly entries: ReadonlyArray<V2ThreadResumeResponse__MemoryCitationEntry>;
13402 readonly threadIds: ReadonlyArray<string>;
13403};
13404export const V2ThreadResumeResponse__MemoryCitation = Schema.Struct({
13405 entries: Schema.Array(V2ThreadResumeResponse__MemoryCitationEntry),
13406 threadIds: Schema.Array(Schema.String),
13407});
13408
13409export type V2ThreadResumeResponse__CodexErrorInfo =
13410 | "contextWindowExceeded"
13411 | "usageLimitExceeded"
13412 | "serverOverloaded"
13413 | "internalServerError"
13414 | "unauthorized"
13415 | "badRequest"
13416 | "threadRollbackFailed"
13417 | "sandboxError"
13418 | "other"
13419 | { readonly httpConnectionFailed: { readonly httpStatusCode?: number | null } }
13420 | { readonly responseStreamConnectionFailed: { readonly httpStatusCode?: number | null } }
13421 | { readonly responseStreamDisconnected: { readonly httpStatusCode?: number | null } }
13422 | { readonly responseTooManyFailedAttempts: { readonly httpStatusCode?: number | null } }
13423 | {
13424 readonly activeTurnNotSteerable: {
13425 readonly turnKind: V2ThreadResumeResponse__NonSteerableTurnKind;
13426 };
13427 };
13428export const V2ThreadResumeResponse__CodexErrorInfo = Schema.Union(
13429 [
13430 Schema.Literals([
13431 "contextWindowExceeded",
13432 "usageLimitExceeded",
13433 "serverOverloaded",
13434 "internalServerError",
13435 "unauthorized",
13436 "badRequest",
13437 "threadRollbackFailed",
13438 "sandboxError",
13439 "other",
13440 ]),
13441 Schema.Struct({
13442 httpConnectionFailed: Schema.Struct({
13443 httpStatusCode: Schema.optionalKey(
13444 Schema.Union([
13445 Schema.Number.annotate({ format: "uint16" })
13446 .check(Schema.isInt())
13447 .check(Schema.isGreaterThanOrEqualTo(0)),
13448 Schema.Null,
13449 ]),
13450 ),
13451 }),
13452 }).annotate({ title: "HttpConnectionFailedCodexErrorInfo" }),
13453 Schema.Struct({
13454 responseStreamConnectionFailed: Schema.Struct({
13455 httpStatusCode: Schema.optionalKey(
13456 Schema.Union([
13457 Schema.Number.annotate({ format: "uint16" })
13458 .check(Schema.isInt())
13459 .check(Schema.isGreaterThanOrEqualTo(0)),
13460 Schema.Null,
13461 ]),
13462 ),
13463 }),
13464 }).annotate({
13465 title: "ResponseStreamConnectionFailedCodexErrorInfo",
13466 description: "Failed to connect to the response SSE stream.",
13467 }),
13468 Schema.Struct({
13469 responseStreamDisconnected: Schema.Struct({
13470 httpStatusCode: Schema.optionalKey(
13471 Schema.Union([
13472 Schema.Number.annotate({ format: "uint16" })
13473 .check(Schema.isInt())
13474 .check(Schema.isGreaterThanOrEqualTo(0)),
13475 Schema.Null,
13476 ]),
13477 ),
13478 }),
13479 }).annotate({
13480 title: "ResponseStreamDisconnectedCodexErrorInfo",
13481 description:
13482 "The response SSE stream disconnected in the middle of a turn before completion.",
13483 }),
13484 Schema.Struct({
13485 responseTooManyFailedAttempts: Schema.Struct({
13486 httpStatusCode: Schema.optionalKey(
13487 Schema.Union([
13488 Schema.Number.annotate({ format: "uint16" })
13489 .check(Schema.isInt())
13490 .check(Schema.isGreaterThanOrEqualTo(0)),
13491 Schema.Null,
13492 ]),
13493 ),
13494 }),
13495 }).annotate({
13496 title: "ResponseTooManyFailedAttemptsCodexErrorInfo",
13497 description: "Reached the retry limit for responses.",
13498 }),
13499 Schema.Struct({
13500 activeTurnNotSteerable: Schema.Struct({
13501 turnKind: V2ThreadResumeResponse__NonSteerableTurnKind,
13502 }),
13503 }).annotate({
13504 title: "ActiveTurnNotSteerableCodexErrorInfo",
13505 description:
13506 "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`.",
13507 }),
13508 ],
13509 { mode: "oneOf" },
13510).annotate({
13511 description:
13512 "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.",
13513});
13514
13515export type V2ThreadResumeResponse__FileUpdateChange = {
13516 readonly diff: string;
13517 readonly kind: V2ThreadResumeResponse__PatchChangeKind;
13518 readonly path: string;
13519};
13520export const V2ThreadResumeResponse__FileUpdateChange = Schema.Struct({
13521 diff: Schema.String,
13522 kind: V2ThreadResumeResponse__PatchChangeKind,
13523 path: Schema.String,
13524});
13525
13526export type V2ThreadResumeResponse__UserInput =
13527 | {
13528 readonly text: string;
13529 readonly text_elements?: ReadonlyArray<V2ThreadResumeResponse__TextElement>;
13530 readonly type: "text";
13531 }
13532 | { readonly type: "image"; readonly url: string }
13533 | { readonly path: string; readonly type: "localImage" }
13534 | { readonly name: string; readonly path: string; readonly type: "skill" }
13535 | { readonly name: string; readonly path: string; readonly type: "mention" };
13536export const V2ThreadResumeResponse__UserInput = Schema.Union(
13537 [
13538 Schema.Struct({
13539 text: Schema.String,
13540 text_elements: Schema.optionalKey(
13541 Schema.Array(V2ThreadResumeResponse__TextElement).annotate({
13542 description: "UI-defined spans within `text` used to render or persist special elements.",
13543 default: [],
13544 }),
13545 ),
13546 type: Schema.Literal("text").annotate({ title: "TextUserInputType" }),
13547 }).annotate({ title: "TextUserInput" }),
13548 Schema.Struct({
13549 type: Schema.Literal("image").annotate({ title: "ImageUserInputType" }),
13550 url: Schema.String,
13551 }).annotate({ title: "ImageUserInput" }),
13552 Schema.Struct({
13553 path: Schema.String,
13554 type: Schema.Literal("localImage").annotate({ title: "LocalImageUserInputType" }),
13555 }).annotate({ title: "LocalImageUserInput" }),
13556 Schema.Struct({
13557 name: Schema.String,
13558 path: Schema.String,
13559 type: Schema.Literal("skill").annotate({ title: "SkillUserInputType" }),
13560 }).annotate({ title: "SkillUserInput" }),
13561 Schema.Struct({
13562 name: Schema.String,
13563 path: Schema.String,
13564 type: Schema.Literal("mention").annotate({ title: "MentionUserInputType" }),
13565 }).annotate({ title: "MentionUserInput" }),
13566 ],
13567 { mode: "oneOf" },
13568);
13569
13570export type V2ThreadResumeResponse__SubAgentSource =
13571 | "review"
13572 | "compact"
13573 | "memory_consolidation"
13574 | {
13575 readonly thread_spawn: {
13576 readonly agent_nickname?: string | null;
13577 readonly agent_path?: V2ThreadResumeResponse__AgentPath | null;
13578 readonly agent_role?: string | null;
13579 readonly depth: number;
13580 readonly parent_thread_id: V2ThreadResumeResponse__ThreadId;
13581 };
13582 }
13583 | { readonly other: string };
13584export const V2ThreadResumeResponse__SubAgentSource = Schema.Union(
13585 [
13586 Schema.Literals(["review", "compact", "memory_consolidation"]),
13587 Schema.Struct({
13588 thread_spawn: Schema.Struct({
13589 agent_nickname: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
13590 agent_path: Schema.optionalKey(
13591 Schema.Union([V2ThreadResumeResponse__AgentPath, Schema.Null]),
13592 ),
13593 agent_role: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
13594 depth: Schema.Number.annotate({ format: "int32" }).check(Schema.isInt()),
13595 parent_thread_id: V2ThreadResumeResponse__ThreadId,
13596 }),
13597 }).annotate({ title: "ThreadSpawnSubAgentSource" }),
13598 Schema.Struct({ other: Schema.String }).annotate({ title: "OtherSubAgentSource" }),
13599 ],
13600 { mode: "oneOf" },
13601);
13602
13603export type V2ThreadRollbackResponse__CollabAgentState = {
13604 readonly message?: string | null;
13605 readonly status: V2ThreadRollbackResponse__CollabAgentStatus;
13606};
13607export const V2ThreadRollbackResponse__CollabAgentState = Schema.Struct({
13608 message: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
13609 status: V2ThreadRollbackResponse__CollabAgentStatus,
13610});
13611
13612export type V2ThreadRollbackResponse__MemoryCitation = {
13613 readonly entries: ReadonlyArray<V2ThreadRollbackResponse__MemoryCitationEntry>;
13614 readonly threadIds: ReadonlyArray<string>;
13615};
13616export const V2ThreadRollbackResponse__MemoryCitation = Schema.Struct({
13617 entries: Schema.Array(V2ThreadRollbackResponse__MemoryCitationEntry),
13618 threadIds: Schema.Array(Schema.String),
13619});
13620
13621export type V2ThreadRollbackResponse__CodexErrorInfo =
13622 | "contextWindowExceeded"
13623 | "usageLimitExceeded"
13624 | "serverOverloaded"
13625 | "internalServerError"
13626 | "unauthorized"
13627 | "badRequest"
13628 | "threadRollbackFailed"
13629 | "sandboxError"
13630 | "other"
13631 | { readonly httpConnectionFailed: { readonly httpStatusCode?: number | null } }
13632 | { readonly responseStreamConnectionFailed: { readonly httpStatusCode?: number | null } }
13633 | { readonly responseStreamDisconnected: { readonly httpStatusCode?: number | null } }
13634 | { readonly responseTooManyFailedAttempts: { readonly httpStatusCode?: number | null } }
13635 | {
13636 readonly activeTurnNotSteerable: {
13637 readonly turnKind: V2ThreadRollbackResponse__NonSteerableTurnKind;
13638 };
13639 };
13640export const V2ThreadRollbackResponse__CodexErrorInfo = Schema.Union(
13641 [
13642 Schema.Literals([
13643 "contextWindowExceeded",
13644 "usageLimitExceeded",
13645 "serverOverloaded",
13646 "internalServerError",
13647 "unauthorized",
13648 "badRequest",
13649 "threadRollbackFailed",
13650 "sandboxError",
13651 "other",
13652 ]),
13653 Schema.Struct({
13654 httpConnectionFailed: Schema.Struct({
13655 httpStatusCode: Schema.optionalKey(
13656 Schema.Union([
13657 Schema.Number.annotate({ format: "uint16" })
13658 .check(Schema.isInt())
13659 .check(Schema.isGreaterThanOrEqualTo(0)),
13660 Schema.Null,
13661 ]),
13662 ),
13663 }),
13664 }).annotate({ title: "HttpConnectionFailedCodexErrorInfo" }),
13665 Schema.Struct({
13666 responseStreamConnectionFailed: Schema.Struct({
13667 httpStatusCode: Schema.optionalKey(
13668 Schema.Union([
13669 Schema.Number.annotate({ format: "uint16" })
13670 .check(Schema.isInt())
13671 .check(Schema.isGreaterThanOrEqualTo(0)),
13672 Schema.Null,
13673 ]),
13674 ),
13675 }),
13676 }).annotate({
13677 title: "ResponseStreamConnectionFailedCodexErrorInfo",
13678 description: "Failed to connect to the response SSE stream.",
13679 }),
13680 Schema.Struct({
13681 responseStreamDisconnected: Schema.Struct({
13682 httpStatusCode: Schema.optionalKey(
13683 Schema.Union([
13684 Schema.Number.annotate({ format: "uint16" })
13685 .check(Schema.isInt())
13686 .check(Schema.isGreaterThanOrEqualTo(0)),
13687 Schema.Null,
13688 ]),
13689 ),
13690 }),
13691 }).annotate({
13692 title: "ResponseStreamDisconnectedCodexErrorInfo",
13693 description:
13694 "The response SSE stream disconnected in the middle of a turn before completion.",
13695 }),
13696 Schema.Struct({
13697 responseTooManyFailedAttempts: Schema.Struct({
13698 httpStatusCode: Schema.optionalKey(
13699 Schema.Union([
13700 Schema.Number.annotate({ format: "uint16" })
13701 .check(Schema.isInt())
13702 .check(Schema.isGreaterThanOrEqualTo(0)),
13703 Schema.Null,
13704 ]),
13705 ),
13706 }),
13707 }).annotate({
13708 title: "ResponseTooManyFailedAttemptsCodexErrorInfo",
13709 description: "Reached the retry limit for responses.",
13710 }),
13711 Schema.Struct({
13712 activeTurnNotSteerable: Schema.Struct({
13713 turnKind: V2ThreadRollbackResponse__NonSteerableTurnKind,
13714 }),
13715 }).annotate({
13716 title: "ActiveTurnNotSteerableCodexErrorInfo",
13717 description:
13718 "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`.",
13719 }),
13720 ],
13721 { mode: "oneOf" },
13722).annotate({
13723 description:
13724 "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.",
13725});
13726
13727export type V2ThreadRollbackResponse__FileUpdateChange = {
13728 readonly diff: string;
13729 readonly kind: V2ThreadRollbackResponse__PatchChangeKind;
13730 readonly path: string;
13731};
13732export const V2ThreadRollbackResponse__FileUpdateChange = Schema.Struct({
13733 diff: Schema.String,
13734 kind: V2ThreadRollbackResponse__PatchChangeKind,
13735 path: Schema.String,
13736});
13737
13738export type V2ThreadRollbackResponse__UserInput =
13739 | {
13740 readonly text: string;
13741 readonly text_elements?: ReadonlyArray<V2ThreadRollbackResponse__TextElement>;
13742 readonly type: "text";
13743 }
13744 | { readonly type: "image"; readonly url: string }
13745 | { readonly path: string; readonly type: "localImage" }
13746 | { readonly name: string; readonly path: string; readonly type: "skill" }
13747 | { readonly name: string; readonly path: string; readonly type: "mention" };
13748export const V2ThreadRollbackResponse__UserInput = Schema.Union(
13749 [
13750 Schema.Struct({
13751 text: Schema.String,
13752 text_elements: Schema.optionalKey(
13753 Schema.Array(V2ThreadRollbackResponse__TextElement).annotate({
13754 description: "UI-defined spans within `text` used to render or persist special elements.",
13755 default: [],
13756 }),
13757 ),
13758 type: Schema.Literal("text").annotate({ title: "TextUserInputType" }),
13759 }).annotate({ title: "TextUserInput" }),
13760 Schema.Struct({
13761 type: Schema.Literal("image").annotate({ title: "ImageUserInputType" }),
13762 url: Schema.String,
13763 }).annotate({ title: "ImageUserInput" }),
13764 Schema.Struct({
13765 path: Schema.String,
13766 type: Schema.Literal("localImage").annotate({ title: "LocalImageUserInputType" }),
13767 }).annotate({ title: "LocalImageUserInput" }),
13768 Schema.Struct({
13769 name: Schema.String,
13770 path: Schema.String,
13771 type: Schema.Literal("skill").annotate({ title: "SkillUserInputType" }),
13772 }).annotate({ title: "SkillUserInput" }),
13773 Schema.Struct({
13774 name: Schema.String,
13775 path: Schema.String,
13776 type: Schema.Literal("mention").annotate({ title: "MentionUserInputType" }),
13777 }).annotate({ title: "MentionUserInput" }),
13778 ],
13779 { mode: "oneOf" },
13780);
13781
13782export type V2ThreadRollbackResponse__SubAgentSource =
13783 | "review"
13784 | "compact"
13785 | "memory_consolidation"
13786 | {
13787 readonly thread_spawn: {
13788 readonly agent_nickname?: string | null;
13789 readonly agent_path?: V2ThreadRollbackResponse__AgentPath | null;
13790 readonly agent_role?: string | null;
13791 readonly depth: number;
13792 readonly parent_thread_id: V2ThreadRollbackResponse__ThreadId;
13793 };
13794 }
13795 | { readonly other: string };
13796export const V2ThreadRollbackResponse__SubAgentSource = Schema.Union(
13797 [
13798 Schema.Literals(["review", "compact", "memory_consolidation"]),
13799 Schema.Struct({
13800 thread_spawn: Schema.Struct({
13801 agent_nickname: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
13802 agent_path: Schema.optionalKey(
13803 Schema.Union([V2ThreadRollbackResponse__AgentPath, Schema.Null]),
13804 ),
13805 agent_role: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
13806 depth: Schema.Number.annotate({ format: "int32" }).check(Schema.isInt()),
13807 parent_thread_id: V2ThreadRollbackResponse__ThreadId,
13808 }),
13809 }).annotate({ title: "ThreadSpawnSubAgentSource" }),
13810 Schema.Struct({ other: Schema.String }).annotate({ title: "OtherSubAgentSource" }),
13811 ],
13812 { mode: "oneOf" },
13813);
13814
13815export type V2ThreadStartedNotification__CollabAgentState = {
13816 readonly message?: string | null;
13817 readonly status: V2ThreadStartedNotification__CollabAgentStatus;
13818};
13819export const V2ThreadStartedNotification__CollabAgentState = Schema.Struct({
13820 message: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
13821 status: V2ThreadStartedNotification__CollabAgentStatus,
13822});
13823
13824export type V2ThreadStartedNotification__MemoryCitation = {
13825 readonly entries: ReadonlyArray<V2ThreadStartedNotification__MemoryCitationEntry>;
13826 readonly threadIds: ReadonlyArray<string>;
13827};
13828export const V2ThreadStartedNotification__MemoryCitation = Schema.Struct({
13829 entries: Schema.Array(V2ThreadStartedNotification__MemoryCitationEntry),
13830 threadIds: Schema.Array(Schema.String),
13831});
13832
13833export type V2ThreadStartedNotification__CodexErrorInfo =
13834 | "contextWindowExceeded"
13835 | "usageLimitExceeded"
13836 | "serverOverloaded"
13837 | "internalServerError"
13838 | "unauthorized"
13839 | "badRequest"
13840 | "threadRollbackFailed"
13841 | "sandboxError"
13842 | "other"
13843 | { readonly httpConnectionFailed: { readonly httpStatusCode?: number | null } }
13844 | { readonly responseStreamConnectionFailed: { readonly httpStatusCode?: number | null } }
13845 | { readonly responseStreamDisconnected: { readonly httpStatusCode?: number | null } }
13846 | { readonly responseTooManyFailedAttempts: { readonly httpStatusCode?: number | null } }
13847 | {
13848 readonly activeTurnNotSteerable: {
13849 readonly turnKind: V2ThreadStartedNotification__NonSteerableTurnKind;
13850 };
13851 };
13852export const V2ThreadStartedNotification__CodexErrorInfo = Schema.Union(
13853 [
13854 Schema.Literals([
13855 "contextWindowExceeded",
13856 "usageLimitExceeded",
13857 "serverOverloaded",
13858 "internalServerError",
13859 "unauthorized",
13860 "badRequest",
13861 "threadRollbackFailed",
13862 "sandboxError",
13863 "other",
13864 ]),
13865 Schema.Struct({
13866 httpConnectionFailed: Schema.Struct({
13867 httpStatusCode: Schema.optionalKey(
13868 Schema.Union([
13869 Schema.Number.annotate({ format: "uint16" })
13870 .check(Schema.isInt())
13871 .check(Schema.isGreaterThanOrEqualTo(0)),
13872 Schema.Null,
13873 ]),
13874 ),
13875 }),
13876 }).annotate({ title: "HttpConnectionFailedCodexErrorInfo" }),
13877 Schema.Struct({
13878 responseStreamConnectionFailed: Schema.Struct({
13879 httpStatusCode: Schema.optionalKey(
13880 Schema.Union([
13881 Schema.Number.annotate({ format: "uint16" })
13882 .check(Schema.isInt())
13883 .check(Schema.isGreaterThanOrEqualTo(0)),
13884 Schema.Null,
13885 ]),
13886 ),
13887 }),
13888 }).annotate({
13889 title: "ResponseStreamConnectionFailedCodexErrorInfo",
13890 description: "Failed to connect to the response SSE stream.",
13891 }),
13892 Schema.Struct({
13893 responseStreamDisconnected: Schema.Struct({
13894 httpStatusCode: Schema.optionalKey(
13895 Schema.Union([
13896 Schema.Number.annotate({ format: "uint16" })
13897 .check(Schema.isInt())
13898 .check(Schema.isGreaterThanOrEqualTo(0)),
13899 Schema.Null,
13900 ]),
13901 ),
13902 }),
13903 }).annotate({
13904 title: "ResponseStreamDisconnectedCodexErrorInfo",
13905 description:
13906 "The response SSE stream disconnected in the middle of a turn before completion.",
13907 }),
13908 Schema.Struct({
13909 responseTooManyFailedAttempts: Schema.Struct({
13910 httpStatusCode: Schema.optionalKey(
13911 Schema.Union([
13912 Schema.Number.annotate({ format: "uint16" })
13913 .check(Schema.isInt())
13914 .check(Schema.isGreaterThanOrEqualTo(0)),
13915 Schema.Null,
13916 ]),
13917 ),
13918 }),
13919 }).annotate({
13920 title: "ResponseTooManyFailedAttemptsCodexErrorInfo",
13921 description: "Reached the retry limit for responses.",
13922 }),
13923 Schema.Struct({
13924 activeTurnNotSteerable: Schema.Struct({
13925 turnKind: V2ThreadStartedNotification__NonSteerableTurnKind,
13926 }),
13927 }).annotate({
13928 title: "ActiveTurnNotSteerableCodexErrorInfo",
13929 description:
13930 "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`.",
13931 }),
13932 ],
13933 { mode: "oneOf" },
13934).annotate({
13935 description:
13936 "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.",
13937});
13938
13939export type V2ThreadStartedNotification__FileUpdateChange = {
13940 readonly diff: string;
13941 readonly kind: V2ThreadStartedNotification__PatchChangeKind;
13942 readonly path: string;
13943};
13944export const V2ThreadStartedNotification__FileUpdateChange = Schema.Struct({
13945 diff: Schema.String,
13946 kind: V2ThreadStartedNotification__PatchChangeKind,
13947 path: Schema.String,
13948});
13949
13950export type V2ThreadStartedNotification__UserInput =
13951 | {
13952 readonly text: string;
13953 readonly text_elements?: ReadonlyArray<V2ThreadStartedNotification__TextElement>;
13954 readonly type: "text";
13955 }
13956 | { readonly type: "image"; readonly url: string }
13957 | { readonly path: string; readonly type: "localImage" }
13958 | { readonly name: string; readonly path: string; readonly type: "skill" }
13959 | { readonly name: string; readonly path: string; readonly type: "mention" };
13960export const V2ThreadStartedNotification__UserInput = Schema.Union(
13961 [
13962 Schema.Struct({
13963 text: Schema.String,
13964 text_elements: Schema.optionalKey(
13965 Schema.Array(V2ThreadStartedNotification__TextElement).annotate({
13966 description: "UI-defined spans within `text` used to render or persist special elements.",
13967 default: [],
13968 }),
13969 ),
13970 type: Schema.Literal("text").annotate({ title: "TextUserInputType" }),
13971 }).annotate({ title: "TextUserInput" }),
13972 Schema.Struct({
13973 type: Schema.Literal("image").annotate({ title: "ImageUserInputType" }),
13974 url: Schema.String,
13975 }).annotate({ title: "ImageUserInput" }),
13976 Schema.Struct({
13977 path: Schema.String,
13978 type: Schema.Literal("localImage").annotate({ title: "LocalImageUserInputType" }),
13979 }).annotate({ title: "LocalImageUserInput" }),
13980 Schema.Struct({
13981 name: Schema.String,
13982 path: Schema.String,
13983 type: Schema.Literal("skill").annotate({ title: "SkillUserInputType" }),
13984 }).annotate({ title: "SkillUserInput" }),
13985 Schema.Struct({
13986 name: Schema.String,
13987 path: Schema.String,
13988 type: Schema.Literal("mention").annotate({ title: "MentionUserInputType" }),
13989 }).annotate({ title: "MentionUserInput" }),
13990 ],
13991 { mode: "oneOf" },
13992);
13993
13994export type V2ThreadStartedNotification__SubAgentSource =
13995 | "review"
13996 | "compact"
13997 | "memory_consolidation"
13998 | {
13999 readonly thread_spawn: {
14000 readonly agent_nickname?: string | null;
14001 readonly agent_path?: V2ThreadStartedNotification__AgentPath | null;
14002 readonly agent_role?: string | null;
14003 readonly depth: number;
14004 readonly parent_thread_id: V2ThreadStartedNotification__ThreadId;
14005 };
14006 }
14007 | { readonly other: string };
14008export const V2ThreadStartedNotification__SubAgentSource = Schema.Union(
14009 [
14010 Schema.Literals(["review", "compact", "memory_consolidation"]),
14011 Schema.Struct({
14012 thread_spawn: Schema.Struct({
14013 agent_nickname: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
14014 agent_path: Schema.optionalKey(
14015 Schema.Union([V2ThreadStartedNotification__AgentPath, Schema.Null]),
14016 ),
14017 agent_role: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
14018 depth: Schema.Number.annotate({ format: "int32" }).check(Schema.isInt()),
14019 parent_thread_id: V2ThreadStartedNotification__ThreadId,
14020 }),
14021 }).annotate({ title: "ThreadSpawnSubAgentSource" }),
14022 Schema.Struct({ other: Schema.String }).annotate({ title: "OtherSubAgentSource" }),
14023 ],
14024 { mode: "oneOf" },
14025);
14026
14027export type V2ThreadStartResponse__SandboxPolicy =
14028 | { readonly type: "dangerFullAccess" }
14029 | {
14030 readonly access?:
14031 | {
14032 readonly includePlatformDefaults?: boolean;
14033 readonly readableRoots?: ReadonlyArray<V2ThreadStartResponse__AbsolutePathBuf>;
14034 readonly type: "restricted";
14035 }
14036 | { readonly type: "fullAccess" };
14037 readonly networkAccess?: boolean;
14038 readonly type: "readOnly";
14039 }
14040 | { readonly networkAccess?: "restricted" | "enabled"; readonly type: "externalSandbox" }
14041 | {
14042 readonly excludeSlashTmp?: boolean;
14043 readonly excludeTmpdirEnvVar?: boolean;
14044 readonly networkAccess?: boolean;
14045 readonly readOnlyAccess?:
14046 | {
14047 readonly includePlatformDefaults?: boolean;
14048 readonly readableRoots?: ReadonlyArray<V2ThreadStartResponse__AbsolutePathBuf>;
14049 readonly type: "restricted";
14050 }
14051 | { readonly type: "fullAccess" };
14052 readonly type: "workspaceWrite";
14053 readonly writableRoots?: ReadonlyArray<V2ThreadStartResponse__AbsolutePathBuf>;
14054 };
14055export const V2ThreadStartResponse__SandboxPolicy = Schema.Union(
14056 [
14057 Schema.Struct({
14058 type: Schema.Literal("dangerFullAccess").annotate({
14059 title: "DangerFullAccessSandboxPolicyType",
14060 }),
14061 }).annotate({ title: "DangerFullAccessSandboxPolicy" }),
14062 Schema.Struct({
14063 access: Schema.optionalKey(
14064 Schema.Union(
14065 [
14066 Schema.Struct({
14067 includePlatformDefaults: Schema.optionalKey(
14068 Schema.Boolean.annotate({ default: true }),
14069 ),
14070 readableRoots: Schema.optionalKey(
14071 Schema.Array(V2ThreadStartResponse__AbsolutePathBuf).annotate({ default: [] }),
14072 ),
14073 type: Schema.Literal("restricted").annotate({
14074 title: "RestrictedReadOnlyAccessType",
14075 }),
14076 }).annotate({ title: "RestrictedReadOnlyAccess" }),
14077 Schema.Struct({
14078 type: Schema.Literal("fullAccess").annotate({
14079 title: "FullAccessReadOnlyAccessType",
14080 }),
14081 }).annotate({ title: "FullAccessReadOnlyAccess" }),
14082 ],
14083 { mode: "oneOf" },
14084 ).annotate({ default: { type: "fullAccess" } }),
14085 ),
14086 networkAccess: Schema.optionalKey(Schema.Boolean.annotate({ default: false })),
14087 type: Schema.Literal("readOnly").annotate({ title: "ReadOnlySandboxPolicyType" }),
14088 }).annotate({ title: "ReadOnlySandboxPolicy" }),
14089 Schema.Struct({
14090 networkAccess: Schema.optionalKey(
14091 Schema.Literals(["restricted", "enabled"]).annotate({ default: "restricted" }),
14092 ),
14093 type: Schema.Literal("externalSandbox").annotate({
14094 title: "ExternalSandboxSandboxPolicyType",
14095 }),
14096 }).annotate({ title: "ExternalSandboxSandboxPolicy" }),
14097 Schema.Struct({
14098 excludeSlashTmp: Schema.optionalKey(Schema.Boolean.annotate({ default: false })),
14099 excludeTmpdirEnvVar: Schema.optionalKey(Schema.Boolean.annotate({ default: false })),
14100 networkAccess: Schema.optionalKey(Schema.Boolean.annotate({ default: false })),
14101 readOnlyAccess: Schema.optionalKey(
14102 Schema.Union(
14103 [
14104 Schema.Struct({
14105 includePlatformDefaults: Schema.optionalKey(
14106 Schema.Boolean.annotate({ default: true }),
14107 ),
14108 readableRoots: Schema.optionalKey(
14109 Schema.Array(V2ThreadStartResponse__AbsolutePathBuf).annotate({ default: [] }),
14110 ),
14111 type: Schema.Literal("restricted").annotate({
14112 title: "RestrictedReadOnlyAccessType",
14113 }),
14114 }).annotate({ title: "RestrictedReadOnlyAccess" }),
14115 Schema.Struct({
14116 type: Schema.Literal("fullAccess").annotate({
14117 title: "FullAccessReadOnlyAccessType",
14118 }),
14119 }).annotate({ title: "FullAccessReadOnlyAccess" }),
14120 ],
14121 { mode: "oneOf" },
14122 ).annotate({ default: { type: "fullAccess" } }),
14123 ),
14124 type: Schema.Literal("workspaceWrite").annotate({ title: "WorkspaceWriteSandboxPolicyType" }),
14125 writableRoots: Schema.optionalKey(
14126 Schema.Array(V2ThreadStartResponse__AbsolutePathBuf).annotate({ default: [] }),
14127 ),
14128 }).annotate({ title: "WorkspaceWriteSandboxPolicy" }),
14129 ],
14130 { mode: "oneOf" },
14131);
14132
14133export type V2ThreadStartResponse__CollabAgentState = {
14134 readonly message?: string | null;
14135 readonly status: V2ThreadStartResponse__CollabAgentStatus;
14136};
14137export const V2ThreadStartResponse__CollabAgentState = Schema.Struct({
14138 message: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
14139 status: V2ThreadStartResponse__CollabAgentStatus,
14140});
14141
14142export type V2ThreadStartResponse__MemoryCitation = {
14143 readonly entries: ReadonlyArray<V2ThreadStartResponse__MemoryCitationEntry>;
14144 readonly threadIds: ReadonlyArray<string>;
14145};
14146export const V2ThreadStartResponse__MemoryCitation = Schema.Struct({
14147 entries: Schema.Array(V2ThreadStartResponse__MemoryCitationEntry),
14148 threadIds: Schema.Array(Schema.String),
14149});
14150
14151export type V2ThreadStartResponse__CodexErrorInfo =
14152 | "contextWindowExceeded"
14153 | "usageLimitExceeded"
14154 | "serverOverloaded"
14155 | "internalServerError"
14156 | "unauthorized"
14157 | "badRequest"
14158 | "threadRollbackFailed"
14159 | "sandboxError"
14160 | "other"
14161 | { readonly httpConnectionFailed: { readonly httpStatusCode?: number | null } }
14162 | { readonly responseStreamConnectionFailed: { readonly httpStatusCode?: number | null } }
14163 | { readonly responseStreamDisconnected: { readonly httpStatusCode?: number | null } }
14164 | { readonly responseTooManyFailedAttempts: { readonly httpStatusCode?: number | null } }
14165 | {
14166 readonly activeTurnNotSteerable: {
14167 readonly turnKind: V2ThreadStartResponse__NonSteerableTurnKind;
14168 };
14169 };
14170export const V2ThreadStartResponse__CodexErrorInfo = Schema.Union(
14171 [
14172 Schema.Literals([
14173 "contextWindowExceeded",
14174 "usageLimitExceeded",
14175 "serverOverloaded",
14176 "internalServerError",
14177 "unauthorized",
14178 "badRequest",
14179 "threadRollbackFailed",
14180 "sandboxError",
14181 "other",
14182 ]),
14183 Schema.Struct({
14184 httpConnectionFailed: Schema.Struct({
14185 httpStatusCode: Schema.optionalKey(
14186 Schema.Union([
14187 Schema.Number.annotate({ format: "uint16" })
14188 .check(Schema.isInt())
14189 .check(Schema.isGreaterThanOrEqualTo(0)),
14190 Schema.Null,
14191 ]),
14192 ),
14193 }),
14194 }).annotate({ title: "HttpConnectionFailedCodexErrorInfo" }),
14195 Schema.Struct({
14196 responseStreamConnectionFailed: Schema.Struct({
14197 httpStatusCode: Schema.optionalKey(
14198 Schema.Union([
14199 Schema.Number.annotate({ format: "uint16" })
14200 .check(Schema.isInt())
14201 .check(Schema.isGreaterThanOrEqualTo(0)),
14202 Schema.Null,
14203 ]),
14204 ),
14205 }),
14206 }).annotate({
14207 title: "ResponseStreamConnectionFailedCodexErrorInfo",
14208 description: "Failed to connect to the response SSE stream.",
14209 }),
14210 Schema.Struct({
14211 responseStreamDisconnected: Schema.Struct({
14212 httpStatusCode: Schema.optionalKey(
14213 Schema.Union([
14214 Schema.Number.annotate({ format: "uint16" })
14215 .check(Schema.isInt())
14216 .check(Schema.isGreaterThanOrEqualTo(0)),
14217 Schema.Null,
14218 ]),
14219 ),
14220 }),
14221 }).annotate({
14222 title: "ResponseStreamDisconnectedCodexErrorInfo",
14223 description:
14224 "The response SSE stream disconnected in the middle of a turn before completion.",
14225 }),
14226 Schema.Struct({
14227 responseTooManyFailedAttempts: Schema.Struct({
14228 httpStatusCode: Schema.optionalKey(
14229 Schema.Union([
14230 Schema.Number.annotate({ format: "uint16" })
14231 .check(Schema.isInt())
14232 .check(Schema.isGreaterThanOrEqualTo(0)),
14233 Schema.Null,
14234 ]),
14235 ),
14236 }),
14237 }).annotate({
14238 title: "ResponseTooManyFailedAttemptsCodexErrorInfo",
14239 description: "Reached the retry limit for responses.",
14240 }),
14241 Schema.Struct({
14242 activeTurnNotSteerable: Schema.Struct({
14243 turnKind: V2ThreadStartResponse__NonSteerableTurnKind,
14244 }),
14245 }).annotate({
14246 title: "ActiveTurnNotSteerableCodexErrorInfo",
14247 description:
14248 "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`.",
14249 }),
14250 ],
14251 { mode: "oneOf" },
14252).annotate({
14253 description:
14254 "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.",
14255});
14256
14257export type V2ThreadStartResponse__FileUpdateChange = {
14258 readonly diff: string;
14259 readonly kind: V2ThreadStartResponse__PatchChangeKind;
14260 readonly path: string;
14261};
14262export const V2ThreadStartResponse__FileUpdateChange = Schema.Struct({
14263 diff: Schema.String,
14264 kind: V2ThreadStartResponse__PatchChangeKind,
14265 path: Schema.String,
14266});
14267
14268export type V2ThreadStartResponse__UserInput =
14269 | {
14270 readonly text: string;
14271 readonly text_elements?: ReadonlyArray<V2ThreadStartResponse__TextElement>;
14272 readonly type: "text";
14273 }
14274 | { readonly type: "image"; readonly url: string }
14275 | { readonly path: string; readonly type: "localImage" }
14276 | { readonly name: string; readonly path: string; readonly type: "skill" }
14277 | { readonly name: string; readonly path: string; readonly type: "mention" };
14278export const V2ThreadStartResponse__UserInput = Schema.Union(
14279 [
14280 Schema.Struct({
14281 text: Schema.String,
14282 text_elements: Schema.optionalKey(
14283 Schema.Array(V2ThreadStartResponse__TextElement).annotate({
14284 description: "UI-defined spans within `text` used to render or persist special elements.",
14285 default: [],
14286 }),
14287 ),
14288 type: Schema.Literal("text").annotate({ title: "TextUserInputType" }),
14289 }).annotate({ title: "TextUserInput" }),
14290 Schema.Struct({
14291 type: Schema.Literal("image").annotate({ title: "ImageUserInputType" }),
14292 url: Schema.String,
14293 }).annotate({ title: "ImageUserInput" }),
14294 Schema.Struct({
14295 path: Schema.String,
14296 type: Schema.Literal("localImage").annotate({ title: "LocalImageUserInputType" }),
14297 }).annotate({ title: "LocalImageUserInput" }),
14298 Schema.Struct({
14299 name: Schema.String,
14300 path: Schema.String,
14301 type: Schema.Literal("skill").annotate({ title: "SkillUserInputType" }),
14302 }).annotate({ title: "SkillUserInput" }),
14303 Schema.Struct({
14304 name: Schema.String,
14305 path: Schema.String,
14306 type: Schema.Literal("mention").annotate({ title: "MentionUserInputType" }),
14307 }).annotate({ title: "MentionUserInput" }),
14308 ],
14309 { mode: "oneOf" },
14310);
14311
14312export type V2ThreadStartResponse__SubAgentSource =
14313 | "review"
14314 | "compact"
14315 | "memory_consolidation"
14316 | {
14317 readonly thread_spawn: {
14318 readonly agent_nickname?: string | null;
14319 readonly agent_path?: V2ThreadStartResponse__AgentPath | null;
14320 readonly agent_role?: string | null;
14321 readonly depth: number;
14322 readonly parent_thread_id: V2ThreadStartResponse__ThreadId;
14323 };
14324 }
14325 | { readonly other: string };
14326export const V2ThreadStartResponse__SubAgentSource = Schema.Union(
14327 [
14328 Schema.Literals(["review", "compact", "memory_consolidation"]),
14329 Schema.Struct({
14330 thread_spawn: Schema.Struct({
14331 agent_nickname: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
14332 agent_path: Schema.optionalKey(
14333 Schema.Union([V2ThreadStartResponse__AgentPath, Schema.Null]),
14334 ),
14335 agent_role: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
14336 depth: Schema.Number.annotate({ format: "int32" }).check(Schema.isInt()),
14337 parent_thread_id: V2ThreadStartResponse__ThreadId,
14338 }),
14339 }).annotate({ title: "ThreadSpawnSubAgentSource" }),
14340 Schema.Struct({ other: Schema.String }).annotate({ title: "OtherSubAgentSource" }),
14341 ],
14342 { mode: "oneOf" },
14343);
14344
14345export type V2ThreadStatusChangedNotification__ThreadStatus =
14346 | { readonly type: "notLoaded" }
14347 | { readonly type: "idle" }
14348 | { readonly type: "systemError" }
14349 | {
14350 readonly activeFlags: ReadonlyArray<V2ThreadStatusChangedNotification__ThreadActiveFlag>;
14351 readonly type: "active";
14352 };
14353export const V2ThreadStatusChangedNotification__ThreadStatus = Schema.Union(
14354 [
14355 Schema.Struct({
14356 type: Schema.Literal("notLoaded").annotate({ title: "NotLoadedThreadStatusType" }),
14357 }).annotate({ title: "NotLoadedThreadStatus" }),
14358 Schema.Struct({
14359 type: Schema.Literal("idle").annotate({ title: "IdleThreadStatusType" }),
14360 }).annotate({ title: "IdleThreadStatus" }),
14361 Schema.Struct({
14362 type: Schema.Literal("systemError").annotate({ title: "SystemErrorThreadStatusType" }),
14363 }).annotate({ title: "SystemErrorThreadStatus" }),
14364 Schema.Struct({
14365 activeFlags: Schema.Array(V2ThreadStatusChangedNotification__ThreadActiveFlag),
14366 type: Schema.Literal("active").annotate({ title: "ActiveThreadStatusType" }),
14367 }).annotate({ title: "ActiveThreadStatus" }),
14368 ],
14369 { mode: "oneOf" },
14370);
14371
14372export type V2ThreadTokenUsageUpdatedNotification__ThreadTokenUsage = {
14373 readonly last: V2ThreadTokenUsageUpdatedNotification__TokenUsageBreakdown;
14374 readonly modelContextWindow?: number | null;
14375 readonly total: V2ThreadTokenUsageUpdatedNotification__TokenUsageBreakdown;
14376};
14377export const V2ThreadTokenUsageUpdatedNotification__ThreadTokenUsage = Schema.Struct({
14378 last: V2ThreadTokenUsageUpdatedNotification__TokenUsageBreakdown,
14379 modelContextWindow: Schema.optionalKey(
14380 Schema.Union([Schema.Number.annotate({ format: "int64" }).check(Schema.isInt()), Schema.Null]),
14381 ),
14382 total: V2ThreadTokenUsageUpdatedNotification__TokenUsageBreakdown,
14383});
14384
14385export type V2ThreadUnarchiveResponse__CollabAgentState = {
14386 readonly message?: string | null;
14387 readonly status: V2ThreadUnarchiveResponse__CollabAgentStatus;
14388};
14389export const V2ThreadUnarchiveResponse__CollabAgentState = Schema.Struct({
14390 message: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
14391 status: V2ThreadUnarchiveResponse__CollabAgentStatus,
14392});
14393
14394export type V2ThreadUnarchiveResponse__MemoryCitation = {
14395 readonly entries: ReadonlyArray<V2ThreadUnarchiveResponse__MemoryCitationEntry>;
14396 readonly threadIds: ReadonlyArray<string>;
14397};
14398export const V2ThreadUnarchiveResponse__MemoryCitation = Schema.Struct({
14399 entries: Schema.Array(V2ThreadUnarchiveResponse__MemoryCitationEntry),
14400 threadIds: Schema.Array(Schema.String),
14401});
14402
14403export type V2ThreadUnarchiveResponse__CodexErrorInfo =
14404 | "contextWindowExceeded"
14405 | "usageLimitExceeded"
14406 | "serverOverloaded"
14407 | "internalServerError"
14408 | "unauthorized"
14409 | "badRequest"
14410 | "threadRollbackFailed"
14411 | "sandboxError"
14412 | "other"
14413 | { readonly httpConnectionFailed: { readonly httpStatusCode?: number | null } }
14414 | { readonly responseStreamConnectionFailed: { readonly httpStatusCode?: number | null } }
14415 | { readonly responseStreamDisconnected: { readonly httpStatusCode?: number | null } }
14416 | { readonly responseTooManyFailedAttempts: { readonly httpStatusCode?: number | null } }
14417 | {
14418 readonly activeTurnNotSteerable: {
14419 readonly turnKind: V2ThreadUnarchiveResponse__NonSteerableTurnKind;
14420 };
14421 };
14422export const V2ThreadUnarchiveResponse__CodexErrorInfo = Schema.Union(
14423 [
14424 Schema.Literals([
14425 "contextWindowExceeded",
14426 "usageLimitExceeded",
14427 "serverOverloaded",
14428 "internalServerError",
14429 "unauthorized",
14430 "badRequest",
14431 "threadRollbackFailed",
14432 "sandboxError",
14433 "other",
14434 ]),
14435 Schema.Struct({
14436 httpConnectionFailed: Schema.Struct({
14437 httpStatusCode: Schema.optionalKey(
14438 Schema.Union([
14439 Schema.Number.annotate({ format: "uint16" })
14440 .check(Schema.isInt())
14441 .check(Schema.isGreaterThanOrEqualTo(0)),
14442 Schema.Null,
14443 ]),
14444 ),
14445 }),
14446 }).annotate({ title: "HttpConnectionFailedCodexErrorInfo" }),
14447 Schema.Struct({
14448 responseStreamConnectionFailed: Schema.Struct({
14449 httpStatusCode: Schema.optionalKey(
14450 Schema.Union([
14451 Schema.Number.annotate({ format: "uint16" })
14452 .check(Schema.isInt())
14453 .check(Schema.isGreaterThanOrEqualTo(0)),
14454 Schema.Null,
14455 ]),
14456 ),
14457 }),
14458 }).annotate({
14459 title: "ResponseStreamConnectionFailedCodexErrorInfo",
14460 description: "Failed to connect to the response SSE stream.",
14461 }),
14462 Schema.Struct({
14463 responseStreamDisconnected: Schema.Struct({
14464 httpStatusCode: Schema.optionalKey(
14465 Schema.Union([
14466 Schema.Number.annotate({ format: "uint16" })
14467 .check(Schema.isInt())
14468 .check(Schema.isGreaterThanOrEqualTo(0)),
14469 Schema.Null,
14470 ]),
14471 ),
14472 }),
14473 }).annotate({
14474 title: "ResponseStreamDisconnectedCodexErrorInfo",
14475 description:
14476 "The response SSE stream disconnected in the middle of a turn before completion.",
14477 }),
14478 Schema.Struct({
14479 responseTooManyFailedAttempts: Schema.Struct({
14480 httpStatusCode: Schema.optionalKey(
14481 Schema.Union([
14482 Schema.Number.annotate({ format: "uint16" })
14483 .check(Schema.isInt())
14484 .check(Schema.isGreaterThanOrEqualTo(0)),
14485 Schema.Null,
14486 ]),
14487 ),
14488 }),
14489 }).annotate({
14490 title: "ResponseTooManyFailedAttemptsCodexErrorInfo",
14491 description: "Reached the retry limit for responses.",
14492 }),
14493 Schema.Struct({
14494 activeTurnNotSteerable: Schema.Struct({
14495 turnKind: V2ThreadUnarchiveResponse__NonSteerableTurnKind,
14496 }),
14497 }).annotate({
14498 title: "ActiveTurnNotSteerableCodexErrorInfo",
14499 description:
14500 "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`.",
14501 }),
14502 ],
14503 { mode: "oneOf" },
14504).annotate({
14505 description:
14506 "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.",
14507});
14508
14509export type V2ThreadUnarchiveResponse__FileUpdateChange = {
14510 readonly diff: string;
14511 readonly kind: V2ThreadUnarchiveResponse__PatchChangeKind;
14512 readonly path: string;
14513};
14514export const V2ThreadUnarchiveResponse__FileUpdateChange = Schema.Struct({
14515 diff: Schema.String,
14516 kind: V2ThreadUnarchiveResponse__PatchChangeKind,
14517 path: Schema.String,
14518});
14519
14520export type V2ThreadUnarchiveResponse__UserInput =
14521 | {
14522 readonly text: string;
14523 readonly text_elements?: ReadonlyArray<V2ThreadUnarchiveResponse__TextElement>;
14524 readonly type: "text";
14525 }
14526 | { readonly type: "image"; readonly url: string }
14527 | { readonly path: string; readonly type: "localImage" }
14528 | { readonly name: string; readonly path: string; readonly type: "skill" }
14529 | { readonly name: string; readonly path: string; readonly type: "mention" };
14530export const V2ThreadUnarchiveResponse__UserInput = Schema.Union(
14531 [
14532 Schema.Struct({
14533 text: Schema.String,
14534 text_elements: Schema.optionalKey(
14535 Schema.Array(V2ThreadUnarchiveResponse__TextElement).annotate({
14536 description: "UI-defined spans within `text` used to render or persist special elements.",
14537 default: [],
14538 }),
14539 ),
14540 type: Schema.Literal("text").annotate({ title: "TextUserInputType" }),
14541 }).annotate({ title: "TextUserInput" }),
14542 Schema.Struct({
14543 type: Schema.Literal("image").annotate({ title: "ImageUserInputType" }),
14544 url: Schema.String,
14545 }).annotate({ title: "ImageUserInput" }),
14546 Schema.Struct({
14547 path: Schema.String,
14548 type: Schema.Literal("localImage").annotate({ title: "LocalImageUserInputType" }),
14549 }).annotate({ title: "LocalImageUserInput" }),
14550 Schema.Struct({
14551 name: Schema.String,
14552 path: Schema.String,
14553 type: Schema.Literal("skill").annotate({ title: "SkillUserInputType" }),
14554 }).annotate({ title: "SkillUserInput" }),
14555 Schema.Struct({
14556 name: Schema.String,
14557 path: Schema.String,
14558 type: Schema.Literal("mention").annotate({ title: "MentionUserInputType" }),
14559 }).annotate({ title: "MentionUserInput" }),
14560 ],
14561 { mode: "oneOf" },
14562);
14563
14564export type V2ThreadUnarchiveResponse__SubAgentSource =
14565 | "review"
14566 | "compact"
14567 | "memory_consolidation"
14568 | {
14569 readonly thread_spawn: {
14570 readonly agent_nickname?: string | null;
14571 readonly agent_path?: V2ThreadUnarchiveResponse__AgentPath | null;
14572 readonly agent_role?: string | null;
14573 readonly depth: number;
14574 readonly parent_thread_id: V2ThreadUnarchiveResponse__ThreadId;
14575 };
14576 }
14577 | { readonly other: string };
14578export const V2ThreadUnarchiveResponse__SubAgentSource = Schema.Union(
14579 [
14580 Schema.Literals(["review", "compact", "memory_consolidation"]),
14581 Schema.Struct({
14582 thread_spawn: Schema.Struct({
14583 agent_nickname: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
14584 agent_path: Schema.optionalKey(
14585 Schema.Union([V2ThreadUnarchiveResponse__AgentPath, Schema.Null]),
14586 ),
14587 agent_role: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
14588 depth: Schema.Number.annotate({ format: "int32" }).check(Schema.isInt()),
14589 parent_thread_id: V2ThreadUnarchiveResponse__ThreadId,
14590 }),
14591 }).annotate({ title: "ThreadSpawnSubAgentSource" }),
14592 Schema.Struct({ other: Schema.String }).annotate({ title: "OtherSubAgentSource" }),
14593 ],
14594 { mode: "oneOf" },
14595);
14596
14597export type V2TurnCompletedNotification__CollabAgentState = {
14598 readonly message?: string | null;
14599 readonly status: V2TurnCompletedNotification__CollabAgentStatus;
14600};
14601export const V2TurnCompletedNotification__CollabAgentState = Schema.Struct({
14602 message: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
14603 status: V2TurnCompletedNotification__CollabAgentStatus,
14604});
14605
14606export type V2TurnCompletedNotification__MemoryCitation = {
14607 readonly entries: ReadonlyArray<V2TurnCompletedNotification__MemoryCitationEntry>;
14608 readonly threadIds: ReadonlyArray<string>;
14609};
14610export const V2TurnCompletedNotification__MemoryCitation = Schema.Struct({
14611 entries: Schema.Array(V2TurnCompletedNotification__MemoryCitationEntry),
14612 threadIds: Schema.Array(Schema.String),
14613});
14614
14615export type V2TurnCompletedNotification__CodexErrorInfo =
14616 | "contextWindowExceeded"
14617 | "usageLimitExceeded"
14618 | "serverOverloaded"
14619 | "internalServerError"
14620 | "unauthorized"
14621 | "badRequest"
14622 | "threadRollbackFailed"
14623 | "sandboxError"
14624 | "other"
14625 | { readonly httpConnectionFailed: { readonly httpStatusCode?: number | null } }
14626 | { readonly responseStreamConnectionFailed: { readonly httpStatusCode?: number | null } }
14627 | { readonly responseStreamDisconnected: { readonly httpStatusCode?: number | null } }
14628 | { readonly responseTooManyFailedAttempts: { readonly httpStatusCode?: number | null } }
14629 | {
14630 readonly activeTurnNotSteerable: {
14631 readonly turnKind: V2TurnCompletedNotification__NonSteerableTurnKind;
14632 };
14633 };
14634export const V2TurnCompletedNotification__CodexErrorInfo = Schema.Union(
14635 [
14636 Schema.Literals([
14637 "contextWindowExceeded",
14638 "usageLimitExceeded",
14639 "serverOverloaded",
14640 "internalServerError",
14641 "unauthorized",
14642 "badRequest",
14643 "threadRollbackFailed",
14644 "sandboxError",
14645 "other",
14646 ]),
14647 Schema.Struct({
14648 httpConnectionFailed: Schema.Struct({
14649 httpStatusCode: Schema.optionalKey(
14650 Schema.Union([
14651 Schema.Number.annotate({ format: "uint16" })
14652 .check(Schema.isInt())
14653 .check(Schema.isGreaterThanOrEqualTo(0)),
14654 Schema.Null,
14655 ]),
14656 ),
14657 }),
14658 }).annotate({ title: "HttpConnectionFailedCodexErrorInfo" }),
14659 Schema.Struct({
14660 responseStreamConnectionFailed: Schema.Struct({
14661 httpStatusCode: Schema.optionalKey(
14662 Schema.Union([
14663 Schema.Number.annotate({ format: "uint16" })
14664 .check(Schema.isInt())
14665 .check(Schema.isGreaterThanOrEqualTo(0)),
14666 Schema.Null,
14667 ]),
14668 ),
14669 }),
14670 }).annotate({
14671 title: "ResponseStreamConnectionFailedCodexErrorInfo",
14672 description: "Failed to connect to the response SSE stream.",
14673 }),
14674 Schema.Struct({
14675 responseStreamDisconnected: Schema.Struct({
14676 httpStatusCode: Schema.optionalKey(
14677 Schema.Union([
14678 Schema.Number.annotate({ format: "uint16" })
14679 .check(Schema.isInt())
14680 .check(Schema.isGreaterThanOrEqualTo(0)),
14681 Schema.Null,
14682 ]),
14683 ),
14684 }),
14685 }).annotate({
14686 title: "ResponseStreamDisconnectedCodexErrorInfo",
14687 description:
14688 "The response SSE stream disconnected in the middle of a turn before completion.",
14689 }),
14690 Schema.Struct({
14691 responseTooManyFailedAttempts: Schema.Struct({
14692 httpStatusCode: Schema.optionalKey(
14693 Schema.Union([
14694 Schema.Number.annotate({ format: "uint16" })
14695 .check(Schema.isInt())
14696 .check(Schema.isGreaterThanOrEqualTo(0)),
14697 Schema.Null,
14698 ]),
14699 ),
14700 }),
14701 }).annotate({
14702 title: "ResponseTooManyFailedAttemptsCodexErrorInfo",
14703 description: "Reached the retry limit for responses.",
14704 }),
14705 Schema.Struct({
14706 activeTurnNotSteerable: Schema.Struct({
14707 turnKind: V2TurnCompletedNotification__NonSteerableTurnKind,
14708 }),
14709 }).annotate({
14710 title: "ActiveTurnNotSteerableCodexErrorInfo",
14711 description:
14712 "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`.",
14713 }),
14714 ],
14715 { mode: "oneOf" },
14716).annotate({
14717 description:
14718 "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.",
14719});
14720
14721export type V2TurnCompletedNotification__FileUpdateChange = {
14722 readonly diff: string;
14723 readonly kind: V2TurnCompletedNotification__PatchChangeKind;
14724 readonly path: string;
14725};
14726export const V2TurnCompletedNotification__FileUpdateChange = Schema.Struct({
14727 diff: Schema.String,
14728 kind: V2TurnCompletedNotification__PatchChangeKind,
14729 path: Schema.String,
14730});
14731
14732export type V2TurnCompletedNotification__UserInput =
14733 | {
14734 readonly text: string;
14735 readonly text_elements?: ReadonlyArray<V2TurnCompletedNotification__TextElement>;
14736 readonly type: "text";
14737 }
14738 | { readonly type: "image"; readonly url: string }
14739 | { readonly path: string; readonly type: "localImage" }
14740 | { readonly name: string; readonly path: string; readonly type: "skill" }
14741 | { readonly name: string; readonly path: string; readonly type: "mention" };
14742export const V2TurnCompletedNotification__UserInput = Schema.Union(
14743 [
14744 Schema.Struct({
14745 text: Schema.String,
14746 text_elements: Schema.optionalKey(
14747 Schema.Array(V2TurnCompletedNotification__TextElement).annotate({
14748 description: "UI-defined spans within `text` used to render or persist special elements.",
14749 default: [],
14750 }),
14751 ),
14752 type: Schema.Literal("text").annotate({ title: "TextUserInputType" }),
14753 }).annotate({ title: "TextUserInput" }),
14754 Schema.Struct({
14755 type: Schema.Literal("image").annotate({ title: "ImageUserInputType" }),
14756 url: Schema.String,
14757 }).annotate({ title: "ImageUserInput" }),
14758 Schema.Struct({
14759 path: Schema.String,
14760 type: Schema.Literal("localImage").annotate({ title: "LocalImageUserInputType" }),
14761 }).annotate({ title: "LocalImageUserInput" }),
14762 Schema.Struct({
14763 name: Schema.String,
14764 path: Schema.String,
14765 type: Schema.Literal("skill").annotate({ title: "SkillUserInputType" }),
14766 }).annotate({ title: "SkillUserInput" }),
14767 Schema.Struct({
14768 name: Schema.String,
14769 path: Schema.String,
14770 type: Schema.Literal("mention").annotate({ title: "MentionUserInputType" }),
14771 }).annotate({ title: "MentionUserInput" }),
14772 ],
14773 { mode: "oneOf" },
14774);
14775
14776export type V2TurnPlanUpdatedNotification__TurnPlanStep = {
14777 readonly status: V2TurnPlanUpdatedNotification__TurnPlanStepStatus;
14778 readonly step: string;
14779};
14780export const V2TurnPlanUpdatedNotification__TurnPlanStep = Schema.Struct({
14781 status: V2TurnPlanUpdatedNotification__TurnPlanStepStatus,
14782 step: Schema.String,
14783});
14784
14785export type V2TurnStartedNotification__CollabAgentState = {
14786 readonly message?: string | null;
14787 readonly status: V2TurnStartedNotification__CollabAgentStatus;
14788};
14789export const V2TurnStartedNotification__CollabAgentState = Schema.Struct({
14790 message: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
14791 status: V2TurnStartedNotification__CollabAgentStatus,
14792});
14793
14794export type V2TurnStartedNotification__MemoryCitation = {
14795 readonly entries: ReadonlyArray<V2TurnStartedNotification__MemoryCitationEntry>;
14796 readonly threadIds: ReadonlyArray<string>;
14797};
14798export const V2TurnStartedNotification__MemoryCitation = Schema.Struct({
14799 entries: Schema.Array(V2TurnStartedNotification__MemoryCitationEntry),
14800 threadIds: Schema.Array(Schema.String),
14801});
14802
14803export type V2TurnStartedNotification__CodexErrorInfo =
14804 | "contextWindowExceeded"
14805 | "usageLimitExceeded"
14806 | "serverOverloaded"
14807 | "internalServerError"
14808 | "unauthorized"
14809 | "badRequest"
14810 | "threadRollbackFailed"
14811 | "sandboxError"
14812 | "other"
14813 | { readonly httpConnectionFailed: { readonly httpStatusCode?: number | null } }
14814 | { readonly responseStreamConnectionFailed: { readonly httpStatusCode?: number | null } }
14815 | { readonly responseStreamDisconnected: { readonly httpStatusCode?: number | null } }
14816 | { readonly responseTooManyFailedAttempts: { readonly httpStatusCode?: number | null } }
14817 | {
14818 readonly activeTurnNotSteerable: {
14819 readonly turnKind: V2TurnStartedNotification__NonSteerableTurnKind;
14820 };
14821 };
14822export const V2TurnStartedNotification__CodexErrorInfo = Schema.Union(
14823 [
14824 Schema.Literals([
14825 "contextWindowExceeded",
14826 "usageLimitExceeded",
14827 "serverOverloaded",
14828 "internalServerError",
14829 "unauthorized",
14830 "badRequest",
14831 "threadRollbackFailed",
14832 "sandboxError",
14833 "other",
14834 ]),
14835 Schema.Struct({
14836 httpConnectionFailed: Schema.Struct({
14837 httpStatusCode: Schema.optionalKey(
14838 Schema.Union([
14839 Schema.Number.annotate({ format: "uint16" })
14840 .check(Schema.isInt())
14841 .check(Schema.isGreaterThanOrEqualTo(0)),
14842 Schema.Null,
14843 ]),
14844 ),
14845 }),
14846 }).annotate({ title: "HttpConnectionFailedCodexErrorInfo" }),
14847 Schema.Struct({
14848 responseStreamConnectionFailed: Schema.Struct({
14849 httpStatusCode: Schema.optionalKey(
14850 Schema.Union([
14851 Schema.Number.annotate({ format: "uint16" })
14852 .check(Schema.isInt())
14853 .check(Schema.isGreaterThanOrEqualTo(0)),
14854 Schema.Null,
14855 ]),
14856 ),
14857 }),
14858 }).annotate({
14859 title: "ResponseStreamConnectionFailedCodexErrorInfo",
14860 description: "Failed to connect to the response SSE stream.",
14861 }),
14862 Schema.Struct({
14863 responseStreamDisconnected: Schema.Struct({
14864 httpStatusCode: Schema.optionalKey(
14865 Schema.Union([
14866 Schema.Number.annotate({ format: "uint16" })
14867 .check(Schema.isInt())
14868 .check(Schema.isGreaterThanOrEqualTo(0)),
14869 Schema.Null,
14870 ]),
14871 ),
14872 }),
14873 }).annotate({
14874 title: "ResponseStreamDisconnectedCodexErrorInfo",
14875 description:
14876 "The response SSE stream disconnected in the middle of a turn before completion.",
14877 }),
14878 Schema.Struct({
14879 responseTooManyFailedAttempts: Schema.Struct({
14880 httpStatusCode: Schema.optionalKey(
14881 Schema.Union([
14882 Schema.Number.annotate({ format: "uint16" })
14883 .check(Schema.isInt())
14884 .check(Schema.isGreaterThanOrEqualTo(0)),
14885 Schema.Null,
14886 ]),
14887 ),
14888 }),
14889 }).annotate({
14890 title: "ResponseTooManyFailedAttemptsCodexErrorInfo",
14891 description: "Reached the retry limit for responses.",
14892 }),
14893 Schema.Struct({
14894 activeTurnNotSteerable: Schema.Struct({
14895 turnKind: V2TurnStartedNotification__NonSteerableTurnKind,
14896 }),
14897 }).annotate({
14898 title: "ActiveTurnNotSteerableCodexErrorInfo",
14899 description:
14900 "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`.",
14901 }),
14902 ],
14903 { mode: "oneOf" },
14904).annotate({
14905 description:
14906 "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.",
14907});
14908
14909export type V2TurnStartedNotification__FileUpdateChange = {
14910 readonly diff: string;
14911 readonly kind: V2TurnStartedNotification__PatchChangeKind;
14912 readonly path: string;
14913};
14914export const V2TurnStartedNotification__FileUpdateChange = Schema.Struct({
14915 diff: Schema.String,
14916 kind: V2TurnStartedNotification__PatchChangeKind,
14917 path: Schema.String,
14918});
14919
14920export type V2TurnStartedNotification__UserInput =
14921 | {
14922 readonly text: string;
14923 readonly text_elements?: ReadonlyArray<V2TurnStartedNotification__TextElement>;
14924 readonly type: "text";
14925 }
14926 | { readonly type: "image"; readonly url: string }
14927 | { readonly path: string; readonly type: "localImage" }
14928 | { readonly name: string; readonly path: string; readonly type: "skill" }
14929 | { readonly name: string; readonly path: string; readonly type: "mention" };
14930export const V2TurnStartedNotification__UserInput = Schema.Union(
14931 [
14932 Schema.Struct({
14933 text: Schema.String,
14934 text_elements: Schema.optionalKey(
14935 Schema.Array(V2TurnStartedNotification__TextElement).annotate({
14936 description: "UI-defined spans within `text` used to render or persist special elements.",
14937 default: [],
14938 }),
14939 ),
14940 type: Schema.Literal("text").annotate({ title: "TextUserInputType" }),
14941 }).annotate({ title: "TextUserInput" }),
14942 Schema.Struct({
14943 type: Schema.Literal("image").annotate({ title: "ImageUserInputType" }),
14944 url: Schema.String,
14945 }).annotate({ title: "ImageUserInput" }),
14946 Schema.Struct({
14947 path: Schema.String,
14948 type: Schema.Literal("localImage").annotate({ title: "LocalImageUserInputType" }),
14949 }).annotate({ title: "LocalImageUserInput" }),
14950 Schema.Struct({
14951 name: Schema.String,
14952 path: Schema.String,
14953 type: Schema.Literal("skill").annotate({ title: "SkillUserInputType" }),
14954 }).annotate({ title: "SkillUserInput" }),
14955 Schema.Struct({
14956 name: Schema.String,
14957 path: Schema.String,
14958 type: Schema.Literal("mention").annotate({ title: "MentionUserInputType" }),
14959 }).annotate({ title: "MentionUserInput" }),
14960 ],
14961 { mode: "oneOf" },
14962);
14963
14964export type V2TurnStartParams__SandboxPolicy =
14965 | { readonly type: "dangerFullAccess" }
14966 | {
14967 readonly access?:
14968 | {
14969 readonly includePlatformDefaults?: boolean;
14970 readonly readableRoots?: ReadonlyArray<V2TurnStartParams__AbsolutePathBuf>;
14971 readonly type: "restricted";
14972 }
14973 | { readonly type: "fullAccess" };
14974 readonly networkAccess?: boolean;
14975 readonly type: "readOnly";
14976 }
14977 | { readonly networkAccess?: "restricted" | "enabled"; readonly type: "externalSandbox" }
14978 | {
14979 readonly excludeSlashTmp?: boolean;
14980 readonly excludeTmpdirEnvVar?: boolean;
14981 readonly networkAccess?: boolean;
14982 readonly readOnlyAccess?:
14983 | {
14984 readonly includePlatformDefaults?: boolean;
14985 readonly readableRoots?: ReadonlyArray<V2TurnStartParams__AbsolutePathBuf>;
14986 readonly type: "restricted";
14987 }
14988 | { readonly type: "fullAccess" };
14989 readonly type: "workspaceWrite";
14990 readonly writableRoots?: ReadonlyArray<V2TurnStartParams__AbsolutePathBuf>;
14991 };
14992export const V2TurnStartParams__SandboxPolicy = Schema.Union(
14993 [
14994 Schema.Struct({
14995 type: Schema.Literal("dangerFullAccess").annotate({
14996 title: "DangerFullAccessSandboxPolicyType",
14997 }),
14998 }).annotate({ title: "DangerFullAccessSandboxPolicy" }),
14999 Schema.Struct({
15000 access: Schema.optionalKey(
15001 Schema.Union(
15002 [
15003 Schema.Struct({
15004 includePlatformDefaults: Schema.optionalKey(
15005 Schema.Boolean.annotate({ default: true }),
15006 ),
15007 readableRoots: Schema.optionalKey(
15008 Schema.Array(V2TurnStartParams__AbsolutePathBuf).annotate({ default: [] }),
15009 ),
15010 type: Schema.Literal("restricted").annotate({
15011 title: "RestrictedReadOnlyAccessType",
15012 }),
15013 }).annotate({ title: "RestrictedReadOnlyAccess" }),
15014 Schema.Struct({
15015 type: Schema.Literal("fullAccess").annotate({
15016 title: "FullAccessReadOnlyAccessType",
15017 }),
15018 }).annotate({ title: "FullAccessReadOnlyAccess" }),
15019 ],
15020 { mode: "oneOf" },
15021 ).annotate({ default: { type: "fullAccess" } }),
15022 ),
15023 networkAccess: Schema.optionalKey(Schema.Boolean.annotate({ default: false })),
15024 type: Schema.Literal("readOnly").annotate({ title: "ReadOnlySandboxPolicyType" }),
15025 }).annotate({ title: "ReadOnlySandboxPolicy" }),
15026 Schema.Struct({
15027 networkAccess: Schema.optionalKey(
15028 Schema.Literals(["restricted", "enabled"]).annotate({ default: "restricted" }),
15029 ),
15030 type: Schema.Literal("externalSandbox").annotate({
15031 title: "ExternalSandboxSandboxPolicyType",
15032 }),
15033 }).annotate({ title: "ExternalSandboxSandboxPolicy" }),
15034 Schema.Struct({
15035 excludeSlashTmp: Schema.optionalKey(Schema.Boolean.annotate({ default: false })),
15036 excludeTmpdirEnvVar: Schema.optionalKey(Schema.Boolean.annotate({ default: false })),
15037 networkAccess: Schema.optionalKey(Schema.Boolean.annotate({ default: false })),
15038 readOnlyAccess: Schema.optionalKey(
15039 Schema.Union(
15040 [
15041 Schema.Struct({
15042 includePlatformDefaults: Schema.optionalKey(
15043 Schema.Boolean.annotate({ default: true }),
15044 ),
15045 readableRoots: Schema.optionalKey(
15046 Schema.Array(V2TurnStartParams__AbsolutePathBuf).annotate({ default: [] }),
15047 ),
15048 type: Schema.Literal("restricted").annotate({
15049 title: "RestrictedReadOnlyAccessType",
15050 }),
15051 }).annotate({ title: "RestrictedReadOnlyAccess" }),
15052 Schema.Struct({
15053 type: Schema.Literal("fullAccess").annotate({
15054 title: "FullAccessReadOnlyAccessType",
15055 }),
15056 }).annotate({ title: "FullAccessReadOnlyAccess" }),
15057 ],
15058 { mode: "oneOf" },
15059 ).annotate({ default: { type: "fullAccess" } }),
15060 ),
15061 type: Schema.Literal("workspaceWrite").annotate({ title: "WorkspaceWriteSandboxPolicyType" }),
15062 writableRoots: Schema.optionalKey(
15063 Schema.Array(V2TurnStartParams__AbsolutePathBuf).annotate({ default: [] }),
15064 ),
15065 }).annotate({ title: "WorkspaceWriteSandboxPolicy" }),
15066 ],
15067 { mode: "oneOf" },
15068);
15069
15070export type V2TurnStartParams__Settings = {
15071 readonly developer_instructions?: string | null;
15072 readonly model: string;
15073 readonly reasoning_effort?: V2TurnStartParams__ReasoningEffort | null;
15074};
15075export const V2TurnStartParams__Settings = Schema.Struct({
15076 developer_instructions: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
15077 model: Schema.String,
15078 reasoning_effort: Schema.optionalKey(
15079 Schema.Union([V2TurnStartParams__ReasoningEffort, Schema.Null]),
15080 ),
15081}).annotate({ description: "Settings for a collaboration mode." });
15082
15083export type V2TurnStartParams__UserInput =
15084 | {
15085 readonly text: string;
15086 readonly text_elements?: ReadonlyArray<V2TurnStartParams__TextElement>;
15087 readonly type: "text";
15088 }
15089 | { readonly type: "image"; readonly url: string }
15090 | { readonly path: string; readonly type: "localImage" }
15091 | { readonly name: string; readonly path: string; readonly type: "skill" }
15092 | { readonly name: string; readonly path: string; readonly type: "mention" };
15093export const V2TurnStartParams__UserInput = Schema.Union(
15094 [
15095 Schema.Struct({
15096 text: Schema.String,
15097 text_elements: Schema.optionalKey(
15098 Schema.Array(V2TurnStartParams__TextElement).annotate({
15099 description: "UI-defined spans within `text` used to render or persist special elements.",
15100 default: [],
15101 }),
15102 ),
15103 type: Schema.Literal("text").annotate({ title: "TextUserInputType" }),
15104 }).annotate({ title: "TextUserInput" }),
15105 Schema.Struct({
15106 type: Schema.Literal("image").annotate({ title: "ImageUserInputType" }),
15107 url: Schema.String,
15108 }).annotate({ title: "ImageUserInput" }),
15109 Schema.Struct({
15110 path: Schema.String,
15111 type: Schema.Literal("localImage").annotate({ title: "LocalImageUserInputType" }),
15112 }).annotate({ title: "LocalImageUserInput" }),
15113 Schema.Struct({
15114 name: Schema.String,
15115 path: Schema.String,
15116 type: Schema.Literal("skill").annotate({ title: "SkillUserInputType" }),
15117 }).annotate({ title: "SkillUserInput" }),
15118 Schema.Struct({
15119 name: Schema.String,
15120 path: Schema.String,
15121 type: Schema.Literal("mention").annotate({ title: "MentionUserInputType" }),
15122 }).annotate({ title: "MentionUserInput" }),
15123 ],
15124 { mode: "oneOf" },
15125);
15126
15127export type V2TurnStartResponse__CollabAgentState = {
15128 readonly message?: string | null;
15129 readonly status: V2TurnStartResponse__CollabAgentStatus;
15130};
15131export const V2TurnStartResponse__CollabAgentState = Schema.Struct({
15132 message: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
15133 status: V2TurnStartResponse__CollabAgentStatus,
15134});
15135
15136export type V2TurnStartResponse__MemoryCitation = {
15137 readonly entries: ReadonlyArray<V2TurnStartResponse__MemoryCitationEntry>;
15138 readonly threadIds: ReadonlyArray<string>;
15139};
15140export const V2TurnStartResponse__MemoryCitation = Schema.Struct({
15141 entries: Schema.Array(V2TurnStartResponse__MemoryCitationEntry),
15142 threadIds: Schema.Array(Schema.String),
15143});
15144
15145export type V2TurnStartResponse__CodexErrorInfo =
15146 | "contextWindowExceeded"
15147 | "usageLimitExceeded"
15148 | "serverOverloaded"
15149 | "internalServerError"
15150 | "unauthorized"
15151 | "badRequest"
15152 | "threadRollbackFailed"
15153 | "sandboxError"
15154 | "other"
15155 | { readonly httpConnectionFailed: { readonly httpStatusCode?: number | null } }
15156 | { readonly responseStreamConnectionFailed: { readonly httpStatusCode?: number | null } }
15157 | { readonly responseStreamDisconnected: { readonly httpStatusCode?: number | null } }
15158 | { readonly responseTooManyFailedAttempts: { readonly httpStatusCode?: number | null } }
15159 | {
15160 readonly activeTurnNotSteerable: {
15161 readonly turnKind: V2TurnStartResponse__NonSteerableTurnKind;
15162 };
15163 };
15164export const V2TurnStartResponse__CodexErrorInfo = Schema.Union(
15165 [
15166 Schema.Literals([
15167 "contextWindowExceeded",
15168 "usageLimitExceeded",
15169 "serverOverloaded",
15170 "internalServerError",
15171 "unauthorized",
15172 "badRequest",
15173 "threadRollbackFailed",
15174 "sandboxError",
15175 "other",
15176 ]),
15177 Schema.Struct({
15178 httpConnectionFailed: Schema.Struct({
15179 httpStatusCode: Schema.optionalKey(
15180 Schema.Union([
15181 Schema.Number.annotate({ format: "uint16" })
15182 .check(Schema.isInt())
15183 .check(Schema.isGreaterThanOrEqualTo(0)),
15184 Schema.Null,
15185 ]),
15186 ),
15187 }),
15188 }).annotate({ title: "HttpConnectionFailedCodexErrorInfo" }),
15189 Schema.Struct({
15190 responseStreamConnectionFailed: Schema.Struct({
15191 httpStatusCode: Schema.optionalKey(
15192 Schema.Union([
15193 Schema.Number.annotate({ format: "uint16" })
15194 .check(Schema.isInt())
15195 .check(Schema.isGreaterThanOrEqualTo(0)),
15196 Schema.Null,
15197 ]),
15198 ),
15199 }),
15200 }).annotate({
15201 title: "ResponseStreamConnectionFailedCodexErrorInfo",
15202 description: "Failed to connect to the response SSE stream.",
15203 }),
15204 Schema.Struct({
15205 responseStreamDisconnected: Schema.Struct({
15206 httpStatusCode: Schema.optionalKey(
15207 Schema.Union([
15208 Schema.Number.annotate({ format: "uint16" })
15209 .check(Schema.isInt())
15210 .check(Schema.isGreaterThanOrEqualTo(0)),
15211 Schema.Null,
15212 ]),
15213 ),
15214 }),
15215 }).annotate({
15216 title: "ResponseStreamDisconnectedCodexErrorInfo",
15217 description:
15218 "The response SSE stream disconnected in the middle of a turn before completion.",
15219 }),
15220 Schema.Struct({
15221 responseTooManyFailedAttempts: Schema.Struct({
15222 httpStatusCode: Schema.optionalKey(
15223 Schema.Union([
15224 Schema.Number.annotate({ format: "uint16" })
15225 .check(Schema.isInt())
15226 .check(Schema.isGreaterThanOrEqualTo(0)),
15227 Schema.Null,
15228 ]),
15229 ),
15230 }),
15231 }).annotate({
15232 title: "ResponseTooManyFailedAttemptsCodexErrorInfo",
15233 description: "Reached the retry limit for responses.",
15234 }),
15235 Schema.Struct({
15236 activeTurnNotSteerable: Schema.Struct({
15237 turnKind: V2TurnStartResponse__NonSteerableTurnKind,
15238 }),
15239 }).annotate({
15240 title: "ActiveTurnNotSteerableCodexErrorInfo",
15241 description:
15242 "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`.",
15243 }),
15244 ],
15245 { mode: "oneOf" },
15246).annotate({
15247 description:
15248 "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.",
15249});
15250
15251export type V2TurnStartResponse__FileUpdateChange = {
15252 readonly diff: string;
15253 readonly kind: V2TurnStartResponse__PatchChangeKind;
15254 readonly path: string;
15255};
15256export const V2TurnStartResponse__FileUpdateChange = Schema.Struct({
15257 diff: Schema.String,
15258 kind: V2TurnStartResponse__PatchChangeKind,
15259 path: Schema.String,
15260});
15261
15262export type V2TurnStartResponse__UserInput =
15263 | {
15264 readonly text: string;
15265 readonly text_elements?: ReadonlyArray<V2TurnStartResponse__TextElement>;
15266 readonly type: "text";
15267 }
15268 | { readonly type: "image"; readonly url: string }
15269 | { readonly path: string; readonly type: "localImage" }
15270 | { readonly name: string; readonly path: string; readonly type: "skill" }
15271 | { readonly name: string; readonly path: string; readonly type: "mention" };
15272export const V2TurnStartResponse__UserInput = Schema.Union(
15273 [
15274 Schema.Struct({
15275 text: Schema.String,
15276 text_elements: Schema.optionalKey(
15277 Schema.Array(V2TurnStartResponse__TextElement).annotate({
15278 description: "UI-defined spans within `text` used to render or persist special elements.",
15279 default: [],
15280 }),
15281 ),
15282 type: Schema.Literal("text").annotate({ title: "TextUserInputType" }),
15283 }).annotate({ title: "TextUserInput" }),
15284 Schema.Struct({
15285 type: Schema.Literal("image").annotate({ title: "ImageUserInputType" }),
15286 url: Schema.String,
15287 }).annotate({ title: "ImageUserInput" }),
15288 Schema.Struct({
15289 path: Schema.String,
15290 type: Schema.Literal("localImage").annotate({ title: "LocalImageUserInputType" }),
15291 }).annotate({ title: "LocalImageUserInput" }),
15292 Schema.Struct({
15293 name: Schema.String,
15294 path: Schema.String,
15295 type: Schema.Literal("skill").annotate({ title: "SkillUserInputType" }),
15296 }).annotate({ title: "SkillUserInput" }),
15297 Schema.Struct({
15298 name: Schema.String,
15299 path: Schema.String,
15300 type: Schema.Literal("mention").annotate({ title: "MentionUserInputType" }),
15301 }).annotate({ title: "MentionUserInput" }),
15302 ],
15303 { mode: "oneOf" },
15304);
15305
15306export type V2TurnSteerParams__UserInput =
15307 | {
15308 readonly text: string;
15309 readonly text_elements?: ReadonlyArray<V2TurnSteerParams__TextElement>;
15310 readonly type: "text";
15311 }
15312 | { readonly type: "image"; readonly url: string }
15313 | { readonly path: string; readonly type: "localImage" }
15314 | { readonly name: string; readonly path: string; readonly type: "skill" }
15315 | { readonly name: string; readonly path: string; readonly type: "mention" };
15316export const V2TurnSteerParams__UserInput = Schema.Union(
15317 [
15318 Schema.Struct({
15319 text: Schema.String,
15320 text_elements: Schema.optionalKey(
15321 Schema.Array(V2TurnSteerParams__TextElement).annotate({
15322 description: "UI-defined spans within `text` used to render or persist special elements.",
15323 default: [],
15324 }),
15325 ),
15326 type: Schema.Literal("text").annotate({ title: "TextUserInputType" }),
15327 }).annotate({ title: "TextUserInput" }),
15328 Schema.Struct({
15329 type: Schema.Literal("image").annotate({ title: "ImageUserInputType" }),
15330 url: Schema.String,
15331 }).annotate({ title: "ImageUserInput" }),
15332 Schema.Struct({
15333 path: Schema.String,
15334 type: Schema.Literal("localImage").annotate({ title: "LocalImageUserInputType" }),
15335 }).annotate({ title: "LocalImageUserInput" }),
15336 Schema.Struct({
15337 name: Schema.String,
15338 path: Schema.String,
15339 type: Schema.Literal("skill").annotate({ title: "SkillUserInputType" }),
15340 }).annotate({ title: "SkillUserInput" }),
15341 Schema.Struct({
15342 name: Schema.String,
15343 path: Schema.String,
15344 type: Schema.Literal("mention").annotate({ title: "MentionUserInputType" }),
15345 }).annotate({ title: "MentionUserInput" }),
15346 ],
15347 { mode: "oneOf" },
15348);
15349
15350export type ApplyPatchApprovalResponse__ReviewDecision =
15351 | "approved"
15352 | {
15353 readonly approved_execpolicy_amendment: {
15354 readonly proposed_execpolicy_amendment: ReadonlyArray<string>;
15355 };
15356 }
15357 | "approved_for_session"
15358 | {
15359 readonly network_policy_amendment: {
15360 readonly network_policy_amendment: ApplyPatchApprovalResponse__NetworkPolicyAmendment;
15361 };
15362 }
15363 | "denied"
15364 | "timed_out"
15365 | "abort";
15366export const ApplyPatchApprovalResponse__ReviewDecision = Schema.Union(
15367 [
15368 Schema.Literal("approved").annotate({
15369 description: "User has approved this command and the agent should execute it.",
15370 }),
15371 Schema.Struct({
15372 approved_execpolicy_amendment: Schema.Struct({
15373 proposed_execpolicy_amendment: Schema.Array(Schema.String),
15374 }),
15375 }).annotate({
15376 title: "ApprovedExecpolicyAmendmentReviewDecision",
15377 description:
15378 "User has approved this command and wants to apply the proposed execpolicy amendment so future matching commands are permitted.",
15379 }),
15380 Schema.Literal("approved_for_session").annotate({
15381 description:
15382 "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.",
15383 }),
15384 Schema.Struct({
15385 network_policy_amendment: Schema.Struct({
15386 network_policy_amendment: ApplyPatchApprovalResponse__NetworkPolicyAmendment,
15387 }),
15388 }).annotate({
15389 title: "NetworkPolicyAmendmentReviewDecision",
15390 description:
15391 "User chose to persist a network policy rule (allow/deny) for future requests to the same host.",
15392 }),
15393 Schema.Literal("denied").annotate({
15394 description:
15395 "User has denied this command and the agent should not execute it, but it should continue the session and try something else.",
15396 }),
15397 Schema.Literal("timed_out").annotate({
15398 description: "Automatic approval review timed out before reaching a decision.",
15399 }),
15400 Schema.Literal("abort").annotate({
15401 description:
15402 "User has denied this command and the agent should not do anything until the user's next command.",
15403 }),
15404 ],
15405 { mode: "oneOf" },
15406).annotate({ description: "User's decision in response to an ExecApprovalRequest." });
15407
15408export type ClientRequest__CommandExecParams = {
15409 readonly command: ReadonlyArray<string>;
15410 readonly cwd?: string | null;
15411 readonly disableOutputCap?: boolean;
15412 readonly disableTimeout?: boolean;
15413 readonly env?: { readonly [x: string]: string | null } | null;
15414 readonly outputBytesCap?: number | null;
15415 readonly processId?: string | null;
15416 readonly sandboxPolicy?: ClientRequest__SandboxPolicy | null;
15417 readonly size?: ClientRequest__CommandExecTerminalSize | null;
15418 readonly streamStdin?: boolean;
15419 readonly streamStdoutStderr?: boolean;
15420 readonly timeoutMs?: number | null;
15421 readonly tty?: boolean;
15422};
15423export const ClientRequest__CommandExecParams = Schema.Struct({
15424 command: Schema.Array(Schema.String).annotate({
15425 description: "Command argv vector. Empty arrays are rejected.",
15426 }),
15427 cwd: Schema.optionalKey(
15428 Schema.Union([
15429 Schema.String.annotate({
15430 description: "Optional working directory. Defaults to the server cwd.",
15431 }),
15432 Schema.Null,
15433 ]),
15434 ),
15435 disableOutputCap: Schema.optionalKey(
15436 Schema.Boolean.annotate({
15437 description:
15438 "Disable stdout/stderr capture truncation for this request.\n\nCannot be combined with `outputBytesCap`.",
15439 }),
15440 ),
15441 disableTimeout: Schema.optionalKey(
15442 Schema.Boolean.annotate({
15443 description:
15444 "Disable the timeout entirely for this request.\n\nCannot be combined with `timeoutMs`.",
15445 }),
15446 ),
15447 env: Schema.optionalKey(
15448 Schema.Union([
15449 Schema.Record(Schema.String, Schema.Union([Schema.String, Schema.Null])).annotate({
15450 description:
15451 "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.",
15452 }),
15453 Schema.Null,
15454 ]),
15455 ),
15456 outputBytesCap: Schema.optionalKey(
15457 Schema.Union([
15458 Schema.Number.annotate({
15459 description:
15460 "Optional per-stream stdout/stderr capture cap in bytes.\n\nWhen omitted, the server default applies. Cannot be combined with `disableOutputCap`.",
15461 format: "uint",
15462 })
15463 .check(Schema.isInt())
15464 .check(Schema.isGreaterThanOrEqualTo(0)),
15465 Schema.Null,
15466 ]),
15467 ),
15468 processId: Schema.optionalKey(
15469 Schema.Union([
15470 Schema.String.annotate({
15471 description:
15472 "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.",
15473 }),
15474 Schema.Null,
15475 ]),
15476 ),
15477 sandboxPolicy: Schema.optionalKey(
15478 Schema.Union([ClientRequest__SandboxPolicy, Schema.Null]).annotate({
15479 description:
15480 "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.",
15481 }),
15482 ),
15483 size: Schema.optionalKey(
15484 Schema.Union([ClientRequest__CommandExecTerminalSize, Schema.Null]).annotate({
15485 description: "Optional initial PTY size in character cells. Only valid when `tty` is true.",
15486 }),
15487 ),
15488 streamStdin: Schema.optionalKey(
15489 Schema.Boolean.annotate({
15490 description:
15491 "Allow follow-up `command/exec/write` requests to write stdin bytes.\n\nRequires a client-supplied `processId`.",
15492 }),
15493 ),
15494 streamStdoutStderr: Schema.optionalKey(
15495 Schema.Boolean.annotate({
15496 description:
15497 "Stream stdout/stderr via `command/exec/outputDelta` notifications.\n\nStreamed bytes are not duplicated into the final response and require a client-supplied `processId`.",
15498 }),
15499 ),
15500 timeoutMs: Schema.optionalKey(
15501 Schema.Union([
15502 Schema.Number.annotate({
15503 description:
15504 "Optional timeout in milliseconds.\n\nWhen omitted, the server default applies. Cannot be combined with `disableTimeout`.",
15505 format: "int64",
15506 }).check(Schema.isInt()),
15507 Schema.Null,
15508 ]),
15509 ),
15510 tty: Schema.optionalKey(
15511 Schema.Boolean.annotate({
15512 description: "Enable PTY mode.\n\nThis implies `streamStdin` and `streamStdoutStderr`.",
15513 }),
15514 ),
15515}).annotate({
15516 description:
15517 "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.",
15518});
15519
15520export type ClientRequest__ExternalAgentConfigImportParams = {
15521 readonly migrationItems: ReadonlyArray<ClientRequest__ExternalAgentConfigMigrationItem>;
15522};
15523export const ClientRequest__ExternalAgentConfigImportParams = Schema.Struct({
15524 migrationItems: Schema.Array(ClientRequest__ExternalAgentConfigMigrationItem),
15525});
15526
15527export type ClientRequest__FunctionCallOutputBody =
15528 | string
15529 | ReadonlyArray<ClientRequest__FunctionCallOutputContentItem>;
15530export const ClientRequest__FunctionCallOutputBody = Schema.Union([
15531 Schema.String,
15532 Schema.Array(ClientRequest__FunctionCallOutputContentItem),
15533]);
15534
15535export type ClientRequest__ConfigBatchWriteParams = {
15536 readonly edits: ReadonlyArray<ClientRequest__ConfigEdit>;
15537 readonly expectedVersion?: string | null;
15538 readonly filePath?: string | null;
15539 readonly reloadUserConfig?: boolean;
15540};
15541export const ClientRequest__ConfigBatchWriteParams = Schema.Struct({
15542 edits: Schema.Array(ClientRequest__ConfigEdit),
15543 expectedVersion: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
15544 filePath: Schema.optionalKey(
15545 Schema.Union([
15546 Schema.String.annotate({
15547 description:
15548 "Path to the config file to write; defaults to the user's `config.toml` when omitted.",
15549 }),
15550 Schema.Null,
15551 ]),
15552 ),
15553 reloadUserConfig: Schema.optionalKey(
15554 Schema.Boolean.annotate({
15555 description:
15556 "When true, hot-reload the updated user config into all loaded threads after writing.",
15557 }),
15558 ),
15559});
15560
15561export type ClientRequest__TurnStartParams = {
15562 readonly approvalPolicy?: ClientRequest__AskForApproval | null;
15563 readonly approvalsReviewer?: ClientRequest__ApprovalsReviewer | null;
15564 readonly cwd?: string | null;
15565 readonly effort?: ClientRequest__ReasoningEffort | null;
15566 readonly input: ReadonlyArray<ClientRequest__UserInput>;
15567 readonly model?: string | null;
15568 readonly outputSchema?: unknown;
15569 readonly personality?: ClientRequest__Personality | null;
15570 readonly sandboxPolicy?: ClientRequest__SandboxPolicy | null;
15571 readonly serviceTier?: ClientRequest__ServiceTier | null | null;
15572 readonly summary?: ClientRequest__ReasoningSummary | null;
15573 readonly threadId: string;
15574};
15575export const ClientRequest__TurnStartParams = Schema.Struct({
15576 approvalPolicy: Schema.optionalKey(
15577 Schema.Union([ClientRequest__AskForApproval, Schema.Null]).annotate({
15578 description: "Override the approval policy for this turn and subsequent turns.",
15579 }),
15580 ),
15581 approvalsReviewer: Schema.optionalKey(
15582 Schema.Union([ClientRequest__ApprovalsReviewer, Schema.Null]).annotate({
15583 description:
15584 "Override where approval requests are routed for review on this turn and subsequent turns.",
15585 }),
15586 ),
15587 cwd: Schema.optionalKey(
15588 Schema.Union([
15589 Schema.String.annotate({
15590 description: "Override the working directory for this turn and subsequent turns.",
15591 }),
15592 Schema.Null,
15593 ]),
15594 ),
15595 effort: Schema.optionalKey(
15596 Schema.Union([ClientRequest__ReasoningEffort, Schema.Null]).annotate({
15597 description: "Override the reasoning effort for this turn and subsequent turns.",
15598 }),
15599 ),
15600 input: Schema.Array(ClientRequest__UserInput),
15601 model: Schema.optionalKey(
15602 Schema.Union([
15603 Schema.String.annotate({
15604 description: "Override the model for this turn and subsequent turns.",
15605 }),
15606 Schema.Null,
15607 ]),
15608 ),
15609 outputSchema: Schema.optionalKey(
15610 Schema.Unknown.annotate({
15611 description:
15612 "Optional JSON Schema used to constrain the final assistant message for this turn.",
15613 }),
15614 ),
15615 personality: Schema.optionalKey(
15616 Schema.Union([ClientRequest__Personality, Schema.Null]).annotate({
15617 description: "Override the personality for this turn and subsequent turns.",
15618 }),
15619 ),
15620 sandboxPolicy: Schema.optionalKey(
15621 Schema.Union([ClientRequest__SandboxPolicy, Schema.Null]).annotate({
15622 description: "Override the sandbox policy for this turn and subsequent turns.",
15623 }),
15624 ),
15625 serviceTier: Schema.optionalKey(
15626 Schema.Union([Schema.Union([ClientRequest__ServiceTier, Schema.Null]), Schema.Null]).annotate({
15627 description: "Override the service tier for this turn and subsequent turns.",
15628 }),
15629 ),
15630 summary: Schema.optionalKey(
15631 Schema.Union([ClientRequest__ReasoningSummary, Schema.Null]).annotate({
15632 description: "Override the reasoning summary for this turn and subsequent turns.",
15633 }),
15634 ),
15635 threadId: Schema.String,
15636});
15637
15638export type ClientRequest__TurnSteerParams = {
15639 readonly expectedTurnId: string;
15640 readonly input: ReadonlyArray<ClientRequest__UserInput>;
15641 readonly threadId: string;
15642};
15643export const ClientRequest__TurnSteerParams = Schema.Struct({
15644 expectedTurnId: Schema.String.annotate({
15645 description:
15646 "Required active turn id precondition. The request fails when it does not match the currently active turn.",
15647 }),
15648 input: Schema.Array(ClientRequest__UserInput),
15649 threadId: Schema.String,
15650});
15651
15652export type CommandExecutionRequestApprovalResponse__CommandExecutionApprovalDecision =
15653 | "accept"
15654 | "acceptForSession"
15655 | {
15656 readonly acceptWithExecpolicyAmendment: {
15657 readonly execpolicy_amendment: ReadonlyArray<string>;
15658 };
15659 }
15660 | {
15661 readonly applyNetworkPolicyAmendment: {
15662 readonly network_policy_amendment: CommandExecutionRequestApprovalResponse__NetworkPolicyAmendment;
15663 };
15664 }
15665 | "decline"
15666 | "cancel";
15667export const CommandExecutionRequestApprovalResponse__CommandExecutionApprovalDecision =
15668 Schema.Union(
15669 [
15670 Schema.Literal("accept").annotate({ description: "User approved the command." }),
15671 Schema.Literal("acceptForSession").annotate({
15672 description:
15673 "User approved the command and future prompts in the same session-scoped approval cache should run without prompting.",
15674 }),
15675 Schema.Struct({
15676 acceptWithExecpolicyAmendment: Schema.Struct({
15677 execpolicy_amendment: Schema.Array(Schema.String),
15678 }),
15679 }).annotate({
15680 title: "AcceptWithExecpolicyAmendmentCommandExecutionApprovalDecision",
15681 description:
15682 "User approved the command, and wants to apply the proposed execpolicy amendment so future matching commands can run without prompting.",
15683 }),
15684 Schema.Struct({
15685 applyNetworkPolicyAmendment: Schema.Struct({
15686 network_policy_amendment: CommandExecutionRequestApprovalResponse__NetworkPolicyAmendment,
15687 }),
15688 }).annotate({
15689 title: "ApplyNetworkPolicyAmendmentCommandExecutionApprovalDecision",
15690 description: "User chose a persistent network policy rule (allow/deny) for this host.",
15691 }),
15692 Schema.Literal("decline").annotate({
15693 description: "User denied the command. The agent will continue the turn.",
15694 }),
15695 Schema.Literal("cancel").annotate({
15696 description: "User denied the command. The turn will also be immediately interrupted.",
15697 }),
15698 ],
15699 { mode: "oneOf" },
15700 );
15701
15702export type ExecCommandApprovalResponse__ReviewDecision =
15703 | "approved"
15704 | {
15705 readonly approved_execpolicy_amendment: {
15706 readonly proposed_execpolicy_amendment: ReadonlyArray<string>;
15707 };
15708 }
15709 | "approved_for_session"
15710 | {
15711 readonly network_policy_amendment: {
15712 readonly network_policy_amendment: ExecCommandApprovalResponse__NetworkPolicyAmendment;
15713 };
15714 }
15715 | "denied"
15716 | "timed_out"
15717 | "abort";
15718export const ExecCommandApprovalResponse__ReviewDecision = Schema.Union(
15719 [
15720 Schema.Literal("approved").annotate({
15721 description: "User has approved this command and the agent should execute it.",
15722 }),
15723 Schema.Struct({
15724 approved_execpolicy_amendment: Schema.Struct({
15725 proposed_execpolicy_amendment: Schema.Array(Schema.String),
15726 }),
15727 }).annotate({
15728 title: "ApprovedExecpolicyAmendmentReviewDecision",
15729 description:
15730 "User has approved this command and wants to apply the proposed execpolicy amendment so future matching commands are permitted.",
15731 }),
15732 Schema.Literal("approved_for_session").annotate({
15733 description:
15734 "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.",
15735 }),
15736 Schema.Struct({
15737 network_policy_amendment: Schema.Struct({
15738 network_policy_amendment: ExecCommandApprovalResponse__NetworkPolicyAmendment,
15739 }),
15740 }).annotate({
15741 title: "NetworkPolicyAmendmentReviewDecision",
15742 description:
15743 "User chose to persist a network policy rule (allow/deny) for future requests to the same host.",
15744 }),
15745 Schema.Literal("denied").annotate({
15746 description:
15747 "User has denied this command and the agent should not execute it, but it should continue the session and try something else.",
15748 }),
15749 Schema.Literal("timed_out").annotate({
15750 description: "Automatic approval review timed out before reaching a decision.",
15751 }),
15752 Schema.Literal("abort").annotate({
15753 description:
15754 "User has denied this command and the agent should not do anything until the user's next command.",
15755 }),
15756 ],
15757 { mode: "oneOf" },
15758).annotate({ description: "User's decision in response to an ExecApprovalRequest." });
15759
15760export type McpServerElicitationRequestParams__McpElicitationTitledMultiSelectEnumSchema = {
15761 readonly default?: ReadonlyArray<string> | null;
15762 readonly description?: string | null;
15763 readonly items: McpServerElicitationRequestParams__McpElicitationTitledEnumItems;
15764 readonly maxItems?: number | null;
15765 readonly minItems?: number | null;
15766 readonly title?: string | null;
15767 readonly type: McpServerElicitationRequestParams__McpElicitationArrayType;
15768};
15769export const McpServerElicitationRequestParams__McpElicitationTitledMultiSelectEnumSchema =
15770 Schema.Struct({
15771 default: Schema.optionalKey(Schema.Union([Schema.Array(Schema.String), Schema.Null])),
15772 description: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
15773 items: McpServerElicitationRequestParams__McpElicitationTitledEnumItems,
15774 maxItems: Schema.optionalKey(
15775 Schema.Union([
15776 Schema.Number.annotate({ format: "uint64" })
15777 .check(Schema.isInt())
15778 .check(Schema.isGreaterThanOrEqualTo(0)),
15779 Schema.Null,
15780 ]),
15781 ),
15782 minItems: Schema.optionalKey(
15783 Schema.Union([
15784 Schema.Number.annotate({ format: "uint64" })
15785 .check(Schema.isInt())
15786 .check(Schema.isGreaterThanOrEqualTo(0)),
15787 Schema.Null,
15788 ]),
15789 ),
15790 title: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
15791 type: McpServerElicitationRequestParams__McpElicitationArrayType,
15792 });
15793
15794export type McpServerElicitationRequestParams__McpElicitationUntitledMultiSelectEnumSchema = {
15795 readonly default?: ReadonlyArray<string> | null;
15796 readonly description?: string | null;
15797 readonly items: McpServerElicitationRequestParams__McpElicitationUntitledEnumItems;
15798 readonly maxItems?: number | null;
15799 readonly minItems?: number | null;
15800 readonly title?: string | null;
15801 readonly type: McpServerElicitationRequestParams__McpElicitationArrayType;
15802};
15803export const McpServerElicitationRequestParams__McpElicitationUntitledMultiSelectEnumSchema =
15804 Schema.Struct({
15805 default: Schema.optionalKey(Schema.Union([Schema.Array(Schema.String), Schema.Null])),
15806 description: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
15807 items: McpServerElicitationRequestParams__McpElicitationUntitledEnumItems,
15808 maxItems: Schema.optionalKey(
15809 Schema.Union([
15810 Schema.Number.annotate({ format: "uint64" })
15811 .check(Schema.isInt())
15812 .check(Schema.isGreaterThanOrEqualTo(0)),
15813 Schema.Null,
15814 ]),
15815 ),
15816 minItems: Schema.optionalKey(
15817 Schema.Union([
15818 Schema.Number.annotate({ format: "uint64" })
15819 .check(Schema.isInt())
15820 .check(Schema.isGreaterThanOrEqualTo(0)),
15821 Schema.Null,
15822 ]),
15823 ),
15824 title: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
15825 type: McpServerElicitationRequestParams__McpElicitationArrayType,
15826 });
15827
15828export type McpServerElicitationRequestParams__McpElicitationSingleSelectEnumSchema =
15829 | McpServerElicitationRequestParams__McpElicitationUntitledSingleSelectEnumSchema
15830 | McpServerElicitationRequestParams__McpElicitationTitledSingleSelectEnumSchema;
15831export const McpServerElicitationRequestParams__McpElicitationSingleSelectEnumSchema = Schema.Union(
15832 [
15833 McpServerElicitationRequestParams__McpElicitationUntitledSingleSelectEnumSchema,
15834 McpServerElicitationRequestParams__McpElicitationTitledSingleSelectEnumSchema,
15835 ],
15836);
15837
15838export type PermissionsRequestApprovalParams__RequestPermissionProfile = {
15839 readonly fileSystem?: PermissionsRequestApprovalParams__AdditionalFileSystemPermissions | null;
15840 readonly network?: PermissionsRequestApprovalParams__AdditionalNetworkPermissions | null;
15841};
15842export const PermissionsRequestApprovalParams__RequestPermissionProfile = Schema.Struct({
15843 fileSystem: Schema.optionalKey(
15844 Schema.Union([PermissionsRequestApprovalParams__AdditionalFileSystemPermissions, Schema.Null]),
15845 ),
15846 network: Schema.optionalKey(
15847 Schema.Union([PermissionsRequestApprovalParams__AdditionalNetworkPermissions, Schema.Null]),
15848 ),
15849});
15850
15851export type PermissionsRequestApprovalResponse__GrantedPermissionProfile = {
15852 readonly fileSystem?: PermissionsRequestApprovalResponse__AdditionalFileSystemPermissions | null;
15853 readonly network?: PermissionsRequestApprovalResponse__AdditionalNetworkPermissions | null;
15854};
15855export const PermissionsRequestApprovalResponse__GrantedPermissionProfile = Schema.Struct({
15856 fileSystem: Schema.optionalKey(
15857 Schema.Union([
15858 PermissionsRequestApprovalResponse__AdditionalFileSystemPermissions,
15859 Schema.Null,
15860 ]),
15861 ),
15862 network: Schema.optionalKey(
15863 Schema.Union([PermissionsRequestApprovalResponse__AdditionalNetworkPermissions, Schema.Null]),
15864 ),
15865});
15866
15867export type ServerNotification__AppInfo = {
15868 readonly appMetadata?: ServerNotification__AppMetadata | null;
15869 readonly branding?: ServerNotification__AppBranding | null;
15870 readonly description?: string | null;
15871 readonly distributionChannel?: string | null;
15872 readonly id: string;
15873 readonly installUrl?: string | null;
15874 readonly isAccessible?: boolean;
15875 readonly isEnabled?: boolean;
15876 readonly labels?: { readonly [x: string]: string } | null;
15877 readonly logoUrl?: string | null;
15878 readonly logoUrlDark?: string | null;
15879 readonly name: string;
15880 readonly pluginDisplayNames?: ReadonlyArray<string>;
15881};
15882export const ServerNotification__AppInfo = Schema.Struct({
15883 appMetadata: Schema.optionalKey(Schema.Union([ServerNotification__AppMetadata, Schema.Null])),
15884 branding: Schema.optionalKey(Schema.Union([ServerNotification__AppBranding, Schema.Null])),
15885 description: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
15886 distributionChannel: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
15887 id: Schema.String,
15888 installUrl: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
15889 isAccessible: Schema.optionalKey(Schema.Boolean.annotate({ default: false })),
15890 isEnabled: Schema.optionalKey(
15891 Schema.Boolean.annotate({
15892 description:
15893 "Whether this app is enabled in config.toml. Example: ```toml [apps.bad_app] enabled = false ```",
15894 default: true,
15895 }),
15896 ),
15897 labels: Schema.optionalKey(
15898 Schema.Union([Schema.Record(Schema.String, Schema.String), Schema.Null]),
15899 ),
15900 logoUrl: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
15901 logoUrlDark: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
15902 name: Schema.String,
15903 pluginDisplayNames: Schema.optionalKey(Schema.Array(Schema.String).annotate({ default: [] })),
15904}).annotate({ description: "EXPERIMENTAL - app metadata returned by app-list APIs." });
15905
15906export type ServerNotification__FuzzyFileSearchSessionUpdatedNotification = {
15907 readonly files: ReadonlyArray<ServerNotification__FuzzyFileSearchResult>;
15908 readonly query: string;
15909 readonly sessionId: string;
15910};
15911export const ServerNotification__FuzzyFileSearchSessionUpdatedNotification = Schema.Struct({
15912 files: Schema.Array(ServerNotification__FuzzyFileSearchResult),
15913 query: Schema.String,
15914 sessionId: Schema.String,
15915});
15916
15917export type ServerNotification__HookRunSummary = {
15918 readonly completedAt?: number | null;
15919 readonly displayOrder: number;
15920 readonly durationMs?: number | null;
15921 readonly entries: ReadonlyArray<ServerNotification__HookOutputEntry>;
15922 readonly eventName: ServerNotification__HookEventName;
15923 readonly executionMode: ServerNotification__HookExecutionMode;
15924 readonly handlerType: ServerNotification__HookHandlerType;
15925 readonly id: string;
15926 readonly scope: ServerNotification__HookScope;
15927 readonly sourcePath: string;
15928 readonly startedAt: number;
15929 readonly status: ServerNotification__HookRunStatus;
15930 readonly statusMessage?: string | null;
15931};
15932export const ServerNotification__HookRunSummary = Schema.Struct({
15933 completedAt: Schema.optionalKey(
15934 Schema.Union([Schema.Number.annotate({ format: "int64" }).check(Schema.isInt()), Schema.Null]),
15935 ),
15936 displayOrder: Schema.Number.annotate({ format: "int64" }).check(Schema.isInt()),
15937 durationMs: Schema.optionalKey(
15938 Schema.Union([Schema.Number.annotate({ format: "int64" }).check(Schema.isInt()), Schema.Null]),
15939 ),
15940 entries: Schema.Array(ServerNotification__HookOutputEntry),
15941 eventName: ServerNotification__HookEventName,
15942 executionMode: ServerNotification__HookExecutionMode,
15943 handlerType: ServerNotification__HookHandlerType,
15944 id: Schema.String,
15945 scope: ServerNotification__HookScope,
15946 sourcePath: Schema.String,
15947 startedAt: Schema.Number.annotate({ format: "int64" }).check(Schema.isInt()),
15948 status: ServerNotification__HookRunStatus,
15949 statusMessage: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
15950});
15951
15952export type ServerNotification__ItemGuardianApprovalReviewCompletedNotification = {
15953 readonly action: ServerNotification__GuardianApprovalReviewAction;
15954 readonly decisionSource: ServerNotification__AutoReviewDecisionSource;
15955 readonly review: ServerNotification__GuardianApprovalReview;
15956 readonly reviewId: string;
15957 readonly targetItemId?: string | null;
15958 readonly threadId: string;
15959 readonly turnId: string;
15960};
15961export const ServerNotification__ItemGuardianApprovalReviewCompletedNotification = Schema.Struct({
15962 action: ServerNotification__GuardianApprovalReviewAction,
15963 decisionSource: ServerNotification__AutoReviewDecisionSource,
15964 review: ServerNotification__GuardianApprovalReview,
15965 reviewId: Schema.String.annotate({ description: "Stable identifier for this review." }),
15966 targetItemId: Schema.optionalKey(
15967 Schema.Union([
15968 Schema.String.annotate({
15969 description:
15970 "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.",
15971 }),
15972 Schema.Null,
15973 ]),
15974 ),
15975 threadId: Schema.String,
15976 turnId: Schema.String,
15977}).annotate({
15978 description:
15979 "[UNSTABLE] Temporary notification payload for guardian automatic approval review. This shape is expected to change soon.",
15980});
15981
15982export type ServerNotification__ItemGuardianApprovalReviewStartedNotification = {
15983 readonly action: ServerNotification__GuardianApprovalReviewAction;
15984 readonly review: ServerNotification__GuardianApprovalReview;
15985 readonly reviewId: string;
15986 readonly targetItemId?: string | null;
15987 readonly threadId: string;
15988 readonly turnId: string;
15989};
15990export const ServerNotification__ItemGuardianApprovalReviewStartedNotification = Schema.Struct({
15991 action: ServerNotification__GuardianApprovalReviewAction,
15992 review: ServerNotification__GuardianApprovalReview,
15993 reviewId: Schema.String.annotate({ description: "Stable identifier for this review." }),
15994 targetItemId: Schema.optionalKey(
15995 Schema.Union([
15996 Schema.String.annotate({
15997 description:
15998 "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.",
15999 }),
16000 Schema.Null,
16001 ]),
16002 ),
16003 threadId: Schema.String,
16004 turnId: Schema.String,
16005}).annotate({
16006 description:
16007 "[UNSTABLE] Temporary notification payload for guardian automatic approval review. This shape is expected to change soon.",
16008});
16009
16010export type ServerNotification__TurnError = {
16011 readonly additionalDetails?: string | null;
16012 readonly codexErrorInfo?: ServerNotification__CodexErrorInfo | null;
16013 readonly message: string;
16014};
16015export const ServerNotification__TurnError = Schema.Struct({
16016 additionalDetails: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
16017 codexErrorInfo: Schema.optionalKey(
16018 Schema.Union([ServerNotification__CodexErrorInfo, Schema.Null]),
16019 ),
16020 message: Schema.String,
16021});
16022
16023export type ServerNotification__AccountRateLimitsUpdatedNotification = {
16024 readonly rateLimits: ServerNotification__RateLimitSnapshot;
16025};
16026export const ServerNotification__AccountRateLimitsUpdatedNotification = Schema.Struct({
16027 rateLimits: ServerNotification__RateLimitSnapshot,
16028});
16029
16030export type ServerNotification__ThreadItem =
16031 | {
16032 readonly content: ReadonlyArray<ServerNotification__UserInput>;
16033 readonly id: string;
16034 readonly type: "userMessage";
16035 }
16036 | {
16037 readonly fragments: ReadonlyArray<ServerNotification__HookPromptFragment>;
16038 readonly id: string;
16039 readonly type: "hookPrompt";
16040 }
16041 | {
16042 readonly id: string;
16043 readonly memoryCitation?: ServerNotification__MemoryCitation | null;
16044 readonly phase?: ServerNotification__MessagePhase | null;
16045 readonly text: string;
16046 readonly type: "agentMessage";
16047 }
16048 | { readonly id: string; readonly text: string; readonly type: "plan" }
16049 | {
16050 readonly content?: ReadonlyArray<string>;
16051 readonly id: string;
16052 readonly summary?: ReadonlyArray<string>;
16053 readonly type: "reasoning";
16054 }
16055 | {
16056 readonly aggregatedOutput?: string | null;
16057 readonly command: string;
16058 readonly commandActions: ReadonlyArray<ServerNotification__CommandAction>;
16059 readonly cwd: string;
16060 readonly durationMs?: number | null;
16061 readonly exitCode?: number | null;
16062 readonly id: string;
16063 readonly processId?: string | null;
16064 readonly source?: "agent" | "userShell" | "unifiedExecStartup" | "unifiedExecInteraction";
16065 readonly status: ServerNotification__CommandExecutionStatus;
16066 readonly type: "commandExecution";
16067 }
16068 | {
16069 readonly changes: ReadonlyArray<ServerNotification__FileUpdateChange>;
16070 readonly id: string;
16071 readonly status: ServerNotification__PatchApplyStatus;
16072 readonly type: "fileChange";
16073 }
16074 | {
16075 readonly arguments: unknown;
16076 readonly durationMs?: number | null;
16077 readonly error?: ServerNotification__McpToolCallError | null;
16078 readonly id: string;
16079 readonly result?: ServerNotification__McpToolCallResult | null;
16080 readonly server: string;
16081 readonly status: ServerNotification__McpToolCallStatus;
16082 readonly tool: string;
16083 readonly type: "mcpToolCall";
16084 }
16085 | {
16086 readonly arguments: unknown;
16087 readonly contentItems?: ReadonlyArray<ServerNotification__DynamicToolCallOutputContentItem> | null;
16088 readonly durationMs?: number | null;
16089 readonly id: string;
16090 readonly status: ServerNotification__DynamicToolCallStatus;
16091 readonly success?: boolean | null;
16092 readonly tool: string;
16093 readonly type: "dynamicToolCall";
16094 }
16095 | {
16096 readonly agentsStates: { readonly [x: string]: ServerNotification__CollabAgentState };
16097 readonly id: string;
16098 readonly model?: string | null;
16099 readonly prompt?: string | null;
16100 readonly reasoningEffort?: ServerNotification__ReasoningEffort | null;
16101 readonly receiverThreadIds: ReadonlyArray<string>;
16102 readonly senderThreadId: string;
16103 readonly status: "inProgress" | "completed" | "failed";
16104 readonly tool: "spawnAgent" | "sendInput" | "resumeAgent" | "wait" | "closeAgent";
16105 readonly type: "collabAgentToolCall";
16106 }
16107 | {
16108 readonly action?: ServerNotification__WebSearchAction | null;
16109 readonly id: string;
16110 readonly query: string;
16111 readonly type: "webSearch";
16112 }
16113 | { readonly id: string; readonly path: string; readonly type: "imageView" }
16114 | {
16115 readonly id: string;
16116 readonly result: string;
16117 readonly revisedPrompt?: string | null;
16118 readonly savedPath?: string | null;
16119 readonly status: string;
16120 readonly type: "imageGeneration";
16121 }
16122 | { readonly id: string; readonly review: string; readonly type: "enteredReviewMode" }
16123 | { readonly id: string; readonly review: string; readonly type: "exitedReviewMode" }
16124 | { readonly id: string; readonly type: "contextCompaction" };
16125export const ServerNotification__ThreadItem = Schema.Union(
16126 [
16127 Schema.Struct({
16128 content: Schema.Array(ServerNotification__UserInput),
16129 id: Schema.String,
16130 type: Schema.Literal("userMessage").annotate({ title: "UserMessageThreadItemType" }),
16131 }).annotate({ title: "UserMessageThreadItem" }),
16132 Schema.Struct({
16133 fragments: Schema.Array(ServerNotification__HookPromptFragment),
16134 id: Schema.String,
16135 type: Schema.Literal("hookPrompt").annotate({ title: "HookPromptThreadItemType" }),
16136 }).annotate({ title: "HookPromptThreadItem" }),
16137 Schema.Struct({
16138 id: Schema.String,
16139 memoryCitation: Schema.optionalKey(
16140 Schema.Union([ServerNotification__MemoryCitation, Schema.Null]),
16141 ),
16142 phase: Schema.optionalKey(Schema.Union([ServerNotification__MessagePhase, Schema.Null])),
16143 text: Schema.String,
16144 type: Schema.Literal("agentMessage").annotate({ title: "AgentMessageThreadItemType" }),
16145 }).annotate({ title: "AgentMessageThreadItem" }),
16146 Schema.Struct({
16147 id: Schema.String,
16148 text: Schema.String,
16149 type: Schema.Literal("plan").annotate({ title: "PlanThreadItemType" }),
16150 }).annotate({
16151 title: "PlanThreadItem",
16152 description:
16153 "EXPERIMENTAL - proposed plan item content. The completed plan item is authoritative and may not match the concatenation of `PlanDelta` text.",
16154 }),
16155 Schema.Struct({
16156 content: Schema.optionalKey(Schema.Array(Schema.String).annotate({ default: [] })),
16157 id: Schema.String,
16158 summary: Schema.optionalKey(Schema.Array(Schema.String).annotate({ default: [] })),
16159 type: Schema.Literal("reasoning").annotate({ title: "ReasoningThreadItemType" }),
16160 }).annotate({ title: "ReasoningThreadItem" }),
16161 Schema.Struct({
16162 aggregatedOutput: Schema.optionalKey(
16163 Schema.Union([
16164 Schema.String.annotate({
16165 description: "The command's output, aggregated from stdout and stderr.",
16166 }),
16167 Schema.Null,
16168 ]),
16169 ),
16170 command: Schema.String.annotate({ description: "The command to be executed." }),
16171 commandActions: Schema.Array(ServerNotification__CommandAction).annotate({
16172 description:
16173 "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.",
16174 }),
16175 cwd: Schema.String.annotate({ description: "The command's working directory." }),
16176 durationMs: Schema.optionalKey(
16177 Schema.Union([
16178 Schema.Number.annotate({
16179 description: "The duration of the command execution in milliseconds.",
16180 format: "int64",
16181 }).check(Schema.isInt()),
16182 Schema.Null,
16183 ]),
16184 ),
16185 exitCode: Schema.optionalKey(
16186 Schema.Union([
16187 Schema.Number.annotate({
16188 description: "The command's exit code.",
16189 format: "int32",
16190 }).check(Schema.isInt()),
16191 Schema.Null,
16192 ]),
16193 ),
16194 id: Schema.String,
16195 processId: Schema.optionalKey(
16196 Schema.Union([
16197 Schema.String.annotate({
16198 description: "Identifier for the underlying PTY process (when available).",
16199 }),
16200 Schema.Null,
16201 ]),
16202 ),
16203 source: Schema.optionalKey(
16204 Schema.Literals([
16205 "agent",
16206 "userShell",
16207 "unifiedExecStartup",
16208 "unifiedExecInteraction",
16209 ]).annotate({ default: "agent" }),
16210 ),
16211 status: ServerNotification__CommandExecutionStatus,
16212 type: Schema.Literal("commandExecution").annotate({
16213 title: "CommandExecutionThreadItemType",
16214 }),
16215 }).annotate({ title: "CommandExecutionThreadItem" }),
16216 Schema.Struct({
16217 changes: Schema.Array(ServerNotification__FileUpdateChange),
16218 id: Schema.String,
16219 status: ServerNotification__PatchApplyStatus,
16220 type: Schema.Literal("fileChange").annotate({ title: "FileChangeThreadItemType" }),
16221 }).annotate({ title: "FileChangeThreadItem" }),
16222 Schema.Struct({
16223 arguments: Schema.Unknown,
16224 durationMs: Schema.optionalKey(
16225 Schema.Union([
16226 Schema.Number.annotate({
16227 description: "The duration of the MCP tool call in milliseconds.",
16228 format: "int64",
16229 }).check(Schema.isInt()),
16230 Schema.Null,
16231 ]),
16232 ),
16233 error: Schema.optionalKey(Schema.Union([ServerNotification__McpToolCallError, Schema.Null])),
16234 id: Schema.String,
16235 result: Schema.optionalKey(
16236 Schema.Union([ServerNotification__McpToolCallResult, Schema.Null]),
16237 ),
16238 server: Schema.String,
16239 status: ServerNotification__McpToolCallStatus,
16240 tool: Schema.String,
16241 type: Schema.Literal("mcpToolCall").annotate({ title: "McpToolCallThreadItemType" }),
16242 }).annotate({ title: "McpToolCallThreadItem" }),
16243 Schema.Struct({
16244 arguments: Schema.Unknown,
16245 contentItems: Schema.optionalKey(
16246 Schema.Union([
16247 Schema.Array(ServerNotification__DynamicToolCallOutputContentItem),
16248 Schema.Null,
16249 ]),
16250 ),
16251 durationMs: Schema.optionalKey(
16252 Schema.Union([
16253 Schema.Number.annotate({
16254 description: "The duration of the dynamic tool call in milliseconds.",
16255 format: "int64",
16256 }).check(Schema.isInt()),
16257 Schema.Null,
16258 ]),
16259 ),
16260 id: Schema.String,
16261 status: ServerNotification__DynamicToolCallStatus,
16262 success: Schema.optionalKey(Schema.Union([Schema.Boolean, Schema.Null])),
16263 tool: Schema.String,
16264 type: Schema.Literal("dynamicToolCall").annotate({ title: "DynamicToolCallThreadItemType" }),
16265 }).annotate({ title: "DynamicToolCallThreadItem" }),
16266 Schema.Struct({
16267 agentsStates: Schema.Record(Schema.String, ServerNotification__CollabAgentState).annotate({
16268 description: "Last known status of the target agents, when available.",
16269 }),
16270 id: Schema.String.annotate({ description: "Unique identifier for this collab tool call." }),
16271 model: Schema.optionalKey(
16272 Schema.Union([
16273 Schema.String.annotate({
16274 description: "Model requested for the spawned agent, when applicable.",
16275 }),
16276 Schema.Null,
16277 ]),
16278 ),
16279 prompt: Schema.optionalKey(
16280 Schema.Union([
16281 Schema.String.annotate({
16282 description: "Prompt text sent as part of the collab tool call, when available.",
16283 }),
16284 Schema.Null,
16285 ]),
16286 ),
16287 reasoningEffort: Schema.optionalKey(
16288 Schema.Union([ServerNotification__ReasoningEffort, Schema.Null]).annotate({
16289 description: "Reasoning effort requested for the spawned agent, when applicable.",
16290 }),
16291 ),
16292 receiverThreadIds: Schema.Array(Schema.String).annotate({
16293 description:
16294 "Thread ID of the receiving agent, when applicable. In case of spawn operation, this corresponds to the newly spawned agent.",
16295 }),
16296 senderThreadId: Schema.String.annotate({
16297 description: "Thread ID of the agent issuing the collab request.",
16298 }),
16299 status: Schema.Literals(["inProgress", "completed", "failed"]).annotate({
16300 description: "Current status of the collab tool call.",
16301 }),
16302 tool: Schema.Literals([
16303 "spawnAgent",
16304 "sendInput",
16305 "resumeAgent",
16306 "wait",
16307 "closeAgent",
16308 ]).annotate({ description: "Name of the collab tool that was invoked." }),
16309 type: Schema.Literal("collabAgentToolCall").annotate({
16310 title: "CollabAgentToolCallThreadItemType",
16311 }),
16312 }).annotate({ title: "CollabAgentToolCallThreadItem" }),
16313 Schema.Struct({
16314 action: Schema.optionalKey(Schema.Union([ServerNotification__WebSearchAction, Schema.Null])),
16315 id: Schema.String,
16316 query: Schema.String,
16317 type: Schema.Literal("webSearch").annotate({ title: "WebSearchThreadItemType" }),
16318 }).annotate({ title: "WebSearchThreadItem" }),
16319 Schema.Struct({
16320 id: Schema.String,
16321 path: Schema.String,
16322 type: Schema.Literal("imageView").annotate({ title: "ImageViewThreadItemType" }),
16323 }).annotate({ title: "ImageViewThreadItem" }),
16324 Schema.Struct({
16325 id: Schema.String,
16326 result: Schema.String,
16327 revisedPrompt: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
16328 savedPath: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
16329 status: Schema.String,
16330 type: Schema.Literal("imageGeneration").annotate({ title: "ImageGenerationThreadItemType" }),
16331 }).annotate({ title: "ImageGenerationThreadItem" }),
16332 Schema.Struct({
16333 id: Schema.String,
16334 review: Schema.String,
16335 type: Schema.Literal("enteredReviewMode").annotate({
16336 title: "EnteredReviewModeThreadItemType",
16337 }),
16338 }).annotate({ title: "EnteredReviewModeThreadItem" }),
16339 Schema.Struct({
16340 id: Schema.String,
16341 review: Schema.String,
16342 type: Schema.Literal("exitedReviewMode").annotate({
16343 title: "ExitedReviewModeThreadItemType",
16344 }),
16345 }).annotate({ title: "ExitedReviewModeThreadItem" }),
16346 Schema.Struct({
16347 id: Schema.String,
16348 type: Schema.Literal("contextCompaction").annotate({
16349 title: "ContextCompactionThreadItemType",
16350 }),
16351 }).annotate({ title: "ContextCompactionThreadItem" }),
16352 ],
16353 { mode: "oneOf" },
16354);
16355
16356export type ServerNotification__ConfigWarningNotification = {
16357 readonly details?: string | null;
16358 readonly path?: string | null;
16359 readonly range?: ServerNotification__TextRange | null;
16360 readonly summary: string;
16361};
16362export const ServerNotification__ConfigWarningNotification = Schema.Struct({
16363 details: Schema.optionalKey(
16364 Schema.Union([
16365 Schema.String.annotate({ description: "Optional extra guidance or error details." }),
16366 Schema.Null,
16367 ]),
16368 ),
16369 path: Schema.optionalKey(
16370 Schema.Union([
16371 Schema.String.annotate({
16372 description: "Optional path to the config file that triggered the warning.",
16373 }),
16374 Schema.Null,
16375 ]),
16376 ),
16377 range: Schema.optionalKey(
16378 Schema.Union([ServerNotification__TextRange, Schema.Null]).annotate({
16379 description: "Optional range for the error location inside the config file.",
16380 }),
16381 ),
16382 summary: Schema.String.annotate({ description: "Concise summary of the warning." }),
16383});
16384
16385export type ServerNotification__ThreadStatusChangedNotification = {
16386 readonly status: ServerNotification__ThreadStatus;
16387 readonly threadId: string;
16388};
16389export const ServerNotification__ThreadStatusChangedNotification = Schema.Struct({
16390 status: ServerNotification__ThreadStatus,
16391 threadId: Schema.String,
16392});
16393
16394export type ServerNotification__ThreadTokenUsageUpdatedNotification = {
16395 readonly threadId: string;
16396 readonly tokenUsage: ServerNotification__ThreadTokenUsage;
16397 readonly turnId: string;
16398};
16399export const ServerNotification__ThreadTokenUsageUpdatedNotification = Schema.Struct({
16400 threadId: Schema.String,
16401 tokenUsage: ServerNotification__ThreadTokenUsage,
16402 turnId: Schema.String,
16403});
16404
16405export type ServerNotification__TurnPlanUpdatedNotification = {
16406 readonly explanation?: string | null;
16407 readonly plan: ReadonlyArray<ServerNotification__TurnPlanStep>;
16408 readonly threadId: string;
16409 readonly turnId: string;
16410};
16411export const ServerNotification__TurnPlanUpdatedNotification = Schema.Struct({
16412 explanation: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
16413 plan: Schema.Array(ServerNotification__TurnPlanStep),
16414 threadId: Schema.String,
16415 turnId: Schema.String,
16416});
16417
16418export type ServerRequest__RequestPermissionProfile = {
16419 readonly fileSystem?: ServerRequest__AdditionalFileSystemPermissions | null;
16420 readonly network?: ServerRequest__AdditionalNetworkPermissions | null;
16421};
16422export const ServerRequest__RequestPermissionProfile = Schema.Struct({
16423 fileSystem: Schema.optionalKey(
16424 Schema.Union([ServerRequest__AdditionalFileSystemPermissions, Schema.Null]),
16425 ),
16426 network: Schema.optionalKey(
16427 Schema.Union([ServerRequest__AdditionalNetworkPermissions, Schema.Null]),
16428 ),
16429});
16430
16431export type ServerRequest__McpElicitationTitledMultiSelectEnumSchema = {
16432 readonly default?: ReadonlyArray<string> | null;
16433 readonly description?: string | null;
16434 readonly items: ServerRequest__McpElicitationTitledEnumItems;
16435 readonly maxItems?: number | null;
16436 readonly minItems?: number | null;
16437 readonly title?: string | null;
16438 readonly type: ServerRequest__McpElicitationArrayType;
16439};
16440export const ServerRequest__McpElicitationTitledMultiSelectEnumSchema = Schema.Struct({
16441 default: Schema.optionalKey(Schema.Union([Schema.Array(Schema.String), Schema.Null])),
16442 description: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
16443 items: ServerRequest__McpElicitationTitledEnumItems,
16444 maxItems: Schema.optionalKey(
16445 Schema.Union([
16446 Schema.Number.annotate({ format: "uint64" })
16447 .check(Schema.isInt())
16448 .check(Schema.isGreaterThanOrEqualTo(0)),
16449 Schema.Null,
16450 ]),
16451 ),
16452 minItems: Schema.optionalKey(
16453 Schema.Union([
16454 Schema.Number.annotate({ format: "uint64" })
16455 .check(Schema.isInt())
16456 .check(Schema.isGreaterThanOrEqualTo(0)),
16457 Schema.Null,
16458 ]),
16459 ),
16460 title: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
16461 type: ServerRequest__McpElicitationArrayType,
16462});
16463
16464export type ServerRequest__McpElicitationUntitledMultiSelectEnumSchema = {
16465 readonly default?: ReadonlyArray<string> | null;
16466 readonly description?: string | null;
16467 readonly items: ServerRequest__McpElicitationUntitledEnumItems;
16468 readonly maxItems?: number | null;
16469 readonly minItems?: number | null;
16470 readonly title?: string | null;
16471 readonly type: ServerRequest__McpElicitationArrayType;
16472};
16473export const ServerRequest__McpElicitationUntitledMultiSelectEnumSchema = Schema.Struct({
16474 default: Schema.optionalKey(Schema.Union([Schema.Array(Schema.String), Schema.Null])),
16475 description: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
16476 items: ServerRequest__McpElicitationUntitledEnumItems,
16477 maxItems: Schema.optionalKey(
16478 Schema.Union([
16479 Schema.Number.annotate({ format: "uint64" })
16480 .check(Schema.isInt())
16481 .check(Schema.isGreaterThanOrEqualTo(0)),
16482 Schema.Null,
16483 ]),
16484 ),
16485 minItems: Schema.optionalKey(
16486 Schema.Union([
16487 Schema.Number.annotate({ format: "uint64" })
16488 .check(Schema.isInt())
16489 .check(Schema.isGreaterThanOrEqualTo(0)),
16490 Schema.Null,
16491 ]),
16492 ),
16493 title: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
16494 type: ServerRequest__McpElicitationArrayType,
16495});
16496
16497export type ServerRequest__McpElicitationSingleSelectEnumSchema =
16498 | ServerRequest__McpElicitationUntitledSingleSelectEnumSchema
16499 | ServerRequest__McpElicitationTitledSingleSelectEnumSchema;
16500export const ServerRequest__McpElicitationSingleSelectEnumSchema = Schema.Union([
16501 ServerRequest__McpElicitationUntitledSingleSelectEnumSchema,
16502 ServerRequest__McpElicitationTitledSingleSelectEnumSchema,
16503]);
16504
16505export type ServerRequest__CommandExecutionRequestApprovalParams = {
16506 readonly approvalId?: string | null;
16507 readonly command?: string | null;
16508 readonly commandActions?: ReadonlyArray<ServerRequest__CommandAction> | null;
16509 readonly cwd?: string | null;
16510 readonly itemId: string;
16511 readonly networkApprovalContext?: ServerRequest__NetworkApprovalContext | null;
16512 readonly proposedExecpolicyAmendment?: ReadonlyArray<string> | null;
16513 readonly proposedNetworkPolicyAmendments?: ReadonlyArray<ServerRequest__NetworkPolicyAmendment> | null;
16514 readonly reason?: string | null;
16515 readonly threadId: string;
16516 readonly turnId: string;
16517};
16518export const ServerRequest__CommandExecutionRequestApprovalParams = Schema.Struct({
16519 approvalId: Schema.optionalKey(
16520 Schema.Union([
16521 Schema.String.annotate({
16522 description:
16523 "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.",
16524 }),
16525 Schema.Null,
16526 ]),
16527 ),
16528 command: Schema.optionalKey(
16529 Schema.Union([
16530 Schema.String.annotate({ description: "The command to be executed." }),
16531 Schema.Null,
16532 ]),
16533 ),
16534 commandActions: Schema.optionalKey(
16535 Schema.Union([
16536 Schema.Array(ServerRequest__CommandAction).annotate({
16537 description: "Best-effort parsed command actions for friendly display.",
16538 }),
16539 Schema.Null,
16540 ]),
16541 ),
16542 cwd: Schema.optionalKey(
16543 Schema.Union([
16544 Schema.String.annotate({ description: "The command's working directory." }),
16545 Schema.Null,
16546 ]),
16547 ),
16548 itemId: Schema.String,
16549 networkApprovalContext: Schema.optionalKey(
16550 Schema.Union([ServerRequest__NetworkApprovalContext, Schema.Null]).annotate({
16551 description: "Optional context for a managed-network approval prompt.",
16552 }),
16553 ),
16554 proposedExecpolicyAmendment: Schema.optionalKey(
16555 Schema.Union([
16556 Schema.Array(Schema.String).annotate({
16557 description:
16558 "Optional proposed execpolicy amendment to allow similar commands without prompting.",
16559 }),
16560 Schema.Null,
16561 ]),
16562 ),
16563 proposedNetworkPolicyAmendments: Schema.optionalKey(
16564 Schema.Union([
16565 Schema.Array(ServerRequest__NetworkPolicyAmendment).annotate({
16566 description:
16567 "Optional proposed network policy amendments (allow/deny host) for future requests.",
16568 }),
16569 Schema.Null,
16570 ]),
16571 ),
16572 reason: Schema.optionalKey(
16573 Schema.Union([
16574 Schema.String.annotate({
16575 description: "Optional explanatory reason (e.g. request for network access).",
16576 }),
16577 Schema.Null,
16578 ]),
16579 ),
16580 threadId: Schema.String,
16581 turnId: Schema.String,
16582});
16583
16584export type ServerRequest__ToolRequestUserInputParams = {
16585 readonly itemId: string;
16586 readonly questions: ReadonlyArray<ServerRequest__ToolRequestUserInputQuestion>;
16587 readonly threadId: string;
16588 readonly turnId: string;
16589};
16590export const ServerRequest__ToolRequestUserInputParams = Schema.Struct({
16591 itemId: Schema.String,
16592 questions: Schema.Array(ServerRequest__ToolRequestUserInputQuestion),
16593 threadId: Schema.String,
16594 turnId: Schema.String,
16595}).annotate({ description: "EXPERIMENTAL. Params sent with a request_user_input event." });
16596
16597export type V2AppListUpdatedNotification__AppInfo = {
16598 readonly appMetadata?: V2AppListUpdatedNotification__AppMetadata | null;
16599 readonly branding?: V2AppListUpdatedNotification__AppBranding | null;
16600 readonly description?: string | null;
16601 readonly distributionChannel?: string | null;
16602 readonly id: string;
16603 readonly installUrl?: string | null;
16604 readonly isAccessible?: boolean;
16605 readonly isEnabled?: boolean;
16606 readonly labels?: { readonly [x: string]: string } | null;
16607 readonly logoUrl?: string | null;
16608 readonly logoUrlDark?: string | null;
16609 readonly name: string;
16610 readonly pluginDisplayNames?: ReadonlyArray<string>;
16611};
16612export const V2AppListUpdatedNotification__AppInfo = Schema.Struct({
16613 appMetadata: Schema.optionalKey(
16614 Schema.Union([V2AppListUpdatedNotification__AppMetadata, Schema.Null]),
16615 ),
16616 branding: Schema.optionalKey(
16617 Schema.Union([V2AppListUpdatedNotification__AppBranding, Schema.Null]),
16618 ),
16619 description: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
16620 distributionChannel: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
16621 id: Schema.String,
16622 installUrl: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
16623 isAccessible: Schema.optionalKey(Schema.Boolean.annotate({ default: false })),
16624 isEnabled: Schema.optionalKey(
16625 Schema.Boolean.annotate({
16626 description:
16627 "Whether this app is enabled in config.toml. Example: ```toml [apps.bad_app] enabled = false ```",
16628 default: true,
16629 }),
16630 ),
16631 labels: Schema.optionalKey(
16632 Schema.Union([Schema.Record(Schema.String, Schema.String), Schema.Null]),
16633 ),
16634 logoUrl: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
16635 logoUrlDark: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
16636 name: Schema.String,
16637 pluginDisplayNames: Schema.optionalKey(Schema.Array(Schema.String).annotate({ default: [] })),
16638}).annotate({ description: "EXPERIMENTAL - app metadata returned by app-list APIs." });
16639
16640export type V2AppsListResponse__AppInfo = {
16641 readonly appMetadata?: V2AppsListResponse__AppMetadata | null;
16642 readonly branding?: V2AppsListResponse__AppBranding | null;
16643 readonly description?: string | null;
16644 readonly distributionChannel?: string | null;
16645 readonly id: string;
16646 readonly installUrl?: string | null;
16647 readonly isAccessible?: boolean;
16648 readonly isEnabled?: boolean;
16649 readonly labels?: { readonly [x: string]: string } | null;
16650 readonly logoUrl?: string | null;
16651 readonly logoUrlDark?: string | null;
16652 readonly name: string;
16653 readonly pluginDisplayNames?: ReadonlyArray<string>;
16654};
16655export const V2AppsListResponse__AppInfo = Schema.Struct({
16656 appMetadata: Schema.optionalKey(Schema.Union([V2AppsListResponse__AppMetadata, Schema.Null])),
16657 branding: Schema.optionalKey(Schema.Union([V2AppsListResponse__AppBranding, Schema.Null])),
16658 description: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
16659 distributionChannel: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
16660 id: Schema.String,
16661 installUrl: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
16662 isAccessible: Schema.optionalKey(Schema.Boolean.annotate({ default: false })),
16663 isEnabled: Schema.optionalKey(
16664 Schema.Boolean.annotate({
16665 description:
16666 "Whether this app is enabled in config.toml. Example: ```toml [apps.bad_app] enabled = false ```",
16667 default: true,
16668 }),
16669 ),
16670 labels: Schema.optionalKey(
16671 Schema.Union([Schema.Record(Schema.String, Schema.String), Schema.Null]),
16672 ),
16673 logoUrl: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
16674 logoUrlDark: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
16675 name: Schema.String,
16676 pluginDisplayNames: Schema.optionalKey(Schema.Array(Schema.String).annotate({ default: [] })),
16677}).annotate({ description: "EXPERIMENTAL - app metadata returned by app-list APIs." });
16678
16679export type V2ConfigReadResponse__ConfigLayer = {
16680 readonly config: unknown;
16681 readonly disabledReason?: string | null;
16682 readonly name: V2ConfigReadResponse__ConfigLayerSource;
16683 readonly version: string;
16684};
16685export const V2ConfigReadResponse__ConfigLayer = Schema.Struct({
16686 config: Schema.Unknown,
16687 disabledReason: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
16688 name: V2ConfigReadResponse__ConfigLayerSource,
16689 version: Schema.String,
16690});
16691
16692export type V2ConfigReadResponse__ConfigLayerMetadata = {
16693 readonly name: V2ConfigReadResponse__ConfigLayerSource;
16694 readonly version: string;
16695};
16696export const V2ConfigReadResponse__ConfigLayerMetadata = Schema.Struct({
16697 name: V2ConfigReadResponse__ConfigLayerSource,
16698 version: Schema.String,
16699});
16700
16701export type V2ConfigReadResponse__ToolsV2 = {
16702 readonly view_image?: boolean | null;
16703 readonly web_search?: V2ConfigReadResponse__WebSearchToolConfig | null;
16704};
16705export const V2ConfigReadResponse__ToolsV2 = Schema.Struct({
16706 view_image: Schema.optionalKey(Schema.Union([Schema.Boolean, Schema.Null])),
16707 web_search: Schema.optionalKey(
16708 Schema.Union([V2ConfigReadResponse__WebSearchToolConfig, Schema.Null]),
16709 ),
16710});
16711
16712export type V2ConfigWriteResponse__ConfigLayerMetadata = {
16713 readonly name: V2ConfigWriteResponse__ConfigLayerSource;
16714 readonly version: string;
16715};
16716export const V2ConfigWriteResponse__ConfigLayerMetadata = Schema.Struct({
16717 name: V2ConfigWriteResponse__ConfigLayerSource,
16718 version: Schema.String,
16719});
16720
16721export type V2ErrorNotification__TurnError = {
16722 readonly additionalDetails?: string | null;
16723 readonly codexErrorInfo?: V2ErrorNotification__CodexErrorInfo | null;
16724 readonly message: string;
16725};
16726export const V2ErrorNotification__TurnError = Schema.Struct({
16727 additionalDetails: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
16728 codexErrorInfo: Schema.optionalKey(
16729 Schema.Union([V2ErrorNotification__CodexErrorInfo, Schema.Null]),
16730 ),
16731 message: Schema.String,
16732});
16733
16734export type V2HookCompletedNotification__HookRunSummary = {
16735 readonly completedAt?: number | null;
16736 readonly displayOrder: number;
16737 readonly durationMs?: number | null;
16738 readonly entries: ReadonlyArray<V2HookCompletedNotification__HookOutputEntry>;
16739 readonly eventName: V2HookCompletedNotification__HookEventName;
16740 readonly executionMode: V2HookCompletedNotification__HookExecutionMode;
16741 readonly handlerType: V2HookCompletedNotification__HookHandlerType;
16742 readonly id: string;
16743 readonly scope: V2HookCompletedNotification__HookScope;
16744 readonly sourcePath: string;
16745 readonly startedAt: number;
16746 readonly status: V2HookCompletedNotification__HookRunStatus;
16747 readonly statusMessage?: string | null;
16748};
16749export const V2HookCompletedNotification__HookRunSummary = Schema.Struct({
16750 completedAt: Schema.optionalKey(
16751 Schema.Union([Schema.Number.annotate({ format: "int64" }).check(Schema.isInt()), Schema.Null]),
16752 ),
16753 displayOrder: Schema.Number.annotate({ format: "int64" }).check(Schema.isInt()),
16754 durationMs: Schema.optionalKey(
16755 Schema.Union([Schema.Number.annotate({ format: "int64" }).check(Schema.isInt()), Schema.Null]),
16756 ),
16757 entries: Schema.Array(V2HookCompletedNotification__HookOutputEntry),
16758 eventName: V2HookCompletedNotification__HookEventName,
16759 executionMode: V2HookCompletedNotification__HookExecutionMode,
16760 handlerType: V2HookCompletedNotification__HookHandlerType,
16761 id: Schema.String,
16762 scope: V2HookCompletedNotification__HookScope,
16763 sourcePath: Schema.String,
16764 startedAt: Schema.Number.annotate({ format: "int64" }).check(Schema.isInt()),
16765 status: V2HookCompletedNotification__HookRunStatus,
16766 statusMessage: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
16767});
16768
16769export type V2HookStartedNotification__HookRunSummary = {
16770 readonly completedAt?: number | null;
16771 readonly displayOrder: number;
16772 readonly durationMs?: number | null;
16773 readonly entries: ReadonlyArray<V2HookStartedNotification__HookOutputEntry>;
16774 readonly eventName: V2HookStartedNotification__HookEventName;
16775 readonly executionMode: V2HookStartedNotification__HookExecutionMode;
16776 readonly handlerType: V2HookStartedNotification__HookHandlerType;
16777 readonly id: string;
16778 readonly scope: V2HookStartedNotification__HookScope;
16779 readonly sourcePath: string;
16780 readonly startedAt: number;
16781 readonly status: V2HookStartedNotification__HookRunStatus;
16782 readonly statusMessage?: string | null;
16783};
16784export const V2HookStartedNotification__HookRunSummary = Schema.Struct({
16785 completedAt: Schema.optionalKey(
16786 Schema.Union([Schema.Number.annotate({ format: "int64" }).check(Schema.isInt()), Schema.Null]),
16787 ),
16788 displayOrder: Schema.Number.annotate({ format: "int64" }).check(Schema.isInt()),
16789 durationMs: Schema.optionalKey(
16790 Schema.Union([Schema.Number.annotate({ format: "int64" }).check(Schema.isInt()), Schema.Null]),
16791 ),
16792 entries: Schema.Array(V2HookStartedNotification__HookOutputEntry),
16793 eventName: V2HookStartedNotification__HookEventName,
16794 executionMode: V2HookStartedNotification__HookExecutionMode,
16795 handlerType: V2HookStartedNotification__HookHandlerType,
16796 id: Schema.String,
16797 scope: V2HookStartedNotification__HookScope,
16798 sourcePath: Schema.String,
16799 startedAt: Schema.Number.annotate({ format: "int64" }).check(Schema.isInt()),
16800 status: V2HookStartedNotification__HookRunStatus,
16801 statusMessage: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
16802});
16803
16804export type V2ItemCompletedNotification__ThreadItem =
16805 | {
16806 readonly content: ReadonlyArray<V2ItemCompletedNotification__UserInput>;
16807 readonly id: string;
16808 readonly type: "userMessage";
16809 }
16810 | {
16811 readonly fragments: ReadonlyArray<V2ItemCompletedNotification__HookPromptFragment>;
16812 readonly id: string;
16813 readonly type: "hookPrompt";
16814 }
16815 | {
16816 readonly id: string;
16817 readonly memoryCitation?: V2ItemCompletedNotification__MemoryCitation | null;
16818 readonly phase?: V2ItemCompletedNotification__MessagePhase | null;
16819 readonly text: string;
16820 readonly type: "agentMessage";
16821 }
16822 | { readonly id: string; readonly text: string; readonly type: "plan" }
16823 | {
16824 readonly content?: ReadonlyArray<string>;
16825 readonly id: string;
16826 readonly summary?: ReadonlyArray<string>;
16827 readonly type: "reasoning";
16828 }
16829 | {
16830 readonly aggregatedOutput?: string | null;
16831 readonly command: string;
16832 readonly commandActions: ReadonlyArray<V2ItemCompletedNotification__CommandAction>;
16833 readonly cwd: string;
16834 readonly durationMs?: number | null;
16835 readonly exitCode?: number | null;
16836 readonly id: string;
16837 readonly processId?: string | null;
16838 readonly source?: "agent" | "userShell" | "unifiedExecStartup" | "unifiedExecInteraction";
16839 readonly status: V2ItemCompletedNotification__CommandExecutionStatus;
16840 readonly type: "commandExecution";
16841 }
16842 | {
16843 readonly changes: ReadonlyArray<V2ItemCompletedNotification__FileUpdateChange>;
16844 readonly id: string;
16845 readonly status: V2ItemCompletedNotification__PatchApplyStatus;
16846 readonly type: "fileChange";
16847 }
16848 | {
16849 readonly arguments: unknown;
16850 readonly durationMs?: number | null;
16851 readonly error?: V2ItemCompletedNotification__McpToolCallError | null;
16852 readonly id: string;
16853 readonly result?: V2ItemCompletedNotification__McpToolCallResult | null;
16854 readonly server: string;
16855 readonly status: V2ItemCompletedNotification__McpToolCallStatus;
16856 readonly tool: string;
16857 readonly type: "mcpToolCall";
16858 }
16859 | {
16860 readonly arguments: unknown;
16861 readonly contentItems?: ReadonlyArray<V2ItemCompletedNotification__DynamicToolCallOutputContentItem> | null;
16862 readonly durationMs?: number | null;
16863 readonly id: string;
16864 readonly status: V2ItemCompletedNotification__DynamicToolCallStatus;
16865 readonly success?: boolean | null;
16866 readonly tool: string;
16867 readonly type: "dynamicToolCall";
16868 }
16869 | {
16870 readonly agentsStates: {
16871 readonly [x: string]: V2ItemCompletedNotification__CollabAgentState;
16872 };
16873 readonly id: string;
16874 readonly model?: string | null;
16875 readonly prompt?: string | null;
16876 readonly reasoningEffort?: V2ItemCompletedNotification__ReasoningEffort | null;
16877 readonly receiverThreadIds: ReadonlyArray<string>;
16878 readonly senderThreadId: string;
16879 readonly status: "inProgress" | "completed" | "failed";
16880 readonly tool: "spawnAgent" | "sendInput" | "resumeAgent" | "wait" | "closeAgent";
16881 readonly type: "collabAgentToolCall";
16882 }
16883 | {
16884 readonly action?: V2ItemCompletedNotification__WebSearchAction | null;
16885 readonly id: string;
16886 readonly query: string;
16887 readonly type: "webSearch";
16888 }
16889 | { readonly id: string; readonly path: string; readonly type: "imageView" }
16890 | {
16891 readonly id: string;
16892 readonly result: string;
16893 readonly revisedPrompt?: string | null;
16894 readonly savedPath?: string | null;
16895 readonly status: string;
16896 readonly type: "imageGeneration";
16897 }
16898 | { readonly id: string; readonly review: string; readonly type: "enteredReviewMode" }
16899 | { readonly id: string; readonly review: string; readonly type: "exitedReviewMode" }
16900 | { readonly id: string; readonly type: "contextCompaction" };
16901export const V2ItemCompletedNotification__ThreadItem = Schema.Union(
16902 [
16903 Schema.Struct({
16904 content: Schema.Array(V2ItemCompletedNotification__UserInput),
16905 id: Schema.String,
16906 type: Schema.Literal("userMessage").annotate({ title: "UserMessageThreadItemType" }),
16907 }).annotate({ title: "UserMessageThreadItem" }),
16908 Schema.Struct({
16909 fragments: Schema.Array(V2ItemCompletedNotification__HookPromptFragment),
16910 id: Schema.String,
16911 type: Schema.Literal("hookPrompt").annotate({ title: "HookPromptThreadItemType" }),
16912 }).annotate({ title: "HookPromptThreadItem" }),
16913 Schema.Struct({
16914 id: Schema.String,
16915 memoryCitation: Schema.optionalKey(
16916 Schema.Union([V2ItemCompletedNotification__MemoryCitation, Schema.Null]),
16917 ),
16918 phase: Schema.optionalKey(
16919 Schema.Union([V2ItemCompletedNotification__MessagePhase, Schema.Null]),
16920 ),
16921 text: Schema.String,
16922 type: Schema.Literal("agentMessage").annotate({ title: "AgentMessageThreadItemType" }),
16923 }).annotate({ title: "AgentMessageThreadItem" }),
16924 Schema.Struct({
16925 id: Schema.String,
16926 text: Schema.String,
16927 type: Schema.Literal("plan").annotate({ title: "PlanThreadItemType" }),
16928 }).annotate({
16929 title: "PlanThreadItem",
16930 description:
16931 "EXPERIMENTAL - proposed plan item content. The completed plan item is authoritative and may not match the concatenation of `PlanDelta` text.",
16932 }),
16933 Schema.Struct({
16934 content: Schema.optionalKey(Schema.Array(Schema.String).annotate({ default: [] })),
16935 id: Schema.String,
16936 summary: Schema.optionalKey(Schema.Array(Schema.String).annotate({ default: [] })),
16937 type: Schema.Literal("reasoning").annotate({ title: "ReasoningThreadItemType" }),
16938 }).annotate({ title: "ReasoningThreadItem" }),
16939 Schema.Struct({
16940 aggregatedOutput: Schema.optionalKey(
16941 Schema.Union([
16942 Schema.String.annotate({
16943 description: "The command's output, aggregated from stdout and stderr.",
16944 }),
16945 Schema.Null,
16946 ]),
16947 ),
16948 command: Schema.String.annotate({ description: "The command to be executed." }),
16949 commandActions: Schema.Array(V2ItemCompletedNotification__CommandAction).annotate({
16950 description:
16951 "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.",
16952 }),
16953 cwd: Schema.String.annotate({ description: "The command's working directory." }),
16954 durationMs: Schema.optionalKey(
16955 Schema.Union([
16956 Schema.Number.annotate({
16957 description: "The duration of the command execution in milliseconds.",
16958 format: "int64",
16959 }).check(Schema.isInt()),
16960 Schema.Null,
16961 ]),
16962 ),
16963 exitCode: Schema.optionalKey(
16964 Schema.Union([
16965 Schema.Number.annotate({
16966 description: "The command's exit code.",
16967 format: "int32",
16968 }).check(Schema.isInt()),
16969 Schema.Null,
16970 ]),
16971 ),
16972 id: Schema.String,
16973 processId: Schema.optionalKey(
16974 Schema.Union([
16975 Schema.String.annotate({
16976 description: "Identifier for the underlying PTY process (when available).",
16977 }),
16978 Schema.Null,
16979 ]),
16980 ),
16981 source: Schema.optionalKey(
16982 Schema.Literals([
16983 "agent",
16984 "userShell",
16985 "unifiedExecStartup",
16986 "unifiedExecInteraction",
16987 ]).annotate({ default: "agent" }),
16988 ),
16989 status: V2ItemCompletedNotification__CommandExecutionStatus,
16990 type: Schema.Literal("commandExecution").annotate({
16991 title: "CommandExecutionThreadItemType",
16992 }),
16993 }).annotate({ title: "CommandExecutionThreadItem" }),
16994 Schema.Struct({
16995 changes: Schema.Array(V2ItemCompletedNotification__FileUpdateChange),
16996 id: Schema.String,
16997 status: V2ItemCompletedNotification__PatchApplyStatus,
16998 type: Schema.Literal("fileChange").annotate({ title: "FileChangeThreadItemType" }),
16999 }).annotate({ title: "FileChangeThreadItem" }),
17000 Schema.Struct({
17001 arguments: Schema.Unknown,
17002 durationMs: Schema.optionalKey(
17003 Schema.Union([
17004 Schema.Number.annotate({
17005 description: "The duration of the MCP tool call in milliseconds.",
17006 format: "int64",
17007 }).check(Schema.isInt()),
17008 Schema.Null,
17009 ]),
17010 ),
17011 error: Schema.optionalKey(
17012 Schema.Union([V2ItemCompletedNotification__McpToolCallError, Schema.Null]),
17013 ),
17014 id: Schema.String,
17015 result: Schema.optionalKey(
17016 Schema.Union([V2ItemCompletedNotification__McpToolCallResult, Schema.Null]),
17017 ),
17018 server: Schema.String,
17019 status: V2ItemCompletedNotification__McpToolCallStatus,
17020 tool: Schema.String,
17021 type: Schema.Literal("mcpToolCall").annotate({ title: "McpToolCallThreadItemType" }),
17022 }).annotate({ title: "McpToolCallThreadItem" }),
17023 Schema.Struct({
17024 arguments: Schema.Unknown,
17025 contentItems: Schema.optionalKey(
17026 Schema.Union([
17027 Schema.Array(V2ItemCompletedNotification__DynamicToolCallOutputContentItem),
17028 Schema.Null,
17029 ]),
17030 ),
17031 durationMs: Schema.optionalKey(
17032 Schema.Union([
17033 Schema.Number.annotate({
17034 description: "The duration of the dynamic tool call in milliseconds.",
17035 format: "int64",
17036 }).check(Schema.isInt()),
17037 Schema.Null,
17038 ]),
17039 ),
17040 id: Schema.String,
17041 status: V2ItemCompletedNotification__DynamicToolCallStatus,
17042 success: Schema.optionalKey(Schema.Union([Schema.Boolean, Schema.Null])),
17043 tool: Schema.String,
17044 type: Schema.Literal("dynamicToolCall").annotate({ title: "DynamicToolCallThreadItemType" }),
17045 }).annotate({ title: "DynamicToolCallThreadItem" }),
17046 Schema.Struct({
17047 agentsStates: Schema.Record(
17048 Schema.String,
17049 V2ItemCompletedNotification__CollabAgentState,
17050 ).annotate({ description: "Last known status of the target agents, when available." }),
17051 id: Schema.String.annotate({ description: "Unique identifier for this collab tool call." }),
17052 model: Schema.optionalKey(
17053 Schema.Union([
17054 Schema.String.annotate({
17055 description: "Model requested for the spawned agent, when applicable.",
17056 }),
17057 Schema.Null,
17058 ]),
17059 ),
17060 prompt: Schema.optionalKey(
17061 Schema.Union([
17062 Schema.String.annotate({
17063 description: "Prompt text sent as part of the collab tool call, when available.",
17064 }),
17065 Schema.Null,
17066 ]),
17067 ),
17068 reasoningEffort: Schema.optionalKey(
17069 Schema.Union([V2ItemCompletedNotification__ReasoningEffort, Schema.Null]).annotate({
17070 description: "Reasoning effort requested for the spawned agent, when applicable.",
17071 }),
17072 ),
17073 receiverThreadIds: Schema.Array(Schema.String).annotate({
17074 description:
17075 "Thread ID of the receiving agent, when applicable. In case of spawn operation, this corresponds to the newly spawned agent.",
17076 }),
17077 senderThreadId: Schema.String.annotate({
17078 description: "Thread ID of the agent issuing the collab request.",
17079 }),
17080 status: Schema.Literals(["inProgress", "completed", "failed"]).annotate({
17081 description: "Current status of the collab tool call.",
17082 }),
17083 tool: Schema.Literals([
17084 "spawnAgent",
17085 "sendInput",
17086 "resumeAgent",
17087 "wait",
17088 "closeAgent",
17089 ]).annotate({ description: "Name of the collab tool that was invoked." }),
17090 type: Schema.Literal("collabAgentToolCall").annotate({
17091 title: "CollabAgentToolCallThreadItemType",
17092 }),
17093 }).annotate({ title: "CollabAgentToolCallThreadItem" }),
17094 Schema.Struct({
17095 action: Schema.optionalKey(
17096 Schema.Union([V2ItemCompletedNotification__WebSearchAction, Schema.Null]),
17097 ),
17098 id: Schema.String,
17099 query: Schema.String,
17100 type: Schema.Literal("webSearch").annotate({ title: "WebSearchThreadItemType" }),
17101 }).annotate({ title: "WebSearchThreadItem" }),
17102 Schema.Struct({
17103 id: Schema.String,
17104 path: Schema.String,
17105 type: Schema.Literal("imageView").annotate({ title: "ImageViewThreadItemType" }),
17106 }).annotate({ title: "ImageViewThreadItem" }),
17107 Schema.Struct({
17108 id: Schema.String,
17109 result: Schema.String,
17110 revisedPrompt: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
17111 savedPath: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
17112 status: Schema.String,
17113 type: Schema.Literal("imageGeneration").annotate({ title: "ImageGenerationThreadItemType" }),
17114 }).annotate({ title: "ImageGenerationThreadItem" }),
17115 Schema.Struct({
17116 id: Schema.String,
17117 review: Schema.String,
17118 type: Schema.Literal("enteredReviewMode").annotate({
17119 title: "EnteredReviewModeThreadItemType",
17120 }),
17121 }).annotate({ title: "EnteredReviewModeThreadItem" }),
17122 Schema.Struct({
17123 id: Schema.String,
17124 review: Schema.String,
17125 type: Schema.Literal("exitedReviewMode").annotate({
17126 title: "ExitedReviewModeThreadItemType",
17127 }),
17128 }).annotate({ title: "ExitedReviewModeThreadItem" }),
17129 Schema.Struct({
17130 id: Schema.String,
17131 type: Schema.Literal("contextCompaction").annotate({
17132 title: "ContextCompactionThreadItemType",
17133 }),
17134 }).annotate({ title: "ContextCompactionThreadItem" }),
17135 ],
17136 { mode: "oneOf" },
17137);
17138
17139export type V2ItemStartedNotification__ThreadItem =
17140 | {
17141 readonly content: ReadonlyArray<V2ItemStartedNotification__UserInput>;
17142 readonly id: string;
17143 readonly type: "userMessage";
17144 }
17145 | {
17146 readonly fragments: ReadonlyArray<V2ItemStartedNotification__HookPromptFragment>;
17147 readonly id: string;
17148 readonly type: "hookPrompt";
17149 }
17150 | {
17151 readonly id: string;
17152 readonly memoryCitation?: V2ItemStartedNotification__MemoryCitation | null;
17153 readonly phase?: V2ItemStartedNotification__MessagePhase | null;
17154 readonly text: string;
17155 readonly type: "agentMessage";
17156 }
17157 | { readonly id: string; readonly text: string; readonly type: "plan" }
17158 | {
17159 readonly content?: ReadonlyArray<string>;
17160 readonly id: string;
17161 readonly summary?: ReadonlyArray<string>;
17162 readonly type: "reasoning";
17163 }
17164 | {
17165 readonly aggregatedOutput?: string | null;
17166 readonly command: string;
17167 readonly commandActions: ReadonlyArray<V2ItemStartedNotification__CommandAction>;
17168 readonly cwd: string;
17169 readonly durationMs?: number | null;
17170 readonly exitCode?: number | null;
17171 readonly id: string;
17172 readonly processId?: string | null;
17173 readonly source?: "agent" | "userShell" | "unifiedExecStartup" | "unifiedExecInteraction";
17174 readonly status: V2ItemStartedNotification__CommandExecutionStatus;
17175 readonly type: "commandExecution";
17176 }
17177 | {
17178 readonly changes: ReadonlyArray<V2ItemStartedNotification__FileUpdateChange>;
17179 readonly id: string;
17180 readonly status: V2ItemStartedNotification__PatchApplyStatus;
17181 readonly type: "fileChange";
17182 }
17183 | {
17184 readonly arguments: unknown;
17185 readonly durationMs?: number | null;
17186 readonly error?: V2ItemStartedNotification__McpToolCallError | null;
17187 readonly id: string;
17188 readonly result?: V2ItemStartedNotification__McpToolCallResult | null;
17189 readonly server: string;
17190 readonly status: V2ItemStartedNotification__McpToolCallStatus;
17191 readonly tool: string;
17192 readonly type: "mcpToolCall";
17193 }
17194 | {
17195 readonly arguments: unknown;
17196 readonly contentItems?: ReadonlyArray<V2ItemStartedNotification__DynamicToolCallOutputContentItem> | null;
17197 readonly durationMs?: number | null;
17198 readonly id: string;
17199 readonly status: V2ItemStartedNotification__DynamicToolCallStatus;
17200 readonly success?: boolean | null;
17201 readonly tool: string;
17202 readonly type: "dynamicToolCall";
17203 }
17204 | {
17205 readonly agentsStates: { readonly [x: string]: V2ItemStartedNotification__CollabAgentState };
17206 readonly id: string;
17207 readonly model?: string | null;
17208 readonly prompt?: string | null;
17209 readonly reasoningEffort?: V2ItemStartedNotification__ReasoningEffort | null;
17210 readonly receiverThreadIds: ReadonlyArray<string>;
17211 readonly senderThreadId: string;
17212 readonly status: "inProgress" | "completed" | "failed";
17213 readonly tool: "spawnAgent" | "sendInput" | "resumeAgent" | "wait" | "closeAgent";
17214 readonly type: "collabAgentToolCall";
17215 }
17216 | {
17217 readonly action?: V2ItemStartedNotification__WebSearchAction | null;
17218 readonly id: string;
17219 readonly query: string;
17220 readonly type: "webSearch";
17221 }
17222 | { readonly id: string; readonly path: string; readonly type: "imageView" }
17223 | {
17224 readonly id: string;
17225 readonly result: string;
17226 readonly revisedPrompt?: string | null;
17227 readonly savedPath?: string | null;
17228 readonly status: string;
17229 readonly type: "imageGeneration";
17230 }
17231 | { readonly id: string; readonly review: string; readonly type: "enteredReviewMode" }
17232 | { readonly id: string; readonly review: string; readonly type: "exitedReviewMode" }
17233 | { readonly id: string; readonly type: "contextCompaction" };
17234export const V2ItemStartedNotification__ThreadItem = Schema.Union(
17235 [
17236 Schema.Struct({
17237 content: Schema.Array(V2ItemStartedNotification__UserInput),
17238 id: Schema.String,
17239 type: Schema.Literal("userMessage").annotate({ title: "UserMessageThreadItemType" }),
17240 }).annotate({ title: "UserMessageThreadItem" }),
17241 Schema.Struct({
17242 fragments: Schema.Array(V2ItemStartedNotification__HookPromptFragment),
17243 id: Schema.String,
17244 type: Schema.Literal("hookPrompt").annotate({ title: "HookPromptThreadItemType" }),
17245 }).annotate({ title: "HookPromptThreadItem" }),
17246 Schema.Struct({
17247 id: Schema.String,
17248 memoryCitation: Schema.optionalKey(
17249 Schema.Union([V2ItemStartedNotification__MemoryCitation, Schema.Null]),
17250 ),
17251 phase: Schema.optionalKey(
17252 Schema.Union([V2ItemStartedNotification__MessagePhase, Schema.Null]),
17253 ),
17254 text: Schema.String,
17255 type: Schema.Literal("agentMessage").annotate({ title: "AgentMessageThreadItemType" }),
17256 }).annotate({ title: "AgentMessageThreadItem" }),
17257 Schema.Struct({
17258 id: Schema.String,
17259 text: Schema.String,
17260 type: Schema.Literal("plan").annotate({ title: "PlanThreadItemType" }),
17261 }).annotate({
17262 title: "PlanThreadItem",
17263 description:
17264 "EXPERIMENTAL - proposed plan item content. The completed plan item is authoritative and may not match the concatenation of `PlanDelta` text.",
17265 }),
17266 Schema.Struct({
17267 content: Schema.optionalKey(Schema.Array(Schema.String).annotate({ default: [] })),
17268 id: Schema.String,
17269 summary: Schema.optionalKey(Schema.Array(Schema.String).annotate({ default: [] })),
17270 type: Schema.Literal("reasoning").annotate({ title: "ReasoningThreadItemType" }),
17271 }).annotate({ title: "ReasoningThreadItem" }),
17272 Schema.Struct({
17273 aggregatedOutput: Schema.optionalKey(
17274 Schema.Union([
17275 Schema.String.annotate({
17276 description: "The command's output, aggregated from stdout and stderr.",
17277 }),
17278 Schema.Null,
17279 ]),
17280 ),
17281 command: Schema.String.annotate({ description: "The command to be executed." }),
17282 commandActions: Schema.Array(V2ItemStartedNotification__CommandAction).annotate({
17283 description:
17284 "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.",
17285 }),
17286 cwd: Schema.String.annotate({ description: "The command's working directory." }),
17287 durationMs: Schema.optionalKey(
17288 Schema.Union([
17289 Schema.Number.annotate({
17290 description: "The duration of the command execution in milliseconds.",
17291 format: "int64",
17292 }).check(Schema.isInt()),
17293 Schema.Null,
17294 ]),
17295 ),
17296 exitCode: Schema.optionalKey(
17297 Schema.Union([
17298 Schema.Number.annotate({
17299 description: "The command's exit code.",
17300 format: "int32",
17301 }).check(Schema.isInt()),
17302 Schema.Null,
17303 ]),
17304 ),
17305 id: Schema.String,
17306 processId: Schema.optionalKey(
17307 Schema.Union([
17308 Schema.String.annotate({
17309 description: "Identifier for the underlying PTY process (when available).",
17310 }),
17311 Schema.Null,
17312 ]),
17313 ),
17314 source: Schema.optionalKey(
17315 Schema.Literals([
17316 "agent",
17317 "userShell",
17318 "unifiedExecStartup",
17319 "unifiedExecInteraction",
17320 ]).annotate({ default: "agent" }),
17321 ),
17322 status: V2ItemStartedNotification__CommandExecutionStatus,
17323 type: Schema.Literal("commandExecution").annotate({
17324 title: "CommandExecutionThreadItemType",
17325 }),
17326 }).annotate({ title: "CommandExecutionThreadItem" }),
17327 Schema.Struct({
17328 changes: Schema.Array(V2ItemStartedNotification__FileUpdateChange),
17329 id: Schema.String,
17330 status: V2ItemStartedNotification__PatchApplyStatus,
17331 type: Schema.Literal("fileChange").annotate({ title: "FileChangeThreadItemType" }),
17332 }).annotate({ title: "FileChangeThreadItem" }),
17333 Schema.Struct({
17334 arguments: Schema.Unknown,
17335 durationMs: Schema.optionalKey(
17336 Schema.Union([
17337 Schema.Number.annotate({
17338 description: "The duration of the MCP tool call in milliseconds.",
17339 format: "int64",
17340 }).check(Schema.isInt()),
17341 Schema.Null,
17342 ]),
17343 ),
17344 error: Schema.optionalKey(
17345 Schema.Union([V2ItemStartedNotification__McpToolCallError, Schema.Null]),
17346 ),
17347 id: Schema.String,
17348 result: Schema.optionalKey(
17349 Schema.Union([V2ItemStartedNotification__McpToolCallResult, Schema.Null]),
17350 ),
17351 server: Schema.String,
17352 status: V2ItemStartedNotification__McpToolCallStatus,
17353 tool: Schema.String,
17354 type: Schema.Literal("mcpToolCall").annotate({ title: "McpToolCallThreadItemType" }),
17355 }).annotate({ title: "McpToolCallThreadItem" }),
17356 Schema.Struct({
17357 arguments: Schema.Unknown,
17358 contentItems: Schema.optionalKey(
17359 Schema.Union([
17360 Schema.Array(V2ItemStartedNotification__DynamicToolCallOutputContentItem),
17361 Schema.Null,
17362 ]),
17363 ),
17364 durationMs: Schema.optionalKey(
17365 Schema.Union([
17366 Schema.Number.annotate({
17367 description: "The duration of the dynamic tool call in milliseconds.",
17368 format: "int64",
17369 }).check(Schema.isInt()),
17370 Schema.Null,
17371 ]),
17372 ),
17373 id: Schema.String,
17374 status: V2ItemStartedNotification__DynamicToolCallStatus,
17375 success: Schema.optionalKey(Schema.Union([Schema.Boolean, Schema.Null])),
17376 tool: Schema.String,
17377 type: Schema.Literal("dynamicToolCall").annotate({ title: "DynamicToolCallThreadItemType" }),
17378 }).annotate({ title: "DynamicToolCallThreadItem" }),
17379 Schema.Struct({
17380 agentsStates: Schema.Record(
17381 Schema.String,
17382 V2ItemStartedNotification__CollabAgentState,
17383 ).annotate({ description: "Last known status of the target agents, when available." }),
17384 id: Schema.String.annotate({ description: "Unique identifier for this collab tool call." }),
17385 model: Schema.optionalKey(
17386 Schema.Union([
17387 Schema.String.annotate({
17388 description: "Model requested for the spawned agent, when applicable.",
17389 }),
17390 Schema.Null,
17391 ]),
17392 ),
17393 prompt: Schema.optionalKey(
17394 Schema.Union([
17395 Schema.String.annotate({
17396 description: "Prompt text sent as part of the collab tool call, when available.",
17397 }),
17398 Schema.Null,
17399 ]),
17400 ),
17401 reasoningEffort: Schema.optionalKey(
17402 Schema.Union([V2ItemStartedNotification__ReasoningEffort, Schema.Null]).annotate({
17403 description: "Reasoning effort requested for the spawned agent, when applicable.",
17404 }),
17405 ),
17406 receiverThreadIds: Schema.Array(Schema.String).annotate({
17407 description:
17408 "Thread ID of the receiving agent, when applicable. In case of spawn operation, this corresponds to the newly spawned agent.",
17409 }),
17410 senderThreadId: Schema.String.annotate({
17411 description: "Thread ID of the agent issuing the collab request.",
17412 }),
17413 status: Schema.Literals(["inProgress", "completed", "failed"]).annotate({
17414 description: "Current status of the collab tool call.",
17415 }),
17416 tool: Schema.Literals([
17417 "spawnAgent",
17418 "sendInput",
17419 "resumeAgent",
17420 "wait",
17421 "closeAgent",
17422 ]).annotate({ description: "Name of the collab tool that was invoked." }),
17423 type: Schema.Literal("collabAgentToolCall").annotate({
17424 title: "CollabAgentToolCallThreadItemType",
17425 }),
17426 }).annotate({ title: "CollabAgentToolCallThreadItem" }),
17427 Schema.Struct({
17428 action: Schema.optionalKey(
17429 Schema.Union([V2ItemStartedNotification__WebSearchAction, Schema.Null]),
17430 ),
17431 id: Schema.String,
17432 query: Schema.String,
17433 type: Schema.Literal("webSearch").annotate({ title: "WebSearchThreadItemType" }),
17434 }).annotate({ title: "WebSearchThreadItem" }),
17435 Schema.Struct({
17436 id: Schema.String,
17437 path: Schema.String,
17438 type: Schema.Literal("imageView").annotate({ title: "ImageViewThreadItemType" }),
17439 }).annotate({ title: "ImageViewThreadItem" }),
17440 Schema.Struct({
17441 id: Schema.String,
17442 result: Schema.String,
17443 revisedPrompt: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
17444 savedPath: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
17445 status: Schema.String,
17446 type: Schema.Literal("imageGeneration").annotate({ title: "ImageGenerationThreadItemType" }),
17447 }).annotate({ title: "ImageGenerationThreadItem" }),
17448 Schema.Struct({
17449 id: Schema.String,
17450 review: Schema.String,
17451 type: Schema.Literal("enteredReviewMode").annotate({
17452 title: "EnteredReviewModeThreadItemType",
17453 }),
17454 }).annotate({ title: "EnteredReviewModeThreadItem" }),
17455 Schema.Struct({
17456 id: Schema.String,
17457 review: Schema.String,
17458 type: Schema.Literal("exitedReviewMode").annotate({
17459 title: "ExitedReviewModeThreadItemType",
17460 }),
17461 }).annotate({ title: "ExitedReviewModeThreadItem" }),
17462 Schema.Struct({
17463 id: Schema.String,
17464 type: Schema.Literal("contextCompaction").annotate({
17465 title: "ContextCompactionThreadItemType",
17466 }),
17467 }).annotate({ title: "ContextCompactionThreadItem" }),
17468 ],
17469 { mode: "oneOf" },
17470);
17471
17472export type V2ModelListResponse__Model = {
17473 readonly additionalSpeedTiers?: ReadonlyArray<string>;
17474 readonly availabilityNux?: V2ModelListResponse__ModelAvailabilityNux | null;
17475 readonly defaultReasoningEffort: V2ModelListResponse__ReasoningEffort;
17476 readonly description: string;
17477 readonly displayName: string;
17478 readonly hidden: boolean;
17479 readonly id: string;
17480 readonly inputModalities?: ReadonlyArray<V2ModelListResponse__InputModality>;
17481 readonly isDefault: boolean;
17482 readonly model: string;
17483 readonly supportedReasoningEfforts: ReadonlyArray<V2ModelListResponse__ReasoningEffortOption>;
17484 readonly supportsPersonality?: boolean;
17485 readonly upgrade?: string | null;
17486 readonly upgradeInfo?: V2ModelListResponse__ModelUpgradeInfo | null;
17487};
17488export const V2ModelListResponse__Model = Schema.Struct({
17489 additionalSpeedTiers: Schema.optionalKey(Schema.Array(Schema.String).annotate({ default: [] })),
17490 availabilityNux: Schema.optionalKey(
17491 Schema.Union([V2ModelListResponse__ModelAvailabilityNux, Schema.Null]),
17492 ),
17493 defaultReasoningEffort: V2ModelListResponse__ReasoningEffort,
17494 description: Schema.String,
17495 displayName: Schema.String,
17496 hidden: Schema.Boolean,
17497 id: Schema.String,
17498 inputModalities: Schema.optionalKey(
17499 Schema.Array(V2ModelListResponse__InputModality).annotate({ default: ["text", "image"] }),
17500 ),
17501 isDefault: Schema.Boolean,
17502 model: Schema.String,
17503 supportedReasoningEfforts: Schema.Array(V2ModelListResponse__ReasoningEffortOption),
17504 supportsPersonality: Schema.optionalKey(Schema.Boolean.annotate({ default: false })),
17505 upgrade: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
17506 upgradeInfo: Schema.optionalKey(
17507 Schema.Union([V2ModelListResponse__ModelUpgradeInfo, Schema.Null]),
17508 ),
17509});
17510
17511export type V2PluginListResponse__PluginSummary = {
17512 readonly authPolicy: V2PluginListResponse__PluginAuthPolicy;
17513 readonly enabled: boolean;
17514 readonly id: string;
17515 readonly installPolicy: V2PluginListResponse__PluginInstallPolicy;
17516 readonly installed: boolean;
17517 readonly interface?: V2PluginListResponse__PluginInterface | null;
17518 readonly name: string;
17519 readonly source: V2PluginListResponse__PluginSource;
17520};
17521export const V2PluginListResponse__PluginSummary = Schema.Struct({
17522 authPolicy: V2PluginListResponse__PluginAuthPolicy,
17523 enabled: Schema.Boolean,
17524 id: Schema.String,
17525 installPolicy: V2PluginListResponse__PluginInstallPolicy,
17526 installed: Schema.Boolean,
17527 interface: Schema.optionalKey(Schema.Union([V2PluginListResponse__PluginInterface, Schema.Null])),
17528 name: Schema.String,
17529 source: V2PluginListResponse__PluginSource,
17530});
17531
17532export type V2PluginReadResponse__PluginSummary = {
17533 readonly authPolicy: V2PluginReadResponse__PluginAuthPolicy;
17534 readonly enabled: boolean;
17535 readonly id: string;
17536 readonly installPolicy: V2PluginReadResponse__PluginInstallPolicy;
17537 readonly installed: boolean;
17538 readonly interface?: V2PluginReadResponse__PluginInterface | null;
17539 readonly name: string;
17540 readonly source: V2PluginReadResponse__PluginSource;
17541};
17542export const V2PluginReadResponse__PluginSummary = Schema.Struct({
17543 authPolicy: V2PluginReadResponse__PluginAuthPolicy,
17544 enabled: Schema.Boolean,
17545 id: Schema.String,
17546 installPolicy: V2PluginReadResponse__PluginInstallPolicy,
17547 installed: Schema.Boolean,
17548 interface: Schema.optionalKey(Schema.Union([V2PluginReadResponse__PluginInterface, Schema.Null])),
17549 name: Schema.String,
17550 source: V2PluginReadResponse__PluginSource,
17551});
17552
17553export type V2RawResponseItemCompletedNotification__FunctionCallOutputBody =
17554 | string
17555 | ReadonlyArray<V2RawResponseItemCompletedNotification__FunctionCallOutputContentItem>;
17556export const V2RawResponseItemCompletedNotification__FunctionCallOutputBody = Schema.Union([
17557 Schema.String,
17558 Schema.Array(V2RawResponseItemCompletedNotification__FunctionCallOutputContentItem),
17559]);
17560
17561export type V2ReviewStartResponse__TurnError = {
17562 readonly additionalDetails?: string | null;
17563 readonly codexErrorInfo?: V2ReviewStartResponse__CodexErrorInfo | null;
17564 readonly message: string;
17565};
17566export const V2ReviewStartResponse__TurnError = Schema.Struct({
17567 additionalDetails: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
17568 codexErrorInfo: Schema.optionalKey(
17569 Schema.Union([V2ReviewStartResponse__CodexErrorInfo, Schema.Null]),
17570 ),
17571 message: Schema.String,
17572});
17573
17574export type V2ReviewStartResponse__ThreadItem =
17575 | {
17576 readonly content: ReadonlyArray<V2ReviewStartResponse__UserInput>;
17577 readonly id: string;
17578 readonly type: "userMessage";
17579 }
17580 | {
17581 readonly fragments: ReadonlyArray<V2ReviewStartResponse__HookPromptFragment>;
17582 readonly id: string;
17583 readonly type: "hookPrompt";
17584 }
17585 | {
17586 readonly id: string;
17587 readonly memoryCitation?: V2ReviewStartResponse__MemoryCitation | null;
17588 readonly phase?: V2ReviewStartResponse__MessagePhase | null;
17589 readonly text: string;
17590 readonly type: "agentMessage";
17591 }
17592 | { readonly id: string; readonly text: string; readonly type: "plan" }
17593 | {
17594 readonly content?: ReadonlyArray<string>;
17595 readonly id: string;
17596 readonly summary?: ReadonlyArray<string>;
17597 readonly type: "reasoning";
17598 }
17599 | {
17600 readonly aggregatedOutput?: string | null;
17601 readonly command: string;
17602 readonly commandActions: ReadonlyArray<V2ReviewStartResponse__CommandAction>;
17603 readonly cwd: string;
17604 readonly durationMs?: number | null;
17605 readonly exitCode?: number | null;
17606 readonly id: string;
17607 readonly processId?: string | null;
17608 readonly source?: "agent" | "userShell" | "unifiedExecStartup" | "unifiedExecInteraction";
17609 readonly status: V2ReviewStartResponse__CommandExecutionStatus;
17610 readonly type: "commandExecution";
17611 }
17612 | {
17613 readonly changes: ReadonlyArray<V2ReviewStartResponse__FileUpdateChange>;
17614 readonly id: string;
17615 readonly status: V2ReviewStartResponse__PatchApplyStatus;
17616 readonly type: "fileChange";
17617 }
17618 | {
17619 readonly arguments: unknown;
17620 readonly durationMs?: number | null;
17621 readonly error?: V2ReviewStartResponse__McpToolCallError | null;
17622 readonly id: string;
17623 readonly result?: V2ReviewStartResponse__McpToolCallResult | null;
17624 readonly server: string;
17625 readonly status: V2ReviewStartResponse__McpToolCallStatus;
17626 readonly tool: string;
17627 readonly type: "mcpToolCall";
17628 }
17629 | {
17630 readonly arguments: unknown;
17631 readonly contentItems?: ReadonlyArray<V2ReviewStartResponse__DynamicToolCallOutputContentItem> | null;
17632 readonly durationMs?: number | null;
17633 readonly id: string;
17634 readonly status: V2ReviewStartResponse__DynamicToolCallStatus;
17635 readonly success?: boolean | null;
17636 readonly tool: string;
17637 readonly type: "dynamicToolCall";
17638 }
17639 | {
17640 readonly agentsStates: { readonly [x: string]: V2ReviewStartResponse__CollabAgentState };
17641 readonly id: string;
17642 readonly model?: string | null;
17643 readonly prompt?: string | null;
17644 readonly reasoningEffort?: V2ReviewStartResponse__ReasoningEffort | null;
17645 readonly receiverThreadIds: ReadonlyArray<string>;
17646 readonly senderThreadId: string;
17647 readonly status: "inProgress" | "completed" | "failed";
17648 readonly tool: "spawnAgent" | "sendInput" | "resumeAgent" | "wait" | "closeAgent";
17649 readonly type: "collabAgentToolCall";
17650 }
17651 | {
17652 readonly action?: V2ReviewStartResponse__WebSearchAction | null;
17653 readonly id: string;
17654 readonly query: string;
17655 readonly type: "webSearch";
17656 }
17657 | { readonly id: string; readonly path: string; readonly type: "imageView" }
17658 | {
17659 readonly id: string;
17660 readonly result: string;
17661 readonly revisedPrompt?: string | null;
17662 readonly savedPath?: string | null;
17663 readonly status: string;
17664 readonly type: "imageGeneration";
17665 }
17666 | { readonly id: string; readonly review: string; readonly type: "enteredReviewMode" }
17667 | { readonly id: string; readonly review: string; readonly type: "exitedReviewMode" }
17668 | { readonly id: string; readonly type: "contextCompaction" };
17669export const V2ReviewStartResponse__ThreadItem = Schema.Union(
17670 [
17671 Schema.Struct({
17672 content: Schema.Array(V2ReviewStartResponse__UserInput),
17673 id: Schema.String,
17674 type: Schema.Literal("userMessage").annotate({ title: "UserMessageThreadItemType" }),
17675 }).annotate({ title: "UserMessageThreadItem" }),
17676 Schema.Struct({
17677 fragments: Schema.Array(V2ReviewStartResponse__HookPromptFragment),
17678 id: Schema.String,
17679 type: Schema.Literal("hookPrompt").annotate({ title: "HookPromptThreadItemType" }),
17680 }).annotate({ title: "HookPromptThreadItem" }),
17681 Schema.Struct({
17682 id: Schema.String,
17683 memoryCitation: Schema.optionalKey(
17684 Schema.Union([V2ReviewStartResponse__MemoryCitation, Schema.Null]),
17685 ),
17686 phase: Schema.optionalKey(Schema.Union([V2ReviewStartResponse__MessagePhase, Schema.Null])),
17687 text: Schema.String,
17688 type: Schema.Literal("agentMessage").annotate({ title: "AgentMessageThreadItemType" }),
17689 }).annotate({ title: "AgentMessageThreadItem" }),
17690 Schema.Struct({
17691 id: Schema.String,
17692 text: Schema.String,
17693 type: Schema.Literal("plan").annotate({ title: "PlanThreadItemType" }),
17694 }).annotate({
17695 title: "PlanThreadItem",
17696 description:
17697 "EXPERIMENTAL - proposed plan item content. The completed plan item is authoritative and may not match the concatenation of `PlanDelta` text.",
17698 }),
17699 Schema.Struct({
17700 content: Schema.optionalKey(Schema.Array(Schema.String).annotate({ default: [] })),
17701 id: Schema.String,
17702 summary: Schema.optionalKey(Schema.Array(Schema.String).annotate({ default: [] })),
17703 type: Schema.Literal("reasoning").annotate({ title: "ReasoningThreadItemType" }),
17704 }).annotate({ title: "ReasoningThreadItem" }),
17705 Schema.Struct({
17706 aggregatedOutput: Schema.optionalKey(
17707 Schema.Union([
17708 Schema.String.annotate({
17709 description: "The command's output, aggregated from stdout and stderr.",
17710 }),
17711 Schema.Null,
17712 ]),
17713 ),
17714 command: Schema.String.annotate({ description: "The command to be executed." }),
17715 commandActions: Schema.Array(V2ReviewStartResponse__CommandAction).annotate({
17716 description:
17717 "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.",
17718 }),
17719 cwd: Schema.String.annotate({ description: "The command's working directory." }),
17720 durationMs: Schema.optionalKey(
17721 Schema.Union([
17722 Schema.Number.annotate({
17723 description: "The duration of the command execution in milliseconds.",
17724 format: "int64",
17725 }).check(Schema.isInt()),
17726 Schema.Null,
17727 ]),
17728 ),
17729 exitCode: Schema.optionalKey(
17730 Schema.Union([
17731 Schema.Number.annotate({
17732 description: "The command's exit code.",
17733 format: "int32",
17734 }).check(Schema.isInt()),
17735 Schema.Null,
17736 ]),
17737 ),
17738 id: Schema.String,
17739 processId: Schema.optionalKey(
17740 Schema.Union([
17741 Schema.String.annotate({
17742 description: "Identifier for the underlying PTY process (when available).",
17743 }),
17744 Schema.Null,
17745 ]),
17746 ),
17747 source: Schema.optionalKey(
17748 Schema.Literals([
17749 "agent",
17750 "userShell",
17751 "unifiedExecStartup",
17752 "unifiedExecInteraction",
17753 ]).annotate({ default: "agent" }),
17754 ),
17755 status: V2ReviewStartResponse__CommandExecutionStatus,
17756 type: Schema.Literal("commandExecution").annotate({
17757 title: "CommandExecutionThreadItemType",
17758 }),
17759 }).annotate({ title: "CommandExecutionThreadItem" }),
17760 Schema.Struct({
17761 changes: Schema.Array(V2ReviewStartResponse__FileUpdateChange),
17762 id: Schema.String,
17763 status: V2ReviewStartResponse__PatchApplyStatus,
17764 type: Schema.Literal("fileChange").annotate({ title: "FileChangeThreadItemType" }),
17765 }).annotate({ title: "FileChangeThreadItem" }),
17766 Schema.Struct({
17767 arguments: Schema.Unknown,
17768 durationMs: Schema.optionalKey(
17769 Schema.Union([
17770 Schema.Number.annotate({
17771 description: "The duration of the MCP tool call in milliseconds.",
17772 format: "int64",
17773 }).check(Schema.isInt()),
17774 Schema.Null,
17775 ]),
17776 ),
17777 error: Schema.optionalKey(
17778 Schema.Union([V2ReviewStartResponse__McpToolCallError, Schema.Null]),
17779 ),
17780 id: Schema.String,
17781 result: Schema.optionalKey(
17782 Schema.Union([V2ReviewStartResponse__McpToolCallResult, Schema.Null]),
17783 ),
17784 server: Schema.String,
17785 status: V2ReviewStartResponse__McpToolCallStatus,
17786 tool: Schema.String,
17787 type: Schema.Literal("mcpToolCall").annotate({ title: "McpToolCallThreadItemType" }),
17788 }).annotate({ title: "McpToolCallThreadItem" }),
17789 Schema.Struct({
17790 arguments: Schema.Unknown,
17791 contentItems: Schema.optionalKey(
17792 Schema.Union([
17793 Schema.Array(V2ReviewStartResponse__DynamicToolCallOutputContentItem),
17794 Schema.Null,
17795 ]),
17796 ),
17797 durationMs: Schema.optionalKey(
17798 Schema.Union([
17799 Schema.Number.annotate({
17800 description: "The duration of the dynamic tool call in milliseconds.",
17801 format: "int64",
17802 }).check(Schema.isInt()),
17803 Schema.Null,
17804 ]),
17805 ),
17806 id: Schema.String,
17807 status: V2ReviewStartResponse__DynamicToolCallStatus,
17808 success: Schema.optionalKey(Schema.Union([Schema.Boolean, Schema.Null])),
17809 tool: Schema.String,
17810 type: Schema.Literal("dynamicToolCall").annotate({ title: "DynamicToolCallThreadItemType" }),
17811 }).annotate({ title: "DynamicToolCallThreadItem" }),
17812 Schema.Struct({
17813 agentsStates: Schema.Record(Schema.String, V2ReviewStartResponse__CollabAgentState).annotate({
17814 description: "Last known status of the target agents, when available.",
17815 }),
17816 id: Schema.String.annotate({ description: "Unique identifier for this collab tool call." }),
17817 model: Schema.optionalKey(
17818 Schema.Union([
17819 Schema.String.annotate({
17820 description: "Model requested for the spawned agent, when applicable.",
17821 }),
17822 Schema.Null,
17823 ]),
17824 ),
17825 prompt: Schema.optionalKey(
17826 Schema.Union([
17827 Schema.String.annotate({
17828 description: "Prompt text sent as part of the collab tool call, when available.",
17829 }),
17830 Schema.Null,
17831 ]),
17832 ),
17833 reasoningEffort: Schema.optionalKey(
17834 Schema.Union([V2ReviewStartResponse__ReasoningEffort, Schema.Null]).annotate({
17835 description: "Reasoning effort requested for the spawned agent, when applicable.",
17836 }),
17837 ),
17838 receiverThreadIds: Schema.Array(Schema.String).annotate({
17839 description:
17840 "Thread ID of the receiving agent, when applicable. In case of spawn operation, this corresponds to the newly spawned agent.",
17841 }),
17842 senderThreadId: Schema.String.annotate({
17843 description: "Thread ID of the agent issuing the collab request.",
17844 }),
17845 status: Schema.Literals(["inProgress", "completed", "failed"]).annotate({
17846 description: "Current status of the collab tool call.",
17847 }),
17848 tool: Schema.Literals([
17849 "spawnAgent",
17850 "sendInput",
17851 "resumeAgent",
17852 "wait",
17853 "closeAgent",
17854 ]).annotate({ description: "Name of the collab tool that was invoked." }),
17855 type: Schema.Literal("collabAgentToolCall").annotate({
17856 title: "CollabAgentToolCallThreadItemType",
17857 }),
17858 }).annotate({ title: "CollabAgentToolCallThreadItem" }),
17859 Schema.Struct({
17860 action: Schema.optionalKey(
17861 Schema.Union([V2ReviewStartResponse__WebSearchAction, Schema.Null]),
17862 ),
17863 id: Schema.String,
17864 query: Schema.String,
17865 type: Schema.Literal("webSearch").annotate({ title: "WebSearchThreadItemType" }),
17866 }).annotate({ title: "WebSearchThreadItem" }),
17867 Schema.Struct({
17868 id: Schema.String,
17869 path: Schema.String,
17870 type: Schema.Literal("imageView").annotate({ title: "ImageViewThreadItemType" }),
17871 }).annotate({ title: "ImageViewThreadItem" }),
17872 Schema.Struct({
17873 id: Schema.String,
17874 result: Schema.String,
17875 revisedPrompt: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
17876 savedPath: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
17877 status: Schema.String,
17878 type: Schema.Literal("imageGeneration").annotate({ title: "ImageGenerationThreadItemType" }),
17879 }).annotate({ title: "ImageGenerationThreadItem" }),
17880 Schema.Struct({
17881 id: Schema.String,
17882 review: Schema.String,
17883 type: Schema.Literal("enteredReviewMode").annotate({
17884 title: "EnteredReviewModeThreadItemType",
17885 }),
17886 }).annotate({ title: "EnteredReviewModeThreadItem" }),
17887 Schema.Struct({
17888 id: Schema.String,
17889 review: Schema.String,
17890 type: Schema.Literal("exitedReviewMode").annotate({
17891 title: "ExitedReviewModeThreadItemType",
17892 }),
17893 }).annotate({ title: "ExitedReviewModeThreadItem" }),
17894 Schema.Struct({
17895 id: Schema.String,
17896 type: Schema.Literal("contextCompaction").annotate({
17897 title: "ContextCompactionThreadItemType",
17898 }),
17899 }).annotate({ title: "ContextCompactionThreadItem" }),
17900 ],
17901 { mode: "oneOf" },
17902);
17903
17904export type V2SkillsListResponse__SkillMetadata = {
17905 readonly dependencies?: V2SkillsListResponse__SkillDependencies | null;
17906 readonly description: string;
17907 readonly enabled: boolean;
17908 readonly interface?: V2SkillsListResponse__SkillInterface | null;
17909 readonly name: string;
17910 readonly path: string;
17911 readonly scope: V2SkillsListResponse__SkillScope;
17912 readonly shortDescription?: string | null;
17913};
17914export const V2SkillsListResponse__SkillMetadata = Schema.Struct({
17915 dependencies: Schema.optionalKey(
17916 Schema.Union([V2SkillsListResponse__SkillDependencies, Schema.Null]),
17917 ),
17918 description: Schema.String,
17919 enabled: Schema.Boolean,
17920 interface: Schema.optionalKey(Schema.Union([V2SkillsListResponse__SkillInterface, Schema.Null])),
17921 name: Schema.String,
17922 path: Schema.String,
17923 scope: V2SkillsListResponse__SkillScope,
17924 shortDescription: Schema.optionalKey(
17925 Schema.Union([
17926 Schema.String.annotate({
17927 description:
17928 "Legacy short_description from SKILL.md. Prefer SKILL.json interface.short_description.",
17929 }),
17930 Schema.Null,
17931 ]),
17932 ),
17933});
17934
17935export type V2ThreadForkResponse__TurnError = {
17936 readonly additionalDetails?: string | null;
17937 readonly codexErrorInfo?: V2ThreadForkResponse__CodexErrorInfo | null;
17938 readonly message: string;
17939};
17940export const V2ThreadForkResponse__TurnError = Schema.Struct({
17941 additionalDetails: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
17942 codexErrorInfo: Schema.optionalKey(
17943 Schema.Union([V2ThreadForkResponse__CodexErrorInfo, Schema.Null]),
17944 ),
17945 message: Schema.String,
17946});
17947
17948export type V2ThreadForkResponse__ThreadItem =
17949 | {
17950 readonly content: ReadonlyArray<V2ThreadForkResponse__UserInput>;
17951 readonly id: string;
17952 readonly type: "userMessage";
17953 }
17954 | {
17955 readonly fragments: ReadonlyArray<V2ThreadForkResponse__HookPromptFragment>;
17956 readonly id: string;
17957 readonly type: "hookPrompt";
17958 }
17959 | {
17960 readonly id: string;
17961 readonly memoryCitation?: V2ThreadForkResponse__MemoryCitation | null;
17962 readonly phase?: V2ThreadForkResponse__MessagePhase | null;
17963 readonly text: string;
17964 readonly type: "agentMessage";
17965 }
17966 | { readonly id: string; readonly text: string; readonly type: "plan" }
17967 | {
17968 readonly content?: ReadonlyArray<string>;
17969 readonly id: string;
17970 readonly summary?: ReadonlyArray<string>;
17971 readonly type: "reasoning";
17972 }
17973 | {
17974 readonly aggregatedOutput?: string | null;
17975 readonly command: string;
17976 readonly commandActions: ReadonlyArray<V2ThreadForkResponse__CommandAction>;
17977 readonly cwd: string;
17978 readonly durationMs?: number | null;
17979 readonly exitCode?: number | null;
17980 readonly id: string;
17981 readonly processId?: string | null;
17982 readonly source?: "agent" | "userShell" | "unifiedExecStartup" | "unifiedExecInteraction";
17983 readonly status: V2ThreadForkResponse__CommandExecutionStatus;
17984 readonly type: "commandExecution";
17985 }
17986 | {
17987 readonly changes: ReadonlyArray<V2ThreadForkResponse__FileUpdateChange>;
17988 readonly id: string;
17989 readonly status: V2ThreadForkResponse__PatchApplyStatus;
17990 readonly type: "fileChange";
17991 }
17992 | {
17993 readonly arguments: unknown;
17994 readonly durationMs?: number | null;
17995 readonly error?: V2ThreadForkResponse__McpToolCallError | null;
17996 readonly id: string;
17997 readonly result?: V2ThreadForkResponse__McpToolCallResult | null;
17998 readonly server: string;
17999 readonly status: V2ThreadForkResponse__McpToolCallStatus;
18000 readonly tool: string;
18001 readonly type: "mcpToolCall";
18002 }
18003 | {
18004 readonly arguments: unknown;
18005 readonly contentItems?: ReadonlyArray<V2ThreadForkResponse__DynamicToolCallOutputContentItem> | null;
18006 readonly durationMs?: number | null;
18007 readonly id: string;
18008 readonly status: V2ThreadForkResponse__DynamicToolCallStatus;
18009 readonly success?: boolean | null;
18010 readonly tool: string;
18011 readonly type: "dynamicToolCall";
18012 }
18013 | {
18014 readonly agentsStates: { readonly [x: string]: V2ThreadForkResponse__CollabAgentState };
18015 readonly id: string;
18016 readonly model?: string | null;
18017 readonly prompt?: string | null;
18018 readonly reasoningEffort?: V2ThreadForkResponse__ReasoningEffort | null;
18019 readonly receiverThreadIds: ReadonlyArray<string>;
18020 readonly senderThreadId: string;
18021 readonly status: "inProgress" | "completed" | "failed";
18022 readonly tool: "spawnAgent" | "sendInput" | "resumeAgent" | "wait" | "closeAgent";
18023 readonly type: "collabAgentToolCall";
18024 }
18025 | {
18026 readonly action?: V2ThreadForkResponse__WebSearchAction | null;
18027 readonly id: string;
18028 readonly query: string;
18029 readonly type: "webSearch";
18030 }
18031 | { readonly id: string; readonly path: string; readonly type: "imageView" }
18032 | {
18033 readonly id: string;
18034 readonly result: string;
18035 readonly revisedPrompt?: string | null;
18036 readonly savedPath?: string | null;
18037 readonly status: string;
18038 readonly type: "imageGeneration";
18039 }
18040 | { readonly id: string; readonly review: string; readonly type: "enteredReviewMode" }
18041 | { readonly id: string; readonly review: string; readonly type: "exitedReviewMode" }
18042 | { readonly id: string; readonly type: "contextCompaction" };
18043export const V2ThreadForkResponse__ThreadItem = Schema.Union(
18044 [
18045 Schema.Struct({
18046 content: Schema.Array(V2ThreadForkResponse__UserInput),
18047 id: Schema.String,
18048 type: Schema.Literal("userMessage").annotate({ title: "UserMessageThreadItemType" }),
18049 }).annotate({ title: "UserMessageThreadItem" }),
18050 Schema.Struct({
18051 fragments: Schema.Array(V2ThreadForkResponse__HookPromptFragment),
18052 id: Schema.String,
18053 type: Schema.Literal("hookPrompt").annotate({ title: "HookPromptThreadItemType" }),
18054 }).annotate({ title: "HookPromptThreadItem" }),
18055 Schema.Struct({
18056 id: Schema.String,
18057 memoryCitation: Schema.optionalKey(
18058 Schema.Union([V2ThreadForkResponse__MemoryCitation, Schema.Null]),
18059 ),
18060 phase: Schema.optionalKey(Schema.Union([V2ThreadForkResponse__MessagePhase, Schema.Null])),
18061 text: Schema.String,
18062 type: Schema.Literal("agentMessage").annotate({ title: "AgentMessageThreadItemType" }),
18063 }).annotate({ title: "AgentMessageThreadItem" }),
18064 Schema.Struct({
18065 id: Schema.String,
18066 text: Schema.String,
18067 type: Schema.Literal("plan").annotate({ title: "PlanThreadItemType" }),
18068 }).annotate({
18069 title: "PlanThreadItem",
18070 description:
18071 "EXPERIMENTAL - proposed plan item content. The completed plan item is authoritative and may not match the concatenation of `PlanDelta` text.",
18072 }),
18073 Schema.Struct({
18074 content: Schema.optionalKey(Schema.Array(Schema.String).annotate({ default: [] })),
18075 id: Schema.String,
18076 summary: Schema.optionalKey(Schema.Array(Schema.String).annotate({ default: [] })),
18077 type: Schema.Literal("reasoning").annotate({ title: "ReasoningThreadItemType" }),
18078 }).annotate({ title: "ReasoningThreadItem" }),
18079 Schema.Struct({
18080 aggregatedOutput: Schema.optionalKey(
18081 Schema.Union([
18082 Schema.String.annotate({
18083 description: "The command's output, aggregated from stdout and stderr.",
18084 }),
18085 Schema.Null,
18086 ]),
18087 ),
18088 command: Schema.String.annotate({ description: "The command to be executed." }),
18089 commandActions: Schema.Array(V2ThreadForkResponse__CommandAction).annotate({
18090 description:
18091 "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.",
18092 }),
18093 cwd: Schema.String.annotate({ description: "The command's working directory." }),
18094 durationMs: Schema.optionalKey(
18095 Schema.Union([
18096 Schema.Number.annotate({
18097 description: "The duration of the command execution in milliseconds.",
18098 format: "int64",
18099 }).check(Schema.isInt()),
18100 Schema.Null,
18101 ]),
18102 ),
18103 exitCode: Schema.optionalKey(
18104 Schema.Union([
18105 Schema.Number.annotate({
18106 description: "The command's exit code.",
18107 format: "int32",
18108 }).check(Schema.isInt()),
18109 Schema.Null,
18110 ]),
18111 ),
18112 id: Schema.String,
18113 processId: Schema.optionalKey(
18114 Schema.Union([
18115 Schema.String.annotate({
18116 description: "Identifier for the underlying PTY process (when available).",
18117 }),
18118 Schema.Null,
18119 ]),
18120 ),
18121 source: Schema.optionalKey(
18122 Schema.Literals([
18123 "agent",
18124 "userShell",
18125 "unifiedExecStartup",
18126 "unifiedExecInteraction",
18127 ]).annotate({ default: "agent" }),
18128 ),
18129 status: V2ThreadForkResponse__CommandExecutionStatus,
18130 type: Schema.Literal("commandExecution").annotate({
18131 title: "CommandExecutionThreadItemType",
18132 }),
18133 }).annotate({ title: "CommandExecutionThreadItem" }),
18134 Schema.Struct({
18135 changes: Schema.Array(V2ThreadForkResponse__FileUpdateChange),
18136 id: Schema.String,
18137 status: V2ThreadForkResponse__PatchApplyStatus,
18138 type: Schema.Literal("fileChange").annotate({ title: "FileChangeThreadItemType" }),
18139 }).annotate({ title: "FileChangeThreadItem" }),
18140 Schema.Struct({
18141 arguments: Schema.Unknown,
18142 durationMs: Schema.optionalKey(
18143 Schema.Union([
18144 Schema.Number.annotate({
18145 description: "The duration of the MCP tool call in milliseconds.",
18146 format: "int64",
18147 }).check(Schema.isInt()),
18148 Schema.Null,
18149 ]),
18150 ),
18151 error: Schema.optionalKey(
18152 Schema.Union([V2ThreadForkResponse__McpToolCallError, Schema.Null]),
18153 ),
18154 id: Schema.String,
18155 result: Schema.optionalKey(
18156 Schema.Union([V2ThreadForkResponse__McpToolCallResult, Schema.Null]),
18157 ),
18158 server: Schema.String,
18159 status: V2ThreadForkResponse__McpToolCallStatus,
18160 tool: Schema.String,
18161 type: Schema.Literal("mcpToolCall").annotate({ title: "McpToolCallThreadItemType" }),
18162 }).annotate({ title: "McpToolCallThreadItem" }),
18163 Schema.Struct({
18164 arguments: Schema.Unknown,
18165 contentItems: Schema.optionalKey(
18166 Schema.Union([
18167 Schema.Array(V2ThreadForkResponse__DynamicToolCallOutputContentItem),
18168 Schema.Null,
18169 ]),
18170 ),
18171 durationMs: Schema.optionalKey(
18172 Schema.Union([
18173 Schema.Number.annotate({
18174 description: "The duration of the dynamic tool call in milliseconds.",
18175 format: "int64",
18176 }).check(Schema.isInt()),
18177 Schema.Null,
18178 ]),
18179 ),
18180 id: Schema.String,
18181 status: V2ThreadForkResponse__DynamicToolCallStatus,
18182 success: Schema.optionalKey(Schema.Union([Schema.Boolean, Schema.Null])),
18183 tool: Schema.String,
18184 type: Schema.Literal("dynamicToolCall").annotate({ title: "DynamicToolCallThreadItemType" }),
18185 }).annotate({ title: "DynamicToolCallThreadItem" }),
18186 Schema.Struct({
18187 agentsStates: Schema.Record(Schema.String, V2ThreadForkResponse__CollabAgentState).annotate({
18188 description: "Last known status of the target agents, when available.",
18189 }),
18190 id: Schema.String.annotate({ description: "Unique identifier for this collab tool call." }),
18191 model: Schema.optionalKey(
18192 Schema.Union([
18193 Schema.String.annotate({
18194 description: "Model requested for the spawned agent, when applicable.",
18195 }),
18196 Schema.Null,
18197 ]),
18198 ),
18199 prompt: Schema.optionalKey(
18200 Schema.Union([
18201 Schema.String.annotate({
18202 description: "Prompt text sent as part of the collab tool call, when available.",
18203 }),
18204 Schema.Null,
18205 ]),
18206 ),
18207 reasoningEffort: Schema.optionalKey(
18208 Schema.Union([V2ThreadForkResponse__ReasoningEffort, Schema.Null]).annotate({
18209 description: "Reasoning effort requested for the spawned agent, when applicable.",
18210 }),
18211 ),
18212 receiverThreadIds: Schema.Array(Schema.String).annotate({
18213 description:
18214 "Thread ID of the receiving agent, when applicable. In case of spawn operation, this corresponds to the newly spawned agent.",
18215 }),
18216 senderThreadId: Schema.String.annotate({
18217 description: "Thread ID of the agent issuing the collab request.",
18218 }),
18219 status: Schema.Literals(["inProgress", "completed", "failed"]).annotate({
18220 description: "Current status of the collab tool call.",
18221 }),
18222 tool: Schema.Literals([
18223 "spawnAgent",
18224 "sendInput",
18225 "resumeAgent",
18226 "wait",
18227 "closeAgent",
18228 ]).annotate({ description: "Name of the collab tool that was invoked." }),
18229 type: Schema.Literal("collabAgentToolCall").annotate({
18230 title: "CollabAgentToolCallThreadItemType",
18231 }),
18232 }).annotate({ title: "CollabAgentToolCallThreadItem" }),
18233 Schema.Struct({
18234 action: Schema.optionalKey(
18235 Schema.Union([V2ThreadForkResponse__WebSearchAction, Schema.Null]),
18236 ),
18237 id: Schema.String,
18238 query: Schema.String,
18239 type: Schema.Literal("webSearch").annotate({ title: "WebSearchThreadItemType" }),
18240 }).annotate({ title: "WebSearchThreadItem" }),
18241 Schema.Struct({
18242 id: Schema.String,
18243 path: Schema.String,
18244 type: Schema.Literal("imageView").annotate({ title: "ImageViewThreadItemType" }),
18245 }).annotate({ title: "ImageViewThreadItem" }),
18246 Schema.Struct({
18247 id: Schema.String,
18248 result: Schema.String,
18249 revisedPrompt: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
18250 savedPath: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
18251 status: Schema.String,
18252 type: Schema.Literal("imageGeneration").annotate({ title: "ImageGenerationThreadItemType" }),
18253 }).annotate({ title: "ImageGenerationThreadItem" }),
18254 Schema.Struct({
18255 id: Schema.String,
18256 review: Schema.String,
18257 type: Schema.Literal("enteredReviewMode").annotate({
18258 title: "EnteredReviewModeThreadItemType",
18259 }),
18260 }).annotate({ title: "EnteredReviewModeThreadItem" }),
18261 Schema.Struct({
18262 id: Schema.String,
18263 review: Schema.String,
18264 type: Schema.Literal("exitedReviewMode").annotate({
18265 title: "ExitedReviewModeThreadItemType",
18266 }),
18267 }).annotate({ title: "ExitedReviewModeThreadItem" }),
18268 Schema.Struct({
18269 id: Schema.String,
18270 type: Schema.Literal("contextCompaction").annotate({
18271 title: "ContextCompactionThreadItemType",
18272 }),
18273 }).annotate({ title: "ContextCompactionThreadItem" }),
18274 ],
18275 { mode: "oneOf" },
18276);
18277
18278export type V2ThreadListResponse__TurnError = {
18279 readonly additionalDetails?: string | null;
18280 readonly codexErrorInfo?: V2ThreadListResponse__CodexErrorInfo | null;
18281 readonly message: string;
18282};
18283export const V2ThreadListResponse__TurnError = Schema.Struct({
18284 additionalDetails: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
18285 codexErrorInfo: Schema.optionalKey(
18286 Schema.Union([V2ThreadListResponse__CodexErrorInfo, Schema.Null]),
18287 ),
18288 message: Schema.String,
18289});
18290
18291export type V2ThreadListResponse__ThreadItem =
18292 | {
18293 readonly content: ReadonlyArray<V2ThreadListResponse__UserInput>;
18294 readonly id: string;
18295 readonly type: "userMessage";
18296 }
18297 | {
18298 readonly fragments: ReadonlyArray<V2ThreadListResponse__HookPromptFragment>;
18299 readonly id: string;
18300 readonly type: "hookPrompt";
18301 }
18302 | {
18303 readonly id: string;
18304 readonly memoryCitation?: V2ThreadListResponse__MemoryCitation | null;
18305 readonly phase?: V2ThreadListResponse__MessagePhase | null;
18306 readonly text: string;
18307 readonly type: "agentMessage";
18308 }
18309 | { readonly id: string; readonly text: string; readonly type: "plan" }
18310 | {
18311 readonly content?: ReadonlyArray<string>;
18312 readonly id: string;
18313 readonly summary?: ReadonlyArray<string>;
18314 readonly type: "reasoning";
18315 }
18316 | {
18317 readonly aggregatedOutput?: string | null;
18318 readonly command: string;
18319 readonly commandActions: ReadonlyArray<V2ThreadListResponse__CommandAction>;
18320 readonly cwd: string;
18321 readonly durationMs?: number | null;
18322 readonly exitCode?: number | null;
18323 readonly id: string;
18324 readonly processId?: string | null;
18325 readonly source?: "agent" | "userShell" | "unifiedExecStartup" | "unifiedExecInteraction";
18326 readonly status: V2ThreadListResponse__CommandExecutionStatus;
18327 readonly type: "commandExecution";
18328 }
18329 | {
18330 readonly changes: ReadonlyArray<V2ThreadListResponse__FileUpdateChange>;
18331 readonly id: string;
18332 readonly status: V2ThreadListResponse__PatchApplyStatus;
18333 readonly type: "fileChange";
18334 }
18335 | {
18336 readonly arguments: unknown;
18337 readonly durationMs?: number | null;
18338 readonly error?: V2ThreadListResponse__McpToolCallError | null;
18339 readonly id: string;
18340 readonly result?: V2ThreadListResponse__McpToolCallResult | null;
18341 readonly server: string;
18342 readonly status: V2ThreadListResponse__McpToolCallStatus;
18343 readonly tool: string;
18344 readonly type: "mcpToolCall";
18345 }
18346 | {
18347 readonly arguments: unknown;
18348 readonly contentItems?: ReadonlyArray<V2ThreadListResponse__DynamicToolCallOutputContentItem> | null;
18349 readonly durationMs?: number | null;
18350 readonly id: string;
18351 readonly status: V2ThreadListResponse__DynamicToolCallStatus;
18352 readonly success?: boolean | null;
18353 readonly tool: string;
18354 readonly type: "dynamicToolCall";
18355 }
18356 | {
18357 readonly agentsStates: { readonly [x: string]: V2ThreadListResponse__CollabAgentState };
18358 readonly id: string;
18359 readonly model?: string | null;
18360 readonly prompt?: string | null;
18361 readonly reasoningEffort?: V2ThreadListResponse__ReasoningEffort | null;
18362 readonly receiverThreadIds: ReadonlyArray<string>;
18363 readonly senderThreadId: string;
18364 readonly status: "inProgress" | "completed" | "failed";
18365 readonly tool: "spawnAgent" | "sendInput" | "resumeAgent" | "wait" | "closeAgent";
18366 readonly type: "collabAgentToolCall";
18367 }
18368 | {
18369 readonly action?: V2ThreadListResponse__WebSearchAction | null;
18370 readonly id: string;
18371 readonly query: string;
18372 readonly type: "webSearch";
18373 }
18374 | { readonly id: string; readonly path: string; readonly type: "imageView" }
18375 | {
18376 readonly id: string;
18377 readonly result: string;
18378 readonly revisedPrompt?: string | null;
18379 readonly savedPath?: string | null;
18380 readonly status: string;
18381 readonly type: "imageGeneration";
18382 }
18383 | { readonly id: string; readonly review: string; readonly type: "enteredReviewMode" }
18384 | { readonly id: string; readonly review: string; readonly type: "exitedReviewMode" }
18385 | { readonly id: string; readonly type: "contextCompaction" };
18386export const V2ThreadListResponse__ThreadItem = Schema.Union(
18387 [
18388 Schema.Struct({
18389 content: Schema.Array(V2ThreadListResponse__UserInput),
18390 id: Schema.String,
18391 type: Schema.Literal("userMessage").annotate({ title: "UserMessageThreadItemType" }),
18392 }).annotate({ title: "UserMessageThreadItem" }),
18393 Schema.Struct({
18394 fragments: Schema.Array(V2ThreadListResponse__HookPromptFragment),
18395 id: Schema.String,
18396 type: Schema.Literal("hookPrompt").annotate({ title: "HookPromptThreadItemType" }),
18397 }).annotate({ title: "HookPromptThreadItem" }),
18398 Schema.Struct({
18399 id: Schema.String,
18400 memoryCitation: Schema.optionalKey(
18401 Schema.Union([V2ThreadListResponse__MemoryCitation, Schema.Null]),
18402 ),
18403 phase: Schema.optionalKey(Schema.Union([V2ThreadListResponse__MessagePhase, Schema.Null])),
18404 text: Schema.String,
18405 type: Schema.Literal("agentMessage").annotate({ title: "AgentMessageThreadItemType" }),
18406 }).annotate({ title: "AgentMessageThreadItem" }),
18407 Schema.Struct({
18408 id: Schema.String,
18409 text: Schema.String,
18410 type: Schema.Literal("plan").annotate({ title: "PlanThreadItemType" }),
18411 }).annotate({
18412 title: "PlanThreadItem",
18413 description:
18414 "EXPERIMENTAL - proposed plan item content. The completed plan item is authoritative and may not match the concatenation of `PlanDelta` text.",
18415 }),
18416 Schema.Struct({
18417 content: Schema.optionalKey(Schema.Array(Schema.String).annotate({ default: [] })),
18418 id: Schema.String,
18419 summary: Schema.optionalKey(Schema.Array(Schema.String).annotate({ default: [] })),
18420 type: Schema.Literal("reasoning").annotate({ title: "ReasoningThreadItemType" }),
18421 }).annotate({ title: "ReasoningThreadItem" }),
18422 Schema.Struct({
18423 aggregatedOutput: Schema.optionalKey(
18424 Schema.Union([
18425 Schema.String.annotate({
18426 description: "The command's output, aggregated from stdout and stderr.",
18427 }),
18428 Schema.Null,
18429 ]),
18430 ),
18431 command: Schema.String.annotate({ description: "The command to be executed." }),
18432 commandActions: Schema.Array(V2ThreadListResponse__CommandAction).annotate({
18433 description:
18434 "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.",
18435 }),
18436 cwd: Schema.String.annotate({ description: "The command's working directory." }),
18437 durationMs: Schema.optionalKey(
18438 Schema.Union([
18439 Schema.Number.annotate({
18440 description: "The duration of the command execution in milliseconds.",
18441 format: "int64",
18442 }).check(Schema.isInt()),
18443 Schema.Null,
18444 ]),
18445 ),
18446 exitCode: Schema.optionalKey(
18447 Schema.Union([
18448 Schema.Number.annotate({
18449 description: "The command's exit code.",
18450 format: "int32",
18451 }).check(Schema.isInt()),
18452 Schema.Null,
18453 ]),
18454 ),
18455 id: Schema.String,
18456 processId: Schema.optionalKey(
18457 Schema.Union([
18458 Schema.String.annotate({
18459 description: "Identifier for the underlying PTY process (when available).",
18460 }),
18461 Schema.Null,
18462 ]),
18463 ),
18464 source: Schema.optionalKey(
18465 Schema.Literals([
18466 "agent",
18467 "userShell",
18468 "unifiedExecStartup",
18469 "unifiedExecInteraction",
18470 ]).annotate({ default: "agent" }),
18471 ),
18472 status: V2ThreadListResponse__CommandExecutionStatus,
18473 type: Schema.Literal("commandExecution").annotate({
18474 title: "CommandExecutionThreadItemType",
18475 }),
18476 }).annotate({ title: "CommandExecutionThreadItem" }),
18477 Schema.Struct({
18478 changes: Schema.Array(V2ThreadListResponse__FileUpdateChange),
18479 id: Schema.String,
18480 status: V2ThreadListResponse__PatchApplyStatus,
18481 type: Schema.Literal("fileChange").annotate({ title: "FileChangeThreadItemType" }),
18482 }).annotate({ title: "FileChangeThreadItem" }),
18483 Schema.Struct({
18484 arguments: Schema.Unknown,
18485 durationMs: Schema.optionalKey(
18486 Schema.Union([
18487 Schema.Number.annotate({
18488 description: "The duration of the MCP tool call in milliseconds.",
18489 format: "int64",
18490 }).check(Schema.isInt()),
18491 Schema.Null,
18492 ]),
18493 ),
18494 error: Schema.optionalKey(
18495 Schema.Union([V2ThreadListResponse__McpToolCallError, Schema.Null]),
18496 ),
18497 id: Schema.String,
18498 result: Schema.optionalKey(
18499 Schema.Union([V2ThreadListResponse__McpToolCallResult, Schema.Null]),
18500 ),
18501 server: Schema.String,
18502 status: V2ThreadListResponse__McpToolCallStatus,
18503 tool: Schema.String,
18504 type: Schema.Literal("mcpToolCall").annotate({ title: "McpToolCallThreadItemType" }),
18505 }).annotate({ title: "McpToolCallThreadItem" }),
18506 Schema.Struct({
18507 arguments: Schema.Unknown,
18508 contentItems: Schema.optionalKey(
18509 Schema.Union([
18510 Schema.Array(V2ThreadListResponse__DynamicToolCallOutputContentItem),
18511 Schema.Null,
18512 ]),
18513 ),
18514 durationMs: Schema.optionalKey(
18515 Schema.Union([
18516 Schema.Number.annotate({
18517 description: "The duration of the dynamic tool call in milliseconds.",
18518 format: "int64",
18519 }).check(Schema.isInt()),
18520 Schema.Null,
18521 ]),
18522 ),
18523 id: Schema.String,
18524 status: V2ThreadListResponse__DynamicToolCallStatus,
18525 success: Schema.optionalKey(Schema.Union([Schema.Boolean, Schema.Null])),
18526 tool: Schema.String,
18527 type: Schema.Literal("dynamicToolCall").annotate({ title: "DynamicToolCallThreadItemType" }),
18528 }).annotate({ title: "DynamicToolCallThreadItem" }),
18529 Schema.Struct({
18530 agentsStates: Schema.Record(Schema.String, V2ThreadListResponse__CollabAgentState).annotate({
18531 description: "Last known status of the target agents, when available.",
18532 }),
18533 id: Schema.String.annotate({ description: "Unique identifier for this collab tool call." }),
18534 model: Schema.optionalKey(
18535 Schema.Union([
18536 Schema.String.annotate({
18537 description: "Model requested for the spawned agent, when applicable.",
18538 }),
18539 Schema.Null,
18540 ]),
18541 ),
18542 prompt: Schema.optionalKey(
18543 Schema.Union([
18544 Schema.String.annotate({
18545 description: "Prompt text sent as part of the collab tool call, when available.",
18546 }),
18547 Schema.Null,
18548 ]),
18549 ),
18550 reasoningEffort: Schema.optionalKey(
18551 Schema.Union([V2ThreadListResponse__ReasoningEffort, Schema.Null]).annotate({
18552 description: "Reasoning effort requested for the spawned agent, when applicable.",
18553 }),
18554 ),
18555 receiverThreadIds: Schema.Array(Schema.String).annotate({
18556 description:
18557 "Thread ID of the receiving agent, when applicable. In case of spawn operation, this corresponds to the newly spawned agent.",
18558 }),
18559 senderThreadId: Schema.String.annotate({
18560 description: "Thread ID of the agent issuing the collab request.",
18561 }),
18562 status: Schema.Literals(["inProgress", "completed", "failed"]).annotate({
18563 description: "Current status of the collab tool call.",
18564 }),
18565 tool: Schema.Literals([
18566 "spawnAgent",
18567 "sendInput",
18568 "resumeAgent",
18569 "wait",
18570 "closeAgent",
18571 ]).annotate({ description: "Name of the collab tool that was invoked." }),
18572 type: Schema.Literal("collabAgentToolCall").annotate({
18573 title: "CollabAgentToolCallThreadItemType",
18574 }),
18575 }).annotate({ title: "CollabAgentToolCallThreadItem" }),
18576 Schema.Struct({
18577 action: Schema.optionalKey(
18578 Schema.Union([V2ThreadListResponse__WebSearchAction, Schema.Null]),
18579 ),
18580 id: Schema.String,
18581 query: Schema.String,
18582 type: Schema.Literal("webSearch").annotate({ title: "WebSearchThreadItemType" }),
18583 }).annotate({ title: "WebSearchThreadItem" }),
18584 Schema.Struct({
18585 id: Schema.String,
18586 path: Schema.String,
18587 type: Schema.Literal("imageView").annotate({ title: "ImageViewThreadItemType" }),
18588 }).annotate({ title: "ImageViewThreadItem" }),
18589 Schema.Struct({
18590 id: Schema.String,
18591 result: Schema.String,
18592 revisedPrompt: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
18593 savedPath: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
18594 status: Schema.String,
18595 type: Schema.Literal("imageGeneration").annotate({ title: "ImageGenerationThreadItemType" }),
18596 }).annotate({ title: "ImageGenerationThreadItem" }),
18597 Schema.Struct({
18598 id: Schema.String,
18599 review: Schema.String,
18600 type: Schema.Literal("enteredReviewMode").annotate({
18601 title: "EnteredReviewModeThreadItemType",
18602 }),
18603 }).annotate({ title: "EnteredReviewModeThreadItem" }),
18604 Schema.Struct({
18605 id: Schema.String,
18606 review: Schema.String,
18607 type: Schema.Literal("exitedReviewMode").annotate({
18608 title: "ExitedReviewModeThreadItemType",
18609 }),
18610 }).annotate({ title: "ExitedReviewModeThreadItem" }),
18611 Schema.Struct({
18612 id: Schema.String,
18613 type: Schema.Literal("contextCompaction").annotate({
18614 title: "ContextCompactionThreadItemType",
18615 }),
18616 }).annotate({ title: "ContextCompactionThreadItem" }),
18617 ],
18618 { mode: "oneOf" },
18619);
18620
18621export type V2ThreadMetadataUpdateResponse__TurnError = {
18622 readonly additionalDetails?: string | null;
18623 readonly codexErrorInfo?: V2ThreadMetadataUpdateResponse__CodexErrorInfo | null;
18624 readonly message: string;
18625};
18626export const V2ThreadMetadataUpdateResponse__TurnError = Schema.Struct({
18627 additionalDetails: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
18628 codexErrorInfo: Schema.optionalKey(
18629 Schema.Union([V2ThreadMetadataUpdateResponse__CodexErrorInfo, Schema.Null]),
18630 ),
18631 message: Schema.String,
18632});
18633
18634export type V2ThreadMetadataUpdateResponse__ThreadItem =
18635 | {
18636 readonly content: ReadonlyArray<V2ThreadMetadataUpdateResponse__UserInput>;
18637 readonly id: string;
18638 readonly type: "userMessage";
18639 }
18640 | {
18641 readonly fragments: ReadonlyArray<V2ThreadMetadataUpdateResponse__HookPromptFragment>;
18642 readonly id: string;
18643 readonly type: "hookPrompt";
18644 }
18645 | {
18646 readonly id: string;
18647 readonly memoryCitation?: V2ThreadMetadataUpdateResponse__MemoryCitation | null;
18648 readonly phase?: V2ThreadMetadataUpdateResponse__MessagePhase | null;
18649 readonly text: string;
18650 readonly type: "agentMessage";
18651 }
18652 | { readonly id: string; readonly text: string; readonly type: "plan" }
18653 | {
18654 readonly content?: ReadonlyArray<string>;
18655 readonly id: string;
18656 readonly summary?: ReadonlyArray<string>;
18657 readonly type: "reasoning";
18658 }
18659 | {
18660 readonly aggregatedOutput?: string | null;
18661 readonly command: string;
18662 readonly commandActions: ReadonlyArray<V2ThreadMetadataUpdateResponse__CommandAction>;
18663 readonly cwd: string;
18664 readonly durationMs?: number | null;
18665 readonly exitCode?: number | null;
18666 readonly id: string;
18667 readonly processId?: string | null;
18668 readonly source?: "agent" | "userShell" | "unifiedExecStartup" | "unifiedExecInteraction";
18669 readonly status: V2ThreadMetadataUpdateResponse__CommandExecutionStatus;
18670 readonly type: "commandExecution";
18671 }
18672 | {
18673 readonly changes: ReadonlyArray<V2ThreadMetadataUpdateResponse__FileUpdateChange>;
18674 readonly id: string;
18675 readonly status: V2ThreadMetadataUpdateResponse__PatchApplyStatus;
18676 readonly type: "fileChange";
18677 }
18678 | {
18679 readonly arguments: unknown;
18680 readonly durationMs?: number | null;
18681 readonly error?: V2ThreadMetadataUpdateResponse__McpToolCallError | null;
18682 readonly id: string;
18683 readonly result?: V2ThreadMetadataUpdateResponse__McpToolCallResult | null;
18684 readonly server: string;
18685 readonly status: V2ThreadMetadataUpdateResponse__McpToolCallStatus;
18686 readonly tool: string;
18687 readonly type: "mcpToolCall";
18688 }
18689 | {
18690 readonly arguments: unknown;
18691 readonly contentItems?: ReadonlyArray<V2ThreadMetadataUpdateResponse__DynamicToolCallOutputContentItem> | null;
18692 readonly durationMs?: number | null;
18693 readonly id: string;
18694 readonly status: V2ThreadMetadataUpdateResponse__DynamicToolCallStatus;
18695 readonly success?: boolean | null;
18696 readonly tool: string;
18697 readonly type: "dynamicToolCall";
18698 }
18699 | {
18700 readonly agentsStates: {
18701 readonly [x: string]: V2ThreadMetadataUpdateResponse__CollabAgentState;
18702 };
18703 readonly id: string;
18704 readonly model?: string | null;
18705 readonly prompt?: string | null;
18706 readonly reasoningEffort?: V2ThreadMetadataUpdateResponse__ReasoningEffort | null;
18707 readonly receiverThreadIds: ReadonlyArray<string>;
18708 readonly senderThreadId: string;
18709 readonly status: "inProgress" | "completed" | "failed";
18710 readonly tool: "spawnAgent" | "sendInput" | "resumeAgent" | "wait" | "closeAgent";
18711 readonly type: "collabAgentToolCall";
18712 }
18713 | {
18714 readonly action?: V2ThreadMetadataUpdateResponse__WebSearchAction | null;
18715 readonly id: string;
18716 readonly query: string;
18717 readonly type: "webSearch";
18718 }
18719 | { readonly id: string; readonly path: string; readonly type: "imageView" }
18720 | {
18721 readonly id: string;
18722 readonly result: string;
18723 readonly revisedPrompt?: string | null;
18724 readonly savedPath?: string | null;
18725 readonly status: string;
18726 readonly type: "imageGeneration";
18727 }
18728 | { readonly id: string; readonly review: string; readonly type: "enteredReviewMode" }
18729 | { readonly id: string; readonly review: string; readonly type: "exitedReviewMode" }
18730 | { readonly id: string; readonly type: "contextCompaction" };
18731export const V2ThreadMetadataUpdateResponse__ThreadItem = Schema.Union(
18732 [
18733 Schema.Struct({
18734 content: Schema.Array(V2ThreadMetadataUpdateResponse__UserInput),
18735 id: Schema.String,
18736 type: Schema.Literal("userMessage").annotate({ title: "UserMessageThreadItemType" }),
18737 }).annotate({ title: "UserMessageThreadItem" }),
18738 Schema.Struct({
18739 fragments: Schema.Array(V2ThreadMetadataUpdateResponse__HookPromptFragment),
18740 id: Schema.String,
18741 type: Schema.Literal("hookPrompt").annotate({ title: "HookPromptThreadItemType" }),
18742 }).annotate({ title: "HookPromptThreadItem" }),
18743 Schema.Struct({
18744 id: Schema.String,
18745 memoryCitation: Schema.optionalKey(
18746 Schema.Union([V2ThreadMetadataUpdateResponse__MemoryCitation, Schema.Null]),
18747 ),
18748 phase: Schema.optionalKey(
18749 Schema.Union([V2ThreadMetadataUpdateResponse__MessagePhase, Schema.Null]),
18750 ),
18751 text: Schema.String,
18752 type: Schema.Literal("agentMessage").annotate({ title: "AgentMessageThreadItemType" }),
18753 }).annotate({ title: "AgentMessageThreadItem" }),
18754 Schema.Struct({
18755 id: Schema.String,
18756 text: Schema.String,
18757 type: Schema.Literal("plan").annotate({ title: "PlanThreadItemType" }),
18758 }).annotate({
18759 title: "PlanThreadItem",
18760 description:
18761 "EXPERIMENTAL - proposed plan item content. The completed plan item is authoritative and may not match the concatenation of `PlanDelta` text.",
18762 }),
18763 Schema.Struct({
18764 content: Schema.optionalKey(Schema.Array(Schema.String).annotate({ default: [] })),
18765 id: Schema.String,
18766 summary: Schema.optionalKey(Schema.Array(Schema.String).annotate({ default: [] })),
18767 type: Schema.Literal("reasoning").annotate({ title: "ReasoningThreadItemType" }),
18768 }).annotate({ title: "ReasoningThreadItem" }),
18769 Schema.Struct({
18770 aggregatedOutput: Schema.optionalKey(
18771 Schema.Union([
18772 Schema.String.annotate({
18773 description: "The command's output, aggregated from stdout and stderr.",
18774 }),
18775 Schema.Null,
18776 ]),
18777 ),
18778 command: Schema.String.annotate({ description: "The command to be executed." }),
18779 commandActions: Schema.Array(V2ThreadMetadataUpdateResponse__CommandAction).annotate({
18780 description:
18781 "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.",
18782 }),
18783 cwd: Schema.String.annotate({ description: "The command's working directory." }),
18784 durationMs: Schema.optionalKey(
18785 Schema.Union([
18786 Schema.Number.annotate({
18787 description: "The duration of the command execution in milliseconds.",
18788 format: "int64",
18789 }).check(Schema.isInt()),
18790 Schema.Null,
18791 ]),
18792 ),
18793 exitCode: Schema.optionalKey(
18794 Schema.Union([
18795 Schema.Number.annotate({
18796 description: "The command's exit code.",
18797 format: "int32",
18798 }).check(Schema.isInt()),
18799 Schema.Null,
18800 ]),
18801 ),
18802 id: Schema.String,
18803 processId: Schema.optionalKey(
18804 Schema.Union([
18805 Schema.String.annotate({
18806 description: "Identifier for the underlying PTY process (when available).",
18807 }),
18808 Schema.Null,
18809 ]),
18810 ),
18811 source: Schema.optionalKey(
18812 Schema.Literals([
18813 "agent",
18814 "userShell",
18815 "unifiedExecStartup",
18816 "unifiedExecInteraction",
18817 ]).annotate({ default: "agent" }),
18818 ),
18819 status: V2ThreadMetadataUpdateResponse__CommandExecutionStatus,
18820 type: Schema.Literal("commandExecution").annotate({
18821 title: "CommandExecutionThreadItemType",
18822 }),
18823 }).annotate({ title: "CommandExecutionThreadItem" }),
18824 Schema.Struct({
18825 changes: Schema.Array(V2ThreadMetadataUpdateResponse__FileUpdateChange),
18826 id: Schema.String,
18827 status: V2ThreadMetadataUpdateResponse__PatchApplyStatus,
18828 type: Schema.Literal("fileChange").annotate({ title: "FileChangeThreadItemType" }),
18829 }).annotate({ title: "FileChangeThreadItem" }),
18830 Schema.Struct({
18831 arguments: Schema.Unknown,
18832 durationMs: Schema.optionalKey(
18833 Schema.Union([
18834 Schema.Number.annotate({
18835 description: "The duration of the MCP tool call in milliseconds.",
18836 format: "int64",
18837 }).check(Schema.isInt()),
18838 Schema.Null,
18839 ]),
18840 ),
18841 error: Schema.optionalKey(
18842 Schema.Union([V2ThreadMetadataUpdateResponse__McpToolCallError, Schema.Null]),
18843 ),
18844 id: Schema.String,
18845 result: Schema.optionalKey(
18846 Schema.Union([V2ThreadMetadataUpdateResponse__McpToolCallResult, Schema.Null]),
18847 ),
18848 server: Schema.String,
18849 status: V2ThreadMetadataUpdateResponse__McpToolCallStatus,
18850 tool: Schema.String,
18851 type: Schema.Literal("mcpToolCall").annotate({ title: "McpToolCallThreadItemType" }),
18852 }).annotate({ title: "McpToolCallThreadItem" }),
18853 Schema.Struct({
18854 arguments: Schema.Unknown,
18855 contentItems: Schema.optionalKey(
18856 Schema.Union([
18857 Schema.Array(V2ThreadMetadataUpdateResponse__DynamicToolCallOutputContentItem),
18858 Schema.Null,
18859 ]),
18860 ),
18861 durationMs: Schema.optionalKey(
18862 Schema.Union([
18863 Schema.Number.annotate({
18864 description: "The duration of the dynamic tool call in milliseconds.",
18865 format: "int64",
18866 }).check(Schema.isInt()),
18867 Schema.Null,
18868 ]),
18869 ),
18870 id: Schema.String,
18871 status: V2ThreadMetadataUpdateResponse__DynamicToolCallStatus,
18872 success: Schema.optionalKey(Schema.Union([Schema.Boolean, Schema.Null])),
18873 tool: Schema.String,
18874 type: Schema.Literal("dynamicToolCall").annotate({ title: "DynamicToolCallThreadItemType" }),
18875 }).annotate({ title: "DynamicToolCallThreadItem" }),
18876 Schema.Struct({
18877 agentsStates: Schema.Record(
18878 Schema.String,
18879 V2ThreadMetadataUpdateResponse__CollabAgentState,
18880 ).annotate({ description: "Last known status of the target agents, when available." }),
18881 id: Schema.String.annotate({ description: "Unique identifier for this collab tool call." }),
18882 model: Schema.optionalKey(
18883 Schema.Union([
18884 Schema.String.annotate({
18885 description: "Model requested for the spawned agent, when applicable.",
18886 }),
18887 Schema.Null,
18888 ]),
18889 ),
18890 prompt: Schema.optionalKey(
18891 Schema.Union([
18892 Schema.String.annotate({
18893 description: "Prompt text sent as part of the collab tool call, when available.",
18894 }),
18895 Schema.Null,
18896 ]),
18897 ),
18898 reasoningEffort: Schema.optionalKey(
18899 Schema.Union([V2ThreadMetadataUpdateResponse__ReasoningEffort, Schema.Null]).annotate({
18900 description: "Reasoning effort requested for the spawned agent, when applicable.",
18901 }),
18902 ),
18903 receiverThreadIds: Schema.Array(Schema.String).annotate({
18904 description:
18905 "Thread ID of the receiving agent, when applicable. In case of spawn operation, this corresponds to the newly spawned agent.",
18906 }),
18907 senderThreadId: Schema.String.annotate({
18908 description: "Thread ID of the agent issuing the collab request.",
18909 }),
18910 status: Schema.Literals(["inProgress", "completed", "failed"]).annotate({
18911 description: "Current status of the collab tool call.",
18912 }),
18913 tool: Schema.Literals([
18914 "spawnAgent",
18915 "sendInput",
18916 "resumeAgent",
18917 "wait",
18918 "closeAgent",
18919 ]).annotate({ description: "Name of the collab tool that was invoked." }),
18920 type: Schema.Literal("collabAgentToolCall").annotate({
18921 title: "CollabAgentToolCallThreadItemType",
18922 }),
18923 }).annotate({ title: "CollabAgentToolCallThreadItem" }),
18924 Schema.Struct({
18925 action: Schema.optionalKey(
18926 Schema.Union([V2ThreadMetadataUpdateResponse__WebSearchAction, Schema.Null]),
18927 ),
18928 id: Schema.String,
18929 query: Schema.String,
18930 type: Schema.Literal("webSearch").annotate({ title: "WebSearchThreadItemType" }),
18931 }).annotate({ title: "WebSearchThreadItem" }),
18932 Schema.Struct({
18933 id: Schema.String,
18934 path: Schema.String,
18935 type: Schema.Literal("imageView").annotate({ title: "ImageViewThreadItemType" }),
18936 }).annotate({ title: "ImageViewThreadItem" }),
18937 Schema.Struct({
18938 id: Schema.String,
18939 result: Schema.String,
18940 revisedPrompt: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
18941 savedPath: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
18942 status: Schema.String,
18943 type: Schema.Literal("imageGeneration").annotate({ title: "ImageGenerationThreadItemType" }),
18944 }).annotate({ title: "ImageGenerationThreadItem" }),
18945 Schema.Struct({
18946 id: Schema.String,
18947 review: Schema.String,
18948 type: Schema.Literal("enteredReviewMode").annotate({
18949 title: "EnteredReviewModeThreadItemType",
18950 }),
18951 }).annotate({ title: "EnteredReviewModeThreadItem" }),
18952 Schema.Struct({
18953 id: Schema.String,
18954 review: Schema.String,
18955 type: Schema.Literal("exitedReviewMode").annotate({
18956 title: "ExitedReviewModeThreadItemType",
18957 }),
18958 }).annotate({ title: "ExitedReviewModeThreadItem" }),
18959 Schema.Struct({
18960 id: Schema.String,
18961 type: Schema.Literal("contextCompaction").annotate({
18962 title: "ContextCompactionThreadItemType",
18963 }),
18964 }).annotate({ title: "ContextCompactionThreadItem" }),
18965 ],
18966 { mode: "oneOf" },
18967);
18968
18969export type V2ThreadReadResponse__TurnError = {
18970 readonly additionalDetails?: string | null;
18971 readonly codexErrorInfo?: V2ThreadReadResponse__CodexErrorInfo | null;
18972 readonly message: string;
18973};
18974export const V2ThreadReadResponse__TurnError = Schema.Struct({
18975 additionalDetails: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
18976 codexErrorInfo: Schema.optionalKey(
18977 Schema.Union([V2ThreadReadResponse__CodexErrorInfo, Schema.Null]),
18978 ),
18979 message: Schema.String,
18980});
18981
18982export type V2ThreadReadResponse__ThreadItem =
18983 | {
18984 readonly content: ReadonlyArray<V2ThreadReadResponse__UserInput>;
18985 readonly id: string;
18986 readonly type: "userMessage";
18987 }
18988 | {
18989 readonly fragments: ReadonlyArray<V2ThreadReadResponse__HookPromptFragment>;
18990 readonly id: string;
18991 readonly type: "hookPrompt";
18992 }
18993 | {
18994 readonly id: string;
18995 readonly memoryCitation?: V2ThreadReadResponse__MemoryCitation | null;
18996 readonly phase?: V2ThreadReadResponse__MessagePhase | null;
18997 readonly text: string;
18998 readonly type: "agentMessage";
18999 }
19000 | { readonly id: string; readonly text: string; readonly type: "plan" }
19001 | {
19002 readonly content?: ReadonlyArray<string>;
19003 readonly id: string;
19004 readonly summary?: ReadonlyArray<string>;
19005 readonly type: "reasoning";
19006 }
19007 | {
19008 readonly aggregatedOutput?: string | null;
19009 readonly command: string;
19010 readonly commandActions: ReadonlyArray<V2ThreadReadResponse__CommandAction>;
19011 readonly cwd: string;
19012 readonly durationMs?: number | null;
19013 readonly exitCode?: number | null;
19014 readonly id: string;
19015 readonly processId?: string | null;
19016 readonly source?: "agent" | "userShell" | "unifiedExecStartup" | "unifiedExecInteraction";
19017 readonly status: V2ThreadReadResponse__CommandExecutionStatus;
19018 readonly type: "commandExecution";
19019 }
19020 | {
19021 readonly changes: ReadonlyArray<V2ThreadReadResponse__FileUpdateChange>;
19022 readonly id: string;
19023 readonly status: V2ThreadReadResponse__PatchApplyStatus;
19024 readonly type: "fileChange";
19025 }
19026 | {
19027 readonly arguments: unknown;
19028 readonly durationMs?: number | null;
19029 readonly error?: V2ThreadReadResponse__McpToolCallError | null;
19030 readonly id: string;
19031 readonly result?: V2ThreadReadResponse__McpToolCallResult | null;
19032 readonly server: string;
19033 readonly status: V2ThreadReadResponse__McpToolCallStatus;
19034 readonly tool: string;
19035 readonly type: "mcpToolCall";
19036 }
19037 | {
19038 readonly arguments: unknown;
19039 readonly contentItems?: ReadonlyArray<V2ThreadReadResponse__DynamicToolCallOutputContentItem> | null;
19040 readonly durationMs?: number | null;
19041 readonly id: string;
19042 readonly status: V2ThreadReadResponse__DynamicToolCallStatus;
19043 readonly success?: boolean | null;
19044 readonly tool: string;
19045 readonly type: "dynamicToolCall";
19046 }
19047 | {
19048 readonly agentsStates: { readonly [x: string]: V2ThreadReadResponse__CollabAgentState };
19049 readonly id: string;
19050 readonly model?: string | null;
19051 readonly prompt?: string | null;
19052 readonly reasoningEffort?: V2ThreadReadResponse__ReasoningEffort | null;
19053 readonly receiverThreadIds: ReadonlyArray<string>;
19054 readonly senderThreadId: string;
19055 readonly status: "inProgress" | "completed" | "failed";
19056 readonly tool: "spawnAgent" | "sendInput" | "resumeAgent" | "wait" | "closeAgent";
19057 readonly type: "collabAgentToolCall";
19058 }
19059 | {
19060 readonly action?: V2ThreadReadResponse__WebSearchAction | null;
19061 readonly id: string;
19062 readonly query: string;
19063 readonly type: "webSearch";
19064 }
19065 | { readonly id: string; readonly path: string; readonly type: "imageView" }
19066 | {
19067 readonly id: string;
19068 readonly result: string;
19069 readonly revisedPrompt?: string | null;
19070 readonly savedPath?: string | null;
19071 readonly status: string;
19072 readonly type: "imageGeneration";
19073 }
19074 | { readonly id: string; readonly review: string; readonly type: "enteredReviewMode" }
19075 | { readonly id: string; readonly review: string; readonly type: "exitedReviewMode" }
19076 | { readonly id: string; readonly type: "contextCompaction" };
19077export const V2ThreadReadResponse__ThreadItem = Schema.Union(
19078 [
19079 Schema.Struct({
19080 content: Schema.Array(V2ThreadReadResponse__UserInput),
19081 id: Schema.String,
19082 type: Schema.Literal("userMessage").annotate({ title: "UserMessageThreadItemType" }),
19083 }).annotate({ title: "UserMessageThreadItem" }),
19084 Schema.Struct({
19085 fragments: Schema.Array(V2ThreadReadResponse__HookPromptFragment),
19086 id: Schema.String,
19087 type: Schema.Literal("hookPrompt").annotate({ title: "HookPromptThreadItemType" }),
19088 }).annotate({ title: "HookPromptThreadItem" }),
19089 Schema.Struct({
19090 id: Schema.String,
19091 memoryCitation: Schema.optionalKey(
19092 Schema.Union([V2ThreadReadResponse__MemoryCitation, Schema.Null]),
19093 ),
19094 phase: Schema.optionalKey(Schema.Union([V2ThreadReadResponse__MessagePhase, Schema.Null])),
19095 text: Schema.String,
19096 type: Schema.Literal("agentMessage").annotate({ title: "AgentMessageThreadItemType" }),
19097 }).annotate({ title: "AgentMessageThreadItem" }),
19098 Schema.Struct({
19099 id: Schema.String,
19100 text: Schema.String,
19101 type: Schema.Literal("plan").annotate({ title: "PlanThreadItemType" }),
19102 }).annotate({
19103 title: "PlanThreadItem",
19104 description:
19105 "EXPERIMENTAL - proposed plan item content. The completed plan item is authoritative and may not match the concatenation of `PlanDelta` text.",
19106 }),
19107 Schema.Struct({
19108 content: Schema.optionalKey(Schema.Array(Schema.String).annotate({ default: [] })),
19109 id: Schema.String,
19110 summary: Schema.optionalKey(Schema.Array(Schema.String).annotate({ default: [] })),
19111 type: Schema.Literal("reasoning").annotate({ title: "ReasoningThreadItemType" }),
19112 }).annotate({ title: "ReasoningThreadItem" }),
19113 Schema.Struct({
19114 aggregatedOutput: Schema.optionalKey(
19115 Schema.Union([
19116 Schema.String.annotate({
19117 description: "The command's output, aggregated from stdout and stderr.",
19118 }),
19119 Schema.Null,
19120 ]),
19121 ),
19122 command: Schema.String.annotate({ description: "The command to be executed." }),
19123 commandActions: Schema.Array(V2ThreadReadResponse__CommandAction).annotate({
19124 description:
19125 "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.",
19126 }),
19127 cwd: Schema.String.annotate({ description: "The command's working directory." }),
19128 durationMs: Schema.optionalKey(
19129 Schema.Union([
19130 Schema.Number.annotate({
19131 description: "The duration of the command execution in milliseconds.",
19132 format: "int64",
19133 }).check(Schema.isInt()),
19134 Schema.Null,
19135 ]),
19136 ),
19137 exitCode: Schema.optionalKey(
19138 Schema.Union([
19139 Schema.Number.annotate({
19140 description: "The command's exit code.",
19141 format: "int32",
19142 }).check(Schema.isInt()),
19143 Schema.Null,
19144 ]),
19145 ),
19146 id: Schema.String,
19147 processId: Schema.optionalKey(
19148 Schema.Union([
19149 Schema.String.annotate({
19150 description: "Identifier for the underlying PTY process (when available).",
19151 }),
19152 Schema.Null,
19153 ]),
19154 ),
19155 source: Schema.optionalKey(
19156 Schema.Literals([
19157 "agent",
19158 "userShell",
19159 "unifiedExecStartup",
19160 "unifiedExecInteraction",
19161 ]).annotate({ default: "agent" }),
19162 ),
19163 status: V2ThreadReadResponse__CommandExecutionStatus,
19164 type: Schema.Literal("commandExecution").annotate({
19165 title: "CommandExecutionThreadItemType",
19166 }),
19167 }).annotate({ title: "CommandExecutionThreadItem" }),
19168 Schema.Struct({
19169 changes: Schema.Array(V2ThreadReadResponse__FileUpdateChange),
19170 id: Schema.String,
19171 status: V2ThreadReadResponse__PatchApplyStatus,
19172 type: Schema.Literal("fileChange").annotate({ title: "FileChangeThreadItemType" }),
19173 }).annotate({ title: "FileChangeThreadItem" }),
19174 Schema.Struct({
19175 arguments: Schema.Unknown,
19176 durationMs: Schema.optionalKey(
19177 Schema.Union([
19178 Schema.Number.annotate({
19179 description: "The duration of the MCP tool call in milliseconds.",
19180 format: "int64",
19181 }).check(Schema.isInt()),
19182 Schema.Null,
19183 ]),
19184 ),
19185 error: Schema.optionalKey(
19186 Schema.Union([V2ThreadReadResponse__McpToolCallError, Schema.Null]),
19187 ),
19188 id: Schema.String,
19189 result: Schema.optionalKey(
19190 Schema.Union([V2ThreadReadResponse__McpToolCallResult, Schema.Null]),
19191 ),
19192 server: Schema.String,
19193 status: V2ThreadReadResponse__McpToolCallStatus,
19194 tool: Schema.String,
19195 type: Schema.Literal("mcpToolCall").annotate({ title: "McpToolCallThreadItemType" }),
19196 }).annotate({ title: "McpToolCallThreadItem" }),
19197 Schema.Struct({
19198 arguments: Schema.Unknown,
19199 contentItems: Schema.optionalKey(
19200 Schema.Union([
19201 Schema.Array(V2ThreadReadResponse__DynamicToolCallOutputContentItem),
19202 Schema.Null,
19203 ]),
19204 ),
19205 durationMs: Schema.optionalKey(
19206 Schema.Union([
19207 Schema.Number.annotate({
19208 description: "The duration of the dynamic tool call in milliseconds.",
19209 format: "int64",
19210 }).check(Schema.isInt()),
19211 Schema.Null,
19212 ]),
19213 ),
19214 id: Schema.String,
19215 status: V2ThreadReadResponse__DynamicToolCallStatus,
19216 success: Schema.optionalKey(Schema.Union([Schema.Boolean, Schema.Null])),
19217 tool: Schema.String,
19218 type: Schema.Literal("dynamicToolCall").annotate({ title: "DynamicToolCallThreadItemType" }),
19219 }).annotate({ title: "DynamicToolCallThreadItem" }),
19220 Schema.Struct({
19221 agentsStates: Schema.Record(Schema.String, V2ThreadReadResponse__CollabAgentState).annotate({
19222 description: "Last known status of the target agents, when available.",
19223 }),
19224 id: Schema.String.annotate({ description: "Unique identifier for this collab tool call." }),
19225 model: Schema.optionalKey(
19226 Schema.Union([
19227 Schema.String.annotate({
19228 description: "Model requested for the spawned agent, when applicable.",
19229 }),
19230 Schema.Null,
19231 ]),
19232 ),
19233 prompt: Schema.optionalKey(
19234 Schema.Union([
19235 Schema.String.annotate({
19236 description: "Prompt text sent as part of the collab tool call, when available.",
19237 }),
19238 Schema.Null,
19239 ]),
19240 ),
19241 reasoningEffort: Schema.optionalKey(
19242 Schema.Union([V2ThreadReadResponse__ReasoningEffort, Schema.Null]).annotate({
19243 description: "Reasoning effort requested for the spawned agent, when applicable.",
19244 }),
19245 ),
19246 receiverThreadIds: Schema.Array(Schema.String).annotate({
19247 description:
19248 "Thread ID of the receiving agent, when applicable. In case of spawn operation, this corresponds to the newly spawned agent.",
19249 }),
19250 senderThreadId: Schema.String.annotate({
19251 description: "Thread ID of the agent issuing the collab request.",
19252 }),
19253 status: Schema.Literals(["inProgress", "completed", "failed"]).annotate({
19254 description: "Current status of the collab tool call.",
19255 }),
19256 tool: Schema.Literals([
19257 "spawnAgent",
19258 "sendInput",
19259 "resumeAgent",
19260 "wait",
19261 "closeAgent",
19262 ]).annotate({ description: "Name of the collab tool that was invoked." }),
19263 type: Schema.Literal("collabAgentToolCall").annotate({
19264 title: "CollabAgentToolCallThreadItemType",
19265 }),
19266 }).annotate({ title: "CollabAgentToolCallThreadItem" }),
19267 Schema.Struct({
19268 action: Schema.optionalKey(
19269 Schema.Union([V2ThreadReadResponse__WebSearchAction, Schema.Null]),
19270 ),
19271 id: Schema.String,
19272 query: Schema.String,
19273 type: Schema.Literal("webSearch").annotate({ title: "WebSearchThreadItemType" }),
19274 }).annotate({ title: "WebSearchThreadItem" }),
19275 Schema.Struct({
19276 id: Schema.String,
19277 path: Schema.String,
19278 type: Schema.Literal("imageView").annotate({ title: "ImageViewThreadItemType" }),
19279 }).annotate({ title: "ImageViewThreadItem" }),
19280 Schema.Struct({
19281 id: Schema.String,
19282 result: Schema.String,
19283 revisedPrompt: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
19284 savedPath: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
19285 status: Schema.String,
19286 type: Schema.Literal("imageGeneration").annotate({ title: "ImageGenerationThreadItemType" }),
19287 }).annotate({ title: "ImageGenerationThreadItem" }),
19288 Schema.Struct({
19289 id: Schema.String,
19290 review: Schema.String,
19291 type: Schema.Literal("enteredReviewMode").annotate({
19292 title: "EnteredReviewModeThreadItemType",
19293 }),
19294 }).annotate({ title: "EnteredReviewModeThreadItem" }),
19295 Schema.Struct({
19296 id: Schema.String,
19297 review: Schema.String,
19298 type: Schema.Literal("exitedReviewMode").annotate({
19299 title: "ExitedReviewModeThreadItemType",
19300 }),
19301 }).annotate({ title: "ExitedReviewModeThreadItem" }),
19302 Schema.Struct({
19303 id: Schema.String,
19304 type: Schema.Literal("contextCompaction").annotate({
19305 title: "ContextCompactionThreadItemType",
19306 }),
19307 }).annotate({ title: "ContextCompactionThreadItem" }),
19308 ],
19309 { mode: "oneOf" },
19310);
19311
19312export type V2ThreadResumeParams__FunctionCallOutputBody =
19313 | string
19314 | ReadonlyArray<V2ThreadResumeParams__FunctionCallOutputContentItem>;
19315export const V2ThreadResumeParams__FunctionCallOutputBody = Schema.Union([
19316 Schema.String,
19317 Schema.Array(V2ThreadResumeParams__FunctionCallOutputContentItem),
19318]);
19319
19320export type V2ThreadResumeResponse__TurnError = {
19321 readonly additionalDetails?: string | null;
19322 readonly codexErrorInfo?: V2ThreadResumeResponse__CodexErrorInfo | null;
19323 readonly message: string;
19324};
19325export const V2ThreadResumeResponse__TurnError = Schema.Struct({
19326 additionalDetails: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
19327 codexErrorInfo: Schema.optionalKey(
19328 Schema.Union([V2ThreadResumeResponse__CodexErrorInfo, Schema.Null]),
19329 ),
19330 message: Schema.String,
19331});
19332
19333export type V2ThreadResumeResponse__ThreadItem =
19334 | {
19335 readonly content: ReadonlyArray<V2ThreadResumeResponse__UserInput>;
19336 readonly id: string;
19337 readonly type: "userMessage";
19338 }
19339 | {
19340 readonly fragments: ReadonlyArray<V2ThreadResumeResponse__HookPromptFragment>;
19341 readonly id: string;
19342 readonly type: "hookPrompt";
19343 }
19344 | {
19345 readonly id: string;
19346 readonly memoryCitation?: V2ThreadResumeResponse__MemoryCitation | null;
19347 readonly phase?: V2ThreadResumeResponse__MessagePhase | null;
19348 readonly text: string;
19349 readonly type: "agentMessage";
19350 }
19351 | { readonly id: string; readonly text: string; readonly type: "plan" }
19352 | {
19353 readonly content?: ReadonlyArray<string>;
19354 readonly id: string;
19355 readonly summary?: ReadonlyArray<string>;
19356 readonly type: "reasoning";
19357 }
19358 | {
19359 readonly aggregatedOutput?: string | null;
19360 readonly command: string;
19361 readonly commandActions: ReadonlyArray<V2ThreadResumeResponse__CommandAction>;
19362 readonly cwd: string;
19363 readonly durationMs?: number | null;
19364 readonly exitCode?: number | null;
19365 readonly id: string;
19366 readonly processId?: string | null;
19367 readonly source?: "agent" | "userShell" | "unifiedExecStartup" | "unifiedExecInteraction";
19368 readonly status: V2ThreadResumeResponse__CommandExecutionStatus;
19369 readonly type: "commandExecution";
19370 }
19371 | {
19372 readonly changes: ReadonlyArray<V2ThreadResumeResponse__FileUpdateChange>;
19373 readonly id: string;
19374 readonly status: V2ThreadResumeResponse__PatchApplyStatus;
19375 readonly type: "fileChange";
19376 }
19377 | {
19378 readonly arguments: unknown;
19379 readonly durationMs?: number | null;
19380 readonly error?: V2ThreadResumeResponse__McpToolCallError | null;
19381 readonly id: string;
19382 readonly result?: V2ThreadResumeResponse__McpToolCallResult | null;
19383 readonly server: string;
19384 readonly status: V2ThreadResumeResponse__McpToolCallStatus;
19385 readonly tool: string;
19386 readonly type: "mcpToolCall";
19387 }
19388 | {
19389 readonly arguments: unknown;
19390 readonly contentItems?: ReadonlyArray<V2ThreadResumeResponse__DynamicToolCallOutputContentItem> | null;
19391 readonly durationMs?: number | null;
19392 readonly id: string;
19393 readonly status: V2ThreadResumeResponse__DynamicToolCallStatus;
19394 readonly success?: boolean | null;
19395 readonly tool: string;
19396 readonly type: "dynamicToolCall";
19397 }
19398 | {
19399 readonly agentsStates: { readonly [x: string]: V2ThreadResumeResponse__CollabAgentState };
19400 readonly id: string;
19401 readonly model?: string | null;
19402 readonly prompt?: string | null;
19403 readonly reasoningEffort?: V2ThreadResumeResponse__ReasoningEffort | null;
19404 readonly receiverThreadIds: ReadonlyArray<string>;
19405 readonly senderThreadId: string;
19406 readonly status: "inProgress" | "completed" | "failed";
19407 readonly tool: "spawnAgent" | "sendInput" | "resumeAgent" | "wait" | "closeAgent";
19408 readonly type: "collabAgentToolCall";
19409 }
19410 | {
19411 readonly action?: V2ThreadResumeResponse__WebSearchAction | null;
19412 readonly id: string;
19413 readonly query: string;
19414 readonly type: "webSearch";
19415 }
19416 | { readonly id: string; readonly path: string; readonly type: "imageView" }
19417 | {
19418 readonly id: string;
19419 readonly result: string;
19420 readonly revisedPrompt?: string | null;
19421 readonly savedPath?: string | null;
19422 readonly status: string;
19423 readonly type: "imageGeneration";
19424 }
19425 | { readonly id: string; readonly review: string; readonly type: "enteredReviewMode" }
19426 | { readonly id: string; readonly review: string; readonly type: "exitedReviewMode" }
19427 | { readonly id: string; readonly type: "contextCompaction" };
19428export const V2ThreadResumeResponse__ThreadItem = Schema.Union(
19429 [
19430 Schema.Struct({
19431 content: Schema.Array(V2ThreadResumeResponse__UserInput),
19432 id: Schema.String,
19433 type: Schema.Literal("userMessage").annotate({ title: "UserMessageThreadItemType" }),
19434 }).annotate({ title: "UserMessageThreadItem" }),
19435 Schema.Struct({
19436 fragments: Schema.Array(V2ThreadResumeResponse__HookPromptFragment),
19437 id: Schema.String,
19438 type: Schema.Literal("hookPrompt").annotate({ title: "HookPromptThreadItemType" }),
19439 }).annotate({ title: "HookPromptThreadItem" }),
19440 Schema.Struct({
19441 id: Schema.String,
19442 memoryCitation: Schema.optionalKey(
19443 Schema.Union([V2ThreadResumeResponse__MemoryCitation, Schema.Null]),
19444 ),
19445 phase: Schema.optionalKey(Schema.Union([V2ThreadResumeResponse__MessagePhase, Schema.Null])),
19446 text: Schema.String,
19447 type: Schema.Literal("agentMessage").annotate({ title: "AgentMessageThreadItemType" }),
19448 }).annotate({ title: "AgentMessageThreadItem" }),
19449 Schema.Struct({
19450 id: Schema.String,
19451 text: Schema.String,
19452 type: Schema.Literal("plan").annotate({ title: "PlanThreadItemType" }),
19453 }).annotate({
19454 title: "PlanThreadItem",
19455 description:
19456 "EXPERIMENTAL - proposed plan item content. The completed plan item is authoritative and may not match the concatenation of `PlanDelta` text.",
19457 }),
19458 Schema.Struct({
19459 content: Schema.optionalKey(Schema.Array(Schema.String).annotate({ default: [] })),
19460 id: Schema.String,
19461 summary: Schema.optionalKey(Schema.Array(Schema.String).annotate({ default: [] })),
19462 type: Schema.Literal("reasoning").annotate({ title: "ReasoningThreadItemType" }),
19463 }).annotate({ title: "ReasoningThreadItem" }),
19464 Schema.Struct({
19465 aggregatedOutput: Schema.optionalKey(
19466 Schema.Union([
19467 Schema.String.annotate({
19468 description: "The command's output, aggregated from stdout and stderr.",
19469 }),
19470 Schema.Null,
19471 ]),
19472 ),
19473 command: Schema.String.annotate({ description: "The command to be executed." }),
19474 commandActions: Schema.Array(V2ThreadResumeResponse__CommandAction).annotate({
19475 description:
19476 "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.",
19477 }),
19478 cwd: Schema.String.annotate({ description: "The command's working directory." }),
19479 durationMs: Schema.optionalKey(
19480 Schema.Union([
19481 Schema.Number.annotate({
19482 description: "The duration of the command execution in milliseconds.",
19483 format: "int64",
19484 }).check(Schema.isInt()),
19485 Schema.Null,
19486 ]),
19487 ),
19488 exitCode: Schema.optionalKey(
19489 Schema.Union([
19490 Schema.Number.annotate({
19491 description: "The command's exit code.",
19492 format: "int32",
19493 }).check(Schema.isInt()),
19494 Schema.Null,
19495 ]),
19496 ),
19497 id: Schema.String,
19498 processId: Schema.optionalKey(
19499 Schema.Union([
19500 Schema.String.annotate({
19501 description: "Identifier for the underlying PTY process (when available).",
19502 }),
19503 Schema.Null,
19504 ]),
19505 ),
19506 source: Schema.optionalKey(
19507 Schema.Literals([
19508 "agent",
19509 "userShell",
19510 "unifiedExecStartup",
19511 "unifiedExecInteraction",
19512 ]).annotate({ default: "agent" }),
19513 ),
19514 status: V2ThreadResumeResponse__CommandExecutionStatus,
19515 type: Schema.Literal("commandExecution").annotate({
19516 title: "CommandExecutionThreadItemType",
19517 }),
19518 }).annotate({ title: "CommandExecutionThreadItem" }),
19519 Schema.Struct({
19520 changes: Schema.Array(V2ThreadResumeResponse__FileUpdateChange),
19521 id: Schema.String,
19522 status: V2ThreadResumeResponse__PatchApplyStatus,
19523 type: Schema.Literal("fileChange").annotate({ title: "FileChangeThreadItemType" }),
19524 }).annotate({ title: "FileChangeThreadItem" }),
19525 Schema.Struct({
19526 arguments: Schema.Unknown,
19527 durationMs: Schema.optionalKey(
19528 Schema.Union([
19529 Schema.Number.annotate({
19530 description: "The duration of the MCP tool call in milliseconds.",
19531 format: "int64",
19532 }).check(Schema.isInt()),
19533 Schema.Null,
19534 ]),
19535 ),
19536 error: Schema.optionalKey(
19537 Schema.Union([V2ThreadResumeResponse__McpToolCallError, Schema.Null]),
19538 ),
19539 id: Schema.String,
19540 result: Schema.optionalKey(
19541 Schema.Union([V2ThreadResumeResponse__McpToolCallResult, Schema.Null]),
19542 ),
19543 server: Schema.String,
19544 status: V2ThreadResumeResponse__McpToolCallStatus,
19545 tool: Schema.String,
19546 type: Schema.Literal("mcpToolCall").annotate({ title: "McpToolCallThreadItemType" }),
19547 }).annotate({ title: "McpToolCallThreadItem" }),
19548 Schema.Struct({
19549 arguments: Schema.Unknown,
19550 contentItems: Schema.optionalKey(
19551 Schema.Union([
19552 Schema.Array(V2ThreadResumeResponse__DynamicToolCallOutputContentItem),
19553 Schema.Null,
19554 ]),
19555 ),
19556 durationMs: Schema.optionalKey(
19557 Schema.Union([
19558 Schema.Number.annotate({
19559 description: "The duration of the dynamic tool call in milliseconds.",
19560 format: "int64",
19561 }).check(Schema.isInt()),
19562 Schema.Null,
19563 ]),
19564 ),
19565 id: Schema.String,
19566 status: V2ThreadResumeResponse__DynamicToolCallStatus,
19567 success: Schema.optionalKey(Schema.Union([Schema.Boolean, Schema.Null])),
19568 tool: Schema.String,
19569 type: Schema.Literal("dynamicToolCall").annotate({ title: "DynamicToolCallThreadItemType" }),
19570 }).annotate({ title: "DynamicToolCallThreadItem" }),
19571 Schema.Struct({
19572 agentsStates: Schema.Record(Schema.String, V2ThreadResumeResponse__CollabAgentState).annotate(
19573 { description: "Last known status of the target agents, when available." },
19574 ),
19575 id: Schema.String.annotate({ description: "Unique identifier for this collab tool call." }),
19576 model: Schema.optionalKey(
19577 Schema.Union([
19578 Schema.String.annotate({
19579 description: "Model requested for the spawned agent, when applicable.",
19580 }),
19581 Schema.Null,
19582 ]),
19583 ),
19584 prompt: Schema.optionalKey(
19585 Schema.Union([
19586 Schema.String.annotate({
19587 description: "Prompt text sent as part of the collab tool call, when available.",
19588 }),
19589 Schema.Null,
19590 ]),
19591 ),
19592 reasoningEffort: Schema.optionalKey(
19593 Schema.Union([V2ThreadResumeResponse__ReasoningEffort, Schema.Null]).annotate({
19594 description: "Reasoning effort requested for the spawned agent, when applicable.",
19595 }),
19596 ),
19597 receiverThreadIds: Schema.Array(Schema.String).annotate({
19598 description:
19599 "Thread ID of the receiving agent, when applicable. In case of spawn operation, this corresponds to the newly spawned agent.",
19600 }),
19601 senderThreadId: Schema.String.annotate({
19602 description: "Thread ID of the agent issuing the collab request.",
19603 }),
19604 status: Schema.Literals(["inProgress", "completed", "failed"]).annotate({
19605 description: "Current status of the collab tool call.",
19606 }),
19607 tool: Schema.Literals([
19608 "spawnAgent",
19609 "sendInput",
19610 "resumeAgent",
19611 "wait",
19612 "closeAgent",
19613 ]).annotate({ description: "Name of the collab tool that was invoked." }),
19614 type: Schema.Literal("collabAgentToolCall").annotate({
19615 title: "CollabAgentToolCallThreadItemType",
19616 }),
19617 }).annotate({ title: "CollabAgentToolCallThreadItem" }),
19618 Schema.Struct({
19619 action: Schema.optionalKey(
19620 Schema.Union([V2ThreadResumeResponse__WebSearchAction, Schema.Null]),
19621 ),
19622 id: Schema.String,
19623 query: Schema.String,
19624 type: Schema.Literal("webSearch").annotate({ title: "WebSearchThreadItemType" }),
19625 }).annotate({ title: "WebSearchThreadItem" }),
19626 Schema.Struct({
19627 id: Schema.String,
19628 path: Schema.String,
19629 type: Schema.Literal("imageView").annotate({ title: "ImageViewThreadItemType" }),
19630 }).annotate({ title: "ImageViewThreadItem" }),
19631 Schema.Struct({
19632 id: Schema.String,
19633 result: Schema.String,
19634 revisedPrompt: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
19635 savedPath: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
19636 status: Schema.String,
19637 type: Schema.Literal("imageGeneration").annotate({ title: "ImageGenerationThreadItemType" }),
19638 }).annotate({ title: "ImageGenerationThreadItem" }),
19639 Schema.Struct({
19640 id: Schema.String,
19641 review: Schema.String,
19642 type: Schema.Literal("enteredReviewMode").annotate({
19643 title: "EnteredReviewModeThreadItemType",
19644 }),
19645 }).annotate({ title: "EnteredReviewModeThreadItem" }),
19646 Schema.Struct({
19647 id: Schema.String,
19648 review: Schema.String,
19649 type: Schema.Literal("exitedReviewMode").annotate({
19650 title: "ExitedReviewModeThreadItemType",
19651 }),
19652 }).annotate({ title: "ExitedReviewModeThreadItem" }),
19653 Schema.Struct({
19654 id: Schema.String,
19655 type: Schema.Literal("contextCompaction").annotate({
19656 title: "ContextCompactionThreadItemType",
19657 }),
19658 }).annotate({ title: "ContextCompactionThreadItem" }),
19659 ],
19660 { mode: "oneOf" },
19661);
19662
19663export type V2ThreadRollbackResponse__TurnError = {
19664 readonly additionalDetails?: string | null;
19665 readonly codexErrorInfo?: V2ThreadRollbackResponse__CodexErrorInfo | null;
19666 readonly message: string;
19667};
19668export const V2ThreadRollbackResponse__TurnError = Schema.Struct({
19669 additionalDetails: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
19670 codexErrorInfo: Schema.optionalKey(
19671 Schema.Union([V2ThreadRollbackResponse__CodexErrorInfo, Schema.Null]),
19672 ),
19673 message: Schema.String,
19674});
19675
19676export type V2ThreadRollbackResponse__ThreadItem =
19677 | {
19678 readonly content: ReadonlyArray<V2ThreadRollbackResponse__UserInput>;
19679 readonly id: string;
19680 readonly type: "userMessage";
19681 }
19682 | {
19683 readonly fragments: ReadonlyArray<V2ThreadRollbackResponse__HookPromptFragment>;
19684 readonly id: string;
19685 readonly type: "hookPrompt";
19686 }
19687 | {
19688 readonly id: string;
19689 readonly memoryCitation?: V2ThreadRollbackResponse__MemoryCitation | null;
19690 readonly phase?: V2ThreadRollbackResponse__MessagePhase | null;
19691 readonly text: string;
19692 readonly type: "agentMessage";
19693 }
19694 | { readonly id: string; readonly text: string; readonly type: "plan" }
19695 | {
19696 readonly content?: ReadonlyArray<string>;
19697 readonly id: string;
19698 readonly summary?: ReadonlyArray<string>;
19699 readonly type: "reasoning";
19700 }
19701 | {
19702 readonly aggregatedOutput?: string | null;
19703 readonly command: string;
19704 readonly commandActions: ReadonlyArray<V2ThreadRollbackResponse__CommandAction>;
19705 readonly cwd: string;
19706 readonly durationMs?: number | null;
19707 readonly exitCode?: number | null;
19708 readonly id: string;
19709 readonly processId?: string | null;
19710 readonly source?: "agent" | "userShell" | "unifiedExecStartup" | "unifiedExecInteraction";
19711 readonly status: V2ThreadRollbackResponse__CommandExecutionStatus;
19712 readonly type: "commandExecution";
19713 }
19714 | {
19715 readonly changes: ReadonlyArray<V2ThreadRollbackResponse__FileUpdateChange>;
19716 readonly id: string;
19717 readonly status: V2ThreadRollbackResponse__PatchApplyStatus;
19718 readonly type: "fileChange";
19719 }
19720 | {
19721 readonly arguments: unknown;
19722 readonly durationMs?: number | null;
19723 readonly error?: V2ThreadRollbackResponse__McpToolCallError | null;
19724 readonly id: string;
19725 readonly result?: V2ThreadRollbackResponse__McpToolCallResult | null;
19726 readonly server: string;
19727 readonly status: V2ThreadRollbackResponse__McpToolCallStatus;
19728 readonly tool: string;
19729 readonly type: "mcpToolCall";
19730 }
19731 | {
19732 readonly arguments: unknown;
19733 readonly contentItems?: ReadonlyArray<V2ThreadRollbackResponse__DynamicToolCallOutputContentItem> | null;
19734 readonly durationMs?: number | null;
19735 readonly id: string;
19736 readonly status: V2ThreadRollbackResponse__DynamicToolCallStatus;
19737 readonly success?: boolean | null;
19738 readonly tool: string;
19739 readonly type: "dynamicToolCall";
19740 }
19741 | {
19742 readonly agentsStates: { readonly [x: string]: V2ThreadRollbackResponse__CollabAgentState };
19743 readonly id: string;
19744 readonly model?: string | null;
19745 readonly prompt?: string | null;
19746 readonly reasoningEffort?: V2ThreadRollbackResponse__ReasoningEffort | null;
19747 readonly receiverThreadIds: ReadonlyArray<string>;
19748 readonly senderThreadId: string;
19749 readonly status: "inProgress" | "completed" | "failed";
19750 readonly tool: "spawnAgent" | "sendInput" | "resumeAgent" | "wait" | "closeAgent";
19751 readonly type: "collabAgentToolCall";
19752 }
19753 | {
19754 readonly action?: V2ThreadRollbackResponse__WebSearchAction | null;
19755 readonly id: string;
19756 readonly query: string;
19757 readonly type: "webSearch";
19758 }
19759 | { readonly id: string; readonly path: string; readonly type: "imageView" }
19760 | {
19761 readonly id: string;
19762 readonly result: string;
19763 readonly revisedPrompt?: string | null;
19764 readonly savedPath?: string | null;
19765 readonly status: string;
19766 readonly type: "imageGeneration";
19767 }
19768 | { readonly id: string; readonly review: string; readonly type: "enteredReviewMode" }
19769 | { readonly id: string; readonly review: string; readonly type: "exitedReviewMode" }
19770 | { readonly id: string; readonly type: "contextCompaction" };
19771export const V2ThreadRollbackResponse__ThreadItem = Schema.Union(
19772 [
19773 Schema.Struct({
19774 content: Schema.Array(V2ThreadRollbackResponse__UserInput),
19775 id: Schema.String,
19776 type: Schema.Literal("userMessage").annotate({ title: "UserMessageThreadItemType" }),
19777 }).annotate({ title: "UserMessageThreadItem" }),
19778 Schema.Struct({
19779 fragments: Schema.Array(V2ThreadRollbackResponse__HookPromptFragment),
19780 id: Schema.String,
19781 type: Schema.Literal("hookPrompt").annotate({ title: "HookPromptThreadItemType" }),
19782 }).annotate({ title: "HookPromptThreadItem" }),
19783 Schema.Struct({
19784 id: Schema.String,
19785 memoryCitation: Schema.optionalKey(
19786 Schema.Union([V2ThreadRollbackResponse__MemoryCitation, Schema.Null]),
19787 ),
19788 phase: Schema.optionalKey(
19789 Schema.Union([V2ThreadRollbackResponse__MessagePhase, Schema.Null]),
19790 ),
19791 text: Schema.String,
19792 type: Schema.Literal("agentMessage").annotate({ title: "AgentMessageThreadItemType" }),
19793 }).annotate({ title: "AgentMessageThreadItem" }),
19794 Schema.Struct({
19795 id: Schema.String,
19796 text: Schema.String,
19797 type: Schema.Literal("plan").annotate({ title: "PlanThreadItemType" }),
19798 }).annotate({
19799 title: "PlanThreadItem",
19800 description:
19801 "EXPERIMENTAL - proposed plan item content. The completed plan item is authoritative and may not match the concatenation of `PlanDelta` text.",
19802 }),
19803 Schema.Struct({
19804 content: Schema.optionalKey(Schema.Array(Schema.String).annotate({ default: [] })),
19805 id: Schema.String,
19806 summary: Schema.optionalKey(Schema.Array(Schema.String).annotate({ default: [] })),
19807 type: Schema.Literal("reasoning").annotate({ title: "ReasoningThreadItemType" }),
19808 }).annotate({ title: "ReasoningThreadItem" }),
19809 Schema.Struct({
19810 aggregatedOutput: Schema.optionalKey(
19811 Schema.Union([
19812 Schema.String.annotate({
19813 description: "The command's output, aggregated from stdout and stderr.",
19814 }),
19815 Schema.Null,
19816 ]),
19817 ),
19818 command: Schema.String.annotate({ description: "The command to be executed." }),
19819 commandActions: Schema.Array(V2ThreadRollbackResponse__CommandAction).annotate({
19820 description:
19821 "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.",
19822 }),
19823 cwd: Schema.String.annotate({ description: "The command's working directory." }),
19824 durationMs: Schema.optionalKey(
19825 Schema.Union([
19826 Schema.Number.annotate({
19827 description: "The duration of the command execution in milliseconds.",
19828 format: "int64",
19829 }).check(Schema.isInt()),
19830 Schema.Null,
19831 ]),
19832 ),
19833 exitCode: Schema.optionalKey(
19834 Schema.Union([
19835 Schema.Number.annotate({
19836 description: "The command's exit code.",
19837 format: "int32",
19838 }).check(Schema.isInt()),
19839 Schema.Null,
19840 ]),
19841 ),
19842 id: Schema.String,
19843 processId: Schema.optionalKey(
19844 Schema.Union([
19845 Schema.String.annotate({
19846 description: "Identifier for the underlying PTY process (when available).",
19847 }),
19848 Schema.Null,
19849 ]),
19850 ),
19851 source: Schema.optionalKey(
19852 Schema.Literals([
19853 "agent",
19854 "userShell",
19855 "unifiedExecStartup",
19856 "unifiedExecInteraction",
19857 ]).annotate({ default: "agent" }),
19858 ),
19859 status: V2ThreadRollbackResponse__CommandExecutionStatus,
19860 type: Schema.Literal("commandExecution").annotate({
19861 title: "CommandExecutionThreadItemType",
19862 }),
19863 }).annotate({ title: "CommandExecutionThreadItem" }),
19864 Schema.Struct({
19865 changes: Schema.Array(V2ThreadRollbackResponse__FileUpdateChange),
19866 id: Schema.String,
19867 status: V2ThreadRollbackResponse__PatchApplyStatus,
19868 type: Schema.Literal("fileChange").annotate({ title: "FileChangeThreadItemType" }),
19869 }).annotate({ title: "FileChangeThreadItem" }),
19870 Schema.Struct({
19871 arguments: Schema.Unknown,
19872 durationMs: Schema.optionalKey(
19873 Schema.Union([
19874 Schema.Number.annotate({
19875 description: "The duration of the MCP tool call in milliseconds.",
19876 format: "int64",
19877 }).check(Schema.isInt()),
19878 Schema.Null,
19879 ]),
19880 ),
19881 error: Schema.optionalKey(
19882 Schema.Union([V2ThreadRollbackResponse__McpToolCallError, Schema.Null]),
19883 ),
19884 id: Schema.String,
19885 result: Schema.optionalKey(
19886 Schema.Union([V2ThreadRollbackResponse__McpToolCallResult, Schema.Null]),
19887 ),
19888 server: Schema.String,
19889 status: V2ThreadRollbackResponse__McpToolCallStatus,
19890 tool: Schema.String,
19891 type: Schema.Literal("mcpToolCall").annotate({ title: "McpToolCallThreadItemType" }),
19892 }).annotate({ title: "McpToolCallThreadItem" }),
19893 Schema.Struct({
19894 arguments: Schema.Unknown,
19895 contentItems: Schema.optionalKey(
19896 Schema.Union([
19897 Schema.Array(V2ThreadRollbackResponse__DynamicToolCallOutputContentItem),
19898 Schema.Null,
19899 ]),
19900 ),
19901 durationMs: Schema.optionalKey(
19902 Schema.Union([
19903 Schema.Number.annotate({
19904 description: "The duration of the dynamic tool call in milliseconds.",
19905 format: "int64",
19906 }).check(Schema.isInt()),
19907 Schema.Null,
19908 ]),
19909 ),
19910 id: Schema.String,
19911 status: V2ThreadRollbackResponse__DynamicToolCallStatus,
19912 success: Schema.optionalKey(Schema.Union([Schema.Boolean, Schema.Null])),
19913 tool: Schema.String,
19914 type: Schema.Literal("dynamicToolCall").annotate({ title: "DynamicToolCallThreadItemType" }),
19915 }).annotate({ title: "DynamicToolCallThreadItem" }),
19916 Schema.Struct({
19917 agentsStates: Schema.Record(
19918 Schema.String,
19919 V2ThreadRollbackResponse__CollabAgentState,
19920 ).annotate({ description: "Last known status of the target agents, when available." }),
19921 id: Schema.String.annotate({ description: "Unique identifier for this collab tool call." }),
19922 model: Schema.optionalKey(
19923 Schema.Union([
19924 Schema.String.annotate({
19925 description: "Model requested for the spawned agent, when applicable.",
19926 }),
19927 Schema.Null,
19928 ]),
19929 ),
19930 prompt: Schema.optionalKey(
19931 Schema.Union([
19932 Schema.String.annotate({
19933 description: "Prompt text sent as part of the collab tool call, when available.",
19934 }),
19935 Schema.Null,
19936 ]),
19937 ),
19938 reasoningEffort: Schema.optionalKey(
19939 Schema.Union([V2ThreadRollbackResponse__ReasoningEffort, Schema.Null]).annotate({
19940 description: "Reasoning effort requested for the spawned agent, when applicable.",
19941 }),
19942 ),
19943 receiverThreadIds: Schema.Array(Schema.String).annotate({
19944 description:
19945 "Thread ID of the receiving agent, when applicable. In case of spawn operation, this corresponds to the newly spawned agent.",
19946 }),
19947 senderThreadId: Schema.String.annotate({
19948 description: "Thread ID of the agent issuing the collab request.",
19949 }),
19950 status: Schema.Literals(["inProgress", "completed", "failed"]).annotate({
19951 description: "Current status of the collab tool call.",
19952 }),
19953 tool: Schema.Literals([
19954 "spawnAgent",
19955 "sendInput",
19956 "resumeAgent",
19957 "wait",
19958 "closeAgent",
19959 ]).annotate({ description: "Name of the collab tool that was invoked." }),
19960 type: Schema.Literal("collabAgentToolCall").annotate({
19961 title: "CollabAgentToolCallThreadItemType",
19962 }),
19963 }).annotate({ title: "CollabAgentToolCallThreadItem" }),
19964 Schema.Struct({
19965 action: Schema.optionalKey(
19966 Schema.Union([V2ThreadRollbackResponse__WebSearchAction, Schema.Null]),
19967 ),
19968 id: Schema.String,
19969 query: Schema.String,
19970 type: Schema.Literal("webSearch").annotate({ title: "WebSearchThreadItemType" }),
19971 }).annotate({ title: "WebSearchThreadItem" }),
19972 Schema.Struct({
19973 id: Schema.String,
19974 path: Schema.String,
19975 type: Schema.Literal("imageView").annotate({ title: "ImageViewThreadItemType" }),
19976 }).annotate({ title: "ImageViewThreadItem" }),
19977 Schema.Struct({
19978 id: Schema.String,
19979 result: Schema.String,
19980 revisedPrompt: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
19981 savedPath: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
19982 status: Schema.String,
19983 type: Schema.Literal("imageGeneration").annotate({ title: "ImageGenerationThreadItemType" }),
19984 }).annotate({ title: "ImageGenerationThreadItem" }),
19985 Schema.Struct({
19986 id: Schema.String,
19987 review: Schema.String,
19988 type: Schema.Literal("enteredReviewMode").annotate({
19989 title: "EnteredReviewModeThreadItemType",
19990 }),
19991 }).annotate({ title: "EnteredReviewModeThreadItem" }),
19992 Schema.Struct({
19993 id: Schema.String,
19994 review: Schema.String,
19995 type: Schema.Literal("exitedReviewMode").annotate({
19996 title: "ExitedReviewModeThreadItemType",
19997 }),
19998 }).annotate({ title: "ExitedReviewModeThreadItem" }),
19999 Schema.Struct({
20000 id: Schema.String,
20001 type: Schema.Literal("contextCompaction").annotate({
20002 title: "ContextCompactionThreadItemType",
20003 }),
20004 }).annotate({ title: "ContextCompactionThreadItem" }),
20005 ],
20006 { mode: "oneOf" },
20007);
20008
20009export type V2ThreadStartedNotification__TurnError = {
20010 readonly additionalDetails?: string | null;
20011 readonly codexErrorInfo?: V2ThreadStartedNotification__CodexErrorInfo | null;
20012 readonly message: string;
20013};
20014export const V2ThreadStartedNotification__TurnError = Schema.Struct({
20015 additionalDetails: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
20016 codexErrorInfo: Schema.optionalKey(
20017 Schema.Union([V2ThreadStartedNotification__CodexErrorInfo, Schema.Null]),
20018 ),
20019 message: Schema.String,
20020});
20021
20022export type V2ThreadStartedNotification__ThreadItem =
20023 | {
20024 readonly content: ReadonlyArray<V2ThreadStartedNotification__UserInput>;
20025 readonly id: string;
20026 readonly type: "userMessage";
20027 }
20028 | {
20029 readonly fragments: ReadonlyArray<V2ThreadStartedNotification__HookPromptFragment>;
20030 readonly id: string;
20031 readonly type: "hookPrompt";
20032 }
20033 | {
20034 readonly id: string;
20035 readonly memoryCitation?: V2ThreadStartedNotification__MemoryCitation | null;
20036 readonly phase?: V2ThreadStartedNotification__MessagePhase | null;
20037 readonly text: string;
20038 readonly type: "agentMessage";
20039 }
20040 | { readonly id: string; readonly text: string; readonly type: "plan" }
20041 | {
20042 readonly content?: ReadonlyArray<string>;
20043 readonly id: string;
20044 readonly summary?: ReadonlyArray<string>;
20045 readonly type: "reasoning";
20046 }
20047 | {
20048 readonly aggregatedOutput?: string | null;
20049 readonly command: string;
20050 readonly commandActions: ReadonlyArray<V2ThreadStartedNotification__CommandAction>;
20051 readonly cwd: string;
20052 readonly durationMs?: number | null;
20053 readonly exitCode?: number | null;
20054 readonly id: string;
20055 readonly processId?: string | null;
20056 readonly source?: "agent" | "userShell" | "unifiedExecStartup" | "unifiedExecInteraction";
20057 readonly status: V2ThreadStartedNotification__CommandExecutionStatus;
20058 readonly type: "commandExecution";
20059 }
20060 | {
20061 readonly changes: ReadonlyArray<V2ThreadStartedNotification__FileUpdateChange>;
20062 readonly id: string;
20063 readonly status: V2ThreadStartedNotification__PatchApplyStatus;
20064 readonly type: "fileChange";
20065 }
20066 | {
20067 readonly arguments: unknown;
20068 readonly durationMs?: number | null;
20069 readonly error?: V2ThreadStartedNotification__McpToolCallError | null;
20070 readonly id: string;
20071 readonly result?: V2ThreadStartedNotification__McpToolCallResult | null;
20072 readonly server: string;
20073 readonly status: V2ThreadStartedNotification__McpToolCallStatus;
20074 readonly tool: string;
20075 readonly type: "mcpToolCall";
20076 }
20077 | {
20078 readonly arguments: unknown;
20079 readonly contentItems?: ReadonlyArray<V2ThreadStartedNotification__DynamicToolCallOutputContentItem> | null;
20080 readonly durationMs?: number | null;
20081 readonly id: string;
20082 readonly status: V2ThreadStartedNotification__DynamicToolCallStatus;
20083 readonly success?: boolean | null;
20084 readonly tool: string;
20085 readonly type: "dynamicToolCall";
20086 }
20087 | {
20088 readonly agentsStates: {
20089 readonly [x: string]: V2ThreadStartedNotification__CollabAgentState;
20090 };
20091 readonly id: string;
20092 readonly model?: string | null;
20093 readonly prompt?: string | null;
20094 readonly reasoningEffort?: V2ThreadStartedNotification__ReasoningEffort | null;
20095 readonly receiverThreadIds: ReadonlyArray<string>;
20096 readonly senderThreadId: string;
20097 readonly status: "inProgress" | "completed" | "failed";
20098 readonly tool: "spawnAgent" | "sendInput" | "resumeAgent" | "wait" | "closeAgent";
20099 readonly type: "collabAgentToolCall";
20100 }
20101 | {
20102 readonly action?: V2ThreadStartedNotification__WebSearchAction | null;
20103 readonly id: string;
20104 readonly query: string;
20105 readonly type: "webSearch";
20106 }
20107 | { readonly id: string; readonly path: string; readonly type: "imageView" }
20108 | {
20109 readonly id: string;
20110 readonly result: string;
20111 readonly revisedPrompt?: string | null;
20112 readonly savedPath?: string | null;
20113 readonly status: string;
20114 readonly type: "imageGeneration";
20115 }
20116 | { readonly id: string; readonly review: string; readonly type: "enteredReviewMode" }
20117 | { readonly id: string; readonly review: string; readonly type: "exitedReviewMode" }
20118 | { readonly id: string; readonly type: "contextCompaction" };
20119export const V2ThreadStartedNotification__ThreadItem = Schema.Union(
20120 [
20121 Schema.Struct({
20122 content: Schema.Array(V2ThreadStartedNotification__UserInput),
20123 id: Schema.String,
20124 type: Schema.Literal("userMessage").annotate({ title: "UserMessageThreadItemType" }),
20125 }).annotate({ title: "UserMessageThreadItem" }),
20126 Schema.Struct({
20127 fragments: Schema.Array(V2ThreadStartedNotification__HookPromptFragment),
20128 id: Schema.String,
20129 type: Schema.Literal("hookPrompt").annotate({ title: "HookPromptThreadItemType" }),
20130 }).annotate({ title: "HookPromptThreadItem" }),
20131 Schema.Struct({
20132 id: Schema.String,
20133 memoryCitation: Schema.optionalKey(
20134 Schema.Union([V2ThreadStartedNotification__MemoryCitation, Schema.Null]),
20135 ),
20136 phase: Schema.optionalKey(
20137 Schema.Union([V2ThreadStartedNotification__MessagePhase, Schema.Null]),
20138 ),
20139 text: Schema.String,
20140 type: Schema.Literal("agentMessage").annotate({ title: "AgentMessageThreadItemType" }),
20141 }).annotate({ title: "AgentMessageThreadItem" }),
20142 Schema.Struct({
20143 id: Schema.String,
20144 text: Schema.String,
20145 type: Schema.Literal("plan").annotate({ title: "PlanThreadItemType" }),
20146 }).annotate({
20147 title: "PlanThreadItem",
20148 description:
20149 "EXPERIMENTAL - proposed plan item content. The completed plan item is authoritative and may not match the concatenation of `PlanDelta` text.",
20150 }),
20151 Schema.Struct({
20152 content: Schema.optionalKey(Schema.Array(Schema.String).annotate({ default: [] })),
20153 id: Schema.String,
20154 summary: Schema.optionalKey(Schema.Array(Schema.String).annotate({ default: [] })),
20155 type: Schema.Literal("reasoning").annotate({ title: "ReasoningThreadItemType" }),
20156 }).annotate({ title: "ReasoningThreadItem" }),
20157 Schema.Struct({
20158 aggregatedOutput: Schema.optionalKey(
20159 Schema.Union([
20160 Schema.String.annotate({
20161 description: "The command's output, aggregated from stdout and stderr.",
20162 }),
20163 Schema.Null,
20164 ]),
20165 ),
20166 command: Schema.String.annotate({ description: "The command to be executed." }),
20167 commandActions: Schema.Array(V2ThreadStartedNotification__CommandAction).annotate({
20168 description:
20169 "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.",
20170 }),
20171 cwd: Schema.String.annotate({ description: "The command's working directory." }),
20172 durationMs: Schema.optionalKey(
20173 Schema.Union([
20174 Schema.Number.annotate({
20175 description: "The duration of the command execution in milliseconds.",
20176 format: "int64",
20177 }).check(Schema.isInt()),
20178 Schema.Null,
20179 ]),
20180 ),
20181 exitCode: Schema.optionalKey(
20182 Schema.Union([
20183 Schema.Number.annotate({
20184 description: "The command's exit code.",
20185 format: "int32",
20186 }).check(Schema.isInt()),
20187 Schema.Null,
20188 ]),
20189 ),
20190 id: Schema.String,
20191 processId: Schema.optionalKey(
20192 Schema.Union([
20193 Schema.String.annotate({
20194 description: "Identifier for the underlying PTY process (when available).",
20195 }),
20196 Schema.Null,
20197 ]),
20198 ),
20199 source: Schema.optionalKey(
20200 Schema.Literals([
20201 "agent",
20202 "userShell",
20203 "unifiedExecStartup",
20204 "unifiedExecInteraction",
20205 ]).annotate({ default: "agent" }),
20206 ),
20207 status: V2ThreadStartedNotification__CommandExecutionStatus,
20208 type: Schema.Literal("commandExecution").annotate({
20209 title: "CommandExecutionThreadItemType",
20210 }),
20211 }).annotate({ title: "CommandExecutionThreadItem" }),
20212 Schema.Struct({
20213 changes: Schema.Array(V2ThreadStartedNotification__FileUpdateChange),
20214 id: Schema.String,
20215 status: V2ThreadStartedNotification__PatchApplyStatus,
20216 type: Schema.Literal("fileChange").annotate({ title: "FileChangeThreadItemType" }),
20217 }).annotate({ title: "FileChangeThreadItem" }),
20218 Schema.Struct({
20219 arguments: Schema.Unknown,
20220 durationMs: Schema.optionalKey(
20221 Schema.Union([
20222 Schema.Number.annotate({
20223 description: "The duration of the MCP tool call in milliseconds.",
20224 format: "int64",
20225 }).check(Schema.isInt()),
20226 Schema.Null,
20227 ]),
20228 ),
20229 error: Schema.optionalKey(
20230 Schema.Union([V2ThreadStartedNotification__McpToolCallError, Schema.Null]),
20231 ),
20232 id: Schema.String,
20233 result: Schema.optionalKey(
20234 Schema.Union([V2ThreadStartedNotification__McpToolCallResult, Schema.Null]),
20235 ),
20236 server: Schema.String,
20237 status: V2ThreadStartedNotification__McpToolCallStatus,
20238 tool: Schema.String,
20239 type: Schema.Literal("mcpToolCall").annotate({ title: "McpToolCallThreadItemType" }),
20240 }).annotate({ title: "McpToolCallThreadItem" }),
20241 Schema.Struct({
20242 arguments: Schema.Unknown,
20243 contentItems: Schema.optionalKey(
20244 Schema.Union([
20245 Schema.Array(V2ThreadStartedNotification__DynamicToolCallOutputContentItem),
20246 Schema.Null,
20247 ]),
20248 ),
20249 durationMs: Schema.optionalKey(
20250 Schema.Union([
20251 Schema.Number.annotate({
20252 description: "The duration of the dynamic tool call in milliseconds.",
20253 format: "int64",
20254 }).check(Schema.isInt()),
20255 Schema.Null,
20256 ]),
20257 ),
20258 id: Schema.String,
20259 status: V2ThreadStartedNotification__DynamicToolCallStatus,
20260 success: Schema.optionalKey(Schema.Union([Schema.Boolean, Schema.Null])),
20261 tool: Schema.String,
20262 type: Schema.Literal("dynamicToolCall").annotate({ title: "DynamicToolCallThreadItemType" }),
20263 }).annotate({ title: "DynamicToolCallThreadItem" }),
20264 Schema.Struct({
20265 agentsStates: Schema.Record(
20266 Schema.String,
20267 V2ThreadStartedNotification__CollabAgentState,
20268 ).annotate({ description: "Last known status of the target agents, when available." }),
20269 id: Schema.String.annotate({ description: "Unique identifier for this collab tool call." }),
20270 model: Schema.optionalKey(
20271 Schema.Union([
20272 Schema.String.annotate({
20273 description: "Model requested for the spawned agent, when applicable.",
20274 }),
20275 Schema.Null,
20276 ]),
20277 ),
20278 prompt: Schema.optionalKey(
20279 Schema.Union([
20280 Schema.String.annotate({
20281 description: "Prompt text sent as part of the collab tool call, when available.",
20282 }),
20283 Schema.Null,
20284 ]),
20285 ),
20286 reasoningEffort: Schema.optionalKey(
20287 Schema.Union([V2ThreadStartedNotification__ReasoningEffort, Schema.Null]).annotate({
20288 description: "Reasoning effort requested for the spawned agent, when applicable.",
20289 }),
20290 ),
20291 receiverThreadIds: Schema.Array(Schema.String).annotate({
20292 description:
20293 "Thread ID of the receiving agent, when applicable. In case of spawn operation, this corresponds to the newly spawned agent.",
20294 }),
20295 senderThreadId: Schema.String.annotate({
20296 description: "Thread ID of the agent issuing the collab request.",
20297 }),
20298 status: Schema.Literals(["inProgress", "completed", "failed"]).annotate({
20299 description: "Current status of the collab tool call.",
20300 }),
20301 tool: Schema.Literals([
20302 "spawnAgent",
20303 "sendInput",
20304 "resumeAgent",
20305 "wait",
20306 "closeAgent",
20307 ]).annotate({ description: "Name of the collab tool that was invoked." }),
20308 type: Schema.Literal("collabAgentToolCall").annotate({
20309 title: "CollabAgentToolCallThreadItemType",
20310 }),
20311 }).annotate({ title: "CollabAgentToolCallThreadItem" }),
20312 Schema.Struct({
20313 action: Schema.optionalKey(
20314 Schema.Union([V2ThreadStartedNotification__WebSearchAction, Schema.Null]),
20315 ),
20316 id: Schema.String,
20317 query: Schema.String,
20318 type: Schema.Literal("webSearch").annotate({ title: "WebSearchThreadItemType" }),
20319 }).annotate({ title: "WebSearchThreadItem" }),
20320 Schema.Struct({
20321 id: Schema.String,
20322 path: Schema.String,
20323 type: Schema.Literal("imageView").annotate({ title: "ImageViewThreadItemType" }),
20324 }).annotate({ title: "ImageViewThreadItem" }),
20325 Schema.Struct({
20326 id: Schema.String,
20327 result: Schema.String,
20328 revisedPrompt: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
20329 savedPath: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
20330 status: Schema.String,
20331 type: Schema.Literal("imageGeneration").annotate({ title: "ImageGenerationThreadItemType" }),
20332 }).annotate({ title: "ImageGenerationThreadItem" }),
20333 Schema.Struct({
20334 id: Schema.String,
20335 review: Schema.String,
20336 type: Schema.Literal("enteredReviewMode").annotate({
20337 title: "EnteredReviewModeThreadItemType",
20338 }),
20339 }).annotate({ title: "EnteredReviewModeThreadItem" }),
20340 Schema.Struct({
20341 id: Schema.String,
20342 review: Schema.String,
20343 type: Schema.Literal("exitedReviewMode").annotate({
20344 title: "ExitedReviewModeThreadItemType",
20345 }),
20346 }).annotate({ title: "ExitedReviewModeThreadItem" }),
20347 Schema.Struct({
20348 id: Schema.String,
20349 type: Schema.Literal("contextCompaction").annotate({
20350 title: "ContextCompactionThreadItemType",
20351 }),
20352 }).annotate({ title: "ContextCompactionThreadItem" }),
20353 ],
20354 { mode: "oneOf" },
20355);
20356
20357export type V2ThreadStartResponse__TurnError = {
20358 readonly additionalDetails?: string | null;
20359 readonly codexErrorInfo?: V2ThreadStartResponse__CodexErrorInfo | null;
20360 readonly message: string;
20361};
20362export const V2ThreadStartResponse__TurnError = Schema.Struct({
20363 additionalDetails: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
20364 codexErrorInfo: Schema.optionalKey(
20365 Schema.Union([V2ThreadStartResponse__CodexErrorInfo, Schema.Null]),
20366 ),
20367 message: Schema.String,
20368});
20369
20370export type V2ThreadStartResponse__ThreadItem =
20371 | {
20372 readonly content: ReadonlyArray<V2ThreadStartResponse__UserInput>;
20373 readonly id: string;
20374 readonly type: "userMessage";
20375 }
20376 | {
20377 readonly fragments: ReadonlyArray<V2ThreadStartResponse__HookPromptFragment>;
20378 readonly id: string;
20379 readonly type: "hookPrompt";
20380 }
20381 | {
20382 readonly id: string;
20383 readonly memoryCitation?: V2ThreadStartResponse__MemoryCitation | null;
20384 readonly phase?: V2ThreadStartResponse__MessagePhase | null;
20385 readonly text: string;
20386 readonly type: "agentMessage";
20387 }
20388 | { readonly id: string; readonly text: string; readonly type: "plan" }
20389 | {
20390 readonly content?: ReadonlyArray<string>;
20391 readonly id: string;
20392 readonly summary?: ReadonlyArray<string>;
20393 readonly type: "reasoning";
20394 }
20395 | {
20396 readonly aggregatedOutput?: string | null;
20397 readonly command: string;
20398 readonly commandActions: ReadonlyArray<V2ThreadStartResponse__CommandAction>;
20399 readonly cwd: string;
20400 readonly durationMs?: number | null;
20401 readonly exitCode?: number | null;
20402 readonly id: string;
20403 readonly processId?: string | null;
20404 readonly source?: "agent" | "userShell" | "unifiedExecStartup" | "unifiedExecInteraction";
20405 readonly status: V2ThreadStartResponse__CommandExecutionStatus;
20406 readonly type: "commandExecution";
20407 }
20408 | {
20409 readonly changes: ReadonlyArray<V2ThreadStartResponse__FileUpdateChange>;
20410 readonly id: string;
20411 readonly status: V2ThreadStartResponse__PatchApplyStatus;
20412 readonly type: "fileChange";
20413 }
20414 | {
20415 readonly arguments: unknown;
20416 readonly durationMs?: number | null;
20417 readonly error?: V2ThreadStartResponse__McpToolCallError | null;
20418 readonly id: string;
20419 readonly result?: V2ThreadStartResponse__McpToolCallResult | null;
20420 readonly server: string;
20421 readonly status: V2ThreadStartResponse__McpToolCallStatus;
20422 readonly tool: string;
20423 readonly type: "mcpToolCall";
20424 }
20425 | {
20426 readonly arguments: unknown;
20427 readonly contentItems?: ReadonlyArray<V2ThreadStartResponse__DynamicToolCallOutputContentItem> | null;
20428 readonly durationMs?: number | null;
20429 readonly id: string;
20430 readonly status: V2ThreadStartResponse__DynamicToolCallStatus;
20431 readonly success?: boolean | null;
20432 readonly tool: string;
20433 readonly type: "dynamicToolCall";
20434 }
20435 | {
20436 readonly agentsStates: { readonly [x: string]: V2ThreadStartResponse__CollabAgentState };
20437 readonly id: string;
20438 readonly model?: string | null;
20439 readonly prompt?: string | null;
20440 readonly reasoningEffort?: V2ThreadStartResponse__ReasoningEffort | null;
20441 readonly receiverThreadIds: ReadonlyArray<string>;
20442 readonly senderThreadId: string;
20443 readonly status: "inProgress" | "completed" | "failed";
20444 readonly tool: "spawnAgent" | "sendInput" | "resumeAgent" | "wait" | "closeAgent";
20445 readonly type: "collabAgentToolCall";
20446 }
20447 | {
20448 readonly action?: V2ThreadStartResponse__WebSearchAction | null;
20449 readonly id: string;
20450 readonly query: string;
20451 readonly type: "webSearch";
20452 }
20453 | { readonly id: string; readonly path: string; readonly type: "imageView" }
20454 | {
20455 readonly id: string;
20456 readonly result: string;
20457 readonly revisedPrompt?: string | null;
20458 readonly savedPath?: string | null;
20459 readonly status: string;
20460 readonly type: "imageGeneration";
20461 }
20462 | { readonly id: string; readonly review: string; readonly type: "enteredReviewMode" }
20463 | { readonly id: string; readonly review: string; readonly type: "exitedReviewMode" }
20464 | { readonly id: string; readonly type: "contextCompaction" };
20465export const V2ThreadStartResponse__ThreadItem = Schema.Union(
20466 [
20467 Schema.Struct({
20468 content: Schema.Array(V2ThreadStartResponse__UserInput),
20469 id: Schema.String,
20470 type: Schema.Literal("userMessage").annotate({ title: "UserMessageThreadItemType" }),
20471 }).annotate({ title: "UserMessageThreadItem" }),
20472 Schema.Struct({
20473 fragments: Schema.Array(V2ThreadStartResponse__HookPromptFragment),
20474 id: Schema.String,
20475 type: Schema.Literal("hookPrompt").annotate({ title: "HookPromptThreadItemType" }),
20476 }).annotate({ title: "HookPromptThreadItem" }),
20477 Schema.Struct({
20478 id: Schema.String,
20479 memoryCitation: Schema.optionalKey(
20480 Schema.Union([V2ThreadStartResponse__MemoryCitation, Schema.Null]),
20481 ),
20482 phase: Schema.optionalKey(Schema.Union([V2ThreadStartResponse__MessagePhase, Schema.Null])),
20483 text: Schema.String,
20484 type: Schema.Literal("agentMessage").annotate({ title: "AgentMessageThreadItemType" }),
20485 }).annotate({ title: "AgentMessageThreadItem" }),
20486 Schema.Struct({
20487 id: Schema.String,
20488 text: Schema.String,
20489 type: Schema.Literal("plan").annotate({ title: "PlanThreadItemType" }),
20490 }).annotate({
20491 title: "PlanThreadItem",
20492 description:
20493 "EXPERIMENTAL - proposed plan item content. The completed plan item is authoritative and may not match the concatenation of `PlanDelta` text.",
20494 }),
20495 Schema.Struct({
20496 content: Schema.optionalKey(Schema.Array(Schema.String).annotate({ default: [] })),
20497 id: Schema.String,
20498 summary: Schema.optionalKey(Schema.Array(Schema.String).annotate({ default: [] })),
20499 type: Schema.Literal("reasoning").annotate({ title: "ReasoningThreadItemType" }),
20500 }).annotate({ title: "ReasoningThreadItem" }),
20501 Schema.Struct({
20502 aggregatedOutput: Schema.optionalKey(
20503 Schema.Union([
20504 Schema.String.annotate({
20505 description: "The command's output, aggregated from stdout and stderr.",
20506 }),
20507 Schema.Null,
20508 ]),
20509 ),
20510 command: Schema.String.annotate({ description: "The command to be executed." }),
20511 commandActions: Schema.Array(V2ThreadStartResponse__CommandAction).annotate({
20512 description:
20513 "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.",
20514 }),
20515 cwd: Schema.String.annotate({ description: "The command's working directory." }),
20516 durationMs: Schema.optionalKey(
20517 Schema.Union([
20518 Schema.Number.annotate({
20519 description: "The duration of the command execution in milliseconds.",
20520 format: "int64",
20521 }).check(Schema.isInt()),
20522 Schema.Null,
20523 ]),
20524 ),
20525 exitCode: Schema.optionalKey(
20526 Schema.Union([
20527 Schema.Number.annotate({
20528 description: "The command's exit code.",
20529 format: "int32",
20530 }).check(Schema.isInt()),
20531 Schema.Null,
20532 ]),
20533 ),
20534 id: Schema.String,
20535 processId: Schema.optionalKey(
20536 Schema.Union([
20537 Schema.String.annotate({
20538 description: "Identifier for the underlying PTY process (when available).",
20539 }),
20540 Schema.Null,
20541 ]),
20542 ),
20543 source: Schema.optionalKey(
20544 Schema.Literals([
20545 "agent",
20546 "userShell",
20547 "unifiedExecStartup",
20548 "unifiedExecInteraction",
20549 ]).annotate({ default: "agent" }),
20550 ),
20551 status: V2ThreadStartResponse__CommandExecutionStatus,
20552 type: Schema.Literal("commandExecution").annotate({
20553 title: "CommandExecutionThreadItemType",
20554 }),
20555 }).annotate({ title: "CommandExecutionThreadItem" }),
20556 Schema.Struct({
20557 changes: Schema.Array(V2ThreadStartResponse__FileUpdateChange),
20558 id: Schema.String,
20559 status: V2ThreadStartResponse__PatchApplyStatus,
20560 type: Schema.Literal("fileChange").annotate({ title: "FileChangeThreadItemType" }),
20561 }).annotate({ title: "FileChangeThreadItem" }),
20562 Schema.Struct({
20563 arguments: Schema.Unknown,
20564 durationMs: Schema.optionalKey(
20565 Schema.Union([
20566 Schema.Number.annotate({
20567 description: "The duration of the MCP tool call in milliseconds.",
20568 format: "int64",
20569 }).check(Schema.isInt()),
20570 Schema.Null,
20571 ]),
20572 ),
20573 error: Schema.optionalKey(
20574 Schema.Union([V2ThreadStartResponse__McpToolCallError, Schema.Null]),
20575 ),
20576 id: Schema.String,
20577 result: Schema.optionalKey(
20578 Schema.Union([V2ThreadStartResponse__McpToolCallResult, Schema.Null]),
20579 ),
20580 server: Schema.String,
20581 status: V2ThreadStartResponse__McpToolCallStatus,
20582 tool: Schema.String,
20583 type: Schema.Literal("mcpToolCall").annotate({ title: "McpToolCallThreadItemType" }),
20584 }).annotate({ title: "McpToolCallThreadItem" }),
20585 Schema.Struct({
20586 arguments: Schema.Unknown,
20587 contentItems: Schema.optionalKey(
20588 Schema.Union([
20589 Schema.Array(V2ThreadStartResponse__DynamicToolCallOutputContentItem),
20590 Schema.Null,
20591 ]),
20592 ),
20593 durationMs: Schema.optionalKey(
20594 Schema.Union([
20595 Schema.Number.annotate({
20596 description: "The duration of the dynamic tool call in milliseconds.",
20597 format: "int64",
20598 }).check(Schema.isInt()),
20599 Schema.Null,
20600 ]),
20601 ),
20602 id: Schema.String,
20603 status: V2ThreadStartResponse__DynamicToolCallStatus,
20604 success: Schema.optionalKey(Schema.Union([Schema.Boolean, Schema.Null])),
20605 tool: Schema.String,
20606 type: Schema.Literal("dynamicToolCall").annotate({ title: "DynamicToolCallThreadItemType" }),
20607 }).annotate({ title: "DynamicToolCallThreadItem" }),
20608 Schema.Struct({
20609 agentsStates: Schema.Record(Schema.String, V2ThreadStartResponse__CollabAgentState).annotate({
20610 description: "Last known status of the target agents, when available.",
20611 }),
20612 id: Schema.String.annotate({ description: "Unique identifier for this collab tool call." }),
20613 model: Schema.optionalKey(
20614 Schema.Union([
20615 Schema.String.annotate({
20616 description: "Model requested for the spawned agent, when applicable.",
20617 }),
20618 Schema.Null,
20619 ]),
20620 ),
20621 prompt: Schema.optionalKey(
20622 Schema.Union([
20623 Schema.String.annotate({
20624 description: "Prompt text sent as part of the collab tool call, when available.",
20625 }),
20626 Schema.Null,
20627 ]),
20628 ),
20629 reasoningEffort: Schema.optionalKey(
20630 Schema.Union([V2ThreadStartResponse__ReasoningEffort, Schema.Null]).annotate({
20631 description: "Reasoning effort requested for the spawned agent, when applicable.",
20632 }),
20633 ),
20634 receiverThreadIds: Schema.Array(Schema.String).annotate({
20635 description:
20636 "Thread ID of the receiving agent, when applicable. In case of spawn operation, this corresponds to the newly spawned agent.",
20637 }),
20638 senderThreadId: Schema.String.annotate({
20639 description: "Thread ID of the agent issuing the collab request.",
20640 }),
20641 status: Schema.Literals(["inProgress", "completed", "failed"]).annotate({
20642 description: "Current status of the collab tool call.",
20643 }),
20644 tool: Schema.Literals([
20645 "spawnAgent",
20646 "sendInput",
20647 "resumeAgent",
20648 "wait",
20649 "closeAgent",
20650 ]).annotate({ description: "Name of the collab tool that was invoked." }),
20651 type: Schema.Literal("collabAgentToolCall").annotate({
20652 title: "CollabAgentToolCallThreadItemType",
20653 }),
20654 }).annotate({ title: "CollabAgentToolCallThreadItem" }),
20655 Schema.Struct({
20656 action: Schema.optionalKey(
20657 Schema.Union([V2ThreadStartResponse__WebSearchAction, Schema.Null]),
20658 ),
20659 id: Schema.String,
20660 query: Schema.String,
20661 type: Schema.Literal("webSearch").annotate({ title: "WebSearchThreadItemType" }),
20662 }).annotate({ title: "WebSearchThreadItem" }),
20663 Schema.Struct({
20664 id: Schema.String,
20665 path: Schema.String,
20666 type: Schema.Literal("imageView").annotate({ title: "ImageViewThreadItemType" }),
20667 }).annotate({ title: "ImageViewThreadItem" }),
20668 Schema.Struct({
20669 id: Schema.String,
20670 result: Schema.String,
20671 revisedPrompt: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
20672 savedPath: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
20673 status: Schema.String,
20674 type: Schema.Literal("imageGeneration").annotate({ title: "ImageGenerationThreadItemType" }),
20675 }).annotate({ title: "ImageGenerationThreadItem" }),
20676 Schema.Struct({
20677 id: Schema.String,
20678 review: Schema.String,
20679 type: Schema.Literal("enteredReviewMode").annotate({
20680 title: "EnteredReviewModeThreadItemType",
20681 }),
20682 }).annotate({ title: "EnteredReviewModeThreadItem" }),
20683 Schema.Struct({
20684 id: Schema.String,
20685 review: Schema.String,
20686 type: Schema.Literal("exitedReviewMode").annotate({
20687 title: "ExitedReviewModeThreadItemType",
20688 }),
20689 }).annotate({ title: "ExitedReviewModeThreadItem" }),
20690 Schema.Struct({
20691 id: Schema.String,
20692 type: Schema.Literal("contextCompaction").annotate({
20693 title: "ContextCompactionThreadItemType",
20694 }),
20695 }).annotate({ title: "ContextCompactionThreadItem" }),
20696 ],
20697 { mode: "oneOf" },
20698);
20699
20700export type V2ThreadUnarchiveResponse__TurnError = {
20701 readonly additionalDetails?: string | null;
20702 readonly codexErrorInfo?: V2ThreadUnarchiveResponse__CodexErrorInfo | null;
20703 readonly message: string;
20704};
20705export const V2ThreadUnarchiveResponse__TurnError = Schema.Struct({
20706 additionalDetails: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
20707 codexErrorInfo: Schema.optionalKey(
20708 Schema.Union([V2ThreadUnarchiveResponse__CodexErrorInfo, Schema.Null]),
20709 ),
20710 message: Schema.String,
20711});
20712
20713export type V2ThreadUnarchiveResponse__ThreadItem =
20714 | {
20715 readonly content: ReadonlyArray<V2ThreadUnarchiveResponse__UserInput>;
20716 readonly id: string;
20717 readonly type: "userMessage";
20718 }
20719 | {
20720 readonly fragments: ReadonlyArray<V2ThreadUnarchiveResponse__HookPromptFragment>;
20721 readonly id: string;
20722 readonly type: "hookPrompt";
20723 }
20724 | {
20725 readonly id: string;
20726 readonly memoryCitation?: V2ThreadUnarchiveResponse__MemoryCitation | null;
20727 readonly phase?: V2ThreadUnarchiveResponse__MessagePhase | null;
20728 readonly text: string;
20729 readonly type: "agentMessage";
20730 }
20731 | { readonly id: string; readonly text: string; readonly type: "plan" }
20732 | {
20733 readonly content?: ReadonlyArray<string>;
20734 readonly id: string;
20735 readonly summary?: ReadonlyArray<string>;
20736 readonly type: "reasoning";
20737 }
20738 | {
20739 readonly aggregatedOutput?: string | null;
20740 readonly command: string;
20741 readonly commandActions: ReadonlyArray<V2ThreadUnarchiveResponse__CommandAction>;
20742 readonly cwd: string;
20743 readonly durationMs?: number | null;
20744 readonly exitCode?: number | null;
20745 readonly id: string;
20746 readonly processId?: string | null;
20747 readonly source?: "agent" | "userShell" | "unifiedExecStartup" | "unifiedExecInteraction";
20748 readonly status: V2ThreadUnarchiveResponse__CommandExecutionStatus;
20749 readonly type: "commandExecution";
20750 }
20751 | {
20752 readonly changes: ReadonlyArray<V2ThreadUnarchiveResponse__FileUpdateChange>;
20753 readonly id: string;
20754 readonly status: V2ThreadUnarchiveResponse__PatchApplyStatus;
20755 readonly type: "fileChange";
20756 }
20757 | {
20758 readonly arguments: unknown;
20759 readonly durationMs?: number | null;
20760 readonly error?: V2ThreadUnarchiveResponse__McpToolCallError | null;
20761 readonly id: string;
20762 readonly result?: V2ThreadUnarchiveResponse__McpToolCallResult | null;
20763 readonly server: string;
20764 readonly status: V2ThreadUnarchiveResponse__McpToolCallStatus;
20765 readonly tool: string;
20766 readonly type: "mcpToolCall";
20767 }
20768 | {
20769 readonly arguments: unknown;
20770 readonly contentItems?: ReadonlyArray<V2ThreadUnarchiveResponse__DynamicToolCallOutputContentItem> | null;
20771 readonly durationMs?: number | null;
20772 readonly id: string;
20773 readonly status: V2ThreadUnarchiveResponse__DynamicToolCallStatus;
20774 readonly success?: boolean | null;
20775 readonly tool: string;
20776 readonly type: "dynamicToolCall";
20777 }
20778 | {
20779 readonly agentsStates: { readonly [x: string]: V2ThreadUnarchiveResponse__CollabAgentState };
20780 readonly id: string;
20781 readonly model?: string | null;
20782 readonly prompt?: string | null;
20783 readonly reasoningEffort?: V2ThreadUnarchiveResponse__ReasoningEffort | null;
20784 readonly receiverThreadIds: ReadonlyArray<string>;
20785 readonly senderThreadId: string;
20786 readonly status: "inProgress" | "completed" | "failed";
20787 readonly tool: "spawnAgent" | "sendInput" | "resumeAgent" | "wait" | "closeAgent";
20788 readonly type: "collabAgentToolCall";
20789 }
20790 | {
20791 readonly action?: V2ThreadUnarchiveResponse__WebSearchAction | null;
20792 readonly id: string;
20793 readonly query: string;
20794 readonly type: "webSearch";
20795 }
20796 | { readonly id: string; readonly path: string; readonly type: "imageView" }
20797 | {
20798 readonly id: string;
20799 readonly result: string;
20800 readonly revisedPrompt?: string | null;
20801 readonly savedPath?: string | null;
20802 readonly status: string;
20803 readonly type: "imageGeneration";
20804 }
20805 | { readonly id: string; readonly review: string; readonly type: "enteredReviewMode" }
20806 | { readonly id: string; readonly review: string; readonly type: "exitedReviewMode" }
20807 | { readonly id: string; readonly type: "contextCompaction" };
20808export const V2ThreadUnarchiveResponse__ThreadItem = Schema.Union(
20809 [
20810 Schema.Struct({
20811 content: Schema.Array(V2ThreadUnarchiveResponse__UserInput),
20812 id: Schema.String,
20813 type: Schema.Literal("userMessage").annotate({ title: "UserMessageThreadItemType" }),
20814 }).annotate({ title: "UserMessageThreadItem" }),
20815 Schema.Struct({
20816 fragments: Schema.Array(V2ThreadUnarchiveResponse__HookPromptFragment),
20817 id: Schema.String,
20818 type: Schema.Literal("hookPrompt").annotate({ title: "HookPromptThreadItemType" }),
20819 }).annotate({ title: "HookPromptThreadItem" }),
20820 Schema.Struct({
20821 id: Schema.String,
20822 memoryCitation: Schema.optionalKey(
20823 Schema.Union([V2ThreadUnarchiveResponse__MemoryCitation, Schema.Null]),
20824 ),
20825 phase: Schema.optionalKey(
20826 Schema.Union([V2ThreadUnarchiveResponse__MessagePhase, Schema.Null]),
20827 ),
20828 text: Schema.String,
20829 type: Schema.Literal("agentMessage").annotate({ title: "AgentMessageThreadItemType" }),
20830 }).annotate({ title: "AgentMessageThreadItem" }),
20831 Schema.Struct({
20832 id: Schema.String,
20833 text: Schema.String,
20834 type: Schema.Literal("plan").annotate({ title: "PlanThreadItemType" }),
20835 }).annotate({
20836 title: "PlanThreadItem",
20837 description:
20838 "EXPERIMENTAL - proposed plan item content. The completed plan item is authoritative and may not match the concatenation of `PlanDelta` text.",
20839 }),
20840 Schema.Struct({
20841 content: Schema.optionalKey(Schema.Array(Schema.String).annotate({ default: [] })),
20842 id: Schema.String,
20843 summary: Schema.optionalKey(Schema.Array(Schema.String).annotate({ default: [] })),
20844 type: Schema.Literal("reasoning").annotate({ title: "ReasoningThreadItemType" }),
20845 }).annotate({ title: "ReasoningThreadItem" }),
20846 Schema.Struct({
20847 aggregatedOutput: Schema.optionalKey(
20848 Schema.Union([
20849 Schema.String.annotate({
20850 description: "The command's output, aggregated from stdout and stderr.",
20851 }),
20852 Schema.Null,
20853 ]),
20854 ),
20855 command: Schema.String.annotate({ description: "The command to be executed." }),
20856 commandActions: Schema.Array(V2ThreadUnarchiveResponse__CommandAction).annotate({
20857 description:
20858 "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.",
20859 }),
20860 cwd: Schema.String.annotate({ description: "The command's working directory." }),
20861 durationMs: Schema.optionalKey(
20862 Schema.Union([
20863 Schema.Number.annotate({
20864 description: "The duration of the command execution in milliseconds.",
20865 format: "int64",
20866 }).check(Schema.isInt()),
20867 Schema.Null,
20868 ]),
20869 ),
20870 exitCode: Schema.optionalKey(
20871 Schema.Union([
20872 Schema.Number.annotate({
20873 description: "The command's exit code.",
20874 format: "int32",
20875 }).check(Schema.isInt()),
20876 Schema.Null,
20877 ]),
20878 ),
20879 id: Schema.String,
20880 processId: Schema.optionalKey(
20881 Schema.Union([
20882 Schema.String.annotate({
20883 description: "Identifier for the underlying PTY process (when available).",
20884 }),
20885 Schema.Null,
20886 ]),
20887 ),
20888 source: Schema.optionalKey(
20889 Schema.Literals([
20890 "agent",
20891 "userShell",
20892 "unifiedExecStartup",
20893 "unifiedExecInteraction",
20894 ]).annotate({ default: "agent" }),
20895 ),
20896 status: V2ThreadUnarchiveResponse__CommandExecutionStatus,
20897 type: Schema.Literal("commandExecution").annotate({
20898 title: "CommandExecutionThreadItemType",
20899 }),
20900 }).annotate({ title: "CommandExecutionThreadItem" }),
20901 Schema.Struct({
20902 changes: Schema.Array(V2ThreadUnarchiveResponse__FileUpdateChange),
20903 id: Schema.String,
20904 status: V2ThreadUnarchiveResponse__PatchApplyStatus,
20905 type: Schema.Literal("fileChange").annotate({ title: "FileChangeThreadItemType" }),
20906 }).annotate({ title: "FileChangeThreadItem" }),
20907 Schema.Struct({
20908 arguments: Schema.Unknown,
20909 durationMs: Schema.optionalKey(
20910 Schema.Union([
20911 Schema.Number.annotate({
20912 description: "The duration of the MCP tool call in milliseconds.",
20913 format: "int64",
20914 }).check(Schema.isInt()),
20915 Schema.Null,
20916 ]),
20917 ),
20918 error: Schema.optionalKey(
20919 Schema.Union([V2ThreadUnarchiveResponse__McpToolCallError, Schema.Null]),
20920 ),
20921 id: Schema.String,
20922 result: Schema.optionalKey(
20923 Schema.Union([V2ThreadUnarchiveResponse__McpToolCallResult, Schema.Null]),
20924 ),
20925 server: Schema.String,
20926 status: V2ThreadUnarchiveResponse__McpToolCallStatus,
20927 tool: Schema.String,
20928 type: Schema.Literal("mcpToolCall").annotate({ title: "McpToolCallThreadItemType" }),
20929 }).annotate({ title: "McpToolCallThreadItem" }),
20930 Schema.Struct({
20931 arguments: Schema.Unknown,
20932 contentItems: Schema.optionalKey(
20933 Schema.Union([
20934 Schema.Array(V2ThreadUnarchiveResponse__DynamicToolCallOutputContentItem),
20935 Schema.Null,
20936 ]),
20937 ),
20938 durationMs: Schema.optionalKey(
20939 Schema.Union([
20940 Schema.Number.annotate({
20941 description: "The duration of the dynamic tool call in milliseconds.",
20942 format: "int64",
20943 }).check(Schema.isInt()),
20944 Schema.Null,
20945 ]),
20946 ),
20947 id: Schema.String,
20948 status: V2ThreadUnarchiveResponse__DynamicToolCallStatus,
20949 success: Schema.optionalKey(Schema.Union([Schema.Boolean, Schema.Null])),
20950 tool: Schema.String,
20951 type: Schema.Literal("dynamicToolCall").annotate({ title: "DynamicToolCallThreadItemType" }),
20952 }).annotate({ title: "DynamicToolCallThreadItem" }),
20953 Schema.Struct({
20954 agentsStates: Schema.Record(
20955 Schema.String,
20956 V2ThreadUnarchiveResponse__CollabAgentState,
20957 ).annotate({ description: "Last known status of the target agents, when available." }),
20958 id: Schema.String.annotate({ description: "Unique identifier for this collab tool call." }),
20959 model: Schema.optionalKey(
20960 Schema.Union([
20961 Schema.String.annotate({
20962 description: "Model requested for the spawned agent, when applicable.",
20963 }),
20964 Schema.Null,
20965 ]),
20966 ),
20967 prompt: Schema.optionalKey(
20968 Schema.Union([
20969 Schema.String.annotate({
20970 description: "Prompt text sent as part of the collab tool call, when available.",
20971 }),
20972 Schema.Null,
20973 ]),
20974 ),
20975 reasoningEffort: Schema.optionalKey(
20976 Schema.Union([V2ThreadUnarchiveResponse__ReasoningEffort, Schema.Null]).annotate({
20977 description: "Reasoning effort requested for the spawned agent, when applicable.",
20978 }),
20979 ),
20980 receiverThreadIds: Schema.Array(Schema.String).annotate({
20981 description:
20982 "Thread ID of the receiving agent, when applicable. In case of spawn operation, this corresponds to the newly spawned agent.",
20983 }),
20984 senderThreadId: Schema.String.annotate({
20985 description: "Thread ID of the agent issuing the collab request.",
20986 }),
20987 status: Schema.Literals(["inProgress", "completed", "failed"]).annotate({
20988 description: "Current status of the collab tool call.",
20989 }),
20990 tool: Schema.Literals([
20991 "spawnAgent",
20992 "sendInput",
20993 "resumeAgent",
20994 "wait",
20995 "closeAgent",
20996 ]).annotate({ description: "Name of the collab tool that was invoked." }),
20997 type: Schema.Literal("collabAgentToolCall").annotate({
20998 title: "CollabAgentToolCallThreadItemType",
20999 }),
21000 }).annotate({ title: "CollabAgentToolCallThreadItem" }),
21001 Schema.Struct({
21002 action: Schema.optionalKey(
21003 Schema.Union([V2ThreadUnarchiveResponse__WebSearchAction, Schema.Null]),
21004 ),
21005 id: Schema.String,
21006 query: Schema.String,
21007 type: Schema.Literal("webSearch").annotate({ title: "WebSearchThreadItemType" }),
21008 }).annotate({ title: "WebSearchThreadItem" }),
21009 Schema.Struct({
21010 id: Schema.String,
21011 path: Schema.String,
21012 type: Schema.Literal("imageView").annotate({ title: "ImageViewThreadItemType" }),
21013 }).annotate({ title: "ImageViewThreadItem" }),
21014 Schema.Struct({
21015 id: Schema.String,
21016 result: Schema.String,
21017 revisedPrompt: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
21018 savedPath: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
21019 status: Schema.String,
21020 type: Schema.Literal("imageGeneration").annotate({ title: "ImageGenerationThreadItemType" }),
21021 }).annotate({ title: "ImageGenerationThreadItem" }),
21022 Schema.Struct({
21023 id: Schema.String,
21024 review: Schema.String,
21025 type: Schema.Literal("enteredReviewMode").annotate({
21026 title: "EnteredReviewModeThreadItemType",
21027 }),
21028 }).annotate({ title: "EnteredReviewModeThreadItem" }),
21029 Schema.Struct({
21030 id: Schema.String,
21031 review: Schema.String,
21032 type: Schema.Literal("exitedReviewMode").annotate({
21033 title: "ExitedReviewModeThreadItemType",
21034 }),
21035 }).annotate({ title: "ExitedReviewModeThreadItem" }),
21036 Schema.Struct({
21037 id: Schema.String,
21038 type: Schema.Literal("contextCompaction").annotate({
21039 title: "ContextCompactionThreadItemType",
21040 }),
21041 }).annotate({ title: "ContextCompactionThreadItem" }),
21042 ],
21043 { mode: "oneOf" },
21044);
21045
21046export type V2TurnCompletedNotification__TurnError = {
21047 readonly additionalDetails?: string | null;
21048 readonly codexErrorInfo?: V2TurnCompletedNotification__CodexErrorInfo | null;
21049 readonly message: string;
21050};
21051export const V2TurnCompletedNotification__TurnError = Schema.Struct({
21052 additionalDetails: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
21053 codexErrorInfo: Schema.optionalKey(
21054 Schema.Union([V2TurnCompletedNotification__CodexErrorInfo, Schema.Null]),
21055 ),
21056 message: Schema.String,
21057});
21058
21059export type V2TurnCompletedNotification__ThreadItem =
21060 | {
21061 readonly content: ReadonlyArray<V2TurnCompletedNotification__UserInput>;
21062 readonly id: string;
21063 readonly type: "userMessage";
21064 }
21065 | {
21066 readonly fragments: ReadonlyArray<V2TurnCompletedNotification__HookPromptFragment>;
21067 readonly id: string;
21068 readonly type: "hookPrompt";
21069 }
21070 | {
21071 readonly id: string;
21072 readonly memoryCitation?: V2TurnCompletedNotification__MemoryCitation | null;
21073 readonly phase?: V2TurnCompletedNotification__MessagePhase | null;
21074 readonly text: string;
21075 readonly type: "agentMessage";
21076 }
21077 | { readonly id: string; readonly text: string; readonly type: "plan" }
21078 | {
21079 readonly content?: ReadonlyArray<string>;
21080 readonly id: string;
21081 readonly summary?: ReadonlyArray<string>;
21082 readonly type: "reasoning";
21083 }
21084 | {
21085 readonly aggregatedOutput?: string | null;
21086 readonly command: string;
21087 readonly commandActions: ReadonlyArray<V2TurnCompletedNotification__CommandAction>;
21088 readonly cwd: string;
21089 readonly durationMs?: number | null;
21090 readonly exitCode?: number | null;
21091 readonly id: string;
21092 readonly processId?: string | null;
21093 readonly source?: "agent" | "userShell" | "unifiedExecStartup" | "unifiedExecInteraction";
21094 readonly status: V2TurnCompletedNotification__CommandExecutionStatus;
21095 readonly type: "commandExecution";
21096 }
21097 | {
21098 readonly changes: ReadonlyArray<V2TurnCompletedNotification__FileUpdateChange>;
21099 readonly id: string;
21100 readonly status: V2TurnCompletedNotification__PatchApplyStatus;
21101 readonly type: "fileChange";
21102 }
21103 | {
21104 readonly arguments: unknown;
21105 readonly durationMs?: number | null;
21106 readonly error?: V2TurnCompletedNotification__McpToolCallError | null;
21107 readonly id: string;
21108 readonly result?: V2TurnCompletedNotification__McpToolCallResult | null;
21109 readonly server: string;
21110 readonly status: V2TurnCompletedNotification__McpToolCallStatus;
21111 readonly tool: string;
21112 readonly type: "mcpToolCall";
21113 }
21114 | {
21115 readonly arguments: unknown;
21116 readonly contentItems?: ReadonlyArray<V2TurnCompletedNotification__DynamicToolCallOutputContentItem> | null;
21117 readonly durationMs?: number | null;
21118 readonly id: string;
21119 readonly status: V2TurnCompletedNotification__DynamicToolCallStatus;
21120 readonly success?: boolean | null;
21121 readonly tool: string;
21122 readonly type: "dynamicToolCall";
21123 }
21124 | {
21125 readonly agentsStates: {
21126 readonly [x: string]: V2TurnCompletedNotification__CollabAgentState;
21127 };
21128 readonly id: string;
21129 readonly model?: string | null;
21130 readonly prompt?: string | null;
21131 readonly reasoningEffort?: V2TurnCompletedNotification__ReasoningEffort | null;
21132 readonly receiverThreadIds: ReadonlyArray<string>;
21133 readonly senderThreadId: string;
21134 readonly status: "inProgress" | "completed" | "failed";
21135 readonly tool: "spawnAgent" | "sendInput" | "resumeAgent" | "wait" | "closeAgent";
21136 readonly type: "collabAgentToolCall";
21137 }
21138 | {
21139 readonly action?: V2TurnCompletedNotification__WebSearchAction | null;
21140 readonly id: string;
21141 readonly query: string;
21142 readonly type: "webSearch";
21143 }
21144 | { readonly id: string; readonly path: string; readonly type: "imageView" }
21145 | {
21146 readonly id: string;
21147 readonly result: string;
21148 readonly revisedPrompt?: string | null;
21149 readonly savedPath?: string | null;
21150 readonly status: string;
21151 readonly type: "imageGeneration";
21152 }
21153 | { readonly id: string; readonly review: string; readonly type: "enteredReviewMode" }
21154 | { readonly id: string; readonly review: string; readonly type: "exitedReviewMode" }
21155 | { readonly id: string; readonly type: "contextCompaction" };
21156export const V2TurnCompletedNotification__ThreadItem = Schema.Union(
21157 [
21158 Schema.Struct({
21159 content: Schema.Array(V2TurnCompletedNotification__UserInput),
21160 id: Schema.String,
21161 type: Schema.Literal("userMessage").annotate({ title: "UserMessageThreadItemType" }),
21162 }).annotate({ title: "UserMessageThreadItem" }),
21163 Schema.Struct({
21164 fragments: Schema.Array(V2TurnCompletedNotification__HookPromptFragment),
21165 id: Schema.String,
21166 type: Schema.Literal("hookPrompt").annotate({ title: "HookPromptThreadItemType" }),
21167 }).annotate({ title: "HookPromptThreadItem" }),
21168 Schema.Struct({
21169 id: Schema.String,
21170 memoryCitation: Schema.optionalKey(
21171 Schema.Union([V2TurnCompletedNotification__MemoryCitation, Schema.Null]),
21172 ),
21173 phase: Schema.optionalKey(
21174 Schema.Union([V2TurnCompletedNotification__MessagePhase, Schema.Null]),
21175 ),
21176 text: Schema.String,
21177 type: Schema.Literal("agentMessage").annotate({ title: "AgentMessageThreadItemType" }),
21178 }).annotate({ title: "AgentMessageThreadItem" }),
21179 Schema.Struct({
21180 id: Schema.String,
21181 text: Schema.String,
21182 type: Schema.Literal("plan").annotate({ title: "PlanThreadItemType" }),
21183 }).annotate({
21184 title: "PlanThreadItem",
21185 description:
21186 "EXPERIMENTAL - proposed plan item content. The completed plan item is authoritative and may not match the concatenation of `PlanDelta` text.",
21187 }),
21188 Schema.Struct({
21189 content: Schema.optionalKey(Schema.Array(Schema.String).annotate({ default: [] })),
21190 id: Schema.String,
21191 summary: Schema.optionalKey(Schema.Array(Schema.String).annotate({ default: [] })),
21192 type: Schema.Literal("reasoning").annotate({ title: "ReasoningThreadItemType" }),
21193 }).annotate({ title: "ReasoningThreadItem" }),
21194 Schema.Struct({
21195 aggregatedOutput: Schema.optionalKey(
21196 Schema.Union([
21197 Schema.String.annotate({
21198 description: "The command's output, aggregated from stdout and stderr.",
21199 }),
21200 Schema.Null,
21201 ]),
21202 ),
21203 command: Schema.String.annotate({ description: "The command to be executed." }),
21204 commandActions: Schema.Array(V2TurnCompletedNotification__CommandAction).annotate({
21205 description:
21206 "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.",
21207 }),
21208 cwd: Schema.String.annotate({ description: "The command's working directory." }),
21209 durationMs: Schema.optionalKey(
21210 Schema.Union([
21211 Schema.Number.annotate({
21212 description: "The duration of the command execution in milliseconds.",
21213 format: "int64",
21214 }).check(Schema.isInt()),
21215 Schema.Null,
21216 ]),
21217 ),
21218 exitCode: Schema.optionalKey(
21219 Schema.Union([
21220 Schema.Number.annotate({
21221 description: "The command's exit code.",
21222 format: "int32",
21223 }).check(Schema.isInt()),
21224 Schema.Null,
21225 ]),
21226 ),
21227 id: Schema.String,
21228 processId: Schema.optionalKey(
21229 Schema.Union([
21230 Schema.String.annotate({
21231 description: "Identifier for the underlying PTY process (when available).",
21232 }),
21233 Schema.Null,
21234 ]),
21235 ),
21236 source: Schema.optionalKey(
21237 Schema.Literals([
21238 "agent",
21239 "userShell",
21240 "unifiedExecStartup",
21241 "unifiedExecInteraction",
21242 ]).annotate({ default: "agent" }),
21243 ),
21244 status: V2TurnCompletedNotification__CommandExecutionStatus,
21245 type: Schema.Literal("commandExecution").annotate({
21246 title: "CommandExecutionThreadItemType",
21247 }),
21248 }).annotate({ title: "CommandExecutionThreadItem" }),
21249 Schema.Struct({
21250 changes: Schema.Array(V2TurnCompletedNotification__FileUpdateChange),
21251 id: Schema.String,
21252 status: V2TurnCompletedNotification__PatchApplyStatus,
21253 type: Schema.Literal("fileChange").annotate({ title: "FileChangeThreadItemType" }),
21254 }).annotate({ title: "FileChangeThreadItem" }),
21255 Schema.Struct({
21256 arguments: Schema.Unknown,
21257 durationMs: Schema.optionalKey(
21258 Schema.Union([
21259 Schema.Number.annotate({
21260 description: "The duration of the MCP tool call in milliseconds.",
21261 format: "int64",
21262 }).check(Schema.isInt()),
21263 Schema.Null,
21264 ]),
21265 ),
21266 error: Schema.optionalKey(
21267 Schema.Union([V2TurnCompletedNotification__McpToolCallError, Schema.Null]),
21268 ),
21269 id: Schema.String,
21270 result: Schema.optionalKey(
21271 Schema.Union([V2TurnCompletedNotification__McpToolCallResult, Schema.Null]),
21272 ),
21273 server: Schema.String,
21274 status: V2TurnCompletedNotification__McpToolCallStatus,
21275 tool: Schema.String,
21276 type: Schema.Literal("mcpToolCall").annotate({ title: "McpToolCallThreadItemType" }),
21277 }).annotate({ title: "McpToolCallThreadItem" }),
21278 Schema.Struct({
21279 arguments: Schema.Unknown,
21280 contentItems: Schema.optionalKey(
21281 Schema.Union([
21282 Schema.Array(V2TurnCompletedNotification__DynamicToolCallOutputContentItem),
21283 Schema.Null,
21284 ]),
21285 ),
21286 durationMs: Schema.optionalKey(
21287 Schema.Union([
21288 Schema.Number.annotate({
21289 description: "The duration of the dynamic tool call in milliseconds.",
21290 format: "int64",
21291 }).check(Schema.isInt()),
21292 Schema.Null,
21293 ]),
21294 ),
21295 id: Schema.String,
21296 status: V2TurnCompletedNotification__DynamicToolCallStatus,
21297 success: Schema.optionalKey(Schema.Union([Schema.Boolean, Schema.Null])),
21298 tool: Schema.String,
21299 type: Schema.Literal("dynamicToolCall").annotate({ title: "DynamicToolCallThreadItemType" }),
21300 }).annotate({ title: "DynamicToolCallThreadItem" }),
21301 Schema.Struct({
21302 agentsStates: Schema.Record(
21303 Schema.String,
21304 V2TurnCompletedNotification__CollabAgentState,
21305 ).annotate({ description: "Last known status of the target agents, when available." }),
21306 id: Schema.String.annotate({ description: "Unique identifier for this collab tool call." }),
21307 model: Schema.optionalKey(
21308 Schema.Union([
21309 Schema.String.annotate({
21310 description: "Model requested for the spawned agent, when applicable.",
21311 }),
21312 Schema.Null,
21313 ]),
21314 ),
21315 prompt: Schema.optionalKey(
21316 Schema.Union([
21317 Schema.String.annotate({
21318 description: "Prompt text sent as part of the collab tool call, when available.",
21319 }),
21320 Schema.Null,
21321 ]),
21322 ),
21323 reasoningEffort: Schema.optionalKey(
21324 Schema.Union([V2TurnCompletedNotification__ReasoningEffort, Schema.Null]).annotate({
21325 description: "Reasoning effort requested for the spawned agent, when applicable.",
21326 }),
21327 ),
21328 receiverThreadIds: Schema.Array(Schema.String).annotate({
21329 description:
21330 "Thread ID of the receiving agent, when applicable. In case of spawn operation, this corresponds to the newly spawned agent.",
21331 }),
21332 senderThreadId: Schema.String.annotate({
21333 description: "Thread ID of the agent issuing the collab request.",
21334 }),
21335 status: Schema.Literals(["inProgress", "completed", "failed"]).annotate({
21336 description: "Current status of the collab tool call.",
21337 }),
21338 tool: Schema.Literals([
21339 "spawnAgent",
21340 "sendInput",
21341 "resumeAgent",
21342 "wait",
21343 "closeAgent",
21344 ]).annotate({ description: "Name of the collab tool that was invoked." }),
21345 type: Schema.Literal("collabAgentToolCall").annotate({
21346 title: "CollabAgentToolCallThreadItemType",
21347 }),
21348 }).annotate({ title: "CollabAgentToolCallThreadItem" }),
21349 Schema.Struct({
21350 action: Schema.optionalKey(
21351 Schema.Union([V2TurnCompletedNotification__WebSearchAction, Schema.Null]),
21352 ),
21353 id: Schema.String,
21354 query: Schema.String,
21355 type: Schema.Literal("webSearch").annotate({ title: "WebSearchThreadItemType" }),
21356 }).annotate({ title: "WebSearchThreadItem" }),
21357 Schema.Struct({
21358 id: Schema.String,
21359 path: Schema.String,
21360 type: Schema.Literal("imageView").annotate({ title: "ImageViewThreadItemType" }),
21361 }).annotate({ title: "ImageViewThreadItem" }),
21362 Schema.Struct({
21363 id: Schema.String,
21364 result: Schema.String,
21365 revisedPrompt: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
21366 savedPath: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
21367 status: Schema.String,
21368 type: Schema.Literal("imageGeneration").annotate({ title: "ImageGenerationThreadItemType" }),
21369 }).annotate({ title: "ImageGenerationThreadItem" }),
21370 Schema.Struct({
21371 id: Schema.String,
21372 review: Schema.String,
21373 type: Schema.Literal("enteredReviewMode").annotate({
21374 title: "EnteredReviewModeThreadItemType",
21375 }),
21376 }).annotate({ title: "EnteredReviewModeThreadItem" }),
21377 Schema.Struct({
21378 id: Schema.String,
21379 review: Schema.String,
21380 type: Schema.Literal("exitedReviewMode").annotate({
21381 title: "ExitedReviewModeThreadItemType",
21382 }),
21383 }).annotate({ title: "ExitedReviewModeThreadItem" }),
21384 Schema.Struct({
21385 id: Schema.String,
21386 type: Schema.Literal("contextCompaction").annotate({
21387 title: "ContextCompactionThreadItemType",
21388 }),
21389 }).annotate({ title: "ContextCompactionThreadItem" }),
21390 ],
21391 { mode: "oneOf" },
21392);
21393
21394export type V2TurnStartedNotification__TurnError = {
21395 readonly additionalDetails?: string | null;
21396 readonly codexErrorInfo?: V2TurnStartedNotification__CodexErrorInfo | null;
21397 readonly message: string;
21398};
21399export const V2TurnStartedNotification__TurnError = Schema.Struct({
21400 additionalDetails: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
21401 codexErrorInfo: Schema.optionalKey(
21402 Schema.Union([V2TurnStartedNotification__CodexErrorInfo, Schema.Null]),
21403 ),
21404 message: Schema.String,
21405});
21406
21407export type V2TurnStartedNotification__ThreadItem =
21408 | {
21409 readonly content: ReadonlyArray<V2TurnStartedNotification__UserInput>;
21410 readonly id: string;
21411 readonly type: "userMessage";
21412 }
21413 | {
21414 readonly fragments: ReadonlyArray<V2TurnStartedNotification__HookPromptFragment>;
21415 readonly id: string;
21416 readonly type: "hookPrompt";
21417 }
21418 | {
21419 readonly id: string;
21420 readonly memoryCitation?: V2TurnStartedNotification__MemoryCitation | null;
21421 readonly phase?: V2TurnStartedNotification__MessagePhase | null;
21422 readonly text: string;
21423 readonly type: "agentMessage";
21424 }
21425 | { readonly id: string; readonly text: string; readonly type: "plan" }
21426 | {
21427 readonly content?: ReadonlyArray<string>;
21428 readonly id: string;
21429 readonly summary?: ReadonlyArray<string>;
21430 readonly type: "reasoning";
21431 }
21432 | {
21433 readonly aggregatedOutput?: string | null;
21434 readonly command: string;
21435 readonly commandActions: ReadonlyArray<V2TurnStartedNotification__CommandAction>;
21436 readonly cwd: string;
21437 readonly durationMs?: number | null;
21438 readonly exitCode?: number | null;
21439 readonly id: string;
21440 readonly processId?: string | null;
21441 readonly source?: "agent" | "userShell" | "unifiedExecStartup" | "unifiedExecInteraction";
21442 readonly status: V2TurnStartedNotification__CommandExecutionStatus;
21443 readonly type: "commandExecution";
21444 }
21445 | {
21446 readonly changes: ReadonlyArray<V2TurnStartedNotification__FileUpdateChange>;
21447 readonly id: string;
21448 readonly status: V2TurnStartedNotification__PatchApplyStatus;
21449 readonly type: "fileChange";
21450 }
21451 | {
21452 readonly arguments: unknown;
21453 readonly durationMs?: number | null;
21454 readonly error?: V2TurnStartedNotification__McpToolCallError | null;
21455 readonly id: string;
21456 readonly result?: V2TurnStartedNotification__McpToolCallResult | null;
21457 readonly server: string;
21458 readonly status: V2TurnStartedNotification__McpToolCallStatus;
21459 readonly tool: string;
21460 readonly type: "mcpToolCall";
21461 }
21462 | {
21463 readonly arguments: unknown;
21464 readonly contentItems?: ReadonlyArray<V2TurnStartedNotification__DynamicToolCallOutputContentItem> | null;
21465 readonly durationMs?: number | null;
21466 readonly id: string;
21467 readonly status: V2TurnStartedNotification__DynamicToolCallStatus;
21468 readonly success?: boolean | null;
21469 readonly tool: string;
21470 readonly type: "dynamicToolCall";
21471 }
21472 | {
21473 readonly agentsStates: { readonly [x: string]: V2TurnStartedNotification__CollabAgentState };
21474 readonly id: string;
21475 readonly model?: string | null;
21476 readonly prompt?: string | null;
21477 readonly reasoningEffort?: V2TurnStartedNotification__ReasoningEffort | null;
21478 readonly receiverThreadIds: ReadonlyArray<string>;
21479 readonly senderThreadId: string;
21480 readonly status: "inProgress" | "completed" | "failed";
21481 readonly tool: "spawnAgent" | "sendInput" | "resumeAgent" | "wait" | "closeAgent";
21482 readonly type: "collabAgentToolCall";
21483 }
21484 | {
21485 readonly action?: V2TurnStartedNotification__WebSearchAction | null;
21486 readonly id: string;
21487 readonly query: string;
21488 readonly type: "webSearch";
21489 }
21490 | { readonly id: string; readonly path: string; readonly type: "imageView" }
21491 | {
21492 readonly id: string;
21493 readonly result: string;
21494 readonly revisedPrompt?: string | null;
21495 readonly savedPath?: string | null;
21496 readonly status: string;
21497 readonly type: "imageGeneration";
21498 }
21499 | { readonly id: string; readonly review: string; readonly type: "enteredReviewMode" }
21500 | { readonly id: string; readonly review: string; readonly type: "exitedReviewMode" }
21501 | { readonly id: string; readonly type: "contextCompaction" };
21502export const V2TurnStartedNotification__ThreadItem = Schema.Union(
21503 [
21504 Schema.Struct({
21505 content: Schema.Array(V2TurnStartedNotification__UserInput),
21506 id: Schema.String,
21507 type: Schema.Literal("userMessage").annotate({ title: "UserMessageThreadItemType" }),
21508 }).annotate({ title: "UserMessageThreadItem" }),
21509 Schema.Struct({
21510 fragments: Schema.Array(V2TurnStartedNotification__HookPromptFragment),
21511 id: Schema.String,
21512 type: Schema.Literal("hookPrompt").annotate({ title: "HookPromptThreadItemType" }),
21513 }).annotate({ title: "HookPromptThreadItem" }),
21514 Schema.Struct({
21515 id: Schema.String,
21516 memoryCitation: Schema.optionalKey(
21517 Schema.Union([V2TurnStartedNotification__MemoryCitation, Schema.Null]),
21518 ),
21519 phase: Schema.optionalKey(
21520 Schema.Union([V2TurnStartedNotification__MessagePhase, Schema.Null]),
21521 ),
21522 text: Schema.String,
21523 type: Schema.Literal("agentMessage").annotate({ title: "AgentMessageThreadItemType" }),
21524 }).annotate({ title: "AgentMessageThreadItem" }),
21525 Schema.Struct({
21526 id: Schema.String,
21527 text: Schema.String,
21528 type: Schema.Literal("plan").annotate({ title: "PlanThreadItemType" }),
21529 }).annotate({
21530 title: "PlanThreadItem",
21531 description:
21532 "EXPERIMENTAL - proposed plan item content. The completed plan item is authoritative and may not match the concatenation of `PlanDelta` text.",
21533 }),
21534 Schema.Struct({
21535 content: Schema.optionalKey(Schema.Array(Schema.String).annotate({ default: [] })),
21536 id: Schema.String,
21537 summary: Schema.optionalKey(Schema.Array(Schema.String).annotate({ default: [] })),
21538 type: Schema.Literal("reasoning").annotate({ title: "ReasoningThreadItemType" }),
21539 }).annotate({ title: "ReasoningThreadItem" }),
21540 Schema.Struct({
21541 aggregatedOutput: Schema.optionalKey(
21542 Schema.Union([
21543 Schema.String.annotate({
21544 description: "The command's output, aggregated from stdout and stderr.",
21545 }),
21546 Schema.Null,
21547 ]),
21548 ),
21549 command: Schema.String.annotate({ description: "The command to be executed." }),
21550 commandActions: Schema.Array(V2TurnStartedNotification__CommandAction).annotate({
21551 description:
21552 "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.",
21553 }),
21554 cwd: Schema.String.annotate({ description: "The command's working directory." }),
21555 durationMs: Schema.optionalKey(
21556 Schema.Union([
21557 Schema.Number.annotate({
21558 description: "The duration of the command execution in milliseconds.",
21559 format: "int64",
21560 }).check(Schema.isInt()),
21561 Schema.Null,
21562 ]),
21563 ),
21564 exitCode: Schema.optionalKey(
21565 Schema.Union([
21566 Schema.Number.annotate({
21567 description: "The command's exit code.",
21568 format: "int32",
21569 }).check(Schema.isInt()),
21570 Schema.Null,
21571 ]),
21572 ),
21573 id: Schema.String,
21574 processId: Schema.optionalKey(
21575 Schema.Union([
21576 Schema.String.annotate({
21577 description: "Identifier for the underlying PTY process (when available).",
21578 }),
21579 Schema.Null,
21580 ]),
21581 ),
21582 source: Schema.optionalKey(
21583 Schema.Literals([
21584 "agent",
21585 "userShell",
21586 "unifiedExecStartup",
21587 "unifiedExecInteraction",
21588 ]).annotate({ default: "agent" }),
21589 ),
21590 status: V2TurnStartedNotification__CommandExecutionStatus,
21591 type: Schema.Literal("commandExecution").annotate({
21592 title: "CommandExecutionThreadItemType",
21593 }),
21594 }).annotate({ title: "CommandExecutionThreadItem" }),
21595 Schema.Struct({
21596 changes: Schema.Array(V2TurnStartedNotification__FileUpdateChange),
21597 id: Schema.String,
21598 status: V2TurnStartedNotification__PatchApplyStatus,
21599 type: Schema.Literal("fileChange").annotate({ title: "FileChangeThreadItemType" }),
21600 }).annotate({ title: "FileChangeThreadItem" }),
21601 Schema.Struct({
21602 arguments: Schema.Unknown,
21603 durationMs: Schema.optionalKey(
21604 Schema.Union([
21605 Schema.Number.annotate({
21606 description: "The duration of the MCP tool call in milliseconds.",
21607 format: "int64",
21608 }).check(Schema.isInt()),
21609 Schema.Null,
21610 ]),
21611 ),
21612 error: Schema.optionalKey(
21613 Schema.Union([V2TurnStartedNotification__McpToolCallError, Schema.Null]),
21614 ),
21615 id: Schema.String,
21616 result: Schema.optionalKey(
21617 Schema.Union([V2TurnStartedNotification__McpToolCallResult, Schema.Null]),
21618 ),
21619 server: Schema.String,
21620 status: V2TurnStartedNotification__McpToolCallStatus,
21621 tool: Schema.String,
21622 type: Schema.Literal("mcpToolCall").annotate({ title: "McpToolCallThreadItemType" }),
21623 }).annotate({ title: "McpToolCallThreadItem" }),
21624 Schema.Struct({
21625 arguments: Schema.Unknown,
21626 contentItems: Schema.optionalKey(
21627 Schema.Union([
21628 Schema.Array(V2TurnStartedNotification__DynamicToolCallOutputContentItem),
21629 Schema.Null,
21630 ]),
21631 ),
21632 durationMs: Schema.optionalKey(
21633 Schema.Union([
21634 Schema.Number.annotate({
21635 description: "The duration of the dynamic tool call in milliseconds.",
21636 format: "int64",
21637 }).check(Schema.isInt()),
21638 Schema.Null,
21639 ]),
21640 ),
21641 id: Schema.String,
21642 status: V2TurnStartedNotification__DynamicToolCallStatus,
21643 success: Schema.optionalKey(Schema.Union([Schema.Boolean, Schema.Null])),
21644 tool: Schema.String,
21645 type: Schema.Literal("dynamicToolCall").annotate({ title: "DynamicToolCallThreadItemType" }),
21646 }).annotate({ title: "DynamicToolCallThreadItem" }),
21647 Schema.Struct({
21648 agentsStates: Schema.Record(
21649 Schema.String,
21650 V2TurnStartedNotification__CollabAgentState,
21651 ).annotate({ description: "Last known status of the target agents, when available." }),
21652 id: Schema.String.annotate({ description: "Unique identifier for this collab tool call." }),
21653 model: Schema.optionalKey(
21654 Schema.Union([
21655 Schema.String.annotate({
21656 description: "Model requested for the spawned agent, when applicable.",
21657 }),
21658 Schema.Null,
21659 ]),
21660 ),
21661 prompt: Schema.optionalKey(
21662 Schema.Union([
21663 Schema.String.annotate({
21664 description: "Prompt text sent as part of the collab tool call, when available.",
21665 }),
21666 Schema.Null,
21667 ]),
21668 ),
21669 reasoningEffort: Schema.optionalKey(
21670 Schema.Union([V2TurnStartedNotification__ReasoningEffort, Schema.Null]).annotate({
21671 description: "Reasoning effort requested for the spawned agent, when applicable.",
21672 }),
21673 ),
21674 receiverThreadIds: Schema.Array(Schema.String).annotate({
21675 description:
21676 "Thread ID of the receiving agent, when applicable. In case of spawn operation, this corresponds to the newly spawned agent.",
21677 }),
21678 senderThreadId: Schema.String.annotate({
21679 description: "Thread ID of the agent issuing the collab request.",
21680 }),
21681 status: Schema.Literals(["inProgress", "completed", "failed"]).annotate({
21682 description: "Current status of the collab tool call.",
21683 }),
21684 tool: Schema.Literals([
21685 "spawnAgent",
21686 "sendInput",
21687 "resumeAgent",
21688 "wait",
21689 "closeAgent",
21690 ]).annotate({ description: "Name of the collab tool that was invoked." }),
21691 type: Schema.Literal("collabAgentToolCall").annotate({
21692 title: "CollabAgentToolCallThreadItemType",
21693 }),
21694 }).annotate({ title: "CollabAgentToolCallThreadItem" }),
21695 Schema.Struct({
21696 action: Schema.optionalKey(
21697 Schema.Union([V2TurnStartedNotification__WebSearchAction, Schema.Null]),
21698 ),
21699 id: Schema.String,
21700 query: Schema.String,
21701 type: Schema.Literal("webSearch").annotate({ title: "WebSearchThreadItemType" }),
21702 }).annotate({ title: "WebSearchThreadItem" }),
21703 Schema.Struct({
21704 id: Schema.String,
21705 path: Schema.String,
21706 type: Schema.Literal("imageView").annotate({ title: "ImageViewThreadItemType" }),
21707 }).annotate({ title: "ImageViewThreadItem" }),
21708 Schema.Struct({
21709 id: Schema.String,
21710 result: Schema.String,
21711 revisedPrompt: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
21712 savedPath: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
21713 status: Schema.String,
21714 type: Schema.Literal("imageGeneration").annotate({ title: "ImageGenerationThreadItemType" }),
21715 }).annotate({ title: "ImageGenerationThreadItem" }),
21716 Schema.Struct({
21717 id: Schema.String,
21718 review: Schema.String,
21719 type: Schema.Literal("enteredReviewMode").annotate({
21720 title: "EnteredReviewModeThreadItemType",
21721 }),
21722 }).annotate({ title: "EnteredReviewModeThreadItem" }),
21723 Schema.Struct({
21724 id: Schema.String,
21725 review: Schema.String,
21726 type: Schema.Literal("exitedReviewMode").annotate({
21727 title: "ExitedReviewModeThreadItemType",
21728 }),
21729 }).annotate({ title: "ExitedReviewModeThreadItem" }),
21730 Schema.Struct({
21731 id: Schema.String,
21732 type: Schema.Literal("contextCompaction").annotate({
21733 title: "ContextCompactionThreadItemType",
21734 }),
21735 }).annotate({ title: "ContextCompactionThreadItem" }),
21736 ],
21737 { mode: "oneOf" },
21738);
21739
21740export type V2TurnStartResponse__TurnError = {
21741 readonly additionalDetails?: string | null;
21742 readonly codexErrorInfo?: V2TurnStartResponse__CodexErrorInfo | null;
21743 readonly message: string;
21744};
21745export const V2TurnStartResponse__TurnError = Schema.Struct({
21746 additionalDetails: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
21747 codexErrorInfo: Schema.optionalKey(
21748 Schema.Union([V2TurnStartResponse__CodexErrorInfo, Schema.Null]),
21749 ),
21750 message: Schema.String,
21751});
21752
21753export type V2TurnStartResponse__ThreadItem =
21754 | {
21755 readonly content: ReadonlyArray<V2TurnStartResponse__UserInput>;
21756 readonly id: string;
21757 readonly type: "userMessage";
21758 }
21759 | {
21760 readonly fragments: ReadonlyArray<V2TurnStartResponse__HookPromptFragment>;
21761 readonly id: string;
21762 readonly type: "hookPrompt";
21763 }
21764 | {
21765 readonly id: string;
21766 readonly memoryCitation?: V2TurnStartResponse__MemoryCitation | null;
21767 readonly phase?: V2TurnStartResponse__MessagePhase | null;
21768 readonly text: string;
21769 readonly type: "agentMessage";
21770 }
21771 | { readonly id: string; readonly text: string; readonly type: "plan" }
21772 | {
21773 readonly content?: ReadonlyArray<string>;
21774 readonly id: string;
21775 readonly summary?: ReadonlyArray<string>;
21776 readonly type: "reasoning";
21777 }
21778 | {
21779 readonly aggregatedOutput?: string | null;
21780 readonly command: string;
21781 readonly commandActions: ReadonlyArray<V2TurnStartResponse__CommandAction>;
21782 readonly cwd: string;
21783 readonly durationMs?: number | null;
21784 readonly exitCode?: number | null;
21785 readonly id: string;
21786 readonly processId?: string | null;
21787 readonly source?: "agent" | "userShell" | "unifiedExecStartup" | "unifiedExecInteraction";
21788 readonly status: V2TurnStartResponse__CommandExecutionStatus;
21789 readonly type: "commandExecution";
21790 }
21791 | {
21792 readonly changes: ReadonlyArray<V2TurnStartResponse__FileUpdateChange>;
21793 readonly id: string;
21794 readonly status: V2TurnStartResponse__PatchApplyStatus;
21795 readonly type: "fileChange";
21796 }
21797 | {
21798 readonly arguments: unknown;
21799 readonly durationMs?: number | null;
21800 readonly error?: V2TurnStartResponse__McpToolCallError | null;
21801 readonly id: string;
21802 readonly result?: V2TurnStartResponse__McpToolCallResult | null;
21803 readonly server: string;
21804 readonly status: V2TurnStartResponse__McpToolCallStatus;
21805 readonly tool: string;
21806 readonly type: "mcpToolCall";
21807 }
21808 | {
21809 readonly arguments: unknown;
21810 readonly contentItems?: ReadonlyArray<V2TurnStartResponse__DynamicToolCallOutputContentItem> | null;
21811 readonly durationMs?: number | null;
21812 readonly id: string;
21813 readonly status: V2TurnStartResponse__DynamicToolCallStatus;
21814 readonly success?: boolean | null;
21815 readonly tool: string;
21816 readonly type: "dynamicToolCall";
21817 }
21818 | {
21819 readonly agentsStates: { readonly [x: string]: V2TurnStartResponse__CollabAgentState };
21820 readonly id: string;
21821 readonly model?: string | null;
21822 readonly prompt?: string | null;
21823 readonly reasoningEffort?: V2TurnStartResponse__ReasoningEffort | null;
21824 readonly receiverThreadIds: ReadonlyArray<string>;
21825 readonly senderThreadId: string;
21826 readonly status: "inProgress" | "completed" | "failed";
21827 readonly tool: "spawnAgent" | "sendInput" | "resumeAgent" | "wait" | "closeAgent";
21828 readonly type: "collabAgentToolCall";
21829 }
21830 | {
21831 readonly action?: V2TurnStartResponse__WebSearchAction | null;
21832 readonly id: string;
21833 readonly query: string;
21834 readonly type: "webSearch";
21835 }
21836 | { readonly id: string; readonly path: string; readonly type: "imageView" }
21837 | {
21838 readonly id: string;
21839 readonly result: string;
21840 readonly revisedPrompt?: string | null;
21841 readonly savedPath?: string | null;
21842 readonly status: string;
21843 readonly type: "imageGeneration";
21844 }
21845 | { readonly id: string; readonly review: string; readonly type: "enteredReviewMode" }
21846 | { readonly id: string; readonly review: string; readonly type: "exitedReviewMode" }
21847 | { readonly id: string; readonly type: "contextCompaction" };
21848export const V2TurnStartResponse__ThreadItem = Schema.Union(
21849 [
21850 Schema.Struct({
21851 content: Schema.Array(V2TurnStartResponse__UserInput),
21852 id: Schema.String,
21853 type: Schema.Literal("userMessage").annotate({ title: "UserMessageThreadItemType" }),
21854 }).annotate({ title: "UserMessageThreadItem" }),
21855 Schema.Struct({
21856 fragments: Schema.Array(V2TurnStartResponse__HookPromptFragment),
21857 id: Schema.String,
21858 type: Schema.Literal("hookPrompt").annotate({ title: "HookPromptThreadItemType" }),
21859 }).annotate({ title: "HookPromptThreadItem" }),
21860 Schema.Struct({
21861 id: Schema.String,
21862 memoryCitation: Schema.optionalKey(
21863 Schema.Union([V2TurnStartResponse__MemoryCitation, Schema.Null]),
21864 ),
21865 phase: Schema.optionalKey(Schema.Union([V2TurnStartResponse__MessagePhase, Schema.Null])),
21866 text: Schema.String,
21867 type: Schema.Literal("agentMessage").annotate({ title: "AgentMessageThreadItemType" }),
21868 }).annotate({ title: "AgentMessageThreadItem" }),
21869 Schema.Struct({
21870 id: Schema.String,
21871 text: Schema.String,
21872 type: Schema.Literal("plan").annotate({ title: "PlanThreadItemType" }),
21873 }).annotate({
21874 title: "PlanThreadItem",
21875 description:
21876 "EXPERIMENTAL - proposed plan item content. The completed plan item is authoritative and may not match the concatenation of `PlanDelta` text.",
21877 }),
21878 Schema.Struct({
21879 content: Schema.optionalKey(Schema.Array(Schema.String).annotate({ default: [] })),
21880 id: Schema.String,
21881 summary: Schema.optionalKey(Schema.Array(Schema.String).annotate({ default: [] })),
21882 type: Schema.Literal("reasoning").annotate({ title: "ReasoningThreadItemType" }),
21883 }).annotate({ title: "ReasoningThreadItem" }),
21884 Schema.Struct({
21885 aggregatedOutput: Schema.optionalKey(
21886 Schema.Union([
21887 Schema.String.annotate({
21888 description: "The command's output, aggregated from stdout and stderr.",
21889 }),
21890 Schema.Null,
21891 ]),
21892 ),
21893 command: Schema.String.annotate({ description: "The command to be executed." }),
21894 commandActions: Schema.Array(V2TurnStartResponse__CommandAction).annotate({
21895 description:
21896 "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.",
21897 }),
21898 cwd: Schema.String.annotate({ description: "The command's working directory." }),
21899 durationMs: Schema.optionalKey(
21900 Schema.Union([
21901 Schema.Number.annotate({
21902 description: "The duration of the command execution in milliseconds.",
21903 format: "int64",
21904 }).check(Schema.isInt()),
21905 Schema.Null,
21906 ]),
21907 ),
21908 exitCode: Schema.optionalKey(
21909 Schema.Union([
21910 Schema.Number.annotate({
21911 description: "The command's exit code.",
21912 format: "int32",
21913 }).check(Schema.isInt()),
21914 Schema.Null,
21915 ]),
21916 ),
21917 id: Schema.String,
21918 processId: Schema.optionalKey(
21919 Schema.Union([
21920 Schema.String.annotate({
21921 description: "Identifier for the underlying PTY process (when available).",
21922 }),
21923 Schema.Null,
21924 ]),
21925 ),
21926 source: Schema.optionalKey(
21927 Schema.Literals([
21928 "agent",
21929 "userShell",
21930 "unifiedExecStartup",
21931 "unifiedExecInteraction",
21932 ]).annotate({ default: "agent" }),
21933 ),
21934 status: V2TurnStartResponse__CommandExecutionStatus,
21935 type: Schema.Literal("commandExecution").annotate({
21936 title: "CommandExecutionThreadItemType",
21937 }),
21938 }).annotate({ title: "CommandExecutionThreadItem" }),
21939 Schema.Struct({
21940 changes: Schema.Array(V2TurnStartResponse__FileUpdateChange),
21941 id: Schema.String,
21942 status: V2TurnStartResponse__PatchApplyStatus,
21943 type: Schema.Literal("fileChange").annotate({ title: "FileChangeThreadItemType" }),
21944 }).annotate({ title: "FileChangeThreadItem" }),
21945 Schema.Struct({
21946 arguments: Schema.Unknown,
21947 durationMs: Schema.optionalKey(
21948 Schema.Union([
21949 Schema.Number.annotate({
21950 description: "The duration of the MCP tool call in milliseconds.",
21951 format: "int64",
21952 }).check(Schema.isInt()),
21953 Schema.Null,
21954 ]),
21955 ),
21956 error: Schema.optionalKey(Schema.Union([V2TurnStartResponse__McpToolCallError, Schema.Null])),
21957 id: Schema.String,
21958 result: Schema.optionalKey(
21959 Schema.Union([V2TurnStartResponse__McpToolCallResult, Schema.Null]),
21960 ),
21961 server: Schema.String,
21962 status: V2TurnStartResponse__McpToolCallStatus,
21963 tool: Schema.String,
21964 type: Schema.Literal("mcpToolCall").annotate({ title: "McpToolCallThreadItemType" }),
21965 }).annotate({ title: "McpToolCallThreadItem" }),
21966 Schema.Struct({
21967 arguments: Schema.Unknown,
21968 contentItems: Schema.optionalKey(
21969 Schema.Union([
21970 Schema.Array(V2TurnStartResponse__DynamicToolCallOutputContentItem),
21971 Schema.Null,
21972 ]),
21973 ),
21974 durationMs: Schema.optionalKey(
21975 Schema.Union([
21976 Schema.Number.annotate({
21977 description: "The duration of the dynamic tool call in milliseconds.",
21978 format: "int64",
21979 }).check(Schema.isInt()),
21980 Schema.Null,
21981 ]),
21982 ),
21983 id: Schema.String,
21984 status: V2TurnStartResponse__DynamicToolCallStatus,
21985 success: Schema.optionalKey(Schema.Union([Schema.Boolean, Schema.Null])),
21986 tool: Schema.String,
21987 type: Schema.Literal("dynamicToolCall").annotate({ title: "DynamicToolCallThreadItemType" }),
21988 }).annotate({ title: "DynamicToolCallThreadItem" }),
21989 Schema.Struct({
21990 agentsStates: Schema.Record(Schema.String, V2TurnStartResponse__CollabAgentState).annotate({
21991 description: "Last known status of the target agents, when available.",
21992 }),
21993 id: Schema.String.annotate({ description: "Unique identifier for this collab tool call." }),
21994 model: Schema.optionalKey(
21995 Schema.Union([
21996 Schema.String.annotate({
21997 description: "Model requested for the spawned agent, when applicable.",
21998 }),
21999 Schema.Null,
22000 ]),
22001 ),
22002 prompt: Schema.optionalKey(
22003 Schema.Union([
22004 Schema.String.annotate({
22005 description: "Prompt text sent as part of the collab tool call, when available.",
22006 }),
22007 Schema.Null,
22008 ]),
22009 ),
22010 reasoningEffort: Schema.optionalKey(
22011 Schema.Union([V2TurnStartResponse__ReasoningEffort, Schema.Null]).annotate({
22012 description: "Reasoning effort requested for the spawned agent, when applicable.",
22013 }),
22014 ),
22015 receiverThreadIds: Schema.Array(Schema.String).annotate({
22016 description:
22017 "Thread ID of the receiving agent, when applicable. In case of spawn operation, this corresponds to the newly spawned agent.",
22018 }),
22019 senderThreadId: Schema.String.annotate({
22020 description: "Thread ID of the agent issuing the collab request.",
22021 }),
22022 status: Schema.Literals(["inProgress", "completed", "failed"]).annotate({
22023 description: "Current status of the collab tool call.",
22024 }),
22025 tool: Schema.Literals([
22026 "spawnAgent",
22027 "sendInput",
22028 "resumeAgent",
22029 "wait",
22030 "closeAgent",
22031 ]).annotate({ description: "Name of the collab tool that was invoked." }),
22032 type: Schema.Literal("collabAgentToolCall").annotate({
22033 title: "CollabAgentToolCallThreadItemType",
22034 }),
22035 }).annotate({ title: "CollabAgentToolCallThreadItem" }),
22036 Schema.Struct({
22037 action: Schema.optionalKey(Schema.Union([V2TurnStartResponse__WebSearchAction, Schema.Null])),
22038 id: Schema.String,
22039 query: Schema.String,
22040 type: Schema.Literal("webSearch").annotate({ title: "WebSearchThreadItemType" }),
22041 }).annotate({ title: "WebSearchThreadItem" }),
22042 Schema.Struct({
22043 id: Schema.String,
22044 path: Schema.String,
22045 type: Schema.Literal("imageView").annotate({ title: "ImageViewThreadItemType" }),
22046 }).annotate({ title: "ImageViewThreadItem" }),
22047 Schema.Struct({
22048 id: Schema.String,
22049 result: Schema.String,
22050 revisedPrompt: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
22051 savedPath: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
22052 status: Schema.String,
22053 type: Schema.Literal("imageGeneration").annotate({ title: "ImageGenerationThreadItemType" }),
22054 }).annotate({ title: "ImageGenerationThreadItem" }),
22055 Schema.Struct({
22056 id: Schema.String,
22057 review: Schema.String,
22058 type: Schema.Literal("enteredReviewMode").annotate({
22059 title: "EnteredReviewModeThreadItemType",
22060 }),
22061 }).annotate({ title: "EnteredReviewModeThreadItem" }),
22062 Schema.Struct({
22063 id: Schema.String,
22064 review: Schema.String,
22065 type: Schema.Literal("exitedReviewMode").annotate({
22066 title: "ExitedReviewModeThreadItemType",
22067 }),
22068 }).annotate({ title: "ExitedReviewModeThreadItem" }),
22069 Schema.Struct({
22070 id: Schema.String,
22071 type: Schema.Literal("contextCompaction").annotate({
22072 title: "ContextCompactionThreadItemType",
22073 }),
22074 }).annotate({ title: "ContextCompactionThreadItem" }),
22075 ],
22076 { mode: "oneOf" },
22077);
22078
22079export type McpServerElicitationRequestParams__McpElicitationMultiSelectEnumSchema =
22080 | McpServerElicitationRequestParams__McpElicitationUntitledMultiSelectEnumSchema
22081 | McpServerElicitationRequestParams__McpElicitationTitledMultiSelectEnumSchema;
22082export const McpServerElicitationRequestParams__McpElicitationMultiSelectEnumSchema = Schema.Union([
22083 McpServerElicitationRequestParams__McpElicitationUntitledMultiSelectEnumSchema,
22084 McpServerElicitationRequestParams__McpElicitationTitledMultiSelectEnumSchema,
22085]);
22086
22087export type ServerNotification__AppListUpdatedNotification = {
22088 readonly data: ReadonlyArray<ServerNotification__AppInfo>;
22089};
22090export const ServerNotification__AppListUpdatedNotification = Schema.Struct({
22091 data: Schema.Array(ServerNotification__AppInfo),
22092}).annotate({ description: "EXPERIMENTAL - notification emitted when the app list changes." });
22093
22094export type ServerNotification__HookCompletedNotification = {
22095 readonly run: ServerNotification__HookRunSummary;
22096 readonly threadId: string;
22097 readonly turnId?: string | null;
22098};
22099export const ServerNotification__HookCompletedNotification = Schema.Struct({
22100 run: ServerNotification__HookRunSummary,
22101 threadId: Schema.String,
22102 turnId: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
22103});
22104
22105export type ServerNotification__HookStartedNotification = {
22106 readonly run: ServerNotification__HookRunSummary;
22107 readonly threadId: string;
22108 readonly turnId?: string | null;
22109};
22110export const ServerNotification__HookStartedNotification = Schema.Struct({
22111 run: ServerNotification__HookRunSummary,
22112 threadId: Schema.String,
22113 turnId: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
22114});
22115
22116export type ServerNotification__ErrorNotification = {
22117 readonly error: ServerNotification__TurnError;
22118 readonly threadId: string;
22119 readonly turnId: string;
22120 readonly willRetry: boolean;
22121};
22122export const ServerNotification__ErrorNotification = Schema.Struct({
22123 error: ServerNotification__TurnError,
22124 threadId: Schema.String,
22125 turnId: Schema.String,
22126 willRetry: Schema.Boolean,
22127});
22128
22129export type ServerNotification__ItemCompletedNotification = {
22130 readonly item: ServerNotification__ThreadItem;
22131 readonly threadId: string;
22132 readonly turnId: string;
22133};
22134export const ServerNotification__ItemCompletedNotification = Schema.Struct({
22135 item: ServerNotification__ThreadItem,
22136 threadId: Schema.String,
22137 turnId: Schema.String,
22138});
22139
22140export type ServerNotification__ItemStartedNotification = {
22141 readonly item: ServerNotification__ThreadItem;
22142 readonly threadId: string;
22143 readonly turnId: string;
22144};
22145export const ServerNotification__ItemStartedNotification = Schema.Struct({
22146 item: ServerNotification__ThreadItem,
22147 threadId: Schema.String,
22148 turnId: Schema.String,
22149});
22150
22151export type ServerNotification__Turn = {
22152 readonly completedAt?: number | null;
22153 readonly durationMs?: number | null;
22154 readonly error?: ServerNotification__TurnError | null;
22155 readonly id: string;
22156 readonly items: ReadonlyArray<ServerNotification__ThreadItem>;
22157 readonly startedAt?: number | null;
22158 readonly status: ServerNotification__TurnStatus;
22159};
22160export const ServerNotification__Turn = Schema.Struct({
22161 completedAt: Schema.optionalKey(
22162 Schema.Union([
22163 Schema.Number.annotate({
22164 description: "Unix timestamp (in seconds) when the turn completed.",
22165 format: "int64",
22166 }).check(Schema.isInt()),
22167 Schema.Null,
22168 ]),
22169 ),
22170 durationMs: Schema.optionalKey(
22171 Schema.Union([
22172 Schema.Number.annotate({
22173 description: "Duration between turn start and completion in milliseconds, if known.",
22174 format: "int64",
22175 }).check(Schema.isInt()),
22176 Schema.Null,
22177 ]),
22178 ),
22179 error: Schema.optionalKey(
22180 Schema.Union([ServerNotification__TurnError, Schema.Null]).annotate({
22181 description: "Only populated when the Turn's status is failed.",
22182 }),
22183 ),
22184 id: Schema.String,
22185 items: Schema.Array(ServerNotification__ThreadItem).annotate({
22186 description:
22187 "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.",
22188 }),
22189 startedAt: Schema.optionalKey(
22190 Schema.Union([
22191 Schema.Number.annotate({
22192 description: "Unix timestamp (in seconds) when the turn started.",
22193 format: "int64",
22194 }).check(Schema.isInt()),
22195 Schema.Null,
22196 ]),
22197 ),
22198 status: ServerNotification__TurnStatus,
22199});
22200
22201export type ServerRequest__PermissionsRequestApprovalParams = {
22202 readonly itemId: string;
22203 readonly permissions: ServerRequest__RequestPermissionProfile;
22204 readonly reason?: string | null;
22205 readonly threadId: string;
22206 readonly turnId: string;
22207};
22208export const ServerRequest__PermissionsRequestApprovalParams = Schema.Struct({
22209 itemId: Schema.String,
22210 permissions: ServerRequest__RequestPermissionProfile,
22211 reason: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
22212 threadId: Schema.String,
22213 turnId: Schema.String,
22214});
22215
22216export type ServerRequest__McpElicitationMultiSelectEnumSchema =
22217 | ServerRequest__McpElicitationUntitledMultiSelectEnumSchema
22218 | ServerRequest__McpElicitationTitledMultiSelectEnumSchema;
22219export const ServerRequest__McpElicitationMultiSelectEnumSchema = Schema.Union([
22220 ServerRequest__McpElicitationUntitledMultiSelectEnumSchema,
22221 ServerRequest__McpElicitationTitledMultiSelectEnumSchema,
22222]);
22223
22224export type V2ConfigReadResponse__ProfileV2 = {
22225 readonly approval_policy?: V2ConfigReadResponse__AskForApproval | null;
22226 readonly approvals_reviewer?: V2ConfigReadResponse__ApprovalsReviewer | null;
22227 readonly chatgpt_base_url?: string | null;
22228 readonly model?: string | null;
22229 readonly model_provider?: string | null;
22230 readonly model_reasoning_effort?: V2ConfigReadResponse__ReasoningEffort | null;
22231 readonly model_reasoning_summary?: V2ConfigReadResponse__ReasoningSummary | null;
22232 readonly model_verbosity?: V2ConfigReadResponse__Verbosity | null;
22233 readonly service_tier?: V2ConfigReadResponse__ServiceTier | null;
22234 readonly tools?: V2ConfigReadResponse__ToolsV2 | null;
22235 readonly web_search?: V2ConfigReadResponse__WebSearchMode | null;
22236 readonly [x: string]: unknown;
22237};
22238export const V2ConfigReadResponse__ProfileV2 = Schema.StructWithRest(
22239 Schema.Struct({
22240 approval_policy: Schema.optionalKey(
22241 Schema.Union([V2ConfigReadResponse__AskForApproval, Schema.Null]),
22242 ),
22243 approvals_reviewer: Schema.optionalKey(
22244 Schema.Union([V2ConfigReadResponse__ApprovalsReviewer, Schema.Null]).annotate({
22245 description:
22246 "[UNSTABLE] Optional profile-level override for where approval requests are routed for review. If omitted, the enclosing config default is used.",
22247 }),
22248 ),
22249 chatgpt_base_url: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
22250 model: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
22251 model_provider: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
22252 model_reasoning_effort: Schema.optionalKey(
22253 Schema.Union([V2ConfigReadResponse__ReasoningEffort, Schema.Null]),
22254 ),
22255 model_reasoning_summary: Schema.optionalKey(
22256 Schema.Union([V2ConfigReadResponse__ReasoningSummary, Schema.Null]),
22257 ),
22258 model_verbosity: Schema.optionalKey(
22259 Schema.Union([V2ConfigReadResponse__Verbosity, Schema.Null]),
22260 ),
22261 service_tier: Schema.optionalKey(
22262 Schema.Union([V2ConfigReadResponse__ServiceTier, Schema.Null]),
22263 ),
22264 tools: Schema.optionalKey(Schema.Union([V2ConfigReadResponse__ToolsV2, Schema.Null])),
22265 web_search: Schema.optionalKey(
22266 Schema.Union([V2ConfigReadResponse__WebSearchMode, Schema.Null]),
22267 ),
22268 }),
22269 [Schema.Record(Schema.String, Schema.Unknown)],
22270);
22271
22272export type V2ConfigWriteResponse__OverriddenMetadata = {
22273 readonly effectiveValue: unknown;
22274 readonly message: string;
22275 readonly overridingLayer: V2ConfigWriteResponse__ConfigLayerMetadata;
22276};
22277export const V2ConfigWriteResponse__OverriddenMetadata = Schema.Struct({
22278 effectiveValue: Schema.Unknown,
22279 message: Schema.String,
22280 overridingLayer: V2ConfigWriteResponse__ConfigLayerMetadata,
22281});
22282
22283export type V2PluginListResponse__PluginMarketplaceEntry = {
22284 readonly interface?: V2PluginListResponse__MarketplaceInterface | null;
22285 readonly name: string;
22286 readonly path: V2PluginListResponse__AbsolutePathBuf;
22287 readonly plugins: ReadonlyArray<V2PluginListResponse__PluginSummary>;
22288};
22289export const V2PluginListResponse__PluginMarketplaceEntry = Schema.Struct({
22290 interface: Schema.optionalKey(
22291 Schema.Union([V2PluginListResponse__MarketplaceInterface, Schema.Null]),
22292 ),
22293 name: Schema.String,
22294 path: V2PluginListResponse__AbsolutePathBuf,
22295 plugins: Schema.Array(V2PluginListResponse__PluginSummary),
22296});
22297
22298export type V2PluginReadResponse__PluginDetail = {
22299 readonly apps: ReadonlyArray<V2PluginReadResponse__AppSummary>;
22300 readonly description?: string | null;
22301 readonly marketplaceName: string;
22302 readonly marketplacePath: V2PluginReadResponse__AbsolutePathBuf;
22303 readonly mcpServers: ReadonlyArray<string>;
22304 readonly skills: ReadonlyArray<V2PluginReadResponse__SkillSummary>;
22305 readonly summary: V2PluginReadResponse__PluginSummary;
22306};
22307export const V2PluginReadResponse__PluginDetail = Schema.Struct({
22308 apps: Schema.Array(V2PluginReadResponse__AppSummary),
22309 description: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
22310 marketplaceName: Schema.String,
22311 marketplacePath: V2PluginReadResponse__AbsolutePathBuf,
22312 mcpServers: Schema.Array(Schema.String),
22313 skills: Schema.Array(V2PluginReadResponse__SkillSummary),
22314 summary: V2PluginReadResponse__PluginSummary,
22315});
22316
22317export type V2RawResponseItemCompletedNotification__ResponseItem =
22318 | {
22319 readonly content: ReadonlyArray<V2RawResponseItemCompletedNotification__ContentItem>;
22320 readonly end_turn?: boolean | null;
22321 readonly id?: string | null;
22322 readonly phase?: V2RawResponseItemCompletedNotification__MessagePhase | null;
22323 readonly role: string;
22324 readonly type: "message";
22325 }
22326 | {
22327 readonly content?: ReadonlyArray<V2RawResponseItemCompletedNotification__ReasoningItemContent> | null;
22328 readonly encrypted_content?: string | null;
22329 readonly summary: ReadonlyArray<V2RawResponseItemCompletedNotification__ReasoningItemReasoningSummary>;
22330 readonly type: "reasoning";
22331 }
22332 | {
22333 readonly action: V2RawResponseItemCompletedNotification__LocalShellAction;
22334 readonly call_id?: string | null;
22335 readonly id?: string | null;
22336 readonly status: V2RawResponseItemCompletedNotification__LocalShellStatus;
22337 readonly type: "local_shell_call";
22338 }
22339 | {
22340 readonly arguments: string;
22341 readonly call_id: string;
22342 readonly id?: string | null;
22343 readonly name: string;
22344 readonly namespace?: string | null;
22345 readonly type: "function_call";
22346 }
22347 | {
22348 readonly arguments: unknown;
22349 readonly call_id?: string | null;
22350 readonly execution: string;
22351 readonly id?: string | null;
22352 readonly status?: string | null;
22353 readonly type: "tool_search_call";
22354 }
22355 | {
22356 readonly call_id: string;
22357 readonly output: V2RawResponseItemCompletedNotification__FunctionCallOutputBody;
22358 readonly type: "function_call_output";
22359 }
22360 | {
22361 readonly call_id: string;
22362 readonly id?: string | null;
22363 readonly input: string;
22364 readonly name: string;
22365 readonly status?: string | null;
22366 readonly type: "custom_tool_call";
22367 }
22368 | {
22369 readonly call_id: string;
22370 readonly name?: string | null;
22371 readonly output: V2RawResponseItemCompletedNotification__FunctionCallOutputBody;
22372 readonly type: "custom_tool_call_output";
22373 }
22374 | {
22375 readonly call_id?: string | null;
22376 readonly execution: string;
22377 readonly status: string;
22378 readonly tools: ReadonlyArray<unknown>;
22379 readonly type: "tool_search_output";
22380 }
22381 | {
22382 readonly action?: V2RawResponseItemCompletedNotification__ResponsesApiWebSearchAction | null;
22383 readonly id?: string | null;
22384 readonly status?: string | null;
22385 readonly type: "web_search_call";
22386 }
22387 | {
22388 readonly id: string;
22389 readonly result: string;
22390 readonly revised_prompt?: string | null;
22391 readonly status: string;
22392 readonly type: "image_generation_call";
22393 }
22394 | {
22395 readonly ghost_commit: V2RawResponseItemCompletedNotification__GhostCommit;
22396 readonly type: "ghost_snapshot";
22397 }
22398 | { readonly encrypted_content: string; readonly type: "compaction" }
22399 | { readonly type: "other" };
22400export const V2RawResponseItemCompletedNotification__ResponseItem = Schema.Union(
22401 [
22402 Schema.Struct({
22403 content: Schema.Array(V2RawResponseItemCompletedNotification__ContentItem),
22404 end_turn: Schema.optionalKey(Schema.Union([Schema.Boolean, Schema.Null])),
22405 id: Schema.optionalKey(
22406 Schema.Union([Schema.String.annotate({ writeOnly: true }), Schema.Null]),
22407 ),
22408 phase: Schema.optionalKey(
22409 Schema.Union([V2RawResponseItemCompletedNotification__MessagePhase, Schema.Null]),
22410 ),
22411 role: Schema.String,
22412 type: Schema.Literal("message").annotate({ title: "MessageResponseItemType" }),
22413 }).annotate({ title: "MessageResponseItem" }),
22414 Schema.Struct({
22415 content: Schema.optionalKey(
22416 Schema.Union([
22417 Schema.Array(V2RawResponseItemCompletedNotification__ReasoningItemContent),
22418 Schema.Null,
22419 ]),
22420 ),
22421 encrypted_content: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
22422 summary: Schema.Array(V2RawResponseItemCompletedNotification__ReasoningItemReasoningSummary),
22423 type: Schema.Literal("reasoning").annotate({ title: "ReasoningResponseItemType" }),
22424 }).annotate({ title: "ReasoningResponseItem" }),
22425 Schema.Struct({
22426 action: V2RawResponseItemCompletedNotification__LocalShellAction,
22427 call_id: Schema.optionalKey(
22428 Schema.Union([
22429 Schema.String.annotate({ description: "Set when using the Responses API." }),
22430 Schema.Null,
22431 ]),
22432 ),
22433 id: Schema.optionalKey(
22434 Schema.Union([
22435 Schema.String.annotate({
22436 description: "Legacy id field retained for compatibility with older payloads.",
22437 writeOnly: true,
22438 }),
22439 Schema.Null,
22440 ]),
22441 ),
22442 status: V2RawResponseItemCompletedNotification__LocalShellStatus,
22443 type: Schema.Literal("local_shell_call").annotate({
22444 title: "LocalShellCallResponseItemType",
22445 }),
22446 }).annotate({ title: "LocalShellCallResponseItem" }),
22447 Schema.Struct({
22448 arguments: Schema.String,
22449 call_id: Schema.String,
22450 id: Schema.optionalKey(
22451 Schema.Union([Schema.String.annotate({ writeOnly: true }), Schema.Null]),
22452 ),
22453 name: Schema.String,
22454 namespace: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
22455 type: Schema.Literal("function_call").annotate({ title: "FunctionCallResponseItemType" }),
22456 }).annotate({ title: "FunctionCallResponseItem" }),
22457 Schema.Struct({
22458 arguments: Schema.Unknown,
22459 call_id: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
22460 execution: Schema.String,
22461 id: Schema.optionalKey(
22462 Schema.Union([Schema.String.annotate({ writeOnly: true }), Schema.Null]),
22463 ),
22464 status: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
22465 type: Schema.Literal("tool_search_call").annotate({
22466 title: "ToolSearchCallResponseItemType",
22467 }),
22468 }).annotate({ title: "ToolSearchCallResponseItem" }),
22469 Schema.Struct({
22470 call_id: Schema.String,
22471 output: V2RawResponseItemCompletedNotification__FunctionCallOutputBody,
22472 type: Schema.Literal("function_call_output").annotate({
22473 title: "FunctionCallOutputResponseItemType",
22474 }),
22475 }).annotate({ title: "FunctionCallOutputResponseItem" }),
22476 Schema.Struct({
22477 call_id: Schema.String,
22478 id: Schema.optionalKey(
22479 Schema.Union([Schema.String.annotate({ writeOnly: true }), Schema.Null]),
22480 ),
22481 input: Schema.String,
22482 name: Schema.String,
22483 status: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
22484 type: Schema.Literal("custom_tool_call").annotate({
22485 title: "CustomToolCallResponseItemType",
22486 }),
22487 }).annotate({ title: "CustomToolCallResponseItem" }),
22488 Schema.Struct({
22489 call_id: Schema.String,
22490 name: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
22491 output: V2RawResponseItemCompletedNotification__FunctionCallOutputBody,
22492 type: Schema.Literal("custom_tool_call_output").annotate({
22493 title: "CustomToolCallOutputResponseItemType",
22494 }),
22495 }).annotate({ title: "CustomToolCallOutputResponseItem" }),
22496 Schema.Struct({
22497 call_id: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
22498 execution: Schema.String,
22499 status: Schema.String,
22500 tools: Schema.Array(Schema.Unknown),
22501 type: Schema.Literal("tool_search_output").annotate({
22502 title: "ToolSearchOutputResponseItemType",
22503 }),
22504 }).annotate({ title: "ToolSearchOutputResponseItem" }),
22505 Schema.Struct({
22506 action: Schema.optionalKey(
22507 Schema.Union([
22508 V2RawResponseItemCompletedNotification__ResponsesApiWebSearchAction,
22509 Schema.Null,
22510 ]),
22511 ),
22512 id: Schema.optionalKey(
22513 Schema.Union([Schema.String.annotate({ writeOnly: true }), Schema.Null]),
22514 ),
22515 status: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
22516 type: Schema.Literal("web_search_call").annotate({ title: "WebSearchCallResponseItemType" }),
22517 }).annotate({ title: "WebSearchCallResponseItem" }),
22518 Schema.Struct({
22519 id: Schema.String,
22520 result: Schema.String,
22521 revised_prompt: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
22522 status: Schema.String,
22523 type: Schema.Literal("image_generation_call").annotate({
22524 title: "ImageGenerationCallResponseItemType",
22525 }),
22526 }).annotate({ title: "ImageGenerationCallResponseItem" }),
22527 Schema.Struct({
22528 ghost_commit: V2RawResponseItemCompletedNotification__GhostCommit,
22529 type: Schema.Literal("ghost_snapshot").annotate({ title: "GhostSnapshotResponseItemType" }),
22530 }).annotate({ title: "GhostSnapshotResponseItem" }),
22531 Schema.Struct({
22532 encrypted_content: Schema.String,
22533 type: Schema.Literal("compaction").annotate({ title: "CompactionResponseItemType" }),
22534 }).annotate({ title: "CompactionResponseItem" }),
22535 Schema.Struct({
22536 type: Schema.Literal("other").annotate({ title: "OtherResponseItemType" }),
22537 }).annotate({ title: "OtherResponseItem" }),
22538 ],
22539 { mode: "oneOf" },
22540);
22541
22542export type V2ReviewStartResponse__Turn = {
22543 readonly completedAt?: number | null;
22544 readonly durationMs?: number | null;
22545 readonly error?: V2ReviewStartResponse__TurnError | null;
22546 readonly id: string;
22547 readonly items: ReadonlyArray<V2ReviewStartResponse__ThreadItem>;
22548 readonly startedAt?: number | null;
22549 readonly status: V2ReviewStartResponse__TurnStatus;
22550};
22551export const V2ReviewStartResponse__Turn = Schema.Struct({
22552 completedAt: Schema.optionalKey(
22553 Schema.Union([
22554 Schema.Number.annotate({
22555 description: "Unix timestamp (in seconds) when the turn completed.",
22556 format: "int64",
22557 }).check(Schema.isInt()),
22558 Schema.Null,
22559 ]),
22560 ),
22561 durationMs: Schema.optionalKey(
22562 Schema.Union([
22563 Schema.Number.annotate({
22564 description: "Duration between turn start and completion in milliseconds, if known.",
22565 format: "int64",
22566 }).check(Schema.isInt()),
22567 Schema.Null,
22568 ]),
22569 ),
22570 error: Schema.optionalKey(
22571 Schema.Union([V2ReviewStartResponse__TurnError, Schema.Null]).annotate({
22572 description: "Only populated when the Turn's status is failed.",
22573 }),
22574 ),
22575 id: Schema.String,
22576 items: Schema.Array(V2ReviewStartResponse__ThreadItem).annotate({
22577 description:
22578 "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.",
22579 }),
22580 startedAt: Schema.optionalKey(
22581 Schema.Union([
22582 Schema.Number.annotate({
22583 description: "Unix timestamp (in seconds) when the turn started.",
22584 format: "int64",
22585 }).check(Schema.isInt()),
22586 Schema.Null,
22587 ]),
22588 ),
22589 status: V2ReviewStartResponse__TurnStatus,
22590});
22591
22592export type V2SkillsListResponse__SkillsListEntry = {
22593 readonly cwd: string;
22594 readonly errors: ReadonlyArray<V2SkillsListResponse__SkillErrorInfo>;
22595 readonly skills: ReadonlyArray<V2SkillsListResponse__SkillMetadata>;
22596};
22597export const V2SkillsListResponse__SkillsListEntry = Schema.Struct({
22598 cwd: Schema.String,
22599 errors: Schema.Array(V2SkillsListResponse__SkillErrorInfo),
22600 skills: Schema.Array(V2SkillsListResponse__SkillMetadata),
22601});
22602
22603export type V2ThreadForkResponse__Turn = {
22604 readonly completedAt?: number | null;
22605 readonly durationMs?: number | null;
22606 readonly error?: V2ThreadForkResponse__TurnError | null;
22607 readonly id: string;
22608 readonly items: ReadonlyArray<V2ThreadForkResponse__ThreadItem>;
22609 readonly startedAt?: number | null;
22610 readonly status: V2ThreadForkResponse__TurnStatus;
22611};
22612export const V2ThreadForkResponse__Turn = Schema.Struct({
22613 completedAt: Schema.optionalKey(
22614 Schema.Union([
22615 Schema.Number.annotate({
22616 description: "Unix timestamp (in seconds) when the turn completed.",
22617 format: "int64",
22618 }).check(Schema.isInt()),
22619 Schema.Null,
22620 ]),
22621 ),
22622 durationMs: Schema.optionalKey(
22623 Schema.Union([
22624 Schema.Number.annotate({
22625 description: "Duration between turn start and completion in milliseconds, if known.",
22626 format: "int64",
22627 }).check(Schema.isInt()),
22628 Schema.Null,
22629 ]),
22630 ),
22631 error: Schema.optionalKey(
22632 Schema.Union([V2ThreadForkResponse__TurnError, Schema.Null]).annotate({
22633 description: "Only populated when the Turn's status is failed.",
22634 }),
22635 ),
22636 id: Schema.String,
22637 items: Schema.Array(V2ThreadForkResponse__ThreadItem).annotate({
22638 description:
22639 "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.",
22640 }),
22641 startedAt: Schema.optionalKey(
22642 Schema.Union([
22643 Schema.Number.annotate({
22644 description: "Unix timestamp (in seconds) when the turn started.",
22645 format: "int64",
22646 }).check(Schema.isInt()),
22647 Schema.Null,
22648 ]),
22649 ),
22650 status: V2ThreadForkResponse__TurnStatus,
22651});
22652
22653export type V2ThreadListResponse__Turn = {
22654 readonly completedAt?: number | null;
22655 readonly durationMs?: number | null;
22656 readonly error?: V2ThreadListResponse__TurnError | null;
22657 readonly id: string;
22658 readonly items: ReadonlyArray<V2ThreadListResponse__ThreadItem>;
22659 readonly startedAt?: number | null;
22660 readonly status: V2ThreadListResponse__TurnStatus;
22661};
22662export const V2ThreadListResponse__Turn = Schema.Struct({
22663 completedAt: Schema.optionalKey(
22664 Schema.Union([
22665 Schema.Number.annotate({
22666 description: "Unix timestamp (in seconds) when the turn completed.",
22667 format: "int64",
22668 }).check(Schema.isInt()),
22669 Schema.Null,
22670 ]),
22671 ),
22672 durationMs: Schema.optionalKey(
22673 Schema.Union([
22674 Schema.Number.annotate({
22675 description: "Duration between turn start and completion in milliseconds, if known.",
22676 format: "int64",
22677 }).check(Schema.isInt()),
22678 Schema.Null,
22679 ]),
22680 ),
22681 error: Schema.optionalKey(
22682 Schema.Union([V2ThreadListResponse__TurnError, Schema.Null]).annotate({
22683 description: "Only populated when the Turn's status is failed.",
22684 }),
22685 ),
22686 id: Schema.String,
22687 items: Schema.Array(V2ThreadListResponse__ThreadItem).annotate({
22688 description:
22689 "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.",
22690 }),
22691 startedAt: Schema.optionalKey(
22692 Schema.Union([
22693 Schema.Number.annotate({
22694 description: "Unix timestamp (in seconds) when the turn started.",
22695 format: "int64",
22696 }).check(Schema.isInt()),
22697 Schema.Null,
22698 ]),
22699 ),
22700 status: V2ThreadListResponse__TurnStatus,
22701});
22702
22703export type V2ThreadMetadataUpdateResponse__Turn = {
22704 readonly completedAt?: number | null;
22705 readonly durationMs?: number | null;
22706 readonly error?: V2ThreadMetadataUpdateResponse__TurnError | null;
22707 readonly id: string;
22708 readonly items: ReadonlyArray<V2ThreadMetadataUpdateResponse__ThreadItem>;
22709 readonly startedAt?: number | null;
22710 readonly status: V2ThreadMetadataUpdateResponse__TurnStatus;
22711};
22712export const V2ThreadMetadataUpdateResponse__Turn = Schema.Struct({
22713 completedAt: Schema.optionalKey(
22714 Schema.Union([
22715 Schema.Number.annotate({
22716 description: "Unix timestamp (in seconds) when the turn completed.",
22717 format: "int64",
22718 }).check(Schema.isInt()),
22719 Schema.Null,
22720 ]),
22721 ),
22722 durationMs: Schema.optionalKey(
22723 Schema.Union([
22724 Schema.Number.annotate({
22725 description: "Duration between turn start and completion in milliseconds, if known.",
22726 format: "int64",
22727 }).check(Schema.isInt()),
22728 Schema.Null,
22729 ]),
22730 ),
22731 error: Schema.optionalKey(
22732 Schema.Union([V2ThreadMetadataUpdateResponse__TurnError, Schema.Null]).annotate({
22733 description: "Only populated when the Turn's status is failed.",
22734 }),
22735 ),
22736 id: Schema.String,
22737 items: Schema.Array(V2ThreadMetadataUpdateResponse__ThreadItem).annotate({
22738 description:
22739 "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.",
22740 }),
22741 startedAt: Schema.optionalKey(
22742 Schema.Union([
22743 Schema.Number.annotate({
22744 description: "Unix timestamp (in seconds) when the turn started.",
22745 format: "int64",
22746 }).check(Schema.isInt()),
22747 Schema.Null,
22748 ]),
22749 ),
22750 status: V2ThreadMetadataUpdateResponse__TurnStatus,
22751});
22752
22753export type V2ThreadReadResponse__Turn = {
22754 readonly completedAt?: number | null;
22755 readonly durationMs?: number | null;
22756 readonly error?: V2ThreadReadResponse__TurnError | null;
22757 readonly id: string;
22758 readonly items: ReadonlyArray<V2ThreadReadResponse__ThreadItem>;
22759 readonly startedAt?: number | null;
22760 readonly status: V2ThreadReadResponse__TurnStatus;
22761};
22762export const V2ThreadReadResponse__Turn = Schema.Struct({
22763 completedAt: Schema.optionalKey(
22764 Schema.Union([
22765 Schema.Number.annotate({
22766 description: "Unix timestamp (in seconds) when the turn completed.",
22767 format: "int64",
22768 }).check(Schema.isInt()),
22769 Schema.Null,
22770 ]),
22771 ),
22772 durationMs: Schema.optionalKey(
22773 Schema.Union([
22774 Schema.Number.annotate({
22775 description: "Duration between turn start and completion in milliseconds, if known.",
22776 format: "int64",
22777 }).check(Schema.isInt()),
22778 Schema.Null,
22779 ]),
22780 ),
22781 error: Schema.optionalKey(
22782 Schema.Union([V2ThreadReadResponse__TurnError, Schema.Null]).annotate({
22783 description: "Only populated when the Turn's status is failed.",
22784 }),
22785 ),
22786 id: Schema.String,
22787 items: Schema.Array(V2ThreadReadResponse__ThreadItem).annotate({
22788 description:
22789 "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.",
22790 }),
22791 startedAt: Schema.optionalKey(
22792 Schema.Union([
22793 Schema.Number.annotate({
22794 description: "Unix timestamp (in seconds) when the turn started.",
22795 format: "int64",
22796 }).check(Schema.isInt()),
22797 Schema.Null,
22798 ]),
22799 ),
22800 status: V2ThreadReadResponse__TurnStatus,
22801});
22802
22803export type V2ThreadResumeResponse__Turn = {
22804 readonly completedAt?: number | null;
22805 readonly durationMs?: number | null;
22806 readonly error?: V2ThreadResumeResponse__TurnError | null;
22807 readonly id: string;
22808 readonly items: ReadonlyArray<V2ThreadResumeResponse__ThreadItem>;
22809 readonly startedAt?: number | null;
22810 readonly status: V2ThreadResumeResponse__TurnStatus;
22811};
22812export const V2ThreadResumeResponse__Turn = Schema.Struct({
22813 completedAt: Schema.optionalKey(
22814 Schema.Union([
22815 Schema.Number.annotate({
22816 description: "Unix timestamp (in seconds) when the turn completed.",
22817 format: "int64",
22818 }).check(Schema.isInt()),
22819 Schema.Null,
22820 ]),
22821 ),
22822 durationMs: Schema.optionalKey(
22823 Schema.Union([
22824 Schema.Number.annotate({
22825 description: "Duration between turn start and completion in milliseconds, if known.",
22826 format: "int64",
22827 }).check(Schema.isInt()),
22828 Schema.Null,
22829 ]),
22830 ),
22831 error: Schema.optionalKey(
22832 Schema.Union([V2ThreadResumeResponse__TurnError, Schema.Null]).annotate({
22833 description: "Only populated when the Turn's status is failed.",
22834 }),
22835 ),
22836 id: Schema.String,
22837 items: Schema.Array(V2ThreadResumeResponse__ThreadItem).annotate({
22838 description:
22839 "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.",
22840 }),
22841 startedAt: Schema.optionalKey(
22842 Schema.Union([
22843 Schema.Number.annotate({
22844 description: "Unix timestamp (in seconds) when the turn started.",
22845 format: "int64",
22846 }).check(Schema.isInt()),
22847 Schema.Null,
22848 ]),
22849 ),
22850 status: V2ThreadResumeResponse__TurnStatus,
22851});
22852
22853export type V2ThreadRollbackResponse__Turn = {
22854 readonly completedAt?: number | null;
22855 readonly durationMs?: number | null;
22856 readonly error?: V2ThreadRollbackResponse__TurnError | null;
22857 readonly id: string;
22858 readonly items: ReadonlyArray<V2ThreadRollbackResponse__ThreadItem>;
22859 readonly startedAt?: number | null;
22860 readonly status: V2ThreadRollbackResponse__TurnStatus;
22861};
22862export const V2ThreadRollbackResponse__Turn = Schema.Struct({
22863 completedAt: Schema.optionalKey(
22864 Schema.Union([
22865 Schema.Number.annotate({
22866 description: "Unix timestamp (in seconds) when the turn completed.",
22867 format: "int64",
22868 }).check(Schema.isInt()),
22869 Schema.Null,
22870 ]),
22871 ),
22872 durationMs: Schema.optionalKey(
22873 Schema.Union([
22874 Schema.Number.annotate({
22875 description: "Duration between turn start and completion in milliseconds, if known.",
22876 format: "int64",
22877 }).check(Schema.isInt()),
22878 Schema.Null,
22879 ]),
22880 ),
22881 error: Schema.optionalKey(
22882 Schema.Union([V2ThreadRollbackResponse__TurnError, Schema.Null]).annotate({
22883 description: "Only populated when the Turn's status is failed.",
22884 }),
22885 ),
22886 id: Schema.String,
22887 items: Schema.Array(V2ThreadRollbackResponse__ThreadItem).annotate({
22888 description:
22889 "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.",
22890 }),
22891 startedAt: Schema.optionalKey(
22892 Schema.Union([
22893 Schema.Number.annotate({
22894 description: "Unix timestamp (in seconds) when the turn started.",
22895 format: "int64",
22896 }).check(Schema.isInt()),
22897 Schema.Null,
22898 ]),
22899 ),
22900 status: V2ThreadRollbackResponse__TurnStatus,
22901});
22902
22903export type V2ThreadStartedNotification__Turn = {
22904 readonly completedAt?: number | null;
22905 readonly durationMs?: number | null;
22906 readonly error?: V2ThreadStartedNotification__TurnError | null;
22907 readonly id: string;
22908 readonly items: ReadonlyArray<V2ThreadStartedNotification__ThreadItem>;
22909 readonly startedAt?: number | null;
22910 readonly status: V2ThreadStartedNotification__TurnStatus;
22911};
22912export const V2ThreadStartedNotification__Turn = Schema.Struct({
22913 completedAt: Schema.optionalKey(
22914 Schema.Union([
22915 Schema.Number.annotate({
22916 description: "Unix timestamp (in seconds) when the turn completed.",
22917 format: "int64",
22918 }).check(Schema.isInt()),
22919 Schema.Null,
22920 ]),
22921 ),
22922 durationMs: Schema.optionalKey(
22923 Schema.Union([
22924 Schema.Number.annotate({
22925 description: "Duration between turn start and completion in milliseconds, if known.",
22926 format: "int64",
22927 }).check(Schema.isInt()),
22928 Schema.Null,
22929 ]),
22930 ),
22931 error: Schema.optionalKey(
22932 Schema.Union([V2ThreadStartedNotification__TurnError, Schema.Null]).annotate({
22933 description: "Only populated when the Turn's status is failed.",
22934 }),
22935 ),
22936 id: Schema.String,
22937 items: Schema.Array(V2ThreadStartedNotification__ThreadItem).annotate({
22938 description:
22939 "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.",
22940 }),
22941 startedAt: Schema.optionalKey(
22942 Schema.Union([
22943 Schema.Number.annotate({
22944 description: "Unix timestamp (in seconds) when the turn started.",
22945 format: "int64",
22946 }).check(Schema.isInt()),
22947 Schema.Null,
22948 ]),
22949 ),
22950 status: V2ThreadStartedNotification__TurnStatus,
22951});
22952
22953export type V2ThreadStartResponse__Turn = {
22954 readonly completedAt?: number | null;
22955 readonly durationMs?: number | null;
22956 readonly error?: V2ThreadStartResponse__TurnError | null;
22957 readonly id: string;
22958 readonly items: ReadonlyArray<V2ThreadStartResponse__ThreadItem>;
22959 readonly startedAt?: number | null;
22960 readonly status: V2ThreadStartResponse__TurnStatus;
22961};
22962export const V2ThreadStartResponse__Turn = Schema.Struct({
22963 completedAt: Schema.optionalKey(
22964 Schema.Union([
22965 Schema.Number.annotate({
22966 description: "Unix timestamp (in seconds) when the turn completed.",
22967 format: "int64",
22968 }).check(Schema.isInt()),
22969 Schema.Null,
22970 ]),
22971 ),
22972 durationMs: Schema.optionalKey(
22973 Schema.Union([
22974 Schema.Number.annotate({
22975 description: "Duration between turn start and completion in milliseconds, if known.",
22976 format: "int64",
22977 }).check(Schema.isInt()),
22978 Schema.Null,
22979 ]),
22980 ),
22981 error: Schema.optionalKey(
22982 Schema.Union([V2ThreadStartResponse__TurnError, Schema.Null]).annotate({
22983 description: "Only populated when the Turn's status is failed.",
22984 }),
22985 ),
22986 id: Schema.String,
22987 items: Schema.Array(V2ThreadStartResponse__ThreadItem).annotate({
22988 description:
22989 "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.",
22990 }),
22991 startedAt: Schema.optionalKey(
22992 Schema.Union([
22993 Schema.Number.annotate({
22994 description: "Unix timestamp (in seconds) when the turn started.",
22995 format: "int64",
22996 }).check(Schema.isInt()),
22997 Schema.Null,
22998 ]),
22999 ),
23000 status: V2ThreadStartResponse__TurnStatus,
23001});
23002
23003export type V2ThreadUnarchiveResponse__Turn = {
23004 readonly completedAt?: number | null;
23005 readonly durationMs?: number | null;
23006 readonly error?: V2ThreadUnarchiveResponse__TurnError | null;
23007 readonly id: string;
23008 readonly items: ReadonlyArray<V2ThreadUnarchiveResponse__ThreadItem>;
23009 readonly startedAt?: number | null;
23010 readonly status: V2ThreadUnarchiveResponse__TurnStatus;
23011};
23012export const V2ThreadUnarchiveResponse__Turn = Schema.Struct({
23013 completedAt: Schema.optionalKey(
23014 Schema.Union([
23015 Schema.Number.annotate({
23016 description: "Unix timestamp (in seconds) when the turn completed.",
23017 format: "int64",
23018 }).check(Schema.isInt()),
23019 Schema.Null,
23020 ]),
23021 ),
23022 durationMs: Schema.optionalKey(
23023 Schema.Union([
23024 Schema.Number.annotate({
23025 description: "Duration between turn start and completion in milliseconds, if known.",
23026 format: "int64",
23027 }).check(Schema.isInt()),
23028 Schema.Null,
23029 ]),
23030 ),
23031 error: Schema.optionalKey(
23032 Schema.Union([V2ThreadUnarchiveResponse__TurnError, Schema.Null]).annotate({
23033 description: "Only populated when the Turn's status is failed.",
23034 }),
23035 ),
23036 id: Schema.String,
23037 items: Schema.Array(V2ThreadUnarchiveResponse__ThreadItem).annotate({
23038 description:
23039 "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.",
23040 }),
23041 startedAt: Schema.optionalKey(
23042 Schema.Union([
23043 Schema.Number.annotate({
23044 description: "Unix timestamp (in seconds) when the turn started.",
23045 format: "int64",
23046 }).check(Schema.isInt()),
23047 Schema.Null,
23048 ]),
23049 ),
23050 status: V2ThreadUnarchiveResponse__TurnStatus,
23051});
23052
23053export type V2TurnCompletedNotification__Turn = {
23054 readonly completedAt?: number | null;
23055 readonly durationMs?: number | null;
23056 readonly error?: V2TurnCompletedNotification__TurnError | null;
23057 readonly id: string;
23058 readonly items: ReadonlyArray<V2TurnCompletedNotification__ThreadItem>;
23059 readonly startedAt?: number | null;
23060 readonly status: V2TurnCompletedNotification__TurnStatus;
23061};
23062export const V2TurnCompletedNotification__Turn = Schema.Struct({
23063 completedAt: Schema.optionalKey(
23064 Schema.Union([
23065 Schema.Number.annotate({
23066 description: "Unix timestamp (in seconds) when the turn completed.",
23067 format: "int64",
23068 }).check(Schema.isInt()),
23069 Schema.Null,
23070 ]),
23071 ),
23072 durationMs: Schema.optionalKey(
23073 Schema.Union([
23074 Schema.Number.annotate({
23075 description: "Duration between turn start and completion in milliseconds, if known.",
23076 format: "int64",
23077 }).check(Schema.isInt()),
23078 Schema.Null,
23079 ]),
23080 ),
23081 error: Schema.optionalKey(
23082 Schema.Union([V2TurnCompletedNotification__TurnError, Schema.Null]).annotate({
23083 description: "Only populated when the Turn's status is failed.",
23084 }),
23085 ),
23086 id: Schema.String,
23087 items: Schema.Array(V2TurnCompletedNotification__ThreadItem).annotate({
23088 description:
23089 "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.",
23090 }),
23091 startedAt: Schema.optionalKey(
23092 Schema.Union([
23093 Schema.Number.annotate({
23094 description: "Unix timestamp (in seconds) when the turn started.",
23095 format: "int64",
23096 }).check(Schema.isInt()),
23097 Schema.Null,
23098 ]),
23099 ),
23100 status: V2TurnCompletedNotification__TurnStatus,
23101});
23102
23103export type V2TurnStartedNotification__Turn = {
23104 readonly completedAt?: number | null;
23105 readonly durationMs?: number | null;
23106 readonly error?: V2TurnStartedNotification__TurnError | null;
23107 readonly id: string;
23108 readonly items: ReadonlyArray<V2TurnStartedNotification__ThreadItem>;
23109 readonly startedAt?: number | null;
23110 readonly status: V2TurnStartedNotification__TurnStatus;
23111};
23112export const V2TurnStartedNotification__Turn = Schema.Struct({
23113 completedAt: Schema.optionalKey(
23114 Schema.Union([
23115 Schema.Number.annotate({
23116 description: "Unix timestamp (in seconds) when the turn completed.",
23117 format: "int64",
23118 }).check(Schema.isInt()),
23119 Schema.Null,
23120 ]),
23121 ),
23122 durationMs: Schema.optionalKey(
23123 Schema.Union([
23124 Schema.Number.annotate({
23125 description: "Duration between turn start and completion in milliseconds, if known.",
23126 format: "int64",
23127 }).check(Schema.isInt()),
23128 Schema.Null,
23129 ]),
23130 ),
23131 error: Schema.optionalKey(
23132 Schema.Union([V2TurnStartedNotification__TurnError, Schema.Null]).annotate({
23133 description: "Only populated when the Turn's status is failed.",
23134 }),
23135 ),
23136 id: Schema.String,
23137 items: Schema.Array(V2TurnStartedNotification__ThreadItem).annotate({
23138 description:
23139 "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.",
23140 }),
23141 startedAt: Schema.optionalKey(
23142 Schema.Union([
23143 Schema.Number.annotate({
23144 description: "Unix timestamp (in seconds) when the turn started.",
23145 format: "int64",
23146 }).check(Schema.isInt()),
23147 Schema.Null,
23148 ]),
23149 ),
23150 status: V2TurnStartedNotification__TurnStatus,
23151});
23152
23153export type V2TurnStartResponse__Turn = {
23154 readonly completedAt?: number | null;
23155 readonly durationMs?: number | null;
23156 readonly error?: V2TurnStartResponse__TurnError | null;
23157 readonly id: string;
23158 readonly items: ReadonlyArray<V2TurnStartResponse__ThreadItem>;
23159 readonly startedAt?: number | null;
23160 readonly status: V2TurnStartResponse__TurnStatus;
23161};
23162export const V2TurnStartResponse__Turn = Schema.Struct({
23163 completedAt: Schema.optionalKey(
23164 Schema.Union([
23165 Schema.Number.annotate({
23166 description: "Unix timestamp (in seconds) when the turn completed.",
23167 format: "int64",
23168 }).check(Schema.isInt()),
23169 Schema.Null,
23170 ]),
23171 ),
23172 durationMs: Schema.optionalKey(
23173 Schema.Union([
23174 Schema.Number.annotate({
23175 description: "Duration between turn start and completion in milliseconds, if known.",
23176 format: "int64",
23177 }).check(Schema.isInt()),
23178 Schema.Null,
23179 ]),
23180 ),
23181 error: Schema.optionalKey(
23182 Schema.Union([V2TurnStartResponse__TurnError, Schema.Null]).annotate({
23183 description: "Only populated when the Turn's status is failed.",
23184 }),
23185 ),
23186 id: Schema.String,
23187 items: Schema.Array(V2TurnStartResponse__ThreadItem).annotate({
23188 description:
23189 "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.",
23190 }),
23191 startedAt: Schema.optionalKey(
23192 Schema.Union([
23193 Schema.Number.annotate({
23194 description: "Unix timestamp (in seconds) when the turn started.",
23195 format: "int64",
23196 }).check(Schema.isInt()),
23197 Schema.Null,
23198 ]),
23199 ),
23200 status: V2TurnStartResponse__TurnStatus,
23201});
23202
23203export type McpServerElicitationRequestParams__McpElicitationEnumSchema =
23204 | McpServerElicitationRequestParams__McpElicitationSingleSelectEnumSchema
23205 | McpServerElicitationRequestParams__McpElicitationMultiSelectEnumSchema
23206 | McpServerElicitationRequestParams__McpElicitationLegacyTitledEnumSchema;
23207export const McpServerElicitationRequestParams__McpElicitationEnumSchema = Schema.Union([
23208 McpServerElicitationRequestParams__McpElicitationSingleSelectEnumSchema,
23209 McpServerElicitationRequestParams__McpElicitationMultiSelectEnumSchema,
23210 McpServerElicitationRequestParams__McpElicitationLegacyTitledEnumSchema,
23211]);
23212
23213export type ServerNotification__Thread = {
23214 readonly agentNickname?: string | null;
23215 readonly agentRole?: string | null;
23216 readonly cliVersion: string;
23217 readonly createdAt: number;
23218 readonly cwd: string;
23219 readonly ephemeral: boolean;
23220 readonly forkedFromId?: string | null;
23221 readonly gitInfo?: ServerNotification__GitInfo | null;
23222 readonly id: string;
23223 readonly modelProvider: string;
23224 readonly name?: string | null;
23225 readonly path?: string | null;
23226 readonly preview: string;
23227 readonly source:
23228 | "cli"
23229 | "vscode"
23230 | "exec"
23231 | "appServer"
23232 | "unknown"
23233 | { readonly custom: string }
23234 | { readonly subAgent: ServerNotification__SubAgentSource };
23235 readonly status:
23236 | { readonly type: "notLoaded" }
23237 | { readonly type: "idle" }
23238 | { readonly type: "systemError" }
23239 | {
23240 readonly activeFlags: ReadonlyArray<ServerNotification__ThreadActiveFlag>;
23241 readonly type: "active";
23242 };
23243 readonly turns: ReadonlyArray<ServerNotification__Turn>;
23244 readonly updatedAt: number;
23245};
23246export const ServerNotification__Thread = Schema.Struct({
23247 agentNickname: Schema.optionalKey(
23248 Schema.Union([
23249 Schema.String.annotate({
23250 description:
23251 "Optional random unique nickname assigned to an AgentControl-spawned sub-agent.",
23252 }),
23253 Schema.Null,
23254 ]),
23255 ),
23256 agentRole: Schema.optionalKey(
23257 Schema.Union([
23258 Schema.String.annotate({
23259 description: "Optional role (agent_role) assigned to an AgentControl-spawned sub-agent.",
23260 }),
23261 Schema.Null,
23262 ]),
23263 ),
23264 cliVersion: Schema.String.annotate({
23265 description: "Version of the CLI that created the thread.",
23266 }),
23267 createdAt: Schema.Number.annotate({
23268 description: "Unix timestamp (in seconds) when the thread was created.",
23269 format: "int64",
23270 }).check(Schema.isInt()),
23271 cwd: Schema.String.annotate({ description: "Working directory captured for the thread." }),
23272 ephemeral: Schema.Boolean.annotate({
23273 description: "Whether the thread is ephemeral and should not be materialized on disk.",
23274 }),
23275 forkedFromId: Schema.optionalKey(
23276 Schema.Union([
23277 Schema.String.annotate({
23278 description: "Source thread id when this thread was created by forking another thread.",
23279 }),
23280 Schema.Null,
23281 ]),
23282 ),
23283 gitInfo: Schema.optionalKey(
23284 Schema.Union([ServerNotification__GitInfo, Schema.Null]).annotate({
23285 description: "Optional Git metadata captured when the thread was created.",
23286 }),
23287 ),
23288 id: Schema.String,
23289 modelProvider: Schema.String.annotate({
23290 description: "Model provider used for this thread (for example, 'openai').",
23291 }),
23292 name: Schema.optionalKey(
23293 Schema.Union([
23294 Schema.String.annotate({ description: "Optional user-facing thread title." }),
23295 Schema.Null,
23296 ]),
23297 ),
23298 path: Schema.optionalKey(
23299 Schema.Union([
23300 Schema.String.annotate({ description: "[UNSTABLE] Path to the thread on disk." }),
23301 Schema.Null,
23302 ]),
23303 ),
23304 preview: Schema.String.annotate({
23305 description: "Usually the first user message in the thread, if available.",
23306 }),
23307 source: Schema.Union(
23308 [
23309 Schema.Literals(["cli", "vscode", "exec", "appServer", "unknown"]),
23310 Schema.Struct({ custom: Schema.String }).annotate({ title: "CustomSessionSource" }),
23311 Schema.Struct({ subAgent: ServerNotification__SubAgentSource }).annotate({
23312 title: "SubAgentSessionSource",
23313 }),
23314 ],
23315 { mode: "oneOf" },
23316 ).annotate({
23317 description: "Origin of the thread (CLI, VSCode, codex exec, codex app-server, etc.).",
23318 }),
23319 status: Schema.Union(
23320 [
23321 Schema.Struct({
23322 type: Schema.Literal("notLoaded").annotate({ title: "NotLoadedThreadStatusType" }),
23323 }).annotate({ title: "NotLoadedThreadStatus" }),
23324 Schema.Struct({
23325 type: Schema.Literal("idle").annotate({ title: "IdleThreadStatusType" }),
23326 }).annotate({ title: "IdleThreadStatus" }),
23327 Schema.Struct({
23328 type: Schema.Literal("systemError").annotate({ title: "SystemErrorThreadStatusType" }),
23329 }).annotate({ title: "SystemErrorThreadStatus" }),
23330 Schema.Struct({
23331 activeFlags: Schema.Array(ServerNotification__ThreadActiveFlag),
23332 type: Schema.Literal("active").annotate({ title: "ActiveThreadStatusType" }),
23333 }).annotate({ title: "ActiveThreadStatus" }),
23334 ],
23335 { mode: "oneOf" },
23336 ).annotate({ description: "Current runtime status for the thread." }),
23337 turns: Schema.Array(ServerNotification__Turn).annotate({
23338 description:
23339 "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.",
23340 }),
23341 updatedAt: Schema.Number.annotate({
23342 description: "Unix timestamp (in seconds) when the thread was last updated.",
23343 format: "int64",
23344 }).check(Schema.isInt()),
23345});
23346
23347export type ServerNotification__TurnCompletedNotification = {
23348 readonly threadId: string;
23349 readonly turn: ServerNotification__Turn;
23350};
23351export const ServerNotification__TurnCompletedNotification = Schema.Struct({
23352 threadId: Schema.String,
23353 turn: ServerNotification__Turn,
23354});
23355
23356export type ServerNotification__TurnStartedNotification = {
23357 readonly threadId: string;
23358 readonly turn: ServerNotification__Turn;
23359};
23360export const ServerNotification__TurnStartedNotification = Schema.Struct({
23361 threadId: Schema.String,
23362 turn: ServerNotification__Turn,
23363});
23364
23365export type ServerRequest__McpElicitationEnumSchema =
23366 | ServerRequest__McpElicitationSingleSelectEnumSchema
23367 | ServerRequest__McpElicitationMultiSelectEnumSchema
23368 | ServerRequest__McpElicitationLegacyTitledEnumSchema;
23369export const ServerRequest__McpElicitationEnumSchema = Schema.Union([
23370 ServerRequest__McpElicitationSingleSelectEnumSchema,
23371 ServerRequest__McpElicitationMultiSelectEnumSchema,
23372 ServerRequest__McpElicitationLegacyTitledEnumSchema,
23373]);
23374
23375export type V2ConfigReadResponse__Config = {
23376 readonly analytics?: V2ConfigReadResponse__AnalyticsConfig | null;
23377 readonly approval_policy?: V2ConfigReadResponse__AskForApproval | null;
23378 readonly approvals_reviewer?: V2ConfigReadResponse__ApprovalsReviewer | null;
23379 readonly compact_prompt?: string | null;
23380 readonly developer_instructions?: string | null;
23381 readonly forced_chatgpt_workspace_id?: string | null;
23382 readonly forced_login_method?: V2ConfigReadResponse__ForcedLoginMethod | null;
23383 readonly instructions?: string | null;
23384 readonly model?: string | null;
23385 readonly model_auto_compact_token_limit?: number | null;
23386 readonly model_context_window?: number | null;
23387 readonly model_provider?: string | null;
23388 readonly model_reasoning_effort?: V2ConfigReadResponse__ReasoningEffort | null;
23389 readonly model_reasoning_summary?: V2ConfigReadResponse__ReasoningSummary | null;
23390 readonly model_verbosity?: V2ConfigReadResponse__Verbosity | null;
23391 readonly profile?: string | null;
23392 readonly profiles?: { readonly [x: string]: V2ConfigReadResponse__ProfileV2 };
23393 readonly review_model?: string | null;
23394 readonly sandbox_mode?: V2ConfigReadResponse__SandboxMode | null;
23395 readonly sandbox_workspace_write?: V2ConfigReadResponse__SandboxWorkspaceWrite | null;
23396 readonly service_tier?: V2ConfigReadResponse__ServiceTier | null;
23397 readonly tools?: V2ConfigReadResponse__ToolsV2 | null;
23398 readonly web_search?: V2ConfigReadResponse__WebSearchMode | null;
23399 readonly [x: string]: unknown;
23400};
23401export const V2ConfigReadResponse__Config = Schema.StructWithRest(
23402 Schema.Struct({
23403 analytics: Schema.optionalKey(
23404 Schema.Union([V2ConfigReadResponse__AnalyticsConfig, Schema.Null]),
23405 ),
23406 approval_policy: Schema.optionalKey(
23407 Schema.Union([V2ConfigReadResponse__AskForApproval, Schema.Null]),
23408 ),
23409 approvals_reviewer: Schema.optionalKey(
23410 Schema.Union([V2ConfigReadResponse__ApprovalsReviewer, Schema.Null]).annotate({
23411 description:
23412 "[UNSTABLE] Optional default for where approval requests are routed for review.",
23413 }),
23414 ),
23415 compact_prompt: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
23416 developer_instructions: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
23417 forced_chatgpt_workspace_id: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
23418 forced_login_method: Schema.optionalKey(
23419 Schema.Union([V2ConfigReadResponse__ForcedLoginMethod, Schema.Null]),
23420 ),
23421 instructions: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
23422 model: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
23423 model_auto_compact_token_limit: Schema.optionalKey(
23424 Schema.Union([
23425 Schema.Number.annotate({ format: "int64" }).check(Schema.isInt()),
23426 Schema.Null,
23427 ]),
23428 ),
23429 model_context_window: Schema.optionalKey(
23430 Schema.Union([
23431 Schema.Number.annotate({ format: "int64" }).check(Schema.isInt()),
23432 Schema.Null,
23433 ]),
23434 ),
23435 model_provider: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
23436 model_reasoning_effort: Schema.optionalKey(
23437 Schema.Union([V2ConfigReadResponse__ReasoningEffort, Schema.Null]),
23438 ),
23439 model_reasoning_summary: Schema.optionalKey(
23440 Schema.Union([V2ConfigReadResponse__ReasoningSummary, Schema.Null]),
23441 ),
23442 model_verbosity: Schema.optionalKey(
23443 Schema.Union([V2ConfigReadResponse__Verbosity, Schema.Null]),
23444 ),
23445 profile: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
23446 profiles: Schema.optionalKey(
23447 Schema.Record(Schema.String, V2ConfigReadResponse__ProfileV2).annotate({ default: {} }),
23448 ),
23449 review_model: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
23450 sandbox_mode: Schema.optionalKey(
23451 Schema.Union([V2ConfigReadResponse__SandboxMode, Schema.Null]),
23452 ),
23453 sandbox_workspace_write: Schema.optionalKey(
23454 Schema.Union([V2ConfigReadResponse__SandboxWorkspaceWrite, Schema.Null]),
23455 ),
23456 service_tier: Schema.optionalKey(
23457 Schema.Union([V2ConfigReadResponse__ServiceTier, Schema.Null]),
23458 ),
23459 tools: Schema.optionalKey(Schema.Union([V2ConfigReadResponse__ToolsV2, Schema.Null])),
23460 web_search: Schema.optionalKey(
23461 Schema.Union([V2ConfigReadResponse__WebSearchMode, Schema.Null]),
23462 ),
23463 }),
23464 [Schema.Record(Schema.String, Schema.Unknown)],
23465);
23466
23467export type V2ThreadForkResponse__Thread = {
23468 readonly agentNickname?: string | null;
23469 readonly agentRole?: string | null;
23470 readonly cliVersion: string;
23471 readonly createdAt: number;
23472 readonly cwd: string;
23473 readonly ephemeral: boolean;
23474 readonly forkedFromId?: string | null;
23475 readonly gitInfo?: V2ThreadForkResponse__GitInfo | null;
23476 readonly id: string;
23477 readonly modelProvider: string;
23478 readonly name?: string | null;
23479 readonly path?: string | null;
23480 readonly preview: string;
23481 readonly source:
23482 | "cli"
23483 | "vscode"
23484 | "exec"
23485 | "appServer"
23486 | "unknown"
23487 | { readonly custom: string }
23488 | { readonly subAgent: V2ThreadForkResponse__SubAgentSource };
23489 readonly status:
23490 | { readonly type: "notLoaded" }
23491 | { readonly type: "idle" }
23492 | { readonly type: "systemError" }
23493 | {
23494 readonly activeFlags: ReadonlyArray<V2ThreadForkResponse__ThreadActiveFlag>;
23495 readonly type: "active";
23496 };
23497 readonly turns: ReadonlyArray<V2ThreadForkResponse__Turn>;
23498 readonly updatedAt: number;
23499};
23500export const V2ThreadForkResponse__Thread = Schema.Struct({
23501 agentNickname: Schema.optionalKey(
23502 Schema.Union([
23503 Schema.String.annotate({
23504 description:
23505 "Optional random unique nickname assigned to an AgentControl-spawned sub-agent.",
23506 }),
23507 Schema.Null,
23508 ]),
23509 ),
23510 agentRole: Schema.optionalKey(
23511 Schema.Union([
23512 Schema.String.annotate({
23513 description: "Optional role (agent_role) assigned to an AgentControl-spawned sub-agent.",
23514 }),
23515 Schema.Null,
23516 ]),
23517 ),
23518 cliVersion: Schema.String.annotate({
23519 description: "Version of the CLI that created the thread.",
23520 }),
23521 createdAt: Schema.Number.annotate({
23522 description: "Unix timestamp (in seconds) when the thread was created.",
23523 format: "int64",
23524 }).check(Schema.isInt()),
23525 cwd: Schema.String.annotate({ description: "Working directory captured for the thread." }),
23526 ephemeral: Schema.Boolean.annotate({
23527 description: "Whether the thread is ephemeral and should not be materialized on disk.",
23528 }),
23529 forkedFromId: Schema.optionalKey(
23530 Schema.Union([
23531 Schema.String.annotate({
23532 description: "Source thread id when this thread was created by forking another thread.",
23533 }),
23534 Schema.Null,
23535 ]),
23536 ),
23537 gitInfo: Schema.optionalKey(
23538 Schema.Union([V2ThreadForkResponse__GitInfo, Schema.Null]).annotate({
23539 description: "Optional Git metadata captured when the thread was created.",
23540 }),
23541 ),
23542 id: Schema.String,
23543 modelProvider: Schema.String.annotate({
23544 description: "Model provider used for this thread (for example, 'openai').",
23545 }),
23546 name: Schema.optionalKey(
23547 Schema.Union([
23548 Schema.String.annotate({ description: "Optional user-facing thread title." }),
23549 Schema.Null,
23550 ]),
23551 ),
23552 path: Schema.optionalKey(
23553 Schema.Union([
23554 Schema.String.annotate({ description: "[UNSTABLE] Path to the thread on disk." }),
23555 Schema.Null,
23556 ]),
23557 ),
23558 preview: Schema.String.annotate({
23559 description: "Usually the first user message in the thread, if available.",
23560 }),
23561 source: Schema.Union(
23562 [
23563 Schema.Literals(["cli", "vscode", "exec", "appServer", "unknown"]),
23564 Schema.Struct({ custom: Schema.String }).annotate({ title: "CustomSessionSource" }),
23565 Schema.Struct({ subAgent: V2ThreadForkResponse__SubAgentSource }).annotate({
23566 title: "SubAgentSessionSource",
23567 }),
23568 ],
23569 { mode: "oneOf" },
23570 ).annotate({
23571 description: "Origin of the thread (CLI, VSCode, codex exec, codex app-server, etc.).",
23572 }),
23573 status: Schema.Union(
23574 [
23575 Schema.Struct({
23576 type: Schema.Literal("notLoaded").annotate({ title: "NotLoadedThreadStatusType" }),
23577 }).annotate({ title: "NotLoadedThreadStatus" }),
23578 Schema.Struct({
23579 type: Schema.Literal("idle").annotate({ title: "IdleThreadStatusType" }),
23580 }).annotate({ title: "IdleThreadStatus" }),
23581 Schema.Struct({
23582 type: Schema.Literal("systemError").annotate({ title: "SystemErrorThreadStatusType" }),
23583 }).annotate({ title: "SystemErrorThreadStatus" }),
23584 Schema.Struct({
23585 activeFlags: Schema.Array(V2ThreadForkResponse__ThreadActiveFlag),
23586 type: Schema.Literal("active").annotate({ title: "ActiveThreadStatusType" }),
23587 }).annotate({ title: "ActiveThreadStatus" }),
23588 ],
23589 { mode: "oneOf" },
23590 ).annotate({ description: "Current runtime status for the thread." }),
23591 turns: Schema.Array(V2ThreadForkResponse__Turn).annotate({
23592 description:
23593 "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.",
23594 }),
23595 updatedAt: Schema.Number.annotate({
23596 description: "Unix timestamp (in seconds) when the thread was last updated.",
23597 format: "int64",
23598 }).check(Schema.isInt()),
23599});
23600
23601export type V2ThreadListResponse__Thread = {
23602 readonly agentNickname?: string | null;
23603 readonly agentRole?: string | null;
23604 readonly cliVersion: string;
23605 readonly createdAt: number;
23606 readonly cwd: string;
23607 readonly ephemeral: boolean;
23608 readonly forkedFromId?: string | null;
23609 readonly gitInfo?: V2ThreadListResponse__GitInfo | null;
23610 readonly id: string;
23611 readonly modelProvider: string;
23612 readonly name?: string | null;
23613 readonly path?: string | null;
23614 readonly preview: string;
23615 readonly source:
23616 | "cli"
23617 | "vscode"
23618 | "exec"
23619 | "appServer"
23620 | "unknown"
23621 | { readonly custom: string }
23622 | { readonly subAgent: V2ThreadListResponse__SubAgentSource };
23623 readonly status:
23624 | { readonly type: "notLoaded" }
23625 | { readonly type: "idle" }
23626 | { readonly type: "systemError" }
23627 | {
23628 readonly activeFlags: ReadonlyArray<V2ThreadListResponse__ThreadActiveFlag>;
23629 readonly type: "active";
23630 };
23631 readonly turns: ReadonlyArray<V2ThreadListResponse__Turn>;
23632 readonly updatedAt: number;
23633};
23634export const V2ThreadListResponse__Thread = Schema.Struct({
23635 agentNickname: Schema.optionalKey(
23636 Schema.Union([
23637 Schema.String.annotate({
23638 description:
23639 "Optional random unique nickname assigned to an AgentControl-spawned sub-agent.",
23640 }),
23641 Schema.Null,
23642 ]),
23643 ),
23644 agentRole: Schema.optionalKey(
23645 Schema.Union([
23646 Schema.String.annotate({
23647 description: "Optional role (agent_role) assigned to an AgentControl-spawned sub-agent.",
23648 }),
23649 Schema.Null,
23650 ]),
23651 ),
23652 cliVersion: Schema.String.annotate({
23653 description: "Version of the CLI that created the thread.",
23654 }),
23655 createdAt: Schema.Number.annotate({
23656 description: "Unix timestamp (in seconds) when the thread was created.",
23657 format: "int64",
23658 }).check(Schema.isInt()),
23659 cwd: Schema.String.annotate({ description: "Working directory captured for the thread." }),
23660 ephemeral: Schema.Boolean.annotate({
23661 description: "Whether the thread is ephemeral and should not be materialized on disk.",
23662 }),
23663 forkedFromId: Schema.optionalKey(
23664 Schema.Union([
23665 Schema.String.annotate({
23666 description: "Source thread id when this thread was created by forking another thread.",
23667 }),
23668 Schema.Null,
23669 ]),
23670 ),
23671 gitInfo: Schema.optionalKey(
23672 Schema.Union([V2ThreadListResponse__GitInfo, Schema.Null]).annotate({
23673 description: "Optional Git metadata captured when the thread was created.",
23674 }),
23675 ),
23676 id: Schema.String,
23677 modelProvider: Schema.String.annotate({
23678 description: "Model provider used for this thread (for example, 'openai').",
23679 }),
23680 name: Schema.optionalKey(
23681 Schema.Union([
23682 Schema.String.annotate({ description: "Optional user-facing thread title." }),
23683 Schema.Null,
23684 ]),
23685 ),
23686 path: Schema.optionalKey(
23687 Schema.Union([
23688 Schema.String.annotate({ description: "[UNSTABLE] Path to the thread on disk." }),
23689 Schema.Null,
23690 ]),
23691 ),
23692 preview: Schema.String.annotate({
23693 description: "Usually the first user message in the thread, if available.",
23694 }),
23695 source: Schema.Union(
23696 [
23697 Schema.Literals(["cli", "vscode", "exec", "appServer", "unknown"]),
23698 Schema.Struct({ custom: Schema.String }).annotate({ title: "CustomSessionSource" }),
23699 Schema.Struct({ subAgent: V2ThreadListResponse__SubAgentSource }).annotate({
23700 title: "SubAgentSessionSource",
23701 }),
23702 ],
23703 { mode: "oneOf" },
23704 ).annotate({
23705 description: "Origin of the thread (CLI, VSCode, codex exec, codex app-server, etc.).",
23706 }),
23707 status: Schema.Union(
23708 [
23709 Schema.Struct({
23710 type: Schema.Literal("notLoaded").annotate({ title: "NotLoadedThreadStatusType" }),
23711 }).annotate({ title: "NotLoadedThreadStatus" }),
23712 Schema.Struct({
23713 type: Schema.Literal("idle").annotate({ title: "IdleThreadStatusType" }),
23714 }).annotate({ title: "IdleThreadStatus" }),
23715 Schema.Struct({
23716 type: Schema.Literal("systemError").annotate({ title: "SystemErrorThreadStatusType" }),
23717 }).annotate({ title: "SystemErrorThreadStatus" }),
23718 Schema.Struct({
23719 activeFlags: Schema.Array(V2ThreadListResponse__ThreadActiveFlag),
23720 type: Schema.Literal("active").annotate({ title: "ActiveThreadStatusType" }),
23721 }).annotate({ title: "ActiveThreadStatus" }),
23722 ],
23723 { mode: "oneOf" },
23724 ).annotate({ description: "Current runtime status for the thread." }),
23725 turns: Schema.Array(V2ThreadListResponse__Turn).annotate({
23726 description:
23727 "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.",
23728 }),
23729 updatedAt: Schema.Number.annotate({
23730 description: "Unix timestamp (in seconds) when the thread was last updated.",
23731 format: "int64",
23732 }).check(Schema.isInt()),
23733});
23734
23735export type V2ThreadMetadataUpdateResponse__Thread = {
23736 readonly agentNickname?: string | null;
23737 readonly agentRole?: string | null;
23738 readonly cliVersion: string;
23739 readonly createdAt: number;
23740 readonly cwd: string;
23741 readonly ephemeral: boolean;
23742 readonly forkedFromId?: string | null;
23743 readonly gitInfo?: V2ThreadMetadataUpdateResponse__GitInfo | null;
23744 readonly id: string;
23745 readonly modelProvider: string;
23746 readonly name?: string | null;
23747 readonly path?: string | null;
23748 readonly preview: string;
23749 readonly source:
23750 | "cli"
23751 | "vscode"
23752 | "exec"
23753 | "appServer"
23754 | "unknown"
23755 | { readonly custom: string }
23756 | { readonly subAgent: V2ThreadMetadataUpdateResponse__SubAgentSource };
23757 readonly status:
23758 | { readonly type: "notLoaded" }
23759 | { readonly type: "idle" }
23760 | { readonly type: "systemError" }
23761 | {
23762 readonly activeFlags: ReadonlyArray<V2ThreadMetadataUpdateResponse__ThreadActiveFlag>;
23763 readonly type: "active";
23764 };
23765 readonly turns: ReadonlyArray<V2ThreadMetadataUpdateResponse__Turn>;
23766 readonly updatedAt: number;
23767};
23768export const V2ThreadMetadataUpdateResponse__Thread = Schema.Struct({
23769 agentNickname: Schema.optionalKey(
23770 Schema.Union([
23771 Schema.String.annotate({
23772 description:
23773 "Optional random unique nickname assigned to an AgentControl-spawned sub-agent.",
23774 }),
23775 Schema.Null,
23776 ]),
23777 ),
23778 agentRole: Schema.optionalKey(
23779 Schema.Union([
23780 Schema.String.annotate({
23781 description: "Optional role (agent_role) assigned to an AgentControl-spawned sub-agent.",
23782 }),
23783 Schema.Null,
23784 ]),
23785 ),
23786 cliVersion: Schema.String.annotate({
23787 description: "Version of the CLI that created the thread.",
23788 }),
23789 createdAt: Schema.Number.annotate({
23790 description: "Unix timestamp (in seconds) when the thread was created.",
23791 format: "int64",
23792 }).check(Schema.isInt()),
23793 cwd: Schema.String.annotate({ description: "Working directory captured for the thread." }),
23794 ephemeral: Schema.Boolean.annotate({
23795 description: "Whether the thread is ephemeral and should not be materialized on disk.",
23796 }),
23797 forkedFromId: Schema.optionalKey(
23798 Schema.Union([
23799 Schema.String.annotate({
23800 description: "Source thread id when this thread was created by forking another thread.",
23801 }),
23802 Schema.Null,
23803 ]),
23804 ),
23805 gitInfo: Schema.optionalKey(
23806 Schema.Union([V2ThreadMetadataUpdateResponse__GitInfo, Schema.Null]).annotate({
23807 description: "Optional Git metadata captured when the thread was created.",
23808 }),
23809 ),
23810 id: Schema.String,
23811 modelProvider: Schema.String.annotate({
23812 description: "Model provider used for this thread (for example, 'openai').",
23813 }),
23814 name: Schema.optionalKey(
23815 Schema.Union([
23816 Schema.String.annotate({ description: "Optional user-facing thread title." }),
23817 Schema.Null,
23818 ]),
23819 ),
23820 path: Schema.optionalKey(
23821 Schema.Union([
23822 Schema.String.annotate({ description: "[UNSTABLE] Path to the thread on disk." }),
23823 Schema.Null,
23824 ]),
23825 ),
23826 preview: Schema.String.annotate({
23827 description: "Usually the first user message in the thread, if available.",
23828 }),
23829 source: Schema.Union(
23830 [
23831 Schema.Literals(["cli", "vscode", "exec", "appServer", "unknown"]),
23832 Schema.Struct({ custom: Schema.String }).annotate({ title: "CustomSessionSource" }),
23833 Schema.Struct({ subAgent: V2ThreadMetadataUpdateResponse__SubAgentSource }).annotate({
23834 title: "SubAgentSessionSource",
23835 }),
23836 ],
23837 { mode: "oneOf" },
23838 ).annotate({
23839 description: "Origin of the thread (CLI, VSCode, codex exec, codex app-server, etc.).",
23840 }),
23841 status: Schema.Union(
23842 [
23843 Schema.Struct({
23844 type: Schema.Literal("notLoaded").annotate({ title: "NotLoadedThreadStatusType" }),
23845 }).annotate({ title: "NotLoadedThreadStatus" }),
23846 Schema.Struct({
23847 type: Schema.Literal("idle").annotate({ title: "IdleThreadStatusType" }),
23848 }).annotate({ title: "IdleThreadStatus" }),
23849 Schema.Struct({
23850 type: Schema.Literal("systemError").annotate({ title: "SystemErrorThreadStatusType" }),
23851 }).annotate({ title: "SystemErrorThreadStatus" }),
23852 Schema.Struct({
23853 activeFlags: Schema.Array(V2ThreadMetadataUpdateResponse__ThreadActiveFlag),
23854 type: Schema.Literal("active").annotate({ title: "ActiveThreadStatusType" }),
23855 }).annotate({ title: "ActiveThreadStatus" }),
23856 ],
23857 { mode: "oneOf" },
23858 ).annotate({ description: "Current runtime status for the thread." }),
23859 turns: Schema.Array(V2ThreadMetadataUpdateResponse__Turn).annotate({
23860 description:
23861 "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.",
23862 }),
23863 updatedAt: Schema.Number.annotate({
23864 description: "Unix timestamp (in seconds) when the thread was last updated.",
23865 format: "int64",
23866 }).check(Schema.isInt()),
23867});
23868
23869export type V2ThreadReadResponse__Thread = {
23870 readonly agentNickname?: string | null;
23871 readonly agentRole?: string | null;
23872 readonly cliVersion: string;
23873 readonly createdAt: number;
23874 readonly cwd: string;
23875 readonly ephemeral: boolean;
23876 readonly forkedFromId?: string | null;
23877 readonly gitInfo?: V2ThreadReadResponse__GitInfo | null;
23878 readonly id: string;
23879 readonly modelProvider: string;
23880 readonly name?: string | null;
23881 readonly path?: string | null;
23882 readonly preview: string;
23883 readonly source:
23884 | "cli"
23885 | "vscode"
23886 | "exec"
23887 | "appServer"
23888 | "unknown"
23889 | { readonly custom: string }
23890 | { readonly subAgent: V2ThreadReadResponse__SubAgentSource };
23891 readonly status:
23892 | { readonly type: "notLoaded" }
23893 | { readonly type: "idle" }
23894 | { readonly type: "systemError" }
23895 | {
23896 readonly activeFlags: ReadonlyArray<V2ThreadReadResponse__ThreadActiveFlag>;
23897 readonly type: "active";
23898 };
23899 readonly turns: ReadonlyArray<V2ThreadReadResponse__Turn>;
23900 readonly updatedAt: number;
23901};
23902export const V2ThreadReadResponse__Thread = Schema.Struct({
23903 agentNickname: Schema.optionalKey(
23904 Schema.Union([
23905 Schema.String.annotate({
23906 description:
23907 "Optional random unique nickname assigned to an AgentControl-spawned sub-agent.",
23908 }),
23909 Schema.Null,
23910 ]),
23911 ),
23912 agentRole: Schema.optionalKey(
23913 Schema.Union([
23914 Schema.String.annotate({
23915 description: "Optional role (agent_role) assigned to an AgentControl-spawned sub-agent.",
23916 }),
23917 Schema.Null,
23918 ]),
23919 ),
23920 cliVersion: Schema.String.annotate({
23921 description: "Version of the CLI that created the thread.",
23922 }),
23923 createdAt: Schema.Number.annotate({
23924 description: "Unix timestamp (in seconds) when the thread was created.",
23925 format: "int64",
23926 }).check(Schema.isInt()),
23927 cwd: Schema.String.annotate({ description: "Working directory captured for the thread." }),
23928 ephemeral: Schema.Boolean.annotate({
23929 description: "Whether the thread is ephemeral and should not be materialized on disk.",
23930 }),
23931 forkedFromId: Schema.optionalKey(
23932 Schema.Union([
23933 Schema.String.annotate({
23934 description: "Source thread id when this thread was created by forking another thread.",
23935 }),
23936 Schema.Null,
23937 ]),
23938 ),
23939 gitInfo: Schema.optionalKey(
23940 Schema.Union([V2ThreadReadResponse__GitInfo, Schema.Null]).annotate({
23941 description: "Optional Git metadata captured when the thread was created.",
23942 }),
23943 ),
23944 id: Schema.String,
23945 modelProvider: Schema.String.annotate({
23946 description: "Model provider used for this thread (for example, 'openai').",
23947 }),
23948 name: Schema.optionalKey(
23949 Schema.Union([
23950 Schema.String.annotate({ description: "Optional user-facing thread title." }),
23951 Schema.Null,
23952 ]),
23953 ),
23954 path: Schema.optionalKey(
23955 Schema.Union([
23956 Schema.String.annotate({ description: "[UNSTABLE] Path to the thread on disk." }),
23957 Schema.Null,
23958 ]),
23959 ),
23960 preview: Schema.String.annotate({
23961 description: "Usually the first user message in the thread, if available.",
23962 }),
23963 source: Schema.Union(
23964 [
23965 Schema.Literals(["cli", "vscode", "exec", "appServer", "unknown"]),
23966 Schema.Struct({ custom: Schema.String }).annotate({ title: "CustomSessionSource" }),
23967 Schema.Struct({ subAgent: V2ThreadReadResponse__SubAgentSource }).annotate({
23968 title: "SubAgentSessionSource",
23969 }),
23970 ],
23971 { mode: "oneOf" },
23972 ).annotate({
23973 description: "Origin of the thread (CLI, VSCode, codex exec, codex app-server, etc.).",
23974 }),
23975 status: Schema.Union(
23976 [
23977 Schema.Struct({
23978 type: Schema.Literal("notLoaded").annotate({ title: "NotLoadedThreadStatusType" }),
23979 }).annotate({ title: "NotLoadedThreadStatus" }),
23980 Schema.Struct({
23981 type: Schema.Literal("idle").annotate({ title: "IdleThreadStatusType" }),
23982 }).annotate({ title: "IdleThreadStatus" }),
23983 Schema.Struct({
23984 type: Schema.Literal("systemError").annotate({ title: "SystemErrorThreadStatusType" }),
23985 }).annotate({ title: "SystemErrorThreadStatus" }),
23986 Schema.Struct({
23987 activeFlags: Schema.Array(V2ThreadReadResponse__ThreadActiveFlag),
23988 type: Schema.Literal("active").annotate({ title: "ActiveThreadStatusType" }),
23989 }).annotate({ title: "ActiveThreadStatus" }),
23990 ],
23991 { mode: "oneOf" },
23992 ).annotate({ description: "Current runtime status for the thread." }),
23993 turns: Schema.Array(V2ThreadReadResponse__Turn).annotate({
23994 description:
23995 "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.",
23996 }),
23997 updatedAt: Schema.Number.annotate({
23998 description: "Unix timestamp (in seconds) when the thread was last updated.",
23999 format: "int64",
24000 }).check(Schema.isInt()),
24001});
24002
24003export type V2ThreadResumeResponse__Thread = {
24004 readonly agentNickname?: string | null;
24005 readonly agentRole?: string | null;
24006 readonly cliVersion: string;
24007 readonly createdAt: number;
24008 readonly cwd: string;
24009 readonly ephemeral: boolean;
24010 readonly forkedFromId?: string | null;
24011 readonly gitInfo?: V2ThreadResumeResponse__GitInfo | null;
24012 readonly id: string;
24013 readonly modelProvider: string;
24014 readonly name?: string | null;
24015 readonly path?: string | null;
24016 readonly preview: string;
24017 readonly source:
24018 | "cli"
24019 | "vscode"
24020 | "exec"
24021 | "appServer"
24022 | "unknown"
24023 | { readonly custom: string }
24024 | { readonly subAgent: V2ThreadResumeResponse__SubAgentSource };
24025 readonly status:
24026 | { readonly type: "notLoaded" }
24027 | { readonly type: "idle" }
24028 | { readonly type: "systemError" }
24029 | {
24030 readonly activeFlags: ReadonlyArray<V2ThreadResumeResponse__ThreadActiveFlag>;
24031 readonly type: "active";
24032 };
24033 readonly turns: ReadonlyArray<V2ThreadResumeResponse__Turn>;
24034 readonly updatedAt: number;
24035};
24036export const V2ThreadResumeResponse__Thread = Schema.Struct({
24037 agentNickname: Schema.optionalKey(
24038 Schema.Union([
24039 Schema.String.annotate({
24040 description:
24041 "Optional random unique nickname assigned to an AgentControl-spawned sub-agent.",
24042 }),
24043 Schema.Null,
24044 ]),
24045 ),
24046 agentRole: Schema.optionalKey(
24047 Schema.Union([
24048 Schema.String.annotate({
24049 description: "Optional role (agent_role) assigned to an AgentControl-spawned sub-agent.",
24050 }),
24051 Schema.Null,
24052 ]),
24053 ),
24054 cliVersion: Schema.String.annotate({
24055 description: "Version of the CLI that created the thread.",
24056 }),
24057 createdAt: Schema.Number.annotate({
24058 description: "Unix timestamp (in seconds) when the thread was created.",
24059 format: "int64",
24060 }).check(Schema.isInt()),
24061 cwd: Schema.String.annotate({ description: "Working directory captured for the thread." }),
24062 ephemeral: Schema.Boolean.annotate({
24063 description: "Whether the thread is ephemeral and should not be materialized on disk.",
24064 }),
24065 forkedFromId: Schema.optionalKey(
24066 Schema.Union([
24067 Schema.String.annotate({
24068 description: "Source thread id when this thread was created by forking another thread.",
24069 }),
24070 Schema.Null,
24071 ]),
24072 ),
24073 gitInfo: Schema.optionalKey(
24074 Schema.Union([V2ThreadResumeResponse__GitInfo, Schema.Null]).annotate({
24075 description: "Optional Git metadata captured when the thread was created.",
24076 }),
24077 ),
24078 id: Schema.String,
24079 modelProvider: Schema.String.annotate({
24080 description: "Model provider used for this thread (for example, 'openai').",
24081 }),
24082 name: Schema.optionalKey(
24083 Schema.Union([
24084 Schema.String.annotate({ description: "Optional user-facing thread title." }),
24085 Schema.Null,
24086 ]),
24087 ),
24088 path: Schema.optionalKey(
24089 Schema.Union([
24090 Schema.String.annotate({ description: "[UNSTABLE] Path to the thread on disk." }),
24091 Schema.Null,
24092 ]),
24093 ),
24094 preview: Schema.String.annotate({
24095 description: "Usually the first user message in the thread, if available.",
24096 }),
24097 source: Schema.Union(
24098 [
24099 Schema.Literals(["cli", "vscode", "exec", "appServer", "unknown"]),
24100 Schema.Struct({ custom: Schema.String }).annotate({ title: "CustomSessionSource" }),
24101 Schema.Struct({ subAgent: V2ThreadResumeResponse__SubAgentSource }).annotate({
24102 title: "SubAgentSessionSource",
24103 }),
24104 ],
24105 { mode: "oneOf" },
24106 ).annotate({
24107 description: "Origin of the thread (CLI, VSCode, codex exec, codex app-server, etc.).",
24108 }),
24109 status: Schema.Union(
24110 [
24111 Schema.Struct({
24112 type: Schema.Literal("notLoaded").annotate({ title: "NotLoadedThreadStatusType" }),
24113 }).annotate({ title: "NotLoadedThreadStatus" }),
24114 Schema.Struct({
24115 type: Schema.Literal("idle").annotate({ title: "IdleThreadStatusType" }),
24116 }).annotate({ title: "IdleThreadStatus" }),
24117 Schema.Struct({
24118 type: Schema.Literal("systemError").annotate({ title: "SystemErrorThreadStatusType" }),
24119 }).annotate({ title: "SystemErrorThreadStatus" }),
24120 Schema.Struct({
24121 activeFlags: Schema.Array(V2ThreadResumeResponse__ThreadActiveFlag),
24122 type: Schema.Literal("active").annotate({ title: "ActiveThreadStatusType" }),
24123 }).annotate({ title: "ActiveThreadStatus" }),
24124 ],
24125 { mode: "oneOf" },
24126 ).annotate({ description: "Current runtime status for the thread." }),
24127 turns: Schema.Array(V2ThreadResumeResponse__Turn).annotate({
24128 description:
24129 "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.",
24130 }),
24131 updatedAt: Schema.Number.annotate({
24132 description: "Unix timestamp (in seconds) when the thread was last updated.",
24133 format: "int64",
24134 }).check(Schema.isInt()),
24135});
24136
24137export type V2ThreadStartedNotification__Thread = {
24138 readonly agentNickname?: string | null;
24139 readonly agentRole?: string | null;
24140 readonly cliVersion: string;
24141 readonly createdAt: number;
24142 readonly cwd: string;
24143 readonly ephemeral: boolean;
24144 readonly forkedFromId?: string | null;
24145 readonly gitInfo?: V2ThreadStartedNotification__GitInfo | null;
24146 readonly id: string;
24147 readonly modelProvider: string;
24148 readonly name?: string | null;
24149 readonly path?: string | null;
24150 readonly preview: string;
24151 readonly source:
24152 | "cli"
24153 | "vscode"
24154 | "exec"
24155 | "appServer"
24156 | "unknown"
24157 | { readonly custom: string }
24158 | { readonly subAgent: V2ThreadStartedNotification__SubAgentSource };
24159 readonly status:
24160 | { readonly type: "notLoaded" }
24161 | { readonly type: "idle" }
24162 | { readonly type: "systemError" }
24163 | {
24164 readonly activeFlags: ReadonlyArray<V2ThreadStartedNotification__ThreadActiveFlag>;
24165 readonly type: "active";
24166 };
24167 readonly turns: ReadonlyArray<V2ThreadStartedNotification__Turn>;
24168 readonly updatedAt: number;
24169};
24170export const V2ThreadStartedNotification__Thread = Schema.Struct({
24171 agentNickname: Schema.optionalKey(
24172 Schema.Union([
24173 Schema.String.annotate({
24174 description:
24175 "Optional random unique nickname assigned to an AgentControl-spawned sub-agent.",
24176 }),
24177 Schema.Null,
24178 ]),
24179 ),
24180 agentRole: Schema.optionalKey(
24181 Schema.Union([
24182 Schema.String.annotate({
24183 description: "Optional role (agent_role) assigned to an AgentControl-spawned sub-agent.",
24184 }),
24185 Schema.Null,
24186 ]),
24187 ),
24188 cliVersion: Schema.String.annotate({
24189 description: "Version of the CLI that created the thread.",
24190 }),
24191 createdAt: Schema.Number.annotate({
24192 description: "Unix timestamp (in seconds) when the thread was created.",
24193 format: "int64",
24194 }).check(Schema.isInt()),
24195 cwd: Schema.String.annotate({ description: "Working directory captured for the thread." }),
24196 ephemeral: Schema.Boolean.annotate({
24197 description: "Whether the thread is ephemeral and should not be materialized on disk.",
24198 }),
24199 forkedFromId: Schema.optionalKey(
24200 Schema.Union([
24201 Schema.String.annotate({
24202 description: "Source thread id when this thread was created by forking another thread.",
24203 }),
24204 Schema.Null,
24205 ]),
24206 ),
24207 gitInfo: Schema.optionalKey(
24208 Schema.Union([V2ThreadStartedNotification__GitInfo, Schema.Null]).annotate({
24209 description: "Optional Git metadata captured when the thread was created.",
24210 }),
24211 ),
24212 id: Schema.String,
24213 modelProvider: Schema.String.annotate({
24214 description: "Model provider used for this thread (for example, 'openai').",
24215 }),
24216 name: Schema.optionalKey(
24217 Schema.Union([
24218 Schema.String.annotate({ description: "Optional user-facing thread title." }),
24219 Schema.Null,
24220 ]),
24221 ),
24222 path: Schema.optionalKey(
24223 Schema.Union([
24224 Schema.String.annotate({ description: "[UNSTABLE] Path to the thread on disk." }),
24225 Schema.Null,
24226 ]),
24227 ),
24228 preview: Schema.String.annotate({
24229 description: "Usually the first user message in the thread, if available.",
24230 }),
24231 source: Schema.Union(
24232 [
24233 Schema.Literals(["cli", "vscode", "exec", "appServer", "unknown"]),
24234 Schema.Struct({ custom: Schema.String }).annotate({ title: "CustomSessionSource" }),
24235 Schema.Struct({ subAgent: V2ThreadStartedNotification__SubAgentSource }).annotate({
24236 title: "SubAgentSessionSource",
24237 }),
24238 ],
24239 { mode: "oneOf" },
24240 ).annotate({
24241 description: "Origin of the thread (CLI, VSCode, codex exec, codex app-server, etc.).",
24242 }),
24243 status: Schema.Union(
24244 [
24245 Schema.Struct({
24246 type: Schema.Literal("notLoaded").annotate({ title: "NotLoadedThreadStatusType" }),
24247 }).annotate({ title: "NotLoadedThreadStatus" }),
24248 Schema.Struct({
24249 type: Schema.Literal("idle").annotate({ title: "IdleThreadStatusType" }),
24250 }).annotate({ title: "IdleThreadStatus" }),
24251 Schema.Struct({
24252 type: Schema.Literal("systemError").annotate({ title: "SystemErrorThreadStatusType" }),
24253 }).annotate({ title: "SystemErrorThreadStatus" }),
24254 Schema.Struct({
24255 activeFlags: Schema.Array(V2ThreadStartedNotification__ThreadActiveFlag),
24256 type: Schema.Literal("active").annotate({ title: "ActiveThreadStatusType" }),
24257 }).annotate({ title: "ActiveThreadStatus" }),
24258 ],
24259 { mode: "oneOf" },
24260 ).annotate({ description: "Current runtime status for the thread." }),
24261 turns: Schema.Array(V2ThreadStartedNotification__Turn).annotate({
24262 description:
24263 "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.",
24264 }),
24265 updatedAt: Schema.Number.annotate({
24266 description: "Unix timestamp (in seconds) when the thread was last updated.",
24267 format: "int64",
24268 }).check(Schema.isInt()),
24269});
24270
24271export type V2ThreadStartResponse__Thread = {
24272 readonly agentNickname?: string | null;
24273 readonly agentRole?: string | null;
24274 readonly cliVersion: string;
24275 readonly createdAt: number;
24276 readonly cwd: string;
24277 readonly ephemeral: boolean;
24278 readonly forkedFromId?: string | null;
24279 readonly gitInfo?: V2ThreadStartResponse__GitInfo | null;
24280 readonly id: string;
24281 readonly modelProvider: string;
24282 readonly name?: string | null;
24283 readonly path?: string | null;
24284 readonly preview: string;
24285 readonly source:
24286 | "cli"
24287 | "vscode"
24288 | "exec"
24289 | "appServer"
24290 | "unknown"
24291 | { readonly custom: string }
24292 | { readonly subAgent: V2ThreadStartResponse__SubAgentSource };
24293 readonly status:
24294 | { readonly type: "notLoaded" }
24295 | { readonly type: "idle" }
24296 | { readonly type: "systemError" }
24297 | {
24298 readonly activeFlags: ReadonlyArray<V2ThreadStartResponse__ThreadActiveFlag>;
24299 readonly type: "active";
24300 };
24301 readonly turns: ReadonlyArray<V2ThreadStartResponse__Turn>;
24302 readonly updatedAt: number;
24303};
24304export const V2ThreadStartResponse__Thread = Schema.Struct({
24305 agentNickname: Schema.optionalKey(
24306 Schema.Union([
24307 Schema.String.annotate({
24308 description:
24309 "Optional random unique nickname assigned to an AgentControl-spawned sub-agent.",
24310 }),
24311 Schema.Null,
24312 ]),
24313 ),
24314 agentRole: Schema.optionalKey(
24315 Schema.Union([
24316 Schema.String.annotate({
24317 description: "Optional role (agent_role) assigned to an AgentControl-spawned sub-agent.",
24318 }),
24319 Schema.Null,
24320 ]),
24321 ),
24322 cliVersion: Schema.String.annotate({
24323 description: "Version of the CLI that created the thread.",
24324 }),
24325 createdAt: Schema.Number.annotate({
24326 description: "Unix timestamp (in seconds) when the thread was created.",
24327 format: "int64",
24328 }).check(Schema.isInt()),
24329 cwd: Schema.String.annotate({ description: "Working directory captured for the thread." }),
24330 ephemeral: Schema.Boolean.annotate({
24331 description: "Whether the thread is ephemeral and should not be materialized on disk.",
24332 }),
24333 forkedFromId: Schema.optionalKey(
24334 Schema.Union([
24335 Schema.String.annotate({
24336 description: "Source thread id when this thread was created by forking another thread.",
24337 }),
24338 Schema.Null,
24339 ]),
24340 ),
24341 gitInfo: Schema.optionalKey(
24342 Schema.Union([V2ThreadStartResponse__GitInfo, Schema.Null]).annotate({
24343 description: "Optional Git metadata captured when the thread was created.",
24344 }),
24345 ),
24346 id: Schema.String,
24347 modelProvider: Schema.String.annotate({
24348 description: "Model provider used for this thread (for example, 'openai').",
24349 }),
24350 name: Schema.optionalKey(
24351 Schema.Union([
24352 Schema.String.annotate({ description: "Optional user-facing thread title." }),
24353 Schema.Null,
24354 ]),
24355 ),
24356 path: Schema.optionalKey(
24357 Schema.Union([
24358 Schema.String.annotate({ description: "[UNSTABLE] Path to the thread on disk." }),
24359 Schema.Null,
24360 ]),
24361 ),
24362 preview: Schema.String.annotate({
24363 description: "Usually the first user message in the thread, if available.",
24364 }),
24365 source: Schema.Union(
24366 [
24367 Schema.Literals(["cli", "vscode", "exec", "appServer", "unknown"]),
24368 Schema.Struct({ custom: Schema.String }).annotate({ title: "CustomSessionSource" }),
24369 Schema.Struct({ subAgent: V2ThreadStartResponse__SubAgentSource }).annotate({
24370 title: "SubAgentSessionSource",
24371 }),
24372 ],
24373 { mode: "oneOf" },
24374 ).annotate({
24375 description: "Origin of the thread (CLI, VSCode, codex exec, codex app-server, etc.).",
24376 }),
24377 status: Schema.Union(
24378 [
24379 Schema.Struct({
24380 type: Schema.Literal("notLoaded").annotate({ title: "NotLoadedThreadStatusType" }),
24381 }).annotate({ title: "NotLoadedThreadStatus" }),
24382 Schema.Struct({
24383 type: Schema.Literal("idle").annotate({ title: "IdleThreadStatusType" }),
24384 }).annotate({ title: "IdleThreadStatus" }),
24385 Schema.Struct({
24386 type: Schema.Literal("systemError").annotate({ title: "SystemErrorThreadStatusType" }),
24387 }).annotate({ title: "SystemErrorThreadStatus" }),
24388 Schema.Struct({
24389 activeFlags: Schema.Array(V2ThreadStartResponse__ThreadActiveFlag),
24390 type: Schema.Literal("active").annotate({ title: "ActiveThreadStatusType" }),
24391 }).annotate({ title: "ActiveThreadStatus" }),
24392 ],
24393 { mode: "oneOf" },
24394 ).annotate({ description: "Current runtime status for the thread." }),
24395 turns: Schema.Array(V2ThreadStartResponse__Turn).annotate({
24396 description:
24397 "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.",
24398 }),
24399 updatedAt: Schema.Number.annotate({
24400 description: "Unix timestamp (in seconds) when the thread was last updated.",
24401 format: "int64",
24402 }).check(Schema.isInt()),
24403});
24404
24405export type V2ThreadUnarchiveResponse__Thread = {
24406 readonly agentNickname?: string | null;
24407 readonly agentRole?: string | null;
24408 readonly cliVersion: string;
24409 readonly createdAt: number;
24410 readonly cwd: string;
24411 readonly ephemeral: boolean;
24412 readonly forkedFromId?: string | null;
24413 readonly gitInfo?: V2ThreadUnarchiveResponse__GitInfo | null;
24414 readonly id: string;
24415 readonly modelProvider: string;
24416 readonly name?: string | null;
24417 readonly path?: string | null;
24418 readonly preview: string;
24419 readonly source:
24420 | "cli"
24421 | "vscode"
24422 | "exec"
24423 | "appServer"
24424 | "unknown"
24425 | { readonly custom: string }
24426 | { readonly subAgent: V2ThreadUnarchiveResponse__SubAgentSource };
24427 readonly status:
24428 | { readonly type: "notLoaded" }
24429 | { readonly type: "idle" }
24430 | { readonly type: "systemError" }
24431 | {
24432 readonly activeFlags: ReadonlyArray<V2ThreadUnarchiveResponse__ThreadActiveFlag>;
24433 readonly type: "active";
24434 };
24435 readonly turns: ReadonlyArray<V2ThreadUnarchiveResponse__Turn>;
24436 readonly updatedAt: number;
24437};
24438export const V2ThreadUnarchiveResponse__Thread = Schema.Struct({
24439 agentNickname: Schema.optionalKey(
24440 Schema.Union([
24441 Schema.String.annotate({
24442 description:
24443 "Optional random unique nickname assigned to an AgentControl-spawned sub-agent.",
24444 }),
24445 Schema.Null,
24446 ]),
24447 ),
24448 agentRole: Schema.optionalKey(
24449 Schema.Union([
24450 Schema.String.annotate({
24451 description: "Optional role (agent_role) assigned to an AgentControl-spawned sub-agent.",
24452 }),
24453 Schema.Null,
24454 ]),
24455 ),
24456 cliVersion: Schema.String.annotate({
24457 description: "Version of the CLI that created the thread.",
24458 }),
24459 createdAt: Schema.Number.annotate({
24460 description: "Unix timestamp (in seconds) when the thread was created.",
24461 format: "int64",
24462 }).check(Schema.isInt()),
24463 cwd: Schema.String.annotate({ description: "Working directory captured for the thread." }),
24464 ephemeral: Schema.Boolean.annotate({
24465 description: "Whether the thread is ephemeral and should not be materialized on disk.",
24466 }),
24467 forkedFromId: Schema.optionalKey(
24468 Schema.Union([
24469 Schema.String.annotate({
24470 description: "Source thread id when this thread was created by forking another thread.",
24471 }),
24472 Schema.Null,
24473 ]),
24474 ),
24475 gitInfo: Schema.optionalKey(
24476 Schema.Union([V2ThreadUnarchiveResponse__GitInfo, Schema.Null]).annotate({
24477 description: "Optional Git metadata captured when the thread was created.",
24478 }),
24479 ),
24480 id: Schema.String,
24481 modelProvider: Schema.String.annotate({
24482 description: "Model provider used for this thread (for example, 'openai').",
24483 }),
24484 name: Schema.optionalKey(
24485 Schema.Union([
24486 Schema.String.annotate({ description: "Optional user-facing thread title." }),
24487 Schema.Null,
24488 ]),
24489 ),
24490 path: Schema.optionalKey(
24491 Schema.Union([
24492 Schema.String.annotate({ description: "[UNSTABLE] Path to the thread on disk." }),
24493 Schema.Null,
24494 ]),
24495 ),
24496 preview: Schema.String.annotate({
24497 description: "Usually the first user message in the thread, if available.",
24498 }),
24499 source: Schema.Union(
24500 [
24501 Schema.Literals(["cli", "vscode", "exec", "appServer", "unknown"]),
24502 Schema.Struct({ custom: Schema.String }).annotate({ title: "CustomSessionSource" }),
24503 Schema.Struct({ subAgent: V2ThreadUnarchiveResponse__SubAgentSource }).annotate({
24504 title: "SubAgentSessionSource",
24505 }),
24506 ],
24507 { mode: "oneOf" },
24508 ).annotate({
24509 description: "Origin of the thread (CLI, VSCode, codex exec, codex app-server, etc.).",
24510 }),
24511 status: Schema.Union(
24512 [
24513 Schema.Struct({
24514 type: Schema.Literal("notLoaded").annotate({ title: "NotLoadedThreadStatusType" }),
24515 }).annotate({ title: "NotLoadedThreadStatus" }),
24516 Schema.Struct({
24517 type: Schema.Literal("idle").annotate({ title: "IdleThreadStatusType" }),
24518 }).annotate({ title: "IdleThreadStatus" }),
24519 Schema.Struct({
24520 type: Schema.Literal("systemError").annotate({ title: "SystemErrorThreadStatusType" }),
24521 }).annotate({ title: "SystemErrorThreadStatus" }),
24522 Schema.Struct({
24523 activeFlags: Schema.Array(V2ThreadUnarchiveResponse__ThreadActiveFlag),
24524 type: Schema.Literal("active").annotate({ title: "ActiveThreadStatusType" }),
24525 }).annotate({ title: "ActiveThreadStatus" }),
24526 ],
24527 { mode: "oneOf" },
24528 ).annotate({ description: "Current runtime status for the thread." }),
24529 turns: Schema.Array(V2ThreadUnarchiveResponse__Turn).annotate({
24530 description:
24531 "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.",
24532 }),
24533 updatedAt: Schema.Number.annotate({
24534 description: "Unix timestamp (in seconds) when the thread was last updated.",
24535 format: "int64",
24536 }).check(Schema.isInt()),
24537});
24538
24539export type McpServerElicitationRequestParams__McpElicitationPrimitiveSchema =
24540 | McpServerElicitationRequestParams__McpElicitationEnumSchema
24541 | McpServerElicitationRequestParams__McpElicitationStringSchema
24542 | McpServerElicitationRequestParams__McpElicitationNumberSchema
24543 | McpServerElicitationRequestParams__McpElicitationBooleanSchema;
24544export const McpServerElicitationRequestParams__McpElicitationPrimitiveSchema = Schema.Union([
24545 McpServerElicitationRequestParams__McpElicitationEnumSchema,
24546 McpServerElicitationRequestParams__McpElicitationStringSchema,
24547 McpServerElicitationRequestParams__McpElicitationNumberSchema,
24548 McpServerElicitationRequestParams__McpElicitationBooleanSchema,
24549]);
24550
24551export type ServerNotification__ThreadStartedNotification = {
24552 readonly thread: ServerNotification__Thread;
24553};
24554export const ServerNotification__ThreadStartedNotification = Schema.Struct({
24555 thread: ServerNotification__Thread,
24556});
24557
24558export type ServerRequest__McpElicitationPrimitiveSchema =
24559 | ServerRequest__McpElicitationEnumSchema
24560 | ServerRequest__McpElicitationStringSchema
24561 | ServerRequest__McpElicitationNumberSchema
24562 | ServerRequest__McpElicitationBooleanSchema;
24563export const ServerRequest__McpElicitationPrimitiveSchema = Schema.Union([
24564 ServerRequest__McpElicitationEnumSchema,
24565 ServerRequest__McpElicitationStringSchema,
24566 ServerRequest__McpElicitationNumberSchema,
24567 ServerRequest__McpElicitationBooleanSchema,
24568]);
24569
24570export type McpServerElicitationRequestParams__McpElicitationSchema = {
24571 readonly $schema?: string | null;
24572 readonly properties: {
24573 readonly [x: string]: McpServerElicitationRequestParams__McpElicitationPrimitiveSchema;
24574 };
24575 readonly required?: ReadonlyArray<string> | null;
24576 readonly type: McpServerElicitationRequestParams__McpElicitationObjectType;
24577};
24578export const McpServerElicitationRequestParams__McpElicitationSchema = Schema.Struct({
24579 $schema: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
24580 properties: Schema.Record(
24581 Schema.String,
24582 McpServerElicitationRequestParams__McpElicitationPrimitiveSchema,
24583 ),
24584 required: Schema.optionalKey(Schema.Union([Schema.Array(Schema.String), Schema.Null])),
24585 type: McpServerElicitationRequestParams__McpElicitationObjectType,
24586}).annotate({
24587 description:
24588 "Typed form schema for MCP `elicitation/create` requests.\n\nThis matches the `requestedSchema` shape from the MCP 2025-11-25 `ElicitRequestFormParams` schema.",
24589});
24590
24591export type ServerRequest__McpElicitationSchema = {
24592 readonly $schema?: string | null;
24593 readonly properties: { readonly [x: string]: ServerRequest__McpElicitationPrimitiveSchema };
24594 readonly required?: ReadonlyArray<string> | null;
24595 readonly type: ServerRequest__McpElicitationObjectType;
24596};
24597export const ServerRequest__McpElicitationSchema = Schema.Struct({
24598 $schema: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
24599 properties: Schema.Record(Schema.String, ServerRequest__McpElicitationPrimitiveSchema),
24600 required: Schema.optionalKey(Schema.Union([Schema.Array(Schema.String), Schema.Null])),
24601 type: ServerRequest__McpElicitationObjectType,
24602}).annotate({
24603 description:
24604 "Typed form schema for MCP `elicitation/create` requests.\n\nThis matches the `requestedSchema` shape from the MCP 2025-11-25 `ElicitRequestFormParams` schema.",
24605});
24606
24607export type ServerRequest__McpServerElicitationRequestParams =
24608 | {
24609 readonly _meta?: unknown;
24610 readonly message: string;
24611 readonly mode: "form";
24612 readonly requestedSchema: ServerRequest__McpElicitationSchema;
24613 readonly serverName: string;
24614 readonly threadId: string;
24615 readonly turnId?: string | null;
24616 }
24617 | {
24618 readonly _meta?: unknown;
24619 readonly elicitationId: string;
24620 readonly message: string;
24621 readonly mode: "url";
24622 readonly url: string;
24623 readonly serverName: string;
24624 readonly threadId: string;
24625 readonly turnId?: string | null;
24626 };
24627export const ServerRequest__McpServerElicitationRequestParams = Schema.Union(
24628 [
24629 Schema.Struct({
24630 _meta: Schema.optionalKey(Schema.Unknown),
24631 message: Schema.String,
24632 mode: Schema.Literal("form"),
24633 requestedSchema: ServerRequest__McpElicitationSchema,
24634 serverName: Schema.String,
24635 threadId: Schema.String,
24636 turnId: Schema.optionalKey(
24637 Schema.Union([
24638 Schema.String.annotate({
24639 description:
24640 "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.",
24641 }),
24642 Schema.Null,
24643 ]),
24644 ),
24645 }),
24646 Schema.Struct({
24647 _meta: Schema.optionalKey(Schema.Unknown),
24648 elicitationId: Schema.String,
24649 message: Schema.String,
24650 mode: Schema.Literal("url"),
24651 url: Schema.String,
24652 serverName: Schema.String,
24653 threadId: Schema.String,
24654 turnId: Schema.optionalKey(
24655 Schema.Union([
24656 Schema.String.annotate({
24657 description:
24658 "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.",
24659 }),
24660 Schema.Null,
24661 ]),
24662 ),
24663 }),
24664 ],
24665 { mode: "oneOf" },
24666);
24667
24668export type ApplyPatchApprovalParams = {
24669 readonly callId: string;
24670 readonly conversationId: ApplyPatchApprovalParams__ThreadId;
24671 readonly fileChanges: { readonly [x: string]: ApplyPatchApprovalParams__FileChange };
24672 readonly grantRoot?: string | null;
24673 readonly reason?: string | null;
24674};
24675export const ApplyPatchApprovalParams = Schema.Struct({
24676 callId: Schema.String.annotate({
24677 description:
24678 "Use to correlate this with [codex_protocol::protocol::PatchApplyBeginEvent] and [codex_protocol::protocol::PatchApplyEndEvent].",
24679 }),
24680 conversationId: ApplyPatchApprovalParams__ThreadId,
24681 fileChanges: Schema.Record(Schema.String, ApplyPatchApprovalParams__FileChange),
24682 grantRoot: Schema.optionalKey(
24683 Schema.Union([
24684 Schema.String.annotate({
24685 description:
24686 "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).",
24687 }),
24688 Schema.Null,
24689 ]),
24690 ),
24691 reason: Schema.optionalKey(
24692 Schema.Union([
24693 Schema.String.annotate({
24694 description: "Optional explanatory reason (e.g. request for extra write access).",
24695 }),
24696 Schema.Null,
24697 ]),
24698 ),
24699}).annotate({ title: "ApplyPatchApprovalParams" });
24700
24701export type ApplyPatchApprovalResponse = {
24702 readonly decision: ApplyPatchApprovalResponse__ReviewDecision;
24703};
24704export const ApplyPatchApprovalResponse = Schema.Struct({
24705 decision: ApplyPatchApprovalResponse__ReviewDecision,
24706}).annotate({ title: "ApplyPatchApprovalResponse" });
24707
24708export type ChatgptAuthTokensRefreshParams = {
24709 readonly previousAccountId?: string | null;
24710 readonly reason: ChatgptAuthTokensRefreshParams__ChatgptAuthTokensRefreshReason;
24711};
24712export const ChatgptAuthTokensRefreshParams = Schema.Struct({
24713 previousAccountId: Schema.optionalKey(
24714 Schema.Union([
24715 Schema.String.annotate({
24716 description:
24717 "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`).",
24718 }),
24719 Schema.Null,
24720 ]),
24721 ),
24722 reason: ChatgptAuthTokensRefreshParams__ChatgptAuthTokensRefreshReason,
24723}).annotate({ title: "ChatgptAuthTokensRefreshParams" });
24724
24725export type ChatgptAuthTokensRefreshResponse = {
24726 readonly accessToken: string;
24727 readonly chatgptAccountId: string;
24728 readonly chatgptPlanType?: string | null;
24729};
24730export const ChatgptAuthTokensRefreshResponse = Schema.Struct({
24731 accessToken: Schema.String,
24732 chatgptAccountId: Schema.String,
24733 chatgptPlanType: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
24734}).annotate({ title: "ChatgptAuthTokensRefreshResponse" });
24735
24736export type ClientNotification = { readonly method: "initialized" };
24737export const ClientNotification = Schema.Union(
24738 [
24739 Schema.Struct({
24740 method: Schema.Literal("initialized").annotate({ title: "InitializedNotificationMethod" }),
24741 }).annotate({ title: "InitializedNotification" }),
24742 ],
24743 { mode: "oneOf" },
24744).annotate({ title: "ClientNotification" });
24745
24746export type ClientRequest =
24747 | {
24748 readonly id: ClientRequest__RequestId;
24749 readonly method: "initialize";
24750 readonly params: ClientRequest__InitializeParams;
24751 }
24752 | {
24753 readonly id: ClientRequest__RequestId;
24754 readonly method: "thread/start";
24755 readonly params: ClientRequest__ThreadStartParams;
24756 }
24757 | {
24758 readonly id: ClientRequest__RequestId;
24759 readonly method: "thread/resume";
24760 readonly params: ClientRequest__ThreadResumeParams;
24761 }
24762 | {
24763 readonly id: ClientRequest__RequestId;
24764 readonly method: "thread/fork";
24765 readonly params: ClientRequest__ThreadForkParams;
24766 }
24767 | {
24768 readonly id: ClientRequest__RequestId;
24769 readonly method: "thread/archive";
24770 readonly params: ClientRequest__ThreadArchiveParams;
24771 }
24772 | {
24773 readonly id: ClientRequest__RequestId;
24774 readonly method: "thread/unsubscribe";
24775 readonly params: ClientRequest__ThreadUnsubscribeParams;
24776 }
24777 | {
24778 readonly id: ClientRequest__RequestId;
24779 readonly method: "thread/name/set";
24780 readonly params: ClientRequest__ThreadSetNameParams;
24781 }
24782 | {
24783 readonly id: ClientRequest__RequestId;
24784 readonly method: "thread/metadata/update";
24785 readonly params: ClientRequest__ThreadMetadataUpdateParams;
24786 }
24787 | {
24788 readonly id: ClientRequest__RequestId;
24789 readonly method: "thread/unarchive";
24790 readonly params: ClientRequest__ThreadUnarchiveParams;
24791 }
24792 | {
24793 readonly id: ClientRequest__RequestId;
24794 readonly method: "thread/compact/start";
24795 readonly params: ClientRequest__ThreadCompactStartParams;
24796 }
24797 | {
24798 readonly id: ClientRequest__RequestId;
24799 readonly method: "thread/shellCommand";
24800 readonly params: ClientRequest__ThreadShellCommandParams;
24801 }
24802 | {
24803 readonly id: ClientRequest__RequestId;
24804 readonly method: "thread/rollback";
24805 readonly params: ClientRequest__ThreadRollbackParams;
24806 }
24807 | {
24808 readonly id: ClientRequest__RequestId;
24809 readonly method: "thread/list";
24810 readonly params: ClientRequest__ThreadListParams;
24811 }
24812 | {
24813 readonly id: ClientRequest__RequestId;
24814 readonly method: "thread/loaded/list";
24815 readonly params: ClientRequest__ThreadLoadedListParams;
24816 }
24817 | {
24818 readonly id: ClientRequest__RequestId;
24819 readonly method: "thread/read";
24820 readonly params: ClientRequest__ThreadReadParams;
24821 }
24822 | {
24823 readonly id: ClientRequest__RequestId;
24824 readonly method: "skills/list";
24825 readonly params: ClientRequest__SkillsListParams;
24826 }
24827 | {
24828 readonly id: ClientRequest__RequestId;
24829 readonly method: "plugin/list";
24830 readonly params: ClientRequest__PluginListParams;
24831 }
24832 | {
24833 readonly id: ClientRequest__RequestId;
24834 readonly method: "plugin/read";
24835 readonly params: ClientRequest__PluginReadParams;
24836 }
24837 | {
24838 readonly id: ClientRequest__RequestId;
24839 readonly method: "app/list";
24840 readonly params: ClientRequest__AppsListParams;
24841 }
24842 | {
24843 readonly id: ClientRequest__RequestId;
24844 readonly method: "fs/readFile";
24845 readonly params: ClientRequest__FsReadFileParams;
24846 }
24847 | {
24848 readonly id: ClientRequest__RequestId;
24849 readonly method: "fs/writeFile";
24850 readonly params: ClientRequest__FsWriteFileParams;
24851 }
24852 | {
24853 readonly id: ClientRequest__RequestId;
24854 readonly method: "fs/createDirectory";
24855 readonly params: ClientRequest__FsCreateDirectoryParams;
24856 }
24857 | {
24858 readonly id: ClientRequest__RequestId;
24859 readonly method: "fs/getMetadata";
24860 readonly params: ClientRequest__FsGetMetadataParams;
24861 }
24862 | {
24863 readonly id: ClientRequest__RequestId;
24864 readonly method: "fs/readDirectory";
24865 readonly params: ClientRequest__FsReadDirectoryParams;
24866 }
24867 | {
24868 readonly id: ClientRequest__RequestId;
24869 readonly method: "fs/remove";
24870 readonly params: ClientRequest__FsRemoveParams;
24871 }
24872 | {
24873 readonly id: ClientRequest__RequestId;
24874 readonly method: "fs/copy";
24875 readonly params: ClientRequest__FsCopyParams;
24876 }
24877 | {
24878 readonly id: ClientRequest__RequestId;
24879 readonly method: "fs/watch";
24880 readonly params: ClientRequest__FsWatchParams;
24881 }
24882 | {
24883 readonly id: ClientRequest__RequestId;
24884 readonly method: "fs/unwatch";
24885 readonly params: ClientRequest__FsUnwatchParams;
24886 }
24887 | {
24888 readonly id: ClientRequest__RequestId;
24889 readonly method: "skills/config/write";
24890 readonly params: ClientRequest__SkillsConfigWriteParams;
24891 }
24892 | {
24893 readonly id: ClientRequest__RequestId;
24894 readonly method: "plugin/install";
24895 readonly params: ClientRequest__PluginInstallParams;
24896 }
24897 | {
24898 readonly id: ClientRequest__RequestId;
24899 readonly method: "plugin/uninstall";
24900 readonly params: ClientRequest__PluginUninstallParams;
24901 }
24902 | {
24903 readonly id: ClientRequest__RequestId;
24904 readonly method: "turn/start";
24905 readonly params: ClientRequest__TurnStartParams;
24906 }
24907 | {
24908 readonly id: ClientRequest__RequestId;
24909 readonly method: "turn/steer";
24910 readonly params: ClientRequest__TurnSteerParams;
24911 }
24912 | {
24913 readonly id: ClientRequest__RequestId;
24914 readonly method: "turn/interrupt";
24915 readonly params: ClientRequest__TurnInterruptParams;
24916 }
24917 | {
24918 readonly id: ClientRequest__RequestId;
24919 readonly method: "review/start";
24920 readonly params: ClientRequest__ReviewStartParams;
24921 }
24922 | {
24923 readonly id: ClientRequest__RequestId;
24924 readonly method: "model/list";
24925 readonly params: ClientRequest__ModelListParams;
24926 }
24927 | {
24928 readonly id: ClientRequest__RequestId;
24929 readonly method: "experimentalFeature/list";
24930 readonly params: ClientRequest__ExperimentalFeatureListParams;
24931 }
24932 | {
24933 readonly id: ClientRequest__RequestId;
24934 readonly method: "experimentalFeature/enablement/set";
24935 readonly params: ClientRequest__ExperimentalFeatureEnablementSetParams;
24936 }
24937 | {
24938 readonly id: ClientRequest__RequestId;
24939 readonly method: "mcpServer/oauth/login";
24940 readonly params: ClientRequest__McpServerOauthLoginParams;
24941 }
24942 | {
24943 readonly id: ClientRequest__RequestId;
24944 readonly method: "config/mcpServer/reload";
24945 readonly params?: null;
24946 }
24947 | {
24948 readonly id: ClientRequest__RequestId;
24949 readonly method: "mcpServerStatus/list";
24950 readonly params: ClientRequest__ListMcpServerStatusParams;
24951 }
24952 | {
24953 readonly id: ClientRequest__RequestId;
24954 readonly method: "mcpServer/resource/read";
24955 readonly params: ClientRequest__McpResourceReadParams;
24956 }
24957 | {
24958 readonly id: ClientRequest__RequestId;
24959 readonly method: "mcpServer/tool/call";
24960 readonly params: ClientRequest__McpServerToolCallParams;
24961 }
24962 | {
24963 readonly id: ClientRequest__RequestId;
24964 readonly method: "windowsSandbox/setupStart";
24965 readonly params: ClientRequest__WindowsSandboxSetupStartParams;
24966 }
24967 | {
24968 readonly id: ClientRequest__RequestId;
24969 readonly method: "account/login/start";
24970 readonly params: ClientRequest__LoginAccountParams;
24971 }
24972 | {
24973 readonly id: ClientRequest__RequestId;
24974 readonly method: "account/login/cancel";
24975 readonly params: ClientRequest__CancelLoginAccountParams;
24976 }
24977 | {
24978 readonly id: ClientRequest__RequestId;
24979 readonly method: "account/logout";
24980 readonly params?: null;
24981 }
24982 | {
24983 readonly id: ClientRequest__RequestId;
24984 readonly method: "account/rateLimits/read";
24985 readonly params?: null;
24986 }
24987 | {
24988 readonly id: ClientRequest__RequestId;
24989 readonly method: "feedback/upload";
24990 readonly params: ClientRequest__FeedbackUploadParams;
24991 }
24992 | {
24993 readonly id: ClientRequest__RequestId;
24994 readonly method: "command/exec";
24995 readonly params: ClientRequest__CommandExecParams;
24996 }
24997 | {
24998 readonly id: ClientRequest__RequestId;
24999 readonly method: "command/exec/write";
25000 readonly params: ClientRequest__CommandExecWriteParams;
25001 }
25002 | {
25003 readonly id: ClientRequest__RequestId;
25004 readonly method: "command/exec/terminate";
25005 readonly params: ClientRequest__CommandExecTerminateParams;
25006 }
25007 | {
25008 readonly id: ClientRequest__RequestId;
25009 readonly method: "command/exec/resize";
25010 readonly params: ClientRequest__CommandExecResizeParams;
25011 }
25012 | {
25013 readonly id: ClientRequest__RequestId;
25014 readonly method: "config/read";
25015 readonly params: ClientRequest__ConfigReadParams;
25016 }
25017 | {
25018 readonly id: ClientRequest__RequestId;
25019 readonly method: "externalAgentConfig/detect";
25020 readonly params: ClientRequest__ExternalAgentConfigDetectParams;
25021 }
25022 | {
25023 readonly id: ClientRequest__RequestId;
25024 readonly method: "externalAgentConfig/import";
25025 readonly params: ClientRequest__ExternalAgentConfigImportParams;
25026 }
25027 | {
25028 readonly id: ClientRequest__RequestId;
25029 readonly method: "config/value/write";
25030 readonly params: ClientRequest__ConfigValueWriteParams;
25031 }
25032 | {
25033 readonly id: ClientRequest__RequestId;
25034 readonly method: "config/batchWrite";
25035 readonly params: ClientRequest__ConfigBatchWriteParams;
25036 }
25037 | {
25038 readonly id: ClientRequest__RequestId;
25039 readonly method: "configRequirements/read";
25040 readonly params?: null;
25041 }
25042 | {
25043 readonly id: ClientRequest__RequestId;
25044 readonly method: "account/read";
25045 readonly params: ClientRequest__GetAccountParams;
25046 }
25047 | {
25048 readonly id: ClientRequest__RequestId;
25049 readonly method: "fuzzyFileSearch";
25050 readonly params: ClientRequest__FuzzyFileSearchParams;
25051 };
25052export const ClientRequest = Schema.Union(
25053 [
25054 Schema.Struct({
25055 id: ClientRequest__RequestId,
25056 method: Schema.Literal("initialize").annotate({ title: "InitializeRequestMethod" }),
25057 params: ClientRequest__InitializeParams,
25058 }).annotate({ title: "InitializeRequest" }),
25059 Schema.Struct({
25060 id: ClientRequest__RequestId,
25061 method: Schema.Literal("thread/start").annotate({ title: "Thread/startRequestMethod" }),
25062 params: ClientRequest__ThreadStartParams,
25063 }).annotate({ title: "Thread/startRequest", description: "NEW APIs" }),
25064 Schema.Struct({
25065 id: ClientRequest__RequestId,
25066 method: Schema.Literal("thread/resume").annotate({ title: "Thread/resumeRequestMethod" }),
25067 params: ClientRequest__ThreadResumeParams,
25068 }).annotate({ title: "Thread/resumeRequest" }),
25069 Schema.Struct({
25070 id: ClientRequest__RequestId,
25071 method: Schema.Literal("thread/fork").annotate({ title: "Thread/forkRequestMethod" }),
25072 params: ClientRequest__ThreadForkParams,
25073 }).annotate({ title: "Thread/forkRequest" }),
25074 Schema.Struct({
25075 id: ClientRequest__RequestId,
25076 method: Schema.Literal("thread/archive").annotate({ title: "Thread/archiveRequestMethod" }),
25077 params: ClientRequest__ThreadArchiveParams,
25078 }).annotate({ title: "Thread/archiveRequest" }),
25079 Schema.Struct({
25080 id: ClientRequest__RequestId,
25081 method: Schema.Literal("thread/unsubscribe").annotate({
25082 title: "Thread/unsubscribeRequestMethod",
25083 }),
25084 params: ClientRequest__ThreadUnsubscribeParams,
25085 }).annotate({ title: "Thread/unsubscribeRequest" }),
25086 Schema.Struct({
25087 id: ClientRequest__RequestId,
25088 method: Schema.Literal("thread/name/set").annotate({ title: "Thread/name/setRequestMethod" }),
25089 params: ClientRequest__ThreadSetNameParams,
25090 }).annotate({ title: "Thread/name/setRequest" }),
25091 Schema.Struct({
25092 id: ClientRequest__RequestId,
25093 method: Schema.Literal("thread/metadata/update").annotate({
25094 title: "Thread/metadata/updateRequestMethod",
25095 }),
25096 params: ClientRequest__ThreadMetadataUpdateParams,
25097 }).annotate({ title: "Thread/metadata/updateRequest" }),
25098 Schema.Struct({
25099 id: ClientRequest__RequestId,
25100 method: Schema.Literal("thread/unarchive").annotate({
25101 title: "Thread/unarchiveRequestMethod",
25102 }),
25103 params: ClientRequest__ThreadUnarchiveParams,
25104 }).annotate({ title: "Thread/unarchiveRequest" }),
25105 Schema.Struct({
25106 id: ClientRequest__RequestId,
25107 method: Schema.Literal("thread/compact/start").annotate({
25108 title: "Thread/compact/startRequestMethod",
25109 }),
25110 params: ClientRequest__ThreadCompactStartParams,
25111 }).annotate({ title: "Thread/compact/startRequest" }),
25112 Schema.Struct({
25113 id: ClientRequest__RequestId,
25114 method: Schema.Literal("thread/shellCommand").annotate({
25115 title: "Thread/shellCommandRequestMethod",
25116 }),
25117 params: ClientRequest__ThreadShellCommandParams,
25118 }).annotate({ title: "Thread/shellCommandRequest" }),
25119 Schema.Struct({
25120 id: ClientRequest__RequestId,
25121 method: Schema.Literal("thread/rollback").annotate({ title: "Thread/rollbackRequestMethod" }),
25122 params: ClientRequest__ThreadRollbackParams,
25123 }).annotate({ title: "Thread/rollbackRequest" }),
25124 Schema.Struct({
25125 id: ClientRequest__RequestId,
25126 method: Schema.Literal("thread/list").annotate({ title: "Thread/listRequestMethod" }),
25127 params: ClientRequest__ThreadListParams,
25128 }).annotate({ title: "Thread/listRequest" }),
25129 Schema.Struct({
25130 id: ClientRequest__RequestId,
25131 method: Schema.Literal("thread/loaded/list").annotate({
25132 title: "Thread/loaded/listRequestMethod",
25133 }),
25134 params: ClientRequest__ThreadLoadedListParams,
25135 }).annotate({ title: "Thread/loaded/listRequest" }),
25136 Schema.Struct({
25137 id: ClientRequest__RequestId,
25138 method: Schema.Literal("thread/read").annotate({ title: "Thread/readRequestMethod" }),
25139 params: ClientRequest__ThreadReadParams,
25140 }).annotate({ title: "Thread/readRequest" }),
25141 Schema.Struct({
25142 id: ClientRequest__RequestId,
25143 method: Schema.Literal("skills/list").annotate({ title: "Skills/listRequestMethod" }),
25144 params: ClientRequest__SkillsListParams,
25145 }).annotate({ title: "Skills/listRequest" }),
25146 Schema.Struct({
25147 id: ClientRequest__RequestId,
25148 method: Schema.Literal("plugin/list").annotate({ title: "Plugin/listRequestMethod" }),
25149 params: ClientRequest__PluginListParams,
25150 }).annotate({ title: "Plugin/listRequest" }),
25151 Schema.Struct({
25152 id: ClientRequest__RequestId,
25153 method: Schema.Literal("plugin/read").annotate({ title: "Plugin/readRequestMethod" }),
25154 params: ClientRequest__PluginReadParams,
25155 }).annotate({ title: "Plugin/readRequest" }),
25156 Schema.Struct({
25157 id: ClientRequest__RequestId,
25158 method: Schema.Literal("app/list").annotate({ title: "App/listRequestMethod" }),
25159 params: ClientRequest__AppsListParams,
25160 }).annotate({ title: "App/listRequest" }),
25161 Schema.Struct({
25162 id: ClientRequest__RequestId,
25163 method: Schema.Literal("fs/readFile").annotate({ title: "Fs/readFileRequestMethod" }),
25164 params: ClientRequest__FsReadFileParams,
25165 }).annotate({ title: "Fs/readFileRequest" }),
25166 Schema.Struct({
25167 id: ClientRequest__RequestId,
25168 method: Schema.Literal("fs/writeFile").annotate({ title: "Fs/writeFileRequestMethod" }),
25169 params: ClientRequest__FsWriteFileParams,
25170 }).annotate({ title: "Fs/writeFileRequest" }),
25171 Schema.Struct({
25172 id: ClientRequest__RequestId,
25173 method: Schema.Literal("fs/createDirectory").annotate({
25174 title: "Fs/createDirectoryRequestMethod",
25175 }),
25176 params: ClientRequest__FsCreateDirectoryParams,
25177 }).annotate({ title: "Fs/createDirectoryRequest" }),
25178 Schema.Struct({
25179 id: ClientRequest__RequestId,
25180 method: Schema.Literal("fs/getMetadata").annotate({ title: "Fs/getMetadataRequestMethod" }),
25181 params: ClientRequest__FsGetMetadataParams,
25182 }).annotate({ title: "Fs/getMetadataRequest" }),
25183 Schema.Struct({
25184 id: ClientRequest__RequestId,
25185 method: Schema.Literal("fs/readDirectory").annotate({
25186 title: "Fs/readDirectoryRequestMethod",
25187 }),
25188 params: ClientRequest__FsReadDirectoryParams,
25189 }).annotate({ title: "Fs/readDirectoryRequest" }),
25190 Schema.Struct({
25191 id: ClientRequest__RequestId,
25192 method: Schema.Literal("fs/remove").annotate({ title: "Fs/removeRequestMethod" }),
25193 params: ClientRequest__FsRemoveParams,
25194 }).annotate({ title: "Fs/removeRequest" }),
25195 Schema.Struct({
25196 id: ClientRequest__RequestId,
25197 method: Schema.Literal("fs/copy").annotate({ title: "Fs/copyRequestMethod" }),
25198 params: ClientRequest__FsCopyParams,
25199 }).annotate({ title: "Fs/copyRequest" }),
25200 Schema.Struct({
25201 id: ClientRequest__RequestId,
25202 method: Schema.Literal("fs/watch").annotate({ title: "Fs/watchRequestMethod" }),
25203 params: ClientRequest__FsWatchParams,
25204 }).annotate({ title: "Fs/watchRequest" }),
25205 Schema.Struct({
25206 id: ClientRequest__RequestId,
25207 method: Schema.Literal("fs/unwatch").annotate({ title: "Fs/unwatchRequestMethod" }),
25208 params: ClientRequest__FsUnwatchParams,
25209 }).annotate({ title: "Fs/unwatchRequest" }),
25210 Schema.Struct({
25211 id: ClientRequest__RequestId,
25212 method: Schema.Literal("skills/config/write").annotate({
25213 title: "Skills/config/writeRequestMethod",
25214 }),
25215 params: ClientRequest__SkillsConfigWriteParams,
25216 }).annotate({ title: "Skills/config/writeRequest" }),
25217 Schema.Struct({
25218 id: ClientRequest__RequestId,
25219 method: Schema.Literal("plugin/install").annotate({ title: "Plugin/installRequestMethod" }),
25220 params: ClientRequest__PluginInstallParams,
25221 }).annotate({ title: "Plugin/installRequest" }),
25222 Schema.Struct({
25223 id: ClientRequest__RequestId,
25224 method: Schema.Literal("plugin/uninstall").annotate({
25225 title: "Plugin/uninstallRequestMethod",
25226 }),
25227 params: ClientRequest__PluginUninstallParams,
25228 }).annotate({ title: "Plugin/uninstallRequest" }),
25229 Schema.Struct({
25230 id: ClientRequest__RequestId,
25231 method: Schema.Literal("turn/start").annotate({ title: "Turn/startRequestMethod" }),
25232 params: ClientRequest__TurnStartParams,
25233 }).annotate({ title: "Turn/startRequest" }),
25234 Schema.Struct({
25235 id: ClientRequest__RequestId,
25236 method: Schema.Literal("turn/steer").annotate({ title: "Turn/steerRequestMethod" }),
25237 params: ClientRequest__TurnSteerParams,
25238 }).annotate({ title: "Turn/steerRequest" }),
25239 Schema.Struct({
25240 id: ClientRequest__RequestId,
25241 method: Schema.Literal("turn/interrupt").annotate({ title: "Turn/interruptRequestMethod" }),
25242 params: ClientRequest__TurnInterruptParams,
25243 }).annotate({ title: "Turn/interruptRequest" }),
25244 Schema.Struct({
25245 id: ClientRequest__RequestId,
25246 method: Schema.Literal("review/start").annotate({ title: "Review/startRequestMethod" }),
25247 params: ClientRequest__ReviewStartParams,
25248 }).annotate({ title: "Review/startRequest" }),
25249 Schema.Struct({
25250 id: ClientRequest__RequestId,
25251 method: Schema.Literal("model/list").annotate({ title: "Model/listRequestMethod" }),
25252 params: ClientRequest__ModelListParams,
25253 }).annotate({ title: "Model/listRequest" }),
25254 Schema.Struct({
25255 id: ClientRequest__RequestId,
25256 method: Schema.Literal("experimentalFeature/list").annotate({
25257 title: "ExperimentalFeature/listRequestMethod",
25258 }),
25259 params: ClientRequest__ExperimentalFeatureListParams,
25260 }).annotate({ title: "ExperimentalFeature/listRequest" }),
25261 Schema.Struct({
25262 id: ClientRequest__RequestId,
25263 method: Schema.Literal("experimentalFeature/enablement/set").annotate({
25264 title: "ExperimentalFeature/enablement/setRequestMethod",
25265 }),
25266 params: ClientRequest__ExperimentalFeatureEnablementSetParams,
25267 }).annotate({ title: "ExperimentalFeature/enablement/setRequest" }),
25268 Schema.Struct({
25269 id: ClientRequest__RequestId,
25270 method: Schema.Literal("mcpServer/oauth/login").annotate({
25271 title: "McpServer/oauth/loginRequestMethod",
25272 }),
25273 params: ClientRequest__McpServerOauthLoginParams,
25274 }).annotate({ title: "McpServer/oauth/loginRequest" }),
25275 Schema.Struct({
25276 id: ClientRequest__RequestId,
25277 method: Schema.Literal("config/mcpServer/reload").annotate({
25278 title: "Config/mcpServer/reloadRequestMethod",
25279 }),
25280 params: Schema.optionalKey(Schema.Null),
25281 }).annotate({ title: "Config/mcpServer/reloadRequest" }),
25282 Schema.Struct({
25283 id: ClientRequest__RequestId,
25284 method: Schema.Literal("mcpServerStatus/list").annotate({
25285 title: "McpServerStatus/listRequestMethod",
25286 }),
25287 params: ClientRequest__ListMcpServerStatusParams,
25288 }).annotate({ title: "McpServerStatus/listRequest" }),
25289 Schema.Struct({
25290 id: ClientRequest__RequestId,
25291 method: Schema.Literal("mcpServer/resource/read").annotate({
25292 title: "McpServer/resource/readRequestMethod",
25293 }),
25294 params: ClientRequest__McpResourceReadParams,
25295 }).annotate({ title: "McpServer/resource/readRequest" }),
25296 Schema.Struct({
25297 id: ClientRequest__RequestId,
25298 method: Schema.Literal("mcpServer/tool/call").annotate({
25299 title: "McpServer/tool/callRequestMethod",
25300 }),
25301 params: ClientRequest__McpServerToolCallParams,
25302 }).annotate({ title: "McpServer/tool/callRequest" }),
25303 Schema.Struct({
25304 id: ClientRequest__RequestId,
25305 method: Schema.Literal("windowsSandbox/setupStart").annotate({
25306 title: "WindowsSandbox/setupStartRequestMethod",
25307 }),
25308 params: ClientRequest__WindowsSandboxSetupStartParams,
25309 }).annotate({ title: "WindowsSandbox/setupStartRequest" }),
25310 Schema.Struct({
25311 id: ClientRequest__RequestId,
25312 method: Schema.Literal("account/login/start").annotate({
25313 title: "Account/login/startRequestMethod",
25314 }),
25315 params: ClientRequest__LoginAccountParams,
25316 }).annotate({ title: "Account/login/startRequest" }),
25317 Schema.Struct({
25318 id: ClientRequest__RequestId,
25319 method: Schema.Literal("account/login/cancel").annotate({
25320 title: "Account/login/cancelRequestMethod",
25321 }),
25322 params: ClientRequest__CancelLoginAccountParams,
25323 }).annotate({ title: "Account/login/cancelRequest" }),
25324 Schema.Struct({
25325 id: ClientRequest__RequestId,
25326 method: Schema.Literal("account/logout").annotate({ title: "Account/logoutRequestMethod" }),
25327 params: Schema.optionalKey(Schema.Null),
25328 }).annotate({ title: "Account/logoutRequest" }),
25329 Schema.Struct({
25330 id: ClientRequest__RequestId,
25331 method: Schema.Literal("account/rateLimits/read").annotate({
25332 title: "Account/rateLimits/readRequestMethod",
25333 }),
25334 params: Schema.optionalKey(Schema.Null),
25335 }).annotate({ title: "Account/rateLimits/readRequest" }),
25336 Schema.Struct({
25337 id: ClientRequest__RequestId,
25338 method: Schema.Literal("feedback/upload").annotate({ title: "Feedback/uploadRequestMethod" }),
25339 params: ClientRequest__FeedbackUploadParams,
25340 }).annotate({ title: "Feedback/uploadRequest" }),
25341 Schema.Struct({
25342 id: ClientRequest__RequestId,
25343 method: Schema.Literal("command/exec").annotate({ title: "Command/execRequestMethod" }),
25344 params: ClientRequest__CommandExecParams,
25345 }).annotate({
25346 title: "Command/execRequest",
25347 description: "Execute a standalone command (argv vector) under the server's sandbox.",
25348 }),
25349 Schema.Struct({
25350 id: ClientRequest__RequestId,
25351 method: Schema.Literal("command/exec/write").annotate({
25352 title: "Command/exec/writeRequestMethod",
25353 }),
25354 params: ClientRequest__CommandExecWriteParams,
25355 }).annotate({
25356 title: "Command/exec/writeRequest",
25357 description: "Write stdin bytes to a running `command/exec` session or close stdin.",
25358 }),
25359 Schema.Struct({
25360 id: ClientRequest__RequestId,
25361 method: Schema.Literal("command/exec/terminate").annotate({
25362 title: "Command/exec/terminateRequestMethod",
25363 }),
25364 params: ClientRequest__CommandExecTerminateParams,
25365 }).annotate({
25366 title: "Command/exec/terminateRequest",
25367 description: "Terminate a running `command/exec` session by client-supplied `processId`.",
25368 }),
25369 Schema.Struct({
25370 id: ClientRequest__RequestId,
25371 method: Schema.Literal("command/exec/resize").annotate({
25372 title: "Command/exec/resizeRequestMethod",
25373 }),
25374 params: ClientRequest__CommandExecResizeParams,
25375 }).annotate({
25376 title: "Command/exec/resizeRequest",
25377 description:
25378 "Resize a running PTY-backed `command/exec` session by client-supplied `processId`.",
25379 }),
25380 Schema.Struct({
25381 id: ClientRequest__RequestId,
25382 method: Schema.Literal("config/read").annotate({ title: "Config/readRequestMethod" }),
25383 params: ClientRequest__ConfigReadParams,
25384 }).annotate({ title: "Config/readRequest" }),
25385 Schema.Struct({
25386 id: ClientRequest__RequestId,
25387 method: Schema.Literal("externalAgentConfig/detect").annotate({
25388 title: "ExternalAgentConfig/detectRequestMethod",
25389 }),
25390 params: ClientRequest__ExternalAgentConfigDetectParams,
25391 }).annotate({ title: "ExternalAgentConfig/detectRequest" }),
25392 Schema.Struct({
25393 id: ClientRequest__RequestId,
25394 method: Schema.Literal("externalAgentConfig/import").annotate({
25395 title: "ExternalAgentConfig/importRequestMethod",
25396 }),
25397 params: ClientRequest__ExternalAgentConfigImportParams,
25398 }).annotate({ title: "ExternalAgentConfig/importRequest" }),
25399 Schema.Struct({
25400 id: ClientRequest__RequestId,
25401 method: Schema.Literal("config/value/write").annotate({
25402 title: "Config/value/writeRequestMethod",
25403 }),
25404 params: ClientRequest__ConfigValueWriteParams,
25405 }).annotate({ title: "Config/value/writeRequest" }),
25406 Schema.Struct({
25407 id: ClientRequest__RequestId,
25408 method: Schema.Literal("config/batchWrite").annotate({
25409 title: "Config/batchWriteRequestMethod",
25410 }),
25411 params: ClientRequest__ConfigBatchWriteParams,
25412 }).annotate({ title: "Config/batchWriteRequest" }),
25413 Schema.Struct({
25414 id: ClientRequest__RequestId,
25415 method: Schema.Literal("configRequirements/read").annotate({
25416 title: "ConfigRequirements/readRequestMethod",
25417 }),
25418 params: Schema.optionalKey(Schema.Null),
25419 }).annotate({ title: "ConfigRequirements/readRequest" }),
25420 Schema.Struct({
25421 id: ClientRequest__RequestId,
25422 method: Schema.Literal("account/read").annotate({ title: "Account/readRequestMethod" }),
25423 params: ClientRequest__GetAccountParams,
25424 }).annotate({ title: "Account/readRequest" }),
25425 Schema.Struct({
25426 id: ClientRequest__RequestId,
25427 method: Schema.Literal("fuzzyFileSearch").annotate({ title: "FuzzyFileSearchRequestMethod" }),
25428 params: ClientRequest__FuzzyFileSearchParams,
25429 }).annotate({ title: "FuzzyFileSearchRequest" }),
25430 ],
25431 { mode: "oneOf" },
25432).annotate({ title: "ClientRequest", description: "Request from the client to the server." });
25433
25434export type ClientRequest__ByteRange = { readonly end: number; readonly start: number };
25435export const ClientRequest__ByteRange = Schema.Struct({
25436 end: Schema.Number.annotate({ format: "uint" })
25437 .check(Schema.isInt())
25438 .check(Schema.isGreaterThanOrEqualTo(0)),
25439 start: Schema.Number.annotate({ format: "uint" })
25440 .check(Schema.isInt())
25441 .check(Schema.isGreaterThanOrEqualTo(0)),
25442});
25443
25444export type ClientRequest__CollaborationMode = {
25445 readonly mode: ClientRequest__ModeKind;
25446 readonly settings: ClientRequest__Settings;
25447};
25448export const ClientRequest__CollaborationMode = Schema.Struct({
25449 mode: ClientRequest__ModeKind,
25450 settings: ClientRequest__Settings,
25451}).annotate({ description: "Collaboration mode for a Codex session." });
25452
25453export type ClientRequest__DynamicToolSpec = {
25454 readonly deferLoading?: boolean;
25455 readonly description: string;
25456 readonly inputSchema: unknown;
25457 readonly name: string;
25458};
25459export const ClientRequest__DynamicToolSpec = Schema.Struct({
25460 deferLoading: Schema.optionalKey(Schema.Boolean),
25461 description: Schema.String,
25462 inputSchema: Schema.Unknown,
25463 name: Schema.String,
25464});
25465
25466export type ClientRequest__NetworkAccess = "restricted" | "enabled";
25467export const ClientRequest__NetworkAccess = Schema.Literals(["restricted", "enabled"]);
25468
25469export type ClientRequest__ReadOnlyAccess =
25470 | {
25471 readonly includePlatformDefaults?: boolean;
25472 readonly readableRoots?: ReadonlyArray<ClientRequest__AbsolutePathBuf>;
25473 readonly type: "restricted";
25474 }
25475 | { readonly type: "fullAccess" };
25476export const ClientRequest__ReadOnlyAccess = Schema.Union(
25477 [
25478 Schema.Struct({
25479 includePlatformDefaults: Schema.optionalKey(Schema.Boolean.annotate({ default: true })),
25480 readableRoots: Schema.optionalKey(
25481 Schema.Array(ClientRequest__AbsolutePathBuf).annotate({ default: [] }),
25482 ),
25483 type: Schema.Literal("restricted").annotate({ title: "RestrictedReadOnlyAccessType" }),
25484 }).annotate({ title: "RestrictedReadOnlyAccess" }),
25485 Schema.Struct({
25486 type: Schema.Literal("fullAccess").annotate({ title: "FullAccessReadOnlyAccessType" }),
25487 }).annotate({ title: "FullAccessReadOnlyAccess" }),
25488 ],
25489 { mode: "oneOf" },
25490);
25491
25492export type ClientRequest__RealtimeVoice =
25493 | "alloy"
25494 | "arbor"
25495 | "ash"
25496 | "ballad"
25497 | "breeze"
25498 | "cedar"
25499 | "coral"
25500 | "cove"
25501 | "echo"
25502 | "ember"
25503 | "juniper"
25504 | "maple"
25505 | "marin"
25506 | "sage"
25507 | "shimmer"
25508 | "sol"
25509 | "spruce"
25510 | "vale"
25511 | "verse";
25512export const ClientRequest__RealtimeVoice = Schema.Literals([
25513 "alloy",
25514 "arbor",
25515 "ash",
25516 "ballad",
25517 "breeze",
25518 "cedar",
25519 "coral",
25520 "cove",
25521 "echo",
25522 "ember",
25523 "juniper",
25524 "maple",
25525 "marin",
25526 "sage",
25527 "shimmer",
25528 "sol",
25529 "spruce",
25530 "vale",
25531 "verse",
25532]);
25533
25534export type ClientRequest__ResponseItem =
25535 | {
25536 readonly content: ReadonlyArray<ClientRequest__ContentItem>;
25537 readonly end_turn?: boolean | null;
25538 readonly id?: string | null;
25539 readonly phase?: ClientRequest__MessagePhase | null;
25540 readonly role: string;
25541 readonly type: "message";
25542 }
25543 | {
25544 readonly content?: ReadonlyArray<ClientRequest__ReasoningItemContent> | null;
25545 readonly encrypted_content?: string | null;
25546 readonly summary: ReadonlyArray<ClientRequest__ReasoningItemReasoningSummary>;
25547 readonly type: "reasoning";
25548 }
25549 | {
25550 readonly action: ClientRequest__LocalShellAction;
25551 readonly call_id?: string | null;
25552 readonly id?: string | null;
25553 readonly status: ClientRequest__LocalShellStatus;
25554 readonly type: "local_shell_call";
25555 }
25556 | {
25557 readonly arguments: string;
25558 readonly call_id: string;
25559 readonly id?: string | null;
25560 readonly name: string;
25561 readonly namespace?: string | null;
25562 readonly type: "function_call";
25563 }
25564 | {
25565 readonly arguments: unknown;
25566 readonly call_id?: string | null;
25567 readonly execution: string;
25568 readonly id?: string | null;
25569 readonly status?: string | null;
25570 readonly type: "tool_search_call";
25571 }
25572 | {
25573 readonly call_id: string;
25574 readonly output: ClientRequest__FunctionCallOutputBody;
25575 readonly type: "function_call_output";
25576 }
25577 | {
25578 readonly call_id: string;
25579 readonly id?: string | null;
25580 readonly input: string;
25581 readonly name: string;
25582 readonly status?: string | null;
25583 readonly type: "custom_tool_call";
25584 }
25585 | {
25586 readonly call_id: string;
25587 readonly name?: string | null;
25588 readonly output: ClientRequest__FunctionCallOutputBody;
25589 readonly type: "custom_tool_call_output";
25590 }
25591 | {
25592 readonly call_id?: string | null;
25593 readonly execution: string;
25594 readonly status: string;
25595 readonly tools: ReadonlyArray<unknown>;
25596 readonly type: "tool_search_output";
25597 }
25598 | {
25599 readonly action?: ClientRequest__ResponsesApiWebSearchAction | null;
25600 readonly id?: string | null;
25601 readonly status?: string | null;
25602 readonly type: "web_search_call";
25603 }
25604 | {
25605 readonly id: string;
25606 readonly result: string;
25607 readonly revised_prompt?: string | null;
25608 readonly status: string;
25609 readonly type: "image_generation_call";
25610 }
25611 | { readonly ghost_commit: ClientRequest__GhostCommit; readonly type: "ghost_snapshot" }
25612 | { readonly encrypted_content: string; readonly type: "compaction" }
25613 | { readonly type: "other" };
25614export const ClientRequest__ResponseItem = Schema.Union(
25615 [
25616 Schema.Struct({
25617 content: Schema.Array(ClientRequest__ContentItem),
25618 end_turn: Schema.optionalKey(Schema.Union([Schema.Boolean, Schema.Null])),
25619 id: Schema.optionalKey(
25620 Schema.Union([Schema.String.annotate({ writeOnly: true }), Schema.Null]),
25621 ),
25622 phase: Schema.optionalKey(Schema.Union([ClientRequest__MessagePhase, Schema.Null])),
25623 role: Schema.String,
25624 type: Schema.Literal("message").annotate({ title: "MessageResponseItemType" }),
25625 }).annotate({ title: "MessageResponseItem" }),
25626 Schema.Struct({
25627 content: Schema.optionalKey(
25628 Schema.Union([Schema.Array(ClientRequest__ReasoningItemContent), Schema.Null]),
25629 ),
25630 encrypted_content: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
25631 summary: Schema.Array(ClientRequest__ReasoningItemReasoningSummary),
25632 type: Schema.Literal("reasoning").annotate({ title: "ReasoningResponseItemType" }),
25633 }).annotate({ title: "ReasoningResponseItem" }),
25634 Schema.Struct({
25635 action: ClientRequest__LocalShellAction,
25636 call_id: Schema.optionalKey(
25637 Schema.Union([
25638 Schema.String.annotate({ description: "Set when using the Responses API." }),
25639 Schema.Null,
25640 ]),
25641 ),
25642 id: Schema.optionalKey(
25643 Schema.Union([
25644 Schema.String.annotate({
25645 description: "Legacy id field retained for compatibility with older payloads.",
25646 writeOnly: true,
25647 }),
25648 Schema.Null,
25649 ]),
25650 ),
25651 status: ClientRequest__LocalShellStatus,
25652 type: Schema.Literal("local_shell_call").annotate({
25653 title: "LocalShellCallResponseItemType",
25654 }),
25655 }).annotate({ title: "LocalShellCallResponseItem" }),
25656 Schema.Struct({
25657 arguments: Schema.String,
25658 call_id: Schema.String,
25659 id: Schema.optionalKey(
25660 Schema.Union([Schema.String.annotate({ writeOnly: true }), Schema.Null]),
25661 ),
25662 name: Schema.String,
25663 namespace: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
25664 type: Schema.Literal("function_call").annotate({ title: "FunctionCallResponseItemType" }),
25665 }).annotate({ title: "FunctionCallResponseItem" }),
25666 Schema.Struct({
25667 arguments: Schema.Unknown,
25668 call_id: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
25669 execution: Schema.String,
25670 id: Schema.optionalKey(
25671 Schema.Union([Schema.String.annotate({ writeOnly: true }), Schema.Null]),
25672 ),
25673 status: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
25674 type: Schema.Literal("tool_search_call").annotate({
25675 title: "ToolSearchCallResponseItemType",
25676 }),
25677 }).annotate({ title: "ToolSearchCallResponseItem" }),
25678 Schema.Struct({
25679 call_id: Schema.String,
25680 output: ClientRequest__FunctionCallOutputBody,
25681 type: Schema.Literal("function_call_output").annotate({
25682 title: "FunctionCallOutputResponseItemType",
25683 }),
25684 }).annotate({ title: "FunctionCallOutputResponseItem" }),
25685 Schema.Struct({
25686 call_id: Schema.String,
25687 id: Schema.optionalKey(
25688 Schema.Union([Schema.String.annotate({ writeOnly: true }), Schema.Null]),
25689 ),
25690 input: Schema.String,
25691 name: Schema.String,
25692 status: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
25693 type: Schema.Literal("custom_tool_call").annotate({
25694 title: "CustomToolCallResponseItemType",
25695 }),
25696 }).annotate({ title: "CustomToolCallResponseItem" }),
25697 Schema.Struct({
25698 call_id: Schema.String,
25699 name: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
25700 output: ClientRequest__FunctionCallOutputBody,
25701 type: Schema.Literal("custom_tool_call_output").annotate({
25702 title: "CustomToolCallOutputResponseItemType",
25703 }),
25704 }).annotate({ title: "CustomToolCallOutputResponseItem" }),
25705 Schema.Struct({
25706 call_id: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
25707 execution: Schema.String,
25708 status: Schema.String,
25709 tools: Schema.Array(Schema.Unknown),
25710 type: Schema.Literal("tool_search_output").annotate({
25711 title: "ToolSearchOutputResponseItemType",
25712 }),
25713 }).annotate({ title: "ToolSearchOutputResponseItem" }),
25714 Schema.Struct({
25715 action: Schema.optionalKey(
25716 Schema.Union([ClientRequest__ResponsesApiWebSearchAction, Schema.Null]),
25717 ),
25718 id: Schema.optionalKey(
25719 Schema.Union([Schema.String.annotate({ writeOnly: true }), Schema.Null]),
25720 ),
25721 status: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
25722 type: Schema.Literal("web_search_call").annotate({ title: "WebSearchCallResponseItemType" }),
25723 }).annotate({ title: "WebSearchCallResponseItem" }),
25724 Schema.Struct({
25725 id: Schema.String,
25726 result: Schema.String,
25727 revised_prompt: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
25728 status: Schema.String,
25729 type: Schema.Literal("image_generation_call").annotate({
25730 title: "ImageGenerationCallResponseItemType",
25731 }),
25732 }).annotate({ title: "ImageGenerationCallResponseItem" }),
25733 Schema.Struct({
25734 ghost_commit: ClientRequest__GhostCommit,
25735 type: Schema.Literal("ghost_snapshot").annotate({ title: "GhostSnapshotResponseItemType" }),
25736 }).annotate({ title: "GhostSnapshotResponseItem" }),
25737 Schema.Struct({
25738 encrypted_content: Schema.String,
25739 type: Schema.Literal("compaction").annotate({ title: "CompactionResponseItemType" }),
25740 }).annotate({ title: "CompactionResponseItem" }),
25741 Schema.Struct({
25742 type: Schema.Literal("other").annotate({ title: "OtherResponseItemType" }),
25743 }).annotate({ title: "OtherResponseItem" }),
25744 ],
25745 { mode: "oneOf" },
25746);
25747
25748export type ClientRequest__ThreadRealtimeAudioChunk = {
25749 readonly data: string;
25750 readonly itemId?: string | null;
25751 readonly numChannels: number;
25752 readonly sampleRate: number;
25753 readonly samplesPerChannel?: number | null;
25754};
25755export const ClientRequest__ThreadRealtimeAudioChunk = Schema.Struct({
25756 data: Schema.String,
25757 itemId: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
25758 numChannels: Schema.Number.annotate({ format: "uint16" })
25759 .check(Schema.isInt())
25760 .check(Schema.isGreaterThanOrEqualTo(0)),
25761 sampleRate: Schema.Number.annotate({ format: "uint32" })
25762 .check(Schema.isInt())
25763 .check(Schema.isGreaterThanOrEqualTo(0)),
25764 samplesPerChannel: Schema.optionalKey(
25765 Schema.Union([
25766 Schema.Number.annotate({ format: "uint32" })
25767 .check(Schema.isInt())
25768 .check(Schema.isGreaterThanOrEqualTo(0)),
25769 Schema.Null,
25770 ]),
25771 ),
25772}).annotate({ description: "EXPERIMENTAL - thread realtime audio chunk." });
25773
25774export type ClientRequest__ThreadRealtimeStartTransport =
25775 | { readonly type: "websocket" }
25776 | { readonly sdp: string; readonly type: "webrtc" };
25777export const ClientRequest__ThreadRealtimeStartTransport = Schema.Union(
25778 [
25779 Schema.Struct({
25780 type: Schema.Literal("websocket").annotate({
25781 title: "WebsocketThreadRealtimeStartTransportType",
25782 }),
25783 }).annotate({ title: "WebsocketThreadRealtimeStartTransport" }),
25784 Schema.Struct({
25785 sdp: Schema.String.annotate({
25786 description:
25787 "SDP offer generated by a WebRTC RTCPeerConnection after configuring audio and the realtime events data channel.",
25788 }),
25789 type: Schema.Literal("webrtc").annotate({ title: "WebrtcThreadRealtimeStartTransportType" }),
25790 }).annotate({ title: "WebrtcThreadRealtimeStartTransport" }),
25791 ],
25792 { mode: "oneOf" },
25793).annotate({ description: "EXPERIMENTAL - transport used by thread realtime." });
25794
25795export type CommandExecutionRequestApprovalParams = {
25796 readonly approvalId?: string | null;
25797 readonly command?: string | null;
25798 readonly commandActions?: ReadonlyArray<CommandExecutionRequestApprovalParams__CommandAction> | null;
25799 readonly cwd?: string | null;
25800 readonly itemId: string;
25801 readonly networkApprovalContext?: CommandExecutionRequestApprovalParams__NetworkApprovalContext | null;
25802 readonly proposedExecpolicyAmendment?: ReadonlyArray<string> | null;
25803 readonly proposedNetworkPolicyAmendments?: ReadonlyArray<CommandExecutionRequestApprovalParams__NetworkPolicyAmendment> | null;
25804 readonly reason?: string | null;
25805 readonly threadId: string;
25806 readonly turnId: string;
25807};
25808export const CommandExecutionRequestApprovalParams = Schema.Struct({
25809 approvalId: Schema.optionalKey(
25810 Schema.Union([
25811 Schema.String.annotate({
25812 description:
25813 "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.",
25814 }),
25815 Schema.Null,
25816 ]),
25817 ),
25818 command: Schema.optionalKey(
25819 Schema.Union([
25820 Schema.String.annotate({ description: "The command to be executed." }),
25821 Schema.Null,
25822 ]),
25823 ),
25824 commandActions: Schema.optionalKey(
25825 Schema.Union([
25826 Schema.Array(CommandExecutionRequestApprovalParams__CommandAction).annotate({
25827 description: "Best-effort parsed command actions for friendly display.",
25828 }),
25829 Schema.Null,
25830 ]),
25831 ),
25832 cwd: Schema.optionalKey(
25833 Schema.Union([
25834 Schema.String.annotate({ description: "The command's working directory." }),
25835 Schema.Null,
25836 ]),
25837 ),
25838 itemId: Schema.String,
25839 networkApprovalContext: Schema.optionalKey(
25840 Schema.Union([
25841 CommandExecutionRequestApprovalParams__NetworkApprovalContext,
25842 Schema.Null,
25843 ]).annotate({ description: "Optional context for a managed-network approval prompt." }),
25844 ),
25845 proposedExecpolicyAmendment: Schema.optionalKey(
25846 Schema.Union([
25847 Schema.Array(Schema.String).annotate({
25848 description:
25849 "Optional proposed execpolicy amendment to allow similar commands without prompting.",
25850 }),
25851 Schema.Null,
25852 ]),
25853 ),
25854 proposedNetworkPolicyAmendments: Schema.optionalKey(
25855 Schema.Union([
25856 Schema.Array(CommandExecutionRequestApprovalParams__NetworkPolicyAmendment).annotate({
25857 description:
25858 "Optional proposed network policy amendments (allow/deny host) for future requests.",
25859 }),
25860 Schema.Null,
25861 ]),
25862 ),
25863 reason: Schema.optionalKey(
25864 Schema.Union([
25865 Schema.String.annotate({
25866 description: "Optional explanatory reason (e.g. request for network access).",
25867 }),
25868 Schema.Null,
25869 ]),
25870 ),
25871 threadId: Schema.String,
25872 turnId: Schema.String,
25873}).annotate({ title: "CommandExecutionRequestApprovalParams" });
25874
25875export type CommandExecutionRequestApprovalParams__AdditionalPermissionProfile = {
25876 readonly fileSystem?: CommandExecutionRequestApprovalParams__AdditionalFileSystemPermissions | null;
25877 readonly network?: CommandExecutionRequestApprovalParams__AdditionalNetworkPermissions | null;
25878};
25879export const CommandExecutionRequestApprovalParams__AdditionalPermissionProfile = Schema.Struct({
25880 fileSystem: Schema.optionalKey(
25881 Schema.Union([
25882 CommandExecutionRequestApprovalParams__AdditionalFileSystemPermissions,
25883 Schema.Null,
25884 ]),
25885 ),
25886 network: Schema.optionalKey(
25887 Schema.Union([
25888 CommandExecutionRequestApprovalParams__AdditionalNetworkPermissions,
25889 Schema.Null,
25890 ]),
25891 ),
25892});
25893
25894export type CommandExecutionRequestApprovalParams__CommandExecutionApprovalDecision =
25895 | "accept"
25896 | "acceptForSession"
25897 | {
25898 readonly acceptWithExecpolicyAmendment: {
25899 readonly execpolicy_amendment: ReadonlyArray<string>;
25900 };
25901 }
25902 | {
25903 readonly applyNetworkPolicyAmendment: {
25904 readonly network_policy_amendment: CommandExecutionRequestApprovalParams__NetworkPolicyAmendment;
25905 };
25906 }
25907 | "decline"
25908 | "cancel";
25909export const CommandExecutionRequestApprovalParams__CommandExecutionApprovalDecision = Schema.Union(
25910 [
25911 Schema.Literal("accept").annotate({ description: "User approved the command." }),
25912 Schema.Literal("acceptForSession").annotate({
25913 description:
25914 "User approved the command and future prompts in the same session-scoped approval cache should run without prompting.",
25915 }),
25916 Schema.Struct({
25917 acceptWithExecpolicyAmendment: Schema.Struct({
25918 execpolicy_amendment: Schema.Array(Schema.String),
25919 }),
25920 }).annotate({
25921 title: "AcceptWithExecpolicyAmendmentCommandExecutionApprovalDecision",
25922 description:
25923 "User approved the command, and wants to apply the proposed execpolicy amendment so future matching commands can run without prompting.",
25924 }),
25925 Schema.Struct({
25926 applyNetworkPolicyAmendment: Schema.Struct({
25927 network_policy_amendment: CommandExecutionRequestApprovalParams__NetworkPolicyAmendment,
25928 }),
25929 }).annotate({
25930 title: "ApplyNetworkPolicyAmendmentCommandExecutionApprovalDecision",
25931 description: "User chose a persistent network policy rule (allow/deny) for this host.",
25932 }),
25933 Schema.Literal("decline").annotate({
25934 description: "User denied the command. The agent will continue the turn.",
25935 }),
25936 Schema.Literal("cancel").annotate({
25937 description: "User denied the command. The turn will also be immediately interrupted.",
25938 }),
25939 ],
25940 { mode: "oneOf" },
25941);
25942
25943export type CommandExecutionRequestApprovalResponse = {
25944 readonly decision: CommandExecutionRequestApprovalResponse__CommandExecutionApprovalDecision;
25945};
25946export const CommandExecutionRequestApprovalResponse = Schema.Struct({
25947 decision: CommandExecutionRequestApprovalResponse__CommandExecutionApprovalDecision,
25948}).annotate({ title: "CommandExecutionRequestApprovalResponse" });
25949
25950export type DynamicToolCallParams = {
25951 readonly arguments: unknown;
25952 readonly callId: string;
25953 readonly threadId: string;
25954 readonly tool: string;
25955 readonly turnId: string;
25956};
25957export const DynamicToolCallParams = Schema.Struct({
25958 arguments: Schema.Unknown,
25959 callId: Schema.String,
25960 threadId: Schema.String,
25961 tool: Schema.String,
25962 turnId: Schema.String,
25963}).annotate({ title: "DynamicToolCallParams" });
25964
25965export type DynamicToolCallResponse = {
25966 readonly contentItems: ReadonlyArray<DynamicToolCallResponse__DynamicToolCallOutputContentItem>;
25967 readonly success: boolean;
25968};
25969export const DynamicToolCallResponse = Schema.Struct({
25970 contentItems: Schema.Array(DynamicToolCallResponse__DynamicToolCallOutputContentItem),
25971 success: Schema.Boolean,
25972}).annotate({ title: "DynamicToolCallResponse" });
25973
25974export type ExecCommandApprovalParams = {
25975 readonly approvalId?: string | null;
25976 readonly callId: string;
25977 readonly command: ReadonlyArray<string>;
25978 readonly conversationId: ExecCommandApprovalParams__ThreadId;
25979 readonly cwd: string;
25980 readonly parsedCmd: ReadonlyArray<ExecCommandApprovalParams__ParsedCommand>;
25981 readonly reason?: string | null;
25982};
25983export const ExecCommandApprovalParams = Schema.Struct({
25984 approvalId: Schema.optionalKey(
25985 Schema.Union([
25986 Schema.String.annotate({ description: "Identifier for this specific approval callback." }),
25987 Schema.Null,
25988 ]),
25989 ),
25990 callId: Schema.String.annotate({
25991 description:
25992 "Use to correlate this with [codex_protocol::protocol::ExecCommandBeginEvent] and [codex_protocol::protocol::ExecCommandEndEvent].",
25993 }),
25994 command: Schema.Array(Schema.String),
25995 conversationId: ExecCommandApprovalParams__ThreadId,
25996 cwd: Schema.String,
25997 parsedCmd: Schema.Array(ExecCommandApprovalParams__ParsedCommand),
25998 reason: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
25999}).annotate({ title: "ExecCommandApprovalParams" });
26000
26001export type ExecCommandApprovalResponse = {
26002 readonly decision: ExecCommandApprovalResponse__ReviewDecision;
26003};
26004export const ExecCommandApprovalResponse = Schema.Struct({
26005 decision: ExecCommandApprovalResponse__ReviewDecision,
26006}).annotate({ title: "ExecCommandApprovalResponse" });
26007
26008export type FileChangeRequestApprovalParams = {
26009 readonly grantRoot?: string | null;
26010 readonly itemId: string;
26011 readonly reason?: string | null;
26012 readonly threadId: string;
26013 readonly turnId: string;
26014};
26015export const FileChangeRequestApprovalParams = Schema.Struct({
26016 grantRoot: Schema.optionalKey(
26017 Schema.Union([
26018 Schema.String.annotate({
26019 description:
26020 "[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).",
26021 }),
26022 Schema.Null,
26023 ]),
26024 ),
26025 itemId: Schema.String,
26026 reason: Schema.optionalKey(
26027 Schema.Union([
26028 Schema.String.annotate({
26029 description: "Optional explanatory reason (e.g. request for extra write access).",
26030 }),
26031 Schema.Null,
26032 ]),
26033 ),
26034 threadId: Schema.String,
26035 turnId: Schema.String,
26036}).annotate({ title: "FileChangeRequestApprovalParams" });
26037
26038export type FileChangeRequestApprovalResponse = {
26039 readonly decision: FileChangeRequestApprovalResponse__FileChangeApprovalDecision;
26040};
26041export const FileChangeRequestApprovalResponse = Schema.Struct({
26042 decision: FileChangeRequestApprovalResponse__FileChangeApprovalDecision,
26043}).annotate({ title: "FileChangeRequestApprovalResponse" });
26044
26045export type FuzzyFileSearchParams = {
26046 readonly cancellationToken?: string | null;
26047 readonly query: string;
26048 readonly roots: ReadonlyArray<string>;
26049};
26050export const FuzzyFileSearchParams = Schema.Struct({
26051 cancellationToken: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
26052 query: Schema.String,
26053 roots: Schema.Array(Schema.String),
26054}).annotate({ title: "FuzzyFileSearchParams" });
26055
26056export type FuzzyFileSearchResponse = {
26057 readonly files: ReadonlyArray<FuzzyFileSearchResponse__FuzzyFileSearchResult>;
26058};
26059export const FuzzyFileSearchResponse = Schema.Struct({
26060 files: Schema.Array(FuzzyFileSearchResponse__FuzzyFileSearchResult),
26061}).annotate({ title: "FuzzyFileSearchResponse" });
26062
26063export type FuzzyFileSearchSessionCompletedNotification = { readonly sessionId: string };
26064export const FuzzyFileSearchSessionCompletedNotification = Schema.Struct({
26065 sessionId: Schema.String,
26066}).annotate({ title: "FuzzyFileSearchSessionCompletedNotification" });
26067
26068export type FuzzyFileSearchSessionUpdatedNotification = {
26069 readonly files: ReadonlyArray<FuzzyFileSearchSessionUpdatedNotification__FuzzyFileSearchResult>;
26070 readonly query: string;
26071 readonly sessionId: string;
26072};
26073export const FuzzyFileSearchSessionUpdatedNotification = Schema.Struct({
26074 files: Schema.Array(FuzzyFileSearchSessionUpdatedNotification__FuzzyFileSearchResult),
26075 query: Schema.String,
26076 sessionId: Schema.String,
26077}).annotate({ title: "FuzzyFileSearchSessionUpdatedNotification" });
26078
26079export type GetAuthStatusParams = {
26080 readonly includeToken?: boolean | null;
26081 readonly refreshToken?: boolean | null;
26082};
26083export const GetAuthStatusParams = Schema.Struct({
26084 includeToken: Schema.optionalKey(Schema.Union([Schema.Boolean, Schema.Null])),
26085 refreshToken: Schema.optionalKey(Schema.Union([Schema.Boolean, Schema.Null])),
26086}).annotate({ title: "GetAuthStatusParams" });
26087
26088export type GetAuthStatusResponse = {
26089 readonly authMethod: unknown | null;
26090 readonly authToken: string | null;
26091 readonly requiresOpenaiAuth: boolean | null;
26092};
26093export const GetAuthStatusResponse = Schema.Struct({
26094 authMethod: Schema.Union([Schema.Unknown, Schema.Null]),
26095 authToken: Schema.Union([Schema.String, Schema.Null]),
26096 requiresOpenaiAuth: Schema.Union([Schema.Boolean, Schema.Null]),
26097}).annotate({ title: "GetAuthStatusResponse" });
26098
26099export type GetConversationSummaryParams =
26100 | { readonly rolloutPath: string }
26101 | { readonly conversationId: string };
26102export const GetConversationSummaryParams = Schema.Union(
26103 [Schema.Struct({ rolloutPath: Schema.String }), Schema.Struct({ conversationId: Schema.String })],
26104 { mode: "oneOf" },
26105).annotate({ title: "GetConversationSummaryParams" });
26106
26107export type GetConversationSummaryResponse = { readonly summary: unknown };
26108export const GetConversationSummaryResponse = Schema.Struct({ summary: Schema.Unknown }).annotate({
26109 title: "GetConversationSummaryResponse",
26110});
26111
26112export type GitDiffToRemoteParams = { readonly cwd: string };
26113export const GitDiffToRemoteParams = Schema.Struct({ cwd: Schema.String }).annotate({
26114 title: "GitDiffToRemoteParams",
26115});
26116
26117export type GitDiffToRemoteResponse = { readonly sha: string; readonly diff: string };
26118export const GitDiffToRemoteResponse = Schema.Struct({
26119 sha: Schema.String,
26120 diff: Schema.String,
26121}).annotate({ title: "GitDiffToRemoteResponse" });
26122
26123export type JSONRPCError = {
26124 readonly error: JSONRPCError__JSONRPCErrorError;
26125 readonly id: JSONRPCError__RequestId;
26126};
26127export const JSONRPCError = Schema.Struct({
26128 error: JSONRPCError__JSONRPCErrorError,
26129 id: JSONRPCError__RequestId,
26130}).annotate({
26131 title: "JSONRPCError",
26132 description: "A response to a request that indicates an error occurred.",
26133});
26134
26135export type JSONRPCErrorError = {
26136 readonly code: number;
26137 readonly data?: unknown;
26138 readonly message: string;
26139};
26140export const JSONRPCErrorError = Schema.Struct({
26141 code: Schema.Number.annotate({ format: "int64" }).check(Schema.isInt()),
26142 data: Schema.optionalKey(Schema.Unknown),
26143 message: Schema.String,
26144}).annotate({ title: "JSONRPCErrorError" });
26145
26146export type JSONRPCMessage =
26147 | JSONRPCMessage__JSONRPCRequest
26148 | JSONRPCMessage__JSONRPCNotification
26149 | JSONRPCMessage__JSONRPCResponse
26150 | JSONRPCMessage__JSONRPCError;
26151export const JSONRPCMessage = Schema.Union([
26152 JSONRPCMessage__JSONRPCRequest,
26153 JSONRPCMessage__JSONRPCNotification,
26154 JSONRPCMessage__JSONRPCResponse,
26155 JSONRPCMessage__JSONRPCError,
26156]).annotate({
26157 title: "JSONRPCMessage",
26158 description:
26159 "Refers to any valid JSON-RPC object that can be decoded off the wire, or encoded to be sent.",
26160});
26161
26162export type JSONRPCNotification = { readonly method: string; readonly params?: unknown };
26163export const JSONRPCNotification = Schema.Struct({
26164 method: Schema.String,
26165 params: Schema.optionalKey(Schema.Unknown),
26166}).annotate({
26167 title: "JSONRPCNotification",
26168 description: "A notification which does not expect a response.",
26169});
26170
26171export type JSONRPCRequest = {
26172 readonly id: JSONRPCRequest__RequestId;
26173 readonly method: string;
26174 readonly params?: unknown;
26175 readonly trace?: JSONRPCRequest__W3cTraceContext | null;
26176};
26177export const JSONRPCRequest = Schema.Struct({
26178 id: JSONRPCRequest__RequestId,
26179 method: Schema.String,
26180 params: Schema.optionalKey(Schema.Unknown),
26181 trace: Schema.optionalKey(
26182 Schema.Union([JSONRPCRequest__W3cTraceContext, Schema.Null]).annotate({
26183 description: "Optional W3C Trace Context for distributed tracing.",
26184 }),
26185 ),
26186}).annotate({ title: "JSONRPCRequest", description: "A request that expects a response." });
26187
26188export type JSONRPCResponse = { readonly id: JSONRPCResponse__RequestId; readonly result: unknown };
26189export const JSONRPCResponse = Schema.Struct({
26190 id: JSONRPCResponse__RequestId,
26191 result: Schema.Unknown,
26192}).annotate({
26193 title: "JSONRPCResponse",
26194 description: "A successful (non-error) response to a request.",
26195});
26196
26197export type McpServerElicitationRequestParams =
26198 | {
26199 readonly _meta?: unknown;
26200 readonly message: string;
26201 readonly mode: "form";
26202 readonly requestedSchema: McpServerElicitationRequestParams__McpElicitationSchema;
26203 readonly serverName: string;
26204 readonly threadId: string;
26205 readonly turnId?: string | null;
26206 }
26207 | {
26208 readonly _meta?: unknown;
26209 readonly elicitationId: string;
26210 readonly message: string;
26211 readonly mode: "url";
26212 readonly url: string;
26213 readonly serverName: string;
26214 readonly threadId: string;
26215 readonly turnId?: string | null;
26216 };
26217export const McpServerElicitationRequestParams = Schema.Union(
26218 [
26219 Schema.Struct({
26220 _meta: Schema.optionalKey(Schema.Unknown),
26221 message: Schema.String,
26222 mode: Schema.Literal("form"),
26223 requestedSchema: McpServerElicitationRequestParams__McpElicitationSchema,
26224 serverName: Schema.String,
26225 threadId: Schema.String,
26226 turnId: Schema.optionalKey(
26227 Schema.Union([
26228 Schema.String.annotate({
26229 description:
26230 "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.",
26231 }),
26232 Schema.Null,
26233 ]),
26234 ),
26235 }).annotate({ title: "McpServerElicitationRequestParams" }),
26236 Schema.Struct({
26237 _meta: Schema.optionalKey(Schema.Unknown),
26238 elicitationId: Schema.String,
26239 message: Schema.String,
26240 mode: Schema.Literal("url"),
26241 url: Schema.String,
26242 serverName: Schema.String,
26243 threadId: Schema.String,
26244 turnId: Schema.optionalKey(
26245 Schema.Union([
26246 Schema.String.annotate({
26247 description:
26248 "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.",
26249 }),
26250 Schema.Null,
26251 ]),
26252 ),
26253 }).annotate({ title: "McpServerElicitationRequestParams" }),
26254 ],
26255 { mode: "oneOf" },
26256);
26257
26258export type McpServerElicitationRequestResponse = {
26259 readonly _meta?: unknown;
26260 readonly action: McpServerElicitationRequestResponse__McpServerElicitationAction;
26261 readonly content?: unknown;
26262};
26263export const McpServerElicitationRequestResponse = Schema.Struct({
26264 _meta: Schema.optionalKey(
26265 Schema.Unknown.annotate({
26266 description: "Optional client metadata for form-mode action handling.",
26267 }),
26268 ),
26269 action: McpServerElicitationRequestResponse__McpServerElicitationAction,
26270 content: Schema.optionalKey(
26271 Schema.Unknown.annotate({
26272 description:
26273 "Structured user input for accepted elicitations, mirroring RMCP `CreateElicitationResult`.\n\nThis is nullable because decline/cancel responses have no content.",
26274 }),
26275 ),
26276}).annotate({ title: "McpServerElicitationRequestResponse" });
26277
26278export type PermissionsRequestApprovalParams = {
26279 readonly itemId: string;
26280 readonly permissions: PermissionsRequestApprovalParams__RequestPermissionProfile;
26281 readonly reason?: string | null;
26282 readonly threadId: string;
26283 readonly turnId: string;
26284};
26285export const PermissionsRequestApprovalParams = Schema.Struct({
26286 itemId: Schema.String,
26287 permissions: PermissionsRequestApprovalParams__RequestPermissionProfile,
26288 reason: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
26289 threadId: Schema.String,
26290 turnId: Schema.String,
26291}).annotate({ title: "PermissionsRequestApprovalParams" });
26292
26293export type PermissionsRequestApprovalResponse = {
26294 readonly permissions: PermissionsRequestApprovalResponse__GrantedPermissionProfile;
26295 readonly scope?: "turn" | "session";
26296};
26297export const PermissionsRequestApprovalResponse = Schema.Struct({
26298 permissions: PermissionsRequestApprovalResponse__GrantedPermissionProfile,
26299 scope: Schema.optionalKey(Schema.Literals(["turn", "session"]).annotate({ default: "turn" })),
26300}).annotate({ title: "PermissionsRequestApprovalResponse" });
26301
26302export type PermissionsRequestApprovalResponse__PermissionGrantScope = "turn" | "session";
26303export const PermissionsRequestApprovalResponse__PermissionGrantScope = Schema.Literals([
26304 "turn",
26305 "session",
26306]);
26307
26308export type RequestId = string | number;
26309export const RequestId = Schema.Union([
26310 Schema.String,
26311 Schema.Number.annotate({ format: "int64" }).check(Schema.isInt()),
26312]).annotate({ title: "RequestId" });
26313
26314export type ServerNotification =
26315 | { readonly method: "error"; readonly params: ServerNotification__ErrorNotification }
26316 | {
26317 readonly method: "thread/started";
26318 readonly params: ServerNotification__ThreadStartedNotification;
26319 }
26320 | {
26321 readonly method: "thread/status/changed";
26322 readonly params: ServerNotification__ThreadStatusChangedNotification;
26323 }
26324 | {
26325 readonly method: "thread/archived";
26326 readonly params: ServerNotification__ThreadArchivedNotification;
26327 }
26328 | {
26329 readonly method: "thread/unarchived";
26330 readonly params: ServerNotification__ThreadUnarchivedNotification;
26331 }
26332 | {
26333 readonly method: "thread/closed";
26334 readonly params: ServerNotification__ThreadClosedNotification;
26335 }
26336 | {
26337 readonly method: "skills/changed";
26338 readonly params: ServerNotification__SkillsChangedNotification;
26339 }
26340 | {
26341 readonly method: "thread/name/updated";
26342 readonly params: ServerNotification__ThreadNameUpdatedNotification;
26343 }
26344 | {
26345 readonly method: "thread/tokenUsage/updated";
26346 readonly params: ServerNotification__ThreadTokenUsageUpdatedNotification;
26347 }
26348 | {
26349 readonly method: "turn/started";
26350 readonly params: ServerNotification__TurnStartedNotification;
26351 }
26352 | {
26353 readonly method: "hook/started";
26354 readonly params: ServerNotification__HookStartedNotification;
26355 }
26356 | {
26357 readonly method: "turn/completed";
26358 readonly params: ServerNotification__TurnCompletedNotification;
26359 }
26360 | {
26361 readonly method: "hook/completed";
26362 readonly params: ServerNotification__HookCompletedNotification;
26363 }
26364 | {
26365 readonly method: "turn/diff/updated";
26366 readonly params: ServerNotification__TurnDiffUpdatedNotification;
26367 }
26368 | {
26369 readonly method: "turn/plan/updated";
26370 readonly params: ServerNotification__TurnPlanUpdatedNotification;
26371 }
26372 | {
26373 readonly method: "item/started";
26374 readonly params: ServerNotification__ItemStartedNotification;
26375 }
26376 | {
26377 readonly method: "item/autoApprovalReview/started";
26378 readonly params: ServerNotification__ItemGuardianApprovalReviewStartedNotification;
26379 }
26380 | {
26381 readonly method: "item/autoApprovalReview/completed";
26382 readonly params: ServerNotification__ItemGuardianApprovalReviewCompletedNotification;
26383 }
26384 | {
26385 readonly method: "item/completed";
26386 readonly params: ServerNotification__ItemCompletedNotification;
26387 }
26388 | {
26389 readonly method: "item/agentMessage/delta";
26390 readonly params: ServerNotification__AgentMessageDeltaNotification;
26391 }
26392 | {
26393 readonly method: "item/plan/delta";
26394 readonly params: ServerNotification__PlanDeltaNotification;
26395 }
26396 | {
26397 readonly method: "command/exec/outputDelta";
26398 readonly params: ServerNotification__CommandExecOutputDeltaNotification;
26399 }
26400 | {
26401 readonly method: "item/commandExecution/outputDelta";
26402 readonly params: ServerNotification__CommandExecutionOutputDeltaNotification;
26403 }
26404 | {
26405 readonly method: "item/commandExecution/terminalInteraction";
26406 readonly params: ServerNotification__TerminalInteractionNotification;
26407 }
26408 | {
26409 readonly method: "item/fileChange/outputDelta";
26410 readonly params: ServerNotification__FileChangeOutputDeltaNotification;
26411 }
26412 | {
26413 readonly method: "serverRequest/resolved";
26414 readonly params: ServerNotification__ServerRequestResolvedNotification;
26415 }
26416 | {
26417 readonly method: "item/mcpToolCall/progress";
26418 readonly params: ServerNotification__McpToolCallProgressNotification;
26419 }
26420 | {
26421 readonly method: "mcpServer/oauthLogin/completed";
26422 readonly params: ServerNotification__McpServerOauthLoginCompletedNotification;
26423 }
26424 | {
26425 readonly method: "mcpServer/startupStatus/updated";
26426 readonly params: ServerNotification__McpServerStatusUpdatedNotification;
26427 }
26428 | {
26429 readonly method: "account/updated";
26430 readonly params: ServerNotification__AccountUpdatedNotification;
26431 }
26432 | {
26433 readonly method: "account/rateLimits/updated";
26434 readonly params: ServerNotification__AccountRateLimitsUpdatedNotification;
26435 }
26436 | {
26437 readonly method: "app/list/updated";
26438 readonly params: ServerNotification__AppListUpdatedNotification;
26439 }
26440 | { readonly method: "fs/changed"; readonly params: ServerNotification__FsChangedNotification }
26441 | {
26442 readonly method: "item/reasoning/summaryTextDelta";
26443 readonly params: ServerNotification__ReasoningSummaryTextDeltaNotification;
26444 }
26445 | {
26446 readonly method: "item/reasoning/summaryPartAdded";
26447 readonly params: ServerNotification__ReasoningSummaryPartAddedNotification;
26448 }
26449 | {
26450 readonly method: "item/reasoning/textDelta";
26451 readonly params: ServerNotification__ReasoningTextDeltaNotification;
26452 }
26453 | {
26454 readonly method: "thread/compacted";
26455 readonly params: ServerNotification__ContextCompactedNotification;
26456 }
26457 | {
26458 readonly method: "model/rerouted";
26459 readonly params: ServerNotification__ModelReroutedNotification;
26460 }
26461 | {
26462 readonly method: "deprecationNotice";
26463 readonly params: ServerNotification__DeprecationNoticeNotification;
26464 }
26465 | {
26466 readonly method: "configWarning";
26467 readonly params: ServerNotification__ConfigWarningNotification;
26468 }
26469 | {
26470 readonly method: "fuzzyFileSearch/sessionUpdated";
26471 readonly params: ServerNotification__FuzzyFileSearchSessionUpdatedNotification;
26472 }
26473 | {
26474 readonly method: "fuzzyFileSearch/sessionCompleted";
26475 readonly params: ServerNotification__FuzzyFileSearchSessionCompletedNotification;
26476 }
26477 | {
26478 readonly method: "thread/realtime/started";
26479 readonly params: ServerNotification__ThreadRealtimeStartedNotification;
26480 }
26481 | {
26482 readonly method: "thread/realtime/itemAdded";
26483 readonly params: ServerNotification__ThreadRealtimeItemAddedNotification;
26484 }
26485 | {
26486 readonly method: "thread/realtime/transcriptUpdated";
26487 readonly params: ServerNotification__ThreadRealtimeTranscriptUpdatedNotification;
26488 }
26489 | {
26490 readonly method: "thread/realtime/outputAudio/delta";
26491 readonly params: ServerNotification__ThreadRealtimeOutputAudioDeltaNotification;
26492 }
26493 | {
26494 readonly method: "thread/realtime/sdp";
26495 readonly params: ServerNotification__ThreadRealtimeSdpNotification;
26496 }
26497 | {
26498 readonly method: "thread/realtime/error";
26499 readonly params: ServerNotification__ThreadRealtimeErrorNotification;
26500 }
26501 | {
26502 readonly method: "thread/realtime/closed";
26503 readonly params: ServerNotification__ThreadRealtimeClosedNotification;
26504 }
26505 | {
26506 readonly method: "windows/worldWritableWarning";
26507 readonly params: ServerNotification__WindowsWorldWritableWarningNotification;
26508 }
26509 | {
26510 readonly method: "windowsSandbox/setupCompleted";
26511 readonly params: ServerNotification__WindowsSandboxSetupCompletedNotification;
26512 }
26513 | {
26514 readonly method: "account/login/completed";
26515 readonly params: ServerNotification__AccountLoginCompletedNotification;
26516 };
26517export const ServerNotification = Schema.Union(
26518 [
26519 Schema.Struct({
26520 method: Schema.Literal("error").annotate({ title: "ErrorNotificationMethod" }),
26521 params: ServerNotification__ErrorNotification,
26522 }).annotate({ title: "ErrorNotification", description: "NEW NOTIFICATIONS" }),
26523 Schema.Struct({
26524 method: Schema.Literal("thread/started").annotate({
26525 title: "Thread/startedNotificationMethod",
26526 }),
26527 params: ServerNotification__ThreadStartedNotification,
26528 }).annotate({ title: "Thread/startedNotification" }),
26529 Schema.Struct({
26530 method: Schema.Literal("thread/status/changed").annotate({
26531 title: "Thread/status/changedNotificationMethod",
26532 }),
26533 params: ServerNotification__ThreadStatusChangedNotification,
26534 }).annotate({ title: "Thread/status/changedNotification" }),
26535 Schema.Struct({
26536 method: Schema.Literal("thread/archived").annotate({
26537 title: "Thread/archivedNotificationMethod",
26538 }),
26539 params: ServerNotification__ThreadArchivedNotification,
26540 }).annotate({ title: "Thread/archivedNotification" }),
26541 Schema.Struct({
26542 method: Schema.Literal("thread/unarchived").annotate({
26543 title: "Thread/unarchivedNotificationMethod",
26544 }),
26545 params: ServerNotification__ThreadUnarchivedNotification,
26546 }).annotate({ title: "Thread/unarchivedNotification" }),
26547 Schema.Struct({
26548 method: Schema.Literal("thread/closed").annotate({
26549 title: "Thread/closedNotificationMethod",
26550 }),
26551 params: ServerNotification__ThreadClosedNotification,
26552 }).annotate({ title: "Thread/closedNotification" }),
26553 Schema.Struct({
26554 method: Schema.Literal("skills/changed").annotate({
26555 title: "Skills/changedNotificationMethod",
26556 }),
26557 params: ServerNotification__SkillsChangedNotification,
26558 }).annotate({ title: "Skills/changedNotification" }),
26559 Schema.Struct({
26560 method: Schema.Literal("thread/name/updated").annotate({
26561 title: "Thread/name/updatedNotificationMethod",
26562 }),
26563 params: ServerNotification__ThreadNameUpdatedNotification,
26564 }).annotate({ title: "Thread/name/updatedNotification" }),
26565 Schema.Struct({
26566 method: Schema.Literal("thread/tokenUsage/updated").annotate({
26567 title: "Thread/tokenUsage/updatedNotificationMethod",
26568 }),
26569 params: ServerNotification__ThreadTokenUsageUpdatedNotification,
26570 }).annotate({ title: "Thread/tokenUsage/updatedNotification" }),
26571 Schema.Struct({
26572 method: Schema.Literal("turn/started").annotate({ title: "Turn/startedNotificationMethod" }),
26573 params: ServerNotification__TurnStartedNotification,
26574 }).annotate({ title: "Turn/startedNotification" }),
26575 Schema.Struct({
26576 method: Schema.Literal("hook/started").annotate({ title: "Hook/startedNotificationMethod" }),
26577 params: ServerNotification__HookStartedNotification,
26578 }).annotate({ title: "Hook/startedNotification" }),
26579 Schema.Struct({
26580 method: Schema.Literal("turn/completed").annotate({
26581 title: "Turn/completedNotificationMethod",
26582 }),
26583 params: ServerNotification__TurnCompletedNotification,
26584 }).annotate({ title: "Turn/completedNotification" }),
26585 Schema.Struct({
26586 method: Schema.Literal("hook/completed").annotate({
26587 title: "Hook/completedNotificationMethod",
26588 }),
26589 params: ServerNotification__HookCompletedNotification,
26590 }).annotate({ title: "Hook/completedNotification" }),
26591 Schema.Struct({
26592 method: Schema.Literal("turn/diff/updated").annotate({
26593 title: "Turn/diff/updatedNotificationMethod",
26594 }),
26595 params: ServerNotification__TurnDiffUpdatedNotification,
26596 }).annotate({ title: "Turn/diff/updatedNotification" }),
26597 Schema.Struct({
26598 method: Schema.Literal("turn/plan/updated").annotate({
26599 title: "Turn/plan/updatedNotificationMethod",
26600 }),
26601 params: ServerNotification__TurnPlanUpdatedNotification,
26602 }).annotate({ title: "Turn/plan/updatedNotification" }),
26603 Schema.Struct({
26604 method: Schema.Literal("item/started").annotate({ title: "Item/startedNotificationMethod" }),
26605 params: ServerNotification__ItemStartedNotification,
26606 }).annotate({ title: "Item/startedNotification" }),
26607 Schema.Struct({
26608 method: Schema.Literal("item/autoApprovalReview/started").annotate({
26609 title: "Item/autoApprovalReview/startedNotificationMethod",
26610 }),
26611 params: ServerNotification__ItemGuardianApprovalReviewStartedNotification,
26612 }).annotate({ title: "Item/autoApprovalReview/startedNotification" }),
26613 Schema.Struct({
26614 method: Schema.Literal("item/autoApprovalReview/completed").annotate({
26615 title: "Item/autoApprovalReview/completedNotificationMethod",
26616 }),
26617 params: ServerNotification__ItemGuardianApprovalReviewCompletedNotification,
26618 }).annotate({ title: "Item/autoApprovalReview/completedNotification" }),
26619 Schema.Struct({
26620 method: Schema.Literal("item/completed").annotate({
26621 title: "Item/completedNotificationMethod",
26622 }),
26623 params: ServerNotification__ItemCompletedNotification,
26624 }).annotate({ title: "Item/completedNotification" }),
26625 Schema.Struct({
26626 method: Schema.Literal("item/agentMessage/delta").annotate({
26627 title: "Item/agentMessage/deltaNotificationMethod",
26628 }),
26629 params: ServerNotification__AgentMessageDeltaNotification,
26630 }).annotate({ title: "Item/agentMessage/deltaNotification" }),
26631 Schema.Struct({
26632 method: Schema.Literal("item/plan/delta").annotate({
26633 title: "Item/plan/deltaNotificationMethod",
26634 }),
26635 params: ServerNotification__PlanDeltaNotification,
26636 }).annotate({
26637 title: "Item/plan/deltaNotification",
26638 description: "EXPERIMENTAL - proposed plan streaming deltas for plan items.",
26639 }),
26640 Schema.Struct({
26641 method: Schema.Literal("command/exec/outputDelta").annotate({
26642 title: "Command/exec/outputDeltaNotificationMethod",
26643 }),
26644 params: ServerNotification__CommandExecOutputDeltaNotification,
26645 }).annotate({
26646 title: "Command/exec/outputDeltaNotification",
26647 description:
26648 "Stream base64-encoded stdout/stderr chunks for a running `command/exec` session.",
26649 }),
26650 Schema.Struct({
26651 method: Schema.Literal("item/commandExecution/outputDelta").annotate({
26652 title: "Item/commandExecution/outputDeltaNotificationMethod",
26653 }),
26654 params: ServerNotification__CommandExecutionOutputDeltaNotification,
26655 }).annotate({ title: "Item/commandExecution/outputDeltaNotification" }),
26656 Schema.Struct({
26657 method: Schema.Literal("item/commandExecution/terminalInteraction").annotate({
26658 title: "Item/commandExecution/terminalInteractionNotificationMethod",
26659 }),
26660 params: ServerNotification__TerminalInteractionNotification,
26661 }).annotate({ title: "Item/commandExecution/terminalInteractionNotification" }),
26662 Schema.Struct({
26663 method: Schema.Literal("item/fileChange/outputDelta").annotate({
26664 title: "Item/fileChange/outputDeltaNotificationMethod",
26665 }),
26666 params: ServerNotification__FileChangeOutputDeltaNotification,
26667 }).annotate({ title: "Item/fileChange/outputDeltaNotification" }),
26668 Schema.Struct({
26669 method: Schema.Literal("serverRequest/resolved").annotate({
26670 title: "ServerRequest/resolvedNotificationMethod",
26671 }),
26672 params: ServerNotification__ServerRequestResolvedNotification,
26673 }).annotate({ title: "ServerRequest/resolvedNotification" }),
26674 Schema.Struct({
26675 method: Schema.Literal("item/mcpToolCall/progress").annotate({
26676 title: "Item/mcpToolCall/progressNotificationMethod",
26677 }),
26678 params: ServerNotification__McpToolCallProgressNotification,
26679 }).annotate({ title: "Item/mcpToolCall/progressNotification" }),
26680 Schema.Struct({
26681 method: Schema.Literal("mcpServer/oauthLogin/completed").annotate({
26682 title: "McpServer/oauthLogin/completedNotificationMethod",
26683 }),
26684 params: ServerNotification__McpServerOauthLoginCompletedNotification,
26685 }).annotate({ title: "McpServer/oauthLogin/completedNotification" }),
26686 Schema.Struct({
26687 method: Schema.Literal("mcpServer/startupStatus/updated").annotate({
26688 title: "McpServer/startupStatus/updatedNotificationMethod",
26689 }),
26690 params: ServerNotification__McpServerStatusUpdatedNotification,
26691 }).annotate({ title: "McpServer/startupStatus/updatedNotification" }),
26692 Schema.Struct({
26693 method: Schema.Literal("account/updated").annotate({
26694 title: "Account/updatedNotificationMethod",
26695 }),
26696 params: ServerNotification__AccountUpdatedNotification,
26697 }).annotate({ title: "Account/updatedNotification" }),
26698 Schema.Struct({
26699 method: Schema.Literal("account/rateLimits/updated").annotate({
26700 title: "Account/rateLimits/updatedNotificationMethod",
26701 }),
26702 params: ServerNotification__AccountRateLimitsUpdatedNotification,
26703 }).annotate({ title: "Account/rateLimits/updatedNotification" }),
26704 Schema.Struct({
26705 method: Schema.Literal("app/list/updated").annotate({
26706 title: "App/list/updatedNotificationMethod",
26707 }),
26708 params: ServerNotification__AppListUpdatedNotification,
26709 }).annotate({ title: "App/list/updatedNotification" }),
26710 Schema.Struct({
26711 method: Schema.Literal("fs/changed").annotate({ title: "Fs/changedNotificationMethod" }),
26712 params: ServerNotification__FsChangedNotification,
26713 }).annotate({ title: "Fs/changedNotification" }),
26714 Schema.Struct({
26715 method: Schema.Literal("item/reasoning/summaryTextDelta").annotate({
26716 title: "Item/reasoning/summaryTextDeltaNotificationMethod",
26717 }),
26718 params: ServerNotification__ReasoningSummaryTextDeltaNotification,
26719 }).annotate({ title: "Item/reasoning/summaryTextDeltaNotification" }),
26720 Schema.Struct({
26721 method: Schema.Literal("item/reasoning/summaryPartAdded").annotate({
26722 title: "Item/reasoning/summaryPartAddedNotificationMethod",
26723 }),
26724 params: ServerNotification__ReasoningSummaryPartAddedNotification,
26725 }).annotate({ title: "Item/reasoning/summaryPartAddedNotification" }),
26726 Schema.Struct({
26727 method: Schema.Literal("item/reasoning/textDelta").annotate({
26728 title: "Item/reasoning/textDeltaNotificationMethod",
26729 }),
26730 params: ServerNotification__ReasoningTextDeltaNotification,
26731 }).annotate({ title: "Item/reasoning/textDeltaNotification" }),
26732 Schema.Struct({
26733 method: Schema.Literal("thread/compacted").annotate({
26734 title: "Thread/compactedNotificationMethod",
26735 }),
26736 params: ServerNotification__ContextCompactedNotification,
26737 }).annotate({
26738 title: "Thread/compactedNotification",
26739 description: "Deprecated: Use `ContextCompaction` item type instead.",
26740 }),
26741 Schema.Struct({
26742 method: Schema.Literal("model/rerouted").annotate({
26743 title: "Model/reroutedNotificationMethod",
26744 }),
26745 params: ServerNotification__ModelReroutedNotification,
26746 }).annotate({ title: "Model/reroutedNotification" }),
26747 Schema.Struct({
26748 method: Schema.Literal("deprecationNotice").annotate({
26749 title: "DeprecationNoticeNotificationMethod",
26750 }),
26751 params: ServerNotification__DeprecationNoticeNotification,
26752 }).annotate({ title: "DeprecationNoticeNotification" }),
26753 Schema.Struct({
26754 method: Schema.Literal("configWarning").annotate({
26755 title: "ConfigWarningNotificationMethod",
26756 }),
26757 params: ServerNotification__ConfigWarningNotification,
26758 }).annotate({ title: "ConfigWarningNotification" }),
26759 Schema.Struct({
26760 method: Schema.Literal("fuzzyFileSearch/sessionUpdated").annotate({
26761 title: "FuzzyFileSearch/sessionUpdatedNotificationMethod",
26762 }),
26763 params: ServerNotification__FuzzyFileSearchSessionUpdatedNotification,
26764 }).annotate({ title: "FuzzyFileSearch/sessionUpdatedNotification" }),
26765 Schema.Struct({
26766 method: Schema.Literal("fuzzyFileSearch/sessionCompleted").annotate({
26767 title: "FuzzyFileSearch/sessionCompletedNotificationMethod",
26768 }),
26769 params: ServerNotification__FuzzyFileSearchSessionCompletedNotification,
26770 }).annotate({ title: "FuzzyFileSearch/sessionCompletedNotification" }),
26771 Schema.Struct({
26772 method: Schema.Literal("thread/realtime/started").annotate({
26773 title: "Thread/realtime/startedNotificationMethod",
26774 }),
26775 params: ServerNotification__ThreadRealtimeStartedNotification,
26776 }).annotate({ title: "Thread/realtime/startedNotification" }),
26777 Schema.Struct({
26778 method: Schema.Literal("thread/realtime/itemAdded").annotate({
26779 title: "Thread/realtime/itemAddedNotificationMethod",
26780 }),
26781 params: ServerNotification__ThreadRealtimeItemAddedNotification,
26782 }).annotate({ title: "Thread/realtime/itemAddedNotification" }),
26783 Schema.Struct({
26784 method: Schema.Literal("thread/realtime/transcriptUpdated").annotate({
26785 title: "Thread/realtime/transcriptUpdatedNotificationMethod",
26786 }),
26787 params: ServerNotification__ThreadRealtimeTranscriptUpdatedNotification,
26788 }).annotate({ title: "Thread/realtime/transcriptUpdatedNotification" }),
26789 Schema.Struct({
26790 method: Schema.Literal("thread/realtime/outputAudio/delta").annotate({
26791 title: "Thread/realtime/outputAudio/deltaNotificationMethod",
26792 }),
26793 params: ServerNotification__ThreadRealtimeOutputAudioDeltaNotification,
26794 }).annotate({ title: "Thread/realtime/outputAudio/deltaNotification" }),
26795 Schema.Struct({
26796 method: Schema.Literal("thread/realtime/sdp").annotate({
26797 title: "Thread/realtime/sdpNotificationMethod",
26798 }),
26799 params: ServerNotification__ThreadRealtimeSdpNotification,
26800 }).annotate({ title: "Thread/realtime/sdpNotification" }),
26801 Schema.Struct({
26802 method: Schema.Literal("thread/realtime/error").annotate({
26803 title: "Thread/realtime/errorNotificationMethod",
26804 }),
26805 params: ServerNotification__ThreadRealtimeErrorNotification,
26806 }).annotate({ title: "Thread/realtime/errorNotification" }),
26807 Schema.Struct({
26808 method: Schema.Literal("thread/realtime/closed").annotate({
26809 title: "Thread/realtime/closedNotificationMethod",
26810 }),
26811 params: ServerNotification__ThreadRealtimeClosedNotification,
26812 }).annotate({ title: "Thread/realtime/closedNotification" }),
26813 Schema.Struct({
26814 method: Schema.Literal("windows/worldWritableWarning").annotate({
26815 title: "Windows/worldWritableWarningNotificationMethod",
26816 }),
26817 params: ServerNotification__WindowsWorldWritableWarningNotification,
26818 }).annotate({
26819 title: "Windows/worldWritableWarningNotification",
26820 description:
26821 "Notifies the user of world-writable directories on Windows, which cannot be protected by the sandbox.",
26822 }),
26823 Schema.Struct({
26824 method: Schema.Literal("windowsSandbox/setupCompleted").annotate({
26825 title: "WindowsSandbox/setupCompletedNotificationMethod",
26826 }),
26827 params: ServerNotification__WindowsSandboxSetupCompletedNotification,
26828 }).annotate({ title: "WindowsSandbox/setupCompletedNotification" }),
26829 Schema.Struct({
26830 method: Schema.Literal("account/login/completed").annotate({
26831 title: "Account/login/completedNotificationMethod",
26832 }),
26833 params: ServerNotification__AccountLoginCompletedNotification,
26834 }).annotate({ title: "Account/login/completedNotification" }),
26835 ],
26836 { mode: "oneOf" },
26837).annotate({
26838 title: "ServerNotification",
26839 description: "Notification sent from the server to the client.",
26840});
26841
26842export type ServerNotification__ByteRange = { readonly end: number; readonly start: number };
26843export const ServerNotification__ByteRange = Schema.Struct({
26844 end: Schema.Number.annotate({ format: "uint" })
26845 .check(Schema.isInt())
26846 .check(Schema.isGreaterThanOrEqualTo(0)),
26847 start: Schema.Number.annotate({ format: "uint" })
26848 .check(Schema.isInt())
26849 .check(Schema.isGreaterThanOrEqualTo(0)),
26850});
26851
26852export type ServerNotification__CollabAgentTool =
26853 | "spawnAgent"
26854 | "sendInput"
26855 | "resumeAgent"
26856 | "wait"
26857 | "closeAgent";
26858export const ServerNotification__CollabAgentTool = Schema.Literals([
26859 "spawnAgent",
26860 "sendInput",
26861 "resumeAgent",
26862 "wait",
26863 "closeAgent",
26864]);
26865
26866export type ServerNotification__CollabAgentToolCallStatus = "inProgress" | "completed" | "failed";
26867export const ServerNotification__CollabAgentToolCallStatus = Schema.Literals([
26868 "inProgress",
26869 "completed",
26870 "failed",
26871]);
26872
26873export type ServerNotification__CommandExecOutputStream = "stdout" | "stderr";
26874export const ServerNotification__CommandExecOutputStream = Schema.Literals([
26875 "stdout",
26876 "stderr",
26877]).annotate({ description: "Stream label for `command/exec/outputDelta` notifications." });
26878
26879export type ServerNotification__CommandExecutionSource =
26880 | "agent"
26881 | "userShell"
26882 | "unifiedExecStartup"
26883 | "unifiedExecInteraction";
26884export const ServerNotification__CommandExecutionSource = Schema.Literals([
26885 "agent",
26886 "userShell",
26887 "unifiedExecStartup",
26888 "unifiedExecInteraction",
26889]);
26890
26891export type ServerNotification__SessionSource =
26892 | "cli"
26893 | "vscode"
26894 | "exec"
26895 | "appServer"
26896 | "unknown"
26897 | { readonly custom: string }
26898 | { readonly subAgent: ServerNotification__SubAgentSource };
26899export const ServerNotification__SessionSource = Schema.Union(
26900 [
26901 Schema.Literals(["cli", "vscode", "exec", "appServer", "unknown"]),
26902 Schema.Struct({ custom: Schema.String }).annotate({ title: "CustomSessionSource" }),
26903 Schema.Struct({ subAgent: ServerNotification__SubAgentSource }).annotate({
26904 title: "SubAgentSessionSource",
26905 }),
26906 ],
26907 { mode: "oneOf" },
26908);
26909
26910export type ServerRequest =
26911 | {
26912 readonly id: ServerRequest__RequestId;
26913 readonly method: "item/commandExecution/requestApproval";
26914 readonly params: ServerRequest__CommandExecutionRequestApprovalParams;
26915 }
26916 | {
26917 readonly id: ServerRequest__RequestId;
26918 readonly method: "item/fileChange/requestApproval";
26919 readonly params: ServerRequest__FileChangeRequestApprovalParams;
26920 }
26921 | {
26922 readonly id: ServerRequest__RequestId;
26923 readonly method: "item/tool/requestUserInput";
26924 readonly params: ServerRequest__ToolRequestUserInputParams;
26925 }
26926 | {
26927 readonly id: ServerRequest__RequestId;
26928 readonly method: "mcpServer/elicitation/request";
26929 readonly params: ServerRequest__McpServerElicitationRequestParams;
26930 }
26931 | {
26932 readonly id: ServerRequest__RequestId;
26933 readonly method: "item/permissions/requestApproval";
26934 readonly params: ServerRequest__PermissionsRequestApprovalParams;
26935 }
26936 | {
26937 readonly id: ServerRequest__RequestId;
26938 readonly method: "item/tool/call";
26939 readonly params: ServerRequest__DynamicToolCallParams;
26940 }
26941 | {
26942 readonly id: ServerRequest__RequestId;
26943 readonly method: "account/chatgptAuthTokens/refresh";
26944 readonly params: ServerRequest__ChatgptAuthTokensRefreshParams;
26945 }
26946 | {
26947 readonly id: ServerRequest__RequestId;
26948 readonly method: "applyPatchApproval";
26949 readonly params: ServerRequest__ApplyPatchApprovalParams;
26950 }
26951 | {
26952 readonly id: ServerRequest__RequestId;
26953 readonly method: "execCommandApproval";
26954 readonly params: ServerRequest__ExecCommandApprovalParams;
26955 };
26956export const ServerRequest = Schema.Union(
26957 [
26958 Schema.Struct({
26959 id: ServerRequest__RequestId,
26960 method: Schema.Literal("item/commandExecution/requestApproval").annotate({
26961 title: "Item/commandExecution/requestApprovalRequestMethod",
26962 }),
26963 params: ServerRequest__CommandExecutionRequestApprovalParams,
26964 }).annotate({
26965 title: "Item/commandExecution/requestApprovalRequest",
26966 description:
26967 "NEW APIs Sent when approval is requested for a specific command execution. This request is used for Turns started via turn/start.",
26968 }),
26969 Schema.Struct({
26970 id: ServerRequest__RequestId,
26971 method: Schema.Literal("item/fileChange/requestApproval").annotate({
26972 title: "Item/fileChange/requestApprovalRequestMethod",
26973 }),
26974 params: ServerRequest__FileChangeRequestApprovalParams,
26975 }).annotate({
26976 title: "Item/fileChange/requestApprovalRequest",
26977 description:
26978 "Sent when approval is requested for a specific file change. This request is used for Turns started via turn/start.",
26979 }),
26980 Schema.Struct({
26981 id: ServerRequest__RequestId,
26982 method: Schema.Literal("item/tool/requestUserInput").annotate({
26983 title: "Item/tool/requestUserInputRequestMethod",
26984 }),
26985 params: ServerRequest__ToolRequestUserInputParams,
26986 }).annotate({
26987 title: "Item/tool/requestUserInputRequest",
26988 description: "EXPERIMENTAL - Request input from the user for a tool call.",
26989 }),
26990 Schema.Struct({
26991 id: ServerRequest__RequestId,
26992 method: Schema.Literal("mcpServer/elicitation/request").annotate({
26993 title: "McpServer/elicitation/requestRequestMethod",
26994 }),
26995 params: ServerRequest__McpServerElicitationRequestParams,
26996 }).annotate({
26997 title: "McpServer/elicitation/requestRequest",
26998 description: "Request input for an MCP server elicitation.",
26999 }),
27000 Schema.Struct({
27001 id: ServerRequest__RequestId,
27002 method: Schema.Literal("item/permissions/requestApproval").annotate({
27003 title: "Item/permissions/requestApprovalRequestMethod",
27004 }),
27005 params: ServerRequest__PermissionsRequestApprovalParams,
27006 }).annotate({
27007 title: "Item/permissions/requestApprovalRequest",
27008 description: "Request approval for additional permissions from the user.",
27009 }),
27010 Schema.Struct({
27011 id: ServerRequest__RequestId,
27012 method: Schema.Literal("item/tool/call").annotate({ title: "Item/tool/callRequestMethod" }),
27013 params: ServerRequest__DynamicToolCallParams,
27014 }).annotate({
27015 title: "Item/tool/callRequest",
27016 description: "Execute a dynamic tool call on the client.",
27017 }),
27018 Schema.Struct({
27019 id: ServerRequest__RequestId,
27020 method: Schema.Literal("account/chatgptAuthTokens/refresh").annotate({
27021 title: "Account/chatgptAuthTokens/refreshRequestMethod",
27022 }),
27023 params: ServerRequest__ChatgptAuthTokensRefreshParams,
27024 }).annotate({ title: "Account/chatgptAuthTokens/refreshRequest" }),
27025 Schema.Struct({
27026 id: ServerRequest__RequestId,
27027 method: Schema.Literal("applyPatchApproval").annotate({
27028 title: "ApplyPatchApprovalRequestMethod",
27029 }),
27030 params: ServerRequest__ApplyPatchApprovalParams,
27031 }).annotate({
27032 title: "ApplyPatchApprovalRequest",
27033 description:
27034 "DEPRECATED APIs below Request to approve a patch. This request is used for Turns started via the legacy APIs (i.e. SendUserTurn, SendUserMessage).",
27035 }),
27036 Schema.Struct({
27037 id: ServerRequest__RequestId,
27038 method: Schema.Literal("execCommandApproval").annotate({
27039 title: "ExecCommandApprovalRequestMethod",
27040 }),
27041 params: ServerRequest__ExecCommandApprovalParams,
27042 }).annotate({
27043 title: "ExecCommandApprovalRequest",
27044 description:
27045 "Request to exec a command. This request is used for Turns started via the legacy APIs (i.e. SendUserTurn, SendUserMessage).",
27046 }),
27047 ],
27048 { mode: "oneOf" },
27049).annotate({
27050 title: "ServerRequest",
27051 description: "Request initiated from the server and sent to the client.",
27052});
27053
27054export type ServerRequest__AdditionalPermissionProfile = {
27055 readonly fileSystem?: ServerRequest__AdditionalFileSystemPermissions | null;
27056 readonly network?: ServerRequest__AdditionalNetworkPermissions | null;
27057};
27058export const ServerRequest__AdditionalPermissionProfile = Schema.Struct({
27059 fileSystem: Schema.optionalKey(
27060 Schema.Union([ServerRequest__AdditionalFileSystemPermissions, Schema.Null]),
27061 ),
27062 network: Schema.optionalKey(
27063 Schema.Union([ServerRequest__AdditionalNetworkPermissions, Schema.Null]),
27064 ),
27065});
27066
27067export type ServerRequest__CommandExecutionApprovalDecision =
27068 | "accept"
27069 | "acceptForSession"
27070 | {
27071 readonly acceptWithExecpolicyAmendment: {
27072 readonly execpolicy_amendment: ReadonlyArray<string>;
27073 };
27074 }
27075 | {
27076 readonly applyNetworkPolicyAmendment: {
27077 readonly network_policy_amendment: ServerRequest__NetworkPolicyAmendment;
27078 };
27079 }
27080 | "decline"
27081 | "cancel";
27082export const ServerRequest__CommandExecutionApprovalDecision = Schema.Union(
27083 [
27084 Schema.Literal("accept").annotate({ description: "User approved the command." }),
27085 Schema.Literal("acceptForSession").annotate({
27086 description:
27087 "User approved the command and future prompts in the same session-scoped approval cache should run without prompting.",
27088 }),
27089 Schema.Struct({
27090 acceptWithExecpolicyAmendment: Schema.Struct({
27091 execpolicy_amendment: Schema.Array(Schema.String),
27092 }),
27093 }).annotate({
27094 title: "AcceptWithExecpolicyAmendmentCommandExecutionApprovalDecision",
27095 description:
27096 "User approved the command, and wants to apply the proposed execpolicy amendment so future matching commands can run without prompting.",
27097 }),
27098 Schema.Struct({
27099 applyNetworkPolicyAmendment: Schema.Struct({
27100 network_policy_amendment: ServerRequest__NetworkPolicyAmendment,
27101 }),
27102 }).annotate({
27103 title: "ApplyNetworkPolicyAmendmentCommandExecutionApprovalDecision",
27104 description: "User chose a persistent network policy rule (allow/deny) for this host.",
27105 }),
27106 Schema.Literal("decline").annotate({
27107 description: "User denied the command. The agent will continue the turn.",
27108 }),
27109 Schema.Literal("cancel").annotate({
27110 description: "User denied the command. The turn will also be immediately interrupted.",
27111 }),
27112 ],
27113 { mode: "oneOf" },
27114);
27115
27116export type ToolRequestUserInputParams = {
27117 readonly itemId: string;
27118 readonly questions: ReadonlyArray<ToolRequestUserInputParams__ToolRequestUserInputQuestion>;
27119 readonly threadId: string;
27120 readonly turnId: string;
27121};
27122export const ToolRequestUserInputParams = Schema.Struct({
27123 itemId: Schema.String,
27124 questions: Schema.Array(ToolRequestUserInputParams__ToolRequestUserInputQuestion),
27125 threadId: Schema.String,
27126 turnId: Schema.String,
27127}).annotate({
27128 title: "ToolRequestUserInputParams",
27129 description: "EXPERIMENTAL. Params sent with a request_user_input event.",
27130});
27131
27132export type ToolRequestUserInputResponse = {
27133 readonly answers: {
27134 readonly [x: string]: ToolRequestUserInputResponse__ToolRequestUserInputAnswer;
27135 };
27136};
27137export const ToolRequestUserInputResponse = Schema.Struct({
27138 answers: Schema.Record(Schema.String, ToolRequestUserInputResponse__ToolRequestUserInputAnswer),
27139}).annotate({
27140 title: "ToolRequestUserInputResponse",
27141 description: "EXPERIMENTAL. Response payload mapping question ids to answers.",
27142});
27143
27144export type V1InitializeParams = {
27145 readonly capabilities?: V1InitializeParams__InitializeCapabilities | null;
27146 readonly clientInfo: V1InitializeParams__ClientInfo;
27147};
27148export const V1InitializeParams = Schema.Struct({
27149 capabilities: Schema.optionalKey(
27150 Schema.Union([V1InitializeParams__InitializeCapabilities, Schema.Null]),
27151 ),
27152 clientInfo: V1InitializeParams__ClientInfo,
27153}).annotate({ title: "InitializeParams" });
27154
27155export type V1InitializeResponse = {
27156 readonly codexHome: string;
27157 readonly platformFamily: string;
27158 readonly platformOs: string;
27159 readonly userAgent: string;
27160};
27161export const V1InitializeResponse = Schema.Struct({
27162 codexHome: Schema.String.annotate({
27163 description:
27164 "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.",
27165 }),
27166 platformFamily: Schema.String.annotate({
27167 description:
27168 'Platform family for the running app-server target, for example `"unix"` or `"windows"`.',
27169 }),
27170 platformOs: Schema.String.annotate({
27171 description:
27172 'Operating system for the running app-server target, for example `"macos"`, `"linux"`, or `"windows"`.',
27173 }),
27174 userAgent: Schema.String,
27175}).annotate({ title: "InitializeResponse" });
27176
27177export type V1InitializeResponse__AbsolutePathBuf = string;
27178export const V1InitializeResponse__AbsolutePathBuf = Schema.String.annotate({
27179 description:
27180 "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.",
27181});
27182
27183export type V2AccountLoginCompletedNotification = {
27184 readonly error?: string | null;
27185 readonly loginId?: string | null;
27186 readonly success: boolean;
27187};
27188export const V2AccountLoginCompletedNotification = Schema.Struct({
27189 error: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
27190 loginId: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
27191 success: Schema.Boolean,
27192}).annotate({ title: "AccountLoginCompletedNotification" });
27193
27194export type V2AccountRateLimitsUpdatedNotification = {
27195 readonly rateLimits: V2AccountRateLimitsUpdatedNotification__RateLimitSnapshot;
27196};
27197export const V2AccountRateLimitsUpdatedNotification = Schema.Struct({
27198 rateLimits: V2AccountRateLimitsUpdatedNotification__RateLimitSnapshot,
27199}).annotate({ title: "AccountRateLimitsUpdatedNotification" });
27200
27201export type V2AccountUpdatedNotification = {
27202 readonly authMode?: V2AccountUpdatedNotification__AuthMode | null;
27203 readonly planType?: V2AccountUpdatedNotification__PlanType | null;
27204};
27205export const V2AccountUpdatedNotification = Schema.Struct({
27206 authMode: Schema.optionalKey(Schema.Union([V2AccountUpdatedNotification__AuthMode, Schema.Null])),
27207 planType: Schema.optionalKey(Schema.Union([V2AccountUpdatedNotification__PlanType, Schema.Null])),
27208}).annotate({ title: "AccountUpdatedNotification" });
27209
27210export type V2AgentMessageDeltaNotification = {
27211 readonly delta: string;
27212 readonly itemId: string;
27213 readonly threadId: string;
27214 readonly turnId: string;
27215};
27216export const V2AgentMessageDeltaNotification = Schema.Struct({
27217 delta: Schema.String,
27218 itemId: Schema.String,
27219 threadId: Schema.String,
27220 turnId: Schema.String,
27221}).annotate({ title: "AgentMessageDeltaNotification" });
27222
27223export type V2AppListUpdatedNotification = {
27224 readonly data: ReadonlyArray<V2AppListUpdatedNotification__AppInfo>;
27225};
27226export const V2AppListUpdatedNotification = Schema.Struct({
27227 data: Schema.Array(V2AppListUpdatedNotification__AppInfo),
27228}).annotate({
27229 title: "AppListUpdatedNotification",
27230 description: "EXPERIMENTAL - notification emitted when the app list changes.",
27231});
27232
27233export type V2AppsListParams = {
27234 readonly cursor?: string | null;
27235 readonly forceRefetch?: boolean;
27236 readonly limit?: number | null;
27237 readonly threadId?: string | null;
27238};
27239export const V2AppsListParams = Schema.Struct({
27240 cursor: Schema.optionalKey(
27241 Schema.Union([
27242 Schema.String.annotate({
27243 description: "Opaque pagination cursor returned by a previous call.",
27244 }),
27245 Schema.Null,
27246 ]),
27247 ),
27248 forceRefetch: Schema.optionalKey(
27249 Schema.Boolean.annotate({
27250 description: "When true, bypass app caches and fetch the latest data from sources.",
27251 }),
27252 ),
27253 limit: Schema.optionalKey(
27254 Schema.Union([
27255 Schema.Number.annotate({
27256 description: "Optional page size; defaults to a reasonable server-side value.",
27257 format: "uint32",
27258 })
27259 .check(Schema.isInt())
27260 .check(Schema.isGreaterThanOrEqualTo(0)),
27261 Schema.Null,
27262 ]),
27263 ),
27264 threadId: Schema.optionalKey(
27265 Schema.Union([
27266 Schema.String.annotate({
27267 description:
27268 "Optional thread id used to evaluate app feature gating from that thread's config.",
27269 }),
27270 Schema.Null,
27271 ]),
27272 ),
27273}).annotate({
27274 title: "AppsListParams",
27275 description: "EXPERIMENTAL - list available apps/connectors.",
27276});
27277
27278export type V2AppsListResponse = {
27279 readonly data: ReadonlyArray<V2AppsListResponse__AppInfo>;
27280 readonly nextCursor?: string | null;
27281};
27282export const V2AppsListResponse = Schema.Struct({
27283 data: Schema.Array(V2AppsListResponse__AppInfo),
27284 nextCursor: Schema.optionalKey(
27285 Schema.Union([
27286 Schema.String.annotate({
27287 description:
27288 "Opaque cursor to pass to the next call to continue after the last item. If None, there are no more items to return.",
27289 }),
27290 Schema.Null,
27291 ]),
27292 ),
27293}).annotate({ title: "AppsListResponse", description: "EXPERIMENTAL - app list response." });
27294
27295export type V2CancelLoginAccountParams = { readonly loginId: string };
27296export const V2CancelLoginAccountParams = Schema.Struct({ loginId: Schema.String }).annotate({
27297 title: "CancelLoginAccountParams",
27298});
27299
27300export type V2CancelLoginAccountResponse = {
27301 readonly status: V2CancelLoginAccountResponse__CancelLoginAccountStatus;
27302};
27303export const V2CancelLoginAccountResponse = Schema.Struct({
27304 status: V2CancelLoginAccountResponse__CancelLoginAccountStatus,
27305}).annotate({ title: "CancelLoginAccountResponse" });
27306
27307export type V2CommandExecOutputDeltaNotification = {
27308 readonly capReached: boolean;
27309 readonly deltaBase64: string;
27310 readonly processId: string;
27311 readonly stream: "stdout" | "stderr";
27312};
27313export const V2CommandExecOutputDeltaNotification = Schema.Struct({
27314 capReached: Schema.Boolean.annotate({
27315 description:
27316 "`true` on the final streamed chunk for a stream when `outputBytesCap` truncated later output on that stream.",
27317 }),
27318 deltaBase64: Schema.String.annotate({ description: "Base64-encoded output bytes." }),
27319 processId: Schema.String.annotate({
27320 description:
27321 "Client-supplied, connection-scoped `processId` from the original `command/exec` request.",
27322 }),
27323 stream: Schema.Literals(["stdout", "stderr"]).annotate({
27324 description: "Stream label for `command/exec/outputDelta` notifications.",
27325 }),
27326}).annotate({
27327 title: "CommandExecOutputDeltaNotification",
27328 description:
27329 "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.",
27330});
27331
27332export type V2CommandExecOutputDeltaNotification__CommandExecOutputStream = "stdout" | "stderr";
27333export const V2CommandExecOutputDeltaNotification__CommandExecOutputStream = Schema.Literals([
27334 "stdout",
27335 "stderr",
27336]).annotate({ description: "Stream label for `command/exec/outputDelta` notifications." });
27337
27338export type V2CommandExecParams = {
27339 readonly command: ReadonlyArray<string>;
27340 readonly cwd?: string | null;
27341 readonly disableOutputCap?: boolean;
27342 readonly disableTimeout?: boolean;
27343 readonly env?: { readonly [x: string]: string | null } | null;
27344 readonly outputBytesCap?: number | null;
27345 readonly processId?: string | null;
27346 readonly sandboxPolicy?: V2CommandExecParams__SandboxPolicy | null;
27347 readonly size?: V2CommandExecParams__CommandExecTerminalSize | null;
27348 readonly streamStdin?: boolean;
27349 readonly streamStdoutStderr?: boolean;
27350 readonly timeoutMs?: number | null;
27351 readonly tty?: boolean;
27352};
27353export const V2CommandExecParams = Schema.Struct({
27354 command: Schema.Array(Schema.String).annotate({
27355 description: "Command argv vector. Empty arrays are rejected.",
27356 }),
27357 cwd: Schema.optionalKey(
27358 Schema.Union([
27359 Schema.String.annotate({
27360 description: "Optional working directory. Defaults to the server cwd.",
27361 }),
27362 Schema.Null,
27363 ]),
27364 ),
27365 disableOutputCap: Schema.optionalKey(
27366 Schema.Boolean.annotate({
27367 description:
27368 "Disable stdout/stderr capture truncation for this request.\n\nCannot be combined with `outputBytesCap`.",
27369 }),
27370 ),
27371 disableTimeout: Schema.optionalKey(
27372 Schema.Boolean.annotate({
27373 description:
27374 "Disable the timeout entirely for this request.\n\nCannot be combined with `timeoutMs`.",
27375 }),
27376 ),
27377 env: Schema.optionalKey(
27378 Schema.Union([
27379 Schema.Record(Schema.String, Schema.Union([Schema.String, Schema.Null])).annotate({
27380 description:
27381 "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.",
27382 }),
27383 Schema.Null,
27384 ]),
27385 ),
27386 outputBytesCap: Schema.optionalKey(
27387 Schema.Union([
27388 Schema.Number.annotate({
27389 description:
27390 "Optional per-stream stdout/stderr capture cap in bytes.\n\nWhen omitted, the server default applies. Cannot be combined with `disableOutputCap`.",
27391 format: "uint",
27392 })
27393 .check(Schema.isInt())
27394 .check(Schema.isGreaterThanOrEqualTo(0)),
27395 Schema.Null,
27396 ]),
27397 ),
27398 processId: Schema.optionalKey(
27399 Schema.Union([
27400 Schema.String.annotate({
27401 description:
27402 "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.",
27403 }),
27404 Schema.Null,
27405 ]),
27406 ),
27407 sandboxPolicy: Schema.optionalKey(
27408 Schema.Union([V2CommandExecParams__SandboxPolicy, Schema.Null]).annotate({
27409 description:
27410 "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.",
27411 }),
27412 ),
27413 size: Schema.optionalKey(
27414 Schema.Union([V2CommandExecParams__CommandExecTerminalSize, Schema.Null]).annotate({
27415 description: "Optional initial PTY size in character cells. Only valid when `tty` is true.",
27416 }),
27417 ),
27418 streamStdin: Schema.optionalKey(
27419 Schema.Boolean.annotate({
27420 description:
27421 "Allow follow-up `command/exec/write` requests to write stdin bytes.\n\nRequires a client-supplied `processId`.",
27422 }),
27423 ),
27424 streamStdoutStderr: Schema.optionalKey(
27425 Schema.Boolean.annotate({
27426 description:
27427 "Stream stdout/stderr via `command/exec/outputDelta` notifications.\n\nStreamed bytes are not duplicated into the final response and require a client-supplied `processId`.",
27428 }),
27429 ),
27430 timeoutMs: Schema.optionalKey(
27431 Schema.Union([
27432 Schema.Number.annotate({
27433 description:
27434 "Optional timeout in milliseconds.\n\nWhen omitted, the server default applies. Cannot be combined with `disableTimeout`.",
27435 format: "int64",
27436 }).check(Schema.isInt()),
27437 Schema.Null,
27438 ]),
27439 ),
27440 tty: Schema.optionalKey(
27441 Schema.Boolean.annotate({
27442 description: "Enable PTY mode.\n\nThis implies `streamStdin` and `streamStdoutStderr`.",
27443 }),
27444 ),
27445}).annotate({
27446 title: "CommandExecParams",
27447 description:
27448 "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.",
27449});
27450
27451export type V2CommandExecParams__NetworkAccess = "restricted" | "enabled";
27452export const V2CommandExecParams__NetworkAccess = Schema.Literals(["restricted", "enabled"]);
27453
27454export type V2CommandExecParams__ReadOnlyAccess =
27455 | {
27456 readonly includePlatformDefaults?: boolean;
27457 readonly readableRoots?: ReadonlyArray<V2CommandExecParams__AbsolutePathBuf>;
27458 readonly type: "restricted";
27459 }
27460 | { readonly type: "fullAccess" };
27461export const V2CommandExecParams__ReadOnlyAccess = Schema.Union(
27462 [
27463 Schema.Struct({
27464 includePlatformDefaults: Schema.optionalKey(Schema.Boolean.annotate({ default: true })),
27465 readableRoots: Schema.optionalKey(
27466 Schema.Array(V2CommandExecParams__AbsolutePathBuf).annotate({ default: [] }),
27467 ),
27468 type: Schema.Literal("restricted").annotate({ title: "RestrictedReadOnlyAccessType" }),
27469 }).annotate({ title: "RestrictedReadOnlyAccess" }),
27470 Schema.Struct({
27471 type: Schema.Literal("fullAccess").annotate({ title: "FullAccessReadOnlyAccessType" }),
27472 }).annotate({ title: "FullAccessReadOnlyAccess" }),
27473 ],
27474 { mode: "oneOf" },
27475);
27476
27477export type V2CommandExecResizeParams = {
27478 readonly processId: string;
27479 readonly size: { readonly cols: number; readonly rows: number };
27480};
27481export const V2CommandExecResizeParams = Schema.Struct({
27482 processId: Schema.String.annotate({
27483 description:
27484 "Client-supplied, connection-scoped `processId` from the original `command/exec` request.",
27485 }),
27486 size: Schema.Struct({
27487 cols: Schema.Number.annotate({
27488 description: "Terminal width in character cells.",
27489 format: "uint16",
27490 })
27491 .check(Schema.isInt())
27492 .check(Schema.isGreaterThanOrEqualTo(0)),
27493 rows: Schema.Number.annotate({
27494 description: "Terminal height in character cells.",
27495 format: "uint16",
27496 })
27497 .check(Schema.isInt())
27498 .check(Schema.isGreaterThanOrEqualTo(0)),
27499 }).annotate({ description: "PTY size in character cells for `command/exec` PTY sessions." }),
27500}).annotate({
27501 title: "CommandExecResizeParams",
27502 description: "Resize a running PTY-backed `command/exec` session.",
27503});
27504
27505export type V2CommandExecResizeParams__CommandExecTerminalSize = {
27506 readonly cols: number;
27507 readonly rows: number;
27508};
27509export const V2CommandExecResizeParams__CommandExecTerminalSize = Schema.Struct({
27510 cols: Schema.Number.annotate({
27511 description: "Terminal width in character cells.",
27512 format: "uint16",
27513 })
27514 .check(Schema.isInt())
27515 .check(Schema.isGreaterThanOrEqualTo(0)),
27516 rows: Schema.Number.annotate({
27517 description: "Terminal height in character cells.",
27518 format: "uint16",
27519 })
27520 .check(Schema.isInt())
27521 .check(Schema.isGreaterThanOrEqualTo(0)),
27522}).annotate({ description: "PTY size in character cells for `command/exec` PTY sessions." });
27523
27524export type V2CommandExecResizeResponse = {};
27525export const V2CommandExecResizeResponse = Schema.Struct({}).annotate({
27526 title: "CommandExecResizeResponse",
27527 description: "Empty success response for `command/exec/resize`.",
27528});
27529
27530export type V2CommandExecResponse = {
27531 readonly exitCode: number;
27532 readonly stderr: string;
27533 readonly stdout: string;
27534};
27535export const V2CommandExecResponse = Schema.Struct({
27536 exitCode: Schema.Number.annotate({ description: "Process exit code.", format: "int32" }).check(
27537 Schema.isInt(),
27538 ),
27539 stderr: Schema.String.annotate({
27540 description:
27541 "Buffered stderr capture.\n\nEmpty when stderr was streamed via `command/exec/outputDelta`.",
27542 }),
27543 stdout: Schema.String.annotate({
27544 description:
27545 "Buffered stdout capture.\n\nEmpty when stdout was streamed via `command/exec/outputDelta`.",
27546 }),
27547}).annotate({
27548 title: "CommandExecResponse",
27549 description: "Final buffered result for `command/exec`.",
27550});
27551
27552export type V2CommandExecTerminateParams = { readonly processId: string };
27553export const V2CommandExecTerminateParams = Schema.Struct({
27554 processId: Schema.String.annotate({
27555 description:
27556 "Client-supplied, connection-scoped `processId` from the original `command/exec` request.",
27557 }),
27558}).annotate({
27559 title: "CommandExecTerminateParams",
27560 description: "Terminate a running `command/exec` session.",
27561});
27562
27563export type V2CommandExecTerminateResponse = {};
27564export const V2CommandExecTerminateResponse = Schema.Struct({}).annotate({
27565 title: "CommandExecTerminateResponse",
27566 description: "Empty success response for `command/exec/terminate`.",
27567});
27568
27569export type V2CommandExecutionOutputDeltaNotification = {
27570 readonly delta: string;
27571 readonly itemId: string;
27572 readonly threadId: string;
27573 readonly turnId: string;
27574};
27575export const V2CommandExecutionOutputDeltaNotification = Schema.Struct({
27576 delta: Schema.String,
27577 itemId: Schema.String,
27578 threadId: Schema.String,
27579 turnId: Schema.String,
27580}).annotate({ title: "CommandExecutionOutputDeltaNotification" });
27581
27582export type V2CommandExecWriteParams = {
27583 readonly closeStdin?: boolean;
27584 readonly deltaBase64?: string | null;
27585 readonly processId: string;
27586};
27587export const V2CommandExecWriteParams = Schema.Struct({
27588 closeStdin: Schema.optionalKey(
27589 Schema.Boolean.annotate({
27590 description: "Close stdin after writing `deltaBase64`, if present.",
27591 }),
27592 ),
27593 deltaBase64: Schema.optionalKey(
27594 Schema.Union([
27595 Schema.String.annotate({ description: "Optional base64-encoded stdin bytes to write." }),
27596 Schema.Null,
27597 ]),
27598 ),
27599 processId: Schema.String.annotate({
27600 description:
27601 "Client-supplied, connection-scoped `processId` from the original `command/exec` request.",
27602 }),
27603}).annotate({
27604 title: "CommandExecWriteParams",
27605 description: "Write stdin bytes to a running `command/exec` session, close stdin, or both.",
27606});
27607
27608export type V2CommandExecWriteResponse = {};
27609export const V2CommandExecWriteResponse = Schema.Struct({}).annotate({
27610 title: "CommandExecWriteResponse",
27611 description: "Empty success response for `command/exec/write`.",
27612});
27613
27614export type V2ConfigBatchWriteParams = {
27615 readonly edits: ReadonlyArray<V2ConfigBatchWriteParams__ConfigEdit>;
27616 readonly expectedVersion?: string | null;
27617 readonly filePath?: string | null;
27618 readonly reloadUserConfig?: boolean;
27619};
27620export const V2ConfigBatchWriteParams = Schema.Struct({
27621 edits: Schema.Array(V2ConfigBatchWriteParams__ConfigEdit),
27622 expectedVersion: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
27623 filePath: Schema.optionalKey(
27624 Schema.Union([
27625 Schema.String.annotate({
27626 description:
27627 "Path to the config file to write; defaults to the user's `config.toml` when omitted.",
27628 }),
27629 Schema.Null,
27630 ]),
27631 ),
27632 reloadUserConfig: Schema.optionalKey(
27633 Schema.Boolean.annotate({
27634 description:
27635 "When true, hot-reload the updated user config into all loaded threads after writing.",
27636 }),
27637 ),
27638}).annotate({ title: "ConfigBatchWriteParams" });
27639
27640export type V2ConfigReadParams = { readonly cwd?: string | null; readonly includeLayers?: boolean };
27641export const V2ConfigReadParams = Schema.Struct({
27642 cwd: Schema.optionalKey(
27643 Schema.Union([
27644 Schema.String.annotate({
27645 description:
27646 "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).",
27647 }),
27648 Schema.Null,
27649 ]),
27650 ),
27651 includeLayers: Schema.optionalKey(Schema.Boolean.annotate({ default: false })),
27652}).annotate({ title: "ConfigReadParams" });
27653
27654export type V2ConfigReadResponse = {
27655 readonly config: V2ConfigReadResponse__Config;
27656 readonly layers?: ReadonlyArray<V2ConfigReadResponse__ConfigLayer> | null;
27657 readonly origins: { readonly [x: string]: V2ConfigReadResponse__ConfigLayerMetadata };
27658};
27659export const V2ConfigReadResponse = Schema.Struct({
27660 config: V2ConfigReadResponse__Config,
27661 layers: Schema.optionalKey(
27662 Schema.Union([Schema.Array(V2ConfigReadResponse__ConfigLayer), Schema.Null]),
27663 ),
27664 origins: Schema.Record(Schema.String, V2ConfigReadResponse__ConfigLayerMetadata),
27665}).annotate({ title: "ConfigReadResponse" });
27666
27667export type V2ConfigReadResponse__AppConfig = {
27668 readonly default_tools_approval_mode?: V2ConfigReadResponse__AppToolApproval | null;
27669 readonly default_tools_enabled?: boolean | null;
27670 readonly destructive_enabled?: boolean | null;
27671 readonly enabled?: boolean;
27672 readonly open_world_enabled?: boolean | null;
27673 readonly tools?: V2ConfigReadResponse__AppToolsConfig | null;
27674};
27675export const V2ConfigReadResponse__AppConfig = Schema.Struct({
27676 default_tools_approval_mode: Schema.optionalKey(
27677 Schema.Union([V2ConfigReadResponse__AppToolApproval, Schema.Null]),
27678 ),
27679 default_tools_enabled: Schema.optionalKey(Schema.Union([Schema.Boolean, Schema.Null])),
27680 destructive_enabled: Schema.optionalKey(Schema.Union([Schema.Boolean, Schema.Null])),
27681 enabled: Schema.optionalKey(Schema.Boolean.annotate({ default: true })),
27682 open_world_enabled: Schema.optionalKey(Schema.Union([Schema.Boolean, Schema.Null])),
27683 tools: Schema.optionalKey(Schema.Union([V2ConfigReadResponse__AppToolsConfig, Schema.Null])),
27684});
27685
27686export type V2ConfigReadResponse__AppsConfig = {
27687 readonly _default?: V2ConfigReadResponse__AppsDefaultConfig | null;
27688};
27689export const V2ConfigReadResponse__AppsConfig = Schema.Struct({
27690 _default: Schema.optionalKey(
27691 Schema.Union([V2ConfigReadResponse__AppsDefaultConfig, Schema.Null]),
27692 ),
27693});
27694
27695export type V2ConfigReadResponse__AppToolConfig = {
27696 readonly approval_mode?: V2ConfigReadResponse__AppToolApproval | null;
27697 readonly enabled?: boolean | null;
27698};
27699export const V2ConfigReadResponse__AppToolConfig = Schema.Struct({
27700 approval_mode: Schema.optionalKey(
27701 Schema.Union([V2ConfigReadResponse__AppToolApproval, Schema.Null]),
27702 ),
27703 enabled: Schema.optionalKey(Schema.Union([Schema.Boolean, Schema.Null])),
27704});
27705
27706export type V2ConfigRequirementsReadResponse = {
27707 readonly requirements?: V2ConfigRequirementsReadResponse__ConfigRequirements | null;
27708};
27709export const V2ConfigRequirementsReadResponse = Schema.Struct({
27710 requirements: Schema.optionalKey(
27711 Schema.Union([V2ConfigRequirementsReadResponse__ConfigRequirements, Schema.Null]).annotate({
27712 description:
27713 "Null if no requirements are configured (e.g. no requirements.toml/MDM entries).",
27714 }),
27715 ),
27716}).annotate({ title: "ConfigRequirementsReadResponse" });
27717
27718export type V2ConfigRequirementsReadResponse__ApprovalsReviewer = "user" | "guardian_subagent";
27719export const V2ConfigRequirementsReadResponse__ApprovalsReviewer = Schema.Literals([
27720 "user",
27721 "guardian_subagent",
27722]).annotate({
27723 description:
27724 "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.",
27725});
27726
27727export type V2ConfigRequirementsReadResponse__NetworkRequirements = {
27728 readonly allowLocalBinding?: boolean | null;
27729 readonly allowUnixSockets?: ReadonlyArray<string> | null;
27730 readonly allowUpstreamProxy?: boolean | null;
27731 readonly allowedDomains?: ReadonlyArray<string> | null;
27732 readonly dangerFullAccessDenylistOnly?: boolean | null;
27733 readonly dangerouslyAllowAllUnixSockets?: boolean | null;
27734 readonly dangerouslyAllowNonLoopbackProxy?: boolean | null;
27735 readonly deniedDomains?: ReadonlyArray<string> | null;
27736 readonly domains?: {
27737 readonly [x: string]: V2ConfigRequirementsReadResponse__NetworkDomainPermission;
27738 } | null;
27739 readonly enabled?: boolean | null;
27740 readonly httpPort?: number | null;
27741 readonly managedAllowedDomainsOnly?: boolean | null;
27742 readonly socksPort?: number | null;
27743 readonly unixSockets?: {
27744 readonly [x: string]: V2ConfigRequirementsReadResponse__NetworkUnixSocketPermission;
27745 } | null;
27746};
27747export const V2ConfigRequirementsReadResponse__NetworkRequirements = Schema.Struct({
27748 allowLocalBinding: Schema.optionalKey(Schema.Union([Schema.Boolean, Schema.Null])),
27749 allowUnixSockets: Schema.optionalKey(
27750 Schema.Union([
27751 Schema.Array(Schema.String).annotate({
27752 description: "Legacy compatibility view derived from `unix_sockets`.",
27753 }),
27754 Schema.Null,
27755 ]),
27756 ),
27757 allowUpstreamProxy: Schema.optionalKey(Schema.Union([Schema.Boolean, Schema.Null])),
27758 allowedDomains: Schema.optionalKey(
27759 Schema.Union([
27760 Schema.Array(Schema.String).annotate({
27761 description: "Legacy compatibility view derived from `domains`.",
27762 }),
27763 Schema.Null,
27764 ]),
27765 ),
27766 dangerFullAccessDenylistOnly: Schema.optionalKey(Schema.Union([Schema.Boolean, Schema.Null])),
27767 dangerouslyAllowAllUnixSockets: Schema.optionalKey(Schema.Union([Schema.Boolean, Schema.Null])),
27768 dangerouslyAllowNonLoopbackProxy: Schema.optionalKey(Schema.Union([Schema.Boolean, Schema.Null])),
27769 deniedDomains: Schema.optionalKey(
27770 Schema.Union([
27771 Schema.Array(Schema.String).annotate({
27772 description: "Legacy compatibility view derived from `domains`.",
27773 }),
27774 Schema.Null,
27775 ]),
27776 ),
27777 domains: Schema.optionalKey(
27778 Schema.Union([
27779 Schema.Record(
27780 Schema.String,
27781 V2ConfigRequirementsReadResponse__NetworkDomainPermission,
27782 ).annotate({ description: "Canonical network permission map for `experimental_network`." }),
27783 Schema.Null,
27784 ]),
27785 ),
27786 enabled: Schema.optionalKey(Schema.Union([Schema.Boolean, Schema.Null])),
27787 httpPort: Schema.optionalKey(
27788 Schema.Union([
27789 Schema.Number.annotate({ format: "uint16" })
27790 .check(Schema.isInt())
27791 .check(Schema.isGreaterThanOrEqualTo(0)),
27792 Schema.Null,
27793 ]),
27794 ),
27795 managedAllowedDomainsOnly: Schema.optionalKey(
27796 Schema.Union([
27797 Schema.Boolean.annotate({
27798 description:
27799 "When true, only managed allowlist entries are respected while managed network enforcement is active.",
27800 }),
27801 Schema.Null,
27802 ]),
27803 ),
27804 socksPort: Schema.optionalKey(
27805 Schema.Union([
27806 Schema.Number.annotate({ format: "uint16" })
27807 .check(Schema.isInt())
27808 .check(Schema.isGreaterThanOrEqualTo(0)),
27809 Schema.Null,
27810 ]),
27811 ),
27812 unixSockets: Schema.optionalKey(
27813 Schema.Union([
27814 Schema.Record(
27815 Schema.String,
27816 V2ConfigRequirementsReadResponse__NetworkUnixSocketPermission,
27817 ).annotate({
27818 description: "Canonical unix socket permission map for `experimental_network`.",
27819 }),
27820 Schema.Null,
27821 ]),
27822 ),
27823});
27824
27825export type V2ConfigValueWriteParams = {
27826 readonly expectedVersion?: string | null;
27827 readonly filePath?: string | null;
27828 readonly keyPath: string;
27829 readonly mergeStrategy: V2ConfigValueWriteParams__MergeStrategy;
27830 readonly value: unknown;
27831};
27832export const V2ConfigValueWriteParams = Schema.Struct({
27833 expectedVersion: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
27834 filePath: Schema.optionalKey(
27835 Schema.Union([
27836 Schema.String.annotate({
27837 description:
27838 "Path to the config file to write; defaults to the user's `config.toml` when omitted.",
27839 }),
27840 Schema.Null,
27841 ]),
27842 ),
27843 keyPath: Schema.String,
27844 mergeStrategy: V2ConfigValueWriteParams__MergeStrategy,
27845 value: Schema.Unknown,
27846}).annotate({ title: "ConfigValueWriteParams" });
27847
27848export type V2ConfigWarningNotification = {
27849 readonly details?: string | null;
27850 readonly path?: string | null;
27851 readonly range?: V2ConfigWarningNotification__TextRange | null;
27852 readonly summary: string;
27853};
27854export const V2ConfigWarningNotification = Schema.Struct({
27855 details: Schema.optionalKey(
27856 Schema.Union([
27857 Schema.String.annotate({ description: "Optional extra guidance or error details." }),
27858 Schema.Null,
27859 ]),
27860 ),
27861 path: Schema.optionalKey(
27862 Schema.Union([
27863 Schema.String.annotate({
27864 description: "Optional path to the config file that triggered the warning.",
27865 }),
27866 Schema.Null,
27867 ]),
27868 ),
27869 range: Schema.optionalKey(
27870 Schema.Union([V2ConfigWarningNotification__TextRange, Schema.Null]).annotate({
27871 description: "Optional range for the error location inside the config file.",
27872 }),
27873 ),
27874 summary: Schema.String.annotate({ description: "Concise summary of the warning." }),
27875}).annotate({ title: "ConfigWarningNotification" });
27876
27877export type V2ConfigWriteResponse = {
27878 readonly filePath: string;
27879 readonly overriddenMetadata?: V2ConfigWriteResponse__OverriddenMetadata | null;
27880 readonly status: V2ConfigWriteResponse__WriteStatus;
27881 readonly version: string;
27882};
27883export const V2ConfigWriteResponse = Schema.Struct({
27884 filePath: Schema.String.annotate({
27885 description:
27886 "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.",
27887 }),
27888 overriddenMetadata: Schema.optionalKey(
27889 Schema.Union([V2ConfigWriteResponse__OverriddenMetadata, Schema.Null]),
27890 ),
27891 status: V2ConfigWriteResponse__WriteStatus,
27892 version: Schema.String,
27893}).annotate({ title: "ConfigWriteResponse" });
27894
27895export type V2ContextCompactedNotification = { readonly threadId: string; readonly turnId: string };
27896export const V2ContextCompactedNotification = Schema.Struct({
27897 threadId: Schema.String,
27898 turnId: Schema.String,
27899}).annotate({
27900 title: "ContextCompactedNotification",
27901 description: "Deprecated: Use `ContextCompaction` item type instead.",
27902});
27903
27904export type V2DeprecationNoticeNotification = {
27905 readonly details?: string | null;
27906 readonly summary: string;
27907};
27908export const V2DeprecationNoticeNotification = Schema.Struct({
27909 details: Schema.optionalKey(
27910 Schema.Union([
27911 Schema.String.annotate({
27912 description: "Optional extra guidance, such as migration steps or rationale.",
27913 }),
27914 Schema.Null,
27915 ]),
27916 ),
27917 summary: Schema.String.annotate({ description: "Concise summary of what is deprecated." }),
27918}).annotate({ title: "DeprecationNoticeNotification" });
27919
27920export type V2ErrorNotification = {
27921 readonly error: V2ErrorNotification__TurnError;
27922 readonly threadId: string;
27923 readonly turnId: string;
27924 readonly willRetry: boolean;
27925};
27926export const V2ErrorNotification = Schema.Struct({
27927 error: V2ErrorNotification__TurnError,
27928 threadId: Schema.String,
27929 turnId: Schema.String,
27930 willRetry: Schema.Boolean,
27931}).annotate({ title: "ErrorNotification" });
27932
27933export type V2ExperimentalFeatureEnablementSetParams = {
27934 readonly enablement: { readonly [x: string]: boolean };
27935};
27936export const V2ExperimentalFeatureEnablementSetParams = Schema.Struct({
27937 enablement: Schema.Record(Schema.String, Schema.Boolean).annotate({
27938 description:
27939 "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.",
27940 }),
27941}).annotate({ title: "ExperimentalFeatureEnablementSetParams" });
27942
27943export type V2ExperimentalFeatureEnablementSetResponse = {
27944 readonly enablement: { readonly [x: string]: boolean };
27945};
27946export const V2ExperimentalFeatureEnablementSetResponse = Schema.Struct({
27947 enablement: Schema.Record(Schema.String, Schema.Boolean).annotate({
27948 description: "Feature enablement entries updated by this request.",
27949 }),
27950}).annotate({ title: "ExperimentalFeatureEnablementSetResponse" });
27951
27952export type V2ExperimentalFeatureListParams = {
27953 readonly cursor?: string | null;
27954 readonly limit?: number | null;
27955};
27956export const V2ExperimentalFeatureListParams = Schema.Struct({
27957 cursor: Schema.optionalKey(
27958 Schema.Union([
27959 Schema.String.annotate({
27960 description: "Opaque pagination cursor returned by a previous call.",
27961 }),
27962 Schema.Null,
27963 ]),
27964 ),
27965 limit: Schema.optionalKey(
27966 Schema.Union([
27967 Schema.Number.annotate({
27968 description: "Optional page size; defaults to a reasonable server-side value.",
27969 format: "uint32",
27970 })
27971 .check(Schema.isInt())
27972 .check(Schema.isGreaterThanOrEqualTo(0)),
27973 Schema.Null,
27974 ]),
27975 ),
27976}).annotate({ title: "ExperimentalFeatureListParams" });
27977
27978export type V2ExperimentalFeatureListResponse = {
27979 readonly data: ReadonlyArray<V2ExperimentalFeatureListResponse__ExperimentalFeature>;
27980 readonly nextCursor?: string | null;
27981};
27982export const V2ExperimentalFeatureListResponse = Schema.Struct({
27983 data: Schema.Array(V2ExperimentalFeatureListResponse__ExperimentalFeature),
27984 nextCursor: Schema.optionalKey(
27985 Schema.Union([
27986 Schema.String.annotate({
27987 description:
27988 "Opaque cursor to pass to the next call to continue after the last item. If None, there are no more items to return.",
27989 }),
27990 Schema.Null,
27991 ]),
27992 ),
27993}).annotate({ title: "ExperimentalFeatureListResponse" });
27994
27995export type V2ExperimentalFeatureListResponse__ExperimentalFeatureStage =
27996 | "beta"
27997 | "underDevelopment"
27998 | "stable"
27999 | "deprecated"
28000 | "removed";
28001export const V2ExperimentalFeatureListResponse__ExperimentalFeatureStage = Schema.Literals([
28002 "beta",
28003 "underDevelopment",
28004 "stable",
28005 "deprecated",
28006 "removed",
28007]);
28008
28009export type V2ExternalAgentConfigDetectParams = {
28010 readonly cwds?: ReadonlyArray<string> | null;
28011 readonly includeHome?: boolean;
28012};
28013export const V2ExternalAgentConfigDetectParams = Schema.Struct({
28014 cwds: Schema.optionalKey(
28015 Schema.Union([
28016 Schema.Array(Schema.String).annotate({
28017 description: "Zero or more working directories to include for repo-scoped detection.",
28018 }),
28019 Schema.Null,
28020 ]),
28021 ),
28022 includeHome: Schema.optionalKey(
28023 Schema.Boolean.annotate({
28024 description: "If true, include detection under the user's home (~/.claude, ~/.codex, etc.).",
28025 }),
28026 ),
28027}).annotate({ title: "ExternalAgentConfigDetectParams" });
28028
28029export type V2ExternalAgentConfigDetectResponse = {
28030 readonly items: ReadonlyArray<V2ExternalAgentConfigDetectResponse__ExternalAgentConfigMigrationItem>;
28031};
28032export const V2ExternalAgentConfigDetectResponse = Schema.Struct({
28033 items: Schema.Array(V2ExternalAgentConfigDetectResponse__ExternalAgentConfigMigrationItem),
28034}).annotate({ title: "ExternalAgentConfigDetectResponse" });
28035
28036export type V2ExternalAgentConfigImportParams = {
28037 readonly migrationItems: ReadonlyArray<V2ExternalAgentConfigImportParams__ExternalAgentConfigMigrationItem>;
28038};
28039export const V2ExternalAgentConfigImportParams = Schema.Struct({
28040 migrationItems: Schema.Array(V2ExternalAgentConfigImportParams__ExternalAgentConfigMigrationItem),
28041}).annotate({ title: "ExternalAgentConfigImportParams" });
28042
28043export type V2ExternalAgentConfigImportResponse = {};
28044export const V2ExternalAgentConfigImportResponse = Schema.Struct({}).annotate({
28045 title: "ExternalAgentConfigImportResponse",
28046});
28047
28048export type V2FeedbackUploadParams = {
28049 readonly classification: string;
28050 readonly extraLogFiles?: ReadonlyArray<string> | null;
28051 readonly includeLogs: boolean;
28052 readonly reason?: string | null;
28053 readonly threadId?: string | null;
28054};
28055export const V2FeedbackUploadParams = Schema.Struct({
28056 classification: Schema.String,
28057 extraLogFiles: Schema.optionalKey(Schema.Union([Schema.Array(Schema.String), Schema.Null])),
28058 includeLogs: Schema.Boolean,
28059 reason: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
28060 threadId: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
28061}).annotate({ title: "FeedbackUploadParams" });
28062
28063export type V2FeedbackUploadResponse = { readonly threadId: string };
28064export const V2FeedbackUploadResponse = Schema.Struct({ threadId: Schema.String }).annotate({
28065 title: "FeedbackUploadResponse",
28066});
28067
28068export type V2FileChangeOutputDeltaNotification = {
28069 readonly delta: string;
28070 readonly itemId: string;
28071 readonly threadId: string;
28072 readonly turnId: string;
28073};
28074export const V2FileChangeOutputDeltaNotification = Schema.Struct({
28075 delta: Schema.String,
28076 itemId: Schema.String,
28077 threadId: Schema.String,
28078 turnId: Schema.String,
28079}).annotate({ title: "FileChangeOutputDeltaNotification" });
28080
28081export type V2FsChangedNotification = {
28082 readonly changedPaths: ReadonlyArray<V2FsChangedNotification__AbsolutePathBuf>;
28083 readonly watchId: string;
28084};
28085export const V2FsChangedNotification = Schema.Struct({
28086 changedPaths: Schema.Array(V2FsChangedNotification__AbsolutePathBuf).annotate({
28087 description: "File or directory paths associated with this event.",
28088 }),
28089 watchId: Schema.String.annotate({
28090 description: "Watch identifier previously provided to `fs/watch`.",
28091 }),
28092}).annotate({
28093 title: "FsChangedNotification",
28094 description: "Filesystem watch notification emitted for `fs/watch` subscribers.",
28095});
28096
28097export type V2FsCopyParams = {
28098 readonly destinationPath: string;
28099 readonly recursive?: boolean;
28100 readonly sourcePath: string;
28101};
28102export const V2FsCopyParams = Schema.Struct({
28103 destinationPath: Schema.String.annotate({
28104 description:
28105 "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.",
28106 }),
28107 recursive: Schema.optionalKey(
28108 Schema.Boolean.annotate({
28109 description: "Required for directory copies; ignored for file copies.",
28110 }),
28111 ),
28112 sourcePath: Schema.String.annotate({
28113 description:
28114 "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.",
28115 }),
28116}).annotate({
28117 title: "FsCopyParams",
28118 description: "Copy a file or directory tree on the host filesystem.",
28119});
28120
28121export type V2FsCopyParams__AbsolutePathBuf = string;
28122export const V2FsCopyParams__AbsolutePathBuf = Schema.String.annotate({
28123 description:
28124 "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.",
28125});
28126
28127export type V2FsCopyResponse = {};
28128export const V2FsCopyResponse = Schema.Struct({}).annotate({
28129 title: "FsCopyResponse",
28130 description: "Successful response for `fs/copy`.",
28131});
28132
28133export type V2FsCreateDirectoryParams = {
28134 readonly path: string;
28135 readonly recursive?: boolean | null;
28136};
28137export const V2FsCreateDirectoryParams = Schema.Struct({
28138 path: Schema.String.annotate({
28139 description:
28140 "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.",
28141 }),
28142 recursive: Schema.optionalKey(
28143 Schema.Union([
28144 Schema.Boolean.annotate({
28145 description: "Whether parent directories should also be created. Defaults to `true`.",
28146 }),
28147 Schema.Null,
28148 ]),
28149 ),
28150}).annotate({
28151 title: "FsCreateDirectoryParams",
28152 description: "Create a directory on the host filesystem.",
28153});
28154
28155export type V2FsCreateDirectoryParams__AbsolutePathBuf = string;
28156export const V2FsCreateDirectoryParams__AbsolutePathBuf = Schema.String.annotate({
28157 description:
28158 "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.",
28159});
28160
28161export type V2FsCreateDirectoryResponse = {};
28162export const V2FsCreateDirectoryResponse = Schema.Struct({}).annotate({
28163 title: "FsCreateDirectoryResponse",
28164 description: "Successful response for `fs/createDirectory`.",
28165});
28166
28167export type V2FsGetMetadataParams = { readonly path: string };
28168export const V2FsGetMetadataParams = Schema.Struct({
28169 path: Schema.String.annotate({
28170 description:
28171 "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.",
28172 }),
28173}).annotate({
28174 title: "FsGetMetadataParams",
28175 description: "Request metadata for an absolute path.",
28176});
28177
28178export type V2FsGetMetadataParams__AbsolutePathBuf = string;
28179export const V2FsGetMetadataParams__AbsolutePathBuf = Schema.String.annotate({
28180 description:
28181 "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.",
28182});
28183
28184export type V2FsGetMetadataResponse = {
28185 readonly createdAtMs: number;
28186 readonly isDirectory: boolean;
28187 readonly isFile: boolean;
28188 readonly modifiedAtMs: number;
28189};
28190export const V2FsGetMetadataResponse = Schema.Struct({
28191 createdAtMs: Schema.Number.annotate({
28192 description: "File creation time in Unix milliseconds when available, otherwise `0`.",
28193 format: "int64",
28194 }).check(Schema.isInt()),
28195 isDirectory: Schema.Boolean.annotate({
28196 description: "Whether the path currently resolves to a directory.",
28197 }),
28198 isFile: Schema.Boolean.annotate({
28199 description: "Whether the path currently resolves to a regular file.",
28200 }),
28201 modifiedAtMs: Schema.Number.annotate({
28202 description: "File modification time in Unix milliseconds when available, otherwise `0`.",
28203 format: "int64",
28204 }).check(Schema.isInt()),
28205}).annotate({
28206 title: "FsGetMetadataResponse",
28207 description: "Metadata returned by `fs/getMetadata`.",
28208});
28209
28210export type V2FsReadDirectoryParams = { readonly path: string };
28211export const V2FsReadDirectoryParams = Schema.Struct({
28212 path: Schema.String.annotate({
28213 description:
28214 "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.",
28215 }),
28216}).annotate({
28217 title: "FsReadDirectoryParams",
28218 description: "List direct child names for a directory.",
28219});
28220
28221export type V2FsReadDirectoryParams__AbsolutePathBuf = string;
28222export const V2FsReadDirectoryParams__AbsolutePathBuf = Schema.String.annotate({
28223 description:
28224 "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.",
28225});
28226
28227export type V2FsReadDirectoryResponse = {
28228 readonly entries: ReadonlyArray<V2FsReadDirectoryResponse__FsReadDirectoryEntry>;
28229};
28230export const V2FsReadDirectoryResponse = Schema.Struct({
28231 entries: Schema.Array(V2FsReadDirectoryResponse__FsReadDirectoryEntry).annotate({
28232 description: "Direct child entries in the requested directory.",
28233 }),
28234}).annotate({
28235 title: "FsReadDirectoryResponse",
28236 description: "Directory entries returned by `fs/readDirectory`.",
28237});
28238
28239export type V2FsReadFileParams = { readonly path: string };
28240export const V2FsReadFileParams = Schema.Struct({
28241 path: Schema.String.annotate({
28242 description:
28243 "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.",
28244 }),
28245}).annotate({ title: "FsReadFileParams", description: "Read a file from the host filesystem." });
28246
28247export type V2FsReadFileParams__AbsolutePathBuf = string;
28248export const V2FsReadFileParams__AbsolutePathBuf = Schema.String.annotate({
28249 description:
28250 "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.",
28251});
28252
28253export type V2FsReadFileResponse = { readonly dataBase64: string };
28254export const V2FsReadFileResponse = Schema.Struct({
28255 dataBase64: Schema.String.annotate({ description: "File contents encoded as base64." }),
28256}).annotate({
28257 title: "FsReadFileResponse",
28258 description: "Base64-encoded file contents returned by `fs/readFile`.",
28259});
28260
28261export type V2FsRemoveParams = {
28262 readonly force?: boolean | null;
28263 readonly path: string;
28264 readonly recursive?: boolean | null;
28265};
28266export const V2FsRemoveParams = Schema.Struct({
28267 force: Schema.optionalKey(
28268 Schema.Union([
28269 Schema.Boolean.annotate({
28270 description: "Whether missing paths should be ignored. Defaults to `true`.",
28271 }),
28272 Schema.Null,
28273 ]),
28274 ),
28275 path: Schema.String.annotate({
28276 description:
28277 "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.",
28278 }),
28279 recursive: Schema.optionalKey(
28280 Schema.Union([
28281 Schema.Boolean.annotate({
28282 description: "Whether directory removal should recurse. Defaults to `true`.",
28283 }),
28284 Schema.Null,
28285 ]),
28286 ),
28287}).annotate({
28288 title: "FsRemoveParams",
28289 description: "Remove a file or directory tree from the host filesystem.",
28290});
28291
28292export type V2FsRemoveParams__AbsolutePathBuf = string;
28293export const V2FsRemoveParams__AbsolutePathBuf = Schema.String.annotate({
28294 description:
28295 "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.",
28296});
28297
28298export type V2FsRemoveResponse = {};
28299export const V2FsRemoveResponse = Schema.Struct({}).annotate({
28300 title: "FsRemoveResponse",
28301 description: "Successful response for `fs/remove`.",
28302});
28303
28304export type V2FsUnwatchParams = { readonly watchId: string };
28305export const V2FsUnwatchParams = Schema.Struct({
28306 watchId: Schema.String.annotate({
28307 description: "Watch identifier previously provided to `fs/watch`.",
28308 }),
28309}).annotate({
28310 title: "FsUnwatchParams",
28311 description: "Stop filesystem watch notifications for a prior `fs/watch`.",
28312});
28313
28314export type V2FsUnwatchResponse = {};
28315export const V2FsUnwatchResponse = Schema.Struct({}).annotate({
28316 title: "FsUnwatchResponse",
28317 description: "Successful response for `fs/unwatch`.",
28318});
28319
28320export type V2FsWatchParams = { readonly path: string; readonly watchId: string };
28321export const V2FsWatchParams = Schema.Struct({
28322 path: Schema.String.annotate({
28323 description:
28324 "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.",
28325 }),
28326 watchId: Schema.String.annotate({
28327 description: "Connection-scoped watch identifier used for `fs/unwatch` and `fs/changed`.",
28328 }),
28329}).annotate({
28330 title: "FsWatchParams",
28331 description: "Start filesystem watch notifications for an absolute path.",
28332});
28333
28334export type V2FsWatchParams__AbsolutePathBuf = string;
28335export const V2FsWatchParams__AbsolutePathBuf = Schema.String.annotate({
28336 description:
28337 "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.",
28338});
28339
28340export type V2FsWatchResponse = { readonly path: string };
28341export const V2FsWatchResponse = Schema.Struct({
28342 path: Schema.String.annotate({
28343 description:
28344 "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.",
28345 }),
28346}).annotate({ title: "FsWatchResponse", description: "Successful response for `fs/watch`." });
28347
28348export type V2FsWatchResponse__AbsolutePathBuf = string;
28349export const V2FsWatchResponse__AbsolutePathBuf = Schema.String.annotate({
28350 description:
28351 "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.",
28352});
28353
28354export type V2FsWriteFileParams = { readonly dataBase64: string; readonly path: string };
28355export const V2FsWriteFileParams = Schema.Struct({
28356 dataBase64: Schema.String.annotate({ description: "File contents encoded as base64." }),
28357 path: Schema.String.annotate({
28358 description:
28359 "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.",
28360 }),
28361}).annotate({ title: "FsWriteFileParams", description: "Write a file on the host filesystem." });
28362
28363export type V2FsWriteFileParams__AbsolutePathBuf = string;
28364export const V2FsWriteFileParams__AbsolutePathBuf = Schema.String.annotate({
28365 description:
28366 "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.",
28367});
28368
28369export type V2FsWriteFileResponse = {};
28370export const V2FsWriteFileResponse = Schema.Struct({}).annotate({
28371 title: "FsWriteFileResponse",
28372 description: "Successful response for `fs/writeFile`.",
28373});
28374
28375export type V2GetAccountParams = { readonly refreshToken?: boolean };
28376export const V2GetAccountParams = Schema.Struct({
28377 refreshToken: Schema.optionalKey(
28378 Schema.Boolean.annotate({
28379 description:
28380 "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`.",
28381 default: false,
28382 }),
28383 ),
28384}).annotate({ title: "GetAccountParams" });
28385
28386export type V2GetAccountRateLimitsResponse = {
28387 readonly rateLimits: {
28388 readonly credits?: V2GetAccountRateLimitsResponse__CreditsSnapshot | null;
28389 readonly limitId?: string | null;
28390 readonly limitName?: string | null;
28391 readonly planType?: V2GetAccountRateLimitsResponse__PlanType | null;
28392 readonly primary?: V2GetAccountRateLimitsResponse__RateLimitWindow | null;
28393 readonly secondary?: V2GetAccountRateLimitsResponse__RateLimitWindow | null;
28394 };
28395 readonly rateLimitsByLimitId?: {
28396 readonly [x: string]: V2GetAccountRateLimitsResponse__RateLimitSnapshot;
28397 } | null;
28398};
28399export const V2GetAccountRateLimitsResponse = Schema.Struct({
28400 rateLimits: Schema.Struct({
28401 credits: Schema.optionalKey(
28402 Schema.Union([V2GetAccountRateLimitsResponse__CreditsSnapshot, Schema.Null]),
28403 ),
28404 limitId: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
28405 limitName: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
28406 planType: Schema.optionalKey(
28407 Schema.Union([V2GetAccountRateLimitsResponse__PlanType, Schema.Null]),
28408 ),
28409 primary: Schema.optionalKey(
28410 Schema.Union([V2GetAccountRateLimitsResponse__RateLimitWindow, Schema.Null]),
28411 ),
28412 secondary: Schema.optionalKey(
28413 Schema.Union([V2GetAccountRateLimitsResponse__RateLimitWindow, Schema.Null]),
28414 ),
28415 }).annotate({
28416 description: "Backward-compatible single-bucket view; mirrors the historical payload.",
28417 }),
28418 rateLimitsByLimitId: Schema.optionalKey(
28419 Schema.Union([
28420 Schema.Record(Schema.String, V2GetAccountRateLimitsResponse__RateLimitSnapshot).annotate({
28421 description: "Multi-bucket view keyed by metered `limit_id` (for example, `codex`).",
28422 }),
28423 Schema.Null,
28424 ]),
28425 ),
28426}).annotate({ title: "GetAccountRateLimitsResponse" });
28427
28428export type V2GetAccountResponse = {
28429 readonly account?: V2GetAccountResponse__Account | null;
28430 readonly requiresOpenaiAuth: boolean;
28431};
28432export const V2GetAccountResponse = Schema.Struct({
28433 account: Schema.optionalKey(Schema.Union([V2GetAccountResponse__Account, Schema.Null])),
28434 requiresOpenaiAuth: Schema.Boolean,
28435}).annotate({ title: "GetAccountResponse" });
28436
28437export type V2HookCompletedNotification = {
28438 readonly run: V2HookCompletedNotification__HookRunSummary;
28439 readonly threadId: string;
28440 readonly turnId?: string | null;
28441};
28442export const V2HookCompletedNotification = Schema.Struct({
28443 run: V2HookCompletedNotification__HookRunSummary,
28444 threadId: Schema.String,
28445 turnId: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
28446}).annotate({ title: "HookCompletedNotification" });
28447
28448export type V2HookStartedNotification = {
28449 readonly run: V2HookStartedNotification__HookRunSummary;
28450 readonly threadId: string;
28451 readonly turnId?: string | null;
28452};
28453export const V2HookStartedNotification = Schema.Struct({
28454 run: V2HookStartedNotification__HookRunSummary,
28455 threadId: Schema.String,
28456 turnId: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
28457}).annotate({ title: "HookStartedNotification" });
28458
28459export type V2ItemCompletedNotification = {
28460 readonly item: V2ItemCompletedNotification__ThreadItem;
28461 readonly threadId: string;
28462 readonly turnId: string;
28463};
28464export const V2ItemCompletedNotification = Schema.Struct({
28465 item: V2ItemCompletedNotification__ThreadItem,
28466 threadId: Schema.String,
28467 turnId: Schema.String,
28468}).annotate({ title: "ItemCompletedNotification" });
28469
28470export type V2ItemCompletedNotification__ByteRange = {
28471 readonly end: number;
28472 readonly start: number;
28473};
28474export const V2ItemCompletedNotification__ByteRange = Schema.Struct({
28475 end: Schema.Number.annotate({ format: "uint" })
28476 .check(Schema.isInt())
28477 .check(Schema.isGreaterThanOrEqualTo(0)),
28478 start: Schema.Number.annotate({ format: "uint" })
28479 .check(Schema.isInt())
28480 .check(Schema.isGreaterThanOrEqualTo(0)),
28481});
28482
28483export type V2ItemCompletedNotification__CollabAgentTool =
28484 | "spawnAgent"
28485 | "sendInput"
28486 | "resumeAgent"
28487 | "wait"
28488 | "closeAgent";
28489export const V2ItemCompletedNotification__CollabAgentTool = Schema.Literals([
28490 "spawnAgent",
28491 "sendInput",
28492 "resumeAgent",
28493 "wait",
28494 "closeAgent",
28495]);
28496
28497export type V2ItemCompletedNotification__CollabAgentToolCallStatus =
28498 | "inProgress"
28499 | "completed"
28500 | "failed";
28501export const V2ItemCompletedNotification__CollabAgentToolCallStatus = Schema.Literals([
28502 "inProgress",
28503 "completed",
28504 "failed",
28505]);
28506
28507export type V2ItemCompletedNotification__CommandExecutionSource =
28508 | "agent"
28509 | "userShell"
28510 | "unifiedExecStartup"
28511 | "unifiedExecInteraction";
28512export const V2ItemCompletedNotification__CommandExecutionSource = Schema.Literals([
28513 "agent",
28514 "userShell",
28515 "unifiedExecStartup",
28516 "unifiedExecInteraction",
28517]);
28518
28519export type V2ItemGuardianApprovalReviewCompletedNotification = {
28520 readonly action: V2ItemGuardianApprovalReviewCompletedNotification__GuardianApprovalReviewAction;
28521 readonly decisionSource: V2ItemGuardianApprovalReviewCompletedNotification__AutoReviewDecisionSource;
28522 readonly review: V2ItemGuardianApprovalReviewCompletedNotification__GuardianApprovalReview;
28523 readonly reviewId: string;
28524 readonly targetItemId?: string | null;
28525 readonly threadId: string;
28526 readonly turnId: string;
28527};
28528export const V2ItemGuardianApprovalReviewCompletedNotification = Schema.Struct({
28529 action: V2ItemGuardianApprovalReviewCompletedNotification__GuardianApprovalReviewAction,
28530 decisionSource: V2ItemGuardianApprovalReviewCompletedNotification__AutoReviewDecisionSource,
28531 review: V2ItemGuardianApprovalReviewCompletedNotification__GuardianApprovalReview,
28532 reviewId: Schema.String.annotate({ description: "Stable identifier for this review." }),
28533 targetItemId: Schema.optionalKey(
28534 Schema.Union([
28535 Schema.String.annotate({
28536 description:
28537 "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.",
28538 }),
28539 Schema.Null,
28540 ]),
28541 ),
28542 threadId: Schema.String,
28543 turnId: Schema.String,
28544}).annotate({
28545 title: "ItemGuardianApprovalReviewCompletedNotification",
28546 description:
28547 "[UNSTABLE] Temporary notification payload for guardian automatic approval review. This shape is expected to change soon.",
28548});
28549
28550export type V2ItemGuardianApprovalReviewStartedNotification = {
28551 readonly action: V2ItemGuardianApprovalReviewStartedNotification__GuardianApprovalReviewAction;
28552 readonly review: V2ItemGuardianApprovalReviewStartedNotification__GuardianApprovalReview;
28553 readonly reviewId: string;
28554 readonly targetItemId?: string | null;
28555 readonly threadId: string;
28556 readonly turnId: string;
28557};
28558export const V2ItemGuardianApprovalReviewStartedNotification = Schema.Struct({
28559 action: V2ItemGuardianApprovalReviewStartedNotification__GuardianApprovalReviewAction,
28560 review: V2ItemGuardianApprovalReviewStartedNotification__GuardianApprovalReview,
28561 reviewId: Schema.String.annotate({ description: "Stable identifier for this review." }),
28562 targetItemId: Schema.optionalKey(
28563 Schema.Union([
28564 Schema.String.annotate({
28565 description:
28566 "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.",
28567 }),
28568 Schema.Null,
28569 ]),
28570 ),
28571 threadId: Schema.String,
28572 turnId: Schema.String,
28573}).annotate({
28574 title: "ItemGuardianApprovalReviewStartedNotification",
28575 description:
28576 "[UNSTABLE] Temporary notification payload for guardian automatic approval review. This shape is expected to change soon.",
28577});
28578
28579export type V2ItemStartedNotification = {
28580 readonly item: V2ItemStartedNotification__ThreadItem;
28581 readonly threadId: string;
28582 readonly turnId: string;
28583};
28584export const V2ItemStartedNotification = Schema.Struct({
28585 item: V2ItemStartedNotification__ThreadItem,
28586 threadId: Schema.String,
28587 turnId: Schema.String,
28588}).annotate({ title: "ItemStartedNotification" });
28589
28590export type V2ItemStartedNotification__ByteRange = { readonly end: number; readonly start: number };
28591export const V2ItemStartedNotification__ByteRange = Schema.Struct({
28592 end: Schema.Number.annotate({ format: "uint" })
28593 .check(Schema.isInt())
28594 .check(Schema.isGreaterThanOrEqualTo(0)),
28595 start: Schema.Number.annotate({ format: "uint" })
28596 .check(Schema.isInt())
28597 .check(Schema.isGreaterThanOrEqualTo(0)),
28598});
28599
28600export type V2ItemStartedNotification__CollabAgentTool =
28601 | "spawnAgent"
28602 | "sendInput"
28603 | "resumeAgent"
28604 | "wait"
28605 | "closeAgent";
28606export const V2ItemStartedNotification__CollabAgentTool = Schema.Literals([
28607 "spawnAgent",
28608 "sendInput",
28609 "resumeAgent",
28610 "wait",
28611 "closeAgent",
28612]);
28613
28614export type V2ItemStartedNotification__CollabAgentToolCallStatus =
28615 | "inProgress"
28616 | "completed"
28617 | "failed";
28618export const V2ItemStartedNotification__CollabAgentToolCallStatus = Schema.Literals([
28619 "inProgress",
28620 "completed",
28621 "failed",
28622]);
28623
28624export type V2ItemStartedNotification__CommandExecutionSource =
28625 | "agent"
28626 | "userShell"
28627 | "unifiedExecStartup"
28628 | "unifiedExecInteraction";
28629export const V2ItemStartedNotification__CommandExecutionSource = Schema.Literals([
28630 "agent",
28631 "userShell",
28632 "unifiedExecStartup",
28633 "unifiedExecInteraction",
28634]);
28635
28636export type V2ListMcpServerStatusParams = {
28637 readonly cursor?: string | null;
28638 readonly detail?: V2ListMcpServerStatusParams__McpServerStatusDetail | null;
28639 readonly limit?: number | null;
28640};
28641export const V2ListMcpServerStatusParams = Schema.Struct({
28642 cursor: Schema.optionalKey(
28643 Schema.Union([
28644 Schema.String.annotate({
28645 description: "Opaque pagination cursor returned by a previous call.",
28646 }),
28647 Schema.Null,
28648 ]),
28649 ),
28650 detail: Schema.optionalKey(
28651 Schema.Union([V2ListMcpServerStatusParams__McpServerStatusDetail, Schema.Null]).annotate({
28652 description:
28653 "Controls how much MCP inventory data to fetch for each server. Defaults to `Full` when omitted.",
28654 }),
28655 ),
28656 limit: Schema.optionalKey(
28657 Schema.Union([
28658 Schema.Number.annotate({
28659 description: "Optional page size; defaults to a server-defined value.",
28660 format: "uint32",
28661 })
28662 .check(Schema.isInt())
28663 .check(Schema.isGreaterThanOrEqualTo(0)),
28664 Schema.Null,
28665 ]),
28666 ),
28667}).annotate({ title: "ListMcpServerStatusParams" });
28668
28669export type V2ListMcpServerStatusResponse = {
28670 readonly data: ReadonlyArray<V2ListMcpServerStatusResponse__McpServerStatus>;
28671 readonly nextCursor?: string | null;
28672};
28673export const V2ListMcpServerStatusResponse = Schema.Struct({
28674 data: Schema.Array(V2ListMcpServerStatusResponse__McpServerStatus),
28675 nextCursor: Schema.optionalKey(
28676 Schema.Union([
28677 Schema.String.annotate({
28678 description:
28679 "Opaque cursor to pass to the next call to continue after the last item. If None, there are no more items to return.",
28680 }),
28681 Schema.Null,
28682 ]),
28683 ),
28684}).annotate({ title: "ListMcpServerStatusResponse" });
28685
28686export type V2LoginAccountParams =
28687 | { readonly apiKey: string; readonly type: "apiKey" }
28688 | { readonly type: "chatgpt" }
28689 | { readonly type: "chatgptDeviceCode" }
28690 | {
28691 readonly accessToken: string;
28692 readonly chatgptAccountId: string;
28693 readonly chatgptPlanType?: string | null;
28694 readonly type: "chatgptAuthTokens";
28695 };
28696export const V2LoginAccountParams = Schema.Union(
28697 [
28698 Schema.Struct({
28699 apiKey: Schema.String,
28700 type: Schema.Literal("apiKey").annotate({ title: "ApiKeyv2::LoginAccountParamsType" }),
28701 }).annotate({ title: "ApiKeyv2::LoginAccountParams" }),
28702 Schema.Struct({
28703 type: Schema.Literal("chatgpt").annotate({ title: "Chatgptv2::LoginAccountParamsType" }),
28704 }).annotate({ title: "Chatgptv2::LoginAccountParams" }),
28705 Schema.Struct({
28706 type: Schema.Literal("chatgptDeviceCode").annotate({
28707 title: "ChatgptDeviceCodev2::LoginAccountParamsType",
28708 }),
28709 }).annotate({ title: "ChatgptDeviceCodev2::LoginAccountParams" }),
28710 Schema.Struct({
28711 accessToken: Schema.String.annotate({
28712 description:
28713 "Access token (JWT) supplied by the client. This token is used for backend API requests and email extraction.",
28714 }),
28715 chatgptAccountId: Schema.String.annotate({
28716 description: "Workspace/account identifier supplied by the client.",
28717 }),
28718 chatgptPlanType: Schema.optionalKey(
28719 Schema.Union([
28720 Schema.String.annotate({
28721 description:
28722 "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`.",
28723 }),
28724 Schema.Null,
28725 ]),
28726 ),
28727 type: Schema.Literal("chatgptAuthTokens").annotate({
28728 title: "ChatgptAuthTokensv2::LoginAccountParamsType",
28729 }),
28730 }).annotate({
28731 title: "ChatgptAuthTokensv2::LoginAccountParams",
28732 description:
28733 "[UNSTABLE] FOR OPENAI INTERNAL USE ONLY - DO NOT USE. The access token must contain the same scopes that Codex-managed ChatGPT auth tokens have.",
28734 }),
28735 ],
28736 { mode: "oneOf" },
28737).annotate({ title: "LoginAccountParams" });
28738
28739export type V2LoginAccountResponse =
28740 | { readonly type: "apiKey" }
28741 | { readonly authUrl: string; readonly loginId: string; readonly type: "chatgpt" }
28742 | {
28743 readonly loginId: string;
28744 readonly type: "chatgptDeviceCode";
28745 readonly userCode: string;
28746 readonly verificationUrl: string;
28747 }
28748 | { readonly type: "chatgptAuthTokens" };
28749export const V2LoginAccountResponse = Schema.Union(
28750 [
28751 Schema.Struct({
28752 type: Schema.Literal("apiKey").annotate({ title: "ApiKeyv2::LoginAccountResponseType" }),
28753 }).annotate({ title: "ApiKeyv2::LoginAccountResponse" }),
28754 Schema.Struct({
28755 authUrl: Schema.String.annotate({
28756 description: "URL the client should open in a browser to initiate the OAuth flow.",
28757 }),
28758 loginId: Schema.String,
28759 type: Schema.Literal("chatgpt").annotate({ title: "Chatgptv2::LoginAccountResponseType" }),
28760 }).annotate({ title: "Chatgptv2::LoginAccountResponse" }),
28761 Schema.Struct({
28762 loginId: Schema.String,
28763 type: Schema.Literal("chatgptDeviceCode").annotate({
28764 title: "ChatgptDeviceCodev2::LoginAccountResponseType",
28765 }),
28766 userCode: Schema.String.annotate({
28767 description: "One-time code the user must enter after signing in.",
28768 }),
28769 verificationUrl: Schema.String.annotate({
28770 description:
28771 "URL the client should open in a browser to complete device code authorization.",
28772 }),
28773 }).annotate({ title: "ChatgptDeviceCodev2::LoginAccountResponse" }),
28774 Schema.Struct({
28775 type: Schema.Literal("chatgptAuthTokens").annotate({
28776 title: "ChatgptAuthTokensv2::LoginAccountResponseType",
28777 }),
28778 }).annotate({ title: "ChatgptAuthTokensv2::LoginAccountResponse" }),
28779 ],
28780 { mode: "oneOf" },
28781).annotate({ title: "LoginAccountResponse" });
28782
28783export type V2LogoutAccountResponse = {};
28784export const V2LogoutAccountResponse = Schema.Struct({}).annotate({
28785 title: "LogoutAccountResponse",
28786});
28787
28788export type V2McpResourceReadParams = {
28789 readonly server: string;
28790 readonly threadId: string;
28791 readonly uri: string;
28792};
28793export const V2McpResourceReadParams = Schema.Struct({
28794 server: Schema.String,
28795 threadId: Schema.String,
28796 uri: Schema.String,
28797}).annotate({ title: "McpResourceReadParams" });
28798
28799export type V2McpResourceReadResponse = {
28800 readonly contents: ReadonlyArray<V2McpResourceReadResponse__ResourceContent>;
28801};
28802export const V2McpResourceReadResponse = Schema.Struct({
28803 contents: Schema.Array(V2McpResourceReadResponse__ResourceContent),
28804}).annotate({ title: "McpResourceReadResponse" });
28805
28806export type V2McpServerOauthLoginCompletedNotification = {
28807 readonly error?: string | null;
28808 readonly name: string;
28809 readonly success: boolean;
28810};
28811export const V2McpServerOauthLoginCompletedNotification = Schema.Struct({
28812 error: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
28813 name: Schema.String,
28814 success: Schema.Boolean,
28815}).annotate({ title: "McpServerOauthLoginCompletedNotification" });
28816
28817export type V2McpServerOauthLoginParams = {
28818 readonly name: string;
28819 readonly scopes?: ReadonlyArray<string> | null;
28820 readonly timeoutSecs?: number | null;
28821};
28822export const V2McpServerOauthLoginParams = Schema.Struct({
28823 name: Schema.String,
28824 scopes: Schema.optionalKey(Schema.Union([Schema.Array(Schema.String), Schema.Null])),
28825 timeoutSecs: Schema.optionalKey(
28826 Schema.Union([Schema.Number.annotate({ format: "int64" }).check(Schema.isInt()), Schema.Null]),
28827 ),
28828}).annotate({ title: "McpServerOauthLoginParams" });
28829
28830export type V2McpServerOauthLoginResponse = { readonly authorizationUrl: string };
28831export const V2McpServerOauthLoginResponse = Schema.Struct({
28832 authorizationUrl: Schema.String,
28833}).annotate({ title: "McpServerOauthLoginResponse" });
28834
28835export type V2McpServerRefreshResponse = {};
28836export const V2McpServerRefreshResponse = Schema.Struct({}).annotate({
28837 title: "McpServerRefreshResponse",
28838});
28839
28840export type V2McpServerStatusUpdatedNotification = {
28841 readonly error?: string | null;
28842 readonly name: string;
28843 readonly status: V2McpServerStatusUpdatedNotification__McpServerStartupState;
28844};
28845export const V2McpServerStatusUpdatedNotification = Schema.Struct({
28846 error: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
28847 name: Schema.String,
28848 status: V2McpServerStatusUpdatedNotification__McpServerStartupState,
28849}).annotate({ title: "McpServerStatusUpdatedNotification" });
28850
28851export type V2McpServerToolCallParams = {
28852 readonly _meta?: unknown;
28853 readonly arguments?: unknown;
28854 readonly server: string;
28855 readonly threadId: string;
28856 readonly tool: string;
28857};
28858export const V2McpServerToolCallParams = Schema.Struct({
28859 _meta: Schema.optionalKey(Schema.Unknown),
28860 arguments: Schema.optionalKey(Schema.Unknown),
28861 server: Schema.String,
28862 threadId: Schema.String,
28863 tool: Schema.String,
28864}).annotate({ title: "McpServerToolCallParams" });
28865
28866export type V2McpServerToolCallResponse = {
28867 readonly _meta?: unknown;
28868 readonly content: ReadonlyArray<unknown>;
28869 readonly isError?: boolean | null;
28870 readonly structuredContent?: unknown;
28871};
28872export const V2McpServerToolCallResponse = Schema.Struct({
28873 _meta: Schema.optionalKey(Schema.Unknown),
28874 content: Schema.Array(Schema.Unknown),
28875 isError: Schema.optionalKey(Schema.Union([Schema.Boolean, Schema.Null])),
28876 structuredContent: Schema.optionalKey(Schema.Unknown),
28877}).annotate({ title: "McpServerToolCallResponse" });
28878
28879export type V2McpToolCallProgressNotification = {
28880 readonly itemId: string;
28881 readonly message: string;
28882 readonly threadId: string;
28883 readonly turnId: string;
28884};
28885export const V2McpToolCallProgressNotification = Schema.Struct({
28886 itemId: Schema.String,
28887 message: Schema.String,
28888 threadId: Schema.String,
28889 turnId: Schema.String,
28890}).annotate({ title: "McpToolCallProgressNotification" });
28891
28892export type V2ModelListParams = {
28893 readonly cursor?: string | null;
28894 readonly includeHidden?: boolean | null;
28895 readonly limit?: number | null;
28896};
28897export const V2ModelListParams = Schema.Struct({
28898 cursor: Schema.optionalKey(
28899 Schema.Union([
28900 Schema.String.annotate({
28901 description: "Opaque pagination cursor returned by a previous call.",
28902 }),
28903 Schema.Null,
28904 ]),
28905 ),
28906 includeHidden: Schema.optionalKey(
28907 Schema.Union([
28908 Schema.Boolean.annotate({
28909 description: "When true, include models that are hidden from the default picker list.",
28910 }),
28911 Schema.Null,
28912 ]),
28913 ),
28914 limit: Schema.optionalKey(
28915 Schema.Union([
28916 Schema.Number.annotate({
28917 description: "Optional page size; defaults to a reasonable server-side value.",
28918 format: "uint32",
28919 })
28920 .check(Schema.isInt())
28921 .check(Schema.isGreaterThanOrEqualTo(0)),
28922 Schema.Null,
28923 ]),
28924 ),
28925}).annotate({ title: "ModelListParams" });
28926
28927export type V2ModelListResponse = {
28928 readonly data: ReadonlyArray<V2ModelListResponse__Model>;
28929 readonly nextCursor?: string | null;
28930};
28931export const V2ModelListResponse = Schema.Struct({
28932 data: Schema.Array(V2ModelListResponse__Model),
28933 nextCursor: Schema.optionalKey(
28934 Schema.Union([
28935 Schema.String.annotate({
28936 description:
28937 "Opaque cursor to pass to the next call to continue after the last item. If None, there are no more items to return.",
28938 }),
28939 Schema.Null,
28940 ]),
28941 ),
28942}).annotate({ title: "ModelListResponse" });
28943
28944export type V2ModelReroutedNotification = {
28945 readonly fromModel: string;
28946 readonly reason: V2ModelReroutedNotification__ModelRerouteReason;
28947 readonly threadId: string;
28948 readonly toModel: string;
28949 readonly turnId: string;
28950};
28951export const V2ModelReroutedNotification = Schema.Struct({
28952 fromModel: Schema.String,
28953 reason: V2ModelReroutedNotification__ModelRerouteReason,
28954 threadId: Schema.String,
28955 toModel: Schema.String,
28956 turnId: Schema.String,
28957}).annotate({ title: "ModelReroutedNotification" });
28958
28959export type V2PlanDeltaNotification = {
28960 readonly delta: string;
28961 readonly itemId: string;
28962 readonly threadId: string;
28963 readonly turnId: string;
28964};
28965export const V2PlanDeltaNotification = Schema.Struct({
28966 delta: Schema.String,
28967 itemId: Schema.String,
28968 threadId: Schema.String,
28969 turnId: Schema.String,
28970}).annotate({
28971 title: "PlanDeltaNotification",
28972 description:
28973 "EXPERIMENTAL - proposed plan streaming deltas for plan items. Clients should not assume concatenated deltas match the completed plan item content.",
28974});
28975
28976export type V2PluginInstallParams = {
28977 readonly forceRemoteSync?: boolean;
28978 readonly marketplacePath: V2PluginInstallParams__AbsolutePathBuf;
28979 readonly pluginName: string;
28980};
28981export const V2PluginInstallParams = Schema.Struct({
28982 forceRemoteSync: Schema.optionalKey(
28983 Schema.Boolean.annotate({
28984 description: "When true, apply the remote plugin change before the local install flow.",
28985 }),
28986 ),
28987 marketplacePath: V2PluginInstallParams__AbsolutePathBuf,
28988 pluginName: Schema.String,
28989}).annotate({ title: "PluginInstallParams" });
28990
28991export type V2PluginInstallResponse = {
28992 readonly appsNeedingAuth: ReadonlyArray<V2PluginInstallResponse__AppSummary>;
28993 readonly authPolicy: V2PluginInstallResponse__PluginAuthPolicy;
28994};
28995export const V2PluginInstallResponse = Schema.Struct({
28996 appsNeedingAuth: Schema.Array(V2PluginInstallResponse__AppSummary),
28997 authPolicy: V2PluginInstallResponse__PluginAuthPolicy,
28998}).annotate({ title: "PluginInstallResponse" });
28999
29000export type V2PluginListParams = {
29001 readonly cwds?: ReadonlyArray<V2PluginListParams__AbsolutePathBuf> | null;
29002 readonly forceRemoteSync?: boolean;
29003};
29004export const V2PluginListParams = Schema.Struct({
29005 cwds: Schema.optionalKey(
29006 Schema.Union([
29007 Schema.Array(V2PluginListParams__AbsolutePathBuf).annotate({
29008 description:
29009 "Optional working directories used to discover repo marketplaces. When omitted, only home-scoped marketplaces and the official curated marketplace are considered.",
29010 }),
29011 Schema.Null,
29012 ]),
29013 ),
29014 forceRemoteSync: Schema.optionalKey(
29015 Schema.Boolean.annotate({
29016 description:
29017 "When true, reconcile the official curated marketplace against the remote plugin state before listing marketplaces.",
29018 }),
29019 ),
29020}).annotate({ title: "PluginListParams" });
29021
29022export type V2PluginListResponse = {
29023 readonly featuredPluginIds?: ReadonlyArray<string>;
29024 readonly marketplaceLoadErrors?: ReadonlyArray<V2PluginListResponse__MarketplaceLoadErrorInfo>;
29025 readonly marketplaces: ReadonlyArray<V2PluginListResponse__PluginMarketplaceEntry>;
29026 readonly remoteSyncError?: string | null;
29027};
29028export const V2PluginListResponse = Schema.Struct({
29029 featuredPluginIds: Schema.optionalKey(Schema.Array(Schema.String).annotate({ default: [] })),
29030 marketplaceLoadErrors: Schema.optionalKey(
29031 Schema.Array(V2PluginListResponse__MarketplaceLoadErrorInfo).annotate({ default: [] }),
29032 ),
29033 marketplaces: Schema.Array(V2PluginListResponse__PluginMarketplaceEntry),
29034 remoteSyncError: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
29035}).annotate({ title: "PluginListResponse" });
29036
29037export type V2PluginReadParams = {
29038 readonly marketplacePath: V2PluginReadParams__AbsolutePathBuf;
29039 readonly pluginName: string;
29040};
29041export const V2PluginReadParams = Schema.Struct({
29042 marketplacePath: V2PluginReadParams__AbsolutePathBuf,
29043 pluginName: Schema.String,
29044}).annotate({ title: "PluginReadParams" });
29045
29046export type V2PluginReadResponse = { readonly plugin: V2PluginReadResponse__PluginDetail };
29047export const V2PluginReadResponse = Schema.Struct({
29048 plugin: V2PluginReadResponse__PluginDetail,
29049}).annotate({ title: "PluginReadResponse" });
29050
29051export type V2PluginUninstallParams = {
29052 readonly forceRemoteSync?: boolean;
29053 readonly pluginId: string;
29054};
29055export const V2PluginUninstallParams = Schema.Struct({
29056 forceRemoteSync: Schema.optionalKey(
29057 Schema.Boolean.annotate({
29058 description: "When true, apply the remote plugin change before the local uninstall flow.",
29059 }),
29060 ),
29061 pluginId: Schema.String,
29062}).annotate({ title: "PluginUninstallParams" });
29063
29064export type V2PluginUninstallResponse = {};
29065export const V2PluginUninstallResponse = Schema.Struct({}).annotate({
29066 title: "PluginUninstallResponse",
29067});
29068
29069export type V2RawResponseItemCompletedNotification = {
29070 readonly item: V2RawResponseItemCompletedNotification__ResponseItem;
29071 readonly threadId: string;
29072 readonly turnId: string;
29073};
29074export const V2RawResponseItemCompletedNotification = Schema.Struct({
29075 item: V2RawResponseItemCompletedNotification__ResponseItem,
29076 threadId: Schema.String,
29077 turnId: Schema.String,
29078}).annotate({ title: "RawResponseItemCompletedNotification" });
29079
29080export type V2ReasoningSummaryPartAddedNotification = {
29081 readonly itemId: string;
29082 readonly summaryIndex: number;
29083 readonly threadId: string;
29084 readonly turnId: string;
29085};
29086export const V2ReasoningSummaryPartAddedNotification = Schema.Struct({
29087 itemId: Schema.String,
29088 summaryIndex: Schema.Number.annotate({ format: "int64" }).check(Schema.isInt()),
29089 threadId: Schema.String,
29090 turnId: Schema.String,
29091}).annotate({ title: "ReasoningSummaryPartAddedNotification" });
29092
29093export type V2ReasoningSummaryTextDeltaNotification = {
29094 readonly delta: string;
29095 readonly itemId: string;
29096 readonly summaryIndex: number;
29097 readonly threadId: string;
29098 readonly turnId: string;
29099};
29100export const V2ReasoningSummaryTextDeltaNotification = Schema.Struct({
29101 delta: Schema.String,
29102 itemId: Schema.String,
29103 summaryIndex: Schema.Number.annotate({ format: "int64" }).check(Schema.isInt()),
29104 threadId: Schema.String,
29105 turnId: Schema.String,
29106}).annotate({ title: "ReasoningSummaryTextDeltaNotification" });
29107
29108export type V2ReasoningTextDeltaNotification = {
29109 readonly contentIndex: number;
29110 readonly delta: string;
29111 readonly itemId: string;
29112 readonly threadId: string;
29113 readonly turnId: string;
29114};
29115export const V2ReasoningTextDeltaNotification = Schema.Struct({
29116 contentIndex: Schema.Number.annotate({ format: "int64" }).check(Schema.isInt()),
29117 delta: Schema.String,
29118 itemId: Schema.String,
29119 threadId: Schema.String,
29120 turnId: Schema.String,
29121}).annotate({ title: "ReasoningTextDeltaNotification" });
29122
29123export type V2ReviewStartParams = {
29124 readonly delivery?: V2ReviewStartParams__ReviewDelivery | null;
29125 readonly target: V2ReviewStartParams__ReviewTarget;
29126 readonly threadId: string;
29127};
29128export const V2ReviewStartParams = Schema.Struct({
29129 delivery: Schema.optionalKey(
29130 Schema.Union([V2ReviewStartParams__ReviewDelivery, Schema.Null]).annotate({
29131 description:
29132 "Where to run the review: inline (default) on the current thread or detached on a new thread (returned in `reviewThreadId`).",
29133 }),
29134 ),
29135 target: V2ReviewStartParams__ReviewTarget,
29136 threadId: Schema.String,
29137}).annotate({ title: "ReviewStartParams" });
29138
29139export type V2ReviewStartResponse = {
29140 readonly reviewThreadId: string;
29141 readonly turn: V2ReviewStartResponse__Turn;
29142};
29143export const V2ReviewStartResponse = Schema.Struct({
29144 reviewThreadId: Schema.String.annotate({
29145 description:
29146 "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.",
29147 }),
29148 turn: V2ReviewStartResponse__Turn,
29149}).annotate({ title: "ReviewStartResponse" });
29150
29151export type V2ReviewStartResponse__ByteRange = { readonly end: number; readonly start: number };
29152export const V2ReviewStartResponse__ByteRange = Schema.Struct({
29153 end: Schema.Number.annotate({ format: "uint" })
29154 .check(Schema.isInt())
29155 .check(Schema.isGreaterThanOrEqualTo(0)),
29156 start: Schema.Number.annotate({ format: "uint" })
29157 .check(Schema.isInt())
29158 .check(Schema.isGreaterThanOrEqualTo(0)),
29159});
29160
29161export type V2ReviewStartResponse__CollabAgentTool =
29162 | "spawnAgent"
29163 | "sendInput"
29164 | "resumeAgent"
29165 | "wait"
29166 | "closeAgent";
29167export const V2ReviewStartResponse__CollabAgentTool = Schema.Literals([
29168 "spawnAgent",
29169 "sendInput",
29170 "resumeAgent",
29171 "wait",
29172 "closeAgent",
29173]);
29174
29175export type V2ReviewStartResponse__CollabAgentToolCallStatus =
29176 | "inProgress"
29177 | "completed"
29178 | "failed";
29179export const V2ReviewStartResponse__CollabAgentToolCallStatus = Schema.Literals([
29180 "inProgress",
29181 "completed",
29182 "failed",
29183]);
29184
29185export type V2ReviewStartResponse__CommandExecutionSource =
29186 | "agent"
29187 | "userShell"
29188 | "unifiedExecStartup"
29189 | "unifiedExecInteraction";
29190export const V2ReviewStartResponse__CommandExecutionSource = Schema.Literals([
29191 "agent",
29192 "userShell",
29193 "unifiedExecStartup",
29194 "unifiedExecInteraction",
29195]);
29196
29197export type V2ServerRequestResolvedNotification = {
29198 readonly requestId: V2ServerRequestResolvedNotification__RequestId;
29199 readonly threadId: string;
29200};
29201export const V2ServerRequestResolvedNotification = Schema.Struct({
29202 requestId: V2ServerRequestResolvedNotification__RequestId,
29203 threadId: Schema.String,
29204}).annotate({ title: "ServerRequestResolvedNotification" });
29205
29206export type V2SkillsChangedNotification = {};
29207export const V2SkillsChangedNotification = Schema.Struct({}).annotate({
29208 title: "SkillsChangedNotification",
29209 description:
29210 "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.",
29211});
29212
29213export type V2SkillsConfigWriteParams = {
29214 readonly enabled: boolean;
29215 readonly name?: string | null;
29216 readonly path?: V2SkillsConfigWriteParams__AbsolutePathBuf | null;
29217};
29218export const V2SkillsConfigWriteParams = Schema.Struct({
29219 enabled: Schema.Boolean,
29220 name: Schema.optionalKey(
29221 Schema.Union([Schema.String.annotate({ description: "Name-based selector." }), Schema.Null]),
29222 ),
29223 path: Schema.optionalKey(
29224 Schema.Union([V2SkillsConfigWriteParams__AbsolutePathBuf, Schema.Null]).annotate({
29225 description: "Path-based selector.",
29226 }),
29227 ),
29228}).annotate({ title: "SkillsConfigWriteParams" });
29229
29230export type V2SkillsConfigWriteResponse = { readonly effectiveEnabled: boolean };
29231export const V2SkillsConfigWriteResponse = Schema.Struct({
29232 effectiveEnabled: Schema.Boolean,
29233}).annotate({ title: "SkillsConfigWriteResponse" });
29234
29235export type V2SkillsListParams = {
29236 readonly cwds?: ReadonlyArray<string>;
29237 readonly forceReload?: boolean;
29238 readonly perCwdExtraUserRoots?: ReadonlyArray<V2SkillsListParams__SkillsListExtraRootsForCwd> | null;
29239};
29240export const V2SkillsListParams = Schema.Struct({
29241 cwds: Schema.optionalKey(
29242 Schema.Array(Schema.String).annotate({
29243 description: "When empty, defaults to the current session working directory.",
29244 }),
29245 ),
29246 forceReload: Schema.optionalKey(
29247 Schema.Boolean.annotate({
29248 description: "When true, bypass the skills cache and re-scan skills from disk.",
29249 }),
29250 ),
29251 perCwdExtraUserRoots: Schema.optionalKey(
29252 Schema.Union([
29253 Schema.Array(V2SkillsListParams__SkillsListExtraRootsForCwd).annotate({
29254 description: "Optional per-cwd extra roots to scan as user-scoped skills.",
29255 }),
29256 Schema.Null,
29257 ]),
29258 ),
29259}).annotate({ title: "SkillsListParams" });
29260
29261export type V2SkillsListResponse = {
29262 readonly data: ReadonlyArray<V2SkillsListResponse__SkillsListEntry>;
29263};
29264export const V2SkillsListResponse = Schema.Struct({
29265 data: Schema.Array(V2SkillsListResponse__SkillsListEntry),
29266}).annotate({ title: "SkillsListResponse" });
29267
29268export type V2TerminalInteractionNotification = {
29269 readonly itemId: string;
29270 readonly processId: string;
29271 readonly stdin: string;
29272 readonly threadId: string;
29273 readonly turnId: string;
29274};
29275export const V2TerminalInteractionNotification = Schema.Struct({
29276 itemId: Schema.String,
29277 processId: Schema.String,
29278 stdin: Schema.String,
29279 threadId: Schema.String,
29280 turnId: Schema.String,
29281}).annotate({ title: "TerminalInteractionNotification" });
29282
29283export type V2ThreadArchivedNotification = { readonly threadId: string };
29284export const V2ThreadArchivedNotification = Schema.Struct({ threadId: Schema.String }).annotate({
29285 title: "ThreadArchivedNotification",
29286});
29287
29288export type V2ThreadArchiveParams = { readonly threadId: string };
29289export const V2ThreadArchiveParams = Schema.Struct({ threadId: Schema.String }).annotate({
29290 title: "ThreadArchiveParams",
29291});
29292
29293export type V2ThreadArchiveResponse = {};
29294export const V2ThreadArchiveResponse = Schema.Struct({}).annotate({
29295 title: "ThreadArchiveResponse",
29296});
29297
29298export type V2ThreadClosedNotification = { readonly threadId: string };
29299export const V2ThreadClosedNotification = Schema.Struct({ threadId: Schema.String }).annotate({
29300 title: "ThreadClosedNotification",
29301});
29302
29303export type V2ThreadCompactStartParams = { readonly threadId: string };
29304export const V2ThreadCompactStartParams = Schema.Struct({ threadId: Schema.String }).annotate({
29305 title: "ThreadCompactStartParams",
29306});
29307
29308export type V2ThreadCompactStartResponse = {};
29309export const V2ThreadCompactStartResponse = Schema.Struct({}).annotate({
29310 title: "ThreadCompactStartResponse",
29311});
29312
29313export type V2ThreadForkParams = {
29314 readonly approvalPolicy?: V2ThreadForkParams__AskForApproval | null;
29315 readonly approvalsReviewer?: V2ThreadForkParams__ApprovalsReviewer | null;
29316 readonly baseInstructions?: string | null;
29317 readonly config?: { readonly [x: string]: unknown } | null;
29318 readonly cwd?: string | null;
29319 readonly developerInstructions?: string | null;
29320 readonly ephemeral?: boolean;
29321 readonly model?: string | null;
29322 readonly modelProvider?: string | null;
29323 readonly sandbox?: V2ThreadForkParams__SandboxMode | null;
29324 readonly serviceTier?: V2ThreadForkParams__ServiceTier | null | null;
29325 readonly threadId: string;
29326};
29327export const V2ThreadForkParams = Schema.Struct({
29328 approvalPolicy: Schema.optionalKey(
29329 Schema.Union([V2ThreadForkParams__AskForApproval, Schema.Null]),
29330 ),
29331 approvalsReviewer: Schema.optionalKey(
29332 Schema.Union([V2ThreadForkParams__ApprovalsReviewer, Schema.Null]).annotate({
29333 description:
29334 "Override where approval requests are routed for review on this thread and subsequent turns.",
29335 }),
29336 ),
29337 baseInstructions: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
29338 config: Schema.optionalKey(
29339 Schema.Union([Schema.Record(Schema.String, Schema.Unknown), Schema.Null]),
29340 ),
29341 cwd: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
29342 developerInstructions: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
29343 ephemeral: Schema.optionalKey(Schema.Boolean),
29344 model: Schema.optionalKey(
29345 Schema.Union([
29346 Schema.String.annotate({
29347 description: "Configuration overrides for the forked thread, if any.",
29348 }),
29349 Schema.Null,
29350 ]),
29351 ),
29352 modelProvider: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
29353 sandbox: Schema.optionalKey(Schema.Union([V2ThreadForkParams__SandboxMode, Schema.Null])),
29354 serviceTier: Schema.optionalKey(
29355 Schema.Union([Schema.Union([V2ThreadForkParams__ServiceTier, Schema.Null]), Schema.Null]),
29356 ),
29357 threadId: Schema.String,
29358}).annotate({
29359 title: "ThreadForkParams",
29360 description:
29361 "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.",
29362});
29363
29364export type V2ThreadForkResponse = {
29365 readonly approvalPolicy: V2ThreadForkResponse__AskForApproval;
29366 readonly approvalsReviewer: "user" | "guardian_subagent";
29367 readonly cwd: string;
29368 readonly model: string;
29369 readonly modelProvider: string;
29370 readonly reasoningEffort?: V2ThreadForkResponse__ReasoningEffort | null;
29371 readonly sandbox: V2ThreadForkResponse__SandboxPolicy;
29372 readonly serviceTier?: V2ThreadForkResponse__ServiceTier | null;
29373 readonly thread: V2ThreadForkResponse__Thread;
29374};
29375export const V2ThreadForkResponse = Schema.Struct({
29376 approvalPolicy: V2ThreadForkResponse__AskForApproval,
29377 approvalsReviewer: Schema.Literals(["user", "guardian_subagent"]).annotate({
29378 description:
29379 "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.",
29380 }),
29381 cwd: Schema.String,
29382 model: Schema.String,
29383 modelProvider: Schema.String,
29384 reasoningEffort: Schema.optionalKey(
29385 Schema.Union([V2ThreadForkResponse__ReasoningEffort, Schema.Null]),
29386 ),
29387 sandbox: V2ThreadForkResponse__SandboxPolicy,
29388 serviceTier: Schema.optionalKey(Schema.Union([V2ThreadForkResponse__ServiceTier, Schema.Null])),
29389 thread: V2ThreadForkResponse__Thread,
29390}).annotate({ title: "ThreadForkResponse" });
29391
29392export type V2ThreadForkResponse__ApprovalsReviewer = "user" | "guardian_subagent";
29393export const V2ThreadForkResponse__ApprovalsReviewer = Schema.Literals([
29394 "user",
29395 "guardian_subagent",
29396]).annotate({
29397 description:
29398 "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.",
29399});
29400
29401export type V2ThreadForkResponse__ByteRange = { readonly end: number; readonly start: number };
29402export const V2ThreadForkResponse__ByteRange = Schema.Struct({
29403 end: Schema.Number.annotate({ format: "uint" })
29404 .check(Schema.isInt())
29405 .check(Schema.isGreaterThanOrEqualTo(0)),
29406 start: Schema.Number.annotate({ format: "uint" })
29407 .check(Schema.isInt())
29408 .check(Schema.isGreaterThanOrEqualTo(0)),
29409});
29410
29411export type V2ThreadForkResponse__CollabAgentTool =
29412 | "spawnAgent"
29413 | "sendInput"
29414 | "resumeAgent"
29415 | "wait"
29416 | "closeAgent";
29417export const V2ThreadForkResponse__CollabAgentTool = Schema.Literals([
29418 "spawnAgent",
29419 "sendInput",
29420 "resumeAgent",
29421 "wait",
29422 "closeAgent",
29423]);
29424
29425export type V2ThreadForkResponse__CollabAgentToolCallStatus = "inProgress" | "completed" | "failed";
29426export const V2ThreadForkResponse__CollabAgentToolCallStatus = Schema.Literals([
29427 "inProgress",
29428 "completed",
29429 "failed",
29430]);
29431
29432export type V2ThreadForkResponse__CommandExecutionSource =
29433 | "agent"
29434 | "userShell"
29435 | "unifiedExecStartup"
29436 | "unifiedExecInteraction";
29437export const V2ThreadForkResponse__CommandExecutionSource = Schema.Literals([
29438 "agent",
29439 "userShell",
29440 "unifiedExecStartup",
29441 "unifiedExecInteraction",
29442]);
29443
29444export type V2ThreadForkResponse__NetworkAccess = "restricted" | "enabled";
29445export const V2ThreadForkResponse__NetworkAccess = Schema.Literals(["restricted", "enabled"]);
29446
29447export type V2ThreadForkResponse__ReadOnlyAccess =
29448 | {
29449 readonly includePlatformDefaults?: boolean;
29450 readonly readableRoots?: ReadonlyArray<V2ThreadForkResponse__AbsolutePathBuf>;
29451 readonly type: "restricted";
29452 }
29453 | { readonly type: "fullAccess" };
29454export const V2ThreadForkResponse__ReadOnlyAccess = Schema.Union(
29455 [
29456 Schema.Struct({
29457 includePlatformDefaults: Schema.optionalKey(Schema.Boolean.annotate({ default: true })),
29458 readableRoots: Schema.optionalKey(
29459 Schema.Array(V2ThreadForkResponse__AbsolutePathBuf).annotate({ default: [] }),
29460 ),
29461 type: Schema.Literal("restricted").annotate({ title: "RestrictedReadOnlyAccessType" }),
29462 }).annotate({ title: "RestrictedReadOnlyAccess" }),
29463 Schema.Struct({
29464 type: Schema.Literal("fullAccess").annotate({ title: "FullAccessReadOnlyAccessType" }),
29465 }).annotate({ title: "FullAccessReadOnlyAccess" }),
29466 ],
29467 { mode: "oneOf" },
29468);
29469
29470export type V2ThreadForkResponse__SessionSource =
29471 | "cli"
29472 | "vscode"
29473 | "exec"
29474 | "appServer"
29475 | "unknown"
29476 | { readonly custom: string }
29477 | { readonly subAgent: V2ThreadForkResponse__SubAgentSource };
29478export const V2ThreadForkResponse__SessionSource = Schema.Union(
29479 [
29480 Schema.Literals(["cli", "vscode", "exec", "appServer", "unknown"]),
29481 Schema.Struct({ custom: Schema.String }).annotate({ title: "CustomSessionSource" }),
29482 Schema.Struct({ subAgent: V2ThreadForkResponse__SubAgentSource }).annotate({
29483 title: "SubAgentSessionSource",
29484 }),
29485 ],
29486 { mode: "oneOf" },
29487);
29488
29489export type V2ThreadForkResponse__ThreadStatus =
29490 | { readonly type: "notLoaded" }
29491 | { readonly type: "idle" }
29492 | { readonly type: "systemError" }
29493 | {
29494 readonly activeFlags: ReadonlyArray<V2ThreadForkResponse__ThreadActiveFlag>;
29495 readonly type: "active";
29496 };
29497export const V2ThreadForkResponse__ThreadStatus = Schema.Union(
29498 [
29499 Schema.Struct({
29500 type: Schema.Literal("notLoaded").annotate({ title: "NotLoadedThreadStatusType" }),
29501 }).annotate({ title: "NotLoadedThreadStatus" }),
29502 Schema.Struct({
29503 type: Schema.Literal("idle").annotate({ title: "IdleThreadStatusType" }),
29504 }).annotate({ title: "IdleThreadStatus" }),
29505 Schema.Struct({
29506 type: Schema.Literal("systemError").annotate({ title: "SystemErrorThreadStatusType" }),
29507 }).annotate({ title: "SystemErrorThreadStatus" }),
29508 Schema.Struct({
29509 activeFlags: Schema.Array(V2ThreadForkResponse__ThreadActiveFlag),
29510 type: Schema.Literal("active").annotate({ title: "ActiveThreadStatusType" }),
29511 }).annotate({ title: "ActiveThreadStatus" }),
29512 ],
29513 { mode: "oneOf" },
29514);
29515
29516export type V2ThreadListParams = {
29517 readonly archived?: boolean | null;
29518 readonly cursor?: string | null;
29519 readonly cwd?: string | null;
29520 readonly limit?: number | null;
29521 readonly modelProviders?: ReadonlyArray<string> | null;
29522 readonly searchTerm?: string | null;
29523 readonly sortKey?: V2ThreadListParams__ThreadSortKey | null;
29524 readonly sourceKinds?: ReadonlyArray<V2ThreadListParams__ThreadSourceKind> | null;
29525};
29526export const V2ThreadListParams = Schema.Struct({
29527 archived: Schema.optionalKey(
29528 Schema.Union([
29529 Schema.Boolean.annotate({
29530 description:
29531 "Optional archived filter; when set to true, only archived threads are returned. If false or null, only non-archived threads are returned.",
29532 }),
29533 Schema.Null,
29534 ]),
29535 ),
29536 cursor: Schema.optionalKey(
29537 Schema.Union([
29538 Schema.String.annotate({
29539 description: "Opaque pagination cursor returned by a previous call.",
29540 }),
29541 Schema.Null,
29542 ]),
29543 ),
29544 cwd: Schema.optionalKey(
29545 Schema.Union([
29546 Schema.String.annotate({
29547 description:
29548 "Optional cwd filter; when set, only threads whose session cwd exactly matches this path are returned.",
29549 }),
29550 Schema.Null,
29551 ]),
29552 ),
29553 limit: Schema.optionalKey(
29554 Schema.Union([
29555 Schema.Number.annotate({
29556 description: "Optional page size; defaults to a reasonable server-side value.",
29557 format: "uint32",
29558 })
29559 .check(Schema.isInt())
29560 .check(Schema.isGreaterThanOrEqualTo(0)),
29561 Schema.Null,
29562 ]),
29563 ),
29564 modelProviders: Schema.optionalKey(
29565 Schema.Union([
29566 Schema.Array(Schema.String).annotate({
29567 description:
29568 "Optional provider filter; when set, only sessions recorded under these providers are returned. When present but empty, includes all providers.",
29569 }),
29570 Schema.Null,
29571 ]),
29572 ),
29573 searchTerm: Schema.optionalKey(
29574 Schema.Union([
29575 Schema.String.annotate({
29576 description: "Optional substring filter for the extracted thread title.",
29577 }),
29578 Schema.Null,
29579 ]),
29580 ),
29581 sortKey: Schema.optionalKey(
29582 Schema.Union([V2ThreadListParams__ThreadSortKey, Schema.Null]).annotate({
29583 description: "Optional sort key; defaults to created_at.",
29584 }),
29585 ),
29586 sourceKinds: Schema.optionalKey(
29587 Schema.Union([
29588 Schema.Array(V2ThreadListParams__ThreadSourceKind).annotate({
29589 description:
29590 "Optional source filter; when set, only sessions from these source kinds are returned. When omitted or empty, defaults to interactive sources.",
29591 }),
29592 Schema.Null,
29593 ]),
29594 ),
29595}).annotate({ title: "ThreadListParams" });
29596
29597export type V2ThreadListResponse = {
29598 readonly data: ReadonlyArray<V2ThreadListResponse__Thread>;
29599 readonly nextCursor?: string | null;
29600};
29601export const V2ThreadListResponse = Schema.Struct({
29602 data: Schema.Array(V2ThreadListResponse__Thread),
29603 nextCursor: Schema.optionalKey(
29604 Schema.Union([
29605 Schema.String.annotate({
29606 description:
29607 "Opaque cursor to pass to the next call to continue after the last item. if None, there are no more items to return.",
29608 }),
29609 Schema.Null,
29610 ]),
29611 ),
29612}).annotate({ title: "ThreadListResponse" });
29613
29614export type V2ThreadListResponse__ByteRange = { readonly end: number; readonly start: number };
29615export const V2ThreadListResponse__ByteRange = Schema.Struct({
29616 end: Schema.Number.annotate({ format: "uint" })
29617 .check(Schema.isInt())
29618 .check(Schema.isGreaterThanOrEqualTo(0)),
29619 start: Schema.Number.annotate({ format: "uint" })
29620 .check(Schema.isInt())
29621 .check(Schema.isGreaterThanOrEqualTo(0)),
29622});
29623
29624export type V2ThreadListResponse__CollabAgentTool =
29625 | "spawnAgent"
29626 | "sendInput"
29627 | "resumeAgent"
29628 | "wait"
29629 | "closeAgent";
29630export const V2ThreadListResponse__CollabAgentTool = Schema.Literals([
29631 "spawnAgent",
29632 "sendInput",
29633 "resumeAgent",
29634 "wait",
29635 "closeAgent",
29636]);
29637
29638export type V2ThreadListResponse__CollabAgentToolCallStatus = "inProgress" | "completed" | "failed";
29639export const V2ThreadListResponse__CollabAgentToolCallStatus = Schema.Literals([
29640 "inProgress",
29641 "completed",
29642 "failed",
29643]);
29644
29645export type V2ThreadListResponse__CommandExecutionSource =
29646 | "agent"
29647 | "userShell"
29648 | "unifiedExecStartup"
29649 | "unifiedExecInteraction";
29650export const V2ThreadListResponse__CommandExecutionSource = Schema.Literals([
29651 "agent",
29652 "userShell",
29653 "unifiedExecStartup",
29654 "unifiedExecInteraction",
29655]);
29656
29657export type V2ThreadListResponse__SessionSource =
29658 | "cli"
29659 | "vscode"
29660 | "exec"
29661 | "appServer"
29662 | "unknown"
29663 | { readonly custom: string }
29664 | { readonly subAgent: V2ThreadListResponse__SubAgentSource };
29665export const V2ThreadListResponse__SessionSource = Schema.Union(
29666 [
29667 Schema.Literals(["cli", "vscode", "exec", "appServer", "unknown"]),
29668 Schema.Struct({ custom: Schema.String }).annotate({ title: "CustomSessionSource" }),
29669 Schema.Struct({ subAgent: V2ThreadListResponse__SubAgentSource }).annotate({
29670 title: "SubAgentSessionSource",
29671 }),
29672 ],
29673 { mode: "oneOf" },
29674);
29675
29676export type V2ThreadListResponse__ThreadStatus =
29677 | { readonly type: "notLoaded" }
29678 | { readonly type: "idle" }
29679 | { readonly type: "systemError" }
29680 | {
29681 readonly activeFlags: ReadonlyArray<V2ThreadListResponse__ThreadActiveFlag>;
29682 readonly type: "active";
29683 };
29684export const V2ThreadListResponse__ThreadStatus = Schema.Union(
29685 [
29686 Schema.Struct({
29687 type: Schema.Literal("notLoaded").annotate({ title: "NotLoadedThreadStatusType" }),
29688 }).annotate({ title: "NotLoadedThreadStatus" }),
29689 Schema.Struct({
29690 type: Schema.Literal("idle").annotate({ title: "IdleThreadStatusType" }),
29691 }).annotate({ title: "IdleThreadStatus" }),
29692 Schema.Struct({
29693 type: Schema.Literal("systemError").annotate({ title: "SystemErrorThreadStatusType" }),
29694 }).annotate({ title: "SystemErrorThreadStatus" }),
29695 Schema.Struct({
29696 activeFlags: Schema.Array(V2ThreadListResponse__ThreadActiveFlag),
29697 type: Schema.Literal("active").annotate({ title: "ActiveThreadStatusType" }),
29698 }).annotate({ title: "ActiveThreadStatus" }),
29699 ],
29700 { mode: "oneOf" },
29701);
29702
29703export type V2ThreadLoadedListParams = {
29704 readonly cursor?: string | null;
29705 readonly limit?: number | null;
29706};
29707export const V2ThreadLoadedListParams = Schema.Struct({
29708 cursor: Schema.optionalKey(
29709 Schema.Union([
29710 Schema.String.annotate({
29711 description: "Opaque pagination cursor returned by a previous call.",
29712 }),
29713 Schema.Null,
29714 ]),
29715 ),
29716 limit: Schema.optionalKey(
29717 Schema.Union([
29718 Schema.Number.annotate({
29719 description: "Optional page size; defaults to no limit.",
29720 format: "uint32",
29721 })
29722 .check(Schema.isInt())
29723 .check(Schema.isGreaterThanOrEqualTo(0)),
29724 Schema.Null,
29725 ]),
29726 ),
29727}).annotate({ title: "ThreadLoadedListParams" });
29728
29729export type V2ThreadLoadedListResponse = {
29730 readonly data: ReadonlyArray<string>;
29731 readonly nextCursor?: string | null;
29732};
29733export const V2ThreadLoadedListResponse = Schema.Struct({
29734 data: Schema.Array(Schema.String).annotate({
29735 description: "Thread ids for sessions currently loaded in memory.",
29736 }),
29737 nextCursor: Schema.optionalKey(
29738 Schema.Union([
29739 Schema.String.annotate({
29740 description:
29741 "Opaque cursor to pass to the next call to continue after the last item. if None, there are no more items to return.",
29742 }),
29743 Schema.Null,
29744 ]),
29745 ),
29746}).annotate({ title: "ThreadLoadedListResponse" });
29747
29748export type V2ThreadMetadataUpdateParams = {
29749 readonly gitInfo?: V2ThreadMetadataUpdateParams__ThreadMetadataGitInfoUpdateParams | null;
29750 readonly threadId: string;
29751};
29752export const V2ThreadMetadataUpdateParams = Schema.Struct({
29753 gitInfo: Schema.optionalKey(
29754 Schema.Union([
29755 V2ThreadMetadataUpdateParams__ThreadMetadataGitInfoUpdateParams,
29756 Schema.Null,
29757 ]).annotate({
29758 description:
29759 "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.",
29760 }),
29761 ),
29762 threadId: Schema.String,
29763}).annotate({ title: "ThreadMetadataUpdateParams" });
29764
29765export type V2ThreadMetadataUpdateResponse = {
29766 readonly thread: V2ThreadMetadataUpdateResponse__Thread;
29767};
29768export const V2ThreadMetadataUpdateResponse = Schema.Struct({
29769 thread: V2ThreadMetadataUpdateResponse__Thread,
29770}).annotate({ title: "ThreadMetadataUpdateResponse" });
29771
29772export type V2ThreadMetadataUpdateResponse__ByteRange = {
29773 readonly end: number;
29774 readonly start: number;
29775};
29776export const V2ThreadMetadataUpdateResponse__ByteRange = Schema.Struct({
29777 end: Schema.Number.annotate({ format: "uint" })
29778 .check(Schema.isInt())
29779 .check(Schema.isGreaterThanOrEqualTo(0)),
29780 start: Schema.Number.annotate({ format: "uint" })
29781 .check(Schema.isInt())
29782 .check(Schema.isGreaterThanOrEqualTo(0)),
29783});
29784
29785export type V2ThreadMetadataUpdateResponse__CollabAgentTool =
29786 | "spawnAgent"
29787 | "sendInput"
29788 | "resumeAgent"
29789 | "wait"
29790 | "closeAgent";
29791export const V2ThreadMetadataUpdateResponse__CollabAgentTool = Schema.Literals([
29792 "spawnAgent",
29793 "sendInput",
29794 "resumeAgent",
29795 "wait",
29796 "closeAgent",
29797]);
29798
29799export type V2ThreadMetadataUpdateResponse__CollabAgentToolCallStatus =
29800 | "inProgress"
29801 | "completed"
29802 | "failed";
29803export const V2ThreadMetadataUpdateResponse__CollabAgentToolCallStatus = Schema.Literals([
29804 "inProgress",
29805 "completed",
29806 "failed",
29807]);
29808
29809export type V2ThreadMetadataUpdateResponse__CommandExecutionSource =
29810 | "agent"
29811 | "userShell"
29812 | "unifiedExecStartup"
29813 | "unifiedExecInteraction";
29814export const V2ThreadMetadataUpdateResponse__CommandExecutionSource = Schema.Literals([
29815 "agent",
29816 "userShell",
29817 "unifiedExecStartup",
29818 "unifiedExecInteraction",
29819]);
29820
29821export type V2ThreadMetadataUpdateResponse__SessionSource =
29822 | "cli"
29823 | "vscode"
29824 | "exec"
29825 | "appServer"
29826 | "unknown"
29827 | { readonly custom: string }
29828 | { readonly subAgent: V2ThreadMetadataUpdateResponse__SubAgentSource };
29829export const V2ThreadMetadataUpdateResponse__SessionSource = Schema.Union(
29830 [
29831 Schema.Literals(["cli", "vscode", "exec", "appServer", "unknown"]),
29832 Schema.Struct({ custom: Schema.String }).annotate({ title: "CustomSessionSource" }),
29833 Schema.Struct({ subAgent: V2ThreadMetadataUpdateResponse__SubAgentSource }).annotate({
29834 title: "SubAgentSessionSource",
29835 }),
29836 ],
29837 { mode: "oneOf" },
29838);
29839
29840export type V2ThreadMetadataUpdateResponse__ThreadStatus =
29841 | { readonly type: "notLoaded" }
29842 | { readonly type: "idle" }
29843 | { readonly type: "systemError" }
29844 | {
29845 readonly activeFlags: ReadonlyArray<V2ThreadMetadataUpdateResponse__ThreadActiveFlag>;
29846 readonly type: "active";
29847 };
29848export const V2ThreadMetadataUpdateResponse__ThreadStatus = Schema.Union(
29849 [
29850 Schema.Struct({
29851 type: Schema.Literal("notLoaded").annotate({ title: "NotLoadedThreadStatusType" }),
29852 }).annotate({ title: "NotLoadedThreadStatus" }),
29853 Schema.Struct({
29854 type: Schema.Literal("idle").annotate({ title: "IdleThreadStatusType" }),
29855 }).annotate({ title: "IdleThreadStatus" }),
29856 Schema.Struct({
29857 type: Schema.Literal("systemError").annotate({ title: "SystemErrorThreadStatusType" }),
29858 }).annotate({ title: "SystemErrorThreadStatus" }),
29859 Schema.Struct({
29860 activeFlags: Schema.Array(V2ThreadMetadataUpdateResponse__ThreadActiveFlag),
29861 type: Schema.Literal("active").annotate({ title: "ActiveThreadStatusType" }),
29862 }).annotate({ title: "ActiveThreadStatus" }),
29863 ],
29864 { mode: "oneOf" },
29865);
29866
29867export type V2ThreadNameUpdatedNotification = {
29868 readonly threadId: string;
29869 readonly threadName?: string | null;
29870};
29871export const V2ThreadNameUpdatedNotification = Schema.Struct({
29872 threadId: Schema.String,
29873 threadName: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
29874}).annotate({ title: "ThreadNameUpdatedNotification" });
29875
29876export type V2ThreadReadParams = { readonly includeTurns?: boolean; readonly threadId: string };
29877export const V2ThreadReadParams = Schema.Struct({
29878 includeTurns: Schema.optionalKey(
29879 Schema.Boolean.annotate({
29880 description: "When true, include turns and their items from rollout history.",
29881 default: false,
29882 }),
29883 ),
29884 threadId: Schema.String,
29885}).annotate({ title: "ThreadReadParams" });
29886
29887export type V2ThreadReadResponse = { readonly thread: V2ThreadReadResponse__Thread };
29888export const V2ThreadReadResponse = Schema.Struct({
29889 thread: V2ThreadReadResponse__Thread,
29890}).annotate({ title: "ThreadReadResponse" });
29891
29892export type V2ThreadReadResponse__ByteRange = { readonly end: number; readonly start: number };
29893export const V2ThreadReadResponse__ByteRange = Schema.Struct({
29894 end: Schema.Number.annotate({ format: "uint" })
29895 .check(Schema.isInt())
29896 .check(Schema.isGreaterThanOrEqualTo(0)),
29897 start: Schema.Number.annotate({ format: "uint" })
29898 .check(Schema.isInt())
29899 .check(Schema.isGreaterThanOrEqualTo(0)),
29900});
29901
29902export type V2ThreadReadResponse__CollabAgentTool =
29903 | "spawnAgent"
29904 | "sendInput"
29905 | "resumeAgent"
29906 | "wait"
29907 | "closeAgent";
29908export const V2ThreadReadResponse__CollabAgentTool = Schema.Literals([
29909 "spawnAgent",
29910 "sendInput",
29911 "resumeAgent",
29912 "wait",
29913 "closeAgent",
29914]);
29915
29916export type V2ThreadReadResponse__CollabAgentToolCallStatus = "inProgress" | "completed" | "failed";
29917export const V2ThreadReadResponse__CollabAgentToolCallStatus = Schema.Literals([
29918 "inProgress",
29919 "completed",
29920 "failed",
29921]);
29922
29923export type V2ThreadReadResponse__CommandExecutionSource =
29924 | "agent"
29925 | "userShell"
29926 | "unifiedExecStartup"
29927 | "unifiedExecInteraction";
29928export const V2ThreadReadResponse__CommandExecutionSource = Schema.Literals([
29929 "agent",
29930 "userShell",
29931 "unifiedExecStartup",
29932 "unifiedExecInteraction",
29933]);
29934
29935export type V2ThreadReadResponse__SessionSource =
29936 | "cli"
29937 | "vscode"
29938 | "exec"
29939 | "appServer"
29940 | "unknown"
29941 | { readonly custom: string }
29942 | { readonly subAgent: V2ThreadReadResponse__SubAgentSource };
29943export const V2ThreadReadResponse__SessionSource = Schema.Union(
29944 [
29945 Schema.Literals(["cli", "vscode", "exec", "appServer", "unknown"]),
29946 Schema.Struct({ custom: Schema.String }).annotate({ title: "CustomSessionSource" }),
29947 Schema.Struct({ subAgent: V2ThreadReadResponse__SubAgentSource }).annotate({
29948 title: "SubAgentSessionSource",
29949 }),
29950 ],
29951 { mode: "oneOf" },
29952);
29953
29954export type V2ThreadReadResponse__ThreadStatus =
29955 | { readonly type: "notLoaded" }
29956 | { readonly type: "idle" }
29957 | { readonly type: "systemError" }
29958 | {
29959 readonly activeFlags: ReadonlyArray<V2ThreadReadResponse__ThreadActiveFlag>;
29960 readonly type: "active";
29961 };
29962export const V2ThreadReadResponse__ThreadStatus = Schema.Union(
29963 [
29964 Schema.Struct({
29965 type: Schema.Literal("notLoaded").annotate({ title: "NotLoadedThreadStatusType" }),
29966 }).annotate({ title: "NotLoadedThreadStatus" }),
29967 Schema.Struct({
29968 type: Schema.Literal("idle").annotate({ title: "IdleThreadStatusType" }),
29969 }).annotate({ title: "IdleThreadStatus" }),
29970 Schema.Struct({
29971 type: Schema.Literal("systemError").annotate({ title: "SystemErrorThreadStatusType" }),
29972 }).annotate({ title: "SystemErrorThreadStatus" }),
29973 Schema.Struct({
29974 activeFlags: Schema.Array(V2ThreadReadResponse__ThreadActiveFlag),
29975 type: Schema.Literal("active").annotate({ title: "ActiveThreadStatusType" }),
29976 }).annotate({ title: "ActiveThreadStatus" }),
29977 ],
29978 { mode: "oneOf" },
29979);
29980
29981export type V2ThreadRealtimeClosedNotification = {
29982 readonly reason?: string | null;
29983 readonly threadId: string;
29984};
29985export const V2ThreadRealtimeClosedNotification = Schema.Struct({
29986 reason: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
29987 threadId: Schema.String,
29988}).annotate({
29989 title: "ThreadRealtimeClosedNotification",
29990 description: "EXPERIMENTAL - emitted when thread realtime transport closes.",
29991});
29992
29993export type V2ThreadRealtimeErrorNotification = {
29994 readonly message: string;
29995 readonly threadId: string;
29996};
29997export const V2ThreadRealtimeErrorNotification = Schema.Struct({
29998 message: Schema.String,
29999 threadId: Schema.String,
30000}).annotate({
30001 title: "ThreadRealtimeErrorNotification",
30002 description: "EXPERIMENTAL - emitted when thread realtime encounters an error.",
30003});
30004
30005export type V2ThreadRealtimeItemAddedNotification = {
30006 readonly item: unknown;
30007 readonly threadId: string;
30008};
30009export const V2ThreadRealtimeItemAddedNotification = Schema.Struct({
30010 item: Schema.Unknown,
30011 threadId: Schema.String,
30012}).annotate({
30013 title: "ThreadRealtimeItemAddedNotification",
30014 description: "EXPERIMENTAL - raw non-audio thread realtime item emitted by the backend.",
30015});
30016
30017export type V2ThreadRealtimeOutputAudioDeltaNotification = {
30018 readonly audio: V2ThreadRealtimeOutputAudioDeltaNotification__ThreadRealtimeAudioChunk;
30019 readonly threadId: string;
30020};
30021export const V2ThreadRealtimeOutputAudioDeltaNotification = Schema.Struct({
30022 audio: V2ThreadRealtimeOutputAudioDeltaNotification__ThreadRealtimeAudioChunk,
30023 threadId: Schema.String,
30024}).annotate({
30025 title: "ThreadRealtimeOutputAudioDeltaNotification",
30026 description: "EXPERIMENTAL - streamed output audio emitted by thread realtime.",
30027});
30028
30029export type V2ThreadRealtimeSdpNotification = { readonly sdp: string; readonly threadId: string };
30030export const V2ThreadRealtimeSdpNotification = Schema.Struct({
30031 sdp: Schema.String,
30032 threadId: Schema.String,
30033}).annotate({
30034 title: "ThreadRealtimeSdpNotification",
30035 description: "EXPERIMENTAL - emitted with the remote SDP for a WebRTC realtime session.",
30036});
30037
30038export type V2ThreadRealtimeStartedNotification = {
30039 readonly sessionId?: string | null;
30040 readonly threadId: string;
30041 readonly version: V2ThreadRealtimeStartedNotification__RealtimeConversationVersion;
30042};
30043export const V2ThreadRealtimeStartedNotification = Schema.Struct({
30044 sessionId: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
30045 threadId: Schema.String,
30046 version: V2ThreadRealtimeStartedNotification__RealtimeConversationVersion,
30047}).annotate({
30048 title: "ThreadRealtimeStartedNotification",
30049 description: "EXPERIMENTAL - emitted when thread realtime startup is accepted.",
30050});
30051
30052export type V2ThreadRealtimeTranscriptUpdatedNotification = {
30053 readonly role: string;
30054 readonly text: string;
30055 readonly threadId: string;
30056};
30057export const V2ThreadRealtimeTranscriptUpdatedNotification = Schema.Struct({
30058 role: Schema.String,
30059 text: Schema.String,
30060 threadId: Schema.String,
30061}).annotate({
30062 title: "ThreadRealtimeTranscriptUpdatedNotification",
30063 description:
30064 "EXPERIMENTAL - flat transcript delta emitted whenever realtime transcript text changes.",
30065});
30066
30067export type V2ThreadResumeParams = {
30068 readonly approvalPolicy?: V2ThreadResumeParams__AskForApproval | null;
30069 readonly approvalsReviewer?: V2ThreadResumeParams__ApprovalsReviewer | null;
30070 readonly baseInstructions?: string | null;
30071 readonly config?: { readonly [x: string]: unknown } | null;
30072 readonly cwd?: string | null;
30073 readonly developerInstructions?: string | null;
30074 readonly model?: string | null;
30075 readonly modelProvider?: string | null;
30076 readonly personality?: V2ThreadResumeParams__Personality | null;
30077 readonly sandbox?: V2ThreadResumeParams__SandboxMode | null;
30078 readonly serviceTier?: V2ThreadResumeParams__ServiceTier | null | null;
30079 readonly threadId: string;
30080};
30081export const V2ThreadResumeParams = Schema.Struct({
30082 approvalPolicy: Schema.optionalKey(
30083 Schema.Union([V2ThreadResumeParams__AskForApproval, Schema.Null]),
30084 ),
30085 approvalsReviewer: Schema.optionalKey(
30086 Schema.Union([V2ThreadResumeParams__ApprovalsReviewer, Schema.Null]).annotate({
30087 description:
30088 "Override where approval requests are routed for review on this thread and subsequent turns.",
30089 }),
30090 ),
30091 baseInstructions: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
30092 config: Schema.optionalKey(
30093 Schema.Union([Schema.Record(Schema.String, Schema.Unknown), Schema.Null]),
30094 ),
30095 cwd: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
30096 developerInstructions: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
30097 model: Schema.optionalKey(
30098 Schema.Union([
30099 Schema.String.annotate({
30100 description: "Configuration overrides for the resumed thread, if any.",
30101 }),
30102 Schema.Null,
30103 ]),
30104 ),
30105 modelProvider: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
30106 personality: Schema.optionalKey(Schema.Union([V2ThreadResumeParams__Personality, Schema.Null])),
30107 sandbox: Schema.optionalKey(Schema.Union([V2ThreadResumeParams__SandboxMode, Schema.Null])),
30108 serviceTier: Schema.optionalKey(
30109 Schema.Union([Schema.Union([V2ThreadResumeParams__ServiceTier, Schema.Null]), Schema.Null]),
30110 ),
30111 threadId: Schema.String,
30112}).annotate({
30113 title: "ThreadResumeParams",
30114 description:
30115 "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.",
30116});
30117
30118export type V2ThreadResumeParams__ResponseItem =
30119 | {
30120 readonly content: ReadonlyArray<V2ThreadResumeParams__ContentItem>;
30121 readonly end_turn?: boolean | null;
30122 readonly id?: string | null;
30123 readonly phase?: V2ThreadResumeParams__MessagePhase | null;
30124 readonly role: string;
30125 readonly type: "message";
30126 }
30127 | {
30128 readonly content?: ReadonlyArray<V2ThreadResumeParams__ReasoningItemContent> | null;
30129 readonly encrypted_content?: string | null;
30130 readonly summary: ReadonlyArray<V2ThreadResumeParams__ReasoningItemReasoningSummary>;
30131 readonly type: "reasoning";
30132 }
30133 | {
30134 readonly action: V2ThreadResumeParams__LocalShellAction;
30135 readonly call_id?: string | null;
30136 readonly id?: string | null;
30137 readonly status: V2ThreadResumeParams__LocalShellStatus;
30138 readonly type: "local_shell_call";
30139 }
30140 | {
30141 readonly arguments: string;
30142 readonly call_id: string;
30143 readonly id?: string | null;
30144 readonly name: string;
30145 readonly namespace?: string | null;
30146 readonly type: "function_call";
30147 }
30148 | {
30149 readonly arguments: unknown;
30150 readonly call_id?: string | null;
30151 readonly execution: string;
30152 readonly id?: string | null;
30153 readonly status?: string | null;
30154 readonly type: "tool_search_call";
30155 }
30156 | {
30157 readonly call_id: string;
30158 readonly output: V2ThreadResumeParams__FunctionCallOutputBody;
30159 readonly type: "function_call_output";
30160 }
30161 | {
30162 readonly call_id: string;
30163 readonly id?: string | null;
30164 readonly input: string;
30165 readonly name: string;
30166 readonly status?: string | null;
30167 readonly type: "custom_tool_call";
30168 }
30169 | {
30170 readonly call_id: string;
30171 readonly name?: string | null;
30172 readonly output: V2ThreadResumeParams__FunctionCallOutputBody;
30173 readonly type: "custom_tool_call_output";
30174 }
30175 | {
30176 readonly call_id?: string | null;
30177 readonly execution: string;
30178 readonly status: string;
30179 readonly tools: ReadonlyArray<unknown>;
30180 readonly type: "tool_search_output";
30181 }
30182 | {
30183 readonly action?: V2ThreadResumeParams__ResponsesApiWebSearchAction | null;
30184 readonly id?: string | null;
30185 readonly status?: string | null;
30186 readonly type: "web_search_call";
30187 }
30188 | {
30189 readonly id: string;
30190 readonly result: string;
30191 readonly revised_prompt?: string | null;
30192 readonly status: string;
30193 readonly type: "image_generation_call";
30194 }
30195 | { readonly ghost_commit: V2ThreadResumeParams__GhostCommit; readonly type: "ghost_snapshot" }
30196 | { readonly encrypted_content: string; readonly type: "compaction" }
30197 | { readonly type: "other" };
30198export const V2ThreadResumeParams__ResponseItem = Schema.Union(
30199 [
30200 Schema.Struct({
30201 content: Schema.Array(V2ThreadResumeParams__ContentItem),
30202 end_turn: Schema.optionalKey(Schema.Union([Schema.Boolean, Schema.Null])),
30203 id: Schema.optionalKey(
30204 Schema.Union([Schema.String.annotate({ writeOnly: true }), Schema.Null]),
30205 ),
30206 phase: Schema.optionalKey(Schema.Union([V2ThreadResumeParams__MessagePhase, Schema.Null])),
30207 role: Schema.String,
30208 type: Schema.Literal("message").annotate({ title: "MessageResponseItemType" }),
30209 }).annotate({ title: "MessageResponseItem" }),
30210 Schema.Struct({
30211 content: Schema.optionalKey(
30212 Schema.Union([Schema.Array(V2ThreadResumeParams__ReasoningItemContent), Schema.Null]),
30213 ),
30214 encrypted_content: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
30215 summary: Schema.Array(V2ThreadResumeParams__ReasoningItemReasoningSummary),
30216 type: Schema.Literal("reasoning").annotate({ title: "ReasoningResponseItemType" }),
30217 }).annotate({ title: "ReasoningResponseItem" }),
30218 Schema.Struct({
30219 action: V2ThreadResumeParams__LocalShellAction,
30220 call_id: Schema.optionalKey(
30221 Schema.Union([
30222 Schema.String.annotate({ description: "Set when using the Responses API." }),
30223 Schema.Null,
30224 ]),
30225 ),
30226 id: Schema.optionalKey(
30227 Schema.Union([
30228 Schema.String.annotate({
30229 description: "Legacy id field retained for compatibility with older payloads.",
30230 writeOnly: true,
30231 }),
30232 Schema.Null,
30233 ]),
30234 ),
30235 status: V2ThreadResumeParams__LocalShellStatus,
30236 type: Schema.Literal("local_shell_call").annotate({
30237 title: "LocalShellCallResponseItemType",
30238 }),
30239 }).annotate({ title: "LocalShellCallResponseItem" }),
30240 Schema.Struct({
30241 arguments: Schema.String,
30242 call_id: Schema.String,
30243 id: Schema.optionalKey(
30244 Schema.Union([Schema.String.annotate({ writeOnly: true }), Schema.Null]),
30245 ),
30246 name: Schema.String,
30247 namespace: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
30248 type: Schema.Literal("function_call").annotate({ title: "FunctionCallResponseItemType" }),
30249 }).annotate({ title: "FunctionCallResponseItem" }),
30250 Schema.Struct({
30251 arguments: Schema.Unknown,
30252 call_id: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
30253 execution: Schema.String,
30254 id: Schema.optionalKey(
30255 Schema.Union([Schema.String.annotate({ writeOnly: true }), Schema.Null]),
30256 ),
30257 status: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
30258 type: Schema.Literal("tool_search_call").annotate({
30259 title: "ToolSearchCallResponseItemType",
30260 }),
30261 }).annotate({ title: "ToolSearchCallResponseItem" }),
30262 Schema.Struct({
30263 call_id: Schema.String,
30264 output: V2ThreadResumeParams__FunctionCallOutputBody,
30265 type: Schema.Literal("function_call_output").annotate({
30266 title: "FunctionCallOutputResponseItemType",
30267 }),
30268 }).annotate({ title: "FunctionCallOutputResponseItem" }),
30269 Schema.Struct({
30270 call_id: Schema.String,
30271 id: Schema.optionalKey(
30272 Schema.Union([Schema.String.annotate({ writeOnly: true }), Schema.Null]),
30273 ),
30274 input: Schema.String,
30275 name: Schema.String,
30276 status: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
30277 type: Schema.Literal("custom_tool_call").annotate({
30278 title: "CustomToolCallResponseItemType",
30279 }),
30280 }).annotate({ title: "CustomToolCallResponseItem" }),
30281 Schema.Struct({
30282 call_id: Schema.String,
30283 name: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
30284 output: V2ThreadResumeParams__FunctionCallOutputBody,
30285 type: Schema.Literal("custom_tool_call_output").annotate({
30286 title: "CustomToolCallOutputResponseItemType",
30287 }),
30288 }).annotate({ title: "CustomToolCallOutputResponseItem" }),
30289 Schema.Struct({
30290 call_id: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
30291 execution: Schema.String,
30292 status: Schema.String,
30293 tools: Schema.Array(Schema.Unknown),
30294 type: Schema.Literal("tool_search_output").annotate({
30295 title: "ToolSearchOutputResponseItemType",
30296 }),
30297 }).annotate({ title: "ToolSearchOutputResponseItem" }),
30298 Schema.Struct({
30299 action: Schema.optionalKey(
30300 Schema.Union([V2ThreadResumeParams__ResponsesApiWebSearchAction, Schema.Null]),
30301 ),
30302 id: Schema.optionalKey(
30303 Schema.Union([Schema.String.annotate({ writeOnly: true }), Schema.Null]),
30304 ),
30305 status: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
30306 type: Schema.Literal("web_search_call").annotate({ title: "WebSearchCallResponseItemType" }),
30307 }).annotate({ title: "WebSearchCallResponseItem" }),
30308 Schema.Struct({
30309 id: Schema.String,
30310 result: Schema.String,
30311 revised_prompt: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
30312 status: Schema.String,
30313 type: Schema.Literal("image_generation_call").annotate({
30314 title: "ImageGenerationCallResponseItemType",
30315 }),
30316 }).annotate({ title: "ImageGenerationCallResponseItem" }),
30317 Schema.Struct({
30318 ghost_commit: V2ThreadResumeParams__GhostCommit,
30319 type: Schema.Literal("ghost_snapshot").annotate({ title: "GhostSnapshotResponseItemType" }),
30320 }).annotate({ title: "GhostSnapshotResponseItem" }),
30321 Schema.Struct({
30322 encrypted_content: Schema.String,
30323 type: Schema.Literal("compaction").annotate({ title: "CompactionResponseItemType" }),
30324 }).annotate({ title: "CompactionResponseItem" }),
30325 Schema.Struct({
30326 type: Schema.Literal("other").annotate({ title: "OtherResponseItemType" }),
30327 }).annotate({ title: "OtherResponseItem" }),
30328 ],
30329 { mode: "oneOf" },
30330);
30331
30332export type V2ThreadResumeResponse = {
30333 readonly approvalPolicy: V2ThreadResumeResponse__AskForApproval;
30334 readonly approvalsReviewer: "user" | "guardian_subagent";
30335 readonly cwd: string;
30336 readonly model: string;
30337 readonly modelProvider: string;
30338 readonly reasoningEffort?: V2ThreadResumeResponse__ReasoningEffort | null;
30339 readonly sandbox: V2ThreadResumeResponse__SandboxPolicy;
30340 readonly serviceTier?: V2ThreadResumeResponse__ServiceTier | null;
30341 readonly thread: V2ThreadResumeResponse__Thread;
30342};
30343export const V2ThreadResumeResponse = Schema.Struct({
30344 approvalPolicy: V2ThreadResumeResponse__AskForApproval,
30345 approvalsReviewer: Schema.Literals(["user", "guardian_subagent"]).annotate({
30346 description:
30347 "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.",
30348 }),
30349 cwd: Schema.String,
30350 model: Schema.String,
30351 modelProvider: Schema.String,
30352 reasoningEffort: Schema.optionalKey(
30353 Schema.Union([V2ThreadResumeResponse__ReasoningEffort, Schema.Null]),
30354 ),
30355 sandbox: V2ThreadResumeResponse__SandboxPolicy,
30356 serviceTier: Schema.optionalKey(Schema.Union([V2ThreadResumeResponse__ServiceTier, Schema.Null])),
30357 thread: V2ThreadResumeResponse__Thread,
30358}).annotate({ title: "ThreadResumeResponse" });
30359
30360export type V2ThreadResumeResponse__ApprovalsReviewer = "user" | "guardian_subagent";
30361export const V2ThreadResumeResponse__ApprovalsReviewer = Schema.Literals([
30362 "user",
30363 "guardian_subagent",
30364]).annotate({
30365 description:
30366 "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.",
30367});
30368
30369export type V2ThreadResumeResponse__ByteRange = { readonly end: number; readonly start: number };
30370export const V2ThreadResumeResponse__ByteRange = Schema.Struct({
30371 end: Schema.Number.annotate({ format: "uint" })
30372 .check(Schema.isInt())
30373 .check(Schema.isGreaterThanOrEqualTo(0)),
30374 start: Schema.Number.annotate({ format: "uint" })
30375 .check(Schema.isInt())
30376 .check(Schema.isGreaterThanOrEqualTo(0)),
30377});
30378
30379export type V2ThreadResumeResponse__CollabAgentTool =
30380 | "spawnAgent"
30381 | "sendInput"
30382 | "resumeAgent"
30383 | "wait"
30384 | "closeAgent";
30385export const V2ThreadResumeResponse__CollabAgentTool = Schema.Literals([
30386 "spawnAgent",
30387 "sendInput",
30388 "resumeAgent",
30389 "wait",
30390 "closeAgent",
30391]);
30392
30393export type V2ThreadResumeResponse__CollabAgentToolCallStatus =
30394 | "inProgress"
30395 | "completed"
30396 | "failed";
30397export const V2ThreadResumeResponse__CollabAgentToolCallStatus = Schema.Literals([
30398 "inProgress",
30399 "completed",
30400 "failed",
30401]);
30402
30403export type V2ThreadResumeResponse__CommandExecutionSource =
30404 | "agent"
30405 | "userShell"
30406 | "unifiedExecStartup"
30407 | "unifiedExecInteraction";
30408export const V2ThreadResumeResponse__CommandExecutionSource = Schema.Literals([
30409 "agent",
30410 "userShell",
30411 "unifiedExecStartup",
30412 "unifiedExecInteraction",
30413]);
30414
30415export type V2ThreadResumeResponse__NetworkAccess = "restricted" | "enabled";
30416export const V2ThreadResumeResponse__NetworkAccess = Schema.Literals(["restricted", "enabled"]);
30417
30418export type V2ThreadResumeResponse__ReadOnlyAccess =
30419 | {
30420 readonly includePlatformDefaults?: boolean;
30421 readonly readableRoots?: ReadonlyArray<V2ThreadResumeResponse__AbsolutePathBuf>;
30422 readonly type: "restricted";
30423 }
30424 | { readonly type: "fullAccess" };
30425export const V2ThreadResumeResponse__ReadOnlyAccess = Schema.Union(
30426 [
30427 Schema.Struct({
30428 includePlatformDefaults: Schema.optionalKey(Schema.Boolean.annotate({ default: true })),
30429 readableRoots: Schema.optionalKey(
30430 Schema.Array(V2ThreadResumeResponse__AbsolutePathBuf).annotate({ default: [] }),
30431 ),
30432 type: Schema.Literal("restricted").annotate({ title: "RestrictedReadOnlyAccessType" }),
30433 }).annotate({ title: "RestrictedReadOnlyAccess" }),
30434 Schema.Struct({
30435 type: Schema.Literal("fullAccess").annotate({ title: "FullAccessReadOnlyAccessType" }),
30436 }).annotate({ title: "FullAccessReadOnlyAccess" }),
30437 ],
30438 { mode: "oneOf" },
30439);
30440
30441export type V2ThreadResumeResponse__SessionSource =
30442 | "cli"
30443 | "vscode"
30444 | "exec"
30445 | "appServer"
30446 | "unknown"
30447 | { readonly custom: string }
30448 | { readonly subAgent: V2ThreadResumeResponse__SubAgentSource };
30449export const V2ThreadResumeResponse__SessionSource = Schema.Union(
30450 [
30451 Schema.Literals(["cli", "vscode", "exec", "appServer", "unknown"]),
30452 Schema.Struct({ custom: Schema.String }).annotate({ title: "CustomSessionSource" }),
30453 Schema.Struct({ subAgent: V2ThreadResumeResponse__SubAgentSource }).annotate({
30454 title: "SubAgentSessionSource",
30455 }),
30456 ],
30457 { mode: "oneOf" },
30458);
30459
30460export type V2ThreadResumeResponse__ThreadStatus =
30461 | { readonly type: "notLoaded" }
30462 | { readonly type: "idle" }
30463 | { readonly type: "systemError" }
30464 | {
30465 readonly activeFlags: ReadonlyArray<V2ThreadResumeResponse__ThreadActiveFlag>;
30466 readonly type: "active";
30467 };
30468export const V2ThreadResumeResponse__ThreadStatus = Schema.Union(
30469 [
30470 Schema.Struct({
30471 type: Schema.Literal("notLoaded").annotate({ title: "NotLoadedThreadStatusType" }),
30472 }).annotate({ title: "NotLoadedThreadStatus" }),
30473 Schema.Struct({
30474 type: Schema.Literal("idle").annotate({ title: "IdleThreadStatusType" }),
30475 }).annotate({ title: "IdleThreadStatus" }),
30476 Schema.Struct({
30477 type: Schema.Literal("systemError").annotate({ title: "SystemErrorThreadStatusType" }),
30478 }).annotate({ title: "SystemErrorThreadStatus" }),
30479 Schema.Struct({
30480 activeFlags: Schema.Array(V2ThreadResumeResponse__ThreadActiveFlag),
30481 type: Schema.Literal("active").annotate({ title: "ActiveThreadStatusType" }),
30482 }).annotate({ title: "ActiveThreadStatus" }),
30483 ],
30484 { mode: "oneOf" },
30485);
30486
30487export type V2ThreadRollbackParams = { readonly numTurns: number; readonly threadId: string };
30488export const V2ThreadRollbackParams = Schema.Struct({
30489 numTurns: Schema.Number.annotate({
30490 description:
30491 "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.",
30492 format: "uint32",
30493 })
30494 .check(Schema.isInt())
30495 .check(Schema.isGreaterThanOrEqualTo(0)),
30496 threadId: Schema.String,
30497}).annotate({ title: "ThreadRollbackParams" });
30498
30499export type V2ThreadRollbackResponse = {
30500 readonly thread: {
30501 readonly agentNickname?: string | null;
30502 readonly agentRole?: string | null;
30503 readonly cliVersion: string;
30504 readonly createdAt: number;
30505 readonly cwd: string;
30506 readonly ephemeral: boolean;
30507 readonly forkedFromId?: string | null;
30508 readonly gitInfo?: V2ThreadRollbackResponse__GitInfo | null;
30509 readonly id: string;
30510 readonly modelProvider: string;
30511 readonly name?: string | null;
30512 readonly path?: string | null;
30513 readonly preview: string;
30514 readonly source:
30515 | "cli"
30516 | "vscode"
30517 | "exec"
30518 | "appServer"
30519 | "unknown"
30520 | { readonly custom: string }
30521 | { readonly subAgent: V2ThreadRollbackResponse__SubAgentSource };
30522 readonly status:
30523 | { readonly type: "notLoaded" }
30524 | { readonly type: "idle" }
30525 | { readonly type: "systemError" }
30526 | {
30527 readonly activeFlags: ReadonlyArray<V2ThreadRollbackResponse__ThreadActiveFlag>;
30528 readonly type: "active";
30529 };
30530 readonly turns: ReadonlyArray<V2ThreadRollbackResponse__Turn>;
30531 readonly updatedAt: number;
30532 };
30533};
30534export const V2ThreadRollbackResponse = Schema.Struct({
30535 thread: Schema.Struct({
30536 agentNickname: Schema.optionalKey(
30537 Schema.Union([
30538 Schema.String.annotate({
30539 description:
30540 "Optional random unique nickname assigned to an AgentControl-spawned sub-agent.",
30541 }),
30542 Schema.Null,
30543 ]),
30544 ),
30545 agentRole: Schema.optionalKey(
30546 Schema.Union([
30547 Schema.String.annotate({
30548 description: "Optional role (agent_role) assigned to an AgentControl-spawned sub-agent.",
30549 }),
30550 Schema.Null,
30551 ]),
30552 ),
30553 cliVersion: Schema.String.annotate({
30554 description: "Version of the CLI that created the thread.",
30555 }),
30556 createdAt: Schema.Number.annotate({
30557 description: "Unix timestamp (in seconds) when the thread was created.",
30558 format: "int64",
30559 }).check(Schema.isInt()),
30560 cwd: Schema.String.annotate({ description: "Working directory captured for the thread." }),
30561 ephemeral: Schema.Boolean.annotate({
30562 description: "Whether the thread is ephemeral and should not be materialized on disk.",
30563 }),
30564 forkedFromId: Schema.optionalKey(
30565 Schema.Union([
30566 Schema.String.annotate({
30567 description: "Source thread id when this thread was created by forking another thread.",
30568 }),
30569 Schema.Null,
30570 ]),
30571 ),
30572 gitInfo: Schema.optionalKey(
30573 Schema.Union([V2ThreadRollbackResponse__GitInfo, Schema.Null]).annotate({
30574 description: "Optional Git metadata captured when the thread was created.",
30575 }),
30576 ),
30577 id: Schema.String,
30578 modelProvider: Schema.String.annotate({
30579 description: "Model provider used for this thread (for example, 'openai').",
30580 }),
30581 name: Schema.optionalKey(
30582 Schema.Union([
30583 Schema.String.annotate({ description: "Optional user-facing thread title." }),
30584 Schema.Null,
30585 ]),
30586 ),
30587 path: Schema.optionalKey(
30588 Schema.Union([
30589 Schema.String.annotate({ description: "[UNSTABLE] Path to the thread on disk." }),
30590 Schema.Null,
30591 ]),
30592 ),
30593 preview: Schema.String.annotate({
30594 description: "Usually the first user message in the thread, if available.",
30595 }),
30596 source: Schema.Union(
30597 [
30598 Schema.Literals(["cli", "vscode", "exec", "appServer", "unknown"]),
30599 Schema.Struct({ custom: Schema.String }).annotate({ title: "CustomSessionSource" }),
30600 Schema.Struct({ subAgent: V2ThreadRollbackResponse__SubAgentSource }).annotate({
30601 title: "SubAgentSessionSource",
30602 }),
30603 ],
30604 { mode: "oneOf" },
30605 ).annotate({
30606 description: "Origin of the thread (CLI, VSCode, codex exec, codex app-server, etc.).",
30607 }),
30608 status: Schema.Union(
30609 [
30610 Schema.Struct({
30611 type: Schema.Literal("notLoaded").annotate({ title: "NotLoadedThreadStatusType" }),
30612 }).annotate({ title: "NotLoadedThreadStatus" }),
30613 Schema.Struct({
30614 type: Schema.Literal("idle").annotate({ title: "IdleThreadStatusType" }),
30615 }).annotate({ title: "IdleThreadStatus" }),
30616 Schema.Struct({
30617 type: Schema.Literal("systemError").annotate({ title: "SystemErrorThreadStatusType" }),
30618 }).annotate({ title: "SystemErrorThreadStatus" }),
30619 Schema.Struct({
30620 activeFlags: Schema.Array(V2ThreadRollbackResponse__ThreadActiveFlag),
30621 type: Schema.Literal("active").annotate({ title: "ActiveThreadStatusType" }),
30622 }).annotate({ title: "ActiveThreadStatus" }),
30623 ],
30624 { mode: "oneOf" },
30625 ).annotate({ description: "Current runtime status for the thread." }),
30626 turns: Schema.Array(V2ThreadRollbackResponse__Turn).annotate({
30627 description:
30628 "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.",
30629 }),
30630 updatedAt: Schema.Number.annotate({
30631 description: "Unix timestamp (in seconds) when the thread was last updated.",
30632 format: "int64",
30633 }).check(Schema.isInt()),
30634 }).annotate({
30635 description:
30636 "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`.",
30637 }),
30638}).annotate({ title: "ThreadRollbackResponse" });
30639
30640export type V2ThreadRollbackResponse__ByteRange = { readonly end: number; readonly start: number };
30641export const V2ThreadRollbackResponse__ByteRange = Schema.Struct({
30642 end: Schema.Number.annotate({ format: "uint" })
30643 .check(Schema.isInt())
30644 .check(Schema.isGreaterThanOrEqualTo(0)),
30645 start: Schema.Number.annotate({ format: "uint" })
30646 .check(Schema.isInt())
30647 .check(Schema.isGreaterThanOrEqualTo(0)),
30648});
30649
30650export type V2ThreadRollbackResponse__CollabAgentTool =
30651 | "spawnAgent"
30652 | "sendInput"
30653 | "resumeAgent"
30654 | "wait"
30655 | "closeAgent";
30656export const V2ThreadRollbackResponse__CollabAgentTool = Schema.Literals([
30657 "spawnAgent",
30658 "sendInput",
30659 "resumeAgent",
30660 "wait",
30661 "closeAgent",
30662]);
30663
30664export type V2ThreadRollbackResponse__CollabAgentToolCallStatus =
30665 | "inProgress"
30666 | "completed"
30667 | "failed";
30668export const V2ThreadRollbackResponse__CollabAgentToolCallStatus = Schema.Literals([
30669 "inProgress",
30670 "completed",
30671 "failed",
30672]);
30673
30674export type V2ThreadRollbackResponse__CommandExecutionSource =
30675 | "agent"
30676 | "userShell"
30677 | "unifiedExecStartup"
30678 | "unifiedExecInteraction";
30679export const V2ThreadRollbackResponse__CommandExecutionSource = Schema.Literals([
30680 "agent",
30681 "userShell",
30682 "unifiedExecStartup",
30683 "unifiedExecInteraction",
30684]);
30685
30686export type V2ThreadRollbackResponse__SessionSource =
30687 | "cli"
30688 | "vscode"
30689 | "exec"
30690 | "appServer"
30691 | "unknown"
30692 | { readonly custom: string }
30693 | { readonly subAgent: V2ThreadRollbackResponse__SubAgentSource };
30694export const V2ThreadRollbackResponse__SessionSource = Schema.Union(
30695 [
30696 Schema.Literals(["cli", "vscode", "exec", "appServer", "unknown"]),
30697 Schema.Struct({ custom: Schema.String }).annotate({ title: "CustomSessionSource" }),
30698 Schema.Struct({ subAgent: V2ThreadRollbackResponse__SubAgentSource }).annotate({
30699 title: "SubAgentSessionSource",
30700 }),
30701 ],
30702 { mode: "oneOf" },
30703);
30704
30705export type V2ThreadRollbackResponse__Thread = {
30706 readonly agentNickname?: string | null;
30707 readonly agentRole?: string | null;
30708 readonly cliVersion: string;
30709 readonly createdAt: number;
30710 readonly cwd: string;
30711 readonly ephemeral: boolean;
30712 readonly forkedFromId?: string | null;
30713 readonly gitInfo?: V2ThreadRollbackResponse__GitInfo | null;
30714 readonly id: string;
30715 readonly modelProvider: string;
30716 readonly name?: string | null;
30717 readonly path?: string | null;
30718 readonly preview: string;
30719 readonly source:
30720 | "cli"
30721 | "vscode"
30722 | "exec"
30723 | "appServer"
30724 | "unknown"
30725 | { readonly custom: string }
30726 | { readonly subAgent: V2ThreadRollbackResponse__SubAgentSource };
30727 readonly status:
30728 | { readonly type: "notLoaded" }
30729 | { readonly type: "idle" }
30730 | { readonly type: "systemError" }
30731 | {
30732 readonly activeFlags: ReadonlyArray<V2ThreadRollbackResponse__ThreadActiveFlag>;
30733 readonly type: "active";
30734 };
30735 readonly turns: ReadonlyArray<V2ThreadRollbackResponse__Turn>;
30736 readonly updatedAt: number;
30737};
30738export const V2ThreadRollbackResponse__Thread = Schema.Struct({
30739 agentNickname: Schema.optionalKey(
30740 Schema.Union([
30741 Schema.String.annotate({
30742 description:
30743 "Optional random unique nickname assigned to an AgentControl-spawned sub-agent.",
30744 }),
30745 Schema.Null,
30746 ]),
30747 ),
30748 agentRole: Schema.optionalKey(
30749 Schema.Union([
30750 Schema.String.annotate({
30751 description: "Optional role (agent_role) assigned to an AgentControl-spawned sub-agent.",
30752 }),
30753 Schema.Null,
30754 ]),
30755 ),
30756 cliVersion: Schema.String.annotate({
30757 description: "Version of the CLI that created the thread.",
30758 }),
30759 createdAt: Schema.Number.annotate({
30760 description: "Unix timestamp (in seconds) when the thread was created.",
30761 format: "int64",
30762 }).check(Schema.isInt()),
30763 cwd: Schema.String.annotate({ description: "Working directory captured for the thread." }),
30764 ephemeral: Schema.Boolean.annotate({
30765 description: "Whether the thread is ephemeral and should not be materialized on disk.",
30766 }),
30767 forkedFromId: Schema.optionalKey(
30768 Schema.Union([
30769 Schema.String.annotate({
30770 description: "Source thread id when this thread was created by forking another thread.",
30771 }),
30772 Schema.Null,
30773 ]),
30774 ),
30775 gitInfo: Schema.optionalKey(
30776 Schema.Union([V2ThreadRollbackResponse__GitInfo, Schema.Null]).annotate({
30777 description: "Optional Git metadata captured when the thread was created.",
30778 }),
30779 ),
30780 id: Schema.String,
30781 modelProvider: Schema.String.annotate({
30782 description: "Model provider used for this thread (for example, 'openai').",
30783 }),
30784 name: Schema.optionalKey(
30785 Schema.Union([
30786 Schema.String.annotate({ description: "Optional user-facing thread title." }),
30787 Schema.Null,
30788 ]),
30789 ),
30790 path: Schema.optionalKey(
30791 Schema.Union([
30792 Schema.String.annotate({ description: "[UNSTABLE] Path to the thread on disk." }),
30793 Schema.Null,
30794 ]),
30795 ),
30796 preview: Schema.String.annotate({
30797 description: "Usually the first user message in the thread, if available.",
30798 }),
30799 source: Schema.Union(
30800 [
30801 Schema.Literals(["cli", "vscode", "exec", "appServer", "unknown"]),
30802 Schema.Struct({ custom: Schema.String }).annotate({ title: "CustomSessionSource" }),
30803 Schema.Struct({ subAgent: V2ThreadRollbackResponse__SubAgentSource }).annotate({
30804 title: "SubAgentSessionSource",
30805 }),
30806 ],
30807 { mode: "oneOf" },
30808 ).annotate({
30809 description: "Origin of the thread (CLI, VSCode, codex exec, codex app-server, etc.).",
30810 }),
30811 status: Schema.Union(
30812 [
30813 Schema.Struct({
30814 type: Schema.Literal("notLoaded").annotate({ title: "NotLoadedThreadStatusType" }),
30815 }).annotate({ title: "NotLoadedThreadStatus" }),
30816 Schema.Struct({
30817 type: Schema.Literal("idle").annotate({ title: "IdleThreadStatusType" }),
30818 }).annotate({ title: "IdleThreadStatus" }),
30819 Schema.Struct({
30820 type: Schema.Literal("systemError").annotate({ title: "SystemErrorThreadStatusType" }),
30821 }).annotate({ title: "SystemErrorThreadStatus" }),
30822 Schema.Struct({
30823 activeFlags: Schema.Array(V2ThreadRollbackResponse__ThreadActiveFlag),
30824 type: Schema.Literal("active").annotate({ title: "ActiveThreadStatusType" }),
30825 }).annotate({ title: "ActiveThreadStatus" }),
30826 ],
30827 { mode: "oneOf" },
30828 ).annotate({ description: "Current runtime status for the thread." }),
30829 turns: Schema.Array(V2ThreadRollbackResponse__Turn).annotate({
30830 description:
30831 "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.",
30832 }),
30833 updatedAt: Schema.Number.annotate({
30834 description: "Unix timestamp (in seconds) when the thread was last updated.",
30835 format: "int64",
30836 }).check(Schema.isInt()),
30837});
30838
30839export type V2ThreadRollbackResponse__ThreadStatus =
30840 | { readonly type: "notLoaded" }
30841 | { readonly type: "idle" }
30842 | { readonly type: "systemError" }
30843 | {
30844 readonly activeFlags: ReadonlyArray<V2ThreadRollbackResponse__ThreadActiveFlag>;
30845 readonly type: "active";
30846 };
30847export const V2ThreadRollbackResponse__ThreadStatus = Schema.Union(
30848 [
30849 Schema.Struct({
30850 type: Schema.Literal("notLoaded").annotate({ title: "NotLoadedThreadStatusType" }),
30851 }).annotate({ title: "NotLoadedThreadStatus" }),
30852 Schema.Struct({
30853 type: Schema.Literal("idle").annotate({ title: "IdleThreadStatusType" }),
30854 }).annotate({ title: "IdleThreadStatus" }),
30855 Schema.Struct({
30856 type: Schema.Literal("systemError").annotate({ title: "SystemErrorThreadStatusType" }),
30857 }).annotate({ title: "SystemErrorThreadStatus" }),
30858 Schema.Struct({
30859 activeFlags: Schema.Array(V2ThreadRollbackResponse__ThreadActiveFlag),
30860 type: Schema.Literal("active").annotate({ title: "ActiveThreadStatusType" }),
30861 }).annotate({ title: "ActiveThreadStatus" }),
30862 ],
30863 { mode: "oneOf" },
30864);
30865
30866export type V2ThreadSetNameParams = { readonly name: string; readonly threadId: string };
30867export const V2ThreadSetNameParams = Schema.Struct({
30868 name: Schema.String,
30869 threadId: Schema.String,
30870}).annotate({ title: "ThreadSetNameParams" });
30871
30872export type V2ThreadSetNameResponse = {};
30873export const V2ThreadSetNameResponse = Schema.Struct({}).annotate({
30874 title: "ThreadSetNameResponse",
30875});
30876
30877export type V2ThreadShellCommandParams = { readonly command: string; readonly threadId: string };
30878export const V2ThreadShellCommandParams = Schema.Struct({
30879 command: Schema.String.annotate({
30880 description:
30881 "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.",
30882 }),
30883 threadId: Schema.String,
30884}).annotate({ title: "ThreadShellCommandParams" });
30885
30886export type V2ThreadShellCommandResponse = {};
30887export const V2ThreadShellCommandResponse = Schema.Struct({}).annotate({
30888 title: "ThreadShellCommandResponse",
30889});
30890
30891export type V2ThreadStartedNotification = { readonly thread: V2ThreadStartedNotification__Thread };
30892export const V2ThreadStartedNotification = Schema.Struct({
30893 thread: V2ThreadStartedNotification__Thread,
30894}).annotate({ title: "ThreadStartedNotification" });
30895
30896export type V2ThreadStartedNotification__ByteRange = {
30897 readonly end: number;
30898 readonly start: number;
30899};
30900export const V2ThreadStartedNotification__ByteRange = Schema.Struct({
30901 end: Schema.Number.annotate({ format: "uint" })
30902 .check(Schema.isInt())
30903 .check(Schema.isGreaterThanOrEqualTo(0)),
30904 start: Schema.Number.annotate({ format: "uint" })
30905 .check(Schema.isInt())
30906 .check(Schema.isGreaterThanOrEqualTo(0)),
30907});
30908
30909export type V2ThreadStartedNotification__CollabAgentTool =
30910 | "spawnAgent"
30911 | "sendInput"
30912 | "resumeAgent"
30913 | "wait"
30914 | "closeAgent";
30915export const V2ThreadStartedNotification__CollabAgentTool = Schema.Literals([
30916 "spawnAgent",
30917 "sendInput",
30918 "resumeAgent",
30919 "wait",
30920 "closeAgent",
30921]);
30922
30923export type V2ThreadStartedNotification__CollabAgentToolCallStatus =
30924 | "inProgress"
30925 | "completed"
30926 | "failed";
30927export const V2ThreadStartedNotification__CollabAgentToolCallStatus = Schema.Literals([
30928 "inProgress",
30929 "completed",
30930 "failed",
30931]);
30932
30933export type V2ThreadStartedNotification__CommandExecutionSource =
30934 | "agent"
30935 | "userShell"
30936 | "unifiedExecStartup"
30937 | "unifiedExecInteraction";
30938export const V2ThreadStartedNotification__CommandExecutionSource = Schema.Literals([
30939 "agent",
30940 "userShell",
30941 "unifiedExecStartup",
30942 "unifiedExecInteraction",
30943]);
30944
30945export type V2ThreadStartedNotification__SessionSource =
30946 | "cli"
30947 | "vscode"
30948 | "exec"
30949 | "appServer"
30950 | "unknown"
30951 | { readonly custom: string }
30952 | { readonly subAgent: V2ThreadStartedNotification__SubAgentSource };
30953export const V2ThreadStartedNotification__SessionSource = Schema.Union(
30954 [
30955 Schema.Literals(["cli", "vscode", "exec", "appServer", "unknown"]),
30956 Schema.Struct({ custom: Schema.String }).annotate({ title: "CustomSessionSource" }),
30957 Schema.Struct({ subAgent: V2ThreadStartedNotification__SubAgentSource }).annotate({
30958 title: "SubAgentSessionSource",
30959 }),
30960 ],
30961 { mode: "oneOf" },
30962);
30963
30964export type V2ThreadStartedNotification__ThreadStatus =
30965 | { readonly type: "notLoaded" }
30966 | { readonly type: "idle" }
30967 | { readonly type: "systemError" }
30968 | {
30969 readonly activeFlags: ReadonlyArray<V2ThreadStartedNotification__ThreadActiveFlag>;
30970 readonly type: "active";
30971 };
30972export const V2ThreadStartedNotification__ThreadStatus = Schema.Union(
30973 [
30974 Schema.Struct({
30975 type: Schema.Literal("notLoaded").annotate({ title: "NotLoadedThreadStatusType" }),
30976 }).annotate({ title: "NotLoadedThreadStatus" }),
30977 Schema.Struct({
30978 type: Schema.Literal("idle").annotate({ title: "IdleThreadStatusType" }),
30979 }).annotate({ title: "IdleThreadStatus" }),
30980 Schema.Struct({
30981 type: Schema.Literal("systemError").annotate({ title: "SystemErrorThreadStatusType" }),
30982 }).annotate({ title: "SystemErrorThreadStatus" }),
30983 Schema.Struct({
30984 activeFlags: Schema.Array(V2ThreadStartedNotification__ThreadActiveFlag),
30985 type: Schema.Literal("active").annotate({ title: "ActiveThreadStatusType" }),
30986 }).annotate({ title: "ActiveThreadStatus" }),
30987 ],
30988 { mode: "oneOf" },
30989);
30990
30991export type V2ThreadStartParams = {
30992 readonly approvalPolicy?: V2ThreadStartParams__AskForApproval | null;
30993 readonly approvalsReviewer?: V2ThreadStartParams__ApprovalsReviewer | null;
30994 readonly baseInstructions?: string | null;
30995 readonly config?: { readonly [x: string]: unknown } | null;
30996 readonly cwd?: string | null;
30997 readonly developerInstructions?: string | null;
30998 readonly ephemeral?: boolean | null;
30999 readonly model?: string | null;
31000 readonly modelProvider?: string | null;
31001 readonly personality?: V2ThreadStartParams__Personality | null;
31002 readonly sandbox?: V2ThreadStartParams__SandboxMode | null;
31003 readonly serviceName?: string | null;
31004 readonly serviceTier?: V2ThreadStartParams__ServiceTier | null | null;
31005 readonly sessionStartSource?: V2ThreadStartParams__ThreadStartSource | null;
31006};
31007export const V2ThreadStartParams = Schema.Struct({
31008 approvalPolicy: Schema.optionalKey(
31009 Schema.Union([V2ThreadStartParams__AskForApproval, Schema.Null]),
31010 ),
31011 approvalsReviewer: Schema.optionalKey(
31012 Schema.Union([V2ThreadStartParams__ApprovalsReviewer, Schema.Null]).annotate({
31013 description:
31014 "Override where approval requests are routed for review on this thread and subsequent turns.",
31015 }),
31016 ),
31017 baseInstructions: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
31018 config: Schema.optionalKey(
31019 Schema.Union([Schema.Record(Schema.String, Schema.Unknown), Schema.Null]),
31020 ),
31021 cwd: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
31022 developerInstructions: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
31023 ephemeral: Schema.optionalKey(Schema.Union([Schema.Boolean, Schema.Null])),
31024 model: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
31025 modelProvider: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
31026 personality: Schema.optionalKey(Schema.Union([V2ThreadStartParams__Personality, Schema.Null])),
31027 sandbox: Schema.optionalKey(Schema.Union([V2ThreadStartParams__SandboxMode, Schema.Null])),
31028 serviceName: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
31029 serviceTier: Schema.optionalKey(
31030 Schema.Union([Schema.Union([V2ThreadStartParams__ServiceTier, Schema.Null]), Schema.Null]),
31031 ),
31032 sessionStartSource: Schema.optionalKey(
31033 Schema.Union([V2ThreadStartParams__ThreadStartSource, Schema.Null]),
31034 ),
31035}).annotate({ title: "ThreadStartParams" });
31036
31037export type V2ThreadStartParams__DynamicToolSpec = {
31038 readonly deferLoading?: boolean;
31039 readonly description: string;
31040 readonly inputSchema: unknown;
31041 readonly name: string;
31042};
31043export const V2ThreadStartParams__DynamicToolSpec = Schema.Struct({
31044 deferLoading: Schema.optionalKey(Schema.Boolean),
31045 description: Schema.String,
31046 inputSchema: Schema.Unknown,
31047 name: Schema.String,
31048});
31049
31050export type V2ThreadStartResponse = {
31051 readonly approvalPolicy: V2ThreadStartResponse__AskForApproval;
31052 readonly approvalsReviewer: "user" | "guardian_subagent";
31053 readonly cwd: string;
31054 readonly model: string;
31055 readonly modelProvider: string;
31056 readonly reasoningEffort?: V2ThreadStartResponse__ReasoningEffort | null;
31057 readonly sandbox: V2ThreadStartResponse__SandboxPolicy;
31058 readonly serviceTier?: V2ThreadStartResponse__ServiceTier | null;
31059 readonly thread: V2ThreadStartResponse__Thread;
31060};
31061export const V2ThreadStartResponse = Schema.Struct({
31062 approvalPolicy: V2ThreadStartResponse__AskForApproval,
31063 approvalsReviewer: Schema.Literals(["user", "guardian_subagent"]).annotate({
31064 description:
31065 "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.",
31066 }),
31067 cwd: Schema.String,
31068 model: Schema.String,
31069 modelProvider: Schema.String,
31070 reasoningEffort: Schema.optionalKey(
31071 Schema.Union([V2ThreadStartResponse__ReasoningEffort, Schema.Null]),
31072 ),
31073 sandbox: V2ThreadStartResponse__SandboxPolicy,
31074 serviceTier: Schema.optionalKey(Schema.Union([V2ThreadStartResponse__ServiceTier, Schema.Null])),
31075 thread: V2ThreadStartResponse__Thread,
31076}).annotate({ title: "ThreadStartResponse" });
31077
31078export type V2ThreadStartResponse__ApprovalsReviewer = "user" | "guardian_subagent";
31079export const V2ThreadStartResponse__ApprovalsReviewer = Schema.Literals([
31080 "user",
31081 "guardian_subagent",
31082]).annotate({
31083 description:
31084 "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.",
31085});
31086
31087export type V2ThreadStartResponse__ByteRange = { readonly end: number; readonly start: number };
31088export const V2ThreadStartResponse__ByteRange = Schema.Struct({
31089 end: Schema.Number.annotate({ format: "uint" })
31090 .check(Schema.isInt())
31091 .check(Schema.isGreaterThanOrEqualTo(0)),
31092 start: Schema.Number.annotate({ format: "uint" })
31093 .check(Schema.isInt())
31094 .check(Schema.isGreaterThanOrEqualTo(0)),
31095});
31096
31097export type V2ThreadStartResponse__CollabAgentTool =
31098 | "spawnAgent"
31099 | "sendInput"
31100 | "resumeAgent"
31101 | "wait"
31102 | "closeAgent";
31103export const V2ThreadStartResponse__CollabAgentTool = Schema.Literals([
31104 "spawnAgent",
31105 "sendInput",
31106 "resumeAgent",
31107 "wait",
31108 "closeAgent",
31109]);
31110
31111export type V2ThreadStartResponse__CollabAgentToolCallStatus =
31112 | "inProgress"
31113 | "completed"
31114 | "failed";
31115export const V2ThreadStartResponse__CollabAgentToolCallStatus = Schema.Literals([
31116 "inProgress",
31117 "completed",
31118 "failed",
31119]);
31120
31121export type V2ThreadStartResponse__CommandExecutionSource =
31122 | "agent"
31123 | "userShell"
31124 | "unifiedExecStartup"
31125 | "unifiedExecInteraction";
31126export const V2ThreadStartResponse__CommandExecutionSource = Schema.Literals([
31127 "agent",
31128 "userShell",
31129 "unifiedExecStartup",
31130 "unifiedExecInteraction",
31131]);
31132
31133export type V2ThreadStartResponse__NetworkAccess = "restricted" | "enabled";
31134export const V2ThreadStartResponse__NetworkAccess = Schema.Literals(["restricted", "enabled"]);
31135
31136export type V2ThreadStartResponse__ReadOnlyAccess =
31137 | {
31138 readonly includePlatformDefaults?: boolean;
31139 readonly readableRoots?: ReadonlyArray<V2ThreadStartResponse__AbsolutePathBuf>;
31140 readonly type: "restricted";
31141 }
31142 | { readonly type: "fullAccess" };
31143export const V2ThreadStartResponse__ReadOnlyAccess = Schema.Union(
31144 [
31145 Schema.Struct({
31146 includePlatformDefaults: Schema.optionalKey(Schema.Boolean.annotate({ default: true })),
31147 readableRoots: Schema.optionalKey(
31148 Schema.Array(V2ThreadStartResponse__AbsolutePathBuf).annotate({ default: [] }),
31149 ),
31150 type: Schema.Literal("restricted").annotate({ title: "RestrictedReadOnlyAccessType" }),
31151 }).annotate({ title: "RestrictedReadOnlyAccess" }),
31152 Schema.Struct({
31153 type: Schema.Literal("fullAccess").annotate({ title: "FullAccessReadOnlyAccessType" }),
31154 }).annotate({ title: "FullAccessReadOnlyAccess" }),
31155 ],
31156 { mode: "oneOf" },
31157);
31158
31159export type V2ThreadStartResponse__SessionSource =
31160 | "cli"
31161 | "vscode"
31162 | "exec"
31163 | "appServer"
31164 | "unknown"
31165 | { readonly custom: string }
31166 | { readonly subAgent: V2ThreadStartResponse__SubAgentSource };
31167export const V2ThreadStartResponse__SessionSource = Schema.Union(
31168 [
31169 Schema.Literals(["cli", "vscode", "exec", "appServer", "unknown"]),
31170 Schema.Struct({ custom: Schema.String }).annotate({ title: "CustomSessionSource" }),
31171 Schema.Struct({ subAgent: V2ThreadStartResponse__SubAgentSource }).annotate({
31172 title: "SubAgentSessionSource",
31173 }),
31174 ],
31175 { mode: "oneOf" },
31176);
31177
31178export type V2ThreadStartResponse__ThreadStatus =
31179 | { readonly type: "notLoaded" }
31180 | { readonly type: "idle" }
31181 | { readonly type: "systemError" }
31182 | {
31183 readonly activeFlags: ReadonlyArray<V2ThreadStartResponse__ThreadActiveFlag>;
31184 readonly type: "active";
31185 };
31186export const V2ThreadStartResponse__ThreadStatus = Schema.Union(
31187 [
31188 Schema.Struct({
31189 type: Schema.Literal("notLoaded").annotate({ title: "NotLoadedThreadStatusType" }),
31190 }).annotate({ title: "NotLoadedThreadStatus" }),
31191 Schema.Struct({
31192 type: Schema.Literal("idle").annotate({ title: "IdleThreadStatusType" }),
31193 }).annotate({ title: "IdleThreadStatus" }),
31194 Schema.Struct({
31195 type: Schema.Literal("systemError").annotate({ title: "SystemErrorThreadStatusType" }),
31196 }).annotate({ title: "SystemErrorThreadStatus" }),
31197 Schema.Struct({
31198 activeFlags: Schema.Array(V2ThreadStartResponse__ThreadActiveFlag),
31199 type: Schema.Literal("active").annotate({ title: "ActiveThreadStatusType" }),
31200 }).annotate({ title: "ActiveThreadStatus" }),
31201 ],
31202 { mode: "oneOf" },
31203);
31204
31205export type V2ThreadStatusChangedNotification = {
31206 readonly status: V2ThreadStatusChangedNotification__ThreadStatus;
31207 readonly threadId: string;
31208};
31209export const V2ThreadStatusChangedNotification = Schema.Struct({
31210 status: V2ThreadStatusChangedNotification__ThreadStatus,
31211 threadId: Schema.String,
31212}).annotate({ title: "ThreadStatusChangedNotification" });
31213
31214export type V2ThreadTokenUsageUpdatedNotification = {
31215 readonly threadId: string;
31216 readonly tokenUsage: V2ThreadTokenUsageUpdatedNotification__ThreadTokenUsage;
31217 readonly turnId: string;
31218};
31219export const V2ThreadTokenUsageUpdatedNotification = Schema.Struct({
31220 threadId: Schema.String,
31221 tokenUsage: V2ThreadTokenUsageUpdatedNotification__ThreadTokenUsage,
31222 turnId: Schema.String,
31223}).annotate({ title: "ThreadTokenUsageUpdatedNotification" });
31224
31225export type V2ThreadUnarchivedNotification = { readonly threadId: string };
31226export const V2ThreadUnarchivedNotification = Schema.Struct({ threadId: Schema.String }).annotate({
31227 title: "ThreadUnarchivedNotification",
31228});
31229
31230export type V2ThreadUnarchiveParams = { readonly threadId: string };
31231export const V2ThreadUnarchiveParams = Schema.Struct({ threadId: Schema.String }).annotate({
31232 title: "ThreadUnarchiveParams",
31233});
31234
31235export type V2ThreadUnarchiveResponse = { readonly thread: V2ThreadUnarchiveResponse__Thread };
31236export const V2ThreadUnarchiveResponse = Schema.Struct({
31237 thread: V2ThreadUnarchiveResponse__Thread,
31238}).annotate({ title: "ThreadUnarchiveResponse" });
31239
31240export type V2ThreadUnarchiveResponse__ByteRange = { readonly end: number; readonly start: number };
31241export const V2ThreadUnarchiveResponse__ByteRange = Schema.Struct({
31242 end: Schema.Number.annotate({ format: "uint" })
31243 .check(Schema.isInt())
31244 .check(Schema.isGreaterThanOrEqualTo(0)),
31245 start: Schema.Number.annotate({ format: "uint" })
31246 .check(Schema.isInt())
31247 .check(Schema.isGreaterThanOrEqualTo(0)),
31248});
31249
31250export type V2ThreadUnarchiveResponse__CollabAgentTool =
31251 | "spawnAgent"
31252 | "sendInput"
31253 | "resumeAgent"
31254 | "wait"
31255 | "closeAgent";
31256export const V2ThreadUnarchiveResponse__CollabAgentTool = Schema.Literals([
31257 "spawnAgent",
31258 "sendInput",
31259 "resumeAgent",
31260 "wait",
31261 "closeAgent",
31262]);
31263
31264export type V2ThreadUnarchiveResponse__CollabAgentToolCallStatus =
31265 | "inProgress"
31266 | "completed"
31267 | "failed";
31268export const V2ThreadUnarchiveResponse__CollabAgentToolCallStatus = Schema.Literals([
31269 "inProgress",
31270 "completed",
31271 "failed",
31272]);
31273
31274export type V2ThreadUnarchiveResponse__CommandExecutionSource =
31275 | "agent"
31276 | "userShell"
31277 | "unifiedExecStartup"
31278 | "unifiedExecInteraction";
31279export const V2ThreadUnarchiveResponse__CommandExecutionSource = Schema.Literals([
31280 "agent",
31281 "userShell",
31282 "unifiedExecStartup",
31283 "unifiedExecInteraction",
31284]);
31285
31286export type V2ThreadUnarchiveResponse__SessionSource =
31287 | "cli"
31288 | "vscode"
31289 | "exec"
31290 | "appServer"
31291 | "unknown"
31292 | { readonly custom: string }
31293 | { readonly subAgent: V2ThreadUnarchiveResponse__SubAgentSource };
31294export const V2ThreadUnarchiveResponse__SessionSource = Schema.Union(
31295 [
31296 Schema.Literals(["cli", "vscode", "exec", "appServer", "unknown"]),
31297 Schema.Struct({ custom: Schema.String }).annotate({ title: "CustomSessionSource" }),
31298 Schema.Struct({ subAgent: V2ThreadUnarchiveResponse__SubAgentSource }).annotate({
31299 title: "SubAgentSessionSource",
31300 }),
31301 ],
31302 { mode: "oneOf" },
31303);
31304
31305export type V2ThreadUnarchiveResponse__ThreadStatus =
31306 | { readonly type: "notLoaded" }
31307 | { readonly type: "idle" }
31308 | { readonly type: "systemError" }
31309 | {
31310 readonly activeFlags: ReadonlyArray<V2ThreadUnarchiveResponse__ThreadActiveFlag>;
31311 readonly type: "active";
31312 };
31313export const V2ThreadUnarchiveResponse__ThreadStatus = Schema.Union(
31314 [
31315 Schema.Struct({
31316 type: Schema.Literal("notLoaded").annotate({ title: "NotLoadedThreadStatusType" }),
31317 }).annotate({ title: "NotLoadedThreadStatus" }),
31318 Schema.Struct({
31319 type: Schema.Literal("idle").annotate({ title: "IdleThreadStatusType" }),
31320 }).annotate({ title: "IdleThreadStatus" }),
31321 Schema.Struct({
31322 type: Schema.Literal("systemError").annotate({ title: "SystemErrorThreadStatusType" }),
31323 }).annotate({ title: "SystemErrorThreadStatus" }),
31324 Schema.Struct({
31325 activeFlags: Schema.Array(V2ThreadUnarchiveResponse__ThreadActiveFlag),
31326 type: Schema.Literal("active").annotate({ title: "ActiveThreadStatusType" }),
31327 }).annotate({ title: "ActiveThreadStatus" }),
31328 ],
31329 { mode: "oneOf" },
31330);
31331
31332export type V2ThreadUnsubscribeParams = { readonly threadId: string };
31333export const V2ThreadUnsubscribeParams = Schema.Struct({ threadId: Schema.String }).annotate({
31334 title: "ThreadUnsubscribeParams",
31335});
31336
31337export type V2ThreadUnsubscribeResponse = {
31338 readonly status: V2ThreadUnsubscribeResponse__ThreadUnsubscribeStatus;
31339};
31340export const V2ThreadUnsubscribeResponse = Schema.Struct({
31341 status: V2ThreadUnsubscribeResponse__ThreadUnsubscribeStatus,
31342}).annotate({ title: "ThreadUnsubscribeResponse" });
31343
31344export type V2TurnCompletedNotification = {
31345 readonly threadId: string;
31346 readonly turn: V2TurnCompletedNotification__Turn;
31347};
31348export const V2TurnCompletedNotification = Schema.Struct({
31349 threadId: Schema.String,
31350 turn: V2TurnCompletedNotification__Turn,
31351}).annotate({ title: "TurnCompletedNotification" });
31352
31353export type V2TurnCompletedNotification__ByteRange = {
31354 readonly end: number;
31355 readonly start: number;
31356};
31357export const V2TurnCompletedNotification__ByteRange = Schema.Struct({
31358 end: Schema.Number.annotate({ format: "uint" })
31359 .check(Schema.isInt())
31360 .check(Schema.isGreaterThanOrEqualTo(0)),
31361 start: Schema.Number.annotate({ format: "uint" })
31362 .check(Schema.isInt())
31363 .check(Schema.isGreaterThanOrEqualTo(0)),
31364});
31365
31366export type V2TurnCompletedNotification__CollabAgentTool =
31367 | "spawnAgent"
31368 | "sendInput"
31369 | "resumeAgent"
31370 | "wait"
31371 | "closeAgent";
31372export const V2TurnCompletedNotification__CollabAgentTool = Schema.Literals([
31373 "spawnAgent",
31374 "sendInput",
31375 "resumeAgent",
31376 "wait",
31377 "closeAgent",
31378]);
31379
31380export type V2TurnCompletedNotification__CollabAgentToolCallStatus =
31381 | "inProgress"
31382 | "completed"
31383 | "failed";
31384export const V2TurnCompletedNotification__CollabAgentToolCallStatus = Schema.Literals([
31385 "inProgress",
31386 "completed",
31387 "failed",
31388]);
31389
31390export type V2TurnCompletedNotification__CommandExecutionSource =
31391 | "agent"
31392 | "userShell"
31393 | "unifiedExecStartup"
31394 | "unifiedExecInteraction";
31395export const V2TurnCompletedNotification__CommandExecutionSource = Schema.Literals([
31396 "agent",
31397 "userShell",
31398 "unifiedExecStartup",
31399 "unifiedExecInteraction",
31400]);
31401
31402export type V2TurnDiffUpdatedNotification = {
31403 readonly diff: string;
31404 readonly threadId: string;
31405 readonly turnId: string;
31406};
31407export const V2TurnDiffUpdatedNotification = Schema.Struct({
31408 diff: Schema.String,
31409 threadId: Schema.String,
31410 turnId: Schema.String,
31411}).annotate({
31412 title: "TurnDiffUpdatedNotification",
31413 description:
31414 "Notification that the turn-level unified diff has changed. Contains the latest aggregated diff across all file changes in the turn.",
31415});
31416
31417export type V2TurnInterruptParams = { readonly threadId: string; readonly turnId: string };
31418export const V2TurnInterruptParams = Schema.Struct({
31419 threadId: Schema.String,
31420 turnId: Schema.String,
31421}).annotate({ title: "TurnInterruptParams" });
31422
31423export type V2TurnInterruptResponse = {};
31424export const V2TurnInterruptResponse = Schema.Struct({}).annotate({
31425 title: "TurnInterruptResponse",
31426});
31427
31428export type V2TurnPlanUpdatedNotification = {
31429 readonly explanation?: string | null;
31430 readonly plan: ReadonlyArray<V2TurnPlanUpdatedNotification__TurnPlanStep>;
31431 readonly threadId: string;
31432 readonly turnId: string;
31433};
31434export const V2TurnPlanUpdatedNotification = Schema.Struct({
31435 explanation: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
31436 plan: Schema.Array(V2TurnPlanUpdatedNotification__TurnPlanStep),
31437 threadId: Schema.String,
31438 turnId: Schema.String,
31439}).annotate({ title: "TurnPlanUpdatedNotification" });
31440
31441export type V2TurnStartedNotification = {
31442 readonly threadId: string;
31443 readonly turn: V2TurnStartedNotification__Turn;
31444};
31445export const V2TurnStartedNotification = Schema.Struct({
31446 threadId: Schema.String,
31447 turn: V2TurnStartedNotification__Turn,
31448}).annotate({ title: "TurnStartedNotification" });
31449
31450export type V2TurnStartedNotification__ByteRange = { readonly end: number; readonly start: number };
31451export const V2TurnStartedNotification__ByteRange = Schema.Struct({
31452 end: Schema.Number.annotate({ format: "uint" })
31453 .check(Schema.isInt())
31454 .check(Schema.isGreaterThanOrEqualTo(0)),
31455 start: Schema.Number.annotate({ format: "uint" })
31456 .check(Schema.isInt())
31457 .check(Schema.isGreaterThanOrEqualTo(0)),
31458});
31459
31460export type V2TurnStartedNotification__CollabAgentTool =
31461 | "spawnAgent"
31462 | "sendInput"
31463 | "resumeAgent"
31464 | "wait"
31465 | "closeAgent";
31466export const V2TurnStartedNotification__CollabAgentTool = Schema.Literals([
31467 "spawnAgent",
31468 "sendInput",
31469 "resumeAgent",
31470 "wait",
31471 "closeAgent",
31472]);
31473
31474export type V2TurnStartedNotification__CollabAgentToolCallStatus =
31475 | "inProgress"
31476 | "completed"
31477 | "failed";
31478export const V2TurnStartedNotification__CollabAgentToolCallStatus = Schema.Literals([
31479 "inProgress",
31480 "completed",
31481 "failed",
31482]);
31483
31484export type V2TurnStartedNotification__CommandExecutionSource =
31485 | "agent"
31486 | "userShell"
31487 | "unifiedExecStartup"
31488 | "unifiedExecInteraction";
31489export const V2TurnStartedNotification__CommandExecutionSource = Schema.Literals([
31490 "agent",
31491 "userShell",
31492 "unifiedExecStartup",
31493 "unifiedExecInteraction",
31494]);
31495
31496export type V2TurnStartParams = {
31497 readonly approvalPolicy?: V2TurnStartParams__AskForApproval | null;
31498 readonly approvalsReviewer?: V2TurnStartParams__ApprovalsReviewer | null;
31499 readonly cwd?: string | null;
31500 readonly effort?: V2TurnStartParams__ReasoningEffort | null;
31501 readonly input: ReadonlyArray<V2TurnStartParams__UserInput>;
31502 readonly model?: string | null;
31503 readonly outputSchema?: unknown;
31504 readonly personality?: V2TurnStartParams__Personality | null;
31505 readonly sandboxPolicy?: V2TurnStartParams__SandboxPolicy | null;
31506 readonly serviceTier?: V2TurnStartParams__ServiceTier | null | null;
31507 readonly summary?: V2TurnStartParams__ReasoningSummary | null;
31508 readonly threadId: string;
31509};
31510export const V2TurnStartParams = Schema.Struct({
31511 approvalPolicy: Schema.optionalKey(
31512 Schema.Union([V2TurnStartParams__AskForApproval, Schema.Null]).annotate({
31513 description: "Override the approval policy for this turn and subsequent turns.",
31514 }),
31515 ),
31516 approvalsReviewer: Schema.optionalKey(
31517 Schema.Union([V2TurnStartParams__ApprovalsReviewer, Schema.Null]).annotate({
31518 description:
31519 "Override where approval requests are routed for review on this turn and subsequent turns.",
31520 }),
31521 ),
31522 cwd: Schema.optionalKey(
31523 Schema.Union([
31524 Schema.String.annotate({
31525 description: "Override the working directory for this turn and subsequent turns.",
31526 }),
31527 Schema.Null,
31528 ]),
31529 ),
31530 effort: Schema.optionalKey(
31531 Schema.Union([V2TurnStartParams__ReasoningEffort, Schema.Null]).annotate({
31532 description: "Override the reasoning effort for this turn and subsequent turns.",
31533 }),
31534 ),
31535 input: Schema.Array(V2TurnStartParams__UserInput),
31536 model: Schema.optionalKey(
31537 Schema.Union([
31538 Schema.String.annotate({
31539 description: "Override the model for this turn and subsequent turns.",
31540 }),
31541 Schema.Null,
31542 ]),
31543 ),
31544 outputSchema: Schema.optionalKey(
31545 Schema.Unknown.annotate({
31546 description:
31547 "Optional JSON Schema used to constrain the final assistant message for this turn.",
31548 }),
31549 ),
31550 personality: Schema.optionalKey(
31551 Schema.Union([V2TurnStartParams__Personality, Schema.Null]).annotate({
31552 description: "Override the personality for this turn and subsequent turns.",
31553 }),
31554 ),
31555 sandboxPolicy: Schema.optionalKey(
31556 Schema.Union([V2TurnStartParams__SandboxPolicy, Schema.Null]).annotate({
31557 description: "Override the sandbox policy for this turn and subsequent turns.",
31558 }),
31559 ),
31560 serviceTier: Schema.optionalKey(
31561 Schema.Union([
31562 Schema.Union([V2TurnStartParams__ServiceTier, Schema.Null]),
31563 Schema.Null,
31564 ]).annotate({ description: "Override the service tier for this turn and subsequent turns." }),
31565 ),
31566 summary: Schema.optionalKey(
31567 Schema.Union([V2TurnStartParams__ReasoningSummary, Schema.Null]).annotate({
31568 description: "Override the reasoning summary for this turn and subsequent turns.",
31569 }),
31570 ),
31571 threadId: Schema.String,
31572}).annotate({ title: "TurnStartParams" });
31573
31574export type V2TurnStartParams__ByteRange = { readonly end: number; readonly start: number };
31575export const V2TurnStartParams__ByteRange = Schema.Struct({
31576 end: Schema.Number.annotate({ format: "uint" })
31577 .check(Schema.isInt())
31578 .check(Schema.isGreaterThanOrEqualTo(0)),
31579 start: Schema.Number.annotate({ format: "uint" })
31580 .check(Schema.isInt())
31581 .check(Schema.isGreaterThanOrEqualTo(0)),
31582});
31583
31584export type V2TurnStartParams__CollaborationMode = {
31585 readonly mode: V2TurnStartParams__ModeKind;
31586 readonly settings: V2TurnStartParams__Settings;
31587};
31588export const V2TurnStartParams__CollaborationMode = Schema.Struct({
31589 mode: V2TurnStartParams__ModeKind,
31590 settings: V2TurnStartParams__Settings,
31591}).annotate({ description: "Collaboration mode for a Codex session." });
31592
31593export type V2TurnStartParams__NetworkAccess = "restricted" | "enabled";
31594export const V2TurnStartParams__NetworkAccess = Schema.Literals(["restricted", "enabled"]);
31595
31596export type V2TurnStartParams__ReadOnlyAccess =
31597 | {
31598 readonly includePlatformDefaults?: boolean;
31599 readonly readableRoots?: ReadonlyArray<V2TurnStartParams__AbsolutePathBuf>;
31600 readonly type: "restricted";
31601 }
31602 | { readonly type: "fullAccess" };
31603export const V2TurnStartParams__ReadOnlyAccess = Schema.Union(
31604 [
31605 Schema.Struct({
31606 includePlatformDefaults: Schema.optionalKey(Schema.Boolean.annotate({ default: true })),
31607 readableRoots: Schema.optionalKey(
31608 Schema.Array(V2TurnStartParams__AbsolutePathBuf).annotate({ default: [] }),
31609 ),
31610 type: Schema.Literal("restricted").annotate({ title: "RestrictedReadOnlyAccessType" }),
31611 }).annotate({ title: "RestrictedReadOnlyAccess" }),
31612 Schema.Struct({
31613 type: Schema.Literal("fullAccess").annotate({ title: "FullAccessReadOnlyAccessType" }),
31614 }).annotate({ title: "FullAccessReadOnlyAccess" }),
31615 ],
31616 { mode: "oneOf" },
31617);
31618
31619export type V2TurnStartResponse = { readonly turn: V2TurnStartResponse__Turn };
31620export const V2TurnStartResponse = Schema.Struct({ turn: V2TurnStartResponse__Turn }).annotate({
31621 title: "TurnStartResponse",
31622});
31623
31624export type V2TurnStartResponse__ByteRange = { readonly end: number; readonly start: number };
31625export const V2TurnStartResponse__ByteRange = Schema.Struct({
31626 end: Schema.Number.annotate({ format: "uint" })
31627 .check(Schema.isInt())
31628 .check(Schema.isGreaterThanOrEqualTo(0)),
31629 start: Schema.Number.annotate({ format: "uint" })
31630 .check(Schema.isInt())
31631 .check(Schema.isGreaterThanOrEqualTo(0)),
31632});
31633
31634export type V2TurnStartResponse__CollabAgentTool =
31635 | "spawnAgent"
31636 | "sendInput"
31637 | "resumeAgent"
31638 | "wait"
31639 | "closeAgent";
31640export const V2TurnStartResponse__CollabAgentTool = Schema.Literals([
31641 "spawnAgent",
31642 "sendInput",
31643 "resumeAgent",
31644 "wait",
31645 "closeAgent",
31646]);
31647
31648export type V2TurnStartResponse__CollabAgentToolCallStatus = "inProgress" | "completed" | "failed";
31649export const V2TurnStartResponse__CollabAgentToolCallStatus = Schema.Literals([
31650 "inProgress",
31651 "completed",
31652 "failed",
31653]);
31654
31655export type V2TurnStartResponse__CommandExecutionSource =
31656 | "agent"
31657 | "userShell"
31658 | "unifiedExecStartup"
31659 | "unifiedExecInteraction";
31660export const V2TurnStartResponse__CommandExecutionSource = Schema.Literals([
31661 "agent",
31662 "userShell",
31663 "unifiedExecStartup",
31664 "unifiedExecInteraction",
31665]);
31666
31667export type V2TurnSteerParams = {
31668 readonly expectedTurnId: string;
31669 readonly input: ReadonlyArray<V2TurnSteerParams__UserInput>;
31670 readonly threadId: string;
31671};
31672export const V2TurnSteerParams = Schema.Struct({
31673 expectedTurnId: Schema.String.annotate({
31674 description:
31675 "Required active turn id precondition. The request fails when it does not match the currently active turn.",
31676 }),
31677 input: Schema.Array(V2TurnSteerParams__UserInput),
31678 threadId: Schema.String,
31679}).annotate({ title: "TurnSteerParams" });
31680
31681export type V2TurnSteerParams__ByteRange = { readonly end: number; readonly start: number };
31682export const V2TurnSteerParams__ByteRange = Schema.Struct({
31683 end: Schema.Number.annotate({ format: "uint" })
31684 .check(Schema.isInt())
31685 .check(Schema.isGreaterThanOrEqualTo(0)),
31686 start: Schema.Number.annotate({ format: "uint" })
31687 .check(Schema.isInt())
31688 .check(Schema.isGreaterThanOrEqualTo(0)),
31689});
31690
31691export type V2TurnSteerResponse = { readonly turnId: string };
31692export const V2TurnSteerResponse = Schema.Struct({ turnId: Schema.String }).annotate({
31693 title: "TurnSteerResponse",
31694});
31695
31696export type V2WindowsSandboxSetupCompletedNotification = {
31697 readonly error?: string | null;
31698 readonly mode: V2WindowsSandboxSetupCompletedNotification__WindowsSandboxSetupMode;
31699 readonly success: boolean;
31700};
31701export const V2WindowsSandboxSetupCompletedNotification = Schema.Struct({
31702 error: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
31703 mode: V2WindowsSandboxSetupCompletedNotification__WindowsSandboxSetupMode,
31704 success: Schema.Boolean,
31705}).annotate({ title: "WindowsSandboxSetupCompletedNotification" });
31706
31707export type V2WindowsSandboxSetupStartParams = {
31708 readonly cwd?: V2WindowsSandboxSetupStartParams__AbsolutePathBuf | null;
31709 readonly mode: V2WindowsSandboxSetupStartParams__WindowsSandboxSetupMode;
31710};
31711export const V2WindowsSandboxSetupStartParams = Schema.Struct({
31712 cwd: Schema.optionalKey(
31713 Schema.Union([V2WindowsSandboxSetupStartParams__AbsolutePathBuf, Schema.Null]),
31714 ),
31715 mode: V2WindowsSandboxSetupStartParams__WindowsSandboxSetupMode,
31716}).annotate({ title: "WindowsSandboxSetupStartParams" });
31717
31718export type V2WindowsSandboxSetupStartResponse = { readonly started: boolean };
31719export const V2WindowsSandboxSetupStartResponse = Schema.Struct({
31720 started: Schema.Boolean,
31721}).annotate({ title: "WindowsSandboxSetupStartResponse" });
31722
31723export type V2WindowsWorldWritableWarningNotification = {
31724 readonly extraCount: number;
31725 readonly failedScan: boolean;
31726 readonly samplePaths: ReadonlyArray<string>;
31727};
31728export const V2WindowsWorldWritableWarningNotification = Schema.Struct({
31729 extraCount: Schema.Number.annotate({ format: "uint" })
31730 .check(Schema.isInt())
31731 .check(Schema.isGreaterThanOrEqualTo(0)),
31732 failedScan: Schema.Boolean,
31733 samplePaths: Schema.Array(Schema.String),
31734}).annotate({ title: "WindowsWorldWritableWarningNotification" });
packages/effect-codex-app-server/src/_internal/shared.ts created+101
...@@ -0,0 +1,101 @@
1import * as Effect from "effect/Effect";
2import * as Schema from "effect/Schema";
3import * as SchemaIssue from "effect/SchemaIssue";
4
5import * as CodexError from "../errors.ts";
6
7const formatSchemaIssue = SchemaIssue.makeFormatterDefault();
8
9export const JsonRpcId = Schema.Union([Schema.Number, Schema.String]);
10
11export const JsonRpcError = Schema.Struct({
12 code: Schema.Number,
13 message: Schema.String,
14 data: Schema.optional(Schema.Unknown),
15});
16
17export const JsonRpcResponseEnvelope = Schema.Struct({
18 id: JsonRpcId,
19 result: Schema.optional(Schema.Unknown),
20 error: Schema.optional(JsonRpcError),
21});
22
23export const decodeOptionalPayload = <A, I>(
24 method: string,
25 schema: Schema.Codec<A, I> | undefined,
26 raw: unknown,
27): Effect.Effect<A, CodexError.CodexAppServerRequestError> => {
28 if (!schema) {
29 if (raw === undefined) {
30 return Effect.sync(() => undefined as A);
31 }
32 return Effect.fail(
33 CodexError.CodexAppServerRequestError.invalidParams(`${method} does not accept params`, raw),
34 );
35 }
36
37 return Schema.decodeUnknownEffect(schema)(raw).pipe(
38 Effect.mapError((error) =>
39 CodexError.CodexAppServerRequestError.invalidParams(
40 `Invalid ${method} payload: ${formatSchemaIssue(error.issue)}`,
41 { issue: error.issue },
42 ),
43 ),
44 );
45};
46
47export const encodeOptionalPayload = <A, I>(
48 method: string,
49 schema: Schema.Codec<A, I> | undefined,
50 payload: A,
51): Effect.Effect<I | undefined, CodexError.CodexAppServerRequestError> => {
52 if (!schema) {
53 if (payload === undefined) {
54 return Effect.sync(() => undefined);
55 }
56 return Effect.fail(
57 CodexError.CodexAppServerRequestError.invalidParams(
58 `${method} does not accept params`,
59 payload,
60 ),
61 );
62 }
63
64 return Schema.encodeEffect(schema)(payload).pipe(
65 Effect.mapError((error) =>
66 CodexError.CodexAppServerRequestError.invalidParams(
67 `Invalid ${method} payload: ${formatSchemaIssue(error.issue)}`,
68 { issue: error.issue },
69 ),
70 ),
71 );
72};
73
74export const decodeNotificationPayload = <A, I>(
75 method: string,
76 schema: Schema.Codec<A, I> | undefined,
77 raw: unknown,
78): Effect.Effect<A, CodexError.CodexAppServerProtocolParseError> =>
79 decodeOptionalPayload(method, schema, raw).pipe(
80 Effect.mapError(
81 (error) =>
82 new CodexError.CodexAppServerProtocolParseError({
83 detail: error.message,
84 cause: error,
85 }),
86 ),
87 );
88
89export const runHandler = Effect.fnUntraced(function* <A, B>(
90 handler: ((payload: A) => Effect.Effect<B, CodexError.CodexAppServerError>) | undefined,
91 payload: A,
92 method: string,
93) {
94 if (!handler) {
95 return yield* CodexError.CodexAppServerRequestError.methodNotFound(method);
96 }
97
98 return yield* handler(payload).pipe(
99 Effect.mapError((error) => CodexError.normalizeToRequestError(error)),
100 );
101});
packages/effect-codex-app-server/src/_internal/stdio.ts created+57
...@@ -0,0 +1,57 @@
1import * as Cause from "effect/Cause";
2import * as Effect from "effect/Effect";
3import * as Queue from "effect/Queue";
4import * as Sink from "effect/Sink";
5import * as Stdio from "effect/Stdio";
6import * as Stream from "effect/Stream";
7import { ChildProcessSpawner } from "effect/unstable/process";
8
9import * as CodexError from "../errors.ts";
10
11const encoder = new TextEncoder();
12
13export const makeChildStdio = (handle: ChildProcessSpawner.ChildProcessHandle) =>
14 Stdio.make({
15 args: Effect.succeed([]),
16 stdin: handle.stdout,
17 stdout: () =>
18 Sink.mapInput(handle.stdin, (chunk: string | Uint8Array) =>
19 typeof chunk === "string" ? encoder.encode(chunk) : chunk,
20 ),
21 stderr: () => Sink.drain,
22 });
23
24export const makeInMemoryStdio = Effect.fn("makeInMemoryStdio")(function* () {
25 const input = yield* Queue.unbounded<Uint8Array, Cause.Done<void>>();
26 const output = yield* Queue.unbounded<string>();
27 const decoder = new TextDecoder();
28
29 return {
30 stdio: Stdio.make({
31 args: Effect.succeed([]),
32 stdin: Stream.fromQueue(input),
33 stdout: () =>
34 Sink.forEach((chunk: string | Uint8Array) =>
35 Queue.offer(
36 output,
37 typeof chunk === "string" ? chunk : decoder.decode(chunk, { stream: true }),
38 ),
39 ),
40 stderr: () => Sink.drain,
41 }),
42 input,
43 output,
44 };
45});
46
47export const makeTerminationError = (
48 handle: ChildProcessSpawner.ChildProcessHandle,
49): Effect.Effect<CodexError.CodexAppServerError> =>
50 Effect.match(handle.exitCode, {
51 onFailure: (cause) =>
52 new CodexError.CodexAppServerTransportError({
53 detail: "Failed to determine Codex App Server process exit status",
54 cause,
55 }),
56 onSuccess: (code) => new CodexError.CodexAppServerProcessExitedError({ code }),
57 });
packages/effect-codex-app-server/src/client.test.ts created+154
...@@ -0,0 +1,154 @@
1import * as Exit from "effect/Exit";
2import * as Layer from "effect/Layer";
3import * as Path from "effect/Path";
4import * as Effect from "effect/Effect";
5import * as Ref from "effect/Ref";
6import * as Scope from "effect/Scope";
7import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
8
9import * as NodeServices from "@effect/platform-node/NodeServices";
10import { assert, it } from "@effect/vitest";
11
12import * as CodexClient from "./client.ts";
13
14const mockPeerPath = Effect.map(Effect.service(Path.Path), (path) =>
15 path.join(import.meta.dirname, "../test/fixtures/codex-app-server-mock-peer.ts"),
16);
17
18it.layer(NodeServices.layer)("effect-codex-app-server client", (it) => {
19 const makeHandle = () =>
20 Effect.gen(function* () {
21 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
22 const path = yield* Path.Path;
23 const command = ChildProcess.make("bun", ["run", yield* mockPeerPath], {
24 cwd: path.join(import.meta.dirname, ".."),
25 shell: process.platform === "win32",
26 });
27 return yield* spawner.spawn(command);
28 });
29
30 it.effect("initializes, handles typed server requests, and reads account and skills data", () =>
31 Effect.gen(function* () {
32 const userInputRequests = yield* Ref.make<Array<unknown>>([]);
33 const messageDeltas = yield* Ref.make<Array<unknown>>([]);
34 const handle = yield* makeHandle();
35 const scope = yield* Scope.make();
36 const clientLayer = CodexClient.layerChildProcess(handle);
37 const context = yield* Layer.buildWithScope(clientLayer, scope);
38
39 const result = yield* Effect.gen(function* () {
40 const client = yield* CodexClient.CodexAppServerClient;
41
42 yield* client.handleServerRequest("item/tool/requestUserInput", (payload) =>
43 Ref.update(userInputRequests, (current) => [...current, payload]).pipe(
44 Effect.as({
45 answers: {
46 approved: {
47 answers: ["yes"],
48 },
49 },
50 }),
51 ),
52 );
53
54 yield* client.handleServerNotification("item/agentMessage/delta", (payload) =>
55 Ref.update(messageDeltas, (current) => [...current, payload]),
56 );
57
58 const initialized = yield* client.request("initialize", {
59 clientInfo: {
60 name: "effect-codex-app-server-test",
61 title: "Effect Codex App Server Test",
62 version: "0.0.0",
63 },
64 capabilities: {
65 experimentalApi: true,
66 optOutNotificationMethods: null,
67 },
68 });
69 assert.equal(initialized.userAgent, "mock-codex-app-server");
70
71 yield* client.notify("initialized", undefined);
72
73 const account = yield* client.request("account/read", {});
74 assert.equal(account.requiresOpenaiAuth, false);
75 assert.deepEqual(account.account, {
76 type: "chatgpt",
77 email: "mock@example.com",
78 planType: "plus",
79 });
80
81 const skills = yield* client.request("skills/list", {
82 cwds: [process.cwd()],
83 });
84 assert.equal(skills.data.length, 1);
85 assert.equal(skills.data[0]?.cwd, process.cwd());
86
87 return {
88 account,
89 skills,
90 };
91 }).pipe(Effect.provide(context), Effect.ensuring(Scope.close(scope, Exit.void)));
92
93 assert.equal(result.skills.data[0]?.skills.length, 0);
94 assert.deepEqual(yield* Ref.get(userInputRequests), [
95 {
96 itemId: "item-approval-1",
97 threadId: "thread-1",
98 turnId: "turn-1",
99 questions: [
100 {
101 id: "approved",
102 header: "Approve",
103 question: "Continue with the mock skills request?",
104 options: [
105 {
106 label: "yes",
107 description: "Approve the request",
108 },
109 ],
110 },
111 ],
112 },
113 ]);
114 assert.deepEqual(yield* Ref.get(messageDeltas), [
115 {
116 delta: "Mock server is ready.",
117 itemId: "item-1",
118 threadId: "thread-1",
119 turnId: "turn-1",
120 },
121 ]);
122 }),
123 );
124
125 it.effect("initializes a command-backed app-server client", () =>
126 Effect.gen(function* () {
127 const path = yield* Path.Path;
128 const scope = yield* Scope.make();
129 const clientLayer = CodexClient.layerCommand({
130 command: "bun",
131 args: ["run", yield* mockPeerPath],
132 cwd: path.join(import.meta.dirname, ".."),
133 });
134 const context = yield* Layer.buildWithScope(clientLayer, scope);
135
136 const initialized = yield* Effect.gen(function* () {
137 const client = yield* CodexClient.CodexAppServerClient;
138 return yield* client.request("initialize", {
139 clientInfo: {
140 name: "effect-codex-app-server-test",
141 title: "Effect Codex App Server Test",
142 version: "0.0.0",
143 },
144 capabilities: {
145 experimentalApi: true,
146 optOutNotificationMethods: null,
147 },
148 });
149 }).pipe(Effect.provide(context), Effect.ensuring(Scope.close(scope, Exit.void)));
150
151 assert.equal(initialized.userAgent, "mock-codex-app-server");
152 }),
153 );
154});
packages/effect-codex-app-server/src/client.ts created+300
...@@ -0,0 +1,300 @@
1import * as Context from "effect/Context";
2import * as Effect from "effect/Effect";
3import * as Layer from "effect/Layer";
4import * as Schema from "effect/Schema";
5import * as Scope from "effect/Scope";
6import * as Stdio from "effect/Stdio";
7import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
8
9import * as CodexRpc from "./_generated/meta.gen.ts";
10import * as CodexError from "./errors.ts";
11import * as CodexProtocol from "./protocol.ts";
12import {
13 decodeNotificationPayload,
14 decodeOptionalPayload,
15 encodeOptionalPayload,
16 runHandler,
17} from "./_internal/shared.ts";
18import { makeChildStdio, makeTerminationError } from "./_internal/stdio.ts";
19
20export interface CodexAppServerClientOptions {
21 readonly logIncoming?: boolean;
22 readonly logOutgoing?: boolean;
23 readonly logger?: (
24 event: CodexProtocol.CodexAppServerProtocolLogEvent,
25 ) => Effect.Effect<void, never>;
26}
27
28interface CodexAppServerClientRaw {
29 readonly notifications: CodexProtocol.CodexAppServerPatchedProtocol["incomingNotifications"];
30 readonly requests: CodexProtocol.CodexAppServerPatchedProtocol["incomingRequests"];
31 readonly request: CodexProtocol.CodexAppServerPatchedProtocol["request"];
32 readonly notify: CodexProtocol.CodexAppServerPatchedProtocol["notify"];
33 readonly respond: CodexProtocol.CodexAppServerPatchedProtocol["respond"];
34 readonly respondError: CodexProtocol.CodexAppServerPatchedProtocol["respondError"];
35}
36
37export interface CodexAppServerClientShape {
38 readonly raw: CodexAppServerClientRaw;
39 readonly request: <M extends CodexRpc.ClientRequestMethod>(
40 method: M,
41 payload: CodexRpc.ClientRequestParamsByMethod[M],
42 ) => Effect.Effect<CodexRpc.ClientRequestResponsesByMethod[M], CodexError.CodexAppServerError>;
43 readonly notify: <M extends CodexRpc.ClientNotificationMethod>(
44 method: M,
45 payload: CodexRpc.ClientNotificationParamsByMethod[M],
46 ) => Effect.Effect<void, CodexError.CodexAppServerError>;
47 readonly handleServerRequest: <M extends CodexRpc.ServerRequestMethod>(
48 method: M,
49 handler: (
50 payload: CodexRpc.ServerRequestParamsByMethod[M],
51 ) => Effect.Effect<CodexRpc.ServerRequestResponsesByMethod[M], CodexError.CodexAppServerError>,
52 ) => Effect.Effect<void>;
53 readonly handleServerNotification: <M extends CodexRpc.ServerNotificationMethod>(
54 method: M,
55 handler: (
56 payload: CodexRpc.ServerNotificationParamsByMethod[M],
57 ) => Effect.Effect<void, CodexError.CodexAppServerError>,
58 ) => Effect.Effect<void>;
59 readonly handleUnknownServerRequest: (
60 handler: (
61 method: string,
62 params: unknown,
63 ) => Effect.Effect<unknown, CodexError.CodexAppServerError>,
64 ) => Effect.Effect<void>;
65 readonly handleUnknownServerNotification: (
66 handler: (
67 method: string,
68 params: unknown,
69 ) => Effect.Effect<void, CodexError.CodexAppServerError>,
70 ) => Effect.Effect<void>;
71}
72
73export class CodexAppServerClient extends Context.Service<
74 CodexAppServerClient,
75 CodexAppServerClientShape
76>()("effect-codex-app-server/CodexAppServerClient") {}
77
78type ServerRequestHandler = (
79 payload: unknown,
80) => Effect.Effect<unknown, CodexError.CodexAppServerError>;
81type ServerNotificationHandler = (
82 payload: unknown,
83) => Effect.Effect<void, CodexError.CodexAppServerError>;
84
85export const make = Effect.fn("effect-codex-app-server/CodexAppServerClient.make")(function* (
86 stdio: Stdio.Stdio,
87 options: CodexAppServerClientOptions = {},
88 terminationError?: Effect.Effect<CodexError.CodexAppServerError>,
89): Effect.fn.Return<CodexAppServerClientShape, never, Scope.Scope> {
90 const requestHandlers = new Map<string, ServerRequestHandler>();
91 const notificationHandlers = new Map<string, Array<ServerNotificationHandler>>();
92 let unknownRequestHandler:
93 | ((method: string, params: unknown) => Effect.Effect<unknown, CodexError.CodexAppServerError>)
94 | undefined;
95 let unknownNotificationHandler:
96 | ((method: string, params: unknown) => Effect.Effect<void, CodexError.CodexAppServerError>)
97 | undefined;
98
99 const getServerRequestParamSchema = <M extends CodexRpc.ServerRequestMethod>(
100 method: M,
101 ):
102 | Schema.Codec<CodexRpc.ServerRequestParamsByMethod[M], CodexRpc.ServerRequestParamsByMethod[M]>
103 | undefined => CodexRpc.SERVER_REQUEST_PARAMS[method] as never;
104
105 const getServerRequestResponseSchema = <M extends CodexRpc.ServerRequestMethod>(
106 method: M,
107 ):
108 | Schema.Codec<
109 CodexRpc.ServerRequestResponsesByMethod[M],
110 CodexRpc.ServerRequestResponsesByMethod[M]
111 >
112 | undefined => CodexRpc.SERVER_REQUEST_RESPONSES[method] as never;
113
114 const getClientRequestParamSchema = <M extends CodexRpc.ClientRequestMethod>(
115 method: M,
116 ):
117 | Schema.Codec<CodexRpc.ClientRequestParamsByMethod[M], CodexRpc.ClientRequestParamsByMethod[M]>
118 | undefined => CodexRpc.CLIENT_REQUEST_PARAMS[method] as never;
119
120 const getClientRequestResponseSchema = <M extends CodexRpc.ClientRequestMethod>(
121 method: M,
122 ):
123 | Schema.Codec<
124 CodexRpc.ClientRequestResponsesByMethod[M],
125 CodexRpc.ClientRequestResponsesByMethod[M]
126 >
127 | undefined => CodexRpc.CLIENT_REQUEST_RESPONSES[method] as never;
128
129 const getClientNotificationParamSchema = <M extends CodexRpc.ClientNotificationMethod>(
130 method: M,
131 ):
132 | Schema.Codec<
133 CodexRpc.ClientNotificationParamsByMethod[M],
134 CodexRpc.ClientNotificationParamsByMethod[M]
135 >
136 | undefined => CodexRpc.CLIENT_NOTIFICATION_PARAMS[method] as never;
137
138 const dispatchNotification = (
139 notification: CodexProtocol.CodexAppServerIncomingNotification,
140 ): Effect.Effect<void, never> => {
141 const schema =
142 notification.method in CodexRpc.SERVER_NOTIFICATION_PARAMS
143 ? CodexRpc.SERVER_NOTIFICATION_PARAMS[
144 notification.method as CodexRpc.ServerNotificationMethod
145 ]
146 : undefined;
147 const handlers = notificationHandlers.get(notification.method) ?? [];
148
149 if (schema) {
150 return decodeNotificationPayload(notification.method, schema, notification.params).pipe(
151 Effect.flatMap((decoded) =>
152 Effect.forEach(handlers, (handler) => handler(decoded), { discard: true }),
153 ),
154 Effect.catch(() => Effect.void),
155 );
156 }
157
158 return unknownNotificationHandler
159 ? unknownNotificationHandler(notification.method, notification.params).pipe(
160 Effect.catch(() => Effect.void),
161 )
162 : Effect.void;
163 };
164
165 const dispatchRequest = (
166 request: CodexProtocol.CodexAppServerIncomingRequest,
167 ): Effect.Effect<unknown, CodexError.CodexAppServerError> => {
168 if (request.method in CodexRpc.SERVER_REQUEST_PARAMS) {
169 const method = request.method as CodexRpc.ServerRequestMethod;
170 const payloadSchema = getServerRequestParamSchema(method);
171 const responseSchema = getServerRequestResponseSchema(method);
172 const handler = requestHandlers.get(method);
173
174 return decodeOptionalPayload(method, payloadSchema, request.params).pipe(
175 Effect.flatMap((decoded) => runHandler(handler, decoded, method)),
176 Effect.flatMap((result) => encodeOptionalPayload(method, responseSchema, result)),
177 );
178 }
179
180 return unknownRequestHandler
181 ? unknownRequestHandler(request.method, request.params)
182 : Effect.fail(CodexError.CodexAppServerRequestError.methodNotFound(request.method));
183 };
184
185 const transport = yield* CodexProtocol.makeCodexAppServerPatchedProtocol({
186 stdio,
187 ...(terminationError ? { terminationError } : {}),
188 ...(options.logIncoming !== undefined ? { logIncoming: options.logIncoming } : {}),
189 ...(options.logOutgoing !== undefined ? { logOutgoing: options.logOutgoing } : {}),
190 ...(options.logger ? { logger: options.logger } : {}),
191 onNotification: dispatchNotification,
192 onRequest: dispatchRequest,
193 });
194
195 const request = <M extends CodexRpc.ClientRequestMethod>(
196 method: M,
197 payload: CodexRpc.ClientRequestParamsByMethod[M],
198 ): Effect.Effect<CodexRpc.ClientRequestResponsesByMethod[M], CodexError.CodexAppServerError> =>
199 encodeOptionalPayload(method, getClientRequestParamSchema(method), payload).pipe(
200 Effect.flatMap((encoded) => transport.request(method, encoded)),
201 Effect.flatMap(
202 (
203 raw,
204 ): Effect.Effect<
205 CodexRpc.ClientRequestResponsesByMethod[M],
206 CodexError.CodexAppServerError
207 > => decodeOptionalPayload(method, getClientRequestResponseSchema(method), raw),
208 ),
209 );
210
211 const notify = <M extends CodexRpc.ClientNotificationMethod>(
212 method: M,
213 payload: CodexRpc.ClientNotificationParamsByMethod[M],
214 ) =>
215 encodeOptionalPayload(method, getClientNotificationParamSchema(method), payload).pipe(
216 Effect.flatMap((encoded) => transport.notify(method, encoded)),
217 );
218
219 return CodexAppServerClient.of({
220 raw: {
221 notifications: transport.incomingNotifications,
222 requests: transport.incomingRequests,
223 request: transport.request,
224 notify: transport.notify,
225 respond: transport.respond,
226 respondError: transport.respondError,
227 },
228 request,
229 notify,
230 handleServerRequest: (method, handler) =>
231 Effect.sync(() => {
232 requestHandlers.set(method, handler as ServerRequestHandler);
233 }),
234 handleServerNotification: (method, handler) =>
235 Effect.sync(() => {
236 const current = notificationHandlers.get(method) ?? [];
237 current.push(handler as ServerNotificationHandler);
238 notificationHandlers.set(method, current);
239 }),
240 handleUnknownServerRequest: (handler) =>
241 Effect.sync(() => {
242 unknownRequestHandler = handler;
243 }),
244 handleUnknownServerNotification: (handler) =>
245 Effect.sync(() => {
246 unknownNotificationHandler = handler;
247 }),
248 });
249});
250
251export const layerChildProcess = (
252 handle: ChildProcessSpawner.ChildProcessHandle,
253 options: CodexAppServerClientOptions = {},
254): Layer.Layer<CodexAppServerClient> => {
255 const stdio = makeChildStdio(handle);
256 const terminationError = makeTerminationError(handle);
257 return Layer.effect(CodexAppServerClient, make(stdio, options, terminationError));
258};
259
260export interface CodexAppServerCommandLayerOptions extends CodexAppServerClientOptions {
261 readonly command: string;
262 readonly args?: ReadonlyArray<string>;
263 readonly cwd?: string;
264 readonly env?: Record<string, string>;
265}
266
267export const layerCommand = (
268 options: CodexAppServerCommandLayerOptions,
269): Layer.Layer<
270 CodexAppServerClient,
271 CodexError.CodexAppServerSpawnError,
272 ChildProcessSpawner.ChildProcessSpawner
273> =>
274 Layer.effect(
275 CodexAppServerClient,
276 Effect.acquireRelease(
277 Effect.gen(function* () {
278 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
279 const command = ChildProcess.make(options.command, [...(options.args ?? [])], {
280 ...(options.cwd ? { cwd: options.cwd } : {}),
281 ...(options.env ? { env: { ...process.env, ...options.env } } : {}),
282 shell: process.platform === "win32",
283 });
284 return yield* spawner.spawn(command).pipe(
285 Effect.mapError(
286 (cause) =>
287 new CodexError.CodexAppServerSpawnError({
288 command: [options.command, ...(options.args ?? [])].join(" "),
289 cause,
290 }),
291 ),
292 );
293 }),
294 (handle) => handle.kill().pipe(Effect.orDie),
295 ).pipe(
296 Effect.flatMap((handle) =>
297 make(makeChildStdio(handle), options, makeTerminationError(handle)),
298 ),
299 ),
300 );
packages/effect-codex-app-server/src/errors.ts created+151
...@@ -0,0 +1,151 @@
1import * as Schema from "effect/Schema";
2
3export interface CodexAppServerProtocolErrorShape {
4 readonly code: number;
5 readonly message: string;
6 readonly data?: unknown;
7}
8
9export class CodexAppServerSpawnError extends Schema.TaggedErrorClass<CodexAppServerSpawnError>()(
10 "CodexAppServerSpawnError",
11 {
12 command: Schema.optional(Schema.String),
13 cause: Schema.Defect,
14 },
15) {
16 override get message() {
17 return this.command
18 ? `Failed to spawn Codex App Server process for command: ${this.command}`
19 : "Failed to spawn Codex App Server process";
20 }
21}
22
23export class CodexAppServerProcessExitedError extends Schema.TaggedErrorClass<CodexAppServerProcessExitedError>()(
24 "CodexAppServerProcessExitedError",
25 {
26 code: Schema.optional(Schema.Number),
27 cause: Schema.optional(Schema.Defect),
28 },
29) {
30 override get message() {
31 return this.code === undefined
32 ? "Codex App Server process exited"
33 : `Codex App Server process exited with code ${this.code}`;
34 }
35}
36
37export class CodexAppServerProtocolParseError extends Schema.TaggedErrorClass<CodexAppServerProtocolParseError>()(
38 "CodexAppServerProtocolParseError",
39 {
40 detail: Schema.String,
41 cause: Schema.optional(Schema.Defect),
42 },
43) {
44 override get message() {
45 return `Failed to parse Codex App Server protocol message: ${this.detail}`;
46 }
47}
48
49export class CodexAppServerTransportError extends Schema.TaggedErrorClass<CodexAppServerTransportError>()(
50 "CodexAppServerTransportError",
51 {
52 detail: Schema.String,
53 cause: Schema.Defect,
54 },
55) {
56 override get message() {
57 return this.detail;
58 }
59}
60
61export class CodexAppServerRequestError extends Schema.TaggedErrorClass<CodexAppServerRequestError>()(
62 "CodexAppServerRequestError",
63 {
64 code: Schema.Number,
65 errorMessage: Schema.String,
66 data: Schema.optional(Schema.Unknown),
67 },
68) {
69 override get message() {
70 return this.errorMessage;
71 }
72
73 static fromProtocolError(error: CodexAppServerProtocolErrorShape) {
74 return new CodexAppServerRequestError({
75 code: error.code,
76 errorMessage: error.message,
77 ...(error.data !== undefined ? { data: error.data } : {}),
78 });
79 }
80
81 static parseError(message = "Parse error", data?: unknown) {
82 return new CodexAppServerRequestError({
83 code: -32700,
84 errorMessage: message,
85 ...(data !== undefined ? { data } : {}),
86 });
87 }
88
89 static invalidRequest(message = "Invalid request", data?: unknown) {
90 return new CodexAppServerRequestError({
91 code: -32600,
92 errorMessage: message,
93 ...(data !== undefined ? { data } : {}),
94 });
95 }
96
97 static methodNotFound(method: string) {
98 return new CodexAppServerRequestError({
99 code: -32601,
100 errorMessage: `Method not found: ${method}`,
101 });
102 }
103
104 static invalidParams(message = "Invalid params", data?: unknown) {
105 return new CodexAppServerRequestError({
106 code: -32602,
107 errorMessage: message,
108 ...(data !== undefined ? { data } : {}),
109 });
110 }
111
112 static internalError(message = "Internal error", data?: unknown) {
113 return new CodexAppServerRequestError({
114 code: -32603,
115 errorMessage: message,
116 ...(data !== undefined ? { data } : {}),
117 });
118 }
119
120 static overloaded(message = "Server overloaded; retry later.", data?: unknown) {
121 return new CodexAppServerRequestError({
122 code: -32001,
123 errorMessage: message,
124 ...(data !== undefined ? { data } : {}),
125 });
126 }
127
128 toProtocolError(): CodexAppServerProtocolErrorShape {
129 return {
130 code: this.code,
131 message: this.errorMessage,
132 ...(this.data !== undefined ? { data: this.data } : {}),
133 };
134 }
135}
136
137export const CodexAppServerError = Schema.Union([
138 CodexAppServerRequestError,
139 CodexAppServerSpawnError,
140 CodexAppServerProcessExitedError,
141 CodexAppServerProtocolParseError,
142 CodexAppServerTransportError,
143]);
144
145export type CodexAppServerError = typeof CodexAppServerError.Type;
146
147export function normalizeToRequestError(error: CodexAppServerError): CodexAppServerRequestError {
148 return Schema.is(CodexAppServerRequestError)(error)
149 ? error
150 : CodexAppServerRequestError.internalError(error.message);
151}
packages/effect-codex-app-server/src/protocol.test.ts created+197
...@@ -0,0 +1,197 @@
1import * as Deferred from "effect/Deferred";
2import * as Effect from "effect/Effect";
3import * as Fiber from "effect/Fiber";
4import * as Queue from "effect/Queue";
5import * as Stream from "effect/Stream";
6
7import * as NodeServices from "@effect/platform-node/NodeServices";
8import { assert, it } from "@effect/vitest";
9
10import * as CodexError from "./errors.ts";
11import * as CodexProtocol from "./protocol.ts";
12import { makeInMemoryStdio } from "./_internal/stdio.ts";
13
14const encoder = new TextEncoder();
15
16const encodeJsonl = (value: unknown) => encoder.encode(`${JSON.stringify(value)}\n`);
17
18it.layer(NodeServices.layer)("effect-codex-app-server protocol", (it) => {
19 it.effect(
20 "encodes requests without a jsonrpc field and routes inbound requests and notifications",
21 () =>
22 Effect.gen(function* () {
23 const { stdio, input, output } = yield* makeInMemoryStdio();
24 const transport = yield* CodexProtocol.makeCodexAppServerPatchedProtocol({ stdio });
25
26 const notificationDeferred =
27 yield* Deferred.make<ReadonlyArray<CodexProtocol.CodexAppServerIncomingNotification>>();
28 const requestDeferred =
29 yield* Deferred.make<ReadonlyArray<CodexProtocol.CodexAppServerIncomingRequest>>();
30
31 yield* transport.incomingNotifications.pipe(
32 Stream.take(1),
33 Stream.runCollect,
34 Effect.flatMap((notifications) => Deferred.succeed(notificationDeferred, notifications)),
35 Effect.forkScoped,
36 );
37
38 yield* transport.incomingRequests.pipe(
39 Stream.take(1),
40 Stream.runCollect,
41 Effect.flatMap((requests) => Deferred.succeed(requestDeferred, requests)),
42 Effect.forkScoped,
43 );
44
45 yield* transport.notify("initialized");
46 assert.equal(yield* Queue.take(output), '{"method":"initialized"}\n');
47
48 const initializeParams = {
49 clientInfo: {
50 name: "effect-codex-app-server-test",
51 title: "Effect Codex App Server Test",
52 version: "0.0.0",
53 },
54 capabilities: {
55 experimentalApi: true,
56 optOutNotificationMethods: null,
57 },
58 };
59
60 const pendingInitialize = yield* transport
61 .request("initialize", initializeParams)
62 .pipe(Effect.forkScoped);
63 assert.deepEqual(JSON.parse(yield* Queue.take(output)), {
64 id: 1,
65 method: "initialize",
66 params: initializeParams,
67 });
68
69 yield* Queue.offer(
70 input,
71 encodeJsonl({
72 method: "item/agentMessage/delta",
73 params: {
74 delta: "Hello from the mock peer.",
75 itemId: "item-1",
76 threadId: "thread-1",
77 turnId: "turn-1",
78 },
79 }),
80 );
81 yield* Queue.offer(
82 input,
83 encodeJsonl({
84 id: 77,
85 method: "item/tool/requestUserInput",
86 params: {
87 itemId: "item-approval-1",
88 threadId: "thread-1",
89 turnId: "turn-1",
90 questions: [
91 {
92 id: "approved",
93 header: "Approve",
94 question: "Continue?",
95 },
96 ],
97 },
98 }),
99 );
100 yield* Queue.offer(
101 input,
102 encodeJsonl({
103 id: 1,
104 result: {
105 userAgent: "mock-codex-app-server",
106 codexHome: "/tmp/codex-home",
107 platformFamily: "unix",
108 platformOs: "macos",
109 },
110 }),
111 );
112
113 assert.deepEqual(yield* Fiber.join(pendingInitialize), {
114 userAgent: "mock-codex-app-server",
115 codexHome: "/tmp/codex-home",
116 platformFamily: "unix",
117 platformOs: "macos",
118 });
119 assert.deepEqual(yield* Deferred.await(notificationDeferred), [
120 {
121 method: "item/agentMessage/delta",
122 params: {
123 delta: "Hello from the mock peer.",
124 itemId: "item-1",
125 threadId: "thread-1",
126 turnId: "turn-1",
127 },
128 },
129 ]);
130 assert.deepEqual(yield* Deferred.await(requestDeferred), [
131 {
132 id: 77,
133 method: "item/tool/requestUserInput",
134 params: {
135 itemId: "item-approval-1",
136 threadId: "thread-1",
137 turnId: "turn-1",
138 questions: [
139 {
140 id: "approved",
141 header: "Approve",
142 question: "Continue?",
143 },
144 ],
145 },
146 },
147 ]);
148
149 yield* transport.respond(77, {
150 answers: {
151 approved: {
152 answers: ["yes"],
153 },
154 },
155 });
156 assert.deepEqual(JSON.parse(yield* Queue.take(output)), {
157 id: 77,
158 result: {
159 answers: {
160 approved: {
161 answers: ["yes"],
162 },
163 },
164 },
165 });
166
167 yield* transport.respondError(
168 78,
169 CodexError.CodexAppServerRequestError.methodNotFound("x/test"),
170 );
171 assert.deepEqual(JSON.parse(yield* Queue.take(output)), {
172 id: 78,
173 error: {
174 code: -32601,
175 message: "Method not found: x/test",
176 },
177 });
178 }),
179 );
180
181 it.effect("surfaces JSON encoding failures as protocol parse errors", () =>
182 Effect.gen(function* () {
183 const { stdio } = yield* makeInMemoryStdio();
184 const transport = yield* CodexProtocol.makeCodexAppServerPatchedProtocol({ stdio });
185
186 const bigintError = yield* transport.notify("x/test", 1n).pipe(Effect.flip);
187 assert.instanceOf(bigintError, CodexError.CodexAppServerProtocolParseError);
188 assert.equal(bigintError.detail, "Failed to encode Codex App Server message");
189
190 const circular: Record<string, unknown> = {};
191 circular.self = circular;
192 const circularError = yield* transport.notify("x/test", circular).pipe(Effect.flip);
193 assert.instanceOf(circularError, CodexError.CodexAppServerProtocolParseError);
194 assert.equal(circularError.detail, "Failed to encode Codex App Server message");
195 }),
196 );
197});
packages/effect-codex-app-server/src/protocol.ts created+394
...@@ -0,0 +1,394 @@
1import * as Cause from "effect/Cause";
2import * as Deferred from "effect/Deferred";
3import * as Effect from "effect/Effect";
4import * as Queue from "effect/Queue";
5import * as Ref from "effect/Ref";
6import * as Scope from "effect/Scope";
7import * as Schema from "effect/Schema";
8import * as Stdio from "effect/Stdio";
9import * as Stream from "effect/Stream";
10
11import * as CodexError from "./errors.ts";
12import { JsonRpcId, JsonRpcResponseEnvelope } from "./_internal/shared.ts";
13
14export interface CodexAppServerProtocolLogEvent {
15 readonly direction: "incoming" | "outgoing";
16 readonly stage: "raw" | "decoded" | "decode_failed";
17 readonly payload: unknown;
18}
19
20export interface CodexAppServerIncomingNotification {
21 readonly method: string;
22 readonly params?: unknown;
23}
24
25export interface CodexAppServerIncomingRequest {
26 readonly id: string | number;
27 readonly method: string;
28 readonly params?: unknown;
29}
30
31export interface CodexAppServerPatchedProtocolOptions {
32 readonly stdio: Stdio.Stdio;
33 readonly terminationError?: Effect.Effect<CodexError.CodexAppServerError>;
34 readonly logIncoming?: boolean;
35 readonly logOutgoing?: boolean;
36 readonly logger?: (event: CodexAppServerProtocolLogEvent) => Effect.Effect<void, never>;
37 readonly onNotification?: (
38 notification: CodexAppServerIncomingNotification,
39 ) => Effect.Effect<void, never>;
40 readonly onRequest?: (
41 request: CodexAppServerIncomingRequest,
42 ) => Effect.Effect<unknown, CodexError.CodexAppServerError>;
43 readonly onTermination?: (error: CodexError.CodexAppServerError) => Effect.Effect<void, never>;
44}
45
46export interface CodexAppServerPatchedProtocol {
47 readonly incomingNotifications: Stream.Stream<CodexAppServerIncomingNotification>;
48 readonly incomingRequests: Stream.Stream<CodexAppServerIncomingRequest>;
49 readonly request: (
50 method: string,
51 payload?: unknown,
52 ) => Effect.Effect<unknown, CodexError.CodexAppServerError>;
53 readonly notify: (
54 method: string,
55 payload?: unknown,
56 ) => Effect.Effect<void, CodexError.CodexAppServerError>;
57 readonly respond: (
58 requestId: string | number,
59 result: unknown,
60 ) => Effect.Effect<void, CodexError.CodexAppServerError>;
61 readonly respondError: (
62 requestId: string | number,
63 error: CodexError.CodexAppServerRequestError,
64 ) => Effect.Effect<void, CodexError.CodexAppServerError>;
65}
66
67function isObject(value: unknown): value is Record<string, unknown> {
68 return typeof value === "object" && value !== null;
69}
70
71function isIncomingRequest(value: unknown): value is CodexAppServerIncomingRequest {
72 if (!isObject(value) || typeof value.method !== "string") {
73 return false;
74 }
75 return Schema.is(JsonRpcId)(value.id);
76}
77
78function isIncomingNotification(value: unknown): value is CodexAppServerIncomingNotification {
79 return isObject(value) && typeof value.method === "string" && !("id" in value);
80}
81
82function isIncomingResponse(value: unknown): value is typeof JsonRpcResponseEnvelope.Type {
83 return Schema.is(JsonRpcResponseEnvelope)(value);
84}
85
86const encodeWireMessage = (
87 message: Record<string, unknown>,
88): Effect.Effect<string, CodexError.CodexAppServerProtocolParseError> =>
89 Effect.try({
90 try: () => `${JSON.stringify(message)}\n`,
91 catch: (cause) =>
92 new CodexError.CodexAppServerProtocolParseError({
93 detail: "Failed to encode Codex App Server message",
94 cause,
95 }),
96 });
97
98const normalizeIncomingError = (error: unknown, detail: string): CodexError.CodexAppServerError =>
99 Schema.is(CodexError.CodexAppServerError)(error)
100 ? error
101 : new CodexError.CodexAppServerTransportError({
102 detail,
103 cause: error,
104 });
105
106const toProtocolMessage = (
107 requestId: string | number,
108 fields: {
109 readonly result?: unknown;
110 readonly error?: CodexError.CodexAppServerProtocolErrorShape;
111 },
112): { readonly [key: string]: unknown } => ({
113 id: requestId,
114 ...(fields.result !== undefined ? { result: fields.result } : {}),
115 ...(fields.error !== undefined ? { error: fields.error } : {}),
116});
117
118export const makeCodexAppServerPatchedProtocol = Effect.fn("makeCodexAppServerPatchedProtocol")(
119 function* (
120 options: CodexAppServerPatchedProtocolOptions,
121 ): Effect.fn.Return<CodexAppServerPatchedProtocol, never, Scope.Scope> {
122 const outgoing = yield* Queue.unbounded<string, Cause.Done<void>>();
123 const incomingNotifications = yield* Queue.unbounded<CodexAppServerIncomingNotification>();
124 const incomingRequests = yield* Queue.unbounded<CodexAppServerIncomingRequest>();
125 const pending = yield* Ref.make(
126 new Map<string, Deferred.Deferred<unknown, CodexError.CodexAppServerError>>(),
127 );
128 const nextRequestId = yield* Ref.make(1);
129 const remainder = yield* Ref.make("");
130 const terminationHandled = yield* Ref.make(false);
131
132 const logProtocol = (event: CodexAppServerProtocolLogEvent) => {
133 if (event.direction === "incoming" && !options.logIncoming) {
134 return Effect.void;
135 }
136 if (event.direction === "outgoing" && !options.logOutgoing) {
137 return Effect.void;
138 }
139 return (
140 options.logger?.(event) ??
141 Effect.logDebug("Codex App Server protocol event").pipe(Effect.annotateLogs({ event }))
142 );
143 };
144
145 const failAllPending = (error: CodexError.CodexAppServerError) =>
146 Ref.get(pending).pipe(
147 Effect.flatMap((current) =>
148 Effect.forEach([...current.values()], (deferred) => Deferred.fail(deferred, error), {
149 discard: true,
150 }),
151 ),
152 Effect.andThen(Ref.set(pending, new Map())),
153 );
154
155 const handleTermination = (classify: () => Effect.Effect<CodexError.CodexAppServerError>) =>
156 Ref.modify(terminationHandled, (handled) => {
157 if (handled) {
158 return [Effect.void, true] as const;
159 }
160 return [
161 Effect.gen(function* () {
162 const error = yield* classify();
163 yield* failAllPending(error);
164 yield* Queue.end(outgoing);
165 if (options.onTermination) {
166 yield* options.onTermination(error);
167 }
168 }),
169 true,
170 ] as const;
171 }).pipe(Effect.flatten);
172
173 const offerOutgoing = (message: Record<string, unknown>) =>
174 Effect.gen(function* () {
175 yield* logProtocol({
176 direction: "outgoing",
177 stage: "decoded",
178 payload: message,
179 });
180 const encoded = yield* encodeWireMessage(message);
181 yield* logProtocol({
182 direction: "outgoing",
183 stage: "raw",
184 payload: encoded,
185 });
186 yield* Queue.offer(outgoing, encoded).pipe(Effect.asVoid);
187 });
188
189 const removePending = (requestId: string) =>
190 Ref.update(pending, (current) => {
191 if (!current.has(requestId)) {
192 return current;
193 }
194 const next = new Map(current);
195 next.delete(requestId);
196 return next;
197 });
198
199 const resolvePending = (
200 requestId: string,
201 handler: (
202 deferred: Deferred.Deferred<unknown, CodexError.CodexAppServerError>,
203 ) => Effect.Effect<void>,
204 ) =>
205 Ref.modify(pending, (current) => {
206 const deferred = current.get(requestId);
207 if (!deferred) {
208 return [Effect.void, current] as const;
209 }
210 const next = new Map(current);
211 next.delete(requestId);
212 return [handler(deferred), next] as const;
213 }).pipe(Effect.flatten);
214
215 const respond = (requestId: string | number, result: unknown) =>
216 offerOutgoing(toProtocolMessage(requestId, { result }));
217
218 const respondError = (
219 requestId: string | number,
220 error: CodexError.CodexAppServerRequestError,
221 ) => offerOutgoing(toProtocolMessage(requestId, { error: error.toProtocolError() }));
222
223 const handleResponse = (response: typeof JsonRpcResponseEnvelope.Type) => {
224 const requestId = String(response.id);
225 const protocolError = response.error;
226 if (protocolError !== undefined) {
227 return resolvePending(requestId, (deferred) =>
228 Deferred.fail(
229 deferred,
230 CodexError.CodexAppServerRequestError.fromProtocolError(protocolError),
231 ),
232 );
233 }
234 return resolvePending(requestId, (deferred) => Deferred.succeed(deferred, response.result));
235 };
236
237 const handleRequest = (request: CodexAppServerIncomingRequest) =>
238 Queue.offer(incomingRequests, request).pipe(
239 Effect.andThen(
240 options.onRequest
241 ? options.onRequest(request).pipe(
242 Effect.matchEffect({
243 onFailure: (error) =>
244 respondError(request.id, CodexError.normalizeToRequestError(error)),
245 onSuccess: (result) => respond(request.id, result),
246 }),
247 )
248 : Effect.void,
249 ),
250 Effect.asVoid,
251 );
252
253 const handleNotification = (notification: CodexAppServerIncomingNotification) =>
254 Queue.offer(incomingNotifications, notification).pipe(
255 Effect.andThen(options.onNotification ? options.onNotification(notification) : Effect.void),
256 Effect.asVoid,
257 );
258
259 const routeMessage = (
260 message: unknown,
261 ): Effect.Effect<void, CodexError.CodexAppServerError> => {
262 if (isIncomingRequest(message)) {
263 return handleRequest(message);
264 }
265 if (isIncomingNotification(message)) {
266 return handleNotification(message);
267 }
268 if (isIncomingResponse(message)) {
269 return handleResponse(message);
270 }
271 return Effect.fail(
272 new CodexError.CodexAppServerProtocolParseError({
273 detail: "Received protocol message in an unknown shape",
274 }),
275 );
276 };
277
278 const handleLine = (line: string): Effect.Effect<void, CodexError.CodexAppServerError> => {
279 if (line.trim().length === 0) {
280 return Effect.void;
281 }
282 return logProtocol({
283 direction: "incoming",
284 stage: "raw",
285 payload: line,
286 }).pipe(
287 Effect.flatMap(() =>
288 Effect.try({
289 try: () => JSON.parse(line),
290 catch: (cause) =>
291 new CodexError.CodexAppServerProtocolParseError({
292 detail: "Failed to decode Codex App Server wire message",
293 cause,
294 }),
295 }),
296 ),
297 Effect.tap((decoded) =>
298 logProtocol({
299 direction: "incoming",
300 stage: "decoded",
301 payload: decoded,
302 }),
303 ),
304 Effect.tapErrorTag("CodexAppServerProtocolParseError", (error) =>
305 logProtocol({
306 direction: "incoming",
307 stage: "decode_failed",
308 payload: {
309 detail: error.detail,
310 cause: error.cause,
311 },
312 }),
313 ),
314 Effect.flatMap(routeMessage),
315 );
316 };
317
318 yield* options.stdio.stdin.pipe(
319 Stream.decodeText(),
320 Stream.runForEach((chunk) =>
321 Ref.modify(remainder, (current) => {
322 const combined = current + chunk;
323 const lines = combined.split("\n");
324 const nextRemainder = lines.pop() ?? "";
325 return [lines.map((line) => line.replace(/\r$/, "")), nextRemainder] as const;
326 }).pipe(Effect.flatMap((lines) => Effect.forEach(lines, handleLine, { discard: true }))),
327 ),
328 Effect.matchEffect({
329 onFailure: (error) =>
330 handleTermination(() =>
331 Effect.succeed(normalizeIncomingError(error, "Codex App Server input stream failed")),
332 ),
333 onSuccess: () =>
334 Ref.get(remainder).pipe(
335 Effect.flatMap((line) => (line.trim().length === 0 ? Effect.void : handleLine(line))),
336 Effect.matchEffect({
337 onFailure: (error) => handleTermination(() => Effect.succeed(error)),
338 onSuccess: () =>
339 handleTermination(
340 () =>
341 options.terminationError ??
342 Effect.succeed(
343 new CodexError.CodexAppServerTransportError({
344 detail: "Codex App Server input stream ended",
345 cause: new Error("Codex App Server input stream ended"),
346 }),
347 ),
348 ),
349 }),
350 ),
351 }),
352 Effect.forkScoped,
353 );
354
355 yield* Stream.fromQueue(outgoing).pipe(Stream.run(options.stdio.stdout()), Effect.forkScoped);
356
357 const request = (method: string, payload?: unknown) =>
358 Effect.gen(function* () {
359 const requestId = yield* Ref.modify(
360 nextRequestId,
361 (current) => [current, current + 1] as const,
362 );
363 const deferred = yield* Deferred.make<unknown, CodexError.CodexAppServerError>();
364 yield* Ref.update(pending, (current) => new Map(current).set(String(requestId), deferred));
365 yield* offerOutgoing({
366 id: requestId,
367 method,
368 ...(payload !== undefined ? { params: payload } : {}),
369 }).pipe(
370 Effect.catch((error) =>
371 removePending(String(requestId)).pipe(Effect.andThen(Effect.fail(error))),
372 ),
373 );
374 return yield* Deferred.await(deferred).pipe(
375 Effect.onInterrupt(() => removePending(String(requestId))),
376 );
377 });
378
379 const notify = (method: string, payload?: unknown) =>
380 offerOutgoing({
381 method,
382 ...(payload !== undefined ? { params: payload } : {}),
383 });
384
385 return {
386 incomingNotifications: Stream.fromQueue(incomingNotifications),
387 incomingRequests: Stream.fromQueue(incomingRequests),
388 request,
389 notify,
390 respond,
391 respondError,
392 } satisfies CodexAppServerPatchedProtocol;
393 },
394);
packages/effect-codex-app-server/src/rpc.ts created+1
...@@ -0,0 +1 @@
1export * from "./_generated/meta.gen.ts";
packages/effect-codex-app-server/src/schema.ts created+3
...@@ -0,0 +1,3 @@
1export * from "./_generated/schema.gen.ts";
2export * from "./_generated/meta.gen.ts";
3export * from "./_generated/namespaces.gen.ts";
packages/effect-codex-app-server/test/examples/codex-app-server-probe.ts created+62
...@@ -0,0 +1,62 @@
1import * as Console from "effect/Console";
2import * as Effect from "effect/Effect";
3
4import * as NodeRuntime from "@effect/platform-node/NodeRuntime";
5import * as NodeServices from "@effect/platform-node/NodeServices";
6
7import * as CodexClient from "../../src/client.ts";
8
9const program = Effect.gen(function* () {
10 const codexLayer = CodexClient.layerCommand({
11 command: process.env.CODEX_BIN ?? "codex",
12 args: ["app-server"],
13 cwd: process.cwd(),
14 logIncoming: true,
15 logOutgoing: true,
16 });
17
18 yield* Effect.gen(function* () {
19 const client = yield* CodexClient.CodexAppServerClient;
20
21 yield* client.handleServerRequest("item/tool/requestUserInput", (payload) =>
22 Effect.succeed({
23 answers: Object.fromEntries(
24 payload.questions.map((question) => [
25 question.id,
26 {
27 answers:
28 question.options && question.options.length > 0
29 ? [question.options[0]!.label]
30 : ["ok"],
31 },
32 ]),
33 ),
34 }),
35 );
36
37 const initialized = yield* client.request("initialize", {
38 clientInfo: {
39 name: "effect-codex-app-server-probe",
40 title: "Effect Codex App Server Probe",
41 version: "0.0.0",
42 },
43 capabilities: {
44 experimentalApi: true,
45 optOutNotificationMethods: null,
46 },
47 });
48 yield* Console.log("initialize", JSON.stringify(initialized, null, 2));
49
50 yield* client.notify("initialized", undefined);
51
52 const account = yield* client.request("account/read", {});
53 yield* Console.log("account/read", JSON.stringify(account, null, 2));
54
55 const skills = yield* client.request("skills/list", {
56 cwds: [process.cwd()],
57 });
58 yield* Console.log("skills/list", JSON.stringify(skills, null, 2));
59 }).pipe(Effect.provide(codexLayer));
60});
61
62program.pipe(Effect.scoped, Effect.provide(NodeServices.layer), NodeRuntime.runMain);
packages/effect-codex-app-server/test/fixtures/codex-app-server-mock-peer.ts created+144
...@@ -0,0 +1,144 @@
1let nextServerRequestId = 10_000;
2let pendingSkillsListRequestId: number | string | null = null;
3let pendingUserInputRequestId: number | null = null;
4
5const writeMessage = (message: unknown) => {
6 process.stdout.write(`${JSON.stringify(message)}\n`);
7};
8
9const respond = (id: number | string, result: unknown) => {
10 writeMessage({ id, result });
11};
12
13const respondError = (id: number | string, code: number, message: string) => {
14 writeMessage({
15 id,
16 error: {
17 code,
18 message,
19 },
20 });
21};
22
23const sendRequest = (method: string, params: unknown) => {
24 const id = nextServerRequestId++;
25 writeMessage({ id, method, params });
26 return id;
27};
28
29const handleMethod = (message: Record<string, unknown>) => {
30 const method = message.method;
31 if (typeof method !== "string") {
32 return;
33 }
34
35 switch (method) {
36 case "initialize": {
37 respond(message.id as number | string, {
38 userAgent: "mock-codex-app-server",
39 codexHome: process.cwd(),
40 platformFamily: process.platform === "win32" ? "windows" : "unix",
41 platformOs: process.platform === "darwin" ? "macos" : process.platform,
42 });
43 return;
44 }
45 case "initialized": {
46 writeMessage({
47 method: "item/agentMessage/delta",
48 params: {
49 delta: "Mock server is ready.",
50 itemId: "item-1",
51 threadId: "thread-1",
52 turnId: "turn-1",
53 },
54 });
55 return;
56 }
57 case "account/read": {
58 respond(message.id as number | string, {
59 account: {
60 type: "chatgpt",
61 email: "mock@example.com",
62 planType: "plus",
63 },
64 requiresOpenaiAuth: false,
65 });
66 return;
67 }
68 case "skills/list": {
69 pendingSkillsListRequestId = message.id as number | string;
70 pendingUserInputRequestId = sendRequest("item/tool/requestUserInput", {
71 itemId: "item-approval-1",
72 threadId: "thread-1",
73 turnId: "turn-1",
74 questions: [
75 {
76 id: "approved",
77 header: "Approve",
78 question: "Continue with the mock skills request?",
79 options: [
80 {
81 label: "yes",
82 description: "Approve the request",
83 },
84 ],
85 },
86 ],
87 });
88 return;
89 }
90 default: {
91 if (message.id !== undefined) {
92 respondError(message.id as number | string, -32601, `Unhandled request: ${method}`);
93 }
94 }
95 }
96};
97
98const handleResponse = (message: Record<string, unknown>) => {
99 if (message.id !== pendingUserInputRequestId) {
100 return;
101 }
102
103 pendingUserInputRequestId = null;
104
105 respond(pendingSkillsListRequestId!, {
106 data: [
107 {
108 cwd: process.cwd(),
109 errors: [],
110 skills: [],
111 },
112 ],
113 });
114 pendingSkillsListRequestId = null;
115};
116
117let remainder = "";
118
119process.stdin.setEncoding("utf8");
120process.stdin.on("data", (chunk) => {
121 remainder += chunk;
122 const lines = remainder.split("\n");
123 remainder = lines.pop() ?? "";
124
125 for (const line of lines) {
126 const trimmed = line.trim();
127 if (trimmed.length === 0) {
128 continue;
129 }
130
131 const message = JSON.parse(trimmed) as Record<string, unknown>;
132 if ("method" in message) {
133 handleMethod(message);
134 continue;
135 }
136 if ("id" in message) {
137 handleResponse(message);
138 }
139 }
140});
141
142process.stdin.on("end", () => {
143 process.exit(0);
144});
packages/effect-codex-app-server/tsconfig.json created+18
...@@ -0,0 +1,18 @@
1{
2 "extends": "../../tsconfig.base.json",
3 "compilerOptions": {
4 "plugins": [
5 {
6 "name": "@effect/language-service",
7 "namespaceImportPackages": ["@effect/platform-node"],
8 "diagnosticSeverity": {
9 "importFromBarrel": "error",
10 "anyUnknownInErrorContext": "warning",
11 "instanceOfSchema": "warning",
12 "deterministicKeys": "warning"
13 }
14 }
15 ]
16 },
17 "include": ["src", "scripts", "test"]
18}
scripts/release-smoke.ts+1
...@@ -25,6 +25,7 @@ const workspaceFiles = [...@@ -25,6 +25,7 @@ const workspaceFiles = [
25 "packages/contracts/package.json",25 "packages/contracts/package.json",
26 "packages/shared/package.json",26 "packages/shared/package.json",
27 "packages/effect-acp/package.json",27 "packages/effect-acp/package.json",
28 "packages/effect-codex-app-server/package.json",
28 "scripts/package.json",29 "scripts/package.json",
29] as const;30] as const;
3031