@orion-agents/orion-code 0.3.66 → 0.4.4

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 (384) hide show
  1. package/CHANGELOG.md +87 -0
  2. package/README.md +78 -361
  3. package/README.zh-CN.md +71 -262
  4. package/bin/orion +4 -1
  5. package/dist/acp/session-updates.d.ts +35 -0
  6. package/dist/acp/session-updates.js +183 -0
  7. package/dist/acp/sessions.d.ts +32 -0
  8. package/dist/acp/sessions.js +328 -0
  9. package/dist/acp/stdio.d.ts +3 -0
  10. package/dist/acp/stdio.js +59 -0
  11. package/dist/cli.js +136 -185
  12. package/dist/commands/context-tool-command-handlers.d.ts +1 -1
  13. package/dist/commands/context-tool-command-handlers.js +24 -3
  14. package/dist/commands/core-command-handlers.js +10 -18
  15. package/dist/commands/diagnostic-command-handlers.js +58 -48
  16. package/dist/commands/diagnostic-commands.js +0 -12
  17. package/dist/commands/init-command.d.ts +3 -0
  18. package/dist/commands/init-command.js +131 -0
  19. package/dist/commands/model-command-handlers.d.ts +1 -2
  20. package/dist/commands/model-command-handlers.js +15 -100
  21. package/dist/commands/model-commands.js +0 -11
  22. package/dist/commands/registry.js +1 -19
  23. package/dist/commands/rsi-command.d.ts +2 -0
  24. package/dist/commands/rsi-command.js +180 -0
  25. package/dist/commands/session-command-handlers.js +28 -19
  26. package/dist/commands/system-commands.js +0 -1
  27. package/dist/commands/target-command.js +49 -6
  28. package/dist/commands/tool-commands.js +1 -1
  29. package/dist/commands/types.d.ts +4 -10
  30. package/dist/commands/types.js +1 -21
  31. package/dist/commands/workflow-command-handlers.js +13 -4
  32. package/dist/commands/workflow-commands.js +2 -2
  33. package/dist/framework/loop-budget-contract.d.ts +2 -8
  34. package/dist/framework/loop-budget-contract.js +0 -3
  35. package/dist/framework/loop-progress.d.ts +18 -0
  36. package/dist/framework/loop-progress.js +63 -0
  37. package/dist/framework/prompt.d.ts +0 -2
  38. package/dist/framework/prompt.js +9 -27
  39. package/dist/framework/query.d.ts +26 -31
  40. package/dist/framework/query.js +451 -292
  41. package/dist/framework/store.d.ts +6 -10
  42. package/dist/framework/store.js +2 -21
  43. package/dist/framework/tool-call-orchestrator.d.ts +7 -0
  44. package/dist/framework/tool-call-orchestrator.js +8 -3
  45. package/dist/framework/tool-state.d.ts +2 -0
  46. package/dist/framework/tool.d.ts +0 -23
  47. package/dist/framework/verification-command.d.ts +15 -0
  48. package/dist/framework/verification-command.js +32 -0
  49. package/dist/harness/assembler.d.ts +1 -0
  50. package/dist/harness/assembler.js +24 -0
  51. package/dist/harness/capsule.d.ts +1 -1
  52. package/dist/harness/capsule.js +33 -14
  53. package/dist/harness/context-harness.d.ts +37 -12
  54. package/dist/harness/context-harness.js +545 -35
  55. package/dist/harness/contract.js +1 -1
  56. package/dist/harness/drift-guard.d.ts +4 -0
  57. package/dist/harness/drift-guard.js +68 -16
  58. package/dist/harness/index.d.ts +1 -1
  59. package/dist/harness/intent.js +21 -0
  60. package/dist/harness/ledger.d.ts +7 -11
  61. package/dist/harness/ledger.js +50 -9
  62. package/dist/harness/progress-controller.d.ts +12 -7
  63. package/dist/harness/progress-controller.js +96 -29
  64. package/dist/harness/state.js +10 -1
  65. package/dist/harness/stop-controller.d.ts +0 -5
  66. package/dist/harness/stop-controller.js +11 -31
  67. package/dist/harness/task-checklist.d.ts +16 -0
  68. package/dist/harness/task-checklist.js +92 -0
  69. package/dist/harness/types.d.ts +78 -1
  70. package/dist/harness/verification.d.ts +19 -1
  71. package/dist/harness/verification.js +116 -29
  72. package/dist/index.d.ts +1 -1
  73. package/dist/index.js +1 -3
  74. package/dist/print-ui/event-stream.d.ts +43 -0
  75. package/dist/print-ui/event-stream.js +204 -0
  76. package/dist/print-ui/launch.d.ts +12 -1
  77. package/dist/print-ui/launch.js +173 -11
  78. package/dist/product/environment.d.ts +1 -1
  79. package/dist/product/environment.js +1 -1
  80. package/dist/product/identity.d.ts +1 -1
  81. package/dist/product/identity.js +1 -1
  82. package/dist/product/paths.d.ts +3 -2
  83. package/dist/product/paths.js +6 -2
  84. package/dist/runtime/agent-loop.d.ts +12 -2
  85. package/dist/runtime/agent-loop.js +172 -29
  86. package/dist/runtime/agent-runtime-controller.d.ts +14 -4
  87. package/dist/runtime/agent-runtime-controller.js +366 -192
  88. package/dist/runtime/agent-runtime-protocol.d.ts +10 -18
  89. package/dist/runtime/agent-runtime-runner.d.ts +10 -0
  90. package/dist/runtime/builtin-tool-provider.js +5 -1
  91. package/dist/runtime/capability-receipt-journal.js +1 -0
  92. package/dist/runtime/durable-tool-receipt-reader.js +2 -1
  93. package/dist/runtime/first-party-tool-services.d.ts +1 -0
  94. package/dist/runtime/first-party-tool-services.js +2 -12
  95. package/dist/runtime/first-party-tool-universe.d.ts +1 -0
  96. package/dist/runtime/first-party-tool-universe.js +1 -1
  97. package/dist/runtime/followup-queue-store.d.ts +16 -0
  98. package/dist/runtime/followup-queue-store.js +75 -0
  99. package/dist/runtime/goal-lifecycle-v2.d.ts +16 -4
  100. package/dist/runtime/goal-lifecycle-v2.js +217 -39
  101. package/dist/runtime/goal-runtime-coordinator.d.ts +14 -2
  102. package/dist/runtime/goal-runtime-coordinator.js +147 -36
  103. package/dist/runtime/goals/presentation.js +3 -1
  104. package/dist/runtime/goals/types.d.ts +1 -3
  105. package/dist/runtime/goals/types.js +0 -3
  106. package/dist/runtime/loop-budget.d.ts +0 -7
  107. package/dist/runtime/loop-budget.js +8 -52
  108. package/dist/runtime/mcp/first-party-mcp-adapter.d.ts +2 -0
  109. package/dist/runtime/mcp/first-party-mcp-adapter.js +23 -19
  110. package/dist/runtime/model-coordinator.js +2 -5
  111. package/dist/runtime/orion-runtime-v1.d.ts +18 -2
  112. package/dist/runtime/orion-runtime-v1.js +183 -46
  113. package/dist/runtime/orion-session-runner.d.ts +7 -0
  114. package/dist/runtime/orion-session-runner.js +82 -0
  115. package/dist/runtime/plan-review.d.ts +1 -0
  116. package/dist/runtime/plan-review.js +8 -4
  117. package/dist/runtime/product-bootstrap.d.ts +6 -0
  118. package/dist/runtime/product-bootstrap.js +41 -51
  119. package/dist/runtime/product-orion-runtime.js +129 -58
  120. package/dist/runtime/release-receipts.d.ts +24 -133
  121. package/dist/runtime/release-receipts.js +129 -693
  122. package/dist/runtime/rich-text/layout.js +108 -65
  123. package/dist/runtime/rsi/contracts.d.ts +50 -0
  124. package/dist/runtime/rsi/contracts.js +17 -0
  125. package/dist/runtime/rsi/diagnosis.d.ts +46 -0
  126. package/dist/runtime/rsi/diagnosis.js +98 -0
  127. package/dist/runtime/rsi/evaluation-suite.d.ts +25 -0
  128. package/dist/runtime/rsi/evaluation-suite.js +141 -0
  129. package/dist/runtime/rsi/evaluation-worker.d.ts +19 -0
  130. package/dist/runtime/rsi/evaluation-worker.js +64 -0
  131. package/dist/runtime/rsi/evaluation.d.ts +49 -0
  132. package/dist/runtime/rsi/evaluation.js +345 -0
  133. package/dist/runtime/rsi/lifecycle.d.ts +54 -0
  134. package/dist/runtime/rsi/lifecycle.js +279 -0
  135. package/dist/runtime/rsi/proposal.d.ts +39 -0
  136. package/dist/runtime/rsi/proposal.js +312 -0
  137. package/dist/runtime/rsi/receipt.d.ts +28 -0
  138. package/dist/runtime/rsi/receipt.js +138 -0
  139. package/dist/runtime/rsi/skill-state.d.ts +7 -0
  140. package/dist/runtime/rsi/skill-state.js +50 -0
  141. package/dist/runtime/rsi/trajectory.d.ts +19 -0
  142. package/dist/runtime/rsi/trajectory.js +314 -0
  143. package/dist/runtime/rsi/triage.d.ts +274 -0
  144. package/dist/runtime/rsi/triage.js +58 -0
  145. package/dist/runtime/session-composer-control.d.ts +5 -24
  146. package/dist/runtime/session-composer-control.js +27 -189
  147. package/dist/runtime/step-snapshot.d.ts +4 -1
  148. package/dist/runtime/step-snapshot.js +11 -1
  149. package/dist/runtime/subagent-thread-runtime.js +27 -5
  150. package/dist/runtime/subagents/policy.js +0 -1
  151. package/dist/runtime/subagents/production.js +1 -5
  152. package/dist/runtime/subagents/runtime-integration.js +2 -4
  153. package/dist/runtime/subagents/types.d.ts +0 -5
  154. package/dist/runtime/subagents/types.js +0 -2
  155. package/dist/runtime/task-context-recovery.d.ts +55 -0
  156. package/dist/runtime/task-context-recovery.js +349 -0
  157. package/dist/runtime/task-context-service.d.ts +20 -10
  158. package/dist/runtime/task-context-service.js +69 -9
  159. package/dist/runtime/thread-admission.d.ts +3 -1
  160. package/dist/runtime/thread-admission.js +21 -7
  161. package/dist/runtime/thread-event-store.d.ts +2 -2
  162. package/dist/runtime/thread-event-store.js +7 -2
  163. package/dist/runtime/thread-projection.js +4 -2
  164. package/dist/runtime/thread-runtime.d.ts +10 -0
  165. package/dist/runtime/thread-runtime.js +85 -3
  166. package/dist/runtime/thread-session-index.d.ts +8 -0
  167. package/dist/runtime/thread-session-index.js +50 -1
  168. package/dist/runtime/thread-session-view.d.ts +2 -1
  169. package/dist/runtime/thread-session-view.js +4 -0
  170. package/dist/runtime/thread-tool-journal.d.ts +1 -0
  171. package/dist/runtime/thread-tool-journal.js +6 -2
  172. package/dist/runtime/thread-ui-adapter.d.ts +1 -0
  173. package/dist/runtime/thread-ui-adapter.js +89 -22
  174. package/dist/runtime/tool-gateway.d.ts +9 -0
  175. package/dist/runtime/tool-gateway.js +24 -0
  176. package/dist/runtime/tool-receipt-validator.js +4 -0
  177. package/dist/runtime/tool-transcript-entry.d.ts +16 -0
  178. package/dist/runtime/tool-transcript-entry.js +73 -0
  179. package/dist/runtime/turn-commit.d.ts +4 -1
  180. package/dist/runtime/turn-commit.js +19 -15
  181. package/dist/runtime/ui-events.d.ts +15 -1
  182. package/dist/runtime/ui-view-model.d.ts +6 -5
  183. package/dist/runtime/ui-view-model.js +78 -61
  184. package/dist/runtime/workspace-runtime-kernel.js +0 -1
  185. package/dist/runtime/workspace-verification.d.ts +7 -0
  186. package/dist/runtime/workspace-verification.js +83 -0
  187. package/dist/services/atomic-write.d.ts +2 -0
  188. package/dist/services/atomic-write.js +12 -1
  189. package/dist/services/code-review/format.d.ts +4 -1
  190. package/dist/services/code-review/format.js +5 -1
  191. package/dist/services/code-review/runner.d.ts +2 -2
  192. package/dist/services/code-review/runner.js +86 -64
  193. package/dist/services/code-review/snapshot.d.ts +9 -9
  194. package/dist/services/code-review/snapshot.js +182 -166
  195. package/dist/services/compact/auto-compact.d.ts +21 -6
  196. package/dist/services/compact/auto-compact.js +148 -22
  197. package/dist/services/compact/background-candidate.d.ts +33 -0
  198. package/dist/services/compact/background-candidate.js +184 -0
  199. package/dist/services/compact/compact.d.ts +4 -1
  200. package/dist/services/compact/compact.js +30 -3
  201. package/dist/services/compact/coordinator.d.ts +10 -4
  202. package/dist/services/compact/coordinator.js +17 -7
  203. package/dist/services/compact/summary-generator.d.ts +4 -2
  204. package/dist/services/compact/summary-generator.js +17 -3
  205. package/dist/services/config.d.ts +5 -5
  206. package/dist/services/config.js +29 -48
  207. package/dist/services/doctor.js +85 -13
  208. package/dist/services/effort.d.ts +5 -5
  209. package/dist/services/effort.js +5 -11
  210. package/dist/services/file-lock.d.ts +9 -3
  211. package/dist/services/file-lock.js +92 -26
  212. package/dist/services/global-config.d.ts +26 -64
  213. package/dist/services/global-config.js +233 -193
  214. package/dist/services/llm.d.ts +42 -4
  215. package/dist/services/llm.js +177 -45
  216. package/dist/services/model-client-pool.d.ts +15 -9
  217. package/dist/services/model-client-pool.js +62 -33
  218. package/dist/services/model-context.d.ts +2 -1
  219. package/dist/services/model-context.js +15 -9
  220. package/dist/services/model-registry.d.ts +4 -15
  221. package/dist/services/model-registry.js +32 -101
  222. package/dist/services/provider-diagnostics.d.ts +8 -0
  223. package/dist/services/provider-diagnostics.js +17 -12
  224. package/dist/services/provider-resilience/coordinator.d.ts +1 -1
  225. package/dist/services/provider-resilience/coordinator.js +10 -6
  226. package/dist/services/provider-resilience/request-gate.d.ts +3 -0
  227. package/dist/services/provider-resilience/request-gate.js +29 -18
  228. package/dist/services/provider-resilience/types.d.ts +2 -0
  229. package/dist/services/session-storage.d.ts +7 -10
  230. package/dist/services/session-storage.js +57 -30
  231. package/dist/services/settings-coordinator.d.ts +0 -6
  232. package/dist/services/settings-coordinator.js +19 -56
  233. package/dist/services/settings-document-repository.d.ts +3 -10
  234. package/dist/services/settings-document-repository.js +7 -85
  235. package/dist/services/usage-state.d.ts +3 -3
  236. package/dist/services/usage-state.js +11 -42
  237. package/dist/terminal-ui/answer-format.d.ts +14 -0
  238. package/dist/terminal-ui/answer-format.js +119 -0
  239. package/dist/terminal-ui/launch.d.ts +7 -6
  240. package/dist/terminal-ui/launch.js +160 -70
  241. package/dist/terminal-ui/output-queue.d.ts +2 -1
  242. package/dist/terminal-ui/output-queue.js +1 -1
  243. package/dist/terminal-ui/raw-editor.d.ts +2 -1
  244. package/dist/terminal-ui/raw-editor.js +56 -15
  245. package/dist/tools/core/edit-file.js +6 -2
  246. package/dist/tools/core/write-file.js +9 -2
  247. package/dist/tools/lsp.d.ts +16 -1
  248. package/dist/tools/lsp.js +60 -19
  249. package/dist/tools/sandbox.d.ts +1 -1
  250. package/dist/tools/sandbox.js +3 -16
  251. package/dist/tools/todo.d.ts +4 -2
  252. package/dist/tools/todo.js +91 -30
  253. package/dist/tui-core/input-parser.d.ts +1 -0
  254. package/dist/tui-core/input-parser.js +6 -0
  255. package/dist/tui-core/style.d.ts +1 -8
  256. package/dist/tui-core/style.js +3 -110
  257. package/dist/tui-ui/chrome-view-model.d.ts +1 -1
  258. package/dist/tui-ui/chrome-view-model.js +36 -32
  259. package/dist/tui-ui/launch.js +14 -14
  260. package/dist/tui-ui/layout.d.ts +5 -7
  261. package/dist/tui-ui/layout.js +129 -124
  262. package/dist/tui-ui/runner.d.ts +11 -12
  263. package/dist/tui-ui/runner.js +88 -67
  264. package/dist/tui-ui/state.d.ts +0 -11
  265. package/dist/tui-ui/state.js +22 -33
  266. package/dist/tui-ui/terminal-image.js +22 -4
  267. package/dist/tui-ui/transcript-inspector-layout.js +6 -3
  268. package/dist/tui-ui/transcript-inspector.d.ts +1 -0
  269. package/dist/tui-ui/transcript-inspector.js +7 -1
  270. package/dist/tui-ui/transcript-layout.js +42 -6
  271. package/dist/utils/terminal-text.d.ts +11 -0
  272. package/dist/utils/terminal-text.js +114 -0
  273. package/docs/cli-guide.md +575 -0
  274. package/docs/orion.example.yaml +43 -0
  275. package/docs/readme.md +12 -57
  276. package/npm-shrinkwrap.json +484 -1855
  277. package/package.json +13 -63
  278. package/dist/migration/command.d.ts +0 -9
  279. package/dist/migration/command.js +0 -100
  280. package/dist/migration/index.d.ts +0 -7
  281. package/dist/migration/index.js +0 -14
  282. package/dist/migration/migrate.d.ts +0 -19
  283. package/dist/migration/migrate.js +0 -406
  284. package/dist/migration/types.d.ts +0 -55
  285. package/dist/migration/types.js +0 -6
  286. package/dist/services/tool-allowlist.d.ts +0 -110
  287. package/dist/services/tool-allowlist.js +0 -299
  288. package/dist/services/yaml-config.d.ts +0 -57
  289. package/dist/services/yaml-config.js +0 -178
  290. package/dist/web/cli-options.d.ts +0 -17
  291. package/dist/web/cli-options.js +0 -51
  292. package/dist/web/code-review-run-service.d.ts +0 -68
  293. package/dist/web/code-review-run-service.js +0 -228
  294. package/dist/web/context-text.d.ts +0 -17
  295. package/dist/web/context-text.js +0 -40
  296. package/dist/web/errors.d.ts +0 -6
  297. package/dist/web/errors.js +0 -13
  298. package/dist/web/event-hub.d.ts +0 -45
  299. package/dist/web/event-hub.js +0 -370
  300. package/dist/web/file-read-service.d.ts +0 -101
  301. package/dist/web/file-read-service.js +0 -593
  302. package/dist/web/file-write-service.d.ts +0 -16
  303. package/dist/web/file-write-service.js +0 -103
  304. package/dist/web/git-compare-service.d.ts +0 -45
  305. package/dist/web/git-compare-service.js +0 -160
  306. package/dist/web/git-diff-document.d.ts +0 -102
  307. package/dist/web/git-diff-document.js +0 -258
  308. package/dist/web/git-file-source.d.ts +0 -25
  309. package/dist/web/git-file-source.js +0 -21
  310. package/dist/web/git-history-service.d.ts +0 -151
  311. package/dist/web/git-history-service.js +0 -619
  312. package/dist/web/git-index-transaction.d.ts +0 -45
  313. package/dist/web/git-index-transaction.js +0 -174
  314. package/dist/web/git-patch-builder.d.ts +0 -30
  315. package/dist/web/git-patch-builder.js +0 -138
  316. package/dist/web/git-read-model-service.d.ts +0 -452
  317. package/dist/web/git-read-model-service.js +0 -1833
  318. package/dist/web/git-version-service.d.ts +0 -79
  319. package/dist/web/git-version-service.js +0 -279
  320. package/dist/web/host-daemon.d.ts +0 -70
  321. package/dist/web/host-daemon.js +0 -237
  322. package/dist/web/index.d.ts +0 -6
  323. package/dist/web/index.js +0 -28
  324. package/dist/web/launch.d.ts +0 -12
  325. package/dist/web/launch.js +0 -89
  326. package/dist/web/native-directory-picker.d.ts +0 -63
  327. package/dist/web/native-directory-picker.js +0 -169
  328. package/dist/web/protocol.d.ts +0 -705
  329. package/dist/web/protocol.js +0 -639
  330. package/dist/web/review-service.d.ts +0 -22
  331. package/dist/web/review-service.js +0 -68
  332. package/dist/web/server.d.ts +0 -20
  333. package/dist/web/server.js +0 -1453
  334. package/dist/web/session-runtime-registry.d.ts +0 -138
  335. package/dist/web/session-runtime-registry.js +0 -471
  336. package/dist/web/terminal-manager.d.ts +0 -156
  337. package/dist/web/terminal-manager.js +0 -779
  338. package/dist/web/terminal-server.d.ts +0 -8
  339. package/dist/web/terminal-server.js +0 -304
  340. package/dist/web/workbench-controller.d.ts +0 -395
  341. package/dist/web/workbench-controller.js +0 -3077
  342. package/dist/web/workspace-discovery.d.ts +0 -92
  343. package/dist/web/workspace-discovery.js +0 -324
  344. package/dist/web/workspace-mutation-arbiter.d.ts +0 -54
  345. package/dist/web/workspace-mutation-arbiter.js +0 -267
  346. package/dist/web/workspace-open-telemetry.d.ts +0 -55
  347. package/dist/web/workspace-open-telemetry.js +0 -73
  348. package/dist/web-client/assets/FilesPanel-CPDovK_K.js +0 -1
  349. package/dist/web-client/assets/GitPanel-DtU_TD61.js +0 -4
  350. package/dist/web-client/assets/ReviewPanel-vMO7BEA3.js +0 -6
  351. package/dist/web-client/assets/TerminalPanel-C9vDTAlS.js +0 -23
  352. package/dist/web-client/assets/TerminalPanel-DLuoa74B.css +0 -1
  353. package/dist/web-client/assets/index-CABdwh4l.css +0 -1
  354. package/dist/web-client/assets/index-KvshfEbl.js +0 -20
  355. package/dist/web-client/assets/useAutoNotice-IE1g2wcb.js +0 -1
  356. package/dist/web-client/favicon.svg +0 -9
  357. package/dist/web-client/index.html +0 -17
  358. package/docs/architecture/agent-mode-permission-contract.md +0 -87
  359. package/docs/architecture/v0.3.0-web-api.yaml +0 -1340
  360. package/docs/architecture/v0.3.1-web-api.yaml +0 -2338
  361. package/docs/architecture/v0.3.2-web-api.yaml +0 -3029
  362. package/docs/architecture/v0.3.3-web-api.yaml +0 -3205
  363. package/docs/architecture/v0.3.4-stabilization-contract.md +0 -32
  364. package/docs/migration/v0.1.9-to-v0.2.0.md +0 -98
  365. package/docs/migration/v0.2.2-to-v0.3.0-settings.md +0 -114
  366. package/docs/migration/v0.2.2-to-v0.3.0.md +0 -55
  367. package/docs/migration/v0.3.0-to-v0.3.1.md +0 -88
  368. package/docs/migration/v0.3.1-to-v0.3.2.md +0 -94
  369. package/docs/migration/v0.3.2-to-v0.3.3.md +0 -62
  370. package/docs/migration/v0.3.3-to-v0.3.4.md +0 -36
  371. package/docs/orion.example.json +0 -86
  372. package/docs/plan/v0.2.0-dsh-harness-redesign-plan.md +0 -1234
  373. package/docs/plan/v0.2.0-release-checklist.md +0 -91
  374. package/docs/plan/v0.3.0-node-runtime-compatibility-plan.md +0 -57
  375. package/docs/plan/v0.3.0-settings-integration-plan.md +0 -740
  376. package/docs/plan/v0.3.0-web-workbench-plan.md +0 -376
  377. package/docs/plan/v0.3.1-web-workbench-professional-shell-plan.md +0 -848
  378. package/docs/plan/v0.3.2-web-workbench-layout-and-composer-plan.md +0 -869
  379. package/docs/plan/v0.3.3-plan.md +0 -1113
  380. package/docs/plan/v0.3.4-stabilization-plan.md +0 -89
  381. package/docs/test/v0.3.1-web-workbench-e2e-plan.md +0 -140
  382. package/docs/test/v0.3.2-web-workbench-e2e-plan.md +0 -100
  383. package/docs/test/v0.3.3-web-workbench-e2e-plan.md +0 -79
  384. package/docs/test/v0.3.4-stabilization-e2e-plan.md +0 -54
@@ -10,28 +10,30 @@
10
10
  * chunks directly to stdout via the callback.
11
11
  */
12
12
  Object.defineProperty(exports, "__esModule", { value: true });
13
- exports.QueryLoopError = exports.DEFAULT_MAX_MODEL_VISIBLE_TOOL_RESULT_BYTES = exports.DEFAULT_LOOP_BUDGET = void 0;
13
+ exports.QueryLoopError = exports.MIN_MODEL_VISIBLE_TOOL_RESULT_BYTES = exports.DEFAULT_MAX_MODEL_VISIBLE_TOOL_RESULT_BYTES = exports.DEFAULT_LOOP_BUDGET = void 0;
14
14
  exports.withLoopFinishReason = withLoopFinishReason;
15
15
  exports.createLocalFastPathLoopStats = createLocalFastPathLoopStats;
16
16
  exports.createFailedLoopStats = createFailedLoopStats;
17
17
  exports.query = query;
18
18
  const llm_1 = require("../services/llm");
19
+ const provider_diagnostics_1 = require("../services/provider-diagnostics");
19
20
  const tool_1 = require("./tool");
20
- const strategy_tracker_1 = require("../core/strategy-tracker");
21
21
  const auto_compact_1 = require("../services/compact/auto-compact");
22
22
  const fingerprint_1 = require("../services/compact/fingerprint");
23
23
  const tool_call_groups_1 = require("../services/compact/tool-call-groups");
24
24
  const tool_call_orchestrator_1 = require("./tool-call-orchestrator");
25
25
  const token_estimate_1 = require("../utils/token-estimate");
26
+ const terminal_text_1 = require("../utils/terminal-text");
26
27
  const tool_serializer_1 = require("./tool-serializer");
27
28
  const model_context_1 = require("../services/model-context");
28
29
  const stop_decision_1 = require("./stop-decision");
30
+ const loop_progress_1 = require("./loop-progress");
29
31
  const loop_budget_contract_1 = require("./loop-budget-contract");
30
32
  var loop_budget_contract_2 = require("./loop-budget-contract");
31
33
  Object.defineProperty(exports, "DEFAULT_LOOP_BUDGET", { enumerable: true, get: function () { return loop_budget_contract_2.DEFAULT_LOOP_BUDGET; } });
32
34
  exports.DEFAULT_MAX_MODEL_VISIBLE_TOOL_RESULT_BYTES = 4096;
33
- /** Read-only tools eligible for the fragmentation hint; kept loop-local so Query has no tool registry. */
34
- const BATCH_READ_ALLOWED_TOOLS = new Set(['git_status', 'list_files', 'glob', 'grep', 'read_file']);
35
+ /** Bounded recovery visibility after the shared compression allowance is spent. */
36
+ exports.MIN_MODEL_VISIBLE_TOOL_RESULT_BYTES = 2048;
35
37
  function isAborted(signal) {
36
38
  return signal?.aborted === true;
37
39
  }
@@ -82,11 +84,7 @@ function parseBatchReadEvidenceSteps(result) {
82
84
  ];
83
85
  });
84
86
  }
85
- const COMPLEX_LOOP_BUDGET = {
86
- maxLlmRequestsPerUserTurn: 48,
87
- maxToolCallsPerUserTurn: 180,
88
- maxModelVisibleToolBytes: 96 * 1024,
89
- };
87
+ const TOOL_PRESSURE_COMPACT_RATIO = 0.9;
90
88
  class QueryLoopError extends Error {
91
89
  constructor(error, stats, aggregateUsage) {
92
90
  super(error instanceof Error ? error.message : String(error));
@@ -113,12 +111,21 @@ function createLoopStats() {
113
111
  providerRetryErrorTypes: [],
114
112
  providerFallbackCount: 0,
115
113
  providerUsingFallback: false,
116
- singleReadOnlyStreak: 0,
117
- batchReadSuggestionCount: 0,
118
114
  localFastPathUsed: false,
119
115
  };
120
116
  }
121
117
  function stopDecisionForLoop(stats, finishReason) {
118
+ const resources = {
119
+ turns: { used: stats.turnsStarted },
120
+ llmRequests: { used: stats.llmRequests },
121
+ toolCalls: { used: stats.toolCalls },
122
+ modelVisibleToolBytes: {
123
+ used: stats.modelVisibleToolBytes,
124
+ ...(stats.loopBudgetMaxModelVisibleBytes === undefined
125
+ ? {}
126
+ : { limit: stats.loopBudgetMaxModelVisibleBytes }),
127
+ },
128
+ };
122
129
  if (finishReason === 'compact_paused' && stats.compactFailure) {
123
130
  const failure = stats.compactFailure;
124
131
  return (0, stop_decision_1.createStopDecision)({
@@ -140,6 +147,7 @@ function stopDecisionForLoop(stats, finishReason) {
140
147
  { kind: 'resume', label: 'Resume after changing context or budget', command: '继续' },
141
148
  ],
142
149
  resources: {
150
+ ...resources,
143
151
  tokens: {
144
152
  used: Math.max(0, Math.round(failure.afterTokens ?? failure.beforeTokens)),
145
153
  limit: Math.max(0, Math.round(failure.targetTokens)),
@@ -147,27 +155,24 @@ function stopDecisionForLoop(stats, finishReason) {
147
155
  },
148
156
  });
149
157
  }
150
- const status = finishReason === 'completed'
151
- ? 'completed'
152
- : finishReason === 'cancelled'
153
- ? 'cancelled'
154
- : finishReason === 'failed'
155
- ? 'failed'
156
- : finishReason === 'blocked'
157
- ? 'blocked'
158
- : 'stopped';
159
- const reasonCode = finishReason === 'budget_exceeded'
160
- ? /LLM request budget/iu.test(stats.budgetExceededReason ?? '')
161
- ? 'llm_request_budget'
162
- : /tool call budget/iu.test(stats.budgetExceededReason ?? '')
163
- ? 'tool_call_budget'
164
- : /preflight|provider/iu.test(stats.budgetExceededReason ?? '')
165
- ? 'provider_preflight_budget'
166
- : 'resource_budget'
167
- : finishReason;
158
+ const missingOutput = finishReason === 'failed' ? stats.missingAssistantOutput : undefined;
159
+ const providerStop = finishReason === 'failed' ? stats.providerStop : undefined;
160
+ const status = finishReason === 'completed' ||
161
+ finishReason === 'cancelled' ||
162
+ finishReason === 'failed' ||
163
+ finishReason === 'blocked'
164
+ ? finishReason
165
+ : 'stopped';
166
+ const reasonCode = providerStop?.code ??
167
+ missingOutput ??
168
+ (finishReason === 'budget_exceeded'
169
+ ? (stats.budgetStopCode ?? 'resource_budget')
170
+ : finishReason);
168
171
  const resumable = finishReason === 'budget_exceeded' ||
169
172
  finishReason === 'completion_gate' ||
170
- finishReason === 'blocked';
173
+ finishReason === 'blocked' ||
174
+ missingOutput !== undefined ||
175
+ providerStop !== undefined;
171
176
  const evidence = [];
172
177
  if (finishReason === 'budget_exceeded') {
173
178
  evidence.push({
@@ -176,6 +181,16 @@ function stopDecisionForLoop(stats, finishReason) {
176
181
  detail: stats.budgetExceededReason ?? 'request resource budget reached',
177
182
  });
178
183
  }
184
+ if (missingOutput) {
185
+ evidence.push({
186
+ kind: 'provider',
187
+ source: 'query',
188
+ detail: 'The provider returned successfully without visible final assistant text.',
189
+ });
190
+ }
191
+ if (providerStop) {
192
+ evidence.push({ kind: 'provider', source: 'query', detail: providerStop.message });
193
+ }
179
194
  if (stats.lastToolName) {
180
195
  evidence.push({
181
196
  kind: 'tool_boundary',
@@ -184,6 +199,24 @@ function stopDecisionForLoop(stats, finishReason) {
184
199
  });
185
200
  }
186
201
  const nextActions = [];
202
+ if (providerStop) {
203
+ nextActions.push({ kind: 'resume', label: 'Continue after resolving the provider stop.' });
204
+ }
205
+ if (missingOutput) {
206
+ if (stats.toolCalls > 0) {
207
+ nextActions.push({
208
+ kind: 'inspect',
209
+ label: 'Inspect the tool results already saved for this turn',
210
+ });
211
+ }
212
+ else {
213
+ nextActions.push({ kind: 'retry', label: 'Retry the request or select another model' });
214
+ }
215
+ nextActions.push({
216
+ kind: 'change_input',
217
+ label: 'Ask for a brief checkpoint or a narrower next step',
218
+ });
219
+ }
187
220
  for (const action of stats.continuationActions ?? []) {
188
221
  if (action === 'reply_continue') {
189
222
  nextActions.push({ kind: 'continue', label: 'Continue the same objective', command: '继续' });
@@ -208,33 +241,16 @@ function stopDecisionForLoop(stats, finishReason) {
208
241
  disposition: resumable ? 'resume_allowed' : 'finish_scope',
209
242
  reason: {
210
243
  code: reasonCode,
211
- message: finishReason === 'budget_exceeded'
212
- ? (stats.budgetExceededReason ?? 'Request resource budget reached')
213
- : `Request finished with ${finishReason}`,
244
+ message: providerStop?.message ??
245
+ (missingOutput
246
+ ? missingAssistantOutputMessage(stats.toolCalls)
247
+ : finishReason === 'budget_exceeded'
248
+ ? (stats.budgetExceededReason ?? 'Request resource budget reached')
249
+ : `Request finished with ${finishReason}`),
214
250
  },
215
251
  evidence,
216
252
  nextActions,
217
- resources: {
218
- turns: { used: stats.turnsStarted },
219
- llmRequests: {
220
- used: stats.llmRequests,
221
- ...(stats.loopBudgetMaxLlmRequests === undefined
222
- ? {}
223
- : { limit: stats.loopBudgetMaxLlmRequests }),
224
- },
225
- toolCalls: {
226
- used: stats.toolCalls,
227
- ...(stats.loopBudgetMaxToolCalls === undefined
228
- ? {}
229
- : { limit: stats.loopBudgetMaxToolCalls }),
230
- },
231
- modelVisibleToolBytes: {
232
- used: stats.modelVisibleToolBytes,
233
- ...(stats.loopBudgetMaxModelVisibleBytes === undefined
234
- ? {}
235
- : { limit: stats.loopBudgetMaxModelVisibleBytes }),
236
- },
237
- },
253
+ resources,
238
254
  });
239
255
  }
240
256
  /** Rebuild terminal loop stats and its StopDecision as one atomic projection. */
@@ -285,14 +301,14 @@ function isLoopBudgetBaseProfile(value) {
285
301
  return value === 'default' || value === 'complex' || value === 'release';
286
302
  }
287
303
  function resolveLoopBudget(partial) {
288
- const numericOverrides = Object.fromEntries(Object.entries(partial ?? {}).filter(([, value]) => typeof value === 'number' && Number.isFinite(value) && value > 0));
289
- const hasNumericOverrides = Object.keys(numericOverrides).length > 0;
290
- const hasExplicitProfile = partial?.profile !== undefined || partial?.baseProfile !== undefined;
291
- const inferredConfigOverride = hasNumericOverrides && !hasExplicitProfile;
292
- const configOverride = partial?.configOverride === true || inferredConfigOverride;
304
+ const visibleBytes = partial?.maxModelVisibleToolBytes;
305
+ const hasOverride = visibleBytes !== undefined && Number.isSafeInteger(visibleBytes) && visibleBytes > 0;
306
+ const hasProfile = partial?.profile !== undefined || partial?.baseProfile !== undefined;
307
+ const configOverride = partial?.configOverride === true || (hasOverride && !hasProfile);
293
308
  return {
294
- ...loop_budget_contract_1.DEFAULT_LOOP_BUDGET,
295
- ...numericOverrides,
309
+ maxModelVisibleToolBytes: hasOverride
310
+ ? visibleBytes
311
+ : loop_budget_contract_1.DEFAULT_LOOP_BUDGET.maxModelVisibleToolBytes,
296
312
  profile: isLoopBudgetSource(partial?.profile)
297
313
  ? partial.profile
298
314
  : configOverride
@@ -308,30 +324,9 @@ function applyLoopBudgetStats(stats, budget) {
308
324
  stats.loopBudgetSource = budget.profile ?? 'default';
309
325
  stats.loopBudgetBaseProfile =
310
326
  budget.baseProfile ?? (budget.profile === 'config' ? 'default' : (budget.profile ?? 'default'));
311
- stats.loopBudgetMaxLlmRequests = budget.maxLlmRequestsPerUserTurn;
312
- stats.loopBudgetMaxToolCalls = budget.maxToolCallsPerUserTurn;
313
- stats.loopBudgetMaxReadOnlyFragmentation = budget.maxReadOnlyFragmentation;
314
327
  stats.loopBudgetMaxModelVisibleBytes = budget.maxModelVisibleToolBytes;
315
328
  stats.loopBudgetConfigOverride = budget.configOverride === true;
316
329
  }
317
- function shouldPromoteDefaultBudget(stats, budget) {
318
- if (budget.configOverride === true || budget.profile !== 'default')
319
- return false;
320
- if (stats.llmRequests < budget.maxLlmRequestsPerUserTurn)
321
- return false;
322
- return (stats.toolCalls >= 8 || stats.readOnlyToolCalls >= 6 || stats.modelVisibleToolBytes >= 16 * 1024);
323
- }
324
- function promoteDefaultBudgetToComplex(budget) {
325
- return {
326
- ...budget,
327
- maxLlmRequestsPerUserTurn: Math.max(budget.maxLlmRequestsPerUserTurn, COMPLEX_LOOP_BUDGET.maxLlmRequestsPerUserTurn),
328
- maxToolCallsPerUserTurn: Math.max(budget.maxToolCallsPerUserTurn, COMPLEX_LOOP_BUDGET.maxToolCallsPerUserTurn),
329
- maxModelVisibleToolBytes: Math.max(budget.maxModelVisibleToolBytes, COMPLEX_LOOP_BUDGET.maxModelVisibleToolBytes),
330
- profile: 'complex',
331
- baseProfile: 'complex',
332
- configOverride: false,
333
- };
334
- }
335
330
  function getLlmRequestDiagnostics(llm) {
336
331
  const diagnosticsReader = llm.getLastRequestDiagnostics;
337
332
  return typeof diagnosticsReader === 'function' ? diagnosticsReader.call(llm) : undefined;
@@ -355,28 +350,22 @@ function applyLlmRequestDiagnostics(stats, diagnostics) {
355
350
  stats.providerFallbackToModel = diagnostics.fallbackToModel;
356
351
  }
357
352
  }
358
- function budgetExceededEvent(llm, stats, reason) {
359
- const continuationActions = [
360
- 'reply_continue',
361
- 'narrow_instruction',
362
- 'inspect_loop_stats',
363
- 'raise_budget',
364
- ];
365
- const continuationHint = 'Reply `继续` to continue the same objective, give a narrower next step, inspect /usage, or raise agentLoop.budget for intentional long work.';
353
+ function missingAssistantOutputMessage(toolCalls) {
354
+ const recovery = toolCalls
355
+ ? 'Inspect the recorded tool results and ask for a checkpoint before repeating work.'
356
+ : 'Retry the request, select another model, or ask for a brief checkpoint.';
357
+ return `Model returned no visible response. ${recovery}`;
358
+ }
359
+ function budgetExceededEvent(llm, stats, code, reason) {
366
360
  return {
367
361
  type: 'complete',
368
- content: [
369
- `Agent loop budget reached: ${reason}.`,
370
- 'I stopped this turn to avoid unnecessary model requests and preserved the current session state.',
371
- 'To continue the same objective, reply `继续` or provide the next concrete step.',
372
- 'Use /usage to inspect request/tool counts. For intentional long work, raise agentLoop.budget in orion.json.',
373
- ].join('\n'),
362
+ content: reason,
374
363
  model: llm.getModel(),
375
364
  stats: cloneLoopStats({
376
365
  ...stats,
366
+ budgetStopCode: code,
377
367
  budgetExceededReason: reason,
378
- continuationActions,
379
- continuationHint,
368
+ continuationActions: ['inspect_loop_stats'],
380
369
  }, 'budget_exceeded'),
381
370
  };
382
371
  }
@@ -414,9 +403,16 @@ function takeUtf8Suffix(text, maxBytes) {
414
403
  return '';
415
404
  let result = '';
416
405
  let bytes = 0;
417
- const chars = Array.from(text);
418
- for (let index = chars.length - 1; index >= 0; index--) {
419
- const char = chars[index];
406
+ for (let index = text.length; index > 0;) {
407
+ const end = index;
408
+ index--;
409
+ const unit = text.charCodeAt(index);
410
+ if (unit >= 0xdc00 && unit <= 0xdfff && index > 0) {
411
+ const previous = text.charCodeAt(index - 1);
412
+ if (previous >= 0xd800 && previous <= 0xdbff)
413
+ index--;
414
+ }
415
+ const char = text.slice(index, end);
420
416
  const nextBytes = byteLength(char);
421
417
  if (bytes + nextBytes > maxBytes)
422
418
  break;
@@ -425,85 +421,94 @@ function takeUtf8Suffix(text, maxBytes) {
425
421
  }
426
422
  return result;
427
423
  }
428
- function truncateForModel(text, maxBytes) {
429
- if (byteLength(text) <= maxBytes)
424
+ function truncateForModel(text, maxBytes, fullBytes = byteLength(text)) {
425
+ if (fullBytes <= maxBytes)
430
426
  return text;
431
427
  const marker = '\n...[truncated]';
432
428
  if (maxBytes <= 128) {
433
429
  return `${takeUtf8Prefix(text, Math.max(0, maxBytes - byteLength(marker)))}${marker}`;
434
430
  }
435
- const middle = `\n...[truncated ${byteLength(text)}B output for model context]...\n`;
431
+ const middle = `\n...[truncated ${fullBytes}B output for model context]...\n`;
436
432
  const contentBudget = Math.max(0, maxBytes - byteLength(middle));
437
433
  const headBytes = Math.floor(contentBudget * 0.65);
438
434
  const tailBytes = contentBudget - headBytes;
439
435
  return [takeUtf8Prefix(text, headBytes), middle, takeUtf8Suffix(text, tailBytes)].join('');
440
436
  }
441
- function summarizeModelVisibleToolResult(executed, maxBytes) {
437
+ function truncateModelField(text, maxSerializedBytes) {
438
+ const fullBytes = byteLength(text);
439
+ let low = 0;
440
+ let high = Math.min(fullBytes, maxSerializedBytes);
441
+ let result = truncateForModel(text, 0, fullBytes);
442
+ while (low <= high) {
443
+ const middle = Math.floor((low + high) / 2);
444
+ const candidate = truncateForModel(text, middle, fullBytes);
445
+ if (byteLength(JSON.stringify(candidate)) <= maxSerializedBytes) {
446
+ result = candidate;
447
+ low = middle + 1;
448
+ }
449
+ else {
450
+ high = middle - 1;
451
+ }
452
+ }
453
+ return result;
454
+ }
455
+ function summarizeModelVisibleToolResult(executed, maxBytes, budgetRemainingBytes, budgetLimitBytes) {
442
456
  const rawBytes = byteLength(executed.result);
443
457
  const fullOutputBytes = executed.outputBytes ?? rawBytes;
444
- if (rawBytes <= maxBytes && !executed.artifactRef) {
445
- return { result: executed.result, bytes: rawBytes, summarizedBytes: 0 };
446
- }
447
458
  const envelope = (0, tool_serializer_1.parseToolResultEnvelope)(executed.result);
448
459
  const output = typeof envelope.output === 'string' ? envelope.output : executed.result;
449
460
  const summary = executed.summary || envelope.summary;
450
- const compactSummary = summary ? truncateForModel(summary, 192) : undefined;
451
461
  const rawError = executed.error ?? envelope.error;
452
- const compactError = rawError ? truncateForModel(rawError, 192) : undefined;
453
- const artifactText = executed.artifactRef
454
- ? ` Full output is available as artifact ${executed.artifactRef.id} (${executed.artifactRef.outputBytes}B).`
455
- : '';
456
- const serializeCompact = (compactOutput) => (0, tool_serializer_1.serializeToolResult)({
462
+ const budgetMetadata = {
463
+ budgetLimitBytes,
464
+ // This snapshot precedes this result, so its envelope overhead cannot make
465
+ // the diagnostic self-referential. Stats count the full serialized bytes.
466
+ budgetRemainingBytes,
467
+ budgetExhausted: budgetRemainingBytes === 0,
468
+ budgetSnapshot: 'before_result',
469
+ modelVisibleBudgetExceeded: budgetRemainingBytes < maxBytes,
470
+ };
471
+ const fullResult = (0, tool_serializer_1.serializeToolResult)({
472
+ ...envelope,
473
+ success: executed.success,
474
+ metadata: { ...envelope.metadata, ...budgetMetadata },
475
+ });
476
+ if (byteLength(fullResult) <= maxBytes) {
477
+ return { result: fullResult, bytes: byteLength(fullResult), summarizedBytes: 0 };
478
+ }
479
+ // Keep a real excerpt, status and a budget signal even after exhaustion. An
480
+ // untrusted tool's arbitrarily large metadata must not displace the excerpt.
481
+ const compactError = rawError ? truncateModelField(rawError, 192) : undefined;
482
+ const minimalError = rawError ? truncateModelField(rawError, 64) : undefined;
483
+ const compactSummary = summary ? truncateModelField(summary, 192) : undefined;
484
+ const serializeCompact = (compactOutput, includeDetails) => (0, tool_serializer_1.serializeToolResult)({
457
485
  success: executed.success,
458
486
  output: compactOutput,
459
- error: compactError,
460
- summary: compactSummary,
487
+ error: includeDetails ? compactError : minimalError,
488
+ summary: includeDetails ? compactSummary : undefined,
461
489
  outputBytes: fullOutputBytes,
462
- artifactRef: executed.artifactRef ?? envelope.artifactRef,
490
+ artifactRef: includeDetails ? (executed.artifactRef ?? envelope.artifactRef) : undefined,
463
491
  metadata: {
464
- ...(envelope.metadata ?? {}),
465
492
  modelVisibleCompressed: true,
466
493
  originalResultBytes: rawBytes,
494
+ ...budgetMetadata,
467
495
  },
468
496
  });
469
- let outputBudget = Math.max(128, maxBytes - 768);
470
- let compact = '';
471
- for (let attempt = 0; attempt < 6; attempt++) {
472
- compact = serializeCompact([
473
- compactSummary
474
- ? `Summary: ${compactSummary}`
475
- : 'Tool output was summarized for model context.',
476
- artifactText.trim(),
477
- truncateForModel(output, outputBudget),
478
- ]
479
- .filter(Boolean)
480
- .join('\n'));
481
- const compactBytes = byteLength(compact);
482
- if (compactBytes <= maxBytes || outputBudget <= 128)
483
- break;
484
- outputBudget = Math.max(128, outputBudget - Math.max(compactBytes - maxBytes, 128));
485
- }
486
- if (byteLength(compact) > maxBytes) {
487
- compact = serializeCompact([
488
- compactSummary
489
- ? `Summary: ${compactSummary}`
490
- : 'Tool output was summarized for model context.',
491
- artifactText.trim(),
492
- `Output body omitted from model context (${fullOutputBytes}B total).`,
493
- ]
494
- .filter(Boolean)
495
- .join('\n'));
496
- }
497
- if (byteLength(compact) > maxBytes) {
498
- compact = (0, tool_serializer_1.serializeToolResult)({
499
- success: executed.success,
500
- output: `Tool result omitted from model context (${fullOutputBytes}B total).`,
501
- outputBytes: fullOutputBytes,
502
- metadata: {
503
- modelVisibleCompressed: true,
504
- originalResultBytes: rawBytes,
505
- },
506
- });
497
+ const includeDetails = byteLength(serializeCompact(truncateForModel(output, 128), true)) <= maxBytes;
498
+ const outputBytes = byteLength(output);
499
+ let low = 0;
500
+ let high = Math.min(outputBytes, maxBytes);
501
+ let compact = serializeCompact(truncateForModel(output, 0, outputBytes), includeDetails);
502
+ while (low <= high) {
503
+ const middle = Math.floor((low + high) / 2);
504
+ const candidate = serializeCompact(truncateForModel(output, middle, outputBytes), includeDetails);
505
+ if (byteLength(candidate) <= maxBytes) {
506
+ compact = candidate;
507
+ low = middle + 1;
508
+ }
509
+ else {
510
+ high = middle - 1;
511
+ }
507
512
  }
508
513
  const bytes = byteLength(compact);
509
514
  return {
@@ -512,25 +517,6 @@ function summarizeModelVisibleToolResult(executed, maxBytes) {
512
517
  summarizedBytes: Math.max(0, fullOutputBytes - bytes),
513
518
  };
514
519
  }
515
- function omitModelVisibleToolResult(executed, maxAggregateBytes) {
516
- const fullBytes = executed.outputBytes ?? byteLength(executed.result);
517
- const compact = (0, tool_serializer_1.serializeToolResult)({
518
- success: executed.success,
519
- output: `Tool result omitted from model context because the per-turn model-visible tool budget (${maxAggregateBytes}B) was reached.`,
520
- outputBytes: fullBytes,
521
- artifactRef: executed.artifactRef,
522
- metadata: {
523
- modelVisibleCompressed: true,
524
- modelVisibleBudgetExceeded: true,
525
- },
526
- });
527
- const bytes = byteLength(compact);
528
- return {
529
- result: compact,
530
- bytes,
531
- summarizedBytes: Math.max(0, fullBytes - bytes),
532
- };
533
- }
534
520
  function queryCompactCommit(mode, result, before, after, uncompactedHistory, prepareSource, semanticHarnessState) {
535
521
  return {
536
522
  mode,
@@ -578,6 +564,7 @@ function publishContextUsage(params, autoCompact, modelId, usedTokens, source =
578
564
  usedTokens,
579
565
  source,
580
566
  outputReserveTokens: stats.outputReserveTokens,
567
+ contextWindow: params.llm.getContextWindow?.(),
581
568
  warningThreshold: stats.preCompactThreshold,
582
569
  autoCompactThreshold: stats.threshold,
583
570
  autoCompactEnabled: stats.enabled,
@@ -668,19 +655,28 @@ function compactPausedEvent(llm, stats, failure, content) {
668
655
  * }
669
656
  */
670
657
  async function* query(params) {
671
- const { messages, tools: initialTools, toolExecutor: initialToolExecutor, llm, abortSignal, streamCallbacks, costTracker, strategyTracker = (0, strategy_tracker_1.createStrategyTracker)({ maxAttempts: 5 }), // 增加到 5 次
672
- harness, input, maxParallelToolCalls = 6, } = params;
658
+ const { messages, tools: initialTools, toolExecutor: initialToolExecutor, llm, abortSignal: userSignal, goalDeadlineAt, streamCallbacks, costTracker, strategyTracker, harness, maxParallelToolCalls = 6, } = params;
659
+ const remainingTime = goalDeadlineAt === undefined ? undefined : Math.max(0, goalDeadlineAt - Date.now());
660
+ // The provider and tools retain their own per-operation timeouts for distant deadlines.
661
+ const goalTimeSignal = remainingTime !== undefined && remainingTime <= 2147483647
662
+ ? AbortSignal.timeout(Math.ceil(remainingTime))
663
+ : undefined;
664
+ const abortSignal = userSignal && goalTimeSignal
665
+ ? AbortSignal.any([userSignal, goalTimeSignal])
666
+ : (userSignal ?? goalTimeSignal);
667
+ const interrupted = () => isAborted(abortSignal) || (goalDeadlineAt !== undefined && Date.now() >= goalDeadlineAt);
668
+ let input = params.input;
673
669
  let turn = 0;
674
- let consecutiveCompletionGateBlocks = 0;
670
+ const rejectedCompletionStates = new Set();
671
+ let successfulToolCalls = 0;
675
672
  const stats = createLoopStats();
676
673
  let pendingCompact;
677
674
  const uncompactedMessages = messages.map(message => ({ ...message }));
678
675
  const appendMessage = (message) => {
679
676
  messages.push(message);
680
- uncompactedMessages.push({ ...message });
681
- if (pendingCompact) {
682
- pendingCompact.uncompactedHistory = uncompactedMessages.map(entry => ({ ...entry }));
683
- }
677
+ const snapshot = { ...message };
678
+ uncompactedMessages.push(snapshot);
679
+ pendingCompact?.uncompactedHistory.push(snapshot);
684
680
  };
685
681
  let compactPrepareSource;
686
682
  const captureCompactPrepareSource = () => {
@@ -697,36 +693,64 @@ async function* query(params) {
697
693
  return compactPrepareSource;
698
694
  };
699
695
  let aggregateUsage;
700
- // Preserve the old option as a resource-budget alias. It no longer emits a
701
- // task-like `max_turns` completion or claims that the objective completed.
702
- const legacyRequestBudget = typeof params.maxTurns === 'number' && Number.isFinite(params.maxTurns) && params.maxTurns > 0
703
- ? Math.floor(params.maxTurns)
704
- : undefined;
705
- let loopBudget = resolveLoopBudget({
706
- ...params.loopBudget,
707
- ...(params.loopBudget?.maxLlmRequestsPerUserTurn === undefined && legacyRequestBudget
708
- ? { maxLlmRequestsPerUserTurn: legacyRequestBudget }
709
- : {}),
710
- });
696
+ const loopBudget = resolveLoopBudget(params.loopBudget);
711
697
  applyLoopBudgetStats(stats, loopBudget);
698
+ const progress = new loop_progress_1.LoopProgress(params.toolContext?.cwd ?? process.cwd());
699
+ function interruptedCompleteEvent() {
700
+ return attachCompactCommit(isAborted(userSignal)
701
+ ? cancelledCompleteEvent(llm, stats)
702
+ : budgetExceededEvent(llm, stats, 'goal_time_budget', 'Goal elapsed time allowance reached.'), pendingCompact, messages, aggregateUsage);
703
+ }
704
+ function appendSteering(steering) {
705
+ for (const text of steering)
706
+ appendMessage({ role: 'user', content: text });
707
+ if (steering.length > 0)
708
+ input = steering[steering.length - 1];
709
+ }
712
710
  const maxModelVisibleToolResultBytes = Math.max(512, params.maxModelVisibleToolResultBytes ?? exports.DEFAULT_MAX_MODEL_VISIBLE_TOOL_RESULT_BYTES);
713
- const fragmentedReadOnlyTools = new Set(BATCH_READ_ALLOWED_TOOLS);
714
- // 无限循环,依赖安全机制停止
711
+ function goalTokenBudgetStop() {
712
+ if (params.remainingGoalTokens === undefined)
713
+ return undefined;
714
+ const usage = aggregateUsage ?? { promptTokens: 0, completionTokens: 0 };
715
+ const used = usage.promptTokens + usage.completionTokens;
716
+ if (used < params.remainingGoalTokens)
717
+ return undefined;
718
+ return attachCompactCommit(budgetExceededEvent(llm, stats, 'goal_token_budget', 'Goal token allowance reached.'), pendingCompact, messages, usage);
719
+ }
715
720
  while (true) {
716
721
  turn++;
717
722
  // Check abort
718
- if (isAborted(abortSignal)) {
719
- yield attachCompactCommit(cancelledCompleteEvent(llm, stats), pendingCompact, messages, aggregateUsage);
723
+ if (interrupted()) {
724
+ yield interruptedCompleteEvent();
720
725
  return;
721
726
  }
722
- if (shouldPromoteDefaultBudget(stats, loopBudget)) {
723
- loopBudget = promoteDefaultBudgetToComplex(loopBudget);
724
- applyLoopBudgetStats(stats, loopBudget);
727
+ const goalBudgetBeforeRequest = goalTokenBudgetStop();
728
+ if (goalBudgetBeforeRequest) {
729
+ yield goalBudgetBeforeRequest;
730
+ return;
725
731
  }
726
- if (stats.llmRequests >= loopBudget.maxLlmRequestsPerUserTurn) {
727
- yield attachCompactCommit(budgetExceededEvent(llm, stats, `LLM request budget ${loopBudget.maxLlmRequestsPerUserTurn} reached`), pendingCompact, messages, aggregateUsage);
732
+ appendSteering(params.takePendingSteering?.() ?? []);
733
+ const planStop = params.checkTaskPlanStop?.();
734
+ if (planStop) {
735
+ const finish = cloneLoopStats(stats, planStop.code === 'task_step_blocked' ? 'blocked' : 'completion_gate');
736
+ const decision = finish.stopDecision;
737
+ finish.stopDecision = {
738
+ ...decision,
739
+ status: planStop.code === 'task_step_blocked' ? 'blocked' : 'stopped',
740
+ reason: { code: planStop.code, message: planStop.message },
741
+ nextActions: [
742
+ { kind: 'inspect', label: 'Inspect the current checklist', command: '/harness explain' },
743
+ { kind: 'continue', label: 'Continue the current task', command: '继续' },
744
+ ],
745
+ };
746
+ yield attachCompactCommit({ type: 'complete', content: planStop.message, model: llm.getModel(), stats: finish }, pendingCompact, messages, aggregateUsage);
728
747
  return;
729
748
  }
749
+ const toolOutputPressure = params.allowToolPressureCompaction === true &&
750
+ successfulToolCalls > 0 &&
751
+ stats.modelVisibleToolBytes >=
752
+ Math.ceil(loopBudget.maxModelVisibleToolBytes * TOOL_PRESSURE_COMPACT_RATIO);
753
+ const shouldTryBudgetCompact = toolOutputPressure && !pendingCompact && stats.budgetCompaction === undefined;
730
754
  const resolvedStep = params.resolveStep
731
755
  ? await params.resolveStep({
732
756
  requestIndex: turn - 1,
@@ -741,8 +765,8 @@ async function* query(params) {
741
765
  harness?.updateCapabilityProfile?.({
742
766
  modelId: llm.getModel(),
743
767
  contextWindow: (0, model_context_1.getModelContextWindow)(llm.getModel()),
744
- permissionMode: params.permissionMode ?? 'default',
745
- toolConfirmation: params.toolConfirmation ?? 'allow',
768
+ permissionMode: 'default',
769
+ toolConfirmation: 'allow',
746
770
  tools: tools.map(tool => tool.name),
747
771
  });
748
772
  // Request start
@@ -766,32 +790,56 @@ async function* query(params) {
766
790
  });
767
791
  // Stream the LLM response. Harness context is injected into a cloned
768
792
  // request payload so the durable conversation history stays clean.
769
- let requestMessages = harness
770
- ? harness.assembleMessages(messages, {
771
- input,
772
- tools: tools.map(tool => ({ name: tool.name, description: tool.description })),
773
- })
774
- : messages;
775
- let requestEstimatedTokens = (0, token_estimate_1.estimateMessagesTokens)(requestMessages);
776
- const predictedTokens = autoCompact.adjustTokenEstimate(requestEstimatedTokens, llm.getModel());
777
- const contextBeforePredictiveCompact = publishContextUsage(params, autoCompact, llm.getModel(), predictedTokens, autoCompact.hasProviderCalibration(llm.getModel()) ? 'provider_adjusted' : 'estimated');
778
- const preCompactObjective = harness?.getCapsule()?.contract?.objective;
779
793
  const compactToolDescriptions = tools.map(tool => ({
780
794
  name: tool.name,
781
795
  description: tool.description,
782
796
  }));
797
+ const assembleRequest = () => harness?.assembleMessages(messages, { input, tools: compactToolDescriptions }) ?? messages;
798
+ let requestMessages = assembleRequest();
799
+ let requestEstimatedTokens = (0, token_estimate_1.estimateMessagesTokens)(requestMessages);
800
+ const predictedTokens = autoCompact.adjustTokenEstimate(requestEstimatedTokens, llm.getModel());
801
+ const contextBeforePredictiveCompact = publishContextUsage(params, autoCompact, llm.getModel(), predictedTokens, autoCompact.hasProviderCalibration(llm.getModel()) ? 'provider_adjusted' : 'estimated');
802
+ const preCompactObjective = harness?.getCapsule()?.contract?.objective;
783
803
  const predictiveStats = autoCompact.getStats();
784
- if (predictiveStats.enabled &&
804
+ const predictiveCompactDue = predictiveStats.enabled &&
785
805
  predictedTokens / Math.max(1, predictiveStats.safeInputBudget) >=
786
- predictiveStats.predictiveCompactThreshold) {
806
+ predictiveStats.predictiveCompactThreshold;
807
+ const budgetCompactDue = shouldTryBudgetCompact && predictiveStats.enabled && !predictiveCompactDue;
808
+ if (predictiveCompactDue || budgetCompactDue)
787
809
  captureCompactPrepareSource();
810
+ if (shouldTryBudgetCompact && !predictiveStats.enabled)
811
+ stats.budgetCompaction = 'disabled';
812
+ let candidatePromptAssembled = false;
813
+ const validatePreCompact = (result) => {
814
+ candidatePromptAssembled = true;
815
+ return validateFinalCompactRequest(result, autoCompact, llm.getModel(), harness, compactToolDescriptions, input);
816
+ };
817
+ const preCompactAttempt = budgetCompactDue
818
+ ? await autoCompact.compactForToolPressure(messages, predictedTokens, validatePreCompact, abortSignal)
819
+ : await autoCompact.checkPredictiveCompactOutcome(messages, predictedTokens, validatePreCompact, abortSignal);
820
+ if (budgetCompactDue) {
821
+ stats.budgetCompaction =
822
+ preCompactAttempt.status === 'compacted' ? 'compacted' : 'unavailable';
823
+ if (stats.budgetCompaction === 'unavailable') {
824
+ compactPrepareSource = undefined;
825
+ // The speculative validator may have written diagnostics for a prompt
826
+ // the provider will never receive. Restore the original assembly.
827
+ if (candidatePromptAssembled && harness) {
828
+ requestMessages = assembleRequest();
829
+ requestEstimatedTokens = (0, token_estimate_1.estimateMessagesTokens)(requestMessages);
830
+ }
831
+ }
832
+ }
833
+ if (interrupted()) {
834
+ yield interruptedCompleteEvent();
835
+ return;
788
836
  }
789
- const preCompactAttempt = await autoCompact.checkPredictiveCompactOutcome(messages, predictedTokens, result => validateFinalCompactRequest(result, autoCompact, llm.getModel(), harness, compactToolDescriptions, input));
790
- if (preCompactAttempt.status === 'paused') {
837
+ if (!budgetCompactDue && preCompactAttempt.status === 'paused') {
791
838
  yield attachCompactCommit(compactPausedEvent(llm, stats, preCompactAttempt.failure), pendingCompact, messages, aggregateUsage);
792
839
  return;
793
840
  }
794
- if (preCompactAttempt.status === 'duplicate' || preCompactAttempt.status === 'rejected') {
841
+ if (!budgetCompactDue &&
842
+ (preCompactAttempt.status === 'duplicate' || preCompactAttempt.status === 'rejected')) {
795
843
  yield attachCompactCommit(compactPausedEvent(llm, stats, failureForUnchangedCompactAttempt(preCompactAttempt, autoCompact)), pendingCompact, messages, aggregateUsage);
796
844
  return;
797
845
  }
@@ -800,12 +848,7 @@ async function* query(params) {
800
848
  stats.compactTrigger = 'pre_turn';
801
849
  messages.length = 0;
802
850
  messages.push(...preCompacted);
803
- requestMessages = harness
804
- ? harness.assembleMessages(messages, {
805
- input,
806
- tools: tools.map(tool => ({ name: tool.name, description: tool.description })),
807
- })
808
- : messages;
851
+ requestMessages = assembleRequest();
809
852
  const postCompactObjective = harness?.getCapsule()?.contract?.objective;
810
853
  if (preCompactObjective &&
811
854
  postCompactObjective &&
@@ -861,8 +904,8 @@ async function* query(params) {
861
904
  return;
862
905
  }
863
906
  }
864
- if (isAborted(abortSignal)) {
865
- yield attachCompactCommit(cancelledCompleteEvent(llm, stats), pendingCompact, messages, aggregateUsage);
907
+ if (interrupted()) {
908
+ yield interruptedCompleteEvent();
866
909
  return;
867
910
  }
868
911
  if (resolvedStep.bindModelRequest) {
@@ -875,11 +918,18 @@ async function* query(params) {
875
918
  toolExecutor = bound.toolExecutor;
876
919
  }
877
920
  let response;
921
+ let sawReasoning = false;
922
+ const holdAssistant = params.holdAssistantUntilCompletionCheck?.() === true;
878
923
  try {
879
924
  stats.llmRequests++;
880
- response = await llm.chatStream(requestMessages, streamCallbacks, openaiTools, {
881
- abortSignal,
882
- });
925
+ response = await llm.chatStream(requestMessages, {
926
+ ...streamCallbacks,
927
+ ...(holdAssistant ? { onChunk: undefined } : {}),
928
+ onThinkingText: text => {
929
+ sawReasoning || (sawReasoning = text.trim().length > 0);
930
+ streamCallbacks?.onThinkingText?.(text);
931
+ },
932
+ }, openaiTools, { abortSignal });
883
933
  applyLlmRequestDiagnostics(stats, getLlmRequestDiagnostics(llm));
884
934
  if (response.usage) {
885
935
  autoCompact.recordProviderUsage(requestEstimatedTokens, response.usage.promptTokens, response.model || llm.getModel());
@@ -887,9 +937,29 @@ async function* query(params) {
887
937
  }
888
938
  catch (error) {
889
939
  applyLlmRequestDiagnostics(stats, getLlmRequestDiagnostics(llm));
940
+ if (interrupted()) {
941
+ yield interruptedCompleteEvent();
942
+ return;
943
+ }
890
944
  if (error instanceof llm_1.ProviderRequestPreflightError) {
891
945
  stats.llmRequests = Math.max(0, stats.llmRequests - 1);
892
- yield attachCompactCommit(budgetExceededEvent(llm, stats, error.message), pendingCompact, messages, aggregateUsage);
946
+ yield attachCompactCommit(budgetExceededEvent(llm, stats, 'provider_preflight_budget', error.message), pendingCompact, messages, aggregateUsage);
947
+ return;
948
+ }
949
+ if (error instanceof provider_diagnostics_1.LLMProviderError) {
950
+ stats.providerStop = {
951
+ code: `provider_${error.diagnostic.type}`,
952
+ message: (0, provider_diagnostics_1.formatProviderErrorMessage)({
953
+ ...error.diagnostic,
954
+ code: undefined,
955
+ }),
956
+ };
957
+ yield attachCompactCommit({
958
+ type: 'complete',
959
+ content: stats.providerStop.message,
960
+ model: llm.getModel(),
961
+ stats: cloneLoopStats(stats, 'failed'),
962
+ }, pendingCompact, messages, aggregateUsage);
893
963
  return;
894
964
  }
895
965
  throw new QueryLoopError(error, cloneLoopStats(stats, 'failed'), aggregateUsage);
@@ -908,36 +978,69 @@ async function* query(params) {
908
978
  completionTokens: (aggregateUsage?.completionTokens ?? 0) + response.usage.completionTokens,
909
979
  };
910
980
  }
911
- if (isAborted(abortSignal)) {
912
- yield attachCompactCommit(cancelledCompleteEvent(llm, stats), pendingCompact, messages, aggregateUsage);
981
+ if (interrupted()) {
982
+ yield interruptedCompleteEvent();
983
+ return;
984
+ }
985
+ const visibleContent = (0, terminal_text_1.hasVisibleAssistantText)(response.content) ? response.content : '';
986
+ if (response.finishReason === 'length' || response.finishReason === 'content_filter') {
987
+ if (visibleContent) {
988
+ appendMessage({ role: 'assistant', content: visibleContent });
989
+ if (holdAssistant)
990
+ streamCallbacks?.onChunk?.(visibleContent);
991
+ yield { type: 'message', role: 'assistant', content: visibleContent };
992
+ }
993
+ stats.providerStop =
994
+ response.finishReason === 'length'
995
+ ? {
996
+ code: 'provider_output_limit',
997
+ message: 'The provider reached its output token limit. Continue with a narrower request.',
998
+ }
999
+ : {
1000
+ code: 'provider_content_filter',
1001
+ message: 'The provider stopped generation at its content filter.',
1002
+ };
1003
+ yield attachCompactCommit({
1004
+ type: 'complete',
1005
+ content: stats.providerStop.message,
1006
+ model: response.model || llm.getModel(),
1007
+ stats: cloneLoopStats(stats, 'failed'),
1008
+ }, pendingCompact, messages, aggregateUsage);
1009
+ return;
1010
+ }
1011
+ const goalBudgetAfterRequest = goalTokenBudgetStop();
1012
+ if (goalBudgetAfterRequest) {
1013
+ // The crossing response is billable, but its proposed tools were never admitted.
1014
+ yield goalBudgetAfterRequest;
913
1015
  return;
914
1016
  }
915
1017
  // Handle tool calls
916
1018
  if (response.toolCalls && response.toolCalls.length > 0) {
917
1019
  const toolCalls = response.toolCalls;
918
- if (stats.toolCalls + toolCalls.length > loopBudget.maxToolCallsPerUserTurn) {
919
- yield attachCompactCommit(budgetExceededEvent(llm, stats, `tool call budget ${loopBudget.maxToolCallsPerUserTurn} would be exceeded by ${toolCalls.length} requested tools`), pendingCompact, messages, aggregateUsage);
920
- return;
921
- }
922
- // Save assistant tool-call message only after budget checks, so future
923
- // requests never inherit unresolved tool calls if this turn is stopped.
1020
+ // Pair every authorized call with its result before sampling again.
924
1021
  const assistantMsg = {
925
1022
  role: 'assistant',
926
- content: response.content,
1023
+ content: visibleContent,
927
1024
  tool_calls: toolCalls,
928
1025
  };
929
1026
  appendMessage(assistantMsg);
930
- harness?.recordAssistantResponse(response);
1027
+ harness?.recordAssistantResponse({ ...response, content: visibleContent });
1028
+ if (holdAssistant && visibleContent)
1029
+ streamCallbacks?.onChunk?.(visibleContent);
931
1030
  yield {
932
1031
  type: 'assistant_tool_calls',
933
- content: response.content,
1032
+ content: visibleContent,
934
1033
  toolCalls,
935
1034
  };
936
1035
  const preparedCalls = (0, tool_call_orchestrator_1.prepareToolCalls)({
937
1036
  toolCalls,
938
1037
  tools,
939
- startApproach: (toolName) => strategyTracker.startApproach(toolName),
940
- addToolToTracker: (attemptId, toolName) => strategyTracker.addTool(attemptId, toolName),
1038
+ ...(strategyTracker
1039
+ ? {
1040
+ startApproach: (toolName) => strategyTracker.startApproach(toolName),
1041
+ addToolToTracker: (attemptId, toolName) => strategyTracker.addTool(attemptId, toolName),
1042
+ }
1043
+ : {}),
941
1044
  harnessDriftCheck: harness
942
1045
  ? ({ name, args }) => harness.beforeToolUse({ name, args })
943
1046
  : undefined,
@@ -951,13 +1054,6 @@ async function* query(params) {
951
1054
  stats.unsafeToolCalls++;
952
1055
  }
953
1056
  }
954
- const singleFragmentedReadOnlyCall = preparedCalls.length === 1 &&
955
- preparedCalls[0].tool?.isReadOnly?.(preparedCalls[0].args) === true &&
956
- fragmentedReadOnlyTools.has(preparedCalls[0].tc.function.name);
957
- stats.singleReadOnlyStreak = singleFragmentedReadOnlyCall
958
- ? stats.singleReadOnlyStreak + 1
959
- : 0;
960
- let pendingStrategySuggestion;
961
1057
  const answeredToolCallIds = new Set();
962
1058
  const preparedCallById = new Map(preparedCalls.map(call => [call.tc.id, call]));
963
1059
  for (const prepared of preparedCalls) {
@@ -976,16 +1072,15 @@ async function* query(params) {
976
1072
  harnessBlockedResult: harness ? drift => harness.asToolBlockedResult(drift) : undefined,
977
1073
  maxParallelToolCalls,
978
1074
  })) {
979
- if (isAborted(abortSignal)) {
980
- yield attachCompactCommit(cancelledCompleteEvent(llm, stats), pendingCompact, messages, aggregateUsage);
1075
+ if (interrupted()) {
1076
+ yield interruptedCompleteEvent();
981
1077
  return;
982
1078
  }
983
1079
  const { prepared } = executed;
984
1080
  const { tc, args, attemptId } = prepared;
985
- const remainingModelVisibleBytes = loopBudget.maxModelVisibleToolBytes - stats.modelVisibleToolBytes;
986
- const modelVisible = remainingModelVisibleBytes < 512
987
- ? omitModelVisibleToolResult(executed, loopBudget.maxModelVisibleToolBytes)
988
- : summarizeModelVisibleToolResult(executed, Math.min(maxModelVisibleToolResultBytes, remainingModelVisibleBytes));
1081
+ const remainingModelVisibleBytes = Math.max(0, loopBudget.maxModelVisibleToolBytes - stats.modelVisibleToolBytes);
1082
+ const visibilityFloor = Math.min(exports.MIN_MODEL_VISIBLE_TOOL_RESULT_BYTES, maxModelVisibleToolResultBytes);
1083
+ const modelVisible = summarizeModelVisibleToolResult(executed, Math.max(visibilityFloor, Math.min(maxModelVisibleToolResultBytes, remainingModelVisibleBytes)), remainingModelVisibleBytes, loopBudget.maxModelVisibleToolBytes);
989
1084
  stats.toolResultBytes += executed.outputBytes ?? byteLength(executed.result);
990
1085
  stats.modelVisibleToolBytes += modelVisible.bytes;
991
1086
  stats.summarizedBytes += modelVisible.summarizedBytes;
@@ -995,7 +1090,9 @@ async function* query(params) {
995
1090
  .trim()
996
1091
  .slice(0, 240);
997
1092
  stats.lastToolSuccess = executed.success;
998
- strategyTracker.recordResult(attemptId, executed.strategyResult, executed.strategyError, executed.duration);
1093
+ if (executed.success)
1094
+ successfulToolCalls++;
1095
+ strategyTracker?.recordResult(attemptId, executed.strategyResult, executed.strategyError, executed.duration);
999
1096
  harness?.recordToolResult({
1000
1097
  name: tc.function.name,
1001
1098
  args,
@@ -1004,10 +1101,30 @@ async function* query(params) {
1004
1101
  success: executed.success,
1005
1102
  error: executed.error,
1006
1103
  summary: executed.summary,
1104
+ verification: executed.verification,
1105
+ toolReceiptDigest: executed.toolReceiptDigest,
1106
+ changedFile: executed.changedFile,
1107
+ readOnly: prepared.tool?.isReadOnly?.(args) === true,
1007
1108
  });
1008
- if (harness && tc.function.name === 'batch_read') {
1109
+ if (prepared.tool &&
1110
+ executed.resultTrust === 'structured' &&
1111
+ executed.success &&
1112
+ tc.function.name !== 'batch_read' &&
1113
+ (!executed.toolReceiptDigest || !prepared.tool.isFileEdit?.(args) || executed.changedFile)) {
1114
+ progress.observe({
1115
+ name: tc.function.name,
1116
+ args,
1117
+ output: (0, tool_serializer_1.parseToolResultEnvelope)(executed.result).output ?? '',
1118
+ fileEdit: prepared.tool.isFileEdit?.(args) === true,
1119
+ assertion: executed.externalAssertion,
1120
+ });
1121
+ }
1122
+ if (tc.function.name === 'batch_read' && prepared.tool) {
1009
1123
  for (const step of parseBatchReadEvidenceSteps(executed.result)) {
1010
- harness.recordToolResult({
1124
+ if (step.success) {
1125
+ progress.observe({ name: step.tool, args: step.args, output: step.output });
1126
+ }
1127
+ harness?.recordToolResult({
1011
1128
  name: step.tool,
1012
1129
  args: step.args,
1013
1130
  result: JSON.stringify({
@@ -1023,6 +1140,7 @@ async function* query(params) {
1023
1140
  });
1024
1141
  }
1025
1142
  }
1143
+ stats.toolProgressObservations = progress.observations;
1026
1144
  if (executed.permissionDecision) {
1027
1145
  yield {
1028
1146
  type: 'permission_decision',
@@ -1065,7 +1183,7 @@ async function* query(params) {
1065
1183
  const skippedError = `Skipped after permission denial for ${tc.function.name}.`;
1066
1184
  const skippedResult = JSON.stringify({ success: false, error: skippedError });
1067
1185
  const skippedBytes = byteLength(skippedResult);
1068
- strategyTracker.recordResult(skippedPrepared.attemptId, 'failed', skippedError, 0);
1186
+ strategyTracker?.recordResult(skippedPrepared.attemptId, 'failed', skippedError, 0);
1069
1187
  harness?.recordToolResult({
1070
1188
  name: skipped.function.name,
1071
1189
  args: skippedPrepared.args,
@@ -1105,50 +1223,77 @@ async function* query(params) {
1105
1223
  yield attachCompactCommit(permissionBlockedEvent(llm, stats, tc.function.name, executed.error, executed.permissionDecision.source), pendingCompact, messages, aggregateUsage);
1106
1224
  return;
1107
1225
  }
1108
- if (!pendingStrategySuggestion && strategyTracker.isExhausted()) {
1109
- pendingStrategySuggestion = strategyTracker.suggestAlternative() ?? undefined;
1110
- }
1111
- }
1112
- if (pendingStrategySuggestion) {
1113
- yield { type: 'strategy_exhausted', suggestion: pendingStrategySuggestion };
1114
- appendMessage({
1115
- role: 'user',
1116
- content: pendingStrategySuggestion,
1117
- });
1118
- strategyTracker.reset();
1119
- }
1120
- if (stats.singleReadOnlyStreak >= loopBudget.maxReadOnlyFragmentation) {
1121
- appendMessage({
1122
- role: 'system',
1123
- content: [
1124
- '[Orion Code loop hint]',
1125
- `You have made ${stats.singleReadOnlyStreak} consecutive turns with a single read-only local tool call.`,
1126
- 'For independent local exploration, prefer batch_read with up to 8 steps using git_status, list_files, glob, grep, and read_file.',
1127
- ].join(' '),
1128
- });
1129
- stats.batchReadSuggestionCount++;
1130
- stats.singleReadOnlyStreak = 0;
1131
1226
  }
1132
1227
  // Continue to next turn
1133
1228
  continue;
1134
1229
  }
1230
+ if (response.finishReason === 'tool_calls') {
1231
+ stats.providerStop = {
1232
+ code: 'provider_missing_tool_calls',
1233
+ message: 'The provider requested tool use without returning a tool call.',
1234
+ };
1235
+ yield attachCompactCommit({
1236
+ type: 'complete',
1237
+ content: stats.providerStop.message,
1238
+ model: response.model || llm.getModel(),
1239
+ stats: cloneLoopStats(stats, 'failed'),
1240
+ }, pendingCompact, messages, aggregateUsage);
1241
+ return;
1242
+ }
1243
+ const queuedSteering = params.takePendingSteering?.() ?? [];
1244
+ if (response.endTurn === false || queuedSteering.length > 0) {
1245
+ if (visibleContent) {
1246
+ appendMessage({ role: 'assistant', content: visibleContent });
1247
+ harness?.recordAssistantResponse({ ...response, content: visibleContent });
1248
+ if (holdAssistant)
1249
+ streamCallbacks?.onChunk?.(visibleContent);
1250
+ yield { type: 'message', role: 'assistant', content: visibleContent };
1251
+ }
1252
+ appendSteering(queuedSteering);
1253
+ continue;
1254
+ }
1255
+ // A clean provider stop may consist entirely of reasoning or invisible text.
1256
+ // Do not persist it or hand it to the completion gate as a final answer.
1257
+ if (!visibleContent) {
1258
+ stats.missingAssistantOutput =
1259
+ response.content.length === 0 && !sawReasoning ? 'empty_output' : 'no_visible_output';
1260
+ yield attachCompactCommit({
1261
+ type: 'complete',
1262
+ content: missingAssistantOutputMessage(stats.toolCalls),
1263
+ model: response.model || llm.getModel(),
1264
+ stats: cloneLoopStats(stats, 'failed'),
1265
+ }, pendingCompact, messages, aggregateUsage);
1266
+ return;
1267
+ }
1135
1268
  const assistantMsg = {
1136
1269
  role: 'assistant',
1137
1270
  content: response.content,
1138
1271
  };
1139
- appendMessage(assistantMsg);
1140
- harness?.recordAssistantResponse(response);
1272
+ if (!holdAssistant) {
1273
+ appendMessage(assistantMsg);
1274
+ harness?.recordAssistantResponse(response);
1275
+ }
1141
1276
  // No tool calls — done, unless the harness requires one more pass.
1142
1277
  const completionGate = harness?.beforeComplete();
1143
1278
  if (completionGate && !completionGate.canComplete) {
1144
- consecutiveCompletionGateBlocks++;
1145
- if (consecutiveCompletionGateBlocks >= 2) {
1279
+ const rejectedState = JSON.stringify([
1280
+ completionGate.missing,
1281
+ completionGate.stopDecision?.criterionStates,
1282
+ completionGate.stopDecision?.evidenceRefs,
1283
+ ]);
1284
+ if (rejectedCompletionStates.has(rejectedState)) {
1146
1285
  const missing = completionGate.missing?.length
1147
1286
  ? completionGate.missing.join('; ')
1148
1287
  : 'required verification evidence is missing';
1149
1288
  const stoppedStats = cloneLoopStats(stats, 'completion_gate');
1150
1289
  if (completionGate.stopDecision) {
1151
- stoppedStats.stopDecision = completionGate.stopDecision;
1290
+ stoppedStats.stopDecision = {
1291
+ ...completionGate.stopDecision,
1292
+ resources: {
1293
+ ...stoppedStats.stopDecision?.resources,
1294
+ ...completionGate.stopDecision.resources,
1295
+ },
1296
+ };
1152
1297
  }
1153
1298
  yield attachCompactCommit({
1154
1299
  type: 'complete',
@@ -1158,11 +1303,16 @@ async function* query(params) {
1158
1303
  }, pendingCompact, messages, aggregateUsage);
1159
1304
  return;
1160
1305
  }
1306
+ rejectedCompletionStates.add(rejectedState);
1161
1307
  appendMessage(harness.asCompletionBlockedMessage(completionGate));
1162
1308
  stats.finishReason = 'completion_gate';
1163
1309
  continue;
1164
1310
  }
1165
- consecutiveCompletionGateBlocks = 0;
1311
+ if (holdAssistant) {
1312
+ appendMessage(assistantMsg);
1313
+ harness?.recordAssistantResponse(response);
1314
+ streamCallbacks?.onChunk?.(response.content);
1315
+ }
1166
1316
  yield { type: 'message', role: 'assistant', content: response.content };
1167
1317
  // Keep the next request safe by compacting the current durable history at
1168
1318
  // 95%. This uses current-message context, not cumulative session tokens.
@@ -1185,8 +1335,12 @@ async function* query(params) {
1185
1335
  captureCompactPrepareSource();
1186
1336
  }
1187
1337
  const postCompactAttempt = pendingCompact
1188
- ? await autoCompact.ensureHeadroomAndCompactOutcome(messages, currentContextTokens, validatePostCompact)
1189
- : await autoCompact.checkAndCompactOutcome(messages, currentContextTokens, validatePostCompact);
1338
+ ? await autoCompact.ensureHeadroomAndCompactOutcome(messages, currentContextTokens, validatePostCompact, abortSignal)
1339
+ : await autoCompact.checkAndCompactOutcome(messages, currentContextTokens, validatePostCompact, abortSignal);
1340
+ if (interrupted()) {
1341
+ yield interruptedCompleteEvent();
1342
+ return;
1343
+ }
1190
1344
  if (postCompactAttempt.status === 'paused') {
1191
1345
  yield attachCompactCommit(compactPausedEvent(llm, stats, postCompactAttempt.failure, response.content), pendingCompact, messages, aggregateUsage);
1192
1346
  return;
@@ -1219,6 +1373,11 @@ async function* query(params) {
1219
1373
  after: contextBeforeThresholdCompact,
1220
1374
  };
1221
1375
  }
1376
+ const finalSteering = params.takePendingSteering?.(true) ?? [];
1377
+ if (finalSteering.length > 0) {
1378
+ appendSteering(finalSteering);
1379
+ continue;
1380
+ }
1222
1381
  yield {
1223
1382
  type: 'complete',
1224
1383
  content: response.content,