mixdog 0.9.152 → 0.9.154

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 (300) hide show
  1. package/LICENSES/browser-import-NOTICE.txt +11 -0
  2. package/NOTICE.md +11 -0
  3. package/README.md +8 -10
  4. package/package.json +19 -3
  5. package/scripts/computer-task-cost-report.mjs +144 -0
  6. package/scripts/run-office-live-tests.mjs +32 -0
  7. package/src/agents/front-worker/AGENT.md +13 -0
  8. package/src/agents/front-worker/agent.json +6 -0
  9. package/src/agents/heavy-worker/AGENT.md +10 -11
  10. package/src/agents/heavy-worker/agent.json +1 -1
  11. package/src/agents/maintainer/AGENT.md +0 -2
  12. package/src/agents/reviewer/AGENT.md +9 -13
  13. package/src/agents/reviewer/agent.json +1 -1
  14. package/src/agents/security/AGENT.md +14 -0
  15. package/src/agents/security/agent.json +6 -0
  16. package/src/agents/worker/AGENT.md +8 -8
  17. package/src/agents/worker/agent.json +1 -1
  18. package/src/agents/writer/AGENT.md +14 -0
  19. package/src/agents/writer/agent.json +6 -0
  20. package/src/rules/agent/00-common.md +4 -7
  21. package/src/rules/lead/01-general.md +0 -3
  22. package/src/rules/shared/10-tool-workflow.md +10 -2
  23. package/src/rules/shared/60-verification.md +2 -0
  24. package/src/runtime/agent/orchestrator/agent-runtime/agent-dispatch.mjs +183 -26
  25. package/src/runtime/agent/orchestrator/agent-runtime/session-builder.mjs +4 -0
  26. package/src/runtime/agent/orchestrator/cache-break-trace.mjs +109 -0
  27. package/src/runtime/agent/orchestrator/config.mjs +7 -2
  28. package/src/runtime/agent/orchestrator/providers/admission-scheduler.mjs +16 -3
  29. package/src/runtime/agent/orchestrator/providers/lib/anthropic-request-utils.mjs +9 -1
  30. package/src/runtime/agent/orchestrator/providers/media-normalization.mjs +30 -9
  31. package/src/runtime/agent/orchestrator/providers/openai-codex-metadata.mjs +18 -26
  32. package/src/runtime/agent/orchestrator/providers/openai-oauth-http-sse.mjs +25 -2
  33. package/src/runtime/agent/orchestrator/providers/openai-oauth-ws.mjs +103 -10
  34. package/src/runtime/agent/orchestrator/providers/openai-turn-state.mjs +68 -0
  35. package/src/runtime/agent/orchestrator/providers/openai-ws-delta.mjs +36 -11
  36. package/src/runtime/agent/orchestrator/providers/openai-ws-pool.mjs +140 -86
  37. package/src/runtime/agent/orchestrator/providers/openai-ws-stream.mjs +9 -13
  38. package/src/runtime/agent/orchestrator/session/agent-loop.mjs +72 -4
  39. package/src/runtime/agent/orchestrator/session/browser-snapshot-supersession.mjs +61 -0
  40. package/src/runtime/agent/orchestrator/session/compact/handoff.mjs +0 -22
  41. package/src/runtime/agent/orchestrator/session/compact/messages.mjs +2 -2
  42. package/src/runtime/agent/orchestrator/session/compact/runner.mjs +11 -23
  43. package/src/runtime/agent/orchestrator/session/compact/summary.mjs +28 -269
  44. package/src/runtime/agent/orchestrator/session/compact.mjs +0 -6
  45. package/src/runtime/agent/orchestrator/session/context-utils.mjs +86 -11
  46. package/src/runtime/agent/orchestrator/session/eager-dispatch.mjs +17 -1
  47. package/src/runtime/agent/orchestrator/session/image-strip-recovery.mjs +12 -8
  48. package/src/runtime/agent/orchestrator/session/loop/compact-policy.mjs +110 -2
  49. package/src/runtime/agent/orchestrator/session/loop/pre-dispatch-deny.mjs +3 -16
  50. package/src/runtime/agent/orchestrator/session/loop/recall-fasttrack.mjs +80 -18
  51. package/src/runtime/agent/orchestrator/session/loop/steering.mjs +6 -0
  52. package/src/runtime/agent/orchestrator/session/loop/tool-exec.mjs +3 -0
  53. package/src/runtime/agent/orchestrator/session/loop/tool-helpers.mjs +6 -0
  54. package/src/runtime/agent/orchestrator/session/manager/ask-session.mjs +80 -21
  55. package/src/runtime/agent/orchestrator/session/manager/compaction-runner.mjs +33 -72
  56. package/src/runtime/agent/orchestrator/session/manager/session-crud.mjs +21 -2
  57. package/src/runtime/agent/orchestrator/session/manager/session-lifecycle.mjs +25 -51
  58. package/src/runtime/agent/orchestrator/session/manager/status-telemetry.mjs +3 -0
  59. package/src/runtime/agent/orchestrator/session/manager/tool-resolution.mjs +4 -110
  60. package/src/runtime/agent/orchestrator/session/manager/turn-checkpoint-journal.mjs +39 -15
  61. package/src/runtime/agent/orchestrator/session/manager/turn-checkpoint.mjs +14 -4
  62. package/src/runtime/agent/orchestrator/session/pre-send-compact.mjs +41 -8
  63. package/src/runtime/agent/orchestrator/session/provider-prefix-guard.mjs +129 -12
  64. package/src/runtime/agent/orchestrator/session/send-with-recovery.mjs +2 -2
  65. package/src/runtime/agent/orchestrator/session/store/listing.mjs +8 -1
  66. package/src/runtime/agent/orchestrator/session/store/save-worker.mjs +15 -1
  67. package/src/runtime/agent/orchestrator/session/store-summary-index.mjs +36 -2
  68. package/src/runtime/agent/orchestrator/session/store-summary-reader.mjs +157 -30
  69. package/src/runtime/agent/orchestrator/session/store-summary-visibility.mjs +57 -0
  70. package/src/runtime/agent/orchestrator/session/store.mjs +3 -1
  71. package/src/runtime/agent/orchestrator/session/tool-batch.mjs +22 -0
  72. package/src/runtime/agent/orchestrator/tools/builtin/read-special-files.mjs +6 -6
  73. package/src/runtime/agent/orchestrator/tools/progress-message.mjs +4 -0
  74. package/src/runtime/attachments/pdf-extract.mjs +3 -0
  75. package/src/runtime/attachments/pdfjs-runtime.mjs +13 -0
  76. package/src/runtime/browser-bridge/action-schema.mjs +251 -0
  77. package/src/runtime/browser-bridge/client.mjs +75 -26
  78. package/src/runtime/browser-bridge/tool-defs.mjs +132 -15
  79. package/src/runtime/computer-bridge/action-schema.mjs +653 -0
  80. package/src/runtime/computer-bridge/client.mjs +211 -28
  81. package/src/runtime/computer-bridge/tool-defs.mjs +25 -45
  82. package/src/runtime/office/assurance-benchmark.mjs +358 -0
  83. package/src/runtime/office/assurance.mjs +833 -0
  84. package/src/runtime/office/benchmark.mjs +496 -0
  85. package/src/runtime/office/capabilities.mjs +551 -0
  86. package/src/runtime/office/com-adapter.mjs +283 -0
  87. package/src/runtime/office/content-model.mjs +183 -0
  88. package/src/runtime/office/contract-benchmark.mjs +105 -0
  89. package/src/runtime/office/design-library.mjs +1562 -0
  90. package/src/runtime/office/design-system.mjs +1966 -0
  91. package/src/runtime/office/index.mjs +2413 -0
  92. package/src/runtime/office/journal.mjs +82 -0
  93. package/src/runtime/office/office-com-host.ps1 +3781 -0
  94. package/src/runtime/office/office-com-session-host.ps1 +855 -0
  95. package/src/runtime/office/ooxml-validator.mjs +271 -0
  96. package/src/runtime/office/pagination.mjs +132 -0
  97. package/src/runtime/office/pdf-adapter.mjs +591 -0
  98. package/src/runtime/office/pdf-analysis.mjs +372 -0
  99. package/src/runtime/office/pdf-render.mjs +167 -0
  100. package/src/runtime/office/pdf-security.mjs +63 -0
  101. package/src/runtime/office/polish-benchmark.mjs +190 -0
  102. package/src/runtime/office/portable-ooxml.mjs +1867 -0
  103. package/src/runtime/office/quality-live-benchmark.mjs +486 -0
  104. package/src/runtime/office/quality-pipeline.mjs +136 -0
  105. package/src/runtime/office/tabular.mjs +302 -0
  106. package/src/runtime/office/templates/mixdog-executive.pptx +0 -0
  107. package/src/runtime/office/templates/mixdog-executive.pptx.mixdog.json +190 -0
  108. package/src/runtime/office/tool-defs.mjs +113 -0
  109. package/src/runtime/office/visual-diff.mjs +89 -0
  110. package/src/runtime/office/xlsx-assertions.mjs +172 -0
  111. package/src/runtime/office/xlsx-contract.mjs +147 -0
  112. package/src/runtime/shared/agent-route-config.mjs +9 -0
  113. package/src/runtime/shared/tool-execution-contract.mjs +16 -0
  114. package/src/runtime/shared/tool-surface.mjs +9 -0
  115. package/src/session-runtime/context-status.mjs +9 -3
  116. package/src/session-runtime/deferred-tool-delta.mjs +104 -0
  117. package/src/session-runtime/goal-runtime.mjs +617 -197
  118. package/src/session-runtime/lifecycle-api.mjs +50 -8
  119. package/src/session-runtime/provider-request-snapshot.mjs +33 -9
  120. package/src/session-runtime/resource-api.mjs +31 -94
  121. package/src/session-runtime/runtime-core.mjs +78 -26
  122. package/src/session-runtime/session-lifecycle.mjs +34 -12
  123. package/src/session-runtime/session-title.mjs +2 -2
  124. package/src/session-runtime/session-turn-api.mjs +15 -14
  125. package/src/session-runtime/tool-catalog-data.mjs +1 -1
  126. package/src/session-runtime/tool-catalog.mjs +38 -99
  127. package/src/session-runtime/tool-defs.mjs +6 -1
  128. package/src/session-runtime/tool-surface.mjs +18 -8
  129. package/src/session-runtime/workflow-agents-api.mjs +8 -25
  130. package/src/session-runtime/workflow.mjs +8 -6
  131. package/src/standalone/agent-tool/helpers.mjs +2 -2
  132. package/src/standalone/agent-tool/job-views.mjs +3 -1
  133. package/src/standalone/agent-tool/notify.mjs +5 -1
  134. package/src/standalone/agent-tool/render.mjs +3 -0
  135. package/src/standalone/agent-tool/spawn-flow.mjs +61 -16
  136. package/src/standalone/agent-tool/tool-def.mjs +1 -1
  137. package/src/standalone/agent-tool/worker-index.mjs +123 -0
  138. package/src/standalone/agent-tool/worker-rows.mjs +2 -1
  139. package/src/standalone/agent-tool.mjs +57 -10
  140. package/src/standalone/daemon.mjs +105 -6
  141. package/src/standalone/session-runtime-host.mjs +61 -48
  142. package/src/standalone/session-runtime-inline-host.mjs +34 -127
  143. package/src/standalone/session-runtime-worker.mjs +20 -198
  144. package/src/standalone/session-service.mjs +632 -7
  145. package/src/tui/dist/index.mjs +24 -1
  146. package/src/tui/lib/voice-setup.mjs +4 -1
  147. package/src/tui/session/context-state.mjs +2 -13
  148. package/src/tui/session/goal-continuation.mjs +38 -7
  149. package/src/tui/session/session-api-ext.mjs +9 -0
  150. package/src/tui/session/session-api.mjs +15 -1
  151. package/src/tui/session/session-flow.mjs +25 -1
  152. package/src/tui/session/turn.mjs +88 -16
  153. package/src/tui/session-local.mjs +25 -3
  154. package/src/vendor/statusline/src/gateway/route-meta.mjs +31 -0
  155. package/scripts/generate-voice-runtime-manifest.test.mjs +0 -135
  156. package/scripts/native-binary-arch.test.mjs +0 -111
  157. package/scripts/patch-replay.test.mjs +0 -94
  158. package/src/headless-exec.test.mjs +0 -539
  159. package/src/runtime/agent/orchestrator/agent-trace-timing.test.mjs +0 -57
  160. package/src/runtime/agent/orchestrator/context/collect-skills.test.mjs +0 -153
  161. package/src/runtime/agent/orchestrator/mcp/cancellation.test.mjs +0 -139
  162. package/src/runtime/agent/orchestrator/mcp/features.test.mjs +0 -66
  163. package/src/runtime/agent/orchestrator/mcp/security.test.mjs +0 -80
  164. package/src/runtime/agent/orchestrator/providers/anthropic-fast-mode.test.mjs +0 -90
  165. package/src/runtime/agent/orchestrator/providers/anthropic-server-fallback.test.mjs +0 -215
  166. package/src/runtime/agent/orchestrator/providers/antigravity-oauth.test.mjs +0 -165
  167. package/src/runtime/agent/orchestrator/providers/media-parity.test.mjs +0 -142
  168. package/src/runtime/agent/orchestrator/providers/openai-codex-identity.test.mjs +0 -153
  169. package/src/runtime/agent/orchestrator/providers/openai-codex-model.test.mjs +0 -24
  170. package/src/runtime/agent/orchestrator/providers/openai-ws-delta-parity.test.mjs +0 -190
  171. package/src/runtime/agent/orchestrator/providers/provider-replay.test.mjs +0 -235
  172. package/src/runtime/agent/orchestrator/providers/sse-framing.test.mjs +0 -719
  173. package/src/runtime/agent/orchestrator/session/cache/prefetch-cache.test.mjs +0 -40
  174. package/src/runtime/agent/orchestrator/session/compact-policy.test.mjs +0 -176
  175. package/src/runtime/agent/orchestrator/session/compaction-read-reset.test.mjs +0 -161
  176. package/src/runtime/agent/orchestrator/session/eager-dispatch.test.mjs +0 -115
  177. package/src/runtime/agent/orchestrator/session/evidence-union.test.mjs +0 -228
  178. package/src/runtime/agent/orchestrator/session/image-strip-recovery.test.mjs +0 -245
  179. package/src/runtime/agent/orchestrator/session/lossless-tool-output.test.mjs +0 -125
  180. package/src/runtime/agent/orchestrator/session/manager/pending-messages-persistence.test.mjs +0 -325
  181. package/src/runtime/agent/orchestrator/session/manager/session-lifecycle.test.mjs +0 -70
  182. package/src/runtime/agent/orchestrator/session/manager/turn-checkpoint-journal.test.mjs +0 -457
  183. package/src/runtime/agent/orchestrator/session/provider-prefix-guard.test.mjs +0 -117
  184. package/src/runtime/agent/orchestrator/session/reduction-metrics.test.mjs +0 -87
  185. package/src/runtime/agent/orchestrator/session/store/serialize.test.mjs +0 -60
  186. package/src/runtime/agent/orchestrator/session/store-summary-reader.test.mjs +0 -583
  187. package/src/runtime/agent/orchestrator/session/task-wait-control.test.mjs +0 -78
  188. package/src/runtime/agent/orchestrator/tools/builtin/absence-absorption.test.mjs +0 -43
  189. package/src/runtime/agent/orchestrator/tools/builtin/absolute-glob-expand.test.mjs +0 -63
  190. package/src/runtime/agent/orchestrator/tools/builtin/bash-tool-cwd-env.test.mjs +0 -14
  191. package/src/runtime/agent/orchestrator/tools/builtin/edit-encoding-eol.test.mjs +0 -224
  192. package/src/runtime/agent/orchestrator/tools/builtin/edit-sequential-occupation.test.mjs +0 -224
  193. package/src/runtime/agent/orchestrator/tools/builtin/enoent-outside-project.test.mjs +0 -56
  194. package/src/runtime/agent/orchestrator/tools/builtin/find-search-budget.test.mjs +0 -103
  195. package/src/runtime/agent/orchestrator/tools/builtin/git-command-policy.test.mjs +0 -30
  196. package/src/runtime/agent/orchestrator/tools/builtin/git-command-tool.test.mjs +0 -390
  197. package/src/runtime/agent/orchestrator/tools/builtin/git-repo-rw-lock.test.mjs +0 -83
  198. package/src/runtime/agent/orchestrator/tools/builtin/grep-output-budget.test.mjs +0 -31
  199. package/src/runtime/agent/orchestrator/tools/builtin/grep-single-file-rescue.test.mjs +0 -106
  200. package/src/runtime/agent/orchestrator/tools/builtin/lib/shell-job-records.test.mjs +0 -102
  201. package/src/runtime/agent/orchestrator/tools/builtin/list-tool-integrity.test.mjs +0 -152
  202. package/src/runtime/agent/orchestrator/tools/builtin/native-search-health.test.mjs +0 -24
  203. package/src/runtime/agent/orchestrator/tools/builtin/native-search-transport.test.mjs +0 -24
  204. package/src/runtime/agent/orchestrator/tools/builtin/noise-dir-visibility.test.mjs +0 -69
  205. package/src/runtime/agent/orchestrator/tools/builtin/read-glob-survey.test.mjs +0 -71
  206. package/src/runtime/agent/orchestrator/tools/builtin/runtime-capabilities.test.mjs +0 -56
  207. package/src/runtime/agent/orchestrator/tools/builtin/search-builders.test.mjs +0 -16
  208. package/src/runtime/agent/orchestrator/tools/builtin/search-glob-top-k.test.mjs +0 -39
  209. package/src/runtime/agent/orchestrator/tools/builtin/write-symlink.test.mjs +0 -153
  210. package/src/runtime/agent/orchestrator/tools/code-graph/aggregate-anchor-relocation.test.mjs +0 -55
  211. package/src/runtime/agent/orchestrator/tools/code-graph/dispatch.test.mjs +0 -88
  212. package/src/runtime/agent/orchestrator/tools/code-graph/loose-file-target.test.mjs +0 -72
  213. package/src/runtime/agent/orchestrator/tools/code-graph/memory-cache.test.mjs +0 -54
  214. package/src/runtime/agent/orchestrator/tools/code-graph/search-references.test.mjs +0 -20
  215. package/src/runtime/agent/orchestrator/tools/code-graph/symbol-search-scope.test.mjs +0 -55
  216. package/src/runtime/agent/orchestrator/tools/code-graph/text-span-mask.test.mjs +0 -268
  217. package/src/runtime/agent/orchestrator/tools/env-scrub.test.mjs +0 -57
  218. package/src/runtime/agent/orchestrator/tools/graph-binary-fetcher.test.mjs +0 -19
  219. package/src/runtime/agent/orchestrator/tools/lib/native-spawn-client.test.mjs +0 -104
  220. package/src/runtime/agent/orchestrator/tools/patch/engine-contract-gate.test.mjs +0 -661
  221. package/src/runtime/agent/orchestrator/tools/patch/patch-codec-eol.test.mjs +0 -552
  222. package/src/runtime/agent/orchestrator/tools/patch/patch-symlink.test.mjs +0 -141
  223. package/src/runtime/agent/orchestrator/tools/patch/v4a-pure-move.test.mjs +0 -57
  224. package/src/runtime/agent/orchestrator/tools/patch/v4a-section-coalesce.test.mjs +0 -81
  225. package/src/runtime/agent/orchestrator/tools/spawn-binary-fetcher.test.mjs +0 -52
  226. package/src/runtime/attachments/store.test.mjs +0 -209
  227. package/src/runtime/channels/lib/voice-runtime-fetcher.test.mjs +0 -17
  228. package/src/runtime/channels/lib/webhook/deliveries.test.mjs +0 -18
  229. package/src/runtime/channels/lib/webhook/relay-tunnel.test.mjs +0 -68
  230. package/src/runtime/media/adapters/codex-image.test.mjs +0 -22
  231. package/src/runtime/media/download.test.mjs +0 -52
  232. package/src/runtime/media/renditions.test.mjs +0 -99
  233. package/src/runtime/media/store.test.mjs +0 -159
  234. package/src/runtime/memory/lib/archive-security.test.mjs +0 -128
  235. package/src/runtime/memory/lib/embedding-model-config.test.mjs +0 -33
  236. package/src/runtime/memory/lib/http-wire.test.mjs +0 -15
  237. package/src/runtime/memory/lib/memory-cycle-packets.test.mjs +0 -49
  238. package/src/runtime/memory/lib/memory-cycle2-shared.test.mjs +0 -78
  239. package/src/runtime/memory/lib/memory-embedding-migration.test.mjs +0 -50
  240. package/src/runtime/memory/lib/pg/process.test.mjs +0 -36
  241. package/src/runtime/memory/lib/trace-store.test.mjs +0 -57
  242. package/src/runtime/memory/lib/transcript-ingest.test.mjs +0 -52
  243. package/src/runtime/shared/background-tasks.test.mjs +0 -78
  244. package/src/runtime/shared/bounded-download.test.mjs +0 -41
  245. package/src/runtime/shared/channel-notification-routing.test.mjs +0 -25
  246. package/src/runtime/shared/child-spawn-remote.test.mjs +0 -124
  247. package/src/runtime/shared/remote-intent.test.mjs +0 -40
  248. package/src/runtime/shared/resource-admission.test.mjs +0 -43
  249. package/src/runtime/shared/runtime-root.test.mjs +0 -34
  250. package/src/runtime/shared/schedule-time.test.mjs +0 -29
  251. package/src/runtime/shared/session-runtime-health.test.mjs +0 -83
  252. package/src/runtime/shared/skill-document.test.mjs +0 -81
  253. package/src/runtime/shared/tool-surface.test.mjs +0 -87
  254. package/src/runtime/shared/update-checker.test.mjs +0 -33
  255. package/src/runtime/shared/user-cwd.test.mjs +0 -43
  256. package/src/runtime/shared/webhook-session-run.test.mjs +0 -14
  257. package/src/session-runtime/agent-disable.test.mjs +0 -123
  258. package/src/session-runtime/cwd-plugins.test.mjs +0 -75
  259. package/src/session-runtime/cwd-tool-routing.test.mjs +0 -61
  260. package/src/session-runtime/global-extensions.test.mjs +0 -28
  261. package/src/session-runtime/goal-runtime.test.mjs +0 -108
  262. package/src/session-runtime/lifecycle-api.test.mjs +0 -21
  263. package/src/session-runtime/model-settings-persist.test.mjs +0 -105
  264. package/src/session-runtime/notification-bus.test.mjs +0 -148
  265. package/src/session-runtime/plugin-mcp-standard.test.mjs +0 -177
  266. package/src/session-runtime/prewarm.test.mjs +0 -52
  267. package/src/session-runtime/provider-request-snapshot.test.mjs +0 -37
  268. package/src/session-runtime/resource-api-global.test.mjs +0 -69
  269. package/src/session-runtime/session-lifecycle.test.mjs +0 -125
  270. package/src/session-runtime/session-title.test.mjs +0 -36
  271. package/src/session-runtime/skills-api.test.mjs +0 -99
  272. package/src/session-runtime/tool-policy-surface.test.mjs +0 -331
  273. package/src/standalone/agent-tool/helpers.test.mjs +0 -62
  274. package/src/standalone/agent-tool/notify.test.mjs +0 -37
  275. package/src/standalone/agent-tool/spawn-flow.test.mjs +0 -63
  276. package/src/standalone/channel-restart.test.mjs +0 -145
  277. package/src/standalone/channel-session-router.test.mjs +0 -37
  278. package/src/standalone/channel-worker-heartbeat.test.mjs +0 -30
  279. package/src/standalone/hook-bus/handlers.test.mjs +0 -88
  280. package/src/standalone/plugin-admin.test.mjs +0 -173
  281. package/src/standalone/session-runtime-agent-control-client.test.mjs +0 -71
  282. package/src/standalone/session-runtime-dispatch-cancel.test.mjs +0 -139
  283. package/src/standalone/session-runtime-host-factory.test.mjs +0 -31
  284. package/src/standalone/session-runtime-host-health.test.mjs +0 -160
  285. package/src/standalone/session-runtime-inline-host.test.mjs +0 -83
  286. package/src/standalone/session-runtime-provider-cooldown.test.mjs +0 -80
  287. package/src/standalone/session-runtime-shard-host.test.mjs +0 -569
  288. package/src/standalone/session-runtime-shard-router.test.mjs +0 -101
  289. package/src/tui/app/live-spinner-visibility.test.mjs +0 -44
  290. package/src/tui/app/panel-epoch.test.mjs +0 -1009
  291. package/src/tui/app/panel-handoff.test.mjs +0 -311
  292. package/src/tui/app/prompt-submit.test.mjs +0 -206
  293. package/src/tui/session/completion-card-restore.test.mjs +0 -111
  294. package/src/tui/session/goal-continuation.test.mjs +0 -84
  295. package/src/tui/session/oauth-flows.test.mjs +0 -134
  296. package/src/tui/session/queue-helpers.test.mjs +0 -46
  297. package/src/tui/session/session-action-surface.test.mjs +0 -108
  298. package/src/tui/session/task-wait-submit.test.mjs +0 -80
  299. package/src/tui/session/tool-result-status.test.mjs +0 -131
  300. package/src/tui/session/tui-steering-persist.test.mjs +0 -104
@@ -116,6 +116,10 @@ function _tokenCacheSet(key, count) {
116
116
  // pre-offload semantics.
117
117
  const BPE_ASYNC_THRESHOLD_CHARS = 32_768;
118
118
  const _nativePendingKeys = new Set();
119
+ // Compact-decision confirmation path: force exact synchronous encodes while a
120
+ // caller re-evaluates a decision that must not act on the conservative
121
+ // heuristic (see withSyncTokenCounts).
122
+ let _forceSyncTokenCounts = false;
119
123
 
120
124
  // Offload one large count to the native mixdog-token server. Returns false
121
125
  // when the native path cannot be attempted (caller encodes synchronously). A
@@ -148,11 +152,16 @@ function bpeTokenCount(enc, s) {
148
152
  tokenCountCache.set(key, hit);
149
153
  return hit;
150
154
  }
151
- if (s.length >= BPE_ASYNC_THRESHOLD_CHARS) {
155
+ if (s.length >= BPE_ASYNC_THRESHOLD_CHARS && !_forceSyncTokenCounts) {
152
156
  if (!_nativePendingKeys.has(key)) _offloadTokenCountNative(key, s);
153
157
  if (_nativePendingKeys.has(key)) return null;
154
158
  }
155
159
  const count = bpeEncodeCount(enc, s);
160
+ // A forced-sync encode may race a pending native count for the same key:
161
+ // consume the pending marker so the late native result cannot double-set,
162
+ // and bump the generation exactly as the native landing would have, so
163
+ // memoized heuristic-based contributions refresh to the exact value.
164
+ if (_nativePendingKeys.delete(key)) tokenEstimateGeneration += 1;
156
165
  _tokenCacheSet(key, count);
157
166
  return count;
158
167
  }
@@ -231,6 +240,28 @@ export function estimateTokens(text) {
231
240
  return legacyEstimateTokens(s);
232
241
  }
233
242
 
243
+ /**
244
+ * True while at least one large string is still being counted by the native
245
+ * token server (its estimate is the conservative legacy heuristic until the
246
+ * exact count lands in the cache).
247
+ */
248
+ export function hasPendingNativeTokenCounts() {
249
+ return _nativePendingKeys.size > 0;
250
+ }
251
+
252
+ /**
253
+ * Run fn with the async native offload disabled: every estimate inside is an
254
+ * exact synchronous BPE encode (seeding the shared cache). Reserved for rare
255
+ * decision-confirmation paths — a sync encode of a huge string costs tens of
256
+ * milliseconds on the shared event loop.
257
+ */
258
+ export function withSyncTokenCounts(fn) {
259
+ const prev = _forceSyncTokenCounts;
260
+ _forceSyncTokenCounts = true;
261
+ try { return fn(); }
262
+ finally { _forceSyncTokenCounts = prev; }
263
+ }
264
+
234
265
  /**
235
266
  * Boot prewarm: load the o200k encoder (WASM init), run one small encode
236
267
  * (JIT), and spawn the token-count worker so the first large transcript
@@ -369,6 +400,25 @@ function messageEstimateText(m) {
369
400
  if (m.role === 'tool' && m.toolCallId) text += `\n${m.toolCallId}`;
370
401
  return text;
371
402
  }
403
+ // Wire reality for replay-carrying assistants: the SAME provider replays
404
+ // providerReplay.items INSTEAD of content/toolCalls, while a different
405
+ // provider sends content/toolCalls without the replay envelope. Summing both
406
+ // halves double-counted the assistant's own output and tool args in every
407
+ // estimate-fallback window. Meter max(base, replay) instead: neither wire
408
+ // projection is ever undercounted and nothing is counted twice.
409
+ // messageEstimateText itself stays byte-identical — prefix signatures and
410
+ // fingerprints hash the full concatenation and must not shift across deploys.
411
+ function messageTextTokens(m, precomputedText = null) {
412
+ const text = precomputedText ?? messageEstimateText(m);
413
+ const replayItems = m?.role === 'assistant'
414
+ && Array.isArray(m.providerReplay?.items) && m.providerReplay.items.length
415
+ ? m.providerReplay.items
416
+ : null;
417
+ const fullTokens = estimateTokens(text);
418
+ if (!replayItems) return fullTokens;
419
+ const replayTokens = estimateTokens(nativeBlocksEstimateText(replayItems));
420
+ return Math.max(fullTokens - replayTokens, replayTokens);
421
+ }
372
422
  function imageDescriptorAllowance(descriptor) {
373
423
  if (descriptor.width && descriptor.height) {
374
424
  // Anthropic vision cost: tokens = (width * height) / 750, with images
@@ -411,7 +461,7 @@ function messageFileAllowance(m) {
411
461
  ), 0);
412
462
  }
413
463
  export function estimateMessageTokens(m) {
414
- return estimateTokens(messageEstimateText(m)) + messageImageAllowance(m) + messageFileAllowance(m) + 4;
464
+ return messageTextTokens(m) + messageImageAllowance(m) + messageFileAllowance(m) + 4;
415
465
  }
416
466
  export function estimateMessagesTokens(messages) {
417
467
  return messages.reduce((sum, m) => sum + estimateMessageTokens(m), 0);
@@ -490,7 +540,11 @@ function contextMessageContribution(message) {
490
540
  }
491
541
  const role = ['system', 'user', 'assistant', 'tool'].includes(fingerprint.role) ? fingerprint.role : 'other';
492
542
  const text = messageEstimateText(message);
493
- const tokens = estimateTokens(text) + messageImageAllowance(message) + 4;
543
+ // Same meter as estimateMessageTokens: replay-aware text tokens plus the
544
+ // image AND document allowances — the gauge summary and the compaction
545
+ // pressure estimate must price a message identically (a PDF counted by
546
+ // one but not the other made the gauge diverge from the decision).
547
+ const tokens = messageTextTokens(message, text) + messageImageAllowance(message) + messageFileAllowance(message) + 4;
494
548
  const contribution = {
495
549
  role,
496
550
  tokens,
@@ -744,24 +798,37 @@ export function contextMessagesSignature(messages, count = messages?.length) {
744
798
 
745
799
  const toolSchemaAnalysisMemo = new WeakMap();
746
800
 
747
- function serializeToolSchemas(tools) {
801
+ function isDeferredToolSchema(tool) {
802
+ return tool?.deferLoading === true || tool?.defer_loading === true;
803
+ }
804
+
805
+ function serializeToolSchemas(tools, { excludeDeferred = false } = {}) {
748
806
  const list = Array.isArray(tools) ? tools : [];
749
807
  const nativePrefixCount = providerNativeToolPrefixCount(list);
750
808
  try {
751
- return JSON.stringify(list.map((tool, index) => {
809
+ const wire = [];
810
+ list.forEach((tool, index) => {
811
+ const deferred = isDeferredToolSchema(tool);
812
+ if (excludeDeferred && deferred) return;
752
813
  if (index < nativePrefixCount) {
753
- return tool;
814
+ wire.push(tool);
815
+ return;
754
816
  }
755
817
  const wireTool = {
756
818
  name: tool?.name,
757
819
  description: tool?.description,
758
820
  input_schema: tool?.inputSchema ?? tool?.input_schema ?? tool?.parameters ?? tool?.schema,
759
821
  };
760
- if (tool?.deferLoading === true || tool?.defer_loading === true) wireTool.defer_loading = true;
761
- return wireTool;
762
- }));
822
+ if (deferred) wireTool.defer_loading = true;
823
+ wire.push(wireTool);
824
+ });
825
+ return JSON.stringify(wire);
826
+ }
827
+ catch {
828
+ return list
829
+ .filter((tool) => !(excludeDeferred && isDeferredToolSchema(tool)))
830
+ .map(t => String(t?.name ?? '')).join('');
763
831
  }
764
- catch { return list.map(t => String(t?.name ?? '')).join(''); }
765
832
  }
766
833
 
767
834
  export function toolSchemaSignature(tools) {
@@ -776,7 +843,15 @@ function analyzeToolSchemas(tools) {
776
843
  const text = serializeToolSchemas(list);
777
844
  const signature = createHash('sha256').update(text).digest('hex');
778
845
  if (cached && currentGeneration && cached.signature === signature) return cached;
779
- const analysis = { signature, tokens: estimateTokens(text), generation: tokenEstimateGeneration };
846
+ // defer_loading schemas ride the wire but the API excludes them from
847
+ // context-token calculation and prompt-cache keys, so metering them at
848
+ // full weight inflated the request reserve. The SIGNATURE keeps hashing
849
+ // the full serialization (a deferred tool joining/leaving must still
850
+ // re-fingerprint the surface); only the token cost drops deferred entries.
851
+ const meterText = list.some(isDeferredToolSchema)
852
+ ? serializeToolSchemas(list, { excludeDeferred: true })
853
+ : text;
854
+ const analysis = { signature, tokens: estimateTokens(meterText), generation: tokenEstimateGeneration };
780
855
  if (Array.isArray(tools)) toolSchemaAnalysisMemo.set(tools, analysis);
781
856
  return analysis;
782
857
  }
@@ -25,7 +25,13 @@ import { tryReadCached, tryScopedToolCached } from './read-dedup.mjs';
25
25
  import { preDispatchDenyForSession } from './loop/pre-dispatch-deny.mjs';
26
26
  import { executeTool } from './loop/tool-exec.mjs';
27
27
  import { crossTurnSignature } from './loop/completion-guards.mjs';
28
- import { getToolKind, isEagerDispatchable, isParallelDispatchable, isToolCallDedupEligible } from './loop/tool-helpers.mjs';
28
+ import {
29
+ getToolKind,
30
+ isEagerDispatchable,
31
+ isParallelDispatchable,
32
+ isSingleCallPerTurnTool,
33
+ isToolCallDedupEligible,
34
+ } from './loop/tool-helpers.mjs';
29
35
 
30
36
  function eagerSettlementFailed(settled) {
31
37
  if (!settled?.ok) return true;
@@ -93,9 +99,19 @@ export function createEagerDispatcher({
93
99
  // re-execute. A fresh Map() is created per turn, so the sig set
94
100
  // resets at the turn boundary without leaking across getIterations().
95
101
  const _eagerInFlightSigs = new Map();
102
+ // Computer Use owns stateful agent-scoped target claims and each mutation
103
+ // returns the fresh state required by the next decision. A provider may still
104
+ // stream parallel calls despite the tool contract, so reserve only the
105
+ // first call before any eager execution starts.
106
+ const _singleCallFirstIdByName = new Map();
96
107
  const epoch = { mutation: 0 };
97
108
  const startEagerTool = (call) => {
98
109
  if (!call?.id || pending.has(call.id) || !isParallelDispatchable(call.name)) return null;
110
+ if (isSingleCallPerTurnTool(call.name)) {
111
+ const firstId = _singleCallFirstIdByName.get(call.name);
112
+ if (firstId && firstId !== call.id) return null;
113
+ if (!firstId) _singleCallFirstIdByName.set(call.name, call.id);
114
+ }
99
115
  // Never eager-execute a call whose arguments failed to parse
100
116
  // (invalid-args marker). It has no usable arguments; the serial
101
117
  // body handles it via the invalid-args feedback path.
@@ -80,6 +80,17 @@ export function stripInlineImages(messages, { startIndex = 0 } = {}) {
80
80
  return { messages: stripped ? next : messages, stripped, uniqueImages: identities.size };
81
81
  }
82
82
 
83
+ export function stripInlineImagesFromLatestTurn(messages) {
84
+ if (!Array.isArray(messages)) return { messages, stripped: 0, uniqueImages: 0 };
85
+ let startIndex = 0;
86
+ for (let index = messages.length - 1; index >= 0; index -= 1) {
87
+ if (messages[index]?.role !== 'assistant') continue;
88
+ startIndex = index + 1;
89
+ break;
90
+ }
91
+ return stripInlineImages(messages, { startIndex });
92
+ }
93
+
83
94
  export function confirmedImageRejection(err) {
84
95
  if (errorStatus(err) !== 400) return false;
85
96
  const code = errorCode(err);
@@ -89,14 +100,7 @@ export function confirmedImageRejection(err) {
89
100
 
90
101
  export function persistenceMessagesForConfirmedImageRejection(err, messages) {
91
102
  if (!confirmedImageRejection(err) || !Array.isArray(messages)) return null;
92
- let startIndex = 0;
93
- for (let i = messages.length - 1; i >= 0; i -= 1) {
94
- if (messages[i]?.role === 'assistant') {
95
- startIndex = i + 1;
96
- break;
97
- }
98
- }
99
- const tail = stripInlineImages(messages, { startIndex });
103
+ const tail = stripInlineImagesFromLatestTurn(messages);
100
104
  return tail.stripped > 0 && tail.uniqueImages === 1 ? tail.messages : null;
101
105
  }
102
106
 
@@ -216,6 +216,95 @@ export function currentContextEstimateTokens(messageTokensEst, policy) {
216
216
  return Math.max(0, Math.round((messageTokensEst + requestReserve) * calibration));
217
217
  }
218
218
 
219
+ const CONTEXT_USAGE_SNAPSHOT_VERSION = 1;
220
+
221
+ function contextUsageSnapshotTail(messages) {
222
+ const tail = Array.isArray(messages) ? messages[messages.length - 1] : null;
223
+ return {
224
+ role: String(tail?.role || ''),
225
+ id: String(tail?.uuid || tail?.id || tail?.toolCallId || ''),
226
+ };
227
+ }
228
+
229
+ export function recordContextUsageSnapshot(sessionRef, policy, {
230
+ messages,
231
+ usedTokens,
232
+ messageTokensEst = null,
233
+ source = 'post_compact',
234
+ updatedAt = Date.now(),
235
+ } = {}) {
236
+ if (!sessionRef || !policy || !Array.isArray(messages)) return null;
237
+ const used = Number(usedTokens);
238
+ if (!Number.isFinite(used) || used < 0) return null;
239
+ const messageEstimate = Number.isFinite(Number(messageTokensEst))
240
+ ? Math.max(0, Math.round(Number(messageTokensEst)))
241
+ : estimateMessagesTokens(messages);
242
+ const tail = contextUsageSnapshotTail(messages);
243
+ const snapshot = {
244
+ version: CONTEXT_USAGE_SNAPSHOT_VERSION,
245
+ source: String(source || 'estimated'),
246
+ usedTokens: Math.max(0, Math.round(used)),
247
+ limitTokens: positiveTokenInt(policy.triggerTokens || policy.boundaryTokens) || null,
248
+ messageTokensEst: messageEstimate,
249
+ messageCount: messages.length,
250
+ messagesSignature: contextMessagesSignature(messages),
251
+ tailRole: tail.role,
252
+ tailId: tail.id,
253
+ usageMetricsTurnId: String(sessionRef.usageMetricsTurnId || ''),
254
+ usageMetricsEpoch: Number(sessionRef.usageMetricsEpoch) || 0,
255
+ toolSchemaSignature: policy.toolSchemaSignature || null,
256
+ provider: sessionRef.provider || policy.provider || null,
257
+ model: sessionRef.model || null,
258
+ contextWindow: positiveTokenInt(policy.contextWindow || sessionRef.contextWindow) || null,
259
+ boundaryTokens: positiveTokenInt(policy.boundaryTokens) || null,
260
+ triggerTokens: positiveTokenInt(policy.triggerTokens || policy.boundaryTokens) || null,
261
+ updatedAt: Math.max(0, Math.round(Number(updatedAt) || Date.now())),
262
+ };
263
+ sessionRef.contextUsageSnapshot = snapshot;
264
+ return snapshot;
265
+ }
266
+
267
+ export function resolveContextUsageSnapshot(sessionRef, policy, {
268
+ messages,
269
+ } = {}) {
270
+ const snapshot = sessionRef?.contextUsageSnapshot;
271
+ if (!snapshot || typeof snapshot !== 'object'
272
+ || snapshot.version !== CONTEXT_USAGE_SNAPSHOT_VERSION
273
+ || !policy || !Array.isArray(messages)) return null;
274
+ if (String(snapshot.provider || '') !== String(sessionRef?.provider || policy.provider || '')
275
+ || String(snapshot.model || '') !== String(sessionRef?.model || '')) return null;
276
+ if (Number(snapshot.messageCount) !== messages.length
277
+ || String(snapshot.usageMetricsTurnId || '') !== String(sessionRef?.usageMetricsTurnId || '')
278
+ || Number(snapshot.usageMetricsEpoch || 0) !== Number(sessionRef?.usageMetricsEpoch || 0)) return null;
279
+ const tail = contextUsageSnapshotTail(messages);
280
+ if (String(snapshot.tailRole || '') !== tail.role
281
+ || String(snapshot.tailId || '') !== tail.id) return null;
282
+ if (String(snapshot.toolSchemaSignature || '') !== String(policy.toolSchemaSignature || '')
283
+ || Number(snapshot.contextWindow || 0) !== Number(policy.contextWindow || sessionRef?.contextWindow || 0)
284
+ || Number(snapshot.boundaryTokens || 0) !== Number(policy.boundaryTokens || 0)
285
+ || Number(snapshot.triggerTokens || 0) !== Number(policy.triggerTokens || policy.boundaryTokens || 0)) return null;
286
+ const exactSignature = contextMessagesSignature(messages);
287
+ if (String(snapshot.messagesSignature || '') !== exactSignature) {
288
+ // Stored-history media normalization can replace inline payloads with
289
+ // durable placeholders without changing the logical transcript. The
290
+ // stable turn/count/tail anchors above preserve the compact snapshot
291
+ // across that serialization boundary while still invalidating it on
292
+ // ordinary subsequent turns.
293
+ const sameLogicalAnchor = Number(snapshot.messageCount) === messages.length
294
+ && String(snapshot.usageMetricsTurnId || '') === String(sessionRef?.usageMetricsTurnId || '')
295
+ && String(snapshot.tailRole || '') === tail.role
296
+ && String(snapshot.tailId || '') === tail.id;
297
+ if (!sameLogicalAnchor) return null;
298
+ }
299
+ const used = Number(snapshot.usedTokens);
300
+ return Number.isFinite(used) && used >= 0 ? snapshot : null;
301
+ }
302
+
303
+ export function invalidateContextUsageSnapshot(sessionRef) {
304
+ if (!sessionRef || typeof sessionRef !== 'object') return;
305
+ delete sessionRef.contextUsageSnapshot;
306
+ }
307
+
219
308
  function providerPressureTokens(sessionRef, usage) {
220
309
  if (!usage || typeof usage !== 'object') return 0;
221
310
  const input = Math.max(0, Number(usage.mainInputTokens ?? usage.inputTokens) || 0);
@@ -246,6 +335,7 @@ export function recordProviderContextBaseline(sessionRef, messages, usage, {
246
335
  }
247
336
  const tokens = providerPressureTokens(sessionRef, usage);
248
337
  if (!tokens) return false;
338
+ invalidateContextUsageSnapshot(sessionRef);
249
339
  sessionRef.contextPressureBaselineTokens = tokens;
250
340
  sessionRef.contextPressureBaselineOutputTokens = Math.max(0, Math.round(Number(usage?.mainOutputTokens ?? usage?.outputTokens) || 0));
251
341
  sessionRef.contextPressureBaselineMessageCount = messages.length;
@@ -253,6 +343,10 @@ export function recordProviderContextBaseline(sessionRef, messages, usage, {
253
343
  sessionRef.contextPressureBaselineProvider = sessionRef.provider || null;
254
344
  sessionRef.contextPressureBaselineModel = sessionRef.model || null;
255
345
  sessionRef.contextPressureBaselineToolSignature = toolSchemaSignature(sendTools);
346
+ sessionRef.contextPressureBaselineRequestReserveTokens = Math.max(
347
+ 0,
348
+ Math.round(estimateRequestReserveTokens(sendTools) * providerTokenCalibration(sessionRef.provider)),
349
+ );
256
350
  // provider_send usage arrives before the response's assistant message is
257
351
  // appended. Mark that request boundary so pressure resolution skips the
258
352
  // first subsequent assistant representation: its output (including opaque
@@ -274,6 +368,7 @@ export function invalidateProviderContextBaseline(sessionRef) {
274
368
  sessionRef.contextPressureBaselineProvider = null;
275
369
  sessionRef.contextPressureBaselineModel = null;
276
370
  sessionRef.contextPressureBaselineToolSignature = null;
371
+ sessionRef.contextPressureBaselineRequestReserveTokens = null;
277
372
  sessionRef.contextPressureBaselineUpdatedAt = null;
278
373
  sessionRef.lastContextTokensStaleAfterCompact = true;
279
374
  }
@@ -299,8 +394,22 @@ function providerBaselinePressureTokens(messages, sessionRef, policy, {
299
394
  || (compactAt > 0 && baselineAt > 0 && baselineAt < compactAt)
300
395
  || sessionRef.contextPressureBaselineProvider !== (sessionRef.provider || null)
301
396
  || sessionRef.contextPressureBaselineModel !== (sessionRef.model || null)
302
- || sessionRef.contextPressureBaselineToolSignature !== policy?.toolSchemaSignature
303
397
  || sessionRef.contextPressureBaselinePrefixSignature !== contextMessagesSignature(messages, count)) return null;
398
+ const calibration = Number(policy?.tokenCalibration) > 0 ? Number(policy.tokenCalibration) : 1;
399
+ if (sessionRef.contextPressureBaselineToolSignature !== policy?.toolSchemaSignature) {
400
+ const currentRequestReserve = Math.max(
401
+ 0,
402
+ Math.round((Number(policy?.requestReserveTokens) || 0) * calibration),
403
+ );
404
+ const storedRequestReserve = Number(sessionRef.contextPressureBaselineRequestReserveTokens);
405
+ // A changed deferred/control-tool surface does not invalidate provider
406
+ // usage for the aligned message prefix. Adjust only the request-schema
407
+ // share. Legacy snapshots lack the old share, so conservatively add the
408
+ // current one rather than falling back to a gross full-history estimate.
409
+ tokens = Number.isFinite(storedRequestReserve) && storedRequestReserve >= 0
410
+ ? Math.max(0, tokens - Math.round(storedRequestReserve) + currentRequestReserve)
411
+ : tokens + currentRequestReserve;
412
+ }
304
413
  if (messages.length > count && baselineAt > 0
305
414
  && (Date.now() - baselineAt) > BASELINE_MAX_STALE_GROWTH_MS) return null;
306
415
  if (sessionRef.contextPressureBaselineBoundary === 'request') {
@@ -318,7 +427,6 @@ function providerBaselinePressureTokens(messages, sessionRef, policy, {
318
427
  try {
319
428
  // Baseline tokens are authoritative provider billing; only the growth
320
429
  // after the baseline is a local estimate and needs billing calibration.
321
- const calibration = Number(policy?.tokenCalibration) > 0 ? Number(policy.tokenCalibration) : 1;
322
430
  const growth = count < messages.length
323
431
  ? Math.round(estimateMessagesTokens(messages.slice(count)) * calibration)
324
432
  : 0;
@@ -5,22 +5,13 @@
5
5
  // Error string the serial path would emit. The eager caller ignores the
6
6
  // message body and just treats non-null as "do not start eager".
7
7
  //
8
- // This is NOT a permission gate — runtime permission enforcement was removed
9
- // (every tool call is trusted). What remains is architectural scoping:
10
- // agent workers are sandboxed to code/research tools. They must never reach
11
- // owner/host control surfaces: session management, the ENTIRE channels module
12
- // (Discord messaging, schedules, webhook/config, channel-bridge toggle,
13
- // command injection), or host input injection. Explicit name list (no imports)
14
- // keeps this hot-path gate dependency-free; add new owner/channel tools here.
8
+ // This is NOT a permission gate — every tool call is trusted. Lead and Agent
9
+ // share the same runtime surface; only recursive Agent session control remains
10
+ // Lead-only.
15
11
  import { isAgentOwner } from '../../agent-owner.mjs';
16
12
 
17
13
  const WORKER_DENIED_TOOLS = new Set([
18
- // session control-plane — unified into the single `agent` tool
19
- // (type=spawn|send|close|list). Denying the one name blocks all worker
20
- // session control.
21
14
  'agent',
22
- // host input injection
23
- 'inject_input',
24
15
  ]);
25
16
 
26
17
  const IMAGE_PATH_RE = /\.(?:png|jpe?g|gif|webp)(?:$|[?#])/i;
@@ -100,10 +91,6 @@ function _preDispatchDeny(call, toolKind, sessionRef) {
100
91
  if (_agentOwned && _controlPlaneTool) {
101
92
  return `Error: control-plane tool "${name}" is Lead-only and not available to agent workers.`;
102
93
  }
103
- const noToolAgent = sessionRef?.agent === 'cycle1-agent' || sessionRef?.agent === 'cycle2-agent';
104
- if (noToolAgent) {
105
- return `Error: tool "${name}" is not available in agent "${sessionRef.agent}". Re-emit the answer as pipe-separated text per the agent's output format (first character a digit, NO tool_use blocks, NO JSON, NO prose, NO apology).`;
106
- }
107
94
  return null;
108
95
  }
109
96
 
@@ -50,6 +50,74 @@ function isAbortLikeError(err, signal) {
50
50
  return /\babort(ed|ing)?\b|\bcancel(l?ed|ling)?\b/.test(msg);
51
51
  }
52
52
 
53
+ // A stalled memory call must NEVER wedge compaction. Every recall-fasttrack
54
+ // memory call is bounded here — the default path included — so the protection
55
+ // no longer depends on which caller happened to wire a bounded search in.
56
+ export const RECALL_MEMORY_CALL_TIMEOUT_MS = Math.max(
57
+ 250,
58
+ Number(process.env.MIXDOG_AGENT_COMPACT_RECALL_TIMEOUT_MS) || 4000,
59
+ );
60
+ // Cold-start allowance: a booting memory runtime can miss the tight first bound
61
+ // (waitForPort + first-RPC warmup ~2-10s). On a timeout we retry ONCE with a
62
+ // longer bound before honoring the bail contract, so a rebooting runtime
63
+ // succeeds instead of instantly failing. 15s keeps the clear path's worst case
64
+ // (2 retried memory calls + 120s semantic) under the TUI watchdog (180s).
65
+ export const RECALL_COLD_START_TIMEOUT_MS = 15_000;
66
+
67
+ export function recallMemoryTimeoutMs(session) {
68
+ const configured = Number(session?.compaction?.recallMemoryTimeoutMs);
69
+ // Clamp ALL sources (session config included) to the 250ms floor so a
70
+ // misconfigured tiny value can't turn the bound into a busy no-wait.
71
+ return Math.max(250, Number.isFinite(configured) && configured > 0
72
+ ? Math.floor(configured)
73
+ : RECALL_MEMORY_CALL_TIMEOUT_MS);
74
+ }
75
+
76
+ function isTimeoutError(err) {
77
+ return typeof err?.message === 'string' && err.message.includes('timed out after');
78
+ }
79
+
80
+ export async function callMemoryBounded(args, callerCtx, timeoutMs, executeMemory = executeInternalTool) {
81
+ const ac = new AbortController();
82
+ const outer = callerCtx?.signal;
83
+ const onOuterAbort = () => { try { ac.abort(); } catch {} };
84
+ if (outer) {
85
+ if (outer.aborted) ac.abort();
86
+ else { try { outer.addEventListener?.('abort', onOuterAbort, { once: true }); } catch {} }
87
+ }
88
+ let timer = null;
89
+ const timeout = new Promise((_, reject) => {
90
+ timer = setTimeout(() => {
91
+ try { ac.abort(); } catch {}
92
+ reject(new Error(`memory ${args?.action || 'call'} timed out after ${timeoutMs}ms`));
93
+ }, timeoutMs);
94
+ try { timer.unref?.(); } catch {}
95
+ });
96
+ try {
97
+ return await Promise.race([
98
+ executeMemory('memory', args, { ...callerCtx, signal: ac.signal }),
99
+ timeout,
100
+ ]);
101
+ } finally {
102
+ if (timer) clearTimeout(timer);
103
+ // Drop the chained-abort listener when the call settles first, so a
104
+ // later outer abort can't fire into a dead controller / leak.
105
+ try { outer?.removeEventListener?.('abort', onOuterAbort); } catch {}
106
+ }
107
+ }
108
+
109
+ export async function callMemoryColdStart(args, callerCtx, timeoutMs, executeMemory) {
110
+ try {
111
+ return await callMemoryBounded(args, callerCtx, timeoutMs, executeMemory);
112
+ } catch (err) {
113
+ if (!isTimeoutError(err) || callerCtx?.signal?.aborted) throw err;
114
+ const coldMs = Math.max(timeoutMs, RECALL_COLD_START_TIMEOUT_MS);
115
+ if (coldMs <= timeoutMs) throw err;
116
+ try { process.stderr.write(`[session] recall-fasttrack ${args?.action || 'call'} cold-start retry (${timeoutMs}ms -> ${coldMs}ms)\n`); } catch {}
117
+ return await callMemoryBounded(args, callerCtx, coldMs, executeMemory);
118
+ }
119
+ }
120
+
53
121
  export function isUsableRecallDigestText(value) {
54
122
  const text = typeof value === 'string' ? value : String(value?.text ?? value ?? '');
55
123
  const trimmed = text.trim();
@@ -69,21 +137,12 @@ export async function runRecallFastTrackCompact({
69
137
  }) {
70
138
  if (!sessionId) throw new Error('recall-fasttrack requires a session id');
71
139
  const startedAt = Date.now();
140
+ // Digest mode only: the full-dump pipeline's per-cycle counters were
141
+ // removed with it in 2026-07 and had been logging fixed nulls since.
72
142
  const diagnostics = {
73
143
  memorySource: 'existing-session',
74
144
  searchMs: null,
75
145
  searchError: null,
76
- initialDumpMs: null,
77
- initialDumpBytes: null,
78
- initialDumpChars: null,
79
- initialRawPending: null,
80
- cycle1Ms: null,
81
- cycle1Skipped: false,
82
- cycle1SkipReason: null,
83
- cycle1Passes: null,
84
- cycle1RawRemaining: null,
85
- cycle1TextBytes: null,
86
- cycle1Error: null,
87
146
  finalRecallBytes: null,
88
147
  finalRecallChars: null,
89
148
  totalMs: null,
@@ -97,7 +156,6 @@ export async function runRecallFastTrackCompact({
97
156
  clientHostPid: sessionRef?.clientHostPid,
98
157
  signal: signal || null,
99
158
  };
100
- let t0 = Date.now();
101
159
  let searchFailed = false;
102
160
  let searchErr = null;
103
161
  // Build the compact handoff from the session rows the always-on transcript
@@ -105,11 +163,19 @@ export async function runRecallFastTrackCompact({
105
163
  // the memory RPC: that duplicates canonical history and can exceed the
106
164
  // bounded HTTP request body before compaction gets a chance to run.
107
165
  let digestBody = '';
108
- t0 = Date.now();
166
+ const t0 = Date.now();
109
167
  try {
168
+ // The default path is bounded exactly like the caller-supplied one: an
169
+ // unbounded memory call here would hang the pre-send compaction that
170
+ // runs between the user's prompt and the provider request.
110
171
  const searchMemory = typeof executeMemorySearch === 'function'
111
172
  ? executeMemorySearch
112
- : (args, ctx) => executeInternalTool('memory', args, ctx);
173
+ : (args, ctx) => callMemoryColdStart(
174
+ args,
175
+ ctx,
176
+ recallMemoryTimeoutMs(sessionRef),
177
+ executeInternalTool,
178
+ );
113
179
  const browsed = await searchMemory({
114
180
  action: 'search',
115
181
  sessionId,
@@ -128,10 +194,6 @@ export async function runRecallFastTrackCompact({
128
194
  try { process.stderr.write(`[loop] recall-digest browse failed (sess=${sessionId || 'unknown'}): ${err?.message || err}\n`); } catch {}
129
195
  }
130
196
  diagnostics.searchMs = Date.now() - t0;
131
- diagnostics.initialDumpMs = diagnostics.searchMs;
132
- diagnostics.cycle1Skipped = true;
133
- diagnostics.cycle1SkipReason = 'digest mode';
134
- diagnostics.cycle1Passes = 0;
135
197
  // Fail-safe: an unavailable or empty stored session cannot support a
136
198
  // truthful recall handoff. Preserve the live head and let the caller use
137
199
  // the semantic fallback instead of silently dropping history.
@@ -25,6 +25,9 @@ function steeringEntryMetadata(entry) {
25
25
  ...(ids.length ? { ids } : {}),
26
26
  ...(Number.isFinite(submittedAt) && submittedAt > 0 ? { submittedAt } : {}),
27
27
  ...(Array.isArray(entry.images) && entry.images.length ? { images: entry.images } : {}),
28
+ ...(entry.transcriptMeta && typeof entry.transcriptMeta === 'object'
29
+ ? { transcriptMeta: { ...entry.transcriptMeta } }
30
+ : {}),
28
31
  };
29
32
  }
30
33
 
@@ -51,10 +54,13 @@ function mergeSteeringMetadata(entries) {
51
54
  const submittedTimes = entries.map((entry) => Number(entry.submittedAt))
52
55
  .filter((value) => Number.isFinite(value) && value > 0);
53
56
  const images = entries.flatMap((entry) => Array.isArray(entry.images) ? entry.images : []);
57
+ const transcriptMeta = entries.find((entry) =>
58
+ entry.transcriptMeta && typeof entry.transcriptMeta === 'object')?.transcriptMeta;
54
59
  return {
55
60
  ...(ids.length ? { ids } : {}),
56
61
  ...(submittedTimes.length ? { submittedAt: Math.min(...submittedTimes) } : {}),
57
62
  ...(images.length ? { images } : {}),
63
+ ...(transcriptMeta ? { transcriptMeta: { ...transcriptMeta } } : {}),
58
64
  };
59
65
  }
60
66
 
@@ -333,7 +333,10 @@ async function executeToolOwned(name, args, cwd, callerSessionId, sessionRef, ex
333
333
  clientHostPid: sessionRef?.clientHostPid,
334
334
  signal: executeOpts.signal,
335
335
  routingSessionId: callerSessionId,
336
+ turnId: Number(sessionRef?.usageMetricsTurnId) || 0,
336
337
  notifyFn,
338
+ toolApprovalHook,
339
+ toolCallId: executeOpts.toolCallId || null,
337
340
  invocationSource: 'model-tool',
338
341
  });
339
342
  }
@@ -49,6 +49,12 @@ export function isParallelDispatchable(name) {
49
49
  return typeof name === 'string' && name.length > 0;
50
50
  }
51
51
 
52
+ const SINGLE_CALL_PER_TURN_TOOL_NAMES = new Set(['computer']);
53
+
54
+ export function isSingleCallPerTurnTool(name) {
55
+ return SINGLE_CALL_PER_TURN_TOOL_NAMES.has(name);
56
+ }
57
+
52
58
  // Read-only is necessary but not sufficient for result deduplication. Loader
53
59
  // calls mutate the active session tool surface and must execute on every
54
60
  // explicit invocation so repeats can truthfully report `alreadyActive`.