@bitkyc08/opencodex 2.95.0 → 2.97.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (276) hide show
  1. package/bin/ocx.mjs +214 -19
  2. package/gui/dist/assets/{App-8yedBkhm.js → App-DuNhggE1.js} +18 -18
  3. package/gui/dist/assets/{Tray-erSMzxPG.js → Tray-CEw0y0jR.js} +1 -1
  4. package/gui/dist/assets/index-CynE_Rue.js +94 -0
  5. package/gui/dist/assets/{quota-summary-BK4VuQNc.js → quota-summary-VHFSlUuM.js} +1 -1
  6. package/gui/dist/index.html +1 -1
  7. package/package.json +1 -1
  8. package/src/adapters/command-code.ts +15 -16
  9. package/src/adapters/cursor/transport-retry.ts +2 -2
  10. package/src/adapters/devin/cloud-direct/chat.ts +15 -6
  11. package/src/adapters/kiro/stream.ts +63 -4
  12. package/src/adapters/kiro-constants.ts +15 -1
  13. package/src/adapters/kiro-events.ts +31 -1
  14. package/src/adapters/kiro-retry.ts +3 -3
  15. package/src/adapters/ollama-native.ts +21 -7
  16. package/src/adapters/openai-responses/canonical-forward.ts +50 -13
  17. package/src/adapters/openai-responses/empty-assistant.ts +15 -3
  18. package/src/adapters/openai-responses/passthrough.ts +8 -8
  19. package/src/adapters/openai-responses/reasoning.ts +9 -4
  20. package/src/adapters/openai-responses/request-strips.ts +1 -1
  21. package/src/adapters/openai-responses/transport.ts +17 -26
  22. package/src/adapters/physical-send.ts +3 -3
  23. package/src/adapters/qoder/adapter.ts +1 -1
  24. package/src/adapters/qoder/image-input.ts +5 -2
  25. package/src/adapters/zed-openai-stream.ts +2 -1
  26. package/src/bridge/errors.ts +11 -2
  27. package/src/bridge/response-json.ts +2 -1
  28. package/src/bridge/sse.ts +14 -6
  29. package/src/chat/failure-verdict.ts +21 -0
  30. package/src/chat/outbound.ts +139 -21
  31. package/src/claude/outbound.ts +49 -2
  32. package/src/cli/agent.ts +44 -15
  33. package/src/cli/capabilities-agents-routing.ts +9 -0
  34. package/src/cli/capabilities-base.ts +25 -3
  35. package/src/cli/capabilities-command.ts +12 -3
  36. package/src/cli/capability-contracts.ts +2 -0
  37. package/src/cli/codex-launch-auth.ts +30 -1
  38. package/src/cli/codex-launcher.ts +12 -5
  39. package/src/cli/codex-shim-autorestore.ts +5 -4
  40. package/src/cli/dispatch.ts +11 -176
  41. package/src/cli/ensure-desired-integrations.ts +4 -3
  42. package/src/cli/help.ts +2 -2
  43. package/src/cli/index.ts +9 -2
  44. package/src/cli/link.ts +1 -1
  45. package/src/cli/message-command.ts +2 -1
  46. package/src/cli/message-mcp-command.ts +29 -0
  47. package/src/cli/registry.ts +12 -4
  48. package/src/cli/root.ts +8 -0
  49. package/src/cli/sync-command.ts +243 -0
  50. package/src/cli/sync-fanout-process.ts +92 -0
  51. package/src/cli/sync-fanout.ts +150 -0
  52. package/src/cli/sync-flags.ts +10 -0
  53. package/src/cli/sync-link-status.ts +39 -0
  54. package/src/cli/sync-update-guard.ts +18 -0
  55. package/src/client/connect.ts +31 -14
  56. package/src/client/link-home.ts +3 -2
  57. package/src/client/machine-listener.ts +3 -0
  58. package/src/client/restore-ownership.ts +19 -1
  59. package/src/client/runtime-restart.ts +12 -4
  60. package/src/client/runtime.ts +40 -11
  61. package/src/client/stop-routing.ts +62 -0
  62. package/src/client/sync-runtime.ts +65 -0
  63. package/src/clients/config-export.ts +32 -3
  64. package/src/codex/account-store.ts +1 -0
  65. package/src/codex/auth-context-provider.ts +15 -0
  66. package/src/codex/auth-context.ts +59 -122
  67. package/src/codex/catalog/antigravity-discovery.ts +16 -5
  68. package/src/codex/catalog/provider-models.ts +6 -8
  69. package/src/codex/forward-transport-headers.ts +65 -36
  70. package/src/codex/inject/config-toml.ts +88 -0
  71. package/src/codex/inject/multi-agent-v2.ts +30 -4
  72. package/src/codex/inject/plan.ts +34 -7
  73. package/src/codex/inject-coordination.ts +11 -0
  74. package/src/codex/inject.ts +18 -7
  75. package/src/codex/installation-id.ts +72 -0
  76. package/src/codex/lineage.ts +13 -7
  77. package/src/codex/quota.ts +22 -6
  78. package/src/codex/request-owned-affinity-key.ts +11 -0
  79. package/src/codex/request-owned-affinity.ts +118 -0
  80. package/src/codex/request-owned-main-pin.ts +86 -0
  81. package/src/codex/role-capability.ts +52 -41
  82. package/src/codex/routing/active-account.ts +13 -5
  83. package/src/codex/routing/selection.ts +40 -1
  84. package/src/codex/routing/thread-affinity-store.ts +916 -0
  85. package/src/codex/routing/thread-affinity.ts +90 -12
  86. package/src/codex/toml-source-lines.ts +72 -13
  87. package/src/combos/failover.ts +6 -109
  88. package/src/combos/request.ts +2 -2
  89. package/src/combos/resolve.ts +29 -11
  90. package/src/config/process-state.ts +5 -0
  91. package/src/config/schema/leaf-validators.ts +1 -0
  92. package/src/generated/compatibility-version.json +496 -192
  93. package/src/grok/sync.ts +10 -1
  94. package/src/images/loop.ts +2 -1
  95. package/src/lib/client-error-body.ts +184 -0
  96. package/src/lib/client-retry-after.ts +66 -0
  97. package/src/lib/config-ownership.ts +4 -0
  98. package/src/lib/context-overflow-verdict.ts +113 -0
  99. package/src/lib/desktop-cli-handoff.d.mts +1 -1
  100. package/src/lib/desktop-cli-handoff.mjs +11 -1
  101. package/src/lib/empty-tool-catalog.ts +25 -3
  102. package/src/lib/error-destination.ts +47 -0
  103. package/src/lib/failure-detail.ts +66 -0
  104. package/src/lib/model-identity.ts +44 -0
  105. package/src/lib/private-sqlite-path.ts +124 -0
  106. package/src/lib/response-service-tier.ts +17 -0
  107. package/src/lib/retry-after.ts +3 -0
  108. package/src/lib/spend-ledger-owner.ts +43 -4
  109. package/src/lib/upstream-condition.ts +142 -0
  110. package/src/lib/upstream-retry.ts +14 -11
  111. package/src/lib/windows-owner-acl.ts +13 -6
  112. package/src/lib/windows-secret-acl.ts +2 -2
  113. package/src/link/remote-platform.ts +14 -0
  114. package/src/link/remote-windows.ts +51 -9
  115. package/src/link/ssh-argv.ts +63 -10
  116. package/src/messaging/mcp-queue-rpc.ts +102 -0
  117. package/src/messaging/mcp-queue-server.ts +42 -0
  118. package/src/messaging/mcp-queue-tools.ts +39 -0
  119. package/src/oauth/anthropic-identity.ts +2 -6
  120. package/src/oauth/generic-account-failover.ts +13 -11
  121. package/src/oauth/index.ts +41 -74
  122. package/src/oauth/oauth-errors.ts +67 -0
  123. package/src/oauth/store.ts +1 -1
  124. package/src/protocols/codecs/ollama.ts +197 -0
  125. package/src/protocols/encoders/adapter-events.ts +4 -0
  126. package/src/protocols/encoders/chat.ts +18 -10
  127. package/src/protocols/trace.ts +18 -0
  128. package/src/providers/anthropic-subscription.ts +25 -0
  129. package/src/providers/claude-cli-usage.ts +15 -67
  130. package/src/providers/fastwire.ts +3 -2
  131. package/src/providers/quota/anthropic-decision-windows.ts +5 -19
  132. package/src/providers/quota/anthropic-usage-windows.ts +65 -0
  133. package/src/providers/quota/vendor-probes-key.ts +60 -24
  134. package/src/providers/request-pacing.ts +3 -2
  135. package/src/responses/apply-patch-envelope.ts +45 -19
  136. package/src/responses/compaction-history-framing.ts +5 -1
  137. package/src/responses/freeform-wrapper-scan.ts +5 -3
  138. package/src/responses/parser-tools.ts +1 -0
  139. package/src/responses/progressive-freeform-input.ts +354 -45
  140. package/src/responses/schema.ts +5 -2
  141. package/src/routing/fallback-policy.ts +3 -1
  142. package/src/server/admission-model-scope.ts +17 -6
  143. package/src/server/admitted-http-turn.ts +56 -0
  144. package/src/server/audio-dictation.ts +3 -0
  145. package/src/server/audio-live.ts +8 -2
  146. package/src/server/audio-upstream.ts +2 -0
  147. package/src/server/auth-cors.ts +5 -0
  148. package/src/server/chat-completions.ts +45 -20
  149. package/src/server/chat-native-sse.ts +52 -7
  150. package/src/server/chat-native.ts +60 -35
  151. package/src/server/claude-bridge-pool-session.ts +59 -0
  152. package/src/server/claude-messages.ts +57 -27
  153. package/src/server/context-history.ts +14 -7
  154. package/src/server/images.ts +14 -5
  155. package/src/server/inbound-body-admission.ts +11 -4
  156. package/src/server/index/live-sideband.ts +16 -2
  157. package/src/server/index/ollama-routes.ts +89 -0
  158. package/src/server/index/serve-options.ts +22 -4
  159. package/src/server/index/websocket-handler.ts +5 -3
  160. package/src/server/index.ts +6 -36
  161. package/src/server/inference/client-encoder-delivery.ts +4 -2
  162. package/src/server/json-serialized-bytes.ts +44 -0
  163. package/src/server/live.ts +30 -5
  164. package/src/server/management/agent-settings-routes.ts +24 -21
  165. package/src/server/management/codex-cli-update-routes.ts +2 -1
  166. package/src/server/management/route-registry.ts +1 -1
  167. package/src/server/messages-native-scope.ts +2 -1
  168. package/src/server/messages-native-tool-guard.ts +1 -1
  169. package/src/server/messages-native.ts +12 -7
  170. package/src/server/messages-shared.ts +6 -2
  171. package/src/server/native-final-log.ts +93 -0
  172. package/src/server/ollama-inbound.ts +349 -0
  173. package/src/server/ollama-native-paths.ts +21 -0
  174. package/src/server/ollama-route-policy.ts +73 -0
  175. package/src/server/relay.ts +22 -3
  176. package/src/server/request-decompress.ts +4 -2
  177. package/src/server/request-log-failure-attribution.ts +22 -0
  178. package/src/server/request-log-failure-detail.ts +80 -0
  179. package/src/server/request-log-terminal-status.ts +4 -2
  180. package/src/server/request-log.ts +79 -42
  181. package/src/server/response-log-body.ts +6 -1
  182. package/src/server/responses/account-change-state.ts +17 -6
  183. package/src/server/responses/adapter-continuation.ts +9 -4
  184. package/src/server/responses/adapter-delivery.ts +5 -4
  185. package/src/server/responses/adapter-dispatch.ts +36 -30
  186. package/src/server/responses/anthropic-thinking-recovery.ts +3 -0
  187. package/src/server/responses/codex-auth-error.ts +22 -17
  188. package/src/server/responses/codex-ws-exchange.ts +11 -8
  189. package/src/server/responses/codex-ws-metadata.ts +94 -21
  190. package/src/server/responses/codex-ws-request.ts +3 -1
  191. package/src/server/responses/combo-required-tool-contract.ts +24 -12
  192. package/src/server/responses/compact.ts +89 -41
  193. package/src/server/responses/compaction-recovery.ts +4 -2
  194. package/src/server/responses/compaction-routing.ts +9 -4
  195. package/src/server/responses/core-auth.ts +32 -14
  196. package/src/server/responses/core-codex-account.ts +34 -12
  197. package/src/server/responses/core-combo-failure.ts +5 -1
  198. package/src/server/responses/core-combo-native.ts +2 -1
  199. package/src/server/responses/core-combo.ts +51 -33
  200. package/src/server/responses/core-errors.ts +22 -20
  201. package/src/server/responses/core-lifetime.ts +6 -3
  202. package/src/server/responses/core-normalize.ts +8 -1
  203. package/src/server/responses/core-options.ts +7 -0
  204. package/src/server/responses/core-pipeline.ts +4 -3
  205. package/src/server/responses/fetch-helpers.ts +7 -1
  206. package/src/server/responses/input-admission.ts +28 -2
  207. package/src/server/responses/native-injection.ts +1 -1
  208. package/src/server/responses/native-response-json.ts +13 -4
  209. package/src/server/responses/native-response-output.ts +1 -2
  210. package/src/server/responses/non-replayable-error.ts +2 -1
  211. package/src/server/responses/pacing-overload.ts +3 -2
  212. package/src/server/responses/passthrough-build-error.ts +36 -0
  213. package/src/server/responses/passthrough-delivery.ts +55 -14
  214. package/src/server/responses/passthrough-dispatch.ts +26 -39
  215. package/src/server/responses/passthrough-error.ts +9 -9
  216. package/src/server/responses/policy-fallback.ts +2 -1
  217. package/src/server/responses/request-prepare.ts +67 -48
  218. package/src/server/responses/request-sidecar-auth.ts +3 -1
  219. package/src/server/responses/request-transport.ts +35 -31
  220. package/src/server/responses/run-turn-execution.ts +6 -6
  221. package/src/server/responses/sidecar-execution.ts +16 -12
  222. package/src/server/responses/spend-storage-error.ts +2 -1
  223. package/src/server/responses/ws-upstream.ts +9 -0
  224. package/src/server/responses-custom-tool-repair.ts +14 -3
  225. package/src/server/responses-terminal-repair.ts +5 -2
  226. package/src/server/responses-undeclared-tool-guard.ts +39 -16
  227. package/src/server/safe-response-headers.ts +162 -13
  228. package/src/server/search.ts +13 -4
  229. package/src/server/turn-state-handles.ts +164 -0
  230. package/src/server/workflow-refusal.ts +2 -1
  231. package/src/server/ws-bridge.ts +5 -2
  232. package/src/service/ownership-mutation-lease.d.mts +11 -2
  233. package/src/service/ownership-mutation-lease.mjs +53 -11
  234. package/src/types/config.ts +2 -0
  235. package/src/update/index.ts +133 -25
  236. package/src/update/npm-install.d.mts +8 -0
  237. package/src/update/npm-install.mjs +20 -1
  238. package/src/update/orchestrated-admission.d.mts +4 -0
  239. package/src/update/orchestrated-admission.mjs +12 -0
  240. package/src/update/orchestrated-arguments.d.mts +12 -0
  241. package/src/update/orchestrated-arguments.mjs +64 -0
  242. package/src/update/orchestrated-child.d.mts +12 -0
  243. package/src/update/orchestrated-child.mjs +70 -0
  244. package/src/update/orchestrated-entry.ts +234 -0
  245. package/src/update/orchestrated-identity-probe-entry.ts +20 -0
  246. package/src/update/orchestrated-identity.ts +53 -0
  247. package/src/update/orchestrated-live-identity.ts +48 -0
  248. package/src/update/orchestrated-node-driver.mjs +99 -0
  249. package/src/update/orchestrated-outcome.d.mts +21 -0
  250. package/src/update/orchestrated-outcome.mjs +40 -0
  251. package/src/update/orchestrated-plan.ts +49 -0
  252. package/src/update/orchestrated-pnpm.d.mts +8 -0
  253. package/src/update/orchestrated-pnpm.mjs +33 -0
  254. package/src/update/orchestrated-session.d.mts +37 -0
  255. package/src/update/orchestrated-session.mjs +264 -0
  256. package/src/update/orchestrated-token.d.mts +10 -0
  257. package/src/update/orchestrated-token.mjs +21 -0
  258. package/src/update/orchestrated-token.ts +3 -0
  259. package/src/update/orchestrated-tree.d.mts +1 -0
  260. package/src/update/orchestrated-tree.mjs +14 -0
  261. package/src/update/pnpm-global-install.d.mts +6 -0
  262. package/src/update/pnpm-global-install.mjs +9 -2
  263. package/src/update/posix-install-supervisor-entry.mjs +6 -0
  264. package/src/update/posix-install-supervisor.d.mts +10 -0
  265. package/src/update/posix-install-supervisor.mjs +88 -0
  266. package/src/update/sync-update-mutex.d.mts +10 -0
  267. package/src/update/sync-update-mutex.mjs +164 -0
  268. package/src/update/sync-update-mutex.ts +1 -0
  269. package/src/update/test-home-guard.mjs +33 -0
  270. package/src/update/transactional-install.mjs +2 -2
  271. package/src/usage/error-detail.ts +225 -0
  272. package/src/usage/log.ts +60 -27
  273. package/src/vision/describe.ts +4 -7
  274. package/src/web-search/executor.ts +4 -7
  275. package/src/web-search/loop.ts +31 -5
  276. package/gui/dist/assets/index-D7DCm5eQ.js +0 -94
@@ -39,6 +39,22 @@ function stripMarkdownCodeFence(text: string, toolName: string): string {
39
39
  return match ? match[1] : text;
40
40
  }
41
41
 
42
+ /** Repair one extra canonical wrapper inside an already unwrapped executable body. */
43
+ function repairUnwrappedBody(text: string, toolName: string): string {
44
+ if (toolName !== "exec" && toolName !== "apply_patch") return text;
45
+ try {
46
+ const nested: unknown = JSON.parse(text);
47
+ if (nested && typeof nested === "object" && !Array.isArray(nested)) {
48
+ const record = nested as Record<string, unknown>;
49
+ const keys = Object.keys(record);
50
+ if (keys.length === 1 && keys[0] === "input" && typeof record.input === "string") text = record.input;
51
+ }
52
+ } catch {
53
+ // Ordinary JavaScript and patches are not JSON wrappers.
54
+ }
55
+ return stripMarkdownCodeFence(text, toolName);
56
+ }
57
+
42
58
  /** Unwrap the `{input:string}` function-call wrapper used for freeform tools. */
43
59
  export function unwrapFreeformToolInput(argumentsText: unknown, toolName = ""): string {
44
60
  if (typeof argumentsText !== "string") return "";
@@ -48,13 +64,13 @@ export function unwrapFreeformToolInput(argumentsText: unknown, toolName = ""):
48
64
  const record = parsed as Record<string, unknown>;
49
65
  if (Object.prototype.hasOwnProperty.call(record, "input")) {
50
66
  return typeof record.input === "string"
51
- ? stripMarkdownCodeFence(record.input, toolName)
67
+ ? repairUnwrappedBody(record.input, toolName)
52
68
  : argumentsText;
53
69
  }
54
70
  const fallbackKeys = freeformFallbackKeys(toolName);
55
71
  const candidates = fallbackKeys.filter(key => typeof record[key] === "string");
56
72
  if (candidates.length === 1) {
57
- return stripMarkdownCodeFence(record[candidates[0]] as string, toolName);
73
+ return repairUnwrappedBody(record[candidates[0]] as string, toolName);
58
74
  }
59
75
  }
60
76
  } catch {
@@ -115,36 +131,46 @@ export function mayBecomePatchEnvelope(text: string): boolean {
115
131
  }
116
132
 
117
133
  /** Largest prefix of an exactly opened patch that completion cannot rewrite. */
118
- export function stableCanonicalPatchPrefix(text: string): string | null {
134
+ export function stableCanonicalPatchPrefix(
135
+ text: string,
136
+ boundedTail = text,
137
+ openingValidated = false,
138
+ ): string | null {
119
139
  const lfOpening = `${PATCH_BEGIN}\n`;
120
140
  const crlfOpening = `${PATCH_BEGIN}\r\n`;
121
- if (!text.startsWith(lfOpening) && !text.startsWith(crlfOpening)) {
141
+ if (!openingValidated && !text.startsWith(lfOpening) && !text.startsWith(crlfOpening)) {
122
142
  return lfOpening.startsWith(text) || crlfOpening.startsWith(text) ? "" : null;
123
143
  }
124
144
 
125
- let core = text;
145
+ let coreLength = text.length;
146
+ let tail = boundedTail;
126
147
  let trailingBreak = "";
127
- if (core.endsWith("\r\n")) {
128
- core = core.slice(0, -2);
148
+ if (tail.endsWith("\r\n")) {
149
+ coreLength -= 2;
150
+ tail = tail.slice(0, -2);
129
151
  trailingBreak = "\r\n";
130
- } else if (core.endsWith("\n")) {
131
- core = core.slice(0, -1);
152
+ } else if (tail.endsWith("\n")) {
153
+ coreLength -= 1;
154
+ tail = tail.slice(0, -1);
132
155
  trailingBreak = "\n";
133
- } else if (core.endsWith("\r")) {
156
+ } else if (tail.endsWith("\r")) {
134
157
  // This may become the first byte of a CRLF. It is stable for a canonical
135
158
  // closer, but must remain behind a decorated closer that may be rewritten.
136
- core = core.slice(0, -1);
159
+ coreLength -= 1;
160
+ tail = tail.slice(0, -1);
137
161
  trailingBreak = "\r";
138
162
  }
139
- const lineStart = Math.max(core.lastIndexOf("\n"), core.lastIndexOf("\r")) + 1;
140
- const line = core.slice(lineStart);
141
- if (!line.startsWith(PATCH_END)) return text;
142
-
143
- const suffix = line.slice(PATCH_END.length);
144
163
  const decoration = " ***";
145
- if (suffix === "") return core + trailingBreak;
146
- if (decoration.startsWith(suffix)) {
147
- return core.slice(0, lineStart + PATCH_END.length);
164
+ // Only a partial terminal decoration can be rewritten at completion. Match its
165
+ // bounded tail instead of searching the complete accumulated patch on every delta.
166
+ for (let suffixLength = decoration.length; suffixLength > 0; suffixLength--) {
167
+ const candidate = PATCH_END + decoration.slice(0, suffixLength);
168
+ if (!tail.endsWith(candidate)) continue;
169
+ const lineStart = coreLength - candidate.length;
170
+ const preceding = tail[tail.length - candidate.length - 1];
171
+ if (lineStart === 0 || preceding === "\n" || preceding === "\r") {
172
+ return text.slice(0, lineStart + PATCH_END.length);
173
+ }
148
174
  }
149
175
  return text;
150
176
  }
@@ -21,6 +21,10 @@ function plainUserText(item: unknown): string | null {
21
21
  return texts.join("\n");
22
22
  }
23
23
 
24
+ export function isLocalCompactionCheckpoint(input: unknown): boolean {
25
+ return Array.isArray(input) && plainUserText(input.at(-1))?.trim() === COMPACT_PROMPT;
26
+ }
27
+
24
28
  function isContext(text: string): boolean {
25
29
  const head = text.trimStart();
26
30
  return head.startsWith("<") || head.startsWith("# AGENTS.md") || head.startsWith("# Context from my IDE");
@@ -44,7 +48,7 @@ export function frameCompactionHistory<T extends { input?: unknown; instructions
44
48
  if (!Array.isArray(input) || input.some(item => isRecord(item) && item.type === "compaction_trigger")) return body;
45
49
  // Codex local compaction appends this user prompt without a compaction_trigger.
46
50
  // Keep that summarizer turn free of generation-only continuation instructions.
47
- if (plainUserText(input.at(-1))?.trim() === COMPACT_PROMPT) return body;
51
+ if (isLocalCompactionCheckpoint(input)) return body;
48
52
  let checkpointIndex = -1;
49
53
  for (let index = input.length - 1; index >= 0; index--) {
50
54
  if (isCheckpoint(input[index])) {
@@ -56,7 +56,9 @@ const NEVER = -2;
56
56
  export type FreeformWrapperScan =
57
57
  | { kind: "hold" }
58
58
  | { kind: "raw" }
59
- | { kind: "input"; valueStart: number };
59
+ // `canonical` is false for a fallback field, which a closed object resolved and trailing text
60
+ // can still withdraw; an own `input` is decided by its prefix and stays decided.
61
+ | { kind: "input"; valueStart: number; canonical: boolean };
60
62
 
61
63
  /** Index of the first non-whitespace character at or after `from`, or HOLD past the end. */
62
64
  function skipWhitespace(text: string, from: number): number {
@@ -249,7 +251,7 @@ export function scanFreeformWrapper(text: string, fallbackKeys: readonly string[
249
251
  // non-string value is decidable too, in the other direction: completion hands back the
250
252
  // argument text unchanged rather than unwrapping a value it cannot use.
251
253
  return bounded[valueAt] === '"'
252
- ? { kind: "input", valueStart: valueAt + 1 }
254
+ ? { kind: "input", valueStart: valueAt + 1, canonical: true }
253
255
  : { kind: "raw" };
254
256
  }
255
257
 
@@ -300,7 +302,7 @@ function afterTopLevelClose(
300
302
  if (!wholeText) return { kind: "hold" };
301
303
  const candidates = fallbackKeys.filter(key => members.get(key)?.stringValue === true);
302
304
  if (candidates.length === 1) {
303
- return { kind: "input", valueStart: members.get(candidates[0]!)!.valueStart };
305
+ return { kind: "input", valueStart: members.get(candidates[0]!)!.valueStart, canonical: false };
304
306
  }
305
307
  return { kind: "raw" };
306
308
  }
@@ -16,6 +16,7 @@ export function mapToolChoice(value: unknown): OcxRequestOptions["toolChoice"] {
16
16
  if (t === "image_generation" || t === "image_gen") {
17
17
  return { name: IMAGE_GEN_TOOL_NAME };
18
18
  }
19
+ if (t === "tool_search") return { name: "tool_search" };
19
20
  if (t === "allowed_tools" && Array.isArray(value.tools)) {
20
21
  const names = value.tools
21
22
  .map(allowedToolName)
@@ -1,5 +1,10 @@
1
1
  import { freeformFallbackKeys } from "./apply-patch-envelope";
2
- import { JSON_ESCAPES, scanFreeformWrapper } from "./freeform-wrapper-scan";
2
+ import {
3
+ JSON_ESCAPES,
4
+ JSON_WHITESPACE,
5
+ MAX_FREEFORM_WRAPPER_SCAN_CHARS,
6
+ scanFreeformWrapper,
7
+ } from "./freeform-wrapper-scan";
3
8
 
4
9
  /**
5
10
  * Whether a body could still grow into one complete outer Markdown fence.
@@ -18,66 +23,291 @@ function mayBecomeFencedBody(text: string, toolName: string): boolean {
18
23
  }
19
24
 
20
25
  const LOW_SURROGATE_ESCAPE = /^\\u[dD][c-fC-F][0-9a-fA-F]{2}$/;
26
+ const HEX_DIGIT = /^[0-9a-fA-F]$/;
27
+ const HEX_QUAD = /^[0-9a-fA-F]{4}$/;
28
+ const JSON_NUMBER_CHAR = /^[-+0-9.eE]$/;
29
+ const JSON_NUMBER = /^-?(?:0|[1-9][0-9]*)(?:\.[0-9]+)?(?:[eE][+-]?[0-9]+)?$/;
30
+ const JSON_LITERALS = ["true", "false", "null"] as const;
31
+ const CANONICAL_KEY = "input";
32
+ const STRING_END = Symbol("string end");
33
+
34
+ const ownsBodyRepair = (toolName: string): boolean => toolName === "exec" || toolName === "apply_patch";
35
+
36
+ type NestedState =
37
+ | "start" | "keyOpen" | "key" | "colon" | "valueOpen" | "string"
38
+ | "scalar" | "container" | "afterValue" | "trailing" | "never";
21
39
 
22
40
  /**
23
- * The decoded prefix of a JSON string body, stopping at the first byte it cannot resolve.
41
+ * Whether a decoded executable body can still grow into the one extra `{"input":string}`
42
+ * wrapper that completion removes, answered one character at a time so a streamed body is walked
43
+ * once rather than once per delta.
44
+ *
45
+ * Ordinary object-leading JavaScript such as `{ let x` or `({` fails within a few characters and
46
+ * streams from there; only a prefix that is still a possible wrapper holds. A false answer never
47
+ * turns true again as the body grows, so the held prefix is flushed once and streaming continues.
48
+ *
49
+ * Every member name must be `input`, because completion unwraps only a single-key object, and
50
+ * duplicates are followed because `JSON.parse` keeps the last. A non-string value is skipped to its
51
+ * end so a later duplicate can still replace it, and an object that closes on a non-string last
52
+ * value is ruled out. Scalars are checked against the JSON grammar; containers are skipped by
53
+ * bracket and string tracking alone. That skip is looser than `JSON.parse` but never unsound: it
54
+ * finds the true end of every valid container, and any text it misreads is invalid JSON, which
55
+ * completion would not unwrap either way.
56
+ */
57
+ class NestedWrapperMatcher {
58
+ scanned = 0;
59
+ private state: NestedState = "start";
60
+ private key = "";
61
+ /** Pending escape inside the current string: "", a backslash, or `\\u` and the hex read so far. */
62
+ private escape = "";
63
+ private scalar = "";
64
+ private readonly closers: string[] = [];
65
+ private inContainerString = false;
66
+ private containerEscape = false;
67
+ private lastValueString = false;
68
+
69
+ get possible(): boolean {
70
+ return this.state !== "never";
71
+ }
72
+
73
+ feed(text: string): boolean {
74
+ for (let i = 0; i < text.length && this.state !== "never"; i++) {
75
+ this.scanned++;
76
+ this.step(text[i]!);
77
+ }
78
+ return this.possible;
79
+ }
80
+
81
+ private step(c: string): void {
82
+ switch (this.state) {
83
+ case "start":
84
+ if (!JSON_WHITESPACE.has(c)) this.state = c === "{" ? "keyOpen" : "never";
85
+ return;
86
+ case "keyOpen":
87
+ if (JSON_WHITESPACE.has(c)) return;
88
+ this.state = c === '"' ? "key" : "never";
89
+ this.key = "";
90
+ this.escape = "";
91
+ return;
92
+ case "key": {
93
+ const part = this.stringStep(c);
94
+ if (part === null) this.state = "never";
95
+ else if (part === STRING_END) this.state = this.key === CANONICAL_KEY ? "colon" : "never";
96
+ else if (!CANONICAL_KEY.startsWith(this.key += part)) this.state = "never";
97
+ return;
98
+ }
99
+ case "colon":
100
+ if (!JSON_WHITESPACE.has(c)) this.state = c === ":" ? "valueOpen" : "never";
101
+ return;
102
+ case "valueOpen":
103
+ if (JSON_WHITESPACE.has(c)) return;
104
+ this.lastValueString = c === '"';
105
+ this.escape = "";
106
+ if (c === '"') this.state = "string";
107
+ else this.startOtherValue(c);
108
+ return;
109
+ case "string": {
110
+ const part = this.stringStep(c);
111
+ if (part === null) this.state = "never";
112
+ else if (part === STRING_END) this.state = "afterValue";
113
+ return;
114
+ }
115
+ case "scalar":
116
+ this.stepScalar(c);
117
+ return;
118
+ case "container":
119
+ this.stepContainer(c);
120
+ return;
121
+ case "afterValue":
122
+ if (JSON_WHITESPACE.has(c)) return;
123
+ if (c === ",") this.state = "keyOpen";
124
+ else this.state = c === "}" && this.lastValueString ? "trailing" : "never";
125
+ return;
126
+ case "trailing":
127
+ if (!JSON_WHITESPACE.has(c)) this.state = "never";
128
+ return;
129
+ case "never":
130
+ return;
131
+ }
132
+ }
133
+
134
+ /**
135
+ * One character of a JSON string: the text it decodes to ("" while an escape is pending),
136
+ * `STRING_END` at the closing quote, or `null` when no continuation can parse. Only key
137
+ * text needs the decoded value, so escapes other than `\\u` keep a marker.
138
+ */
139
+ private stringStep(c: string): string | typeof STRING_END | null {
140
+ if (this.escape === "") {
141
+ if (c === '"') return STRING_END;
142
+ if (c.charCodeAt(0) <= 0x1f) return null;
143
+ if (c !== "\\") return c;
144
+ this.escape = "\\";
145
+ return "";
146
+ }
147
+ if (this.escape === "\\") {
148
+ if (c === "u") {
149
+ this.escape = "\\u";
150
+ return "";
151
+ }
152
+ if (!JSON_ESCAPES.has(c)) return null;
153
+ this.escape = "";
154
+ return "\\" + c;
155
+ }
156
+ if (!HEX_DIGIT.test(c)) return null;
157
+ this.escape += c;
158
+ if (this.escape.length < 6) return "";
159
+ const code = parseInt(this.escape.slice(2), 16);
160
+ this.escape = "";
161
+ return String.fromCharCode(code);
162
+ }
163
+
164
+ private startOtherValue(c: string): void {
165
+ if (c === "{" || c === "[") {
166
+ this.closers.length = 0;
167
+ this.closers.push(c === "{" ? "}" : "]");
168
+ this.inContainerString = false;
169
+ this.containerEscape = false;
170
+ this.state = "container";
171
+ return;
172
+ }
173
+ if (JSON_NUMBER_CHAR.test(c) || c === "t" || c === "f" || c === "n") {
174
+ this.scalar = c;
175
+ this.state = "scalar";
176
+ return;
177
+ }
178
+ this.state = "never";
179
+ }
180
+
181
+ private stepScalar(c: string): void {
182
+ if (JSON_WHITESPACE.has(c) || c === "," || c === "}") {
183
+ const complete = (JSON_LITERALS as readonly string[]).includes(this.scalar) || JSON_NUMBER.test(this.scalar);
184
+ if (!complete) {
185
+ this.state = "never";
186
+ return;
187
+ }
188
+ this.state = "afterValue";
189
+ this.step(c);
190
+ return;
191
+ }
192
+ this.scalar += c;
193
+ const literal = JSON_LITERALS.find(word => word[0] === this.scalar[0]);
194
+ const viable = literal ? literal.startsWith(this.scalar) : JSON_NUMBER_CHAR.test(c);
195
+ if (!viable) this.state = "never";
196
+ }
197
+
198
+ private stepContainer(c: string): void {
199
+ if (this.inContainerString) {
200
+ if (this.containerEscape) this.containerEscape = false;
201
+ else if (c === "\\") this.containerEscape = true;
202
+ else if (c === '"') this.inContainerString = false;
203
+ return;
204
+ }
205
+ if (c === '"') this.inContainerString = true;
206
+ else if (c === "{" || c === "[") this.closers.push(c === "{" ? "}" : "]");
207
+ else if (c === "}" || c === "]") {
208
+ if (this.closers.pop() !== c) this.state = "never";
209
+ else if (this.closers.length === 0) this.state = "afterValue";
210
+ }
211
+ }
212
+ }
213
+
214
+ type DecodeStop = "open" | "closed" | "stalled" | "invalid";
215
+
216
+ /**
217
+ * Decode the JSON string body in `text` from `from`, stopping at the first byte it cannot
218
+ * resolve. `next` is where decoding resumes once more text arrives; `scanned` counts the characters
219
+ * read, including a split escape that will be read again.
24
220
  *
25
221
  * Every stop is a hold rather than a guess, because `JSON.parse` decides the completed value
26
222
  * and anything invented here would be retracted. Three of them are not obvious:
27
223
  *
28
224
  * An escape JSON does not define makes the whole wrapper unparseable no matter what arrives
29
- * next, so completion falls back to the raw text. Returning `null` for that case stops the
30
- * preview rather than continuing to decode a value the completed item will never carry.
31
- * `\\b` and `\\f` are defined, and were previously decoded to the letters b and f.
225
+ * next, so completion falls back to the raw text. `invalid` stops the preview rather than
226
+ * continuing to decode a value the completed item will never carry. `\\b` and `\\f` are defined,
227
+ * and were previously decoded to the letters b and f. A literal control character is not legal
228
+ * inside a JSON string either, and stops the same way.
32
229
  *
33
230
  * A lone high surrogate is not a character. Emitting one alone puts an unpaired code unit in a
34
- * delta the client has to decode by itself, so the pair is emitted together or not at all.
231
+ * delta the client has to decode by itself, so the pair is emitted together or not at all; a
232
+ * complete escape that is not its low half leaves the preview `stalled` for the rest of the call.
35
233
  */
36
- function decodeJsonStringPrefix(body: string): string | null {
37
- let out = "";
38
- for (let i = 0; i < body.length; i++) {
39
- const c = body[i];
40
- if (c === '"') break; // unescaped closing quote: value complete
234
+ function decodeJsonStringChunk(
235
+ text: string,
236
+ from: number,
237
+ ): { chunk: string; next: number; stop: DecodeStop; scanned: number } {
238
+ let chunk = "";
239
+ let scanned = 0;
240
+ let i = from;
241
+ let stop: DecodeStop = "open";
242
+ while (i < text.length) {
243
+ const c = text[i]!;
244
+ scanned++;
245
+ if (c === '"') {
246
+ stop = "closed";
247
+ break;
248
+ }
41
249
  if (c !== "\\") {
42
- // A literal control character is not legal inside a JSON string, so `JSON.parse` will
43
- // reject this wrapper and completion will return the raw text. Emitting the decoded value
44
- // first is the disagreement this decoder exists to prevent, so stop instead.
45
- if (c!.charCodeAt(0) <= 0x1f) return null;
46
- out += c;
250
+ if (c.charCodeAt(0) <= 0x1f) {
251
+ stop = "invalid";
252
+ break;
253
+ }
254
+ chunk += c;
255
+ i++;
47
256
  continue;
48
257
  }
49
- const n = body[i + 1];
258
+ const n = text[i + 1];
50
259
  if (n === undefined) break; // escape split across chunks: wait for more
260
+ scanned++;
51
261
  if (n === "u") {
52
- const hex = body.slice(i + 2, i + 6);
262
+ const hex = text.slice(i + 2, i + 6);
263
+ scanned += hex.length;
53
264
  if (hex.length < 4) break; // split across chunks: wait for more
54
- if (!/^[0-9a-fA-F]{4}$/.test(hex)) return null; // never parses
265
+ if (!HEX_QUAD.test(hex)) {
266
+ stop = "invalid";
267
+ break;
268
+ }
55
269
  const code = parseInt(hex, 16);
56
270
  if (code >= 0xd800 && code <= 0xdbff) {
57
- const low = body.slice(i + 6, i + 12);
58
- if (!LOW_SURROGATE_ESCAPE.test(low)) break;
59
- out += String.fromCharCode(code, parseInt(low.slice(2), 16));
60
- i += 11;
271
+ const low = text.slice(i + 6, i + 12);
272
+ scanned += low.length;
273
+ if (!LOW_SURROGATE_ESCAPE.test(low)) {
274
+ if (low.length === 6) stop = "stalled";
275
+ break;
276
+ }
277
+ chunk += String.fromCharCode(code, parseInt(low.slice(2), 16));
278
+ i += 12;
61
279
  continue;
62
280
  }
63
- out += String.fromCharCode(code);
64
- i += 5;
281
+ chunk += String.fromCharCode(code);
282
+ i += 6;
65
283
  continue;
66
284
  }
67
285
  const escaped = JSON_ESCAPES.get(n);
68
- if (escaped === undefined) return null; // never parses
69
- out += escaped;
70
- i += 1;
286
+ if (escaped === undefined) {
287
+ stop = "invalid";
288
+ break;
289
+ }
290
+ chunk += escaped;
291
+ i += 2;
71
292
  }
72
- return out;
293
+ return { chunk, next: i, stop, scanned };
73
294
  }
74
295
 
75
296
  /**
76
- * The value to stream so far, or `null` to HOLD because nothing can be decided yet.
297
+ * The value to stream so far for one call's growing arguments, or `null` to HOLD because nothing
298
+ * can be decided yet.
299
+ *
300
+ * A reader belongs to one call and is fed that call's whole accumulated arguments on each delta.
301
+ * They only grow, so it resumes where the previous delta stopped: the canonical value is decoded
302
+ * and checked for a nested wrapper once overall, which keeps a long body streamed in small deltas
303
+ * linear instead of quadratic. A shorter buffer or a different tool name starts over.
304
+ *
77
305
  *
78
306
  * `input` is decidable from its prefix: `unwrapFreeformToolInput` returns it whenever the
79
307
  * key is present, whatever else the object carries, so its value can be unescaped
80
- * progressively and never retracted.
308
+ * progressively and never retracted, except for executable bodies that may contain one
309
+ * extra canonical wrapper. Such a body holds only while its prefix can still become that
310
+ * wrapper (`mayBecomeNestedWrapper`); the first byte that rules it out flushes the held text.
81
311
  *
82
312
  * One case escapes that claim and is accepted rather than fixed: a duplicate `input` key.
83
313
  * `JSON.parse` keeps the last one, so `{"input":"a","input":"b"}` streams a and completes with
@@ -106,19 +336,98 @@ function decodeJsonStringPrefix(body: string): string | null {
106
336
  * cost of holding is preview on an object body that turns out not to be a wrapper; the cost of
107
337
  * not holding was publishing bytes the completed item removes.
108
338
  */
109
- export function progressiveFreeformInput(args: string, toolName: string): string | null {
110
- const scan = scanFreeformWrapper(args, freeformFallbackKeys(toolName));
111
- if (scan.kind === "input") {
112
- const decoded = decodeJsonStringPrefix(args.slice(scan.valueStart));
113
- if (decoded === null) return null;
114
- return mayBecomeFencedBody(decoded, toolName) ? null : decoded;
339
+ export class ProgressiveFreeformInputReader {
340
+ private toolName: string | undefined;
341
+ private seen = 0;
342
+ private mode: "scan" | "raw" | "hold" | "input" = "scan";
343
+ private next = 0;
344
+ private decoded = "";
345
+ private stop: DecodeStop = "open";
346
+ private nested: NestedWrapperMatcher | null = null;
347
+ private fenceRuledOut = false;
348
+ private decodeScanned = 0;
349
+
350
+ /** Characters this reader has walked so far; a test seam for the linear-work bound. */
351
+ get scannedChars(): number {
352
+ return this.decodeScanned + (this.nested?.scanned ?? 0);
353
+ }
354
+
355
+ update(args: string, toolName: string): string | null {
356
+ if (toolName !== this.toolName || args.length < this.seen) this.reset(toolName);
357
+ this.seen = args.length;
358
+ if (this.mode === "scan") {
359
+ const scan = scanFreeformWrapper(args, freeformFallbackKeys(toolName));
360
+ if (scan.kind === "raw") {
361
+ // Prefix-decided: no extension of this text becomes a wrapper again.
362
+ this.mode = "raw";
363
+ } else if (scan.kind === "hold") {
364
+ // Past the bound the scan only ever sees the same clamped prefix, so it holds for good.
365
+ if (args.length > MAX_FREEFORM_WRAPPER_SCAN_CHARS) this.mode = "hold";
366
+ return null;
367
+ } else if (scan.canonical) {
368
+ this.mode = "input";
369
+ this.next = scan.valueStart;
370
+ this.nested = ownsBodyRepair(toolName) ? new NestedWrapperMatcher() : null;
371
+ } else {
372
+ // A closed fallback wrapper can still be withdrawn by trailing text, so it is decided
373
+ // afresh on each delta. Its object fits inside the scan bound, which bounds this too.
374
+ return this.closedFallbackValue(args, scan.valueStart, toolName);
375
+ }
376
+ }
377
+ if (this.mode === "hold") return null;
378
+ if (this.mode === "raw") return this.mayBecomeFenced(args) ? null : args;
379
+ return this.canonicalValue(args);
380
+ }
381
+
382
+ private reset(toolName: string): void {
383
+ this.toolName = toolName;
384
+ this.seen = 0;
385
+ this.mode = "scan";
386
+ this.next = 0;
387
+ this.decoded = "";
388
+ this.stop = "open";
389
+ this.nested = null;
390
+ this.fenceRuledOut = false;
115
391
  }
116
- if (scan.kind === "raw") return mayBecomeFencedBody(args, toolName) ? null : args;
117
-
118
- // Undecided: an incomplete object, or a close whose tail is clamped out of view. Both stay
119
- // held — the first is provably incomplete, and re-walking a budget-exhausted buffer on every
120
- // delta is work for a preview that arrives in the same instant as the authoritative
121
- // completion behind it. A closed object the scan could see whole never reaches here: its
122
- // member table already resolved it to `input` or `raw`.
123
- return null;
392
+
393
+ private canonicalValue(args: string): string | null {
394
+ if (this.stop === "open") {
395
+ const step = decodeJsonStringChunk(args, this.next);
396
+ this.decodeScanned += step.scanned;
397
+ this.next = step.next;
398
+ this.stop = step.stop;
399
+ this.decoded += step.chunk;
400
+ if (this.nested?.possible) this.nested.feed(step.chunk);
401
+ }
402
+ if (this.stop === "invalid") return null;
403
+ // Completion may remove one extra {input:string} body wrapper, so hold while it can.
404
+ if (this.nested?.possible) return null;
405
+ return this.mayBecomeFenced(this.decoded) ? null : this.decoded;
406
+ }
407
+
408
+ private closedFallbackValue(args: string, valueStart: number, toolName: string): string | null {
409
+ const step = decodeJsonStringChunk(args, valueStart);
410
+ this.decodeScanned += step.scanned;
411
+ if (step.stop === "invalid") return null;
412
+ if (ownsBodyRepair(toolName)) {
413
+ const nested = new NestedWrapperMatcher();
414
+ const possible = nested.feed(step.chunk);
415
+ this.decodeScanned += nested.scanned;
416
+ if (possible) return null;
417
+ }
418
+ return mayBecomeFencedBody(step.chunk, toolName) ? null : step.chunk;
419
+ }
420
+
421
+ /** `mayBecomeFencedBody`, remembering a false answer: a ruled-out fence never returns. */
422
+ private mayBecomeFenced(text: string): boolean {
423
+ if (this.fenceRuledOut) return false;
424
+ if (mayBecomeFencedBody(text, this.toolName ?? "")) return true;
425
+ this.fenceRuledOut = true;
426
+ return false;
427
+ }
428
+ }
429
+
430
+ /** One-shot form of `ProgressiveFreeformInputReader` for a buffer read once. */
431
+ export function progressiveFreeformInput(args: string, toolName: string): string | null {
432
+ return new ProgressiveFreeformInputReader().update(args, toolName);
124
433
  }
@@ -162,12 +162,15 @@ const builtinToolSchema = z.object({ type: z.string() }).loose();
162
162
  */
163
163
  export const HOSTED_TOOL_TYPES = [
164
164
  "web_search", "web_search_preview", "file_search", "computer_use_preview",
165
- "code_interpreter", "image_generation", "mcp",
165
+ "code_interpreter", "image_generation", "mcp", "tool_search", "computer_use", "image_gen",
166
166
  ] as const;
167
167
 
168
168
  const hostedToolType = z.enum(HOSTED_TOOL_TYPES);
169
169
 
170
- const allowedToolEntrySchema = z.object({ type: z.string(), name: z.string().optional() });
170
+ const allowedToolEntrySchema = z.union([
171
+ z.object({ type: z.literal("mcp"), server_label: z.string().min(1), name: z.string().nullable().optional() }),
172
+ z.object({ type: z.string(), name: z.string().optional() }),
173
+ ]);
171
174
 
172
175
  export const toolChoiceSchema = z.union([
173
176
  z.literal("auto"),
@@ -13,6 +13,7 @@
13
13
  * Privacy: events carry public selectors, coarse trigger codes and device ids only. No request
14
14
  * body, credential, account id, label or email reaches the ring or the refusal body.
15
15
  */
16
+ import { formatClientRetryAfter } from "../lib/client-retry-after";
16
17
  import type { OcxConfig } from "../types";
17
18
  import type { OcxFallbackConfig, OcxFallbackKind, OcxFallbackSwitches } from "../types/fallback";
18
19
  import { FALLBACK_DEVICE_ID, FALLBACK_SELECTOR } from "../config/schema/fallback-policy";
@@ -262,7 +263,8 @@ export function fallbackRefusedResponse(event: FallbackEvent, hop: Pick<Fallback
262
263
  + " fallback to " + event.to + " is off " + scopePhrase(event) + ", so OpenCodex did not send the request there."
263
264
  + " To allow it: ocx fallback on --kind " + event.kind + scopeFlag(event);
264
265
  const headers = new Headers({ "x-opencodex-fallback": "refused", "cache-control": "no-store" });
265
- if (hop.retryAfter) headers.set("retry-after", hop.retryAfter);
266
+ const advice = formatClientRetryAfter(hop.retryAfter);
267
+ if (advice !== undefined) headers.set("retry-after", advice);
266
268
  return Response.json({
267
269
  error: {
268
270
  message,