stitchkit 0.130.1 → 0.131.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (152) hide show
  1. package/CHANGELOG.md +42 -0
  2. package/dist/agent-executor/acp/v1-connect.d.ts +40 -26
  3. package/dist/agent-executor/acp/v1-connect.d.ts.map +1 -1
  4. package/dist/agent-executor/acp/v1-driver.d.ts +10 -4
  5. package/dist/agent-executor/acp/v1-driver.d.ts.map +1 -1
  6. package/dist/agent-executor/acp/v1-handlers.d.ts +6 -2
  7. package/dist/agent-executor/acp/v1-handlers.d.ts.map +1 -1
  8. package/dist/agent-executor/acp/v1-probe.d.ts +38 -0
  9. package/dist/agent-executor/acp/v1-probe.d.ts.map +1 -0
  10. package/dist/agent-executor/acp/v1-protocol.d.ts +15 -0
  11. package/dist/agent-executor/acp/v1-protocol.d.ts.map +1 -1
  12. package/dist/agent-executor/acp/v1-session.d.ts +9 -7
  13. package/dist/agent-executor/acp/v1-session.d.ts.map +1 -1
  14. package/dist/agent-executor/claude/cli-driver.d.ts +7 -7
  15. package/dist/agent-executor/claude/cli-driver.d.ts.map +1 -1
  16. package/dist/agent-executor/claude/limits.d.ts +6 -4
  17. package/dist/agent-executor/claude/limits.d.ts.map +1 -1
  18. package/dist/agent-executor/claude/session.d.ts +3 -3
  19. package/dist/agent-executor/claude/session.d.ts.map +1 -1
  20. package/dist/agent-executor/claude-sdk/controls.d.ts +1 -0
  21. package/dist/agent-executor/claude-sdk/controls.d.ts.map +1 -1
  22. package/dist/agent-executor/claude-sdk/driver.d.ts +51 -50
  23. package/dist/agent-executor/claude-sdk/driver.d.ts.map +1 -1
  24. package/dist/agent-executor/claude-sdk/probe.d.ts +3 -3
  25. package/dist/agent-executor/claude-sdk/probe.d.ts.map +1 -1
  26. package/dist/agent-executor/claude-sdk/query-loop.d.ts +2 -1
  27. package/dist/agent-executor/claude-sdk/query-loop.d.ts.map +1 -1
  28. package/dist/agent-executor/codex/classify.d.ts.map +1 -1
  29. package/dist/agent-executor/codex/connect.d.ts +7 -7
  30. package/dist/agent-executor/codex/connect.d.ts.map +1 -1
  31. package/dist/agent-executor/codex/control-client.d.ts +86 -99
  32. package/dist/agent-executor/codex/control-client.d.ts.map +1 -1
  33. package/dist/agent-executor/codex/control-read-methods.d.ts +7 -0
  34. package/dist/agent-executor/codex/control-read-methods.d.ts.map +1 -0
  35. package/dist/agent-executor/codex/driver.d.ts +29 -28
  36. package/dist/agent-executor/codex/driver.d.ts.map +1 -1
  37. package/dist/agent-executor/codex/event-routing.d.ts +14 -0
  38. package/dist/agent-executor/codex/event-routing.d.ts.map +1 -0
  39. package/dist/agent-executor/codex/handlers.d.ts +2 -2
  40. package/dist/agent-executor/codex/handlers.d.ts.map +1 -1
  41. package/dist/agent-executor/codex/limits.d.ts +9 -3
  42. package/dist/agent-executor/codex/limits.d.ts.map +1 -1
  43. package/dist/agent-executor/codex/notifications.d.ts +183 -0
  44. package/dist/agent-executor/codex/notifications.d.ts.map +1 -0
  45. package/dist/agent-executor/codex/pagination.d.ts +54 -0
  46. package/dist/agent-executor/codex/pagination.d.ts.map +1 -0
  47. package/dist/agent-executor/codex/protocol.d.ts +586 -148
  48. package/dist/agent-executor/codex/protocol.d.ts.map +1 -1
  49. package/dist/agent-executor/codex/request-answers.d.ts +4 -2
  50. package/dist/agent-executor/codex/request-answers.d.ts.map +1 -1
  51. package/dist/agent-executor/codex/responses.d.ts +855 -0
  52. package/dist/agent-executor/codex/responses.d.ts.map +1 -0
  53. package/dist/agent-executor/codex/session-bind.d.ts +410 -0
  54. package/dist/agent-executor/codex/session-bind.d.ts.map +1 -0
  55. package/dist/agent-executor/codex/session-controls.d.ts +19 -190
  56. package/dist/agent-executor/codex/session-controls.d.ts.map +1 -1
  57. package/dist/agent-executor/codex/session-types.d.ts +190 -0
  58. package/dist/agent-executor/codex/session-types.d.ts.map +1 -0
  59. package/dist/agent-executor/codex/session.d.ts +1 -1
  60. package/dist/agent-executor/codex/session.d.ts.map +1 -1
  61. package/dist/agent-executor/codex/shared-server.d.ts +4 -4
  62. package/dist/agent-executor/codex/shared-server.d.ts.map +1 -1
  63. package/dist/agent-executor/codex/shared-thread.d.ts +5 -5
  64. package/dist/agent-executor/codex/shared-thread.d.ts.map +1 -1
  65. package/dist/agent-executor/codex/thread-controls.d.ts +45 -36
  66. package/dist/agent-executor/codex/thread-controls.d.ts.map +1 -1
  67. package/dist/agent-executor/codex/thread-list-query.d.ts +5 -0
  68. package/dist/agent-executor/codex/thread-list-query.d.ts.map +1 -0
  69. package/dist/agent-executor/codex/thread-open.d.ts +20 -20
  70. package/dist/agent-executor/codex/thread-open.d.ts.map +1 -1
  71. package/dist/agent-executor/codex/turn-input.d.ts +4 -3
  72. package/dist/agent-executor/codex/turn-input.d.ts.map +1 -1
  73. package/dist/agent-executor/codex/unix-socket-target.d.ts +12 -3
  74. package/dist/agent-executor/codex/unix-socket-target.d.ts.map +1 -1
  75. package/dist/agent-executor/codex/ws-frame.d.ts +4 -1
  76. package/dist/agent-executor/codex/ws-frame.d.ts.map +1 -1
  77. package/dist/agent-executor/contract.d.ts +3 -1
  78. package/dist/agent-executor/contract.d.ts.map +1 -1
  79. package/dist/agent-executor/engine-process.d.ts +4 -4
  80. package/dist/agent-executor/engine-process.d.ts.map +1 -1
  81. package/dist/agent-executor/engine.d.ts +3 -3
  82. package/dist/agent-executor/engine.d.ts.map +1 -1
  83. package/dist/agent-executor/handoff.d.ts.map +1 -1
  84. package/dist/agent-executor/hello.d.ts +7 -0
  85. package/dist/agent-executor/hello.d.ts.map +1 -1
  86. package/dist/agent-executor/json-rpc-peer.d.ts +9 -4
  87. package/dist/agent-executor/json-rpc-peer.d.ts.map +1 -1
  88. package/dist/agent-executor/leases.d.ts +1 -1
  89. package/dist/agent-executor/leases.d.ts.map +1 -1
  90. package/dist/agent-executor/plan-limits.d.ts +12 -1
  91. package/dist/agent-executor/plan-limits.d.ts.map +1 -1
  92. package/dist/agent-executor/profile.d.ts +7 -0
  93. package/dist/agent-executor/profile.d.ts.map +1 -1
  94. package/dist/agent-executor/session-primitives.d.ts +8 -0
  95. package/dist/agent-executor/session-primitives.d.ts.map +1 -1
  96. package/dist/agent-executor/testing/consumer-stubs.d.ts +45 -0
  97. package/dist/agent-executor/testing/consumer-stubs.d.ts.map +1 -0
  98. package/dist/agent-executor/testing/fake-claude-sdk-query.d.ts +88 -0
  99. package/dist/agent-executor/testing/fake-claude-sdk-query.d.ts.map +1 -0
  100. package/dist/agent-executor/testing/fake-codex-app-server.d.ts +56 -0
  101. package/dist/agent-executor/testing/fake-codex-app-server.d.ts.map +1 -0
  102. package/dist/agent-executor/testing/fixtures.d.ts +26 -0
  103. package/dist/agent-executor/testing/fixtures.d.ts.map +1 -0
  104. package/dist/agent-executor/testing/replay-driver.d.ts +8 -8
  105. package/dist/agent-executor/testing/replay-driver.d.ts.map +1 -1
  106. package/dist/agent-executor/testing/replay-runner.d.ts +3 -2
  107. package/dist/agent-executor/testing/replay-runner.d.ts.map +1 -1
  108. package/dist/agent-executor/testing/replay-transcript.d.ts +5 -3
  109. package/dist/agent-executor/testing/replay-transcript.d.ts.map +1 -1
  110. package/dist/agent-runtime/branch-observations.d.ts +19 -19
  111. package/dist/agent-runtime/sql-rows.d.ts +10 -10
  112. package/dist/agent-runtime/store-conformance-lifecycle.d.ts +20 -20
  113. package/dist/agent-runtime/store-conformance-support.d.ts +10 -10
  114. package/dist/agent-runtime/terminal-commit.d.ts +10 -10
  115. package/dist/entrypoints/agent-executor/acp.d.ts +2 -1
  116. package/dist/entrypoints/agent-executor/acp.d.ts.map +1 -1
  117. package/dist/entrypoints/agent-executor/acp.js +284 -82
  118. package/dist/entrypoints/agent-executor/claude-sdk.d.ts +4 -0
  119. package/dist/entrypoints/agent-executor/claude-sdk.d.ts.map +1 -1
  120. package/dist/entrypoints/agent-executor/claude-sdk.js +58 -32
  121. package/dist/entrypoints/agent-executor/claude.d.ts +2 -2
  122. package/dist/entrypoints/agent-executor/claude.d.ts.map +1 -1
  123. package/dist/entrypoints/agent-executor/claude.js +25 -20
  124. package/dist/entrypoints/agent-executor/codex.d.ts +9 -5
  125. package/dist/entrypoints/agent-executor/codex.d.ts.map +1 -1
  126. package/dist/entrypoints/agent-executor/codex.js +1724 -1557
  127. package/dist/entrypoints/agent-executor/testing.d.ts +4 -0
  128. package/dist/entrypoints/agent-executor/testing.d.ts.map +1 -1
  129. package/dist/entrypoints/agent-executor/testing.js +880 -18
  130. package/dist/entrypoints/agent-executor.d.ts +3 -3
  131. package/dist/entrypoints/agent-executor.d.ts.map +1 -1
  132. package/dist/entrypoints/agent-executor.js +42 -8
  133. package/dist/entrypoints/process.js +3 -3
  134. package/dist/{index-jrn3prgm.js → index-32vaajec.js} +29 -4
  135. package/dist/{index-p1qmpq0p.js → index-64e9p079.js} +92 -56
  136. package/dist/{index-dbp6xemn.js → index-g2d9kws8.js} +199 -3
  137. package/dist/index-gm9yz82v.js +56 -0
  138. package/dist/index-j15dhkda.js +749 -0
  139. package/dist/{index-1q0n6zek.js → index-kwsr7j5k.js} +84 -44
  140. package/llms/agent-executor-acp.txt +5 -5
  141. package/llms/agent-executor-claude-sdk.txt +3 -1
  142. package/llms/agent-executor-claude.txt +2 -2
  143. package/llms/agent-executor-codex.txt +11 -8
  144. package/llms/agent-executor-testing.txt +5 -1
  145. package/llms/agent-executor.txt +4 -4
  146. package/llms/stitchkit.txt +75 -74
  147. package/llms/{upgrading-0.128.0-0.130.0.txt → upgrading-0.128.0-0.131.0.txt} +56 -3
  148. package/llms/upgrading.txt +1 -1
  149. package/llms-full.txt +158 -95
  150. package/llms.txt +8 -8
  151. package/package.json +3 -3
  152. package/dist/index-2s8sy57y.js +0 -229
@@ -1,16 +1,18 @@
1
- import"../../index-2rf33y2h.js";
2
- import {
3
- InteractionReplySchema2,
4
- PlanWindowSchema2,
5
- engineProfile,
6
- engineEnvironment2
7
- } from "../../index-dbp6xemn.js";
8
1
  import"../../index-09f7w2qq.js";
9
2
  import"../../index-v59pxmf1.js";
10
3
  import"../../index-qa2jjb65.js";
11
4
  import"../../index-6kec3b14.js";
5
+ import"../../index-2rf33y2h.js";
12
6
  import {
7
+ InteractionReplySchema2,
8
+ PlanWindowSchema2,
9
+ PlanLimitsSchema2,
10
+ engineProfile,
11
+ engineEnvironment2,
12
+ TURN_QUEUE,
13
13
  nonEmptyString,
14
+ clampPlanName,
15
+ epochMsToIso,
14
16
  epochSecondsToIso,
15
17
  createTurnDeltaChannel,
16
18
  offerTurnDelta,
@@ -21,26 +23,72 @@ import {
21
23
  safeJsonValue,
22
24
  invokeSafely,
23
25
  emitStartupPhase,
24
- clampUniqueWindowName,
25
- holdEngineRequest,
26
- answerEngineRequest,
27
- drainEngineRequests,
28
- endEngineTurn,
29
- loseEngineTurn
30
- } from "../../index-2s8sy57y.js";
31
- import"../../index-673drwkn.js";
32
- import"../../index-vmbxj75t.js";
26
+ clampUniqueWindowName
27
+ } from "../../index-g2d9kws8.js";
33
28
  import {
29
+ JsonRpcValueSchema2,
34
30
  JsonRpcError2,
35
31
  JSON_RPC_METHOD_NOT_FOUND2,
36
32
  createJsonRpcPeer2
37
- } from "../../index-1q0n6zek.js";
33
+ } from "../../index-kwsr7j5k.js";
34
+ import {
35
+ CodexProtocolError2,
36
+ parseCodexResponse,
37
+ unknownTypedRecordSchema,
38
+ CodexApprovalPolicySchema2,
39
+ CodexSandboxModeSchema2,
40
+ CodexSandboxPolicySchema2,
41
+ CodexThreadStatusSchema2,
42
+ CodexTurnStatusSchema2,
43
+ CodexTurnItemsViewSchema2,
44
+ CODEX_THREAD_SOURCE_KINDS2,
45
+ CodexThreadSourceKindSchema2,
46
+ CodexCollaborationModeSchema2,
47
+ CodexThreadItemSchema2,
48
+ CodexTurnSchema,
49
+ CodexListedTurnSchema2,
50
+ CodexTurnsPageSchema2,
51
+ CodexThreadSchema2,
52
+ CodexThreadContextSchema2,
53
+ CodexInitializeResponseSchema,
54
+ CodexStartedThreadSchema,
55
+ extractCodexThreadContext,
56
+ CodexStartedTurnSchema,
57
+ CodexTurnSteerResponseSchema,
58
+ CodexThreadRevertResponseSchema,
59
+ CodexApprovalParamsSchema,
60
+ CodexUserInputParamsSchema,
61
+ CodexUserInputAnswersSchema,
62
+ CodexPermissionsApprovalParamsSchema,
63
+ CodexMcpElicitationParamsSchema,
64
+ CodexMcpElicitationAnswerSchema,
65
+ CODEX_APPROVAL_REQUESTS,
66
+ CODEX_PERMISSIONS_APPROVAL_REQUEST,
67
+ CODEX_INPUT_REQUEST,
68
+ CODEX_ELICITATION_REQUEST,
69
+ CODEX_APPROVAL_DECISION,
70
+ CodexUnixSocketError2,
71
+ validateCodexUnixSocketPath,
72
+ assertCodexUnixListenTargetAvailable,
73
+ assertCodexUnixSocketClientTarget,
74
+ maskedWsFrameByteLength,
75
+ encodeMaskedWsFrame,
76
+ createWsFrameDecoder
77
+ } from "../../index-j15dhkda.js";
78
+ import"../../index-673drwkn.js";
79
+ import"../../index-vmbxj75t.js";
38
80
  import {
39
81
  validateImageOptions,
40
82
  inlineOrderedParts,
41
83
  guardedTurnStarter
42
84
  } from "../../index-y0a4gt1s.js";
43
- import"../../index-pzhqydxb.js";
85
+ import {
86
+ holdEngineRequest,
87
+ answerEngineRequest,
88
+ drainEngineRequests,
89
+ endEngineTurn,
90
+ loseEngineTurn
91
+ } from "../../index-gm9yz82v.js";
44
92
  import {
45
93
  spawnEngineProcess2
46
94
  } from "../../index-rxh3qy4x.js";
@@ -48,11 +96,10 @@ import"../../index-3fym4j8n.js";
48
96
  import {
49
97
  planLimitsReadFailed2,
50
98
  mergeRateLimitEvent2
51
- } from "../../index-jrn3prgm.js";
99
+ } from "../../index-32vaajec.js";
100
+ import"../../index-pzhqydxb.js";
52
101
  import {
53
- assertUnixSocketPathLength,
54
- assertExpectedOwnerUid,
55
- unixSocketDirectoryViolation
102
+ assertExpectedOwnerUid
56
103
  } from "../../index-hab790s6.js";
57
104
  import {
58
105
  errnoOf
@@ -71,29 +118,12 @@ import {
71
118
  } from "../../index-agy5fqgf.js";
72
119
  import {
73
120
  abortReason,
74
- raceAbort
121
+ raceAbort,
122
+ withLinkedAbortSignals
75
123
  } from "../../index-rptj3qnc.js";
76
124
 
77
- // src/agent-executor/codex/protocol.ts
125
+ // src/agent-executor/codex/notifications.ts
78
126
  import { z } from "zod";
79
- var CodexCollaborationModeSchema = z.strictObject({
80
- mode: z.enum(["plan", "default"]),
81
- settings: z.strictObject({
82
- model: z.string().min(1),
83
- reasoning_effort: z.string().min(1).nullable().optional(),
84
- developer_instructions: z.string().nullable().optional()
85
- })
86
- });
87
- var CodexThreadItemSchema = z.looseObject({
88
- type: z.string(),
89
- id: z.string().min(1)
90
- });
91
- var CodexTurnSchema = z.looseObject({
92
- id: z.string().min(1),
93
- status: z.enum(["completed", "interrupted", "failed", "inProgress"]),
94
- error: z.looseObject({ message: z.string(), codexErrorInfo: z.json().nullable().optional() }).nullable().optional(),
95
- items: z.array(z.looseObject({ type: z.string(), clientId: z.string().nullable().optional() })).optional()
96
- });
97
127
  var CodexTokenUsageBreakdownSchema = z.looseObject({
98
128
  inputTokens: z.int().nonnegative().optional(),
99
129
  outputTokens: z.int().nonnegative().optional(),
@@ -103,13 +133,67 @@ var CodexTokenUsageBreakdownSchema = z.looseObject({
103
133
  totalTokens: z.int().nonnegative().optional()
104
134
  });
105
135
  var CodexNotificationParams = {
106
- "item/agentMessage/delta": z.looseObject({ itemId: z.string(), delta: z.string() }),
107
- "item/reasoning/textDelta": z.looseObject({ itemId: z.string(), delta: z.string() }),
108
- "item/reasoning/summaryTextDelta": z.looseObject({ itemId: z.string(), delta: z.string() }),
109
- "item/started": z.looseObject({ item: CodexThreadItemSchema }),
110
- "item/completed": z.looseObject({ item: CodexThreadItemSchema }),
111
- "turn/completed": z.looseObject({ turn: CodexTurnSchema }),
136
+ "item/agentMessage/delta": z.looseObject({
137
+ threadId: z.string().optional(),
138
+ turnId: z.string().optional(),
139
+ itemId: z.string(),
140
+ delta: z.string()
141
+ }),
142
+ "item/reasoning/textDelta": z.looseObject({
143
+ threadId: z.string().optional(),
144
+ turnId: z.string().optional(),
145
+ itemId: z.string(),
146
+ delta: z.string()
147
+ }),
148
+ "item/reasoning/summaryTextDelta": z.looseObject({
149
+ threadId: z.string().optional(),
150
+ turnId: z.string().optional(),
151
+ itemId: z.string(),
152
+ delta: z.string(),
153
+ summaryIndex: z.number().int().optional()
154
+ }),
155
+ "item/plan/delta": z.looseObject({
156
+ threadId: z.string().optional(),
157
+ turnId: z.string().optional(),
158
+ itemId: z.string(),
159
+ delta: z.string()
160
+ }),
161
+ "item/started": z.looseObject({
162
+ threadId: z.string().optional(),
163
+ turnId: z.string().optional(),
164
+ item: CodexThreadItemSchema2
165
+ }),
166
+ "item/completed": z.looseObject({
167
+ threadId: z.string().optional(),
168
+ turnId: z.string().optional(),
169
+ item: CodexThreadItemSchema2
170
+ }),
171
+ "turn/started": z.looseObject({
172
+ threadId: z.string().optional(),
173
+ turn: CodexTurnSchema
174
+ }),
175
+ "turn/completed": z.looseObject({
176
+ threadId: z.string().optional(),
177
+ turn: CodexTurnSchema
178
+ }),
179
+ "thread/status/changed": z.looseObject({
180
+ threadId: z.string(),
181
+ status: CodexThreadStatusSchema2
182
+ }),
183
+ "thread/settings/updated": z.looseObject({
184
+ threadId: z.string(),
185
+ threadSettings: z.looseObject({})
186
+ }),
187
+ "model/rerouted": z.looseObject({
188
+ threadId: z.string(),
189
+ turnId: z.string(),
190
+ fromModel: z.string(),
191
+ toModel: z.string(),
192
+ reason: z.string().optional()
193
+ }),
112
194
  "thread/tokenUsage/updated": z.looseObject({
195
+ threadId: z.string().optional(),
196
+ turnId: z.string().optional(),
113
197
  tokenUsage: z.looseObject({
114
198
  last: z.looseObject({
115
199
  inputTokens: z.int().nonnegative(),
@@ -123,149 +207,15 @@ var CodexNotificationParams = {
123
207
  modelContextWindow: z.int().nonnegative().nullable().optional()
124
208
  })
125
209
  }),
126
- "serverRequest/resolved": z.looseObject({ requestId: z.union([z.string(), z.int()]) }),
210
+ "serverRequest/resolved": z.looseObject({
211
+ threadId: z.string().optional(),
212
+ requestId: z.union([z.string(), z.int()])
213
+ }),
127
214
  "account/rateLimits/updated": z.looseObject({
128
- rateLimits: z.json(),
129
- rateLimitsByLimitId: z.json().optional()
215
+ rateLimits: JsonRpcValueSchema2,
216
+ rateLimitsByLimitId: JsonRpcValueSchema2.optional()
130
217
  })
131
218
  };
132
- var CodexApprovalParamsSchema = z.looseObject({
133
- itemId: z.string(),
134
- command: z.string().nullable().optional(),
135
- cwd: z.string().nullable().optional(),
136
- reason: z.string().nullable().optional(),
137
- grantRoot: z.string().nullable().optional(),
138
- kind: z.string().nullable().optional(),
139
- approvalId: z.string().nullable().optional(),
140
- commandActions: z.array(z.json()).nullable().optional(),
141
- availableDecisions: z.array(z.json()).nullable().optional()
142
- });
143
- var CodexUserInputOptionSchema = z.looseObject({
144
- label: z.string(),
145
- description: z.string()
146
- });
147
- var CodexUserInputQuestionSchema = z.looseObject({
148
- id: z.string(),
149
- question: z.string(),
150
- header: z.string(),
151
- isOther: z.boolean().optional(),
152
- isSecret: z.boolean().optional(),
153
- options: z.array(CodexUserInputOptionSchema).nullable().optional()
154
- });
155
- var CodexUserInputParamsSchema = z.looseObject({
156
- itemId: z.string(),
157
- questions: z.array(CodexUserInputQuestionSchema)
158
- });
159
- var CodexUserInputAnswersSchema = z.record(z.string(), z.strictObject({ answers: z.array(z.string()) }));
160
- var CodexPermissionProfileSchema = z.looseObject({
161
- fileSystem: z.json().nullable().optional(),
162
- network: z.json().nullable().optional()
163
- });
164
- var CodexPermissionsApprovalParamsSchema = z.looseObject({
165
- threadId: z.string(),
166
- turnId: z.string(),
167
- itemId: z.string(),
168
- cwd: z.string(),
169
- permissions: CodexPermissionProfileSchema,
170
- startedAtMs: z.number().int(),
171
- reason: z.string().nullable().optional(),
172
- environmentId: z.string().nullable().optional()
173
- });
174
- var CodexMcpElicitationBaseFields = {
175
- serverName: z.string(),
176
- threadId: z.string(),
177
- turnId: z.string().nullable().optional(),
178
- environmentId: z.string().nullable().optional(),
179
- message: z.string(),
180
- _meta: z.json().optional()
181
- };
182
- var CodexMcpElicitationFormSchemaSchema = z.looseObject({
183
- type: z.literal("object"),
184
- properties: z.record(z.string(), z.json()),
185
- required: z.array(z.string()).nullable().optional(),
186
- $schema: z.string().nullable().optional()
187
- });
188
- var CodexMcpElicitationParamsSchema = z.discriminatedUnion("mode", [
189
- z.looseObject({
190
- ...CodexMcpElicitationBaseFields,
191
- mode: z.literal("form"),
192
- requestedSchema: CodexMcpElicitationFormSchemaSchema
193
- }),
194
- z.looseObject({
195
- ...CodexMcpElicitationBaseFields,
196
- mode: z.literal("openai/form"),
197
- requestedSchema: z.json()
198
- }),
199
- z.looseObject({
200
- ...CodexMcpElicitationBaseFields,
201
- mode: z.literal("openaiForm"),
202
- requestedSchema: z.json()
203
- }),
204
- z.looseObject({
205
- ...CodexMcpElicitationBaseFields,
206
- mode: z.literal("url"),
207
- elicitationId: z.string(),
208
- url: z.string()
209
- })
210
- ]);
211
- var CodexMcpElicitationAnswerSchema = z.strictObject({
212
- action: z.enum(["accept", "decline", "cancel"]),
213
- content: z.json().optional(),
214
- _meta: z.json().optional()
215
- });
216
- var CodexThreadContextSchema = z.object({
217
- model: z.string().optional(),
218
- modelProvider: z.string().optional(),
219
- reasoningEffort: z.string().nullable().optional(),
220
- approvalPolicy: z.json().optional(),
221
- sandbox: z.json().optional(),
222
- cwd: z.string().optional(),
223
- runtimeWorkspaceRoots: z.array(z.string()).readonly().optional(),
224
- thread: z.json().optional()
225
- });
226
- var CodexInitializeResponseSchema = z.looseObject({
227
- userAgent: z.string().nullable().optional()
228
- });
229
- var CodexStartedThreadSchema = CodexThreadContextSchema.extend({
230
- thread: z.looseObject({ id: z.string().min(1) })
231
- }).loose();
232
- function extractCodexThreadContext(parsed) {
233
- return {
234
- ...parsed.model !== undefined && { model: parsed.model },
235
- ...parsed.modelProvider !== undefined && { modelProvider: parsed.modelProvider },
236
- ...parsed.reasoningEffort !== undefined && { reasoningEffort: parsed.reasoningEffort },
237
- ...parsed.approvalPolicy !== undefined && { approvalPolicy: parsed.approvalPolicy },
238
- ...parsed.sandbox !== undefined && { sandbox: parsed.sandbox },
239
- ...parsed.cwd !== undefined && { cwd: parsed.cwd },
240
- ...parsed.runtimeWorkspaceRoots !== undefined && {
241
- runtimeWorkspaceRoots: parsed.runtimeWorkspaceRoots
242
- },
243
- thread: safeJsonValue(parsed.thread)
244
- };
245
- }
246
- var CodexStartedTurnSchema = z.looseObject({
247
- turn: z.looseObject({ id: z.string().min(1) })
248
- });
249
- var CodexTurnSteerResponseSchema = z.looseObject({
250
- turnId: z.string().min(1)
251
- });
252
- var CodexListedTurnItemSchema = z.looseObject({
253
- type: z.string(),
254
- clientId: z.string().nullable().optional()
255
- });
256
- var CodexListedTurnSchema = CodexTurnSchema.extend({
257
- items: z.array(CodexListedTurnItemSchema),
258
- itemsView: z.literal("full").optional()
259
- });
260
- var CodexTurnsPageSchema = z.looseObject({
261
- data: z.array(CodexListedTurnSchema),
262
- nextCursor: z.string().nullable().optional()
263
- });
264
- var CodexThreadRevertResponseSchema = z.looseObject({
265
- thread: z.looseObject({ id: z.string().min(1) }),
266
- turnsBackwardsCursor: z.string().nullable().optional(),
267
- itemsBackwardsCursor: z.string().nullable().optional()
268
- });
269
219
  var CODEX_OPTED_OUT_NOTIFICATIONS = [
270
220
  "app/list/updated",
271
221
  "item/commandExecution/outputDelta",
@@ -325,375 +275,399 @@ var CODEX_QUIET_NOTIFICATIONS = new Set([
325
275
  "modelProvider/authRecoveryCompleted",
326
276
  "error"
327
277
  ]);
328
- var CODEX_APPROVAL_REQUESTS = new Set([
329
- "item/commandExecution/requestApproval",
330
- "item/fileChange/requestApproval"
331
- ]);
332
- var CODEX_PERMISSIONS_APPROVAL_REQUEST = "item/permissions/requestApproval";
333
- var CODEX_INPUT_REQUEST = "item/tool/requestUserInput";
334
- var CODEX_ELICITATION_REQUEST = "mcpServer/elicitation/request";
335
- var CODEX_APPROVAL_DECISION = {
336
- approve: "accept",
337
- approveForSession: "acceptForSession",
338
- deny: "decline",
339
- interrupted: "cancel"
340
- };
341
-
342
- // src/agent-executor/codex/unix-socket.ts
343
- import { createHash, randomBytes as randomBytes2 } from "node:crypto";
344
- import { createConnection } from "node:net";
345
-
346
- // src/agent-executor/codex/unix-socket-target.ts
347
- import { lstatSync, realpathSync } from "node:fs";
348
- import { dirname } from "node:path";
349
- class CodexUnixSocketError extends Error {
350
- kind;
351
- socketPath;
352
- constructor(kind, socketPath, message, options) {
353
- super(message, options);
354
- this.kind = kind;
355
- this.socketPath = socketPath;
356
- this.name = "CodexUnixSocketError";
278
+ function parseCodexNotification(event) {
279
+ const { method, params } = event;
280
+ switch (method) {
281
+ case "item/agentMessage/delta":
282
+ return {
283
+ method,
284
+ params: parseCodexResponse(method, CodexNotificationParams[method], params, "notification")
285
+ };
286
+ case "item/reasoning/textDelta":
287
+ return {
288
+ method,
289
+ params: parseCodexResponse(method, CodexNotificationParams[method], params, "notification")
290
+ };
291
+ case "item/reasoning/summaryTextDelta":
292
+ return {
293
+ method,
294
+ params: parseCodexResponse(method, CodexNotificationParams[method], params, "notification")
295
+ };
296
+ case "item/plan/delta":
297
+ return {
298
+ method,
299
+ params: parseCodexResponse(method, CodexNotificationParams[method], params, "notification")
300
+ };
301
+ case "item/started":
302
+ return {
303
+ method,
304
+ params: parseCodexResponse(method, CodexNotificationParams[method], params, "notification")
305
+ };
306
+ case "item/completed":
307
+ return {
308
+ method,
309
+ params: parseCodexResponse(method, CodexNotificationParams[method], params, "notification")
310
+ };
311
+ case "turn/started":
312
+ return {
313
+ method,
314
+ params: parseCodexResponse(method, CodexNotificationParams[method], params, "notification")
315
+ };
316
+ case "turn/completed":
317
+ return {
318
+ method,
319
+ params: parseCodexResponse(method, CodexNotificationParams[method], params, "notification")
320
+ };
321
+ case "thread/status/changed":
322
+ return {
323
+ method,
324
+ params: parseCodexResponse(method, CodexNotificationParams[method], params, "notification")
325
+ };
326
+ case "thread/settings/updated":
327
+ return {
328
+ method,
329
+ params: parseCodexResponse(method, CodexNotificationParams[method], params, "notification")
330
+ };
331
+ case "model/rerouted":
332
+ return {
333
+ method,
334
+ params: parseCodexResponse(method, CodexNotificationParams[method], params, "notification")
335
+ };
336
+ case "thread/tokenUsage/updated":
337
+ return {
338
+ method,
339
+ params: parseCodexResponse(method, CodexNotificationParams[method], params, "notification")
340
+ };
341
+ case "serverRequest/resolved":
342
+ return {
343
+ method,
344
+ params: parseCodexResponse(method, CodexNotificationParams[method], params, "notification")
345
+ };
346
+ case "account/rateLimits/updated":
347
+ return {
348
+ method,
349
+ params: parseCodexResponse(method, CodexNotificationParams[method], params, "notification")
350
+ };
351
+ default:
352
+ return null;
357
353
  }
358
354
  }
359
- function validateCodexUnixSocketPath(socketPath, caller) {
360
- if (typeof socketPath !== "string" || socketPath.length === 0) {
361
- throw new TypeError(`[stitchkit] ${caller}: unix socketPath must be a non-empty string`);
362
- }
363
- if (!socketPath.startsWith("/")) {
364
- throw new TypeError(`[stitchkit] ${caller}: unix socketPath must be an absolute path starting with "/", received ${JSON.stringify(socketPath)}`);
355
+
356
+ // src/agent-executor/codex/classify.ts
357
+ var raw = (type) => ({ source: "codex", type });
358
+ var CODEX_TOOL_ITEMS = new Set([
359
+ "commandExecution",
360
+ "fileChange",
361
+ "mcpToolCall",
362
+ "dynamicToolCall",
363
+ "collabAgentToolCall",
364
+ "webSearch",
365
+ "imageView",
366
+ "sleep",
367
+ "imageGeneration",
368
+ "functionCallOutput"
369
+ ]);
370
+ var STATUSLESS_TOOL_ITEMS = new Set([
371
+ "webSearch",
372
+ "imageView",
373
+ "sleep",
374
+ "functionCallOutput"
375
+ ]);
376
+ var CODEX_CONTENT_ITEMS = new Set([
377
+ "agentMessage",
378
+ "reasoning",
379
+ "userMessage",
380
+ "plan",
381
+ "contextCompaction",
382
+ "hookPrompt",
383
+ "subAgentActivity",
384
+ "enteredReviewMode",
385
+ "exitedReviewMode"
386
+ ]);
387
+ var KNOWN_CODEX_ERROR_CODES = new Set([
388
+ "contextWindowExceeded",
389
+ "sessionBudgetExceeded",
390
+ "usageLimitExceeded",
391
+ "rateLimitExceeded",
392
+ "flexUnavailable",
393
+ "serverOverloaded",
394
+ "modelNotFound",
395
+ "policyCapacityUnavailable",
396
+ "cyberPolicy",
397
+ "bioPolicy",
398
+ "misalignmentPolicyViolation",
399
+ "tooManyDenials",
400
+ "internalServerError",
401
+ "unauthorized",
402
+ "badRequest",
403
+ "threadRollbackFailed",
404
+ "sandboxError",
405
+ "other",
406
+ "inferenceHookDenied"
407
+ ]);
408
+ var KNOWN_CODEX_ERROR_OBJECT_KEYS = new Set([
409
+ "httpConnectionFailed",
410
+ "responseStreamConnectionFailed",
411
+ "responseStreamDisconnected",
412
+ "responseTooManyFailedAttempts",
413
+ "activeTurnNotSteerable"
414
+ ]);
415
+ var MAX_ERROR_INFO_SUMMARY_CHARS = 512;
416
+ function toolName(item) {
417
+ if (item.type === "mcpToolCall" || item.type === "dynamicToolCall" || item.type === "collabAgentToolCall") {
418
+ return nonEmptyString(Reflect.get(item, "tool")) ?? item.type;
365
419
  }
366
- if (/[\0\r\n\s?#]/.test(socketPath)) {
367
- throw new TypeError(`[stitchkit] ${caller}: unix socketPath contains forbidden characters (whitespace, NUL, ?, or #)`);
420
+ if (item.type === "functionCallOutput") {
421
+ return nonEmptyString(Reflect.get(item, "name")) ?? item.type;
368
422
  }
369
- assertUnixSocketPathLength(socketPath, caller);
423
+ return item.type;
370
424
  }
371
- function lstatTarget(targetPath, label, socketPath, caller) {
372
- try {
373
- return lstatSync(targetPath, { throwIfNoEntry: false });
374
- } catch (error) {
375
- if (errnoOf(error) === "ENOENT")
376
- return;
377
- throw new CodexUnixSocketError("target-refused", socketPath, `[stitchkit] ${caller}: failed to inspect unix socket ${label} "${targetPath}"`, { cause: error });
378
- }
425
+ function toolInput(item) {
426
+ const { id: _id, type: _type, status: _status, aggregatedOutput: _output, ...rest } = item;
427
+ return safeJsonValue(rest);
379
428
  }
380
- function assertPrivateDirStats(dir, requiredUid, socketPath, caller) {
381
- const stats = lstatTarget(dir, "directory", socketPath, caller);
382
- if (stats === undefined)
383
- return "absent";
384
- const violation = unixSocketDirectoryViolation(dir, stats, caller, requiredUid);
385
- if (violation !== undefined) {
386
- throw new CodexUnixSocketError("target-refused", socketPath, violation);
429
+ function isKnownCodexErrorInfo(info) {
430
+ if (typeof info === "string")
431
+ return KNOWN_CODEX_ERROR_CODES.has(info);
432
+ if (typeof info === "object" && info !== null && !Array.isArray(info)) {
433
+ const keys = Object.keys(info);
434
+ return keys.length === 1 && keys[0] !== undefined && KNOWN_CODEX_ERROR_OBJECT_KEYS.has(keys[0]);
387
435
  }
388
- return "present";
436
+ return false;
389
437
  }
390
- function assertCodexUnixListenTargetAvailable(socketPath, caller) {
391
- const dir = dirname(socketPath);
392
- const requiredUid = typeof process.getuid === "function" ? process.getuid() : undefined;
393
- if (assertPrivateDirStats(dir, requiredUid, socketPath, caller) === "absent") {
394
- throw new CodexUnixSocketError("target-refused", socketPath, `[stitchkit] ${caller}: unix socket directory "${dir}" does not exist`);
438
+ function formatCodexErrorInfo(info) {
439
+ if (info === null || info === undefined)
440
+ return;
441
+ if (typeof info === "string") {
442
+ const trimmed = info.trim();
443
+ return trimmed.length > 0 ? trimmed.slice(0, MAX_ERROR_INFO_SUMMARY_CHARS) : undefined;
395
444
  }
396
- const existing = lstatTarget(socketPath, "path", socketPath, caller);
397
- if (existing !== undefined) {
398
- throw new CodexUnixSocketError("target-refused", socketPath, `[stitchkit] ${caller}: unix socket path "${socketPath}" already exists — choose a fresh socket path or remove the stale socket first`);
445
+ try {
446
+ const serialized = JSON.stringify(safeJsonValue(info));
447
+ if (serialized === undefined || serialized.length === 0)
448
+ return;
449
+ return serialized.length > MAX_ERROR_INFO_SUMMARY_CHARS ? `${serialized.slice(0, MAX_ERROR_INFO_SUMMARY_CHARS - 1)}…` : serialized;
450
+ } catch {
451
+ return String(info).slice(0, MAX_ERROR_INFO_SUMMARY_CHARS);
399
452
  }
400
453
  }
401
- function assertCodexUnixSocketClientTarget(socketPath, caller, expectedOwnerUid) {
402
- assertExpectedOwnerUid(expectedOwnerUid, caller);
403
- const requiredUid = expectedOwnerUid !== undefined ? expectedOwnerUid : typeof process.getuid === "function" ? process.getuid() : undefined;
404
- if (assertPrivateDirStats(dirname(socketPath), requiredUid, socketPath, caller) === "absent") {
405
- return "absent";
406
- }
407
- const stats = lstatTarget(socketPath, "path", socketPath, caller);
408
- if (stats === undefined)
409
- return "absent";
410
- if (requiredUid !== undefined && stats.uid !== requiredUid) {
411
- throw new CodexUnixSocketError("target-refused", socketPath, `[stitchkit] ${caller}: unix socket "${socketPath}" is owned by uid ${stats.uid}, expected ${requiredUid}`);
412
- }
413
- if (stats.isSymbolicLink()) {
414
- let resolved;
415
- try {
416
- resolved = realpathSync(socketPath);
417
- } catch (error) {
418
- if (errnoOf(error) === "ENOENT")
419
- return "absent";
420
- throw new CodexUnixSocketError("target-refused", socketPath, `[stitchkit] ${caller}: failed to resolve unix socket symlink "${socketPath}"`, { cause: error });
421
- }
422
- if (assertPrivateDirStats(dirname(resolved), requiredUid, socketPath, caller) === "absent") {
423
- return "absent";
424
- }
425
- const targetStats = lstatTarget(resolved, "resolved target", socketPath, caller);
426
- if (targetStats === undefined)
427
- return "absent";
428
- if (!targetStats.isSocket()) {
429
- throw new CodexUnixSocketError("target-refused", socketPath, `[stitchkit] ${caller}: resolved unix socket target "${resolved}" is not a socket`);
430
- }
431
- if (requiredUid !== undefined && targetStats.uid !== requiredUid) {
432
- throw new CodexUnixSocketError("target-refused", socketPath, `[stitchkit] ${caller}: resolved unix socket target "${resolved}" is owned by uid ${targetStats.uid}, expected ${requiredUid}`);
454
+ function codexFailureMessage(turn) {
455
+ const rawMessage = turn.error?.message.trim() ?? "";
456
+ const info = turn.error?.codexErrorInfo;
457
+ const infoSummary = formatCodexErrorInfo(info);
458
+ if (rawMessage.length > 0) {
459
+ if (infoSummary !== undefined && !isKnownCodexErrorInfo(info) && !rawMessage.includes(infoSummary)) {
460
+ return `${rawMessage} (${infoSummary})`;
433
461
  }
434
- return "present";
462
+ return rawMessage;
435
463
  }
436
- if (!stats.isSocket()) {
437
- throw new CodexUnixSocketError("target-refused", socketPath, `[stitchkit] ${caller}: "${socketPath}" is not a unix socket`);
464
+ if (infoSummary !== undefined) {
465
+ return `Codex ended the turn ${turn.status} (${infoSummary})`;
438
466
  }
439
- return "present";
440
- }
441
-
442
- // src/agent-executor/codex/ws-frame.ts
443
- import { randomBytes } from "node:crypto";
444
- var MAX_WS_FRAGMENTS = 1024;
445
- var MAX_CONTROL_PAYLOAD_BYTES = 125;
446
- function maskedWsFrameByteLength(payloadBytes) {
447
- const headerLen = payloadBytes < 126 ? 2 : payloadBytes <= 65535 ? 4 : 10;
448
- return headerLen + 4 + payloadBytes;
449
- }
450
- function encodeMaskedWsFrame(opcode, payload) {
451
- const len = payload.byteLength;
452
- const headerLen = len < 126 ? 2 : len <= 65535 ? 4 : 10;
453
- const frame = Buffer.allocUnsafe(headerLen + 4 + len);
454
- frame[0] = 128 | opcode & 15;
455
- if (len < 126) {
456
- frame[1] = 128 | len;
457
- } else if (len <= 65535) {
458
- frame[1] = 128 | 126;
459
- frame.writeUInt16BE(len, 2);
460
- } else {
461
- frame[1] = 128 | 127;
462
- const hi = Math.floor(len / 4294967296);
463
- const lo = len >>> 0;
464
- frame.writeUInt32BE(hi, 2);
465
- frame.writeUInt32BE(lo, 6);
466
- }
467
- const mask = randomBytes(4);
468
- frame[headerLen] = mask[0] ?? 0;
469
- frame[headerLen + 1] = mask[1] ?? 0;
470
- frame[headerLen + 2] = mask[2] ?? 0;
471
- frame[headerLen + 3] = mask[3] ?? 0;
472
- const bodyOffset = headerLen + 4;
473
- for (let i = 0;i < len; i += 1) {
474
- frame[bodyOffset + i] = (payload[i] ?? 0) ^ (mask[i & 3] ?? 0);
475
- }
476
- return frame;
477
- }
478
- function createByteQueue() {
479
- const chunks = [];
480
- let headOffset = 0;
481
- let total = 0;
482
- return {
483
- get length() {
484
- return total;
485
- },
486
- push(chunk) {
487
- if (chunk.byteLength === 0)
488
- return;
489
- chunks.push(chunk);
490
- total += chunk.byteLength;
491
- },
492
- peekBytes(count) {
493
- const first = chunks[0];
494
- if (first !== undefined && first.byteLength - headOffset >= count) {
495
- return first.subarray(headOffset, headOffset + count);
496
- }
497
- const out = Buffer.allocUnsafe(count);
498
- let written = 0;
499
- let idx = 0;
500
- let off = headOffset;
501
- while (written < count && idx < chunks.length) {
502
- const cur = chunks[idx];
503
- if (cur === undefined)
504
- break;
505
- const take = Math.min(cur.byteLength - off, count - written);
506
- cur.copy(out, written, off, off + take);
507
- written += take;
508
- idx += 1;
509
- off = 0;
510
- }
511
- return out;
512
- },
513
- consume(count) {
514
- const out = Buffer.allocUnsafe(count);
515
- let written = 0;
516
- while (written < count && chunks.length > 0) {
517
- const cur = chunks[0];
518
- if (cur === undefined)
519
- break;
520
- const avail = cur.byteLength - headOffset;
521
- const take = Math.min(avail, count - written);
522
- cur.copy(out, written, headOffset, headOffset + take);
523
- written += take;
524
- total -= take;
525
- if (take === avail) {
526
- chunks.shift();
527
- headOffset = 0;
528
- } else {
529
- headOffset += take;
530
- }
531
- }
532
- return out;
533
- },
534
- skip(count) {
535
- let left = count;
536
- while (left > 0 && chunks.length > 0) {
537
- const cur = chunks[0];
538
- if (cur === undefined)
539
- break;
540
- const avail = cur.byteLength - headOffset;
541
- if (left >= avail) {
542
- chunks.shift();
543
- headOffset = 0;
544
- total -= avail;
545
- left -= avail;
546
- } else {
547
- headOffset += left;
548
- total -= left;
549
- left = 0;
550
- }
551
- }
552
- },
553
- clear() {
554
- chunks.length = 0;
555
- headOffset = 0;
556
- total = 0;
557
- }
558
- };
467
+ return `Codex ended the turn ${turn.status}`;
559
468
  }
560
- function createWsFrameDecoder(handlers) {
561
- const utf8 = new TextDecoder("utf-8", { fatal: true });
562
- const queue = createByteQueue();
563
- let fragments;
564
- let fragmentBytes = 0;
565
- let stopped = false;
566
- const fail = (message) => {
567
- stopped = true;
568
- queue.clear();
569
- fragments = undefined;
570
- fragmentBytes = 0;
571
- handlers.onProtocolError(message);
572
- };
573
- return {
574
- push(chunk) {
575
- if (stopped || chunk.byteLength === 0)
576
- return;
577
- queue.push(chunk);
578
- while (!stopped && queue.length >= 2) {
579
- const head2 = queue.peekBytes(2);
580
- const b0 = head2[0] ?? 0;
581
- const b1 = head2[1] ?? 0;
582
- if ((b0 & 112) !== 0)
583
- return fail("Server WebSocket frame set reserved RSV bits");
584
- if ((b1 & 128) !== 0)
585
- return fail("Server WebSocket frame must not be masked");
586
- const fin = (b0 & 128) !== 0;
587
- const opcode = b0 & 15;
588
- const len7 = b1 & 127;
589
- let headerLen = 2;
590
- let payloadLen = len7;
591
- if (len7 === 126) {
592
- if (queue.length < 4)
593
- break;
594
- headerLen = 4;
595
- payloadLen = queue.peekBytes(4).readUInt16BE(2);
596
- } else if (len7 === 127) {
597
- if (queue.length < 10)
598
- break;
599
- headerLen = 10;
600
- const head10 = queue.peekBytes(10);
601
- const hi = head10.readUInt32BE(2);
602
- const lo = head10.readUInt32BE(6);
603
- if ((hi & 2147483648) !== 0)
604
- return fail("WebSocket 64-bit frame length has MSB set");
605
- payloadLen = hi * 4294967296 + lo;
606
- }
607
- if (opcode >= 8) {
608
- if (!fin)
609
- return fail("Control WebSocket frame must not be fragmented");
610
- if (payloadLen > MAX_CONTROL_PAYLOAD_BYTES) {
611
- return fail(`Control WebSocket frame payload (${payloadLen} bytes) exceeds 125 bytes`);
612
- }
613
- if (opcode !== 8 && opcode !== 9 && opcode !== 10) {
614
- return fail(`Unsupported WebSocket control opcode 0x${opcode.toString(16)}`);
615
- }
616
- } else {
617
- if (opcode !== 0 && opcode !== 1) {
618
- return fail(`Unsupported WebSocket data opcode 0x${opcode.toString(16)}`);
619
- }
620
- if (!Number.isSafeInteger(payloadLen) || payloadLen > handlers.maxFrameBytes) {
621
- return fail(`WebSocket frame payload (${payloadLen} bytes) exceeds maxFrameBytes (${handlers.maxFrameBytes})`);
622
- }
623
- if (opcode === 1 && fragments !== undefined) {
624
- return fail("Interleaved WebSocket text frame during fragmented message");
625
- }
626
- if (opcode === 0 && fragments === undefined) {
627
- return fail("Unexpected WebSocket continuation frame without an active message");
628
- }
629
- if (fragments !== undefined) {
630
- if (fragments.length + 1 > MAX_WS_FRAGMENTS) {
631
- return fail(`Fragmented WebSocket message exceeded ${MAX_WS_FRAGMENTS} frames`);
632
- }
633
- if (fragmentBytes + payloadLen > handlers.maxFrameBytes) {
634
- return fail(`Fragmented WebSocket message exceeded maxFrameBytes (${handlers.maxFrameBytes})`);
635
- }
636
- }
637
- }
638
- if (queue.length < headerLen + payloadLen)
639
- break;
640
- queue.skip(headerLen);
641
- const payload = queue.consume(payloadLen);
642
- if (opcode === 9) {
643
- handlers.onPing(payload);
644
- } else if (opcode === 10) {} else if (opcode === 8) {
645
- if (payload.byteLength === 1)
646
- return fail("WebSocket close frame payload cannot be 1 byte");
647
- const code = payload.byteLength >= 2 ? payload.readUInt16BE(0) : undefined;
648
- let reason = "";
649
- if (payload.byteLength > 2) {
650
- try {
651
- reason = utf8.decode(payload.subarray(2));
652
- } catch {
653
- return fail("WebSocket close frame reason is not valid UTF-8");
654
- }
469
+ function httpStatusOf(value, depth = 0) {
470
+ if (depth > 3 || typeof value !== "object" || value === null)
471
+ return;
472
+ const direct = Reflect.get(value, "httpStatusCode");
473
+ if (typeof direct === "number")
474
+ return direct;
475
+ for (const nested of Object.values(value)) {
476
+ const found = httpStatusOf(nested, depth + 1);
477
+ if (found !== undefined)
478
+ return found;
479
+ }
480
+ return;
481
+ }
482
+ function failureKind(info) {
483
+ if (info === "unauthorized")
484
+ return "authRequired";
485
+ if (info === "usageLimitExceeded" || info === "rateLimitExceeded" || info === "sessionBudgetExceeded")
486
+ return "rateLimited";
487
+ const status = httpStatusOf(info);
488
+ if (status === 401 || status === 403)
489
+ return "authRequired";
490
+ if (status === 429)
491
+ return "rateLimited";
492
+ return "restartRecommended";
493
+ }
494
+ function normalizeCodexTokenTotals(rawTotals) {
495
+ if (rawTotals === undefined)
496
+ return;
497
+ const normalized = {
498
+ ...rawTotals.inputTokens !== undefined && { inputTokens: rawTotals.inputTokens },
499
+ ...rawTotals.outputTokens !== undefined && { outputTokens: rawTotals.outputTokens },
500
+ ...rawTotals.cachedInputTokens !== undefined && {
501
+ cachedInputTokens: rawTotals.cachedInputTokens
502
+ },
503
+ ...rawTotals.cacheWriteInputTokens !== undefined && {
504
+ cacheCreationInputTokens: rawTotals.cacheWriteInputTokens
505
+ },
506
+ ...rawTotals.reasoningOutputTokens !== undefined && {
507
+ thinkingTokens: rawTotals.reasoningOutputTokens
508
+ },
509
+ ...rawTotals.totalTokens !== undefined && { totalTokens: rawTotals.totalTokens }
510
+ };
511
+ return Object.keys(normalized).length > 0 ? normalized : undefined;
512
+ }
513
+ function classifyCodexTokenUsage(params, base) {
514
+ const { last, total } = CodexNotificationParams["thread/tokenUsage/updated"].parse(params).tokenUsage;
515
+ const normalizedTotal = normalizeCodexTokenTotals(total);
516
+ return {
517
+ kind: "deltas",
518
+ deltas: [
519
+ {
520
+ type: "usage",
521
+ ...base,
522
+ itemId: "usage",
523
+ raw: raw("thread/tokenUsage/updated"),
524
+ inputTokens: last.inputTokens,
525
+ outputTokens: last.outputTokens,
526
+ ...last.cachedInputTokens !== undefined && {
527
+ cachedInputTokens: last.cachedInputTokens
528
+ },
529
+ ...last.cacheWriteInputTokens !== undefined && {
530
+ cacheCreationInputTokens: last.cacheWriteInputTokens
531
+ },
532
+ ...last.reasoningOutputTokens !== undefined && {
533
+ thinkingTokens: last.reasoningOutputTokens
534
+ },
535
+ ...last.totalTokens !== undefined && { totalTokens: last.totalTokens },
536
+ ...normalizedTotal !== undefined && { total: normalizedTotal }
537
+ }
538
+ ]
539
+ };
540
+ }
541
+ function classifyCodexNotification(method, params, state) {
542
+ const base = { turnId: state.turnId };
543
+ switch (method) {
544
+ case "item/agentMessage/delta": {
545
+ const p = CodexNotificationParams[method].parse(params);
546
+ return {
547
+ kind: "deltas",
548
+ deltas: [{ type: "text", ...base, itemId: p.itemId, raw: raw(method), text: p.delta }]
549
+ };
550
+ }
551
+ case "item/reasoning/textDelta":
552
+ case "item/reasoning/summaryTextDelta": {
553
+ const p = CodexNotificationParams[method].parse(params);
554
+ return {
555
+ kind: "deltas",
556
+ deltas: [
557
+ { type: "reasoning", ...base, itemId: p.itemId, raw: raw(method), text: p.delta }
558
+ ]
559
+ };
560
+ }
561
+ case "item/started":
562
+ case "item/completed": {
563
+ const { item } = CodexNotificationParams[method].parse(params);
564
+ if (CODEX_CONTENT_ITEMS.has(item.type))
565
+ return { kind: "ignore", reason: `${method} ${item.type}` };
566
+ if (!CODEX_TOOL_ITEMS.has(item.type)) {
567
+ return {
568
+ kind: "unhandled",
569
+ delta: {
570
+ type: "error",
571
+ ...base,
572
+ itemId: `unhandled:${item.id}`,
573
+ raw: raw(`${method}/${item.type}`),
574
+ kind: "unhandled",
575
+ message: `Codex item ${item.type} is not known to this driver`
655
576
  }
656
- stopped = true;
657
- queue.clear();
658
- fragments = undefined;
659
- fragmentBytes = 0;
660
- handlers.onClose(code, reason);
661
- return;
662
- } else if (opcode === 1) {
663
- if (fin) {
664
- let text;
665
- try {
666
- text = utf8.decode(payload);
667
- } catch {
668
- return fail("WebSocket text frame is not valid UTF-8");
577
+ };
578
+ }
579
+ if (method === "item/started") {
580
+ return {
581
+ kind: "deltas",
582
+ deltas: [
583
+ {
584
+ type: "tool-call",
585
+ ...base,
586
+ itemId: `call:${item.id}`,
587
+ raw: raw(method),
588
+ callId: item.id,
589
+ toolName: toolName(item),
590
+ input: toolInput(item)
669
591
  }
670
- handlers.onMessage(text);
671
- } else {
672
- fragments = [payload];
673
- fragmentBytes = payload.byteLength;
674
- }
675
- } else if (opcode === 0 && fragments !== undefined) {
676
- fragments.push(payload);
677
- fragmentBytes += payload.byteLength;
678
- if (fin) {
679
- const combined = Buffer.concat(fragments, fragmentBytes);
680
- fragments = undefined;
681
- fragmentBytes = 0;
682
- let text;
683
- try {
684
- text = utf8.decode(combined);
685
- } catch {
686
- return fail("Reassembled WebSocket text message is not valid UTF-8");
592
+ ]
593
+ };
594
+ }
595
+ const status = Reflect.get(item, "status");
596
+ const failure = Reflect.get(item, "failure");
597
+ const output = failure ?? Reflect.get(item, "aggregatedOutput") ?? Reflect.get(item, "output") ?? Reflect.get(item, "savedPath") ?? Reflect.get(item, "fileId") ?? Reflect.get(item, "result") ?? Reflect.get(item, "results") ?? Reflect.get(item, "contentItems") ?? Reflect.get(item, "changes") ?? Reflect.get(item, "agentsStates") ?? Reflect.get(item, "error");
598
+ const hasFailure = failure !== undefined && failure !== null;
599
+ const outcome = !hasFailure && (status === "completed" || STATUSLESS_TOOL_ITEMS.has(item.type) && status === undefined) ? "success" : status === "declined" || status === "interrupted" ? "interrupted" : "error";
600
+ return {
601
+ kind: "deltas",
602
+ deltas: [
603
+ {
604
+ type: "tool-result",
605
+ ...base,
606
+ itemId: `result:${item.id}`,
607
+ raw: raw(method),
608
+ callId: item.id,
609
+ toolName: toolName(item),
610
+ outcome,
611
+ ...output !== undefined && output !== null && {
612
+ output: safeJsonValue(output)
687
613
  }
688
- handlers.onMessage(text);
689
614
  }
690
- }
615
+ ]
616
+ };
617
+ }
618
+ case "turn/completed": {
619
+ const { turn } = CodexNotificationParams[method].parse(params);
620
+ const outcome = state.interruptRequested ? "interrupted" : turn.status === "completed" ? "completed" : turn.status === "interrupted" ? "interrupted" : "failed";
621
+ const deltas = [];
622
+ if (outcome === "failed") {
623
+ deltas.push({
624
+ type: "error",
625
+ ...base,
626
+ itemId: "failure",
627
+ raw: raw(method),
628
+ kind: failureKind(turn.error?.codexErrorInfo),
629
+ message: codexFailureMessage(turn)
630
+ });
691
631
  }
632
+ deltas.push({ type: "turn-end", ...base, itemId: "end", raw: raw(method), outcome });
633
+ return { kind: "end", deltas, outcome };
692
634
  }
693
- };
635
+ case "thread/tokenUsage/updated":
636
+ return classifyCodexTokenUsage(params, base);
637
+ case "serverRequest/resolved":
638
+ return {
639
+ kind: "resolved",
640
+ requestId: String(CodexNotificationParams[method].parse(params).requestId)
641
+ };
642
+ case "account/rateLimits/updated": {
643
+ const parsed = CodexNotificationParams[method].parse(params);
644
+ return {
645
+ kind: "limits",
646
+ rateLimits: parsed.rateLimitsByLimitId !== undefined ? {
647
+ rateLimits: parsed.rateLimits,
648
+ rateLimitsByLimitId: parsed.rateLimitsByLimitId
649
+ } : parsed.rateLimits
650
+ };
651
+ }
652
+ default:
653
+ if (CODEX_QUIET_NOTIFICATIONS.has(method))
654
+ return { kind: "ignore", reason: method };
655
+ return {
656
+ kind: "unhandled",
657
+ delta: {
658
+ type: "error",
659
+ ...base,
660
+ itemId: `unhandled:${method}`,
661
+ raw: raw(method),
662
+ kind: "unhandled",
663
+ message: `Codex notification ${method} is not known to this driver`
664
+ }
665
+ };
666
+ }
694
667
  }
695
-
696
668
  // src/agent-executor/codex/unix-socket.ts
669
+ import { createHash, randomBytes } from "node:crypto";
670
+ import { createConnection } from "node:net";
697
671
  var WS_MAGIC_GUID = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
698
672
  var MAX_HANDSHAKE_HEADER_BYTES = 64 * 1024;
699
673
  var DEFAULT_HANDSHAKE_TIMEOUT_MS = 15000;
@@ -705,7 +679,7 @@ function validateHandshakeResponse(headerText, expectedAccept, socketPath) {
705
679
  `);
706
680
  const statusLine = lines[0] ?? "";
707
681
  if (!/^HTTP\/1\.1 101(?:\s|$)/.test(statusLine)) {
708
- throw new CodexUnixSocketError("upgrade-refused", socketPath, `Codex Unix socket WebSocket upgrade failed: ${statusLine || "empty response"}`);
682
+ throw new CodexUnixSocketError2("upgrade-refused", socketPath, `Codex Unix socket WebSocket upgrade failed: ${statusLine || "empty response"}`);
709
683
  }
710
684
  const headers = new Map;
711
685
  for (let i = 1;i < lines.length; i += 1) {
@@ -714,7 +688,7 @@ function validateHandshakeResponse(headerText, expectedAccept, socketPath) {
714
688
  continue;
715
689
  const colon = line.indexOf(":");
716
690
  if (colon <= 0) {
717
- throw new CodexUnixSocketError("upgrade-refused", socketPath, "Codex Unix socket upgrade response contained a malformed HTTP header line");
691
+ throw new CodexUnixSocketError2("upgrade-refused", socketPath, "Codex Unix socket upgrade response contained a malformed HTTP header line");
718
692
  }
719
693
  const key = line.slice(0, colon).trim().toLowerCase();
720
694
  const value = line.slice(colon + 1).trim();
@@ -722,30 +696,30 @@ function validateHandshakeResponse(headerText, expectedAccept, socketPath) {
722
696
  headers.set(key, existing === undefined ? value : `${existing}, ${value}`);
723
697
  }
724
698
  if ((headers.get("upgrade") ?? "").toLowerCase() !== "websocket") {
725
- throw new CodexUnixSocketError("upgrade-refused", socketPath, 'Codex Unix socket upgrade response missing "Upgrade: websocket" header');
699
+ throw new CodexUnixSocketError2("upgrade-refused", socketPath, 'Codex Unix socket upgrade response missing "Upgrade: websocket" header');
726
700
  }
727
701
  const connectionTokens = (headers.get("connection") ?? "").toLowerCase().split(",").map((token) => token.trim());
728
702
  if (!connectionTokens.includes("upgrade")) {
729
- throw new CodexUnixSocketError("upgrade-refused", socketPath, 'Codex Unix socket upgrade response missing "Connection: upgrade" header');
703
+ throw new CodexUnixSocketError2("upgrade-refused", socketPath, 'Codex Unix socket upgrade response missing "Connection: upgrade" header');
730
704
  }
731
705
  if (headers.get("sec-websocket-accept") !== expectedAccept) {
732
- throw new CodexUnixSocketError("upgrade-refused", socketPath, "Codex Unix socket upgrade response returned an invalid Sec-WebSocket-Accept header");
706
+ throw new CodexUnixSocketError2("upgrade-refused", socketPath, "Codex Unix socket upgrade response returned an invalid Sec-WebSocket-Accept header");
733
707
  }
734
708
  }
735
709
  function classifyConnectError(error, socketPath) {
736
710
  const code = errnoOf(error);
737
711
  if (code === "ENOENT") {
738
- return new CodexUnixSocketError("endpoint-absent", socketPath, `Codex Unix socket "${socketPath}" does not exist`, { cause: error });
712
+ return new CodexUnixSocketError2("endpoint-absent", socketPath, `Codex Unix socket "${socketPath}" does not exist`, { cause: error });
739
713
  }
740
714
  if (code === "ECONNREFUSED") {
741
- return new CodexUnixSocketError("endpoint-not-listening", socketPath, `Codex Unix socket "${socketPath}" refused connection`, { cause: error });
715
+ return new CodexUnixSocketError2("endpoint-not-listening", socketPath, `Codex Unix socket "${socketPath}" refused connection`, { cause: error });
742
716
  }
743
- return new CodexUnixSocketError("connection-lost", socketPath, `Failed to connect to Codex Unix socket "${socketPath}": ${error instanceof Error ? error.message : String(error)}`, { cause: error });
717
+ return new CodexUnixSocketError2("connection-lost", socketPath, `Failed to connect to Codex Unix socket "${socketPath}": ${error instanceof Error ? error.message : String(error)}`, { cause: error });
744
718
  }
745
719
  function performWsUpgrade(input) {
746
- const wsKey = randomBytes2(16).toString("base64");
720
+ const wsKey = randomBytes(16).toString("base64");
747
721
  const expectedAccept = createHash("sha1").update(`${wsKey}${WS_MAGIC_GUID}`).digest("base64");
748
- return withSignalDeadline(input.handshakeTimeoutMs, input.signal, () => new CodexUnixSocketError("upgrade-refused", input.socketPath, `Codex Unix socket WebSocket handshake timed out after ${input.handshakeTimeoutMs} ms`), (handshakeSignal) => new Promise((resolve, reject) => {
722
+ return withSignalDeadline(input.handshakeTimeoutMs, input.signal, () => new CodexUnixSocketError2("upgrade-refused", input.socketPath, `Codex Unix socket WebSocket handshake timed out after ${input.handshakeTimeoutMs} ms`), (handshakeSignal) => new Promise((resolve, reject) => {
749
723
  let settled = false;
750
724
  let handshakeBuf = Buffer.alloc(0);
751
725
  const sock = createConnection({ path: input.socketPath });
@@ -778,7 +752,7 @@ Sec-WebSocket-Version: 13\r
778
752
  const onData = (chunk) => {
779
753
  const combinedLen = handshakeBuf.byteLength + chunk.byteLength;
780
754
  if (handshakeBuf.byteLength > MAX_HANDSHAKE_HEADER_BYTES) {
781
- fail(new CodexUnixSocketError("upgrade-refused", input.socketPath, `Codex Unix socket upgrade headers exceeded ${MAX_HANDSHAKE_HEADER_BYTES} bytes`));
755
+ fail(new CodexUnixSocketError2("upgrade-refused", input.socketPath, `Codex Unix socket upgrade headers exceeded ${MAX_HANDSHAKE_HEADER_BYTES} bytes`));
782
756
  return;
783
757
  }
784
758
  const nextBuf = handshakeBuf.byteLength === 0 ? chunk : Buffer.concat([handshakeBuf, chunk]);
@@ -787,14 +761,14 @@ Sec-WebSocket-Version: 13\r
787
761
  `);
788
762
  if (boundary === -1) {
789
763
  if (combinedLen > MAX_HANDSHAKE_HEADER_BYTES) {
790
- fail(new CodexUnixSocketError("upgrade-refused", input.socketPath, `Codex Unix socket upgrade headers exceeded ${MAX_HANDSHAKE_HEADER_BYTES} bytes`));
764
+ fail(new CodexUnixSocketError2("upgrade-refused", input.socketPath, `Codex Unix socket upgrade headers exceeded ${MAX_HANDSHAKE_HEADER_BYTES} bytes`));
791
765
  return;
792
766
  }
793
767
  handshakeBuf = nextBuf;
794
768
  return;
795
769
  }
796
770
  if (boundary > MAX_HANDSHAKE_HEADER_BYTES) {
797
- fail(new CodexUnixSocketError("upgrade-refused", input.socketPath, `Codex Unix socket upgrade headers exceeded ${MAX_HANDSHAKE_HEADER_BYTES} bytes`));
771
+ fail(new CodexUnixSocketError2("upgrade-refused", input.socketPath, `Codex Unix socket upgrade headers exceeded ${MAX_HANDSHAKE_HEADER_BYTES} bytes`));
798
772
  return;
799
773
  }
800
774
  const headerText = nextBuf.subarray(0, boundary).toString("latin1");
@@ -811,7 +785,7 @@ Sec-WebSocket-Version: 13\r
811
785
  resolve({ socket: sock, trailing: rest });
812
786
  };
813
787
  const onError = (error) => fail(classifyConnectError(error, input.socketPath));
814
- const onClose = () => fail(new CodexUnixSocketError("upgrade-refused", input.socketPath, "Codex Unix socket closed before completing WebSocket upgrade"));
788
+ const onClose = () => fail(new CodexUnixSocketError2("upgrade-refused", input.socketPath, "Codex Unix socket closed before completing WebSocket upgrade"));
815
789
  handshakeSignal.addEventListener("abort", onAbort, { once: true });
816
790
  sock.once("connect", onConnect);
817
791
  sock.on("data", onData);
@@ -828,7 +802,7 @@ async function connectCodexUnixSocket(input) {
828
802
  input.connectSignal?.throwIfAborted();
829
803
  const targetState = assertCodexUnixSocketClientTarget(input.socketPath, "connectCodexUnixSocket", input.expectedOwnerUid);
830
804
  if (targetState === "absent") {
831
- throw new CodexUnixSocketError("endpoint-absent", input.socketPath, `Codex Unix socket "${input.socketPath}" does not exist`);
805
+ throw new CodexUnixSocketError2("endpoint-absent", input.socketPath, `Codex Unix socket "${input.socketPath}" does not exist`);
832
806
  }
833
807
  const maxFrameBytes = input.maxFrameBytes ?? DEFAULT_MAX_FRAME_BYTES;
834
808
  const maxPendingWriteBytes = input.maxPendingWriteBytes ?? DEFAULT_MAX_PENDING_WRITE_BYTES;
@@ -842,7 +816,7 @@ async function connectCodexUnixSocket(input) {
842
816
  throw abortReason(input.signal);
843
817
  }
844
818
  if (socket.destroyed) {
845
- throw new CodexUnixSocketError("connection-lost", input.socketPath, `Codex Unix socket "${input.socketPath}" closed during WebSocket upgrade`);
819
+ throw new CodexUnixSocketError2("connection-lost", input.socketPath, `Codex Unix socket "${input.socketPath}" closed during WebSocket upgrade`);
846
820
  }
847
821
  let closed = false;
848
822
  let closeSent = false;
@@ -887,7 +861,7 @@ async function connectCodexUnixSocket(input) {
887
861
  }
888
862
  };
889
863
  const onSignalAbort = () => {
890
- const err = new CodexUnixSocketError("connection-lost", input.socketPath, "Codex Unix socket connection aborted", { cause: abortReason(input.signal) });
864
+ const err = new CodexUnixSocketError2("connection-lost", input.socketPath, "Codex Unix socket connection aborted", { cause: abortReason(input.signal) });
891
865
  socket.destroy();
892
866
  finishClosed(err);
893
867
  };
@@ -903,20 +877,20 @@ async function connectCodexUnixSocket(input) {
903
877
  }
904
878
  socket.end();
905
879
  const suffix = reason.length > 0 ? `: ${reason}` : "";
906
- finishClosed(new CodexUnixSocketError("connection-lost", input.socketPath, `Codex Unix socket closed by peer (${code ?? "no-code"})${suffix}`));
880
+ finishClosed(new CodexUnixSocketError2("connection-lost", input.socketPath, `Codex Unix socket closed by peer (${code ?? "no-code"})${suffix}`));
907
881
  },
908
882
  onProtocolError: (message) => {
909
- const err = new CodexUnixSocketError("connection-lost", input.socketPath, message);
883
+ const err = new CodexUnixSocketError2("connection-lost", input.socketPath, message);
910
884
  socket.destroy();
911
885
  finishClosed(err);
912
886
  }
913
887
  });
914
888
  socket.on("data", (chunk) => decoder.push(chunk));
915
889
  socket.on("error", (error) => {
916
- finishClosed(new CodexUnixSocketError("connection-lost", input.socketPath, `Codex Unix socket error: ${error.message}`, { cause: error }));
890
+ finishClosed(new CodexUnixSocketError2("connection-lost", input.socketPath, `Codex Unix socket error: ${error.message}`, { cause: error }));
917
891
  });
918
892
  socket.on("close", () => {
919
- finishClosed(new CodexUnixSocketError("connection-lost", input.socketPath, `Codex Unix socket "${input.socketPath}" closed`));
893
+ finishClosed(new CodexUnixSocketError2("connection-lost", input.socketPath, `Codex Unix socket "${input.socketPath}" closed`));
920
894
  });
921
895
  if (trailing.byteLength > 0)
922
896
  decoder.push(trailing);
@@ -925,7 +899,7 @@ async function connectCodexUnixSocket(input) {
925
899
  return {
926
900
  send(text) {
927
901
  if (closed || socket.destroyed || !socket.writable) {
928
- throw new CodexUnixSocketError("connection-lost", input.socketPath, "Codex Unix socket connection is closed");
902
+ throw new CodexUnixSocketError2("connection-lost", input.socketPath, "Codex Unix socket connection is closed");
929
903
  }
930
904
  const payloadBytes = Buffer.byteLength(text, "utf8");
931
905
  const frameBytes = maskedWsFrameByteLength(payloadBytes);
@@ -985,7 +959,7 @@ async function initializeCodexPeer(peer, version) {
985
959
  optOutNotificationMethods: CODEX_OPTED_OUT_NOTIFICATIONS
986
960
  }
987
961
  }, { timeoutMs: BOOTSTRAP_MS });
988
- const parsed = CodexInitializeResponseSchema.parse(reply);
962
+ const parsed = parseCodexResponse("initialize", CodexInitializeResponseSchema, reply);
989
963
  peer.notify("initialized");
990
964
  return nonEmptyString(parsed.userAgent);
991
965
  }
@@ -1016,7 +990,7 @@ async function dialWithEngineRace(input) {
1016
990
  exitedEarly = new Error(`Codex app-server failed before listening on "${input.socketPath}": ${error instanceof Error ? error.message : String(error)}${detail.length > 0 ? ` (${detail})` : ""}`, { cause: error });
1017
991
  exitAbort.abort(exitedEarly);
1018
992
  });
1019
- return withSignalDeadline(input.listenTimeoutMs, input.signal, () => new CodexUnixSocketError("endpoint-absent", input.socketPath, `Codex app-server did not listen on "${input.socketPath}" within ${input.listenTimeoutMs} ms`), async (deadlineSignal) => {
993
+ return withSignalDeadline(input.listenTimeoutMs, input.signal, () => new CodexUnixSocketError2("endpoint-absent", input.socketPath, `Codex app-server did not listen on "${input.socketPath}" within ${input.listenTimeoutMs} ms`), async (deadlineSignal) => {
1020
994
  let delayMs = POLL_INITIAL_MS;
1021
995
  for (;; ) {
1022
996
  if (exitedEarly !== undefined)
@@ -1038,7 +1012,7 @@ async function dialWithEngineRace(input) {
1038
1012
  } catch (error) {
1039
1013
  if (exitedEarly !== undefined)
1040
1014
  throw exitedEarly;
1041
- const retryable = error instanceof CodexUnixSocketError && (error.kind === "endpoint-absent" || error.kind === "endpoint-not-listening");
1015
+ const retryable = error instanceof CodexUnixSocketError2 && (error.kind === "endpoint-absent" || error.kind === "endpoint-not-listening");
1042
1016
  if (!retryable)
1043
1017
  throw error;
1044
1018
  await raceAbort(sleepAbortable(delayMs, deadlineSignal), exitAbort.signal);
@@ -1231,134 +1205,199 @@ async function connectCodex(config, profile, cwd, signal, handlers = {}, onEnd =
1231
1205
  }
1232
1206
  }
1233
1207
 
1234
- // src/agent-executor/codex/limits.ts
1208
+ // src/agent-executor/codex/responses.ts
1235
1209
  import { z as z2 } from "zod";
1236
- var MAX_WINDOW_NAME_CHARS = 256;
1237
- var MAX_PLAN_WINDOWS = 32;
1238
- var WindowSchema = z2.looseObject({
1239
- usedPercent: z2.number().min(0),
1240
- windowDurationMins: z2.number().positive().nullable().optional(),
1241
- resetsAt: z2.number().nonnegative().nullable().optional()
1210
+ var KNOWN_ACCOUNT_TYPES = new Set(["apiKey", "chatgpt", "amazonBedrock", "gcp"]);
1211
+ var CodexEmptyResponseSchema = z2.looseObject({});
1212
+ var CodexReadThreadResponseSchema = z2.looseObject({
1213
+ thread: CodexThreadSchema2,
1214
+ readState: JsonRpcValueSchema2.nullable().optional()
1215
+ });
1216
+ var CodexResumeThreadResponseSchema = CodexStartedThreadSchema;
1217
+ var CodexThreadItemEntrySchema = z2.looseObject({
1218
+ turnId: z2.string(),
1219
+ item: CodexThreadItemSchema2,
1220
+ outputDeferred: z2.boolean().optional(),
1221
+ startedAtMs: z2.number().int().nullable().optional(),
1222
+ completedAtMs: z2.number().int().nullable().optional()
1223
+ });
1224
+ var CodexItemsPageSchema = z2.looseObject({
1225
+ data: z2.array(CodexThreadItemEntrySchema),
1226
+ nextCursor: z2.string().nullable().optional(),
1227
+ backwardsCursor: z2.string().nullable().optional()
1228
+ });
1229
+ var CodexThreadsPageSchema = z2.looseObject({
1230
+ data: z2.array(CodexThreadSchema2),
1231
+ nextCursor: z2.string().nullable().optional(),
1232
+ backwardsCursor: z2.string().nullable().optional(),
1233
+ readStates: z2.record(z2.string(), JsonRpcValueSchema2.nullable()).nullable().optional()
1234
+ });
1235
+ var CodexLoadedThreadsPageSchema = z2.looseObject({
1236
+ data: z2.array(z2.string()),
1237
+ nextCursor: z2.string().nullable().optional()
1238
+ });
1239
+ var CodexReasoningEffortOptionSchema = z2.looseObject({
1240
+ reasoningEffort: z2.string(),
1241
+ description: z2.string().optional()
1242
+ });
1243
+ var CodexModelSchema = z2.looseObject({
1244
+ id: z2.string().min(1),
1245
+ model: z2.string().optional(),
1246
+ displayName: z2.string().optional(),
1247
+ description: z2.string().optional(),
1248
+ hidden: z2.boolean().optional(),
1249
+ isDefault: z2.boolean().optional(),
1250
+ defaultReasoningEffort: z2.string().optional(),
1251
+ supportedReasoningEfforts: z2.array(CodexReasoningEffortOptionSchema).optional(),
1252
+ inputModalities: z2.array(z2.string()).optional(),
1253
+ upgrade: z2.string().nullable().optional(),
1254
+ defaultServiceTier: z2.string().nullable().optional(),
1255
+ modelSpecialty: z2.string().nullable().optional()
1256
+ });
1257
+ var CodexModelsPageSchema = z2.looseObject({
1258
+ data: z2.array(CodexModelSchema),
1259
+ nextCursor: z2.string().nullable().optional()
1260
+ });
1261
+ var CodexSkillMetadataSchema = z2.looseObject({
1262
+ name: z2.string(),
1263
+ description: z2.string().optional(),
1264
+ path: z2.string().optional(),
1265
+ scope: z2.string().optional(),
1266
+ enabled: z2.boolean().optional(),
1267
+ pluginId: z2.string().nullable().optional(),
1268
+ shortDescription: z2.string().nullable().optional(),
1269
+ interface: JsonRpcValueSchema2.nullable().optional(),
1270
+ dependencies: JsonRpcValueSchema2.nullable().optional()
1271
+ });
1272
+ var CodexSkillErrorInfoSchema = z2.looseObject({
1273
+ path: z2.string(),
1274
+ message: z2.string()
1275
+ });
1276
+ var CodexSkillsListEntrySchema = z2.looseObject({
1277
+ cwd: z2.string(),
1278
+ skills: z2.array(CodexSkillMetadataSchema),
1279
+ errors: z2.array(CodexSkillErrorInfoSchema).optional()
1280
+ });
1281
+ var CodexSkillsListResponseSchema = z2.looseObject({
1282
+ data: z2.array(CodexSkillsListEntrySchema)
1283
+ });
1284
+ var CodexCollaborationModePresetSchema = z2.looseObject({
1285
+ name: z2.string(),
1286
+ mode: z2.string().nullable().optional(),
1287
+ model: z2.string().nullable().optional(),
1288
+ reasoning_effort: z2.string().nullable().optional()
1289
+ });
1290
+ var CodexCollaborationModesResponseSchema = z2.looseObject({
1291
+ data: z2.array(CodexCollaborationModePresetSchema)
1242
1292
  });
1243
- var SnapshotSchema = z2.looseObject({
1293
+ var CodexMcpServerStatusSchema = z2.looseObject({
1294
+ name: z2.string(),
1295
+ authStatus: z2.string().optional(),
1296
+ runtimeStatus: z2.union([z2.string(), z2.looseObject({ type: z2.string() })]).nullable().optional(),
1297
+ tools: z2.record(z2.string(), JsonRpcValueSchema2).optional(),
1298
+ resources: z2.array(JsonRpcValueSchema2).optional(),
1299
+ resourceTemplates: z2.array(JsonRpcValueSchema2).optional(),
1300
+ environmentId: z2.string().nullable().optional(),
1301
+ httpOrigin: z2.string().nullable().optional(),
1302
+ pluginId: z2.string().nullable().optional(),
1303
+ serverInfo: JsonRpcValueSchema2.nullable().optional(),
1304
+ serverCapabilities: JsonRpcValueSchema2.optional(),
1305
+ toolListMeta: JsonRpcValueSchema2.optional(),
1306
+ toolsError: z2.string().nullable().optional()
1307
+ });
1308
+ var CodexMcpServerStatusPageSchema = z2.looseObject({
1309
+ data: z2.array(CodexMcpServerStatusSchema),
1310
+ nextCursor: z2.string().nullable().optional()
1311
+ });
1312
+ var CodexConfigSchema = z2.looseObject({
1313
+ model: z2.string().nullable().optional(),
1314
+ model_provider: z2.string().nullable().optional(),
1315
+ model_reasoning_effort: z2.string().nullable().optional(),
1316
+ model_reasoning_summary: z2.string().nullable().optional(),
1317
+ model_verbosity: z2.string().nullable().optional(),
1318
+ model_context_window: z2.number().int().nullable().optional(),
1319
+ approval_policy: CodexApprovalPolicySchema2.nullable().optional(),
1320
+ approvals_reviewer: z2.string().nullable().optional(),
1321
+ sandbox_mode: z2.string().nullable().optional(),
1322
+ service_tier: z2.string().nullable().optional(),
1323
+ review_model: z2.string().nullable().optional(),
1324
+ instructions: z2.string().nullable().optional(),
1325
+ developer_instructions: z2.string().nullable().optional(),
1326
+ compact_prompt: z2.string().nullable().optional()
1327
+ });
1328
+ var CodexConfigLayerMetadataSchema = z2.looseObject({
1329
+ name: JsonRpcValueSchema2,
1330
+ version: z2.string()
1331
+ });
1332
+ var CodexConfigReadResponseSchema = z2.looseObject({
1333
+ config: CodexConfigSchema,
1334
+ origins: z2.record(z2.string(), CodexConfigLayerMetadataSchema).optional(),
1335
+ layers: z2.array(JsonRpcValueSchema2).nullable().optional()
1336
+ });
1337
+ var CodexAccountSchema = z2.union([
1338
+ z2.looseObject({ type: z2.literal("apiKey") }),
1339
+ z2.looseObject({
1340
+ type: z2.literal("chatgpt"),
1341
+ email: z2.string().nullable().optional(),
1342
+ planType: z2.string().nullable().optional(),
1343
+ workspaceName: z2.string().nullable().optional()
1344
+ }),
1345
+ z2.looseObject({
1346
+ type: z2.literal("amazonBedrock"),
1347
+ usesCodexManagedCredentials: z2.boolean().optional()
1348
+ }),
1349
+ z2.looseObject({ type: z2.literal("gcp") }),
1350
+ unknownTypedRecordSchema(KNOWN_ACCOUNT_TYPES)
1351
+ ]);
1352
+ var CodexAccountReadResponseSchema = z2.looseObject({
1353
+ account: CodexAccountSchema.nullable().optional(),
1354
+ requiresOpenaiAuth: z2.boolean(),
1355
+ userId: z2.string().nullable().optional(),
1356
+ workspaceRouting: JsonRpcValueSchema2.nullable().optional()
1357
+ });
1358
+ var CodexRateLimitWindowSchema = z2.looseObject({
1359
+ usedPercent: z2.number(),
1360
+ windowDurationMins: z2.number().int().nullable().optional(),
1361
+ resetsAt: z2.number().int().nullable().optional()
1362
+ });
1363
+ var CodexRateLimitSnapshotSchema = z2.looseObject({
1244
1364
  limitId: z2.string().nullable().optional(),
1245
1365
  limitName: z2.string().nullable().optional(),
1246
- primary: WindowSchema.nullable().optional(),
1247
- secondary: WindowSchema.nullable().optional()
1366
+ normalModelSlug: z2.string().nullable().optional(),
1367
+ planType: z2.string().nullable().optional(),
1368
+ primary: CodexRateLimitWindowSchema.nullable().optional(),
1369
+ secondary: CodexRateLimitWindowSchema.nullable().optional(),
1370
+ credits: JsonRpcValueSchema2.nullable().optional(),
1371
+ individualLimit: JsonRpcValueSchema2.nullable().optional(),
1372
+ rateLimitReachedType: z2.string().nullable().optional(),
1373
+ spendControlReached: z2.boolean().nullable().optional()
1374
+ });
1375
+ var CodexRateLimitsResponseSchema = z2.looseObject({
1376
+ rateLimits: CodexRateLimitSnapshotSchema,
1377
+ rateLimitsByLimitId: z2.record(z2.string(), CodexRateLimitSnapshotSchema).nullable().optional(),
1378
+ accountId: z2.string().nullable().optional(),
1379
+ ordinaryUsageAllowed: z2.boolean().nullable().optional(),
1380
+ rateLimitResetCredits: JsonRpcValueSchema2.nullable().optional(),
1381
+ rateLimitUpsell: JsonRpcValueSchema2.optional()
1382
+ });
1383
+ var CodexThreadUnsubscribeStatusSchema = z2.union([
1384
+ z2.enum(["notLoaded", "notSubscribed", "unsubscribed"]),
1385
+ z2.custom((value) => typeof value === "string" && value.length > 0, {
1386
+ message: "Expected a non-empty ThreadUnsubscribeStatus string"
1387
+ })
1388
+ ]);
1389
+ var CodexThreadUnsubscribeResponseSchema = z2.looseObject({
1390
+ status: CodexThreadUnsubscribeStatusSchema
1391
+ });
1392
+ var CodexThreadUnarchiveResponseSchema = z2.looseObject({
1393
+ thread: CodexThreadSchema2
1394
+ });
1395
+ var CodexThreadMetadataUpdateResponseSchema = z2.looseObject({
1396
+ thread: CodexThreadSchema2
1248
1397
  });
1249
- function positiveSafeInt(value) {
1250
- return isPositiveSafeInteger(value) ? value : undefined;
1251
- }
1252
- function clampLabel(value) {
1253
- const trimmed = nonEmptyString(value)?.trim();
1254
- if (trimmed === undefined)
1255
- return;
1256
- return trimmed.slice(0, MAX_WINDOW_NAME_CHARS);
1257
- }
1258
- function appendBucketWindows(out, seenNames, bucketId, seedKey, snapshot) {
1259
- const label = clampLabel(snapshot.limitName);
1260
- const primary = snapshot.primary ?? undefined;
1261
- const secondary = snapshot.secondary ?? undefined;
1262
- const primaryMins = positiveSafeInt(primary?.windowDurationMins);
1263
- const secondaryMins = positiveSafeInt(secondary?.windowDurationMins);
1264
- const duplicateDuration = primary !== undefined && secondary !== undefined && primaryMins !== undefined && primaryMins === secondaryMins;
1265
- const slots = [
1266
- ["primary", primary, primaryMins],
1267
- ["secondary", secondary, secondaryMins]
1268
- ];
1269
- for (const [slot, window, mins] of slots) {
1270
- if (window === undefined || out.length >= MAX_PLAN_WINDOWS)
1271
- continue;
1272
- const suffix = mins === undefined ? `:${slot}` : duplicateDuration ? `:${mins}m:${slot}` : `:${mins}m`;
1273
- const name = clampUniqueWindowName(bucketId, suffix, seenNames, `${seedKey}:${bucketId}:${slot}`, MAX_WINDOW_NAME_CHARS);
1274
- const resetsAt = window.resetsAt !== undefined && window.resetsAt !== null && window.resetsAt > 0 ? epochSecondsToIso(window.resetsAt) : undefined;
1275
- out.push(PlanWindowSchema2.parse({
1276
- name,
1277
- usedPercent: Math.min(100, window.usedPercent),
1278
- ...resetsAt !== undefined && { resetsAt },
1279
- ...mins !== undefined && { windowDurationMins: mins },
1280
- ...label !== undefined && { label }
1281
- }));
1282
- }
1283
- }
1284
- function isPlainRecord(value) {
1285
- return typeof value === "object" && value !== null && !Array.isArray(value);
1286
- }
1287
- function codexPlanWindows(reported) {
1288
- const windows = [];
1289
- const seenNames = new Set;
1290
- if (isPlainRecord(reported) && (("rateLimits" in reported) || ("rateLimitsByLimitId" in reported))) {
1291
- const seenLimitIds = new Set;
1292
- const rawById = reported.rateLimitsByLimitId;
1293
- if (isPlainRecord(rawById)) {
1294
- for (const mapKey of Object.keys(rawById).sort((a, b) => a.localeCompare(b))) {
1295
- const parsed = SnapshotSchema.safeParse(rawById[mapKey]);
1296
- if (!parsed.success)
1297
- continue;
1298
- const limitId = nonEmptyString(parsed.data.limitId)?.trim() ?? nonEmptyString(mapKey)?.trim() ?? "limit";
1299
- seenLimitIds.add(limitId);
1300
- appendBucketWindows(windows, seenNames, limitId, mapKey, parsed.data);
1301
- if (windows.length >= MAX_PLAN_WINDOWS)
1302
- return windows;
1303
- }
1304
- }
1305
- if (windows.length < MAX_PLAN_WINDOWS && reported.rateLimits !== undefined) {
1306
- const parsedSingle = SnapshotSchema.safeParse(reported.rateLimits);
1307
- if (parsedSingle.success) {
1308
- const explicitId = nonEmptyString(parsedSingle.data.limitId)?.trim();
1309
- const shouldIncludeSingle = seenLimitIds.size === 0 || explicitId !== undefined && !seenLimitIds.has(explicitId);
1310
- if (shouldIncludeSingle) {
1311
- appendBucketWindows(windows, seenNames, explicitId ?? "limit", explicitId ?? "rateLimits", parsedSingle.data);
1312
- }
1313
- }
1314
- }
1315
- return windows;
1316
- }
1317
- const single = SnapshotSchema.safeParse(reported);
1318
- if (!single.success)
1319
- return [];
1320
- const limitId = nonEmptyString(single.data.limitId)?.trim() ?? "limit";
1321
- appendBucketWindows(windows, seenNames, limitId, limitId, single.data);
1322
- return windows;
1323
- }
1324
1398
 
1325
- // src/agent-executor/codex/thread-controls.ts
1326
- var MAX_UINT32 = 4294967295;
1399
+ // src/agent-executor/codex/thread-list-query.ts
1327
1400
  var MAX_THREAD_LIST_IDS = 100;
1328
- function assertNonEmptyThreadId(threadId, caller) {
1329
- if (typeof threadId !== "string" || threadId.trim().length === 0) {
1330
- throw new TypeError(`[stitchkit] ${caller}: threadId must be a non-empty string`);
1331
- }
1332
- return threadId;
1333
- }
1334
- function assertRequiredNonEmptyString(value, field, caller) {
1335
- if (typeof value !== "string" || value.trim().length === 0) {
1336
- throw new TypeError(`[stitchkit] ${caller}: ${field} must be a non-empty string`);
1337
- }
1338
- return value;
1339
- }
1340
- function assertOptionalNonEmptyString(value, field, caller) {
1341
- if (value === undefined)
1342
- return;
1343
- if (typeof value !== "string" || value.trim().length === 0) {
1344
- throw new TypeError(`[stitchkit] ${caller}: ${field} must be a non-empty string`);
1345
- }
1346
- }
1347
- function assertOptionalNonEmptyNoNulString(value, field, caller) {
1348
- if (value === undefined)
1349
- return;
1350
- if (typeof value !== "string" || value.trim().length === 0 || value.includes("\x00")) {
1351
- throw new TypeError(`[stitchkit] ${caller}: ${field} must be a non-empty string without NUL bytes`);
1352
- }
1353
- }
1354
- function assertOptionalLimit(limit, caller) {
1355
- if (limit === undefined || limit === null)
1356
- return;
1357
- assertNonNegativeSafeInteger(`[stitchkit] ${caller}: limit`, limit, TypeError);
1358
- if (limit > MAX_UINT32) {
1359
- throw new TypeError(`[stitchkit] ${caller}: limit must not exceed ${MAX_UINT32}`);
1360
- }
1361
- }
1362
1401
  function assertBoundedThreadIdFilter(ids, field, caller) {
1363
1402
  if (ids === undefined || ids === null)
1364
1403
  return ids;
@@ -1440,329 +1479,233 @@ function buildListThreadsPayload(params) {
1440
1479
  ...params?.useStateDbOnly !== undefined && { useStateDbOnly: params.useStateDbOnly }
1441
1480
  };
1442
1481
  }
1482
+
1483
+ // src/agent-executor/codex/thread-controls.ts
1484
+ var MAX_UINT32 = 4294967295;
1485
+ function validateCodexRpcCallOptions(options) {
1486
+ if (options === undefined)
1487
+ return;
1488
+ if (options.timeoutMs !== undefined) {
1489
+ assertTimerMs("timeoutMs", options.timeoutMs);
1490
+ }
1491
+ if (options.signal?.aborted) {
1492
+ throw abortReason(options.signal);
1493
+ }
1494
+ }
1495
+ function assertNonEmptyThreadId(threadId, caller) {
1496
+ if (typeof threadId !== "string" || threadId.trim().length === 0) {
1497
+ throw new TypeError(`[stitchkit] ${caller}: threadId must be a non-empty string`);
1498
+ }
1499
+ return threadId;
1500
+ }
1501
+ function assertRequiredNonEmptyString(value, field, caller) {
1502
+ if (typeof value !== "string" || value.trim().length === 0) {
1503
+ throw new TypeError(`[stitchkit] ${caller}: ${field} must be a non-empty string`);
1504
+ }
1505
+ return value;
1506
+ }
1507
+ function assertOptionalNonEmptyString(value, field, caller) {
1508
+ if (value === undefined)
1509
+ return;
1510
+ if (typeof value !== "string" || value.trim().length === 0) {
1511
+ throw new TypeError(`[stitchkit] ${caller}: ${field} must be a non-empty string`);
1512
+ }
1513
+ }
1514
+ function assertOptionalNonEmptyNoNulString(value, field, caller) {
1515
+ if (value === undefined)
1516
+ return;
1517
+ if (typeof value !== "string" || value.trim().length === 0 || value.includes("\x00")) {
1518
+ throw new TypeError(`[stitchkit] ${caller}: ${field} must be a non-empty string without NUL bytes`);
1519
+ }
1520
+ }
1521
+ function assertOptionalLimit(limit, caller) {
1522
+ if (limit === undefined || limit === null)
1523
+ return;
1524
+ assertNonNegativeSafeInteger(`[stitchkit] ${caller}: limit`, limit, TypeError);
1525
+ if (limit > MAX_UINT32) {
1526
+ throw new TypeError(`[stitchkit] ${caller}: limit must not exceed ${MAX_UINT32}`);
1527
+ }
1528
+ }
1443
1529
  function createCodexThreadControlMethods(call, options = {}) {
1444
1530
  return {
1445
- async revertThread(params) {
1531
+ async revertThread(params, rpcOptions) {
1446
1532
  const threadId = assertNonEmptyThreadId(params.threadId, "CodexControlClient.revertThread");
1447
1533
  const beforeTurnId = assertRequiredNonEmptyString(params.beforeTurnId, "beforeTurnId", "CodexControlClient.revertThread");
1448
- const rawReply = await call("thread/revert", { threadId, beforeTurnId });
1449
- const parsed = CodexThreadRevertResponseSchema.parse(rawReply);
1534
+ const rawReply = await call("thread/revert", { threadId, beforeTurnId }, rpcOptions);
1535
+ const parsed = parseCodexResponse("thread/revert", CodexThreadRevertResponseSchema, rawReply);
1450
1536
  return {
1451
- thread: safeJsonValue(parsed.thread),
1537
+ thread: parsed.thread,
1452
1538
  turnsBackwardsCursor: parsed.turnsBackwardsCursor ?? null,
1453
1539
  itemsBackwardsCursor: parsed.itemsBackwardsCursor ?? null
1454
1540
  };
1455
1541
  },
1456
- async injectItems(params) {
1542
+ async injectItems(params, rpcOptions) {
1457
1543
  const threadId = assertNonEmptyThreadId(params.threadId, "CodexControlClient.injectItems");
1458
1544
  if (!Array.isArray(params.items)) {
1459
1545
  throw new TypeError("[stitchkit] CodexControlClient.injectItems: items must be an array");
1460
1546
  }
1461
1547
  const items = params.items.map((item) => safeJsonValue(item));
1462
- return call("thread/inject_items", { threadId, items });
1548
+ const raw = await call("thread/inject_items", { threadId, items }, rpcOptions);
1549
+ parseCodexResponse("thread/inject_items", CodexEmptyResponseSchema, raw);
1463
1550
  },
1464
- async unsubscribeThread(params) {
1551
+ async unsubscribeThread(params, rpcOptions) {
1465
1552
  const threadId = assertNonEmptyThreadId(params.threadId, "CodexControlClient.unsubscribeThread");
1466
- return call("thread/unsubscribe", { threadId });
1553
+ return parseCodexResponse("thread/unsubscribe", CodexThreadUnsubscribeResponseSchema, await call("thread/unsubscribe", { threadId }, rpcOptions));
1467
1554
  },
1468
- async listThreads(params) {
1469
- return call("thread/list", buildListThreadsPayload(params));
1555
+ async listThreads(params, rpcOptions) {
1556
+ return parseCodexResponse("thread/list", CodexThreadsPageSchema, await call("thread/list", buildListThreadsPayload(params), rpcOptions));
1470
1557
  },
1471
- async listLoadedThreads(params) {
1558
+ async listLoadedThreads(params, rpcOptions) {
1472
1559
  assertOptionalLimit(params?.limit, "CodexControlClient.listLoadedThreads");
1473
- return call("thread/loaded/list", {
1560
+ return parseCodexResponse("thread/loaded/list", CodexLoadedThreadsPageSchema, await call("thread/loaded/list", {
1474
1561
  ...params?.cursor !== undefined && { cursor: params.cursor },
1475
1562
  ...params?.limit !== undefined && { limit: params.limit }
1476
- });
1563
+ }, rpcOptions));
1477
1564
  },
1478
- async archiveThread(params) {
1565
+ async archiveThread(params, rpcOptions) {
1479
1566
  const threadId = assertNonEmptyThreadId(params.threadId, "CodexControlClient.archiveThread");
1480
- return call("thread/archive", { threadId });
1567
+ const raw = await call("thread/archive", { threadId }, rpcOptions);
1568
+ parseCodexResponse("thread/archive", CodexEmptyResponseSchema, raw);
1481
1569
  },
1482
- async unarchiveThread(params) {
1570
+ async unarchiveThread(params, rpcOptions) {
1483
1571
  const threadId = assertNonEmptyThreadId(params.threadId, "CodexControlClient.unarchiveThread");
1484
- return call("thread/unarchive", { threadId });
1572
+ return parseCodexResponse("thread/unarchive", CodexThreadUnarchiveResponseSchema, await call("thread/unarchive", { threadId }, rpcOptions));
1485
1573
  },
1486
- async updateThreadMetadata(params) {
1574
+ async updateThreadMetadata(params, rpcOptions) {
1487
1575
  const caller = "CodexControlClient.updateThreadMetadata";
1488
1576
  const threadId = assertNonEmptyThreadId(params.threadId, caller);
1489
1577
  const gitInfo = validateGitInfoUpdate(params.gitInfo, caller);
1490
- return call("thread/metadata/update", {
1578
+ return parseCodexResponse("thread/metadata/update", CodexThreadMetadataUpdateResponseSchema, await call("thread/metadata/update", {
1491
1579
  threadId,
1492
1580
  ...gitInfo !== undefined && { gitInfo }
1493
- });
1581
+ }, rpcOptions));
1494
1582
  },
1495
- async setThreadName(params) {
1583
+ async setThreadName(params, rpcOptions) {
1496
1584
  const caller = "CodexControlClient.setThreadName";
1497
1585
  const threadId = assertNonEmptyThreadId(params.threadId, caller);
1498
1586
  const name = assertRequiredNonEmptyString(params.name, "name", caller);
1499
- return call("thread/name/set", { threadId, name });
1587
+ const raw = await call("thread/name/set", { threadId, name }, rpcOptions);
1588
+ parseCodexResponse("thread/name/set", CodexEmptyResponseSchema, raw);
1500
1589
  },
1501
- async interruptTurn(params) {
1590
+ async interruptTurn(params, rpcOptions) {
1502
1591
  options.ensureAlive?.();
1592
+ validateCodexRpcCallOptions(rpcOptions);
1503
1593
  const caller = "CodexControlClient.interruptTurn";
1504
1594
  const threadId = assertNonEmptyThreadId(params.threadId, caller);
1505
1595
  const turnId = assertRequiredNonEmptyString(params.turnId, "turnId", caller);
1506
1596
  options.onBeforeInterruptTurn?.(threadId, turnId);
1507
- await call("turn/interrupt", { threadId, turnId });
1597
+ await call("turn/interrupt", { threadId, turnId }, rpcOptions);
1508
1598
  },
1509
- async compactThread(params) {
1599
+ async compactThread(params, rpcOptions) {
1510
1600
  const threadId = assertNonEmptyThreadId(params.threadId, "CodexControlClient.compactThread");
1511
- await call("thread/compact/start", { threadId });
1601
+ await call("thread/compact/start", { threadId }, rpcOptions);
1512
1602
  }
1513
1603
  };
1514
1604
  }
1515
1605
 
1516
- // src/agent-executor/codex/request-answers.ts
1517
- function isKnownCodexRequestMethod(method) {
1518
- return CODEX_APPROVAL_REQUESTS.has(method) || method === CODEX_PERMISSIONS_APPROVAL_REQUEST || method === CODEX_INPUT_REQUEST || method === CODEX_ELICITATION_REQUEST;
1519
- }
1520
- function externalCodexTurnIdOf(params) {
1521
- if (typeof params !== "object" || params === null)
1522
- return "external";
1523
- const direct = nonEmptyString(Reflect.get(params, "turnId"));
1524
- if (direct !== undefined)
1525
- return direct;
1526
- const turn = Reflect.get(params, "turn");
1527
- if (typeof turn === "object" && turn !== null) {
1528
- const nested = nonEmptyString(Reflect.get(turn, "id"));
1529
- if (nested !== undefined)
1530
- return nested;
1606
+ // src/agent-executor/codex/control-read-methods.ts
1607
+ function assertOptionalItemsCursor(cursor, caller) {
1608
+ if (cursor === undefined || cursor === null || cursor === "")
1609
+ return;
1610
+ if (typeof cursor === "string") {
1611
+ if (cursor.trim().length === 0) {
1612
+ throw new TypeError(`[stitchkit] ${caller}: item cursor cannot be whitespace-only`);
1613
+ }
1614
+ return;
1615
+ }
1616
+ if (typeof cursor !== "object" || cursor.type !== "item" || typeof cursor.itemId !== "string" || cursor.itemId.trim().length === 0) {
1617
+ throw new TypeError(`[stitchkit] ${caller}: item cursor must have type "item" and a non-empty itemId`);
1531
1618
  }
1532
- return "external";
1533
1619
  }
1534
- function parseCodexApprovalRequest(method, params) {
1535
- const asked = CodexApprovalParamsSchema.parse(params);
1536
- const callId = nonEmptyString(asked.itemId);
1537
- const metadata = {};
1538
- if (typeof asked.command === "string")
1539
- metadata.command = asked.command;
1540
- if (typeof asked.cwd === "string")
1541
- metadata.cwd = asked.cwd;
1542
- if (typeof asked.reason === "string")
1543
- metadata.reason = asked.reason;
1544
- if (typeof asked.grantRoot === "string")
1545
- metadata.grantRoot = asked.grantRoot;
1546
- if (typeof asked.kind === "string")
1547
- metadata.kind = asked.kind;
1548
- if (typeof asked.approvalId === "string")
1549
- metadata.approvalId = asked.approvalId;
1550
- if (asked.commandActions != null)
1551
- metadata.commandActions = asked.commandActions;
1552
- if (asked.availableDecisions != null)
1553
- metadata.availableDecisions = asked.availableDecisions;
1554
- const input = Object.keys(metadata).length > 0 ? safeJsonValue(metadata) : undefined;
1555
- const detail = {
1556
- method,
1557
- ...typeof asked.kind === "string" && { kind: asked.kind },
1558
- ...Array.isArray(asked.availableDecisions) && {
1559
- availableDecisions: asked.availableDecisions
1560
- }
1561
- };
1620
+ function createCodexReadMethods(call) {
1562
1621
  return {
1563
- detail,
1564
- deltaFields: {
1565
- ...callId !== undefined && { callId },
1566
- ...typeof asked.command === "string" && { prompt: asked.command },
1567
- ...input !== undefined && { input }
1568
- }
1569
- };
1570
- }
1571
- function parseCodexInputRequest(params) {
1572
- const asked = CodexUserInputParamsSchema.parse(params);
1573
- const callId = nonEmptyString(asked.itemId);
1574
- const questions = asked.questions.map((question) => ({
1575
- id: question.id,
1576
- header: question.header,
1577
- question: question.question,
1578
- ...question.options !== undefined && {
1579
- options: question.options === null ? null : question.options.map((option) => ({
1580
- label: option.label,
1581
- description: option.description
1582
- }))
1622
+ async readConfig(params, rpcOptions) {
1623
+ return parseCodexResponse("config/read", CodexConfigReadResponseSchema, await call("config/read", {
1624
+ ...params?.cwd !== undefined && { cwd: params.cwd },
1625
+ ...params?.includeLayers !== undefined && {
1626
+ includeLayers: params.includeLayers
1627
+ }
1628
+ }, rpcOptions));
1583
1629
  },
1584
- ...question.isOther !== undefined && { isOther: question.isOther },
1585
- ...question.isSecret !== undefined && { isSecret: question.isSecret }
1586
- }));
1587
- const detail = { method: CODEX_INPUT_REQUEST };
1588
- return {
1589
- detail,
1590
- deltaFields: {
1591
- ...callId !== undefined && { callId },
1592
- input: safeJsonValue(questions)
1593
- }
1594
- };
1595
- }
1596
- function parseCodexPermissionsRequest(params) {
1597
- const asked = CodexPermissionsApprovalParamsSchema.parse(params);
1598
- const callId = nonEmptyString(asked.itemId);
1599
- const permissions = safeJsonValue(asked.permissions);
1600
- const metadata = {
1601
- threadId: asked.threadId,
1602
- turnId: asked.turnId,
1603
- cwd: asked.cwd,
1604
- permissions,
1605
- startedAtMs: asked.startedAtMs
1606
- };
1607
- if (typeof asked.reason === "string")
1608
- metadata.reason = asked.reason;
1609
- if (typeof asked.environmentId === "string")
1610
- metadata.environmentId = asked.environmentId;
1611
- const detail = {
1612
- method: CODEX_PERMISSIONS_APPROVAL_REQUEST,
1613
- permissions
1614
- };
1615
- return {
1616
- detail,
1617
- deltaFields: {
1618
- ...callId !== undefined && { callId },
1619
- ...typeof asked.reason === "string" && { prompt: asked.reason },
1620
- input: safeJsonValue(metadata)
1630
+ async readThread(params, rpcOptions) {
1631
+ const threadId = assertNonEmptyThreadId(params.threadId, "CodexControlClient.readThread");
1632
+ return parseCodexResponse("thread/read", CodexReadThreadResponseSchema, await call("thread/read", {
1633
+ threadId,
1634
+ ...params.includeTurns !== undefined && { includeTurns: params.includeTurns }
1635
+ }, rpcOptions));
1636
+ },
1637
+ async listCollaborationModes(rpcOptions) {
1638
+ return parseCodexResponse("collaborationMode/list", CodexCollaborationModesResponseSchema, await call("collaborationMode/list", {}, rpcOptions));
1639
+ },
1640
+ async listTurns(params, rpcOptions) {
1641
+ const caller = "CodexControlClient.listTurns";
1642
+ const threadId = assertNonEmptyThreadId(params.threadId, caller);
1643
+ assertOptionalLimit(params.limit, caller);
1644
+ if (params.cursor !== undefined && params.cursor !== null && typeof params.cursor !== "string") {
1645
+ throw new TypeError(`[stitchkit] ${caller}: cursor must be a string or null`);
1646
+ }
1647
+ return parseCodexResponse("thread/turns/list", CodexTurnsPageSchema2, await call("thread/turns/list", {
1648
+ threadId,
1649
+ ...params.cursor !== undefined && { cursor: params.cursor },
1650
+ ...params.limit !== undefined && { limit: params.limit },
1651
+ ...params.itemsView !== undefined && { itemsView: params.itemsView },
1652
+ ...params.sortDirection !== undefined && { sortDirection: params.sortDirection }
1653
+ }, rpcOptions));
1654
+ },
1655
+ async listItems(params, rpcOptions) {
1656
+ const caller = "CodexControlClient.listItems";
1657
+ const threadId = assertNonEmptyThreadId(params.threadId, caller);
1658
+ assertOptionalLimit(params.limit, caller);
1659
+ assertOptionalNonEmptyString(params.turnId, "turnId", caller);
1660
+ assertOptionalItemsCursor(params.cursor, caller);
1661
+ return parseCodexResponse("thread/items/list", CodexItemsPageSchema, await call("thread/items/list", {
1662
+ threadId,
1663
+ ...params.turnId !== undefined && { turnId: params.turnId },
1664
+ ...params.cursor !== undefined && { cursor: safeJsonValue(params.cursor) },
1665
+ ...params.limit !== undefined && { limit: params.limit },
1666
+ ...params.sortDirection !== undefined && { sortDirection: params.sortDirection },
1667
+ ...params.deferOutput !== undefined && {
1668
+ deferOutput: safeJsonValue(params.deferOutput)
1669
+ }
1670
+ }, rpcOptions));
1671
+ },
1672
+ async listMcpServerStatus(params, rpcOptions) {
1673
+ return parseCodexResponse("mcpServerStatus/list", CodexMcpServerStatusPageSchema, await call("mcpServerStatus/list", {
1674
+ ...params?.cursor !== undefined && { cursor: params.cursor },
1675
+ ...params?.limit !== undefined && { limit: params.limit },
1676
+ ...params?.threadId !== undefined && { threadId: params.threadId },
1677
+ ...params?.serverName !== undefined && { serverName: params.serverName },
1678
+ ...params?.detail !== undefined && { detail: params.detail }
1679
+ }, rpcOptions));
1680
+ },
1681
+ async listSkills(params, rpcOptions) {
1682
+ return parseCodexResponse("skills/list", CodexSkillsListResponseSchema, await call("skills/list", {
1683
+ ...params?.cwds !== undefined && { cwds: [...params.cwds] },
1684
+ ...params?.forceReload !== undefined && { forceReload: params.forceReload }
1685
+ }, rpcOptions));
1686
+ },
1687
+ async listModels(params, rpcOptions) {
1688
+ return parseCodexResponse("model/list", CodexModelsPageSchema, await call("model/list", {
1689
+ ...params?.cursor !== undefined && { cursor: params.cursor },
1690
+ ...params?.limit !== undefined && { limit: params.limit },
1691
+ ...params?.includeHidden !== undefined && {
1692
+ includeHidden: params.includeHidden
1693
+ },
1694
+ ...params?.modelProvider !== undefined && {
1695
+ modelProvider: params.modelProvider
1696
+ }
1697
+ }, rpcOptions));
1698
+ },
1699
+ async readAccount(params, rpcOptions) {
1700
+ return parseCodexResponse("account/read", CodexAccountReadResponseSchema, await call("account/read", {
1701
+ ...params?.refreshToken !== undefined && { refreshToken: params.refreshToken }
1702
+ }, rpcOptions));
1703
+ },
1704
+ async readRateLimits(rpcOptions) {
1705
+ return parseCodexResponse("account/rateLimits/read", CodexRateLimitsResponseSchema, await call("account/rateLimits/read", undefined, rpcOptions));
1621
1706
  }
1622
1707
  };
1623
1708
  }
1624
- function parseCodexElicitationRequest(params) {
1625
- const asked = CodexMcpElicitationParamsSchema.parse(params);
1626
- const toolName = nonEmptyString(asked.serverName);
1627
- const callId = asked.mode === "url" ? nonEmptyString(asked.elicitationId) : undefined;
1628
- const metadata = {
1629
- serverName: asked.serverName,
1630
- threadId: asked.threadId,
1631
- mode: asked.mode,
1632
- message: asked.message
1633
- };
1634
- if (asked.turnId !== undefined)
1635
- metadata.turnId = asked.turnId;
1636
- if (asked.environmentId !== undefined)
1637
- metadata.environmentId = asked.environmentId;
1638
- if (asked._meta !== undefined)
1639
- metadata._meta = asked._meta;
1640
- if (asked.mode === "url") {
1641
- metadata.elicitationId = asked.elicitationId;
1642
- metadata.url = asked.url;
1643
- } else {
1644
- metadata.requestedSchema = asked.requestedSchema;
1645
- }
1646
- const detail = {
1647
- method: CODEX_ELICITATION_REQUEST,
1648
- elicitationMode: asked.mode
1649
- };
1650
- return {
1651
- detail,
1652
- deltaFields: {
1653
- ...callId !== undefined && { callId },
1654
- ...toolName !== undefined && { toolName },
1655
- prompt: asked.message,
1656
- input: safeJsonValue(metadata)
1657
- }
1658
- };
1659
- }
1660
- function parseCodexServerRequest(method, params) {
1661
- if (CODEX_APPROVAL_REQUESTS.has(method)) {
1662
- return { kind: "approval", ...parseCodexApprovalRequest(method, params) };
1663
- }
1664
- if (method === CODEX_PERMISSIONS_APPROVAL_REQUEST) {
1665
- return { kind: "approval", ...parseCodexPermissionsRequest(params) };
1666
- }
1667
- if (method === CODEX_ELICITATION_REQUEST) {
1668
- return { kind: "input", ...parseCodexElicitationRequest(params) };
1669
- }
1670
- return { kind: "input", ...parseCodexInputRequest(params) };
1671
- }
1672
- function codexStoppedAnswer(method) {
1673
- if (CODEX_APPROVAL_REQUESTS.has(method)) {
1674
- return { decision: CODEX_APPROVAL_DECISION.interrupted };
1675
- }
1676
- if (method === CODEX_PERMISSIONS_APPROVAL_REQUEST) {
1677
- return { permissions: {} };
1678
- }
1679
- if (method === CODEX_ELICITATION_REQUEST) {
1680
- return { action: "cancel" };
1681
- }
1682
- return { answers: {} };
1683
- }
1684
- var codexStopped = (waiting) => codexStoppedAnswer(waiting.detail.method);
1685
- function buildCodexRequestAnswer(detail, rawReply) {
1686
- const reply = InteractionReplySchema2.shape.reply.parse(rawReply);
1687
- if (CODEX_APPROVAL_REQUESTS.has(detail.method)) {
1688
- if (reply.kind === "input") {
1689
- throw new TypeError("A Codex approval is approved or denied, not answered with input");
1690
- }
1691
- if (reply.kind === "approve" && reply.updatedInput !== undefined) {
1692
- throw new TypeError("Codex approval requests do not support updatedInput");
1693
- }
1694
- const decision = reply.kind === "approve" ? reply.scope === "session" ? CODEX_APPROVAL_DECISION.approveForSession : CODEX_APPROVAL_DECISION.approve : reply.interrupt === true ? CODEX_APPROVAL_DECISION.interrupted : CODEX_APPROVAL_DECISION.deny;
1695
- if (detail.kind === "humanCommand" && decision === CODEX_APPROVAL_DECISION.approveForSession) {
1696
- throw new TypeError("Codex humanCommand approval does not allow acceptForSession");
1697
- }
1698
- if (detail.availableDecisions !== undefined) {
1699
- const allowed = detail.availableDecisions.some((entry) => entry === decision);
1700
- if (!allowed) {
1701
- throw new TypeError(`Codex approval request does not offer decision ${JSON.stringify(decision)}`);
1702
- }
1703
- }
1704
- return { decision };
1705
- }
1706
- if (detail.method === CODEX_PERMISSIONS_APPROVAL_REQUEST) {
1707
- if (reply.kind === "input") {
1708
- throw new TypeError("A Codex permissions approval is approved or denied, not answered with input");
1709
- }
1710
- if (reply.kind === "approve") {
1711
- if (reply.updatedInput !== undefined) {
1712
- throw new TypeError("Codex permissions approval requests do not support updatedInput");
1713
- }
1714
- return {
1715
- permissions: detail.permissions ?? {},
1716
- scope: reply.scope === "session" ? "session" : "turn"
1717
- };
1718
- }
1719
- if (reply.interrupt === true) {
1720
- throw new TypeError("Codex permissions approval requests do not support interrupt on deny");
1721
- }
1722
- return { permissions: {} };
1723
- }
1724
- if (detail.method === CODEX_ELICITATION_REQUEST) {
1725
- if (reply.kind === "approve") {
1726
- throw new TypeError("A Codex MCP elicitation request is answered with input or deny, not approve");
1727
- }
1728
- if (reply.kind === "deny") {
1729
- return {
1730
- action: detail.elicitationMode === "url" || reply.interrupt === true ? "cancel" : "decline"
1731
- };
1732
- }
1733
- const parsed = CodexMcpElicitationAnswerSchema.parse(reply.value);
1734
- return {
1735
- action: parsed.action,
1736
- ...parsed.content !== undefined && { content: parsed.content },
1737
- ...parsed._meta !== undefined && { _meta: parsed._meta }
1738
- };
1739
- }
1740
- if (reply.kind !== "input") {
1741
- throw new TypeError("A Codex input request is answered with input");
1742
- }
1743
- return { answers: CodexUserInputAnswersSchema.parse(reply.value) };
1744
- }
1745
- function answerActiveCodexTurnRequest(turn, interactionId, rawReply) {
1746
- const waiting = turn.pending.get(interactionId);
1747
- if (waiting === undefined) {
1748
- throw new TypeError(`Unknown interaction ${interactionId} for this turn`);
1749
- }
1750
- const answer = buildCodexRequestAnswer(waiting.detail, rawReply);
1751
- answerEngineRequest(turn, interactionId, answer);
1752
- }
1753
- function answerCodexSessionRequest(input) {
1754
- if (input.turn?.pending.has(input.interactionId)) {
1755
- answerActiveCodexTurnRequest(input.turn, input.interactionId, input.reply);
1756
- return;
1757
- }
1758
- const external = input.externalPending.get(input.interactionId);
1759
- if (external === undefined || input.expectedEntry !== undefined && external !== input.expectedEntry) {
1760
- throw new TypeError(`Unknown interaction ${input.interactionId} for this Codex connection`);
1761
- }
1762
- const answer = buildCodexRequestAnswer(external.detail, input.reply);
1763
- input.externalPending.delete(input.interactionId);
1764
- external.resolve(answer);
1765
- }
1766
1709
 
1767
1710
  // src/agent-executor/codex/turn-input.ts
1768
1711
  import { isAbsolute } from "node:path";
@@ -1827,13 +1770,13 @@ function codexTurnInput(parts) {
1827
1770
  }
1828
1771
  return out;
1829
1772
  }
1830
- async function sendCodexTurnSteer(peer, params) {
1831
- const steered = CodexTurnSteerResponseSchema.parse(await peer.request("turn/steer", {
1773
+ async function sendCodexTurnSteer(peer, params, rpcOptions) {
1774
+ const steered = parseCodexResponse("turn/steer", CodexTurnSteerResponseSchema, await peer.request("turn/steer", {
1832
1775
  threadId: params.threadId,
1833
1776
  expectedTurnId: params.expectedTurnId,
1834
1777
  input: codexTurnInput(params.parts),
1835
1778
  ...params.clientId !== undefined && { clientUserMessageId: params.clientId }
1836
- }));
1779
+ }, rpcOptions));
1837
1780
  return { turnId: steered.turnId };
1838
1781
  }
1839
1782
 
@@ -1886,28 +1829,30 @@ function buildCodexThreadPolicyParams(base, overrides) {
1886
1829
  params.config = safeJsonValue(merged.config);
1887
1830
  return params;
1888
1831
  }
1889
- function validateCodexTurnStartOverrides(turnInput, activeModelProvider) {
1890
- assertOptionalNonEmptyNoNulString(turnInput.cwd, "cwd", "CodexSession.startTurn");
1832
+ function validateCodexTurnStartOverrides(caller, turnInput, activeModelProvider) {
1833
+ assertRequiredNonEmptyString(turnInput.clientId, "clientId", caller);
1834
+ assertOptionalNonEmptyNoNulString(turnInput.cwd, "cwd", caller);
1891
1835
  if (turnInput.modelProvider !== undefined) {
1892
1836
  if (activeModelProvider === undefined || turnInput.modelProvider !== activeModelProvider) {
1893
1837
  throw new TypeError(`Codex turn/start cannot switch modelProvider to ${JSON.stringify(turnInput.modelProvider)} (thread active provider is ${JSON.stringify(activeModelProvider ?? "unknown")})`);
1894
1838
  }
1895
1839
  }
1896
1840
  if (turnInput.collaborationMode !== undefined) {
1897
- CodexCollaborationModeSchema.parse(turnInput.collaborationMode);
1841
+ CodexCollaborationModeSchema2.parse(turnInput.collaborationMode);
1898
1842
  }
1899
1843
  if (turnInput.approvalPolicy !== undefined) {
1900
- safeJsonValue(turnInput.approvalPolicy);
1844
+ CodexApprovalPolicySchema2.parse(turnInput.approvalPolicy);
1901
1845
  }
1902
1846
  if (turnInput.sandboxPolicy !== undefined) {
1847
+ CodexSandboxPolicySchema2.parse(turnInput.sandboxPolicy);
1903
1848
  safeJsonValue(turnInput.sandboxPolicy);
1904
1849
  }
1905
1850
  if (turnInput.runtimeWorkspaceRoots !== undefined) {
1906
- validateCodexPolicyOverrides({ runtimeWorkspaceRoots: turnInput.runtimeWorkspaceRoots }, "CodexSession.startTurn");
1851
+ validateCodexPolicyOverrides({ runtimeWorkspaceRoots: turnInput.runtimeWorkspaceRoots }, caller);
1907
1852
  }
1908
1853
  }
1909
- function buildCodexTurnStartParams(threadId, turnInput, parts, activeModelProvider) {
1910
- validateCodexTurnStartOverrides(turnInput, activeModelProvider);
1854
+ function buildCodexTurnStartRpcParams(caller, threadId, turnInput, parts, activeModelProvider) {
1855
+ validateCodexTurnStartOverrides(caller, turnInput, activeModelProvider);
1911
1856
  const params = {
1912
1857
  threadId,
1913
1858
  input: codexTurnInput(parts),
@@ -1920,7 +1865,7 @@ function buildCodexTurnStartParams(threadId, turnInput, parts, activeModelProvid
1920
1865
  if (turnInput.reasoningEffort !== undefined)
1921
1866
  params.effort = turnInput.reasoningEffort;
1922
1867
  if (turnInput.collaborationMode !== undefined) {
1923
- params.collaborationMode = CodexCollaborationModeSchema.parse(turnInput.collaborationMode);
1868
+ params.collaborationMode = CodexCollaborationModeSchema2.parse(turnInput.collaborationMode);
1924
1869
  }
1925
1870
  if (turnInput.approvalPolicy !== undefined) {
1926
1871
  params.approvalPolicy = safeJsonValue(turnInput.approvalPolicy);
@@ -1935,26 +1880,28 @@ function buildCodexTurnStartParams(threadId, turnInput, parts, activeModelProvid
1935
1880
  }
1936
1881
  function createCodexSessionMutators(input) {
1937
1882
  return {
1938
- async steerTurn(steerInput) {
1883
+ async steerTurn(steerInput, rpcOptions) {
1939
1884
  input.ensureAlive();
1885
+ validateCodexRpcCallOptions(rpcOptions);
1940
1886
  const caller = "CodexSession.steerTurn";
1941
1887
  const targetThreadId = steerInput.threadId === undefined ? input.threadId : assertNonEmptyThreadId(steerInput.threadId, caller);
1942
1888
  assertOptionalNonEmptyString(steerInput.clientId, "clientId", caller);
1943
1889
  assertOptionalNonEmptyString(steerInput.expectedTurnId, "expectedTurnId", caller);
1944
1890
  if (targetThreadId !== input.threadId) {
1945
1891
  const expectedTurnId = assertRequiredNonEmptyString(steerInput.expectedTurnId, "expectedTurnId", caller);
1946
- const parts = await inlineCodexParts(steerInput.input, {
1892
+ const parts = await withLinkedAbortSignals(rpcOptions?.signal, input.signal, (signal) => inlineCodexParts(steerInput.input, {
1947
1893
  ...input.imageOptions,
1948
1894
  driverLabel: "The Codex driver",
1949
- signal: input.signal
1950
- });
1895
+ signal
1896
+ }));
1951
1897
  input.ensureAlive();
1898
+ validateCodexRpcCallOptions(rpcOptions);
1952
1899
  return sendCodexTurnSteer(input.peer, {
1953
1900
  threadId: targetThreadId,
1954
1901
  expectedTurnId,
1955
1902
  parts,
1956
1903
  ...steerInput.clientId !== undefined && { clientId: steerInput.clientId }
1957
- });
1904
+ }, rpcOptions);
1958
1905
  }
1959
1906
  const active = input.getActiveTurn();
1960
1907
  let expectedTurnId;
@@ -1972,12 +1919,13 @@ function createCodexSessionMutators(input) {
1972
1919
  }
1973
1920
  expectedTurnId = steerInput.expectedTurnId;
1974
1921
  }
1975
- const parts = await inlineCodexParts(steerInput.input, {
1922
+ const parts = await withLinkedAbortSignals(rpcOptions?.signal, input.signal, (signal) => inlineCodexParts(steerInput.input, {
1976
1923
  ...input.imageOptions,
1977
1924
  driverLabel: "The Codex driver",
1978
- signal: input.signal
1979
- });
1925
+ signal
1926
+ }));
1980
1927
  input.ensureAlive();
1928
+ validateCodexRpcCallOptions(rpcOptions);
1981
1929
  const afterAwait = input.getActiveTurn();
1982
1930
  if (active !== undefined) {
1983
1931
  if (afterAwait !== active || afterAwait.codexTurnId !== expectedTurnId) {
@@ -1991,13 +1939,14 @@ function createCodexSessionMutators(input) {
1991
1939
  expectedTurnId,
1992
1940
  parts,
1993
1941
  ...steerInput.clientId !== undefined && { clientId: steerInput.clientId }
1994
- });
1942
+ }, rpcOptions);
1995
1943
  },
1996
- async forkThread(options = {}) {
1944
+ async forkThread(options = {}, rpcOptions) {
1997
1945
  input.ensureAlive();
1946
+ validateCodexRpcCallOptions(rpcOptions);
1998
1947
  validateCodexForkBounds(options, "CodexSession.forkThread");
1999
1948
  const policyParams = buildCodexThreadPolicyParams({}, options);
2000
- const forked = CodexStartedThreadSchema.parse(await input.peer.request("thread/fork", {
1949
+ const forked = parseCodexResponse("thread/fork", CodexStartedThreadSchema, await input.peer.request("thread/fork", {
2001
1950
  threadId: input.threadId,
2002
1951
  ...policyParams,
2003
1952
  ...options.cwd !== undefined && { cwd: options.cwd },
@@ -2007,7 +1956,7 @@ function createCodexSessionMutators(input) {
2007
1956
  ...options.deferGoalContinuation !== undefined && {
2008
1957
  deferGoalContinuation: options.deferGoalContinuation
2009
1958
  }
2010
- }));
1959
+ }, rpcOptions));
2011
1960
  return {
2012
1961
  nativeThreadId: forked.thread.id,
2013
1962
  threadContext: extractCodexThreadContext(forked)
@@ -2016,64 +1965,358 @@ function createCodexSessionMutators(input) {
2016
1965
  };
2017
1966
  }
2018
1967
 
2019
- // src/agent-executor/codex/thread-open.ts
2020
- function interruptLocalCodexTurn(turn, turnId) {
2021
- if (turn === undefined || turn.codexTurnId !== turnId)
1968
+ // src/agent-executor/codex/event-routing.ts
1969
+ function field(object, key) {
1970
+ return isRecord(object) ? nonEmptyString(object[key]) : undefined;
1971
+ }
1972
+ function codexThreadIdOf(params) {
1973
+ if (!isRecord(params))
2022
1974
  return;
2023
- turn.state.interruptRequested = true;
2024
- drainEngineRequests(turn, codexStopped);
1975
+ return field(params, "threadId") ?? field(params.thread, "id") ?? field(params.turn, "threadId") ?? field(params.item, "threadId");
2025
1976
  }
2026
- function buildCodexResumeThreadParams(params) {
2027
- const caller = "CodexControlClient.resumeThread";
2028
- const threadId = assertNonEmptyThreadId(params.threadId, caller);
2029
- assertOptionalNonEmptyNoNulString(params.cwd, "cwd", caller);
2030
- if (params.excludeTurns !== undefined && typeof params.excludeTurns !== "boolean") {
2031
- throw new TypeError(`[stitchkit] ${caller}: excludeTurns must be a boolean`);
2032
- }
2033
- const policyParams = buildCodexThreadPolicyParams({}, params);
1977
+ function codexTurnIdOf(params) {
1978
+ if (!isRecord(params))
1979
+ return;
1980
+ return field(params, "turnId") ?? field(params.turn, "id") ?? field(params.item, "turnId");
1981
+ }
1982
+
1983
+ class CodexStartingTurn {
1984
+ waiting = [];
1985
+ bytes = 0;
1986
+ failure;
1987
+ defer(params, deliver) {
1988
+ if (this.failure !== undefined)
1989
+ throw this.failure;
1990
+ this.bytes += JSON.stringify(params ?? null).length;
1991
+ if (this.waiting.length >= TURN_QUEUE.maxItems || this.bytes > TURN_QUEUE.maxBytes) {
1992
+ this.failure = new Error("Codex events before turn/start exceeded the turn queue limit");
1993
+ throw this.failure;
1994
+ }
1995
+ this.waiting.push(deliver);
1996
+ }
1997
+ flush() {
1998
+ for (const deliver of this.waiting.splice(0))
1999
+ deliver();
2000
+ if (this.failure !== undefined)
2001
+ throw this.failure;
2002
+ }
2003
+ }
2004
+ function codexEventTurn(current, params) {
2005
+ if (current === undefined)
2006
+ return;
2007
+ const threadId = codexThreadIdOf(params);
2008
+ if (threadId !== undefined && current.threadId !== undefined && threadId !== current.threadId)
2009
+ return;
2010
+ const turnId = codexTurnIdOf(params);
2011
+ if (turnId !== undefined && current.codexTurnId !== undefined && turnId !== current.codexTurnId)
2012
+ return;
2013
+ return current;
2014
+ }
2015
+
2016
+ // src/agent-executor/codex/request-answers.ts
2017
+ function isKnownCodexRequestMethod(method) {
2018
+ return CODEX_APPROVAL_REQUESTS.has(method) || method === CODEX_PERMISSIONS_APPROVAL_REQUEST || method === CODEX_INPUT_REQUEST || method === CODEX_ELICITATION_REQUEST;
2019
+ }
2020
+ function parseCodexApprovalRequest(method, params) {
2021
+ const asked = CodexApprovalParamsSchema.parse(params);
2022
+ const callId = nonEmptyString(asked.itemId);
2023
+ const metadata = {};
2024
+ if (typeof asked.command === "string")
2025
+ metadata.command = asked.command;
2026
+ if (typeof asked.cwd === "string")
2027
+ metadata.cwd = asked.cwd;
2028
+ if (typeof asked.reason === "string")
2029
+ metadata.reason = asked.reason;
2030
+ if (typeof asked.grantRoot === "string")
2031
+ metadata.grantRoot = asked.grantRoot;
2032
+ if (typeof asked.kind === "string")
2033
+ metadata.kind = asked.kind;
2034
+ if (typeof asked.approvalId === "string")
2035
+ metadata.approvalId = asked.approvalId;
2036
+ if (asked.commandActions != null)
2037
+ metadata.commandActions = asked.commandActions;
2038
+ if (asked.availableDecisions != null)
2039
+ metadata.availableDecisions = asked.availableDecisions;
2040
+ const input = Object.keys(metadata).length > 0 ? safeJsonValue(metadata) : undefined;
2041
+ const detail = {
2042
+ method,
2043
+ ...typeof asked.kind === "string" && { kind: asked.kind },
2044
+ ...Array.isArray(asked.availableDecisions) && {
2045
+ availableDecisions: asked.availableDecisions
2046
+ }
2047
+ };
2034
2048
  return {
2035
- threadId,
2036
- excludeTurns: params.excludeTurns ?? true,
2037
- ...policyParams,
2038
- ...params.cwd !== undefined && { cwd: params.cwd }
2049
+ detail,
2050
+ deltaFields: {
2051
+ ...callId !== undefined && { callId },
2052
+ ...typeof asked.command === "string" && { prompt: asked.command },
2053
+ ...input !== undefined && { input }
2054
+ }
2039
2055
  };
2040
2056
  }
2041
- function createCodexStartTurn(input) {
2042
- return guardedTurnStarter({
2043
- busyMessage: "A turn is already running in this Codex thread",
2044
- check: (turnInput) => {
2045
- input.ensureAlive();
2046
- if (input.getTurn() !== undefined) {
2047
- throw new Error("A turn is already running in this Codex thread");
2048
- }
2049
- validateCodexTurnStartOverrides(turnInput, input.activeModelProvider);
2057
+ function parseCodexInputRequest(params) {
2058
+ const asked = CodexUserInputParamsSchema.parse(params);
2059
+ const callId = nonEmptyString(asked.itemId);
2060
+ const questions = asked.questions.map((question) => ({
2061
+ id: question.id,
2062
+ header: question.header,
2063
+ question: question.question,
2064
+ ...question.options !== undefined && {
2065
+ options: question.options === null ? null : question.options.map((option) => ({
2066
+ label: option.label,
2067
+ description: option.description
2068
+ }))
2050
2069
  },
2051
- inline: (turnInput) => inlineCodexParts(turnInput.input, {
2052
- ...input.config,
2053
- driverLabel: "The Codex driver",
2054
- signal: input.signal
2055
- }),
2056
- dispatch: async (turnInput, parts) => {
2057
- const turnParams = buildCodexTurnStartParams(input.threadId, turnInput, parts, input.activeModelProvider);
2058
- const turn = {
2059
- state: { turnId: turnInput.turnId, interruptRequested: false },
2060
- channel: createTurnDeltaChannel(),
2061
- pending: new Map
2062
- };
2063
- input.setTurn(turn);
2064
- let nativeTurnId;
2065
- try {
2066
- const started = await input.peer.request("turn/start", turnParams);
2067
- nativeTurnId = CodexStartedTurnSchema.parse(started).turn.id;
2068
- turn.codexTurnId = nativeTurnId;
2069
- } catch (error) {
2070
- if (input.getTurn() === turn)
2071
- input.setTurn(undefined);
2072
- throw error;
2073
- }
2074
- return {
2075
- nativeTurnId,
2076
- deltas: turn.channel,
2070
+ ...question.isOther !== undefined && { isOther: question.isOther },
2071
+ ...question.isSecret !== undefined && { isSecret: question.isSecret }
2072
+ }));
2073
+ const detail = { method: CODEX_INPUT_REQUEST };
2074
+ return {
2075
+ detail,
2076
+ deltaFields: {
2077
+ ...callId !== undefined && { callId },
2078
+ input: safeJsonValue(questions)
2079
+ }
2080
+ };
2081
+ }
2082
+ function parseCodexPermissionsRequest(params) {
2083
+ const asked = CodexPermissionsApprovalParamsSchema.parse(params);
2084
+ const callId = nonEmptyString(asked.itemId);
2085
+ const permissions = safeJsonValue(asked.permissions);
2086
+ const metadata = {
2087
+ threadId: asked.threadId,
2088
+ turnId: asked.turnId,
2089
+ cwd: asked.cwd,
2090
+ permissions,
2091
+ startedAtMs: asked.startedAtMs
2092
+ };
2093
+ if (typeof asked.reason === "string")
2094
+ metadata.reason = asked.reason;
2095
+ if (typeof asked.environmentId === "string")
2096
+ metadata.environmentId = asked.environmentId;
2097
+ const detail = {
2098
+ method: CODEX_PERMISSIONS_APPROVAL_REQUEST,
2099
+ permissions
2100
+ };
2101
+ return {
2102
+ detail,
2103
+ deltaFields: {
2104
+ ...callId !== undefined && { callId },
2105
+ ...typeof asked.reason === "string" && { prompt: asked.reason },
2106
+ input: safeJsonValue(metadata)
2107
+ }
2108
+ };
2109
+ }
2110
+ function parseCodexElicitationRequest(params) {
2111
+ const asked = CodexMcpElicitationParamsSchema.parse(params);
2112
+ const toolName = nonEmptyString(asked.serverName);
2113
+ const callId = asked.mode === "url" ? nonEmptyString(asked.elicitationId) : undefined;
2114
+ const metadata = {
2115
+ serverName: asked.serverName,
2116
+ threadId: asked.threadId,
2117
+ mode: asked.mode,
2118
+ message: asked.message
2119
+ };
2120
+ if (asked.turnId !== undefined)
2121
+ metadata.turnId = asked.turnId;
2122
+ if (asked.environmentId !== undefined)
2123
+ metadata.environmentId = asked.environmentId;
2124
+ if (asked._meta !== undefined)
2125
+ metadata._meta = asked._meta;
2126
+ if (asked.mode === "url") {
2127
+ metadata.elicitationId = asked.elicitationId;
2128
+ metadata.url = asked.url;
2129
+ } else {
2130
+ metadata.requestedSchema = asked.requestedSchema;
2131
+ }
2132
+ const detail = {
2133
+ method: CODEX_ELICITATION_REQUEST,
2134
+ elicitationMode: asked.mode
2135
+ };
2136
+ return {
2137
+ detail,
2138
+ deltaFields: {
2139
+ ...callId !== undefined && { callId },
2140
+ ...toolName !== undefined && { toolName },
2141
+ prompt: asked.message,
2142
+ input: safeJsonValue(metadata)
2143
+ }
2144
+ };
2145
+ }
2146
+ function parseCodexServerRequest(method, params) {
2147
+ if (CODEX_APPROVAL_REQUESTS.has(method)) {
2148
+ return { kind: "approval", ...parseCodexApprovalRequest(method, params) };
2149
+ }
2150
+ if (method === CODEX_PERMISSIONS_APPROVAL_REQUEST) {
2151
+ return { kind: "approval", ...parseCodexPermissionsRequest(params) };
2152
+ }
2153
+ if (method === CODEX_ELICITATION_REQUEST) {
2154
+ return { kind: "input", ...parseCodexElicitationRequest(params) };
2155
+ }
2156
+ return { kind: "input", ...parseCodexInputRequest(params) };
2157
+ }
2158
+ function codexStoppedAnswer(method) {
2159
+ if (CODEX_APPROVAL_REQUESTS.has(method)) {
2160
+ return { decision: CODEX_APPROVAL_DECISION.interrupted };
2161
+ }
2162
+ if (method === CODEX_PERMISSIONS_APPROVAL_REQUEST) {
2163
+ return { permissions: {} };
2164
+ }
2165
+ if (method === CODEX_ELICITATION_REQUEST) {
2166
+ return { action: "cancel" };
2167
+ }
2168
+ return { answers: {} };
2169
+ }
2170
+ var codexStopped = (waiting) => codexStoppedAnswer(waiting.detail.method);
2171
+ function buildCodexRequestAnswer(detail, rawReply) {
2172
+ const reply = InteractionReplySchema2.shape.reply.parse(rawReply);
2173
+ if (CODEX_APPROVAL_REQUESTS.has(detail.method)) {
2174
+ if (reply.kind === "input") {
2175
+ throw new TypeError("A Codex approval is approved or denied, not answered with input");
2176
+ }
2177
+ if (reply.kind === "approve" && reply.updatedInput !== undefined) {
2178
+ throw new TypeError("Codex approval requests do not support updatedInput");
2179
+ }
2180
+ const decision = reply.kind === "approve" ? reply.scope === "session" ? CODEX_APPROVAL_DECISION.approveForSession : CODEX_APPROVAL_DECISION.approve : reply.interrupt === true ? CODEX_APPROVAL_DECISION.interrupted : CODEX_APPROVAL_DECISION.deny;
2181
+ if (detail.kind === "humanCommand" && decision === CODEX_APPROVAL_DECISION.approveForSession) {
2182
+ throw new TypeError("Codex humanCommand approval does not allow acceptForSession");
2183
+ }
2184
+ if (detail.availableDecisions !== undefined) {
2185
+ const allowed = detail.availableDecisions.some((entry) => entry === decision);
2186
+ if (!allowed) {
2187
+ throw new TypeError(`Codex approval request does not offer decision ${JSON.stringify(decision)}`);
2188
+ }
2189
+ }
2190
+ return { decision };
2191
+ }
2192
+ if (detail.method === CODEX_PERMISSIONS_APPROVAL_REQUEST) {
2193
+ if (reply.kind === "input") {
2194
+ throw new TypeError("A Codex permissions approval is approved or denied, not answered with input");
2195
+ }
2196
+ if (reply.kind === "approve") {
2197
+ if (reply.updatedInput !== undefined) {
2198
+ throw new TypeError("Codex permissions approval requests do not support updatedInput");
2199
+ }
2200
+ return {
2201
+ permissions: detail.permissions ?? {},
2202
+ scope: reply.scope === "session" ? "session" : "turn"
2203
+ };
2204
+ }
2205
+ if (reply.interrupt === true) {
2206
+ throw new TypeError("Codex permissions approval requests do not support interrupt on deny");
2207
+ }
2208
+ return { permissions: {} };
2209
+ }
2210
+ if (detail.method === CODEX_ELICITATION_REQUEST) {
2211
+ if (reply.kind === "approve") {
2212
+ throw new TypeError("A Codex MCP elicitation request is answered with input or deny, not approve");
2213
+ }
2214
+ if (reply.kind === "deny") {
2215
+ return {
2216
+ action: detail.elicitationMode === "url" || reply.interrupt === true ? "cancel" : "decline"
2217
+ };
2218
+ }
2219
+ const parsed = CodexMcpElicitationAnswerSchema.parse(reply.value);
2220
+ return {
2221
+ action: parsed.action,
2222
+ ...parsed.content !== undefined && { content: parsed.content },
2223
+ ...parsed._meta !== undefined && { _meta: parsed._meta }
2224
+ };
2225
+ }
2226
+ if (reply.kind !== "input") {
2227
+ throw new TypeError("A Codex input request is answered with input");
2228
+ }
2229
+ return { answers: CodexUserInputAnswersSchema.parse(reply.value) };
2230
+ }
2231
+ function answerActiveCodexTurnRequest(turn, interactionId, rawReply) {
2232
+ const waiting = turn.pending.get(interactionId);
2233
+ if (waiting === undefined) {
2234
+ throw new TypeError(`Unknown interaction ${interactionId} for this turn`);
2235
+ }
2236
+ const answer = buildCodexRequestAnswer(waiting.detail, rawReply);
2237
+ answerEngineRequest(turn, interactionId, answer);
2238
+ }
2239
+ function answerCodexSessionRequest(input) {
2240
+ if (input.turn?.pending.has(input.interactionId)) {
2241
+ answerActiveCodexTurnRequest(input.turn, input.interactionId, input.reply);
2242
+ return;
2243
+ }
2244
+ const external = input.externalPending.get(input.interactionId);
2245
+ if (external === undefined || input.expectedEntry !== undefined && external !== input.expectedEntry) {
2246
+ throw new TypeError(`Unknown interaction ${input.interactionId} for this Codex connection`);
2247
+ }
2248
+ const answer = buildCodexRequestAnswer(external.detail, input.reply);
2249
+ input.externalPending.delete(input.interactionId);
2250
+ external.resolve(answer);
2251
+ }
2252
+
2253
+ // src/agent-executor/codex/thread-open.ts
2254
+ function interruptLocalCodexTurn(turn, turnId) {
2255
+ if (turn === undefined || turn.codexTurnId !== turnId)
2256
+ return;
2257
+ turn.state.interruptRequested = true;
2258
+ drainEngineRequests(turn, codexStopped);
2259
+ }
2260
+ function buildCodexResumeThreadParams(params) {
2261
+ const caller = "CodexControlClient.resumeThread";
2262
+ const threadId = assertNonEmptyThreadId(params.threadId, caller);
2263
+ assertOptionalNonEmptyNoNulString(params.cwd, "cwd", caller);
2264
+ if (params.excludeTurns !== undefined && typeof params.excludeTurns !== "boolean") {
2265
+ throw new TypeError(`[stitchkit] ${caller}: excludeTurns must be a boolean`);
2266
+ }
2267
+ const policyParams = buildCodexThreadPolicyParams({}, params);
2268
+ return {
2269
+ threadId,
2270
+ excludeTurns: params.excludeTurns ?? true,
2271
+ ...policyParams,
2272
+ ...params.cwd !== undefined && { cwd: params.cwd }
2273
+ };
2274
+ }
2275
+ function createCodexStartTurn(input) {
2276
+ return guardedTurnStarter({
2277
+ busyMessage: "A turn is already running in this Codex thread",
2278
+ check: (turnInput) => {
2279
+ input.ensureAlive();
2280
+ if (input.getTurn() !== undefined) {
2281
+ throw new Error("A turn is already running in this Codex thread");
2282
+ }
2283
+ validateCodexTurnStartOverrides("CodexSession.startTurn", turnInput, input.activeModelProvider);
2284
+ },
2285
+ inline: (turnInput) => inlineCodexParts(turnInput.input, {
2286
+ ...input.config,
2287
+ driverLabel: "The Codex driver",
2288
+ signal: input.signal
2289
+ }),
2290
+ dispatch: async (turnInput, parts) => {
2291
+ const turnParams = buildCodexTurnStartRpcParams("CodexSession.startTurn", input.threadId, turnInput, parts, input.activeModelProvider);
2292
+ const starting = new CodexStartingTurn;
2293
+ const turn = {
2294
+ threadId: input.threadId,
2295
+ starting,
2296
+ state: { turnId: turnInput.turnId, interruptRequested: false },
2297
+ channel: createTurnDeltaChannel(),
2298
+ pending: new Map
2299
+ };
2300
+ input.setTurn(turn);
2301
+ let nativeTurnId;
2302
+ try {
2303
+ const started = await input.peer.request("turn/start", turnParams);
2304
+ nativeTurnId = parseCodexResponse("turn/start", CodexStartedTurnSchema, started).turn.id;
2305
+ turn.codexTurnId = nativeTurnId;
2306
+ delete turn.starting;
2307
+ starting.flush();
2308
+ } catch (error) {
2309
+ if (input.getTurn() === turn)
2310
+ input.setTurn(undefined);
2311
+ if (turn.starting !== undefined) {
2312
+ delete turn.starting;
2313
+ starting.flush();
2314
+ }
2315
+ throw error;
2316
+ }
2317
+ return {
2318
+ nativeTurnId,
2319
+ deltas: turn.channel,
2077
2320
  async interrupt() {
2078
2321
  interruptLocalCodexTurn(turn, nativeTurnId);
2079
2322
  await input.peer.request("turn/interrupt", {
@@ -2163,125 +2406,55 @@ function openCodexThreadRpc(peer, config, input, dynamicOverrides) {
2163
2406
  }
2164
2407
 
2165
2408
  // src/agent-executor/codex/control-client.ts
2166
- function assertOptionalItemsCursor(cursor, caller) {
2167
- if (cursor === undefined || cursor === null)
2168
- return;
2169
- if (typeof cursor === "string") {
2170
- if (cursor.trim().length === 0) {
2171
- throw new TypeError(`[stitchkit] ${caller}: cursor must be a non-empty string`);
2172
- }
2173
- return;
2174
- }
2175
- if (typeof cursor !== "object" || cursor.type !== "item" || typeof cursor.itemId !== "string" || cursor.itemId.trim().length === 0) {
2176
- throw new TypeError(`[stitchkit] ${caller}: item cursor must have type "item" and a non-empty itemId`);
2177
- }
2178
- }
2179
2409
  function createCodexControlClient(input) {
2180
- const call = async (method, params) => {
2410
+ const call = async (method, params, rpcOptions) => {
2411
+ validateCodexRpcCallOptions(rpcOptions);
2181
2412
  input.ensureAlive();
2182
- return input.peer.request(method, params);
2413
+ return input.peer.request(method, params, rpcOptions);
2183
2414
  };
2184
2415
  return {
2185
- readConfig(params) {
2186
- return call("config/read", {
2187
- ...params?.cwd !== undefined && { cwd: params.cwd },
2188
- ...params?.includeLayers !== undefined && { includeLayers: params.includeLayers }
2189
- });
2416
+ ...createCodexReadMethods(call),
2417
+ async resumeThread(params, rpcOptions) {
2418
+ input.ensureAlive();
2419
+ return parseCodexResponse("thread/resume", CodexResumeThreadResponseSchema, await call("thread/resume", buildCodexResumeThreadParams(params), rpcOptions));
2190
2420
  },
2191
- async readThread(params) {
2192
- const threadId = assertNonEmptyThreadId(params.threadId, "CodexControlClient.readThread");
2193
- return call("thread/read", {
2194
- threadId,
2195
- ...params.includeTurns !== undefined && { includeTurns: params.includeTurns }
2196
- });
2197
- },
2198
- listCollaborationModes() {
2199
- return call("collaborationMode/list", {});
2200
- },
2201
- async listTurns(params) {
2202
- const caller = "CodexControlClient.listTurns";
2421
+ async startThreadTurn(params, rpcOptions) {
2422
+ input.ensureAlive();
2423
+ validateCodexRpcCallOptions(rpcOptions);
2424
+ const caller = "CodexControlClient.startThreadTurn";
2203
2425
  const threadId = assertNonEmptyThreadId(params.threadId, caller);
2204
- assertOptionalLimit(params.limit, caller);
2205
- if (params.cursor !== undefined && params.cursor !== null && typeof params.cursor !== "string") {
2206
- throw new TypeError(`[stitchkit] ${caller}: cursor must be a string or null`);
2207
- }
2208
- return call("thread/turns/list", {
2209
- threadId,
2210
- ...params.cursor !== undefined && { cursor: params.cursor },
2211
- ...params.limit !== undefined && { limit: params.limit },
2212
- ...params.itemsView !== undefined && { itemsView: params.itemsView },
2213
- ...params.sortDirection !== undefined && { sortDirection: params.sortDirection }
2214
- });
2215
- },
2216
- async listItems(params) {
2217
- const threadId = assertNonEmptyThreadId(params.threadId, "CodexControlClient.listItems");
2218
- assertOptionalLimit(params.limit, "CodexControlClient.listItems");
2219
- assertOptionalNonEmptyString(params.turnId, "turnId", "CodexControlClient.listItems");
2220
- assertOptionalItemsCursor(params.cursor, "CodexControlClient.listItems");
2221
- return call("thread/items/list", {
2222
- threadId,
2223
- ...params.turnId !== undefined && { turnId: params.turnId },
2224
- ...params.cursor !== undefined && { cursor: safeJsonValue(params.cursor) },
2225
- ...params.limit !== undefined && { limit: params.limit },
2226
- ...params.sortDirection !== undefined && { sortDirection: params.sortDirection },
2227
- ...params.deferOutput !== undefined && {
2228
- deferOutput: safeJsonValue(params.deferOutput)
2229
- }
2230
- });
2231
- },
2232
- listMcpServerStatus(params) {
2233
- return call("mcpServerStatus/list", {
2234
- ...params?.cursor !== undefined && { cursor: params.cursor },
2235
- ...params?.limit !== undefined && { limit: params.limit },
2236
- ...params?.threadId !== undefined && { threadId: params.threadId },
2237
- ...params?.serverName !== undefined && { serverName: params.serverName },
2238
- ...params?.detail !== undefined && { detail: params.detail }
2239
- });
2240
- },
2241
- listSkills(params) {
2242
- return call("skills/list", {
2243
- ...params?.cwds !== undefined && { cwds: [...params.cwds] },
2244
- ...params?.forceReload !== undefined && { forceReload: params.forceReload }
2245
- });
2246
- },
2247
- listModels(params) {
2248
- return call("model/list", {
2249
- ...params?.cursor !== undefined && { cursor: params.cursor },
2250
- ...params?.limit !== undefined && { limit: params.limit },
2251
- ...params?.includeHidden !== undefined && { includeHidden: params.includeHidden },
2252
- ...params?.modelProvider !== undefined && { modelProvider: params.modelProvider }
2253
- });
2254
- },
2255
- readAccount(params) {
2256
- return call("account/read", {
2257
- ...params?.refreshToken !== undefined && { refreshToken: params.refreshToken }
2258
- });
2259
- },
2260
- readRateLimits() {
2261
- return call("account/rateLimits/read");
2262
- },
2263
- async resumeThread(params) {
2426
+ validateCodexTurnStartOverrides(caller, params);
2427
+ const parts = await withLinkedAbortSignals(rpcOptions?.signal, input.signal, (signal) => inlineCodexParts(params.input, {
2428
+ ...input.imageOptions,
2429
+ driverLabel: "The Codex driver",
2430
+ signal
2431
+ }));
2264
2432
  input.ensureAlive();
2265
- return call("thread/resume", buildCodexResumeThreadParams(params));
2433
+ validateCodexRpcCallOptions(rpcOptions);
2434
+ const rpcParams = buildCodexTurnStartRpcParams(caller, threadId, params, parts);
2435
+ const started = parseCodexResponse("turn/start", CodexStartedTurnSchema, await call("turn/start", rpcParams, rpcOptions));
2436
+ return { turnId: started.turn.id };
2266
2437
  },
2267
- async steerTurn(params) {
2438
+ async steerTurn(params, rpcOptions) {
2268
2439
  input.ensureAlive();
2440
+ validateCodexRpcCallOptions(rpcOptions);
2269
2441
  const caller = "CodexControlClient.steerTurn";
2270
2442
  const threadId = assertNonEmptyThreadId(params.threadId, caller);
2271
2443
  const expectedTurnId = assertRequiredNonEmptyString(params.expectedTurnId, "expectedTurnId", caller);
2272
2444
  assertOptionalNonEmptyString(params.clientId, "clientId", caller);
2273
- const parts = await inlineCodexParts(params.input, {
2445
+ const parts = await withLinkedAbortSignals(rpcOptions?.signal, input.signal, (signal) => inlineCodexParts(params.input, {
2274
2446
  ...input.imageOptions,
2275
2447
  driverLabel: "The Codex driver",
2276
- signal: input.signal
2277
- });
2448
+ signal
2449
+ }));
2278
2450
  input.ensureAlive();
2451
+ validateCodexRpcCallOptions(rpcOptions);
2279
2452
  return sendCodexTurnSteer(input.peer, {
2280
2453
  threadId,
2281
2454
  expectedTurnId,
2282
2455
  parts,
2283
2456
  ...params.clientId !== undefined && { clientId: params.clientId }
2284
- });
2457
+ }, rpcOptions);
2285
2458
  },
2286
2459
  ...createCodexThreadControlMethods(call, {
2287
2460
  ensureAlive: input.ensureAlive,
@@ -2291,396 +2464,238 @@ function createCodexControlClient(input) {
2291
2464
  })
2292
2465
  };
2293
2466
  }
2294
- function bindCodexSessionThreadControls(controlClient, threadId) {
2295
- return {
2296
- readThread(params) {
2297
- return controlClient.readThread({
2298
- ...params,
2299
- threadId: params?.threadId ?? threadId
2300
- });
2301
- },
2302
- listTurns(params) {
2303
- return controlClient.listTurns({
2304
- ...params,
2305
- threadId: params?.threadId ?? threadId
2306
- });
2307
- },
2308
- listItems(params) {
2309
- return controlClient.listItems({
2310
- ...params,
2311
- threadId: params?.threadId ?? threadId
2312
- });
2313
- },
2314
- resumeThread(params) {
2315
- return controlClient.resumeThread({
2316
- ...params,
2317
- threadId: params?.threadId ?? threadId
2318
- });
2319
- },
2320
- revertThread(params) {
2321
- return controlClient.revertThread({
2322
- ...params,
2323
- threadId: params.threadId ?? threadId
2324
- });
2325
- },
2326
- injectItems(params) {
2327
- return controlClient.injectItems({
2328
- ...params,
2329
- threadId: params.threadId ?? threadId
2330
- });
2331
- },
2332
- unsubscribeThread(params) {
2333
- return controlClient.unsubscribeThread({
2334
- threadId: params?.threadId ?? threadId
2335
- });
2336
- },
2337
- archiveThread(params) {
2338
- return controlClient.archiveThread({
2339
- threadId: params?.threadId ?? threadId
2340
- });
2341
- },
2342
- unarchiveThread(params) {
2343
- return controlClient.unarchiveThread({
2344
- threadId: params?.threadId ?? threadId
2345
- });
2346
- },
2347
- updateThreadMetadata(params) {
2348
- return controlClient.updateThreadMetadata({
2349
- ...params,
2350
- threadId: params?.threadId ?? threadId
2351
- });
2352
- },
2353
- setThreadName(params) {
2354
- return controlClient.setThreadName({
2355
- ...params,
2356
- threadId: params.threadId ?? threadId
2357
- });
2358
- },
2359
- interruptTurn(params) {
2360
- return controlClient.interruptTurn({
2361
- ...params,
2362
- threadId: params.threadId ?? threadId
2363
- });
2364
- },
2365
- compactThread(params) {
2366
- return controlClient.compactThread({
2367
- threadId: params?.threadId ?? threadId
2368
- });
2369
- }
2370
- };
2371
- }
2372
2467
 
2373
- // src/agent-executor/codex/classify.ts
2374
- var raw = (type) => ({ source: "codex", type });
2375
- var CODEX_TOOL_ITEMS = new Set([
2376
- "commandExecution",
2377
- "fileChange",
2378
- "mcpToolCall",
2379
- "dynamicToolCall",
2380
- "collabAgentToolCall",
2381
- "webSearch",
2382
- "imageView",
2383
- "sleep",
2384
- "imageGeneration",
2385
- "functionCallOutput"
2386
- ]);
2387
- var STATUSLESS_TOOL_ITEMS = new Set([
2388
- "webSearch",
2389
- "imageView",
2390
- "sleep",
2391
- "functionCallOutput"
2392
- ]);
2393
- var CODEX_CONTENT_ITEMS = new Set([
2394
- "agentMessage",
2395
- "reasoning",
2396
- "userMessage",
2397
- "plan",
2398
- "contextCompaction",
2399
- "hookPrompt",
2400
- "subAgentActivity",
2401
- "enteredReviewMode",
2402
- "exitedReviewMode"
2403
- ]);
2404
- var KNOWN_CODEX_ERROR_CODES = new Set([
2405
- "contextWindowExceeded",
2406
- "sessionBudgetExceeded",
2407
- "usageLimitExceeded",
2408
- "rateLimitExceeded",
2409
- "flexUnavailable",
2410
- "serverOverloaded",
2411
- "modelNotFound",
2412
- "policyCapacityUnavailable",
2413
- "cyberPolicy",
2414
- "bioPolicy",
2415
- "misalignmentPolicyViolation",
2416
- "tooManyDenials",
2417
- "internalServerError",
2418
- "unauthorized",
2419
- "badRequest",
2420
- "threadRollbackFailed",
2421
- "sandboxError",
2422
- "other",
2423
- "inferenceHookDenied"
2424
- ]);
2425
- var KNOWN_CODEX_ERROR_OBJECT_KEYS = new Set([
2426
- "httpConnectionFailed",
2427
- "responseStreamConnectionFailed",
2428
- "responseStreamDisconnected",
2429
- "responseTooManyFailedAttempts",
2430
- "activeTurnNotSteerable"
2431
- ]);
2432
- var MAX_ERROR_INFO_SUMMARY_CHARS = 512;
2433
- function toolName(item) {
2434
- if (item.type === "mcpToolCall" || item.type === "dynamicToolCall" || item.type === "collabAgentToolCall") {
2435
- return nonEmptyString(Reflect.get(item, "tool")) ?? item.type;
2436
- }
2437
- if (item.type === "functionCallOutput") {
2438
- return nonEmptyString(Reflect.get(item, "name")) ?? item.type;
2439
- }
2440
- return item.type;
2441
- }
2442
- function toolInput(item) {
2443
- const { id: _id, type: _type, status: _status, aggregatedOutput: _output, ...rest } = item;
2444
- return safeJsonValue(rest);
2445
- }
2446
- function isKnownCodexErrorInfo(info) {
2447
- if (typeof info === "string")
2448
- return KNOWN_CODEX_ERROR_CODES.has(info);
2449
- if (typeof info === "object" && info !== null && !Array.isArray(info)) {
2450
- const keys = Object.keys(info);
2451
- return keys.length === 1 && keys[0] !== undefined && KNOWN_CODEX_ERROR_OBJECT_KEYS.has(keys[0]);
2452
- }
2453
- return false;
2468
+ // src/agent-executor/codex/limits.ts
2469
+ import { z as z4 } from "zod";
2470
+ var MAX_WINDOW_NAME_CHARS = 256;
2471
+ var MAX_PLAN_WINDOWS = 32;
2472
+ var EPOCH_MS_THRESHOLD = 1000000000000;
2473
+ var WindowSchema = z4.looseObject({
2474
+ usedPercent: z4.number().min(0).optional(),
2475
+ used_percent: z4.number().min(0).optional(),
2476
+ windowDurationMins: z4.number().positive().nullable().optional(),
2477
+ window_duration_mins: z4.number().positive().nullable().optional(),
2478
+ window_minutes: z4.number().positive().nullable().optional(),
2479
+ resetsAt: z4.union([z4.number(), z4.string()]).nullable().optional(),
2480
+ resets_at: z4.union([z4.number(), z4.string()]).nullable().optional()
2481
+ });
2482
+ var SnapshotSchema = z4.looseObject({
2483
+ limitId: z4.string().nullable().optional(),
2484
+ limit_id: z4.string().nullable().optional(),
2485
+ limitName: z4.string().nullable().optional(),
2486
+ limit_name: z4.string().nullable().optional(),
2487
+ planType: z4.string().nullable().optional(),
2488
+ plan_type: z4.string().nullable().optional(),
2489
+ primary: z4.unknown().optional(),
2490
+ secondary: z4.unknown().optional()
2491
+ });
2492
+ function positiveSafeInt(value) {
2493
+ return isPositiveSafeInteger(value) ? value : undefined;
2454
2494
  }
2455
- function formatCodexErrorInfo(info) {
2456
- if (info === null || info === undefined)
2495
+ function parseCodexResetsAt(raw) {
2496
+ if (raw === undefined || raw === null)
2457
2497
  return;
2458
- if (typeof info === "string") {
2459
- const trimmed = info.trim();
2460
- return trimmed.length > 0 ? trimmed.slice(0, MAX_ERROR_INFO_SUMMARY_CHARS) : undefined;
2461
- }
2462
- try {
2463
- const serialized = JSON.stringify(safeJsonValue(info));
2464
- if (serialized === undefined || serialized.length === 0)
2498
+ if (typeof raw === "number") {
2499
+ if (!Number.isFinite(raw) || raw <= 0)
2465
2500
  return;
2466
- return serialized.length > MAX_ERROR_INFO_SUMMARY_CHARS ? `${serialized.slice(0, MAX_ERROR_INFO_SUMMARY_CHARS - 1)}…` : serialized;
2467
- } catch {
2468
- return String(info).slice(0, MAX_ERROR_INFO_SUMMARY_CHARS);
2469
- }
2470
- }
2471
- function codexFailureMessage(turn) {
2472
- const rawMessage = turn.error?.message.trim() ?? "";
2473
- const info = turn.error?.codexErrorInfo;
2474
- const infoSummary = formatCodexErrorInfo(info);
2475
- if (rawMessage.length > 0) {
2476
- if (infoSummary !== undefined && !isKnownCodexErrorInfo(info) && !rawMessage.includes(infoSummary)) {
2477
- return `${rawMessage} (${infoSummary})`;
2478
- }
2479
- return rawMessage;
2480
- }
2481
- if (infoSummary !== undefined) {
2482
- return `Codex ended the turn ${turn.status} (${infoSummary})`;
2501
+ return raw < EPOCH_MS_THRESHOLD ? epochSecondsToIso(raw) : epochMsToIso(raw);
2483
2502
  }
2484
- return `Codex ended the turn ${turn.status}`;
2485
- }
2486
- function httpStatusOf(value, depth = 0) {
2487
- if (depth > 3 || typeof value !== "object" || value === null)
2503
+ const trimmed = raw.trim();
2504
+ if (trimmed.length === 0)
2488
2505
  return;
2489
- const direct = Reflect.get(value, "httpStatusCode");
2490
- if (typeof direct === "number")
2491
- return direct;
2492
- for (const nested of Object.values(value)) {
2493
- const found = httpStatusOf(nested, depth + 1);
2494
- if (found !== undefined)
2495
- return found;
2496
- }
2497
- return;
2498
- }
2499
- function failureKind(info) {
2500
- if (info === "unauthorized")
2501
- return "authRequired";
2502
- if (info === "usageLimitExceeded" || info === "rateLimitExceeded" || info === "sessionBudgetExceeded")
2503
- return "rateLimited";
2504
- const status = httpStatusOf(info);
2505
- if (status === 401 || status === 403)
2506
- return "authRequired";
2507
- if (status === 429)
2508
- return "rateLimited";
2509
- return "restartRecommended";
2506
+ const parsed = PlanWindowSchema2.shape.resetsAt.safeParse(trimmed);
2507
+ return parsed.success ? parsed.data : undefined;
2510
2508
  }
2511
- function normalizeCodexTokenTotals(rawTotals) {
2512
- if (rawTotals === undefined)
2509
+ function resolveWindowFields(raw) {
2510
+ const parsed = WindowSchema.safeParse(raw);
2511
+ if (!parsed.success)
2513
2512
  return;
2514
- const normalized = {
2515
- ...rawTotals.inputTokens !== undefined && { inputTokens: rawTotals.inputTokens },
2516
- ...rawTotals.outputTokens !== undefined && { outputTokens: rawTotals.outputTokens },
2517
- ...rawTotals.cachedInputTokens !== undefined && {
2518
- cachedInputTokens: rawTotals.cachedInputTokens
2519
- },
2520
- ...rawTotals.cacheWriteInputTokens !== undefined && {
2521
- cacheCreationInputTokens: rawTotals.cacheWriteInputTokens
2522
- },
2523
- ...rawTotals.reasoningOutputTokens !== undefined && {
2524
- thinkingTokens: rawTotals.reasoningOutputTokens
2525
- },
2526
- ...rawTotals.totalTokens !== undefined && { totalTokens: rawTotals.totalTokens }
2527
- };
2528
- return Object.keys(normalized).length > 0 ? normalized : undefined;
2529
- }
2530
- function classifyCodexTokenUsage(params, base) {
2531
- const { last, total } = CodexNotificationParams["thread/tokenUsage/updated"].parse(params).tokenUsage;
2532
- const normalizedTotal = normalizeCodexTokenTotals(total);
2533
- return {
2534
- kind: "deltas",
2535
- deltas: [
2536
- {
2537
- type: "usage",
2538
- ...base,
2539
- itemId: "usage",
2540
- raw: raw("thread/tokenUsage/updated"),
2541
- inputTokens: last.inputTokens,
2542
- outputTokens: last.outputTokens,
2543
- ...last.cachedInputTokens !== undefined && {
2544
- cachedInputTokens: last.cachedInputTokens
2545
- },
2546
- ...last.cacheWriteInputTokens !== undefined && {
2547
- cacheCreationInputTokens: last.cacheWriteInputTokens
2548
- },
2549
- ...last.reasoningOutputTokens !== undefined && {
2550
- thinkingTokens: last.reasoningOutputTokens
2551
- },
2552
- ...last.totalTokens !== undefined && { totalTokens: last.totalTokens },
2553
- ...normalizedTotal !== undefined && { total: normalizedTotal }
2554
- }
2555
- ]
2556
- };
2513
+ const window = parsed.data;
2514
+ const usedPercent = window.usedPercent ?? window.used_percent;
2515
+ if (usedPercent === undefined || !Number.isFinite(usedPercent) || usedPercent < 0) {
2516
+ return;
2517
+ }
2518
+ const mins = positiveSafeInt(window.windowDurationMins ?? window.window_duration_mins ?? window.window_minutes);
2519
+ const resetsAt = parseCodexResetsAt(window.resetsAt ?? window.resets_at);
2520
+ return { usedPercent, mins, resetsAt };
2557
2521
  }
2558
- function classifyCodexNotification(method, params, state) {
2559
- const base = { turnId: state.turnId };
2560
- switch (method) {
2561
- case "item/agentMessage/delta": {
2562
- const p = CodexNotificationParams[method].parse(params);
2563
- return {
2564
- kind: "deltas",
2565
- deltas: [{ type: "text", ...base, itemId: p.itemId, raw: raw(method), text: p.delta }]
2566
- };
2522
+ function appendBucketWindows(out, seenNames, bucketId, seedKey, snapshot) {
2523
+ const label = clampPlanName(snapshot.limitName ?? snapshot.limit_name, MAX_WINDOW_NAME_CHARS);
2524
+ const primary = resolveWindowFields(snapshot.primary);
2525
+ const secondary = resolveWindowFields(snapshot.secondary);
2526
+ const duplicateDuration = primary !== undefined && secondary !== undefined && primary.mins !== undefined && primary.mins === secondary.mins;
2527
+ const slots = [
2528
+ ["primary", primary],
2529
+ ["secondary", secondary]
2530
+ ];
2531
+ for (const [slot, window] of slots) {
2532
+ if (window === undefined || out.length >= MAX_PLAN_WINDOWS)
2533
+ continue;
2534
+ const suffix = window.mins === undefined ? `:${slot}` : duplicateDuration ? `:${window.mins}m:${slot}` : `:${window.mins}m`;
2535
+ const name = clampUniqueWindowName(bucketId, suffix, seenNames, `${seedKey}:${bucketId}:${slot}`, MAX_WINDOW_NAME_CHARS);
2536
+ out.push(PlanWindowSchema2.parse({
2537
+ name,
2538
+ usedPercent: Math.min(100, window.usedPercent),
2539
+ ...window.resetsAt !== undefined && { resetsAt: window.resetsAt },
2540
+ ...window.mins !== undefined && { windowDurationMins: window.mins },
2541
+ ...label !== undefined && { label }
2542
+ }));
2543
+ }
2544
+ }
2545
+ function parseCodexRateLimitsInternal(reported) {
2546
+ const windows = [];
2547
+ const seenNames = new Set;
2548
+ let plan;
2549
+ const capturePlan = (snapshot) => {
2550
+ if (plan === undefined) {
2551
+ plan = clampPlanName(snapshot.planType ?? snapshot.plan_type, MAX_WINDOW_NAME_CHARS);
2567
2552
  }
2568
- case "item/reasoning/textDelta":
2569
- case "item/reasoning/summaryTextDelta": {
2570
- const p = CodexNotificationParams[method].parse(params);
2571
- return {
2572
- kind: "deltas",
2573
- deltas: [
2574
- { type: "reasoning", ...base, itemId: p.itemId, raw: raw(method), text: p.delta }
2575
- ]
2576
- };
2553
+ };
2554
+ if (isRecord(reported) && (("rateLimits" in reported) || ("rateLimitsByLimitId" in reported) || ("rate_limits" in reported) || ("rate_limits_by_limit_id" in reported))) {
2555
+ const seenLimitIds = new Set;
2556
+ const rawById = reported.rateLimitsByLimitId ?? reported.rate_limits_by_limit_id;
2557
+ if (isRecord(rawById)) {
2558
+ for (const mapKey of Object.keys(rawById).sort((a, b) => a.localeCompare(b))) {
2559
+ const parsed = SnapshotSchema.safeParse(rawById[mapKey]);
2560
+ if (!parsed.success)
2561
+ continue;
2562
+ capturePlan(parsed.data);
2563
+ const limitId = nonEmptyString(parsed.data.limitId ?? parsed.data.limit_id)?.trim() ?? nonEmptyString(mapKey)?.trim() ?? "limit";
2564
+ seenLimitIds.add(limitId);
2565
+ appendBucketWindows(windows, seenNames, limitId, mapKey, parsed.data);
2566
+ if (windows.length >= MAX_PLAN_WINDOWS)
2567
+ return { windows, plan };
2568
+ }
2577
2569
  }
2578
- case "item/started":
2579
- case "item/completed": {
2580
- const { item } = CodexNotificationParams[method].parse(params);
2581
- if (CODEX_CONTENT_ITEMS.has(item.type))
2582
- return { kind: "ignore", reason: `${method} ${item.type}` };
2583
- if (!CODEX_TOOL_ITEMS.has(item.type)) {
2584
- return {
2585
- kind: "unhandled",
2586
- delta: {
2587
- type: "error",
2588
- ...base,
2589
- itemId: `unhandled:${item.id}`,
2590
- raw: raw(`${method}/${item.type}`),
2591
- kind: "unhandled",
2592
- message: `Codex item ${item.type} is not known to this driver`
2593
- }
2594
- };
2570
+ const rawSingle = reported.rateLimits ?? reported.rate_limits;
2571
+ if (windows.length < MAX_PLAN_WINDOWS && rawSingle !== undefined) {
2572
+ const parsedSingle = SnapshotSchema.safeParse(rawSingle);
2573
+ if (parsedSingle.success) {
2574
+ capturePlan(parsedSingle.data);
2575
+ const explicitId = nonEmptyString(parsedSingle.data.limitId ?? parsedSingle.data.limit_id)?.trim();
2576
+ const shouldIncludeSingle = seenLimitIds.size === 0 || explicitId !== undefined && !seenLimitIds.has(explicitId);
2577
+ if (shouldIncludeSingle) {
2578
+ appendBucketWindows(windows, seenNames, explicitId ?? "limit", explicitId ?? "rateLimits", parsedSingle.data);
2579
+ }
2595
2580
  }
2596
- if (method === "item/started") {
2597
- return {
2598
- kind: "deltas",
2599
- deltas: [
2600
- {
2601
- type: "tool-call",
2602
- ...base,
2603
- itemId: `call:${item.id}`,
2604
- raw: raw(method),
2605
- callId: item.id,
2606
- toolName: toolName(item),
2607
- input: toolInput(item)
2608
- }
2609
- ]
2610
- };
2581
+ }
2582
+ return { windows, plan };
2583
+ }
2584
+ const single = SnapshotSchema.safeParse(reported);
2585
+ if (!single.success)
2586
+ return { windows: [], plan: undefined };
2587
+ capturePlan(single.data);
2588
+ const limitId = nonEmptyString(single.data.limitId ?? single.data.limit_id)?.trim() ?? "limit";
2589
+ appendBucketWindows(windows, seenNames, limitId, limitId, single.data);
2590
+ return { windows, plan };
2591
+ }
2592
+ function codexPlanWindows(reported) {
2593
+ return parseCodexRateLimitsInternal(reported).windows;
2594
+ }
2595
+ function codexPlanLimits(reported, now = new Date) {
2596
+ const { windows, plan } = parseCodexRateLimitsInternal(reported);
2597
+ return PlanLimitsSchema2.parse({
2598
+ answer: windows.length > 0 ? "known" : "unpublished",
2599
+ windows,
2600
+ observedAt: now.toISOString(),
2601
+ ...plan !== undefined && { plan }
2602
+ });
2603
+ }
2604
+
2605
+ // src/agent-executor/codex/pagination.ts
2606
+ var DEFAULT_FIND_TURN_MAX_PAGES = 256;
2607
+ var DEFAULT_FIND_TURN_PAGE_SIZE = 50;
2608
+ var MAX_UINT322 = 4294967295;
2609
+ async function walkCodexPages(fetchPage, options, onPage, repeatedCursorLabel) {
2610
+ assertPositiveSafeInteger("maxPages", options.maxPages, TypeError, { absent: "refused" });
2611
+ const onRepeatedCursor = options.onRepeatedCursor ?? "throw";
2612
+ if (onRepeatedCursor !== "throw" && onRepeatedCursor !== "stop") {
2613
+ throw new TypeError(`[stitchkit] iterateCodexPages: onRepeatedCursor must be "throw" or "stop", received ${JSON.stringify(onRepeatedCursor)}`);
2614
+ }
2615
+ const signal = options.signal;
2616
+ const seen = new Set;
2617
+ let cursor;
2618
+ for (let pageIndex = 0;pageIndex < options.maxPages; pageIndex += 1) {
2619
+ if (signal?.aborted)
2620
+ throw abortReason(signal);
2621
+ const pending = fetchPage(cursor);
2622
+ const page = signal !== undefined ? await raceAbort(pending, signal) : await pending;
2623
+ if (signal?.aborted)
2624
+ throw abortReason(signal);
2625
+ if (onPage(page) === "stop") {
2626
+ return { truncated: false, stoppedByConsumer: true };
2627
+ }
2628
+ const next = page.nextCursor;
2629
+ if (next === null || next === undefined) {
2630
+ return { truncated: false, stoppedByConsumer: false };
2631
+ }
2632
+ if (seen.has(next)) {
2633
+ if (onRepeatedCursor === "stop") {
2634
+ return { truncated: true, stoppedByConsumer: false };
2611
2635
  }
2612
- const status = Reflect.get(item, "status");
2613
- const failure = Reflect.get(item, "failure");
2614
- const output = failure ?? Reflect.get(item, "aggregatedOutput") ?? Reflect.get(item, "output") ?? Reflect.get(item, "savedPath") ?? Reflect.get(item, "fileId") ?? Reflect.get(item, "result") ?? Reflect.get(item, "results") ?? Reflect.get(item, "contentItems") ?? Reflect.get(item, "changes") ?? Reflect.get(item, "agentsStates") ?? Reflect.get(item, "error");
2615
- const hasFailure = failure !== undefined && failure !== null;
2616
- const outcome = !hasFailure && (status === "completed" || STATUSLESS_TOOL_ITEMS.has(item.type) && status === undefined) ? "success" : status === "declined" || status === "interrupted" ? "interrupted" : "error";
2617
- return {
2618
- kind: "deltas",
2619
- deltas: [
2620
- {
2621
- type: "tool-result",
2622
- ...base,
2623
- itemId: `result:${item.id}`,
2624
- raw: raw(method),
2625
- callId: item.id,
2626
- toolName: toolName(item),
2627
- outcome,
2628
- ...output !== undefined && output !== null && {
2629
- output: safeJsonValue(output)
2630
- }
2631
- }
2632
- ]
2633
- };
2636
+ throw new Error(`Codex ${repeatedCursorLabel} repeated cursor ${JSON.stringify(next)} before history ended`);
2634
2637
  }
2635
- case "turn/completed": {
2636
- const { turn } = CodexNotificationParams[method].parse(params);
2637
- const outcome = state.interruptRequested ? "interrupted" : turn.status === "completed" ? "completed" : turn.status === "interrupted" ? "interrupted" : "failed";
2638
- const deltas = [];
2639
- if (outcome === "failed") {
2640
- deltas.push({
2641
- type: "error",
2642
- ...base,
2643
- itemId: "failure",
2644
- raw: raw(method),
2645
- kind: failureKind(turn.error?.codexErrorInfo),
2646
- message: codexFailureMessage(turn)
2647
- });
2638
+ seen.add(next);
2639
+ cursor = next;
2640
+ }
2641
+ return { truncated: true, stoppedByConsumer: false };
2642
+ }
2643
+ async function iterateCodexPages(fetchPage, options) {
2644
+ const pages = [];
2645
+ const outcome = await walkCodexPages(fetchPage, options, (page) => {
2646
+ pages.push(page);
2647
+ return "continue";
2648
+ }, "pagination");
2649
+ return { pages, truncated: outcome.truncated };
2650
+ }
2651
+ async function findCodexTurnByClientId(controls, params) {
2652
+ const caller = "findCodexTurnByClientId";
2653
+ const threadId = assertNonEmptyThreadId(params.threadId, caller);
2654
+ const clientId = assertRequiredNonEmptyString(params.clientId, "clientId", caller);
2655
+ const maxPages = params.maxPages ?? DEFAULT_FIND_TURN_MAX_PAGES;
2656
+ const pageSize = params.pageSize ?? DEFAULT_FIND_TURN_PAGE_SIZE;
2657
+ assertPositiveSafeInteger(`[stitchkit] ${caller}: maxPages`, maxPages);
2658
+ assertPositiveSafeInteger(`[stitchkit] ${caller}: pageSize`, pageSize);
2659
+ if (pageSize > MAX_UINT322) {
2660
+ throw new TypeError(`[stitchkit] ${caller}: pageSize must not exceed ${MAX_UINT322}`);
2661
+ }
2662
+ if (params.timeoutMs !== undefined) {
2663
+ assertTimerMs("timeoutMs", params.timeoutMs);
2664
+ }
2665
+ const rpcOptions = params.timeoutMs !== undefined || params.signal !== undefined ? {
2666
+ ...params.timeoutMs !== undefined && { timeoutMs: params.timeoutMs },
2667
+ ...params.signal !== undefined && { signal: params.signal }
2668
+ } : undefined;
2669
+ let matched = null;
2670
+ const outcome = await walkCodexPages((cursor) => controls.listTurns({
2671
+ threadId,
2672
+ limit: pageSize,
2673
+ itemsView: "full",
2674
+ ...cursor !== undefined && { cursor }
2675
+ }, rpcOptions), {
2676
+ maxPages,
2677
+ signal: params.signal,
2678
+ onRepeatedCursor: "throw"
2679
+ }, (page) => {
2680
+ for (const turn of page.data) {
2681
+ if (turn.itemsView !== undefined && turn.itemsView !== "full") {
2682
+ throw new Error(`Codex thread/turns/list returned incomplete itemsView ${JSON.stringify(turn.itemsView)} for turn ${turn.id}`);
2648
2683
  }
2649
- deltas.push({ type: "turn-end", ...base, itemId: "end", raw: raw(method), outcome });
2650
- return { kind: "end", deltas, outcome };
2651
2684
  }
2652
- case "thread/tokenUsage/updated":
2653
- return classifyCodexTokenUsage(params, base);
2654
- case "serverRequest/resolved":
2655
- return {
2656
- kind: "resolved",
2657
- requestId: String(CodexNotificationParams[method].parse(params).requestId)
2658
- };
2659
- case "account/rateLimits/updated": {
2660
- const parsed = CodexNotificationParams[method].parse(params);
2661
- return {
2662
- kind: "limits",
2663
- rateLimits: parsed.rateLimitsByLimitId !== undefined ? {
2664
- rateLimits: parsed.rateLimits,
2665
- rateLimitsByLimitId: parsed.rateLimitsByLimitId
2666
- } : parsed.rateLimits
2667
- };
2685
+ for (const turn of page.data) {
2686
+ if (turn.items.some((item) => item.type === "userMessage" && item.clientId === clientId)) {
2687
+ matched = turn;
2688
+ return "stop";
2689
+ }
2668
2690
  }
2669
- default:
2670
- if (CODEX_QUIET_NOTIFICATIONS.has(method))
2671
- return { kind: "ignore", reason: method };
2672
- return {
2673
- kind: "unhandled",
2674
- delta: {
2675
- type: "error",
2676
- ...base,
2677
- itemId: `unhandled:${method}`,
2678
- raw: raw(method),
2679
- kind: "unhandled",
2680
- message: `Codex notification ${method} is not known to this driver`
2681
- }
2682
- };
2691
+ return "continue";
2692
+ }, "thread/turns/list");
2693
+ if (outcome.stoppedByConsumer)
2694
+ return matched;
2695
+ if (outcome.truncated) {
2696
+ throw new Error(`Codex thread/turns/list exceeded ${maxPages} pages without reaching the end of history`);
2683
2697
  }
2698
+ return null;
2684
2699
  }
2685
2700
 
2686
2701
  // src/agent-executor/codex/handlers.ts
@@ -2692,9 +2707,9 @@ function emitCodexNotification(state, method, params, duringActiveTurn, deltas)
2692
2707
  invokeSafely(() => state.onNotification?.({ method, params, duringActiveTurn, deltas }));
2693
2708
  }
2694
2709
  function handleCodexNotification(state, method, params) {
2695
- const turn = state.getTurn();
2710
+ const turn = codexEventTurn(state.getTurn(), params);
2696
2711
  const duringActiveTurn = turn !== undefined;
2697
- const effectiveTurnId = turn?.state.turnId ?? externalCodexTurnIdOf(params);
2712
+ const effectiveTurnId = turn?.state.turnId ?? codexTurnIdOf(params) ?? "external";
2698
2713
  let verdict;
2699
2714
  try {
2700
2715
  verdict = classifyCodexNotification(method, params, turn?.state ?? { turnId: effectiveTurnId, interruptRequested: false });
@@ -2715,9 +2730,11 @@ function handleCodexNotification(state, method, params) {
2715
2730
  switch (verdict.kind) {
2716
2731
  case "limits":
2717
2732
  try {
2733
+ const parsedLimits = codexPlanLimits(verdict.rateLimits, new Date);
2718
2734
  state.limits.set(state.profileId, mergeRateLimitEvent2({
2719
2735
  previous: state.limits.get(state.profileId),
2720
- windows: codexPlanWindows(verdict.rateLimits),
2736
+ windows: parsedLimits.windows,
2737
+ ...parsedLimits.plan !== undefined && { plan: parsedLimits.plan },
2721
2738
  now: new Date
2722
2739
  }));
2723
2740
  emitCodexNotification(state, method, params, duringActiveTurn, []);
@@ -2738,7 +2755,9 @@ function handleCodexNotification(state, method, params) {
2738
2755
  case "resolved": {
2739
2756
  const resolvedTurn = turn?.pending.delete(verdict.requestId) === true;
2740
2757
  const externalEntry = state.externalPending.get(verdict.requestId);
2741
- const resolvedExternal = externalEntry !== undefined;
2758
+ const threadId = codexThreadIdOf(params);
2759
+ const nativeTurnId = codexTurnIdOf(params);
2760
+ const resolvedExternal = !resolvedTurn && externalEntry !== undefined && (threadId === undefined || externalEntry.threadId === undefined || threadId === externalEntry.threadId) && (nativeTurnId === undefined || nativeTurnId === externalEntry.turnId);
2742
2761
  if (resolvedExternal)
2743
2762
  state.externalPending.delete(verdict.requestId);
2744
2763
  const resolvedDelta = {
@@ -2750,7 +2769,7 @@ function handleCodexNotification(state, method, params) {
2750
2769
  };
2751
2770
  if (resolvedTurn && turn !== undefined)
2752
2771
  offerTurnDelta(turn.channel, resolvedDelta);
2753
- emitCodexNotification(state, method, params, duringActiveTurn, resolvedTurn || resolvedExternal ? [resolvedDelta] : []);
2772
+ emitCodexNotification(state, method, params, duringActiveTurn && !resolvedExternal, resolvedTurn || resolvedExternal ? [resolvedDelta] : []);
2754
2773
  return;
2755
2774
  }
2756
2775
  case "deltas":
@@ -2765,7 +2784,8 @@ function handleCodexNotification(state, method, params) {
2765
2784
  }
2766
2785
  case "end":
2767
2786
  endEngineTurn(turn, codexStopped, verdict.deltas);
2768
- state.clearTurn();
2787
+ if (turn !== undefined)
2788
+ state.clearTurn();
2769
2789
  emitCodexNotification(state, method, params, duringActiveTurn, verdict.deltas);
2770
2790
  return;
2771
2791
  case "ignore":
@@ -2774,7 +2794,7 @@ function handleCodexNotification(state, method, params) {
2774
2794
  }
2775
2795
  }
2776
2796
  function handleCodexRequest(state, method, params, id) {
2777
- const turn = state.getTurn();
2797
+ const turn = codexEventTurn(state.getTurn(), params);
2778
2798
  if (!isKnownCodexRequestMethod(method)) {
2779
2799
  if (turn !== undefined) {
2780
2800
  offerTurnDelta(turn.channel, {
@@ -2837,7 +2857,7 @@ function handleCodexRequest(state, method, params, id) {
2837
2857
  throw new JsonRpcError2(JSON_RPC_INTERNAL_ERROR, `Duplicate pending external Codex server request ${interactionId}`);
2838
2858
  }
2839
2859
  const parsed = parseCodexServerRequest(method, params);
2840
- const turnId = externalCodexTurnIdOf(params);
2860
+ const turnId = codexTurnIdOf(params) ?? "external";
2841
2861
  const delta = {
2842
2862
  type: "request",
2843
2863
  turnId,
@@ -2848,7 +2868,13 @@ function handleCodexRequest(state, method, params, id) {
2848
2868
  ...parsed.deltaFields
2849
2869
  };
2850
2870
  return new Promise((resolve, reject) => {
2851
- const entry = { detail: parsed.detail, turnId, resolve };
2871
+ const threadId = codexThreadIdOf(params);
2872
+ const entry = {
2873
+ detail: parsed.detail,
2874
+ turnId,
2875
+ ...threadId !== undefined && { threadId },
2876
+ resolve
2877
+ };
2852
2878
  state.externalPending.set(interactionId, entry);
2853
2879
  const onObserverError = (error) => {
2854
2880
  if (state.externalPending.get(interactionId) !== entry)
@@ -2885,8 +2911,109 @@ function handleCodexRequest(state, method, params, id) {
2885
2911
  }
2886
2912
  function createCodexHandlers(state) {
2887
2913
  return {
2888
- onNotification: (method, params) => handleCodexNotification(state, method, params),
2889
- onRequest: (method, params, id) => handleCodexRequest(state, method, params, id)
2914
+ onNotification(method, params) {
2915
+ const starting = codexEventTurn(state.getTurn(), params)?.starting;
2916
+ const deliver = () => handleCodexNotification(state, method, params);
2917
+ if (starting === undefined)
2918
+ deliver();
2919
+ else
2920
+ starting.defer(params, deliver);
2921
+ },
2922
+ onRequest(method, params, id) {
2923
+ const starting = codexEventTurn(state.getTurn(), params)?.starting;
2924
+ const deliver = () => handleCodexRequest(state, method, params, id);
2925
+ if (starting === undefined)
2926
+ return deliver();
2927
+ return new Promise((resolve, reject) => {
2928
+ starting.defer(params, () => {
2929
+ try {
2930
+ resolve(deliver());
2931
+ } catch (error) {
2932
+ reject(error);
2933
+ }
2934
+ });
2935
+ });
2936
+ }
2937
+ };
2938
+ }
2939
+
2940
+ // src/agent-executor/codex/session-bind.ts
2941
+ function bindCodexSessionThreadControls(controlClient, threadId) {
2942
+ return {
2943
+ readThread(params, options) {
2944
+ return controlClient.readThread({
2945
+ ...params,
2946
+ threadId: params?.threadId ?? threadId
2947
+ }, options);
2948
+ },
2949
+ listTurns(params, options) {
2950
+ return controlClient.listTurns({
2951
+ ...params,
2952
+ threadId: params?.threadId ?? threadId
2953
+ }, options);
2954
+ },
2955
+ listItems(params, options) {
2956
+ return controlClient.listItems({
2957
+ ...params,
2958
+ threadId: params?.threadId ?? threadId
2959
+ }, options);
2960
+ },
2961
+ resumeThread(params, options) {
2962
+ return controlClient.resumeThread({
2963
+ ...params,
2964
+ threadId: params?.threadId ?? threadId
2965
+ }, options);
2966
+ },
2967
+ revertThread(params, options) {
2968
+ return controlClient.revertThread({
2969
+ ...params,
2970
+ threadId: params.threadId ?? threadId
2971
+ }, options);
2972
+ },
2973
+ injectItems(params, options) {
2974
+ return controlClient.injectItems({
2975
+ ...params,
2976
+ threadId: params.threadId ?? threadId
2977
+ }, options);
2978
+ },
2979
+ unsubscribeThread(params, options) {
2980
+ return controlClient.unsubscribeThread({
2981
+ threadId: params?.threadId ?? threadId
2982
+ }, options);
2983
+ },
2984
+ archiveThread(params, options) {
2985
+ return controlClient.archiveThread({
2986
+ threadId: params?.threadId ?? threadId
2987
+ }, options);
2988
+ },
2989
+ unarchiveThread(params, options) {
2990
+ return controlClient.unarchiveThread({
2991
+ threadId: params?.threadId ?? threadId
2992
+ }, options);
2993
+ },
2994
+ updateThreadMetadata(params, options) {
2995
+ return controlClient.updateThreadMetadata({
2996
+ ...params,
2997
+ threadId: params?.threadId ?? threadId
2998
+ }, options);
2999
+ },
3000
+ setThreadName(params, options) {
3001
+ return controlClient.setThreadName({
3002
+ ...params,
3003
+ threadId: params.threadId ?? threadId
3004
+ }, options);
3005
+ },
3006
+ interruptTurn(params, options) {
3007
+ return controlClient.interruptTurn({
3008
+ ...params,
3009
+ threadId: params.threadId ?? threadId
3010
+ }, options);
3011
+ },
3012
+ compactThread(params, options) {
3013
+ return controlClient.compactThread({
3014
+ threadId: params?.threadId ?? threadId
3015
+ }, options);
3016
+ }
2890
3017
  };
2891
3018
  }
2892
3019
 
@@ -2976,7 +3103,8 @@ async function openCodexSession(config, input) {
2976
3103
  linked.signal.throwIfAborted();
2977
3104
  }
2978
3105
  const openedReply = await openCodexThreadRpc(peer, config, input, dynamicOverrides);
2979
- const parsed = CodexStartedThreadSchema.parse(openedReply);
3106
+ const openMethod = input.forkFrom !== undefined ? "thread/fork" : input.nativeThreadId !== undefined ? "thread/resume" : "thread/start";
3107
+ const parsed = parseCodexResponse(openMethod, CodexStartedThreadSchema, openedReply);
2980
3108
  threadId = parsed.thread.id;
2981
3109
  activeThreadId = threadId;
2982
3110
  threadContext = extractCodexThreadContext(parsed);
@@ -3279,7 +3407,8 @@ async function openSharedCodexThread(state, threadInput) {
3279
3407
  const openedReply = await raceAbort(openCodexThreadRpc(state.peer, state.config, threadInput, dynamicOverrides), threadAbort.signal, disposeLateOpen);
3280
3408
  threadAbort.signal.throwIfAborted();
3281
3409
  state.ensureServerAlive();
3282
- const parsed = CodexStartedThreadSchema.parse(openedReply);
3410
+ const openMethod = threadInput.forkFrom !== undefined ? "thread/fork" : threadInput.nativeThreadId !== undefined ? "thread/resume" : "thread/start";
3411
+ const parsed = parseCodexResponse(openMethod, CodexStartedThreadSchema, openedReply);
3283
3412
  const threadId = parsed.thread.id;
3284
3413
  const threadContext = extractCodexThreadContext(parsed);
3285
3414
  if (state.threads.has(threadId)) {
@@ -3355,19 +3484,6 @@ async function openSharedCodexThread(state, threadInput) {
3355
3484
  // src/agent-executor/codex/shared-server.ts
3356
3485
  var DEFAULT_MAX_SHARED_THREADS = 32;
3357
3486
  var HARD_MAX_SHARED_THREADS = 256;
3358
- function extractCodexThreadId(params) {
3359
- if (!isRecord(params))
3360
- return;
3361
- if (typeof params.threadId === "string" && params.threadId.length > 0)
3362
- return params.threadId;
3363
- if (isRecord(params.thread) && typeof params.thread.id === "string" && params.thread.id.length > 0) {
3364
- return params.thread.id;
3365
- }
3366
- if (isRecord(params.turn) && typeof params.turn.threadId === "string" && params.turn.threadId.length > 0) {
3367
- return params.turn.threadId;
3368
- }
3369
- return;
3370
- }
3371
3487
  function validateSharedServerInputs(config, input) {
3372
3488
  if (config.transport !== undefined && config.transport.kind !== "stdio") {
3373
3489
  throw new TypeError(`[stitchkit] CodexDriver.openSharedServer: shared multi-thread mode requires stdio transport (received ${JSON.stringify(config.transport.kind)})`);
@@ -3425,7 +3541,7 @@ async function openCodexSharedServer(config, baseCapabilities, input) {
3425
3541
  invokeSafely(() => globalHandlers.onNotification(method, params));
3426
3542
  return;
3427
3543
  }
3428
- const targetId = extractCodexThreadId(params);
3544
+ const targetId = codexThreadIdOf(params);
3429
3545
  const slot = targetId !== undefined ? threads.get(targetId) : undefined;
3430
3546
  if (slot !== undefined) {
3431
3547
  invokeSafely(() => slot.handlers.onNotification(method, params));
@@ -3434,7 +3550,7 @@ async function openCodexSharedServer(config, baseCapabilities, input) {
3434
3550
  invokeSafely(() => globalHandlers.onNotification(method, params));
3435
3551
  },
3436
3552
  onRequest(method, params, id) {
3437
- const targetId = extractCodexThreadId(params);
3553
+ const targetId = codexThreadIdOf(params);
3438
3554
  const slot = targetId !== undefined ? threads.get(targetId) : undefined;
3439
3555
  if (slot !== undefined)
3440
3556
  return slot.handlers.onRequest(method, params, id);
@@ -3519,32 +3635,7 @@ async function openCodexSharedServer(config, baseCapabilities, input) {
3519
3635
  }
3520
3636
 
3521
3637
  // src/agent-executor/codex/driver.ts
3522
- var MAX_HISTORY_PAGES = 256;
3523
3638
  var FIND_INPUT_MAX_LINE_BYTES = 64 * 1024 * 1024;
3524
- async function findCodexClientInput(peer, nativeThreadId, clientId) {
3525
- const seen = new Set;
3526
- let cursor;
3527
- for (let pageNumber = 0;pageNumber < MAX_HISTORY_PAGES; pageNumber += 1) {
3528
- const page = CodexTurnsPageSchema.parse(await peer.request("thread/turns/list", {
3529
- threadId: nativeThreadId,
3530
- limit: 50,
3531
- itemsView: "full",
3532
- ...cursor !== undefined && { cursor }
3533
- }));
3534
- if (page.data.some((turn) => turn.items.some((item) => item.type === "userMessage" && item.clientId === clientId))) {
3535
- return true;
3536
- }
3537
- const next = page.nextCursor;
3538
- if (next === null || next === undefined)
3539
- return false;
3540
- if (seen.has(next)) {
3541
- throw new Error(`Codex thread/turns/list repeated cursor ${JSON.stringify(next)} before history ended`);
3542
- }
3543
- seen.add(next);
3544
- cursor = next;
3545
- }
3546
- throw new Error(`Codex thread/turns/list exceeded ${MAX_HISTORY_PAGES} pages without reaching the end of history`);
3547
- }
3548
3639
  function validateCodexDriverOptions(config) {
3549
3640
  validateImageOptions(config);
3550
3641
  assertPositiveSafeInteger("maxFrameBytes", config.maxFrameBytes);
@@ -3658,37 +3749,68 @@ function createCodexDriver(config = {}) {
3658
3749
  const decoder = new TextDecoder;
3659
3750
  const text = `${decoder.decode(loginResult.stdout)}
3660
3751
  ${decoder.decode(loginResult.stderr)}`.trim();
3661
- const signedIn = loginResult.exitCode === 0 && /(?:^|\n)Logged in/im.test(text);
3662
- const credential = !signedIn ? "none" : /chatgpt/i.test(text) ? "subscription" : /api key/i.test(text) ? "api-key" : "unknown";
3663
- let planLimits = limits.get(parsed.profileId);
3752
+ const line = text.split(/\r?\n/).map((value) => value.trim()).find((value) => /^Logged in(?:\s|$)/i.test(value));
3753
+ const signedIn = loginResult.exitCode === 0 && line !== undefined;
3754
+ const signedOut = loginResult.exitCode === 1 && /^Not logged in\s*$/im.test(text);
3755
+ const credential = signedIn ? /chatgpt/i.test(line) ? "subscription" : /api key/i.test(line) ? "api-key" : "unknown" : signedOut ? "none" : "unknown";
3756
+ let planLimits;
3664
3757
  if (credential === "subscription") {
3665
3758
  try {
3666
3759
  const answer = await ask(parsed, process.cwd(), (peer) => peer.request("account/rateLimits/read"));
3667
- const windows = codexPlanWindows(answer);
3668
- planLimits = mergeRateLimitEvent2({ previous: planLimits, windows, now: new Date });
3760
+ const snapshot = codexPlanLimits(answer);
3761
+ planLimits = {
3762
+ ...snapshot,
3763
+ windows: snapshot.windows.toSorted((a, b) => a.name.localeCompare(b.name))
3764
+ };
3669
3765
  limits.set(parsed.profileId, planLimits);
3670
3766
  } catch (error) {
3671
3767
  planLimits = planLimitsReadFailed2({
3672
- previous: planLimits,
3768
+ previous: limits.get(parsed.profileId),
3673
3769
  error: error instanceof Error ? error.message : String(error),
3674
3770
  now: new Date
3675
3771
  });
3676
3772
  }
3677
3773
  } else if (credential === "api-key") {
3774
+ limits.delete(parsed.profileId);
3678
3775
  planLimits = {
3679
3776
  answer: "no-plan-limit",
3680
3777
  windows: [],
3681
3778
  observedAt: new Date().toISOString()
3682
3779
  };
3683
3780
  }
3781
+ if (signedOut)
3782
+ limits.delete(parsed.profileId);
3783
+ if (credential === "unknown") {
3784
+ const previous = limits.get(parsed.profileId);
3785
+ if (previous !== undefined)
3786
+ planLimits = planLimitsReadFailed2({
3787
+ previous,
3788
+ error: "Codex login status could not confirm the credential",
3789
+ now: new Date
3790
+ });
3791
+ }
3684
3792
  return {
3685
- login: { state: signedIn ? "signed-in" : "signed-out" },
3793
+ login: { state: signedIn ? "signed-in" : signedOut ? "signed-out" : "unknown" },
3686
3794
  effectiveCredential: credential,
3687
3795
  ...planLimits && { planLimits }
3688
3796
  };
3689
3797
  },
3690
3798
  async findInput(input) {
3691
- return ask(input.profile, input.cwd, (peer) => findCodexClientInput(peer, input.nativeThreadId, input.clientId), Math.max(FIND_INPUT_MAX_LINE_BYTES, config.maxFrameBytes ?? 0));
3799
+ return ask(input.profile, input.cwd, async (peer) => {
3800
+ const controls = createCodexControlClient({
3801
+ peer,
3802
+ imageOptions: config,
3803
+ signal: new AbortController().signal,
3804
+ ensureAlive: () => {
3805
+ return;
3806
+ }
3807
+ });
3808
+ const found = await findCodexTurnByClientId(controls, {
3809
+ threadId: input.nativeThreadId,
3810
+ clientId: input.clientId
3811
+ });
3812
+ return found !== null;
3813
+ }, Math.max(FIND_INPUT_MAX_LINE_BYTES, config.maxFrameBytes ?? 0));
3692
3814
  },
3693
3815
  open: (input) => openCodexSession(session(), input),
3694
3816
  connectControl: (input) => openCodexControlConnection(session(), input),
@@ -3781,10 +3903,55 @@ var codexFakeScenarios = {
3781
3903
  crash: () => steps(text("dying "), { do: "crash" })
3782
3904
  };
3783
3905
  export {
3906
+ CODEX_THREAD_SOURCE_KINDS2 as CODEX_THREAD_SOURCE_KINDS,
3907
+ CODEX_TOOL_ITEMS,
3908
+ CodexAccountReadResponseSchema,
3909
+ CodexAccountSchema,
3910
+ CodexApprovalPolicySchema2 as CodexApprovalPolicySchema,
3911
+ CodexCollaborationModePresetSchema,
3912
+ CodexCollaborationModeSchema2 as CodexCollaborationModeSchema,
3913
+ CodexCollaborationModesResponseSchema,
3914
+ CodexConfigReadResponseSchema,
3915
+ CodexConfigSchema,
3916
+ CodexItemsPageSchema,
3917
+ CodexListedTurnSchema2 as CodexListedTurnSchema,
3918
+ CodexLoadedThreadsPageSchema,
3784
3919
  CodexLocalImageInputSchema,
3920
+ CodexMcpServerStatusPageSchema,
3921
+ CodexMcpServerStatusSchema,
3922
+ CodexModelSchema,
3923
+ CodexModelsPageSchema,
3924
+ CodexNotificationParams,
3925
+ CodexProtocolError2 as CodexProtocolError,
3926
+ CodexRateLimitSnapshotSchema,
3927
+ CodexRateLimitWindowSchema,
3928
+ CodexRateLimitsResponseSchema,
3929
+ CodexReadThreadResponseSchema,
3930
+ CodexResumeThreadResponseSchema,
3931
+ CodexSandboxModeSchema2 as CodexSandboxModeSchema,
3932
+ CodexSandboxPolicySchema2 as CodexSandboxPolicySchema,
3785
3933
  CodexSkillInputSchema,
3786
- CodexUnixSocketError,
3934
+ CodexSkillsListResponseSchema,
3935
+ CodexThreadContextSchema2 as CodexThreadContextSchema,
3936
+ CodexThreadItemEntrySchema,
3937
+ CodexThreadItemSchema2 as CodexThreadItemSchema,
3938
+ CodexThreadMetadataUpdateResponseSchema,
3939
+ CodexThreadSchema2 as CodexThreadSchema,
3940
+ CodexThreadSourceKindSchema2 as CodexThreadSourceKindSchema,
3941
+ CodexThreadStatusSchema2 as CodexThreadStatusSchema,
3942
+ CodexThreadUnarchiveResponseSchema,
3943
+ CodexThreadUnsubscribeResponseSchema,
3944
+ CodexThreadUnsubscribeStatusSchema,
3945
+ CodexThreadsPageSchema,
3946
+ CodexTurnItemsViewSchema2 as CodexTurnItemsViewSchema,
3947
+ CodexTurnStatusSchema2 as CodexTurnStatusSchema,
3948
+ CodexTurnsPageSchema2 as CodexTurnsPageSchema,
3949
+ CodexUnixSocketError2 as CodexUnixSocketError,
3787
3950
  codexFakeScenarios,
3951
+ codexPlanLimits,
3788
3952
  codexPlanWindows,
3789
- createCodexDriver
3953
+ createCodexDriver,
3954
+ findCodexTurnByClientId,
3955
+ iterateCodexPages,
3956
+ parseCodexNotification
3790
3957
  };