The best way to control Claude Code, Codex and more from any computer or phone
Mirrored from https://github.com/Camo67/t3code.git
Synced Nov 25, 06:15 UTC
`effect-codex-app-server` (#1942)
Co-authored-by: codex <codex@users.noreply.github.com>
Julius Marminge committed
Apr 19, 2026 at 21:46 UTC
3b98fe3548831c536cf8c22d4b8a63e03e0a7d58
35 files changed
+38106
-5381
apps/server/package.json
+1
@@ -44,6 +44,7 @@
44
"@types/bun": "catalog:",
45
"@types/node": "catalog:",
46
"effect-acp": "workspace:*",
47
+ "effect-codex-app-server": "workspace:*",
48
"tsdown": "catalog:",
49
"typescript": "catalog:",
50
"vitest": "catalog:"
apps/server/src/codexAppServerManager.test.ts
deleted
-1218
@@ -1,1218 +0,0 @@
1
-import { describe, expect, it, vi } from "vitest";
2
-import { randomUUID } from "node:crypto";
3
-import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
4
-import os from "node:os";
5
-import path from "node:path";
6
-import { ApprovalRequestId, ThreadId } from "@t3tools/contracts";
7
-
8
-import {
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
-
20
-const asThreadId = (value: string): ThreadId => ThreadId.make(value);
21
-
22
-function 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
-
66
-function 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
-
99
-function 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
-
141
-function 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
-
178
-describe("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
-
210
-describe("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
-
246
-describe("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
-
262
-describe("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
-
284
-describe("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
-
339
-describe("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
-
371
-describe("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
-
623
-describe("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
-
799
-describe("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
-
887
-describe("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
-
1001
-describe("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
-
1147
-describe.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 @@
1
-import { type ChildProcessWithoutNullStreams, spawn, spawnSync } from "node:child_process";
2
-import { randomUUID } from "node:crypto";
3
-import { EventEmitter } from "node:events";
4
-import readline from "node:readline";
5
-
6
-import {
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";
21
-import { normalizeModelSlug } from "@t3tools/shared/model";
22
-import { Effect, Context } from "effect";
23
-
24
-import {
25
- formatCodexCliUpgradeMessage,
26
- isCodexCliVersionSupported,
27
- parseCodexCliVersion,
28
-} from "./provider/codexCliVersion.ts";
29
-import {
30
- readCodexAccountSnapshot,
31
- resolveCodexModelForAccount,
32
- type CodexAccountSnapshot,
33
-} from "./provider/codexAccount.ts";
34
-import { buildCodexInitializeParams, killCodexChildProcess } from "./provider/codexAppServer.ts";
35
-import { expandHomePath } from "./pathExpansion.ts";
36
-
37
-export { buildCodexInitializeParams } from "./provider/codexAppServer.ts";
38
-export { readCodexAccountSnapshot, resolveCodexModelForAccount } from "./provider/codexAccount.ts";
39
-
40
-type PendingRequestKey = string;
41
-
42
-interface PendingRequest {
43
- method: string;
44
- timeout: ReturnType<typeof setTimeout>;
45
- resolve: (value: unknown) => void;
46
- reject: (error: Error) => void;
47
-}
48
-
49
-interface 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
-
62
-interface PendingUserInputRequest {
63
- requestId: ApprovalRequestId;
64
- jsonRpcId: string | number;
65
- threadId: ThreadId;
66
- turnId?: TurnId;
67
- itemId?: ProviderItemId;
68
-}
69
-
70
-interface CodexUserInputAnswer {
71
- answers: string[];
72
-}
73
-
74
-interface 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
-
87
-interface JsonRpcError {
88
- code?: number;
89
- message?: string;
90
-}
91
-
92
-interface JsonRpcRequest {
93
- id: string | number;
94
- method: string;
95
- params?: unknown;
96
-}
97
-
98
-interface JsonRpcResponse {
99
- id: string | number;
100
- result?: unknown;
101
- error?: JsonRpcError;
102
-}
103
-
104
-interface JsonRpcNotification {
105
- method: string;
106
- params?: unknown;
107
-}
108
-
109
-export 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
-
119
-export 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
-
131
-export interface CodexThreadTurnSnapshot {
132
- id: TurnId;
133
- items: unknown[];
134
-}
135
-
136
-export interface CodexThreadSnapshot {
137
- threadId: string;
138
- turns: CodexThreadTurnSnapshot[];
139
-}
140
-
141
-const CODEX_VERSION_CHECK_TIMEOUT_MS = 4_000;
142
-
143
-const ANSI_ESCAPE_CHAR = String.fromCharCode(27);
144
-const ANSI_ESCAPE_REGEX = new RegExp(`${ANSI_ESCAPE_CHAR}\\[[0-9;]*m`, "g");
145
-const CODEX_STDERR_LOG_REGEX =
146
- /^\d{4}-\d{2}-\d{2}T\S+\s+(TRACE|DEBUG|INFO|WARN|ERROR)\s+\S+:\s+(.*)$/;
147
-const 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
-];
151
-const RECOVERABLE_THREAD_RESUME_ERROR_SNIPPETS = [
152
- "not found",
153
- "missing thread",
154
- "no such thread",
155
- "unknown thread",
156
- "does not exist",
157
-];
158
-export const CODEX_PLAN_MODE_DEVELOPER_INSTRUCTIONS = `<collaboration_mode># Plan Mode (Conversational)
159
-
160
-You work in 3 phases, and you should *chat your way* to a great plan before finalizing it. A great plan is very detailed-intent- and implementation-wise-so that it can be handed to another engineer or agent to be implemented right away. It must be **decision complete**, where the implementer does not need to make any decisions.
161
-
162
-## Mode rules (strict)
163
-
164
-You are in **Plan Mode** until a developer message explicitly ends it.
165
-
166
-Plan Mode is not changed by user intent, tone, or imperative language. If a user asks for execution while still in Plan Mode, treat it as a request to **plan the execution**, not perform it.
167
-
168
-## Plan Mode vs update_plan tool
169
-
170
-Plan Mode is a collaboration mode that can involve requesting user input and eventually issuing a \`<proposed_plan>\` block.
171
-
172
-Separately, \`update_plan\` is a checklist/progress/TODOs tool; it does not enter or exit Plan Mode. Do not confuse it with Plan mode or try to use it while in Plan mode. If you try to use \`update_plan\` in Plan mode, it will return an error.
173
-
174
-## Execution vs. mutation in Plan Mode
175
-
176
-You 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
-
180
-Actions 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
-
189
-Actions 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
-
196
-When 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
-
200
-Begin by grounding yourself in the actual environment. Eliminate unknowns in the prompt by discovering facts, not by asking the user. Resolve all questions that can be answered through exploration or inspection. Identify missing or ambiguous details only if they cannot be derived from the environment. Silent exploration between turns is allowed and encouraged.
201
-
202
-Before asking the user any question, perform at least one targeted non-mutating exploration pass (for example: search relevant files, inspect likely entrypoints/configs, confirm current implementation shape), unless no local environment/repo is available.
203
-
204
-Exception: you may ask clarifying questions about the user's prompt before exploring, ONLY if there are obvious ambiguities or contradictions in the prompt itself. However, if ambiguity might be resolved by exploring, always prefer exploring first.
205
-
206
-Do not ask questions that can be answered from the repo or system (for example, "where is this struct?" or "which UI component should we use?" when exploration can make it clear). Only ask once you have exhausted reasonable non-mutating exploration.
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
-
219
-Critical 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
-
225
-You 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
-
232
-Use the \`request_user_input\` tool only for decisions that materially change the plan, for confirming important assumptions, or for information that cannot be discovered via non-mutating exploration.
233
-
234
-## Two kinds of unknowns (treat differently)
235
-
236
-1. **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
-
243
-2. **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
-
251
-Only output the final plan when it is decision complete and leaves no decisions to the implementer.
252
-
253
-When you present the official plan, wrap it in a \`<proposed_plan>\` block so the client can render it specially:
254
-
255
-1) The opening tag must be on its own line.
256
-2) Start the plan content on the next line (no text on the same line as the tag).
257
-3) The closing tag must be on its own line.
258
-4) Use Markdown inside the block.
259
-5) 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
-
261
-Example:
262
-
263
-<proposed_plan>
264
-plan content
265
-</proposed_plan>
266
-
267
-plan 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
-
275
-Do not ask "should I proceed?" in the final output. The user can easily switch out of Plan mode and request implementation if you have included a \`<proposed_plan>\` block in your response. Alternatively, they can decide to stay in Plan mode and continue refining the plan.
276
-
277
-Only produce at most one \`<proposed_plan>\` block per turn, and only when you are presenting a complete spec.
278
-</collaboration_mode>`;
279
-
280
-export const CODEX_DEFAULT_MODE_DEVELOPER_INSTRUCTIONS = `<collaboration_mode># Collaboration Mode: Default
281
-
282
-You are now in Default mode. Any previous instructions for other modes (e.g. Plan mode) are no longer active.
283
-
284
-Your 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
-
288
-The \`request_user_input\` tool is unavailable in Default mode. If you call it while in Default mode, it will return an error.
289
-
290
-In Default mode, strongly prefer making reasonable assumptions and executing the user's request rather than stopping to ask questions. If you absolutely must ask a question because the answer cannot be discovered from local context and a reasonable assumption would be risky, ask the user directly with a concise plain-text question. Never write a multiple choice question as a textual assistant message.
291
-</collaboration_mode>`;
292
-
293
-function 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
- */
321
-function killChildTree(child: ChildProcessWithoutNullStreams): void {
322
- killCodexChildProcess(child);
323
-}
324
-
325
-export 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
-
341
-function 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
-
372
-function 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
-
393
-function 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
-
404
-export 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
-
426
-export 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
-
435
-export interface CodexAppServerManagerEvents {
436
- event: [event: ProviderEvent];
437
-}
438
-
439
-export 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
-
1554
-function 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
-
1562
-function normalizeProviderThreadId(value: string | undefined): string | undefined {
1563
- return brandIfNonEmpty(value, (normalized) => normalized);
1564
-}
1565
-
1566
-function 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
-
1611
-function 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
-
1619
-function readResumeThreadId(input: {
1620
- readonly resumeCursor?: unknown;
1621
- readonly threadId?: ThreadId;
1622
- readonly runtimeMode?: RuntimeMode;
1623
-}): string | undefined {
1624
- return readResumeCursorThreadId(input.resumeCursor);
1625
-}
1626
-
1627
-function toTurnId(value: string | undefined): TurnId | undefined {
1628
- return brandIfNonEmpty(value, TurnId.make);
1629
-}
1630
-
1631
-function 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
sanitizeThreadTitle,
30
toJsonSchemaObject,
31
} from "../Utils.ts";
32
-import { getCodexModelCapabilities } from "../../provider/Layers/CodexProvider.ts";
32
import { ServerSettingsService } from "../../serverSettings.ts";
34
-import { normalizeCodexModelOptionsWithCapabilities } from "@t3tools/shared/model";
33
34
const CODEX_GIT_TEXT_GENERATION_REASONING_EFFORT = "low";
35
const CODEX_TIMEOUT_MS = 180_000;
@@ -156,10 +154,6 @@ const makeCodexTextGeneration = Effect.gen(function* () {
154
).pipe(Effect.catch(() => Effect.undefined));
155
156
const runCodexCommand = Effect.fn("runCodexJson.runCodexCommand")(function* () {
159
- const normalizedOptions = normalizeCodexModelOptionsWithCapabilities(
160
- getCodexModelCapabilities(modelSelection.model),
161
- modelSelection.options,
162
- );
157
const reasoningEffort =
158
modelSelection.options?.reasoningEffort ?? CODEX_GIT_TEXT_GENERATION_REASONING_EFFORT;
159
const command = ChildProcess.make(
@@ -174,7 +168,7 @@ const makeCodexTextGeneration = Effect.gen(function* () {
168
modelSelection.model,
169
"--config",
170
`model_reasoning_effort="${reasoningEffort}"`,
177
- ...(normalizedOptions?.fastMode ? ["--config", `service_tier="fast"`] : []),
171
+ ...(modelSelection.options?.fastMode ? ["--config", `service_tier="fast"`] : []),
172
"--output-schema",
173
schemaPath,
174
"--output-last-message",
apps/server/src/provider/CodexDeveloperInstructions.ts
new
+134
@@ -0,0 +1,134 @@
1
+export const CODEX_PLAN_MODE_DEVELOPER_INSTRUCTIONS = `<collaboration_mode># Plan Mode (Conversational)
2
+
3
+You work in 3 phases, and you should *chat your way* to a great plan before finalizing it. A great plan is very detailed-intent- and implementation-wise-so that it can be handed to another engineer or agent to be implemented right away. It must be **decision complete**, where the implementer does not need to make any decisions.
4
+
5
+## Mode rules (strict)
6
+
7
+You are in **Plan Mode** until a developer message explicitly ends it.
8
+
9
+Plan Mode is not changed by user intent, tone, or imperative language. If a user asks for execution while still in Plan Mode, treat it as a request to **plan the execution**, not perform it.
10
+
11
+## Plan Mode vs update_plan tool
12
+
13
+Plan Mode is a collaboration mode that can involve requesting user input and eventually issuing a \`<proposed_plan>\` block.
14
+
15
+Separately, \`update_plan\` is a checklist/progress/TODOs tool; it does not enter or exit Plan Mode. Do not confuse it with Plan mode or try to use it while in Plan mode. If you try to use \`update_plan\` in Plan mode, it will return an error.
16
+
17
+## Execution vs. mutation in Plan Mode
18
+
19
+You 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
+
23
+Actions 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
+
32
+Actions 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
+
39
+When 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
+
43
+Begin by grounding yourself in the actual environment. Eliminate unknowns in the prompt by discovering facts, not by asking the user. Resolve all questions that can be answered through exploration or inspection. Identify missing or ambiguous details only if they cannot be derived from the environment. Silent exploration between turns is allowed and encouraged.
44
+
45
+Before asking the user any question, perform at least one targeted non-mutating exploration pass (for example: search relevant files, inspect likely entrypoints/configs, confirm current implementation shape), unless no local environment/repo is available.
46
+
47
+Exception: you may ask clarifying questions about the user's prompt before exploring, ONLY if there are obvious ambiguities or contradictions in the prompt itself. However, if ambiguity might be resolved by exploring, always prefer exploring first.
48
+
49
+Do not ask questions that can be answered from the repo or system (for example, "where is this struct?" or "which UI component should we use?" when exploration can make it clear). Only ask once you have exhausted reasonable non-mutating exploration.
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
+
62
+Critical 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
+
68
+You 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
+
75
+Use the \`request_user_input\` tool only for decisions that materially change the plan, for confirming important assumptions, or for information that cannot be discovered via non-mutating exploration.
76
+
77
+## Two kinds of unknowns (treat differently)
78
+
79
+1. **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
+
86
+2. **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
+
94
+Only output the final plan when it is decision complete and leaves no decisions to the implementer.
95
+
96
+When you present the official plan, wrap it in a \`<proposed_plan>\` block so the client can render it specially:
97
+
98
+1) The opening tag must be on its own line.
99
+2) Start the plan content on the next line (no text on the same line as the tag).
100
+3) The closing tag must be on its own line.
101
+4) Use Markdown inside the block.
102
+5) 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
+
104
+Example:
105
+
106
+<proposed_plan>
107
+plan content
108
+</proposed_plan>
109
+
110
+plan 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
+
118
+Do not ask "should I proceed?" in the final output. The user can easily switch out of Plan mode and request implementation if you have included a \`<proposed_plan>\` block in your response. Alternatively, they can decide to stay in Plan mode and continue refining the plan.
119
+
120
+Only produce at most one \`<proposed_plan>\` block per turn, and only when you are presenting a complete spec.
121
+</collaboration_mode>`;
122
+
123
+export const CODEX_DEFAULT_MODE_DEVELOPER_INSTRUCTIONS = `<collaboration_mode># Collaboration Mode: Default
124
+
125
+You are now in Default mode. Any previous instructions for other modes (e.g. Plan mode) are no longer active.
126
+
127
+Your 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
+
131
+The \`request_user_input\` tool is unavailable in Default mode. If you call it while in Default mode, it will return an error.
132
+
133
+In Default mode, strongly prefer making reasonable assumptions and executing the user's request rather than stopping to ask questions. If you absolutely must ask a question because the answer cannot be discovered from local context and a reasonable assumption would be risky, ask the user directly with a concise plain-text question. Never write a multiple choice question as a textual assistant message.
134
+</collaboration_mode>`;
apps/server/src/provider/Layers/CodexAdapter.test.ts
+348
-302
@@ -1,4 +1,7 @@
1
import assert from "node:assert/strict";
2
+import fs from "node:fs";
3
+import os from "node:os";
4
+import path from "node:path";
5
import {
6
ApprovalRequestId,
7
EventId,
@@ -12,20 +15,22 @@ import {
15
TurnId,
16
} from "@t3tools/contracts";
17
import * as NodeServices from "@effect/platform-node/NodeServices";
15
-import { afterAll, it, vi } from "@effect/vitest";
18
+import { it, vi } from "@effect/vitest";
19
17
-import { Effect, Fiber, Layer, Option, Stream } from "effect";
20
+import { Effect, Exit, Fiber, Layer, Option, Queue, Scope, Stream } from "effect";
21
+import * as CodexErrors from "effect-codex-app-server/errors";
22
19
-import {
20
- CodexAppServerManager,
21
- type CodexAppServerStartSessionInput,
22
- type CodexAppServerSendTurnInput,
23
-} from "../../codexAppServerManager.ts";
23
import { ServerConfig } from "../../config.ts";
24
import { ServerSettingsService } from "../../serverSettings.ts";
25
import { ProviderAdapterValidationError } from "../Errors.ts";
26
import { CodexAdapter } from "../Services/CodexAdapter.ts";
27
import { ProviderSessionDirectory } from "../Services/ProviderSessionDirectory.ts";
28
+import {
29
+ type CodexSessionRuntimeOptions,
30
+ type CodexSessionRuntimeSendTurnInput,
31
+ type CodexSessionRuntimeShape,
32
+ type CodexThreadSnapshot,
33
+} from "./CodexSessionRuntime.ts";
34
import { makeCodexAdapterLive } from "./CodexAdapter.ts";
35
36
const asThreadId = (value: string): ThreadId => ThreadId.make(value);
@@ -33,112 +38,159 @@ const asTurnId = (value: string): TurnId => TurnId.make(value);
38
const asEventId = (value: string): EventId => EventId.make(value);
39
const asItemId = (value: string): ProviderItemId => ProviderItemId.make(value);
40
36
-class FakeCodexManager extends CodexAppServerManager {
37
- public startSessionImpl = vi.fn(
38
- async (input: CodexAppServerStartSessionInput): Promise<ProviderSession> => {
39
- const now = new Date().toISOString();
40
- return {
41
- provider: "codex",
42
- status: "ready",
43
- runtimeMode: input.runtimeMode,
44
- threadId: input.threadId,
45
- cwd: input.cwd,
46
- createdAt: now,
47
- updatedAt: now,
48
- };
49
- },
41
+class FakeCodexRuntime implements CodexSessionRuntimeShape {
42
+ private readonly eventQueue = Effect.runSync(Queue.unbounded<ProviderEvent>());
43
+ private readonly now = new Date().toISOString();
44
+
45
+ public readonly startImpl = vi.fn(() =>
46
+ Promise.resolve({
47
+ provider: "codex" as const,
48
+ status: "ready" as const,
49
+ runtimeMode: this.options.runtimeMode,
50
+ threadId: this.options.threadId,
51
+ cwd: this.options.cwd,
52
+ ...(this.options.model ? { model: this.options.model } : {}),
53
+ createdAt: this.now,
54
+ updatedAt: this.now,
55
+ } satisfies ProviderSession),
56
);
57
52
- public sendTurnImpl = vi.fn(
53
- async (_input: CodexAppServerSendTurnInput): Promise<ProviderTurnStartResult> => ({
54
- threadId: asThreadId("thread-1"),
55
- turnId: asTurnId("turn-1"),
56
- }),
58
+ public readonly sendTurnImpl = vi.fn(
59
+ (_input: CodexSessionRuntimeSendTurnInput): Promise<ProviderTurnStartResult> =>
60
+ Promise.resolve({
61
+ threadId: this.options.threadId,
62
+ turnId: asTurnId("turn-1"),
63
+ }),
64
);
65
59
- public interruptTurnImpl = vi.fn(
60
- async (_threadId: ThreadId, _turnId?: TurnId): Promise<void> => undefined,
66
+ public readonly interruptTurnImpl = vi.fn(
67
+ (_turnId?: TurnId): Promise<void> => Promise.resolve(undefined),
68
);
69
63
- public readThreadImpl = vi.fn(async (_threadId: ThreadId) => ({
64
- threadId: asThreadId("thread-1"),
65
- turns: [],
66
- }));
67
-
68
- public rollbackThreadImpl = vi.fn(async (_threadId: ThreadId, _numTurns: number) => ({
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,
70
+ public readonly readThreadImpl = vi.fn(
71
+ (): Promise<CodexThreadSnapshot> =>
72
+ Promise.resolve({
73
+ threadId: "provider-thread-1",
74
+ turns: [],
75
+ }),
76
);
77
81
- public respondToUserInputImpl = vi.fn(
82
- async (
83
- _threadId: ThreadId,
84
- _requestId: ApprovalRequestId,
85
- _answers: ProviderUserInputAnswers,
86
- ): Promise<void> => undefined,
78
+ public readonly rollbackThreadImpl = vi.fn(
79
+ (_numTurns: number): Promise<CodexThreadSnapshot> =>
80
+ Promise.resolve({
81
+ threadId: "provider-thread-1",
82
+ turns: [],
83
+ }),
84
);
85
89
- public stopAllImpl = vi.fn(() => undefined);
86
+ public readonly respondToRequestImpl = vi.fn(
87
+ (_requestId: ApprovalRequestId, _decision: ProviderApprovalDecision): Promise<void> =>
88
+ Promise.resolve(undefined),
89
+ );
90
91
- override startSession(input: CodexAppServerStartSessionInput): Promise<ProviderSession> {
92
- return this.startSessionImpl(input);
93
- }
91
+ public readonly respondToUserInputImpl = vi.fn(
92
+ (_requestId: ApprovalRequestId, _answers: ProviderUserInputAnswers): Promise<void> =>
93
+ Promise.resolve(undefined),
94
+ );
95
95
- override sendTurn(input: CodexAppServerSendTurnInput): Promise<ProviderTurnStartResult> {
96
- return this.sendTurnImpl(input);
97
- }
96
+ public readonly closeImpl = vi.fn(() => Promise.resolve(undefined));
97
+
98
+ readonly options: CodexSessionRuntimeOptions;
99
99
- override interruptTurn(threadId: ThreadId, turnId?: TurnId): Promise<void> {
100
- return this.interruptTurnImpl(threadId, turnId);
100
+ constructor(options: CodexSessionRuntimeOptions) {
101
+ this.options = options;
102
}
103
103
- override readThread(threadId: ThreadId) {
104
- return this.readThreadImpl(threadId);
104
+ start() {
105
+ return Effect.promise(() => this.startImpl());
106
}
107
107
- override rollbackThread(threadId: ThreadId, numTurns: number) {
108
- return this.rollbackThreadImpl(threadId, numTurns);
108
+ getSession = Effect.promise(() => this.startImpl());
109
+
110
+ sendTurn(input: CodexSessionRuntimeSendTurnInput) {
111
+ return Effect.promise(() => this.sendTurnImpl(input));
112
}
113
111
- override respondToRequest(
112
- threadId: ThreadId,
113
- requestId: ApprovalRequestId,
114
- decision: ProviderApprovalDecision,
115
- ): Promise<void> {
116
- return this.respondToRequestImpl(threadId, requestId, decision);
114
+ interruptTurn(turnId?: TurnId) {
115
+ return Effect.promise(() => this.interruptTurnImpl(turnId));
116
}
117
119
- override respondToUserInput(
120
- threadId: ThreadId,
121
- requestId: ApprovalRequestId,
122
- answers: ProviderUserInputAnswers,
123
- ): Promise<void> {
124
- return this.respondToUserInputImpl(threadId, requestId, answers);
118
+ readThread = Effect.promise(() => this.readThreadImpl());
119
+
120
+ rollbackThread(numTurns: number) {
121
+ return Effect.promise(() => this.rollbackThreadImpl(numTurns));
122
}
123
127
- override stopSession(_threadId: ThreadId): void {}
124
+ respondToRequest(requestId: ApprovalRequestId, decision: ProviderApprovalDecision) {
125
+ return Effect.promise(() => this.respondToRequestImpl(requestId, decision));
126
+ }
127
129
- override listSessions(): ProviderSession[] {
130
- return [];
128
+ respondToUserInput(requestId: ApprovalRequestId, answers: ProviderUserInputAnswers) {
129
+ return Effect.promise(() => this.respondToUserInputImpl(requestId, answers));
130
}
131
133
- override hasSession(_threadId: ThreadId): boolean {
134
- return false;
132
+ get events() {
133
+ return Stream.fromQueue(this.eventQueue);
134
}
135
137
- override stopAll(): void {
138
- this.stopAllImpl();
136
+ close = Effect.promise(() => this.closeImpl());
137
+
138
+ emit(event: ProviderEvent) {
139
+ return Queue.offer(this.eventQueue, event).pipe(Effect.asVoid);
140
}
141
}
142
143
+function 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
+
159
+function 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
+
194
const providerSessionDirectoryTestLayer = Layer.succeed(ProviderSessionDirectory, {
195
upsert: () => Effect.void,
196
getProvider: () =>
@@ -148,9 +200,9 @@ const providerSessionDirectoryTestLayer = Layer.succeed(ProviderSessionDirectory
200
listBindings: () => Effect.succeed([]),
201
});
202
151
-const validationManager = new FakeCodexManager();
203
+const validationRuntimeFactory = makeRuntimeFactory();
204
const validationLayer = it.layer(
153
- makeCodexAdapterLive({ manager: validationManager }).pipe(
205
+ makeCodexAdapterLive({ makeRuntime: validationRuntimeFactory.factory }).pipe(
206
Layer.provideMerge(ServerConfig.layerTest(process.cwd(), process.cwd())),
207
Layer.provideMerge(ServerSettingsService.layerTest()),
208
Layer.provideMerge(providerSessionDirectoryTestLayer),
@@ -179,12 +231,12 @@ validationLayer("CodexAdapterLive validation", (it) => {
231
issue: "Expected provider 'codex' but received 'claudeAgent'.",
232
}),
233
);
182
- assert.equal(validationManager.startSessionImpl.mock.calls.length, 0);
234
+ assert.equal(validationRuntimeFactory.factory.mock.calls.length, 0);
235
}),
236
);
237
it.effect("maps codex model options before starting a session", () =>
238
Effect.gen(function* () {
187
- validationManager.startSessionImpl.mockClear();
239
+ validationRuntimeFactory.factory.mockClear();
240
const adapter = yield* CodexAdapter;
241
242
yield* adapter.startSession({
@@ -200,24 +252,21 @@ validationLayer("CodexAdapterLive validation", (it) => {
252
runtimeMode: "full-access",
253
});
254
203
- assert.deepStrictEqual(validationManager.startSessionImpl.mock.calls[0]?.[0], {
204
- provider: "codex",
205
- threadId: asThreadId("thread-1"),
255
+ assert.deepStrictEqual(validationRuntimeFactory.factory.mock.calls[0]?.[0], {
256
binaryPath: "codex",
257
+ cwd: process.cwd(),
258
model: "gpt-5.3-codex",
259
serviceTier: "fast",
260
+ threadId: asThreadId("thread-1"),
261
runtimeMode: "full-access",
262
});
263
}),
264
);
265
});
266
215
-const sessionErrorManager = new FakeCodexManager();
216
-sessionErrorManager.sendTurnImpl.mockImplementation(async () => {
217
- throw new Error("Unknown session: sess-missing");
218
-});
267
+const sessionRuntimeFactory = makeRuntimeFactory();
268
const sessionErrorLayer = it.layer(
220
- makeCodexAdapterLive({ manager: sessionErrorManager }).pipe(
269
+ makeCodexAdapterLive({ makeRuntime: sessionRuntimeFactory.factory }).pipe(
270
Layer.provideMerge(ServerConfig.layerTest(process.cwd(), process.cwd())),
271
Layer.provideMerge(ServerSettingsService.layerTest()),
272
Layer.provideMerge(providerSessionDirectoryTestLayer),
@@ -226,7 +275,7 @@ const sessionErrorLayer = it.layer(
275
);
276
277
sessionErrorLayer("CodexAdapterLive session errors", (it) => {
229
- it.effect("maps unknown-session sendTurn errors to ProviderAdapterSessionNotFoundError", () =>
278
+ it.effect("maps missing adapter sessions to ProviderAdapterSessionNotFoundError", () =>
279
Effect.gen(function* () {
280
const adapter = yield* CodexAdapter;
281
const result = yield* adapter
@@ -241,14 +290,20 @@ sessionErrorLayer("CodexAdapterLive session errors", (it) => {
290
assert.equal(result.failure._tag, "ProviderAdapterSessionNotFoundError");
291
assert.equal(result.failure.provider, "codex");
292
assert.equal(result.failure.threadId, "sess-missing");
244
- assert.equal(result.failure.cause instanceof Error, true);
293
}),
294
);
295
296
it.effect("maps codex model options before sending a turn", () =>
297
Effect.gen(function* () {
250
- sessionErrorManager.sendTurnImpl.mockClear();
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();
307
308
yield* Effect.ignore(
309
adapter.sendTurn({
@@ -266,8 +321,7 @@ sessionErrorLayer("CodexAdapterLive session errors", (it) => {
321
}),
322
);
323
269
- assert.deepStrictEqual(sessionErrorManager.sendTurnImpl.mock.calls[0]?.[0], {
270
- threadId: asThreadId("sess-missing"),
324
+ assert.deepStrictEqual(runtime.sendTurnImpl.mock.calls[0]?.[0], {
325
input: "hello",
326
model: "gpt-5.3-codex",
327
effort: "high",
@@ -277,9 +331,9 @@ sessionErrorLayer("CodexAdapterLive session errors", (it) => {
331
);
332
});
333
280
-const lifecycleManager = new FakeCodexManager();
334
+const lifecycleRuntimeFactory = makeRuntimeFactory();
335
const lifecycleLayer = it.layer(
282
- makeCodexAdapterLive({ manager: lifecycleManager }).pipe(
336
+ makeCodexAdapterLive({ makeRuntime: lifecycleRuntimeFactory.factory }).pipe(
337
Layer.provideMerge(ServerConfig.layerTest(process.cwd(), process.cwd())),
338
Layer.provideMerge(ServerSettingsService.layerTest()),
339
Layer.provideMerge(providerSessionDirectoryTestLayer),
@@ -287,10 +341,24 @@ const lifecycleLayer = it.layer(
341
),
342
);
343
344
+function 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
+
358
lifecycleLayer("CodexAdapterLive lifecycle", (it) => {
359
it.effect("maps completed agent message items to canonical item.completed events", () =>
360
Effect.gen(function* () {
293
- const adapter = yield* CodexAdapter;
361
+ const { adapter, runtime } = yield* startLifecycleRuntime();
362
const firstEventFiber = yield* Stream.runHead(adapter.streamEvents).pipe(Effect.forkChild);
363
364
const event: ProviderEvent = {
@@ -303,14 +371,17 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => {
371
turnId: asTurnId("turn-1"),
372
itemId: asItemId("msg_1"),
373
payload: {
374
+ threadId: "thread-1",
375
+ turnId: "turn-1",
376
item: {
377
type: "agentMessage",
378
id: "msg_1",
379
+ text: "done",
380
},
381
},
382
};
383
313
- lifecycleManager.emit("event", event);
384
+ yield* runtime.emit(event);
385
const firstEvent = yield* Fiber.join(firstEventFiber);
386
387
assert.equal(firstEvent._tag, "Some");
@@ -329,7 +400,7 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => {
400
401
it.effect("maps completed plan items to canonical proposed-plan completion events", () =>
402
Effect.gen(function* () {
332
- const adapter = yield* CodexAdapter;
403
+ const { adapter, runtime } = yield* startLifecycleRuntime();
404
const firstEventFiber = yield* Stream.runHead(adapter.streamEvents).pipe(Effect.forkChild);
405
406
const event: ProviderEvent = {
@@ -342,15 +413,17 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => {
413
turnId: asTurnId("turn-1"),
414
itemId: asItemId("plan_1"),
415
payload: {
416
+ threadId: "thread-1",
417
+ turnId: "turn-1",
418
item: {
346
- type: "Plan",
419
+ type: "plan",
420
id: "plan_1",
421
text: "## Final plan\n\n- one\n- two",
422
},
423
},
424
};
425
353
- lifecycleManager.emit("event", event);
426
+ yield* runtime.emit(event);
427
const firstEvent = yield* Fiber.join(firstEventFiber);
428
429
assert.equal(firstEvent._tag, "Some");
@@ -368,10 +441,10 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => {
441
442
it.effect("maps plan deltas to canonical proposed-plan delta events", () =>
443
Effect.gen(function* () {
371
- const adapter = yield* CodexAdapter;
444
+ const { adapter, runtime } = yield* startLifecycleRuntime();
445
const firstEventFiber = yield* Stream.runHead(adapter.streamEvents).pipe(Effect.forkChild);
446
374
- lifecycleManager.emit("event", {
447
+ yield* runtime.emit({
448
id: asEventId("evt-plan-delta"),
449
kind: "notification",
450
provider: "codex",
@@ -381,6 +454,9 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => {
454
turnId: asTurnId("turn-1"),
455
itemId: asItemId("plan_1"),
456
payload: {
457
+ threadId: "thread-1",
458
+ turnId: "turn-1",
459
+ itemId: "plan_1",
460
delta: "## Final plan",
461
},
462
} satisfies ProviderEvent);
@@ -402,7 +478,7 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => {
478
479
it.effect("maps session/closed lifecycle events to canonical session.exited runtime events", () =>
480
Effect.gen(function* () {
405
- const adapter = yield* CodexAdapter;
481
+ const { adapter, runtime } = yield* startLifecycleRuntime();
482
const firstEventFiber = yield* Stream.runHead(adapter.streamEvents).pipe(Effect.forkChild);
483
484
const event: ProviderEvent = {
@@ -415,7 +491,7 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => {
491
message: "Session stopped",
492
};
493
418
- lifecycleManager.emit("event", event);
494
+ yield* runtime.emit(event);
495
const firstEvent = yield* Fiber.join(firstEventFiber);
496
497
assert.equal(firstEvent._tag, "Some");
@@ -433,10 +509,10 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => {
509
510
it.effect("maps retryable Codex error notifications to runtime.warning", () =>
511
Effect.gen(function* () {
436
- const adapter = yield* CodexAdapter;
512
+ const { adapter, runtime } = yield* startLifecycleRuntime();
513
const firstEventFiber = yield* Stream.runHead(adapter.streamEvents).pipe(Effect.forkChild);
514
439
- lifecycleManager.emit("event", {
515
+ yield* runtime.emit({
516
id: asEventId("evt-retryable-error"),
517
kind: "notification",
518
provider: "codex",
@@ -445,6 +521,8 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => {
521
method: "error",
522
turnId: asTurnId("turn-1"),
523
payload: {
524
+ threadId: "thread-1",
525
+ turnId: "turn-1",
526
error: {
527
message: "Reconnecting... 2/5",
528
},
@@ -469,10 +547,10 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => {
547
548
it.effect("maps process stderr notifications to runtime.warning", () =>
549
Effect.gen(function* () {
472
- const adapter = yield* CodexAdapter;
550
+ const { adapter, runtime } = yield* startLifecycleRuntime();
551
const firstEventFiber = yield* Stream.runHead(adapter.streamEvents).pipe(Effect.forkChild);
552
475
- lifecycleManager.emit("event", {
553
+ yield* runtime.emit({
554
id: asEventId("evt-process-stderr"),
555
kind: "notification",
556
provider: "codex",
@@ -503,10 +581,10 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => {
581
582
it.effect("maps fatal websocket stderr notifications to runtime.error", () =>
583
Effect.gen(function* () {
506
- const adapter = yield* CodexAdapter;
584
+ const { adapter, runtime } = yield* startLifecycleRuntime();
585
const firstEventFiber = yield* Stream.runHead(adapter.streamEvents).pipe(Effect.forkChild);
586
509
- lifecycleManager.emit("event", {
587
+ yield* runtime.emit({
588
id: asEventId("evt-process-stderr-websocket"),
589
kind: "notification",
590
provider: "codex",
@@ -539,7 +617,7 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => {
617
618
it.effect("preserves request type when mapping serverRequest/resolved", () =>
619
Effect.gen(function* () {
542
- const adapter = yield* CodexAdapter;
620
+ const { adapter, runtime } = yield* startLifecycleRuntime();
621
const firstEventFiber = yield* Stream.runHead(adapter.streamEvents).pipe(Effect.forkChild);
622
623
const event: ProviderEvent = {
@@ -549,16 +627,15 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => {
627
threadId: asThreadId("thread-1"),
628
createdAt: new Date().toISOString(),
629
method: "serverRequest/resolved",
630
+ requestKind: "command",
631
requestId: ApprovalRequestId.make("req-1"),
632
payload: {
554
- request: {
555
- method: "item/commandExecution/requestApproval",
556
- },
557
- decision: "accept",
633
+ threadId: "thread-1",
634
+ requestId: "req-1",
635
},
636
};
637
561
- lifecycleManager.emit("event", event);
638
+ yield* runtime.emit(event);
639
const firstEvent = yield* Fiber.join(firstEventFiber);
640
641
assert.equal(firstEvent._tag, "Some");
@@ -575,7 +652,7 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => {
652
653
it.effect("preserves file-read request type when mapping serverRequest/resolved", () =>
654
Effect.gen(function* () {
578
- const adapter = yield* CodexAdapter;
655
+ const { adapter, runtime } = yield* startLifecycleRuntime();
656
const firstEventFiber = yield* Stream.runHead(adapter.streamEvents).pipe(Effect.forkChild);
657
658
const event: ProviderEvent = {
@@ -585,16 +662,15 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => {
662
threadId: asThreadId("thread-1"),
663
createdAt: new Date().toISOString(),
664
method: "serverRequest/resolved",
665
+ requestKind: "file-read",
666
requestId: ApprovalRequestId.make("req-file-read-1"),
667
payload: {
590
- request: {
591
- method: "item/fileRead/requestApproval",
592
- },
593
- decision: "accept",
668
+ threadId: "thread-1",
669
+ requestId: "req-file-read-1",
670
},
671
};
672
597
- lifecycleManager.emit("event", event);
673
+ yield* runtime.emit(event);
674
const firstEvent = yield* Fiber.join(firstEventFiber);
675
676
assert.equal(firstEvent._tag, "Some");
@@ -611,7 +687,7 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => {
687
688
it.effect("preserves explicit empty multi-select user-input answers", () =>
689
Effect.gen(function* () {
614
- const adapter = yield* CodexAdapter;
690
+ const { adapter, runtime } = yield* startLifecycleRuntime();
691
const firstEventFiber = yield* Stream.runHead(adapter.streamEvents).pipe(Effect.forkChild);
692
693
const event: ProviderEvent = {
@@ -623,12 +699,14 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => {
699
method: "item/tool/requestUserInput/answered",
700
payload: {
701
answers: {
626
- scope: [],
702
+ scope: {
703
+ answers: [],
704
+ },
705
},
706
},
707
};
708
631
- lifecycleManager.emit("event", event);
709
+ yield* runtime.emit(event);
710
const firstEvent = yield* Fiber.join(firstEventFiber);
711
712
assert.equal(firstEvent._tag, "Some");
@@ -647,7 +725,7 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => {
725
726
it.effect("maps windowsSandbox/setupCompleted to session state and warning on failure", () =>
727
Effect.gen(function* () {
650
- const adapter = yield* CodexAdapter;
728
+ const { adapter, runtime } = yield* startLifecycleRuntime();
729
const eventsFiber = yield* Stream.runCollect(Stream.take(adapter.streamEvents, 2)).pipe(
730
Effect.forkChild,
731
);
@@ -661,12 +739,13 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => {
739
method: "windowsSandbox/setupCompleted",
740
message: "Sandbox setup failed",
741
payload: {
742
+ mode: "unelevated",
743
success: false,
665
- detail: "unsupported environment",
744
+ error: "unsupported environment",
745
},
746
};
747
669
- lifecycleManager.emit("event", event);
748
+ yield* runtime.emit(event);
749
const events = Array.from(yield* Fiber.join(eventsFiber));
750
751
assert.equal(events.length, 2);
@@ -691,12 +770,12 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => {
770
"maps requestUserInput requests and answered notifications to canonical user-input events",
771
() =>
772
Effect.gen(function* () {
694
- const adapter = yield* CodexAdapter;
773
+ const { adapter, runtime } = yield* startLifecycleRuntime();
774
const eventsFiber = yield* Stream.runCollect(Stream.take(adapter.streamEvents, 2)).pipe(
775
Effect.forkChild,
776
);
777
699
- lifecycleManager.emit("event", {
778
+ yield* runtime.emit({
779
id: asEventId("evt-user-input-requested"),
780
kind: "request",
781
provider: "codex",
@@ -705,6 +784,9 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => {
784
method: "item/tool/requestUserInput",
785
requestId: ApprovalRequestId.make("req-user-input-1"),
786
payload: {
787
+ itemId: "item-user-input-1",
788
+ threadId: "thread-1",
789
+ turnId: "turn-1",
790
questions: [
791
{
792
id: "sandbox_mode",
@@ -716,12 +798,11 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => {
798
description: "Allow workspace writes only",
799
},
800
],
719
- multiSelect: true,
801
},
802
],
803
},
804
} satisfies ProviderEvent);
724
- lifecycleManager.emit("event", {
805
+ yield* runtime.emit({
806
id: asEventId("evt-user-input-resolved"),
807
kind: "notification",
808
provider: "codex",
@@ -743,7 +824,7 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => {
824
if (events[0]?.type === "user-input.requested") {
825
assert.equal(events[0].requestId, "req-user-input-1");
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);
828
}
829
830
assert.equal(events[1]?.type, "user-input.resolved");
@@ -756,168 +837,12 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => {
837
}),
838
);
839
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
-
840
it.effect("unwraps Codex token usage payloads for context window events", () =>
841
Effect.gen(function* () {
917
- const adapter = yield* CodexAdapter;
842
+ const { adapter, runtime } = yield* startLifecycleRuntime();
843
const firstEventFiber = yield* Stream.runHead(adapter.streamEvents).pipe(Effect.forkChild);
844
920
- lifecycleManager.emit("event", {
845
+ yield* runtime.emit({
846
id: asEventId("evt-codex-thread-token-usage-updated"),
847
kind: "notification",
848
provider: "codex",
@@ -977,9 +902,130 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => {
902
);
903
});
904
980
-afterAll(() => {
981
- if (lifecycleManager.stopAllImpl.mock.calls.length === 0) {
982
- lifecycleManager.stopAll();
983
- }
984
- assert.ok(lifecycleManager.stopAllImpl.mock.calls.length >= 1);
905
+const scopedLifecycleRuntimeFactory = makeScopedRuntimeFactory();
906
+const scopedLifecycleLayer = it.layer(
907
+ makeCodexAdapterLive({ makeRuntime: scopedLifecycleRuntimeFactory.factory }).pipe(
908
+ Layer.provideMerge(ServerConfig.layerTest(process.cwd(), process.cwd())),
909
+ Layer.provideMerge(ServerSettingsService.layerTest()),
910
+ Layer.provideMerge(providerSessionDirectoryTestLayer),
911
+ Layer.provideMerge(NodeServices.layer),
912
+ ),
913
+);
914
+
915
+scopedLifecycleLayer("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
+ );
939
});
940
+
941
+const scopedFailureRuntimeFactory = makeScopedRuntimeFactory({ failConstruction: true });
942
+const 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
+
951
+scopedFailureLayer("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
+
975
+it.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
/**
2
* CodexAdapterLive - Scoped live implementation for the Codex provider adapter.
3
*
4
- * Wraps `CodexAppServerManager` behind the `CodexAdapter` service contract and
5
- * maps manager failures into the shared `ProviderAdapterError` algebra.
4
+ * Wraps the typed Codex session runtime behind the `CodexAdapter` service
5
+ * contract and maps runtime failures into the shared `ProviderAdapterError`
6
+ * algebra.
7
*
8
* @module CodexAdapterLive
9
*/
@@ -11,98 +12,118 @@ import {
12
type CanonicalRequestType,
13
type ProviderEvent,
14
type ProviderRuntimeEvent,
15
+ type ProviderRequestKind,
16
type ThreadTokenUsageSnapshot,
17
type ProviderUserInputAnswers,
18
RuntimeItemId,
19
RuntimeRequestId,
18
- RuntimeTaskId,
20
ProviderApprovalDecision,
20
- ProviderItemId,
21
ThreadId,
22
- TurnId,
22
ProviderSendTurnInput,
23
} from "@t3tools/contracts";
25
-import { Effect, FileSystem, Layer, Queue, Schema, Context, Stream } from "effect";
24
+import { Effect, Exit, Fiber, FileSystem, Layer, Queue, Schema, Scope, Stream } from "effect";
25
+import { ChildProcessSpawner } from "effect/unstable/process";
26
+import * as CodexErrors from "effect-codex-app-server/errors";
27
+import * as EffectCodexSchema from "effect-codex-app-server/schema";
28
29
import {
28
- ProviderAdapterProcessError,
30
ProviderAdapterRequestError,
31
+ ProviderAdapterProcessError,
32
ProviderAdapterSessionClosedError,
33
ProviderAdapterSessionNotFoundError,
34
ProviderAdapterValidationError,
35
type ProviderAdapterError,
36
} from "../Errors.ts";
37
import { CodexAdapter, type CodexAdapterShape } from "../Services/CodexAdapter.ts";
36
-import {
37
- CodexAppServerManager,
38
- type CodexAppServerStartSessionInput,
39
-} from "../../codexAppServerManager.ts";
38
import { resolveAttachmentPath } from "../../attachmentStore.ts";
39
import { ServerConfig } from "../../config.ts";
40
import { ServerSettingsService } from "../../serverSettings.ts";
41
+import {
42
+ CodexResumeCursorSchema,
43
+ CodexSessionRuntimeThreadIdMissingError,
44
+ makeCodexSessionRuntime,
45
+ type CodexSessionRuntimeError,
46
+ type CodexSessionRuntimeOptions,
47
+ type CodexSessionRuntimeShape,
48
+} from "./CodexSessionRuntime.ts";
49
import { type EventNdjsonLogger, makeEventNdjsonLogger } from "./EventNdjsonLogger.ts";
50
51
const PROVIDER = "codex" as const;
52
53
export interface CodexAdapterLiveOptions {
48
- readonly manager?: CodexAppServerManager;
49
- readonly makeManager?: (services?: Context.Context<never>) => CodexAppServerManager;
54
+ readonly makeRuntime?: (
55
+ options: CodexSessionRuntimeOptions,
56
+ ) => Effect.Effect<
57
+ CodexSessionRuntimeShape,
58
+ CodexSessionRuntimeError,
59
+ ChildProcessSpawner.ChildProcessSpawner | Scope.Scope
60
+ >;
61
readonly nativeEventLogPath?: string;
62
readonly nativeEventLogger?: EventNdjsonLogger;
63
}
64
54
-function toSessionError(
65
+interface 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
+
73
+function mapCodexRuntimeError(
74
threadId: ThreadId,
56
- cause: unknown,
57
-): ProviderAdapterSessionNotFoundError | ProviderAdapterSessionClosedError | undefined {
58
- const normalized = cause instanceof Error ? cause.message.toLowerCase() : "";
59
- if (normalized.includes("unknown session") || normalized.includes("unknown provider session")) {
60
- return new ProviderAdapterSessionNotFoundError({
75
+ method: string,
76
+ error: CodexSessionRuntimeError,
77
+): ProviderAdapterError {
78
+ if (
79
+ Schema.is(CodexErrors.CodexAppServerProcessExitedError)(error) ||
80
+ Schema.is(CodexErrors.CodexAppServerTransportError)(error)
81
+ ) {
82
+ return new ProviderAdapterSessionClosedError({
83
provider: PROVIDER,
84
threadId,
63
- cause,
85
+ cause: error,
86
});
87
}
66
- if (normalized.includes("session is closed")) {
67
- return new ProviderAdapterSessionClosedError({
88
+
89
+ if (Schema.is(CodexSessionRuntimeThreadIdMissingError)(error)) {
90
+ return new ProviderAdapterSessionNotFoundError({
91
provider: PROVIDER,
92
threadId,
70
- cause,
93
+ cause: error,
94
});
95
}
73
- return undefined;
74
-}
96
76
-function toRequestError(threadId: ThreadId, method: string, cause: unknown): ProviderAdapterError {
77
- const sessionError = toSessionError(threadId, cause);
78
- if (sessionError) {
79
- return sessionError;
80
- }
97
return new ProviderAdapterRequestError({
98
provider: PROVIDER,
99
method,
84
- detail: cause instanceof Error ? `${method} failed: ${cause.message}` : `${method} failed`,
85
- cause,
100
+ detail: error.message,
101
+ cause: error,
102
});
103
}
104
89
-function asObject(value: unknown): Record<string, unknown> | undefined {
90
- if (!value || typeof value !== "object") {
91
- return undefined;
92
- }
93
- return value as Record<string, unknown>;
94
-}
105
+type CodexLifecycleItem =
106
+ | EffectCodexSchema.V2ItemStartedNotification["item"]
107
+ | EffectCodexSchema.V2ItemCompletedNotification["item"];
108
96
-function asString(value: unknown): string | undefined {
97
- return typeof value === "string" ? value : undefined;
98
-}
109
+type CodexToolUserInputQuestion =
110
+ | EffectCodexSchema.ServerRequest__ToolRequestUserInputQuestion
111
+ | EffectCodexSchema.ToolRequestUserInputParams__ToolRequestUserInputQuestion;
112
100
-function asArray(value: unknown): unknown[] | undefined {
101
- return Array.isArray(value) ? value : undefined;
113
+const ApprovalDecisionPayload = Schema.Struct({
114
+ decision: ProviderApprovalDecision,
115
+});
116
+
117
+function readPayload<A>(
118
+ schema: Schema.Schema<A>,
119
+ payload: ProviderEvent["payload"],
120
+): A | undefined {
121
+ return Schema.is(schema)(payload) ? payload : undefined;
122
}
123
104
-function asNumber(value: unknown): number | undefined {
105
- return typeof value === "number" && Number.isFinite(value) ? value : undefined;
124
+function trimText(value: string | undefined | null): string | undefined {
125
+ const trimmed = value?.trim();
126
+ return trimmed && trimmed.length > 0 ? trimmed : undefined;
127
}
128
129
const FATAL_CODEX_STDERR_SNIPPETS = ["failed to connect to websocket"];
@@ -112,26 +133,20 @@ function isFatalCodexProcessStderrMessage(message: string): boolean {
133
return FATAL_CODEX_STDERR_SNIPPETS.some((snippet) => normalized.includes(snippet));
134
}
135
115
-function normalizeCodexTokenUsage(value: unknown): ThreadTokenUsageSnapshot | undefined {
116
- const usage = asObject(value);
117
- const totalUsage = asObject(usage?.total_token_usage ?? usage?.total);
118
- const lastUsage = asObject(usage?.last_token_usage ?? usage?.last);
119
-
120
- const totalProcessedTokens =
121
- asNumber(totalUsage?.total_tokens) ?? asNumber(totalUsage?.totalTokens);
122
- const usedTokens =
123
- asNumber(lastUsage?.total_tokens) ?? asNumber(lastUsage?.totalTokens) ?? totalProcessedTokens;
136
+function normalizeCodexTokenUsage(
137
+ usage: EffectCodexSchema.V2ThreadTokenUsageUpdatedNotification["tokenUsage"],
138
+): ThreadTokenUsageSnapshot | undefined {
139
+ const totalProcessedTokens = usage.total.totalTokens;
140
+ const usedTokens = usage.last.totalTokens;
141
if (usedTokens === undefined || usedTokens <= 0) {
142
return undefined;
143
}
144
128
- const maxTokens = asNumber(usage?.model_context_window) ?? asNumber(usage?.modelContextWindow);
129
- const inputTokens = asNumber(lastUsage?.input_tokens) ?? asNumber(lastUsage?.inputTokens);
130
- const cachedInputTokens =
131
- asNumber(lastUsage?.cached_input_tokens) ?? asNumber(lastUsage?.cachedInputTokens);
132
- const outputTokens = asNumber(lastUsage?.output_tokens) ?? asNumber(lastUsage?.outputTokens);
133
- const reasoningOutputTokens =
134
- asNumber(lastUsage?.reasoning_output_tokens) ?? asNumber(lastUsage?.reasoningOutputTokens);
145
+ const maxTokens = usage.modelContextWindow ?? undefined;
146
+ const inputTokens = usage.last.inputTokens;
147
+ const cachedInputTokens = usage.last.cachedInputTokens;
148
+ const outputTokens = usage.last.outputTokens;
149
+ const reasoningOutputTokens = usage.last.reasoningOutputTokens;
150
151
return {
152
usedTokens,
@@ -154,15 +169,9 @@ function normalizeCodexTokenUsage(value: unknown): ThreadTokenUsageSnapshot | un
169
};
170
}
171
157
-function toTurnId(value: string | undefined): TurnId | undefined {
158
- return value?.trim() ? TurnId.make(value) : undefined;
159
-}
160
-
161
-function toProviderItemId(value: string | undefined): ProviderItemId | undefined {
162
- return value?.trim() ? ProviderItemId.make(value) : undefined;
163
-}
164
-
165
-function toTurnStatus(value: unknown): "completed" | "failed" | "cancelled" | "interrupted" {
172
+function toTurnStatus(
173
+ value: EffectCodexSchema.V2TurnCompletedNotification["turn"]["status"] | "cancelled",
174
+): "completed" | "failed" | "cancelled" | "interrupted" {
175
switch (value) {
176
case "completed":
177
case "failed":
@@ -174,8 +183,8 @@ function toTurnStatus(value: unknown): "completed" | "failed" | "cancelled" | "i
183
}
184
}
185
177
-function normalizeItemType(raw: unknown): string {
178
- const type = asString(raw);
186
+function normalizeItemType(raw: string | undefined | null): string {
187
+ const type = trimText(raw);
188
if (!type) return "item";
189
return type
190
.replace(/([a-z0-9])([A-Z])/g, "$1 $2")
@@ -185,7 +194,7 @@ function normalizeItemType(raw: unknown): string {
194
.toLowerCase();
195
}
196
188
-function toCanonicalItemType(raw: unknown): CanonicalItemType {
197
+function toCanonicalItemType(raw: string | undefined | null): CanonicalItemType {
198
const type = normalizeItemType(raw);
199
if (type.includes("user")) return "user_message";
200
if (type.includes("agent message") || type.includes("assistant")) return "assistant_message";
@@ -235,27 +244,18 @@ function itemTitle(itemType: CanonicalItemType): string | undefined {
244
}
245
}
246
238
-function itemDetail(
239
- item: Record<string, unknown>,
240
- payload: Record<string, unknown>,
241
-): string | undefined {
242
- const nestedResult = asObject(item.result);
247
+function itemDetail(item: CodexLifecycleItem): string | undefined {
248
const candidates = [
244
- asString(item.command),
245
- asString(item.title),
246
- asString(item.summary),
247
- asString(item.text),
248
- asString(item.path),
249
- asString(item.prompt),
250
- asString(nestedResult?.command),
251
- asString(payload.command),
252
- asString(payload.message),
253
- asString(payload.prompt),
249
+ "command" in item ? item.command : undefined,
250
+ "title" in item ? item.title : undefined,
251
+ "summary" in item ? item.summary : undefined,
252
+ "text" in item ? item.text : undefined,
253
+ "path" in item ? item.path : undefined,
254
+ "prompt" in item ? item.prompt : undefined,
255
];
256
for (const candidate of candidates) {
256
- if (!candidate) continue;
257
- const trimmed = candidate.trim();
258
- if (trimmed.length === 0) continue;
257
+ const trimmed = typeof candidate === "string" ? trimText(candidate) : undefined;
258
+ if (!trimmed) continue;
259
return trimmed;
260
}
261
return undefined;
@@ -284,7 +284,7 @@ function toRequestTypeFromMethod(method: string): CanonicalRequestType {
284
}
285
}
286
287
-function toRequestTypeFromKind(kind: unknown): CanonicalRequestType {
287
+function toRequestTypeFromKind(kind: ProviderRequestKind | undefined): CanonicalRequestType {
288
switch (kind) {
289
case "command":
290
return "command_execution_approval";
@@ -297,77 +297,36 @@ function toRequestTypeFromKind(kind: unknown): CanonicalRequestType {
297
}
298
}
299
300
-function 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
-
300
function toCanonicalUserInputAnswers(
316
- answers: ProviderUserInputAnswers | undefined,
301
+ answers: EffectCodexSchema.ToolRequestUserInputResponse["answers"],
302
): ProviderUserInputAnswers {
318
- if (!answers) {
319
- return {};
320
- }
321
-
303
return Object.fromEntries(
323
- Object.entries(answers).flatMap(([questionId, value]) => {
324
- if (typeof value === "string") {
325
- return [[questionId, value] 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];
304
+ Object.entries(answers).map(([questionId, value]) => {
305
+ const normalizedAnswers = value.answers.length === 1 ? value.answers[0]! : [...value.answers];
306
+ return [questionId, normalizedAnswers] as const;
307
}),
308
);
309
}
310
345
-function toUserInputQuestions(payload: Record<string, unknown> | undefined) {
346
- const questions = asArray(payload?.questions);
347
- if (!questions) {
348
- return undefined;
349
- }
350
-
311
+function toUserInputQuestions(questions: ReadonlyArray<CodexToolUserInputQuestion>) {
312
const parsedQuestions = questions
352
- .map((entry) => {
353
- const question = asObject(entry);
354
- if (!question) return undefined;
355
- const options = asArray(question.options)
356
- ?.map((option) => {
357
- const optionRecord = asObject(option);
358
- if (!optionRecord) return undefined;
359
- const label = asString(optionRecord.label)?.trim();
360
- const description = asString(optionRecord.description)?.trim();
361
- if (!label || !description) {
362
- return undefined;
363
- }
364
- return { label, description };
365
- })
366
- .filter((option): option is { label: string; description: string } => option !== undefined);
367
- const id = asString(question.id)?.trim();
368
- const header = asString(question.header)?.trim();
369
- const prompt = asString(question.question)?.trim();
370
- if (!id || !header || !prompt || !options || options.length === 0) {
313
+ .map((question) => {
314
+ const options =
315
+ question.options
316
+ ?.map((option) => {
317
+ const label = trimText(option.label);
318
+ const description = trimText(option.description);
319
+ if (!label || !description) {
320
+ return undefined;
321
+ }
322
+ return { label, description };
323
+ })
324
+ .filter((option) => option !== undefined) ?? [];
325
+
326
+ const id = trimText(question.id);
327
+ const header = trimText(question.header);
328
+ const prompt = trimText(question.question);
329
+ if (!id || !header || !prompt || options.length === 0) {
330
return undefined;
331
}
332
return {
@@ -375,38 +334,21 @@ function toUserInputQuestions(payload: Record<string, unknown> | undefined) {
334
header,
335
question: prompt,
336
options,
378
- multiSelect: question.multiSelect === true,
337
+ multiSelect: false,
338
};
339
})
381
- .filter(
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
- );
340
+ .filter((question) => question !== undefined);
341
342
return parsedQuestions.length > 0 ? parsedQuestions : undefined;
343
}
344
345
function toThreadState(
397
- value: unknown,
346
+ status: EffectCodexSchema.V2ThreadStatusChangedNotification["status"],
347
): "active" | "idle" | "archived" | "closed" | "compacted" | "error" {
399
- switch (value) {
348
+ switch (status.type) {
349
case "idle":
350
return "idle";
402
- case "archived":
403
- return "archived";
404
- case "closed":
405
- return "closed";
406
- case "compacted":
407
- return "compacted";
408
- case "error":
409
- case "failed":
351
+ case "systemError":
352
return "error";
353
default:
354
return "active";
@@ -438,15 +380,7 @@ function contentStreamKindFromMethod(
380
}
381
}
382
441
-const PROPOSED_PLAN_BLOCK_REGEX = /<proposed_plan>\s*([\s\S]*?)\s*<\/proposed_plan>/i;
442
-
443
-function 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
-
449
-function asRuntimeItemId(itemId: ProviderItemId): RuntimeItemId {
383
+function asRuntimeItemId(itemId: ProviderEvent["itemId"] & string): RuntimeItemId {
384
return RuntimeItemId.make(itemId);
385
}
386
@@ -454,48 +388,6 @@ function asRuntimeRequestId(requestId: string): RuntimeRequestId {
388
return RuntimeRequestId.make(requestId);
389
}
390
457
-function asRuntimeTaskId(taskId: string): RuntimeTaskId {
458
- return RuntimeTaskId.make(taskId);
459
-}
460
-
461
-function codexEventMessage(
462
- payload: Record<string, unknown> | undefined,
463
-): Record<string, unknown> | undefined {
464
- return asObject(payload?.msg);
465
-}
466
-
467
-function 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
-
391
function eventRawSource(event: ProviderEvent): NonNullable<ProviderRuntimeEvent["raw"]>["source"] {
392
return event.kind === "request" ? "codex.app-server.request" : "codex.app-server.notification";
393
}
@@ -538,19 +430,19 @@ function mapItemLifecycle(
430
canonicalThreadId: ThreadId,
431
lifecycle: "item.started" | "item.updated" | "item.completed",
432
): ProviderRuntimeEvent | undefined {
541
- const payload = asObject(event.payload);
542
- const item = asObject(payload?.item);
543
- const source = item ?? payload;
544
- if (!source) {
433
+ const payload =
434
+ readPayload(EffectCodexSchema.V2ItemStartedNotification, event.payload) ??
435
+ readPayload(EffectCodexSchema.V2ItemCompletedNotification, event.payload);
436
+ const item = payload?.item;
437
+ if (!item) {
438
return undefined;
439
}
547
-
548
- const itemType = toCanonicalItemType(source.type ?? source.kind);
440
+ const itemType = toCanonicalItemType(item.type);
441
if (itemType === "unknown" && lifecycle !== "item.updated") {
442
return undefined;
443
}
444
553
- const detail = itemDetail(source, payload ?? {});
445
+ const detail = itemDetail(item);
446
const status =
447
lifecycle === "item.started"
448
? "inProgress"
@@ -575,9 +467,6 @@ function mapToRuntimeEvents(
467
event: ProviderEvent,
468
canonicalThreadId: ThreadId,
469
): ReadonlyArray<ProviderRuntimeEvent> {
578
- const payload = asObject(event.payload);
579
- const turn = asObject(payload?.turn);
580
-
470
if (event.kind === "error") {
471
if (!event.message) {
472
return [];
@@ -597,7 +486,10 @@ function mapToRuntimeEvents(
486
487
if (event.kind === "request") {
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;
493
if (!questions) {
494
return [];
495
}
@@ -612,8 +504,48 @@ function mapToRuntimeEvents(
504
];
505
}
506
615
- const detail =
616
- asString(payload?.command) ?? asString(payload?.reason) ?? asString(payload?.prompt);
507
+ const detail = (() => {
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
+
549
return [
550
{
551
...runtimeEventBase(event, canonicalThreadId),
@@ -628,7 +560,7 @@ function mapToRuntimeEvents(
560
}
561
562
if (event.method === "item/requestApproval/decision" && event.requestId) {
631
- const decision = Schema.decodeUnknownSync(ProviderApprovalDecision)(payload?.decision);
563
+ const payload = readPayload(ApprovalDecisionPayload, event.payload);
564
const requestType =
565
event.requestKind !== undefined
566
? toRequestTypeFromKind(event.requestKind)
@@ -639,7 +571,7 @@ function mapToRuntimeEvents(
571
type: "request.resolved",
572
payload: {
573
requestType,
642
- ...(decision ? { decision } : {}),
574
+ ...(payload ? { decision: payload.decision } : {}),
575
...(event.payload !== undefined ? { resolution: event.payload } : {}),
576
},
577
},
@@ -699,9 +631,8 @@ function mapToRuntimeEvents(
631
}
632
633
if (event.method === "thread/started") {
702
- const payloadThreadId = asString(asObject(payload?.thread)?.id);
703
- const providerThreadId = payloadThreadId ?? asString(payload?.threadId);
704
- if (!providerThreadId) {
634
+ const payload = readPayload(EffectCodexSchema.V2ThreadStartedNotification, event.payload);
635
+ if (!payload) {
636
return [];
637
}
638
return [
@@ -709,7 +640,7 @@ function mapToRuntimeEvents(
640
...runtimeEventBase(event, canonicalThreadId),
641
type: "thread.started",
642
payload: {
712
- providerThreadId,
643
+ providerThreadId: payload.thread.id,
644
},
645
},
646
];
@@ -722,6 +653,10 @@ function mapToRuntimeEvents(
653
event.method === "thread/closed" ||
654
event.method === "thread/compacted"
655
) {
656
+ const payload =
657
+ event.method === "thread/status/changed"
658
+ ? readPayload(EffectCodexSchema.V2ThreadStatusChangedNotification, event.payload)
659
+ : undefined;
660
return [
661
{
662
type: "thread.state.changed",
@@ -734,7 +669,9 @@ function mapToRuntimeEvents(
669
? "closed"
670
: event.method === "thread/compacted"
671
? "compacted"
737
- : toThreadState(asObject(payload?.thread)?.state ?? payload?.state),
672
+ : payload
673
+ ? toThreadState(payload.status)
674
+ : "active",
675
...(event.payload !== undefined ? { detail: event.payload } : {}),
676
},
677
},
@@ -742,21 +679,34 @@ function mapToRuntimeEvents(
679
}
680
681
if (event.method === "thread/name/updated") {
682
+ const payload = readPayload(EffectCodexSchema.V2ThreadNameUpdatedNotification, event.payload);
683
return [
684
{
685
type: "thread.metadata.updated",
686
...runtimeEventBase(event, canonicalThreadId),
687
payload: {
750
- ...(asString(payload?.threadName) ? { name: asString(payload?.threadName) } : {}),
751
- ...(event.payload !== undefined ? { metadata: asObject(event.payload) } : {}),
688
+ ...(trimText(payload?.threadName) ? { name: trimText(payload?.threadName) } : {}),
689
+ ...(payload
690
+ ? {
691
+ metadata: {
692
+ threadId: payload.threadId,
693
+ ...(payload.threadName !== undefined && payload.threadName !== null
694
+ ? { threadName: payload.threadName }
695
+ : {}),
696
+ },
697
+ }
698
+ : {}),
699
},
700
},
701
];
702
}
703
704
if (event.method === "thread/tokenUsage/updated") {
758
- const tokenUsage = asObject(payload?.tokenUsage);
759
- const normalizedUsage = normalizeCodexTokenUsage(tokenUsage ?? event.payload);
705
+ const payload = readPayload(
706
+ EffectCodexSchema.V2ThreadTokenUsageUpdatedNotification,
707
+ event.payload,
708
+ );
709
+ const normalizedUsage = payload ? normalizeCodexTokenUsage(payload.tokenUsage) : undefined;
710
if (!normalizedUsage) {
711
return [];
712
}
@@ -781,28 +731,23 @@ function mapToRuntimeEvents(
731
...runtimeEventBase(event, canonicalThreadId),
732
turnId,
733
type: "turn.started",
784
- payload: {
785
- ...(asString(turn?.model) ? { model: asString(turn?.model) } : {}),
786
- ...(asString(turn?.effort) ? { effort: asString(turn?.effort) } : {}),
787
- },
734
+ payload: {},
735
},
736
];
737
}
738
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);
745
return [
746
{
747
...runtimeEventBase(event, canonicalThreadId),
748
type: "turn.completed",
749
payload: {
799
- state: toTurnStatus(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
- : {}),
750
+ state: toTurnStatus(payload.turn.status),
751
...(errorMessage ? { errorMessage } : {}),
752
},
753
},
@@ -822,41 +767,37 @@ function mapToRuntimeEvents(
767
}
768
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
+ }
774
return [
775
{
776
...runtimeEventBase(event, canonicalThreadId),
777
type: "turn.plan.updated",
778
payload: {
831
- ...(asString(payload?.explanation)
832
- ? { explanation: asString(payload?.explanation) }
833
- : {}),
834
- plan: steps
835
- .map((entry) => asObject(entry))
836
- .filter((entry): entry is Record<string, unknown> => entry !== undefined)
837
- .map((entry) => ({
838
- step: asString(entry.step) ?? "step",
839
- status:
840
- entry.status === "completed" || entry.status === "inProgress"
841
- ? entry.status
842
- : "pending",
843
- })),
779
+ ...(trimText(payload.explanation) ? { explanation: trimText(payload.explanation) } : {}),
780
+ plan: payload.plan.map((step) => ({
781
+ step: trimText(step.step) ?? "step",
782
+ status:
783
+ step.status === "completed" || step.status === "inProgress" ? step.status : "pending",
784
+ })),
785
},
786
},
787
];
788
}
789
790
if (event.method === "turn/diff/updated") {
791
+ const payload = readPayload(EffectCodexSchema.V2TurnDiffUpdatedNotification, event.payload);
792
+ if (!payload) {
793
+ return [];
794
+ }
795
return [
796
{
797
...runtimeEventBase(event, canonicalThreadId),
798
type: "turn.diff.updated",
799
payload: {
855
- unifiedDiff:
856
- asString(payload?.unifiedDiff) ??
857
- asString(payload?.diff) ??
858
- asString(payload?.patch) ??
859
- "",
800
+ unifiedDiff: payload.diff,
801
},
802
},
803
];
@@ -868,15 +809,14 @@ function mapToRuntimeEvents(
809
}
810
811
if (event.method === "item/completed") {
871
- const payload = asObject(event.payload);
872
- const item = asObject(payload?.item);
873
- const source = item ?? payload;
874
- if (!source) {
812
+ const payload = readPayload(EffectCodexSchema.V2ItemCompletedNotification, event.payload);
813
+ const item = payload?.item;
814
+ if (!item) {
815
return [];
816
}
877
- const itemType = source ? toCanonicalItemType(source.type ?? source.kind) : "unknown";
817
+ const itemType = toCanonicalItemType(item.type);
818
if (itemType === "plan") {
879
- const detail = itemDetail(source, payload ?? {});
819
+ const detail = itemDetail(item);
820
if (!detail) {
821
return [];
822
}
@@ -898,16 +838,22 @@ function mapToRuntimeEvents(
838
event.method === "item/reasoning/summaryPartAdded" ||
839
event.method === "item/commandExecution/terminalInteraction"
840
) {
901
- const updated = mapItemLifecycle(event, canonicalThreadId, "item.updated");
902
- return updated ? [updated] : [];
841
+ return [
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
+ ];
852
}
853
854
if (event.method === "item/plan/delta") {
906
- const delta =
907
- event.textDelta ??
908
- asString(payload?.delta) ??
909
- asString(payload?.text) ??
910
- asString(asObject(payload?.content)?.text);
855
+ const payload = readPayload(EffectCodexSchema.V2PlanDeltaNotification, event.payload);
856
+ const delta = event.textDelta ?? payload?.delta;
857
if (!delta || delta.length === 0) {
858
return [];
859
}
@@ -922,18 +868,9 @@ function mapToRuntimeEvents(
868
];
869
}
870
925
- if (
926
- event.method === "item/agentMessage/delta" ||
927
- event.method === "item/commandExecution/outputDelta" ||
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);
871
+ if (event.method === "item/agentMessage/delta") {
872
+ const payload = readPayload(EffectCodexSchema.V2AgentMessageDeltaNotification, event.payload);
873
+ const delta = event.textDelta ?? payload?.delta;
874
if (!delta || delta.length === 0) {
875
return [];
876
}
@@ -944,216 +881,207 @@ function mapToRuntimeEvents(
881
payload: {
882
streamKind: contentStreamKindFromMethod(event.method),
883
delta,
947
- ...(typeof payload?.contentIndex === "number"
948
- ? { contentIndex: payload.contentIndex }
949
- : {}),
950
- ...(typeof payload?.summaryIndex === "number"
951
- ? { summaryIndex: payload.summaryIndex }
952
- : {}),
884
},
885
},
886
];
887
}
888
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
+ }
898
return [
899
{
900
...runtimeEventBase(event, canonicalThreadId),
962
- type: "tool.progress",
901
+ type: "content.delta",
902
payload: {
964
- ...(asString(payload?.toolUseId) ? { toolUseId: asString(payload?.toolUseId) } : {}),
965
- ...(asString(payload?.toolName) ? { toolName: asString(payload?.toolName) } : {}),
966
- ...(asString(payload?.summary) ? { summary: asString(payload?.summary) } : {}),
967
- ...(asNumber(payload?.elapsedSeconds) !== undefined
968
- ? { elapsedSeconds: asNumber(payload?.elapsedSeconds) }
969
- : {}),
903
+ streamKind: "command_output",
904
+ delta,
905
},
906
},
907
];
908
}
909
975
- if (event.method === "serverRequest/resolved") {
976
- const requestType =
977
- toRequestTypeFromResolvedPayload(payload) !== "unknown"
978
- ? toRequestTypeFromResolvedPayload(payload)
979
- : event.requestId && event.requestKind !== undefined
980
- ? toRequestTypeFromKind(event.requestKind)
981
- : "unknown";
910
+ if (event.method === "item/fileChange/outputDelta") {
911
+ const payload = readPayload(
912
+ EffectCodexSchema.V2FileChangeOutputDeltaNotification,
913
+ event.payload,
914
+ );
915
+ const delta = event.textDelta ?? payload?.delta;
916
+ if (!delta || delta.length === 0) {
917
+ return [];
918
+ }
919
return [
920
{
921
...runtimeEventBase(event, canonicalThreadId),
985
- type: "request.resolved",
922
+ type: "content.delta",
923
payload: {
987
- requestType,
988
- ...(event.payload !== undefined ? { resolution: event.payload } : {}),
924
+ streamKind: "file_change_output",
925
+ delta,
926
},
927
},
928
];
929
}
930
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
+ }
940
return [
941
{
942
...runtimeEventBase(event, canonicalThreadId),
998
- type: "user-input.resolved",
943
+ type: "content.delta",
944
payload: {
1000
- answers: toCanonicalUserInputAnswers(
1001
- asObject(event.payload)?.answers as ProviderUserInputAnswers | undefined,
1002
- ),
945
+ streamKind: "reasoning_summary_text",
946
+ delta,
947
+ ...(payload ? { summaryIndex: payload.summaryIndex } : {}),
948
},
949
},
950
];
951
}
952
1008
- if (event.method === "codex/event/task_started") {
1009
- const msg = codexEventMessage(payload);
1010
- const taskId = asString(payload?.id) ?? asString(msg?.turn_id);
1011
- if (!taskId) {
953
+ if (event.method === "item/reasoning/textDelta") {
954
+ const payload = readPayload(EffectCodexSchema.V2ReasoningTextDeltaNotification, event.payload);
955
+ const delta = event.textDelta ?? payload?.delta;
956
+ if (!delta || delta.length === 0) {
957
return [];
958
}
959
return [
960
{
1016
- ...codexEventBase(event, canonicalThreadId),
1017
- type: "task.started",
961
+ ...runtimeEventBase(event, canonicalThreadId),
962
+ type: "content.delta",
963
payload: {
1019
- taskId: asRuntimeTaskId(taskId),
1020
- ...(asString(msg?.collaboration_mode_kind)
1021
- ? { taskType: asString(msg?.collaboration_mode_kind) }
1022
- : {}),
964
+ streamKind: "reasoning_text",
965
+ delta,
966
+ ...(payload ? { contentIndex: payload.contentIndex } : {}),
967
},
968
},
969
];
970
}
971
1028
- if (event.method === "codex/event/task_complete") {
1029
- const msg = codexEventMessage(payload);
1030
- const taskId = asString(payload?.id) ?? asString(msg?.turn_id);
1031
- const proposedPlanMarkdown = extractProposedPlanMarkdown(asString(msg?.last_agent_message));
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
- ];
972
+ if (event.method === "item/mcpToolCall/progress") {
973
+ const payload = readPayload(EffectCodexSchema.V2McpToolCallProgressNotification, event.payload);
974
+ if (!payload) {
975
+ return [];
976
}
1046
- const events: ProviderRuntimeEvent[] = [
977
+ return [
978
{
1048
- ...codexEventBase(event, canonicalThreadId),
1049
- type: "task.completed",
979
+ ...runtimeEventBase(event, canonicalThreadId),
980
+ type: "tool.progress",
981
payload: {
1051
- taskId: asRuntimeTaskId(taskId),
1052
- status: "completed",
1053
- ...(asString(msg?.last_agent_message)
1054
- ? { summary: asString(msg?.last_agent_message) }
1055
- : {}),
982
+ summary: payload.message,
983
},
984
},
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;
986
}
987
1071
- if (event.method === "codex/event/agent_reasoning") {
1072
- const msg = codexEventMessage(payload);
1073
- const taskId = asString(payload?.id);
1074
- const description = asString(msg?.text);
1075
- if (!taskId || !description) {
988
+ if (event.method === "serverRequest/resolved") {
989
+ const payload = readPayload(
990
+ EffectCodexSchema.V2ServerRequestResolvedNotification,
991
+ event.payload,
992
+ );
993
+ if (!payload) {
994
return [];
995
}
996
+ const requestType = toRequestTypeFromKind(event.requestKind);
997
return [
998
{
1080
- ...codexEventBase(event, canonicalThreadId),
1081
- type: "task.progress",
999
+ ...runtimeEventBase(event, canonicalThreadId),
1000
+ type: "request.resolved",
1001
payload: {
1083
- taskId: asRuntimeTaskId(taskId),
1084
- description,
1002
+ requestType,
1003
+ ...(event.payload !== undefined ? { resolution: event.payload } : {}),
1004
},
1005
},
1006
];
1007
}
1008
1090
- if (event.method === "codex/event/reasoning_content_delta") {
1091
- const msg = codexEventMessage(payload);
1092
- const delta = asString(msg?.delta);
1093
- if (!delta) {
1009
+ if (event.method === "item/tool/requestUserInput/answered") {
1010
+ const payload = readPayload(EffectCodexSchema.ToolRequestUserInputResponse, event.payload);
1011
+ if (!payload) {
1012
return [];
1013
}
1014
return [
1015
{
1098
- ...codexEventBase(event, canonicalThreadId),
1099
- type: "content.delta",
1016
+ ...runtimeEventBase(event, canonicalThreadId),
1017
+ type: "user-input.resolved",
1018
payload: {
1101
- streamKind:
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
- : {}),
1019
+ answers: toCanonicalUserInputAnswers(payload.answers),
1020
},
1021
},
1022
];
1023
}
1024
1025
if (event.method === "model/rerouted") {
1026
+ const payload = readPayload(EffectCodexSchema.V2ModelReroutedNotification, event.payload);
1027
+ if (!payload) {
1028
+ return [];
1029
+ }
1030
return [
1031
{
1032
type: "model.rerouted",
1033
...runtimeEventBase(event, canonicalThreadId),
1034
payload: {
1120
- fromModel: asString(payload?.fromModel) ?? "unknown",
1121
- toModel: asString(payload?.toModel) ?? "unknown",
1122
- reason: asString(payload?.reason) ?? "unknown",
1035
+ fromModel: payload.fromModel,
1036
+ toModel: payload.toModel,
1037
+ reason: payload.reason,
1038
},
1039
},
1040
];
1041
}
1042
1043
if (event.method === "deprecationNotice") {
1044
+ const payload = readPayload(EffectCodexSchema.V2DeprecationNoticeNotification, event.payload);
1045
+ if (!payload) {
1046
+ return [];
1047
+ }
1048
return [
1049
{
1050
type: "deprecation.notice",
1051
...runtimeEventBase(event, canonicalThreadId),
1052
payload: {
1134
- summary: asString(payload?.summary) ?? "Deprecation notice",
1135
- ...(asString(payload?.details) ? { details: asString(payload?.details) } : {}),
1053
+ summary: payload.summary,
1054
+ ...(trimText(payload.details) ? { details: trimText(payload.details) } : {}),
1055
},
1056
},
1057
];
1058
}
1059
1060
if (event.method === "configWarning") {
1061
+ const payload = readPayload(EffectCodexSchema.V2ConfigWarningNotification, event.payload);
1062
+ if (!payload) {
1063
+ return [];
1064
+ }
1065
return [
1066
{
1067
type: "config.warning",
1068
...runtimeEventBase(event, canonicalThreadId),
1069
payload: {
1147
- summary: asString(payload?.summary) ?? "Configuration warning",
1148
- ...(asString(payload?.details) ? { details: asString(payload?.details) } : {}),
1149
- ...(asString(payload?.path) ? { path: asString(payload?.path) } : {}),
1150
- ...(payload?.range !== undefined ? { range: payload.range } : {}),
1070
+ summary: payload.summary,
1071
+ ...(trimText(payload.details) ? { details: trimText(payload.details) } : {}),
1072
+ ...(trimText(payload.path) ? { path: trimText(payload.path) } : {}),
1073
+ ...(payload.range !== undefined && payload.range !== null
1074
+ ? { range: payload.range }
1075
+ : {}),
1076
},
1077
},
1078
];
1079
}
1080
1081
if (event.method === "account/updated") {
1082
+ if (!readPayload(EffectCodexSchema.V2AccountUpdatedNotification, event.payload)) {
1083
+ return [];
1084
+ }
1085
return [
1086
{
1087
type: "account.updated",
@@ -1166,6 +1094,9 @@ function mapToRuntimeEvents(
1094
}
1095
1096
if (event.method === "account/rateLimits/updated") {
1097
+ if (!readPayload(EffectCodexSchema.V2AccountRateLimitsUpdatedNotification, event.payload)) {
1098
+ return [];
1099
+ }
1100
return [
1101
{
1102
type: "account.rate-limits.updated",
@@ -1178,58 +1109,86 @@ function mapToRuntimeEvents(
1109
}
1110
1111
if (event.method === "mcpServer/oauthLogin/completed") {
1112
+ const payload = readPayload(
1113
+ EffectCodexSchema.V2McpServerOauthLoginCompletedNotification,
1114
+ event.payload,
1115
+ );
1116
+ if (!payload) {
1117
+ return [];
1118
+ }
1119
return [
1120
{
1121
type: "mcp.oauth.completed",
1122
...runtimeEventBase(event, canonicalThreadId),
1123
payload: {
1186
- success: payload?.success === true,
1187
- ...(asString(payload?.name) ? { name: asString(payload?.name) } : {}),
1188
- ...(asString(payload?.error) ? { error: asString(payload?.error) } : {}),
1124
+ success: payload.success,
1125
+ name: payload.name,
1126
+ ...(trimText(payload.error) ? { error: trimText(payload.error) } : {}),
1127
},
1128
},
1129
];
1130
}
1131
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
+ }
1140
return [
1141
{
1142
type: "thread.realtime.started",
1143
...runtimeEventBase(event, canonicalThreadId),
1144
payload: {
1201
- realtimeSessionId,
1145
+ realtimeSessionId: payload.sessionId ?? undefined,
1146
},
1147
},
1148
];
1149
}
1150
1151
if (event.method === "thread/realtime/itemAdded") {
1152
+ const payload = readPayload(
1153
+ EffectCodexSchema.V2ThreadRealtimeItemAddedNotification,
1154
+ event.payload,
1155
+ );
1156
+ if (!payload) {
1157
+ return [];
1158
+ }
1159
return [
1160
{
1161
type: "thread.realtime.item-added",
1162
...runtimeEventBase(event, canonicalThreadId),
1163
payload: {
1213
- item: event.payload ?? {},
1164
+ item: payload.item,
1165
},
1166
},
1167
];
1168
}
1169
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
+ }
1178
return [
1179
{
1180
type: "thread.realtime.audio.delta",
1181
...runtimeEventBase(event, canonicalThreadId),
1182
payload: {
1225
- audio: event.payload ?? {},
1183
+ audio: payload.audio,
1184
},
1185
},
1186
];
1187
}
1188
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";
1192
return [
1193
{
1194
type: "thread.realtime.error",
@@ -1242,20 +1201,24 @@ function mapToRuntimeEvents(
1201
}
1202
1203
if (event.method === "thread/realtime/closed") {
1204
+ const payload = readPayload(
1205
+ EffectCodexSchema.V2ThreadRealtimeClosedNotification,
1206
+ event.payload,
1207
+ );
1208
return [
1209
{
1210
type: "thread.realtime.closed",
1211
...runtimeEventBase(event, canonicalThreadId),
1212
payload: {
1250
- reason: event.message,
1213
+ reason: payload?.reason ?? event.message,
1214
},
1215
},
1216
];
1217
}
1218
1219
if (event.method === "error") {
1257
- const message =
1258
- asString(asObject(payload?.error)?.message) ?? event.message ?? "Provider runtime error";
1220
+ const payload = readPayload(EffectCodexSchema.V2ErrorNotification, event.payload);
1221
+ const message = payload?.error.message ?? event.message ?? "Provider runtime error";
1222
const willRetry = payload?.willRetry === true;
1223
return [
1224
{
@@ -1296,6 +1259,9 @@ function mapToRuntimeEvents(
1259
}
1260
1261
if (event.method === "windows/worldWritableWarning") {
1262
+ if (!readPayload(EffectCodexSchema.V2WindowsWorldWritableWarningNotification, event.payload)) {
1263
+ return [];
1264
+ }
1265
return [
1266
{
1267
type: "runtime.warning",
@@ -1309,8 +1275,13 @@ function mapToRuntimeEvents(
1275
}
1276
1277
if (event.method === "windowsSandbox/setupCompleted") {
1312
- const payloadRecord = asObject(event.payload);
1313
- const success = payloadRecord?.success;
1278
+ const payload = readPayload(
1279
+ EffectCodexSchema.V2WindowsSandboxSetupCompletedNotification,
1280
+ event.payload,
1281
+ );
1282
+ if (!payload) {
1283
+ return [];
1284
+ }
1285
const successMessage = event.message ?? "Windows sandbox setup completed";
1286
const failureMessage = event.message ?? "Windows sandbox setup failed";
1287
@@ -1319,12 +1290,12 @@ function mapToRuntimeEvents(
1290
type: "session.state.changed",
1291
...runtimeEventBase(event, canonicalThreadId),
1292
payload: {
1322
- state: success === false ? "error" : "ready",
1323
- reason: success === false ? failureMessage : successMessage,
1293
+ state: payload.success === false ? "error" : "ready",
1294
+ reason: payload.success === false ? failureMessage : successMessage,
1295
...(event.payload !== undefined ? { detail: event.payload } : {}),
1296
},
1297
},
1327
- ...(success === false
1298
+ ...(payload.success === false
1299
? [
1300
{
1301
type: "runtime.warning" as const,
@@ -1346,6 +1317,7 @@ const makeCodexAdapter = Effect.fn("makeCodexAdapter")(function* (
1317
options?: CodexAdapterLiveOptions,
1318
) {
1319
const fileSystem = yield* FileSystem.FileSystem;
1320
+ const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
1321
const serverConfig = yield* Effect.service(ServerConfig);
1322
const nativeEventLogger =
1323
options?.nativeEventLogger ??
@@ -1354,78 +1326,124 @@ const makeCodexAdapter = Effect.fn("makeCodexAdapter")(function* (
1326
stream: "native",
1327
})
1328
: undefined);
1357
-
1358
- const acquireManager = Effect.fn("acquireManager")(function* () {
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
- );
1329
+ const managedNativeEventLogger =
1330
+ options?.nativeEventLogger === undefined ? nativeEventLogger : undefined;
1331
const serverSettingsService = yield* ServerSettingsService;
1332
+ const runtimeEventQueue = yield* Queue.unbounded<ProviderRuntimeEvent>();
1333
+ const sessions = new Map<ThreadId, CodexAdapterSessionContext>();
1334
1377
- const startSession: CodexAdapterShape["startSession"] = Effect.fn("startSession")(
1378
- function* (input) {
1379
- if (input.provider !== undefined && input.provider !== PROVIDER) {
1380
- return yield* new ProviderAdapterValidationError({
1381
- provider: PROVIDER,
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({
1335
+ const startSession: CodexAdapterShape["startSession"] = (input) =>
1336
+ Effect.scoped(
1337
+ Effect.gen(function* () {
1338
+ if (input.provider !== undefined && input.provider !== PROVIDER) {
1339
+ return yield* new ProviderAdapterValidationError({
1340
provider: PROVIDER,
1422
- threadId: input.threadId,
1423
- detail: `Failed to start Codex adapter session: ${cause instanceof Error ? cause.message : String(cause)}.`,
1424
- cause,
1341
+ operation: "startSession",
1342
+ issue: `Expected provider '${PROVIDER}' but received '${input.provider}'.`,
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);
1413
}),
1426
- });
1427
- },
1428
- );
1414
+ ).pipe(Effect.forkChild);
1415
+
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
+ );
1447
1448
const resolveAttachment = Effect.fn("resolveAttachment")(function* (
1449
input: ProviderSendTurnInput,
@@ -1436,11 +1454,11 @@ const makeCodexAdapter = Effect.fn("makeCodexAdapter")(function* (
1454
attachment,
1455
});
1456
if (!attachmentPath) {
1439
- return yield* toRequestError(
1440
- input.threadId,
1441
- "turn/start",
1442
- new Error(`Invalid attachment id '${attachment.id}'.`),
1443
- );
1457
+ return yield* new ProviderAdapterRequestError({
1458
+ provider: PROVIDER,
1459
+ method: "turn/start",
1460
+ detail: `Invalid attachment id '${attachment.id}'.`,
1461
+ });
1462
}
1463
const bytes = yield* fileSystem.readFile(attachmentPath).pipe(
1464
Effect.mapError(
@@ -1466,48 +1484,55 @@ const makeCodexAdapter = Effect.fn("makeCodexAdapter")(function* (
1484
{ concurrency: 1 },
1485
);
1486
1469
- return yield* Effect.tryPromise({
1470
- try: () => {
1471
- const managerInput = {
1472
- threadId: input.threadId,
1473
- ...(input.input !== undefined ? { input: input.input } : {}),
1474
- ...(input.modelSelection?.provider === "codex"
1475
- ? { model: input.modelSelection.model }
1476
- : {}),
1477
- ...(input.modelSelection?.provider === "codex" &&
1478
- input.modelSelection.options?.reasoningEffort !== undefined
1479
- ? { effort: input.modelSelection.options.reasoningEffort }
1480
- : {}),
1481
- ...(input.modelSelection?.provider === "codex" && input.modelSelection.options?.fastMode
1482
- ? { serviceTier: "fast" }
1483
- : {}),
1484
- ...(input.interactionMode !== undefined
1485
- ? { interactionMode: input.interactionMode }
1486
- : {}),
1487
- ...(codexAttachments.length > 0 ? { attachments: codexAttachments } : {}),
1488
- };
1489
- return manager.sendTurn(managerInput);
1490
- },
1491
- catch: (cause) => toRequestError(input.threadId, "turn/start", cause),
1492
- }).pipe(
1493
- Effect.map((result) => ({
1494
- ...result,
1495
- threadId: input.threadId,
1496
- })),
1497
- );
1487
+ const session = yield* requireSession(input.threadId);
1488
+ return yield* session.runtime
1489
+ .sendTurn({
1490
+ ...(input.input !== undefined ? { input: input.input } : {}),
1491
+ ...(input.modelSelection?.provider === "codex"
1492
+ ? { model: input.modelSelection.model }
1493
+ : {}),
1494
+ ...(input.modelSelection?.provider === "codex" &&
1495
+ input.modelSelection.options?.reasoningEffort !== undefined
1496
+ ? { effort: input.modelSelection.options.reasoningEffort }
1497
+ : {}),
1498
+ ...(input.modelSelection?.provider === "codex" && input.modelSelection.options?.fastMode
1499
+ ? { serviceTier: "fast" }
1500
+ : {}),
1501
+ ...(input.interactionMode !== undefined ? { interactionMode: input.interactionMode } : {}),
1502
+ ...(codexAttachments.length > 0 ? { attachments: codexAttachments } : {}),
1503
+ })
1504
+ .pipe(Effect.mapError((cause) => mapCodexRuntimeError(input.threadId, "turn/start", cause)));
1505
+ });
1506
+
1507
+ const requireSession = Effect.fn("requireSession")(function* (threadId: ThreadId) {
1508
+ const session = sessions.get(threadId);
1509
+ if (!session || session.stopped) {
1510
+ return yield* new ProviderAdapterSessionNotFoundError({
1511
+ provider: PROVIDER,
1512
+ threadId,
1513
+ });
1514
+ }
1515
+ return session;
1516
});
1517
1518
const interruptTurn: CodexAdapterShape["interruptTurn"] = (threadId, turnId) =>
1501
- Effect.tryPromise({
1502
- try: () => manager.interruptTurn(threadId, turnId),
1503
- catch: (cause) => toRequestError(threadId, "turn/interrupt", cause),
1504
- });
1519
+ requireSession(threadId).pipe(
1520
+ Effect.flatMap((session) => session.runtime.interruptTurn(turnId)),
1521
+ Effect.mapError((cause) =>
1522
+ cause._tag === "ProviderAdapterSessionNotFoundError"
1523
+ ? cause
1524
+ : mapCodexRuntimeError(threadId, "turn/interrupt", cause),
1525
+ ),
1526
+ );
1527
1528
const readThread: CodexAdapterShape["readThread"] = (threadId) =>
1507
- Effect.tryPromise({
1508
- try: () => manager.readThread(threadId),
1509
- catch: (cause) => toRequestError(threadId, "thread/read", cause),
1510
- }).pipe(
1529
+ requireSession(threadId).pipe(
1530
+ Effect.flatMap((session) => session.runtime.readThread),
1531
+ Effect.mapError((cause) =>
1532
+ cause._tag === "ProviderAdapterSessionNotFoundError"
1533
+ ? cause
1534
+ : mapCodexRuntimeError(threadId, "thread/read", cause),
1535
+ ),
1536
Effect.map((snapshot) => ({
1537
threadId,
1538
turns: snapshot.turns,
@@ -1525,10 +1550,13 @@ const makeCodexAdapter = Effect.fn("makeCodexAdapter")(function* (
1550
);
1551
}
1552
1528
- return Effect.tryPromise({
1529
- try: () => manager.rollbackThread(threadId, numTurns),
1530
- catch: (cause) => toRequestError(threadId, "thread/rollback", cause),
1531
- }).pipe(
1553
+ return requireSession(threadId).pipe(
1554
+ Effect.flatMap((session) => session.runtime.rollbackThread(numTurns)),
1555
+ Effect.mapError((cause) =>
1556
+ cause._tag === "ProviderAdapterSessionNotFoundError"
1557
+ ? cause
1558
+ : mapCodexRuntimeError(threadId, "thread/rollback", cause),
1559
+ ),
1560
Effect.map((snapshot) => ({
1561
threadId,
1562
turns: snapshot.turns,
@@ -1537,38 +1565,28 @@ const makeCodexAdapter = Effect.fn("makeCodexAdapter")(function* (
1565
};
1566
1567
const respondToRequest: CodexAdapterShape["respondToRequest"] = (threadId, requestId, decision) =>
1540
- Effect.tryPromise({
1541
- try: () => manager.respondToRequest(threadId, requestId, decision),
1542
- catch: (cause) => toRequestError(threadId, "item/requestApproval/decision", cause),
1543
- });
1568
+ requireSession(threadId).pipe(
1569
+ Effect.flatMap((session) => session.runtime.respondToRequest(requestId, decision)),
1570
+ Effect.mapError((cause) =>
1571
+ cause._tag === "ProviderAdapterSessionNotFoundError"
1572
+ ? cause
1573
+ : mapCodexRuntimeError(threadId, "item/requestApproval/decision", cause),
1574
+ ),
1575
+ );
1576
1577
const respondToUserInput: CodexAdapterShape["respondToUserInput"] = (
1578
threadId,
1579
requestId,
1580
answers,
1581
) =>
1550
- Effect.tryPromise({
1551
- try: () => manager.respondToUserInput(threadId, requestId, answers),
1552
- catch: (cause) => toRequestError(threadId, "item/tool/requestUserInput", cause),
1553
- });
1554
-
1555
- const stopSession: CodexAdapterShape["stopSession"] = (threadId) =>
1556
- Effect.sync(() => {
1557
- manager.stopSession(threadId);
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>();
1582
+ requireSession(threadId).pipe(
1583
+ Effect.flatMap((session) => session.runtime.respondToUserInput(requestId, answers)),
1584
+ Effect.mapError((cause) =>
1585
+ cause._tag === "ProviderAdapterSessionNotFoundError"
1586
+ ? cause
1587
+ : mapCodexRuntimeError(threadId, "item/tool/requestUserInput", cause),
1588
+ ),
1589
+ );
1590
1591
const writeNativeEvent = Effect.fn("writeNativeEvent")(function* (event: ProviderEvent) {
1592
if (!nativeEventLogger) {
@@ -1577,38 +1595,51 @@ const makeCodexAdapter = Effect.fn("makeCodexAdapter")(function* (
1595
yield* nativeEventLogger.write(event, event.threadId);
1596
});
1597
1580
- const registerListener = Effect.fn("registerListener")(function* () {
1581
- const services = yield* Effect.context<never>();
1582
- const listenerEffect = Effect.fn("listener")(function* (event: ProviderEvent) {
1583
- yield* writeNativeEvent(event);
1584
- const runtimeEvents = mapToRuntimeEvents(event, event.threadId);
1585
- if (runtimeEvents.length === 0) {
1586
- yield* Effect.logDebug("ignoring unhandled Codex provider event", {
1587
- method: event.method,
1588
- threadId: event.threadId,
1589
- turnId: event.turnId,
1590
- itemId: event.itemId,
1591
- });
1598
+ const stopSessionInternal = Effect.fn("stopSessionInternal")(function* (
1599
+ session: CodexAdapterSessionContext,
1600
+ ) {
1601
+ if (session.stopped) {
1602
+ return;
1603
+ }
1604
+ session.stopped = true;
1605
+ sessions.delete(session.threadId);
1606
+ yield* session.runtime.close.pipe(Effect.ignore);
1607
+ yield* Effect.ignore(Scope.close(session.scope, Exit.void));
1608
+ yield* Fiber.interrupt(session.eventFiber).pipe(Effect.ignore);
1609
+ });
1610
+
1611
+ const stopSession: CodexAdapterShape["stopSession"] = (threadId) =>
1612
+ Effect.gen(function* () {
1613
+ const session = sessions.get(threadId);
1614
+ if (!session) {
1615
return;
1616
}
1594
- yield* Queue.offerAll(runtimeEventQueue, runtimeEvents);
1617
+ yield* stopSessionInternal(session);
1618
});
1596
- const listener = (event: ProviderEvent) =>
1597
- listenerEffect(event).pipe(Effect.runPromiseWith(services));
1598
- manager.on("event", listener);
1599
- return listener;
1600
- });
1619
1602
- const unregisterListener = Effect.fn("unregisterListener")(function* (
1603
- listener: (event: ProviderEvent) => Promise<void>,
1604
- ) {
1605
- yield* Effect.sync(() => {
1606
- manager.off("event", listener);
1607
- });
1608
- yield* Queue.shutdown(runtimeEventQueue);
1609
- });
1620
+ const listSessions: CodexAdapterShape["listSessions"] = () =>
1621
+ Effect.forEach(
1622
+ Array.from(sessions.values()).filter((session) => !session.stopped),
1623
+ (session) => session.runtime.getSession,
1624
+ { concurrency: 1 },
1625
+ );
1626
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
+ );
1643
1644
return {
1645
provider: PROVIDER,
apps/server/src/provider/Layers/CodexProvider.ts
+344
-517
@@ -1,366 +1,290 @@
1
-import * as OS from "node:os";
2
-import type {
3
- ModelCapabilities,
4
- CodexSettings,
5
- ServerProvider,
6
- ServerProviderModel,
7
- ServerProviderAuth,
8
- ServerProviderSkill,
9
- ServerProviderState,
10
-} from "@t3tools/contracts";
1
import {
12
- Cache,
2
+ DateTime,
3
Duration,
4
Effect,
5
Equal,
16
- FileSystem,
6
Layer,
7
Option,
19
- Path,
8
Result,
9
+ Schema,
10
Stream,
11
+ Types,
12
} from "effect";
23
-import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
13
+import { ChildProcessSpawner } from "effect/unstable/process";
14
+import * as CodexClient from "effect-codex-app-server/client";
15
+import * as CodexSchema from "effect-codex-app-server/schema";
16
+import * as CodexErrors from "effect-codex-app-server/errors";
17
+
18
+import type {
19
+ CodexSettings,
20
+ ServerProvider,
21
+ ServerProviderState,
22
+ ModelCapabilities,
23
+ ServerProviderModel,
24
+ ServerProviderSkill,
25
+} from "@t3tools/contracts";
26
+import { ServerSettingsError } from "@t3tools/contracts";
27
25
-import {
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";
28
import { makeManagedServerProvider } from "../makeManagedServerProvider.ts";
37
-import {
38
- formatCodexCliUpgradeMessage,
39
- isCodexCliVersionSupported,
40
- parseCodexCliVersion,
41
-} from "../codexCliVersion.ts";
42
-import {
43
- adjustCodexModelsForAccount,
44
- codexAuthSubLabel,
45
- codexAuthSubType,
46
- type CodexAccountSnapshot,
47
-} from "../codexAccount.ts";
48
-import { probeCodexDiscovery } from "../codexAppServer.ts";
29
+import { buildServerProvider } from "../providerSnapshot.ts";
30
import { CodexProvider } from "../Services/CodexProvider.ts";
50
-import { expandHomePath } from "../../pathExpansion.ts";
31
import { ServerSettingsService } from "../../serverSettings.ts";
52
-import { ServerSettingsError } from "@t3tools/contracts";
32
+import packageJson from "../../../package.json" with { type: "json" };
33
54
-const DEFAULT_CODEX_MODEL_CAPABILITIES: ModelCapabilities = {
55
- reasoningEffortLevels: [
56
- { value: "xhigh", label: "Extra High" },
57
- { value: "high", label: "High", isDefault: true },
58
- { value: "medium", label: "Medium" },
59
- { value: "low", label: "Low" },
60
- ],
61
- supportsFastMode: true,
62
- supportsThinkingToggle: false,
63
- contextWindowOptions: [],
64
- promptInjectedEffortLevels: [],
34
+const PROVIDER = "codex" as const;
35
+const PROVIDER_PROBE_TIMEOUT_MS = 8_000;
36
+
37
+export interface CodexAppServerProviderSnapshot {
38
+ readonly account: CodexSchema.V2GetAccountResponse;
39
+ readonly version: string | undefined;
40
+ readonly models: ReadonlyArray<ServerProviderModel>;
41
+ readonly skills: ReadonlyArray<ServerProviderSkill>;
42
+}
43
+
44
+const 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",
51
};
52
67
-const PROVIDER = "codex" as const;
68
-const OPENAI_AUTH_PROVIDERS = new Set(["openai"]);
69
-const BUILT_IN_MODELS: ReadonlyArray<ServerProviderModel> = [
70
- {
71
- slug: "gpt-5.4",
72
- name: "GPT-5.4",
73
- isCustom: false,
74
- capabilities: {
75
- reasoningEffortLevels: [
76
- { value: "xhigh", label: "Extra High" },
77
- { value: "high", label: "High", isDefault: true },
78
- { value: "medium", label: "Medium" },
79
- { value: "low", label: "Low" },
80
- ],
81
- supportsFastMode: true,
82
- supportsThinkingToggle: false,
83
- contextWindowOptions: [],
84
- promptInjectedEffortLevels: [],
85
- },
86
- },
87
- {
88
- slug: "gpt-5.4-mini",
89
- name: "GPT-5.4 Mini",
90
- isCustom: false,
91
- capabilities: {
92
- reasoningEffortLevels: [
93
- { value: "xhigh", label: "Extra High" },
94
- { value: "high", label: "High", isDefault: true },
95
- { value: "medium", label: "Medium" },
96
- { value: "low", label: "Low" },
97
- ],
98
- supportsFastMode: true,
99
- supportsThinkingToggle: false,
100
- contextWindowOptions: [],
101
- promptInjectedEffortLevels: [],
102
- },
103
- },
104
- {
105
- slug: "gpt-5.3-codex",
106
- name: "GPT-5.3 Codex",
107
- isCustom: false,
108
- capabilities: {
109
- reasoningEffortLevels: [
110
- { value: "xhigh", label: "Extra High" },
111
- { value: "high", label: "High", isDefault: true },
112
- { value: "medium", label: "Medium" },
113
- { value: "low", label: "Low" },
114
- ],
115
- supportsFastMode: true,
116
- supportsThinkingToggle: false,
117
- contextWindowOptions: [],
118
- promptInjectedEffortLevels: [],
119
- },
120
- },
121
- {
122
- slug: "gpt-5.3-codex-spark",
123
- name: "GPT-5.3 Codex Spark",
124
- isCustom: false,
125
- capabilities: {
126
- reasoningEffortLevels: [
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",
53
+function codexAccountAuthLabel(account: CodexSchema.V2GetAccountResponse["account"]) {
54
+ if (!account) return undefined;
55
+ if (account.type === "apiKey") return "OpenAI API Key";
56
+
57
+ switch (account.planType) {
58
+ case "free":
59
+ return "ChatGPT Free Subscription";
60
+ case "go":
61
+ return "ChatGPT Go Subscription";
62
+ case "plus":
63
+ return "ChatGPT Plus Subscription";
64
+ case "pro":
65
+ return "ChatGPT Pro Subscription";
66
+ case "team":
67
+ return "ChatGPT Team Subscription";
68
+ case "self_serve_business_usage_based":
69
+ case "business":
70
+ return "ChatGPT Business Subscription";
71
+ case "enterprise_cbp_usage_based":
72
+ case "enterprise":
73
+ return "ChatGPT Enterprise Subscription";
74
+ case "edu":
75
+ return "ChatGPT Edu Subscription";
76
+ case "unknown":
77
+ return "ChatGPT Subscription";
78
+ default:
79
+ account.planType satisfies never;
80
+ return undefined;
81
+ }
82
+}
83
+
84
+function mapCodexModelCapabilities(
85
+ model: CodexSchema.V2ModelListResponse__Model,
86
+): ModelCapabilities {
87
+ return {
88
+ reasoningEffortLevels: model.supportedReasoningEfforts.map(({ reasoningEffort }) => ({
89
+ value: reasoningEffort,
90
+ label: REASONING_EFFORT_LABELS[reasoningEffort],
91
+ ...(reasoningEffort === model.defaultReasoningEffort ? { isDefault: true } : {}),
92
+ })),
93
+ supportsFastMode: (model.additionalSpeedTiers ?? []).includes("fast"),
94
+ supportsThinkingToggle: false,
95
+ contextWindowOptions: [],
96
+ promptInjectedEffortLevels: [],
97
+ };
98
+}
99
+
100
+const toDisplayName = (model: CodexSchema.V2ModelListResponse__Model): string => {
101
+ // Capitalize 'gpt' to 'GPT-' and capitalize any letter following a dash
102
+ return model.displayName
103
+ .replace(/^gpt/i, "GPT") // Handle start with 'gpt' or 'GPT'
104
+ .replace(/-([a-z])/g, (_, c) => "-" + c.toUpperCase());
105
+};
106
+
107
+function parseCodexModelListResponse(
108
+ response: CodexSchema.V2ModelListResponse,
109
+): ReadonlyArray<ServerProviderModel> {
110
+ return response.data.map((model) => ({
111
+ slug: model.model,
112
+ name: toDisplayName(model),
113
isCustom: false,
159
- capabilities: {
160
- reasoningEffortLevels: [
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
-
174
-export 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
- );
114
+ capabilities: mapCodexModelCapabilities(model),
115
+ }));
116
}
117
182
-export function parseAuthStatusFromOutput(result: CommandResult): {
183
- readonly status: Exclude<ServerProviderState, "disabled">;
184
- readonly auth: Pick<ServerProviderAuth, "status">;
185
- readonly message?: string;
186
-} {
187
- const lowerOutput = `${result.stdout}\n${result.stderr}`.toLowerCase();
118
+function appendCustomCodexModels(
119
+ models: ReadonlyArray<ServerProviderModel>,
120
+ customModels: ReadonlyArray<string>,
121
+): ReadonlyArray<ServerProviderModel> {
122
+ if (customModels.length === 0) {
123
+ return models;
124
+ }
125
189
- if (
190
- lowerOutput.includes("unknown command") ||
191
- lowerOutput.includes("unrecognized command") ||
192
- lowerOutput.includes("unexpected argument")
193
- ) {
194
- return {
195
- status: "warning",
196
- auth: { status: "unknown" },
197
- message: "Codex CLI authentication status command is unavailable in this Codex version.",
198
- };
126
+ const seen = new Set(models.map((model) => model.slug));
127
+ const fallbackCapabilities = models.find((model) => model.capabilities)?.capabilities ?? null;
128
+ const customEntries: ServerProviderModel[] = [];
129
+ for (const rawModel of customModels) {
130
+ const slug = rawModel.trim();
131
+ if (!slug || seen.has(slug)) {
132
+ continue;
133
+ }
134
+ seen.add(slug);
135
+ customEntries.push({
136
+ slug,
137
+ name: slug,
138
+ isCustom: true,
139
+ capabilities: fallbackCapabilities,
140
+ });
141
}
142
+ return customEntries.length === 0 ? models : [...models, ...customEntries];
143
+}
144
201
- if (
202
- lowerOutput.includes("not logged in") ||
203
- lowerOutput.includes("login required") ||
204
- lowerOutput.includes("authentication required") ||
205
- lowerOutput.includes("run `codex login`") ||
206
- lowerOutput.includes("run codex login")
207
- ) {
208
- return {
209
- status: "error",
210
- auth: { status: "unauthenticated" },
211
- message: "Codex CLI is not authenticated. Run `codex login` and try again.",
145
+function parseCodexSkillsListResponse(
146
+ response: CodexSchema.V2SkillsListResponse,
147
+ cwd: string,
148
+): ReadonlyArray<ServerProviderSkill> {
149
+ const matchingEntry = response.data.find((entry) => entry.cwd === cwd);
150
+ const skills = matchingEntry
151
+ ? matchingEntry.skills
152
+ : response.data.flatMap((entry) => entry.skills);
153
+
154
+ return skills.map((skill) => {
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,
162
};
213
- }
163
215
- const parsedAuth = (() => {
216
- const trimmed = result.stdout.trim();
217
- if (!trimmed || (!trimmed.startsWith("{") && !trimmed.startsWith("["))) {
218
- return { attemptedJsonParse: false as const, auth: undefined as boolean | undefined };
164
+ if (skill.description) {
165
+ parsedSkill.description = skill.description;
166
}
220
- try {
221
- return {
222
- attemptedJsonParse: true as const,
223
- auth: extractAuthBoolean(JSON.parse(trimmed)),
224
- };
225
- } catch {
226
- return { attemptedJsonParse: false as const, auth: undefined as boolean | undefined };
167
+ if (skill.scope) {
168
+ parsedSkill.scope = skill.scope;
169
+ }
170
+ if (skill.interface?.displayName) {
171
+ parsedSkill.displayName = skill.interface.displayName;
172
+ }
173
+ if (shortDescription) {
174
+ parsedSkill.shortDescription = shortDescription;
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
- }
176
252
- const detail = detailFromResult(result);
253
- return {
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
- };
177
+ return parsedSkill;
178
+ });
179
}
180
262
-export const readCodexConfigModelProvider = Effect.fn("readCodexConfigModelProvider")(function* () {
263
- const fileSystem = yield* FileSystem.FileSystem;
264
- const path = yield* Path.Path;
265
- const settingsService = yield* ServerSettingsService;
266
- const codexHome = yield* settingsService.getSettings.pipe(
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");
181
+const requestAllCodexModels = Effect.fn("requestAllCodexModels")(function* (
182
+ client: CodexClient.CodexAppServerClientShape,
183
+) {
184
+ const models: ServerProviderModel[] = [];
185
+ let cursor: string | null | undefined = undefined;
186
276
- const content = yield* fileSystem
277
- .readFileString(configPath)
278
- .pipe(Effect.orElseSucceed(() => undefined));
279
- if (content === undefined) {
280
- return undefined;
281
- }
282
-
283
- let inTopLevel = true;
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;
187
+ do {
188
+ const response: CodexSchema.V2ModelListResponse = yield* client.request(
189
+ "model/list",
190
+ cursor ? { cursor } : {},
191
+ );
192
+ models.push(...parseCodexModelListResponse(response));
193
+ cursor = response.nextCursor;
194
+ } while (cursor);
195
293
- const match = trimmed.match(/^model_provider\s*=\s*["']([^"']+)["']/);
294
- if (match) return match[1];
295
- }
296
- return undefined;
196
+ return models;
197
});
198
299
-export const hasCustomModelProvider = readCodexConfigModelProvider().pipe(
300
- Effect.map((provider) => provider !== undefined && !OPENAI_AUTH_PROVIDERS.has(provider)),
301
- Effect.orElseSucceed(() => false),
302
-);
303
-
304
-const CAPABILITIES_PROBE_TIMEOUT_MS = 8_000;
199
+export function buildCodexInitializeParams(): CodexSchema.V1InitializeParams {
200
+ return {
201
+ clientInfo: {
202
+ name: "t3code_desktop",
203
+ title: "T3 Code Desktop",
204
+ version: packageJson.version,
205
+ },
206
+ capabilities: {
207
+ experimentalApi: true,
208
+ },
209
+ };
210
+}
211
306
-const probeCodexCapabilities = (input: {
212
+const probeCodexAppServerProvider = Effect.fn("probeCodexAppServerProvider")(function* (input: {
213
readonly binaryPath: string;
214
readonly homePath?: string;
215
readonly cwd: string;
310
-}) =>
311
- Effect.tryPromise((signal) => probeCodexDiscovery({ ...input, signal })).pipe(
312
- Effect.timeoutOption(CAPABILITIES_PROBE_TIMEOUT_MS),
313
- Effect.result,
314
- Effect.map((result) => {
315
- if (Result.isFailure(result)) return undefined;
316
- return Option.isSome(result.success) ? result.success.value : undefined;
216
+ readonly customModels?: ReadonlyArray<string>;
217
+}) {
218
+ const clientContext = yield* Layer.build(
219
+ CodexClient.layerCommand({
220
+ command: input.binaryPath,
221
+ args: ["app-server"],
222
+ cwd: input.cwd,
223
+ ...(input.homePath ? { env: { CODEX_HOME: input.homePath } } : {}),
224
}),
225
);
319
-
320
-const runCodexCommand = Effect.fn("runCodexCommand")(function* (args: ReadonlyArray<string>) {
321
- const settingsService = yield* ServerSettingsService;
322
- const codexSettings = yield* settingsService.getSettings.pipe(
323
- Effect.map((settings) => settings.providers.codex),
226
+ const client = yield* Effect.service(CodexClient.CodexAppServerClient).pipe(
227
+ Effect.provide(clientContext),
228
);
325
- const command = ChildProcess.make(codexSettings.binaryPath, [...args], {
326
- shell: process.platform === "win32",
327
- env: {
328
- ...process.env,
329
- ...(codexSettings.homePath ? { CODEX_HOME: expandHomePath(codexSettings.homePath) } : {}),
229
+
230
+ const initialize = yield* client.request("initialize", {
231
+ clientInfo: {
232
+ name: "t3code_desktop",
233
+ title: "T3 Code Desktop",
234
+ version: "0.1.0",
235
+ },
236
+ capabilities: {
237
+ experimentalApi: true,
238
},
239
});
332
- return yield* spawnAndCollect(codexSettings.binaryPath, command);
333
-});
240
+ yield* client.notify("initialized", undefined);
241
335
-export const checkCodexProviderStatus = Effect.fn("checkCodexProviderStatus")(function* (
336
- resolveAccount?: (input: {
337
- readonly binaryPath: string;
338
- readonly homePath?: string;
339
- }) => Effect.Effect<CodexAccountSnapshot | undefined>,
340
- resolveSkills?: (input: {
341
- readonly binaryPath: string;
342
- readonly homePath?: string;
343
- readonly cwd: string;
344
- }) => Effect.Effect<ReadonlyArray<ServerProviderSkill> | undefined>,
345
-): Effect.fn.Return<
346
- ServerProvider,
347
- ServerSettingsError,
348
- | ChildProcessSpawner.ChildProcessSpawner
349
- | FileSystem.FileSystem
350
- | Path.Path
351
- | ServerSettingsService
352
-> {
353
- const codexSettings = yield* Effect.service(ServerSettingsService).pipe(
354
- Effect.flatMap((service) => service.getSettings),
355
- Effect.map((settings) => settings.providers.codex),
242
+ // Extract the version string after the first '/' in userAgent, up to the next space or the end
243
+ const versionMatch = initialize.userAgent.match(/\/([^\s]+)/);
244
+ const version = versionMatch ? versionMatch[1] : undefined;
245
+
246
+ const accountResponse = yield* client.request("account/read", {});
247
+ if (!accountResponse.account && accountResponse.requiresOpenaiAuth) {
248
+ return {
249
+ account: accountResponse,
250
+ version,
251
+ models: appendCustomCodexModels([], input.customModels ?? []),
252
+ skills: [],
253
+ } satisfies CodexAppServerProviderSnapshot;
254
+ }
255
+
256
+ const [skillsResponse, models] = yield* Effect.all(
257
+ [
258
+ client.request("skills/list", {
259
+ cwds: [input.cwd],
260
+ }),
261
+ requestAllCodexModels(client),
262
+ ],
263
+ { concurrency: "unbounded" },
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
+
274
+const 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
+
285
+const makePendingCodexProvider = (codexSettings: CodexSettings): ServerProvider => {
286
const checkedAt = new Date().toISOString();
358
- const models = providerModelsFromSettings(
359
- BUILT_IN_MODELS,
360
- PROVIDER,
361
- codexSettings.customModels,
362
- DEFAULT_CODEX_MODEL_CAPABILITIES,
363
- );
287
+ const models = emptyCodexModelsFromSettings(codexSettings);
288
289
if (!codexSettings.enabled) {
290
return buildServerProvider({
@@ -368,6 +292,7 @@ export const checkCodexProviderStatus = Effect.fn("checkCodexProviderStatus")(fu
292
enabled: false,
293
checkedAt,
294
models,
295
+ skills: [],
296
probe: {
297
installed: false,
298
version: null,
@@ -378,259 +303,160 @@ export const checkCodexProviderStatus = Effect.fn("checkCodexProviderStatus")(fu
303
});
304
}
305
381
- const versionProbe = yield* runCodexCommand(["--version"]).pipe(
382
- Effect.timeoutOption(DEFAULT_TIMEOUT_MS),
383
- Effect.result,
384
- );
306
+ return buildServerProvider({
307
+ provider: PROVIDER,
308
+ enabled: true,
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
+};
321
386
- if (Result.isFailure(versionProbe)) {
387
- const error = versionProbe.failure;
388
- return buildServerProvider({
389
- provider: PROVIDER,
390
- enabled: codexSettings.enabled,
391
- checkedAt,
392
- models,
393
- probe: {
394
- installed: !isCommandMissingCause(error),
395
- version: null,
396
- status: "error",
397
- auth: { status: "unknown" },
398
- message: isCommandMissingCause(error)
399
- ? "Codex CLI (`codex`) is not installed or not on PATH."
400
- : `Failed to execute Codex CLI health check: ${error.message}.`,
401
- },
402
- });
322
+function accountProbeStatus(account: CodexAppServerProviderSnapshot["account"]): {
323
+ readonly status: Exclude<ServerProviderState, "disabled">;
324
+ readonly auth: ServerProvider["auth"];
325
+ readonly message?: string;
326
+} {
327
+ const authLabel = codexAccountAuthLabel(account.account);
328
+ const auth = {
329
+ status: account.account ? ("authenticated" as const) : ("unknown" as const),
330
+ ...(account.account?.type ? { type: account.account?.type } : {}),
331
+ ...(authLabel ? { label: authLabel } : {}),
332
+ } satisfies ServerProvider["auth"];
333
+
334
+ if (account.account) {
335
+ return { status: "ready", auth };
336
}
337
405
- if (Option.isNone(versionProbe.success)) {
406
- return buildServerProvider({
407
- provider: PROVIDER,
408
- enabled: codexSettings.enabled,
409
- checkedAt,
410
- models,
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
- });
338
+ if (account.requiresOpenaiAuth) {
339
+ return {
340
+ status: "error",
341
+ auth: { status: "unauthenticated" },
342
+ message: "Codex CLI is not authenticated. Run `codex login` and try again.",
343
+ };
344
}
345
421
- const version = versionProbe.success.value;
422
- const parsedVersion =
423
- parseCodexCliVersion(`${version.stdout}\n${version.stderr}`) ??
424
- parseGenericCliVersion(`${version.stdout}\n${version.stderr}`);
425
- if (version.code !== 0) {
426
- const detail = detailFromResult(version);
427
- return buildServerProvider({
428
- provider: PROVIDER,
429
- enabled: codexSettings.enabled,
430
- checkedAt,
431
- models,
432
- probe: {
433
- installed: true,
434
- version: parsedVersion,
435
- status: "error",
436
- auth: { status: "unknown" },
437
- message: detail
438
- ? `Codex CLI is installed but failed to run. ${detail}`
439
- : "Codex CLI is installed but failed to run.",
440
- },
441
- });
442
- }
346
+ return { status: "ready", auth };
347
+}
348
+
349
+export const checkCodexProviderStatus = Effect.fn("checkCodexProviderStatus")(function* (
350
+ probe: (input: {
351
+ readonly binaryPath: string;
352
+ readonly homePath?: string;
353
+ readonly cwd: string;
354
+ readonly customModels: ReadonlyArray<string>;
355
+ }) => Effect.Effect<
356
+ CodexAppServerProviderSnapshot,
357
+ CodexErrors.CodexAppServerError,
358
+ ChildProcessSpawner.ChildProcessSpawner
359
+ > = probeCodexAppServerProvider,
360
+): Effect.fn.Return<
361
+ ServerProvider,
362
+ ServerSettingsError,
363
+ ServerSettingsService | ChildProcessSpawner.ChildProcessSpawner
364
+> {
365
+ const codexSettings = yield* Effect.service(ServerSettingsService).pipe(
366
+ Effect.flatMap((service) => service.getSettings),
367
+ Effect.map((settings) => settings.providers.codex),
368
+ );
369
+ const checkedAt = DateTime.formatIso(yield* DateTime.now);
370
+ const emptyModels = emptyCodexModelsFromSettings(codexSettings);
371
444
- if (parsedVersion && !isCodexCliVersionSupported(parsedVersion)) {
372
+ if (!codexSettings.enabled) {
373
return buildServerProvider({
374
provider: PROVIDER,
447
- enabled: codexSettings.enabled,
375
+ enabled: false,
376
checkedAt,
449
- models,
377
+ models: emptyModels,
378
+ skills: [],
379
probe: {
451
- installed: true,
452
- version: parsedVersion,
453
- status: "error",
380
+ installed: false,
381
+ version: null,
382
+ status: "warning",
383
auth: { status: "unknown" },
455
- message: formatCodexCliUpgradeMessage(parsedVersion),
384
+ message: "Codex is disabled in T3 Code settings.",
385
},
386
});
387
}
388
460
- const skills =
461
- (resolveSkills
462
- ? yield* resolveSkills({
463
- binaryPath: codexSettings.binaryPath,
464
- homePath: codexSettings.homePath,
465
- cwd: process.cwd(),
466
- }).pipe(Effect.orElseSucceed(() => undefined))
467
- : undefined) ?? [];
389
+ const probeResult = yield* probe({
390
+ binaryPath: codexSettings.binaryPath,
391
+ homePath: codexSettings.homePath,
392
+ cwd: process.cwd(),
393
+ customModels: codexSettings.customModels,
394
+ }).pipe(Effect.timeoutOption(Duration.millis(PROVIDER_PROBE_TIMEOUT_MS)), Effect.result);
395
469
- if (yield* hasCustomModelProvider) {
396
+ if (Result.isFailure(probeResult)) {
397
+ const error = probeResult.failure;
398
+ const installed = !Schema.is(CodexErrors.CodexAppServerSpawnError)(error);
399
return buildServerProvider({
400
provider: PROVIDER,
401
enabled: codexSettings.enabled,
402
checkedAt,
474
- models,
475
- skills,
403
+ models: emptyModels,
404
+ skills: [],
405
probe: {
477
- installed: true,
478
- version: parsedVersion,
479
- status: "ready",
406
+ installed,
407
+ version: null,
408
+ status: "error",
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.",
413
},
414
});
415
}
416
486
- const authProbe = yield* runCodexCommand(["login", "status"]).pipe(
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;
417
+ if (Option.isNone(probeResult.success)) {
418
return buildServerProvider({
419
provider: PROVIDER,
420
enabled: codexSettings.enabled,
421
checkedAt,
504
- models: resolvedModels,
505
- skills,
422
+ models: emptyModels,
423
+ skills: [],
424
probe: {
425
installed: true,
508
- version: parsedVersion,
509
- status: "warning",
426
+ version: null,
427
+ status: "error",
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.",
430
},
431
});
432
}
433
516
- if (Option.isNone(authProbe.success)) {
517
- return buildServerProvider({
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
- }
434
+ const snapshot = probeResult.success.value;
435
+ const accountStatus = accountProbeStatus(snapshot.account);
436
533
- const parsed = parseAuthStatusFromOutput(authProbe.success.value);
534
- const authType = codexAuthSubType(account);
535
- const authLabel = codexAuthSubLabel(account);
437
return buildServerProvider({
438
provider: PROVIDER,
439
enabled: codexSettings.enabled,
440
checkedAt,
540
- models: resolvedModels,
541
- skills,
441
+ models: snapshot.models,
442
+ skills: snapshot.skills,
443
probe: {
444
installed: true,
544
- version: parsedVersion,
545
- status: parsed.status,
546
- auth: {
547
- ...parsed.auth,
548
- ...(authType ? { type: authType } : {}),
549
- ...(authLabel ? { label: authLabel } : {}),
550
- },
551
- ...(parsed.message ? { message: parsed.message } : {}),
445
+ version: snapshot.version ?? null,
446
+ status: accountStatus.status,
447
+ auth: accountStatus.auth,
448
+ ...(accountStatus.message ? { message: accountStatus.message } : {}),
449
},
450
});
451
});
452
556
-const 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
-
453
export const CodexProviderLive = Layer.effect(
454
CodexProvider,
455
Effect.gen(function* () {
456
const serverSettings = yield* ServerSettingsService;
600
- const fileSystem = yield* FileSystem.FileSystem;
601
- const path = yield* Path.Path;
457
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
603
- const accountProbeCache = yield* Cache.make({
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(
458
+ const checkProvider = checkCodexProviderStatus().pipe(
459
Effect.provideService(ServerSettingsService, serverSettings),
632
- Effect.provideService(FileSystem.FileSystem, fileSystem),
633
- Effect.provideService(Path.Path, path),
460
Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
461
);
462
@@ -645,6 +471,7 @@ export const CodexProviderLive = Layer.effect(
471
haveSettingsChanged: (previous, next) => !Equal.equals(previous, next),
472
initialSnapshot: makePendingCodexProvider,
473
checkProvider,
474
+ refreshInterval: Duration.minutes(5),
475
});
476
}),
477
);
apps/server/src/provider/Layers/CodexSessionRuntime.test.ts
new
+275
@@ -0,0 +1,275 @@
1
+import assert from "node:assert/strict";
2
+
3
+import { Effect, Schema } from "effect";
4
+import { describe, it } from "vitest";
5
+import { ThreadId } from "@t3tools/contracts";
6
+import * as CodexErrors from "effect-codex-app-server/errors";
7
+import * as CodexRpc from "effect-codex-app-server/rpc";
8
+
9
+import {
10
+ CODEX_DEFAULT_MODE_DEVELOPER_INSTRUCTIONS,
11
+ CODEX_PLAN_MODE_DEVELOPER_INSTRUCTIONS,
12
+} from "../CodexDeveloperInstructions.ts";
13
+import {
14
+ buildTurnStartParams,
15
+ isRecoverableThreadResumeError,
16
+ openCodexThread,
17
+} from "./CodexSessionRuntime.ts";
18
+
19
+function 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
+
42
+describe("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
+
150
+describe("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
+
197
+describe("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
new
+1325
@@ -0,0 +1,1325 @@
1
+import { randomUUID } from "node:crypto";
2
+
3
+import {
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";
19
+import { normalizeModelSlug } from "@t3tools/shared/model";
20
+import { Deferred, Effect, Exit, Layer, Queue, Ref, Scope, Schema, Stream } from "effect";
21
+import * as SchemaIssue from "effect/SchemaIssue";
22
+import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
23
+import * as CodexClient from "effect-codex-app-server/client";
24
+import * as CodexErrors from "effect-codex-app-server/errors";
25
+import * as CodexRpc from "effect-codex-app-server/rpc";
26
+import * as EffectCodexSchema from "effect-codex-app-server/schema";
27
+
28
+import { buildCodexInitializeParams } from "./CodexProvider.ts";
29
+import {
30
+ CODEX_DEFAULT_MODE_DEVELOPER_INSTRUCTIONS,
31
+ CODEX_PLAN_MODE_DEVELOPER_INSTRUCTIONS,
32
+} from "../CodexDeveloperInstructions.ts";
33
+
34
+const PROVIDER = "codex" as const;
35
+
36
+const ANSI_ESCAPE_CHAR = String.fromCharCode(27);
37
+const ANSI_ESCAPE_REGEX = new RegExp(`${ANSI_ESCAPE_CHAR}\\[[0-9;]*m`, "g");
38
+const CODEX_STDERR_LOG_REGEX =
39
+ /^\d{4}-\d{2}-\d{2}T\S+\s+(TRACE|DEBUG|INFO|WARN|ERROR)\s+\S+:\s+(.*)$/;
40
+const 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
+];
44
+const RECOVERABLE_THREAD_RESUME_ERROR_SNIPPETS = [
45
+ "not found",
46
+ "missing thread",
47
+ "no such thread",
48
+ "unknown thread",
49
+ "does not exist",
50
+];
51
+
52
+export const CodexResumeCursorSchema = Schema.Struct({
53
+ threadId: Schema.String,
54
+});
55
+const 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.
61
+const CodexTurnStartParamsWithCollaborationMode = EffectCodexSchema.V2TurnStartParams.pipe(
62
+ Schema.fieldsAssign({
63
+ collaborationMode: Schema.optionalKey(EffectCodexSchema.V2TurnStartParams__CollaborationMode),
64
+ }),
65
+);
66
+
67
+export type CodexTurnStartParamsWithCollaborationMode =
68
+ typeof CodexTurnStartParamsWithCollaborationMode.Type;
69
+const formatSchemaIssue = SchemaIssue.makeFormatterDefault();
70
+
71
+export type CodexResumeCursor = typeof CodexResumeCursorSchema.Type;
72
+type CodexThreadItem =
73
+ | EffectCodexSchema.V2ThreadReadResponse["thread"]["turns"][number]["items"][number]
74
+ | EffectCodexSchema.V2ThreadRollbackResponse["thread"]["turns"][number]["items"][number];
75
+
76
+export 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
+
87
+export 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
+
96
+export interface CodexThreadTurnSnapshot {
97
+ readonly id: TurnId;
98
+ readonly items: ReadonlyArray<CodexThreadItem>;
99
+}
100
+
101
+export interface CodexThreadSnapshot {
102
+ readonly threadId: string;
103
+ readonly turns: ReadonlyArray<CodexThreadTurnSnapshot>;
104
+}
105
+
106
+export 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
+
129
+export type CodexSessionRuntimeError =
130
+ | CodexErrors.CodexAppServerError
131
+ | CodexSessionRuntimePendingApprovalNotFoundError
132
+ | CodexSessionRuntimePendingUserInputNotFoundError
133
+ | CodexSessionRuntimeInvalidUserInputAnswersError
134
+ | CodexSessionRuntimeThreadIdMissingError;
135
+
136
+export 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
+
147
+export 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
+
158
+export 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
+
169
+export 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
+
180
+interface 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
+
189
+interface ApprovalCorrelation {
190
+ readonly requestId: ApprovalRequestId;
191
+ readonly requestKind: ProviderRequestKind;
192
+ readonly turnId: TurnId | undefined;
193
+ readonly itemId: ProviderItemId | undefined;
194
+}
195
+
196
+interface PendingUserInput {
197
+ readonly requestId: ApprovalRequestId;
198
+ readonly turnId: TurnId | undefined;
199
+ readonly itemId: ProviderItemId | undefined;
200
+ readonly answers: Deferred.Deferred<ProviderUserInputAnswers>;
201
+}
202
+
203
+type CodexServerNotification = {
204
+ readonly [M in CodexRpc.ServerNotificationMethod]: {
205
+ readonly method: M;
206
+ readonly params: CodexRpc.ServerNotificationParamsByMethod[M];
207
+ };
208
+}[CodexRpc.ServerNotificationMethod];
209
+
210
+function makeCodexServerNotification<M extends CodexRpc.ServerNotificationMethod>(
211
+ method: M,
212
+ params: CodexRpc.ServerNotificationParamsByMethod[M],
213
+): CodexServerNotification {
214
+ return { method, params } as CodexServerNotification;
215
+}
216
+
217
+function 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
+
231
+function readResumeCursorThreadId(
232
+ resumeCursor: ProviderSession["resumeCursor"],
233
+): string | undefined {
234
+ return Schema.is(CodexResumeCursorSchema)(resumeCursor) ? resumeCursor.threadId : undefined;
235
+}
236
+
237
+function 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
+
261
+function 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
+
277
+function 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
+
297
+function 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
+
319
+export 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
+
364
+function 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
+
384
+export 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
+
392
+type CodexThreadOpenResponse =
393
+ | CodexRpc.ClientRequestResponsesByMethod["thread/start"]
394
+ | CodexRpc.ClientRequestResponsesByMethod["thread/resume"];
395
+
396
+type CodexThreadOpenMethod = "thread/start" | "thread/resume";
397
+
398
+interface 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
+
405
+export 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
+
444
+function 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
+
490
+function 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
+
548
+function 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
+
570
+function 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
+
589
+function 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
+
609
+function 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
+
625
+function 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
+
635
+function currentProviderThreadId(session: ProviderSession): string | undefined {
636
+ return readResumeCursorThreadId(session.resumeCursor);
637
+}
638
+
639
+function 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
+
650
+function 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
+
662
+export 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
import * as NodeServices from "@effect/platform-node/NodeServices";
2
import { describe, it, assert } from "@effect/vitest";
3
-import {
4
- Effect,
5
- Exit,
6
- FileSystem,
7
- Layer,
8
- Path,
9
- PubSub,
10
- Ref,
11
- Schema,
12
- Scope,
13
- Sink,
14
- Stream,
15
-} from "effect";
3
+import { Effect, Exit, Layer, PubSub, Ref, Schema, Scope, Sink, Stream } from "effect";
4
+import * as CodexErrors from "effect-codex-app-server/errors";
5
import {
6
DEFAULT_SERVER_SETTINGS,
7
ServerSettings,
@@ -23,19 +12,13 @@ import * as PlatformError from "effect/PlatformError";
12
import { ChildProcessSpawner } from "effect/unstable/process";
13
import { deepMerge } from "@t3tools/shared/Struct";
14
26
-import {
27
- checkCodexProviderStatus,
28
- hasCustomModelProvider,
29
- parseAuthStatusFromOutput,
30
- readCodexConfigModelProvider,
31
-} from "./CodexProvider.ts";
15
+import { checkCodexProviderStatus, type CodexAppServerProviderSnapshot } from "./CodexProvider.ts";
16
import { checkClaudeProviderStatus, parseClaudeAuthStatusFromOutput } from "./ClaudeProvider.ts";
17
import {
18
haveProvidersChanged,
19
mergeProviderSnapshot,
20
ProviderRegistryLive,
21
} from "./ProviderRegistry.ts";
38
-import { OpenCodeProvider } from "../Services/OpenCodeProvider.ts";
22
import { ServerConfig } from "../../config.ts";
23
import { ServerSettingsService, type ServerSettingsShape } from "../../serverSettings.ts";
24
import { ProviderRegistry } from "../Services/ProviderRegistry.ts";
@@ -45,19 +28,6 @@ process.env.T3CODE_CURSOR_ENABLED = "1";
28
// ── Test helpers ────────────────────────────────────────────────────
29
30
const encoder = new TextEncoder();
48
-const 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
-};
31
32
function mockHandle(result: { stdout: string; stderr: string; code: number }) {
33
return ChildProcessSpawner.makeHandle({
@@ -118,6 +88,43 @@ function failingSpawnerLayer(description: string) {
88
);
89
}
90
91
+const 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
+
102
+function 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
+
128
function makeMutableServerSettingsService(
129
initial: ContractServerSettings = DEFAULT_SERVER_SETTINGS,
130
) {
@@ -144,126 +151,43 @@ function makeMutableServerSettingsService(
151
});
152
}
153
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
- */
151
-function 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
-
154
it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(
155
"ProviderRegistry",
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
-
157
describe("checkCodexProviderStatus", () => {
191
- it.effect("returns ready when codex is installed and authenticated", () =>
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", () =>
158
+ it.effect("uses the app-server account and model list for provider status", () =>
159
Effect.gen(function* () {
215
- yield* withTempCodexHome();
160
const status = yield* checkCodexProviderStatus(() =>
217
- Effect.succeed({
218
- type: "chatgpt" as const,
219
- planType: "pro" as const,
220
- sparkEnabled: true,
221
- }),
161
+ Effect.succeed(
162
+ makeCodexProbeSnapshot({
163
+ skills: [
164
+ {
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
+ ),
174
);
175
176
assert.strictEqual(status.provider, "codex");
177
assert.strictEqual(status.status, "ready");
178
+ assert.strictEqual(status.installed, true);
179
+ assert.strictEqual(status.version, "1.0.0");
180
assert.strictEqual(status.auth.status, "authenticated");
227
- assert.strictEqual(status.auth.type, "pro");
181
+ assert.strictEqual(status.auth.type, "chatgpt");
182
assert.strictEqual(status.auth.label, "ChatGPT Pro Subscription");
229
- assert.deepStrictEqual(
230
- status.models.some((model) => model.slug === "gpt-5.3-codex-spark"),
231
- true,
232
- );
233
- }).pipe(
234
- Effect.provide(
235
- mockSpawnerLayer((args) => {
236
- const joined = args.join(" ");
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
-
183
+ assert.deepStrictEqual(status.models, [
184
+ {
185
+ slug: "gpt-live-codex",
186
+ name: "GPT Live Codex",
187
+ isCustom: false,
188
+ capabilities: codexModelCapabilities,
189
+ },
190
+ ]);
191
assert.deepStrictEqual(status.skills, [
192
{
193
name: "github:gh-fix-ci",
@@ -273,172 +197,81 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(
197
shortDescription: "Debug failing GitHub Actions checks",
198
},
199
]);
276
- }).pipe(
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
- ),
200
+ }),
201
);
202
288
- it.effect("hides spark from codex models for unsupported chatgpt plans", () =>
203
+ it.effect("returns unauthenticated when app-server requires OpenAI auth", () =>
204
Effect.gen(function* () {
290
- yield* withTempCodexHome();
205
const status = yield* checkCodexProviderStatus(() =>
292
- Effect.succeed({
293
- type: "chatgpt" as const,
294
- planType: "plus" as const,
295
- sparkEnabled: false,
296
- }),
206
+ Effect.succeed(
207
+ makeCodexProbeSnapshot({
208
+ account: {
209
+ account: null,
210
+ requiresOpenaiAuth: true,
211
+ },
212
+ }),
213
+ ),
214
);
215
299
- assert.strictEqual(status.provider, "codex");
300
- assert.strictEqual(status.status, "ready");
301
- assert.strictEqual(status.auth.status, "authenticated");
302
- assert.strictEqual(status.auth.type, "plus");
303
- assert.strictEqual(status.auth.label, "ChatGPT Plus Subscription");
304
- assert.deepStrictEqual(
305
- status.models.some((model) => model.slug === "gpt-5.3-codex-spark"),
306
- false,
216
+ assert.strictEqual(status.status, "error");
217
+ assert.strictEqual(status.auth.status, "unauthenticated");
218
+ assert.strictEqual(
219
+ status.message,
220
+ "Codex CLI is not authenticated. Run `codex login` and try again.",
221
);
308
- }).pipe(
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
- ),
222
+ }),
223
);
224
320
- it.effect("hides spark from codex models for non-pro chatgpt subscriptions", () =>
321
- Effect.gen(function* () {
322
- yield* withTempCodexHome();
323
- const status = yield* checkCodexProviderStatus(() =>
324
- Effect.succeed({
325
- type: "chatgpt" as const,
326
- planType: "team" as const,
327
- sparkEnabled: false,
328
- }),
329
- );
225
+ it.effect(
226
+ "returns ready with unknown auth when app-server does not require OpenAI auth",
227
+ () =>
228
+ Effect.gen(function* () {
229
+ const status = yield* checkCodexProviderStatus(() =>
230
+ Effect.succeed(
231
+ makeCodexProbeSnapshot({
232
+ account: {
233
+ account: null,
234
+ requiresOpenaiAuth: false,
235
+ },
236
+ }),
237
+ ),
238
+ );
239
331
- assert.strictEqual(status.provider, "codex");
332
- assert.strictEqual(status.auth.type, "team");
333
- assert.strictEqual(status.auth.label, "ChatGPT Team Subscription");
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
- ),
240
+ assert.strictEqual(status.status, "ready");
241
+ assert.strictEqual(status.auth.status, "unknown");
242
+ }),
243
);
244
245
it.effect("returns an api key label for codex api key auth", () =>
246
Effect.gen(function* () {
352
- yield* withTempCodexHome();
247
const status = yield* checkCodexProviderStatus(() =>
354
- Effect.succeed({
355
- type: "apiKey" as const,
356
- planType: null,
357
- sparkEnabled: false,
358
- }),
248
+ Effect.succeed(
249
+ makeCodexProbeSnapshot({
250
+ account: {
251
+ account: { type: "apiKey" },
252
+ requiresOpenaiAuth: false,
253
+ },
254
+ }),
255
+ ),
256
);
257
361
- assert.strictEqual(status.provider, "codex");
258
assert.strictEqual(status.status, "ready");
259
assert.strictEqual(status.auth.status, "authenticated");
260
assert.strictEqual(status.auth.type, "apiKey");
261
assert.strictEqual(status.auth.label, "OpenAI API Key");
366
- assert.deepStrictEqual(
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
- }),
262
+ }),
263
);
264
265
it.effect("returns unavailable when codex is missing", () =>
266
Effect.gen(function* () {
440
- yield* withTempCodexHome();
441
- const status = yield* checkCodexProviderStatus();
267
+ 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
+ );
275
assert.strictEqual(status.provider, "codex");
276
assert.strictEqual(status.status, "error");
277
assert.strictEqual(status.installed, false);
@@ -447,107 +280,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(
280
status.message,
281
"Codex CLI (`codex`) is not installed or not on PATH.",
282
);
450
- }).pipe(Effect.provide(failingSpawnerLayer("spawn codex ENOENT"))),
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
- ),
283
+ }),
284
);
285
});
286
@@ -677,7 +410,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(
410
Schema.decodeSync(ServerSettings)(
411
deepMerge(DEFAULT_SERVER_SETTINGS, {
412
providers: {
680
- claudeAgent: { enabled: false },
413
+ codex: { enabled: false },
414
cursor: { enabled: false },
415
},
416
}),
@@ -697,14 +430,8 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(
430
spawnCount += 1;
431
const joined = args.join(" ");
432
if (joined === "--version") {
700
- if (command === "codex") {
701
- return { stdout: "codex 1.0.0\n", stderr: "", code: 0 };
702
- }
433
return { stdout: "claude 1.0.0\n", stderr: "", code: 0 };
434
}
705
- if (joined === "login status") {
706
- return { stdout: "Logged in\n", stderr: "", code: 0 };
707
- }
435
if (joined === "auth status") {
436
return { stdout: '{"authenticated":true}\n', stderr: "", code: 0 };
437
}
@@ -722,8 +449,10 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(
449
const refreshed = yield* Effect.gen(function* () {
450
for (let remainingAttempts = 50; remainingAttempts > 0; remainingAttempts -= 1) {
451
const providers = yield* registry.getProviders;
725
- const codexProvider = providers.find((provider) => provider.provider === "codex");
726
- if (codexProvider?.status === "ready") {
452
+ const claudeProvider = providers.find(
453
+ (provider) => provider.provider === "claudeAgent",
454
+ );
455
+ if (claudeProvider?.status === "ready") {
456
return providers;
457
}
458
yield* Effect.sleep("10 millis");
@@ -731,99 +460,13 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(
460
return yield* registry.getProviders;
461
});
462
assert.strictEqual(
734
- refreshed.find((provider) => provider.provider === "codex")?.status,
463
+ refreshed.find((provider) => provider.provider === "claudeAgent")?.status,
464
"ready",
465
);
466
}).pipe(Effect.provide(runtimeServices));
467
}),
468
);
469
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
-
470
it.effect(
471
"keeps cursor disabled and skips probing when the provider setting is disabled",
472
() =>
@@ -832,6 +475,9 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(
475
Schema.decodeSync(ServerSettings)(
476
deepMerge(DEFAULT_SERVER_SETTINGS, {
477
providers: {
478
+ codex: {
479
+ enabled: false,
480
+ },
481
cursor: {
482
enabled: false,
483
},
@@ -858,9 +504,6 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(
504
if (joined === "--version") {
505
return { stdout: `${command} 1.0.0\n`, stderr: "", code: 0 };
506
}
861
- if (joined === "login status") {
862
- return { stdout: "Logged in\n", stderr: "", code: 0 };
863
- }
507
if (joined === "auth status") {
508
return { stdout: '{"authenticated":true}\n', stderr: "", code: 0 };
509
}
@@ -919,238 +562,6 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(
562
);
563
});
564
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
-
565
// ── checkClaudeProviderStatus tests ──────────────────────────
566
567
describe("checkClaudeProviderStatus", () => {
apps/server/src/provider/codexAccount.ts
deleted
-123
@@ -1,123 +0,0 @@
1
-import type { ServerProviderModel } from "@t3tools/contracts";
2
-
3
-export type CodexPlanType =
4
- | "free"
5
- | "go"
6
- | "plus"
7
- | "pro"
8
- | "team"
9
- | "business"
10
- | "enterprise"
11
- | "edu"
12
- | "unknown";
13
-
14
-export interface CodexAccountSnapshot {
15
- readonly type: "apiKey" | "chatgpt" | "unknown";
16
- readonly planType: CodexPlanType | null;
17
- readonly sparkEnabled: boolean;
18
-}
19
-
20
-export const CODEX_DEFAULT_MODEL = "gpt-5.3-codex";
21
-export const CODEX_SPARK_MODEL = "gpt-5.3-codex-spark";
22
-const CODEX_SPARK_ENABLED_PLAN_TYPES = new Set<CodexPlanType>(["pro"]);
23
-
24
-function 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
-
31
-function asString(value: unknown): string | undefined {
32
- return typeof value === "string" ? value : undefined;
33
-}
34
-
35
-export 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
-
64
-export 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
-
76
-export 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
-
103
-export 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
-
114
-export 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 @@
1
-import { spawn, spawnSync, type ChildProcessWithoutNullStreams } from "node:child_process";
2
-import readline from "node:readline";
3
-import type { ServerProviderSkill } from "@t3tools/contracts";
4
-import { readCodexAccountSnapshot, type CodexAccountSnapshot } from "./codexAccount.ts";
5
-import { expandHomePath } from "../pathExpansion.ts";
6
-
7
-interface JsonRpcProbeResponse {
8
- readonly id?: unknown;
9
- readonly result?: unknown;
10
- readonly error?: {
11
- readonly message?: unknown;
12
- };
13
-}
14
-
15
-export interface CodexDiscoverySnapshot {
16
- readonly account: CodexAccountSnapshot;
17
- readonly skills: ReadonlyArray<ServerProviderSkill>;
18
-}
19
-
20
-function readErrorMessage(response: JsonRpcProbeResponse): string | undefined {
21
- return typeof response.error?.message === "string" ? response.error.message : undefined;
22
-}
23
-
24
-function readObject(value: unknown): Record<string, unknown> | undefined {
25
- return value && typeof value === "object" ? (value as Record<string, unknown>) : undefined;
26
-}
27
-
28
-function readArray(value: unknown): ReadonlyArray<unknown> | undefined {
29
- return Array.isArray(value) ? value : undefined;
30
-}
31
-
32
-function readString(value: unknown): string | undefined {
33
- return typeof value === "string" ? value : undefined;
34
-}
35
-
36
-function nonEmptyTrimmed(value: unknown): string | undefined {
37
- const candidate = readString(value)?.trim();
38
- return candidate ? candidate : undefined;
39
-}
40
-
41
-function 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
-
83
-export 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
-
96
-export 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
-
109
-export 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 @@
1
-import { compareCliVersions, normalizeCliVersion } from "./cliVersion.ts";
2
-
3
-const CODEX_VERSION_PATTERN = /\bv?(\d+\.\d+(?:\.\d+)?(?:-[0-9A-Za-z.-]+)?)\b/;
4
-
5
-export const MINIMUM_CODEX_CLI_VERSION = "0.37.0";
6
-
7
-export const compareCodexCliVersions = compareCliVersions;
8
-
9
-export 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
-
18
-export function isCodexCliVersionSupported(version: string): boolean {
19
- return compareCodexCliVersions(version, MINIMUM_CODEX_CLI_VERSION) >= 0;
20
-}
21
-
22
-export 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
deriveCompletionDividerBeforeEntryId,
12
deriveActiveWorkStartedAt,
13
deriveActivePlanState,
14
- PROVIDER_OPTIONS,
14
derivePendingApprovals,
15
derivePendingUserInputs,
16
deriveTimelineEntries,
bun.lock
+18
@@ -67,6 +67,7 @@
67
"@types/bun": "catalog:",
68
"@types/node": "catalog:",
69
"effect-acp": "workspace:*",
70
+ "effect-codex-app-server": "workspace:*",
71
"tsdown": "catalog:",
72
"typescript": "catalog:",
73
"vitest": "catalog:",
@@ -166,6 +167,21 @@
167
"vitest": "catalog:",
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
+ },
185
"packages/shared": {
186
"name": "@t3tools/shared",
187
"version": "0.0.0-alpha.1",
@@ -1083,6 +1099,8 @@
1099
1100
"effect-acp": ["effect-acp@workspace:packages/effect-acp"],
1101
1102
+ "effect-codex-app-server": ["effect-codex-app-server@workspace:packages/effect-codex-app-server"],
1103
+
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=="],
1105
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
import * as AcpError from "../errors.ts";
10
11
const encoder = new TextEncoder();
12
-const decoder = new TextDecoder();
12
13
export const makeChildStdio = (handle: ChildProcessSpawner.ChildProcessHandle) =>
14
Stdio.make({
@@ -25,6 +24,7 @@ export const makeChildStdio = (handle: ChildProcessSpawner.ChildProcessHandle) =
24
export 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({
@@ -32,7 +32,10 @@ export const makeInMemoryStdio = Effect.fn("makeInMemoryStdio")(function* () {
32
stdin: Stream.fromQueue(input),
33
stdout: () =>
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
+ ),
39
),
40
stderr: () => Sink.drain,
41
}),
packages/effect-codex-app-server/package.json
new
+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
new
+772
@@ -0,0 +1,772 @@
1
+#!/usr/bin/env node
2
+
3
+import * as NodeRuntime from "@effect/platform-node/NodeRuntime";
4
+import * as NodeServices from "@effect/platform-node/NodeServices";
5
+import { make as makeJsonSchemaGenerator } from "@effect/openapi-generator/JsonSchemaGenerator";
6
+import { Effect, FileSystem, Layer, Logger, Path, Schema } from "effect";
7
+import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
8
+
9
+const UPSTREAM_REF = "dbfe855f4fd0f5dcdf079882652a8efe622b0595";
10
+const USER_AGENT = "effect-codex-app-server-generator";
11
+const GITHUB_API_BASE =
12
+ "https://api.github.com/repos/openai/codex/contents/codex-rs/app-server-protocol";
13
+
14
+const 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
+);
22
+type GithubContentEntry = (typeof GithubContentEntries.Type)[number];
23
+
24
+interface GeneratedPaths {
25
+ readonly generatedDir: string;
26
+ readonly schemaOutputPath: string;
27
+ readonly metaOutputPath: string;
28
+ readonly namespacesOutputPath: string;
29
+}
30
+
31
+interface MethodEntry {
32
+ readonly method: string;
33
+ readonly paramsType?: string;
34
+}
35
+
36
+interface JsonSchemaFile {
37
+ readonly namespace?: string;
38
+ readonly exportName: string;
39
+ readonly fileName: string;
40
+ readonly downloadUrl: string;
41
+ readonly qualifiedName: string;
42
+}
43
+
44
+class 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
+
53
+const 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
+
128
+const 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
+
139
+const 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
+
145
+const 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
+
182
+const 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
+
187
+function 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
+
222
+function 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
+
273
+function 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
+
288
+function 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
+
298
+function 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
+
311
+function 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
+
324
+function 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
+
347
+function 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
+
378
+function 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
+
389
+function 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
+
402
+function 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
+
420
+function renderSchemaTypeReference(schemaName: string) {
421
+ return schemaName === "undefined" ? "undefined" : `typeof CodexSchema.${schemaName}.Type`;
422
+}
423
+
424
+function 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
+
439
+function 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
+
471
+function 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
+
529
+const 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
+
768
+generateFiles().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
new
+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
+
4
+import * as CodexSchema from "./schema.gen.ts";
5
+
6
+export 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
+
73
+export const CLIENT_NOTIFICATION_METHODS = {
74
+ initialized: "initialized",
75
+} as const;
76
+
77
+export 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
+
89
+export 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
+
145
+export type ClientRequestMethod = keyof typeof CLIENT_REQUEST_METHODS;
146
+export type ClientNotificationMethod = keyof typeof CLIENT_NOTIFICATION_METHODS;
147
+export type ServerRequestMethod = keyof typeof SERVER_REQUEST_METHODS;
148
+export type ServerNotificationMethod = keyof typeof SERVER_NOTIFICATION_METHODS;
149
+
150
+export 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
+
217
+export 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
+
284
+export interface ClientNotificationParamsByMethod {
285
+ readonly initialized: undefined;
286
+}
287
+
288
+export 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
+
300
+export 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
+
312
+export 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
+
368
+export 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
+
435
+export 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
+
502
+export const CLIENT_NOTIFICATION_PARAMS = {
503
+ initialized: undefined,
504
+} as const;
505
+
506
+export 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
+
518
+export 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
+
530
+export 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
new
+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
+
4
+import * as CodexSchema from "./schema.gen.ts";
5
+
6
+export const v1 = {
7
+ InitializeParams: CodexSchema.V1InitializeParams,
8
+ InitializeResponse: CodexSchema.V1InitializeResponse,
9
+} as const;
10
+
11
+export 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
new
+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
+
4
+import * as Schema from "effect/Schema";
5
+
6
+export 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 };
10
+export 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
+
29
+export type ApplyPatchApprovalParams__ThreadId = string;
30
+export const ApplyPatchApprovalParams__ThreadId = Schema.String;
31
+
32
+export type ApplyPatchApprovalResponse__NetworkPolicyRuleAction = "allow" | "deny";
33
+export const ApplyPatchApprovalResponse__NetworkPolicyRuleAction = Schema.Literals([
34
+ "allow",
35
+ "deny",
36
+]);
37
+
38
+export type ChatgptAuthTokensRefreshParams__ChatgptAuthTokensRefreshReason = "unauthorized";
39
+export const ChatgptAuthTokensRefreshParams__ChatgptAuthTokensRefreshReason =
40
+ Schema.Literal("unauthorized");
41
+
42
+export type ClientRequest__AbsolutePathBuf = string;
43
+export 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
+
48
+export type ClientRequest__ApprovalsReviewer = "user" | "guardian_subagent";
49
+export 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
+
57
+export type ClientRequest__AppsListParams = {
58
+ readonly cursor?: string | null;
59
+ readonly forceRefetch?: boolean;
60
+ readonly limit?: number | null;
61
+ readonly threadId?: string | null;
62
+};
63
+export 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
+
99
+export 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
+ };
113
+export 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
+
129
+export type ClientRequest__CancelLoginAccountParams = { readonly loginId: string };
130
+export const ClientRequest__CancelLoginAccountParams = Schema.Struct({ loginId: Schema.String });
131
+
132
+export type ClientRequest__ClientInfo = {
133
+ readonly name: string;
134
+ readonly title?: string | null;
135
+ readonly version: string;
136
+};
137
+export 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
+
143
+export type ClientRequest__CommandExecResizeParams = {
144
+ readonly processId: string;
145
+ readonly size: { readonly cols: number; readonly rows: number };
146
+};
147
+export 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
+
168
+export type ClientRequest__CommandExecTerminalSize = {
169
+ readonly cols: number;
170
+ readonly rows: number;
171
+};
172
+export 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
+
187
+export type ClientRequest__CommandExecTerminateParams = { readonly processId: string };
188
+export 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
+
195
+export type ClientRequest__CommandExecWriteParams = {
196
+ readonly closeStdin?: boolean;
197
+ readonly deltaBase64?: string | null;
198
+ readonly processId: string;
199
+};
200
+export 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
+
220
+export type ClientRequest__ConfigReadParams = {
221
+ readonly cwd?: string | null;
222
+ readonly includeLayers?: boolean;
223
+};
224
+export 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
+
237
+export 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" };
241
+export 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
+
259
+export type ClientRequest__ExperimentalFeatureEnablementSetParams = {
260
+ readonly enablement: { readonly [x: string]: boolean };
261
+};
262
+export 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
+
269
+export type ClientRequest__ExperimentalFeatureListParams = {
270
+ readonly cursor?: string | null;
271
+ readonly limit?: number | null;
272
+};
273
+export 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
+
295
+export type ClientRequest__ExternalAgentConfigDetectParams = {
296
+ readonly cwds?: ReadonlyArray<string> | null;
297
+ readonly includeHome?: boolean;
298
+};
299
+export 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
+
315
+export type ClientRequest__ExternalAgentConfigMigrationItemType =
316
+ | "AGENTS_MD"
317
+ | "CONFIG"
318
+ | "SKILLS"
319
+ | "MCP_SERVER_CONFIG";
320
+export const ClientRequest__ExternalAgentConfigMigrationItemType = Schema.Literals([
321
+ "AGENTS_MD",
322
+ "CONFIG",
323
+ "SKILLS",
324
+ "MCP_SERVER_CONFIG",
325
+]);
326
+
327
+export 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
+};
334
+export 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
+
342
+export type ClientRequest__FsCopyParams = {
343
+ readonly destinationPath: string;
344
+ readonly recursive?: boolean;
345
+ readonly sourcePath: string;
346
+};
347
+export 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
+
363
+export type ClientRequest__FsCreateDirectoryParams = {
364
+ readonly path: string;
365
+ readonly recursive?: boolean | null;
366
+};
367
+export 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
+
382
+export type ClientRequest__FsGetMetadataParams = { readonly path: string };
383
+export 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
+
390
+export type ClientRequest__FsReadDirectoryParams = { readonly path: string };
391
+export 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
+
398
+export type ClientRequest__FsReadFileParams = { readonly path: string };
399
+export 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
+
406
+export type ClientRequest__FsRemoveParams = {
407
+ readonly force?: boolean | null;
408
+ readonly path: string;
409
+ readonly recursive?: boolean | null;
410
+};
411
+export 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
+
434
+export type ClientRequest__FsUnwatchParams = { readonly watchId: string };
435
+export 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
+
441
+export type ClientRequest__FsWatchParams = { readonly path: string; readonly watchId: string };
442
+export 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
+
452
+export type ClientRequest__FsWriteFileParams = {
453
+ readonly dataBase64: string;
454
+ readonly path: string;
455
+};
456
+export 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
+
464
+export type ClientRequest__FuzzyFileSearchParams = {
465
+ readonly cancellationToken?: string | null;
466
+ readonly query: string;
467
+ readonly roots: ReadonlyArray<string>;
468
+};
469
+export 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
+
475
+export type ClientRequest__GetAccountParams = { readonly refreshToken?: boolean };
476
+export 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
+
486
+export 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
+};
492
+export 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
+
499
+export type ClientRequest__ImageDetail = "auto" | "low" | "high" | "original";
500
+export const ClientRequest__ImageDetail = Schema.Literals(["auto", "low", "high", "original"]);
501
+
502
+export type ClientRequest__InitializeCapabilities = {
503
+ readonly experimentalApi?: boolean;
504
+ readonly optOutNotificationMethods?: ReadonlyArray<string> | null;
505
+};
506
+export 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
+
524
+export 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
+};
532
+export 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
+
555
+export type ClientRequest__LocalShellStatus = "completed" | "in_progress" | "incomplete";
556
+export const ClientRequest__LocalShellStatus = Schema.Literals([
557
+ "completed",
558
+ "in_progress",
559
+ "incomplete",
560
+]);
561
+
562
+export 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
+ };
572
+export 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
+
615
+export type ClientRequest__McpResourceReadParams = {
616
+ readonly server: string;
617
+ readonly threadId: string;
618
+ readonly uri: string;
619
+};
620
+export const ClientRequest__McpResourceReadParams = Schema.Struct({
621
+ server: Schema.String,
622
+ threadId: Schema.String,
623
+ uri: Schema.String,
624
+});
625
+
626
+export type ClientRequest__McpServerOauthLoginParams = {
627
+ readonly name: string;
628
+ readonly scopes?: ReadonlyArray<string> | null;
629
+ readonly timeoutSecs?: number | null;
630
+};
631
+export 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
+
639
+export type ClientRequest__McpServerStatusDetail = "full" | "toolsAndAuthOnly";
640
+export const ClientRequest__McpServerStatusDetail = Schema.Literals(["full", "toolsAndAuthOnly"]);
641
+
642
+export type ClientRequest__McpServerToolCallParams = {
643
+ readonly _meta?: unknown;
644
+ readonly arguments?: unknown;
645
+ readonly server: string;
646
+ readonly threadId: string;
647
+ readonly tool: string;
648
+};
649
+export 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
+
657
+export type ClientRequest__MergeStrategy = "replace" | "upsert";
658
+export const ClientRequest__MergeStrategy = Schema.Literals(["replace", "upsert"]);
659
+
660
+export type ClientRequest__MessagePhase = "commentary" | "final_answer";
661
+export 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
+
668
+export type ClientRequest__ModeKind = "plan" | "default";
669
+export const ClientRequest__ModeKind = Schema.Literals(["plan", "default"]).annotate({
670
+ description: "Initial collaboration mode to use when the TUI starts.",
671
+});
672
+
673
+export type ClientRequest__ModelListParams = {
674
+ readonly cursor?: string | null;
675
+ readonly includeHidden?: boolean | null;
676
+ readonly limit?: number | null;
677
+};
678
+export 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
+
708
+export type ClientRequest__Personality = "none" | "friendly" | "pragmatic";
709
+export const ClientRequest__Personality = Schema.Literals(["none", "friendly", "pragmatic"]);
710
+
711
+export type ClientRequest__PluginUninstallParams = {
712
+ readonly forceRemoteSync?: boolean;
713
+ readonly pluginId: string;
714
+};
715
+export 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
+
724
+export type ClientRequest__ReasoningEffort =
725
+ | "none"
726
+ | "minimal"
727
+ | "low"
728
+ | "medium"
729
+ | "high"
730
+ | "xhigh";
731
+export 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
+
743
+export type ClientRequest__ReasoningItemContent =
744
+ | { readonly text: string; readonly type: "reasoning_text" }
745
+ | { readonly text: string; readonly type: "text" };
746
+export 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
+
762
+export type ClientRequest__ReasoningItemReasoningSummary = {
763
+ readonly text: string;
764
+ readonly type: "summary_text";
765
+};
766
+export 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
+
778
+export type ClientRequest__ReasoningSummary = "auto" | "concise" | "detailed" | "none";
779
+export 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
+
790
+export type ClientRequest__RequestId = string | number;
791
+export const ClientRequest__RequestId = Schema.Union([
792
+ Schema.String,
793
+ Schema.Number.annotate({ format: "int64" }).check(Schema.isInt()),
794
+]);
795
+
796
+export 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" };
809
+export 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
+
836
+export type ClientRequest__ReviewDelivery = "inline" | "detached";
837
+export const ClientRequest__ReviewDelivery = Schema.Literals(["inline", "detached"]);
838
+
839
+export 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" };
844
+export 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
+
887
+export type ClientRequest__SandboxMode = "read-only" | "workspace-write" | "danger-full-access";
888
+export const ClientRequest__SandboxMode = Schema.Literals([
889
+ "read-only",
890
+ "workspace-write",
891
+ "danger-full-access",
892
+]);
893
+
894
+export type ClientRequest__ServiceTier = "fast" | "flex";
895
+export const ClientRequest__ServiceTier = Schema.Literals(["fast", "flex"]);
896
+
897
+export type ClientRequest__SkillsListExtraRootsForCwd = {
898
+ readonly cwd: string;
899
+ readonly extraUserRoots: ReadonlyArray<string>;
900
+};
901
+export const ClientRequest__SkillsListExtraRootsForCwd = Schema.Struct({
902
+ cwd: Schema.String,
903
+ extraUserRoots: Schema.Array(Schema.String),
904
+});
905
+
906
+export type ClientRequest__TextElement = {
907
+ readonly byteRange: { readonly end: number; readonly start: number };
908
+ readonly placeholder?: string | null;
909
+};
910
+export 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
+
931
+export type ClientRequest__ThreadArchiveParams = { readonly threadId: string };
932
+export const ClientRequest__ThreadArchiveParams = Schema.Struct({ threadId: Schema.String });
933
+
934
+export type ClientRequest__ThreadCompactStartParams = { readonly threadId: string };
935
+export const ClientRequest__ThreadCompactStartParams = Schema.Struct({ threadId: Schema.String });
936
+
937
+export type ClientRequest__ThreadLoadedListParams = {
938
+ readonly cursor?: string | null;
939
+ readonly limit?: number | null;
940
+};
941
+export 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
+
963
+export type ClientRequest__ThreadMetadataGitInfoUpdateParams = {
964
+ readonly branch?: string | null;
965
+ readonly originUrl?: string | null;
966
+ readonly sha?: string | null;
967
+};
968
+export 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
+
998
+export type ClientRequest__ThreadReadParams = {
999
+ readonly includeTurns?: boolean;
1000
+ readonly threadId: string;
1001
+};
1002
+export 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
+
1012
+export type ClientRequest__ThreadRollbackParams = {
1013
+ readonly numTurns: number;
1014
+ readonly threadId: string;
1015
+};
1016
+export 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
+
1027
+export type ClientRequest__ThreadSetNameParams = {
1028
+ readonly name: string;
1029
+ readonly threadId: string;
1030
+};
1031
+export const ClientRequest__ThreadSetNameParams = Schema.Struct({
1032
+ name: Schema.String,
1033
+ threadId: Schema.String,
1034
+});
1035
+
1036
+export type ClientRequest__ThreadShellCommandParams = {
1037
+ readonly command: string;
1038
+ readonly threadId: string;
1039
+};
1040
+export 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
+
1048
+export type ClientRequest__ThreadSortKey = "created_at" | "updated_at";
1049
+export const ClientRequest__ThreadSortKey = Schema.Literals(["created_at", "updated_at"]);
1050
+
1051
+export type ClientRequest__ThreadSourceKind =
1052
+ | "cli"
1053
+ | "vscode"
1054
+ | "exec"
1055
+ | "appServer"
1056
+ | "subAgent"
1057
+ | "subAgentReview"
1058
+ | "subAgentCompact"
1059
+ | "subAgentThreadSpawn"
1060
+ | "subAgentOther"
1061
+ | "unknown";
1062
+export 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
+
1075
+export type ClientRequest__ThreadStartSource = "startup" | "clear";
1076
+export const ClientRequest__ThreadStartSource = Schema.Literals(["startup", "clear"]);
1077
+
1078
+export type ClientRequest__ThreadUnarchiveParams = { readonly threadId: string };
1079
+export const ClientRequest__ThreadUnarchiveParams = Schema.Struct({ threadId: Schema.String });
1080
+
1081
+export type ClientRequest__ThreadUnsubscribeParams = { readonly threadId: string };
1082
+export const ClientRequest__ThreadUnsubscribeParams = Schema.Struct({ threadId: Schema.String });
1083
+
1084
+export type ClientRequest__TurnInterruptParams = {
1085
+ readonly threadId: string;
1086
+ readonly turnId: string;
1087
+};
1088
+export const ClientRequest__TurnInterruptParams = Schema.Struct({
1089
+ threadId: Schema.String,
1090
+ turnId: Schema.String,
1091
+});
1092
+
1093
+export type ClientRequest__WindowsSandboxSetupMode = "elevated" | "unelevated";
1094
+export const ClientRequest__WindowsSandboxSetupMode = Schema.Literals(["elevated", "unelevated"]);
1095
+
1096
+export type CommandExecutionRequestApprovalParams__AbsolutePathBuf = string;
1097
+export 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
+
1102
+export type CommandExecutionRequestApprovalParams__AdditionalNetworkPermissions = {
1103
+ readonly enabled?: boolean | null;
1104
+};
1105
+export const CommandExecutionRequestApprovalParams__AdditionalNetworkPermissions = Schema.Struct({
1106
+ enabled: Schema.optionalKey(Schema.Union([Schema.Boolean, Schema.Null])),
1107
+});
1108
+
1109
+export 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" };
1124
+export 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
+
1151
+export type CommandExecutionRequestApprovalParams__NetworkApprovalProtocol =
1152
+ | "http"
1153
+ | "https"
1154
+ | "socks5Tcp"
1155
+ | "socks5Udp";
1156
+export const CommandExecutionRequestApprovalParams__NetworkApprovalProtocol = Schema.Literals([
1157
+ "http",
1158
+ "https",
1159
+ "socks5Tcp",
1160
+ "socks5Udp",
1161
+]);
1162
+
1163
+export type CommandExecutionRequestApprovalParams__NetworkPolicyRuleAction = "allow" | "deny";
1164
+export const CommandExecutionRequestApprovalParams__NetworkPolicyRuleAction = Schema.Literals([
1165
+ "allow",
1166
+ "deny",
1167
+]);
1168
+
1169
+export type CommandExecutionRequestApprovalResponse__NetworkPolicyRuleAction = "allow" | "deny";
1170
+export const CommandExecutionRequestApprovalResponse__NetworkPolicyRuleAction = Schema.Literals([
1171
+ "allow",
1172
+ "deny",
1173
+]);
1174
+
1175
+export type DynamicToolCallResponse__DynamicToolCallOutputContentItem =
1176
+ | { readonly text: string; readonly type: "inputText" }
1177
+ | { readonly imageUrl: string; readonly type: "inputImage" };
1178
+export 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
+
1196
+export 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" };
1206
+export 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
+
1236
+export type ExecCommandApprovalParams__ThreadId = string;
1237
+export const ExecCommandApprovalParams__ThreadId = Schema.String;
1238
+
1239
+export type ExecCommandApprovalResponse__NetworkPolicyRuleAction = "allow" | "deny";
1240
+export const ExecCommandApprovalResponse__NetworkPolicyRuleAction = Schema.Literals([
1241
+ "allow",
1242
+ "deny",
1243
+]);
1244
+
1245
+export type FileChangeRequestApprovalResponse__FileChangeApprovalDecision =
1246
+ | "accept"
1247
+ | "acceptForSession"
1248
+ | "decline"
1249
+ | "cancel";
1250
+export const FileChangeRequestApprovalResponse__FileChangeApprovalDecision = Schema.Literals([
1251
+ "accept",
1252
+ "acceptForSession",
1253
+ "decline",
1254
+ "cancel",
1255
+]);
1256
+
1257
+export type FuzzyFileSearchResponse__FuzzyFileSearchMatchType = "file" | "directory";
1258
+export const FuzzyFileSearchResponse__FuzzyFileSearchMatchType = Schema.Literals([
1259
+ "file",
1260
+ "directory",
1261
+]);
1262
+
1263
+export type FuzzyFileSearchSessionUpdatedNotification__FuzzyFileSearchMatchType =
1264
+ | "file"
1265
+ | "directory";
1266
+export const FuzzyFileSearchSessionUpdatedNotification__FuzzyFileSearchMatchType = Schema.Literals([
1267
+ "file",
1268
+ "directory",
1269
+]);
1270
+
1271
+export type JSONRPCError__JSONRPCErrorError = {
1272
+ readonly code: number;
1273
+ readonly data?: unknown;
1274
+ readonly message: string;
1275
+};
1276
+export 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
+
1282
+export type JSONRPCError__RequestId = string | number;
1283
+export const JSONRPCError__RequestId = Schema.Union([
1284
+ Schema.String,
1285
+ Schema.Number.annotate({ format: "int64" }).check(Schema.isInt()),
1286
+]);
1287
+
1288
+export type JSONRPCMessage__JSONRPCErrorError = {
1289
+ readonly code: number;
1290
+ readonly data?: unknown;
1291
+ readonly message: string;
1292
+};
1293
+export 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
+
1299
+export type JSONRPCMessage__JSONRPCNotification = {
1300
+ readonly method: string;
1301
+ readonly params?: unknown;
1302
+};
1303
+export 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
+
1308
+export type JSONRPCMessage__RequestId = string | number;
1309
+export const JSONRPCMessage__RequestId = Schema.Union([
1310
+ Schema.String,
1311
+ Schema.Number.annotate({ format: "int64" }).check(Schema.isInt()),
1312
+]);
1313
+
1314
+export type JSONRPCMessage__W3cTraceContext = {
1315
+ readonly traceparent?: string | null;
1316
+ readonly tracestate?: string | null;
1317
+};
1318
+export 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
+
1323
+export type JSONRPCRequest__RequestId = string | number;
1324
+export const JSONRPCRequest__RequestId = Schema.Union([
1325
+ Schema.String,
1326
+ Schema.Number.annotate({ format: "int64" }).check(Schema.isInt()),
1327
+]);
1328
+
1329
+export type JSONRPCRequest__W3cTraceContext = {
1330
+ readonly traceparent?: string | null;
1331
+ readonly tracestate?: string | null;
1332
+};
1333
+export 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
+
1338
+export type JSONRPCResponse__RequestId = string | number;
1339
+export const JSONRPCResponse__RequestId = Schema.Union([
1340
+ Schema.String,
1341
+ Schema.Number.annotate({ format: "int64" }).check(Schema.isInt()),
1342
+]);
1343
+
1344
+export type McpServerElicitationRequestParams__McpElicitationArrayType = "array";
1345
+export const McpServerElicitationRequestParams__McpElicitationArrayType = Schema.Literal("array");
1346
+
1347
+export type McpServerElicitationRequestParams__McpElicitationBooleanType = "boolean";
1348
+export const McpServerElicitationRequestParams__McpElicitationBooleanType =
1349
+ Schema.Literal("boolean");
1350
+
1351
+export type McpServerElicitationRequestParams__McpElicitationConstOption = {
1352
+ readonly const: string;
1353
+ readonly title: string;
1354
+};
1355
+export const McpServerElicitationRequestParams__McpElicitationConstOption = Schema.Struct({
1356
+ const: Schema.String,
1357
+ title: Schema.String,
1358
+});
1359
+
1360
+export type McpServerElicitationRequestParams__McpElicitationNumberType = "number" | "integer";
1361
+export const McpServerElicitationRequestParams__McpElicitationNumberType = Schema.Literals([
1362
+ "number",
1363
+ "integer",
1364
+]);
1365
+
1366
+export type McpServerElicitationRequestParams__McpElicitationObjectType = "object";
1367
+export const McpServerElicitationRequestParams__McpElicitationObjectType = Schema.Literal("object");
1368
+
1369
+export type McpServerElicitationRequestParams__McpElicitationStringFormat =
1370
+ | "email"
1371
+ | "uri"
1372
+ | "date"
1373
+ | "date-time";
1374
+export const McpServerElicitationRequestParams__McpElicitationStringFormat = Schema.Literals([
1375
+ "email",
1376
+ "uri",
1377
+ "date",
1378
+ "date-time",
1379
+]);
1380
+
1381
+export type McpServerElicitationRequestParams__McpElicitationStringType = "string";
1382
+export const McpServerElicitationRequestParams__McpElicitationStringType = Schema.Literal("string");
1383
+
1384
+export type McpServerElicitationRequestResponse__McpServerElicitationAction =
1385
+ | "accept"
1386
+ | "decline"
1387
+ | "cancel";
1388
+export const McpServerElicitationRequestResponse__McpServerElicitationAction = Schema.Literals([
1389
+ "accept",
1390
+ "decline",
1391
+ "cancel",
1392
+]);
1393
+
1394
+export type PermissionsRequestApprovalParams__AbsolutePathBuf = string;
1395
+export 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
+
1400
+export type PermissionsRequestApprovalParams__AdditionalNetworkPermissions = {
1401
+ readonly enabled?: boolean | null;
1402
+};
1403
+export const PermissionsRequestApprovalParams__AdditionalNetworkPermissions = Schema.Struct({
1404
+ enabled: Schema.optionalKey(Schema.Union([Schema.Boolean, Schema.Null])),
1405
+});
1406
+
1407
+export type PermissionsRequestApprovalResponse__AbsolutePathBuf = string;
1408
+export 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
+
1413
+export type PermissionsRequestApprovalResponse__AdditionalNetworkPermissions = {
1414
+ readonly enabled?: boolean | null;
1415
+};
1416
+export const PermissionsRequestApprovalResponse__AdditionalNetworkPermissions = Schema.Struct({
1417
+ enabled: Schema.optionalKey(Schema.Union([Schema.Boolean, Schema.Null])),
1418
+});
1419
+
1420
+export type ServerNotification__AbsolutePathBuf = string;
1421
+export 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
+
1426
+export type ServerNotification__AccountLoginCompletedNotification = {
1427
+ readonly error?: string | null;
1428
+ readonly loginId?: string | null;
1429
+ readonly success: boolean;
1430
+};
1431
+export 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
+
1437
+export type ServerNotification__AgentMessageDeltaNotification = {
1438
+ readonly delta: string;
1439
+ readonly itemId: string;
1440
+ readonly threadId: string;
1441
+ readonly turnId: string;
1442
+};
1443
+export const ServerNotification__AgentMessageDeltaNotification = Schema.Struct({
1444
+ delta: Schema.String,
1445
+ itemId: Schema.String,
1446
+ threadId: Schema.String,
1447
+ turnId: Schema.String,
1448
+});
1449
+
1450
+export type ServerNotification__AgentPath = string;
1451
+export const ServerNotification__AgentPath = Schema.String;
1452
+
1453
+export 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
+};
1461
+export 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
+
1470
+export type ServerNotification__AppReview = { readonly status: string };
1471
+export const ServerNotification__AppReview = Schema.Struct({ status: Schema.String });
1472
+
1473
+export type ServerNotification__AppScreenshot = {
1474
+ readonly fileId?: string | null;
1475
+ readonly url?: string | null;
1476
+ readonly userPrompt: string;
1477
+};
1478
+export 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
+
1484
+export type ServerNotification__AuthMode = "apikey" | "chatgpt" | "chatgptAuthTokens";
1485
+export const ServerNotification__AuthMode = Schema.Literals([
1486
+ "apikey",
1487
+ "chatgpt",
1488
+ "chatgptAuthTokens",
1489
+]).annotate({ description: "Authentication mode for OpenAI-backed providers." });
1490
+
1491
+export type ServerNotification__AutoReviewDecisionSource = "agent";
1492
+export const ServerNotification__AutoReviewDecisionSource = Schema.Literal("agent").annotate({
1493
+ description: "[UNSTABLE] Source that produced a terminal guardian approval review decision.",
1494
+});
1495
+
1496
+export type ServerNotification__CollabAgentStatus =
1497
+ | "pendingInit"
1498
+ | "running"
1499
+ | "interrupted"
1500
+ | "completed"
1501
+ | "errored"
1502
+ | "shutdown"
1503
+ | "notFound";
1504
+export const ServerNotification__CollabAgentStatus = Schema.Literals([
1505
+ "pendingInit",
1506
+ "running",
1507
+ "interrupted",
1508
+ "completed",
1509
+ "errored",
1510
+ "shutdown",
1511
+ "notFound",
1512
+]);
1513
+
1514
+export 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" };
1529
+export 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
+
1556
+export type ServerNotification__CommandExecOutputDeltaNotification = {
1557
+ readonly capReached: boolean;
1558
+ readonly deltaBase64: string;
1559
+ readonly processId: string;
1560
+ readonly stream: "stdout" | "stderr";
1561
+};
1562
+export 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
+
1580
+export type ServerNotification__CommandExecutionOutputDeltaNotification = {
1581
+ readonly delta: string;
1582
+ readonly itemId: string;
1583
+ readonly threadId: string;
1584
+ readonly turnId: string;
1585
+};
1586
+export const ServerNotification__CommandExecutionOutputDeltaNotification = Schema.Struct({
1587
+ delta: Schema.String,
1588
+ itemId: Schema.String,
1589
+ threadId: Schema.String,
1590
+ turnId: Schema.String,
1591
+});
1592
+
1593
+export type ServerNotification__CommandExecutionStatus =
1594
+ | "inProgress"
1595
+ | "completed"
1596
+ | "failed"
1597
+ | "declined";
1598
+export const ServerNotification__CommandExecutionStatus = Schema.Literals([
1599
+ "inProgress",
1600
+ "completed",
1601
+ "failed",
1602
+ "declined",
1603
+]);
1604
+
1605
+export type ServerNotification__ContextCompactedNotification = {
1606
+ readonly threadId: string;
1607
+ readonly turnId: string;
1608
+};
1609
+export const ServerNotification__ContextCompactedNotification = Schema.Struct({
1610
+ threadId: Schema.String,
1611
+ turnId: Schema.String,
1612
+}).annotate({ description: "Deprecated: Use `ContextCompaction` item type instead." });
1613
+
1614
+export type ServerNotification__CreditsSnapshot = {
1615
+ readonly balance?: string | null;
1616
+ readonly hasCredits: boolean;
1617
+ readonly unlimited: boolean;
1618
+};
1619
+export 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
+
1625
+export type ServerNotification__DeprecationNoticeNotification = {
1626
+ readonly details?: string | null;
1627
+ readonly summary: string;
1628
+};
1629
+export 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
+
1641
+export type ServerNotification__DynamicToolCallOutputContentItem =
1642
+ | { readonly text: string; readonly type: "inputText" }
1643
+ | { readonly imageUrl: string; readonly type: "inputImage" };
1644
+export 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
+
1662
+export type ServerNotification__DynamicToolCallStatus = "inProgress" | "completed" | "failed";
1663
+export const ServerNotification__DynamicToolCallStatus = Schema.Literals([
1664
+ "inProgress",
1665
+ "completed",
1666
+ "failed",
1667
+]);
1668
+
1669
+export type ServerNotification__FileChangeOutputDeltaNotification = {
1670
+ readonly delta: string;
1671
+ readonly itemId: string;
1672
+ readonly threadId: string;
1673
+ readonly turnId: string;
1674
+};
1675
+export const ServerNotification__FileChangeOutputDeltaNotification = Schema.Struct({
1676
+ delta: Schema.String,
1677
+ itemId: Schema.String,
1678
+ threadId: Schema.String,
1679
+ turnId: Schema.String,
1680
+});
1681
+
1682
+export type ServerNotification__FuzzyFileSearchMatchType = "file" | "directory";
1683
+export const ServerNotification__FuzzyFileSearchMatchType = Schema.Literals(["file", "directory"]);
1684
+
1685
+export type ServerNotification__FuzzyFileSearchSessionCompletedNotification = {
1686
+ readonly sessionId: string;
1687
+};
1688
+export const ServerNotification__FuzzyFileSearchSessionCompletedNotification = Schema.Struct({
1689
+ sessionId: Schema.String,
1690
+});
1691
+
1692
+export type ServerNotification__GitInfo = {
1693
+ readonly branch?: string | null;
1694
+ readonly originUrl?: string | null;
1695
+ readonly sha?: string | null;
1696
+};
1697
+export 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
+
1703
+export type ServerNotification__GuardianApprovalReviewStatus =
1704
+ | "inProgress"
1705
+ | "approved"
1706
+ | "denied"
1707
+ | "timedOut"
1708
+ | "aborted";
1709
+export 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
+
1717
+export type ServerNotification__GuardianCommandSource = "shell" | "unifiedExec";
1718
+export const ServerNotification__GuardianCommandSource = Schema.Literals(["shell", "unifiedExec"]);
1719
+
1720
+export type ServerNotification__GuardianRiskLevel = "low" | "medium" | "high" | "critical";
1721
+export 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
+
1728
+export type ServerNotification__GuardianUserAuthorization = "unknown" | "low" | "medium" | "high";
1729
+export 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
+
1738
+export type ServerNotification__HookEventName =
1739
+ | "preToolUse"
1740
+ | "postToolUse"
1741
+ | "sessionStart"
1742
+ | "userPromptSubmit"
1743
+ | "stop";
1744
+export const ServerNotification__HookEventName = Schema.Literals([
1745
+ "preToolUse",
1746
+ "postToolUse",
1747
+ "sessionStart",
1748
+ "userPromptSubmit",
1749
+ "stop",
1750
+]);
1751
+
1752
+export type ServerNotification__HookExecutionMode = "sync" | "async";
1753
+export const ServerNotification__HookExecutionMode = Schema.Literals(["sync", "async"]);
1754
+
1755
+export type ServerNotification__HookHandlerType = "command" | "prompt" | "agent";
1756
+export const ServerNotification__HookHandlerType = Schema.Literals(["command", "prompt", "agent"]);
1757
+
1758
+export type ServerNotification__HookOutputEntryKind =
1759
+ | "warning"
1760
+ | "stop"
1761
+ | "feedback"
1762
+ | "context"
1763
+ | "error";
1764
+export const ServerNotification__HookOutputEntryKind = Schema.Literals([
1765
+ "warning",
1766
+ "stop",
1767
+ "feedback",
1768
+ "context",
1769
+ "error",
1770
+]);
1771
+
1772
+export type ServerNotification__HookPromptFragment = {
1773
+ readonly hookRunId: string;
1774
+ readonly text: string;
1775
+};
1776
+export const ServerNotification__HookPromptFragment = Schema.Struct({
1777
+ hookRunId: Schema.String,
1778
+ text: Schema.String,
1779
+});
1780
+
1781
+export type ServerNotification__HookRunStatus =
1782
+ | "running"
1783
+ | "completed"
1784
+ | "failed"
1785
+ | "blocked"
1786
+ | "stopped";
1787
+export const ServerNotification__HookRunStatus = Schema.Literals([
1788
+ "running",
1789
+ "completed",
1790
+ "failed",
1791
+ "blocked",
1792
+ "stopped",
1793
+]);
1794
+
1795
+export type ServerNotification__HookScope = "thread" | "turn";
1796
+export const ServerNotification__HookScope = Schema.Literals(["thread", "turn"]);
1797
+
1798
+export type ServerNotification__McpServerOauthLoginCompletedNotification = {
1799
+ readonly error?: string | null;
1800
+ readonly name: string;
1801
+ readonly success: boolean;
1802
+};
1803
+export 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
+
1809
+export type ServerNotification__McpServerStartupState =
1810
+ | "starting"
1811
+ | "ready"
1812
+ | "failed"
1813
+ | "cancelled";
1814
+export const ServerNotification__McpServerStartupState = Schema.Literals([
1815
+ "starting",
1816
+ "ready",
1817
+ "failed",
1818
+ "cancelled",
1819
+]);
1820
+
1821
+export type ServerNotification__McpToolCallError = { readonly message: string };
1822
+export const ServerNotification__McpToolCallError = Schema.Struct({ message: Schema.String });
1823
+
1824
+export type ServerNotification__McpToolCallProgressNotification = {
1825
+ readonly itemId: string;
1826
+ readonly message: string;
1827
+ readonly threadId: string;
1828
+ readonly turnId: string;
1829
+};
1830
+export const ServerNotification__McpToolCallProgressNotification = Schema.Struct({
1831
+ itemId: Schema.String,
1832
+ message: Schema.String,
1833
+ threadId: Schema.String,
1834
+ turnId: Schema.String,
1835
+});
1836
+
1837
+export type ServerNotification__McpToolCallResult = {
1838
+ readonly _meta?: unknown;
1839
+ readonly content: ReadonlyArray<unknown>;
1840
+ readonly structuredContent?: unknown;
1841
+};
1842
+export 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
+
1848
+export type ServerNotification__McpToolCallStatus = "inProgress" | "completed" | "failed";
1849
+export const ServerNotification__McpToolCallStatus = Schema.Literals([
1850
+ "inProgress",
1851
+ "completed",
1852
+ "failed",
1853
+]);
1854
+
1855
+export type ServerNotification__MemoryCitationEntry = {
1856
+ readonly lineEnd: number;
1857
+ readonly lineStart: number;
1858
+ readonly note: string;
1859
+ readonly path: string;
1860
+};
1861
+export 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
+
1872
+export type ServerNotification__MessagePhase = "commentary" | "final_answer";
1873
+export 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
+
1881
+export type ServerNotification__ModelRerouteReason = "highRiskCyberActivity";
1882
+export const ServerNotification__ModelRerouteReason = Schema.Literal("highRiskCyberActivity");
1883
+
1884
+export type ServerNotification__NetworkApprovalProtocol =
1885
+ | "http"
1886
+ | "https"
1887
+ | "socks5Tcp"
1888
+ | "socks5Udp";
1889
+export const ServerNotification__NetworkApprovalProtocol = Schema.Literals([
1890
+ "http",
1891
+ "https",
1892
+ "socks5Tcp",
1893
+ "socks5Udp",
1894
+]);
1895
+
1896
+export type ServerNotification__NonSteerableTurnKind = "review" | "compact";
1897
+export const ServerNotification__NonSteerableTurnKind = Schema.Literals(["review", "compact"]);
1898
+
1899
+export type ServerNotification__PatchApplyStatus =
1900
+ | "inProgress"
1901
+ | "completed"
1902
+ | "failed"
1903
+ | "declined";
1904
+export const ServerNotification__PatchApplyStatus = Schema.Literals([
1905
+ "inProgress",
1906
+ "completed",
1907
+ "failed",
1908
+ "declined",
1909
+]);
1910
+
1911
+export type ServerNotification__PatchChangeKind =
1912
+ | { readonly type: "add" }
1913
+ | { readonly type: "delete" }
1914
+ | { readonly move_path?: string | null; readonly type: "update" };
1915
+export 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
+
1931
+export type ServerNotification__PlanDeltaNotification = {
1932
+ readonly delta: string;
1933
+ readonly itemId: string;
1934
+ readonly threadId: string;
1935
+ readonly turnId: string;
1936
+};
1937
+export 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
+
1947
+export 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";
1959
+export 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
+
1973
+export type ServerNotification__RateLimitWindow = {
1974
+ readonly resetsAt?: number | null;
1975
+ readonly usedPercent: number;
1976
+ readonly windowDurationMins?: number | null;
1977
+};
1978
+export 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
+
1988
+export type ServerNotification__RealtimeConversationVersion = "v1" | "v2";
1989
+export const ServerNotification__RealtimeConversationVersion = Schema.Literals(["v1", "v2"]);
1990
+
1991
+export type ServerNotification__ReasoningEffort =
1992
+ | "none"
1993
+ | "minimal"
1994
+ | "low"
1995
+ | "medium"
1996
+ | "high"
1997
+ | "xhigh";
1998
+export 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
+
2010
+export type ServerNotification__ReasoningSummaryPartAddedNotification = {
2011
+ readonly itemId: string;
2012
+ readonly summaryIndex: number;
2013
+ readonly threadId: string;
2014
+ readonly turnId: string;
2015
+};
2016
+export 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
+
2023
+export type ServerNotification__ReasoningSummaryTextDeltaNotification = {
2024
+ readonly delta: string;
2025
+ readonly itemId: string;
2026
+ readonly summaryIndex: number;
2027
+ readonly threadId: string;
2028
+ readonly turnId: string;
2029
+};
2030
+export 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
+
2038
+export type ServerNotification__ReasoningTextDeltaNotification = {
2039
+ readonly contentIndex: number;
2040
+ readonly delta: string;
2041
+ readonly itemId: string;
2042
+ readonly threadId: string;
2043
+ readonly turnId: string;
2044
+};
2045
+export 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
+
2053
+export type ServerNotification__RequestId = string | number;
2054
+export const ServerNotification__RequestId = Schema.Union([
2055
+ Schema.String,
2056
+ Schema.Number.annotate({ format: "int64" }).check(Schema.isInt()),
2057
+]);
2058
+
2059
+export type ServerNotification__SkillsChangedNotification = {};
2060
+export 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
+
2065
+export type ServerNotification__TerminalInteractionNotification = {
2066
+ readonly itemId: string;
2067
+ readonly processId: string;
2068
+ readonly stdin: string;
2069
+ readonly threadId: string;
2070
+ readonly turnId: string;
2071
+};
2072
+export 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
+
2080
+export type ServerNotification__TextElement = {
2081
+ readonly byteRange: { readonly end: number; readonly start: number };
2082
+ readonly placeholder?: string | null;
2083
+};
2084
+export 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
+
2105
+export type ServerNotification__TextPosition = { readonly column: number; readonly line: number };
2106
+export 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
+
2118
+export type ServerNotification__ThreadActiveFlag = "waitingOnApproval" | "waitingOnUserInput";
2119
+export const ServerNotification__ThreadActiveFlag = Schema.Literals([
2120
+ "waitingOnApproval",
2121
+ "waitingOnUserInput",
2122
+]);
2123
+
2124
+export type ServerNotification__ThreadArchivedNotification = { readonly threadId: string };
2125
+export const ServerNotification__ThreadArchivedNotification = Schema.Struct({
2126
+ threadId: Schema.String,
2127
+});
2128
+
2129
+export type ServerNotification__ThreadClosedNotification = { readonly threadId: string };
2130
+export const ServerNotification__ThreadClosedNotification = Schema.Struct({
2131
+ threadId: Schema.String,
2132
+});
2133
+
2134
+export type ServerNotification__ThreadId = string;
2135
+export const ServerNotification__ThreadId = Schema.String;
2136
+
2137
+export type ServerNotification__ThreadNameUpdatedNotification = {
2138
+ readonly threadId: string;
2139
+ readonly threadName?: string | null;
2140
+};
2141
+export const ServerNotification__ThreadNameUpdatedNotification = Schema.Struct({
2142
+ threadId: Schema.String,
2143
+ threadName: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
2144
+});
2145
+
2146
+export 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
+};
2153
+export 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
+
2172
+export type ServerNotification__ThreadRealtimeClosedNotification = {
2173
+ readonly reason?: string | null;
2174
+ readonly threadId: string;
2175
+};
2176
+export 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
+
2181
+export type ServerNotification__ThreadRealtimeErrorNotification = {
2182
+ readonly message: string;
2183
+ readonly threadId: string;
2184
+};
2185
+export 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
+
2190
+export type ServerNotification__ThreadRealtimeItemAddedNotification = {
2191
+ readonly item: unknown;
2192
+ readonly threadId: string;
2193
+};
2194
+export 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
+
2201
+export type ServerNotification__ThreadRealtimeSdpNotification = {
2202
+ readonly sdp: string;
2203
+ readonly threadId: string;
2204
+};
2205
+export 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
+
2212
+export type ServerNotification__ThreadRealtimeTranscriptUpdatedNotification = {
2213
+ readonly role: string;
2214
+ readonly text: string;
2215
+ readonly threadId: string;
2216
+};
2217
+export 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
+
2226
+export type ServerNotification__ThreadUnarchivedNotification = { readonly threadId: string };
2227
+export const ServerNotification__ThreadUnarchivedNotification = Schema.Struct({
2228
+ threadId: Schema.String,
2229
+});
2230
+
2231
+export type ServerNotification__TokenUsageBreakdown = {
2232
+ readonly cachedInputTokens: number;
2233
+ readonly inputTokens: number;
2234
+ readonly outputTokens: number;
2235
+ readonly reasoningOutputTokens: number;
2236
+ readonly totalTokens: number;
2237
+};
2238
+export 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
+
2246
+export type ServerNotification__TurnDiffUpdatedNotification = {
2247
+ readonly diff: string;
2248
+ readonly threadId: string;
2249
+ readonly turnId: string;
2250
+};
2251
+export 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
+
2260
+export type ServerNotification__TurnPlanStepStatus = "pending" | "inProgress" | "completed";
2261
+export const ServerNotification__TurnPlanStepStatus = Schema.Literals([
2262
+ "pending",
2263
+ "inProgress",
2264
+ "completed",
2265
+]);
2266
+
2267
+export type ServerNotification__TurnStatus = "completed" | "interrupted" | "failed" | "inProgress";
2268
+export const ServerNotification__TurnStatus = Schema.Literals([
2269
+ "completed",
2270
+ "interrupted",
2271
+ "failed",
2272
+ "inProgress",
2273
+]);
2274
+
2275
+export 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" };
2284
+export 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
+
2307
+export type ServerNotification__WindowsSandboxSetupMode = "elevated" | "unelevated";
2308
+export const ServerNotification__WindowsSandboxSetupMode = Schema.Literals([
2309
+ "elevated",
2310
+ "unelevated",
2311
+]);
2312
+
2313
+export type ServerNotification__WindowsWorldWritableWarningNotification = {
2314
+ readonly extraCount: number;
2315
+ readonly failedScan: boolean;
2316
+ readonly samplePaths: ReadonlyArray<string>;
2317
+};
2318
+export 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
+
2326
+export type ServerRequest__AbsolutePathBuf = string;
2327
+export 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
+
2332
+export type ServerRequest__AdditionalNetworkPermissions = { readonly enabled?: boolean | null };
2333
+export const ServerRequest__AdditionalNetworkPermissions = Schema.Struct({
2334
+ enabled: Schema.optionalKey(Schema.Union([Schema.Boolean, Schema.Null])),
2335
+});
2336
+
2337
+export type ServerRequest__ChatgptAuthTokensRefreshReason = "unauthorized";
2338
+export const ServerRequest__ChatgptAuthTokensRefreshReason = Schema.Literal("unauthorized");
2339
+
2340
+export 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" };
2355
+export 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
+
2382
+export type ServerRequest__DynamicToolCallParams = {
2383
+ readonly arguments: unknown;
2384
+ readonly callId: string;
2385
+ readonly threadId: string;
2386
+ readonly tool: string;
2387
+ readonly turnId: string;
2388
+};
2389
+export 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
+
2397
+export 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 };
2401
+export 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
+
2420
+export 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
+};
2427
+export 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
+
2450
+export type ServerRequest__McpElicitationArrayType = "array";
2451
+export const ServerRequest__McpElicitationArrayType = Schema.Literal("array");
2452
+
2453
+export type ServerRequest__McpElicitationBooleanType = "boolean";
2454
+export const ServerRequest__McpElicitationBooleanType = Schema.Literal("boolean");
2455
+
2456
+export type ServerRequest__McpElicitationConstOption = {
2457
+ readonly const: string;
2458
+ readonly title: string;
2459
+};
2460
+export const ServerRequest__McpElicitationConstOption = Schema.Struct({
2461
+ const: Schema.String,
2462
+ title: Schema.String,
2463
+});
2464
+
2465
+export type ServerRequest__McpElicitationNumberType = "number" | "integer";
2466
+export const ServerRequest__McpElicitationNumberType = Schema.Literals(["number", "integer"]);
2467
+
2468
+export type ServerRequest__McpElicitationObjectType = "object";
2469
+export const ServerRequest__McpElicitationObjectType = Schema.Literal("object");
2470
+
2471
+export type ServerRequest__McpElicitationStringFormat = "email" | "uri" | "date" | "date-time";
2472
+export const ServerRequest__McpElicitationStringFormat = Schema.Literals([
2473
+ "email",
2474
+ "uri",
2475
+ "date",
2476
+ "date-time",
2477
+]);
2478
+
2479
+export type ServerRequest__McpElicitationStringType = "string";
2480
+export const ServerRequest__McpElicitationStringType = Schema.Literal("string");
2481
+
2482
+export type ServerRequest__NetworkApprovalProtocol = "http" | "https" | "socks5Tcp" | "socks5Udp";
2483
+export const ServerRequest__NetworkApprovalProtocol = Schema.Literals([
2484
+ "http",
2485
+ "https",
2486
+ "socks5Tcp",
2487
+ "socks5Udp",
2488
+]);
2489
+
2490
+export type ServerRequest__NetworkPolicyRuleAction = "allow" | "deny";
2491
+export const ServerRequest__NetworkPolicyRuleAction = Schema.Literals(["allow", "deny"]);
2492
+
2493
+export 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" };
2503
+export 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
+
2533
+export type ServerRequest__RequestId = string | number;
2534
+export const ServerRequest__RequestId = Schema.Union([
2535
+ Schema.String,
2536
+ Schema.Number.annotate({ format: "int64" }).check(Schema.isInt()),
2537
+]);
2538
+
2539
+export type ServerRequest__ThreadId = string;
2540
+export const ServerRequest__ThreadId = Schema.String;
2541
+
2542
+export type ServerRequest__ToolRequestUserInputOption = {
2543
+ readonly description: string;
2544
+ readonly label: string;
2545
+};
2546
+export 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
+
2553
+export type ToolRequestUserInputParams__ToolRequestUserInputOption = {
2554
+ readonly description: string;
2555
+ readonly label: string;
2556
+};
2557
+export 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
+
2564
+export type ToolRequestUserInputResponse__ToolRequestUserInputAnswer = {
2565
+ readonly answers: ReadonlyArray<string>;
2566
+};
2567
+export 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
+
2573
+export type V1InitializeParams__ClientInfo = {
2574
+ readonly name: string;
2575
+ readonly title?: string | null;
2576
+ readonly version: string;
2577
+};
2578
+export 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
+
2584
+export type V1InitializeParams__InitializeCapabilities = {
2585
+ readonly experimentalApi?: boolean;
2586
+ readonly optOutNotificationMethods?: ReadonlyArray<string> | null;
2587
+};
2588
+export 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
+
2606
+export type V2AccountRateLimitsUpdatedNotification__CreditsSnapshot = {
2607
+ readonly balance?: string | null;
2608
+ readonly hasCredits: boolean;
2609
+ readonly unlimited: boolean;
2610
+};
2611
+export 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
+
2617
+export 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";
2629
+export 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
+
2643
+export type V2AccountRateLimitsUpdatedNotification__RateLimitWindow = {
2644
+ readonly resetsAt?: number | null;
2645
+ readonly usedPercent: number;
2646
+ readonly windowDurationMins?: number | null;
2647
+};
2648
+export 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
+
2658
+export type V2AccountUpdatedNotification__AuthMode = "apikey" | "chatgpt" | "chatgptAuthTokens";
2659
+export const V2AccountUpdatedNotification__AuthMode = Schema.Literals([
2660
+ "apikey",
2661
+ "chatgpt",
2662
+ "chatgptAuthTokens",
2663
+]).annotate({ description: "Authentication mode for OpenAI-backed providers." });
2664
+
2665
+export 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";
2677
+export 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
+
2691
+export 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
+};
2699
+export 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
+
2708
+export type V2AppListUpdatedNotification__AppReview = { readonly status: string };
2709
+export const V2AppListUpdatedNotification__AppReview = Schema.Struct({ status: Schema.String });
2710
+
2711
+export type V2AppListUpdatedNotification__AppScreenshot = {
2712
+ readonly fileId?: string | null;
2713
+ readonly url?: string | null;
2714
+ readonly userPrompt: string;
2715
+};
2716
+export 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
+
2722
+export 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
+};
2730
+export 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
+
2739
+export type V2AppsListResponse__AppReview = { readonly status: string };
2740
+export const V2AppsListResponse__AppReview = Schema.Struct({ status: Schema.String });
2741
+
2742
+export type V2AppsListResponse__AppScreenshot = {
2743
+ readonly fileId?: string | null;
2744
+ readonly url?: string | null;
2745
+ readonly userPrompt: string;
2746
+};
2747
+export 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
+
2753
+export type V2CancelLoginAccountResponse__CancelLoginAccountStatus = "canceled" | "notFound";
2754
+export const V2CancelLoginAccountResponse__CancelLoginAccountStatus = Schema.Literals([
2755
+ "canceled",
2756
+ "notFound",
2757
+]);
2758
+
2759
+export type V2CommandExecParams__AbsolutePathBuf = string;
2760
+export 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
+
2765
+export type V2CommandExecParams__CommandExecTerminalSize = {
2766
+ readonly cols: number;
2767
+ readonly rows: number;
2768
+};
2769
+export 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
+
2784
+export type V2ConfigBatchWriteParams__MergeStrategy = "replace" | "upsert";
2785
+export const V2ConfigBatchWriteParams__MergeStrategy = Schema.Literals(["replace", "upsert"]);
2786
+
2787
+export type V2ConfigReadResponse__AbsolutePathBuf = string;
2788
+export 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
+
2793
+export type V2ConfigReadResponse__AnalyticsConfig = {
2794
+ readonly enabled?: boolean | null;
2795
+ readonly [x: string]: unknown;
2796
+};
2797
+export 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
+
2802
+export type V2ConfigReadResponse__AppToolApproval = "auto" | "prompt" | "approve";
2803
+export const V2ConfigReadResponse__AppToolApproval = Schema.Literals(["auto", "prompt", "approve"]);
2804
+
2805
+export type V2ConfigReadResponse__AppToolsConfig = {};
2806
+export const V2ConfigReadResponse__AppToolsConfig = Schema.Struct({});
2807
+
2808
+export type V2ConfigReadResponse__ApprovalsReviewer = "user" | "guardian_subagent";
2809
+export 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
+
2817
+export type V2ConfigReadResponse__AppsDefaultConfig = {
2818
+ readonly destructive_enabled?: boolean;
2819
+ readonly enabled?: boolean;
2820
+ readonly open_world_enabled?: boolean;
2821
+};
2822
+export 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
+
2828
+export 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
+ };
2842
+export 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
+
2858
+export type V2ConfigReadResponse__ForcedLoginMethod = "chatgpt" | "api";
2859
+export const V2ConfigReadResponse__ForcedLoginMethod = Schema.Literals(["chatgpt", "api"]);
2860
+
2861
+export type V2ConfigReadResponse__ReasoningEffort =
2862
+ | "none"
2863
+ | "minimal"
2864
+ | "low"
2865
+ | "medium"
2866
+ | "high"
2867
+ | "xhigh";
2868
+export 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
+
2880
+export type V2ConfigReadResponse__ReasoningSummary = "auto" | "concise" | "detailed" | "none";
2881
+export 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
+
2892
+export type V2ConfigReadResponse__SandboxMode =
2893
+ | "read-only"
2894
+ | "workspace-write"
2895
+ | "danger-full-access";
2896
+export const V2ConfigReadResponse__SandboxMode = Schema.Literals([
2897
+ "read-only",
2898
+ "workspace-write",
2899
+ "danger-full-access",
2900
+]);
2901
+
2902
+export 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
+};
2908
+export 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
+
2915
+export type V2ConfigReadResponse__ServiceTier = "fast" | "flex";
2916
+export const V2ConfigReadResponse__ServiceTier = Schema.Literals(["fast", "flex"]);
2917
+
2918
+export type V2ConfigReadResponse__Verbosity = "low" | "medium" | "high";
2919
+export 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
+
2924
+export type V2ConfigReadResponse__WebSearchContextSize = "low" | "medium" | "high";
2925
+export const V2ConfigReadResponse__WebSearchContextSize = Schema.Literals([
2926
+ "low",
2927
+ "medium",
2928
+ "high",
2929
+]);
2930
+
2931
+export type V2ConfigReadResponse__WebSearchLocation = {
2932
+ readonly city?: string | null;
2933
+ readonly country?: string | null;
2934
+ readonly region?: string | null;
2935
+ readonly timezone?: string | null;
2936
+};
2937
+export 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
+
2944
+export type V2ConfigReadResponse__WebSearchMode = "disabled" | "cached" | "live";
2945
+export const V2ConfigReadResponse__WebSearchMode = Schema.Literals(["disabled", "cached", "live"]);
2946
+
2947
+export 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
+ };
2961
+export 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
+
2977
+export type V2ConfigRequirementsReadResponse__NetworkDomainPermission = "allow" | "deny";
2978
+export const V2ConfigRequirementsReadResponse__NetworkDomainPermission = Schema.Literals([
2979
+ "allow",
2980
+ "deny",
2981
+]);
2982
+
2983
+export type V2ConfigRequirementsReadResponse__NetworkUnixSocketPermission = "allow" | "none";
2984
+export const V2ConfigRequirementsReadResponse__NetworkUnixSocketPermission = Schema.Literals([
2985
+ "allow",
2986
+ "none",
2987
+]);
2988
+
2989
+export type V2ConfigRequirementsReadResponse__ResidencyRequirement = "us";
2990
+export const V2ConfigRequirementsReadResponse__ResidencyRequirement = Schema.Literal("us");
2991
+
2992
+export type V2ConfigRequirementsReadResponse__SandboxMode =
2993
+ | "read-only"
2994
+ | "workspace-write"
2995
+ | "danger-full-access";
2996
+export const V2ConfigRequirementsReadResponse__SandboxMode = Schema.Literals([
2997
+ "read-only",
2998
+ "workspace-write",
2999
+ "danger-full-access",
3000
+]);
3001
+
3002
+export type V2ConfigRequirementsReadResponse__WebSearchMode = "disabled" | "cached" | "live";
3003
+export const V2ConfigRequirementsReadResponse__WebSearchMode = Schema.Literals([
3004
+ "disabled",
3005
+ "cached",
3006
+ "live",
3007
+]);
3008
+
3009
+export type V2ConfigValueWriteParams__MergeStrategy = "replace" | "upsert";
3010
+export const V2ConfigValueWriteParams__MergeStrategy = Schema.Literals(["replace", "upsert"]);
3011
+
3012
+export type V2ConfigWarningNotification__TextPosition = {
3013
+ readonly column: number;
3014
+ readonly line: number;
3015
+};
3016
+export 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
+
3028
+export type V2ConfigWriteResponse__AbsolutePathBuf = string;
3029
+export 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
+
3034
+export type V2ConfigWriteResponse__WriteStatus = "ok" | "okOverridden";
3035
+export const V2ConfigWriteResponse__WriteStatus = Schema.Literals(["ok", "okOverridden"]);
3036
+
3037
+export type V2ErrorNotification__NonSteerableTurnKind = "review" | "compact";
3038
+export const V2ErrorNotification__NonSteerableTurnKind = Schema.Literals(["review", "compact"]);
3039
+
3040
+export 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
+};
3049
+export 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
+
3091
+export type V2ExternalAgentConfigDetectResponse__ExternalAgentConfigMigrationItemType =
3092
+ | "AGENTS_MD"
3093
+ | "CONFIG"
3094
+ | "SKILLS"
3095
+ | "MCP_SERVER_CONFIG";
3096
+export const V2ExternalAgentConfigDetectResponse__ExternalAgentConfigMigrationItemType =
3097
+ Schema.Literals(["AGENTS_MD", "CONFIG", "SKILLS", "MCP_SERVER_CONFIG"]);
3098
+
3099
+export type V2ExternalAgentConfigImportParams__ExternalAgentConfigMigrationItemType =
3100
+ | "AGENTS_MD"
3101
+ | "CONFIG"
3102
+ | "SKILLS"
3103
+ | "MCP_SERVER_CONFIG";
3104
+export const V2ExternalAgentConfigImportParams__ExternalAgentConfigMigrationItemType =
3105
+ Schema.Literals(["AGENTS_MD", "CONFIG", "SKILLS", "MCP_SERVER_CONFIG"]);
3106
+
3107
+export type V2FsChangedNotification__AbsolutePathBuf = string;
3108
+export 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
+
3113
+export type V2FsReadDirectoryResponse__FsReadDirectoryEntry = {
3114
+ readonly fileName: string;
3115
+ readonly isDirectory: boolean;
3116
+ readonly isFile: boolean;
3117
+};
3118
+export 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
+
3130
+export type V2GetAccountRateLimitsResponse__CreditsSnapshot = {
3131
+ readonly balance?: string | null;
3132
+ readonly hasCredits: boolean;
3133
+ readonly unlimited: boolean;
3134
+};
3135
+export 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
+
3141
+export 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";
3153
+export 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
+
3167
+export type V2GetAccountRateLimitsResponse__RateLimitWindow = {
3168
+ readonly resetsAt?: number | null;
3169
+ readonly usedPercent: number;
3170
+ readonly windowDurationMins?: number | null;
3171
+};
3172
+export 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
+
3182
+export 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";
3194
+export 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
+
3208
+export type V2HookCompletedNotification__HookEventName =
3209
+ | "preToolUse"
3210
+ | "postToolUse"
3211
+ | "sessionStart"
3212
+ | "userPromptSubmit"
3213
+ | "stop";
3214
+export const V2HookCompletedNotification__HookEventName = Schema.Literals([
3215
+ "preToolUse",
3216
+ "postToolUse",
3217
+ "sessionStart",
3218
+ "userPromptSubmit",
3219
+ "stop",
3220
+]);
3221
+
3222
+export type V2HookCompletedNotification__HookExecutionMode = "sync" | "async";
3223
+export const V2HookCompletedNotification__HookExecutionMode = Schema.Literals(["sync", "async"]);
3224
+
3225
+export type V2HookCompletedNotification__HookHandlerType = "command" | "prompt" | "agent";
3226
+export const V2HookCompletedNotification__HookHandlerType = Schema.Literals([
3227
+ "command",
3228
+ "prompt",
3229
+ "agent",
3230
+]);
3231
+
3232
+export type V2HookCompletedNotification__HookOutputEntryKind =
3233
+ | "warning"
3234
+ | "stop"
3235
+ | "feedback"
3236
+ | "context"
3237
+ | "error";
3238
+export const V2HookCompletedNotification__HookOutputEntryKind = Schema.Literals([
3239
+ "warning",
3240
+ "stop",
3241
+ "feedback",
3242
+ "context",
3243
+ "error",
3244
+]);
3245
+
3246
+export type V2HookCompletedNotification__HookRunStatus =
3247
+ | "running"
3248
+ | "completed"
3249
+ | "failed"
3250
+ | "blocked"
3251
+ | "stopped";
3252
+export const V2HookCompletedNotification__HookRunStatus = Schema.Literals([
3253
+ "running",
3254
+ "completed",
3255
+ "failed",
3256
+ "blocked",
3257
+ "stopped",
3258
+]);
3259
+
3260
+export type V2HookCompletedNotification__HookScope = "thread" | "turn";
3261
+export const V2HookCompletedNotification__HookScope = Schema.Literals(["thread", "turn"]);
3262
+
3263
+export type V2HookStartedNotification__HookEventName =
3264
+ | "preToolUse"
3265
+ | "postToolUse"
3266
+ | "sessionStart"
3267
+ | "userPromptSubmit"
3268
+ | "stop";
3269
+export const V2HookStartedNotification__HookEventName = Schema.Literals([
3270
+ "preToolUse",
3271
+ "postToolUse",
3272
+ "sessionStart",
3273
+ "userPromptSubmit",
3274
+ "stop",
3275
+]);
3276
+
3277
+export type V2HookStartedNotification__HookExecutionMode = "sync" | "async";
3278
+export const V2HookStartedNotification__HookExecutionMode = Schema.Literals(["sync", "async"]);
3279
+
3280
+export type V2HookStartedNotification__HookHandlerType = "command" | "prompt" | "agent";
3281
+export const V2HookStartedNotification__HookHandlerType = Schema.Literals([
3282
+ "command",
3283
+ "prompt",
3284
+ "agent",
3285
+]);
3286
+
3287
+export type V2HookStartedNotification__HookOutputEntryKind =
3288
+ | "warning"
3289
+ | "stop"
3290
+ | "feedback"
3291
+ | "context"
3292
+ | "error";
3293
+export const V2HookStartedNotification__HookOutputEntryKind = Schema.Literals([
3294
+ "warning",
3295
+ "stop",
3296
+ "feedback",
3297
+ "context",
3298
+ "error",
3299
+]);
3300
+
3301
+export type V2HookStartedNotification__HookRunStatus =
3302
+ | "running"
3303
+ | "completed"
3304
+ | "failed"
3305
+ | "blocked"
3306
+ | "stopped";
3307
+export const V2HookStartedNotification__HookRunStatus = Schema.Literals([
3308
+ "running",
3309
+ "completed",
3310
+ "failed",
3311
+ "blocked",
3312
+ "stopped",
3313
+]);
3314
+
3315
+export type V2HookStartedNotification__HookScope = "thread" | "turn";
3316
+export const V2HookStartedNotification__HookScope = Schema.Literals(["thread", "turn"]);
3317
+
3318
+export type V2ItemCompletedNotification__CollabAgentStatus =
3319
+ | "pendingInit"
3320
+ | "running"
3321
+ | "interrupted"
3322
+ | "completed"
3323
+ | "errored"
3324
+ | "shutdown"
3325
+ | "notFound";
3326
+export const V2ItemCompletedNotification__CollabAgentStatus = Schema.Literals([
3327
+ "pendingInit",
3328
+ "running",
3329
+ "interrupted",
3330
+ "completed",
3331
+ "errored",
3332
+ "shutdown",
3333
+ "notFound",
3334
+]);
3335
+
3336
+export 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" };
3351
+export 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
+
3378
+export type V2ItemCompletedNotification__CommandExecutionStatus =
3379
+ | "inProgress"
3380
+ | "completed"
3381
+ | "failed"
3382
+ | "declined";
3383
+export const V2ItemCompletedNotification__CommandExecutionStatus = Schema.Literals([
3384
+ "inProgress",
3385
+ "completed",
3386
+ "failed",
3387
+ "declined",
3388
+]);
3389
+
3390
+export type V2ItemCompletedNotification__DynamicToolCallOutputContentItem =
3391
+ | { readonly text: string; readonly type: "inputText" }
3392
+ | { readonly imageUrl: string; readonly type: "inputImage" };
3393
+export 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
+
3411
+export type V2ItemCompletedNotification__DynamicToolCallStatus =
3412
+ | "inProgress"
3413
+ | "completed"
3414
+ | "failed";
3415
+export const V2ItemCompletedNotification__DynamicToolCallStatus = Schema.Literals([
3416
+ "inProgress",
3417
+ "completed",
3418
+ "failed",
3419
+]);
3420
+
3421
+export type V2ItemCompletedNotification__HookPromptFragment = {
3422
+ readonly hookRunId: string;
3423
+ readonly text: string;
3424
+};
3425
+export const V2ItemCompletedNotification__HookPromptFragment = Schema.Struct({
3426
+ hookRunId: Schema.String,
3427
+ text: Schema.String,
3428
+});
3429
+
3430
+export type V2ItemCompletedNotification__McpToolCallError = { readonly message: string };
3431
+export const V2ItemCompletedNotification__McpToolCallError = Schema.Struct({
3432
+ message: Schema.String,
3433
+});
3434
+
3435
+export type V2ItemCompletedNotification__McpToolCallResult = {
3436
+ readonly _meta?: unknown;
3437
+ readonly content: ReadonlyArray<unknown>;
3438
+ readonly structuredContent?: unknown;
3439
+};
3440
+export 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
+
3446
+export type V2ItemCompletedNotification__McpToolCallStatus = "inProgress" | "completed" | "failed";
3447
+export const V2ItemCompletedNotification__McpToolCallStatus = Schema.Literals([
3448
+ "inProgress",
3449
+ "completed",
3450
+ "failed",
3451
+]);
3452
+
3453
+export type V2ItemCompletedNotification__MemoryCitationEntry = {
3454
+ readonly lineEnd: number;
3455
+ readonly lineStart: number;
3456
+ readonly note: string;
3457
+ readonly path: string;
3458
+};
3459
+export 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
+
3470
+export type V2ItemCompletedNotification__MessagePhase = "commentary" | "final_answer";
3471
+export 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
+
3479
+export type V2ItemCompletedNotification__PatchApplyStatus =
3480
+ | "inProgress"
3481
+ | "completed"
3482
+ | "failed"
3483
+ | "declined";
3484
+export const V2ItemCompletedNotification__PatchApplyStatus = Schema.Literals([
3485
+ "inProgress",
3486
+ "completed",
3487
+ "failed",
3488
+ "declined",
3489
+]);
3490
+
3491
+export type V2ItemCompletedNotification__PatchChangeKind =
3492
+ | { readonly type: "add" }
3493
+ | { readonly type: "delete" }
3494
+ | { readonly move_path?: string | null; readonly type: "update" };
3495
+export 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
+
3511
+export type V2ItemCompletedNotification__ReasoningEffort =
3512
+ | "none"
3513
+ | "minimal"
3514
+ | "low"
3515
+ | "medium"
3516
+ | "high"
3517
+ | "xhigh";
3518
+export 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
+
3530
+export type V2ItemCompletedNotification__TextElement = {
3531
+ readonly byteRange: { readonly end: number; readonly start: number };
3532
+ readonly placeholder?: string | null;
3533
+};
3534
+export 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
+
3555
+export 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" };
3564
+export 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
+
3587
+export type V2ItemGuardianApprovalReviewCompletedNotification__AutoReviewDecisionSource = "agent";
3588
+export const V2ItemGuardianApprovalReviewCompletedNotification__AutoReviewDecisionSource =
3589
+ Schema.Literal("agent").annotate({
3590
+ description: "[UNSTABLE] Source that produced a terminal guardian approval review decision.",
3591
+ });
3592
+
3593
+export type V2ItemGuardianApprovalReviewCompletedNotification__GuardianApprovalReviewStatus =
3594
+ | "inProgress"
3595
+ | "approved"
3596
+ | "denied"
3597
+ | "timedOut"
3598
+ | "aborted";
3599
+export const V2ItemGuardianApprovalReviewCompletedNotification__GuardianApprovalReviewStatus =
3600
+ Schema.Literals(["inProgress", "approved", "denied", "timedOut", "aborted"]).annotate({
3601
+ description: "[UNSTABLE] Lifecycle state for a guardian approval review.",
3602
+ });
3603
+
3604
+export type V2ItemGuardianApprovalReviewCompletedNotification__GuardianCommandSource =
3605
+ | "shell"
3606
+ | "unifiedExec";
3607
+export const V2ItemGuardianApprovalReviewCompletedNotification__GuardianCommandSource =
3608
+ Schema.Literals(["shell", "unifiedExec"]);
3609
+
3610
+export type V2ItemGuardianApprovalReviewCompletedNotification__GuardianRiskLevel =
3611
+ | "low"
3612
+ | "medium"
3613
+ | "high"
3614
+ | "critical";
3615
+export const V2ItemGuardianApprovalReviewCompletedNotification__GuardianRiskLevel = Schema.Literals(
3616
+ ["low", "medium", "high", "critical"],
3617
+).annotate({ description: "[UNSTABLE] Risk level assigned by guardian approval review." });
3618
+
3619
+export type V2ItemGuardianApprovalReviewCompletedNotification__GuardianUserAuthorization =
3620
+ | "unknown"
3621
+ | "low"
3622
+ | "medium"
3623
+ | "high";
3624
+export const V2ItemGuardianApprovalReviewCompletedNotification__GuardianUserAuthorization =
3625
+ Schema.Literals(["unknown", "low", "medium", "high"]).annotate({
3626
+ description: "[UNSTABLE] Authorization level assigned by guardian approval review.",
3627
+ });
3628
+
3629
+export type V2ItemGuardianApprovalReviewCompletedNotification__NetworkApprovalProtocol =
3630
+ | "http"
3631
+ | "https"
3632
+ | "socks5Tcp"
3633
+ | "socks5Udp";
3634
+export const V2ItemGuardianApprovalReviewCompletedNotification__NetworkApprovalProtocol =
3635
+ Schema.Literals(["http", "https", "socks5Tcp", "socks5Udp"]);
3636
+
3637
+export type V2ItemGuardianApprovalReviewStartedNotification__GuardianApprovalReviewStatus =
3638
+ | "inProgress"
3639
+ | "approved"
3640
+ | "denied"
3641
+ | "timedOut"
3642
+ | "aborted";
3643
+export const V2ItemGuardianApprovalReviewStartedNotification__GuardianApprovalReviewStatus =
3644
+ Schema.Literals(["inProgress", "approved", "denied", "timedOut", "aborted"]).annotate({
3645
+ description: "[UNSTABLE] Lifecycle state for a guardian approval review.",
3646
+ });
3647
+
3648
+export type V2ItemGuardianApprovalReviewStartedNotification__GuardianCommandSource =
3649
+ | "shell"
3650
+ | "unifiedExec";
3651
+export const V2ItemGuardianApprovalReviewStartedNotification__GuardianCommandSource =
3652
+ Schema.Literals(["shell", "unifiedExec"]);
3653
+
3654
+export type V2ItemGuardianApprovalReviewStartedNotification__GuardianRiskLevel =
3655
+ | "low"
3656
+ | "medium"
3657
+ | "high"
3658
+ | "critical";
3659
+export 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
+
3666
+export type V2ItemGuardianApprovalReviewStartedNotification__GuardianUserAuthorization =
3667
+ | "unknown"
3668
+ | "low"
3669
+ | "medium"
3670
+ | "high";
3671
+export const V2ItemGuardianApprovalReviewStartedNotification__GuardianUserAuthorization =
3672
+ Schema.Literals(["unknown", "low", "medium", "high"]).annotate({
3673
+ description: "[UNSTABLE] Authorization level assigned by guardian approval review.",
3674
+ });
3675
+
3676
+export type V2ItemGuardianApprovalReviewStartedNotification__NetworkApprovalProtocol =
3677
+ | "http"
3678
+ | "https"
3679
+ | "socks5Tcp"
3680
+ | "socks5Udp";
3681
+export const V2ItemGuardianApprovalReviewStartedNotification__NetworkApprovalProtocol =
3682
+ Schema.Literals(["http", "https", "socks5Tcp", "socks5Udp"]);
3683
+
3684
+export type V2ItemStartedNotification__CollabAgentStatus =
3685
+ | "pendingInit"
3686
+ | "running"
3687
+ | "interrupted"
3688
+ | "completed"
3689
+ | "errored"
3690
+ | "shutdown"
3691
+ | "notFound";
3692
+export const V2ItemStartedNotification__CollabAgentStatus = Schema.Literals([
3693
+ "pendingInit",
3694
+ "running",
3695
+ "interrupted",
3696
+ "completed",
3697
+ "errored",
3698
+ "shutdown",
3699
+ "notFound",
3700
+]);
3701
+
3702
+export 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" };
3717
+export 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
+
3744
+export type V2ItemStartedNotification__CommandExecutionStatus =
3745
+ | "inProgress"
3746
+ | "completed"
3747
+ | "failed"
3748
+ | "declined";
3749
+export const V2ItemStartedNotification__CommandExecutionStatus = Schema.Literals([
3750
+ "inProgress",
3751
+ "completed",
3752
+ "failed",
3753
+ "declined",
3754
+]);
3755
+
3756
+export type V2ItemStartedNotification__DynamicToolCallOutputContentItem =
3757
+ | { readonly text: string; readonly type: "inputText" }
3758
+ | { readonly imageUrl: string; readonly type: "inputImage" };
3759
+export 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
+
3777
+export type V2ItemStartedNotification__DynamicToolCallStatus =
3778
+ | "inProgress"
3779
+ | "completed"
3780
+ | "failed";
3781
+export const V2ItemStartedNotification__DynamicToolCallStatus = Schema.Literals([
3782
+ "inProgress",
3783
+ "completed",
3784
+ "failed",
3785
+]);
3786
+
3787
+export type V2ItemStartedNotification__HookPromptFragment = {
3788
+ readonly hookRunId: string;
3789
+ readonly text: string;
3790
+};
3791
+export const V2ItemStartedNotification__HookPromptFragment = Schema.Struct({
3792
+ hookRunId: Schema.String,
3793
+ text: Schema.String,
3794
+});
3795
+
3796
+export type V2ItemStartedNotification__McpToolCallError = { readonly message: string };
3797
+export const V2ItemStartedNotification__McpToolCallError = Schema.Struct({
3798
+ message: Schema.String,
3799
+});
3800
+
3801
+export type V2ItemStartedNotification__McpToolCallResult = {
3802
+ readonly _meta?: unknown;
3803
+ readonly content: ReadonlyArray<unknown>;
3804
+ readonly structuredContent?: unknown;
3805
+};
3806
+export 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
+
3812
+export type V2ItemStartedNotification__McpToolCallStatus = "inProgress" | "completed" | "failed";
3813
+export const V2ItemStartedNotification__McpToolCallStatus = Schema.Literals([
3814
+ "inProgress",
3815
+ "completed",
3816
+ "failed",
3817
+]);
3818
+
3819
+export type V2ItemStartedNotification__MemoryCitationEntry = {
3820
+ readonly lineEnd: number;
3821
+ readonly lineStart: number;
3822
+ readonly note: string;
3823
+ readonly path: string;
3824
+};
3825
+export 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
+
3836
+export type V2ItemStartedNotification__MessagePhase = "commentary" | "final_answer";
3837
+export 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
+
3845
+export type V2ItemStartedNotification__PatchApplyStatus =
3846
+ | "inProgress"
3847
+ | "completed"
3848
+ | "failed"
3849
+ | "declined";
3850
+export const V2ItemStartedNotification__PatchApplyStatus = Schema.Literals([
3851
+ "inProgress",
3852
+ "completed",
3853
+ "failed",
3854
+ "declined",
3855
+]);
3856
+
3857
+export type V2ItemStartedNotification__PatchChangeKind =
3858
+ | { readonly type: "add" }
3859
+ | { readonly type: "delete" }
3860
+ | { readonly move_path?: string | null; readonly type: "update" };
3861
+export 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
+
3877
+export type V2ItemStartedNotification__ReasoningEffort =
3878
+ | "none"
3879
+ | "minimal"
3880
+ | "low"
3881
+ | "medium"
3882
+ | "high"
3883
+ | "xhigh";
3884
+export 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
+
3896
+export type V2ItemStartedNotification__TextElement = {
3897
+ readonly byteRange: { readonly end: number; readonly start: number };
3898
+ readonly placeholder?: string | null;
3899
+};
3900
+export 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
+
3921
+export 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" };
3930
+export 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
+
3953
+export type V2ListMcpServerStatusParams__McpServerStatusDetail = "full" | "toolsAndAuthOnly";
3954
+export const V2ListMcpServerStatusParams__McpServerStatusDetail = Schema.Literals([
3955
+ "full",
3956
+ "toolsAndAuthOnly",
3957
+]);
3958
+
3959
+export type V2ListMcpServerStatusResponse__McpAuthStatus =
3960
+ | "unsupported"
3961
+ | "notLoggedIn"
3962
+ | "bearerToken"
3963
+ | "oAuth";
3964
+export const V2ListMcpServerStatusResponse__McpAuthStatus = Schema.Literals([
3965
+ "unsupported",
3966
+ "notLoggedIn",
3967
+ "bearerToken",
3968
+ "oAuth",
3969
+]);
3970
+
3971
+export 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
+};
3982
+export 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
+
3996
+export 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
+};
4004
+export 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
+
4013
+export 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
+};
4023
+export 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
+
4034
+export 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
+ };
4047
+export 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
+
4062
+export type V2McpServerStatusUpdatedNotification__McpServerStartupState =
4063
+ | "starting"
4064
+ | "ready"
4065
+ | "failed"
4066
+ | "cancelled";
4067
+export const V2McpServerStatusUpdatedNotification__McpServerStartupState = Schema.Literals([
4068
+ "starting",
4069
+ "ready",
4070
+ "failed",
4071
+ "cancelled",
4072
+]);
4073
+
4074
+export type V2ModelListResponse__InputModality = "text" | "image";
4075
+export const V2ModelListResponse__InputModality = Schema.Literals(["text", "image"]).annotate({
4076
+ description: "Canonical user-input modality tags advertised by a model.",
4077
+});
4078
+
4079
+export type V2ModelListResponse__ModelAvailabilityNux = { readonly message: string };
4080
+export const V2ModelListResponse__ModelAvailabilityNux = Schema.Struct({ message: Schema.String });
4081
+
4082
+export type V2ModelListResponse__ModelUpgradeInfo = {
4083
+ readonly migrationMarkdown?: string | null;
4084
+ readonly model: string;
4085
+ readonly modelLink?: string | null;
4086
+ readonly upgradeCopy?: string | null;
4087
+};
4088
+export 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
+
4095
+export type V2ModelListResponse__ReasoningEffort =
4096
+ | "none"
4097
+ | "minimal"
4098
+ | "low"
4099
+ | "medium"
4100
+ | "high"
4101
+ | "xhigh";
4102
+export 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
+
4114
+export type V2ModelReroutedNotification__ModelRerouteReason = "highRiskCyberActivity";
4115
+export const V2ModelReroutedNotification__ModelRerouteReason =
4116
+ Schema.Literal("highRiskCyberActivity");
4117
+
4118
+export type V2PluginInstallParams__AbsolutePathBuf = string;
4119
+export 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
+
4124
+export 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
+};
4131
+export 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
+
4139
+export type V2PluginInstallResponse__PluginAuthPolicy = "ON_INSTALL" | "ON_USE";
4140
+export const V2PluginInstallResponse__PluginAuthPolicy = Schema.Literals(["ON_INSTALL", "ON_USE"]);
4141
+
4142
+export type V2PluginListParams__AbsolutePathBuf = string;
4143
+export 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
+
4148
+export type V2PluginListResponse__AbsolutePathBuf = string;
4149
+export 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
+
4154
+export type V2PluginListResponse__MarketplaceInterface = { readonly displayName?: string | null };
4155
+export const V2PluginListResponse__MarketplaceInterface = Schema.Struct({
4156
+ displayName: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),
4157
+});
4158
+
4159
+export type V2PluginListResponse__PluginAuthPolicy = "ON_INSTALL" | "ON_USE";
4160
+export const V2PluginListResponse__PluginAuthPolicy = Schema.Literals(["ON_INSTALL", "ON_USE"]);
4161
+
4162
+export type V2PluginListResponse__PluginInstallPolicy =
4163
+ | "NOT_AVAILABLE"
4164
+ | "AVAILABLE"
4165
+ | "INSTALLED_BY_DEFAULT";
4166
+export const V2PluginListResponse__PluginInstallPolicy = Schema.Literals([
4167
+ "NOT_AVAILABLE",
4168
+ "AVAILABLE",
4169
+ "INSTALLED_BY_DEFAULT",
4170
+]);
4171
+
4172
+export type V2PluginReadParams__AbsolutePathBuf = string;
4173
+export 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
+
4178
+export type V2PluginReadResponse__AbsolutePathBuf = string;
4179
+export 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
+
4184
+export 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
+};
4191
+export 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
+
4199
+export type V2PluginReadResponse__PluginAuthPolicy = "ON_INSTALL" | "ON_USE";
4200
+export const V2PluginReadResponse__PluginAuthPolicy = Schema.Literals(["ON_INSTALL", "ON_USE"]);
4201
+
4202
+export type V2PluginReadResponse__PluginInstallPolicy =
4203
+ | "NOT_AVAILABLE"
4204
+ | "AVAILABLE"
4205
+ | "INSTALLED_BY_DEFAULT";
4206
+export const V2PluginReadResponse__PluginInstallPolicy = Schema.Literals([
4207
+ "NOT_AVAILABLE",
4208
+ "AVAILABLE",
4209
+ "INSTALLED_BY_DEFAULT",
4210
+]);
4211
+
4212
+export 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
+};
4220
+export 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
+
4229
+export 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" };
4233
+export 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
+
4251
+export 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
+};
4257
+export 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
+
4264
+export type V2RawResponseItemCompletedNotification__ImageDetail =
4265
+ | "auto"
4266
+ | "low"
4267
+ | "high"
4268
+ | "original";
4269
+export const V2RawResponseItemCompletedNotification__ImageDetail = Schema.Literals([
4270
+ "auto",
4271
+ "low",
4272
+ "high",
4273
+ "original",
4274
+]);
4275
+
4276
+export 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
+};
4284
+export 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
+
4307
+export type V2RawResponseItemCompletedNotification__LocalShellStatus =
4308
+ | "completed"
4309
+ | "in_progress"
4310
+ | "incomplete";
4311
+export const V2RawResponseItemCompletedNotification__LocalShellStatus = Schema.Literals([
4312
+ "completed",
4313
+ "in_progress",
4314
+ "incomplete",
4315
+]);
4316
+
4317
+export type V2RawResponseItemCompletedNotification__MessagePhase = "commentary" | "final_answer";
4318
+export 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
+
4326
+export type V2RawResponseItemCompletedNotification__ReasoningItemContent =
4327
+ | { readonly text: string; readonly type: "reasoning_text" }
4328
+ | { readonly text: string; readonly type: "text" };
4329
+export 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
+
4345
+export type V2RawResponseItemCompletedNotification__ReasoningItemReasoningSummary = {
4346
+ readonly text: string;
4347
+ readonly type: "summary_text";
4348
+};
4349
+export 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
+
4361
+export 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" };
4374
+export 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
+
4401
+export type V2ReviewStartParams__ReviewDelivery = "inline" | "detached";
4402
+export const V2ReviewStartParams__ReviewDelivery = Schema.Literals(["inline", "detached"]);
4403
+
4404
+export 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" };
4409
+export 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
+
4452
+export type V2ReviewStartResponse__CollabAgentStatus =
4453
+ | "pendingInit"
4454
+ | "running"
4455
+ | "interrupted"
4456
+ | "completed"
4457
+ | "errored"
4458
+ | "shutdown"
4459
+ | "notFound";
4460
+export const V2ReviewStartResponse__CollabAgentStatus = Schema.Literals([
4461
+ "pendingInit",
4462
+ "running",
4463
+ "interrupted",
4464
+ "completed",
4465
+ "errored",
4466
+ "shutdown",
4467
+ "notFound",
4468
+]);
4469
+
4470
+export 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" };
4485
+export 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
+
4512
+export type V2ReviewStartResponse__CommandExecutionStatus =
4513
+ | "inProgress"
4514
+ | "completed"
4515
+ | "failed"
4516
+ | "declined";
4517
+export const V2ReviewStartResponse__CommandExecutionStatus = Schema.Literals([
4518
+ "inProgress",
4519
+ "completed",
4520
+ "failed",
4521
+ "declined",
4522
+]);
4523
+
4524
+export type V2ReviewStartResponse__DynamicToolCallOutputContentItem =
4525
+ | { readonly text: string; readonly type: "inputText" }
4526
+ | { readonly imageUrl: string; readonly type: "inputImage" };
4527
+export 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
+
4545
+export type V2ReviewStartResponse__DynamicToolCallStatus = "inProgress" | "completed" | "failed";
4546
+export const V2ReviewStartResponse__DynamicToolCallStatus = Schema.Literals([
4547
+ "inProgress",
4548
+ "completed",
4549
+ "failed",
4550
+]);
4551
+
4552
+export type V2ReviewStartResponse__HookPromptFragment = {
4553
+ readonly hookRunId: string;
4554
+ readonly text: string;
4555
+};
4556
+export const V2ReviewStartResponse__HookPromptFragment = Schema.Struct({
4557
+ hookRunId: Schema.String,
4558
+ text: Schema.String,
4559
+});
4560
+
4561
+export type V2ReviewStartResponse__McpToolCallError = { readonly message: string };
4562
+export const V2ReviewStartResponse__McpToolCallError = Schema.Struct({ message: Schema.String });
4563
+
4564
+export type V2ReviewStartResponse__McpToolCallResult = {
4565
+ readonly _meta?: unknown;
4566
+ readonly content: ReadonlyArray<unknown>;
4567
+ readonly structuredContent?: unknown;
4568
+};
4569
+export 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
+
4575
+export type V2ReviewStartResponse__McpToolCallStatus = "inProgress" | "completed" | "failed";
4576
+export const V2ReviewStartResponse__McpToolCallStatus = Schema.Literals([
4577
+ "inProgress",
4578
+ "completed",
4579
+ "failed",
4580
+]);
4581
+
4582
+export type V2ReviewStartResponse__MemoryCitationEntry = {
4583
+ readonly lineEnd: number;
4584
+ readonly lineStart: number;
4585
+ readonly note: string;
4586
+ readonly path: string;
4587
+};
4588
+export 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
+
4599
+export type V2ReviewStartResponse__MessagePhase = "commentary" | "final_answer";
4600
+export 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
+
4608
+export type V2ReviewStartResponse__NonSteerableTurnKind = "review" | "compact";
4609
+export const V2ReviewStartResponse__NonSteerableTurnKind = Schema.Literals(["review", "compact"]);
4610
+
4611
+export type V2ReviewStartResponse__PatchApplyStatus =
4612
+ | "inProgress"
4613
+ | "completed"
4614
+ | "failed"
4615
+ | "declined";
4616
+export const V2ReviewStartResponse__PatchApplyStatus = Schema.Literals([
4617
+ "inProgress",
4618
+ "completed",
4619
+ "failed",
4620
+ "declined",
4621
+]);
4622
+
4623
+export type V2ReviewStartResponse__PatchChangeKind =
4624
+ | { readonly type: "add" }
4625
+ | { readonly type: "delete" }
4626
+ | { readonly move_path?: string | null; readonly type: "update" };
4627
+export 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
+
4643
+export type V2ReviewStartResponse__ReasoningEffort =
4644
+ | "none"
4645
+ | "minimal"
4646
+ | "low"
4647
+ | "medium"
4648
+ | "high"
4649
+ | "xhigh";
4650
+export 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
+
4662
+export type V2ReviewStartResponse__TextElement = {
4663
+ readonly byteRange: { readonly end: number; readonly start: number };
4664
+ readonly placeholder?: string | null;
4665
+};
4666
+export 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
+
4687
+export type V2ReviewStartResponse__TurnStatus =
4688
+ | "completed"
4689
+ | "interrupted"
4690
+ | "failed"
4691
+ | "inProgress";
4692
+export const V2ReviewStartResponse__TurnStatus = Schema.Literals([
4693
+ "completed",
4694
+ "interrupted",
4695
+ "failed",
4696
+ "inProgress",
4697
+]);
4698
+
4699
+export 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" };
4708
+export 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
+
4731
+export type V2ServerRequestResolvedNotification__RequestId = string | number;
4732
+export const V2ServerRequestResolvedNotification__RequestId = Schema.Union([
4733
+ Schema.String,
4734
+ Schema.Number.annotate({ format: "int64" }).check(Schema.isInt()),
4735
+]);
4736
+
4737
+export type V2SkillsConfigWriteParams__AbsolutePathBuf = string;
4738
+export 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
+
4743
+export type V2SkillsListParams__SkillsListExtraRootsForCwd = {
4744
+ readonly cwd: string;
4745
+ readonly extraUserRoots: ReadonlyArray<string>;
4746
+};
4747
+export const V2SkillsListParams__SkillsListExtraRootsForCwd = Schema.Struct({
4748
+ cwd: Schema.String,
4749
+ extraUserRoots: Schema.Array(Schema.String),
4750
+});
4751
+
4752
+export type V2SkillsListResponse__SkillErrorInfo = {
4753
+ readonly message: string;
4754
+ readonly path: string;
4755
+};
4756
+export const V2SkillsListResponse__SkillErrorInfo = Schema.Struct({
4757
+ message: Schema.String,
4758
+ path: Schema.String,
4759
+});
4760
+
4761
+export 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
+};
4769
+export 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
+
4778
+export type V2SkillsListResponse__SkillScope = "user" | "repo" | "system" | "admin";
4779
+export const V2SkillsListResponse__SkillScope = Schema.Literals([
4780
+ "user",
4781
+ "repo",
4782
+ "system",
4783
+ "admin",
4784
+]);
4785
+
4786
+export 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
+};
4794
+export 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
+
4803
+export type V2ThreadForkParams__ApprovalsReviewer = "user" | "guardian_subagent";
4804
+export 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
+
4812
+export 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
+ };
4826
+export 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
+
4842
+export type V2ThreadForkParams__SandboxMode =
4843
+ | "read-only"
4844
+ | "workspace-write"
4845
+ | "danger-full-access";
4846
+export const V2ThreadForkParams__SandboxMode = Schema.Literals([
4847
+ "read-only",
4848
+ "workspace-write",
4849
+ "danger-full-access",
4850
+]);
4851
+
4852
+export type V2ThreadForkParams__ServiceTier = "fast" | "flex";
4853
+export const V2ThreadForkParams__ServiceTier = Schema.Literals(["fast", "flex"]);
4854
+
4855
+export type V2ThreadForkResponse__AbsolutePathBuf = string;
4856
+export 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
+
4861
+export type V2ThreadForkResponse__AgentPath = string;
4862
+export const V2ThreadForkResponse__AgentPath = Schema.String;
4863
+
4864
+export 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
+ };
4878
+export 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
+
4894
+export type V2ThreadForkResponse__CollabAgentStatus =
4895
+ | "pendingInit"
4896
+ | "running"
4897
+ | "interrupted"
4898
+ | "completed"
4899
+ | "errored"
4900
+ | "shutdown"
4901
+ | "notFound";
4902
+export const V2ThreadForkResponse__CollabAgentStatus = Schema.Literals([
4903
+ "pendingInit",
4904
+ "running",
4905
+ "interrupted",
4906
+ "completed",
4907
+ "errored",
4908
+ "shutdown",
4909
+ "notFound",
4910
+]);
4911
+
4912
+export 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" };
4927
+export 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
+
4954
+export type V2ThreadForkResponse__CommandExecutionStatus =
4955
+ | "inProgress"
4956
+ | "completed"
4957
+ | "failed"
4958
+ | "declined";
4959
+export const V2ThreadForkResponse__CommandExecutionStatus = Schema.Literals([
4960
+ "inProgress",
4961
+ "completed",
4962
+ "failed",
4963
+ "declined",
4964
+]);
4965
+
4966
+export type V2ThreadForkResponse__DynamicToolCallOutputContentItem =
4967
+ | { readonly text: string; readonly type: "inputText" }
4968
+ | { readonly imageUrl: string; readonly type: "inputImage" };
4969
+export 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
+
4987
+export type V2ThreadForkResponse__DynamicToolCallStatus = "inProgress" | "completed" | "failed";
4988
+export const V2ThreadForkResponse__DynamicToolCallStatus = Schema.Literals([
4989
+ "inProgress",
4990
+ "completed",
4991
+ "failed",
4992
+]);
4993
+
4994
+export type V2ThreadForkResponse__GitInfo = {
4995
+ readonly branch?: string | null;
4996
+ readonly originUrl?: string | null;
4997
+ readonly sha?: string | null;
4998
+};
4999
+export const V2ThreadForkResponse__GitInfo = Schema.Struct({
This file is too large to show in full.
packages/effect-codex-app-server/src/_internal/shared.ts
new
+101
@@ -0,0 +1,101 @@
1
+import * as Effect from "effect/Effect";
2
+import * as Schema from "effect/Schema";
3
+import * as SchemaIssue from "effect/SchemaIssue";
4
+
5
+import * as CodexError from "../errors.ts";
6
+
7
+const formatSchemaIssue = SchemaIssue.makeFormatterDefault();
8
+
9
+export const JsonRpcId = Schema.Union([Schema.Number, Schema.String]);
10
+
11
+export const JsonRpcError = Schema.Struct({
12
+ code: Schema.Number,
13
+ message: Schema.String,
14
+ data: Schema.optional(Schema.Unknown),
15
+});
16
+
17
+export const JsonRpcResponseEnvelope = Schema.Struct({
18
+ id: JsonRpcId,
19
+ result: Schema.optional(Schema.Unknown),
20
+ error: Schema.optional(JsonRpcError),
21
+});
22
+
23
+export 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
+
47
+export 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
+
74
+export 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
+
89
+export 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
new
+57
@@ -0,0 +1,57 @@
1
+import * as Cause from "effect/Cause";
2
+import * as Effect from "effect/Effect";
3
+import * as Queue from "effect/Queue";
4
+import * as Sink from "effect/Sink";
5
+import * as Stdio from "effect/Stdio";
6
+import * as Stream from "effect/Stream";
7
+import { ChildProcessSpawner } from "effect/unstable/process";
8
+
9
+import * as CodexError from "../errors.ts";
10
+
11
+const encoder = new TextEncoder();
12
+
13
+export 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
+
24
+export 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
+
47
+export 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
new
+154
@@ -0,0 +1,154 @@
1
+import * as Exit from "effect/Exit";
2
+import * as Layer from "effect/Layer";
3
+import * as Path from "effect/Path";
4
+import * as Effect from "effect/Effect";
5
+import * as Ref from "effect/Ref";
6
+import * as Scope from "effect/Scope";
7
+import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
8
+
9
+import * as NodeServices from "@effect/platform-node/NodeServices";
10
+import { assert, it } from "@effect/vitest";
11
+
12
+import * as CodexClient from "./client.ts";
13
+
14
+const mockPeerPath = Effect.map(Effect.service(Path.Path), (path) =>
15
+ path.join(import.meta.dirname, "../test/fixtures/codex-app-server-mock-peer.ts"),
16
+);
17
+
18
+it.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
new
+300
@@ -0,0 +1,300 @@
1
+import * as Context from "effect/Context";
2
+import * as Effect from "effect/Effect";
3
+import * as Layer from "effect/Layer";
4
+import * as Schema from "effect/Schema";
5
+import * as Scope from "effect/Scope";
6
+import * as Stdio from "effect/Stdio";
7
+import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
8
+
9
+import * as CodexRpc from "./_generated/meta.gen.ts";
10
+import * as CodexError from "./errors.ts";
11
+import * as CodexProtocol from "./protocol.ts";
12
+import {
13
+ decodeNotificationPayload,
14
+ decodeOptionalPayload,
15
+ encodeOptionalPayload,
16
+ runHandler,
17
+} from "./_internal/shared.ts";
18
+import { makeChildStdio, makeTerminationError } from "./_internal/stdio.ts";
19
+
20
+export interface CodexAppServerClientOptions {
21
+ readonly logIncoming?: boolean;
22
+ readonly logOutgoing?: boolean;
23
+ readonly logger?: (
24
+ event: CodexProtocol.CodexAppServerProtocolLogEvent,
25
+ ) => Effect.Effect<void, never>;
26
+}
27
+
28
+interface 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
+
37
+export 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
+
73
+export class CodexAppServerClient extends Context.Service<
74
+ CodexAppServerClient,
75
+ CodexAppServerClientShape
76
+>()("effect-codex-app-server/CodexAppServerClient") {}
77
+
78
+type ServerRequestHandler = (
79
+ payload: unknown,
80
+) => Effect.Effect<unknown, CodexError.CodexAppServerError>;
81
+type ServerNotificationHandler = (
82
+ payload: unknown,
83
+) => Effect.Effect<void, CodexError.CodexAppServerError>;
84
+
85
+export 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
+
251
+export 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
+
260
+export 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
+
267
+export 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
new
+151
@@ -0,0 +1,151 @@
1
+import * as Schema from "effect/Schema";
2
+
3
+export interface CodexAppServerProtocolErrorShape {
4
+ readonly code: number;
5
+ readonly message: string;
6
+ readonly data?: unknown;
7
+}
8
+
9
+export 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
+
23
+export 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
+
37
+export 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
+
49
+export 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
+
61
+export 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
+
137
+export const CodexAppServerError = Schema.Union([
138
+ CodexAppServerRequestError,
139
+ CodexAppServerSpawnError,
140
+ CodexAppServerProcessExitedError,
141
+ CodexAppServerProtocolParseError,
142
+ CodexAppServerTransportError,
143
+]);
144
+
145
+export type CodexAppServerError = typeof CodexAppServerError.Type;
146
+
147
+export 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
new
+197
@@ -0,0 +1,197 @@
1
+import * as Deferred from "effect/Deferred";
2
+import * as Effect from "effect/Effect";
3
+import * as Fiber from "effect/Fiber";
4
+import * as Queue from "effect/Queue";
5
+import * as Stream from "effect/Stream";
6
+
7
+import * as NodeServices from "@effect/platform-node/NodeServices";
8
+import { assert, it } from "@effect/vitest";
9
+
10
+import * as CodexError from "./errors.ts";
11
+import * as CodexProtocol from "./protocol.ts";
12
+import { makeInMemoryStdio } from "./_internal/stdio.ts";
13
+
14
+const encoder = new TextEncoder();
15
+
16
+const encodeJsonl = (value: unknown) => encoder.encode(`${JSON.stringify(value)}\n`);
17
+
18
+it.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
new
+394
@@ -0,0 +1,394 @@
1
+import * as Cause from "effect/Cause";
2
+import * as Deferred from "effect/Deferred";
3
+import * as Effect from "effect/Effect";
4
+import * as Queue from "effect/Queue";
5
+import * as Ref from "effect/Ref";
6
+import * as Scope from "effect/Scope";
7
+import * as Schema from "effect/Schema";
8
+import * as Stdio from "effect/Stdio";
9
+import * as Stream from "effect/Stream";
10
+
11
+import * as CodexError from "./errors.ts";
12
+import { JsonRpcId, JsonRpcResponseEnvelope } from "./_internal/shared.ts";
13
+
14
+export interface CodexAppServerProtocolLogEvent {
15
+ readonly direction: "incoming" | "outgoing";
16
+ readonly stage: "raw" | "decoded" | "decode_failed";
17
+ readonly payload: unknown;
18
+}
19
+
20
+export interface CodexAppServerIncomingNotification {
21
+ readonly method: string;
22
+ readonly params?: unknown;
23
+}
24
+
25
+export interface CodexAppServerIncomingRequest {
26
+ readonly id: string | number;
27
+ readonly method: string;
28
+ readonly params?: unknown;
29
+}
30
+
31
+export 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
+
46
+export 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
+
67
+function isObject(value: unknown): value is Record<string, unknown> {
68
+ return typeof value === "object" && value !== null;
69
+}
70
+
71
+function 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
+
78
+function isIncomingNotification(value: unknown): value is CodexAppServerIncomingNotification {
79
+ return isObject(value) && typeof value.method === "string" && !("id" in value);
80
+}
81
+
82
+function isIncomingResponse(value: unknown): value is typeof JsonRpcResponseEnvelope.Type {
83
+ return Schema.is(JsonRpcResponseEnvelope)(value);
84
+}
85
+
86
+const 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
+
98
+const 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
+
106
+const 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
+
118
+export 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
new
+1
@@ -0,0 +1 @@
1
+export * from "./_generated/meta.gen.ts";
packages/effect-codex-app-server/src/schema.ts
new
+3
@@ -0,0 +1,3 @@
1
+export * from "./_generated/schema.gen.ts";
2
+export * from "./_generated/meta.gen.ts";
3
+export * from "./_generated/namespaces.gen.ts";
packages/effect-codex-app-server/test/examples/codex-app-server-probe.ts
new
+62
@@ -0,0 +1,62 @@
1
+import * as Console from "effect/Console";
2
+import * as Effect from "effect/Effect";
3
+
4
+import * as NodeRuntime from "@effect/platform-node/NodeRuntime";
5
+import * as NodeServices from "@effect/platform-node/NodeServices";
6
+
7
+import * as CodexClient from "../../src/client.ts";
8
+
9
+const 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
+
62
+program.pipe(Effect.scoped, Effect.provide(NodeServices.layer), NodeRuntime.runMain);
packages/effect-codex-app-server/test/fixtures/codex-app-server-mock-peer.ts
new
+144
@@ -0,0 +1,144 @@
1
+let nextServerRequestId = 10_000;
2
+let pendingSkillsListRequestId: number | string | null = null;
3
+let pendingUserInputRequestId: number | null = null;
4
+
5
+const writeMessage = (message: unknown) => {
6
+ process.stdout.write(`${JSON.stringify(message)}\n`);
7
+};
8
+
9
+const respond = (id: number | string, result: unknown) => {
10
+ writeMessage({ id, result });
11
+};
12
+
13
+const respondError = (id: number | string, code: number, message: string) => {
14
+ writeMessage({
15
+ id,
16
+ error: {
17
+ code,
18
+ message,
19
+ },
20
+ });
21
+};
22
+
23
+const sendRequest = (method: string, params: unknown) => {
24
+ const id = nextServerRequestId++;
25
+ writeMessage({ id, method, params });
26
+ return id;
27
+};
28
+
29
+const 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
+
98
+const 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
+
117
+let remainder = "";
118
+
119
+process.stdin.setEncoding("utf8");
120
+process.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
+
142
+process.stdin.on("end", () => {
143
+ process.exit(0);
144
+});
packages/effect-codex-app-server/tsconfig.json
new
+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
"packages/contracts/package.json",
26
"packages/shared/package.json",
27
"packages/effect-acp/package.json",
28
+ "packages/effect-codex-app-server/package.json",
29
"scripts/package.json",
30
] as const;
31