@mininglamp-oss/octo-runtime 1.1.7 → 1.1.9

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 (124) hide show
  1. package/apps/cli/README.md +3 -1
  2. package/apps/cli/dist/build-info.json +2 -2
  3. package/apps/cli/dist/command-tree.js +3 -1
  4. package/apps/cli/dist/output.js +5 -2
  5. package/apps/cli/dist/playboard.js +11 -2
  6. package/dist/public/executor-kernel.d.ts +2 -2
  7. package/dist/public/executor-kernel.js +1 -1
  8. package/dist/public/protocol.d.ts +1 -1
  9. package/dist/public/protocol.js +1 -1
  10. package/node_modules/@mininglamp-oss/octo-runtime-acp-client/package.json +3 -3
  11. package/node_modules/@mininglamp-oss/octo-runtime-adapter-acp/package.json +4 -4
  12. package/node_modules/@mininglamp-oss/octo-runtime-adapter-antigravity/package.json +3 -3
  13. package/node_modules/@mininglamp-oss/octo-runtime-adapter-claude-code/package.json +3 -3
  14. package/node_modules/@mininglamp-oss/octo-runtime-adapter-codebuddy/package.json +4 -4
  15. package/node_modules/@mininglamp-oss/octo-runtime-adapter-codex/dist/app-server.d.ts +1 -0
  16. package/node_modules/@mininglamp-oss/octo-runtime-adapter-codex/dist/app-server.js +200 -106
  17. package/node_modules/@mininglamp-oss/octo-runtime-adapter-codex/dist/async-questions.d.ts +27 -0
  18. package/node_modules/@mininglamp-oss/octo-runtime-adapter-codex/dist/async-questions.js +205 -0
  19. package/node_modules/@mininglamp-oss/octo-runtime-adapter-codex/dist/stdin-writer.d.ts +30 -0
  20. package/node_modules/@mininglamp-oss/octo-runtime-adapter-codex/dist/stdin-writer.js +223 -0
  21. package/node_modules/@mininglamp-oss/octo-runtime-adapter-codex/package.json +3 -3
  22. package/node_modules/@mininglamp-oss/octo-runtime-adapter-dsh/dist/{chunk-V5W6ZTYC.js → chunk-FGFEM7JP.js} +1 -1
  23. package/node_modules/@mininglamp-oss/octo-runtime-adapter-dsh/dist/{chunk-CFKMMCO6.js → chunk-R3PDZLX5.js} +3 -3
  24. package/node_modules/@mininglamp-oss/octo-runtime-adapter-dsh/dist/{chunk-LO34KB7D.js → chunk-TSRZVLIG.js} +1 -1
  25. package/node_modules/@mininglamp-oss/octo-runtime-adapter-dsh/dist/dsh-sdk-NOTICE.txt +2 -2
  26. package/node_modules/@mininglamp-oss/octo-runtime-adapter-dsh/dist/errors.js +1 -1
  27. package/node_modules/@mininglamp-oss/octo-runtime-adapter-dsh/dist/index.js +5 -5
  28. package/node_modules/@mininglamp-oss/octo-runtime-adapter-dsh/dist/launch.js +2 -2
  29. package/node_modules/@mininglamp-oss/octo-runtime-adapter-dsh/dist/trajectory.js +2 -2
  30. package/node_modules/@mininglamp-oss/octo-runtime-adapter-dsh/package.json +3 -3
  31. package/node_modules/@mininglamp-oss/octo-runtime-adapter-grok-build/package.json +5 -5
  32. package/node_modules/@mininglamp-oss/octo-runtime-adapter-hermes/package.json +2 -2
  33. package/node_modules/@mininglamp-oss/octo-runtime-adapter-kimi-code/package.json +2 -2
  34. package/node_modules/@mininglamp-oss/octo-runtime-adapter-mcode/package.json +2 -2
  35. package/node_modules/@mininglamp-oss/octo-runtime-adapter-openclaw/dist/gateway.d.ts +3 -0
  36. package/node_modules/@mininglamp-oss/octo-runtime-adapter-openclaw/dist/gateway.js +57 -13
  37. package/node_modules/@mininglamp-oss/octo-runtime-adapter-openclaw/dist/index.d.ts +3 -2
  38. package/node_modules/@mininglamp-oss/octo-runtime-adapter-openclaw/dist/index.js +4 -2
  39. package/node_modules/@mininglamp-oss/octo-runtime-adapter-openclaw/package.json +3 -3
  40. package/node_modules/@mininglamp-oss/octo-runtime-adapter-opencode/package.json +4 -4
  41. package/node_modules/@mininglamp-oss/octo-runtime-adapter-qodercli/package.json +2 -2
  42. package/node_modules/@mininglamp-oss/octo-runtime-adapter-qoderclicn/package.json +2 -2
  43. package/node_modules/@mininglamp-oss/octo-runtime-adapter-sdk/dist/approval.js +2 -0
  44. package/node_modules/@mininglamp-oss/octo-runtime-adapter-sdk/dist/index.d.ts +1 -1
  45. package/node_modules/@mininglamp-oss/octo-runtime-adapter-sdk/dist/index.js +1 -1
  46. package/node_modules/@mininglamp-oss/octo-runtime-adapter-sdk/dist/public-display.d.ts +2 -0
  47. package/node_modules/@mininglamp-oss/octo-runtime-adapter-sdk/dist/public-display.js +22 -0
  48. package/node_modules/@mininglamp-oss/octo-runtime-adapter-sdk/dist/runtime-log.js +20 -0
  49. package/node_modules/@mininglamp-oss/octo-runtime-adapter-sdk/dist/service-status.js +14 -1
  50. package/node_modules/@mininglamp-oss/octo-runtime-adapter-sdk/package.json +2 -2
  51. package/node_modules/@mininglamp-oss/octo-runtime-adapter-zcode-gui/package.json +3 -3
  52. package/node_modules/@mininglamp-oss/octo-runtime-cli/dist/build-info.json +2 -2
  53. package/node_modules/@mininglamp-oss/octo-runtime-cli/dist/command-tree.js +3 -1
  54. package/node_modules/@mininglamp-oss/octo-runtime-cli/dist/output.js +5 -2
  55. package/node_modules/@mininglamp-oss/octo-runtime-cli/dist/playboard.js +11 -2
  56. package/node_modules/@mininglamp-oss/octo-runtime-cli/package.json +24 -24
  57. package/node_modules/@mininglamp-oss/octo-runtime-cross-service/dist/launchd.d.ts +2 -2
  58. package/node_modules/@mininglamp-oss/octo-runtime-cross-service/dist/launchd.js +12 -11
  59. package/node_modules/@mininglamp-oss/octo-runtime-cross-service/package.json +1 -1
  60. package/node_modules/@mininglamp-oss/octo-runtime-executor-core/dist/experience.js +2 -1
  61. package/node_modules/@mininglamp-oss/octo-runtime-executor-core/dist/index.d.ts +5 -4
  62. package/node_modules/@mininglamp-oss/octo-runtime-executor-core/dist/index.js +7 -4
  63. package/node_modules/@mininglamp-oss/octo-runtime-executor-core/dist/invoke-input.js +9 -2
  64. package/node_modules/@mininglamp-oss/octo-runtime-executor-core/dist/watchdog.js +6 -3
  65. package/node_modules/@mininglamp-oss/octo-runtime-executor-core/package.json +3 -3
  66. package/node_modules/@mininglamp-oss/octo-runtime-executor-kernel/dist/async-question-reply.d.ts +30 -0
  67. package/node_modules/@mininglamp-oss/octo-runtime-executor-kernel/dist/async-question-reply.js +199 -0
  68. package/node_modules/@mininglamp-oss/octo-runtime-executor-kernel/dist/host-run-service.js +2 -2
  69. package/node_modules/@mininglamp-oss/octo-runtime-executor-kernel/dist/index.d.ts +1 -0
  70. package/node_modules/@mininglamp-oss/octo-runtime-executor-kernel/dist/index.js +1 -0
  71. package/node_modules/@mininglamp-oss/octo-runtime-executor-kernel/dist/rpc.d.ts +2 -0
  72. package/node_modules/@mininglamp-oss/octo-runtime-executor-kernel/dist/rpc.js +16 -3
  73. package/node_modules/@mininglamp-oss/octo-runtime-executor-kernel/dist/server.js +36 -19
  74. package/node_modules/@mininglamp-oss/octo-runtime-executor-kernel/package.json +4 -4
  75. package/node_modules/@mininglamp-oss/octo-runtime-extra-channel-gateway/dist/application/im-channel.js +27 -35
  76. package/node_modules/@mininglamp-oss/octo-runtime-extra-channel-gateway/dist/contracts.d.ts +5 -4
  77. package/node_modules/@mininglamp-oss/octo-runtime-extra-channel-gateway/dist/delivery/dispatcher.d.ts +4 -0
  78. package/node_modules/@mininglamp-oss/octo-runtime-extra-channel-gateway/dist/delivery/dispatcher.js +29 -6
  79. package/node_modules/@mininglamp-oss/octo-runtime-extra-channel-gateway/dist/delivery/identity.d.ts +1 -1
  80. package/node_modules/@mininglamp-oss/octo-runtime-extra-channel-gateway/dist/delivery/identity.js +2 -2
  81. package/node_modules/@mininglamp-oss/octo-runtime-extra-channel-gateway/dist/delivery/send-error.d.ts +6 -0
  82. package/node_modules/@mininglamp-oss/octo-runtime-extra-channel-gateway/dist/delivery/send-error.js +10 -0
  83. package/node_modules/@mininglamp-oss/octo-runtime-extra-channel-gateway/dist/execution/task.js +14 -0
  84. package/node_modules/@mininglamp-oss/octo-runtime-extra-channel-gateway/dist/transport/card-session.d.ts +3 -2
  85. package/node_modules/@mininglamp-oss/octo-runtime-extra-channel-gateway/dist/transport/card-session.js +54 -10
  86. package/node_modules/@mininglamp-oss/octo-runtime-extra-channel-gateway/dist/transport/channel.d.ts +4 -2
  87. package/node_modules/@mininglamp-oss/octo-runtime-extra-channel-gateway/dist/transport/channel.js +77 -109
  88. package/node_modules/@mininglamp-oss/octo-runtime-extra-channel-gateway/dist/transport/connector.d.ts +3 -5
  89. package/node_modules/@mininglamp-oss/octo-runtime-extra-channel-gateway/dist/transport/connector.js +27 -40
  90. package/node_modules/@mininglamp-oss/octo-runtime-extra-channel-gateway/dist/transport/interaction-card.js +2 -1
  91. package/node_modules/@mininglamp-oss/octo-runtime-extra-channel-gateway/dist/transport/reasoning-frame.js +42 -7
  92. package/node_modules/@mininglamp-oss/octo-runtime-extra-channel-gateway/dist/transport/session-command.d.ts +9 -0
  93. package/node_modules/@mininglamp-oss/octo-runtime-extra-channel-gateway/dist/transport/session-command.js +71 -0
  94. package/node_modules/@mininglamp-oss/octo-runtime-extra-channel-gateway/dist/transport/wukong.d.ts +1 -12
  95. package/node_modules/@mininglamp-oss/octo-runtime-extra-channel-gateway/dist/transport/wukong.js +6 -126
  96. package/node_modules/@mininglamp-oss/octo-runtime-extra-channel-gateway/package.json +6 -6
  97. package/node_modules/@mininglamp-oss/octo-runtime-extra-channel-wecom/dist/application/im-channel.js +14 -0
  98. package/node_modules/@mininglamp-oss/octo-runtime-extra-channel-wecom/package.json +5 -5
  99. package/node_modules/@mininglamp-oss/octo-runtime-extra-webui/dist/web/assets/{index-CXTvRGim.js → index-BVxePruX.js} +11 -10
  100. package/node_modules/@mininglamp-oss/octo-runtime-extra-webui/dist/web/index.html +1 -1
  101. package/node_modules/@mininglamp-oss/octo-runtime-extra-webui/package.json +2 -2
  102. package/node_modules/@mininglamp-oss/octo-runtime-host-sdk/dist/context-loader.js +1 -1
  103. package/node_modules/@mininglamp-oss/octo-runtime-host-sdk/package.json +4 -4
  104. package/node_modules/@mininglamp-oss/octo-runtime-protocol/dist/browser.d.ts +1 -0
  105. package/node_modules/@mininglamp-oss/octo-runtime-protocol/dist/browser.js +1 -0
  106. package/node_modules/@mininglamp-oss/octo-runtime-protocol/dist/context.d.ts +2 -0
  107. package/node_modules/@mininglamp-oss/octo-runtime-protocol/dist/context.js +4 -1
  108. package/node_modules/@mininglamp-oss/octo-runtime-protocol/dist/failure.d.ts +3 -0
  109. package/node_modules/@mininglamp-oss/octo-runtime-protocol/dist/failure.js +63 -12
  110. package/node_modules/@mininglamp-oss/octo-runtime-protocol/dist/generated/protocol-types.d.ts +110 -5
  111. package/node_modules/@mininglamp-oss/octo-runtime-protocol/dist/index.d.ts +7 -4
  112. package/node_modules/@mininglamp-oss/octo-runtime-protocol/dist/index.js +28 -6
  113. package/node_modules/@mininglamp-oss/octo-runtime-protocol/dist/invoke-input.js +2 -0
  114. package/node_modules/@mininglamp-oss/octo-runtime-protocol/dist/questions.d.ts +9 -0
  115. package/node_modules/@mininglamp-oss/octo-runtime-protocol/dist/questions.js +84 -0
  116. package/node_modules/@mininglamp-oss/octo-runtime-protocol/dist/run-protocol.d.ts +1 -1
  117. package/node_modules/@mininglamp-oss/octo-runtime-protocol/dist/run-protocol.js +11 -5
  118. package/node_modules/@mininglamp-oss/octo-runtime-protocol/package.json +1 -1
  119. package/package.json +27 -27
  120. package/packages/octo-runtime-protocol/schema/protocol.schema.json +156 -4
  121. package/node_modules/@mininglamp-oss/octo-runtime-extra-channel-gateway/dist/delivery/text-send.d.ts +0 -19
  122. package/node_modules/@mininglamp-oss/octo-runtime-extra-channel-gateway/dist/delivery/text-send.js +0 -86
  123. package/node_modules/@mininglamp-oss/octo-runtime-extra-channel-gateway/dist/presentation/delivery-notice.d.ts +0 -5
  124. package/node_modules/@mininglamp-oss/octo-runtime-extra-channel-gateway/dist/presentation/delivery-notice.js +0 -35
@@ -1,6 +1,8 @@
1
1
  import { actmodeEvidence, invocationEnvs, mapReasoningEffort } from "@mininglamp-oss/octo-runtime-adapter-sdk";
2
- import { canonicalTerminalStatus, classifyFailure, contextHash, contextActmode, assertJsonByteLimit, INVOKE_REQUEST_MAX_BYTES, hasImageInput, providerInputParts, PROVIDER_DIAGNOSTIC_MAX_BYTES, resolveStreamLimitPolicy, streamCapacityError } from "@mininglamp-oss/octo-runtime-protocol";
2
+ import { canonicalTerminalStatus, classifyFailure, isCodexLocalFailureReason, isStreamCapacityReason, contextHash, contextActmode, assertJsonByteLimit, INVOKE_REQUEST_MAX_BYTES, hasImageInput, providerInputParts, PROVIDER_DIAGNOSTIC_MAX_BYTES, resolveStreamLimitPolicy, streamCapacityError } from "@mininglamp-oss/octo-runtime-protocol";
3
+ import { CodexStdinWriter, codexTransportError } from "./stdin-writer.js";
3
4
  import { codexEnvironmentConfig } from "./environment.js";
5
+ import { CodexAsyncQuestions, asyncQuestionMetadata } from "./async-questions.js";
4
6
  import { createProcessCleanup } from "@mininglamp-oss/octo-runtime-adapter-sdk/process-cleanup";
5
7
  import { resolveProcessLaunch } from "@mininglamp-oss/octo-runtime-adapter-sdk/process-launch";
6
8
  /**
@@ -50,6 +52,7 @@ export class CodexAppServerRpcError extends Error {
50
52
  /** Error for when the subprocess exits without producing a run terminal, preserving exit code/signal. */
51
53
  export class CodexAppServerProcessError extends Error {
52
54
  exit;
55
+ code = "CODEX_TRANSPORT_FAILED";
53
56
  constructor(message, exit) {
54
57
  super(message);
55
58
  this.exit = exit;
@@ -138,6 +141,8 @@ export async function* runCodexAppServerTurn({ request, spec, spawnFn = defaultS
138
141
  resumed = true;
139
142
  }
140
143
  catch (error) {
144
+ if (request.providerSession?.requireResume === true)
145
+ throw error;
141
146
  // A failed resume does not abort this turn; record a low-cardinality reason and fall back to a fresh thread.
142
147
  resumeFallback = rpcFailureReason(error);
143
148
  }
@@ -148,6 +153,8 @@ export async function* runCodexAppServerTurn({ request, spec, spawnFn = defaultS
148
153
  let threadId = extractThreadId(threadResult);
149
154
  if (!threadId)
150
155
  throw new Error("codex thread start/resume returned no thread id");
156
+ if (request.providerSession?.requireResume === true && threadId !== requestedSessionId)
157
+ throw new Error("codex required session resume returned a different thread id");
151
158
  client.setActiveThread(threadId);
152
159
  // 名称属于调用方;只命名本轮新建 thread,恢复时保留原生标题与句柄。
153
160
  if (!resumed && request.sessionName)
@@ -187,7 +194,7 @@ export async function* runCodexAppServerTurn({ request, spec, spawnFn = defaultS
187
194
  }
188
195
  catch (error) {
189
196
  // Some corrupt sessions pass thread/resume but only reveal the missing rollout at turn/start.
190
- if (!resumed || !isThreadNotFound(error))
197
+ if (!resumed || !isThreadNotFound(error) || request.providerSession?.requireResume === true)
191
198
  throw error;
192
199
  resumeFallback = "turn_start_thread_not_found";
193
200
  resumed = false;
@@ -216,7 +223,7 @@ export async function* runCodexAppServerTurn({ request, spec, spawnFn = defaultS
216
223
  nativeMode: effectiveMode,
217
224
  ...(effectiveMode !== requestedMode ? { reason: "provider_unsupported" } : {})
218
225
  }, context?.protocolMode);
219
- // Must come after turn/start: otherwise the Core would persist a provider session that cannot be executed.
226
+ // turn/start 成功后才发布权威会话更新,供调用方保存完整 binding;Core 不持久化业务会话绑定。
220
227
  const session = {
221
228
  protocolVersion: 2,
222
229
  type: "session.update",
@@ -330,8 +337,12 @@ async function closeClientAndResources(client, spec, executionFailure) {
330
337
  }
331
338
  catch (cleanupError) {
332
339
  // R06b:清理失败不能覆盖原始执行失败,也不能阻止调用方资源释放。
333
- if (executionFailure !== undefined)
334
- throw new AggregateError([executionFailure, cleanupError], "Codex execution and process cleanup failed", { cause: cleanupError });
340
+ if (executionFailure !== undefined) {
341
+ const error = new AggregateError([executionFailure, cleanupError], "Codex execution and process cleanup failed", { cause: cleanupError });
342
+ // Core 从顶层 code 分类;保留本地执行首因,同时用 errors/cause 暴露清理失败。
343
+ const code = stringErrorCode(executionFailure);
344
+ throw isCodexLocalFailureReason(code) ? Object.assign(error, { code }) : error;
345
+ }
335
346
  throw cleanupError;
336
347
  }
337
348
  finally {
@@ -1007,7 +1018,9 @@ class CodexAppServerClient {
1007
1018
  #normalizer;
1008
1019
  #native;
1009
1020
  #pending = new Map();
1021
+ #writer;
1010
1022
  #interactions = new Map();
1023
+ #asyncQuestions;
1011
1024
  #nativeRequestIds = new Set();
1012
1025
  #requestTimeoutMs;
1013
1026
  #interactive;
@@ -1084,8 +1097,14 @@ class CodexAppServerClient {
1084
1097
  const id = stringValue(item?.id);
1085
1098
  if (id)
1086
1099
  this.#openItems.delete(id);
1100
+ // 旁路消息不是最终收尾;completed-only 通知也必须撤销先前的收尾猜测。
1101
+ if (item?.type === "agentMessage" && item.delivery === "async") {
1102
+ this.#clearFinalizationTimer();
1103
+ return;
1104
+ }
1087
1105
  if (item?.type !== "agentMessage" ||
1088
1106
  item.phase !== "final_answer" ||
1107
+ item.delivery === "async" ||
1089
1108
  params.threadId !== this.#activeThreadId ||
1090
1109
  notificationTurnId(params) !== this.#activeTurnId ||
1091
1110
  this.#openItems.size ||
@@ -1105,6 +1124,7 @@ class CodexAppServerClient {
1105
1124
  this.#finalizationGraceTimer = setTimeout(() => {
1106
1125
  if (this.#terminal || this.#closed)
1107
1126
  return;
1127
+ this.#invalidateInteractions("run_terminal");
1108
1128
  this.#terminal = true;
1109
1129
  this.#queue.push(this.#finalizationFailure());
1110
1130
  if (this.#native)
@@ -1156,9 +1176,11 @@ class CodexAppServerClient {
1156
1176
  this.#streamLimits = resolveStreamLimitPolicy(context?.streamLimits);
1157
1177
  this.#queue = new DriverQueue({
1158
1178
  limits: this.#streamLimits,
1159
- boundary: "codex.event_queue"
1179
+ boundary: "codex.event_queue",
1180
+ onFailure: (error) => this.#handleProcessError(error)
1160
1181
  });
1161
1182
  this.#native = context?.protocolMode === "native";
1183
+ this.#asyncQuestions = new CodexAsyncQuestions(invocation.invocationId, (event) => this.#queue.push(event), (params, accept, rejected) => this.request("turn/steer", params, this.#requestTimeoutMs, undefined, undefined, accept, rejected));
1162
1184
  if (!this.#native)
1163
1185
  this.#normalizer = new CodexEventNormalizer();
1164
1186
  this.#requestTimeoutMs = requestTimeoutMs;
@@ -1169,6 +1191,7 @@ class CodexAppServerClient {
1169
1191
  this.#resolveExit = resolve;
1170
1192
  });
1171
1193
  this.#child = spawnFn(spec.command, spec.args, { cwd: spec.cwd, env: spec.env });
1194
+ this.#writer = new CodexStdinWriter(this.#child.stdin, (error) => this.#handleProcessError(error));
1172
1195
  this.#cleanupProcess = createProcessCleanup(this.#child, {
1173
1196
  // 只有 production defaultSpawn 明确拥有独立组;注入的 child 不推定拥有组。
1174
1197
  processGroup: isolatedProcessGroups.has(this.#child)
@@ -1184,7 +1207,14 @@ class CodexAppServerClient {
1184
1207
  signalProcessTree(this.#child, "SIGTERM");
1185
1208
  });
1186
1209
  this.#reader = createInterface({ input: this.#child.stdout });
1187
- this.#reader.on("line", (line) => this.#handleLine(line));
1210
+ this.#reader.on("line", (line) => {
1211
+ try {
1212
+ this.#handleLine(line);
1213
+ }
1214
+ catch (error) {
1215
+ this.#handleProcessError(error instanceof Error ? error : new Error(String(error)), "protocol");
1216
+ }
1217
+ });
1188
1218
  this.#child.stderr.setEncoding("utf8");
1189
1219
  this.#child.stderr.on("data", (chunk) => {
1190
1220
  this.#stderr = (this.#stderr + chunk.toString()).slice(-STDERR_TAIL_LIMIT);
@@ -1260,22 +1290,39 @@ class CodexAppServerClient {
1260
1290
  }
1261
1291
  else
1262
1292
  throw protocolError("NATIVE_METHOD_UNSUPPORTED");
1293
+ await this.#deliverInteraction(interactionId, pending, payload);
1294
+ }
1295
+ /** 冻结一次决定后立即释放人工额度;只有写回调成功才能确认 resolved。 */
1296
+ #deliverInteraction(interactionId, pending, reply, outcome, automatic = false) {
1263
1297
  pending.responding = true;
1264
- await new Promise((resolve, reject) => this.#write(payload, (error) => {
1265
- this.#invalidateInteractions("response_delivery_failed");
1266
- this.#queue.fail(error);
1267
- signalProcessTree(this.#child, "SIGTERM");
1268
- reject(error);
1269
- }, () => {
1270
- if (!this.#interactions.has(interactionId)) {
1271
- reject(protocolError("INTERACTION_NOT_ACTIVE"));
1272
- return;
1273
- }
1274
- clearTimeout(pending.timer);
1275
- this.#interactions.delete(interactionId);
1276
- this.#interactionState(interactionId, pending.rpcId, "resolved");
1277
- resolve();
1278
- }));
1298
+ pending.params = {};
1299
+ pending.retainedBytes = 0;
1300
+ clearTimeout(pending.timer);
1301
+ return new Promise((resolve, reject) => {
1302
+ this.#write(reply, reject, () => {
1303
+ if (this.#interactions.get(interactionId) !== pending || this.#terminal) {
1304
+ reject(protocolError("INTERACTION_NOT_ACTIVE"));
1305
+ return;
1306
+ }
1307
+ this.#interactions.delete(interactionId);
1308
+ if (this.#native || automatic) {
1309
+ this.#interactionState(interactionId, pending.rpcId, "resolved", automatic ? "full_access_policy" : undefined);
1310
+ }
1311
+ else {
1312
+ this.#queue.push({
1313
+ protocolVersion: 2,
1314
+ type: "interaction.resolved",
1315
+ payload: {
1316
+ interactionId,
1317
+ executionInstanceId: this.invocation.invocationId,
1318
+ status: "resolved",
1319
+ outcome
1320
+ }
1321
+ });
1322
+ }
1323
+ resolve();
1324
+ }, { timeoutMs: Math.max(1, pending.expiresAt - Date.now()) });
1325
+ });
1279
1326
  }
1280
1327
  #interactionState(interactionId, requestId, status, reasonCode) {
1281
1328
  this.#queue.push(this.#native
@@ -1294,6 +1341,11 @@ class CodexAppServerClient {
1294
1341
  }
1295
1342
  /** Resume one provider reverse request after the durable Worker response reaches this invocation. */
1296
1343
  respondInteraction(response) {
1344
+ if (response.interactionId.startsWith("codex:async:")) {
1345
+ if (this.#native || this.#closed || this.#exited || this.#terminal)
1346
+ return Promise.reject(protocolError("INTERACTION_NOT_ACTIVE"));
1347
+ return this.#asyncQuestions.respond(response);
1348
+ }
1297
1349
  if (this.#closed || this.#exited || this.#terminal) {
1298
1350
  return Promise.reject(new Error("codex interaction is no longer active"));
1299
1351
  }
@@ -1313,40 +1365,21 @@ class CodexAppServerClient {
1313
1365
  catch (error) {
1314
1366
  return Promise.reject(error instanceof Error ? error : new Error(String(error)));
1315
1367
  }
1316
- pending.responding = true;
1317
- return new Promise((resolve, reject) => {
1318
- this.#write({ jsonrpc: "2.0", id: pending.rpcId, ...reply }, (error) => {
1319
- pending.responding = false;
1320
- reject(error);
1321
- }, () => {
1322
- if (!this.#interactions.has(response.interactionId)) {
1323
- reject(new Error("INTERACTION_NOT_ACTIVE"));
1324
- return;
1325
- }
1326
- clearTimeout(pending.timer);
1327
- this.#interactions.delete(response.interactionId);
1328
- this.#queue.push({
1329
- protocolVersion: 2,
1330
- type: "interaction.resolved",
1331
- payload: {
1332
- interactionId: response.interactionId,
1333
- executionInstanceId: this.invocation.invocationId,
1334
- status: "resolved",
1335
- outcome: response.outcome
1336
- }
1337
- });
1338
- resolve();
1339
- });
1340
- });
1368
+ return this.#deliverInteraction(response.interactionId, pending, { jsonrpc: "2.0", id: pending.rpcId, ...reply }, response.outcome);
1341
1369
  }
1342
1370
  exit() {
1343
1371
  return this.#exitPromise;
1344
1372
  }
1345
- request(method, params, timeoutMs = this.#requestTimeoutMs, onWritten, requestId) {
1373
+ request(method, params, timeoutMs = this.#requestTimeoutMs, onWritten, requestId, accept, rejected) {
1346
1374
  if (this.#transportFailure)
1347
- return Promise.reject(this.#transportFailure);
1375
+ return Promise.reject(Object.assign(new Error("codex transport unavailable", { cause: this.#transportFailure }), {
1376
+ deliveryNotAttempted: true,
1377
+ ...(stringErrorCode(this.#transportFailure)
1378
+ ? { code: stringErrorCode(this.#transportFailure) }
1379
+ : {})
1380
+ }));
1348
1381
  if (this.#closed || this.#exited) {
1349
- return Promise.reject(new Error("codex app-server is closed"));
1382
+ return Promise.reject(Object.assign(new Error("codex app-server is closed"), { deliveryNotAttempted: true }));
1350
1383
  }
1351
1384
  const id = requestId ?? this.reserveRequestId();
1352
1385
  if (this.#pending.has(id)) {
@@ -1355,8 +1388,10 @@ class CodexAppServerClient {
1355
1388
  return new Promise((resolve, reject) => {
1356
1389
  // Register pending before writing stdin, so a synchronous reply from a test server/local process cannot arrive first.
1357
1390
  const timer = setTimeout(() => {
1391
+ const expired = this.#pending.get(id);
1358
1392
  if (!this.#pending.delete(id))
1359
1393
  return;
1394
+ expired?.cancelWrite?.();
1360
1395
  reject(Object.assign(new Error(`codex app-server ${method} timed out after ${timeoutMs}ms`), {
1361
1396
  code: "RPC_TIMEOUT",
1362
1397
  timeoutStage: "rpc",
@@ -1364,17 +1399,27 @@ class CodexAppServerClient {
1364
1399
  timeoutMs
1365
1400
  }));
1366
1401
  }, timeoutMs);
1367
- this.#pending.set(id, { method, resolve, reject, timer });
1402
+ this.#pending.set(id, {
1403
+ method,
1404
+ resolve,
1405
+ reject,
1406
+ timer,
1407
+ ...(accept ? { accept } : {}),
1408
+ ...(rejected ? { rejected } : {})
1409
+ });
1368
1410
  // onWritten is deliberately passed through to #write instead of running
1369
1411
  // before it; callers use it as the transport-written observation boundary.
1370
- this.#write({ jsonrpc: "2.0", id, method, params }, (error) => {
1412
+ const cancelWrite = this.#write({ jsonrpc: "2.0", id, method, params }, (error) => {
1371
1413
  const pending = this.#pending.get(id);
1372
1414
  if (!pending)
1373
1415
  return;
1374
1416
  this.#pending.delete(id);
1375
1417
  clearTimeout(pending.timer);
1376
1418
  pending.reject(error);
1377
- }, onWritten);
1419
+ }, onWritten, { control: method === "turn/interrupt", timeoutMs });
1420
+ const pending = this.#pending.get(id);
1421
+ if (pending)
1422
+ pending.cancelWrite = cancelWrite;
1378
1423
  });
1379
1424
  }
1380
1425
  /** Allocate the exact JSON-RPC id a subsequent request will put on the wire. */
@@ -1396,6 +1441,7 @@ class CodexAppServerClient {
1396
1441
  close() {
1397
1442
  return (this.#closePromise ??= (async () => {
1398
1443
  this.#closed = true;
1444
+ this.#writer.stop(protocolError("INTERACTION_NOT_ACTIVE"));
1399
1445
  this.#clearFinalizationTimer();
1400
1446
  if (this.#finalizationGraceTimer)
1401
1447
  clearTimeout(this.#finalizationGraceTimer);
@@ -1473,7 +1519,7 @@ class CodexAppServerClient {
1473
1519
  if (this.#native) {
1474
1520
  this.#queue.push({ kind: "native", messageKind: "notification", payload: message });
1475
1521
  if (method === "turn/completed") {
1476
- this.#invalidateInteractions("run_terminal");
1522
+ this.#invalidateInteractions(recordValue(params.turn)?.status === "completed" ? "run_completed" : "run_terminal");
1477
1523
  this.#terminal = true;
1478
1524
  this.#clearFinalizationTimer();
1479
1525
  if (this.#finalizationGraceTimer)
@@ -1497,7 +1543,7 @@ class CodexAppServerClient {
1497
1543
  this.context?.reportConversion?.();
1498
1544
  for (const event of this.#normalizer.normalize({ method, params })) {
1499
1545
  if (isTerminalEvent(event)) {
1500
- this.#invalidateInteractions("run_terminal");
1546
+ this.#invalidateInteractions(event.type === "run.completed" ? "run_completed" : "run_terminal");
1501
1547
  this.#terminal = true;
1502
1548
  this.#clearFinalizationTimer();
1503
1549
  if (this.#finalizationGraceTimer)
@@ -1510,6 +1556,14 @@ class CodexAppServerClient {
1510
1556
  else
1511
1557
  this.#queue.push(event);
1512
1558
  }
1559
+ if (method === "item/completed" &&
1560
+ !this.#terminal &&
1561
+ params.threadId === this.#activeThreadId &&
1562
+ notificationTurnId(params) === this.#activeTurnId) {
1563
+ const item = recordValue(params.item);
1564
+ if (item?.type === "agentMessage" && this.#activeThreadId && this.#activeTurnId)
1565
+ this.#asyncQuestions.register(item, this.#activeThreadId, this.#activeTurnId, [...this.#interactions.values()].filter((pending) => pending.kind !== "approval").length);
1566
+ }
1513
1567
  }
1514
1568
  #isBoundedInputEcho(message) {
1515
1569
  if (this.#native || !message)
@@ -1567,10 +1621,18 @@ class CodexAppServerClient {
1567
1621
  this.context?.reportActivity?.({ kind: "transport_response", method: "rpc_response" });
1568
1622
  const error = recordValue(message.error);
1569
1623
  if (error) {
1570
- pending.reject(new CodexAppServerRpcError(pending.method, numberValue(error.code) ?? -32000, stringValue(error.message) || "unknown app-server error", error.data));
1624
+ const rejected = new CodexAppServerRpcError(pending.method, numberValue(error.code) ?? -32000, stringValue(error.message) || "unknown app-server error", error.data);
1625
+ pending.rejected?.(rejected);
1626
+ pending.reject(rejected);
1571
1627
  return;
1572
1628
  }
1573
- pending.resolve(message.result);
1629
+ try {
1630
+ pending.accept?.(message.result);
1631
+ pending.resolve(message.result);
1632
+ }
1633
+ catch (error) {
1634
+ pending.reject(error instanceof Error ? error : new Error(String(error)));
1635
+ }
1574
1636
  }
1575
1637
  #handleServerRequest(id, method, params, message) {
1576
1638
  this.#clearFinalizationTimer();
@@ -1602,44 +1664,77 @@ class CodexAppServerClient {
1602
1664
  this.#nativeRequestIds.add(id);
1603
1665
  if (method === "item/permissions/requestApproval") {
1604
1666
  this.#rejectServerRequest(id, method);
1605
- this.#queue.fail(new Error("APPROVAL_GRANT_SCOPE_UNSUPPORTED"));
1606
- return;
1607
- }
1608
- if (this.#interactions.size >= 16) {
1609
- this.#rejectServerRequest(id, method);
1610
- this.#queue.fail(new Error("APPROVAL_PENDING_LIMIT_EXCEEDED"));
1667
+ this.#handleProcessError(codexTransportError("APPROVAL_GRANT_SCOPE_UNSUPPORTED"));
1611
1668
  return;
1612
1669
  }
1613
- const interactionId = codexInteractionId(id, this.invocation.invocationId, this.#nextInteractionId++);
1614
1670
  if ([...this.#interactions.values()].some((pending) => pending.rpcId === id)) {
1615
1671
  this.#write({
1616
1672
  jsonrpc: "2.0",
1617
1673
  id,
1618
1674
  error: { code: -32600, message: "duplicate provider interaction id" }
1675
+ }, undefined, undefined, { control: true });
1676
+ return;
1677
+ }
1678
+ const automatic = !this.#interactive && kind === "approval";
1679
+ const waiting = [...this.#interactions.values()];
1680
+ if (!automatic &&
1681
+ kind === "approval" &&
1682
+ waiting.filter((pending) => pending.kind === "approval" && !pending.responding).length >= 256) {
1683
+ if (this.#native)
1684
+ this.#queue.push({ kind: "native", messageKind: "request", payload: message });
1685
+ this.context?.log?.("warn", "codex.approval_capacity", {
1686
+ invocation_id: this.invocation.invocationId,
1687
+ code: "APPROVAL_PENDING_LIMIT_EXCEEDED"
1619
1688
  });
1689
+ // 容量拒绝也是正常突发流量,使用普通有界队列;不能因 9 条拒绝挤满控制预留而终止整轮。
1690
+ this.#write({ jsonrpc: "2.0", id, error: { code: -32000, message: "APPROVAL_PENDING_LIMIT_EXCEEDED" } }, undefined, undefined, { control: false });
1620
1691
  return;
1621
1692
  }
1693
+ if (kind !== "approval" &&
1694
+ waiting.filter((pending) => pending.kind !== "approval").length + this.#asyncQuestions.size >=
1695
+ 16) {
1696
+ this.#handleProcessError(codexTransportError("CODEX_INTERACTION_PENDING_LIMIT_EXCEEDED"));
1697
+ return;
1698
+ }
1699
+ const retainedBytes = automatic ? 0 : Buffer.byteLength(JSON.stringify(params));
1700
+ if (waiting.reduce((bytes, pending) => bytes + pending.retainedBytes, retainedBytes) >
1701
+ this.#streamLimits.adapterQueueMaxBytes) {
1702
+ this.#handleProcessError(codexTransportError("CODEX_INTERACTION_BYTES_EXCEEDED"));
1703
+ return;
1704
+ }
1705
+ const interactionId = codexInteractionId(id, this.invocation.invocationId, this.#nextInteractionId++);
1622
1706
  const expiresAt = Date.now() + 600_000;
1623
1707
  const timer = setTimeout(() => {
1624
1708
  this.#interactions.delete(interactionId);
1625
1709
  this.#interactionState(interactionId, id, "expired", "approval_timeout");
1626
1710
  this.#rejectServerRequest(id, method);
1627
- this.#queue.fail(new Error("INTERACTION_EXPIRED"));
1628
- }, 600_000);
1711
+ this.#handleProcessError(codexTransportError("INTERACTION_EXPIRED"));
1712
+ }, expiresAt - Date.now());
1629
1713
  timer.unref?.();
1630
1714
  this.#interactions.set(interactionId, {
1631
1715
  rpcId: id,
1632
1716
  method,
1633
1717
  params,
1634
- responding: false,
1718
+ responding: automatic,
1719
+ kind,
1720
+ retainedBytes,
1635
1721
  timer,
1636
1722
  expiresAt
1637
1723
  });
1724
+ // 自动审批的响应仍由 Driver 写入并确认;pending 只声明外部是否需要回答,
1725
+ // 不能让消费者将“正在自动处理”误判为已批准或执行完成。
1726
+ const responseRequired = this.#interactive || kind !== "approval";
1638
1727
  if (this.#native) {
1639
1728
  this.#queue.push({ kind: "native", messageKind: "request", payload: message });
1640
1729
  this.#queue.push({
1641
1730
  kind: "control",
1642
- control: { type: "interaction", requestId: id, status: "pending", expiresAt }
1731
+ control: {
1732
+ type: "interaction",
1733
+ requestId: id,
1734
+ status: "pending",
1735
+ expiresAt,
1736
+ responseRequired
1737
+ }
1643
1738
  });
1644
1739
  }
1645
1740
  else {
@@ -1650,6 +1745,7 @@ class CodexAppServerClient {
1650
1745
  payload: {
1651
1746
  interactionId,
1652
1747
  kind,
1748
+ responseRequired,
1653
1749
  executionInstanceId: this.invocation.invocationId,
1654
1750
  expiresAt: new Date(expiresAt).toISOString(),
1655
1751
  request: kind === "approval"
@@ -1682,21 +1778,14 @@ class CodexAppServerClient {
1682
1778
  if (automatic === undefined) {
1683
1779
  this.#rejectServerRequest(id, method);
1684
1780
  this.#invalidateInteractions("approval_mapping_unsupported");
1685
- this.#queue.fail(new Error("APPROVAL_OPERATION_UNSUPPORTED"));
1781
+ this.#handleProcessError(codexTransportError("APPROVAL_OPERATION_UNSUPPORTED"));
1686
1782
  return;
1687
1783
  }
1688
- this.#interactions.get(interactionId).responding = true;
1689
- this.#write({ jsonrpc: "2.0", id, result: automatic }, (error) => {
1690
- this.#invalidateInteractions("response_delivery_failed");
1691
- this.#queue.fail(error);
1692
- }, () => {
1693
- const pending = this.#interactions.get(interactionId);
1694
- if (!pending)
1695
- return;
1696
- clearTimeout(pending.timer);
1697
- this.#interactions.delete(interactionId);
1698
- this.#interactionState(interactionId, id, "resolved", "full_access_policy");
1699
- });
1784
+ const pending = this.#interactions.get(interactionId);
1785
+ // 发布 pending 期间输出队列可能已失败,不能继续发送已经失效的批准。
1786
+ if (!pending)
1787
+ return;
1788
+ void this.#deliverInteraction(interactionId, pending, { jsonrpc: "2.0", id, result: automatic }, undefined, true).catch(() => undefined);
1700
1789
  }
1701
1790
  }
1702
1791
  #rejectServerRequest(id, method) {
@@ -1707,30 +1796,17 @@ class CodexAppServerClient {
1707
1796
  error: { code: -32601, message: `unhandled server request: ${method}` }
1708
1797
  });
1709
1798
  }
1710
- #write(message, onError, onWritten) {
1711
- if (this.#transportFailure) {
1712
- onError?.(this.#transportFailure);
1713
- return;
1714
- }
1715
- if (this.#closed || this.#exited) {
1716
- onError?.(new Error("codex app-server is closed"));
1717
- return;
1718
- }
1719
- let line;
1720
- try {
1721
- line = `${JSON.stringify(message)}\n`;
1722
- }
1723
- catch (error) {
1724
- onError?.(error instanceof Error ? error : new Error(String(error)));
1725
- return;
1799
+ #write(message, onError, onWritten, options = {}) {
1800
+ const error = this.#transportFailure ??
1801
+ (this.#closed || this.#exited ? codexTransportError("CODEX_TRANSPORT_FAILED") : undefined);
1802
+ if (error) {
1803
+ onError?.(error);
1804
+ return () => { };
1726
1805
  }
1727
- this.#child.stdin.write(line, (error) => {
1728
- // Writable completion means local acceptance of the bytes. Only a later
1729
- // frame with the same JSON-RPC id can acknowledge a request.
1730
- if (error)
1731
- onError?.(error);
1732
- else
1733
- onWritten?.();
1806
+ return this.#writer.write(message, onError ?? (() => { }), onWritten, {
1807
+ ...options,
1808
+ // 普通容量拒绝可显式走普通队列;协议拒绝默认使用控制预留,批准不借用预留。
1809
+ control: options.control ?? Object.hasOwn(message, "error")
1734
1810
  });
1735
1811
  }
1736
1812
  #acceptNotification(params) {
@@ -1811,16 +1887,28 @@ class CodexAppServerClient {
1811
1887
  });
1812
1888
  }
1813
1889
  }
1814
- #handleProcessError(error) {
1890
+ #handleProcessError(error, source = "transport") {
1815
1891
  if (this.#transportFailure)
1816
1892
  return;
1893
+ // 本地传输异常保留稳定原因;spawn errno 与容量错误继续使用既有专用分类。
1894
+ const code = stringErrorCode(error);
1895
+ if (!(source === "protocol" && code !== undefined) &&
1896
+ !isCodexLocalFailureReason(code) &&
1897
+ !isStreamCapacityReason(code) &&
1898
+ !["ENOENT", "ENOTDIR", "EACCES", "EPERM"].includes(code ?? ""))
1899
+ error = codexTransportError("CODEX_TRANSPORT_FAILED", error);
1817
1900
  this.#transportFailure = error;
1901
+ this.#writer.stop(error);
1818
1902
  this.#reader.close();
1819
1903
  this.#clearFinalizationTimer();
1820
1904
  this.#rejectPending(error);
1821
1905
  this.#invalidateInteractions("execution_lost");
1822
- if (!this.#closing && !this.#terminal)
1906
+ if (!this.#closing && !this.#terminal) {
1823
1907
  this.#queue.fail(error);
1908
+ queueMicrotask(() => {
1909
+ void this.close().catch(() => undefined);
1910
+ });
1911
+ }
1824
1912
  }
1825
1913
  #handleExit(exit) {
1826
1914
  this.#clearFinalizationTimer();
@@ -1829,12 +1917,15 @@ class CodexAppServerClient {
1829
1917
  this.#exited = true;
1830
1918
  this.#resolveExit(exit);
1831
1919
  const error = new CodexAppServerProcessError(this.processErrorMessage(exit), exit);
1920
+ this.#writer.stop(error);
1832
1921
  this.#rejectPending(error);
1833
1922
  this.#invalidateInteractions("execution_lost");
1834
1923
  if (!this.#closing && !this.#terminal)
1835
1924
  this.#queue.fail(error);
1836
1925
  }
1837
1926
  #invalidateInteractions(reasonCode) {
1927
+ this.#writer.cancelPending(protocolError("INTERACTION_NOT_ACTIVE"));
1928
+ this.#asyncQuestions.invalidate(reasonCode);
1838
1929
  for (const [interactionId, pending] of this.#interactions) {
1839
1930
  clearTimeout(pending.timer);
1840
1931
  this.#interactionState(interactionId, pending.rpcId, "invalidated", reasonCode);
@@ -1844,6 +1935,7 @@ class CodexAppServerClient {
1844
1935
  #rejectPending(error) {
1845
1936
  for (const pending of this.#pending.values()) {
1846
1937
  clearTimeout(pending.timer);
1938
+ pending.cancelWrite?.();
1847
1939
  pending.reject(error);
1848
1940
  }
1849
1941
  this.#pending.clear();
@@ -2006,6 +2098,7 @@ function itemStartedEvents(item, stepId) {
2006
2098
  role: "assistant",
2007
2099
  status: "streaming",
2008
2100
  channel,
2101
+ ...asyncQuestionMetadata(item),
2009
2102
  ...(id ? { messageId: id } : {}),
2010
2103
  ...(stepId ? { stepId } : {})
2011
2104
  }
@@ -2063,6 +2156,7 @@ function itemCompletedEvents(item, stepId, knownChannel) {
2063
2156
  role: "assistant",
2064
2157
  status: "completed",
2065
2158
  channel,
2159
+ ...asyncQuestionMetadata(item),
2066
2160
  ...(id ? { messageId: id } : {}),
2067
2161
  ...(stepId ? { stepId } : {}),
2068
2162
  ...(typeof item.text === "string" ? { text: item.text } : {})
@@ -0,0 +1,27 @@
1
+ import { type AsyncUserInputQuestion, type CanonicalEvent, type InteractionResponse } from "@mininglamp-oss/octo-runtime-protocol";
2
+ type JsonRecord = Record<string, unknown>;
3
+ /** 保留原生异步快照;不从正文推断问题,也不授权回答历史消息。 */
4
+ export declare function asyncQuestionMetadata(item: JsonRecord): {
5
+ delivery?: "async";
6
+ questions?: AsyncUserInputQuestion[];
7
+ };
8
+ /**
9
+ * invocation 独享有界状态;transport 在读取成功 RPC 帧时同步调用 accept,
10
+ * 避免同一缓冲区的后续 turn/completed 覆盖已经观察到的接纳事实。
11
+ */
12
+ export declare class CodexAsyncQuestions {
13
+ #private;
14
+ readonly invocationId: string;
15
+ readonly emit: (event: CanonicalEvent) => void;
16
+ readonly send: (params: JsonRecord, accept: (value: unknown) => void, rejected: (error: Error) => void) => Promise<unknown>;
17
+ readonly now: () => number;
18
+ readonly lifetimeMs: number;
19
+ constructor(invocationId: string, emit: (event: CanonicalEvent) => void, send: (params: JsonRecord, accept: (value: unknown) => void, rejected: (error: Error) => void) => Promise<unknown>, now?: () => number, lifetimeMs?: number);
20
+ get size(): number;
21
+ register(item: JsonRecord, threadId: string, turnId: string, otherPending: number): void;
22
+ /** 提交只允许一个在途请求;取消仅关闭表单,不向 Provider 伪造答案。 */
23
+ respond(response: InteractionResponse): Promise<void>;
24
+ /** 正常完成仅释放未答旁路;宿主可续跑。已发出未确认的答案仍为未知,不得重投。 */
25
+ invalidate(reason: string): void;
26
+ }
27
+ export {};