@bitkyc08/opencodex 2.100.5 → 2.100.6

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 (536) hide show
  1. package/README.md +1 -1
  2. package/bin/ocx.mjs +2 -0
  3. package/gui/dist/assets/App-BI8LQ7Qk.css +1 -0
  4. package/gui/dist/assets/App-CsZ1Gr7S.js +60 -0
  5. package/gui/dist/assets/Tray-CVqm4S4W.js +1 -0
  6. package/gui/dist/assets/brand-mark-BebhnAtV.js +1 -0
  7. package/gui/dist/assets/index-BtwVlpeQ.css +2 -0
  8. package/gui/dist/assets/index-CEeMegqE.js +138 -0
  9. package/gui/dist/assets/{segment-thumb-features-Bquysdn5.js → segment-thumb-features-COdzmORE.js} +1 -1
  10. package/gui/dist/classic/assets/App-BJgUWNJ8.js +59 -0
  11. package/gui/dist/classic/assets/App-CoiVLRW3.css +1 -0
  12. package/gui/dist/classic/assets/Tray-BDlcOLDK.js +1 -0
  13. package/gui/dist/classic/assets/index-B9Jgli_W.js +138 -0
  14. package/gui/dist/classic/assets/usage-companion-chart-vbzDcND0.js +1 -0
  15. package/gui/dist/classic/index.html +1 -1
  16. package/gui/dist/index.html +2 -2
  17. package/native/ocx-child/Cargo.lock +62 -0
  18. package/native/ocx-child/Cargo.toml +1 -0
  19. package/native/ocx-child/src/journal.rs +32 -10
  20. package/native/ocx-child/src/state.rs +2 -1
  21. package/native/ocx-child/src/toml_surgeon.rs +183 -72
  22. package/package.json +2 -2
  23. package/src/adapters/agy-acp/acp.ts +202 -0
  24. package/src/adapters/agy-acp/adapter.ts +554 -0
  25. package/src/adapters/agy-acp/binary.ts +79 -0
  26. package/src/adapters/agy-acp/options.ts +163 -0
  27. package/src/adapters/agy-acp/output-redaction.ts +270 -0
  28. package/src/adapters/agy-acp/policy.ts +105 -0
  29. package/src/adapters/agy-acp/process.ts +218 -0
  30. package/src/adapters/anthropic/account-metadata.ts +4 -1
  31. package/src/adapters/anthropic/advisor-tool.ts +43 -9
  32. package/src/adapters/anthropic/client-identity.ts +2 -0
  33. package/src/adapters/anthropic.ts +102 -14
  34. package/src/adapters/antigravity-refusal.ts +5 -1
  35. package/src/adapters/base.ts +25 -2
  36. package/src/adapters/claude-cli/adapter.ts +1 -0
  37. package/src/adapters/claude-cli/usage-admission.ts +12 -9
  38. package/src/adapters/codebuddy/adapter.ts +1 -0
  39. package/src/adapters/command-code.ts +2 -2
  40. package/src/adapters/cursor/http1-bidi.ts +7 -2
  41. package/src/adapters/cursor/live-transport.ts +2 -0
  42. package/src/adapters/cursor/request-builder.ts +4 -4
  43. package/src/adapters/cursor/tool-naming.ts +5 -5
  44. package/src/adapters/cursor/transport-retry.ts +14 -8
  45. package/src/adapters/cursor/transport.ts +2 -0
  46. package/src/adapters/cursor.ts +8 -2
  47. package/src/adapters/google-error-details.ts +105 -0
  48. package/src/adapters/google-errors.ts +183 -31
  49. package/src/adapters/google-http.ts +66 -22
  50. package/src/adapters/google-truncation.ts +48 -3
  51. package/src/adapters/google-vertex-endpoint.ts +12 -1
  52. package/src/adapters/google.ts +54 -26
  53. package/src/adapters/kiro/adapter.ts +39 -38
  54. package/src/adapters/kiro/stream.ts +59 -9
  55. package/src/adapters/kiro-retry.ts +5 -3
  56. package/src/adapters/m365-copilot/LICENSE +21 -0
  57. package/src/adapters/m365-copilot/fenced.ts +745 -0
  58. package/src/adapters/m365-copilot/images.ts +89 -0
  59. package/src/adapters/m365-copilot/tools.ts +284 -0
  60. package/src/adapters/m365-copilot/transport.ts +232 -0
  61. package/src/adapters/m365-copilot.ts +143 -0
  62. package/src/adapters/openai-chat/tool-schema.ts +2 -2
  63. package/src/adapters/openai-responses/passthrough.ts +1 -0
  64. package/src/adapters/openai-responses/reasoning.ts +23 -3
  65. package/src/adapters/physical-send.ts +11 -4
  66. package/src/adapters/qoder/adapter.ts +17 -3
  67. package/src/adapters/registry.ts +15 -1
  68. package/src/adapters/zed.ts +2 -1
  69. package/src/advisor/consult.ts +1 -0
  70. package/src/bridge/response-json.ts +6 -2
  71. package/src/bridge/sse.ts +21 -9
  72. package/src/chat/inbound.ts +11 -8
  73. package/src/chat/outbound.ts +28 -7
  74. package/src/claude/context-windows.ts +32 -8
  75. package/src/claude/desktop-3p.ts +18 -14
  76. package/src/claude/desktop-picker-platform.ts +1 -1
  77. package/src/claude/desktop-picker.ts +3 -3
  78. package/src/claude/inbound-content-options.ts +11 -1
  79. package/src/claude/intercept/picker-ca-cleanup.ts +17 -5
  80. package/src/claude/intercept/picker-ca.ts +162 -27
  81. package/src/claude/intercept/picker-trust-linux.ts +411 -0
  82. package/src/claude/intercept/picker-trust.ts +35 -3
  83. package/src/claude/intercept/runtime.ts +2 -2
  84. package/src/claude/subagent-force-status.ts +24 -5
  85. package/src/claude/subscription-reserve.ts +87 -0
  86. package/src/cli/account-api.ts +3 -0
  87. package/src/cli/account-auth.ts +65 -11
  88. package/src/cli/account-extended.ts +1 -1
  89. package/src/cli/account-next-actions.ts +4 -1
  90. package/src/cli/account-policy-dto.ts +1 -1
  91. package/src/cli/account-policy.ts +6 -3
  92. package/src/cli/account-probe.ts +66 -0
  93. package/src/cli/account.ts +8 -2
  94. package/src/cli/capabilities-accounts.ts +8 -1
  95. package/src/cli/capabilities-agents-routing.ts +2 -2
  96. package/src/cli/capabilities-base.ts +4 -4
  97. package/src/cli/capabilities-integrations.ts +44 -4
  98. package/src/cli/capabilities-provider-models.ts +6 -0
  99. package/src/cli/claude-context-settings.ts +60 -0
  100. package/src/cli/claude-desktop.ts +2 -2
  101. package/src/cli/claude.ts +15 -7
  102. package/src/cli/client-start-fence.ts +64 -1
  103. package/src/cli/combo-result.ts +1 -0
  104. package/src/cli/combo-stats.ts +1 -1
  105. package/src/cli/combo.ts +19 -2
  106. package/src/cli/config-command.ts +21 -8
  107. package/src/cli/connect.ts +16 -0
  108. package/src/cli/cross-home-owner.ts +65 -18
  109. package/src/cli/dispatch.ts +4 -0
  110. package/src/cli/gateway-client-command.ts +128 -0
  111. package/src/cli/index.ts +98 -97
  112. package/src/cli/init.ts +20 -4
  113. package/src/cli/integrations.ts +23 -3
  114. package/src/cli/launcher-context.ts +12 -1
  115. package/src/cli/link.ts +24 -5
  116. package/src/cli/models-runtime-subcommands.ts +1 -0
  117. package/src/cli/models-runtime.ts +32 -0
  118. package/src/cli/start-owner-fence.ts +5 -2
  119. package/src/cli/status.ts +3 -3
  120. package/src/cli/stop-client-process.ts +51 -0
  121. package/src/cli/stop-restore.ts +383 -36
  122. package/src/cli/sync-command.ts +2 -2
  123. package/src/cli/uninstall-client-state.ts +7 -0
  124. package/src/client/connect.ts +72 -13
  125. package/src/client/hub-client.ts +38 -0
  126. package/src/client/hub-relay.ts +61 -36
  127. package/src/client/hub-session.ts +106 -0
  128. package/src/client/lifecycle-lock.ts +6 -1
  129. package/src/client/link-relay.ts +2 -1
  130. package/src/client/machine-listener.ts +60 -1
  131. package/src/client/runtime-restart.ts +1 -0
  132. package/src/client/runtime.ts +104 -34
  133. package/src/client/state.ts +11 -0
  134. package/src/client/stop-darwin-process.ts +73 -0
  135. package/src/client/stop-file-routing.ts +49 -0
  136. package/src/client/stop-native-handoff.ts +108 -0
  137. package/src/client/stop-routing.ts +41 -7
  138. package/src/client/stop-teardown-owner.ts +173 -0
  139. package/src/client/sync-runtime.ts +23 -4
  140. package/src/clients/config-export/opencode-wire.ts +24 -0
  141. package/src/clients/config-export.ts +28 -19
  142. package/src/codex/auth-api/login-flow.ts +68 -33
  143. package/src/codex/auth-api/main-account-probe.ts +3 -3
  144. package/src/codex/auth-api/pool-quota-probe.ts +8 -7
  145. package/src/codex/auth-api/routes.ts +1 -1
  146. package/src/codex/catalog/aggregation.ts +22 -10
  147. package/src/codex/catalog/gather-capture.ts +11 -2
  148. package/src/codex/catalog/m365-copilot-models.ts +52 -0
  149. package/src/codex/catalog/provider-models.ts +126 -53
  150. package/src/codex/catalog/routed-gather.ts +26 -12
  151. package/src/codex/catalog-admission.ts +4 -6
  152. package/src/codex/catalog-auto-refresh.ts +4 -2
  153. package/src/codex/catalog-self-heal.ts +4 -2
  154. package/src/codex/control-plane-models.ts +6 -0
  155. package/src/codex/convergence.ts +10 -0
  156. package/src/codex/desktop-app/picker-freshness.ts +3 -14
  157. package/src/codex/desktop-app/types.ts +6 -0
  158. package/src/codex/desktop-app/windows-command-payload.ts +9 -0
  159. package/src/codex/desktop-app/windows.ts +20 -12
  160. package/src/codex/desktop-compatibility/installed-build.ts +61 -58
  161. package/src/codex/desktop-compatibility/runtime-ownership.ts +11 -5
  162. package/src/codex/desktop-compatibility/runtime.ts +51 -14
  163. package/src/codex/desktop-compatibility/windows-activation-source.ts +28 -13
  164. package/src/codex/desktop-compatibility/windows-package-command.ts +73 -33
  165. package/src/codex/desktop-compatibility/windows-package-launch.ts +41 -9
  166. package/src/codex/desktop-compatibility/windows-package-proof.ts +104 -0
  167. package/src/codex/inject/config-toml.ts +67 -73
  168. package/src/codex/inject/plan.ts +11 -10
  169. package/src/codex/inject/remove.ts +4 -1
  170. package/src/codex/inject.ts +1 -0
  171. package/src/codex/journal-config-restore.ts +31 -4
  172. package/src/codex/journal.ts +16 -4
  173. package/src/codex/model-cache.ts +98 -27
  174. package/src/codex/native-residue.ts +14 -13
  175. package/src/codex/paths.ts +65 -28
  176. package/src/codex/quota-observation-freshness.ts +4 -0
  177. package/src/codex/quota.ts +71 -8
  178. package/src/codex/routing/selection.ts +32 -8
  179. package/src/combos/capability-policy.ts +31 -0
  180. package/src/combos/failover.ts +82 -74
  181. package/src/combos/identifiers.ts +2 -2
  182. package/src/combos/index.ts +3 -0
  183. package/src/combos/jev-model-backend.ts +12 -4
  184. package/src/combos/jev-session-pin-config.ts +22 -9
  185. package/src/combos/jev.ts +15 -4
  186. package/src/combos/request-capability.ts +214 -0
  187. package/src/combos/request.ts +22 -15
  188. package/src/combos/resolve.ts +5 -2
  189. package/src/combos/suggestion-channel.ts +89 -0
  190. package/src/combos/types.ts +14 -1
  191. package/src/config/account-auto-pause-revisions.ts +33 -10
  192. package/src/config/atomic-write.ts +1 -1
  193. package/src/config/codex-ws-incremental-setting.ts +34 -0
  194. package/src/config/diagnostics.ts +47 -8
  195. package/src/config/live-topology.ts +4 -2
  196. package/src/config/load-degrade.ts +96 -2
  197. package/src/config/mutation-lock.ts +7 -3
  198. package/src/config/paths.ts +3 -0
  199. package/src/config/pending-teardown.ts +19 -3
  200. package/src/config/process-state.ts +30 -12
  201. package/src/config/provider-validation.ts +10 -0
  202. package/src/config/salvage.ts +2 -2
  203. package/src/config/schema/account-auto-pause.ts +15 -1
  204. package/src/config/schema/agy-acp-references.ts +257 -0
  205. package/src/config/schema/config-schema.ts +32 -0
  206. package/src/config/schema/leaf-validators.ts +42 -0
  207. package/src/config/schema/subscription-reserve.ts +33 -0
  208. package/src/config/windows-process-command-line.ts +27 -9
  209. package/src/config.ts +6 -0
  210. package/src/generated/compatibility-version.json +806 -402
  211. package/src/images/loop.ts +79 -39
  212. package/src/integrations/catalog-refresh.ts +19 -1
  213. package/src/integrations/gateway-clients/agy.ts +340 -0
  214. package/src/integrations/gateway-clients/antigravity.ts +224 -0
  215. package/src/integrations/gateway-clients/index.ts +89 -0
  216. package/src/integrations/gateway-clients/io.ts +278 -0
  217. package/src/integrations/gateway-clients/types.ts +80 -0
  218. package/src/integrations/route-intent-disconnect.ts +37 -21
  219. package/src/lib/app-owned-memory-stores.ts +9 -0
  220. package/src/lib/cloud-code-appeal-link.ts +30 -0
  221. package/src/lib/errors.ts +32 -0
  222. package/src/lib/executor-physical-send-receipt.ts +42 -0
  223. package/src/lib/failure-detail.ts +1 -0
  224. package/src/lib/gcp-adc.ts +5 -0
  225. package/src/lib/http-date.ts +91 -0
  226. package/src/lib/lab-passive-linker-registration.ts +2 -1
  227. package/src/lib/local-chat-completion.ts +13 -3
  228. package/src/lib/local-internal-call-capability.ts +1 -3
  229. package/src/lib/messages-error-body.ts +2 -1
  230. package/src/lib/outbound-credential-registry.ts +40 -4
  231. package/src/lib/pinned-http.ts +7 -2
  232. package/src/lib/process-control.ts +1 -0
  233. package/src/lib/provider-egress.ts +16 -0
  234. package/src/lib/provider-outbound.ts +3 -0
  235. package/src/lib/redact-folding.ts +12 -3
  236. package/src/lib/redact.ts +37 -19
  237. package/src/lib/request-execution-budget.ts +241 -32
  238. package/src/lib/request-peer-scope.ts +64 -0
  239. package/src/lib/response-send-readings.ts +41 -0
  240. package/src/lib/state-store-registrations.ts +5 -0
  241. package/src/lib/tool-envelope-echo-filter.ts +33 -5
  242. package/src/lib/upstream-condition.ts +10 -3
  243. package/src/lib/upstream-retry.ts +95 -20
  244. package/src/lib/windows-secret-acl.ts +24 -7
  245. package/src/link/child-activity.ts +60 -4
  246. package/src/link/codex-settings.ts +2 -1
  247. package/src/link/relay-auth.ts +1 -0
  248. package/src/link/route-rounds.ts +32 -9
  249. package/src/link/status-projection.ts +42 -5
  250. package/src/link/supervisor.ts +96 -11
  251. package/src/link/tunnel-history.ts +5 -0
  252. package/src/oauth/account-auto-pause-policy.ts +72 -19
  253. package/src/oauth/account-auto-pause.ts +40 -16
  254. package/src/oauth/anthropic-account-refusal.ts +7 -0
  255. package/src/oauth/anthropic-continuity.ts +70 -9
  256. package/src/oauth/anthropic-identity.ts +75 -11
  257. package/src/oauth/anthropic-login-slot.ts +258 -0
  258. package/src/oauth/anthropic-routing.ts +24 -9
  259. package/src/oauth/anthropic-send-ownership.ts +4 -3
  260. package/src/oauth/anthropic.ts +30 -11
  261. package/src/oauth/health.ts +7 -2
  262. package/src/oauth/index.ts +50 -48
  263. package/src/oauth/key-providers.ts +2 -0
  264. package/src/oauth/login-cli.ts +11 -0
  265. package/src/oauth/login-flow-state.ts +10 -4
  266. package/src/oauth/m365-copilot-browser.ts +222 -0
  267. package/src/oauth/m365-copilot-web-session.ts +25 -0
  268. package/src/oauth/m365-copilot.ts +57 -0
  269. package/src/oauth/model-discovery-auth.ts +5 -0
  270. package/src/oauth/plan.ts +44 -0
  271. package/src/oauth/pool-kernel.ts +22 -8
  272. package/src/oauth/pool-settings-capability.ts +14 -3
  273. package/src/oauth/reauth-precheck.ts +27 -0
  274. package/src/oauth/store-anthropic-instance.ts +3 -1
  275. package/src/oauth/store.ts +121 -23
  276. package/src/oauth/types.ts +27 -2
  277. package/src/protocols/codecs/chat-ir.ts +7 -4
  278. package/src/protocols/codecs/gemini-interactions.ts +770 -0
  279. package/src/protocols/codecs/gemini.ts +470 -0
  280. package/src/protocols/contract.ts +2 -0
  281. package/src/protocols/encoders/adapter-events.ts +5 -3
  282. package/src/protocols/encoders/chat.ts +23 -7
  283. package/src/protocols/settings.ts +3 -0
  284. package/src/providers/account-quota-disk.ts +26 -8
  285. package/src/providers/api-key-pause.ts +2 -2
  286. package/src/providers/api-key-response-ownership.ts +14 -4
  287. package/src/providers/claude-cli-usage-state.ts +1 -0
  288. package/src/providers/claude-cli-usage.ts +24 -7
  289. package/src/providers/default-aliases.ts +11 -5
  290. package/src/providers/derive.ts +5 -1
  291. package/src/providers/fastwire.ts +6 -5
  292. package/src/providers/free-directory.ts +2 -2
  293. package/src/providers/google-vertex-location.ts +2 -1
  294. package/src/providers/google-vertex-model-discovery.ts +22 -0
  295. package/src/providers/key-failover.ts +18 -23
  296. package/src/providers/m365-copilot-discovery-fetch.ts +17 -0
  297. package/src/providers/m365-copilot-discovery.ts +68 -0
  298. package/src/providers/m365-copilot-models.ts +32 -0
  299. package/src/providers/model-rename-fields.ts +6 -0
  300. package/src/providers/new-model-policy-runtime.ts +27 -6
  301. package/src/providers/openai-forward-destination.ts +19 -0
  302. package/src/providers/openai-tiers-destination.ts +3 -19
  303. package/src/providers/quota/account-cache.ts +183 -27
  304. package/src/providers/quota/anthropic-account-quota.ts +21 -17
  305. package/src/providers/quota/anthropic-cooldown-recovery.ts +57 -27
  306. package/src/providers/quota/anthropic-decision-windows.ts +7 -3
  307. package/src/providers/quota/anthropic-usage-windows.ts +34 -4
  308. package/src/providers/quota/antigravity-account-probe.ts +165 -0
  309. package/src/providers/quota/antigravity.ts +71 -3
  310. package/src/providers/quota/vendor-probes-oauth.ts +52 -28
  311. package/src/providers/quota-decision-publication.ts +1 -1
  312. package/src/providers/quota-decision-snapshot.ts +4 -1
  313. package/src/providers/quota-types.ts +2 -0
  314. package/src/providers/quota.ts +8 -7
  315. package/src/providers/registry/agy-acp-models.ts +3 -0
  316. package/src/providers/registry/entries-core.ts +9 -0
  317. package/src/providers/registry/entries-extended.ts +60 -0
  318. package/src/providers/registry/model-seeds.ts +51 -0
  319. package/src/providers/request-pacing.ts +37 -7
  320. package/src/providers/service-tier.ts +2 -0
  321. package/src/providers/xai-privacy-mode.ts +52 -0
  322. package/src/remote/hub-management-relay.ts +74 -0
  323. package/src/responses/id-limits.ts +2 -0
  324. package/src/responses/input-media.ts +15 -3
  325. package/src/responses/parser-tools.ts +74 -11
  326. package/src/responses/parser.ts +16 -14
  327. package/src/responses/provider-opaque-metadata.ts +10 -0
  328. package/src/responses/reasoning-envelope.ts +3 -0
  329. package/src/responses/schema.ts +2 -3
  330. package/src/responses/spill-store.ts +5 -3
  331. package/src/responses/state/connection-scope.ts +232 -0
  332. package/src/responses/state/entry-types.ts +47 -0
  333. package/src/responses/state/snapshot-codec.ts +75 -14
  334. package/src/responses/state/snapshot-select.ts +2 -0
  335. package/src/responses/state/spill-codec.ts +59 -0
  336. package/src/responses/state/spill-queue.ts +11 -2
  337. package/src/responses/state.ts +178 -159
  338. package/src/router.ts +2 -6
  339. package/src/routing/compatibility/behavior.ts +6 -2
  340. package/src/routing/compatibility/subject.ts +17 -12
  341. package/src/routing/machine-weighted-routing.ts +58 -0
  342. package/src/server/advisor-admission-scope.ts +15 -7
  343. package/src/server/auth-cors.ts +27 -0
  344. package/src/server/chat-completions.ts +37 -17
  345. package/src/server/chat-native-eligibility.ts +21 -0
  346. package/src/server/chat-native.ts +15 -6
  347. package/src/server/claude-messages.ts +54 -6
  348. package/src/server/credential-recovery-attempt.ts +32 -0
  349. package/src/server/effort-policy.ts +6 -3
  350. package/src/server/gemini-inbound.ts +267 -0
  351. package/src/server/gemini-interactions-inbound.ts +229 -0
  352. package/src/server/gemini-interactions-store.ts +129 -0
  353. package/src/server/gemini-native-catalog.ts +64 -0
  354. package/src/server/gemini-native-log.ts +33 -0
  355. package/src/server/gemini-native-paths.ts +88 -0
  356. package/src/server/gemini-native-wire.ts +201 -0
  357. package/src/server/gemini-native.ts +218 -0
  358. package/src/server/grok-upstream-envelope-echo.ts +8 -2
  359. package/src/server/hub-relay-auth.ts +87 -0
  360. package/src/server/hub-usage-windows.ts +135 -0
  361. package/src/server/hub-usage.ts +16 -3
  362. package/src/server/inbound-body-admission.ts +2 -1
  363. package/src/server/index/anthropic-model-listing.ts +75 -0
  364. package/src/server/index/gemini-routes.ts +147 -0
  365. package/src/server/index/link-management.ts +3 -22
  366. package/src/server/index/link-relay-sessions.ts +71 -13
  367. package/src/server/index/link-websocket.ts +2 -0
  368. package/src/server/index/passive-management-read.ts +55 -0
  369. package/src/server/index/serve-options.ts +93 -107
  370. package/src/server/index/websocket-handler.ts +15 -2
  371. package/src/server/index.ts +10 -0
  372. package/src/server/inference/client-encoder-delivery.ts +2 -1
  373. package/src/server/inference/context.ts +33 -6
  374. package/src/server/management/agent-settings-routes.ts +33 -16
  375. package/src/server/management/claude-code-settings-patch.ts +6 -0
  376. package/src/server/management/combo-routes.ts +21 -1
  377. package/src/server/management/combo-suggestion-routes.ts +212 -0
  378. package/src/server/management/config-routes.ts +12 -4
  379. package/src/server/management/context.ts +2 -0
  380. package/src/server/management/gateway-client-routes.ts +62 -0
  381. package/src/server/management/integration-routes.ts +5 -0
  382. package/src/server/management/link-routes.ts +5 -1
  383. package/src/server/management/m365-copilot-provider-probe.ts +23 -0
  384. package/src/server/management/model-routes.ts +32 -2
  385. package/src/server/management/model-rows.ts +36 -3
  386. package/src/server/management/oauth-account-routes.ts +68 -15
  387. package/src/server/management/protocol-settings-patch.ts +1 -0
  388. package/src/server/management/provider-omitted-fields.ts +25 -0
  389. package/src/server/management/provider-overwrite-carry.ts +33 -8
  390. package/src/server/management/provider-routes.ts +10 -16
  391. package/src/server/management/request-history-routes.ts +2 -2
  392. package/src/server/management/route-registry.ts +10 -0
  393. package/src/server/management/shared.ts +118 -30
  394. package/src/server/management/sibling-guard.ts +2 -1
  395. package/src/server/management/system-routes.ts +6 -0
  396. package/src/server/management-auth.ts +8 -1
  397. package/src/server/messages-native-scope.ts +19 -0
  398. package/src/server/messages-native.ts +156 -59
  399. package/src/server/messages-shared.ts +6 -0
  400. package/src/server/models-capabilities.ts +24 -0
  401. package/src/server/native-chat-bridge.ts +259 -0
  402. package/src/server/ollama-inbound.ts +36 -184
  403. package/src/server/passive-route-linker.ts +3 -1
  404. package/src/server/port-reclaim.ts +48 -4
  405. package/src/server/proxy-liveness.ts +79 -22
  406. package/src/server/relay.ts +16 -9
  407. package/src/server/request-log-account-rotation.ts +2 -1
  408. package/src/server/request-log-attempt-recovery.ts +24 -2
  409. package/src/server/request-log-attempt-usage.ts +5 -4
  410. package/src/server/request-log-committed-terminal.ts +87 -0
  411. package/src/server/request-log-failure-attribution.ts +3 -3
  412. package/src/server/request-log-failure-detail.ts +34 -0
  413. package/src/server/request-log-key-failure.ts +27 -0
  414. package/src/server/request-log-terminal-status.ts +25 -12
  415. package/src/server/request-log.ts +59 -63
  416. package/src/server/responses/adapter-continuation.ts +77 -44
  417. package/src/server/responses/adapter-delivery.ts +47 -22
  418. package/src/server/responses/adapter-dispatch.ts +150 -149
  419. package/src/server/responses/advisor-retention.ts +12 -4
  420. package/src/server/responses/advisor-slot.ts +97 -2
  421. package/src/server/responses/agent-task-recovery.ts +44 -11
  422. package/src/server/responses/agy-acp-preflight.ts +41 -0
  423. package/src/server/responses/anthropic-image-context.ts +44 -0
  424. package/src/server/responses/antigravity-validation-refusal.ts +25 -1
  425. package/src/server/responses/buffered-sse-json.ts +18 -1
  426. package/src/server/responses/codex-ws-correlation.ts +5 -2
  427. package/src/server/responses/codex-ws-exchange.ts +91 -8
  428. package/src/server/responses/codex-ws-incremental.ts +136 -0
  429. package/src/server/responses/codex-ws-pool.ts +22 -8
  430. package/src/server/responses/codex-ws-request.ts +5 -0
  431. package/src/server/responses/codex-ws-send-accounting.ts +8 -0
  432. package/src/server/responses/codex-ws-session.ts +14 -0
  433. package/src/server/responses/codex-ws-wire.ts +44 -22
  434. package/src/server/responses/combo-admission-snapshot.ts +93 -0
  435. package/src/server/responses/combo-required-tool-stream.ts +16 -4
  436. package/src/server/responses/combo-selection-keepalive.ts +5 -0
  437. package/src/server/responses/combo-stream-preflight.ts +182 -73
  438. package/src/server/responses/compact-response-body.ts +27 -0
  439. package/src/server/responses/compact.ts +174 -121
  440. package/src/server/responses/compaction-recovery.ts +7 -0
  441. package/src/server/responses/core-codex-account.ts +88 -62
  442. package/src/server/responses/core-combo-failure.ts +15 -0
  443. package/src/server/responses/core-combo-native.ts +12 -1
  444. package/src/server/responses/core-combo.ts +340 -94
  445. package/src/server/responses/core-normalize.ts +19 -12
  446. package/src/server/responses/core-opaque-recovery.ts +15 -4
  447. package/src/server/responses/core-options.ts +50 -5
  448. package/src/server/responses/core-pipeline.ts +11 -0
  449. package/src/server/responses/core.ts +7 -1
  450. package/src/server/responses/empty-completion-guard.ts +21 -7
  451. package/src/server/responses/estimated-usage.ts +2 -1
  452. package/src/server/responses/fetch-helpers.ts +95 -19
  453. package/src/server/responses/history-slim.ts +204 -0
  454. package/src/server/responses/hosted-advisor-spend.ts +49 -0
  455. package/src/server/responses/image-context-recovery.ts +199 -0
  456. package/src/server/responses/input-admission.ts +36 -11
  457. package/src/server/responses/jev-model-invoke.ts +23 -16
  458. package/src/server/responses/non-replayable-error.ts +12 -2
  459. package/src/server/responses/passthrough-build-error.ts +5 -3
  460. package/src/server/responses/passthrough-delivery.ts +74 -33
  461. package/src/server/responses/passthrough-dispatch.ts +170 -197
  462. package/src/server/responses/policy-fallback.ts +7 -2
  463. package/src/server/responses/policy-request-scope.ts +36 -2
  464. package/src/server/responses/replay-owner.ts +20 -0
  465. package/src/server/responses/request-prepare.ts +97 -16
  466. package/src/server/responses/request-send-budget.ts +97 -25
  467. package/src/server/responses/request-sidecar-auth.ts +138 -65
  468. package/src/server/responses/request-spend-target.ts +13 -1
  469. package/src/server/responses/request-spend.ts +228 -47
  470. package/src/server/responses/request-transport.ts +395 -70
  471. package/src/server/responses/run-turn-execution.ts +40 -9
  472. package/src/server/responses/sidecar-execution.ts +214 -67
  473. package/src/server/responses/sidecar-send-budget.ts +9 -9
  474. package/src/server/responses/terminal-guard.ts +35 -9
  475. package/src/server/responses/ws-upstream.ts +27 -6
  476. package/src/server/responses-phase-inference.ts +32 -9
  477. package/src/server/responses-terminal-repair.ts +14 -35
  478. package/src/server/system-env.ts +8 -5
  479. package/src/server/ws-bridge.ts +23 -17
  480. package/src/service/health-sentinel-linux.ts +16 -7
  481. package/src/service/systemd.ts +11 -2
  482. package/src/service/windows-checked-stop-live.ts +60 -55
  483. package/src/service/windows-checked-stop.ts +29 -11
  484. package/src/service/windows-guarded-manager.ts +14 -26
  485. package/src/service/windows-process-evidence.ts +82 -74
  486. package/src/service/windows-process-native.ts +69 -20
  487. package/src/service/windows-service-stop.ts +14 -12
  488. package/src/service/windows-stop-binding.ts +14 -5
  489. package/src/service/windows-stop-confirm.ts +1 -1
  490. package/src/service/windows-task-instance-stop.ts +98 -0
  491. package/src/service/windows-taskxml.ts +30 -7
  492. package/src/sidecar/anthropic-binding.ts +1 -1
  493. package/src/stall-timeout.ts +30 -0
  494. package/src/telemetry/aggregate.ts +6 -3
  495. package/src/types/account-auto-pause.ts +19 -1
  496. package/src/types/accounts.ts +21 -0
  497. package/src/types/anthropic-account-pool.ts +1 -1
  498. package/src/types/combo-capability-policy.ts +19 -0
  499. package/src/types/config.ts +22 -2
  500. package/src/types/provider.ts +42 -8
  501. package/src/types/request.ts +15 -0
  502. package/src/types/tools.ts +22 -5
  503. package/src/types/wire.ts +1 -0
  504. package/src/types.ts +4 -0
  505. package/src/update/check-types.ts +2 -0
  506. package/src/update/job.ts +8 -3
  507. package/src/update/managed-release.ts +6 -0
  508. package/src/update/orchestrated-entry.ts +13 -4
  509. package/src/update/refresh-scheduler.ts +17 -7
  510. package/src/usage/attempt-delivery.ts +6 -0
  511. package/src/usage/cache-provenance.ts +71 -0
  512. package/src/usage/cost.ts +216 -27
  513. package/src/usage/credit-billing.ts +88 -0
  514. package/src/usage/jev-stats.ts +13 -9
  515. package/src/usage/log.ts +5 -33
  516. package/src/usage/summary.ts +8 -43
  517. package/src/usage/user-cost-overlays.ts +13 -1
  518. package/src/vision/index.ts +8 -3
  519. package/src/vision/plan.ts +28 -14
  520. package/src/vision/routed-describe.ts +24 -36
  521. package/src/web-search/header-deadline.ts +14 -3
  522. package/src/web-search/index.ts +6 -4
  523. package/src/web-search/loop.ts +240 -78
  524. package/src/web-search/progress-stream.ts +29 -2
  525. package/src/web-search/run-turn-loop.ts +5 -1
  526. package/gui/dist/assets/App-BGP8I0V4.css +0 -1
  527. package/gui/dist/assets/App-BRExzhwL.js +0 -60
  528. package/gui/dist/assets/Tray-DHCWAn8V.js +0 -1
  529. package/gui/dist/assets/brand-mark-C70PuQ3j.js +0 -1
  530. package/gui/dist/assets/index-DJxM-imn.css +0 -2
  531. package/gui/dist/assets/index-Dy1jIGty.js +0 -138
  532. package/gui/dist/classic/assets/App-B4j-Txmb.css +0 -1
  533. package/gui/dist/classic/assets/App-CaC-E6Vl.js +0 -59
  534. package/gui/dist/classic/assets/Tray-BG253fiL.js +0 -1
  535. package/gui/dist/classic/assets/index-CR_AThOp.js +0 -138
  536. package/gui/dist/classic/assets/quota-summary-B7KQPpEC.js +0 -1
@@ -0,0 +1,745 @@
1
+ // Adapted from cramt/m365-copilot-proxy (65905e8), copyright 2026 Alexandra Østermark. MIT; see LICENSE.
2
+ import { getToneForModel, isSonnet55Model } from "../../providers/m365-copilot-models";
3
+ import type { ParsedToolCall, ToolDef } from "./tools";
4
+ const BODY_PARAM_NAMES = [
5
+ "command", "content", "code", "body", "script", "text",
6
+ "query", "input", "patch", "cmd", "data", "contents",
7
+ ];
8
+ const SEARCH_KEYS = ["old", "search", "find", "old_str", "old_string", "target"];
9
+ const REPLACE_KEYS = ["new", "replace", "replacement", "new_str", "new_string"];
10
+ const SHELL_LANGS = new Set([
11
+ "bash", "sh", "shell", "zsh", "console", "shell-session", "shellsession", "shsession",
12
+ "container.exec", "container.run", "container.bash",
13
+ "powershell", "pwsh", "ps1", "posh", "cmd", "bat", "batch", "dosbatch",
14
+ ]);
15
+ const SHELL_TOOL_NAME = /^(bash|sh|shell|zsh|run|exec|execute|command|cmd|terminal|run_command|run_terminal_cmd|execute_command|execute_bash|shell_exec|system)$/i;
16
+ const WRITE_PATH_PARAM = /^(path|file_path|filepath|filename|file)$/i;
17
+ const WRITE_CONTENT_PARAM = /^(content|contents|text|body)$/i;
18
+ export function findWriteTool(tools: ToolDef[]): ToolDef | undefined {
19
+ return tools.find((t) => {
20
+ const props = Object.keys(t.function.parameters?.properties ?? {});
21
+ return props.some((p) => WRITE_PATH_PARAM.test(p)) &&
22
+ props.some((p) => WRITE_CONTENT_PARAM.test(p)) &&
23
+ !props.some((p) => SEARCH_KEYS.includes(p));
24
+ });
25
+ }
26
+ export function findShellTool(tools: ToolDef[]): ToolDef | undefined {
27
+ return tools.find((t) => SHELL_TOOL_NAME.test(t.function.name)) ??
28
+ tools.find((t) => {
29
+ const props = Object.keys(t.function.parameters?.properties ?? {});
30
+ return props.length === 1 && /^(command|cmd|script|input)$/i.test(props[0]);
31
+ });
32
+ }
33
+ export interface FencedToolSpec {
34
+ name: string;
35
+ description?: string;
36
+ parameterTypes: Record<string, string>;
37
+ headerParams: string[];
38
+ bodyParam?: string;
39
+ editPair?: {
40
+ search: string;
41
+ replace: string;
42
+ };
43
+ }
44
+ export function deriveFencedSpec(tool: ToolDef): FencedToolSpec {
45
+ const name = tool.function.name;
46
+ const description = tool.function.description;
47
+ const propsSchema = tool.function.parameters?.properties ?? {};
48
+ const props = Object.keys(propsSchema);
49
+ const parameterTypes = Object.fromEntries(Object.entries(propsSchema).map(([k, v]: any) => [
50
+ k,
51
+ v?.type ?? "string",
52
+ ]));
53
+ const search = props.find((p) => SEARCH_KEYS.includes(p));
54
+ const replace = props.find((p) => REPLACE_KEYS.includes(p));
55
+ if (search && replace) {
56
+ return {
57
+ name,
58
+ description,
59
+ parameterTypes,
60
+ editPair: { search, replace },
61
+ headerParams: props.filter((p) => p !== search && p !== replace),
62
+ };
63
+ }
64
+ const bodyParam = props.find((p) => BODY_PARAM_NAMES.includes(p)) ??
65
+ (props.length === 1 ? props[0] : undefined);
66
+ return {
67
+ name,
68
+ description,
69
+ parameterTypes,
70
+ bodyParam,
71
+ headerParams: props.filter((p) => p !== bodyParam),
72
+ };
73
+ }
74
+ export function buildSpecMap(tools: ToolDef[]): Map<string, FencedToolSpec> {
75
+ const m = new Map<string, FencedToolSpec>();
76
+ for (const t of tools)
77
+ m.set(t.function.name, deriveFencedSpec(t));
78
+ const shell = findShellTool(tools);
79
+ if (shell) {
80
+ const shellSpec = m.get(shell.function.name)!;
81
+ for (const lang of SHELL_LANGS) {
82
+ if (!m.has(lang))
83
+ m.set(lang, shellSpec);
84
+ }
85
+ }
86
+ return m;
87
+ }
88
+ function scalarToString(v: unknown): string {
89
+ if (v === null || v === undefined)
90
+ return "";
91
+ if (typeof v === "string")
92
+ return v;
93
+ return JSON.stringify(v);
94
+ }
95
+ export function renderFencedCall(spec: FencedToolSpec, args: Record<string, unknown>): string {
96
+ const lines: string[] = [];
97
+ for (const h of spec.headerParams) {
98
+ if (args[h] !== undefined)
99
+ lines.push(`${h}: ${scalarToString(args[h])}`);
100
+ }
101
+ if (spec.editPair) {
102
+ lines.push("<<<<<<< SEARCH");
103
+ lines.push(scalarToString(args[spec.editPair.search]));
104
+ lines.push("=======");
105
+ lines.push(scalarToString(args[spec.editPair.replace]));
106
+ lines.push(">>>>>>> REPLACE");
107
+ }
108
+ else if (spec.bodyParam !== undefined) {
109
+ if (lines.length)
110
+ lines.push("");
111
+ lines.push(scalarToString(args[spec.bodyParam]));
112
+ }
113
+ return "```" + spec.name + "\n" + lines.join("\n") + "\n```";
114
+ }
115
+ function renderFencedTemplate(spec: FencedToolSpec): string {
116
+ const lines: string[] = [];
117
+ for (const h of spec.headerParams)
118
+ lines.push(`${h}: <${h}>`);
119
+ if (spec.editPair) {
120
+ lines.push("<<<<<<< SEARCH");
121
+ lines.push(`<${spec.editPair.search}>`);
122
+ lines.push("=======");
123
+ lines.push(`<${spec.editPair.replace}>`);
124
+ lines.push(">>>>>>> REPLACE");
125
+ }
126
+ else if (spec.bodyParam !== undefined) {
127
+ if (lines.length)
128
+ lines.push("");
129
+ lines.push(`<${spec.bodyParam}>`);
130
+ }
131
+ const header = spec.description ? `${spec.name} — ${spec.description}` : spec.name;
132
+ return `${header}\n\`\`\`${spec.name}\n${lines.join("\n")}\n\`\`\``;
133
+ }
134
+ export function formatFencedToolDefinitions(tools: ToolDef[], variantOverride?: string): string {
135
+ const variant = variantOverride ?? currentFramingVariant();
136
+ const key = variant === "reply_tool" ? "baseline" : variant;
137
+ const build = FRAMING_VARIANTS[key] ?? FRAMING_VARIANTS.baseline;
138
+ return build(tools) + hostPlatformNote(findShellTool(tools), undefined, findWriteTool(tools));
139
+ }
140
+ export function shellDialect(shell: ToolDef | undefined, platform: NodeJS.Platform = process.platform): "posix" | "powershell" | undefined {
141
+ if (!shell)
142
+ return undefined;
143
+ const override: string | undefined = undefined;
144
+ if (override === "bash" || override === "sh" || override === "posix")
145
+ return "posix";
146
+ if (override === "powershell" || override === "pwsh")
147
+ return "powershell";
148
+ const claim = `${shell.function.name} ${shell.function.description ?? ""}`.toLowerCase();
149
+ if (/\b(powershell|pwsh|cmd\.exe)\b/.test(claim))
150
+ return "powershell";
151
+ if (/\b(bash|zsh|sh|posix|wsl)\b/.test(claim))
152
+ return "posix";
153
+ return platform === "win32" ? "powershell" : "posix";
154
+ }
155
+ export function hostPlatformNote(shell: ToolDef | undefined, platform: NodeJS.Platform = process.platform, writeTool?: ToolDef): string {
156
+ if (platform !== "win32" || !shell)
157
+ return "";
158
+ if (shellDialect(shell, platform) === "posix") {
159
+ const longWrite = writeTool
160
+ ? `write any file longer than a few thousand characters with the \`${writeTool.function.name}\` tool, never in one heredoc`
161
+ : "write a long file in parts: create it with the first part, then append the rest with `cat >> file <<'EOF'` in later turns";
162
+ return `
163
+
164
+ HOST PLATFORM: Windows, but the \`${shell.function.name}\` tool is a POSIX shell on it (Git Bash or WSL), NOT PowerShell and NOT a container. Keep using \`\`\`${"bash"} blocks and POSIX idioms — \`<<'EOF'\` heredocs, \`sed -i\`, \`ls\`/\`grep\` all work. Do NOT emit PowerShell: \`Get-ChildItem\`, \`Set-Content\` and \`Write-Output\` are not commands here and the turn will fail.
165
+
166
+ The Windows command line is capped near 8,000 characters and a longer command is cut off silently, so a big heredoc leaves a truncated file. Keep each command short and ${longWrite}.
167
+
168
+ Only the filesystem is Windows: paths may be \`C:/Users/...\` or contain spaces, so quote them and prefer forward slashes. You are NOT in a Linux sandbox and have no \`/mnt/data\`; the working directory is the caller's real project directory — run \`pwd\` if you need to see it.`;
169
+ }
170
+ return `
171
+
172
+ HOST PLATFORM: Windows. The \`${shell.function.name}\` tool runs PowerShell on a real Windows machine — not Linux, and not a container. Any POSIX idiom named above is wrong here and will fail: there are no \`<<'EOF'\` heredocs, no \`sed -i\`, no \`ls\`/\`grep\`. Emit \`\`\`powershell blocks instead of \`\`\`bash, and use the Windows equivalents:
173
+
174
+ - create/overwrite a file: \`Set-Content -Path name -Value @'\n…\n'@\`
175
+ - edit in place: \`(Get-Content f) -replace 'old','new' | Set-Content f\`
176
+ - inspect: \`Get-Content\` / \`Get-ChildItem\` / \`Select-String\`
177
+ - paths use \`\\\` and may contain spaces — quote them.
178
+
179
+ You are NOT in a Linux sandbox and have no \`/mnt/data\`. The working directory is a real Windows path; run \`Get-Location\` if you need to see it.`;
180
+ }
181
+ export function currentFramingVariant(fallback: string = "baseline"): string {
182
+ return fallback;
183
+ }
184
+ export function defaultFramingForTone(tone?: string): string | undefined {
185
+ if (tone === "Claude_Opus")
186
+ return "relay_batch";
187
+ if (tone === "Claude_Sonnet")
188
+ return "relay_batch";
189
+ if (tone === "Claude_Sonnet_5")
190
+ return SONNET_5_DEFAULT_FRAMING;
191
+ if (tone === "Gpt_6_Reasoning")
192
+ return "relay_batch";
193
+ if (tone === "Gpt_6_Sol_Reasoning")
194
+ return "relay_batch";
195
+ if (tone === "Gpt_61_Sol_Reasoning")
196
+ return "relay_batch";
197
+ return undefined;
198
+ }
199
+ export function defaultFramingForModel(model: string): string | undefined {
200
+ if (isSonnet55Model(model))
201
+ return SONNET_5_5_DEFAULT_FRAMING;
202
+ return defaultFramingForTone(getToneForModel(model));
203
+ }
204
+ const SONNET_5_DEFAULT_FRAMING = "relay";
205
+ const SONNET_5_5_DEFAULT_FRAMING = "relay";
206
+ export interface TranscriptStyle {
207
+ framingTag: string | null;
208
+ systemTag: string;
209
+ }
210
+ const SYSTEM_STYLE: TranscriptStyle = { framingTag: "system", systemTag: "system" };
211
+ const RETAG_STYLE: TranscriptStyle = { framingTag: "harness_instructions", systemTag: "harness_system_prompt" };
212
+ const USER_VOICE_STYLE: TranscriptStyle = { framingTag: null, systemTag: "harness_system_prompt" };
213
+ const TRANSCRIPT_STYLES: Record<string, TranscriptStyle> = {
214
+ retag: RETAG_STYLE,
215
+ honest: USER_VOICE_STYLE,
216
+ terse_user: USER_VOICE_STYLE,
217
+ relay: USER_VOICE_STYLE,
218
+ relay_batch: USER_VOICE_STYLE,
219
+ };
220
+ export function transcriptStyleForVariant(variant: string): TranscriptStyle {
221
+ return TRANSCRIPT_STYLES[variant] ?? SYSTEM_STYLE;
222
+ }
223
+ const BUILT_IN_SANDBOX = "bash_tool, create_file, str_replace, view, …";
224
+ const SANDBOX_PATHS = "/home/claude, /mnt/user-data";
225
+ type FramingBuilder = (tools: ToolDef[]) => string;
226
+ function toolsBlock(tools: ToolDef[]): string {
227
+ const defs = tools.map((t) => renderFencedTemplate(deriveFencedSpec(t))).join("\n\n");
228
+ return `<tools>\n${defs}\n</tools>`;
229
+ }
230
+ const FRAMING_VARIANTS: Record<string, FramingBuilder> = {
231
+ baseline(tools) {
232
+ const shell = findShellTool(tools);
233
+ const shellFraming = shell ? `
234
+
235
+ THE WAY YOU DO ANYTHING IS BY WRITING A SHELL SCRIPT. You have a real shell (the \`${shell.function.name}\` tool). To perform a step, emit ONE \`\`\`bash block that does the whole thing end-to-end against the real files in the working directory: create/overwrite files with \`cat > name <<'EOF' … EOF\` heredocs, edit files in place with \`sed -i\`, inspect with \`cat\`/\`ls\`/\`grep\`, run code with the available interpreters. The block is executed for real and you get its output back. Writing the commands IS doing the task; describing what you "would" run, or claiming you did it, accomplishes nothing.
236
+
237
+ You have NOT run any command yet and have NO results. NEVER claim a command "returned no output", that files are "missing", or that you "cannot access" / "cannot list" the environment before you have actually emitted a \`\`\`bash block and seen its <tool_response>. The files named in the task are present on a real filesystem right now. Your FIRST output must be a \`\`\`bash block (e.g. \`ls -la\` then \`cat\` the relevant files) — never open with prose, a question, or a request for the user to paste files. Do not assume a file's contents or a command's result; run a command and read the real output. One self-contained \`\`\`bash block per turn.` : "";
238
+ return `You are the execution core of an automated agent, not a chat assistant. Your output is parsed by a program — a real runtime that executes your tool calls against a live system and returns the actual results to you in <tool_response> blocks.${shellFraming}
239
+
240
+ Performing the task with tools is your PRIMARY JOB. Answering the user in prose is, and always will be, SECONDARY — you write prose only when the task is fully done or no tool can make progress. Default to acting, not talking.
241
+
242
+ TOOL USE IS REQUIRED when the user asks you to read files, run commands, inspect the repository, fetch data, or perform any action a tool can accomplish. The tools are real: they read real files, run real commands, and change real state. Never answer from memory or simulate a result when a tool can provide it.
243
+
244
+ To call a tool, output ONLY a single fenced code block whose info-string is the tool name. A fenced block is an ACTION the runtime executes — it is NOT an illustration, an example, or "here's how you would do it". No text before or after it:
245
+
246
+ \`\`\`<tool_name>
247
+ <header lines: one "key: value" per scalar argument>
248
+
249
+ <body argument, if the tool has one>
250
+ \`\`\`
251
+
252
+ STRICT RULES:
253
+ - Output ONLY the fenced block when calling a tool. No prose, no second fence, no commentary before or after.
254
+ - Never describe your intent ("I'll read the file…", "Let me check…") and never emit filler or acknowledgements ("Good, that's fixable", "You're absolutely right"). Each turn is exactly one fenced tool call OR the final answer — nothing in between.
255
+ - One tool call per response, then stop and wait for its <tool_response>. Never emit two fenced blocks in one response.
256
+ - The fence info-string and the header keys must match a tool defined below exactly.
257
+ - A <tool_response> is the real result from the live system — treat it as ground truth, never invent or assume results.
258
+ - NEVER claim you have done something — read a file, run a command, written code, built, or succeeded — unless a <tool_response> proving it already appears above. Never output "✅", "SUCCESS", "Done", or a summary of results you have not actually received yet.
259
+ - If a tool call fails or returns partial data, immediately call another tool to resolve it. Do not give up.
260
+ - Do not defer work or promise future results ("I'll do this next…").
261
+ - Do not ask the user questions unless tool execution is impossible.
262
+ - Produce natural-language text only when the task is complete and no further tool call applies; that text is the answer returned to the caller. When you do, output only the answer itself — no preamble, no sign-off.
263
+
264
+ ${toolsBlock(tools)}`;
265
+ },
266
+ relay(tools) {
267
+ const lang = findShellTool(tools) ? "bash" : "<tool_name>";
268
+ return `Before the task, a note on how we'll work: I'd like you to guide me through this from my terminal, one command at a time. Please don't use your own sandbox tools (${BUILT_IN_SANDBOX}) — that's a separate cloud machine (${SANDBOX_PATHS}) and my project isn't on it.
269
+
270
+ Each time you want something run or looked at, reply with just the command in a single \`\`\`${lang} block (or one of the other tool blocks below). I'll run it in my project directory right away and paste the real output back to you as a <tool_response>. The files the task mentions are already there, so it's best to start by looking at them. When the task is complete, tell me in a sentence instead of sending a block.
271
+
272
+ ${toolsBlock(tools)}`;
273
+ },
274
+ relay_batch(tools) {
275
+ if (!findShellTool(tools))
276
+ return FRAMING_VARIANTS.relay(tools);
277
+ return `Before the task, a note on how we'll work: I'd like you to guide me through this from my terminal. Please don't use your own sandbox tools (${BUILT_IN_SANDBOX}) — that's a separate cloud machine (${SANDBOX_PATHS}) and my project isn't on it.
278
+
279
+ Each time you want something run, reply with just a single \`\`\`bash block (or one of the other tool blocks below). I'll run it in my project directory right away and paste the real output back to you as a <tool_response>. Each round trip takes me a while, so put as much as you can into one block: a script can look at the files, make the change and check the result all at once. The files the task mentions are already there. When the task is complete, tell me in a sentence instead of sending a block.
280
+
281
+ ${toolsBlock(tools)}`;
282
+ }
283
+ };
284
+ const FENCE_OPEN = /^[ \t]*```([A-Za-z0-9_.-]*)[ \t]*$/;
285
+ const FENCE_CLOSE = /^[ \t]*```[ \t]*$/;
286
+ const FENCE_OPEN_MIDLINE = /```([A-Za-z0-9_.-]+)[ \t]*$/;
287
+ const FENCE_CLOSE_GLUED = /\S```[ \t]*$/;
288
+ interface FenceBlock {
289
+ info: string;
290
+ inner: string;
291
+ start: number;
292
+ end: number;
293
+ }
294
+ function scanFences(text: string): FenceBlock[] {
295
+ const blocks: FenceBlock[] = [];
296
+ let depth = 0;
297
+ let open: {
298
+ info: string;
299
+ start: number;
300
+ bodyStart: number;
301
+ } | null = null;
302
+ let offset = 0;
303
+ for (const raw of text.split("\n")) {
304
+ const line = raw.endsWith("\r") ? raw.slice(0, -1) : raw;
305
+ const lineEnd = offset + raw.length;
306
+ const opener = FENCE_OPEN.exec(line)?.[1];
307
+ if (depth === 0) {
308
+ const midline = opener ? null : FENCE_OPEN_MIDLINE.exec(line);
309
+ if (opener || midline) {
310
+ open = { info: opener || midline![1], start: offset + (midline?.index ?? 0), bodyStart: lineEnd + 1 };
311
+ depth = 1;
312
+ }
313
+ }
314
+ else if (FENCE_CLOSE.test(line)) {
315
+ if (--depth === 0 && open) {
316
+ let inner = text.slice(open.bodyStart, Math.max(open.bodyStart, offset - 1));
317
+ if (inner.endsWith("\r"))
318
+ inner = inner.slice(0, -1);
319
+ blocks.push({ info: open.info, inner, start: open.start, end: lineEnd });
320
+ open = null;
321
+ }
322
+ }
323
+ else if (opener) {
324
+ depth++;
325
+ }
326
+ else if (depth === 1 && open && FENCE_CLOSE_GLUED.test(line)) {
327
+ const inner = text.slice(open.bodyStart, offset + line.trimEnd().length - 3);
328
+ blocks.push({ info: open.info, inner, start: open.start, end: lineEnd });
329
+ open = null;
330
+ depth = 0;
331
+ }
332
+ offset = lineEnd + 1;
333
+ }
334
+ return blocks;
335
+ }
336
+ const FENCE_OPEN_REGEX = /```([A-Za-z0-9_.-]+)[ \t]*\r?\n/g;
337
+ const SEARCH_REPLACE_REGEX = /<{5,}\s*SEARCH\s*\r?\n([\s\S]*?)\r?\n={5,}\s*\r?\n([\s\S]*?)\r?\n>{5,}\s*REPLACE/;
338
+ const escapeRegExp = (s: string) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
339
+ const NATIVE_TRAILER_LINE = String.raw `(?:<\/?(?:invoke|function_calls|parameter)\b[^\r\n]*|[^\p{L}\p{N}\r\n]{0,3})`;
340
+ function nativeCloserRegex(name: string): RegExp {
341
+ return new RegExp(String.raw `(?:\r?\n<\/?parameter\b[^\r\n]*)*\r?\n<\/(?:invoke|function_calls|parameter|${escapeRegExp(name)})>[ \t]*(?:\r?\n${NATIVE_TRAILER_LINE})*\s*$`, "u");
342
+ }
343
+ function gluedNativeCloserRegex(name: string): RegExp {
344
+ return new RegExp(String.raw `(?<=\S)[ \t]*<\/(invoke|function_calls|parameter|${escapeRegExp(name)})>[ \t]*(?:\r?\n${NATIVE_TRAILER_LINE})*\s*$`, "u");
345
+ }
346
+ function stripNativeCloser(inner: string, name: string): string | null {
347
+ const m = nativeCloserRegex(name).exec(inner);
348
+ const rest = m ? inner.slice(0, m.index) : inner;
349
+ const g = gluedNativeCloserRegex(name).exec(rest);
350
+ if (g) {
351
+ const line = rest.slice(rest.lastIndexOf("\n", g.index) + 1, g.index);
352
+ if (!new RegExp(String.raw `<${escapeRegExp(g[1])}\b`).test(line))
353
+ return rest.slice(0, g.index);
354
+ }
355
+ return m ? rest : null;
356
+ }
357
+ function findUnclosedToolFence(text: string, specs: Map<string, FencedToolSpec>): {
358
+ start: number;
359
+ end: number;
360
+ spec: FencedToolSpec;
361
+ inner: string;
362
+ } | null {
363
+ let last: RegExpExecArray | null = null;
364
+ const re = new RegExp(FENCE_OPEN_REGEX.source, "g");
365
+ for (let m = re.exec(text); m !== null; m = re.exec(text))
366
+ last = m;
367
+ if (!last)
368
+ return null;
369
+ const spec = specs.get(last[1]);
370
+ if (!spec)
371
+ return null;
372
+ const bodyStart = last.index + last[0].length;
373
+ const tail = text.slice(bodyStart);
374
+ if (tail.includes("```"))
375
+ return null;
376
+ const inner = stripNativeCloser(tail, last[1]);
377
+ if (inner === null)
378
+ return null;
379
+ return { start: last.index, end: text.length, spec, inner };
380
+ }
381
+ function makeCall(name: string, args: Record<string, unknown>): ParsedToolCall {
382
+ return {
383
+ id: `call_${crypto.randomUUID().replace(/-/g, "").slice(0, 24)}`,
384
+ type: "function",
385
+ function: { name, arguments: JSON.stringify(args) },
386
+ };
387
+ }
388
+ const TRUE_WORDS = new Set(["true", "yes", "y", "1", "on"]);
389
+ const FALSE_WORDS = new Set(["false", "no", "n", "0", "off"]);
390
+ function coerceHeaderValue(value: string, declaredType: string | undefined): unknown {
391
+ switch (declaredType) {
392
+ case "boolean": {
393
+ const v = value.toLowerCase();
394
+ if (TRUE_WORDS.has(v))
395
+ return true;
396
+ if (FALSE_WORDS.has(v))
397
+ return false;
398
+ return value;
399
+ }
400
+ case "integer":
401
+ case "number": {
402
+ if (value === "")
403
+ return value;
404
+ const n = Number(value);
405
+ if (!Number.isFinite(n))
406
+ return value;
407
+ if (declaredType === "integer" && !Number.isInteger(n))
408
+ return value;
409
+ return n;
410
+ }
411
+ case "array": {
412
+ if (value === "")
413
+ return [];
414
+ try {
415
+ const parsed = JSON.parse(value);
416
+ if (Array.isArray(parsed))
417
+ return parsed;
418
+ }
419
+ catch {
420
+ return [value];
421
+ }
422
+ return [value];
423
+ }
424
+ default:
425
+ return value;
426
+ }
427
+ }
428
+ const indentOf = (line: string): number => line.length - line.trimStart().length;
429
+ function yamlBlockEnd(lines: string[], from: number, isArray: boolean): number {
430
+ let end = from;
431
+ for (let j = from; j < lines.length; j++) {
432
+ const line = lines[j];
433
+ if (line.trim() === "")
434
+ continue;
435
+ if (/^[ \t]/.test(line) || (isArray && /^-([ \t]|$)/.test(line)))
436
+ end = j + 1;
437
+ else
438
+ break;
439
+ }
440
+ return end;
441
+ }
442
+ function parseYamlBlockValue(block: string[], declaredType: string): unknown {
443
+ let value: unknown;
444
+ try {
445
+ value = parseYamlNode(block.map((l) => l.replace(/\t/g, " ")));
446
+ }
447
+ catch {
448
+ return undefined;
449
+ }
450
+ if (declaredType === "array")
451
+ return Array.isArray(value) ? value : undefined;
452
+ return value !== null && typeof value === "object" && !Array.isArray(value) ? value : undefined;
453
+ }
454
+ class YamlSubsetError extends Error {
455
+ }
456
+ function parseYamlNode(lines: string[]): unknown {
457
+ const first = lines.findIndex((l) => l.trim() !== "");
458
+ if (first < 0)
459
+ throw new YamlSubsetError("empty block");
460
+ const body = lines.slice(first);
461
+ const indent = indentOf(body[0]);
462
+ const head = body[0].trimStart();
463
+ if (/^-([ \t]|$)/.test(head))
464
+ return parseYamlSequence(body, indent);
465
+ if (YAML_KEY.test(head))
466
+ return parseYamlMapping(body, indent);
467
+ if (body.slice(1).some((l) => l.trim() !== ""))
468
+ throw new YamlSubsetError("multi-line plain scalar");
469
+ return parseYamlScalar(head);
470
+ }
471
+ const YAML_KEY = /^("(?:[^"\\]|\\.)*"|'(?:[^']|'')*'|[^\s:#'"\-][^:]*?):(?:[ \t]+(.*)|[ \t]*)$/;
472
+ function childLines(lines: string[], from: number, indent: number): {
473
+ lines: string[];
474
+ next: number;
475
+ } {
476
+ let j = from;
477
+ for (; j < lines.length; j++) {
478
+ if (lines[j].trim() !== "" && indentOf(lines[j]) <= indent)
479
+ break;
480
+ }
481
+ return { lines: lines.slice(from, j), next: j };
482
+ }
483
+ function parseYamlSequence(lines: string[], indent: number): unknown[] {
484
+ const items: unknown[] = [];
485
+ let i = 0;
486
+ while (i < lines.length) {
487
+ const line = lines[i];
488
+ if (line.trim() === "") {
489
+ i++;
490
+ continue;
491
+ }
492
+ if (indentOf(line) !== indent || !/^-([ \t]|$)/.test(line.trimStart()))
493
+ throw new YamlSubsetError(`bad sequence line: ${line}`);
494
+ const rest = line.trimStart().slice(1);
495
+ const kids = childLines(lines, i + 1, indent);
496
+ if (rest.trim() === "") {
497
+ items.push(parseYamlNode(kids.lines));
498
+ }
499
+ else {
500
+ const itemIndent = indent + 1 + (rest.length - rest.trimStart().length);
501
+ const itemLines = [" ".repeat(itemIndent) + rest.trimStart(), ...kids.lines];
502
+ items.push(YAML_KEY.test(rest.trimStart()) ? parseYamlMapping(itemLines, itemIndent) : parseYamlValue(rest.trim(), kids.lines, indent));
503
+ }
504
+ i = kids.next;
505
+ }
506
+ return items;
507
+ }
508
+ function parseYamlMapping(lines: string[], indent: number): Record<string, unknown> {
509
+ const out: Record<string, unknown> = {};
510
+ let i = 0;
511
+ while (i < lines.length) {
512
+ const line = lines[i];
513
+ if (line.trim() === "") {
514
+ i++;
515
+ continue;
516
+ }
517
+ const m = indentOf(line) === indent ? line.trimStart().match(YAML_KEY) : null;
518
+ if (!m)
519
+ throw new YamlSubsetError(`bad mapping line: ${line}`);
520
+ const key = String(parseYamlScalar(m[1]));
521
+ let j = i + 1;
522
+ for (; j < lines.length; j++) {
523
+ const l = lines[j];
524
+ if (l.trim() === "")
525
+ continue;
526
+ const ind = indentOf(l);
527
+ if (ind > indent || (ind === indent && /^-([ \t]|$)/.test(l.trimStart()) && !(m[2] ?? "").trim()))
528
+ continue;
529
+ break;
530
+ }
531
+ out[key] = parseYamlValue((m[2] ?? "").trim(), lines.slice(i + 1, j), indent);
532
+ i = j;
533
+ }
534
+ return out;
535
+ }
536
+ function parseYamlValue(inline: string, nested: string[], parentIndent: number): unknown {
537
+ const block = inline.match(/^([|>])([-+]?)$/);
538
+ if (block)
539
+ return parseYamlBlockScalar(nested, parentIndent, block[1] === ">", block[2]);
540
+ if (inline === "")
541
+ return nested.some((l) => l.trim() !== "") ? parseYamlNode(nested) : "";
542
+ if (nested.some((l) => l.trim() !== ""))
543
+ throw new YamlSubsetError("value with both inline text and nested lines");
544
+ return parseYamlScalar(inline);
545
+ }
546
+ function parseYamlScalar(raw: string): unknown {
547
+ const s = raw.trim();
548
+ if (s.startsWith('"') && s.endsWith('"') && s.length >= 2) {
549
+ try {
550
+ return JSON.parse(s);
551
+ }
552
+ catch {
553
+ return s.slice(1, -1);
554
+ }
555
+ }
556
+ if (s.startsWith("'") && s.endsWith("'") && s.length >= 2)
557
+ return s.slice(1, -1).replace(/''/g, "'");
558
+ if ((s.startsWith("[") && s.endsWith("]")) || (s.startsWith("{") && s.endsWith("}"))) {
559
+ try {
560
+ return JSON.parse(s);
561
+ }
562
+ catch {
563
+ return s;
564
+ }
565
+ }
566
+ return s;
567
+ }
568
+ function parseYamlBlockScalar(lines: string[], parentIndent: number, folded: boolean, chomp: string): string {
569
+ const content = lines.filter((l) => l.trim() !== "");
570
+ if (!content.length)
571
+ return "";
572
+ const indent = Math.min(...content.map(indentOf));
573
+ if (indent <= parentIndent)
574
+ throw new YamlSubsetError("block scalar not indented");
575
+ const rows = lines.map((l) => (l.trim() === "" ? "" : l.slice(indent)));
576
+ let text = folded
577
+ ? rows.reduce((acc, row, k) => (k === 0 ? row : row === "" || rows[k - 1] === "" ? `${acc}\n${row}` : `${acc} ${row}`), "")
578
+ : rows.join("\n");
579
+ const trailing = text.match(/\n*$/)![0].length;
580
+ if (chomp === "+")
581
+ return `${text}\n`;
582
+ text = text.slice(0, text.length - trailing);
583
+ return chomp === "-" ? text : `${text}\n`;
584
+ }
585
+ function headerTextValue(inline: string, more: string[]): string {
586
+ const rows = [...more];
587
+ while (rows.length && rows[rows.length - 1].trim() === "")
588
+ rows.pop();
589
+ if (!rows.length)
590
+ return inline;
591
+ const block = inline.match(/^([|>])([-+]?)$/);
592
+ if (block) {
593
+ try {
594
+ return parseYamlBlockScalar(rows, 0, block[1] === ">", block[2]);
595
+ }
596
+ catch {
597
+ return headerTextValue("", rows);
598
+ }
599
+ }
600
+ if (inline === "" || block) {
601
+ const indent = Math.min(...rows.filter((l) => l.trim() !== "").map(indentOf));
602
+ return rows.map((l) => l.slice(Math.min(indent, indentOf(l)))).join("\n");
603
+ }
604
+ return [inline, ...rows].join("\n");
605
+ }
606
+ function parseFencedInner(spec: FencedToolSpec, inner: string): Record<string, unknown> | null {
607
+ const lines = inner.split("\n");
608
+ const args: Record<string, unknown> = {};
609
+ const headerOnly = !spec.editPair && spec.bodyParam === undefined;
610
+ let open: {
611
+ key: string;
612
+ inline: string;
613
+ more: string[];
614
+ } | null = null;
615
+ const closeOpen = () => {
616
+ if (open?.more.length)
617
+ args[open.key] = headerTextValue(open.inline, open.more);
618
+ open = null;
619
+ };
620
+ let i = 0;
621
+ if (spec.headerParams.length) {
622
+ for (; i < lines.length; i++) {
623
+ const line = lines[i];
624
+ const m = line.match(/^([A-Za-z0-9_]+):[ \t]?(.*)$/);
625
+ if (m && spec.headerParams.includes(m[1])) {
626
+ closeOpen();
627
+ const key = m[1];
628
+ const type = spec.parameterTypes[key];
629
+ if (m[2].trim() === "" && (type === "array" || type === "object")) {
630
+ const end = yamlBlockEnd(lines, i + 1, type === "array");
631
+ const value = end > i + 1 ? parseYamlBlockValue(lines.slice(i + 1, end), type) : undefined;
632
+ if (value !== undefined) {
633
+ args[key] = value;
634
+ i = end - 1;
635
+ continue;
636
+ }
637
+ }
638
+ args[key] = coerceHeaderValue(m[2].trim(), type);
639
+ if (headerOnly && (type ?? "string") === "string")
640
+ open = { key, inline: m[2].trim(), more: [] };
641
+ }
642
+ else if (open) {
643
+ open.more.push(line);
644
+ }
645
+ else if (line.trim() === "") {
646
+ i++;
647
+ break;
648
+ }
649
+ else {
650
+ break;
651
+ }
652
+ }
653
+ closeOpen();
654
+ }
655
+ const rest = lines.slice(i).join("\n");
656
+ if (spec.editPair) {
657
+ const sr = rest.match(SEARCH_REPLACE_REGEX);
658
+ if (!sr) {
659
+ return null;
660
+ }
661
+ args[spec.editPair.search] = sr[1];
662
+ args[spec.editPair.replace] = sr[2];
663
+ }
664
+ else if (spec.bodyParam !== undefined) {
665
+ args[spec.bodyParam] = rest;
666
+ }
667
+ return args;
668
+ }
669
+ export interface FencedParseResult {
670
+ calls: ParsedToolCall[];
671
+ leftover: string;
672
+ }
673
+ const RESTATED_SIMILARITY = 0.85;
674
+ const RESTATEMENT_GAP_CHARS = 300;
675
+ const CORRECTION_WORDS = /\b(?:oops|sorry|apolog\w*|mistake|typo|wrong|malformed|broken|incorrect\w*|corrected|correctly|fixed|same command|re-?formatted|properly formatted|try(?:ing)? again|let me redo)\b/i;
676
+ interface ToolFence {
677
+ start: number;
678
+ end: number;
679
+ name: string;
680
+ args: Record<string, unknown>;
681
+ hadNativeCloser: boolean;
682
+ }
683
+ function argTokens(args: Record<string, unknown>): Set<string> {
684
+ const text = Object.values(args).map((v) => (typeof v === "string" ? v : JSON.stringify(v))).join(" ");
685
+ return new Set(text.split(/\s+/).filter(Boolean));
686
+ }
687
+ function restates(prev: ToolFence, next: ToolFence, gap: string): boolean {
688
+ if (prev.name !== next.name || gap.trim().length > RESTATEMENT_GAP_CHARS)
689
+ return false;
690
+ if (!prev.hadNativeCloser && !CORRECTION_WORDS.test(gap))
691
+ return false;
692
+ const a = argTokens(prev.args);
693
+ const b = argTokens(next.args);
694
+ const shared = [...a].filter((t) => b.has(t)).length;
695
+ return shared / Math.max(1, new Set([...a, ...b]).size) >= RESTATED_SIMILARITY;
696
+ }
697
+ function toolFences(text: string, specs: Map<string, FencedToolSpec>): ToolFence[] {
698
+ const fences: ToolFence[] = [];
699
+ for (const block of scanFences(text)) {
700
+ const spec = specs.get(block.info);
701
+ if (!spec)
702
+ continue;
703
+ const stripped = stripNativeCloser(block.inner, block.info);
704
+ const args = parseFencedInner(spec, stripped ?? block.inner);
705
+ if (!args)
706
+ continue;
707
+ const fence: ToolFence = { start: block.start, end: block.end, name: spec.name, args, hadNativeCloser: stripped !== null };
708
+ const prev = fences[fences.length - 1];
709
+ if (prev && restates(prev, fence, text.slice(prev.end, fence.start))) {
710
+ fences[fences.length - 1] = { ...fence, start: prev.start };
711
+ continue;
712
+ }
713
+ fences.push(fence);
714
+ }
715
+ return fences;
716
+ }
717
+ export function parseFencedToolCalls(text: string, specs: Map<string, FencedToolSpec>): FencedParseResult {
718
+ const calls: ParsedToolCall[] = [];
719
+ let leftover = text;
720
+ for (const fence of toolFences(text, specs)) {
721
+ calls.push(makeCall(fence.name, fence.args));
722
+ leftover = leftover.replace(text.slice(fence.start, fence.end), "");
723
+ }
724
+ if (calls.length === 0) {
725
+ const open = findUnclosedToolFence(text, specs);
726
+ const args = open && parseFencedInner(open.spec, open.inner);
727
+ if (open && args) {
728
+ calls.push(makeCall(open.spec.name, args));
729
+ leftover = text.slice(0, open.start);
730
+ }
731
+ }
732
+ return { calls, leftover };
733
+ }
734
+ export function findFirstToolFence(text: string, specs: Map<string, FencedToolSpec>): {
735
+ start: number;
736
+ end: number;
737
+ } | null {
738
+ const first = toolFences(text, specs)[0];
739
+ if (first)
740
+ return { start: first.start, end: first.end };
741
+ const open = findUnclosedToolFence(text, specs);
742
+ if (open && parseFencedInner(open.spec, open.inner))
743
+ return { start: open.start, end: open.end };
744
+ return null;
745
+ }