stitchkit 0.130.0 → 0.130.1

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 (37) hide show
  1. package/CHANGELOG.md +6 -0
  2. package/dist/agent-executor/codex/connect.d.ts +3 -1
  3. package/dist/agent-executor/codex/connect.d.ts.map +1 -1
  4. package/dist/agent-executor/codex/control-client.d.ts +44 -6
  5. package/dist/agent-executor/codex/control-client.d.ts.map +1 -1
  6. package/dist/agent-executor/codex/driver.d.ts +15 -5
  7. package/dist/agent-executor/codex/driver.d.ts.map +1 -1
  8. package/dist/agent-executor/codex/handlers.d.ts +7 -2
  9. package/dist/agent-executor/codex/handlers.d.ts.map +1 -1
  10. package/dist/agent-executor/codex/protocol.d.ts +4 -0
  11. package/dist/agent-executor/codex/protocol.d.ts.map +1 -1
  12. package/dist/agent-executor/codex/session-controls.d.ts +36 -13
  13. package/dist/agent-executor/codex/session-controls.d.ts.map +1 -1
  14. package/dist/agent-executor/codex/session.d.ts +5 -53
  15. package/dist/agent-executor/codex/session.d.ts.map +1 -1
  16. package/dist/agent-executor/codex/shared-server.d.ts +3 -1
  17. package/dist/agent-executor/codex/shared-server.d.ts.map +1 -1
  18. package/dist/agent-executor/codex/shared-thread.d.ts +3 -3
  19. package/dist/agent-executor/codex/shared-thread.d.ts.map +1 -1
  20. package/dist/agent-executor/codex/thread-controls.d.ts +19 -3
  21. package/dist/agent-executor/codex/thread-controls.d.ts.map +1 -1
  22. package/dist/agent-executor/codex/thread-open.d.ts +66 -0
  23. package/dist/agent-executor/codex/thread-open.d.ts.map +1 -0
  24. package/dist/agent-executor/codex/turn-input.d.ts +23 -6
  25. package/dist/agent-executor/codex/turn-input.d.ts.map +1 -1
  26. package/dist/agent-runtime/branch-observations.d.ts +18 -18
  27. package/dist/agent-runtime/sql-rows.d.ts +10 -10
  28. package/dist/agent-runtime/store-conformance-lifecycle.d.ts +20 -20
  29. package/dist/agent-runtime/store-conformance-support.d.ts +10 -10
  30. package/dist/agent-runtime/terminal-commit.d.ts +10 -10
  31. package/dist/entrypoints/agent-executor/codex.d.ts +5 -4
  32. package/dist/entrypoints/agent-executor/codex.d.ts.map +1 -1
  33. package/dist/entrypoints/agent-executor/codex.js +1475 -1222
  34. package/llms/agent-executor-codex.txt +8 -8
  35. package/llms-full.txt +8 -8
  36. package/llms.txt +1 -1
  37. package/package.json +1 -1
@@ -220,7 +220,11 @@ var CodexThreadContextSchema = z.object({
220
220
  approvalPolicy: z.json().optional(),
221
221
  sandbox: z.json().optional(),
222
222
  cwd: z.string().optional(),
223
- runtimeWorkspaceRoots: z.array(z.string()).readonly().optional()
223
+ runtimeWorkspaceRoots: z.array(z.string()).readonly().optional(),
224
+ thread: z.json().optional()
225
+ });
226
+ var CodexInitializeResponseSchema = z.looseObject({
227
+ userAgent: z.string().nullable().optional()
224
228
  });
225
229
  var CodexStartedThreadSchema = CodexThreadContextSchema.extend({
226
230
  thread: z.looseObject({ id: z.string().min(1) })
@@ -235,7 +239,8 @@ function extractCodexThreadContext(parsed) {
235
239
  ...parsed.cwd !== undefined && { cwd: parsed.cwd },
236
240
  ...parsed.runtimeWorkspaceRoots !== undefined && {
237
241
  runtimeWorkspaceRoots: parsed.runtimeWorkspaceRoots
238
- }
242
+ },
243
+ thread: safeJsonValue(parsed.thread)
239
244
  };
240
245
  }
241
246
  var CodexStartedTurnSchema = z.looseObject({
@@ -973,14 +978,16 @@ function validateCodexTransportAndArgs(config) {
973
978
  throw new TypeError(`[stitchkit] createCodexDriver: unsupported transport kind ${JSON.stringify(Reflect.get(Object(transport), "kind"))}`);
974
979
  }
975
980
  async function initializeCodexPeer(peer, version) {
976
- await peer.request("initialize", {
981
+ const reply = await peer.request("initialize", {
977
982
  clientInfo: { name: "stitchkit-agent-executor", version },
978
983
  capabilities: {
979
984
  experimentalApi: true,
980
985
  optOutNotificationMethods: CODEX_OPTED_OUT_NOTIFICATIONS
981
986
  }
982
987
  }, { timeoutMs: BOOTSTRAP_MS });
988
+ const parsed = CodexInitializeResponseSchema.parse(reply);
983
989
  peer.notify("initialized");
990
+ return nonEmptyString(parsed.userAgent);
984
991
  }
985
992
  function sleepAbortable(ms, signal) {
986
993
  if (signal.aborted)
@@ -1040,63 +1047,66 @@ async function dialWithEngineRace(input) {
1040
1047
  }
1041
1048
  });
1042
1049
  }
1050
+ async function connectCodexStdio(config, profile, cwd, extraArgs, signal, handlers, onEnd, onStartupPhase) {
1051
+ const env = engineEnvironment2(profile, config.ambient);
1052
+ let endedError;
1053
+ let ready = false;
1054
+ const peer = createJsonRpcPeer2({
1055
+ header: "omitted",
1056
+ requestTimeoutMs: REQUEST_MS,
1057
+ send: (line) => engine.send(line),
1058
+ ...handlers
1059
+ });
1060
+ const finishEnd = (error) => {
1061
+ if (endedError !== undefined)
1062
+ return;
1063
+ endedError = error;
1064
+ peer.close(error);
1065
+ if (ready)
1066
+ onEnd(error);
1067
+ };
1068
+ emitStartupPhase(onStartupPhase, "spawning");
1069
+ const engine = spawnEngineProcess2({
1070
+ executable: config.executable,
1071
+ args: [...config.prefix, "app-server", ...extraArgs],
1072
+ cwd,
1073
+ env,
1074
+ signal,
1075
+ ...config.maxFrameBytes !== undefined && { maxLineBytes: config.maxFrameBytes }
1076
+ });
1077
+ const reading = (async () => {
1078
+ try {
1079
+ for await (const line of engine.lines)
1080
+ peer.receive(line);
1081
+ finishEnd(new Error(`Codex app-server exited: ${engine.stderrTail().slice(-2000)}`));
1082
+ } catch (error) {
1083
+ const failed = error instanceof Error ? error : new Error(String(error));
1084
+ finishEnd(failed);
1085
+ await engine.stop().catch(() => {
1086
+ return;
1087
+ });
1088
+ }
1089
+ })();
1090
+ try {
1091
+ emitStartupPhase(onStartupPhase, "initializing");
1092
+ const userAgent = await initializeCodexPeer(peer, config.version);
1093
+ const providerPid = await engine.pidReady ?? engine.pid;
1094
+ if (endedError !== undefined)
1095
+ throw endedError;
1096
+ ready = true;
1097
+ return { engine, peer, reading, providerPid, userAgent };
1098
+ } catch (error) {
1099
+ await stopConnection({ engine, reading }, { error });
1100
+ throw error;
1101
+ }
1102
+ }
1043
1103
  async function connectCodex(config, profile, cwd, signal, handlers = {}, onEnd = () => {
1044
1104
  return;
1045
1105
  }, onStartupPhase) {
1046
1106
  const transport = config.transport ?? { kind: "stdio" };
1047
1107
  const extraArgs = config.serverArgs ?? [];
1048
1108
  if (transport.kind === "stdio") {
1049
- const env = engineEnvironment2(profile, config.ambient);
1050
- let endedError;
1051
- let ready = false;
1052
- const peer = createJsonRpcPeer2({
1053
- header: "omitted",
1054
- requestTimeoutMs: REQUEST_MS,
1055
- send: (line) => engine.send(line),
1056
- ...handlers
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");
1067
- const engine = spawnEngineProcess2({
1068
- executable: config.executable,
1069
- args: [...config.prefix, "app-server", ...extraArgs],
1070
- cwd,
1071
- env,
1072
- signal,
1073
- ...config.maxLineBytes !== undefined && { maxLineBytes: config.maxLineBytes }
1074
- });
1075
- const reading = (async () => {
1076
- try {
1077
- for await (const line of engine.lines)
1078
- peer.receive(line);
1079
- finishEnd(new Error(`Codex app-server exited: ${engine.stderrTail().slice(-2000)}`));
1080
- } catch (error) {
1081
- const failed = error instanceof Error ? error : new Error(String(error));
1082
- finishEnd(failed);
1083
- await engine.stop().catch(() => {
1084
- return;
1085
- });
1086
- }
1087
- })();
1088
- try {
1089
- emitStartupPhase(onStartupPhase, "initializing");
1090
- await initializeCodexPeer(peer, config.version);
1091
- const providerPid = await engine.pidReady ?? engine.pid;
1092
- if (endedError !== undefined)
1093
- throw endedError;
1094
- ready = true;
1095
- return { engine, peer, reading, providerPid };
1096
- } catch (error) {
1097
- await stopConnection({ engine, reading }, { error });
1098
- throw error;
1099
- }
1109
+ return connectCodexStdio(config, profile, cwd, extraArgs, signal, handlers, onEnd, onStartupPhase);
1100
1110
  }
1101
1111
  let wsClient;
1102
1112
  let spawnedEngine;
@@ -1155,13 +1165,13 @@ async function connectCodex(config, profile, cwd, signal, handlers = {}, onEnd =
1155
1165
  env,
1156
1166
  signal,
1157
1167
  stdoutMode: "drain",
1158
- ...config.maxLineBytes !== undefined && { maxLineBytes: config.maxLineBytes }
1168
+ ...config.maxFrameBytes !== undefined && { maxLineBytes: config.maxFrameBytes }
1159
1169
  });
1160
1170
  try {
1161
1171
  wsClient = await dialWithEngineRace({
1162
1172
  socketPath: transport.socketPath,
1163
1173
  listenTimeoutMs: transport.listenTimeoutMs ?? DEFAULT_LISTEN_TIMEOUT_MS,
1164
- ...config.maxLineBytes !== undefined && { maxFrameBytes: config.maxLineBytes },
1174
+ ...config.maxFrameBytes !== undefined && { maxFrameBytes: config.maxFrameBytes },
1165
1175
  signal,
1166
1176
  engine: spawnedEngine,
1167
1177
  onMessage,
@@ -1182,7 +1192,7 @@ async function connectCodex(config, profile, cwd, signal, handlers = {}, onEnd =
1182
1192
  expectedOwnerUid: transport.expectedOwnerUid
1183
1193
  },
1184
1194
  signal,
1185
- ...config.maxLineBytes !== undefined && { maxFrameBytes: config.maxLineBytes },
1195
+ ...config.maxFrameBytes !== undefined && { maxFrameBytes: config.maxFrameBytes },
1186
1196
  onMessage,
1187
1197
  onClose
1188
1198
  });
@@ -1207,14 +1217,14 @@ async function connectCodex(config, profile, cwd, signal, handlers = {}, onEnd =
1207
1217
  if (endedError !== undefined)
1208
1218
  throw endedError;
1209
1219
  emitStartupPhase(onStartupPhase, "initializing");
1210
- await initializeCodexPeer(peer, config.version);
1220
+ const userAgent = await initializeCodexPeer(peer, config.version);
1211
1221
  if (endedError !== undefined)
1212
1222
  throw endedError;
1213
1223
  const providerPid = spawnedEngine !== undefined ? await spawnedEngine.pidReady ?? spawnedEngine.pid : undefined;
1214
1224
  if (endedError !== undefined)
1215
1225
  throw endedError;
1216
1226
  ready = true;
1217
- return { engine: compositeEngine, peer, reading, providerPid };
1227
+ return { engine: compositeEngine, peer, reading, providerPid, userAgent };
1218
1228
  } catch (error) {
1219
1229
  await stopConnection({ engine: compositeEngine, reading }, { error });
1220
1230
  throw error;
@@ -1334,6 +1344,13 @@ function assertOptionalNonEmptyString(value, field, caller) {
1334
1344
  throw new TypeError(`[stitchkit] ${caller}: ${field} must be a non-empty string`);
1335
1345
  }
1336
1346
  }
1347
+ function assertOptionalNonEmptyNoNulString(value, field, caller) {
1348
+ if (value === undefined)
1349
+ return;
1350
+ if (typeof value !== "string" || value.trim().length === 0 || value.includes("\x00")) {
1351
+ throw new TypeError(`[stitchkit] ${caller}: ${field} must be a non-empty string without NUL bytes`);
1352
+ }
1353
+ }
1337
1354
  function assertOptionalLimit(limit, caller) {
1338
1355
  if (limit === undefined || limit === null)
1339
1356
  return;
@@ -1423,7 +1440,7 @@ function buildListThreadsPayload(params) {
1423
1440
  ...params?.useStateDbOnly !== undefined && { useStateDbOnly: params.useStateDbOnly }
1424
1441
  };
1425
1442
  }
1426
- function createCodexThreadControlMethods(call) {
1443
+ function createCodexThreadControlMethods(call, options = {}) {
1427
1444
  return {
1428
1445
  async revertThread(params) {
1429
1446
  const threadId = assertNonEmptyThreadId(params.threadId, "CodexControlClient.revertThread");
@@ -1480,1121 +1497,547 @@ function createCodexThreadControlMethods(call) {
1480
1497
  const threadId = assertNonEmptyThreadId(params.threadId, caller);
1481
1498
  const name = assertRequiredNonEmptyString(params.name, "name", caller);
1482
1499
  return call("thread/name/set", { threadId, name });
1500
+ },
1501
+ async interruptTurn(params) {
1502
+ options.ensureAlive?.();
1503
+ const caller = "CodexControlClient.interruptTurn";
1504
+ const threadId = assertNonEmptyThreadId(params.threadId, caller);
1505
+ const turnId = assertRequiredNonEmptyString(params.turnId, "turnId", caller);
1506
+ options.onBeforeInterruptTurn?.(threadId, turnId);
1507
+ await call("turn/interrupt", { threadId, turnId });
1508
+ },
1509
+ async compactThread(params) {
1510
+ const threadId = assertNonEmptyThreadId(params.threadId, "CodexControlClient.compactThread");
1511
+ await call("thread/compact/start", { threadId });
1483
1512
  }
1484
1513
  };
1485
1514
  }
1486
1515
 
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`);
1516
+ // src/agent-executor/codex/request-answers.ts
1517
+ function isKnownCodexRequestMethod(method) {
1518
+ return CODEX_APPROVAL_REQUESTS.has(method) || method === CODEX_PERMISSIONS_APPROVAL_REQUEST || method === CODEX_INPUT_REQUEST || method === CODEX_ELICITATION_REQUEST;
1519
+ }
1520
+ function externalCodexTurnIdOf(params) {
1521
+ if (typeof params !== "object" || params === null)
1522
+ return "external";
1523
+ const direct = nonEmptyString(Reflect.get(params, "turnId"));
1524
+ if (direct !== undefined)
1525
+ return direct;
1526
+ const turn = Reflect.get(params, "turn");
1527
+ if (typeof turn === "object" && turn !== null) {
1528
+ const nested = nonEmptyString(Reflect.get(turn, "id"));
1529
+ if (nested !== undefined)
1530
+ return nested;
1499
1531
  }
1532
+ return "external";
1500
1533
  }
1501
- function createCodexControlClient(input) {
1502
- const call = async (method, params) => {
1503
- input.ensureAlive();
1504
- return input.peer.request(method, params);
1534
+ function parseCodexApprovalRequest(method, params) {
1535
+ const asked = CodexApprovalParamsSchema.parse(params);
1536
+ const callId = nonEmptyString(asked.itemId);
1537
+ const metadata = {};
1538
+ if (typeof asked.command === "string")
1539
+ metadata.command = asked.command;
1540
+ if (typeof asked.cwd === "string")
1541
+ metadata.cwd = asked.cwd;
1542
+ if (typeof asked.reason === "string")
1543
+ metadata.reason = asked.reason;
1544
+ if (typeof asked.grantRoot === "string")
1545
+ metadata.grantRoot = asked.grantRoot;
1546
+ if (typeof asked.kind === "string")
1547
+ metadata.kind = asked.kind;
1548
+ if (typeof asked.approvalId === "string")
1549
+ metadata.approvalId = asked.approvalId;
1550
+ if (asked.commandActions != null)
1551
+ metadata.commandActions = asked.commandActions;
1552
+ if (asked.availableDecisions != null)
1553
+ metadata.availableDecisions = asked.availableDecisions;
1554
+ const input = Object.keys(metadata).length > 0 ? safeJsonValue(metadata) : undefined;
1555
+ const detail = {
1556
+ method,
1557
+ ...typeof asked.kind === "string" && { kind: asked.kind },
1558
+ ...Array.isArray(asked.availableDecisions) && {
1559
+ availableDecisions: asked.availableDecisions
1560
+ }
1505
1561
  };
1506
1562
  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");
1563
+ detail,
1564
+ deltaFields: {
1565
+ ...callId !== undefined && { callId },
1566
+ ...typeof asked.command === "string" && { prompt: asked.command },
1567
+ ...input !== undefined && { input }
1568
+ }
1569
+ };
1570
+ }
1571
+ function parseCodexInputRequest(params) {
1572
+ const asked = CodexUserInputParamsSchema.parse(params);
1573
+ const callId = nonEmptyString(asked.itemId);
1574
+ const questions = asked.questions.map((question) => ({
1575
+ id: question.id,
1576
+ header: question.header,
1577
+ question: question.question,
1578
+ ...question.options !== undefined && {
1579
+ options: question.options === null ? null : question.options.map((option) => ({
1580
+ label: option.label,
1581
+ description: option.description
1582
+ }))
1580
1583
  },
1581
- ...createCodexThreadControlMethods(call)
1584
+ ...question.isOther !== undefined && { isOther: question.isOther },
1585
+ ...question.isSecret !== undefined && { isSecret: question.isSecret }
1586
+ }));
1587
+ const detail = { method: CODEX_INPUT_REQUEST };
1588
+ return {
1589
+ detail,
1590
+ deltaFields: {
1591
+ ...callId !== undefined && { callId },
1592
+ input: safeJsonValue(questions)
1593
+ }
1582
1594
  };
1583
1595
  }
1584
- function bindCodexSessionThreadControls(controlClient, threadId) {
1596
+ function parseCodexPermissionsRequest(params) {
1597
+ const asked = CodexPermissionsApprovalParamsSchema.parse(params);
1598
+ const callId = nonEmptyString(asked.itemId);
1599
+ const permissions = safeJsonValue(asked.permissions);
1600
+ const metadata = {
1601
+ threadId: asked.threadId,
1602
+ turnId: asked.turnId,
1603
+ cwd: asked.cwd,
1604
+ permissions,
1605
+ startedAtMs: asked.startedAtMs
1606
+ };
1607
+ if (typeof asked.reason === "string")
1608
+ metadata.reason = asked.reason;
1609
+ if (typeof asked.environmentId === "string")
1610
+ metadata.environmentId = asked.environmentId;
1611
+ const detail = {
1612
+ method: CODEX_PERMISSIONS_APPROVAL_REQUEST,
1613
+ permissions
1614
+ };
1585
1615
  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
- });
1616
+ detail,
1617
+ deltaFields: {
1618
+ ...callId !== undefined && { callId },
1619
+ ...typeof asked.reason === "string" && { prompt: asked.reason },
1620
+ input: safeJsonValue(metadata)
1642
1621
  }
1643
1622
  };
1644
1623
  }
1645
-
1646
- // src/agent-executor/codex/classify.ts
1647
- var raw = (type) => ({ source: "codex", type });
1648
- var CODEX_TOOL_ITEMS = new Set([
1649
- "commandExecution",
1650
- "fileChange",
1651
- "mcpToolCall",
1652
- "dynamicToolCall",
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"
1665
- ]);
1666
- var CODEX_CONTENT_ITEMS = new Set([
1667
- "agentMessage",
1668
- "reasoning",
1669
- "userMessage",
1670
- "plan",
1671
- "contextCompaction",
1672
- "hookPrompt",
1673
- "subAgentActivity",
1674
- "enteredReviewMode",
1675
- "exitedReviewMode"
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;
1706
- function toolName(item) {
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;
1624
+ function parseCodexElicitationRequest(params) {
1625
+ const asked = CodexMcpElicitationParamsSchema.parse(params);
1626
+ const toolName = nonEmptyString(asked.serverName);
1627
+ const callId = asked.mode === "url" ? nonEmptyString(asked.elicitationId) : undefined;
1628
+ const metadata = {
1629
+ serverName: asked.serverName,
1630
+ threadId: asked.threadId,
1631
+ mode: asked.mode,
1632
+ message: asked.message
1633
+ };
1634
+ if (asked.turnId !== undefined)
1635
+ metadata.turnId = asked.turnId;
1636
+ if (asked.environmentId !== undefined)
1637
+ metadata.environmentId = asked.environmentId;
1638
+ if (asked._meta !== undefined)
1639
+ metadata._meta = asked._meta;
1640
+ if (asked.mode === "url") {
1641
+ metadata.elicitationId = asked.elicitationId;
1642
+ metadata.url = asked.url;
1643
+ } else {
1644
+ metadata.requestedSchema = asked.requestedSchema;
1712
1645
  }
1713
- return item.type;
1714
- }
1715
- function toolInput(item) {
1716
- const { id: _id, type: _type, status: _status, aggregatedOutput: _output, ...rest } = item;
1717
- return safeJsonValue(rest);
1646
+ const detail = {
1647
+ method: CODEX_ELICITATION_REQUEST,
1648
+ elicitationMode: asked.mode
1649
+ };
1650
+ return {
1651
+ detail,
1652
+ deltaFields: {
1653
+ ...callId !== undefined && { callId },
1654
+ ...toolName !== undefined && { toolName },
1655
+ prompt: asked.message,
1656
+ input: safeJsonValue(metadata)
1657
+ }
1658
+ };
1718
1659
  }
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]);
1660
+ function parseCodexServerRequest(method, params) {
1661
+ if (CODEX_APPROVAL_REQUESTS.has(method)) {
1662
+ return { kind: "approval", ...parseCodexApprovalRequest(method, params) };
1725
1663
  }
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;
1664
+ if (method === CODEX_PERMISSIONS_APPROVAL_REQUEST) {
1665
+ return { kind: "approval", ...parseCodexPermissionsRequest(params) };
1734
1666
  }
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);
1667
+ if (method === CODEX_ELICITATION_REQUEST) {
1668
+ return { kind: "input", ...parseCodexElicitationRequest(params) };
1742
1669
  }
1670
+ return { kind: "input", ...parseCodexInputRequest(params) };
1743
1671
  }
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;
1672
+ function codexStoppedAnswer(method) {
1673
+ if (CODEX_APPROVAL_REQUESTS.has(method)) {
1674
+ return { decision: CODEX_APPROVAL_DECISION.interrupted };
1753
1675
  }
1754
- if (infoSummary !== undefined) {
1755
- return `Codex ended the turn ${turn.status} (${infoSummary})`;
1676
+ if (method === CODEX_PERMISSIONS_APPROVAL_REQUEST) {
1677
+ return { permissions: {} };
1756
1678
  }
1757
- return `Codex ended the turn ${turn.status}`;
1758
- }
1759
- function httpStatusOf(value, depth = 0) {
1760
- if (depth > 3 || typeof value !== "object" || value === null)
1761
- return;
1762
- const direct = Reflect.get(value, "httpStatusCode");
1763
- if (typeof direct === "number")
1764
- return direct;
1765
- for (const nested of Object.values(value)) {
1766
- const found = httpStatusOf(nested, depth + 1);
1767
- if (found !== undefined)
1768
- return found;
1679
+ if (method === CODEX_ELICITATION_REQUEST) {
1680
+ return { action: "cancel" };
1769
1681
  }
1770
- return;
1771
- }
1772
- function failureKind(info) {
1773
- if (info === "unauthorized")
1774
- return "authRequired";
1775
- if (info === "usageLimitExceeded" || info === "rateLimitExceeded" || info === "sessionBudgetExceeded")
1776
- return "rateLimited";
1777
- const status = httpStatusOf(info);
1778
- if (status === 401 || status === 403)
1779
- return "authRequired";
1780
- if (status === 429)
1781
- return "rateLimited";
1782
- return "restartRecommended";
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;
1682
+ return { answers: {} };
1802
1683
  }
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
- }
1831
- function classifyCodexNotification(method, params, state) {
1832
- const base = { turnId: state.turnId };
1833
- switch (method) {
1834
- case "item/agentMessage/delta": {
1835
- const p = CodexNotificationParams[method].parse(params);
1836
- return {
1837
- kind: "deltas",
1838
- deltas: [{ type: "text", ...base, itemId: p.itemId, raw: raw(method), text: p.delta }]
1839
- };
1684
+ var codexStopped = (waiting) => codexStoppedAnswer(waiting.detail.method);
1685
+ function buildCodexRequestAnswer(detail, rawReply) {
1686
+ const reply = InteractionReplySchema2.shape.reply.parse(rawReply);
1687
+ if (CODEX_APPROVAL_REQUESTS.has(detail.method)) {
1688
+ if (reply.kind === "input") {
1689
+ throw new TypeError("A Codex approval is approved or denied, not answered with input");
1840
1690
  }
1841
- case "item/reasoning/textDelta":
1842
- case "item/reasoning/summaryTextDelta": {
1843
- const p = CodexNotificationParams[method].parse(params);
1844
- return {
1845
- kind: "deltas",
1846
- deltas: [
1847
- { type: "reasoning", ...base, itemId: p.itemId, raw: raw(method), text: p.delta }
1848
- ]
1849
- };
1691
+ if (reply.kind === "approve" && reply.updatedInput !== undefined) {
1692
+ throw new TypeError("Codex approval requests do not support updatedInput");
1850
1693
  }
1851
- case "item/started":
1852
- case "item/completed": {
1853
- const { item } = CodexNotificationParams[method].parse(params);
1854
- if (CODEX_CONTENT_ITEMS.has(item.type))
1855
- return { kind: "ignore", reason: `${method} ${item.type}` };
1856
- if (!CODEX_TOOL_ITEMS.has(item.type)) {
1857
- return {
1858
- kind: "unhandled",
1859
- delta: {
1860
- type: "error",
1861
- ...base,
1862
- itemId: `unhandled:${item.id}`,
1863
- raw: raw(`${method}/${item.type}`),
1864
- kind: "unhandled",
1865
- message: `Codex item ${item.type} is not known to this driver`
1866
- }
1867
- };
1694
+ const decision = reply.kind === "approve" ? reply.scope === "session" ? CODEX_APPROVAL_DECISION.approveForSession : CODEX_APPROVAL_DECISION.approve : reply.interrupt === true ? CODEX_APPROVAL_DECISION.interrupted : CODEX_APPROVAL_DECISION.deny;
1695
+ if (detail.kind === "humanCommand" && decision === CODEX_APPROVAL_DECISION.approveForSession) {
1696
+ throw new TypeError("Codex humanCommand approval does not allow acceptForSession");
1697
+ }
1698
+ if (detail.availableDecisions !== undefined) {
1699
+ const allowed = detail.availableDecisions.some((entry) => entry === decision);
1700
+ if (!allowed) {
1701
+ throw new TypeError(`Codex approval request does not offer decision ${JSON.stringify(decision)}`);
1868
1702
  }
1869
- if (method === "item/started") {
1870
- return {
1871
- kind: "deltas",
1872
- deltas: [
1873
- {
1874
- type: "tool-call",
1875
- ...base,
1876
- itemId: `call:${item.id}`,
1877
- raw: raw(method),
1878
- callId: item.id,
1879
- toolName: toolName(item),
1880
- input: toolInput(item)
1881
- }
1882
- ]
1883
- };
1703
+ }
1704
+ return { decision };
1705
+ }
1706
+ if (detail.method === CODEX_PERMISSIONS_APPROVAL_REQUEST) {
1707
+ if (reply.kind === "input") {
1708
+ throw new TypeError("A Codex permissions approval is approved or denied, not answered with input");
1709
+ }
1710
+ if (reply.kind === "approve") {
1711
+ if (reply.updatedInput !== undefined) {
1712
+ throw new TypeError("Codex permissions approval requests do not support updatedInput");
1884
1713
  }
1885
- const status = Reflect.get(item, "status");
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";
1890
1714
  return {
1891
- kind: "deltas",
1892
- deltas: [
1893
- {
1894
- type: "tool-result",
1895
- ...base,
1896
- itemId: `result:${item.id}`,
1897
- raw: raw(method),
1898
- callId: item.id,
1899
- toolName: toolName(item),
1900
- outcome,
1901
- ...output !== undefined && output !== null && {
1902
- output: safeJsonValue(output)
1903
- }
1904
- }
1905
- ]
1715
+ permissions: detail.permissions ?? {},
1716
+ scope: reply.scope === "session" ? "session" : "turn"
1906
1717
  };
1907
1718
  }
1908
- case "turn/completed": {
1909
- const { turn } = CodexNotificationParams[method].parse(params);
1910
- const outcome = state.interruptRequested ? "interrupted" : turn.status === "completed" ? "completed" : turn.status === "interrupted" ? "interrupted" : "failed";
1911
- const deltas = [];
1912
- if (outcome === "failed") {
1913
- deltas.push({
1914
- type: "error",
1915
- ...base,
1916
- itemId: "failure",
1917
- raw: raw(method),
1918
- kind: failureKind(turn.error?.codexErrorInfo),
1919
- message: codexFailureMessage(turn)
1920
- });
1921
- }
1922
- deltas.push({ type: "turn-end", ...base, itemId: "end", raw: raw(method), outcome });
1923
- return { kind: "end", deltas, outcome };
1719
+ if (reply.interrupt === true) {
1720
+ throw new TypeError("Codex permissions approval requests do not support interrupt on deny");
1924
1721
  }
1925
- case "thread/tokenUsage/updated":
1926
- return classifyCodexTokenUsage(params, base);
1927
- case "serverRequest/resolved":
1928
- return {
1929
- kind: "resolved",
1930
- requestId: String(CodexNotificationParams[method].parse(params).requestId)
1931
- };
1932
- case "account/rateLimits/updated": {
1933
- const parsed = CodexNotificationParams[method].parse(params);
1934
- return {
1935
- kind: "limits",
1936
- rateLimits: parsed.rateLimitsByLimitId !== undefined ? {
1937
- rateLimits: parsed.rateLimits,
1938
- rateLimitsByLimitId: parsed.rateLimitsByLimitId
1939
- } : parsed.rateLimits
1940
- };
1722
+ return { permissions: {} };
1723
+ }
1724
+ if (detail.method === CODEX_ELICITATION_REQUEST) {
1725
+ if (reply.kind === "approve") {
1726
+ throw new TypeError("A Codex MCP elicitation request is answered with input or deny, not approve");
1941
1727
  }
1942
- default:
1943
- if (CODEX_QUIET_NOTIFICATIONS.has(method))
1944
- return { kind: "ignore", reason: method };
1728
+ if (reply.kind === "deny") {
1945
1729
  return {
1946
- kind: "unhandled",
1947
- delta: {
1948
- type: "error",
1949
- ...base,
1950
- itemId: `unhandled:${method}`,
1951
- raw: raw(method),
1952
- kind: "unhandled",
1953
- message: `Codex notification ${method} is not known to this driver`
1954
- }
1730
+ action: detail.elicitationMode === "url" || reply.interrupt === true ? "cancel" : "decline"
1955
1731
  };
1732
+ }
1733
+ const parsed = CodexMcpElicitationAnswerSchema.parse(reply.value);
1734
+ return {
1735
+ action: parsed.action,
1736
+ ...parsed.content !== undefined && { content: parsed.content },
1737
+ ...parsed._meta !== undefined && { _meta: parsed._meta }
1738
+ };
1739
+ }
1740
+ if (reply.kind !== "input") {
1741
+ throw new TypeError("A Codex input request is answered with input");
1956
1742
  }
1743
+ return { answers: CodexUserInputAnswersSchema.parse(reply.value) };
1957
1744
  }
1958
-
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;
1745
+ function answerActiveCodexTurnRequest(turn, interactionId, rawReply) {
1746
+ const waiting = turn.pending.get(interactionId);
1747
+ if (waiting === undefined) {
1748
+ throw new TypeError(`Unknown interaction ${interactionId} for this turn`);
1749
+ }
1750
+ const answer = buildCodexRequestAnswer(waiting.detail, rawReply);
1751
+ answerEngineRequest(turn, interactionId, answer);
1962
1752
  }
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;
1753
+ function answerCodexSessionRequest(input) {
1754
+ if (input.turn?.pending.has(input.interactionId)) {
1755
+ answerActiveCodexTurnRequest(input.turn, input.interactionId, input.reply);
1756
+ return;
1974
1757
  }
1975
- return "external";
1758
+ const external = input.externalPending.get(input.interactionId);
1759
+ if (external === undefined || input.expectedEntry !== undefined && external !== input.expectedEntry) {
1760
+ throw new TypeError(`Unknown interaction ${input.interactionId} for this Codex connection`);
1761
+ }
1762
+ const answer = buildCodexRequestAnswer(external.detail, input.reply);
1763
+ input.externalPending.delete(input.interactionId);
1764
+ external.resolve(answer);
1976
1765
  }
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
1766
+
1767
+ // src/agent-executor/codex/turn-input.ts
1768
+ import { isAbsolute } from "node:path";
1769
+ import { z as z3 } from "zod";
1770
+ var NonEmptyNoNulStringSchema = z3.string().min(1).refine((value) => value.trim().length > 0 && !value.includes("\x00"), {
1771
+ message: "must be a non-empty string without NUL bytes"
1772
+ });
1773
+ var AbsolutePathNoNulSchema = z3.string().min(1).refine((value) => value.trim().length > 0 && !value.includes("\x00") && isAbsolute(value), {
1774
+ message: "must be an absolute path without NUL bytes"
1775
+ });
1776
+ var CodexSkillInputSchema = z3.strictObject({
1777
+ type: z3.literal("skill"),
1778
+ name: NonEmptyNoNulStringSchema,
1779
+ path: NonEmptyNoNulStringSchema
1780
+ });
1781
+ var CodexLocalImageInputSchema = z3.strictObject({
1782
+ type: z3.literal("localImage"),
1783
+ path: AbsolutePathNoNulSchema
1784
+ });
1785
+ function validateCodexExtraInput(part) {
1786
+ if (part.type === "skill") {
1787
+ const parsed = CodexSkillInputSchema.safeParse(part);
1788
+ if (!parsed.success) {
1789
+ throw new TypeError("Codex skill input name and path must be non-empty strings without NUL bytes");
2003
1790
  }
2004
- };
2005
- return {
2006
- detail,
2007
- deltaFields: {
2008
- ...callId !== undefined && { callId },
2009
- ...typeof asked.command === "string" && { prompt: asked.command },
2010
- ...input !== undefined && { input }
2011
- }
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)
1791
+ return { type: "skill", name: parsed.data.name, path: parsed.data.path };
1792
+ }
1793
+ if (part.type === "localImage") {
1794
+ const parsed = CodexLocalImageInputSchema.safeParse(part);
1795
+ if (!parsed.success) {
1796
+ throw new TypeError("Codex localImage input path must be an absolute path without NUL bytes");
2036
1797
  }
2037
- };
1798
+ return { type: "localImage", path: parsed.data.path };
1799
+ }
1800
+ return;
2038
1801
  }
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
- };
1802
+ function inlineCodexParts(parts, options) {
1803
+ return inlineOrderedParts(parts, {
1804
+ ...options,
1805
+ acceptedDescription: "text, images, local images, and skills",
1806
+ validateExtra: validateCodexExtraInput
1807
+ });
2066
1808
  }
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;
1809
+ function codexTurnInput(parts) {
1810
+ if (parts.every((part) => part.type === "text")) {
1811
+ return [
1812
+ { type: "text", text: parts.map((part) => part.text).join(`
1813
+ `), text_elements: [] }
1814
+ ];
2088
1815
  }
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)
1816
+ const out = [];
1817
+ for (const part of parts) {
1818
+ if (part.type === "text") {
1819
+ out.push({ type: "text", text: part.text, text_elements: [] });
1820
+ } else if (part.type === "skill") {
1821
+ out.push({ type: "skill", name: part.name, path: part.path });
1822
+ } else if (part.type === "localImage") {
1823
+ out.push({ type: "localImage", path: part.path });
1824
+ } else {
1825
+ out.push({ type: "image", url: `data:${part.mediaType};base64,${part.base64}` });
2100
1826
  }
2101
- };
2102
- }
2103
- function parseCodexServerRequest(method, params) {
2104
- if (CODEX_APPROVAL_REQUESTS.has(method)) {
2105
- return { kind: "approval", ...parseCodexApprovalRequest(method, params) };
2106
1827
  }
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) };
1828
+ return out;
2114
1829
  }
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" };
1830
+ async function sendCodexTurnSteer(peer, params) {
1831
+ const steered = CodexTurnSteerResponseSchema.parse(await peer.request("turn/steer", {
1832
+ threadId: params.threadId,
1833
+ expectedTurnId: params.expectedTurnId,
1834
+ input: codexTurnInput(params.parts),
1835
+ ...params.clientId !== undefined && { clientUserMessageId: params.clientId }
1836
+ }));
1837
+ return { turnId: steered.turnId };
1838
+ }
1839
+
1840
+ // src/agent-executor/codex/session-controls.ts
1841
+ function validateCodexForkBounds(options, caller) {
1842
+ if (options.beforeTurnId !== undefined && options.lastTurnId !== undefined) {
1843
+ throw new TypeError(`[stitchkit] ${caller}: beforeTurnId and lastTurnId are mutually exclusive`);
2124
1844
  }
2125
- return { answers: {} };
2126
1845
  }
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");
1846
+ function validateCodexPolicyOverrides(overrides, caller) {
1847
+ if (overrides.runtimeWorkspaceRoots !== undefined) {
1848
+ if (!Array.isArray(overrides.runtimeWorkspaceRoots)) {
1849
+ throw new TypeError(`[stitchkit] ${caller}: runtimeWorkspaceRoots must be an array of strings`);
2140
1850
  }
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)}`);
1851
+ for (const root of overrides.runtimeWorkspaceRoots) {
1852
+ if (typeof root !== "string" || root.trim().length === 0) {
1853
+ throw new TypeError(`[stitchkit] ${caller}: every runtimeWorkspaceRoots entry must be a non-empty string`);
2145
1854
  }
2146
1855
  }
2147
- return { decision };
2148
1856
  }
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");
1857
+ if (overrides.config !== undefined) {
1858
+ if (typeof overrides.config !== "object" || overrides.config === null || Array.isArray(overrides.config)) {
1859
+ throw new TypeError(`[stitchkit] ${caller}: config must be a plain JSON object`);
2164
1860
  }
2165
- return { permissions: {} };
1861
+ safeJsonValue(overrides.config);
2166
1862
  }
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
- };
1863
+ }
1864
+ function buildCodexThreadPolicyParams(base, overrides) {
1865
+ const mergedConfig = base.config !== undefined || overrides?.config !== undefined ? { ...base.config ?? {}, ...overrides?.config ?? {} } : undefined;
1866
+ const merged = {
1867
+ ...base,
1868
+ ...overrides,
1869
+ ...mergedConfig !== undefined && { config: mergedConfig }
1870
+ };
1871
+ validateCodexPolicyOverrides(merged, "CodexSession");
1872
+ const params = {};
1873
+ if (merged.model !== undefined)
1874
+ params.model = merged.model;
1875
+ if (merged.modelProvider !== undefined)
1876
+ params.modelProvider = merged.modelProvider;
1877
+ if (merged.approvalPolicy !== undefined)
1878
+ params.approvalPolicy = safeJsonValue(merged.approvalPolicy);
1879
+ if (merged.sandbox !== undefined)
1880
+ params.sandbox = merged.sandbox;
1881
+ if (merged.developerInstructions !== undefined)
1882
+ params.developerInstructions = merged.developerInstructions;
1883
+ if (merged.runtimeWorkspaceRoots !== undefined)
1884
+ params.runtimeWorkspaceRoots = [...merged.runtimeWorkspaceRoots];
1885
+ if (merged.config !== undefined)
1886
+ params.config = safeJsonValue(merged.config);
1887
+ return params;
1888
+ }
1889
+ function validateCodexTurnStartOverrides(turnInput, activeModelProvider) {
1890
+ assertOptionalNonEmptyNoNulString(turnInput.cwd, "cwd", "CodexSession.startTurn");
1891
+ if (turnInput.modelProvider !== undefined) {
1892
+ if (activeModelProvider === undefined || turnInput.modelProvider !== activeModelProvider) {
1893
+ throw new TypeError(`Codex turn/start cannot switch modelProvider to ${JSON.stringify(turnInput.modelProvider)} (thread active provider is ${JSON.stringify(activeModelProvider ?? "unknown")})`);
2175
1894
  }
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
1895
  }
2183
- if (reply.kind !== "input") {
2184
- throw new TypeError("A Codex input request is answered with input");
1896
+ if (turnInput.collaborationMode !== undefined) {
1897
+ CodexCollaborationModeSchema.parse(turnInput.collaborationMode);
2185
1898
  }
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`);
1899
+ if (turnInput.approvalPolicy !== undefined) {
1900
+ safeJsonValue(turnInput.approvalPolicy);
2192
1901
  }
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;
1902
+ if (turnInput.sandboxPolicy !== undefined) {
1903
+ safeJsonValue(turnInput.sandboxPolicy);
2200
1904
  }
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`);
1905
+ if (turnInput.runtimeWorkspaceRoots !== undefined) {
1906
+ validateCodexPolicyOverrides({ runtimeWorkspaceRoots: turnInput.runtimeWorkspaceRoots }, "CodexSession.startTurn");
2204
1907
  }
2205
- const answer = buildCodexRequestAnswer(external.detail, input.reply);
2206
- input.externalPending.delete(input.interactionId);
2207
- external.resolve(answer);
2208
1908
  }
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
- });
1909
+ function buildCodexTurnStartParams(threadId, turnInput, parts, activeModelProvider) {
1910
+ validateCodexTurnStartOverrides(turnInput, activeModelProvider);
1911
+ const params = {
1912
+ threadId,
1913
+ input: codexTurnInput(parts),
1914
+ clientUserMessageId: turnInput.clientId
1915
+ };
1916
+ if (turnInput.cwd !== undefined)
1917
+ params.cwd = turnInput.cwd;
1918
+ if (turnInput.model !== undefined)
1919
+ params.model = turnInput.model;
1920
+ if (turnInput.reasoningEffort !== undefined)
1921
+ params.effort = turnInput.reasoningEffort;
1922
+ if (turnInput.collaborationMode !== undefined) {
1923
+ params.collaborationMode = CodexCollaborationModeSchema.parse(turnInput.collaborationMode);
2336
1924
  }
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`);
1925
+ if (turnInput.approvalPolicy !== undefined) {
1926
+ params.approvalPolicy = safeJsonValue(turnInput.approvalPolicy);
2340
1927
  }
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})`);
1928
+ if (turnInput.sandboxPolicy !== undefined) {
1929
+ params.sandboxPolicy = safeJsonValue(turnInput.sandboxPolicy);
2343
1930
  }
2344
- if (state.externalPending.has(interactionId)) {
2345
- throw new JsonRpcError2(JSON_RPC_INTERNAL_ERROR, `Duplicate pending external Codex server request ${interactionId}`);
1931
+ if (turnInput.runtimeWorkspaceRoots !== undefined) {
1932
+ params.runtimeWorkspaceRoots = [...turnInput.runtimeWorkspaceRoots];
2346
1933
  }
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
- });
1934
+ return params;
1935
+ }
1936
+ function createCodexSessionMutators(input) {
1937
+ return {
1938
+ async steerTurn(steerInput) {
1939
+ input.ensureAlive();
1940
+ const caller = "CodexSession.steerTurn";
1941
+ const targetThreadId = steerInput.threadId === undefined ? input.threadId : assertNonEmptyThreadId(steerInput.threadId, caller);
1942
+ assertOptionalNonEmptyString(steerInput.clientId, "clientId", caller);
1943
+ assertOptionalNonEmptyString(steerInput.expectedTurnId, "expectedTurnId", caller);
1944
+ if (targetThreadId !== input.threadId) {
1945
+ const expectedTurnId = assertRequiredNonEmptyString(steerInput.expectedTurnId, "expectedTurnId", caller);
1946
+ const parts = await inlineCodexParts(steerInput.input, {
1947
+ ...input.imageOptions,
1948
+ driverLabel: "The Codex driver",
1949
+ signal: input.signal
1950
+ });
1951
+ input.ensureAlive();
1952
+ return sendCodexTurnSteer(input.peer, {
1953
+ threadId: targetThreadId,
1954
+ expectedTurnId,
1955
+ parts,
1956
+ ...steerInput.clientId !== undefined && { clientId: steerInput.clientId }
1957
+ });
1958
+ }
1959
+ const active = input.getActiveTurn();
1960
+ let expectedTurnId;
1961
+ if (active !== undefined) {
1962
+ if (active.codexTurnId === undefined) {
1963
+ throw new Error("Cannot steer turn: no Codex turn is currently running");
2382
1964
  }
1965
+ if (steerInput.expectedTurnId !== undefined && steerInput.expectedTurnId !== active.codexTurnId) {
1966
+ throw new TypeError(`Expected active Codex turn ${steerInput.expectedTurnId}, but current turn is ${active.codexTurnId}`);
1967
+ }
1968
+ expectedTurnId = active.codexTurnId;
1969
+ } else {
1970
+ if (steerInput.expectedTurnId === undefined) {
1971
+ throw new Error("Cannot steer turn: no Codex turn is currently running");
1972
+ }
1973
+ expectedTurnId = steerInput.expectedTurnId;
1974
+ }
1975
+ const parts = await inlineCodexParts(steerInput.input, {
1976
+ ...input.imageOptions,
1977
+ driverLabel: "The Codex driver",
1978
+ signal: input.signal
2383
1979
  });
2384
- if (typeof outcome === "object" && outcome !== null && "then" in outcome && typeof outcome.then === "function") {
2385
- Promise.resolve(outcome).catch(onObserverError);
1980
+ input.ensureAlive();
1981
+ const afterAwait = input.getActiveTurn();
1982
+ if (active !== undefined) {
1983
+ if (afterAwait !== active || afterAwait.codexTurnId !== expectedTurnId) {
1984
+ throw new Error("Cannot steer turn: the active Codex turn ended before steering was sent");
1985
+ }
1986
+ } else if (afterAwait !== undefined && afterAwait.codexTurnId !== expectedTurnId) {
1987
+ throw new TypeError(`Expected active Codex turn ${expectedTurnId}, but current turn is ${afterAwait.codexTurnId ?? "starting"}`);
2386
1988
  }
2387
- } catch (error) {
2388
- onObserverError(error);
1989
+ return sendCodexTurnSteer(input.peer, {
1990
+ threadId: input.threadId,
1991
+ expectedTurnId,
1992
+ parts,
1993
+ ...steerInput.clientId !== undefined && { clientId: steerInput.clientId }
1994
+ });
1995
+ },
1996
+ async forkThread(options = {}) {
1997
+ input.ensureAlive();
1998
+ validateCodexForkBounds(options, "CodexSession.forkThread");
1999
+ const policyParams = buildCodexThreadPolicyParams({}, options);
2000
+ const forked = CodexStartedThreadSchema.parse(await input.peer.request("thread/fork", {
2001
+ threadId: input.threadId,
2002
+ ...policyParams,
2003
+ ...options.cwd !== undefined && { cwd: options.cwd },
2004
+ ...options.beforeTurnId !== undefined && { beforeTurnId: options.beforeTurnId },
2005
+ ...options.lastTurnId !== undefined && { lastTurnId: options.lastTurnId },
2006
+ ...options.excludeTurns !== undefined && { excludeTurns: options.excludeTurns },
2007
+ ...options.deferGoalContinuation !== undefined && {
2008
+ deferGoalContinuation: options.deferGoalContinuation
2009
+ }
2010
+ }));
2011
+ return {
2012
+ nativeThreadId: forked.thread.id,
2013
+ threadContext: extractCodexThreadContext(forked)
2014
+ };
2389
2015
  }
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
2016
  };
2397
2017
  }
2398
2018
 
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")
2019
+ // src/agent-executor/codex/thread-open.ts
2020
+ function interruptLocalCodexTurn(turn, turnId) {
2021
+ if (turn === undefined || turn.codexTurnId !== turnId)
2411
2022
  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
- });
2023
+ turn.state.interruptRequested = true;
2024
+ drainEngineRequests(turn, codexStopped);
2424
2025
  }
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
- ];
2026
+ function buildCodexResumeThreadParams(params) {
2027
+ const caller = "CodexControlClient.resumeThread";
2028
+ const threadId = assertNonEmptyThreadId(params.threadId, caller);
2029
+ assertOptionalNonEmptyNoNulString(params.cwd, "cwd", caller);
2030
+ if (params.excludeTurns !== undefined && typeof params.excludeTurns !== "boolean") {
2031
+ throw new TypeError(`[stitchkit] ${caller}: excludeTurns must be a boolean`);
2431
2032
  }
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,
2473
- ...overrides,
2474
- ...mergedConfig !== undefined && { config: mergedConfig }
2475
- };
2476
- validateCodexPolicyOverrides(merged, "CodexSession");
2477
- const params = {};
2478
- if (merged.model !== undefined)
2479
- params.model = merged.model;
2480
- if (merged.modelProvider !== undefined)
2481
- params.modelProvider = merged.modelProvider;
2482
- if (merged.approvalPolicy !== undefined)
2483
- params.approvalPolicy = safeJsonValue(merged.approvalPolicy);
2484
- if (merged.sandbox !== undefined)
2485
- params.sandbox = merged.sandbox;
2486
- if (merged.developerInstructions !== undefined)
2487
- params.developerInstructions = merged.developerInstructions;
2488
- if (merged.runtimeWorkspaceRoots !== undefined)
2489
- params.runtimeWorkspaceRoots = [...merged.runtimeWorkspaceRoots];
2490
- if (merged.config !== undefined)
2491
- params.config = safeJsonValue(merged.config);
2492
- return params;
2493
- }
2494
- function validateCodexTurnStartOverrides(turnInput, activeModelProvider) {
2495
- if (turnInput.modelProvider !== undefined) {
2496
- if (activeModelProvider === undefined || turnInput.modelProvider !== activeModelProvider) {
2497
- throw new TypeError(`Codex turn/start cannot switch modelProvider to ${JSON.stringify(turnInput.modelProvider)} (thread active provider is ${JSON.stringify(activeModelProvider ?? "unknown")})`);
2498
- }
2499
- }
2500
- if (turnInput.collaborationMode !== undefined) {
2501
- CodexCollaborationModeSchema.parse(turnInput.collaborationMode);
2502
- }
2503
- if (turnInput.approvalPolicy !== undefined) {
2504
- safeJsonValue(turnInput.approvalPolicy);
2505
- }
2506
- if (turnInput.sandboxPolicy !== undefined) {
2507
- safeJsonValue(turnInput.sandboxPolicy);
2508
- }
2509
- if (turnInput.runtimeWorkspaceRoots !== undefined) {
2510
- validateCodexPolicyOverrides({ runtimeWorkspaceRoots: turnInput.runtimeWorkspaceRoots }, "CodexSession.startTurn");
2511
- }
2512
- }
2513
- function buildCodexTurnStartParams(threadId, turnInput, parts, activeModelProvider) {
2514
- validateCodexTurnStartOverrides(turnInput, activeModelProvider);
2515
- const params = {
2516
- threadId,
2517
- input: codexTurnInput(parts),
2518
- clientUserMessageId: turnInput.clientId
2519
- };
2520
- if (turnInput.model !== undefined)
2521
- params.model = turnInput.model;
2522
- if (turnInput.reasoningEffort !== undefined)
2523
- params.effort = turnInput.reasoningEffort;
2524
- if (turnInput.collaborationMode !== undefined) {
2525
- params.collaborationMode = CodexCollaborationModeSchema.parse(turnInput.collaborationMode);
2526
- }
2527
- if (turnInput.approvalPolicy !== undefined) {
2528
- params.approvalPolicy = safeJsonValue(turnInput.approvalPolicy);
2529
- }
2530
- if (turnInput.sandboxPolicy !== undefined) {
2531
- params.sandboxPolicy = safeJsonValue(turnInput.sandboxPolicy);
2532
- }
2533
- if (turnInput.runtimeWorkspaceRoots !== undefined) {
2534
- params.runtimeWorkspaceRoots = [...turnInput.runtimeWorkspaceRoots];
2535
- }
2536
- return params;
2537
- }
2538
- function createCodexSessionMutators(input) {
2033
+ const policyParams = buildCodexThreadPolicyParams({}, params);
2539
2034
  return {
2540
- async steerTurn(steerInput) {
2541
- input.ensureAlive();
2542
- const active = input.getActiveTurn();
2543
- const expectedTurnId = active?.codexTurnId;
2544
- if (active === undefined || expectedTurnId === undefined) {
2545
- throw new Error("Cannot steer turn: no Codex turn is currently running");
2546
- }
2547
- if (steerInput.expectedTurnId !== undefined && steerInput.expectedTurnId !== expectedTurnId) {
2548
- throw new TypeError(`Expected active Codex turn ${steerInput.expectedTurnId}, but current turn is ${expectedTurnId}`);
2549
- }
2550
- const parts = await inlineCodexParts(steerInput.input, {
2551
- ...input.imageOptions,
2552
- driverLabel: "The Codex driver",
2553
- signal: input.signal
2554
- });
2555
- input.ensureAlive();
2556
- const afterAwait = input.getActiveTurn();
2557
- if (afterAwait !== active || afterAwait.codexTurnId !== expectedTurnId) {
2558
- throw new Error("Cannot steer turn: the active Codex turn ended before steering was sent");
2559
- }
2560
- const steered = CodexTurnSteerResponseSchema.parse(await input.peer.request("turn/steer", {
2561
- threadId: input.threadId,
2562
- expectedTurnId,
2563
- input: codexTurnInput(parts),
2564
- ...steerInput.clientId !== undefined && {
2565
- clientUserMessageId: steerInput.clientId
2566
- }
2567
- }));
2568
- return { turnId: steered.turnId };
2569
- },
2570
- async forkThread(options = {}) {
2571
- input.ensureAlive();
2572
- validateCodexForkBounds(options, "CodexSession.forkThread");
2573
- const policyParams = buildCodexThreadPolicyParams({}, options);
2574
- const forked = CodexStartedThreadSchema.parse(await input.peer.request("thread/fork", {
2575
- threadId: input.threadId,
2576
- ...policyParams,
2577
- ...options.cwd !== undefined && { cwd: options.cwd },
2578
- ...options.beforeTurnId !== undefined && { beforeTurnId: options.beforeTurnId },
2579
- ...options.lastTurnId !== undefined && { lastTurnId: options.lastTurnId },
2580
- ...options.excludeTurns !== undefined && { excludeTurns: options.excludeTurns },
2581
- ...options.deferGoalContinuation !== undefined && {
2582
- deferGoalContinuation: options.deferGoalContinuation
2583
- }
2584
- }));
2585
- return {
2586
- nativeThreadId: forked.thread.id,
2587
- threadContext: extractCodexThreadContext(forked)
2588
- };
2589
- },
2590
- async compactThread() {
2591
- input.ensureAlive();
2592
- await input.peer.request("thread/compact/start", { threadId: input.threadId });
2593
- }
2035
+ threadId,
2036
+ excludeTurns: params.excludeTurns ?? true,
2037
+ ...policyParams,
2038
+ ...params.cwd !== undefined && { cwd: params.cwd }
2594
2039
  };
2595
2040
  }
2596
-
2597
- // src/agent-executor/codex/session.ts
2598
2041
  function createCodexStartTurn(input) {
2599
2042
  return guardedTurnStarter({
2600
2043
  busyMessage: "A turn is already running in this Codex thread",
@@ -2618,112 +2061,843 @@ function createCodexStartTurn(input) {
2618
2061
  pending: new Map
2619
2062
  };
2620
2063
  input.setTurn(turn);
2064
+ let nativeTurnId;
2621
2065
  try {
2622
2066
  const started = await input.peer.request("turn/start", turnParams);
2623
- turn.codexTurnId = CodexStartedTurnSchema.parse(started).turn.id;
2067
+ nativeTurnId = CodexStartedTurnSchema.parse(started).turn.id;
2068
+ turn.codexTurnId = nativeTurnId;
2624
2069
  } catch (error) {
2625
2070
  if (input.getTurn() === turn)
2626
2071
  input.setTurn(undefined);
2627
2072
  throw error;
2628
2073
  }
2629
- return {
2630
- deltas: turn.channel,
2631
- async interrupt() {
2632
- turn.state.interruptRequested = true;
2633
- drainEngineRequests(turn, codexStopped);
2634
- if (turn.codexTurnId !== undefined) {
2635
- await input.peer.request("turn/interrupt", {
2636
- threadId: input.threadId,
2637
- turnId: turn.codexTurnId
2638
- });
2639
- }
2640
- },
2641
- async respond(interactionId, rawReply) {
2642
- answerActiveCodexTurnRequest(turn, interactionId, rawReply);
2643
- }
2074
+ return {
2075
+ nativeTurnId,
2076
+ deltas: turn.channel,
2077
+ async interrupt() {
2078
+ interruptLocalCodexTurn(turn, nativeTurnId);
2079
+ await input.peer.request("turn/interrupt", {
2080
+ threadId: input.threadId,
2081
+ turnId: nativeTurnId
2082
+ });
2083
+ },
2084
+ async respond(interactionId, rawReply) {
2085
+ answerActiveCodexTurnRequest(turn, interactionId, rawReply);
2086
+ }
2087
+ };
2088
+ }
2089
+ });
2090
+ }
2091
+ function validateCodexOpenInput(input) {
2092
+ if (input.nativeThreadId !== undefined && input.forkFrom !== undefined) {
2093
+ throw new TypeError("[stitchkit] CodexDriver.open: nativeThreadId and forkFrom are mutually exclusive");
2094
+ }
2095
+ if (input.forkFrom !== undefined) {
2096
+ if (typeof input.forkFrom.threadId !== "string" || input.forkFrom.threadId.trim().length === 0) {
2097
+ throw new TypeError("[stitchkit] CodexDriver.open: forkFrom.threadId must be a non-empty string");
2098
+ }
2099
+ validateCodexForkBounds(input.forkFrom, "CodexDriver.open");
2100
+ validateCodexPolicyOverrides(input.forkFrom, "CodexDriver.open");
2101
+ }
2102
+ }
2103
+ function mergeOpenThreadPolicy(config, forkFrom, dynamicOverrides) {
2104
+ const basePolicy = {
2105
+ ...config.model !== undefined && { model: config.model },
2106
+ ...config.modelProvider !== undefined && { modelProvider: config.modelProvider },
2107
+ ...config.approvalPolicy !== undefined && { approvalPolicy: config.approvalPolicy },
2108
+ ...config.sandbox !== undefined && { sandbox: config.sandbox },
2109
+ ...config.developerInstructions !== undefined && {
2110
+ developerInstructions: config.developerInstructions
2111
+ },
2112
+ ...config.runtimeWorkspaceRoots !== undefined && {
2113
+ runtimeWorkspaceRoots: config.runtimeWorkspaceRoots
2114
+ },
2115
+ ...config.config !== undefined && { config: config.config }
2116
+ };
2117
+ const withFork = forkFrom === undefined ? basePolicy : {
2118
+ ...basePolicy,
2119
+ ...forkFrom.model !== undefined && { model: forkFrom.model },
2120
+ ...forkFrom.modelProvider !== undefined && {
2121
+ modelProvider: forkFrom.modelProvider
2122
+ },
2123
+ ...forkFrom.approvalPolicy !== undefined && {
2124
+ approvalPolicy: forkFrom.approvalPolicy
2125
+ },
2126
+ ...forkFrom.sandbox !== undefined && { sandbox: forkFrom.sandbox },
2127
+ ...forkFrom.developerInstructions !== undefined && {
2128
+ developerInstructions: forkFrom.developerInstructions
2129
+ },
2130
+ ...forkFrom.runtimeWorkspaceRoots !== undefined && {
2131
+ runtimeWorkspaceRoots: forkFrom.runtimeWorkspaceRoots
2132
+ },
2133
+ ...basePolicy.config !== undefined || forkFrom.config !== undefined ? { config: { ...basePolicy.config ?? {}, ...forkFrom.config ?? {} } } : {}
2134
+ };
2135
+ return buildCodexThreadPolicyParams(withFork, dynamicOverrides);
2136
+ }
2137
+ function openCodexThreadRpc(peer, config, input, dynamicOverrides) {
2138
+ const threadParams = {
2139
+ cwd: input.cwd,
2140
+ ...mergeOpenThreadPolicy(config, input.forkFrom, dynamicOverrides)
2141
+ };
2142
+ if (input.forkFrom !== undefined) {
2143
+ const fork = input.forkFrom;
2144
+ return peer.request("thread/fork", {
2145
+ threadId: fork.threadId,
2146
+ excludeTurns: fork.excludeTurns ?? true,
2147
+ ...threadParams,
2148
+ ...fork.beforeTurnId !== undefined && { beforeTurnId: fork.beforeTurnId },
2149
+ ...fork.lastTurnId !== undefined && { lastTurnId: fork.lastTurnId },
2150
+ ...fork.deferGoalContinuation !== undefined && {
2151
+ deferGoalContinuation: fork.deferGoalContinuation
2152
+ }
2153
+ });
2154
+ }
2155
+ if (input.nativeThreadId !== undefined) {
2156
+ return peer.request("thread/resume", {
2157
+ threadId: input.nativeThreadId,
2158
+ excludeTurns: true,
2159
+ ...threadParams
2160
+ });
2161
+ }
2162
+ return peer.request("thread/start", threadParams);
2163
+ }
2164
+
2165
+ // src/agent-executor/codex/control-client.ts
2166
+ function assertOptionalItemsCursor(cursor, caller) {
2167
+ if (cursor === undefined || cursor === null)
2168
+ return;
2169
+ if (typeof cursor === "string") {
2170
+ if (cursor.trim().length === 0) {
2171
+ throw new TypeError(`[stitchkit] ${caller}: cursor must be a non-empty string`);
2172
+ }
2173
+ return;
2174
+ }
2175
+ if (typeof cursor !== "object" || cursor.type !== "item" || typeof cursor.itemId !== "string" || cursor.itemId.trim().length === 0) {
2176
+ throw new TypeError(`[stitchkit] ${caller}: item cursor must have type "item" and a non-empty itemId`);
2177
+ }
2178
+ }
2179
+ function createCodexControlClient(input) {
2180
+ const call = async (method, params) => {
2181
+ input.ensureAlive();
2182
+ return input.peer.request(method, params);
2183
+ };
2184
+ return {
2185
+ readConfig(params) {
2186
+ return call("config/read", {
2187
+ ...params?.cwd !== undefined && { cwd: params.cwd },
2188
+ ...params?.includeLayers !== undefined && { includeLayers: params.includeLayers }
2189
+ });
2190
+ },
2191
+ async readThread(params) {
2192
+ const threadId = assertNonEmptyThreadId(params.threadId, "CodexControlClient.readThread");
2193
+ return call("thread/read", {
2194
+ threadId,
2195
+ ...params.includeTurns !== undefined && { includeTurns: params.includeTurns }
2196
+ });
2197
+ },
2198
+ listCollaborationModes() {
2199
+ return call("collaborationMode/list", {});
2200
+ },
2201
+ async listTurns(params) {
2202
+ const caller = "CodexControlClient.listTurns";
2203
+ const threadId = assertNonEmptyThreadId(params.threadId, caller);
2204
+ assertOptionalLimit(params.limit, caller);
2205
+ if (params.cursor !== undefined && params.cursor !== null && typeof params.cursor !== "string") {
2206
+ throw new TypeError(`[stitchkit] ${caller}: cursor must be a string or null`);
2207
+ }
2208
+ return call("thread/turns/list", {
2209
+ threadId,
2210
+ ...params.cursor !== undefined && { cursor: params.cursor },
2211
+ ...params.limit !== undefined && { limit: params.limit },
2212
+ ...params.itemsView !== undefined && { itemsView: params.itemsView },
2213
+ ...params.sortDirection !== undefined && { sortDirection: params.sortDirection }
2214
+ });
2215
+ },
2216
+ async listItems(params) {
2217
+ const threadId = assertNonEmptyThreadId(params.threadId, "CodexControlClient.listItems");
2218
+ assertOptionalLimit(params.limit, "CodexControlClient.listItems");
2219
+ assertOptionalNonEmptyString(params.turnId, "turnId", "CodexControlClient.listItems");
2220
+ assertOptionalItemsCursor(params.cursor, "CodexControlClient.listItems");
2221
+ return call("thread/items/list", {
2222
+ threadId,
2223
+ ...params.turnId !== undefined && { turnId: params.turnId },
2224
+ ...params.cursor !== undefined && { cursor: safeJsonValue(params.cursor) },
2225
+ ...params.limit !== undefined && { limit: params.limit },
2226
+ ...params.sortDirection !== undefined && { sortDirection: params.sortDirection },
2227
+ ...params.deferOutput !== undefined && {
2228
+ deferOutput: safeJsonValue(params.deferOutput)
2229
+ }
2230
+ });
2231
+ },
2232
+ listMcpServerStatus(params) {
2233
+ return call("mcpServerStatus/list", {
2234
+ ...params?.cursor !== undefined && { cursor: params.cursor },
2235
+ ...params?.limit !== undefined && { limit: params.limit },
2236
+ ...params?.threadId !== undefined && { threadId: params.threadId },
2237
+ ...params?.serverName !== undefined && { serverName: params.serverName },
2238
+ ...params?.detail !== undefined && { detail: params.detail }
2239
+ });
2240
+ },
2241
+ listSkills(params) {
2242
+ return call("skills/list", {
2243
+ ...params?.cwds !== undefined && { cwds: [...params.cwds] },
2244
+ ...params?.forceReload !== undefined && { forceReload: params.forceReload }
2245
+ });
2246
+ },
2247
+ listModels(params) {
2248
+ return call("model/list", {
2249
+ ...params?.cursor !== undefined && { cursor: params.cursor },
2250
+ ...params?.limit !== undefined && { limit: params.limit },
2251
+ ...params?.includeHidden !== undefined && { includeHidden: params.includeHidden },
2252
+ ...params?.modelProvider !== undefined && { modelProvider: params.modelProvider }
2253
+ });
2254
+ },
2255
+ readAccount(params) {
2256
+ return call("account/read", {
2257
+ ...params?.refreshToken !== undefined && { refreshToken: params.refreshToken }
2258
+ });
2259
+ },
2260
+ readRateLimits() {
2261
+ return call("account/rateLimits/read");
2262
+ },
2263
+ async resumeThread(params) {
2264
+ input.ensureAlive();
2265
+ return call("thread/resume", buildCodexResumeThreadParams(params));
2266
+ },
2267
+ async steerTurn(params) {
2268
+ input.ensureAlive();
2269
+ const caller = "CodexControlClient.steerTurn";
2270
+ const threadId = assertNonEmptyThreadId(params.threadId, caller);
2271
+ const expectedTurnId = assertRequiredNonEmptyString(params.expectedTurnId, "expectedTurnId", caller);
2272
+ assertOptionalNonEmptyString(params.clientId, "clientId", caller);
2273
+ const parts = await inlineCodexParts(params.input, {
2274
+ ...input.imageOptions,
2275
+ driverLabel: "The Codex driver",
2276
+ signal: input.signal
2277
+ });
2278
+ input.ensureAlive();
2279
+ return sendCodexTurnSteer(input.peer, {
2280
+ threadId,
2281
+ expectedTurnId,
2282
+ parts,
2283
+ ...params.clientId !== undefined && { clientId: params.clientId }
2284
+ });
2285
+ },
2286
+ ...createCodexThreadControlMethods(call, {
2287
+ ensureAlive: input.ensureAlive,
2288
+ ...input.onBeforeInterruptTurn !== undefined && {
2289
+ onBeforeInterruptTurn: input.onBeforeInterruptTurn
2290
+ }
2291
+ })
2292
+ };
2293
+ }
2294
+ function bindCodexSessionThreadControls(controlClient, threadId) {
2295
+ return {
2296
+ readThread(params) {
2297
+ return controlClient.readThread({
2298
+ ...params,
2299
+ threadId: params?.threadId ?? threadId
2300
+ });
2301
+ },
2302
+ listTurns(params) {
2303
+ return controlClient.listTurns({
2304
+ ...params,
2305
+ threadId: params?.threadId ?? threadId
2306
+ });
2307
+ },
2308
+ listItems(params) {
2309
+ return controlClient.listItems({
2310
+ ...params,
2311
+ threadId: params?.threadId ?? threadId
2312
+ });
2313
+ },
2314
+ resumeThread(params) {
2315
+ return controlClient.resumeThread({
2316
+ ...params,
2317
+ threadId: params?.threadId ?? threadId
2318
+ });
2319
+ },
2320
+ revertThread(params) {
2321
+ return controlClient.revertThread({
2322
+ ...params,
2323
+ threadId: params.threadId ?? threadId
2324
+ });
2325
+ },
2326
+ injectItems(params) {
2327
+ return controlClient.injectItems({
2328
+ ...params,
2329
+ threadId: params.threadId ?? threadId
2330
+ });
2331
+ },
2332
+ unsubscribeThread(params) {
2333
+ return controlClient.unsubscribeThread({
2334
+ threadId: params?.threadId ?? threadId
2335
+ });
2336
+ },
2337
+ archiveThread(params) {
2338
+ return controlClient.archiveThread({
2339
+ threadId: params?.threadId ?? threadId
2340
+ });
2341
+ },
2342
+ unarchiveThread(params) {
2343
+ return controlClient.unarchiveThread({
2344
+ threadId: params?.threadId ?? threadId
2345
+ });
2346
+ },
2347
+ updateThreadMetadata(params) {
2348
+ return controlClient.updateThreadMetadata({
2349
+ ...params,
2350
+ threadId: params?.threadId ?? threadId
2351
+ });
2352
+ },
2353
+ setThreadName(params) {
2354
+ return controlClient.setThreadName({
2355
+ ...params,
2356
+ threadId: params.threadId ?? threadId
2357
+ });
2358
+ },
2359
+ interruptTurn(params) {
2360
+ return controlClient.interruptTurn({
2361
+ ...params,
2362
+ threadId: params.threadId ?? threadId
2363
+ });
2364
+ },
2365
+ compactThread(params) {
2366
+ return controlClient.compactThread({
2367
+ threadId: params?.threadId ?? threadId
2368
+ });
2369
+ }
2370
+ };
2371
+ }
2372
+
2373
+ // src/agent-executor/codex/classify.ts
2374
+ var raw = (type) => ({ source: "codex", type });
2375
+ var CODEX_TOOL_ITEMS = new Set([
2376
+ "commandExecution",
2377
+ "fileChange",
2378
+ "mcpToolCall",
2379
+ "dynamicToolCall",
2380
+ "collabAgentToolCall",
2381
+ "webSearch",
2382
+ "imageView",
2383
+ "sleep",
2384
+ "imageGeneration",
2385
+ "functionCallOutput"
2386
+ ]);
2387
+ var STATUSLESS_TOOL_ITEMS = new Set([
2388
+ "webSearch",
2389
+ "imageView",
2390
+ "sleep",
2391
+ "functionCallOutput"
2392
+ ]);
2393
+ var CODEX_CONTENT_ITEMS = new Set([
2394
+ "agentMessage",
2395
+ "reasoning",
2396
+ "userMessage",
2397
+ "plan",
2398
+ "contextCompaction",
2399
+ "hookPrompt",
2400
+ "subAgentActivity",
2401
+ "enteredReviewMode",
2402
+ "exitedReviewMode"
2403
+ ]);
2404
+ var KNOWN_CODEX_ERROR_CODES = new Set([
2405
+ "contextWindowExceeded",
2406
+ "sessionBudgetExceeded",
2407
+ "usageLimitExceeded",
2408
+ "rateLimitExceeded",
2409
+ "flexUnavailable",
2410
+ "serverOverloaded",
2411
+ "modelNotFound",
2412
+ "policyCapacityUnavailable",
2413
+ "cyberPolicy",
2414
+ "bioPolicy",
2415
+ "misalignmentPolicyViolation",
2416
+ "tooManyDenials",
2417
+ "internalServerError",
2418
+ "unauthorized",
2419
+ "badRequest",
2420
+ "threadRollbackFailed",
2421
+ "sandboxError",
2422
+ "other",
2423
+ "inferenceHookDenied"
2424
+ ]);
2425
+ var KNOWN_CODEX_ERROR_OBJECT_KEYS = new Set([
2426
+ "httpConnectionFailed",
2427
+ "responseStreamConnectionFailed",
2428
+ "responseStreamDisconnected",
2429
+ "responseTooManyFailedAttempts",
2430
+ "activeTurnNotSteerable"
2431
+ ]);
2432
+ var MAX_ERROR_INFO_SUMMARY_CHARS = 512;
2433
+ function toolName(item) {
2434
+ if (item.type === "mcpToolCall" || item.type === "dynamicToolCall" || item.type === "collabAgentToolCall") {
2435
+ return nonEmptyString(Reflect.get(item, "tool")) ?? item.type;
2436
+ }
2437
+ if (item.type === "functionCallOutput") {
2438
+ return nonEmptyString(Reflect.get(item, "name")) ?? item.type;
2439
+ }
2440
+ return item.type;
2441
+ }
2442
+ function toolInput(item) {
2443
+ const { id: _id, type: _type, status: _status, aggregatedOutput: _output, ...rest } = item;
2444
+ return safeJsonValue(rest);
2445
+ }
2446
+ function isKnownCodexErrorInfo(info) {
2447
+ if (typeof info === "string")
2448
+ return KNOWN_CODEX_ERROR_CODES.has(info);
2449
+ if (typeof info === "object" && info !== null && !Array.isArray(info)) {
2450
+ const keys = Object.keys(info);
2451
+ return keys.length === 1 && keys[0] !== undefined && KNOWN_CODEX_ERROR_OBJECT_KEYS.has(keys[0]);
2452
+ }
2453
+ return false;
2454
+ }
2455
+ function formatCodexErrorInfo(info) {
2456
+ if (info === null || info === undefined)
2457
+ return;
2458
+ if (typeof info === "string") {
2459
+ const trimmed = info.trim();
2460
+ return trimmed.length > 0 ? trimmed.slice(0, MAX_ERROR_INFO_SUMMARY_CHARS) : undefined;
2461
+ }
2462
+ try {
2463
+ const serialized = JSON.stringify(safeJsonValue(info));
2464
+ if (serialized === undefined || serialized.length === 0)
2465
+ return;
2466
+ return serialized.length > MAX_ERROR_INFO_SUMMARY_CHARS ? `${serialized.slice(0, MAX_ERROR_INFO_SUMMARY_CHARS - 1)}…` : serialized;
2467
+ } catch {
2468
+ return String(info).slice(0, MAX_ERROR_INFO_SUMMARY_CHARS);
2469
+ }
2470
+ }
2471
+ function codexFailureMessage(turn) {
2472
+ const rawMessage = turn.error?.message.trim() ?? "";
2473
+ const info = turn.error?.codexErrorInfo;
2474
+ const infoSummary = formatCodexErrorInfo(info);
2475
+ if (rawMessage.length > 0) {
2476
+ if (infoSummary !== undefined && !isKnownCodexErrorInfo(info) && !rawMessage.includes(infoSummary)) {
2477
+ return `${rawMessage} (${infoSummary})`;
2478
+ }
2479
+ return rawMessage;
2480
+ }
2481
+ if (infoSummary !== undefined) {
2482
+ return `Codex ended the turn ${turn.status} (${infoSummary})`;
2483
+ }
2484
+ return `Codex ended the turn ${turn.status}`;
2485
+ }
2486
+ function httpStatusOf(value, depth = 0) {
2487
+ if (depth > 3 || typeof value !== "object" || value === null)
2488
+ return;
2489
+ const direct = Reflect.get(value, "httpStatusCode");
2490
+ if (typeof direct === "number")
2491
+ return direct;
2492
+ for (const nested of Object.values(value)) {
2493
+ const found = httpStatusOf(nested, depth + 1);
2494
+ if (found !== undefined)
2495
+ return found;
2496
+ }
2497
+ return;
2498
+ }
2499
+ function failureKind(info) {
2500
+ if (info === "unauthorized")
2501
+ return "authRequired";
2502
+ if (info === "usageLimitExceeded" || info === "rateLimitExceeded" || info === "sessionBudgetExceeded")
2503
+ return "rateLimited";
2504
+ const status = httpStatusOf(info);
2505
+ if (status === 401 || status === 403)
2506
+ return "authRequired";
2507
+ if (status === 429)
2508
+ return "rateLimited";
2509
+ return "restartRecommended";
2510
+ }
2511
+ function normalizeCodexTokenTotals(rawTotals) {
2512
+ if (rawTotals === undefined)
2513
+ return;
2514
+ const normalized = {
2515
+ ...rawTotals.inputTokens !== undefined && { inputTokens: rawTotals.inputTokens },
2516
+ ...rawTotals.outputTokens !== undefined && { outputTokens: rawTotals.outputTokens },
2517
+ ...rawTotals.cachedInputTokens !== undefined && {
2518
+ cachedInputTokens: rawTotals.cachedInputTokens
2519
+ },
2520
+ ...rawTotals.cacheWriteInputTokens !== undefined && {
2521
+ cacheCreationInputTokens: rawTotals.cacheWriteInputTokens
2522
+ },
2523
+ ...rawTotals.reasoningOutputTokens !== undefined && {
2524
+ thinkingTokens: rawTotals.reasoningOutputTokens
2525
+ },
2526
+ ...rawTotals.totalTokens !== undefined && { totalTokens: rawTotals.totalTokens }
2527
+ };
2528
+ return Object.keys(normalized).length > 0 ? normalized : undefined;
2529
+ }
2530
+ function classifyCodexTokenUsage(params, base) {
2531
+ const { last, total } = CodexNotificationParams["thread/tokenUsage/updated"].parse(params).tokenUsage;
2532
+ const normalizedTotal = normalizeCodexTokenTotals(total);
2533
+ return {
2534
+ kind: "deltas",
2535
+ deltas: [
2536
+ {
2537
+ type: "usage",
2538
+ ...base,
2539
+ itemId: "usage",
2540
+ raw: raw("thread/tokenUsage/updated"),
2541
+ inputTokens: last.inputTokens,
2542
+ outputTokens: last.outputTokens,
2543
+ ...last.cachedInputTokens !== undefined && {
2544
+ cachedInputTokens: last.cachedInputTokens
2545
+ },
2546
+ ...last.cacheWriteInputTokens !== undefined && {
2547
+ cacheCreationInputTokens: last.cacheWriteInputTokens
2548
+ },
2549
+ ...last.reasoningOutputTokens !== undefined && {
2550
+ thinkingTokens: last.reasoningOutputTokens
2551
+ },
2552
+ ...last.totalTokens !== undefined && { totalTokens: last.totalTokens },
2553
+ ...normalizedTotal !== undefined && { total: normalizedTotal }
2554
+ }
2555
+ ]
2556
+ };
2557
+ }
2558
+ function classifyCodexNotification(method, params, state) {
2559
+ const base = { turnId: state.turnId };
2560
+ switch (method) {
2561
+ case "item/agentMessage/delta": {
2562
+ const p = CodexNotificationParams[method].parse(params);
2563
+ return {
2564
+ kind: "deltas",
2565
+ deltas: [{ type: "text", ...base, itemId: p.itemId, raw: raw(method), text: p.delta }]
2566
+ };
2567
+ }
2568
+ case "item/reasoning/textDelta":
2569
+ case "item/reasoning/summaryTextDelta": {
2570
+ const p = CodexNotificationParams[method].parse(params);
2571
+ return {
2572
+ kind: "deltas",
2573
+ deltas: [
2574
+ { type: "reasoning", ...base, itemId: p.itemId, raw: raw(method), text: p.delta }
2575
+ ]
2576
+ };
2577
+ }
2578
+ case "item/started":
2579
+ case "item/completed": {
2580
+ const { item } = CodexNotificationParams[method].parse(params);
2581
+ if (CODEX_CONTENT_ITEMS.has(item.type))
2582
+ return { kind: "ignore", reason: `${method} ${item.type}` };
2583
+ if (!CODEX_TOOL_ITEMS.has(item.type)) {
2584
+ return {
2585
+ kind: "unhandled",
2586
+ delta: {
2587
+ type: "error",
2588
+ ...base,
2589
+ itemId: `unhandled:${item.id}`,
2590
+ raw: raw(`${method}/${item.type}`),
2591
+ kind: "unhandled",
2592
+ message: `Codex item ${item.type} is not known to this driver`
2593
+ }
2594
+ };
2595
+ }
2596
+ if (method === "item/started") {
2597
+ return {
2598
+ kind: "deltas",
2599
+ deltas: [
2600
+ {
2601
+ type: "tool-call",
2602
+ ...base,
2603
+ itemId: `call:${item.id}`,
2604
+ raw: raw(method),
2605
+ callId: item.id,
2606
+ toolName: toolName(item),
2607
+ input: toolInput(item)
2608
+ }
2609
+ ]
2610
+ };
2611
+ }
2612
+ const status = Reflect.get(item, "status");
2613
+ const failure = Reflect.get(item, "failure");
2614
+ const output = failure ?? Reflect.get(item, "aggregatedOutput") ?? Reflect.get(item, "output") ?? Reflect.get(item, "savedPath") ?? Reflect.get(item, "fileId") ?? Reflect.get(item, "result") ?? Reflect.get(item, "results") ?? Reflect.get(item, "contentItems") ?? Reflect.get(item, "changes") ?? Reflect.get(item, "agentsStates") ?? Reflect.get(item, "error");
2615
+ const hasFailure = failure !== undefined && failure !== null;
2616
+ const outcome = !hasFailure && (status === "completed" || STATUSLESS_TOOL_ITEMS.has(item.type) && status === undefined) ? "success" : status === "declined" || status === "interrupted" ? "interrupted" : "error";
2617
+ return {
2618
+ kind: "deltas",
2619
+ deltas: [
2620
+ {
2621
+ type: "tool-result",
2622
+ ...base,
2623
+ itemId: `result:${item.id}`,
2624
+ raw: raw(method),
2625
+ callId: item.id,
2626
+ toolName: toolName(item),
2627
+ outcome,
2628
+ ...output !== undefined && output !== null && {
2629
+ output: safeJsonValue(output)
2630
+ }
2631
+ }
2632
+ ]
2633
+ };
2634
+ }
2635
+ case "turn/completed": {
2636
+ const { turn } = CodexNotificationParams[method].parse(params);
2637
+ const outcome = state.interruptRequested ? "interrupted" : turn.status === "completed" ? "completed" : turn.status === "interrupted" ? "interrupted" : "failed";
2638
+ const deltas = [];
2639
+ if (outcome === "failed") {
2640
+ deltas.push({
2641
+ type: "error",
2642
+ ...base,
2643
+ itemId: "failure",
2644
+ raw: raw(method),
2645
+ kind: failureKind(turn.error?.codexErrorInfo),
2646
+ message: codexFailureMessage(turn)
2647
+ });
2648
+ }
2649
+ deltas.push({ type: "turn-end", ...base, itemId: "end", raw: raw(method), outcome });
2650
+ return { kind: "end", deltas, outcome };
2651
+ }
2652
+ case "thread/tokenUsage/updated":
2653
+ return classifyCodexTokenUsage(params, base);
2654
+ case "serverRequest/resolved":
2655
+ return {
2656
+ kind: "resolved",
2657
+ requestId: String(CodexNotificationParams[method].parse(params).requestId)
2658
+ };
2659
+ case "account/rateLimits/updated": {
2660
+ const parsed = CodexNotificationParams[method].parse(params);
2661
+ return {
2662
+ kind: "limits",
2663
+ rateLimits: parsed.rateLimitsByLimitId !== undefined ? {
2664
+ rateLimits: parsed.rateLimits,
2665
+ rateLimitsByLimitId: parsed.rateLimitsByLimitId
2666
+ } : parsed.rateLimits
2667
+ };
2668
+ }
2669
+ default:
2670
+ if (CODEX_QUIET_NOTIFICATIONS.has(method))
2671
+ return { kind: "ignore", reason: method };
2672
+ return {
2673
+ kind: "unhandled",
2674
+ delta: {
2675
+ type: "error",
2676
+ ...base,
2677
+ itemId: `unhandled:${method}`,
2678
+ raw: raw(method),
2679
+ kind: "unhandled",
2680
+ message: `Codex notification ${method} is not known to this driver`
2681
+ }
2682
+ };
2683
+ }
2684
+ }
2685
+
2686
+ // src/agent-executor/codex/handlers.ts
2687
+ var JSON_RPC_INTERNAL_ERROR = -32603;
2688
+ var MAX_EXTERNAL_PENDING_REQUESTS = 256;
2689
+ function emitCodexNotification(state, method, params, duringActiveTurn, deltas) {
2690
+ if (state.onNotification === undefined)
2691
+ return;
2692
+ invokeSafely(() => state.onNotification?.({ method, params, duringActiveTurn, deltas }));
2693
+ }
2694
+ function handleCodexNotification(state, method, params) {
2695
+ const turn = state.getTurn();
2696
+ const duringActiveTurn = turn !== undefined;
2697
+ const effectiveTurnId = turn?.state.turnId ?? externalCodexTurnIdOf(params);
2698
+ let verdict;
2699
+ try {
2700
+ verdict = classifyCodexNotification(method, params, turn?.state ?? { turnId: effectiveTurnId, interruptRequested: false });
2701
+ } catch (error) {
2702
+ const errorDelta = {
2703
+ type: "error",
2704
+ turnId: effectiveTurnId,
2705
+ itemId: `unhandled:${method}`,
2706
+ raw: { source: "codex", type: method },
2707
+ kind: "unhandled",
2708
+ message: `Codex notification ${method} did not match schema: ${error instanceof Error ? error.message : String(error)}`
2709
+ };
2710
+ if (turn !== undefined)
2711
+ offerTurnDelta(turn.channel, errorDelta);
2712
+ emitCodexNotification(state, method, params, duringActiveTurn, [errorDelta]);
2713
+ return;
2714
+ }
2715
+ switch (verdict.kind) {
2716
+ case "limits":
2717
+ try {
2718
+ state.limits.set(state.profileId, mergeRateLimitEvent2({
2719
+ previous: state.limits.get(state.profileId),
2720
+ windows: codexPlanWindows(verdict.rateLimits),
2721
+ now: new Date
2722
+ }));
2723
+ emitCodexNotification(state, method, params, duringActiveTurn, []);
2724
+ } catch (error) {
2725
+ const errorDelta = {
2726
+ type: "error",
2727
+ turnId: effectiveTurnId,
2728
+ itemId: `unhandled:${method}`,
2729
+ raw: { source: "codex", type: method },
2730
+ kind: "unhandled",
2731
+ message: `Codex rate-limit update could not be merged: ${error instanceof Error ? error.message : String(error)}`
2732
+ };
2733
+ if (turn !== undefined)
2734
+ offerTurnDelta(turn.channel, errorDelta);
2735
+ emitCodexNotification(state, method, params, duringActiveTurn, [errorDelta]);
2736
+ }
2737
+ return;
2738
+ case "resolved": {
2739
+ const resolvedTurn = turn?.pending.delete(verdict.requestId) === true;
2740
+ const externalEntry = state.externalPending.get(verdict.requestId);
2741
+ const resolvedExternal = externalEntry !== undefined;
2742
+ if (resolvedExternal)
2743
+ state.externalPending.delete(verdict.requestId);
2744
+ const resolvedDelta = {
2745
+ type: "request-resolved",
2746
+ turnId: resolvedTurn ? turn?.state.turnId ?? effectiveTurnId : externalEntry?.turnId ?? effectiveTurnId,
2747
+ itemId: `resolved:${verdict.requestId}`,
2748
+ raw: { source: "codex", type: "serverRequest/resolved" },
2749
+ interactionId: verdict.requestId
2644
2750
  };
2751
+ if (resolvedTurn && turn !== undefined)
2752
+ offerTurnDelta(turn.channel, resolvedDelta);
2753
+ emitCodexNotification(state, method, params, duringActiveTurn, resolvedTurn || resolvedExternal ? [resolvedDelta] : []);
2754
+ return;
2645
2755
  }
2646
- });
2756
+ case "deltas":
2757
+ case "unhandled": {
2758
+ const emitted = verdict.kind === "deltas" ? verdict.deltas : [verdict.delta];
2759
+ if (turn !== undefined) {
2760
+ for (const delta of emitted)
2761
+ offerTurnDelta(turn.channel, delta);
2762
+ }
2763
+ emitCodexNotification(state, method, params, duringActiveTurn, emitted);
2764
+ return;
2765
+ }
2766
+ case "end":
2767
+ endEngineTurn(turn, codexStopped, verdict.deltas);
2768
+ state.clearTurn();
2769
+ emitCodexNotification(state, method, params, duringActiveTurn, verdict.deltas);
2770
+ return;
2771
+ case "ignore":
2772
+ emitCodexNotification(state, method, params, duringActiveTurn, []);
2773
+ return;
2774
+ }
2647
2775
  }
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");
2776
+ function handleCodexRequest(state, method, params, id) {
2777
+ const turn = state.getTurn();
2778
+ if (!isKnownCodexRequestMethod(method)) {
2779
+ if (turn !== undefined) {
2780
+ offerTurnDelta(turn.channel, {
2781
+ type: "error",
2782
+ turnId: turn.state.turnId,
2783
+ itemId: `unhandled-request:${id}`,
2784
+ raw: { source: "codex", type: method },
2785
+ kind: "unhandled",
2786
+ message: `Codex request ${method} is not known to this driver; refused`
2787
+ });
2788
+ }
2789
+ throw new JsonRpcError2(JSON_RPC_METHOD_NOT_FOUND2, `${method} is not handled by this executor`);
2651
2790
  }
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");
2791
+ const interactionId = String(id);
2792
+ if (turn !== undefined) {
2793
+ const parsed = parseCodexServerRequest(method, params);
2794
+ const delta = {
2795
+ type: "request",
2796
+ turnId: turn.state.turnId,
2797
+ itemId: `request:${interactionId}`,
2798
+ raw: { source: "codex", type: method },
2799
+ interactionId,
2800
+ kind: parsed.kind,
2801
+ ...parsed.deltaFields
2802
+ };
2803
+ const promise = new Promise((resolve) => {
2804
+ holdEngineRequest(turn, {
2805
+ interactionId,
2806
+ detail: parsed.detail,
2807
+ answeredBy: { source: "codex", type: method },
2808
+ delta: () => delta,
2809
+ refusal: codexStoppedAnswer(method),
2810
+ resolve
2811
+ });
2812
+ });
2813
+ if (state.serverRequestDelivery === "all" && state.onServerRequest !== undefined && turn.pending.has(interactionId)) {
2814
+ const observer = state.onServerRequest;
2815
+ invokeSafely(() => observer({
2816
+ interactionId,
2817
+ requestId: id,
2818
+ method,
2819
+ params,
2820
+ duringActiveTurn: true,
2821
+ delta,
2822
+ async respond(reply) {
2823
+ answerActiveCodexTurnRequest(turn, interactionId, reply);
2824
+ }
2825
+ }));
2655
2826
  }
2656
- validateCodexForkBounds(input.forkFrom, "CodexDriver.open");
2657
- validateCodexPolicyOverrides(input.forkFrom, "CodexDriver.open");
2827
+ return promise;
2658
2828
  }
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 ?? {} } } : {}
2829
+ const observer = state.onServerRequest;
2830
+ if (observer === undefined) {
2831
+ throw new JsonRpcError2(JSON_RPC_METHOD_NOT_FOUND2, `${method} is not handled by this executor`);
2832
+ }
2833
+ if (state.externalPending.size >= MAX_EXTERNAL_PENDING_REQUESTS) {
2834
+ throw new JsonRpcError2(JSON_RPC_INTERNAL_ERROR, `Too many pending external Codex server requests (limit ${MAX_EXTERNAL_PENDING_REQUESTS})`);
2835
+ }
2836
+ if (state.externalPending.has(interactionId)) {
2837
+ throw new JsonRpcError2(JSON_RPC_INTERNAL_ERROR, `Duplicate pending external Codex server request ${interactionId}`);
2838
+ }
2839
+ const parsed = parseCodexServerRequest(method, params);
2840
+ const turnId = externalCodexTurnIdOf(params);
2841
+ const delta = {
2842
+ type: "request",
2843
+ turnId,
2844
+ itemId: `request:${interactionId}`,
2845
+ raw: { source: "codex", type: method },
2846
+ interactionId,
2847
+ kind: parsed.kind,
2848
+ ...parsed.deltaFields
2691
2849
  };
2692
- return buildCodexThreadPolicyParams(withFork, dynamicOverrides);
2850
+ return new Promise((resolve, reject) => {
2851
+ const entry = { detail: parsed.detail, turnId, resolve };
2852
+ state.externalPending.set(interactionId, entry);
2853
+ const onObserverError = (error) => {
2854
+ if (state.externalPending.get(interactionId) !== entry)
2855
+ return;
2856
+ state.externalPending.delete(interactionId);
2857
+ if (error instanceof JsonRpcError2)
2858
+ reject(error);
2859
+ };
2860
+ try {
2861
+ const outcome = observer({
2862
+ interactionId,
2863
+ requestId: id,
2864
+ method,
2865
+ params,
2866
+ duringActiveTurn: false,
2867
+ delta,
2868
+ async respond(reply) {
2869
+ answerCodexSessionRequest({
2870
+ turn: undefined,
2871
+ externalPending: state.externalPending,
2872
+ expectedEntry: entry,
2873
+ interactionId,
2874
+ reply
2875
+ });
2876
+ }
2877
+ });
2878
+ if (typeof outcome === "object" && outcome !== null && "then" in outcome && typeof outcome.then === "function") {
2879
+ Promise.resolve(outcome).catch(onObserverError);
2880
+ }
2881
+ } catch (error) {
2882
+ onObserverError(error);
2883
+ }
2884
+ });
2693
2885
  }
2694
- function openCodexThreadRpc(peer, config, input, dynamicOverrides) {
2695
- const threadParams = {
2696
- cwd: input.cwd,
2697
- ...mergeOpenThreadPolicy(config, input.forkFrom, dynamicOverrides)
2886
+ function createCodexHandlers(state) {
2887
+ return {
2888
+ onNotification: (method, params) => handleCodexNotification(state, method, params),
2889
+ onRequest: (method, params, id) => handleCodexRequest(state, method, params, id)
2698
2890
  };
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
2891
  }
2892
+
2893
+ // src/agent-executor/codex/session.ts
2721
2894
  async function openCodexSession(config, input) {
2722
2895
  validateCodexOpenInput(input);
2723
2896
  const profile = engineProfile("codex", input.profile);
2724
2897
  const linked = sessionAbort(input.signal);
2725
2898
  const externalPending = new Map;
2726
2899
  let current;
2900
+ let activeThreadId;
2727
2901
  let dead;
2728
2902
  let opened = false;
2729
2903
  let closing = false;
@@ -2740,6 +2914,9 @@ async function openCodexSession(config, input) {
2740
2914
  ...config.onNotification !== undefined && { onNotification: config.onNotification },
2741
2915
  ...config.onServerRequest !== undefined && {
2742
2916
  onServerRequest: config.onServerRequest
2917
+ },
2918
+ ...config.serverRequestDelivery !== undefined && {
2919
+ serverRequestDelivery: config.serverRequestDelivery
2743
2920
  }
2744
2921
  }), (error) => {
2745
2922
  const shouldNotify = opened && !closing && input.signal?.aborted !== true;
@@ -2756,7 +2933,7 @@ async function openCodexSession(config, input) {
2756
2933
  linked.release();
2757
2934
  throw error;
2758
2935
  }
2759
- const { peer, providerPid } = connected;
2936
+ const { peer, providerPid, userAgent } = connected;
2760
2937
  const ensureAlive = () => {
2761
2938
  if (closing)
2762
2939
  throw new Error("The Codex session is closed");
@@ -2773,7 +2950,16 @@ async function openCodexSession(config, input) {
2773
2950
  linked.release();
2774
2951
  }
2775
2952
  };
2776
- const controlClient = createCodexControlClient({ peer, ensureAlive });
2953
+ const controlClient = createCodexControlClient({
2954
+ peer,
2955
+ imageOptions: config,
2956
+ signal: linked.signal,
2957
+ ensureAlive,
2958
+ onBeforeInterruptTurn: (targetThreadId, turnId) => {
2959
+ if (targetThreadId === activeThreadId)
2960
+ interruptLocalCodexTurn(current, turnId);
2961
+ }
2962
+ });
2777
2963
  let threadId;
2778
2964
  let threadContext;
2779
2965
  let dynamicOverrides;
@@ -2792,6 +2978,7 @@ async function openCodexSession(config, input) {
2792
2978
  const openedReply = await openCodexThreadRpc(peer, config, input, dynamicOverrides);
2793
2979
  const parsed = CodexStartedThreadSchema.parse(openedReply);
2794
2980
  threadId = parsed.thread.id;
2981
+ activeThreadId = threadId;
2795
2982
  threadContext = extractCodexThreadContext(parsed);
2796
2983
  if (config.verifyThread !== undefined) {
2797
2984
  emitStartupPhase(input.onStartupPhase, "verifying");
@@ -2834,6 +3021,7 @@ async function openCodexSession(config, input) {
2834
3021
  return {
2835
3022
  nativeThreadId: threadId,
2836
3023
  providerPid,
3024
+ userAgent,
2837
3025
  threadContext,
2838
3026
  startTurn,
2839
3027
  async respond(interactionId, reply) {
@@ -2870,6 +3058,9 @@ async function openCodexControlConnection(config, input) {
2870
3058
  ...config.onNotification !== undefined && { onNotification: config.onNotification },
2871
3059
  ...config.onServerRequest !== undefined && {
2872
3060
  onServerRequest: config.onServerRequest
3061
+ },
3062
+ ...config.serverRequestDelivery !== undefined && {
3063
+ serverRequestDelivery: config.serverRequestDelivery
2873
3064
  }
2874
3065
  }), (error) => {
2875
3066
  const shouldNotify = opened && !closing && input.signal?.aborted !== true;
@@ -2901,10 +3092,16 @@ async function openCodexControlConnection(config, input) {
2901
3092
  if (dead !== undefined)
2902
3093
  throw dead;
2903
3094
  };
2904
- const controlClient = createCodexControlClient({ peer: connected.peer, ensureAlive });
3095
+ const controlClient = createCodexControlClient({
3096
+ peer: connected.peer,
3097
+ imageOptions: config,
3098
+ signal: linked.signal,
3099
+ ensureAlive
3100
+ });
2905
3101
  opened = true;
2906
3102
  return {
2907
3103
  providerPid: connected.providerPid,
3104
+ userAgent: connected.userAgent,
2908
3105
  ...controlClient,
2909
3106
  async respond(interactionId, reply) {
2910
3107
  ensureAlive();
@@ -2947,7 +3144,10 @@ function buildSharedThreadSession(params) {
2947
3144
  };
2948
3145
  const threadControlClient = createCodexControlClient({
2949
3146
  peer: state.peer,
2950
- ensureAlive: ensureThreadAlive
3147
+ imageOptions: state.config,
3148
+ signal: threadAbort.signal,
3149
+ ensureAlive: ensureThreadAlive,
3150
+ onBeforeInterruptTurn: state.onBeforeInterruptTurn
2951
3151
  });
2952
3152
  const startTurn = createCodexStartTurn({
2953
3153
  config: state.config,
@@ -3002,6 +3202,7 @@ function buildSharedThreadSession(params) {
3002
3202
  return {
3003
3203
  nativeThreadId: threadId,
3004
3204
  providerPid: state.providerPid,
3205
+ userAgent: state.userAgent,
3005
3206
  threadContext,
3006
3207
  startTurn,
3007
3208
  async respond(interactionId, reply) {
@@ -3044,12 +3245,22 @@ async function openSharedCodexThread(state, threadInput) {
3044
3245
  state.openingNativeThreadIds.add(threadInput.nativeThreadId);
3045
3246
  }
3046
3247
  let registeredThreadId;
3248
+ const openControls = createCodexControlClient({
3249
+ peer: state.peer,
3250
+ imageOptions: state.config,
3251
+ signal: threadAbort.signal,
3252
+ ensureAlive: () => {
3253
+ threadAbort.signal.throwIfAborted();
3254
+ state.ensureServerAlive();
3255
+ },
3256
+ onBeforeInterruptTurn: state.onBeforeInterruptTurn
3257
+ });
3047
3258
  try {
3048
3259
  threadAbort.signal.throwIfAborted();
3049
3260
  let dynamicOverrides;
3050
3261
  if (state.config.prepareThread !== undefined) {
3051
3262
  dynamicOverrides = await raceAbort(Promise.resolve(state.config.prepareThread({
3052
- controls: state.controlClient,
3263
+ controls: openControls,
3053
3264
  cwd: threadInput.cwd,
3054
3265
  ...threadInput.nativeThreadId !== undefined && {
3055
3266
  nativeThreadId: threadInput.nativeThreadId
@@ -3096,6 +3307,9 @@ async function openSharedCodexThread(state, threadInput) {
3096
3307
  },
3097
3308
  ...state.config.onServerRequest !== undefined && {
3098
3309
  onServerRequest: state.config.onServerRequest
3310
+ },
3311
+ ...state.config.serverRequestDelivery !== undefined && {
3312
+ serverRequestDelivery: state.config.serverRequestDelivery
3099
3313
  }
3100
3314
  })
3101
3315
  };
@@ -3106,7 +3320,7 @@ async function openSharedCodexThread(state, threadInput) {
3106
3320
  await raceAbort(Promise.resolve(state.config.verifyThread({
3107
3321
  nativeThreadId: threadId,
3108
3322
  threadContext,
3109
- controls: state.controlClient
3323
+ controls: openControls
3110
3324
  })), threadAbort.signal);
3111
3325
  threadAbort.signal.throwIfAborted();
3112
3326
  }
@@ -3185,7 +3399,10 @@ async function openCodexSharedServer(config, baseCapabilities, input) {
3185
3399
  return;
3186
3400
  },
3187
3401
  ...config.onNotification !== undefined && { onNotification: config.onNotification },
3188
- ...config.onServerRequest !== undefined && { onServerRequest: config.onServerRequest }
3402
+ ...config.onServerRequest !== undefined && { onServerRequest: config.onServerRequest },
3403
+ ...config.serverRequestDelivery !== undefined && {
3404
+ serverRequestDelivery: config.serverRequestDelivery
3405
+ }
3189
3406
  });
3190
3407
  const failAllThreads = (error) => {
3191
3408
  for (const slot of [...threads.values()]) {
@@ -3236,14 +3453,23 @@ async function openCodexSharedServer(config, baseCapabilities, input) {
3236
3453
  linked.release();
3237
3454
  throw error;
3238
3455
  }
3239
- const { peer, providerPid } = connected;
3456
+ const { peer, providerPid, userAgent } = connected;
3240
3457
  const ensureServerAlive = () => {
3241
3458
  if (serverClosing)
3242
3459
  throw new Error("The Codex shared server is closed");
3243
3460
  if (serverDead !== undefined)
3244
3461
  throw serverDead;
3245
3462
  };
3246
- const controlClient = createCodexControlClient({ peer, ensureAlive: ensureServerAlive });
3463
+ const onBeforeInterruptTurn = (targetThreadId, turnId) => {
3464
+ interruptLocalCodexTurn(threads.get(targetThreadId)?.current, turnId);
3465
+ };
3466
+ const controlClient = createCodexControlClient({
3467
+ peer,
3468
+ imageOptions: config,
3469
+ signal: linked.signal,
3470
+ ensureAlive: ensureServerAlive,
3471
+ onBeforeInterruptTurn
3472
+ });
3247
3473
  const sharedCapabilities = {
3248
3474
  ...baseCapabilities,
3249
3475
  multiThreadPerProcess: true
@@ -3253,8 +3479,9 @@ async function openCodexSharedServer(config, baseCapabilities, input) {
3253
3479
  profile,
3254
3480
  peer,
3255
3481
  providerPid,
3482
+ userAgent,
3256
3483
  maxThreads,
3257
- controlClient,
3484
+ onBeforeInterruptTurn,
3258
3485
  serverSignal: linked.signal,
3259
3486
  threads,
3260
3487
  openingNativeThreadIds: new Set,
@@ -3279,6 +3506,7 @@ async function openCodexSharedServer(config, baseCapabilities, input) {
3279
3506
  opened = true;
3280
3507
  return {
3281
3508
  providerPid,
3509
+ userAgent,
3282
3510
  maxThreads,
3283
3511
  get activeThreadCount() {
3284
3512
  return threads.size;
@@ -3317,10 +3545,56 @@ async function findCodexClientInput(peer, nativeThreadId, clientId) {
3317
3545
  }
3318
3546
  throw new Error(`Codex thread/turns/list exceeded ${MAX_HISTORY_PAGES} pages without reaching the end of history`);
3319
3547
  }
3320
- function createCodexDriver(config = {}) {
3548
+ function validateCodexDriverOptions(config) {
3321
3549
  validateImageOptions(config);
3550
+ assertPositiveSafeInteger("maxFrameBytes", config.maxFrameBytes);
3322
3551
  validateCodexTransportAndArgs(config);
3323
3552
  validateCodexPolicyOverrides(config, "createCodexDriver");
3553
+ if (config.serverRequestDelivery !== undefined && config.serverRequestDelivery !== "external-only" && config.serverRequestDelivery !== "all") {
3554
+ throw new TypeError(`[stitchkit] createCodexDriver: serverRequestDelivery must be "external-only" or "all", received ${JSON.stringify(config.serverRequestDelivery)}`);
3555
+ }
3556
+ if (config.serverRequestDelivery === "all" && config.onServerRequest === undefined) {
3557
+ throw new TypeError('[stitchkit] createCodexDriver: serverRequestDelivery "all" requires onServerRequest');
3558
+ }
3559
+ }
3560
+ function buildCodexSessionConfig(input) {
3561
+ const { config } = input;
3562
+ const transport = input.forceStdioForListen && config.transport?.kind === "unix-listen" ? { kind: "stdio" } : config.transport;
3563
+ const maxFrameBytes = input.maxFrameBytes ?? config.maxFrameBytes;
3564
+ return {
3565
+ executable: input.executable,
3566
+ prefix: input.prefix,
3567
+ ...transport !== undefined && { transport },
3568
+ ...config.serverArgs !== undefined && { serverArgs: config.serverArgs },
3569
+ ...config.model !== undefined && { model: config.model },
3570
+ ...config.modelProvider !== undefined && { modelProvider: config.modelProvider },
3571
+ approvalPolicy: config.approvalPolicy ?? "on-request",
3572
+ sandbox: config.sandbox ?? "workspace-write",
3573
+ ...config.developerInstructions !== undefined && {
3574
+ developerInstructions: config.developerInstructions
3575
+ },
3576
+ ...config.runtimeWorkspaceRoots !== undefined && {
3577
+ runtimeWorkspaceRoots: config.runtimeWorkspaceRoots
3578
+ },
3579
+ ...config.config !== undefined && { config: config.config },
3580
+ ...config.prepareThread !== undefined && { prepareThread: config.prepareThread },
3581
+ ...config.verifyThread !== undefined && { verifyThread: config.verifyThread },
3582
+ ...!input.ephemeralProbe && config.onNotification !== undefined && { onNotification: config.onNotification },
3583
+ ...!input.ephemeralProbe && config.onServerRequest !== undefined && { onServerRequest: config.onServerRequest },
3584
+ ...!input.ephemeralProbe && config.serverRequestDelivery !== undefined && {
3585
+ serverRequestDelivery: config.serverRequestDelivery
3586
+ },
3587
+ ...!input.ephemeralProbe && config.onDisconnect !== undefined && { onDisconnect: config.onDisconnect },
3588
+ ambient: input.ambient,
3589
+ limits: input.limits,
3590
+ version: input.version,
3591
+ ...config.resolveFile !== undefined && { resolveFile: config.resolveFile },
3592
+ ...config.maxImageBytes !== undefined && { maxImageBytes: config.maxImageBytes },
3593
+ ...maxFrameBytes !== undefined && { maxFrameBytes }
3594
+ };
3595
+ }
3596
+ function createCodexDriver(config = {}) {
3597
+ validateCodexDriverOptions(config);
3324
3598
  const executable = config.executable ?? "codex";
3325
3599
  const prefix = config.prefixArgs ?? [];
3326
3600
  const ambient = config.ambient ?? process.env;
@@ -3342,40 +3616,18 @@ function createCodexDriver(config = {}) {
3342
3616
  images: config.resolveFile !== undefined,
3343
3617
  planLimits: "pull"
3344
3618
  };
3345
- const session = (options) => {
3346
- const transport = options?.forceStdioForListen && config.transport?.kind === "unix-listen" ? { kind: "stdio" } : config.transport;
3347
- return {
3348
- executable,
3349
- prefix,
3350
- ...transport !== undefined && { transport },
3351
- ...config.serverArgs !== undefined && { serverArgs: config.serverArgs },
3352
- ...config.model !== undefined && { model: config.model },
3353
- ...config.modelProvider !== undefined && { modelProvider: config.modelProvider },
3354
- approvalPolicy: config.approvalPolicy ?? "on-request",
3355
- sandbox: config.sandbox ?? "workspace-write",
3356
- ...config.developerInstructions !== undefined && {
3357
- developerInstructions: config.developerInstructions
3358
- },
3359
- ...config.runtimeWorkspaceRoots !== undefined && {
3360
- runtimeWorkspaceRoots: config.runtimeWorkspaceRoots
3361
- },
3362
- ...config.config !== undefined && { config: config.config },
3363
- ...config.prepareThread !== undefined && { prepareThread: config.prepareThread },
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 },
3368
- ambient,
3369
- limits,
3370
- version,
3371
- ...config.resolveFile !== undefined && { resolveFile: config.resolveFile },
3372
- ...config.maxImageBytes !== undefined && { maxImageBytes: config.maxImageBytes },
3373
- ...options?.maxLineBytes !== undefined && { maxLineBytes: options.maxLineBytes }
3374
- };
3375
- };
3619
+ const session = (options) => buildCodexSessionConfig({
3620
+ config,
3621
+ executable,
3622
+ prefix,
3623
+ ambient,
3624
+ limits,
3625
+ version,
3626
+ ...options
3627
+ });
3376
3628
  const cli = (profile, args) => runEngineCli({ executable, prefix, args, profile, ambient });
3377
- const ask = (profile, cwd, question, maxLineBytes) => withEphemeralConnection((signal) => connectCodex(session({
3378
- ...maxLineBytes !== undefined && { maxLineBytes },
3629
+ const ask = (profile, cwd, question, maxFrameBytes) => withEphemeralConnection((signal) => connectCodex(session({
3630
+ ...maxFrameBytes !== undefined && { maxFrameBytes },
3379
3631
  forceStdioForListen: true,
3380
3632
  ephemeralProbe: true
3381
3633
  }), engineProfile("codex", profile), cwd, signal), (connection) => question(connection.peer));
@@ -3436,7 +3688,7 @@ ${decoder.decode(loginResult.stderr)}`.trim();
3436
3688
  };
3437
3689
  },
3438
3690
  async findInput(input) {
3439
- return ask(input.profile, input.cwd, (peer) => findCodexClientInput(peer, input.nativeThreadId, input.clientId), FIND_INPUT_MAX_LINE_BYTES);
3691
+ return ask(input.profile, input.cwd, (peer) => findCodexClientInput(peer, input.nativeThreadId, input.clientId), Math.max(FIND_INPUT_MAX_LINE_BYTES, config.maxFrameBytes ?? 0));
3440
3692
  },
3441
3693
  open: (input) => openCodexSession(session(), input),
3442
3694
  connectControl: (input) => openCodexControlConnection(session(), input),
@@ -3529,6 +3781,7 @@ var codexFakeScenarios = {
3529
3781
  crash: () => steps(text("dying "), { do: "crash" })
3530
3782
  };
3531
3783
  export {
3784
+ CodexLocalImageInputSchema,
3532
3785
  CodexSkillInputSchema,
3533
3786
  CodexUnixSocketError,
3534
3787
  codexFakeScenarios,