stitchkit 0.129.0 → 0.130.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 (156) hide show
  1. package/CHANGELOG.md +26 -0
  2. package/dist/agent-executor/acp/v1-connect.d.ts +87 -19
  3. package/dist/agent-executor/acp/v1-connect.d.ts.map +1 -1
  4. package/dist/agent-executor/acp/v1-driver.d.ts +4 -2
  5. package/dist/agent-executor/acp/v1-driver.d.ts.map +1 -1
  6. package/dist/agent-executor/acp/v1-handlers.d.ts +56 -0
  7. package/dist/agent-executor/acp/v1-handlers.d.ts.map +1 -0
  8. package/dist/agent-executor/acp/v1-map.d.ts +13 -2
  9. package/dist/agent-executor/acp/v1-map.d.ts.map +1 -1
  10. package/dist/agent-executor/acp/v1-permission.d.ts +44 -0
  11. package/dist/agent-executor/acp/v1-permission.d.ts.map +1 -0
  12. package/dist/agent-executor/acp/v1-protocol.d.ts +63 -10
  13. package/dist/agent-executor/acp/v1-protocol.d.ts.map +1 -1
  14. package/dist/agent-executor/acp/v1-session.d.ts +34 -7
  15. package/dist/agent-executor/acp/v1-session.d.ts.map +1 -1
  16. package/dist/agent-executor/acp/v1-turn.d.ts +51 -13
  17. package/dist/agent-executor/acp/v1-turn.d.ts.map +1 -1
  18. package/dist/agent-executor/claude/classify.d.ts +10 -0
  19. package/dist/agent-executor/claude/classify.d.ts.map +1 -1
  20. package/dist/agent-executor/claude/cli-driver.d.ts +4 -1
  21. package/dist/agent-executor/claude/cli-driver.d.ts.map +1 -1
  22. package/dist/agent-executor/claude/events.d.ts +146 -0
  23. package/dist/agent-executor/claude/events.d.ts.map +1 -0
  24. package/dist/agent-executor/claude/limits.d.ts +7 -1
  25. package/dist/agent-executor/claude/limits.d.ts.map +1 -1
  26. package/dist/agent-executor/claude/protocol.d.ts +49 -9
  27. package/dist/agent-executor/claude/protocol.d.ts.map +1 -1
  28. package/dist/agent-executor/claude/session.d.ts +2 -0
  29. package/dist/agent-executor/claude/session.d.ts.map +1 -1
  30. package/dist/agent-executor/claude-sdk/controls.d.ts +10 -1
  31. package/dist/agent-executor/claude-sdk/controls.d.ts.map +1 -1
  32. package/dist/agent-executor/claude-sdk/driver.d.ts +97 -3
  33. package/dist/agent-executor/claude-sdk/driver.d.ts.map +1 -1
  34. package/dist/agent-executor/claude-sdk/probe.d.ts +29 -0
  35. package/dist/agent-executor/claude-sdk/probe.d.ts.map +1 -0
  36. package/dist/agent-executor/claude-sdk/query-loop.d.ts +53 -5
  37. package/dist/agent-executor/claude-sdk/query-loop.d.ts.map +1 -1
  38. package/dist/agent-executor/claude-sdk/query-options.d.ts +2 -0
  39. package/dist/agent-executor/claude-sdk/query-options.d.ts.map +1 -1
  40. package/dist/agent-executor/claude-sdk/session.d.ts +2 -3
  41. package/dist/agent-executor/claude-sdk/session.d.ts.map +1 -1
  42. package/dist/agent-executor/claude-sdk/turn-usage.d.ts +81 -0
  43. package/dist/agent-executor/claude-sdk/turn-usage.d.ts.map +1 -0
  44. package/dist/agent-executor/codex/classify.d.ts +4 -0
  45. package/dist/agent-executor/codex/classify.d.ts.map +1 -1
  46. package/dist/agent-executor/codex/connect.d.ts +2 -1
  47. package/dist/agent-executor/codex/connect.d.ts.map +1 -1
  48. package/dist/agent-executor/codex/control-client.d.ts +168 -0
  49. package/dist/agent-executor/codex/control-client.d.ts.map +1 -0
  50. package/dist/agent-executor/codex/driver.d.ts +22 -2
  51. package/dist/agent-executor/codex/driver.d.ts.map +1 -1
  52. package/dist/agent-executor/codex/handlers.d.ts +47 -0
  53. package/dist/agent-executor/codex/handlers.d.ts.map +1 -0
  54. package/dist/agent-executor/codex/limits.d.ts.map +1 -1
  55. package/dist/agent-executor/codex/protocol.d.ts +124 -0
  56. package/dist/agent-executor/codex/protocol.d.ts.map +1 -1
  57. package/dist/agent-executor/codex/request-answers.d.ts +101 -0
  58. package/dist/agent-executor/codex/request-answers.d.ts.map +1 -0
  59. package/dist/agent-executor/codex/session-controls.d.ts +91 -51
  60. package/dist/agent-executor/codex/session-controls.d.ts.map +1 -1
  61. package/dist/agent-executor/codex/session.d.ts +34 -12
  62. package/dist/agent-executor/codex/session.d.ts.map +1 -1
  63. package/dist/agent-executor/codex/shared-server.d.ts +29 -0
  64. package/dist/agent-executor/codex/shared-server.d.ts.map +1 -0
  65. package/dist/agent-executor/codex/shared-thread.d.ts +46 -0
  66. package/dist/agent-executor/codex/shared-thread.d.ts.map +1 -0
  67. package/dist/agent-executor/codex/thread-controls.d.ts +128 -0
  68. package/dist/agent-executor/codex/thread-controls.d.ts.map +1 -0
  69. package/dist/agent-executor/codex/turn-input.d.ts +30 -0
  70. package/dist/agent-executor/codex/turn-input.d.ts.map +1 -0
  71. package/dist/agent-executor/contract.d.ts +77 -0
  72. package/dist/agent-executor/contract.d.ts.map +1 -1
  73. package/dist/agent-executor/engine.d.ts +6 -2
  74. package/dist/agent-executor/engine.d.ts.map +1 -1
  75. package/dist/agent-executor/executor-contract.d.ts +54 -0
  76. package/dist/agent-executor/executor-contract.d.ts.map +1 -1
  77. package/dist/agent-executor/handoff-schemas.d.ts +407 -0
  78. package/dist/agent-executor/handoff-schemas.d.ts.map +1 -0
  79. package/dist/agent-executor/handoff.d.ts +12 -0
  80. package/dist/agent-executor/handoff.d.ts.map +1 -0
  81. package/dist/agent-executor/hello.d.ts +72 -0
  82. package/dist/agent-executor/hello.d.ts.map +1 -1
  83. package/dist/agent-executor/image-input.d.ts +22 -0
  84. package/dist/agent-executor/image-input.d.ts.map +1 -1
  85. package/dist/agent-executor/projection.d.ts +2 -2
  86. package/dist/agent-executor/projection.d.ts.map +1 -1
  87. package/dist/agent-executor/session-primitives.d.ts +10 -1
  88. package/dist/agent-executor/session-primitives.d.ts.map +1 -1
  89. package/dist/agent-executor/testing/conformance.d.ts.map +1 -1
  90. package/dist/agent-executor/testing/replay-driver.d.ts +41 -0
  91. package/dist/agent-executor/testing/replay-driver.d.ts.map +1 -0
  92. package/dist/agent-executor/testing/replay-gate.d.ts +11 -0
  93. package/dist/agent-executor/testing/replay-gate.d.ts.map +1 -0
  94. package/dist/agent-executor/testing/replay-runner.d.ts +27 -0
  95. package/dist/agent-executor/testing/replay-runner.d.ts.map +1 -0
  96. package/dist/agent-executor/testing/replay-scenarios.d.ts +21 -0
  97. package/dist/agent-executor/testing/replay-scenarios.d.ts.map +1 -0
  98. package/dist/agent-executor/testing/replay-transcript.d.ts +296 -0
  99. package/dist/agent-executor/testing/replay-transcript.d.ts.map +1 -0
  100. package/dist/agent-executor/vocabulary.d.ts +135 -0
  101. package/dist/agent-executor/vocabulary.d.ts.map +1 -1
  102. package/dist/agent-runtime/branch-provider.d.ts +2 -2
  103. package/dist/agent-runtime/deferred-tool-selection.d.ts.map +1 -1
  104. package/dist/entrypoints/agent-executor/acp.d.ts +4 -1
  105. package/dist/entrypoints/agent-executor/acp.d.ts.map +1 -1
  106. package/dist/entrypoints/agent-executor/acp.js +847 -214
  107. package/dist/entrypoints/agent-executor/claude-sdk.d.ts +5 -1
  108. package/dist/entrypoints/agent-executor/claude-sdk.d.ts.map +1 -1
  109. package/dist/entrypoints/agent-executor/claude-sdk.js +713 -205
  110. package/dist/entrypoints/agent-executor/claude.js +44 -19
  111. package/dist/entrypoints/agent-executor/codex.d.ts +9 -2
  112. package/dist/entrypoints/agent-executor/codex.d.ts.map +1 -1
  113. package/dist/entrypoints/agent-executor/codex.js +1775 -359
  114. package/dist/entrypoints/agent-executor/testing.d.ts +4 -0
  115. package/dist/entrypoints/agent-executor/testing.d.ts.map +1 -1
  116. package/dist/entrypoints/agent-executor/testing.js +1002 -2
  117. package/dist/entrypoints/agent-executor.d.ts +4 -2
  118. package/dist/entrypoints/agent-executor.d.ts.map +1 -1
  119. package/dist/entrypoints/agent-executor.js +411 -23
  120. package/dist/entrypoints/agent-runtime.js +4 -23
  121. package/dist/entrypoints/tools/mcp.d.ts +1 -0
  122. package/dist/entrypoints/tools/mcp.d.ts.map +1 -1
  123. package/dist/entrypoints/tools/mcp.js +1 -1
  124. package/dist/entrypoints/tools/toolkit.js +1 -1
  125. package/dist/{index-wv2amqm4.js → index-2s8sy57y.js} +36 -103
  126. package/dist/{index-afb6z77w.js → index-dbp6xemn.js} +75 -7
  127. package/dist/{index-bjmj2q1z.js → index-jrn3prgm.js} +1 -1
  128. package/dist/index-kne9g2c5.js +30 -0
  129. package/dist/index-p1qmpq0p.js +1300 -0
  130. package/dist/{index-7jqn3b3g.js → index-v759mzed.js} +152 -2
  131. package/dist/{index-cbhxhma2.js → index-x5ayy5bn.js} +1 -0
  132. package/dist/index-y0a4gt1s.js +142 -0
  133. package/dist/tools/internal/rank-tools.d.ts +10 -0
  134. package/dist/tools/internal/rank-tools.d.ts.map +1 -0
  135. package/dist/tools/mcp/handler.d.ts +7 -3
  136. package/dist/tools/mcp/handler.d.ts.map +1 -1
  137. package/dist/tools/mcp/lazy-discovery.d.ts +47 -0
  138. package/dist/tools/mcp/lazy-discovery.d.ts.map +1 -0
  139. package/dist/tools/mcp/mount.d.ts +7 -0
  140. package/dist/tools/mcp/mount.d.ts.map +1 -1
  141. package/dist/tools/mcp/register.d.ts +2 -2
  142. package/dist/tools/mcp/register.d.ts.map +1 -1
  143. package/llms/agent-executor-acp.txt +7 -8
  144. package/llms/agent-executor-claude-sdk.txt +4 -2
  145. package/llms/agent-executor-codex.txt +8 -4
  146. package/llms/agent-executor-testing.txt +5 -1
  147. package/llms/agent-executor.txt +7 -6
  148. package/llms/stitchkit.txt +74 -74
  149. package/llms/tools-mcp.txt +3 -2
  150. package/llms/tools.txt +24 -0
  151. package/llms/{upgrading-0.128.0-0.129.0.txt → upgrading-0.128.0-0.130.0.txt} +30 -3
  152. package/llms/upgrading.txt +1 -1
  153. package/llms-full.txt +159 -97
  154. package/llms.txt +8 -8
  155. package/package.json +1 -1
  156. package/dist/index-y71zn1gw.js +0 -586
@@ -4,7 +4,7 @@ import {
4
4
  PlanWindowSchema2,
5
5
  engineProfile,
6
6
  engineEnvironment2
7
- } from "../../index-afb6z77w.js";
7
+ } from "../../index-dbp6xemn.js";
8
8
  import"../../index-09f7w2qq.js";
9
9
  import"../../index-v59pxmf1.js";
10
10
  import"../../index-qa2jjb65.js";
@@ -19,15 +19,15 @@ import {
19
19
  stopConnection,
20
20
  withEphemeralConnection,
21
21
  safeJsonValue,
22
- validateImageOptions,
23
- inlineParts,
24
- imageTurnStarter,
22
+ invokeSafely,
23
+ emitStartupPhase,
24
+ clampUniqueWindowName,
25
25
  holdEngineRequest,
26
26
  answerEngineRequest,
27
27
  drainEngineRequests,
28
28
  endEngineTurn,
29
29
  loseEngineTurn
30
- } from "../../index-wv2amqm4.js";
30
+ } from "../../index-2s8sy57y.js";
31
31
  import"../../index-673drwkn.js";
32
32
  import"../../index-vmbxj75t.js";
33
33
  import {
@@ -35,6 +35,11 @@ import {
35
35
  JSON_RPC_METHOD_NOT_FOUND2,
36
36
  createJsonRpcPeer2
37
37
  } from "../../index-1q0n6zek.js";
38
+ import {
39
+ validateImageOptions,
40
+ inlineOrderedParts,
41
+ guardedTurnStarter
42
+ } from "../../index-y0a4gt1s.js";
38
43
  import"../../index-pzhqydxb.js";
39
44
  import {
40
45
  spawnEngineProcess2
@@ -43,7 +48,7 @@ import"../../index-3fym4j8n.js";
43
48
  import {
44
49
  planLimitsReadFailed2,
45
50
  mergeRateLimitEvent2
46
- } from "../../index-bjmj2q1z.js";
51
+ } from "../../index-jrn3prgm.js";
47
52
  import {
48
53
  assertUnixSocketPathLength,
49
54
  assertExpectedOwnerUid,
@@ -54,8 +59,12 @@ import {
54
59
  } from "../../index-jj9228tt.js";
55
60
  import {
56
61
  isPositiveSafeInteger,
57
- assertPositiveSafeInteger
62
+ assertPositiveSafeInteger,
63
+ assertNonNegativeSafeInteger
58
64
  } from "../../index-gr0kxymw.js";
65
+ import {
66
+ isRecord
67
+ } from "../../index-ps3djm8d.js";
59
68
  import {
60
69
  assertTimerMs,
61
70
  withSignalDeadline
@@ -85,6 +94,14 @@ var CodexTurnSchema = z.looseObject({
85
94
  error: z.looseObject({ message: z.string(), codexErrorInfo: z.json().nullable().optional() }).nullable().optional(),
86
95
  items: z.array(z.looseObject({ type: z.string(), clientId: z.string().nullable().optional() })).optional()
87
96
  });
97
+ var CodexTokenUsageBreakdownSchema = z.looseObject({
98
+ inputTokens: z.int().nonnegative().optional(),
99
+ outputTokens: z.int().nonnegative().optional(),
100
+ cachedInputTokens: z.int().nonnegative().optional(),
101
+ cacheWriteInputTokens: z.int().nonnegative().optional(),
102
+ reasoningOutputTokens: z.int().nonnegative().optional(),
103
+ totalTokens: z.int().nonnegative().optional()
104
+ });
88
105
  var CodexNotificationParams = {
89
106
  "item/agentMessage/delta": z.looseObject({ itemId: z.string(), delta: z.string() }),
90
107
  "item/reasoning/textDelta": z.looseObject({ itemId: z.string(), delta: z.string() }),
@@ -97,8 +114,13 @@ var CodexNotificationParams = {
97
114
  last: z.looseObject({
98
115
  inputTokens: z.int().nonnegative(),
99
116
  outputTokens: z.int().nonnegative(),
100
- cachedInputTokens: z.int().nonnegative().optional()
101
- })
117
+ cachedInputTokens: z.int().nonnegative().optional(),
118
+ cacheWriteInputTokens: z.int().nonnegative().optional(),
119
+ reasoningOutputTokens: z.int().nonnegative().optional(),
120
+ totalTokens: z.int().nonnegative().optional()
121
+ }),
122
+ total: CodexTokenUsageBreakdownSchema.optional(),
123
+ modelContextWindow: z.int().nonnegative().nullable().optional()
102
124
  })
103
125
  }),
104
126
  "serverRequest/resolved": z.looseObject({ requestId: z.union([z.string(), z.int()]) }),
@@ -110,13 +132,87 @@ var CodexNotificationParams = {
110
132
  var CodexApprovalParamsSchema = z.looseObject({
111
133
  itemId: z.string(),
112
134
  command: z.string().nullable().optional(),
113
- reason: 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()
114
154
  });
115
155
  var CodexUserInputParamsSchema = z.looseObject({
116
156
  itemId: z.string(),
117
- questions: z.array(z.looseObject({ id: z.string(), question: z.string(), header: z.string() }))
157
+ questions: z.array(CodexUserInputQuestionSchema)
118
158
  });
119
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
+ });
120
216
  var CodexThreadContextSchema = z.object({
121
217
  model: z.string().optional(),
122
218
  modelProvider: z.string().optional(),
@@ -160,7 +256,13 @@ var CodexTurnsPageSchema = z.looseObject({
160
256
  data: z.array(CodexListedTurnSchema),
161
257
  nextCursor: z.string().nullable().optional()
162
258
  });
259
+ var CodexThreadRevertResponseSchema = z.looseObject({
260
+ thread: z.looseObject({ id: z.string().min(1) }),
261
+ turnsBackwardsCursor: z.string().nullable().optional(),
262
+ itemsBackwardsCursor: z.string().nullable().optional()
263
+ });
163
264
  var CODEX_OPTED_OUT_NOTIFICATIONS = [
265
+ "app/list/updated",
164
266
  "item/commandExecution/outputDelta",
165
267
  "item/fileChange/outputDelta",
166
268
  "item/fileChange/patchUpdated",
@@ -173,27 +275,61 @@ var CODEX_QUIET_NOTIFICATIONS = new Set([
173
275
  ...CODEX_OPTED_OUT_NOTIFICATIONS,
174
276
  "thread/started",
175
277
  "thread/status/changed",
278
+ "thread/readState/changed",
279
+ "thread/archived",
280
+ "thread/deleted",
281
+ "thread/unarchived",
282
+ "thread/closed",
283
+ "thread/reverted",
284
+ "thread/name/updated",
285
+ "thread/section/changed",
286
+ "thread/attachment/updated",
287
+ "thread/goal/updated",
288
+ "thread/prediction/updated",
289
+ "thread/goal/cleared",
290
+ "thread/queue/changed",
291
+ "project/changed",
292
+ "thread/project/updated",
293
+ "thread/environment/connected",
294
+ "thread/environment/disconnected",
295
+ "thread/settings/updated",
296
+ "thread/compacted",
176
297
  "turn/started",
177
298
  "turn/plan/updated",
299
+ "turn/moderationMetadata",
178
300
  "item/plan/delta",
301
+ "item/commandExecution/terminalInteraction",
302
+ "item/mcpToolCall/progress",
303
+ "item/autoApprovalReview/started",
304
+ "item/autoApprovalReview/completed",
305
+ "autoApprovalReview/strictReviewRequired",
179
306
  "item/reasoning/summaryPartAdded",
180
307
  "hook/started",
181
308
  "hook/completed",
182
309
  "warning",
310
+ "guardianWarning",
311
+ "deprecationNotice",
312
+ "configWarning",
313
+ "windows/worldWritableWarning",
183
314
  "account/updated",
184
- "thread/name/updated",
185
- "thread/settings/updated",
186
- "thread/compacted",
315
+ "account/gatewayOAuth/changed",
187
316
  "model/rerouted",
317
+ "model/verification",
318
+ "model/safetyBuffering/updated",
319
+ "modelProvider/authRecoveryStarted",
320
+ "modelProvider/authRecoveryCompleted",
188
321
  "error"
189
322
  ]);
190
323
  var CODEX_APPROVAL_REQUESTS = new Set([
191
324
  "item/commandExecution/requestApproval",
192
325
  "item/fileChange/requestApproval"
193
326
  ]);
327
+ var CODEX_PERMISSIONS_APPROVAL_REQUEST = "item/permissions/requestApproval";
194
328
  var CODEX_INPUT_REQUEST = "item/tool/requestUserInput";
329
+ var CODEX_ELICITATION_REQUEST = "mcpServer/elicitation/request";
195
330
  var CODEX_APPROVAL_DECISION = {
196
331
  approve: "accept",
332
+ approveForSession: "acceptForSession",
197
333
  deny: "decline",
198
334
  interrupted: "cancel"
199
335
  };
@@ -906,17 +1042,28 @@ async function dialWithEngineRace(input) {
906
1042
  }
907
1043
  async function connectCodex(config, profile, cwd, signal, handlers = {}, onEnd = () => {
908
1044
  return;
909
- }) {
1045
+ }, onStartupPhase) {
910
1046
  const transport = config.transport ?? { kind: "stdio" };
911
1047
  const extraArgs = config.serverArgs ?? [];
912
1048
  if (transport.kind === "stdio") {
913
1049
  const env = engineEnvironment2(profile, config.ambient);
1050
+ let endedError;
1051
+ let ready = false;
914
1052
  const peer = createJsonRpcPeer2({
915
1053
  header: "omitted",
916
1054
  requestTimeoutMs: REQUEST_MS,
917
1055
  send: (line) => engine.send(line),
918
1056
  ...handlers
919
1057
  });
1058
+ const finishEnd = (error) => {
1059
+ if (endedError !== undefined)
1060
+ return;
1061
+ endedError = error;
1062
+ peer.close(error);
1063
+ if (ready)
1064
+ onEnd(error);
1065
+ };
1066
+ emitStartupPhase(onStartupPhase, "spawning");
920
1067
  const engine = spawnEngineProcess2({
921
1068
  executable: config.executable,
922
1069
  args: [...config.prefix, "app-server", ...extraArgs],
@@ -929,21 +1076,22 @@ async function connectCodex(config, profile, cwd, signal, handlers = {}, onEnd =
929
1076
  try {
930
1077
  for await (const line of engine.lines)
931
1078
  peer.receive(line);
932
- const ended = new Error(`Codex app-server exited: ${engine.stderrTail().slice(-2000)}`);
933
- peer.close(ended);
934
- onEnd(ended);
1079
+ finishEnd(new Error(`Codex app-server exited: ${engine.stderrTail().slice(-2000)}`));
935
1080
  } catch (error) {
936
1081
  const failed = error instanceof Error ? error : new Error(String(error));
937
- peer.close(failed);
938
- onEnd(failed);
1082
+ finishEnd(failed);
939
1083
  await engine.stop().catch(() => {
940
1084
  return;
941
1085
  });
942
1086
  }
943
1087
  })();
944
1088
  try {
1089
+ emitStartupPhase(onStartupPhase, "initializing");
945
1090
  await initializeCodexPeer(peer, config.version);
946
1091
  const providerPid = await engine.pidReady ?? engine.pid;
1092
+ if (endedError !== undefined)
1093
+ throw endedError;
1094
+ ready = true;
947
1095
  return { engine, peer, reading, providerPid };
948
1096
  } catch (error) {
949
1097
  await stopConnection({ engine, reading }, { error });
@@ -993,6 +1141,7 @@ async function connectCodex(config, profile, cwd, signal, handlers = {}, onEnd =
993
1141
  if (transport.kind === "unix-listen") {
994
1142
  assertCodexUnixListenTargetAvailable(transport.socketPath, "createCodexDriver");
995
1143
  const env = engineEnvironment2(profile, config.ambient);
1144
+ emitStartupPhase(onStartupPhase, "spawning");
996
1145
  spawnedEngine = spawnEngineProcess2({
997
1146
  executable: config.executable,
998
1147
  args: [
@@ -1057,10 +1206,13 @@ async function connectCodex(config, profile, cwd, signal, handlers = {}, onEnd =
1057
1206
  try {
1058
1207
  if (endedError !== undefined)
1059
1208
  throw endedError;
1209
+ emitStartupPhase(onStartupPhase, "initializing");
1060
1210
  await initializeCodexPeer(peer, config.version);
1061
1211
  if (endedError !== undefined)
1062
1212
  throw endedError;
1063
1213
  const providerPid = spawnedEngine !== undefined ? await spawnedEngine.pidReady ?? spawnedEngine.pid : undefined;
1214
+ if (endedError !== undefined)
1215
+ throw endedError;
1064
1216
  ready = true;
1065
1217
  return { engine: compositeEngine, peer, reading, providerPid };
1066
1218
  } catch (error) {
@@ -1070,7 +1222,6 @@ async function connectCodex(config, profile, cwd, signal, handlers = {}, onEnd =
1070
1222
  }
1071
1223
 
1072
1224
  // src/agent-executor/codex/limits.ts
1073
- import { createHash as createHash2 } from "node:crypto";
1074
1225
  import { z as z2 } from "zod";
1075
1226
  var MAX_WINDOW_NAME_CHARS = 256;
1076
1227
  var MAX_PLAN_WINDOWS = 32;
@@ -1088,27 +1239,6 @@ var SnapshotSchema = z2.looseObject({
1088
1239
  function positiveSafeInt(value) {
1089
1240
  return isPositiveSafeInteger(value) ? value : undefined;
1090
1241
  }
1091
- function clampWindowName(prefix, suffix, seenNames, disambiguatorSeed) {
1092
- const maxPrefix = Math.max(1, MAX_WINDOW_NAME_CHARS - suffix.length);
1093
- let candidate = prefix.length > maxPrefix ? `${prefix.slice(0, maxPrefix)}${suffix}`.slice(0, MAX_WINDOW_NAME_CHARS) : `${prefix}${suffix}`;
1094
- if (!seenNames.has(candidate)) {
1095
- seenNames.add(candidate);
1096
- return candidate;
1097
- }
1098
- const digest = createHash2("sha256").update(disambiguatorSeed).digest("hex").slice(0, 8);
1099
- const tag = `#${digest}${suffix}`;
1100
- const room = Math.max(1, MAX_WINDOW_NAME_CHARS - tag.length);
1101
- candidate = `${prefix.slice(0, room)}${tag}`.slice(0, MAX_WINDOW_NAME_CHARS);
1102
- let n = 2;
1103
- while (seenNames.has(candidate)) {
1104
- const indexedTag = `#${digest}_${n}${suffix}`;
1105
- const indexedRoom = Math.max(1, MAX_WINDOW_NAME_CHARS - indexedTag.length);
1106
- candidate = `${prefix.slice(0, indexedRoom)}${indexedTag}`.slice(0, MAX_WINDOW_NAME_CHARS);
1107
- n += 1;
1108
- }
1109
- seenNames.add(candidate);
1110
- return candidate;
1111
- }
1112
1242
  function clampLabel(value) {
1113
1243
  const trimmed = nonEmptyString(value)?.trim();
1114
1244
  if (trimmed === undefined)
@@ -1130,7 +1260,7 @@ function appendBucketWindows(out, seenNames, bucketId, seedKey, snapshot) {
1130
1260
  if (window === undefined || out.length >= MAX_PLAN_WINDOWS)
1131
1261
  continue;
1132
1262
  const suffix = mins === undefined ? `:${slot}` : duplicateDuration ? `:${mins}m:${slot}` : `:${mins}m`;
1133
- const name = clampWindowName(bucketId, suffix, seenNames, `${seedKey}:${bucketId}:${slot}`);
1263
+ const name = clampUniqueWindowName(bucketId, suffix, seenNames, `${seedKey}:${bucketId}:${slot}`, MAX_WINDOW_NAME_CHARS);
1134
1264
  const resetsAt = window.resetsAt !== undefined && window.resetsAt !== null && window.resetsAt > 0 ? epochSecondsToIso(window.resetsAt) : undefined;
1135
1265
  out.push(PlanWindowSchema2.parse({
1136
1266
  name,
@@ -1182,31 +1312,450 @@ function codexPlanWindows(reported) {
1182
1312
  return windows;
1183
1313
  }
1184
1314
 
1315
+ // src/agent-executor/codex/thread-controls.ts
1316
+ var MAX_UINT32 = 4294967295;
1317
+ var MAX_THREAD_LIST_IDS = 100;
1318
+ function assertNonEmptyThreadId(threadId, caller) {
1319
+ if (typeof threadId !== "string" || threadId.trim().length === 0) {
1320
+ throw new TypeError(`[stitchkit] ${caller}: threadId must be a non-empty string`);
1321
+ }
1322
+ return threadId;
1323
+ }
1324
+ function assertRequiredNonEmptyString(value, field, caller) {
1325
+ if (typeof value !== "string" || value.trim().length === 0) {
1326
+ throw new TypeError(`[stitchkit] ${caller}: ${field} must be a non-empty string`);
1327
+ }
1328
+ return value;
1329
+ }
1330
+ function assertOptionalNonEmptyString(value, field, caller) {
1331
+ if (value === undefined)
1332
+ return;
1333
+ if (typeof value !== "string" || value.trim().length === 0) {
1334
+ throw new TypeError(`[stitchkit] ${caller}: ${field} must be a non-empty string`);
1335
+ }
1336
+ }
1337
+ function assertOptionalLimit(limit, caller) {
1338
+ if (limit === undefined || limit === null)
1339
+ return;
1340
+ assertNonNegativeSafeInteger(`[stitchkit] ${caller}: limit`, limit, TypeError);
1341
+ if (limit > MAX_UINT32) {
1342
+ throw new TypeError(`[stitchkit] ${caller}: limit must not exceed ${MAX_UINT32}`);
1343
+ }
1344
+ }
1345
+ function assertBoundedThreadIdFilter(ids, field, caller) {
1346
+ if (ids === undefined || ids === null)
1347
+ return ids;
1348
+ if (!Array.isArray(ids)) {
1349
+ throw new TypeError(`[stitchkit] ${caller}: ${field} must be an array of strings`);
1350
+ }
1351
+ if (ids.length > MAX_THREAD_LIST_IDS) {
1352
+ throw new TypeError(`[stitchkit] ${caller}: ${field} must contain at most ${MAX_THREAD_LIST_IDS} entries`);
1353
+ }
1354
+ for (const id of ids) {
1355
+ if (typeof id !== "string" || id.trim().length === 0) {
1356
+ throw new TypeError(`[stitchkit] ${caller}: every ${field} entry must be a non-empty string`);
1357
+ }
1358
+ }
1359
+ return [...ids];
1360
+ }
1361
+ function validateGitInfoUpdate(gitInfo, caller) {
1362
+ if (gitInfo === undefined)
1363
+ return;
1364
+ if (gitInfo === null)
1365
+ return null;
1366
+ if (typeof gitInfo !== "object" || Array.isArray(gitInfo)) {
1367
+ throw new TypeError(`[stitchkit] ${caller}: gitInfo must be a plain object or null`);
1368
+ }
1369
+ const normalized = {};
1370
+ for (const field of ["branch", "originUrl", "sha"]) {
1371
+ const value = gitInfo[field];
1372
+ if (value === undefined)
1373
+ continue;
1374
+ if (value === null) {
1375
+ normalized[field] = null;
1376
+ continue;
1377
+ }
1378
+ if (typeof value !== "string" || value.trim().length === 0) {
1379
+ throw new TypeError(`[stitchkit] ${caller}: gitInfo.${field} must be a non-empty string or null`);
1380
+ }
1381
+ normalized[field] = value;
1382
+ }
1383
+ return normalized;
1384
+ }
1385
+ function normalizeListThreadsCwd(cwd) {
1386
+ if (cwd === undefined || cwd === null || typeof cwd === "string")
1387
+ return cwd;
1388
+ return [...cwd];
1389
+ }
1390
+ function buildListThreadsPayload(params) {
1391
+ const caller = "CodexControlClient.listThreads";
1392
+ assertOptionalLimit(params?.limit, caller);
1393
+ const includedThreadIds = assertBoundedThreadIdFilter(params?.includedThreadIds, "includedThreadIds", caller);
1394
+ const excludedThreadIds = assertBoundedThreadIdFilter(params?.excludedThreadIds, "excludedThreadIds", caller);
1395
+ const cwd = normalizeListThreadsCwd(params?.cwd);
1396
+ return {
1397
+ ...params?.cursor !== undefined && { cursor: params.cursor },
1398
+ ...params?.limit !== undefined && { limit: params.limit },
1399
+ ...params?.sortKey !== undefined && { sortKey: params.sortKey },
1400
+ ...params?.sortDirection !== undefined && { sortDirection: params.sortDirection },
1401
+ ...params?.modelProviders !== undefined && {
1402
+ modelProviders: params.modelProviders === null ? null : [...params.modelProviders]
1403
+ },
1404
+ ...params?.sourceKinds !== undefined && {
1405
+ sourceKinds: params.sourceKinds === null ? null : [...params.sourceKinds]
1406
+ },
1407
+ ...params?.archived !== undefined && { archived: params.archived },
1408
+ ...cwd !== undefined && { cwd },
1409
+ ...params?.searchTerm !== undefined && { searchTerm: params.searchTerm },
1410
+ ...params?.sectionId !== undefined && { sectionId: params.sectionId },
1411
+ ...includedThreadIds !== undefined && {
1412
+ includedThreadIds: includedThreadIds === null ? null : [...includedThreadIds]
1413
+ },
1414
+ ...excludedThreadIds !== undefined && {
1415
+ excludedThreadIds: excludedThreadIds === null ? null : [...excludedThreadIds]
1416
+ },
1417
+ ...params?.originators !== undefined && {
1418
+ originators: params.originators === null ? null : [...params.originators]
1419
+ },
1420
+ ...params?.currentAccountOnly !== undefined && {
1421
+ currentAccountOnly: params.currentAccountOnly
1422
+ },
1423
+ ...params?.useStateDbOnly !== undefined && { useStateDbOnly: params.useStateDbOnly }
1424
+ };
1425
+ }
1426
+ function createCodexThreadControlMethods(call) {
1427
+ return {
1428
+ async revertThread(params) {
1429
+ const threadId = assertNonEmptyThreadId(params.threadId, "CodexControlClient.revertThread");
1430
+ const beforeTurnId = assertRequiredNonEmptyString(params.beforeTurnId, "beforeTurnId", "CodexControlClient.revertThread");
1431
+ const rawReply = await call("thread/revert", { threadId, beforeTurnId });
1432
+ const parsed = CodexThreadRevertResponseSchema.parse(rawReply);
1433
+ return {
1434
+ thread: safeJsonValue(parsed.thread),
1435
+ turnsBackwardsCursor: parsed.turnsBackwardsCursor ?? null,
1436
+ itemsBackwardsCursor: parsed.itemsBackwardsCursor ?? null
1437
+ };
1438
+ },
1439
+ async injectItems(params) {
1440
+ const threadId = assertNonEmptyThreadId(params.threadId, "CodexControlClient.injectItems");
1441
+ if (!Array.isArray(params.items)) {
1442
+ throw new TypeError("[stitchkit] CodexControlClient.injectItems: items must be an array");
1443
+ }
1444
+ const items = params.items.map((item) => safeJsonValue(item));
1445
+ return call("thread/inject_items", { threadId, items });
1446
+ },
1447
+ async unsubscribeThread(params) {
1448
+ const threadId = assertNonEmptyThreadId(params.threadId, "CodexControlClient.unsubscribeThread");
1449
+ return call("thread/unsubscribe", { threadId });
1450
+ },
1451
+ async listThreads(params) {
1452
+ return call("thread/list", buildListThreadsPayload(params));
1453
+ },
1454
+ async listLoadedThreads(params) {
1455
+ assertOptionalLimit(params?.limit, "CodexControlClient.listLoadedThreads");
1456
+ return call("thread/loaded/list", {
1457
+ ...params?.cursor !== undefined && { cursor: params.cursor },
1458
+ ...params?.limit !== undefined && { limit: params.limit }
1459
+ });
1460
+ },
1461
+ async archiveThread(params) {
1462
+ const threadId = assertNonEmptyThreadId(params.threadId, "CodexControlClient.archiveThread");
1463
+ return call("thread/archive", { threadId });
1464
+ },
1465
+ async unarchiveThread(params) {
1466
+ const threadId = assertNonEmptyThreadId(params.threadId, "CodexControlClient.unarchiveThread");
1467
+ return call("thread/unarchive", { threadId });
1468
+ },
1469
+ async updateThreadMetadata(params) {
1470
+ const caller = "CodexControlClient.updateThreadMetadata";
1471
+ const threadId = assertNonEmptyThreadId(params.threadId, caller);
1472
+ const gitInfo = validateGitInfoUpdate(params.gitInfo, caller);
1473
+ return call("thread/metadata/update", {
1474
+ threadId,
1475
+ ...gitInfo !== undefined && { gitInfo }
1476
+ });
1477
+ },
1478
+ async setThreadName(params) {
1479
+ const caller = "CodexControlClient.setThreadName";
1480
+ const threadId = assertNonEmptyThreadId(params.threadId, caller);
1481
+ const name = assertRequiredNonEmptyString(params.name, "name", caller);
1482
+ return call("thread/name/set", { threadId, name });
1483
+ }
1484
+ };
1485
+ }
1486
+
1487
+ // src/agent-executor/codex/control-client.ts
1488
+ function assertOptionalItemsCursor(cursor, caller) {
1489
+ if (cursor === undefined)
1490
+ return;
1491
+ if (typeof cursor === "string") {
1492
+ if (cursor.trim().length === 0) {
1493
+ throw new TypeError(`[stitchkit] ${caller}: cursor must be a non-empty string`);
1494
+ }
1495
+ return;
1496
+ }
1497
+ if (typeof cursor !== "object" || cursor === null || cursor.type !== "item" || typeof cursor.itemId !== "string" || cursor.itemId.trim().length === 0) {
1498
+ throw new TypeError(`[stitchkit] ${caller}: item cursor must have type "item" and a non-empty itemId`);
1499
+ }
1500
+ }
1501
+ function createCodexControlClient(input) {
1502
+ const call = async (method, params) => {
1503
+ input.ensureAlive();
1504
+ return input.peer.request(method, params);
1505
+ };
1506
+ return {
1507
+ readConfig(params) {
1508
+ return call("config/read", {
1509
+ ...params?.cwd !== undefined && { cwd: params.cwd },
1510
+ ...params?.includeLayers !== undefined && { includeLayers: params.includeLayers }
1511
+ });
1512
+ },
1513
+ async readThread(params) {
1514
+ const threadId = assertNonEmptyThreadId(params.threadId, "CodexControlClient.readThread");
1515
+ return call("thread/read", {
1516
+ threadId,
1517
+ ...params.includeTurns !== undefined && { includeTurns: params.includeTurns }
1518
+ });
1519
+ },
1520
+ listCollaborationModes() {
1521
+ return call("collaborationMode/list", {});
1522
+ },
1523
+ async listTurns(params) {
1524
+ const threadId = assertNonEmptyThreadId(params.threadId, "CodexControlClient.listTurns");
1525
+ assertOptionalLimit(params.limit, "CodexControlClient.listTurns");
1526
+ return call("thread/turns/list", {
1527
+ threadId,
1528
+ ...params.cursor !== undefined && { cursor: params.cursor },
1529
+ ...params.limit !== undefined && { limit: params.limit },
1530
+ ...params.itemsView !== undefined && { itemsView: params.itemsView },
1531
+ ...params.sortDirection !== undefined && { sortDirection: params.sortDirection }
1532
+ });
1533
+ },
1534
+ async listItems(params) {
1535
+ const threadId = assertNonEmptyThreadId(params.threadId, "CodexControlClient.listItems");
1536
+ assertOptionalLimit(params.limit, "CodexControlClient.listItems");
1537
+ assertOptionalNonEmptyString(params.turnId, "turnId", "CodexControlClient.listItems");
1538
+ assertOptionalItemsCursor(params.cursor, "CodexControlClient.listItems");
1539
+ return call("thread/items/list", {
1540
+ threadId,
1541
+ ...params.turnId !== undefined && { turnId: params.turnId },
1542
+ ...params.cursor !== undefined && { cursor: safeJsonValue(params.cursor) },
1543
+ ...params.limit !== undefined && { limit: params.limit },
1544
+ ...params.sortDirection !== undefined && { sortDirection: params.sortDirection },
1545
+ ...params.deferOutput !== undefined && {
1546
+ deferOutput: safeJsonValue(params.deferOutput)
1547
+ }
1548
+ });
1549
+ },
1550
+ listMcpServerStatus(params) {
1551
+ return call("mcpServerStatus/list", {
1552
+ ...params?.cursor !== undefined && { cursor: params.cursor },
1553
+ ...params?.limit !== undefined && { limit: params.limit },
1554
+ ...params?.threadId !== undefined && { threadId: params.threadId },
1555
+ ...params?.serverName !== undefined && { serverName: params.serverName },
1556
+ ...params?.detail !== undefined && { detail: params.detail }
1557
+ });
1558
+ },
1559
+ listSkills(params) {
1560
+ return call("skills/list", {
1561
+ ...params?.cwds !== undefined && { cwds: [...params.cwds] },
1562
+ ...params?.forceReload !== undefined && { forceReload: params.forceReload }
1563
+ });
1564
+ },
1565
+ listModels(params) {
1566
+ return call("model/list", {
1567
+ ...params?.cursor !== undefined && { cursor: params.cursor },
1568
+ ...params?.limit !== undefined && { limit: params.limit },
1569
+ ...params?.includeHidden !== undefined && { includeHidden: params.includeHidden },
1570
+ ...params?.modelProvider !== undefined && { modelProvider: params.modelProvider }
1571
+ });
1572
+ },
1573
+ readAccount(params) {
1574
+ return call("account/read", {
1575
+ ...params?.refreshToken !== undefined && { refreshToken: params.refreshToken }
1576
+ });
1577
+ },
1578
+ readRateLimits() {
1579
+ return call("account/rateLimits/read");
1580
+ },
1581
+ ...createCodexThreadControlMethods(call)
1582
+ };
1583
+ }
1584
+ function bindCodexSessionThreadControls(controlClient, threadId) {
1585
+ return {
1586
+ readThread(params) {
1587
+ return controlClient.readThread({
1588
+ ...params,
1589
+ threadId: params?.threadId ?? threadId
1590
+ });
1591
+ },
1592
+ listTurns(params) {
1593
+ return controlClient.listTurns({
1594
+ ...params,
1595
+ threadId: params?.threadId ?? threadId
1596
+ });
1597
+ },
1598
+ listItems(params) {
1599
+ return controlClient.listItems({
1600
+ ...params,
1601
+ threadId: params?.threadId ?? threadId
1602
+ });
1603
+ },
1604
+ revertThread(params) {
1605
+ return controlClient.revertThread({
1606
+ ...params,
1607
+ threadId: params.threadId ?? threadId
1608
+ });
1609
+ },
1610
+ injectItems(params) {
1611
+ return controlClient.injectItems({
1612
+ ...params,
1613
+ threadId: params.threadId ?? threadId
1614
+ });
1615
+ },
1616
+ unsubscribeThread(params) {
1617
+ return controlClient.unsubscribeThread({
1618
+ threadId: params?.threadId ?? threadId
1619
+ });
1620
+ },
1621
+ archiveThread(params) {
1622
+ return controlClient.archiveThread({
1623
+ threadId: params?.threadId ?? threadId
1624
+ });
1625
+ },
1626
+ unarchiveThread(params) {
1627
+ return controlClient.unarchiveThread({
1628
+ threadId: params?.threadId ?? threadId
1629
+ });
1630
+ },
1631
+ updateThreadMetadata(params) {
1632
+ return controlClient.updateThreadMetadata({
1633
+ ...params,
1634
+ threadId: params?.threadId ?? threadId
1635
+ });
1636
+ },
1637
+ setThreadName(params) {
1638
+ return controlClient.setThreadName({
1639
+ ...params,
1640
+ threadId: params.threadId ?? threadId
1641
+ });
1642
+ }
1643
+ };
1644
+ }
1645
+
1185
1646
  // src/agent-executor/codex/classify.ts
1186
1647
  var raw = (type) => ({ source: "codex", type });
1187
- var TOOL_ITEMS = new Set([
1648
+ var CODEX_TOOL_ITEMS = new Set([
1188
1649
  "commandExecution",
1189
1650
  "fileChange",
1190
1651
  "mcpToolCall",
1191
1652
  "dynamicToolCall",
1192
- "webSearch"
1653
+ "collabAgentToolCall",
1654
+ "webSearch",
1655
+ "imageView",
1656
+ "sleep",
1657
+ "imageGeneration",
1658
+ "functionCallOutput"
1659
+ ]);
1660
+ var STATUSLESS_TOOL_ITEMS = new Set([
1661
+ "webSearch",
1662
+ "imageView",
1663
+ "sleep",
1664
+ "functionCallOutput"
1193
1665
  ]);
1194
- var CONTENT_ITEMS = new Set([
1666
+ var CODEX_CONTENT_ITEMS = new Set([
1195
1667
  "agentMessage",
1196
1668
  "reasoning",
1197
1669
  "userMessage",
1198
1670
  "plan",
1199
1671
  "contextCompaction",
1200
- "hookPrompt"
1672
+ "hookPrompt",
1673
+ "subAgentActivity",
1674
+ "enteredReviewMode",
1675
+ "exitedReviewMode"
1201
1676
  ]);
1677
+ var KNOWN_CODEX_ERROR_CODES = new Set([
1678
+ "contextWindowExceeded",
1679
+ "sessionBudgetExceeded",
1680
+ "usageLimitExceeded",
1681
+ "rateLimitExceeded",
1682
+ "flexUnavailable",
1683
+ "serverOverloaded",
1684
+ "modelNotFound",
1685
+ "policyCapacityUnavailable",
1686
+ "cyberPolicy",
1687
+ "bioPolicy",
1688
+ "misalignmentPolicyViolation",
1689
+ "tooManyDenials",
1690
+ "internalServerError",
1691
+ "unauthorized",
1692
+ "badRequest",
1693
+ "threadRollbackFailed",
1694
+ "sandboxError",
1695
+ "other",
1696
+ "inferenceHookDenied"
1697
+ ]);
1698
+ var KNOWN_CODEX_ERROR_OBJECT_KEYS = new Set([
1699
+ "httpConnectionFailed",
1700
+ "responseStreamConnectionFailed",
1701
+ "responseStreamDisconnected",
1702
+ "responseTooManyFailedAttempts",
1703
+ "activeTurnNotSteerable"
1704
+ ]);
1705
+ var MAX_ERROR_INFO_SUMMARY_CHARS = 512;
1202
1706
  function toolName(item) {
1203
- const tool = Reflect.get(item, "tool");
1204
- return item.type === "mcpToolCall" || item.type === "dynamicToolCall" ? nonEmptyString(tool) ?? item.type : item.type;
1707
+ if (item.type === "mcpToolCall" || item.type === "dynamicToolCall" || item.type === "collabAgentToolCall") {
1708
+ return nonEmptyString(Reflect.get(item, "tool")) ?? item.type;
1709
+ }
1710
+ if (item.type === "functionCallOutput") {
1711
+ return nonEmptyString(Reflect.get(item, "name")) ?? item.type;
1712
+ }
1713
+ return item.type;
1205
1714
  }
1206
1715
  function toolInput(item) {
1207
1716
  const { id: _id, type: _type, status: _status, aggregatedOutput: _output, ...rest } = item;
1208
1717
  return safeJsonValue(rest);
1209
1718
  }
1719
+ function isKnownCodexErrorInfo(info) {
1720
+ if (typeof info === "string")
1721
+ return KNOWN_CODEX_ERROR_CODES.has(info);
1722
+ if (typeof info === "object" && info !== null && !Array.isArray(info)) {
1723
+ const keys = Object.keys(info);
1724
+ return keys.length === 1 && keys[0] !== undefined && KNOWN_CODEX_ERROR_OBJECT_KEYS.has(keys[0]);
1725
+ }
1726
+ return false;
1727
+ }
1728
+ function formatCodexErrorInfo(info) {
1729
+ if (info === null || info === undefined)
1730
+ return;
1731
+ if (typeof info === "string") {
1732
+ const trimmed = info.trim();
1733
+ return trimmed.length > 0 ? trimmed.slice(0, MAX_ERROR_INFO_SUMMARY_CHARS) : undefined;
1734
+ }
1735
+ try {
1736
+ const serialized = JSON.stringify(safeJsonValue(info));
1737
+ if (serialized === undefined || serialized.length === 0)
1738
+ return;
1739
+ return serialized.length > MAX_ERROR_INFO_SUMMARY_CHARS ? `${serialized.slice(0, MAX_ERROR_INFO_SUMMARY_CHARS - 1)}…` : serialized;
1740
+ } catch {
1741
+ return String(info).slice(0, MAX_ERROR_INFO_SUMMARY_CHARS);
1742
+ }
1743
+ }
1744
+ function codexFailureMessage(turn) {
1745
+ const rawMessage = turn.error?.message.trim() ?? "";
1746
+ const info = turn.error?.codexErrorInfo;
1747
+ const infoSummary = formatCodexErrorInfo(info);
1748
+ if (rawMessage.length > 0) {
1749
+ if (infoSummary !== undefined && !isKnownCodexErrorInfo(info) && !rawMessage.includes(infoSummary)) {
1750
+ return `${rawMessage} (${infoSummary})`;
1751
+ }
1752
+ return rawMessage;
1753
+ }
1754
+ if (infoSummary !== undefined) {
1755
+ return `Codex ended the turn ${turn.status} (${infoSummary})`;
1756
+ }
1757
+ return `Codex ended the turn ${turn.status}`;
1758
+ }
1210
1759
  function httpStatusOf(value, depth = 0) {
1211
1760
  if (depth > 3 || typeof value !== "object" || value === null)
1212
1761
  return;
@@ -1232,6 +1781,53 @@ function failureKind(info) {
1232
1781
  return "rateLimited";
1233
1782
  return "restartRecommended";
1234
1783
  }
1784
+ function normalizeCodexTokenTotals(rawTotals) {
1785
+ if (rawTotals === undefined)
1786
+ return;
1787
+ const normalized = {
1788
+ ...rawTotals.inputTokens !== undefined && { inputTokens: rawTotals.inputTokens },
1789
+ ...rawTotals.outputTokens !== undefined && { outputTokens: rawTotals.outputTokens },
1790
+ ...rawTotals.cachedInputTokens !== undefined && {
1791
+ cachedInputTokens: rawTotals.cachedInputTokens
1792
+ },
1793
+ ...rawTotals.cacheWriteInputTokens !== undefined && {
1794
+ cacheCreationInputTokens: rawTotals.cacheWriteInputTokens
1795
+ },
1796
+ ...rawTotals.reasoningOutputTokens !== undefined && {
1797
+ thinkingTokens: rawTotals.reasoningOutputTokens
1798
+ },
1799
+ ...rawTotals.totalTokens !== undefined && { totalTokens: rawTotals.totalTokens }
1800
+ };
1801
+ return Object.keys(normalized).length > 0 ? normalized : undefined;
1802
+ }
1803
+ function classifyCodexTokenUsage(params, base) {
1804
+ const { last, total } = CodexNotificationParams["thread/tokenUsage/updated"].parse(params).tokenUsage;
1805
+ const normalizedTotal = normalizeCodexTokenTotals(total);
1806
+ return {
1807
+ kind: "deltas",
1808
+ deltas: [
1809
+ {
1810
+ type: "usage",
1811
+ ...base,
1812
+ itemId: "usage",
1813
+ raw: raw("thread/tokenUsage/updated"),
1814
+ inputTokens: last.inputTokens,
1815
+ outputTokens: last.outputTokens,
1816
+ ...last.cachedInputTokens !== undefined && {
1817
+ cachedInputTokens: last.cachedInputTokens
1818
+ },
1819
+ ...last.cacheWriteInputTokens !== undefined && {
1820
+ cacheCreationInputTokens: last.cacheWriteInputTokens
1821
+ },
1822
+ ...last.reasoningOutputTokens !== undefined && {
1823
+ thinkingTokens: last.reasoningOutputTokens
1824
+ },
1825
+ ...last.totalTokens !== undefined && { totalTokens: last.totalTokens },
1826
+ ...normalizedTotal !== undefined && { total: normalizedTotal }
1827
+ }
1828
+ ]
1829
+ };
1830
+ }
1235
1831
  function classifyCodexNotification(method, params, state) {
1236
1832
  const base = { turnId: state.turnId };
1237
1833
  switch (method) {
@@ -1255,9 +1851,9 @@ function classifyCodexNotification(method, params, state) {
1255
1851
  case "item/started":
1256
1852
  case "item/completed": {
1257
1853
  const { item } = CodexNotificationParams[method].parse(params);
1258
- if (CONTENT_ITEMS.has(item.type))
1854
+ if (CODEX_CONTENT_ITEMS.has(item.type))
1259
1855
  return { kind: "ignore", reason: `${method} ${item.type}` };
1260
- if (!TOOL_ITEMS.has(item.type)) {
1856
+ if (!CODEX_TOOL_ITEMS.has(item.type)) {
1261
1857
  return {
1262
1858
  kind: "unhandled",
1263
1859
  delta: {
@@ -1287,8 +1883,10 @@ function classifyCodexNotification(method, params, state) {
1287
1883
  };
1288
1884
  }
1289
1885
  const status = Reflect.get(item, "status");
1290
- const output = Reflect.get(item, "aggregatedOutput") ?? Reflect.get(item, "result") ?? Reflect.get(item, "results") ?? Reflect.get(item, "contentItems") ?? Reflect.get(item, "changes") ?? Reflect.get(item, "error");
1291
- const outcome = status === "completed" || item.type === "webSearch" && status === undefined ? "success" : status === "declined" ? "interrupted" : "error";
1886
+ const failure = Reflect.get(item, "failure");
1887
+ 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");
1888
+ const hasFailure = failure !== undefined && failure !== null;
1889
+ const outcome = !hasFailure && (status === "completed" || STATUSLESS_TOOL_ITEMS.has(item.type) && status === undefined) ? "success" : status === "declined" || status === "interrupted" ? "interrupted" : "error";
1292
1890
  return {
1293
1891
  kind: "deltas",
1294
1892
  deltas: [
@@ -1318,31 +1916,14 @@ function classifyCodexNotification(method, params, state) {
1318
1916
  itemId: "failure",
1319
1917
  raw: raw(method),
1320
1918
  kind: failureKind(turn.error?.codexErrorInfo),
1321
- message: turn.error?.message || `Codex ended the turn ${turn.status}`
1919
+ message: codexFailureMessage(turn)
1322
1920
  });
1323
1921
  }
1324
1922
  deltas.push({ type: "turn-end", ...base, itemId: "end", raw: raw(method), outcome });
1325
1923
  return { kind: "end", deltas, outcome };
1326
1924
  }
1327
- case "thread/tokenUsage/updated": {
1328
- const { last } = CodexNotificationParams[method].parse(params).tokenUsage;
1329
- return {
1330
- kind: "deltas",
1331
- deltas: [
1332
- {
1333
- type: "usage",
1334
- ...base,
1335
- itemId: "usage",
1336
- raw: raw(method),
1337
- inputTokens: last.inputTokens,
1338
- outputTokens: last.outputTokens,
1339
- ...last.cachedInputTokens !== undefined && {
1340
- cachedInputTokens: last.cachedInputTokens
1341
- }
1342
- }
1343
- ]
1344
- };
1345
- }
1925
+ case "thread/tokenUsage/updated":
1926
+ return classifyCodexTokenUsage(params, base);
1346
1927
  case "serverRequest/resolved":
1347
1928
  return {
1348
1929
  kind: "resolved",
@@ -1375,46 +1956,520 @@ function classifyCodexNotification(method, params, state) {
1375
1956
  }
1376
1957
  }
1377
1958
 
1378
- // src/agent-executor/codex/session-controls.ts
1379
- function codexTurnInput(parts) {
1380
- if (parts.every((part) => part.type === "text")) {
1381
- return [
1382
- { type: "text", text: parts.map((part) => part.text).join(`
1383
- `), text_elements: [] }
1384
- ];
1385
- }
1386
- const out = [];
1387
- for (const part of parts) {
1388
- if (part.type === "text") {
1389
- out.push({ type: "text", text: part.text, text_elements: [] });
1390
- } else {
1391
- out.push({ type: "image", url: `data:${part.mediaType};base64,${part.base64}` });
1392
- }
1959
+ // src/agent-executor/codex/request-answers.ts
1960
+ function isKnownCodexRequestMethod(method) {
1961
+ return CODEX_APPROVAL_REQUESTS.has(method) || method === CODEX_PERMISSIONS_APPROVAL_REQUEST || method === CODEX_INPUT_REQUEST || method === CODEX_ELICITATION_REQUEST;
1962
+ }
1963
+ function externalCodexTurnIdOf(params) {
1964
+ if (typeof params !== "object" || params === null)
1965
+ return "external";
1966
+ const direct = nonEmptyString(Reflect.get(params, "turnId"));
1967
+ if (direct !== undefined)
1968
+ return direct;
1969
+ const turn = Reflect.get(params, "turn");
1970
+ if (typeof turn === "object" && turn !== null) {
1971
+ const nested = nonEmptyString(Reflect.get(turn, "id"));
1972
+ if (nested !== undefined)
1973
+ return nested;
1393
1974
  }
1394
- return out;
1975
+ return "external";
1395
1976
  }
1396
- function validateCodexPolicyOverrides(overrides, caller) {
1397
- if (overrides.runtimeWorkspaceRoots !== undefined) {
1398
- if (!Array.isArray(overrides.runtimeWorkspaceRoots)) {
1399
- throw new TypeError(`[stitchkit] ${caller}: runtimeWorkspaceRoots must be an array of strings`);
1977
+ function parseCodexApprovalRequest(method, params) {
1978
+ const asked = CodexApprovalParamsSchema.parse(params);
1979
+ const callId = nonEmptyString(asked.itemId);
1980
+ const metadata = {};
1981
+ if (typeof asked.command === "string")
1982
+ metadata.command = asked.command;
1983
+ if (typeof asked.cwd === "string")
1984
+ metadata.cwd = asked.cwd;
1985
+ if (typeof asked.reason === "string")
1986
+ metadata.reason = asked.reason;
1987
+ if (typeof asked.grantRoot === "string")
1988
+ metadata.grantRoot = asked.grantRoot;
1989
+ if (typeof asked.kind === "string")
1990
+ metadata.kind = asked.kind;
1991
+ if (typeof asked.approvalId === "string")
1992
+ metadata.approvalId = asked.approvalId;
1993
+ if (asked.commandActions != null)
1994
+ metadata.commandActions = asked.commandActions;
1995
+ if (asked.availableDecisions != null)
1996
+ metadata.availableDecisions = asked.availableDecisions;
1997
+ const input = Object.keys(metadata).length > 0 ? safeJsonValue(metadata) : undefined;
1998
+ const detail = {
1999
+ method,
2000
+ ...typeof asked.kind === "string" && { kind: asked.kind },
2001
+ ...Array.isArray(asked.availableDecisions) && {
2002
+ availableDecisions: asked.availableDecisions
1400
2003
  }
1401
- for (const root of overrides.runtimeWorkspaceRoots) {
1402
- if (typeof root !== "string" || root.trim().length === 0) {
1403
- throw new TypeError(`[stitchkit] ${caller}: every runtimeWorkspaceRoots entry must be a non-empty string`);
1404
- }
2004
+ };
2005
+ return {
2006
+ detail,
2007
+ deltaFields: {
2008
+ ...callId !== undefined && { callId },
2009
+ ...typeof asked.command === "string" && { prompt: asked.command },
2010
+ ...input !== undefined && { input }
1405
2011
  }
1406
- }
1407
- if (overrides.config !== undefined) {
1408
- if (typeof overrides.config !== "object" || overrides.config === null || Array.isArray(overrides.config)) {
1409
- throw new TypeError(`[stitchkit] ${caller}: config must be a plain JSON object`);
2012
+ };
2013
+ }
2014
+ function parseCodexInputRequest(params) {
2015
+ const asked = CodexUserInputParamsSchema.parse(params);
2016
+ const callId = nonEmptyString(asked.itemId);
2017
+ const questions = asked.questions.map((question) => ({
2018
+ id: question.id,
2019
+ header: question.header,
2020
+ question: question.question,
2021
+ ...question.options !== undefined && {
2022
+ options: question.options === null ? null : question.options.map((option) => ({
2023
+ label: option.label,
2024
+ description: option.description
2025
+ }))
2026
+ },
2027
+ ...question.isOther !== undefined && { isOther: question.isOther },
2028
+ ...question.isSecret !== undefined && { isSecret: question.isSecret }
2029
+ }));
2030
+ const detail = { method: CODEX_INPUT_REQUEST };
2031
+ return {
2032
+ detail,
2033
+ deltaFields: {
2034
+ ...callId !== undefined && { callId },
2035
+ input: safeJsonValue(questions)
1410
2036
  }
1411
- safeJsonValue(overrides.config);
1412
- }
2037
+ };
1413
2038
  }
1414
- function buildCodexThreadPolicyParams(base, overrides) {
1415
- const mergedConfig = base.config !== undefined || overrides?.config !== undefined ? { ...base.config ?? {}, ...overrides?.config ?? {} } : undefined;
1416
- const merged = {
1417
- ...base,
2039
+ function parseCodexPermissionsRequest(params) {
2040
+ const asked = CodexPermissionsApprovalParamsSchema.parse(params);
2041
+ const callId = nonEmptyString(asked.itemId);
2042
+ const permissions = safeJsonValue(asked.permissions);
2043
+ const metadata = {
2044
+ threadId: asked.threadId,
2045
+ turnId: asked.turnId,
2046
+ cwd: asked.cwd,
2047
+ permissions,
2048
+ startedAtMs: asked.startedAtMs
2049
+ };
2050
+ if (typeof asked.reason === "string")
2051
+ metadata.reason = asked.reason;
2052
+ if (typeof asked.environmentId === "string")
2053
+ metadata.environmentId = asked.environmentId;
2054
+ const detail = {
2055
+ method: CODEX_PERMISSIONS_APPROVAL_REQUEST,
2056
+ permissions
2057
+ };
2058
+ return {
2059
+ detail,
2060
+ deltaFields: {
2061
+ ...callId !== undefined && { callId },
2062
+ ...typeof asked.reason === "string" && { prompt: asked.reason },
2063
+ input: safeJsonValue(metadata)
2064
+ }
2065
+ };
2066
+ }
2067
+ function parseCodexElicitationRequest(params) {
2068
+ const asked = CodexMcpElicitationParamsSchema.parse(params);
2069
+ const toolName = nonEmptyString(asked.serverName);
2070
+ const callId = asked.mode === "url" ? nonEmptyString(asked.elicitationId) : undefined;
2071
+ const metadata = {
2072
+ serverName: asked.serverName,
2073
+ threadId: asked.threadId,
2074
+ mode: asked.mode,
2075
+ message: asked.message
2076
+ };
2077
+ if (asked.turnId !== undefined)
2078
+ metadata.turnId = asked.turnId;
2079
+ if (asked.environmentId !== undefined)
2080
+ metadata.environmentId = asked.environmentId;
2081
+ if (asked._meta !== undefined)
2082
+ metadata._meta = asked._meta;
2083
+ if (asked.mode === "url") {
2084
+ metadata.elicitationId = asked.elicitationId;
2085
+ metadata.url = asked.url;
2086
+ } else {
2087
+ metadata.requestedSchema = asked.requestedSchema;
2088
+ }
2089
+ const detail = {
2090
+ method: CODEX_ELICITATION_REQUEST,
2091
+ elicitationMode: asked.mode
2092
+ };
2093
+ return {
2094
+ detail,
2095
+ deltaFields: {
2096
+ ...callId !== undefined && { callId },
2097
+ ...toolName !== undefined && { toolName },
2098
+ prompt: asked.message,
2099
+ input: safeJsonValue(metadata)
2100
+ }
2101
+ };
2102
+ }
2103
+ function parseCodexServerRequest(method, params) {
2104
+ if (CODEX_APPROVAL_REQUESTS.has(method)) {
2105
+ return { kind: "approval", ...parseCodexApprovalRequest(method, params) };
2106
+ }
2107
+ if (method === CODEX_PERMISSIONS_APPROVAL_REQUEST) {
2108
+ return { kind: "approval", ...parseCodexPermissionsRequest(params) };
2109
+ }
2110
+ if (method === CODEX_ELICITATION_REQUEST) {
2111
+ return { kind: "input", ...parseCodexElicitationRequest(params) };
2112
+ }
2113
+ return { kind: "input", ...parseCodexInputRequest(params) };
2114
+ }
2115
+ function codexStoppedAnswer(method) {
2116
+ if (CODEX_APPROVAL_REQUESTS.has(method)) {
2117
+ return { decision: CODEX_APPROVAL_DECISION.interrupted };
2118
+ }
2119
+ if (method === CODEX_PERMISSIONS_APPROVAL_REQUEST) {
2120
+ return { permissions: {} };
2121
+ }
2122
+ if (method === CODEX_ELICITATION_REQUEST) {
2123
+ return { action: "cancel" };
2124
+ }
2125
+ return { answers: {} };
2126
+ }
2127
+ var codexStopped = (waiting) => codexStoppedAnswer(waiting.detail.method);
2128
+ function buildCodexRequestAnswer(detail, rawReply) {
2129
+ const reply = InteractionReplySchema2.shape.reply.parse(rawReply);
2130
+ if (CODEX_APPROVAL_REQUESTS.has(detail.method)) {
2131
+ if (reply.kind === "input") {
2132
+ throw new TypeError("A Codex approval is approved or denied, not answered with input");
2133
+ }
2134
+ if (reply.kind === "approve" && reply.updatedInput !== undefined) {
2135
+ throw new TypeError("Codex approval requests do not support updatedInput");
2136
+ }
2137
+ 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;
2138
+ if (detail.kind === "humanCommand" && decision === CODEX_APPROVAL_DECISION.approveForSession) {
2139
+ throw new TypeError("Codex humanCommand approval does not allow acceptForSession");
2140
+ }
2141
+ if (detail.availableDecisions !== undefined) {
2142
+ const allowed = detail.availableDecisions.some((entry) => entry === decision);
2143
+ if (!allowed) {
2144
+ throw new TypeError(`Codex approval request does not offer decision ${JSON.stringify(decision)}`);
2145
+ }
2146
+ }
2147
+ return { decision };
2148
+ }
2149
+ if (detail.method === CODEX_PERMISSIONS_APPROVAL_REQUEST) {
2150
+ if (reply.kind === "input") {
2151
+ throw new TypeError("A Codex permissions approval is approved or denied, not answered with input");
2152
+ }
2153
+ if (reply.kind === "approve") {
2154
+ if (reply.updatedInput !== undefined) {
2155
+ throw new TypeError("Codex permissions approval requests do not support updatedInput");
2156
+ }
2157
+ return {
2158
+ permissions: detail.permissions ?? {},
2159
+ scope: reply.scope === "session" ? "session" : "turn"
2160
+ };
2161
+ }
2162
+ if (reply.interrupt === true) {
2163
+ throw new TypeError("Codex permissions approval requests do not support interrupt on deny");
2164
+ }
2165
+ return { permissions: {} };
2166
+ }
2167
+ if (detail.method === CODEX_ELICITATION_REQUEST) {
2168
+ if (reply.kind === "approve") {
2169
+ throw new TypeError("A Codex MCP elicitation request is answered with input or deny, not approve");
2170
+ }
2171
+ if (reply.kind === "deny") {
2172
+ return {
2173
+ action: detail.elicitationMode === "url" || reply.interrupt === true ? "cancel" : "decline"
2174
+ };
2175
+ }
2176
+ const parsed = CodexMcpElicitationAnswerSchema.parse(reply.value);
2177
+ return {
2178
+ action: parsed.action,
2179
+ ...parsed.content !== undefined && { content: parsed.content },
2180
+ ...parsed._meta !== undefined && { _meta: parsed._meta }
2181
+ };
2182
+ }
2183
+ if (reply.kind !== "input") {
2184
+ throw new TypeError("A Codex input request is answered with input");
2185
+ }
2186
+ return { answers: CodexUserInputAnswersSchema.parse(reply.value) };
2187
+ }
2188
+ function answerActiveCodexTurnRequest(turn, interactionId, rawReply) {
2189
+ const waiting = turn.pending.get(interactionId);
2190
+ if (waiting === undefined) {
2191
+ throw new TypeError(`Unknown interaction ${interactionId} for this turn`);
2192
+ }
2193
+ const answer = buildCodexRequestAnswer(waiting.detail, rawReply);
2194
+ answerEngineRequest(turn, interactionId, answer);
2195
+ }
2196
+ function answerCodexSessionRequest(input) {
2197
+ if (input.turn?.pending.has(input.interactionId)) {
2198
+ answerActiveCodexTurnRequest(input.turn, input.interactionId, input.reply);
2199
+ return;
2200
+ }
2201
+ const external = input.externalPending.get(input.interactionId);
2202
+ if (external === undefined || input.expectedEntry !== undefined && external !== input.expectedEntry) {
2203
+ throw new TypeError(`Unknown interaction ${input.interactionId} for this Codex connection`);
2204
+ }
2205
+ const answer = buildCodexRequestAnswer(external.detail, input.reply);
2206
+ input.externalPending.delete(input.interactionId);
2207
+ external.resolve(answer);
2208
+ }
2209
+
2210
+ // src/agent-executor/codex/handlers.ts
2211
+ var JSON_RPC_INTERNAL_ERROR = -32603;
2212
+ var MAX_EXTERNAL_PENDING_REQUESTS = 256;
2213
+ function emitCodexNotification(state, method, params, duringActiveTurn, deltas) {
2214
+ if (state.onNotification === undefined)
2215
+ return;
2216
+ invokeSafely(() => state.onNotification?.({ method, params, duringActiveTurn, deltas }));
2217
+ }
2218
+ function handleCodexNotification(state, method, params) {
2219
+ const turn = state.getTurn();
2220
+ const duringActiveTurn = turn !== undefined;
2221
+ const effectiveTurnId = turn?.state.turnId ?? externalCodexTurnIdOf(params);
2222
+ let verdict;
2223
+ try {
2224
+ verdict = classifyCodexNotification(method, params, turn?.state ?? { turnId: effectiveTurnId, interruptRequested: false });
2225
+ } catch (error) {
2226
+ const errorDelta = {
2227
+ type: "error",
2228
+ turnId: effectiveTurnId,
2229
+ itemId: `unhandled:${method}`,
2230
+ raw: { source: "codex", type: method },
2231
+ kind: "unhandled",
2232
+ message: `Codex notification ${method} did not match schema: ${error instanceof Error ? error.message : String(error)}`
2233
+ };
2234
+ if (turn !== undefined)
2235
+ offerTurnDelta(turn.channel, errorDelta);
2236
+ emitCodexNotification(state, method, params, duringActiveTurn, [errorDelta]);
2237
+ return;
2238
+ }
2239
+ switch (verdict.kind) {
2240
+ case "limits":
2241
+ try {
2242
+ state.limits.set(state.profileId, mergeRateLimitEvent2({
2243
+ previous: state.limits.get(state.profileId),
2244
+ windows: codexPlanWindows(verdict.rateLimits),
2245
+ now: new Date
2246
+ }));
2247
+ emitCodexNotification(state, method, params, duringActiveTurn, []);
2248
+ } catch (error) {
2249
+ const errorDelta = {
2250
+ type: "error",
2251
+ turnId: effectiveTurnId,
2252
+ itemId: `unhandled:${method}`,
2253
+ raw: { source: "codex", type: method },
2254
+ kind: "unhandled",
2255
+ message: `Codex rate-limit update could not be merged: ${error instanceof Error ? error.message : String(error)}`
2256
+ };
2257
+ if (turn !== undefined)
2258
+ offerTurnDelta(turn.channel, errorDelta);
2259
+ emitCodexNotification(state, method, params, duringActiveTurn, [errorDelta]);
2260
+ }
2261
+ return;
2262
+ case "resolved": {
2263
+ const resolvedTurn = turn?.pending.delete(verdict.requestId) === true;
2264
+ const externalEntry = state.externalPending.get(verdict.requestId);
2265
+ const resolvedExternal = externalEntry !== undefined;
2266
+ if (resolvedExternal)
2267
+ state.externalPending.delete(verdict.requestId);
2268
+ const resolvedDelta = {
2269
+ type: "request-resolved",
2270
+ turnId: resolvedTurn ? turn?.state.turnId ?? effectiveTurnId : externalEntry?.turnId ?? effectiveTurnId,
2271
+ itemId: `resolved:${verdict.requestId}`,
2272
+ raw: { source: "codex", type: "serverRequest/resolved" },
2273
+ interactionId: verdict.requestId
2274
+ };
2275
+ if (resolvedTurn && turn !== undefined)
2276
+ offerTurnDelta(turn.channel, resolvedDelta);
2277
+ emitCodexNotification(state, method, params, duringActiveTurn, resolvedTurn || resolvedExternal ? [resolvedDelta] : []);
2278
+ return;
2279
+ }
2280
+ case "deltas":
2281
+ case "unhandled": {
2282
+ const emitted = verdict.kind === "deltas" ? verdict.deltas : [verdict.delta];
2283
+ if (turn !== undefined) {
2284
+ for (const delta of emitted)
2285
+ offerTurnDelta(turn.channel, delta);
2286
+ }
2287
+ emitCodexNotification(state, method, params, duringActiveTurn, emitted);
2288
+ return;
2289
+ }
2290
+ case "end":
2291
+ endEngineTurn(turn, codexStopped, verdict.deltas);
2292
+ state.clearTurn();
2293
+ emitCodexNotification(state, method, params, duringActiveTurn, verdict.deltas);
2294
+ return;
2295
+ case "ignore":
2296
+ emitCodexNotification(state, method, params, duringActiveTurn, []);
2297
+ return;
2298
+ }
2299
+ }
2300
+ function handleCodexRequest(state, method, params, id) {
2301
+ const turn = state.getTurn();
2302
+ if (!isKnownCodexRequestMethod(method)) {
2303
+ if (turn !== undefined) {
2304
+ offerTurnDelta(turn.channel, {
2305
+ type: "error",
2306
+ turnId: turn.state.turnId,
2307
+ itemId: `unhandled-request:${id}`,
2308
+ raw: { source: "codex", type: method },
2309
+ kind: "unhandled",
2310
+ message: `Codex request ${method} is not known to this driver; refused`
2311
+ });
2312
+ }
2313
+ throw new JsonRpcError2(JSON_RPC_METHOD_NOT_FOUND2, `${method} is not handled by this executor`);
2314
+ }
2315
+ const interactionId = String(id);
2316
+ if (turn !== undefined) {
2317
+ const parsed = parseCodexServerRequest(method, params);
2318
+ return new Promise((resolve) => {
2319
+ holdEngineRequest(turn, {
2320
+ interactionId,
2321
+ detail: parsed.detail,
2322
+ answeredBy: { source: "codex", type: method },
2323
+ delta: () => ({
2324
+ type: "request",
2325
+ turnId: turn.state.turnId,
2326
+ itemId: `request:${interactionId}`,
2327
+ raw: { source: "codex", type: method },
2328
+ interactionId,
2329
+ kind: parsed.kind,
2330
+ ...parsed.deltaFields
2331
+ }),
2332
+ refusal: codexStoppedAnswer(method),
2333
+ resolve
2334
+ });
2335
+ });
2336
+ }
2337
+ const observer = state.onServerRequest;
2338
+ if (observer === undefined) {
2339
+ throw new JsonRpcError2(JSON_RPC_METHOD_NOT_FOUND2, `${method} is not handled by this executor`);
2340
+ }
2341
+ if (state.externalPending.size >= MAX_EXTERNAL_PENDING_REQUESTS) {
2342
+ throw new JsonRpcError2(JSON_RPC_INTERNAL_ERROR, `Too many pending external Codex server requests (limit ${MAX_EXTERNAL_PENDING_REQUESTS})`);
2343
+ }
2344
+ if (state.externalPending.has(interactionId)) {
2345
+ throw new JsonRpcError2(JSON_RPC_INTERNAL_ERROR, `Duplicate pending external Codex server request ${interactionId}`);
2346
+ }
2347
+ const parsed = parseCodexServerRequest(method, params);
2348
+ const turnId = externalCodexTurnIdOf(params);
2349
+ const delta = {
2350
+ type: "request",
2351
+ turnId,
2352
+ itemId: `request:${interactionId}`,
2353
+ raw: { source: "codex", type: method },
2354
+ interactionId,
2355
+ kind: parsed.kind,
2356
+ ...parsed.deltaFields
2357
+ };
2358
+ return new Promise((resolve, reject) => {
2359
+ const entry = { detail: parsed.detail, turnId, resolve };
2360
+ state.externalPending.set(interactionId, entry);
2361
+ const onObserverError = (error) => {
2362
+ if (state.externalPending.get(interactionId) !== entry)
2363
+ return;
2364
+ state.externalPending.delete(interactionId);
2365
+ if (error instanceof JsonRpcError2)
2366
+ reject(error);
2367
+ };
2368
+ try {
2369
+ const outcome = observer({
2370
+ interactionId,
2371
+ method,
2372
+ params,
2373
+ delta,
2374
+ async respond(reply) {
2375
+ answerCodexSessionRequest({
2376
+ turn: undefined,
2377
+ externalPending: state.externalPending,
2378
+ expectedEntry: entry,
2379
+ interactionId,
2380
+ reply
2381
+ });
2382
+ }
2383
+ });
2384
+ if (typeof outcome === "object" && outcome !== null && "then" in outcome && typeof outcome.then === "function") {
2385
+ Promise.resolve(outcome).catch(onObserverError);
2386
+ }
2387
+ } catch (error) {
2388
+ onObserverError(error);
2389
+ }
2390
+ });
2391
+ }
2392
+ function createCodexHandlers(state) {
2393
+ return {
2394
+ onNotification: (method, params) => handleCodexNotification(state, method, params),
2395
+ onRequest: (method, params, id) => handleCodexRequest(state, method, params, id)
2396
+ };
2397
+ }
2398
+
2399
+ // src/agent-executor/codex/turn-input.ts
2400
+ import { z as z3 } from "zod";
2401
+ var NonEmptyNoNulStringSchema = z3.string().min(1).refine((value) => value.trim().length > 0 && !value.includes("\x00"), {
2402
+ message: "must be a non-empty string without NUL bytes"
2403
+ });
2404
+ var CodexSkillInputSchema = z3.strictObject({
2405
+ type: z3.literal("skill"),
2406
+ name: NonEmptyNoNulStringSchema,
2407
+ path: NonEmptyNoNulStringSchema
2408
+ });
2409
+ function validateSkillInput(part) {
2410
+ if (part.type !== "skill")
2411
+ return;
2412
+ const parsed = CodexSkillInputSchema.safeParse(part);
2413
+ if (!parsed.success) {
2414
+ throw new TypeError("Codex skill input name and path must be non-empty strings without NUL bytes");
2415
+ }
2416
+ return { type: "skill", name: parsed.data.name, path: parsed.data.path };
2417
+ }
2418
+ function inlineCodexParts(parts, options) {
2419
+ return inlineOrderedParts(parts, {
2420
+ ...options,
2421
+ acceptedDescription: "text, images, and skills",
2422
+ validateExtra: validateSkillInput
2423
+ });
2424
+ }
2425
+ function codexTurnInput(parts) {
2426
+ if (parts.every((part) => part.type === "text")) {
2427
+ return [
2428
+ { type: "text", text: parts.map((part) => part.text).join(`
2429
+ `), text_elements: [] }
2430
+ ];
2431
+ }
2432
+ const out = [];
2433
+ for (const part of parts) {
2434
+ if (part.type === "text") {
2435
+ out.push({ type: "text", text: part.text, text_elements: [] });
2436
+ } else if (part.type === "skill") {
2437
+ out.push({ type: "skill", name: part.name, path: part.path });
2438
+ } else {
2439
+ out.push({ type: "image", url: `data:${part.mediaType};base64,${part.base64}` });
2440
+ }
2441
+ }
2442
+ return out;
2443
+ }
2444
+
2445
+ // src/agent-executor/codex/session-controls.ts
2446
+ function validateCodexForkBounds(options, caller) {
2447
+ if (options.beforeTurnId !== undefined && options.lastTurnId !== undefined) {
2448
+ throw new TypeError(`[stitchkit] ${caller}: beforeTurnId and lastTurnId are mutually exclusive`);
2449
+ }
2450
+ }
2451
+ function validateCodexPolicyOverrides(overrides, caller) {
2452
+ if (overrides.runtimeWorkspaceRoots !== undefined) {
2453
+ if (!Array.isArray(overrides.runtimeWorkspaceRoots)) {
2454
+ throw new TypeError(`[stitchkit] ${caller}: runtimeWorkspaceRoots must be an array of strings`);
2455
+ }
2456
+ for (const root of overrides.runtimeWorkspaceRoots) {
2457
+ if (typeof root !== "string" || root.trim().length === 0) {
2458
+ throw new TypeError(`[stitchkit] ${caller}: every runtimeWorkspaceRoots entry must be a non-empty string`);
2459
+ }
2460
+ }
2461
+ }
2462
+ if (overrides.config !== undefined) {
2463
+ if (typeof overrides.config !== "object" || overrides.config === null || Array.isArray(overrides.config)) {
2464
+ throw new TypeError(`[stitchkit] ${caller}: config must be a plain JSON object`);
2465
+ }
2466
+ safeJsonValue(overrides.config);
2467
+ }
2468
+ }
2469
+ function buildCodexThreadPolicyParams(base, overrides) {
2470
+ const mergedConfig = base.config !== undefined || overrides?.config !== undefined ? { ...base.config ?? {}, ...overrides?.config ?? {} } : undefined;
2471
+ const merged = {
2472
+ ...base,
1418
2473
  ...overrides,
1419
2474
  ...mergedConfig !== undefined && { config: mergedConfig }
1420
2475
  };
@@ -1480,51 +2535,6 @@ function buildCodexTurnStartParams(threadId, turnInput, parts, activeModelProvid
1480
2535
  }
1481
2536
  return params;
1482
2537
  }
1483
- function createCodexControlClient(input) {
1484
- const call = async (method, params) => {
1485
- input.ensureAlive();
1486
- return input.peer.request(method, params);
1487
- };
1488
- return {
1489
- readConfig(params) {
1490
- return call("config/read", {
1491
- ...params?.cwd !== undefined && { cwd: params.cwd },
1492
- ...params?.includeLayers !== undefined && { includeLayers: params.includeLayers }
1493
- });
1494
- },
1495
- listMcpServerStatus(params) {
1496
- return call("mcpServerStatus/list", {
1497
- ...params?.cursor !== undefined && { cursor: params.cursor },
1498
- ...params?.limit !== undefined && { limit: params.limit },
1499
- ...params?.threadId !== undefined && { threadId: params.threadId },
1500
- ...params?.serverName !== undefined && { serverName: params.serverName },
1501
- ...params?.detail !== undefined && { detail: params.detail }
1502
- });
1503
- },
1504
- listSkills(params) {
1505
- return call("skills/list", {
1506
- ...params?.cwds !== undefined && { cwds: [...params.cwds] },
1507
- ...params?.forceReload !== undefined && { forceReload: params.forceReload }
1508
- });
1509
- },
1510
- listModels(params) {
1511
- return call("model/list", {
1512
- ...params?.cursor !== undefined && { cursor: params.cursor },
1513
- ...params?.limit !== undefined && { limit: params.limit },
1514
- ...params?.includeHidden !== undefined && { includeHidden: params.includeHidden },
1515
- ...params?.modelProvider !== undefined && { modelProvider: params.modelProvider }
1516
- });
1517
- },
1518
- readAccount(params) {
1519
- return call("account/read", {
1520
- ...params?.refreshToken !== undefined && { refreshToken: params.refreshToken }
1521
- });
1522
- },
1523
- readRateLimits() {
1524
- return call("account/rateLimits/read");
1525
- }
1526
- };
1527
- }
1528
2538
  function createCodexSessionMutators(input) {
1529
2539
  return {
1530
2540
  async steerTurn(steerInput) {
@@ -1537,7 +2547,7 @@ function createCodexSessionMutators(input) {
1537
2547
  if (steerInput.expectedTurnId !== undefined && steerInput.expectedTurnId !== expectedTurnId) {
1538
2548
  throw new TypeError(`Expected active Codex turn ${steerInput.expectedTurnId}, but current turn is ${expectedTurnId}`);
1539
2549
  }
1540
- const parts = await inlineParts(steerInput.input, {
2550
+ const parts = await inlineCodexParts(steerInput.input, {
1541
2551
  ...input.imageOptions,
1542
2552
  driverLabel: "The Codex driver",
1543
2553
  signal: input.signal
@@ -1559,6 +2569,7 @@ function createCodexSessionMutators(input) {
1559
2569
  },
1560
2570
  async forkThread(options = {}) {
1561
2571
  input.ensureAlive();
2572
+ validateCodexForkBounds(options, "CodexSession.forkThread");
1562
2573
  const policyParams = buildCodexThreadPolicyParams({}, options);
1563
2574
  const forked = CodexStartedThreadSchema.parse(await input.peer.request("thread/fork", {
1564
2575
  threadId: input.threadId,
@@ -1566,7 +2577,10 @@ function createCodexSessionMutators(input) {
1566
2577
  ...options.cwd !== undefined && { cwd: options.cwd },
1567
2578
  ...options.beforeTurnId !== undefined && { beforeTurnId: options.beforeTurnId },
1568
2579
  ...options.lastTurnId !== undefined && { lastTurnId: options.lastTurnId },
1569
- ...options.excludeTurns !== undefined && { excludeTurns: options.excludeTurns }
2580
+ ...options.excludeTurns !== undefined && { excludeTurns: options.excludeTurns },
2581
+ ...options.deferGoalContinuation !== undefined && {
2582
+ deferGoalContinuation: options.deferGoalContinuation
2583
+ }
1570
2584
  }));
1571
2585
  return {
1572
2586
  nativeThreadId: forked.thread.id,
@@ -1581,147 +2595,22 @@ function createCodexSessionMutators(input) {
1581
2595
  }
1582
2596
 
1583
2597
  // src/agent-executor/codex/session.ts
1584
- function approvalDetail(params) {
1585
- const asked = CodexApprovalParamsSchema.parse(params);
1586
- const callId = nonEmptyString(asked.itemId);
1587
- return {
1588
- ...callId !== undefined && { callId },
1589
- ...typeof asked.command === "string" && { prompt: asked.command }
1590
- };
1591
- }
1592
- function inputDetail(params) {
1593
- const asked = CodexUserInputParamsSchema.parse(params);
1594
- const callId = nonEmptyString(asked.itemId);
1595
- return {
1596
- ...callId !== undefined && { callId },
1597
- input: asked.questions.map((question) => ({
1598
- id: question.id,
1599
- question: question.question
1600
- }))
1601
- };
1602
- }
1603
- function codexStoppedAnswer(method) {
1604
- return CODEX_APPROVAL_REQUESTS.has(method) ? { decision: CODEX_APPROVAL_DECISION.interrupted } : { answers: {} };
1605
- }
1606
- var codexStopped = (waiting) => codexStoppedAnswer(waiting.detail.method);
1607
- function createCodexHandlers(state) {
1608
- return {
1609
- onNotification(method, params) {
1610
- const turn = state.getTurn();
1611
- let verdict;
1612
- try {
1613
- verdict = classifyCodexNotification(method, params, turn?.state ?? { turnId: "between-turns", interruptRequested: false });
1614
- } catch (error) {
1615
- if (turn !== undefined) {
1616
- offerTurnDelta(turn.channel, {
1617
- type: "error",
1618
- turnId: turn.state.turnId,
1619
- itemId: `unhandled:${method}`,
1620
- raw: { source: "codex", type: method },
1621
- kind: "unhandled",
1622
- message: `Codex notification ${method} did not match schema: ${error instanceof Error ? error.message : String(error)}`
1623
- });
1624
- }
1625
- return;
1626
- }
1627
- switch (verdict.kind) {
1628
- case "limits":
1629
- try {
1630
- state.limits.set(state.profileId, mergeRateLimitEvent2({
1631
- previous: state.limits.get(state.profileId),
1632
- windows: codexPlanWindows(verdict.rateLimits),
1633
- now: new Date
1634
- }));
1635
- } catch (error) {
1636
- if (turn !== undefined) {
1637
- offerTurnDelta(turn.channel, {
1638
- type: "error",
1639
- turnId: turn.state.turnId,
1640
- itemId: `unhandled:${method}`,
1641
- raw: { source: "codex", type: method },
1642
- kind: "unhandled",
1643
- message: `Codex rate-limit update could not be merged: ${error instanceof Error ? error.message : String(error)}`
1644
- });
1645
- }
1646
- }
1647
- return;
1648
- case "resolved":
1649
- if (turn?.pending.delete(verdict.requestId)) {
1650
- offerTurnDelta(turn.channel, {
1651
- type: "request-resolved",
1652
- turnId: turn.state.turnId,
1653
- itemId: `resolved:${verdict.requestId}`,
1654
- raw: { source: "codex", type: "serverRequest/resolved" },
1655
- interactionId: verdict.requestId
1656
- });
1657
- }
1658
- return;
1659
- case "deltas":
1660
- case "unhandled":
1661
- if (turn !== undefined)
1662
- for (const delta of verdict.kind === "deltas" ? verdict.deltas : [verdict.delta])
1663
- offerTurnDelta(turn.channel, delta);
1664
- return;
1665
- case "end":
1666
- endEngineTurn(turn, codexStopped, verdict.deltas);
1667
- state.clearTurn();
1668
- return;
1669
- case "ignore":
1670
- return;
1671
- }
1672
- },
1673
- onRequest(method, params, id) {
1674
- const turn = state.getTurn();
1675
- const known = CODEX_APPROVAL_REQUESTS.has(method) || method === CODEX_INPUT_REQUEST;
1676
- if (turn === undefined || !known) {
1677
- if (turn !== undefined) {
1678
- offerTurnDelta(turn.channel, {
1679
- type: "error",
1680
- turnId: turn.state.turnId,
1681
- itemId: `unhandled-request:${id}`,
1682
- raw: { source: "codex", type: method },
1683
- kind: "unhandled",
1684
- message: `Codex request ${method} is not known to this driver; refused`
1685
- });
1686
- }
1687
- throw new JsonRpcError2(JSON_RPC_METHOD_NOT_FOUND2, `${method} is not handled by this executor`);
1688
- }
1689
- const interactionId = String(id);
1690
- const approval = CODEX_APPROVAL_REQUESTS.has(method);
1691
- return new Promise((resolve) => {
1692
- holdEngineRequest(turn, {
1693
- interactionId,
1694
- detail: { method },
1695
- answeredBy: { source: "codex", type: method },
1696
- delta: () => ({
1697
- type: "request",
1698
- turnId: turn.state.turnId,
1699
- itemId: `request:${interactionId}`,
1700
- raw: { source: "codex", type: method },
1701
- interactionId,
1702
- kind: approval ? "approval" : "input",
1703
- ...approval ? approvalDetail(params) : inputDetail(params)
1704
- }),
1705
- refusal: codexStoppedAnswer(method),
1706
- resolve
1707
- });
1708
- });
1709
- }
1710
- };
1711
- }
1712
2598
  function createCodexStartTurn(input) {
1713
- return imageTurnStarter({
1714
- driverLabel: "The Codex driver",
2599
+ return guardedTurnStarter({
1715
2600
  busyMessage: "A turn is already running in this Codex thread",
1716
- imageOptions: input.config,
1717
- signal: input.signal,
1718
- check(turnInput) {
2601
+ check: (turnInput) => {
1719
2602
  input.ensureAlive();
1720
- if (input.getTurn() !== undefined)
2603
+ if (input.getTurn() !== undefined) {
1721
2604
  throw new Error("A turn is already running in this Codex thread");
2605
+ }
1722
2606
  validateCodexTurnStartOverrides(turnInput, input.activeModelProvider);
1723
2607
  },
1724
- async dispatch(turnInput, parts) {
2608
+ inline: (turnInput) => inlineCodexParts(turnInput.input, {
2609
+ ...input.config,
2610
+ driverLabel: "The Codex driver",
2611
+ signal: input.signal
2612
+ }),
2613
+ dispatch: async (turnInput, parts) => {
1725
2614
  const turnParams = buildCodexTurnStartParams(input.threadId, turnInput, parts, input.activeModelProvider);
1726
2615
  const turn = {
1727
2616
  state: { turnId: turnInput.turnId, interruptRequested: false },
@@ -1750,50 +2639,119 @@ function createCodexStartTurn(input) {
1750
2639
  }
1751
2640
  },
1752
2641
  async respond(interactionId, rawReply) {
1753
- const reply = InteractionReplySchema2.shape.reply.parse(rawReply);
1754
- const waiting = turn.pending.get(interactionId);
1755
- if (waiting === undefined)
1756
- throw new TypeError(`Unknown interaction ${interactionId} for this turn`);
1757
- if (CODEX_APPROVAL_REQUESTS.has(waiting.detail.method)) {
1758
- if (reply.kind === "input")
1759
- throw new TypeError("A Codex approval is approved or denied, not answered with input");
1760
- answerEngineRequest(turn, interactionId, {
1761
- decision: reply.kind === "approve" ? CODEX_APPROVAL_DECISION.approve : CODEX_APPROVAL_DECISION.deny
1762
- });
1763
- } else {
1764
- if (reply.kind !== "input")
1765
- throw new TypeError("A Codex input request is answered with input");
1766
- answerEngineRequest(turn, interactionId, {
1767
- answers: CodexUserInputAnswersSchema.parse(reply.value)
1768
- });
1769
- }
2642
+ answerActiveCodexTurnRequest(turn, interactionId, rawReply);
1770
2643
  }
1771
2644
  };
1772
2645
  }
1773
2646
  });
1774
2647
  }
2648
+ function validateCodexOpenInput(input) {
2649
+ if (input.nativeThreadId !== undefined && input.forkFrom !== undefined) {
2650
+ throw new TypeError("[stitchkit] CodexDriver.open: nativeThreadId and forkFrom are mutually exclusive");
2651
+ }
2652
+ if (input.forkFrom !== undefined) {
2653
+ if (typeof input.forkFrom.threadId !== "string" || input.forkFrom.threadId.trim().length === 0) {
2654
+ throw new TypeError("[stitchkit] CodexDriver.open: forkFrom.threadId must be a non-empty string");
2655
+ }
2656
+ validateCodexForkBounds(input.forkFrom, "CodexDriver.open");
2657
+ validateCodexPolicyOverrides(input.forkFrom, "CodexDriver.open");
2658
+ }
2659
+ }
2660
+ function mergeOpenThreadPolicy(config, forkFrom, dynamicOverrides) {
2661
+ const basePolicy = {
2662
+ ...config.model !== undefined && { model: config.model },
2663
+ ...config.modelProvider !== undefined && { modelProvider: config.modelProvider },
2664
+ ...config.approvalPolicy !== undefined && { approvalPolicy: config.approvalPolicy },
2665
+ ...config.sandbox !== undefined && { sandbox: config.sandbox },
2666
+ ...config.developerInstructions !== undefined && {
2667
+ developerInstructions: config.developerInstructions
2668
+ },
2669
+ ...config.runtimeWorkspaceRoots !== undefined && {
2670
+ runtimeWorkspaceRoots: config.runtimeWorkspaceRoots
2671
+ },
2672
+ ...config.config !== undefined && { config: config.config }
2673
+ };
2674
+ const withFork = forkFrom === undefined ? basePolicy : {
2675
+ ...basePolicy,
2676
+ ...forkFrom.model !== undefined && { model: forkFrom.model },
2677
+ ...forkFrom.modelProvider !== undefined && {
2678
+ modelProvider: forkFrom.modelProvider
2679
+ },
2680
+ ...forkFrom.approvalPolicy !== undefined && {
2681
+ approvalPolicy: forkFrom.approvalPolicy
2682
+ },
2683
+ ...forkFrom.sandbox !== undefined && { sandbox: forkFrom.sandbox },
2684
+ ...forkFrom.developerInstructions !== undefined && {
2685
+ developerInstructions: forkFrom.developerInstructions
2686
+ },
2687
+ ...forkFrom.runtimeWorkspaceRoots !== undefined && {
2688
+ runtimeWorkspaceRoots: forkFrom.runtimeWorkspaceRoots
2689
+ },
2690
+ ...basePolicy.config !== undefined || forkFrom.config !== undefined ? { config: { ...basePolicy.config ?? {}, ...forkFrom.config ?? {} } } : {}
2691
+ };
2692
+ return buildCodexThreadPolicyParams(withFork, dynamicOverrides);
2693
+ }
2694
+ function openCodexThreadRpc(peer, config, input, dynamicOverrides) {
2695
+ const threadParams = {
2696
+ cwd: input.cwd,
2697
+ ...mergeOpenThreadPolicy(config, input.forkFrom, dynamicOverrides)
2698
+ };
2699
+ if (input.forkFrom !== undefined) {
2700
+ const fork = input.forkFrom;
2701
+ return peer.request("thread/fork", {
2702
+ threadId: fork.threadId,
2703
+ excludeTurns: fork.excludeTurns ?? true,
2704
+ ...threadParams,
2705
+ ...fork.beforeTurnId !== undefined && { beforeTurnId: fork.beforeTurnId },
2706
+ ...fork.lastTurnId !== undefined && { lastTurnId: fork.lastTurnId },
2707
+ ...fork.deferGoalContinuation !== undefined && {
2708
+ deferGoalContinuation: fork.deferGoalContinuation
2709
+ }
2710
+ });
2711
+ }
2712
+ if (input.nativeThreadId !== undefined) {
2713
+ return peer.request("thread/resume", {
2714
+ threadId: input.nativeThreadId,
2715
+ excludeTurns: true,
2716
+ ...threadParams
2717
+ });
2718
+ }
2719
+ return peer.request("thread/start", threadParams);
2720
+ }
1775
2721
  async function openCodexSession(config, input) {
2722
+ validateCodexOpenInput(input);
1776
2723
  const profile = engineProfile("codex", input.profile);
1777
2724
  const linked = sessionAbort(input.signal);
2725
+ const externalPending = new Map;
1778
2726
  let current;
1779
2727
  let dead;
2728
+ let opened = false;
1780
2729
  let closing = false;
1781
2730
  let connected;
1782
2731
  try {
1783
2732
  connected = await connectCodex(config, profile, input.cwd, linked.signal, createCodexHandlers({
1784
2733
  profileId: profile.profileId,
1785
2734
  limits: config.limits,
2735
+ externalPending,
1786
2736
  getTurn: () => current,
1787
2737
  clearTurn: () => {
1788
2738
  current = undefined;
2739
+ },
2740
+ ...config.onNotification !== undefined && { onNotification: config.onNotification },
2741
+ ...config.onServerRequest !== undefined && {
2742
+ onServerRequest: config.onServerRequest
1789
2743
  }
1790
2744
  }), (error) => {
2745
+ const shouldNotify = opened && !closing && input.signal?.aborted !== true;
1791
2746
  dead = error;
1792
2747
  const turn = current;
1793
2748
  current = undefined;
2749
+ externalPending.clear();
1794
2750
  loseEngineTurn(turn, codexStopped, error);
1795
2751
  linked.abort();
1796
- });
2752
+ if (shouldNotify)
2753
+ invokeSafely(() => config.onDisconnect?.(error));
2754
+ }, input.onStartupPhase);
1797
2755
  } catch (error) {
1798
2756
  linked.release();
1799
2757
  throw error;
@@ -1807,6 +2765,7 @@ async function openCodexSession(config, input) {
1807
2765
  };
1808
2766
  const stop = async (primary) => {
1809
2767
  closing = true;
2768
+ externalPending.clear();
1810
2769
  try {
1811
2770
  await stopConnection(connected, primary);
1812
2771
  } finally {
@@ -1825,36 +2784,17 @@ async function openCodexSession(config, input) {
1825
2784
  cwd: input.cwd,
1826
2785
  ...input.nativeThreadId !== undefined && {
1827
2786
  nativeThreadId: input.nativeThreadId
1828
- }
2787
+ },
2788
+ ...input.forkFrom !== undefined && { forkFrom: input.forkFrom }
1829
2789
  })), linked.signal);
1830
2790
  linked.signal.throwIfAborted();
1831
2791
  }
1832
- const basePolicy = {
1833
- ...config.model !== undefined && { model: config.model },
1834
- ...config.modelProvider !== undefined && { modelProvider: config.modelProvider },
1835
- ...config.approvalPolicy !== undefined && { approvalPolicy: config.approvalPolicy },
1836
- ...config.sandbox !== undefined && { sandbox: config.sandbox },
1837
- ...config.developerInstructions !== undefined && {
1838
- developerInstructions: config.developerInstructions
1839
- },
1840
- ...config.runtimeWorkspaceRoots !== undefined && {
1841
- runtimeWorkspaceRoots: config.runtimeWorkspaceRoots
1842
- },
1843
- ...config.config !== undefined && { config: config.config }
1844
- };
1845
- const threadParams = {
1846
- cwd: input.cwd,
1847
- ...buildCodexThreadPolicyParams(basePolicy, dynamicOverrides)
1848
- };
1849
- const opened = input.nativeThreadId ? await peer.request("thread/resume", {
1850
- threadId: input.nativeThreadId,
1851
- excludeTurns: true,
1852
- ...threadParams
1853
- }) : await peer.request("thread/start", threadParams);
1854
- const parsed = CodexStartedThreadSchema.parse(opened);
2792
+ const openedReply = await openCodexThreadRpc(peer, config, input, dynamicOverrides);
2793
+ const parsed = CodexStartedThreadSchema.parse(openedReply);
1855
2794
  threadId = parsed.thread.id;
1856
2795
  threadContext = extractCodexThreadContext(parsed);
1857
2796
  if (config.verifyThread !== undefined) {
2797
+ emitStartupPhase(input.onStartupPhase, "verifying");
1858
2798
  await raceAbort(Promise.resolve(config.verifyThread({
1859
2799
  nativeThreadId: threadId,
1860
2800
  threadContext,
@@ -1862,11 +2802,14 @@ async function openCodexSession(config, input) {
1862
2802
  })), linked.signal);
1863
2803
  linked.signal.throwIfAborted();
1864
2804
  }
2805
+ if (dead !== undefined)
2806
+ throw dead;
2807
+ linked.signal.throwIfAborted();
1865
2808
  } catch (error) {
1866
2809
  await stop({ error });
1867
2810
  throw error;
1868
2811
  }
1869
- const activeModelProvider = threadContext.modelProvider ?? dynamicOverrides?.modelProvider ?? config.modelProvider;
2812
+ const activeModelProvider = threadContext.modelProvider ?? dynamicOverrides?.modelProvider ?? input.forkFrom?.modelProvider ?? config.modelProvider;
1870
2813
  const startTurn = createCodexStartTurn({
1871
2814
  config,
1872
2815
  peer,
@@ -1887,22 +2830,493 @@ async function openCodexSession(config, input) {
1887
2830
  ensureAlive,
1888
2831
  getActiveTurn: () => current
1889
2832
  });
2833
+ opened = true;
1890
2834
  return {
1891
2835
  nativeThreadId: threadId,
1892
2836
  providerPid,
1893
2837
  threadContext,
1894
2838
  startTurn,
2839
+ async respond(interactionId, reply) {
2840
+ ensureAlive();
2841
+ answerCodexSessionRequest({ turn: current, externalPending, interactionId, reply });
2842
+ },
1895
2843
  ...controlClient,
2844
+ ...bindCodexSessionThreadControls(controlClient, threadId),
1896
2845
  ...mutators,
1897
2846
  async close() {
1898
2847
  await stop();
1899
2848
  }
1900
2849
  };
1901
2850
  }
2851
+ async function openCodexControlConnection(config, input) {
2852
+ const profile = engineProfile("codex", input.profile);
2853
+ const linked = sessionAbort(input.signal);
2854
+ const externalPending = new Map;
2855
+ let dead;
2856
+ let opened = false;
2857
+ let closing = false;
2858
+ let connected;
2859
+ try {
2860
+ connected = await connectCodex(config, profile, input.cwd, linked.signal, createCodexHandlers({
2861
+ profileId: profile.profileId,
2862
+ limits: config.limits,
2863
+ externalPending,
2864
+ getTurn: () => {
2865
+ return;
2866
+ },
2867
+ clearTurn: () => {
2868
+ return;
2869
+ },
2870
+ ...config.onNotification !== undefined && { onNotification: config.onNotification },
2871
+ ...config.onServerRequest !== undefined && {
2872
+ onServerRequest: config.onServerRequest
2873
+ }
2874
+ }), (error) => {
2875
+ const shouldNotify = opened && !closing && input.signal?.aborted !== true;
2876
+ dead = error;
2877
+ externalPending.clear();
2878
+ linked.abort();
2879
+ if (shouldNotify)
2880
+ invokeSafely(() => config.onDisconnect?.(error));
2881
+ }, input.onStartupPhase);
2882
+ } catch (error) {
2883
+ linked.release();
2884
+ throw error;
2885
+ }
2886
+ if (dead !== undefined || linked.signal.aborted) {
2887
+ const reason = dead ?? abortReason(linked.signal);
2888
+ closing = true;
2889
+ externalPending.clear();
2890
+ try {
2891
+ await stopConnection(connected, { error: reason });
2892
+ } finally {
2893
+ linked.abort();
2894
+ linked.release();
2895
+ }
2896
+ throw reason;
2897
+ }
2898
+ const ensureAlive = () => {
2899
+ if (closing)
2900
+ throw new Error("The Codex control connection is closed");
2901
+ if (dead !== undefined)
2902
+ throw dead;
2903
+ };
2904
+ const controlClient = createCodexControlClient({ peer: connected.peer, ensureAlive });
2905
+ opened = true;
2906
+ return {
2907
+ providerPid: connected.providerPid,
2908
+ ...controlClient,
2909
+ async respond(interactionId, reply) {
2910
+ ensureAlive();
2911
+ answerCodexSessionRequest({ turn: undefined, externalPending, interactionId, reply });
2912
+ },
2913
+ async close() {
2914
+ closing = true;
2915
+ externalPending.clear();
2916
+ try {
2917
+ await stopConnection(connected);
2918
+ } finally {
2919
+ linked.abort();
2920
+ linked.release();
2921
+ }
2922
+ }
2923
+ };
2924
+ }
2925
+
2926
+ // src/agent-executor/codex/shared-thread.ts
2927
+ var CLOSE_UNSUBSCRIBE_TIMEOUT_MS = 5000;
2928
+ function bestEffortUnsubscribe(state, threadId) {
2929
+ if (state.isServerClosing() || state.getServerDead() !== undefined) {
2930
+ return Promise.resolve();
2931
+ }
2932
+ return state.peer.request("thread/unsubscribe", { threadId }, { timeoutMs: CLOSE_UNSUBSCRIBE_TIMEOUT_MS }).then(() => {
2933
+ return;
2934
+ }, () => {
2935
+ return;
2936
+ });
2937
+ }
2938
+ function buildSharedThreadSession(params) {
2939
+ const { state, slot, threadContext, activeModelProvider, threadAbort } = params;
2940
+ const { threadId } = slot;
2941
+ const ensureThreadAlive = () => {
2942
+ if (slot.closed)
2943
+ throw new Error("The Codex session is closed");
2944
+ if (slot.dead !== undefined)
2945
+ throw slot.dead;
2946
+ state.ensureServerAlive();
2947
+ };
2948
+ const threadControlClient = createCodexControlClient({
2949
+ peer: state.peer,
2950
+ ensureAlive: ensureThreadAlive
2951
+ });
2952
+ const startTurn = createCodexStartTurn({
2953
+ config: state.config,
2954
+ peer: state.peer,
2955
+ threadId,
2956
+ activeModelProvider,
2957
+ signal: threadAbort.signal,
2958
+ ensureAlive: ensureThreadAlive,
2959
+ getTurn: () => slot.current,
2960
+ setTurn: (turn) => {
2961
+ slot.current = turn;
2962
+ }
2963
+ });
2964
+ const mutators = createCodexSessionMutators({
2965
+ peer: state.peer,
2966
+ threadId,
2967
+ imageOptions: state.config,
2968
+ signal: threadAbort.signal,
2969
+ ensureAlive: ensureThreadAlive,
2970
+ getActiveTurn: () => slot.current
2971
+ });
2972
+ const closeThread = async () => {
2973
+ if (slot.closed)
2974
+ return;
2975
+ slot.closed = true;
2976
+ const turn = slot.current;
2977
+ slot.current = undefined;
2978
+ slot.externalPending.clear();
2979
+ loseEngineTurn(turn, codexStopped, new Error("The Codex session closed"));
2980
+ state.threads.delete(threadId);
2981
+ try {
2982
+ await bestEffortUnsubscribe(state, threadId);
2983
+ } finally {
2984
+ threadAbort.abort();
2985
+ slot.releaseThreadSignal();
2986
+ }
2987
+ };
2988
+ threadAbort.signal.addEventListener("abort", () => {
2989
+ if (slot.closed)
2990
+ return;
2991
+ slot.closed = true;
2992
+ const reason = abortReason(threadAbort.signal);
2993
+ slot.dead = slot.dead ?? (reason instanceof Error ? reason : new Error(String(reason)));
2994
+ const turn = slot.current;
2995
+ slot.current = undefined;
2996
+ slot.externalPending.clear();
2997
+ loseEngineTurn(turn, codexStopped, slot.dead);
2998
+ state.threads.delete(threadId);
2999
+ slot.releaseThreadSignal();
3000
+ bestEffortUnsubscribe(state, threadId);
3001
+ }, { once: true });
3002
+ return {
3003
+ nativeThreadId: threadId,
3004
+ providerPid: state.providerPid,
3005
+ threadContext,
3006
+ startTurn,
3007
+ async respond(interactionId, reply) {
3008
+ ensureThreadAlive();
3009
+ answerCodexSessionRequest({
3010
+ turn: slot.current,
3011
+ externalPending: slot.externalPending,
3012
+ interactionId,
3013
+ reply
3014
+ });
3015
+ },
3016
+ ...threadControlClient,
3017
+ ...bindCodexSessionThreadControls(threadControlClient, threadId),
3018
+ ...mutators,
3019
+ close: closeThread
3020
+ };
3021
+ }
3022
+ async function openSharedCodexThread(state, threadInput) {
3023
+ state.ensureServerAlive();
3024
+ validateCodexOpenInput({ ...threadInput, profile: state.profile });
3025
+ if (threadInput.nativeThreadId !== undefined && (state.threads.has(threadInput.nativeThreadId) || state.openingNativeThreadIds.has(threadInput.nativeThreadId))) {
3026
+ throw new Error(`[stitchkit] CodexSharedServer.openThread: thread ${threadInput.nativeThreadId} is already open on this shared server`);
3027
+ }
3028
+ if (state.threads.size + state.openingThreads >= state.maxThreads) {
3029
+ throw new RangeError(`[stitchkit] CodexSharedServer.openThread: active thread limit (${state.maxThreads}) reached`);
3030
+ }
3031
+ const threadAbort = sessionAbort(threadInput.signal);
3032
+ const onServerAbort = () => threadAbort.abort();
3033
+ state.serverSignal.addEventListener("abort", onServerAbort, { once: true });
3034
+ let signalReleased = false;
3035
+ const releaseThreadSignal = () => {
3036
+ if (signalReleased)
3037
+ return;
3038
+ signalReleased = true;
3039
+ state.serverSignal.removeEventListener("abort", onServerAbort);
3040
+ threadAbort.release();
3041
+ };
3042
+ state.openingThreads += 1;
3043
+ if (threadInput.nativeThreadId !== undefined) {
3044
+ state.openingNativeThreadIds.add(threadInput.nativeThreadId);
3045
+ }
3046
+ let registeredThreadId;
3047
+ try {
3048
+ threadAbort.signal.throwIfAborted();
3049
+ let dynamicOverrides;
3050
+ if (state.config.prepareThread !== undefined) {
3051
+ dynamicOverrides = await raceAbort(Promise.resolve(state.config.prepareThread({
3052
+ controls: state.controlClient,
3053
+ cwd: threadInput.cwd,
3054
+ ...threadInput.nativeThreadId !== undefined && {
3055
+ nativeThreadId: threadInput.nativeThreadId
3056
+ },
3057
+ ...threadInput.forkFrom !== undefined && { forkFrom: threadInput.forkFrom }
3058
+ })), threadAbort.signal);
3059
+ threadAbort.signal.throwIfAborted();
3060
+ state.ensureServerAlive();
3061
+ }
3062
+ const disposeLateOpen = (reply) => {
3063
+ const parsedLate = CodexStartedThreadSchema.safeParse(reply);
3064
+ if (parsedLate.success && !state.threads.has(parsedLate.data.thread.id)) {
3065
+ bestEffortUnsubscribe(state, parsedLate.data.thread.id);
3066
+ }
3067
+ };
3068
+ const openedReply = await raceAbort(openCodexThreadRpc(state.peer, state.config, threadInput, dynamicOverrides), threadAbort.signal, disposeLateOpen);
3069
+ threadAbort.signal.throwIfAborted();
3070
+ state.ensureServerAlive();
3071
+ const parsed = CodexStartedThreadSchema.parse(openedReply);
3072
+ const threadId = parsed.thread.id;
3073
+ const threadContext = extractCodexThreadContext(parsed);
3074
+ if (state.threads.has(threadId)) {
3075
+ throw new Error(`[stitchkit] CodexSharedServer.openThread: thread ${threadId} is already open on this shared server`);
3076
+ }
3077
+ const externalPending = new Map;
3078
+ const slot = {
3079
+ threadId,
3080
+ current: undefined,
3081
+ externalPending,
3082
+ closed: false,
3083
+ dead: undefined,
3084
+ abortThread: () => threadAbort.abort(),
3085
+ releaseThreadSignal,
3086
+ handlers: createCodexHandlers({
3087
+ profileId: state.profile.profileId,
3088
+ limits: state.config.limits,
3089
+ externalPending,
3090
+ getTurn: () => slot.current,
3091
+ clearTurn: () => {
3092
+ slot.current = undefined;
3093
+ },
3094
+ ...state.config.onNotification !== undefined && {
3095
+ onNotification: state.config.onNotification
3096
+ },
3097
+ ...state.config.onServerRequest !== undefined && {
3098
+ onServerRequest: state.config.onServerRequest
3099
+ }
3100
+ })
3101
+ };
3102
+ state.threads.set(threadId, slot);
3103
+ registeredThreadId = threadId;
3104
+ if (state.config.verifyThread !== undefined) {
3105
+ emitStartupPhase(threadInput.onStartupPhase, "verifying");
3106
+ await raceAbort(Promise.resolve(state.config.verifyThread({
3107
+ nativeThreadId: threadId,
3108
+ threadContext,
3109
+ controls: state.controlClient
3110
+ })), threadAbort.signal);
3111
+ threadAbort.signal.throwIfAborted();
3112
+ }
3113
+ state.ensureServerAlive();
3114
+ threadAbort.signal.throwIfAborted();
3115
+ if (slot.dead !== undefined)
3116
+ throw slot.dead;
3117
+ const activeModelProvider = threadContext.modelProvider ?? dynamicOverrides?.modelProvider ?? threadInput.forkFrom?.modelProvider ?? state.config.modelProvider;
3118
+ return buildSharedThreadSession({
3119
+ state,
3120
+ slot,
3121
+ threadContext,
3122
+ activeModelProvider,
3123
+ threadAbort
3124
+ });
3125
+ } catch (error) {
3126
+ if (registeredThreadId !== undefined) {
3127
+ state.threads.delete(registeredThreadId);
3128
+ await bestEffortUnsubscribe(state, registeredThreadId);
3129
+ }
3130
+ threadAbort.abort();
3131
+ releaseThreadSignal();
3132
+ throw error;
3133
+ } finally {
3134
+ state.openingThreads -= 1;
3135
+ if (threadInput.nativeThreadId !== undefined) {
3136
+ state.openingNativeThreadIds.delete(threadInput.nativeThreadId);
3137
+ }
3138
+ }
3139
+ }
3140
+
3141
+ // src/agent-executor/codex/shared-server.ts
3142
+ var DEFAULT_MAX_SHARED_THREADS = 32;
3143
+ var HARD_MAX_SHARED_THREADS = 256;
3144
+ function extractCodexThreadId(params) {
3145
+ if (!isRecord(params))
3146
+ return;
3147
+ if (typeof params.threadId === "string" && params.threadId.length > 0)
3148
+ return params.threadId;
3149
+ if (isRecord(params.thread) && typeof params.thread.id === "string" && params.thread.id.length > 0) {
3150
+ return params.thread.id;
3151
+ }
3152
+ if (isRecord(params.turn) && typeof params.turn.threadId === "string" && params.turn.threadId.length > 0) {
3153
+ return params.turn.threadId;
3154
+ }
3155
+ return;
3156
+ }
3157
+ function validateSharedServerInputs(config, input) {
3158
+ if (config.transport !== undefined && config.transport.kind !== "stdio") {
3159
+ throw new TypeError(`[stitchkit] CodexDriver.openSharedServer: shared multi-thread mode requires stdio transport (received ${JSON.stringify(config.transport.kind)})`);
3160
+ }
3161
+ const maxThreads = input.maxThreads ?? DEFAULT_MAX_SHARED_THREADS;
3162
+ assertPositiveSafeInteger("[stitchkit] CodexDriver.openSharedServer: maxThreads", maxThreads);
3163
+ if (maxThreads > HARD_MAX_SHARED_THREADS) {
3164
+ throw new RangeError(`[stitchkit] CodexDriver.openSharedServer: maxThreads (${maxThreads}) must not exceed ${HARD_MAX_SHARED_THREADS}`);
3165
+ }
3166
+ return maxThreads;
3167
+ }
3168
+ async function openCodexSharedServer(config, baseCapabilities, input) {
3169
+ const maxThreads = validateSharedServerInputs(config, input);
3170
+ const profile = engineProfile("codex", input.profile);
3171
+ const linked = sessionAbort(input.signal);
3172
+ const threads = new Map;
3173
+ const globalExternalPending = new Map;
3174
+ let serverDead;
3175
+ let serverClosing = false;
3176
+ let opened = false;
3177
+ const globalHandlers = createCodexHandlers({
3178
+ profileId: profile.profileId,
3179
+ limits: config.limits,
3180
+ externalPending: globalExternalPending,
3181
+ getTurn: () => {
3182
+ return;
3183
+ },
3184
+ clearTurn: () => {
3185
+ return;
3186
+ },
3187
+ ...config.onNotification !== undefined && { onNotification: config.onNotification },
3188
+ ...config.onServerRequest !== undefined && { onServerRequest: config.onServerRequest }
3189
+ });
3190
+ const failAllThreads = (error) => {
3191
+ for (const slot of [...threads.values()]) {
3192
+ slot.closed = true;
3193
+ slot.dead = error;
3194
+ const turn = slot.current;
3195
+ slot.current = undefined;
3196
+ slot.externalPending.clear();
3197
+ loseEngineTurn(turn, codexStopped, error);
3198
+ slot.abortThread();
3199
+ slot.releaseThreadSignal();
3200
+ }
3201
+ threads.clear();
3202
+ };
3203
+ let connected;
3204
+ try {
3205
+ connected = await connectCodex(config, profile, input.cwd, linked.signal, {
3206
+ onNotification(method, params) {
3207
+ if (method === "account/rateLimits/updated") {
3208
+ invokeSafely(() => globalHandlers.onNotification(method, params));
3209
+ return;
3210
+ }
3211
+ const targetId = extractCodexThreadId(params);
3212
+ const slot = targetId !== undefined ? threads.get(targetId) : undefined;
3213
+ if (slot !== undefined) {
3214
+ invokeSafely(() => slot.handlers.onNotification(method, params));
3215
+ return;
3216
+ }
3217
+ invokeSafely(() => globalHandlers.onNotification(method, params));
3218
+ },
3219
+ onRequest(method, params, id) {
3220
+ const targetId = extractCodexThreadId(params);
3221
+ const slot = targetId !== undefined ? threads.get(targetId) : undefined;
3222
+ if (slot !== undefined)
3223
+ return slot.handlers.onRequest(method, params, id);
3224
+ return globalHandlers.onRequest(method, params, id);
3225
+ }
3226
+ }, (error) => {
3227
+ const shouldNotify = opened && !serverClosing && input.signal?.aborted !== true;
3228
+ serverDead = error;
3229
+ globalExternalPending.clear();
3230
+ failAllThreads(error);
3231
+ linked.abort();
3232
+ if (shouldNotify)
3233
+ invokeSafely(() => config.onDisconnect?.(error));
3234
+ }, input.onStartupPhase);
3235
+ } catch (error) {
3236
+ linked.release();
3237
+ throw error;
3238
+ }
3239
+ const { peer, providerPid } = connected;
3240
+ const ensureServerAlive = () => {
3241
+ if (serverClosing)
3242
+ throw new Error("The Codex shared server is closed");
3243
+ if (serverDead !== undefined)
3244
+ throw serverDead;
3245
+ };
3246
+ const controlClient = createCodexControlClient({ peer, ensureAlive: ensureServerAlive });
3247
+ const sharedCapabilities = {
3248
+ ...baseCapabilities,
3249
+ multiThreadPerProcess: true
3250
+ };
3251
+ const state = {
3252
+ config,
3253
+ profile,
3254
+ peer,
3255
+ providerPid,
3256
+ maxThreads,
3257
+ controlClient,
3258
+ serverSignal: linked.signal,
3259
+ threads,
3260
+ openingNativeThreadIds: new Set,
3261
+ openingThreads: 0,
3262
+ isServerClosing: () => serverClosing,
3263
+ getServerDead: () => serverDead,
3264
+ ensureServerAlive
3265
+ };
3266
+ const closeServer = async () => {
3267
+ if (serverClosing)
3268
+ return;
3269
+ serverClosing = true;
3270
+ globalExternalPending.clear();
3271
+ failAllThreads(new Error("The Codex shared server closed"));
3272
+ try {
3273
+ await stopConnection(connected);
3274
+ } finally {
3275
+ linked.abort();
3276
+ linked.release();
3277
+ }
3278
+ };
3279
+ opened = true;
3280
+ return {
3281
+ providerPid,
3282
+ maxThreads,
3283
+ get activeThreadCount() {
3284
+ return threads.size;
3285
+ },
3286
+ capabilities: sharedCapabilities,
3287
+ ...controlClient,
3288
+ openThread: (threadInput) => openSharedCodexThread(state, threadInput),
3289
+ close: closeServer
3290
+ };
3291
+ }
1902
3292
 
1903
3293
  // src/agent-executor/codex/driver.ts
1904
3294
  var MAX_HISTORY_PAGES = 256;
1905
3295
  var FIND_INPUT_MAX_LINE_BYTES = 64 * 1024 * 1024;
3296
+ async function findCodexClientInput(peer, nativeThreadId, clientId) {
3297
+ const seen = new Set;
3298
+ let cursor;
3299
+ for (let pageNumber = 0;pageNumber < MAX_HISTORY_PAGES; pageNumber += 1) {
3300
+ const page = CodexTurnsPageSchema.parse(await peer.request("thread/turns/list", {
3301
+ threadId: nativeThreadId,
3302
+ limit: 50,
3303
+ itemsView: "full",
3304
+ ...cursor !== undefined && { cursor }
3305
+ }));
3306
+ if (page.data.some((turn) => turn.items.some((item) => item.type === "userMessage" && item.clientId === clientId))) {
3307
+ return true;
3308
+ }
3309
+ const next = page.nextCursor;
3310
+ if (next === null || next === undefined)
3311
+ return false;
3312
+ if (seen.has(next)) {
3313
+ throw new Error(`Codex thread/turns/list repeated cursor ${JSON.stringify(next)} before history ended`);
3314
+ }
3315
+ seen.add(next);
3316
+ cursor = next;
3317
+ }
3318
+ throw new Error(`Codex thread/turns/list exceeded ${MAX_HISTORY_PAGES} pages without reaching the end of history`);
3319
+ }
1906
3320
  function createCodexDriver(config = {}) {
1907
3321
  validateImageOptions(config);
1908
3322
  validateCodexTransportAndArgs(config);
@@ -1912,6 +3326,22 @@ function createCodexDriver(config = {}) {
1912
3326
  const ambient = config.ambient ?? process.env;
1913
3327
  const limits = new Map;
1914
3328
  let version = "unknown";
3329
+ const capabilities = {
3330
+ runtimePolicyEnforcement: "native",
3331
+ sessionApproval: true,
3332
+ interruptOnDeny: true,
3333
+ updatedToolInput: false,
3334
+ structuredInput: true,
3335
+ steer: true,
3336
+ fork: true,
3337
+ revert: true,
3338
+ compact: true,
3339
+ injectItems: true,
3340
+ backgroundWorkOutlivesTurn: false,
3341
+ multiThreadPerProcess: false,
3342
+ images: config.resolveFile !== undefined,
3343
+ planLimits: "pull"
3344
+ };
1915
3345
  const session = (options) => {
1916
3346
  const transport = options?.forceStdioForListen && config.transport?.kind === "unix-listen" ? { kind: "stdio" } : config.transport;
1917
3347
  return {
@@ -1932,6 +3362,9 @@ function createCodexDriver(config = {}) {
1932
3362
  ...config.config !== undefined && { config: config.config },
1933
3363
  ...config.prepareThread !== undefined && { prepareThread: config.prepareThread },
1934
3364
  ...config.verifyThread !== undefined && { verifyThread: config.verifyThread },
3365
+ ...!options?.ephemeralProbe && config.onNotification !== undefined && { onNotification: config.onNotification },
3366
+ ...!options?.ephemeralProbe && config.onServerRequest !== undefined && { onServerRequest: config.onServerRequest },
3367
+ ...!options?.ephemeralProbe && config.onDisconnect !== undefined && { onDisconnect: config.onDisconnect },
1935
3368
  ambient,
1936
3369
  limits,
1937
3370
  version,
@@ -1943,11 +3376,13 @@ function createCodexDriver(config = {}) {
1943
3376
  const cli = (profile, args) => runEngineCli({ executable, prefix, args, profile, ambient });
1944
3377
  const ask = (profile, cwd, question, maxLineBytes) => withEphemeralConnection((signal) => connectCodex(session({
1945
3378
  ...maxLineBytes !== undefined && { maxLineBytes },
1946
- forceStdioForListen: true
3379
+ forceStdioForListen: true,
3380
+ ephemeralProbe: true
1947
3381
  }), engineProfile("codex", profile), cwd, signal), (connection) => question(connection.peer));
1948
3382
  return {
1949
3383
  engine: "codex",
1950
3384
  reconcile: "client-id",
3385
+ capabilities,
1951
3386
  async info() {
1952
3387
  const probe = {
1953
3388
  profileId: "version-probe",
@@ -1961,7 +3396,8 @@ function createCodexDriver(config = {}) {
1961
3396
  engine: "codex",
1962
3397
  version,
1963
3398
  reconcile: "client-id",
1964
- models: { answer: "not-asked" }
3399
+ models: { answer: "not-asked" },
3400
+ capabilities
1965
3401
  };
1966
3402
  },
1967
3403
  async status(profile) {
@@ -2000,32 +3436,11 @@ ${decoder.decode(loginResult.stderr)}`.trim();
2000
3436
  };
2001
3437
  },
2002
3438
  async findInput(input) {
2003
- return ask(input.profile, input.cwd, async (peer) => {
2004
- const seen = new Set;
2005
- let cursor;
2006
- for (let pageNumber = 0;pageNumber < MAX_HISTORY_PAGES; pageNumber += 1) {
2007
- const page = CodexTurnsPageSchema.parse(await peer.request("thread/turns/list", {
2008
- threadId: input.nativeThreadId,
2009
- limit: 50,
2010
- itemsView: "full",
2011
- ...cursor !== undefined && { cursor }
2012
- }));
2013
- if (page.data.some((turn) => turn.items.some((item) => item.type === "userMessage" && item.clientId === input.clientId))) {
2014
- return true;
2015
- }
2016
- const next = page.nextCursor;
2017
- if (next === null || next === undefined)
2018
- return false;
2019
- if (seen.has(next)) {
2020
- throw new Error(`Codex thread/turns/list repeated cursor ${JSON.stringify(next)} before history ended`);
2021
- }
2022
- seen.add(next);
2023
- cursor = next;
2024
- }
2025
- throw new Error(`Codex thread/turns/list exceeded ${MAX_HISTORY_PAGES} pages without reaching the end of history`);
2026
- }, FIND_INPUT_MAX_LINE_BYTES);
3439
+ return ask(input.profile, input.cwd, (peer) => findCodexClientInput(peer, input.nativeThreadId, input.clientId), FIND_INPUT_MAX_LINE_BYTES);
2027
3440
  },
2028
- open: (input) => openCodexSession(session(), input)
3441
+ open: (input) => openCodexSession(session(), input),
3442
+ connectControl: (input) => openCodexControlConnection(session(), input),
3443
+ openSharedServer: (input) => openCodexSharedServer(session(), capabilities, input)
2029
3444
  };
2030
3445
  }
2031
3446
  // src/agent-executor/codex/scenarios.ts
@@ -2114,6 +3529,7 @@ var codexFakeScenarios = {
2114
3529
  crash: () => steps(text("dying "), { do: "crash" })
2115
3530
  };
2116
3531
  export {
3532
+ CodexSkillInputSchema,
2117
3533
  CodexUnixSocketError,
2118
3534
  codexFakeScenarios,
2119
3535
  codexPlanWindows,